CGameHandler.cpp 152 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245
  1. #include "../hch/CCampaignHandler.h"
  2. #include "../StartInfo.h"
  3. #include "../hch/CArtHandler.h"
  4. #include "../hch/CBuildingHandler.h"
  5. #include "../hch/CDefObjInfoHandler.h"
  6. #include "../hch/CHeroHandler.h"
  7. #include "../hch/CObjectHandler.h"
  8. #include "../hch/CSpellHandler.h"
  9. #include "../hch/CGeneralTextHandler.h"
  10. #include "../hch/CTownHandler.h"
  11. #include "../hch/CCreatureHandler.h"
  12. #include "../lib/CGameState.h"
  13. #include "../lib/CondSh.h"
  14. #include "../lib/NetPacks.h"
  15. #include "../lib/VCMI_Lib.h"
  16. #include "../lib/map.h"
  17. #include "../lib/VCMIDirs.h"
  18. #include "CGameHandler.h"
  19. #include <boost/bind.hpp>
  20. #include <boost/date_time/posix_time/posix_time_types.hpp> //no i/o just types
  21. #include <boost/foreach.hpp>
  22. #include <boost/thread.hpp>
  23. #include <boost/thread/shared_mutex.hpp>
  24. #include <boost/assign/list_of.hpp>
  25. #include <boost/random/linear_congruential.hpp>
  26. #include <fstream>
  27. #include <boost/system/system_error.hpp>
  28. /*
  29. * CGameHandler.cpp, part of VCMI engine
  30. *
  31. * Authors: listed in file AUTHORS in main folder
  32. *
  33. * License: GNU General Public License v2.0 or later
  34. * Full text of license available in license.txt file, in main folder
  35. *
  36. */
  37. #undef DLL_EXPORT
  38. #define DLL_EXPORT
  39. #include "../lib/RegisterTypes.cpp"
  40. #ifndef _MSC_VER
  41. #include <boost/thread/xtime.hpp>
  42. #endif
  43. extern bool end2;
  44. #ifdef min
  45. #undef min
  46. #endif
  47. #ifdef max
  48. #undef max
  49. #endif
  50. #define COMPLAIN_RET(txt) {complain(txt); return false;}
  51. #define NEW_ROUND BattleNextRound bnr;\
  52. bnr.round = gs->curB->round + 1;\
  53. sendAndApply(&bnr);
  54. CondSh<bool> battleMadeAction;
  55. CondSh<BattleResult *> battleResult(NULL);
  56. std::ptrdiff_t randomizer (ptrdiff_t i) {return rand();}
  57. std::ptrdiff_t (*p_myrandom)(std::ptrdiff_t) = randomizer;
  58. template <typename T> class CApplyOnGH;
  59. class CBaseForGHApply
  60. {
  61. public:
  62. virtual bool applyOnGH(CGameHandler *gh, CConnection *c, void *pack) const =0;
  63. virtual ~CBaseForGHApply(){}
  64. template<typename U> static CBaseForGHApply *getApplier(const U * t=NULL)
  65. {
  66. return new CApplyOnGH<U>;
  67. }
  68. };
  69. template <typename T> class CApplyOnGH : public CBaseForGHApply
  70. {
  71. public:
  72. bool applyOnGH(CGameHandler *gh, CConnection *c, void *pack) const
  73. {
  74. T *ptr = static_cast<T*>(pack);
  75. ptr->c = c;
  76. return ptr->applyGh(gh);
  77. }
  78. };
  79. static CApplier<CBaseForGHApply> *applier = NULL;
  80. CMP_stack cmpst ;
  81. static inline double distance(int3 a, int3 b)
  82. {
  83. return std::sqrt( (double)(a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) );
  84. }
  85. static void giveExp(BattleResult &r)
  86. {
  87. r.exp[0] = 0;
  88. r.exp[1] = 0;
  89. for(std::map<ui32,si32>::iterator i = r.casualties[!r.winner].begin(); i!=r.casualties[!r.winner].end(); i++)
  90. {
  91. r.exp[r.winner] += VLC->creh->creatures[i->first]->valOfBonuses(Bonus::STACK_HEALTH) * i->second;
  92. }
  93. }
  94. PlayerStatus PlayerStatuses::operator[](ui8 player)
  95. {
  96. boost::unique_lock<boost::mutex> l(mx);
  97. if(players.find(player) != players.end())
  98. {
  99. return players[player];
  100. }
  101. else
  102. {
  103. throw std::string("No such player!");
  104. }
  105. }
  106. void PlayerStatuses::addPlayer(ui8 player)
  107. {
  108. boost::unique_lock<boost::mutex> l(mx);
  109. players[player];
  110. }
  111. bool PlayerStatuses::hasQueries(ui8 player)
  112. {
  113. boost::unique_lock<boost::mutex> l(mx);
  114. if(players.find(player) != players.end())
  115. {
  116. return players[player].queries.size();
  117. }
  118. else
  119. {
  120. throw std::string("No such player!");
  121. }
  122. }
  123. bool PlayerStatuses::checkFlag(ui8 player, bool PlayerStatus::*flag)
  124. {
  125. boost::unique_lock<boost::mutex> l(mx);
  126. if(players.find(player) != players.end())
  127. {
  128. return players[player].*flag;
  129. }
  130. else
  131. {
  132. throw std::string("No such player!");
  133. }
  134. }
  135. void PlayerStatuses::setFlag(ui8 player, bool PlayerStatus::*flag, bool val)
  136. {
  137. boost::unique_lock<boost::mutex> l(mx);
  138. if(players.find(player) != players.end())
  139. {
  140. players[player].*flag = val;
  141. }
  142. else
  143. {
  144. throw std::string("No such player!");
  145. }
  146. cv.notify_all();
  147. }
  148. void PlayerStatuses::addQuery(ui8 player, ui32 id)
  149. {
  150. boost::unique_lock<boost::mutex> l(mx);
  151. if(players.find(player) != players.end())
  152. {
  153. players[player].queries.insert(id);
  154. }
  155. else
  156. {
  157. throw std::string("No such player!");
  158. }
  159. cv.notify_all();
  160. }
  161. void PlayerStatuses::removeQuery(ui8 player, ui32 id)
  162. {
  163. boost::unique_lock<boost::mutex> l(mx);
  164. if(players.find(player) != players.end())
  165. {
  166. players[player].queries.erase(id);
  167. }
  168. else
  169. {
  170. throw std::string("No such player!");
  171. }
  172. cv.notify_all();
  173. }
  174. template <typename T>
  175. void callWith(std::vector<T> args, boost::function<void(T)> fun, ui32 which)
  176. {
  177. fun(args[which]);
  178. }
  179. void CGameHandler::levelUpHero(int ID, int skill)
  180. {
  181. changeSecSkill(ID, skill, 1, 0);
  182. levelUpHero(ID);
  183. }
  184. void CGameHandler::levelUpHero(int ID)
  185. {
  186. CGHeroInstance *hero = static_cast<CGHeroInstance *>(gs->map->objects[ID]);
  187. if (hero->exp < VLC->heroh->reqExp(hero->level+1)) // no more level-ups
  188. return;
  189. //give prim skill
  190. tlog5 << hero->name <<" got level "<<hero->level<<std::endl;
  191. int r = rand()%100, pom=0, x=0;
  192. int std::pair<int,int>::*g = (hero->level>9) ? (&std::pair<int,int>::second) : (&std::pair<int,int>::first);
  193. for(;x<PRIMARY_SKILLS;x++)
  194. {
  195. pom += hero->type->heroClass->primChance[x].*g;
  196. if(r<pom)
  197. break;
  198. }
  199. tlog5 << "Bohater dostaje umiejetnosc pierwszorzedna " << x << " (wynik losowania "<<r<<")"<<std::endl;
  200. SetPrimSkill sps;
  201. sps.id = ID;
  202. sps.which = x;
  203. sps.abs = false;
  204. sps.val = 1;
  205. sendAndApply(&sps);
  206. HeroLevelUp hlu;
  207. hlu.heroid = ID;
  208. hlu.primskill = x;
  209. hlu.level = hero->level+1;
  210. //picking sec. skills for choice
  211. std::set<int> basicAndAdv, expert, none;
  212. for(int i=0;i<SKILL_QUANTITY;i++)
  213. if (isAllowed(2,i))
  214. none.insert(i);
  215. for(unsigned i=0;i<hero->secSkills.size();i++)
  216. {
  217. if(hero->secSkills[i].second < 3)
  218. basicAndAdv.insert(hero->secSkills[i].first);
  219. else
  220. expert.insert(hero->secSkills[i].first);
  221. none.erase(hero->secSkills[i].first);
  222. }
  223. //first offered skill
  224. if(basicAndAdv.size())
  225. {
  226. int s = hero->type->heroClass->chooseSecSkill(basicAndAdv);//upgrade existing
  227. hlu.skills.push_back(s);
  228. basicAndAdv.erase(s);
  229. }
  230. else if(none.size() && hero->secSkills.size() < hero->type->heroClass->skillLimit)
  231. {
  232. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(none)); //give new skill
  233. none.erase(hlu.skills.back());
  234. }
  235. //second offered skill
  236. if(none.size() && hero->secSkills.size() < hero->type->heroClass->skillLimit) //hero have free skill slot
  237. {
  238. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(none)); //new skill
  239. }
  240. else if(basicAndAdv.size())
  241. {
  242. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(basicAndAdv)); //upgrade existing
  243. }
  244. if(hlu.skills.size() > 1) //apply and ask for secondary skill
  245. {
  246. boost::function<void(ui32)> callback = boost::function<void(ui32)>(boost::bind(callWith<ui16>,hlu.skills,boost::function<void(ui16)>(boost::bind(&CGameHandler::levelUpHero,this,ID,_1)),_1));
  247. applyAndAsk(&hlu,hero->tempOwner,callback); //call levelUpHero when client responds
  248. }
  249. else if(hlu.skills.size() == 1) //apply, give only possible skill and send info
  250. {
  251. sendAndApply(&hlu);
  252. levelUpHero(ID, hlu.skills.back());
  253. }
  254. else //apply and send info
  255. {
  256. sendAndApply(&hlu);
  257. levelUpHero(ID);
  258. }
  259. }
  260. void CGameHandler::changePrimSkill(int ID, int which, si64 val, bool abs)
  261. {
  262. SetPrimSkill sps;
  263. sps.id = ID;
  264. sps.which = which;
  265. sps.abs = abs;
  266. sps.val = val;
  267. sendAndApply(&sps);
  268. if(which==4) //only for exp - hero may level up
  269. {
  270. levelUpHero(ID);
  271. }
  272. }
  273. void CGameHandler::changeSecSkill( int ID, int which, int val, bool abs/*=false*/ )
  274. {
  275. SetSecSkill sss;
  276. sss.id = ID;
  277. sss.which = which;
  278. sss.val = val;
  279. sss.abs = abs;
  280. sendAndApply(&sss);
  281. if(which == 7) //Wisdom
  282. {
  283. const CGHeroInstance *h = getHero(ID);
  284. if(h && h->visitedTown)
  285. giveSpells(h->visitedTown, h);
  286. }
  287. }
  288. static CCreatureSet takeCasualties(int color, const CCreatureSet &set, BattleInfo *bat)
  289. {
  290. if(color == 254)
  291. color = 255;
  292. CCreatureSet ret(set);
  293. for(int i=0; i<bat->stacks.size();i++)
  294. {
  295. CStack *st = bat->stacks[i];
  296. if(vstd::contains(st->state, SUMMONED)) //don't take into account sumoned stacks
  297. continue;
  298. if(st->owner==color && !set.slotEmpty(st->slot) && st->count < set.getAmount(st->slot))
  299. {
  300. if(st->alive())
  301. ret.setStackCount(st->slot, st->count);
  302. else
  303. ret.eraseStack(st->slot);
  304. }
  305. }
  306. return ret;
  307. }
  308. void CGameHandler::startBattle(const CArmedInstance *army1, const CArmedInstance * army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool creatureBank, boost::function<void(BattleResult*)> cb, const CGTownInstance *town)
  309. {
  310. battleEndCallback = new boost::function<void(BattleResult*)>(cb);
  311. bEndArmy1 = army1;
  312. bEndArmy2 = army2;
  313. {
  314. BattleInfo *curB = new BattleInfo;
  315. curB->side1 = army1->tempOwner;
  316. curB->side2 = army2->tempOwner;
  317. if(curB->side2 == 254)
  318. curB->side2 = 255;
  319. setupBattle(curB, tile, army1, army2, hero1, hero2, creatureBank, town); //initializes stacks, places creatures on battlefield, blocks and informs player interfaces
  320. }
  321. NEW_ROUND;
  322. //TODO: pre-tactic stuff, call scripts etc.
  323. //tactic round
  324. {
  325. NEW_ROUND;
  326. if( (hero1 && hero1->getSecSkillLevel(19)>0) ||
  327. ( hero2 && hero2->getSecSkillLevel(19)>0) )//someone has tactics
  328. {
  329. //TODO: tactic round (round -1)
  330. }
  331. }
  332. //spells opening battle
  333. if (hero1 && hero1->hasBonusOfType(Bonus::OPENING_BATTLE_SPELL))
  334. {
  335. BonusList bl;
  336. hero1->getBonuses(bl, Selector::type(Bonus::OPENING_BATTLE_SPELL));
  337. BOOST_FOREACH (Bonus b, bl)
  338. {
  339. handleSpellCasting(b.subtype, 3, -1, 0, hero1->tempOwner, NULL, hero2, b.val);
  340. }
  341. }
  342. if (hero2 && hero2->hasBonusOfType(Bonus::OPENING_BATTLE_SPELL))
  343. {
  344. BonusList bl;
  345. hero2->getBonuses(bl, Selector::type(Bonus::OPENING_BATTLE_SPELL));
  346. BOOST_FOREACH (Bonus b, bl)
  347. {
  348. handleSpellCasting(b.subtype, 3, -1, 1, hero2->tempOwner, NULL, hero1, b.val);
  349. }
  350. }
  351. //main loop
  352. while(!battleResult.get()) //till the end of the battle ;]
  353. {
  354. NEW_ROUND;
  355. std::vector<CStack*> & stacks = (gs->curB->stacks);
  356. const BattleInfo & curB = *gs->curB;
  357. //stack loop
  358. const CStack *next;
  359. while(!battleResult.get() && (next = curB.getNextStack()) && next->willMove())
  360. {
  361. //check for bad morale => freeze
  362. int nextStackMorale = next->MoraleVal();
  363. if( nextStackMorale < 0 &&
  364. !(NBonus::hasOfType(hero1, Bonus::BLOCK_MORALE) || NBonus::hasOfType(hero2, Bonus::BLOCK_MORALE)) //checking if heroes have (or don't have) morale blocking bonuses)
  365. )
  366. {
  367. if( rand()%24 < -2 * nextStackMorale)
  368. {
  369. //unit loses its turn - empty freeze action
  370. BattleAction ba;
  371. ba.actionType = 11;
  372. ba.additionalInfo = 1;
  373. ba.side = !next->attackerOwned;
  374. ba.stackNumber = next->ID;
  375. sendAndApply(&StartAction(ba));
  376. sendAndApply(&EndAction());
  377. checkForBattleEnd(stacks); //check if this "action" ended the battle (not likely but who knows...)
  378. continue;
  379. }
  380. }
  381. if(next->hasBonusOfType(Bonus::ATTACKS_NEAREST_CREATURE)) //while in berserk
  382. {
  383. std::pair<const CStack *, int> attackInfo = curB.getNearestStack(next, boost::logic::indeterminate);
  384. if(attackInfo.first != NULL)
  385. {
  386. BattleAction attack;
  387. attack.actionType = 6;
  388. attack.side = !next->attackerOwned;
  389. attack.stackNumber = next->ID;
  390. attack.additionalInfo = attackInfo.first->position;
  391. attack.destinationTile = attackInfo.second;
  392. makeBattleAction(attack);
  393. checkForBattleEnd(stacks);
  394. }
  395. continue;
  396. }
  397. const CGHeroInstance * curOwner = gs->battleGetOwner(next->ID);
  398. if( (next->position < 0 && (!curOwner || curOwner->getSecSkillLevel(10) == 0)) //arrow turret, hero has no ballistics
  399. || (next->type->idNumber == 146 && (!curOwner || curOwner->getSecSkillLevel(20) == 0))) //ballista, hero has no artillery
  400. {
  401. BattleAction attack;
  402. attack.actionType = 7;
  403. attack.side = !next->attackerOwned;
  404. attack.stackNumber = next->ID;
  405. for(int g=0; g<gs->curB->stacks.size(); ++g)
  406. {
  407. if(gs->curB->stacks[g]->owner != next->owner && gs->curB->stacks[g]->alive())
  408. {
  409. attack.destinationTile = gs->curB->stacks[g]->position;
  410. break;
  411. }
  412. }
  413. makeBattleAction(attack);
  414. checkForBattleEnd(stacks);
  415. continue;
  416. }
  417. if(next->type->idNumber == 145 && (!curOwner || curOwner->getSecSkillLevel(10) == 0)) //catapult, hero has no ballistics
  418. {
  419. BattleAction attack;
  420. static const int wallHexes[] = {50, 183, 182, 130, 62, 29, 12, 95};
  421. attack.destinationTile = wallHexes[ rand()%ARRAY_COUNT(wallHexes) ];
  422. attack.actionType = 9;
  423. attack.additionalInfo = 0;
  424. attack.side = !next->attackerOwned;
  425. attack.stackNumber = next->ID;
  426. makeBattleAction(attack);
  427. continue;
  428. }
  429. if(next->type->idNumber == 147 && (!curOwner || curOwner->getSecSkillLevel(27) == 0)) //first aid tent, hero has no first aid
  430. {
  431. BattleAction heal;
  432. std::vector< const CStack * > possibleStacks;
  433. for (int v=0; v<gs->curB->stacks.size(); ++v)
  434. {
  435. const CStack * cstack = gs->curB->stacks[v];
  436. if (cstack->owner == next->owner && cstack->firstHPleft < cstack->MaxHealth() && cstack->alive()) //it's friendly and not fully healthy
  437. {
  438. possibleStacks.push_back(cstack);
  439. }
  440. }
  441. if(possibleStacks.size() == 0)
  442. {
  443. //nothing to heal
  444. BattleAction doNothing;
  445. doNothing.actionType = 0;
  446. doNothing.additionalInfo = 0;
  447. doNothing.destinationTile = -1;
  448. doNothing.side = !next->attackerOwned;
  449. doNothing.stackNumber = next->ID;
  450. sendAndApply(&StartAction(doNothing));
  451. sendAndApply(&EndAction());
  452. continue;
  453. }
  454. else
  455. {
  456. //heal random creature
  457. const CStack * toBeHealed = possibleStacks[ rand()%possibleStacks.size() ];
  458. heal.actionType = 12;
  459. heal.additionalInfo = 0;
  460. heal.destinationTile = toBeHealed->position;
  461. heal.side = !next->attackerOwned;
  462. heal.stackNumber = next->ID;
  463. makeBattleAction(heal);
  464. }
  465. continue;
  466. }
  467. int numberOfAsks = 1;
  468. bool breakOuter = false;
  469. do
  470. {//ask interface and wait for answer
  471. if(!battleResult.get())
  472. {
  473. BattleSetActiveStack sas;
  474. sas.stack = next->ID;
  475. sendAndApply(&sas);
  476. boost::unique_lock<boost::mutex> lock(battleMadeAction.mx);
  477. while(next->alive() && (!battleMadeAction.data && !battleResult.get())) //active stack hasn't made its action and battle is still going
  478. battleMadeAction.cond.wait(lock);
  479. battleMadeAction.data = false;
  480. }
  481. if(battleResult.get()) //don't touch it, battle could be finished while waiting got action
  482. {
  483. breakOuter = true;
  484. break;
  485. }
  486. //we're after action, all results applied
  487. checkForBattleEnd(stacks); //check if this action ended the battle
  488. //check for good morale
  489. nextStackMorale = next->MoraleVal();
  490. if(!vstd::contains(next->state,HAD_MORALE) //only one extra move per turn possible
  491. && !vstd::contains(next->state,DEFENDING)
  492. && !vstd::contains(next->state,WAITING)
  493. && next->alive()
  494. && nextStackMorale > 0
  495. && !(NBonus::hasOfType(hero1, Bonus::BLOCK_MORALE) || NBonus::hasOfType(hero2, Bonus::BLOCK_MORALE)) //checking if heroes have (or don't have) morale blocking bonuses
  496. )
  497. {
  498. if(rand()%24 < nextStackMorale) //this stack hasn't got morale this turn
  499. ++numberOfAsks; //move this stack once more
  500. }
  501. --numberOfAsks;
  502. } while (numberOfAsks > 0);
  503. if (breakOuter)
  504. {
  505. break;
  506. }
  507. }
  508. }
  509. endBattle(tile, hero1, hero2);
  510. }
  511. void CGameHandler::endBattle(int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2)
  512. {
  513. BattleResultsApplied resultsApplied;
  514. resultsApplied.player1 = bEndArmy1->tempOwner;
  515. resultsApplied.player2 = bEndArmy2->tempOwner;
  516. //unblock engaged players
  517. if(bEndArmy1->tempOwner<PLAYER_LIMIT)
  518. states.setFlag(bEndArmy1->tempOwner, &PlayerStatus::engagedIntoBattle, false);
  519. if(bEndArmy2 && bEndArmy2->tempOwner<PLAYER_LIMIT)
  520. states.setFlag(bEndArmy2->tempOwner, &PlayerStatus::engagedIntoBattle, false);
  521. //casualties among heroes armies
  522. SetGarrisons sg;
  523. sg.garrs[bEndArmy1->id] = takeCasualties(bEndArmy1->tempOwner, *bEndArmy1, gs->curB);
  524. sg.garrs[bEndArmy2->id] = takeCasualties(bEndArmy2->tempOwner, *bEndArmy2, gs->curB);
  525. sendAndApply(&sg);
  526. ui8 sides[2];
  527. sides[0] = gs->curB->side1;
  528. sides[1] = gs->curB->side2;
  529. ui8 loser = sides[!battleResult.data->winner];
  530. //end battle, remove all info, free memory
  531. giveExp(*battleResult.data);
  532. if (hero1)
  533. battleResult.data->exp[0] *= (100+hero1->getSecSkillLevel(21)*5)/100.0f;//sholar skill
  534. if (hero2)
  535. battleResult.data->exp[1] *= (100+hero2->getSecSkillLevel(21)*5)/100.0f;
  536. sendAndApply(battleResult.data);
  537. //if one hero has lost we will erase him
  538. if(battleResult.data->winner!=0 && hero1)
  539. {
  540. RemoveObject ro(hero1->id);
  541. sendAndApply(&ro);
  542. }
  543. if(battleResult.data->winner!=1 && hero2)
  544. {
  545. RemoveObject ro(hero2->id);
  546. sendAndApply(&ro);
  547. }
  548. //give exp
  549. if(battleResult.data->exp[0] && hero1)
  550. changePrimSkill(hero1->id,4,battleResult.data->exp[0]);
  551. if(battleResult.data->exp[1] && hero2)
  552. changePrimSkill(hero2->id,4,battleResult.data->exp[1]);
  553. sendAndApply(&resultsApplied);
  554. if(battleEndCallback && *battleEndCallback) //TODO: object interaction after level dialog is handled
  555. {
  556. (*battleEndCallback)(battleResult.data);
  557. delete battleEndCallback;
  558. battleEndCallback = 0;
  559. }
  560. // Necromancy if applicable.
  561. const CGHeroInstance *winnerHero = battleResult.data->winner != 0 ? hero2 : hero1;
  562. const CGHeroInstance *loserHero = battleResult.data->winner != 0 ? hero1 : hero2;
  563. if (winnerHero)
  564. {
  565. CStackInstance raisedStack = winnerHero->calculateNecromancy(*battleResult.data);
  566. // Give raised units to winner and show dialog, if any were raised.
  567. if (raisedStack.type)
  568. {
  569. int slot = winnerHero->getSlotFor(raisedStack.type->idNumber);
  570. if (slot != -1)
  571. {
  572. SetGarrisons sg;
  573. sg.garrs[winnerHero->id] = winnerHero->getArmy();
  574. sg.garrs[winnerHero->id].addToSlot(slot, raisedStack);
  575. // if (vstd::contains(winnerHero->slots, slot)) // Add to existing stack.
  576. // sg.garrs[winnerHero->id].slots[slot].count += raisedStack.count;
  577. // else // Create a new stack.
  578. // sg.garrs[winnerHero->id].slots[slot] = raisedStack;
  579. winnerHero->showNecromancyDialog(raisedStack);
  580. sendAndApply(&sg);
  581. }
  582. }
  583. }
  584. if(visitObjectAfterVictory && winnerHero == hero1)
  585. {
  586. visitObjectOnTile(*getTile(winnerHero->getPosition()), winnerHero);
  587. }
  588. visitObjectAfterVictory = false;
  589. winLoseHandle(1<<sides[0] | 1<<sides[1]); //handle victory/loss of engaged players
  590. int result = battleResult.get()->result;
  591. if(result == 1 || result == 2) //loser has escaped or surrendered
  592. {
  593. SetAvailableHeroes sah;
  594. sah.player = loser;
  595. sah.hid[0] = loserHero->subID;
  596. if(result == 1) //retreat
  597. {
  598. sah.army[0] = new CCreatureSet();
  599. sah.army[0]->addToSlot(0, VLC->creh->nameToID[loserHero->type->refTypeStack[0]],1);
  600. }
  601. if(const CGHeroInstance *another = getPlayerState(loser)->availableHeroes[1])
  602. sah.hid[1] = another->subID;
  603. else
  604. sah.hid[1] = -1;
  605. sendAndApply(&sah);
  606. }
  607. delete battleResult.data;
  608. }
  609. void CGameHandler::prepareAttacked(BattleStackAttacked &bsa, const CStack *def)
  610. {
  611. bsa.killedAmount = bsa.damageAmount / def->MaxHealth();
  612. unsigned damageFirst = bsa.damageAmount % def->MaxHealth();
  613. if( def->firstHPleft <= damageFirst )
  614. {
  615. bsa.killedAmount++;
  616. bsa.newHP = def->firstHPleft + def->MaxHealth() - damageFirst;
  617. }
  618. else
  619. {
  620. bsa.newHP = def->firstHPleft - damageFirst;
  621. }
  622. if(def->count <= bsa.killedAmount) //stack killed
  623. {
  624. bsa.newAmount = 0;
  625. bsa.flags |= 1;
  626. bsa.killedAmount = def->count; //we cannot kill more creatures than we have
  627. }
  628. else
  629. {
  630. bsa.newAmount = def->count - bsa.killedAmount;
  631. }
  632. }
  633. void CGameHandler::prepareAttack(BattleAttack &bat, const CStack *att, const CStack *def, int distance)
  634. {
  635. bat.bsa.clear();
  636. bat.stackAttacking = att->ID;
  637. bat.bsa.push_back(BattleStackAttacked());
  638. BattleStackAttacked *bsa = &bat.bsa.back();
  639. bsa->stackAttacked = def->ID;
  640. bsa->attackerID = att->ID;
  641. int attackerLuck = att->LuckVal();
  642. const CGHeroInstance * h0 = gs->curB->heroes[0],
  643. * h1 = gs->curB->heroes[1];
  644. bool noLuck = false;
  645. if(h0 && NBonus::hasOfType(h0, Bonus::BLOCK_LUCK) ||
  646. h1 && NBonus::hasOfType(h1, Bonus::BLOCK_LUCK))
  647. {
  648. noLuck = true;
  649. }
  650. if(!noLuck && attackerLuck > 0 && rand()%24 < attackerLuck) //TODO?: negative luck option?
  651. {
  652. bsa->damageAmount *= 2;
  653. bat.flags |= 4;
  654. }
  655. bsa->damageAmount = gs->curB->calculateDmg(att, def, gs->battleGetOwner(att->ID), gs->battleGetOwner(def->ID), bat.shot(), distance, bat.lucky());//counting dealt damage
  656. int dmg = bsa->damageAmount;
  657. prepareAttacked(*bsa, def);
  658. //life drain handling
  659. if (att->hasBonusOfType(Bonus::LIFE_DRAIN))
  660. {
  661. StacksHealedOrResurrected shi;
  662. shi.lifeDrain = true;
  663. shi.drainedFrom = def->ID;
  664. StacksHealedOrResurrected::HealInfo hi;
  665. hi.stackID = att->ID;
  666. hi.healedHP = std::min<int>(dmg, att->MaxHealth() - att->firstHPleft + att->MaxHealth() * (att->baseAmount - att->count) );
  667. hi.lowLevelResurrection = false;
  668. shi.healedStacks.push_back(hi);
  669. if (hi.healedHP > 0)
  670. {
  671. bsa->healedStacks.push_back(shi);
  672. }
  673. }
  674. else
  675. {
  676. }
  677. //fire shield handling
  678. if ( !bat.shot() && def->hasBonusOfType(Bonus::FIRE_SHIELD) && !bsa->killed() )
  679. {
  680. bat.bsa.push_back(BattleStackAttacked());
  681. BattleStackAttacked *bsa = &bat.bsa.back();
  682. bsa->stackAttacked = att->ID;
  683. bsa->attackerID = def->ID;
  684. bsa->flags |= 2;
  685. bsa->effect = 11;
  686. bsa->damageAmount = (dmg * def->valOfBonuses(Bonus::FIRE_SHIELD)) / 100;
  687. prepareAttacked(*bsa, att);
  688. }
  689. }
  690. void CGameHandler::handleConnection(std::set<int> players, CConnection &c)
  691. {
  692. srand(time(NULL));
  693. CPack *pack = NULL;
  694. try
  695. {
  696. while(1)//server should never shut connection first //was: while(!end2)
  697. {
  698. {
  699. boost::unique_lock<boost::mutex> lock(*c.rmx);
  700. c >> pack; //get the package
  701. tlog5 << "Received client message of type " << typeid(*pack).name() << std::endl;
  702. }
  703. int packType = typeList.getTypeID(pack); //get the id of type
  704. CBaseForGHApply *apply = applier->apps[packType]; //and appropriae applier object
  705. if(apply)
  706. {
  707. bool result = apply->applyOnGH(this,&c,pack);
  708. tlog5 << "Message successfully applied (result=" << result << ")!\n";
  709. //send confirmation that we've applied the package
  710. if(pack->type != 6000) //WORKAROUND - not confirm query replies TODO: reconsider
  711. {
  712. PackageApplied applied;
  713. applied.result = result;
  714. applied.packType = packType;
  715. {
  716. boost::unique_lock<boost::mutex> lock(*c.wmx);
  717. c << &applied;
  718. }
  719. }
  720. }
  721. else
  722. {
  723. tlog1 << "Message cannot be applied, cannot find applier (unregistered type)!\n";
  724. }
  725. delete pack;
  726. pack = NULL;
  727. }
  728. }
  729. catch(boost::system::system_error &e) //for boost errors just log, not crash - probably client shut down connection
  730. {
  731. assert(!c.connected); //make sure that connection has been marked as broken
  732. tlog1 << e.what() << std::endl;
  733. end2 = true;
  734. }
  735. HANDLE_EXCEPTION(end2 = true);
  736. tlog1 << "Ended handling connection\n";
  737. }
  738. int CGameHandler::moveStack(int stack, int dest)
  739. {
  740. int ret = 0;
  741. CStack *curStack = gs->curB->getStack(stack),
  742. *stackAtEnd = gs->curB->getStackT(dest);
  743. assert(curStack);
  744. assert(dest < BFIELD_SIZE);
  745. //initing necessary tables
  746. bool accessibility[BFIELD_SIZE];
  747. std::vector<int> accessible = gs->curB->getAccessibility(curStack->ID, false);
  748. for(int b=0; b<BFIELD_SIZE; ++b)
  749. {
  750. accessibility[b] = false;
  751. }
  752. for(int g=0; g<accessible.size(); ++g)
  753. {
  754. accessibility[accessible[g]] = true;
  755. }
  756. //shifting destination (if we have double wide stack and we can occupy dest but not be exactly there)
  757. if(!stackAtEnd && curStack->doubleWide() && !accessibility[dest])
  758. {
  759. if(curStack->attackerOwned)
  760. {
  761. if(accessibility[dest+1])
  762. dest+=1;
  763. }
  764. else
  765. {
  766. if(accessibility[dest-1])
  767. dest-=1;
  768. }
  769. }
  770. if((stackAtEnd && stackAtEnd!=curStack && stackAtEnd->alive()) || !accessibility[dest])
  771. return 0;
  772. bool accessibilityWithOccupyable[BFIELD_SIZE];
  773. std::vector<int> accOc = gs->curB->getAccessibility(curStack->ID, true);
  774. for(int b=0; b<BFIELD_SIZE; ++b)
  775. {
  776. accessibilityWithOccupyable[b] = false;
  777. }
  778. for(int g=0; g<accOc.size(); ++g)
  779. {
  780. accessibilityWithOccupyable[accOc[g]] = true;
  781. }
  782. //if(dists[dest] > curStack->creature->speed && !(stackAtEnd && dists[dest] == curStack->creature->speed+1)) //we can attack a stack if we can go to adjacent hex
  783. // return false;
  784. std::pair< std::vector<int>, int > path = gs->curB->getPath(curStack->position, dest, accessibilityWithOccupyable, curStack->hasBonusOfType(Bonus::FLYING), curStack->doubleWide(), curStack->attackerOwned);
  785. ret = path.second;
  786. if(curStack->hasBonusOfType(Bonus::FLYING))
  787. {
  788. if(path.second <= curStack->Speed() && path.first.size() > 0)
  789. {
  790. //inform clients about move
  791. BattleStackMoved sm;
  792. sm.stack = curStack->ID;
  793. sm.tile = path.first[0];
  794. sm.distance = path.second;
  795. sm.ending = true;
  796. sm.teleporting = false;
  797. sendAndApply(&sm);
  798. }
  799. }
  800. else //for non-flying creatures
  801. {
  802. int tilesToMove = std::max((int)(path.first.size() - curStack->Speed()), 0);
  803. for(int v=path.first.size()-1; v>=tilesToMove; --v)
  804. {
  805. //inform clients about move
  806. BattleStackMoved sm;
  807. sm.stack = curStack->ID;
  808. sm.tile = path.first[v];
  809. sm.distance = path.second;
  810. sm.ending = v==tilesToMove;
  811. sm.teleporting = false;
  812. sendAndApply(&sm);
  813. }
  814. }
  815. return ret;
  816. }
  817. CGameHandler::CGameHandler(void)
  818. {
  819. QID = 1;
  820. gs = NULL;
  821. IObjectInterface::cb = this;
  822. applier = new CApplier<CBaseForGHApply>;
  823. registerTypes3(*applier);
  824. visitObjectAfterVictory = false;
  825. }
  826. CGameHandler::~CGameHandler(void)
  827. {
  828. delete applier;
  829. applier = NULL;
  830. delete gs;
  831. }
  832. void CGameHandler::init(StartInfo *si, int Seed)
  833. {
  834. gs = new CGameState();
  835. tlog0 << "Gamestate created!" << std::endl;
  836. gs->init(si, 0, Seed);
  837. tlog0 << "Gamestate initialized!" << std::endl;
  838. for(std::map<ui8,PlayerState>::iterator i = gs->players.begin(); i != gs->players.end(); i++)
  839. states.addPlayer(i->first);
  840. }
  841. static bool evntCmp(const CMapEvent *a, const CMapEvent *b)
  842. {
  843. return *a < *b;
  844. }
  845. void CGameHandler::setPortalDwelling(const CGTownInstance * town, bool forced=false, bool clear = false)
  846. {// bool forced = true - if creature should be replaced, if false - only if no creature was set
  847. if (forced || town->creatures[CREATURES_PER_TOWN].second.empty())//we need to change creature
  848. {
  849. SetAvailableCreatures ssi;
  850. ssi.tid = town->id;
  851. ssi.creatures = town->creatures;
  852. ssi.creatures[CREATURES_PER_TOWN].second.clear();//remove old one
  853. const std::vector<CGDwelling *> &dwellings = gs->getPlayer(town->tempOwner)->dwellings;
  854. if (dwellings.empty())//no dwellings - just remove
  855. {
  856. sendAndApply(&ssi);
  857. return;
  858. }
  859. ui32 dwellpos = rand()%dwellings.size();//take random dwelling
  860. ui32 creapos = rand()%dwellings[dwellpos]->creatures.size();//for multi-creature dwellings like Golem Factory
  861. ui32 creature = dwellings[dwellpos]->creatures[creapos].second[0];
  862. if (clear)
  863. ssi.creatures[CREATURES_PER_TOWN].first = std::max((ui32)1, (VLC->creh->creatures[creature]->growth)/2);
  864. else
  865. ssi.creatures[CREATURES_PER_TOWN].first = VLC->creh->creatures[creature]->growth;
  866. ssi.creatures[CREATURES_PER_TOWN].second.push_back(creature);
  867. sendAndApply(&ssi);
  868. }
  869. }
  870. void CGameHandler::newTurn()
  871. {
  872. tlog5 << "Turn " << gs->day+1 << std::endl;
  873. NewTurn n;
  874. n.creatureid = -1;
  875. n.day = gs->day + 1;
  876. n.resetBuilded = true;
  877. bool newmonth = false;
  878. std::map<ui8, si32> hadGold;//starting gold - for buildings like dwarven treasury
  879. srand(time(NULL));
  880. if (getDate(1) == 7 && getDate(0)>1) //new week (day numbers are confusing, as day was not yet switched)
  881. {
  882. int monsterid;
  883. int monthType = rand()%100;
  884. if(getDate(4) == 28) //new month
  885. {
  886. newmonth = true;
  887. if (monthType < 40) //double growth
  888. {
  889. n.specialWeek = NewTurn::DOUBLE_GROWTH;
  890. if (ALLCREATURESGETDOUBLEMONTHS)
  891. {
  892. std::pair<int,int> newMonster(54, VLC->creh->pickRandomMonster(boost::ref(rand)));
  893. n.creatureid = newMonster.second;
  894. }
  895. else
  896. {
  897. std::set<TCreature>::const_iterator it = VLC->creh->doubledCreatures.begin();
  898. std::advance (it, rand() % VLC->creh->doubledCreatures.size()); //picking random elelemnt of set is tiring
  899. n.creatureid = *it;
  900. }
  901. }
  902. else if (monthType < 90)
  903. n.specialWeek = NewTurn::NORMAL;
  904. else
  905. n.specialWeek = NewTurn::PLAGUE;
  906. }
  907. else //it's a week, but not full month
  908. {
  909. newmonth = false;
  910. if (monthType < 25)
  911. {
  912. n.specialWeek = NewTurn::BONUS_GROWTH; //+5
  913. std::pair<int,int> newMonster (54, VLC->creh->pickRandomMonster(boost::ref(rand)));
  914. monsterid = newMonster.second;
  915. }
  916. else
  917. n.specialWeek = NewTurn::NORMAL;
  918. }
  919. }
  920. else
  921. n.specialWeek = NewTurn::NO_ACTION; //don't remove bonuses
  922. std::map<ui32,CGHeroInstance *> pool = gs->hpool.heroesPool;
  923. for ( std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  924. {
  925. if(i->first == 255)
  926. continue;
  927. else if(i->first >= PLAYER_LIMIT)
  928. assert(0); //illegal player number!
  929. std::pair<ui8,si32> playerGold(i->first,i->second.resources[6]);
  930. hadGold.insert(playerGold);
  931. if(gs->getDate(1)==7) //first day of week - new heroes in tavern
  932. {
  933. SetAvailableHeroes sah;
  934. sah.player = i->first;
  935. //pick heroes and their armies
  936. CHeroClass *banned = NULL;
  937. for (int j = 0; j < AVAILABLE_HEROES_PER_PLAYER; j++)
  938. {
  939. if(CGHeroInstance *h = gs->hpool.pickHeroFor(j == 0, i->first, getNativeTown(i->first), pool, banned)) //first hero - native if possible, second hero -> any other class
  940. {
  941. sah.hid[j] = h->subID;
  942. h->initArmy(sah.army[j] = new CCreatureSet());
  943. banned = h->type->heroClass;
  944. }
  945. else
  946. sah.hid[j] = -1;
  947. }
  948. sendAndApply(&sah);
  949. }
  950. n.res[i->first] = i->second.resources;
  951. // SetResources r;
  952. // r.player = i->first;
  953. // for(int j=0;j<RESOURCE_QUANTITY;j++)
  954. // r.res[j] = i->second.resources[j];
  955. BOOST_FOREACH(CGHeroInstance *h, (*i).second.heroes)
  956. {
  957. if(h->visitedTown)
  958. giveSpells(h->visitedTown, h);
  959. NewTurn::Hero hth;
  960. hth.id = h->id;
  961. hth.move = h->maxMovePoints(gs->map->getTile(h->getPosition(false)).tertype != TerrainTile::water);
  962. if(h->visitedTown && vstd::contains(h->visitedTown->builtBuildings,0)) //if hero starts turn in town with mage guild
  963. hth.mana = std::max(h->mana, h->manaLimit()); //restore all mana
  964. else
  965. hth.mana = std::max(si32(0), std::max(h->mana, std::min(h->mana + h->manaRegain(), h->manaLimit())) );
  966. n.heroes.insert(hth);
  967. if(gs->day) //not first day
  968. {
  969. n.res[i->first][6] += h->valOfBonuses(Selector::typeSybtype(Bonus::SECONDARY_SKILL, 13)); //estates
  970. for (int k = 0; k < RESOURCE_QUANTITY; k++)
  971. {
  972. n.res[i->first][k] += h->valOfBonuses(Bonus::GENERATE_RESOURCE, k);
  973. }
  974. }
  975. }
  976. //n.res.push_back(r);
  977. }
  978. // townID, creatureID, amount
  979. std::map<si32, std::map<si32, si32> > newCreas;//creatures that needs to be added by town events
  980. for(std::vector<CGTownInstance *>::iterator j = gs->map->towns.begin(); j!=gs->map->towns.end(); j++)//handle towns
  981. {
  982. ui8 player = (*j)->tempOwner;
  983. if(gs->getDate(1)==7) //first day of week
  984. {
  985. if ((*j)->subID == 5 && vstd::contains((*j)->builtBuildings, 22))
  986. setPortalDwelling(*j, true, (n.specialWeek == NewTurn::PLAGUE ? true : false)); //set creatures for Portal of Summoning
  987. if ((**j).subID == 1 && gs->getDate(0) && player < PLAYER_LIMIT && vstd::contains((**j).builtBuildings, 22))//dwarven treasury
  988. n.res[player][6] += hadGold[player]/10; //give 10% of starting gold
  989. }
  990. if(gs->day && player < PLAYER_LIMIT)//not the first day and town not neutral
  991. {
  992. ////SetResources r;
  993. //r.player = (**j).tempOwner;
  994. if(vstd::contains((**j).builtBuildings,15)) //there is resource silo
  995. {
  996. if((**j).town->primaryRes == 127) //we'll give wood and ore
  997. {
  998. n.res[player][0] += 1;
  999. n.res[player][2] += 1;
  1000. }
  1001. else
  1002. {
  1003. n.res[player][(**j).town->primaryRes] += 1;
  1004. }
  1005. }
  1006. n.res[player][6] += (**j).dailyIncome();
  1007. }
  1008. handleTownEvents(*j, n, newCreas);
  1009. if (vstd::contains((**j).builtBuildings, 26))
  1010. {
  1011. switch ((**j).subID)
  1012. {
  1013. case 2: // Skyship, probably easier to handle same as Veil of darkness
  1014. { //do it every new day after veils apply
  1015. FoWChange fw;
  1016. fw.mode = 1;
  1017. fw.player = player;
  1018. getAllTiles(fw.tiles, player, -1, 0);
  1019. sendAndApply (&fw);
  1020. }
  1021. break;
  1022. case 3: //Deity of Fire
  1023. {
  1024. if (getDate(0) > 1)
  1025. {
  1026. n.specialWeek = NewTurn::DEITYOFFIRE; //spawn familiars on new month
  1027. n.creatureid = 42; //familiar
  1028. }
  1029. }
  1030. break;
  1031. }
  1032. }
  1033. if ((**j).hasBonusOfType (Bonus::DARKNESS))
  1034. {
  1035. (**j).hideTiles((**j).getOwner(), (**j).getBonus(Selector::type(Bonus::DARKNESS))->val);
  1036. }
  1037. //unhiding what shouldn't be hidden? //that's handled in netpacks client
  1038. }
  1039. if(getDate(2) == 1) //first week
  1040. {
  1041. SetAvailableArtifacts saa;
  1042. saa.id = -1;
  1043. pickAllowedArtsSet(saa.arts);
  1044. sendAndApply(&saa);
  1045. }
  1046. sendAndApply(&n);
  1047. if (gs->getDate(1)==1) //first day of week, day has already been changed
  1048. {
  1049. if (getDate(4) == 1 && (n.specialWeek == NewTurn::DOUBLE_GROWTH || n.specialWeek == NewTurn::DEITYOFFIRE))
  1050. { //spawn wandering monsters
  1051. std::vector<int3>::iterator tile;
  1052. std::vector<int3> tiles;
  1053. getFreeTiles(tiles);
  1054. ui32 amount = (tiles.size()) >> 6;
  1055. std::random_shuffle(tiles.begin(), tiles.end(), p_myrandom);
  1056. for (int i = 0; i < amount; ++i)
  1057. {
  1058. tile = tiles.begin();
  1059. TerrainTile *tinfo = &gs->map->terrain[tile->x][tile->y][tile->z];
  1060. NewObject no;
  1061. no.ID = 54; //creature
  1062. no.subID= n.creatureid;
  1063. no.pos = *tile;
  1064. sendAndApply(&no);
  1065. tiles.erase(tile); //not use it again
  1066. }
  1067. }
  1068. NewTurn n2; //just to handle creature growths after bonuses are applied
  1069. n2.specialWeek = NewTurn::NO_ACTION;
  1070. n2.day = gs->day;
  1071. for(std::vector<CGTownInstance *>::iterator j = gs->map->towns.begin(); j!=gs->map->towns.end(); j++)//handle towns
  1072. {
  1073. ui8 player = (*j)->tempOwner;
  1074. SetAvailableCreatures sac;
  1075. sac.tid = (**j).id;
  1076. sac.creatures = (**j).creatures;
  1077. for (int k=0; k < CREATURES_PER_TOWN; k++) //creature growths
  1078. {
  1079. if((**j).creatureDwelling(k))//there is dwelling (k-level)
  1080. {
  1081. if (n.specialWeek == NewTurn::PLAGUE)
  1082. sac.creatures[k].first = (**j).creatures[k].first / 2; //halve their number, no growth
  1083. else
  1084. {
  1085. sac.creatures[k].first += (**j).creatureGrowth(k);
  1086. if(gs->getDate(0) == 1) //first day of game: use only basic growths
  1087. amin(sac.creatures[k].first, VLC->creh->creatures[(*j)->town->basicCreatures[k]]->growth);
  1088. }
  1089. }
  1090. }
  1091. //creatures from town events
  1092. if (vstd::contains(newCreas, (**j).id))
  1093. for(std::map<si32, si32>::iterator i=newCreas[(**j).id].begin() ; i!=newCreas[(**j).id].end(); i++)
  1094. sac.creatures[i->first].first += i->second;
  1095. n2.cres.push_back(sac);
  1096. }
  1097. if (gs->getDate(0) > 1)
  1098. {
  1099. InfoWindow iw; //new week info
  1100. switch (n.specialWeek)
  1101. {
  1102. case NewTurn::DOUBLE_GROWTH:
  1103. iw.text.addTxt(MetaString::ARRAY_TXT, 131);
  1104. iw.text.addReplacement(MetaString::CRE_SING_NAMES, n.creatureid);
  1105. iw.text.addReplacement(MetaString::CRE_SING_NAMES, n.creatureid);
  1106. break;
  1107. case NewTurn::PLAGUE:
  1108. iw.text.addTxt(MetaString::ARRAY_TXT, 132);
  1109. break;
  1110. case NewTurn::BONUS_GROWTH:
  1111. iw.text.addTxt(MetaString::ARRAY_TXT, 134);
  1112. iw.text.addReplacement(MetaString::CRE_SING_NAMES, n.creatureid);
  1113. iw.text.addReplacement(MetaString::CRE_SING_NAMES, n.creatureid);
  1114. break;
  1115. case NewTurn::DEITYOFFIRE:
  1116. iw.text.addTxt(MetaString::ARRAY_TXT, 135);
  1117. iw.text.addReplacement(MetaString::CRE_SING_NAMES, 42); //%s imp
  1118. iw.text.addReplacement(MetaString::CRE_SING_NAMES, 42); //%s imp
  1119. iw.text.addReplacement2(15); //%+d 15
  1120. iw.text.addReplacement(MetaString::CRE_SING_NAMES, 43); //%s familiar
  1121. iw.text.addReplacement2(15); //%+d 15
  1122. break;
  1123. default:
  1124. iw.text.addTxt(MetaString::ARRAY_TXT, (newmonth ? 130 : 133));
  1125. iw.text.addReplacement(MetaString::ARRAY_TXT, 43 + rand()%15);
  1126. }
  1127. for (std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end(); i++)
  1128. {
  1129. iw.player = i->first;
  1130. sendAndApply(&iw);
  1131. }
  1132. }
  1133. sendAndApply(&n2);
  1134. }
  1135. tlog5 << "Info about turn " << n.day << "has been sent!" << std::endl;
  1136. handleTimeEvents();
  1137. //call objects
  1138. for(size_t i = 0; i<gs->map->objects.size(); i++)
  1139. {
  1140. if(gs->map->objects[i])
  1141. gs->map->objects[i]->newTurn();
  1142. }
  1143. winLoseHandle(0xff);
  1144. //warn players without town
  1145. if(gs->day)
  1146. {
  1147. for (std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  1148. {
  1149. if(i->second.status || i->second.towns.size() || i->second.color >= PLAYER_LIMIT)
  1150. continue;
  1151. InfoWindow iw;
  1152. iw.player = i->first;
  1153. iw.components.push_back(Component(Component::FLAG,i->first,0,0));
  1154. if(!i->second.daysWithoutCastle)
  1155. {
  1156. iw.text.addTxt(MetaString::GENERAL_TXT,6); //%s, you have lost your last town. If you do not conquer another town in the next week, you will be eliminated.
  1157. iw.text.addReplacement(MetaString::COLOR, i->first);
  1158. }
  1159. else if(i->second.daysWithoutCastle == 6)
  1160. {
  1161. iw.text.addTxt(MetaString::ARRAY_TXT,129); //%s, this is your last day to capture a town or you will be banished from this land.
  1162. iw.text.addReplacement(MetaString::COLOR, i->first);
  1163. }
  1164. else
  1165. {
  1166. iw.text.addTxt(MetaString::ARRAY_TXT,128); //%s, you only have %d days left to capture a town or you will be banished from this land.
  1167. iw.text.addReplacement(MetaString::COLOR, i->first);
  1168. iw.text.addReplacement(7 - i->second.daysWithoutCastle);
  1169. }
  1170. sendAndApply(&iw);
  1171. }
  1172. }
  1173. }
  1174. void CGameHandler::run(bool resume)
  1175. {
  1176. using namespace boost::posix_time;
  1177. BOOST_FOREACH(CConnection *cc, conns)
  1178. {//init conn.
  1179. ui32 quantity;
  1180. ui8 pom;
  1181. //ui32 seed;
  1182. if(!resume)
  1183. (*cc) << gs->scenarioOps << gs->map->checksum << gs->seed; // gs->scenarioOps
  1184. (*cc) >> quantity; //how many players will be handled at that client
  1185. tlog0 << "Connection " << cc->connectionID << " will handle " << quantity << " player: ";
  1186. for(int i=0;i<quantity;i++)
  1187. {
  1188. (*cc) >> pom; //read player color
  1189. tlog0 << (int)pom << " ";
  1190. {
  1191. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  1192. connections[pom] = cc;
  1193. }
  1194. }
  1195. tlog0 << std::endl;
  1196. }
  1197. for(std::set<CConnection*>::iterator i = conns.begin(); i!=conns.end();i++)
  1198. {
  1199. std::set<int> pom;
  1200. for(std::map<int,CConnection*>::iterator j = connections.begin(); j!=connections.end();j++)
  1201. if(j->second == *i)
  1202. pom.insert(j->first);
  1203. boost::thread(boost::bind(&CGameHandler::handleConnection,this,pom,boost::ref(**i)));
  1204. }
  1205. while (!end2)
  1206. {
  1207. if(!resume)
  1208. newTurn();
  1209. std::map<ui8,PlayerState>::iterator i;
  1210. if(!resume)
  1211. i = gs->players.begin();
  1212. else
  1213. i = gs->players.find(gs->currentPlayer);
  1214. resume = false;
  1215. for(; i != gs->players.end(); i++)
  1216. {
  1217. if(i->second.towns.size()==0 && i->second.heroes.size()==0
  1218. || i->second.color<0
  1219. || i->first>=PLAYER_LIMIT
  1220. || i->second.status)
  1221. {
  1222. continue;
  1223. }
  1224. states.setFlag(i->first,&PlayerStatus::makingTurn,true);
  1225. {
  1226. YourTurn yt;
  1227. yt.player = i->first;
  1228. sendAndApply(&yt);
  1229. }
  1230. //wait till turn is done
  1231. boost::unique_lock<boost::mutex> lock(states.mx);
  1232. while(states.players[i->first].makingTurn && !end2)
  1233. {
  1234. static time_duration p = milliseconds(200);
  1235. states.cv.timed_wait(lock,p);
  1236. }
  1237. }
  1238. }
  1239. while(conns.size() && (*conns.begin())->isOpen())
  1240. boost::this_thread::sleep(boost::posix_time::milliseconds(5)); //give time client to close socket
  1241. }
  1242. namespace CGH
  1243. {
  1244. using namespace std;
  1245. static void readItTo(ifstream & input, vector< vector<int> > & dest) //reads 7 lines, i-th one containing i integers, and puts it to dest
  1246. {
  1247. for(int j=0; j<7; ++j)
  1248. {
  1249. std::vector<int> pom;
  1250. for(int g=0; g<j+1; ++g)
  1251. {
  1252. int hlp; input>>hlp;
  1253. pom.push_back(hlp);
  1254. }
  1255. dest.push_back(pom);
  1256. }
  1257. }
  1258. }
  1259. void CGameHandler::setupBattle(BattleInfo * curB, int3 tile, const CArmedInstance *army1, const CArmedInstance *army2, const CGHeroInstance * hero1, const CGHeroInstance * hero2, bool creatureBank, const CGTownInstance *town)
  1260. {
  1261. battleResult.set(NULL);
  1262. std::vector<CStack*> & stacks = (curB->stacks);
  1263. curB->tile = tile;
  1264. curB->belligerents[0] = const_cast<CArmedInstance*>(army1);
  1265. curB->belligerents[1] = const_cast<CArmedInstance*>(army2);
  1266. curB->heroes[0] = const_cast<CGHeroInstance*>(hero1);
  1267. curB->heroes[1] = const_cast<CGHeroInstance*>(hero2);
  1268. curB->round = -2;
  1269. curB->activeStack = -1;
  1270. if(town)
  1271. {
  1272. curB->tid = town->id;
  1273. curB->siege = town->fortLevel();
  1274. }
  1275. else
  1276. {
  1277. curB->tid = -1;
  1278. curB->siege = 0;
  1279. }
  1280. //reading battleStartpos
  1281. std::ifstream positions;
  1282. positions.open(DATA_DIR "/config/battleStartpos.txt", std::ios_base::in|std::ios_base::binary);
  1283. if(!positions.is_open())
  1284. {
  1285. tlog1<<"Unable to open battleStartpos.txt!"<<std::endl;
  1286. }
  1287. std::string dump;
  1288. positions>>dump; positions>>dump;
  1289. std::vector< std::vector<int> > attackerLoose, defenderLoose, attackerTight, defenderTight, attackerCreBank, defenderCreBank;
  1290. CGH::readItTo(positions, attackerLoose);
  1291. positions>>dump;
  1292. CGH::readItTo(positions, defenderLoose);
  1293. positions>>dump;
  1294. positions>>dump;
  1295. CGH::readItTo(positions, attackerTight);
  1296. positions>>dump;
  1297. CGH::readItTo(positions, defenderTight);
  1298. positions>>dump;
  1299. positions>>dump;
  1300. CGH::readItTo(positions, attackerCreBank);
  1301. positions>>dump;
  1302. CGH::readItTo(positions, defenderCreBank);
  1303. positions.close();
  1304. //battleStartpos read
  1305. int k = 0; //stack serial
  1306. for(TSlots::const_iterator i = army1->Slots().begin(); i!=army1->Slots().end(); i++, k++)
  1307. {
  1308. int pos;
  1309. if(creatureBank)
  1310. pos = attackerCreBank[army1->stacksCount()-1][k];
  1311. else if(army1->formation)
  1312. pos = attackerTight[army1->stacksCount()-1][k];
  1313. else
  1314. pos = attackerLoose[army1->stacksCount()-1][k];
  1315. CStack * stack = curB->generateNewStack(i->second, stacks.size(), true, i->first, gs->map->terrain[tile.x][tile.y][tile.z].tertype, pos);
  1316. stacks.push_back(stack);
  1317. }
  1318. k = 0;
  1319. for(TSlots::const_iterator i = army2->Slots().begin(); i!=army2->Slots().end(); i++, k++)
  1320. {
  1321. int pos;
  1322. if(creatureBank)
  1323. pos = defenderCreBank[army2->stacksCount()-1][k];
  1324. else if(army2->formation)
  1325. pos = defenderTight[army2->stacksCount()-1][k];
  1326. else
  1327. pos = defenderLoose[army2->stacksCount()-1][k];
  1328. CStack * stack = curB->generateNewStack(i->second, stacks.size(), false, i->first, gs->map->terrain[tile.x][tile.y][tile.z].tertype, pos);
  1329. stacks.push_back(stack);
  1330. }
  1331. for(unsigned g=0; g<stacks.size(); ++g) //shifting positions of two-hex creatures
  1332. {
  1333. if((stacks[g]->position%17)==1 && stacks[g]->doubleWide() && stacks[g]->attackerOwned)
  1334. {
  1335. stacks[g]->position += 1;
  1336. }
  1337. else if((stacks[g]->position%17)==15 && stacks[g]->doubleWide() && !stacks[g]->attackerOwned)
  1338. {
  1339. stacks[g]->position -= 1;
  1340. }
  1341. }
  1342. //adding war machines
  1343. if(hero1)
  1344. {
  1345. if(hero1->getArt(13)) //ballista
  1346. {
  1347. CStack * stack = curB->generateNewStack(CStackInstance(146, 1, hero1), stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 52);
  1348. stacks.push_back(stack);
  1349. }
  1350. if(hero1->getArt(14)) //ammo cart
  1351. {
  1352. CStack * stack = curB->generateNewStack(CStackInstance(148, 1, hero1), stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 18);
  1353. stacks.push_back(stack);
  1354. }
  1355. if(hero1->getArt(15)) //first aid tent
  1356. {
  1357. CStack * stack = curB->generateNewStack(CStackInstance(147, 1, hero1), stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 154);
  1358. stacks.push_back(stack);
  1359. }
  1360. }
  1361. if(hero2)
  1362. {
  1363. //defending hero shouldn't receive ballista (bug #551)
  1364. if(hero2->getArt(13) && !town) //ballista
  1365. {
  1366. CStack * stack = curB->generateNewStack(CStackInstance(146, 1, hero2), stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 66);
  1367. stacks.push_back(stack);
  1368. }
  1369. if(hero2->getArt(14)) //ammo cart
  1370. {
  1371. CStack * stack = curB->generateNewStack(CStackInstance(148, 1, hero1), stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 32);
  1372. stacks.push_back(stack);
  1373. }
  1374. if(hero2->getArt(15)) //first aid tent
  1375. {
  1376. CStack * stack = curB->generateNewStack(CStackInstance(147, 1, hero2), stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 168);
  1377. stacks.push_back(stack);
  1378. }
  1379. }
  1380. if(town && hero1 && town->hasFort()) //catapult
  1381. {
  1382. CStack * stack = curB->generateNewStack(CStackInstance(145, 1, hero1), stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 120);
  1383. stacks.push_back(stack);
  1384. }
  1385. //war machines added
  1386. switch(curB->siege) //adding towers
  1387. {
  1388. case 3: //castle
  1389. {//lower tower / upper tower
  1390. CStack * stack = curB->generateNewStack(CStackInstance(149, 1, hero2), stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, -4);
  1391. stacks.push_back(stack);
  1392. stack = curB->generateNewStack(CStackInstance(149, 1, hero2), stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, -3);
  1393. stacks.push_back(stack);
  1394. }
  1395. case 2: //citadel
  1396. {//main tower
  1397. CStack * stack = curB->generateNewStack(CStackInstance(149, 1, hero2), stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, -2);
  1398. stacks.push_back(stack);
  1399. }
  1400. }
  1401. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  1402. //seting up siege
  1403. if(town && town->hasFort())
  1404. {
  1405. for(int b=0; b<ARRAY_COUNT(curB->si.wallState); ++b)
  1406. {
  1407. curB->si.wallState[b] = 1;
  1408. }
  1409. }
  1410. int terType = gs->battleGetBattlefieldType(tile);
  1411. //randomize obstacles
  1412. if(town == NULL && !creatureBank) //do it only when it's not siege and not creature bank
  1413. {
  1414. bool obAv[BFIELD_SIZE]; //availability of hexes for obstacles;
  1415. std::vector<int> possibleObstacles;
  1416. for(int i=0; i<BFIELD_SIZE; ++i)
  1417. {
  1418. if(i%17 < 4 || i%17 > 12)
  1419. {
  1420. obAv[i] = false;
  1421. }
  1422. else
  1423. {
  1424. obAv[i] = true;
  1425. }
  1426. }
  1427. for(std::map<int, CObstacleInfo>::const_iterator g=VLC->heroh->obstacles.begin(); g!=VLC->heroh->obstacles.end(); ++g)
  1428. {
  1429. if(g->second.allowedTerrains[terType-1] == '1') //we need to take terType with -1 because terrain ids start from 1 and allowedTerrains array is indexed from 0
  1430. {
  1431. possibleObstacles.push_back(g->first);
  1432. }
  1433. }
  1434. srand(time(NULL));
  1435. if(possibleObstacles.size() > 0) //we cannot place any obstacles when we don't have them
  1436. {
  1437. int toBlock = rand()%6 + 6; //how many hexes should be blocked by obstacles
  1438. while(toBlock>0)
  1439. {
  1440. CObstacleInstance coi;
  1441. coi.uniqueID = curB->obstacles.size();
  1442. coi.ID = possibleObstacles[rand()%possibleObstacles.size()];
  1443. coi.pos = rand()%BFIELD_SIZE;
  1444. std::vector<int> block = VLC->heroh->obstacles[coi.ID].getBlocked(coi.pos);
  1445. bool badObstacle = false;
  1446. for(int b=0; b<block.size(); ++b)
  1447. {
  1448. if(block[b] < 0 || block[b] >= BFIELD_SIZE || !obAv[block[b]])
  1449. {
  1450. badObstacle = true;
  1451. break;
  1452. }
  1453. }
  1454. if(badObstacle) continue;
  1455. //obstacle can be placed
  1456. curB->obstacles.push_back(coi);
  1457. for(int b=0; b<block.size(); ++b)
  1458. {
  1459. if(block[b] >= 0 && block[b] < BFIELD_SIZE)
  1460. obAv[block[b]] = false;
  1461. }
  1462. toBlock -= block.size();
  1463. }
  1464. }
  1465. }
  1466. //giving building bonuses, if siege and we have harrisoned hero
  1467. if (town)
  1468. {
  1469. if (hero2)
  1470. {
  1471. for (int i=0; i<4; i++)
  1472. {
  1473. int val = town->defenceBonus(i);
  1474. if (val)
  1475. {
  1476. GiveBonus gs;
  1477. gs.bonus = Bonus(Bonus::ONE_BATTLE, Bonus::PRIMARY_SKILL, Bonus::OBJECT, val, -1, "", i);
  1478. gs.id = hero2->id;
  1479. sendAndApply(&gs);
  1480. }
  1481. }
  1482. }
  1483. else//if we don't have hero - apply separately, if hero present - will be taken from hero bonuses
  1484. {
  1485. if(town->subID == 0 && vstd::contains(town->builtBuildings,22)) //castle, brotherhood of sword built
  1486. for(int g=0; g<stacks.size(); ++g)
  1487. stacks[g]->bonuses.push_back(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, 2, Bonus::TOWN_STRUCTURE));
  1488. else if(vstd::contains(town->builtBuildings,5)) //tavern is built
  1489. for(int g=0; g<stacks.size(); ++g)
  1490. stacks[g]->bonuses.push_back(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, 1, Bonus::TOWN_STRUCTURE));
  1491. if(town->subID == 1 && vstd::contains(town->builtBuildings,21)) //rampart, fountain of fortune is present
  1492. for(int g=0; g<stacks.size(); ++g)
  1493. stacks[g]->bonuses.push_back(makeFeature(Bonus::LUCK, Bonus::ONE_BATTLE, 0, 2, Bonus::TOWN_STRUCTURE));
  1494. }
  1495. }
  1496. //giving terrain premies for heroes & stacks
  1497. int bonusSubtype = -1;
  1498. switch(terType)
  1499. {
  1500. case 9: //magic plains
  1501. {
  1502. bonusSubtype = 0;
  1503. }
  1504. case 14: //fiery fields
  1505. {
  1506. if(bonusSubtype == -1) bonusSubtype = 1;
  1507. }
  1508. case 15: //rock lands
  1509. {
  1510. if(bonusSubtype == -1) bonusSubtype = 8;
  1511. }
  1512. case 16: //magic clouds
  1513. {
  1514. if(bonusSubtype == -1) bonusSubtype = 2;
  1515. }
  1516. case 17: //lucid pools
  1517. {
  1518. if(bonusSubtype == -1) bonusSubtype = 4;
  1519. }
  1520. { //common part for cases 9, 14, 15, 16, 17
  1521. const CGHeroInstance * cHero = NULL;
  1522. for(int i=0; i<2; ++i)
  1523. {
  1524. if(i == 0) cHero = hero1;
  1525. else cHero = hero2;
  1526. if(cHero == NULL) continue;
  1527. GiveBonus gs;
  1528. gs.bonus = Bonus(Bonus::ONE_BATTLE, Bonus::MAGIC_SCHOOL_SKILL, Bonus::OBJECT, 3, -1, "", bonusSubtype);
  1529. gs.id = cHero->id;
  1530. sendAndApply(&gs);
  1531. }
  1532. break;
  1533. }
  1534. case 18: //holy ground
  1535. {
  1536. for(int g=0; g<stacks.size(); ++g) //+1 morale bonus for good creatures, -1 morale bonus for evil creatures
  1537. {
  1538. if (stacks[g]->type->isGood())
  1539. stacks[g]->bonuses.push_back(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, 1, Bonus::TERRAIN_OVERLAY));
  1540. else if (stacks[g]->type->isEvil())
  1541. stacks[g]->bonuses.push_back(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY));
  1542. }
  1543. break;
  1544. }
  1545. case 19: //clover field
  1546. {
  1547. for(int g=0; g<stacks.size(); ++g)
  1548. {
  1549. if(stacks[g]->type->faction == -1) //+2 luck bonus for neutral creatures
  1550. {
  1551. stacks[g]->bonuses.push_back(makeFeature(Bonus::LUCK, Bonus::ONE_BATTLE, 0, 2, Bonus::TERRAIN_OVERLAY));
  1552. }
  1553. }
  1554. break;
  1555. }
  1556. case 20: //evil fog
  1557. {
  1558. for(int g=0; g<stacks.size(); ++g) //-1 morale bonus for good creatures, +1 morale bonus for evil creatures
  1559. {
  1560. if (stacks[g]->type->isGood())
  1561. stacks[g]->bonuses.push_back(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY));
  1562. else if (stacks[g]->type->isEvil())
  1563. stacks[g]->bonuses.push_back(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, 1, Bonus::TERRAIN_OVERLAY));
  1564. }
  1565. break;
  1566. }
  1567. case 22: //cursed ground
  1568. {
  1569. for(int g=0; g<stacks.size(); ++g) //no luck nor morale
  1570. {
  1571. stacks[g]->bonuses.push_back(makeFeature(Bonus::NO_MORALE, Bonus::ONE_BATTLE, 0, 0, Bonus::TERRAIN_OVERLAY));
  1572. stacks[g]->bonuses.push_back(makeFeature(Bonus::NO_LUCK, Bonus::ONE_BATTLE, 0, 0, Bonus::TERRAIN_OVERLAY));
  1573. }
  1574. const CGHeroInstance * cHero = NULL;
  1575. for(int i=0; i<2; ++i) //blocking spells above level 1
  1576. {
  1577. if(i == 0) cHero = hero1;
  1578. else cHero = hero2;
  1579. if(cHero == NULL) continue;
  1580. GiveBonus gs;
  1581. gs.bonus = Bonus(Bonus::ONE_BATTLE, Bonus::BLOCK_SPELLS_ABOVE_LEVEL, Bonus::OBJECT, 1, -1, "", bonusSubtype);
  1582. gs.id = cHero->id;
  1583. sendAndApply(&gs);
  1584. }
  1585. break;
  1586. }
  1587. }
  1588. //premies given
  1589. //send info about battles
  1590. BattleStart bs;
  1591. bs.info = curB;
  1592. sendAndApply(&bs);
  1593. }
  1594. void CGameHandler::checkForBattleEnd( std::vector<CStack*> &stacks )
  1595. {
  1596. //checking winning condition
  1597. bool hasStack[2]; //hasStack[0] - true if attacker has a living stack; defender similarily
  1598. hasStack[0] = hasStack[1] = false;
  1599. for(int b = 0; b<stacks.size(); ++b)
  1600. {
  1601. if(stacks[b]->alive() && !stacks[b]->hasBonusOfType(Bonus::SIEGE_WEAPON))
  1602. {
  1603. hasStack[1-stacks[b]->attackerOwned] = true;
  1604. }
  1605. }
  1606. if(!hasStack[0] || !hasStack[1]) //somebody has won
  1607. {
  1608. BattleResult *br = new BattleResult; //will be deleted at the end of startBattle(...)
  1609. br->result = 0;
  1610. br->winner = hasStack[1]; //fleeing side loses
  1611. gs->curB->calculateCasualties(br->casualties);
  1612. battleResult.set(br);
  1613. }
  1614. }
  1615. void CGameHandler::giveSpells( const CGTownInstance *t, const CGHeroInstance *h )
  1616. {
  1617. if(!vstd::contains(h->artifWorn,17))
  1618. return; //hero hasn't spellbok
  1619. ChangeSpells cs;
  1620. cs.hid = h->id;
  1621. cs.learn = true;
  1622. for(int i=0; i<std::min(t->mageGuildLevel(),h->getSecSkillLevel(7)+2);i++)
  1623. {
  1624. if (t->subID == 8 && vstd::contains(t->builtBuildings, 26)) //Aurora Borealis
  1625. {
  1626. std::vector<ui16> spells;
  1627. getAllowedSpells(spells, i);
  1628. for (int j = 0; j < spells.size(); ++j)
  1629. cs.spells.insert(spells[j]);
  1630. }
  1631. else
  1632. {
  1633. for(int j=0; j<t->spellsAtLevel(i+1,true) && j<t->spells[i].size(); j++)
  1634. {
  1635. if(!vstd::contains(h->spells,t->spells[i][j]))
  1636. cs.spells.insert(t->spells[i][j]);
  1637. }
  1638. }
  1639. }
  1640. if(cs.spells.size())
  1641. sendAndApply(&cs);
  1642. }
  1643. void CGameHandler::setBlockVis(int objid, bool bv)
  1644. {
  1645. SetObjectProperty sop(objid,2,bv);
  1646. sendAndApply(&sop);
  1647. }
  1648. bool CGameHandler::removeObject( int objid )
  1649. {
  1650. if(!getObj(objid))
  1651. {
  1652. tlog1 << "Something wrong, that object already has been removed or hasn't existed!\n";
  1653. return false;
  1654. }
  1655. RemoveObject ro;
  1656. ro.id = objid;
  1657. sendAndApply(&ro);
  1658. winLoseHandle(255); //eg if monster escaped (removing objs after battle is done dircetly by endBattle, not this function)
  1659. return true;
  1660. }
  1661. void CGameHandler::setAmount(int objid, ui32 val)
  1662. {
  1663. SetObjectProperty sop(objid,3,val);
  1664. sendAndApply(&sop);
  1665. }
  1666. bool CGameHandler::moveHero( si32 hid, int3 dst, ui8 instant, ui8 asker /*= 255*/ )
  1667. {
  1668. bool blockvis = false;
  1669. const CGHeroInstance *h = getHero(hid);
  1670. if(!h || asker != 255 && (instant || h->getOwner() != gs->currentPlayer) //not turn of that hero or player can't simply teleport hero (at least not with this function)
  1671. )
  1672. {
  1673. tlog1 << "Illegal call to move hero!\n";
  1674. return false;
  1675. }
  1676. tlog5 << "Player " <<int(asker) << " wants to move hero "<< hid << " from "<< h->pos << " to " << dst << std::endl;
  1677. int3 hmpos = dst + int3(-1,0,0);
  1678. if(!gs->map->isInTheMap(hmpos))
  1679. {
  1680. tlog1 << "Destination tile is outside the map!\n";
  1681. return false;
  1682. }
  1683. TerrainTile t = gs->map->terrain[hmpos.x][hmpos.y][hmpos.z];
  1684. int cost = gs->getMovementCost(h, h->getPosition(false), CGHeroInstance::convertPosition(dst,false),h->movement);
  1685. int3 guardPos = gs->guardingCreaturePosition(hmpos);
  1686. //result structure for start - movement failed, no move points used
  1687. TryMoveHero tmh;
  1688. tmh.id = hid;
  1689. tmh.start = h->pos;
  1690. tmh.end = dst;
  1691. tmh.result = TryMoveHero::FAILED;
  1692. tmh.movePoints = h->movement;
  1693. //check if destination tile is available
  1694. //it's a rock or blocked and not visitable tile
  1695. //OR hero is on land and dest is water and (there is not present only one object - boat)
  1696. if((t.tertype == TerrainTile::rock || (t.blocked && !t.visitable && !h->hasBonusOfType(Bonus::FLYING_MOVEMENT) ))
  1697. && complain("Cannot move hero, destination tile is blocked!")
  1698. || (!h->boat && !h->canWalkOnSea() && t.tertype == TerrainTile::water && (t.visitableObjects.size() != 1 || (t.visitableObjects.front()->ID != 8 && t.visitableObjects.front()->ID != HEROI_TYPE))) //hero is not on boat/water walking and dst water tile doesn't contain boat/hero (objs visitable from land)
  1699. && complain("Cannot move hero, destination tile is on water!")
  1700. || (h->boat && t.tertype != TerrainTile::water && t.blocked)
  1701. && complain("Cannot disembark hero, tile is blocked!")
  1702. || (h->movement < cost && dst != h->pos && !instant)
  1703. && complain("Hero doesn't have any movement points left!")
  1704. || states.checkFlag(h->tempOwner, &PlayerStatus::engagedIntoBattle)
  1705. && complain("Cannot move hero during the battle"))
  1706. {
  1707. //send info about movement failure
  1708. sendAndApply(&tmh);
  1709. return false;
  1710. }
  1711. //hero enters the boat
  1712. if(!h->boat && t.visitableObjects.size() && t.visitableObjects.front()->ID == 8)
  1713. {
  1714. tmh.result = TryMoveHero::EMBARK;
  1715. tmh.movePoints = 0; //embarking takes all move points
  1716. //TODO: check for bonus that removes that penalty
  1717. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1718. sendAndApply(&tmh);
  1719. return true;
  1720. }
  1721. //hero leaves the boat
  1722. else if(h->boat && t.tertype != TerrainTile::water && !t.blocked)
  1723. {
  1724. tmh.result = TryMoveHero::DISEMBARK;
  1725. tmh.movePoints = 0; //disembarking takes all move points
  1726. //TODO: check for bonus that removes that penalty
  1727. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1728. sendAndApply(&tmh);
  1729. tryAttackingGuard(guardPos, h);
  1730. return true;
  1731. }
  1732. //checks for standard movement
  1733. if(!instant)
  1734. {
  1735. if( distance(h->pos,dst) >= 1.5 && complain("Tiles are not neighboring!")
  1736. || h->movement < cost && h->movement < 100 && complain("Not enough move points!"))
  1737. {
  1738. sendAndApply(&tmh);
  1739. return false;
  1740. }
  1741. //check if there is blocking visitable object
  1742. blockvis = false;
  1743. tmh.movePoints = std::max(si32(0),h->movement-cost); //take move points
  1744. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1745. {
  1746. if(obj != h && obj->blockVisit && !(obj->getPassableness() & 1<<h->tempOwner))
  1747. {
  1748. blockvis = true;
  1749. break;
  1750. }
  1751. }
  1752. //we start moving
  1753. if(blockvis)//interaction with blocking object (like resources)
  1754. {
  1755. tmh.result = TryMoveHero::BLOCKING_VISIT;
  1756. sendAndApply(&tmh);
  1757. //failed to move to that tile but we visit object
  1758. if(t.visitableObjects.size())
  1759. objectVisited(t.visitableObjects.back(), h);
  1760. // BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1761. // {
  1762. // if (obj->blockVisit)
  1763. // {
  1764. // objectVisited(obj, h);
  1765. // }
  1766. // }
  1767. tlog5 << "Blocking visit at " << hmpos << std::endl;
  1768. return true;
  1769. }
  1770. else //normal move
  1771. {
  1772. BOOST_FOREACH(CGObjectInstance *obj, gs->map->terrain[h->pos.x-1][h->pos.y][h->pos.z].visitableObjects)
  1773. {
  1774. obj->onHeroLeave(h);
  1775. }
  1776. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1777. tmh.result = TryMoveHero::SUCCESS;
  1778. tmh.attackedFrom = guardPos;
  1779. sendAndApply(&tmh);
  1780. tlog5 << "Moved to " <<tmh.end<<std::endl;
  1781. // If a creature guards the tile, block visit.
  1782. const bool fightingGuard = tryAttackingGuard(guardPos, h);
  1783. if(!fightingGuard && t.visitableObjects.size()) //call objects if they are visited
  1784. {
  1785. visitObjectOnTile(t, h);
  1786. }
  1787. // BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1788. // {
  1789. // objectVisited(obj, h);
  1790. // }
  1791. tlog5 << "Movement end!\n";
  1792. return true;
  1793. }
  1794. }
  1795. else //instant move - teleportation
  1796. {
  1797. BOOST_FOREACH(CGObjectInstance* obj, t.blockingObjects)
  1798. {
  1799. if(obj->ID==HEROI_TYPE)
  1800. {
  1801. CGHeroInstance *dh = static_cast<CGHeroInstance *>(obj);
  1802. if( gameState()->getPlayerRelations(dh->tempOwner, h->tempOwner))
  1803. {
  1804. heroExchange(h->id, dh->id);
  1805. return true;
  1806. }
  1807. startBattleI(h, dh);
  1808. return true;
  1809. }
  1810. }
  1811. tmh.result = TryMoveHero::TELEPORTATION;
  1812. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1813. sendAndApply(&tmh);
  1814. return true;
  1815. }
  1816. }
  1817. bool CGameHandler::teleportHero(si32 hid, si32 dstid, ui8 source, ui8 asker/* = 255*/)
  1818. {
  1819. const CGHeroInstance *h = getHero(hid);
  1820. const CGTownInstance *t = getTown(dstid);
  1821. if ( !h || !t || h->getOwner() != gs->currentPlayer )
  1822. tlog1<<"Invalid call to teleportHero!";
  1823. const CGTownInstance *from = h->visitedTown;
  1824. if((h->getOwner() != t->getOwner())
  1825. && complain("Cannot teleport hero to another player")
  1826. || (!from || from->subID!=3 || !vstd::contains(from->builtBuildings, 22))
  1827. && complain("Hero must be in town with Castle gate for teleporting")
  1828. || (t->subID!=3 || !vstd::contains(t->builtBuildings, 22))
  1829. && complain("Cannot teleport hero to town without Castle gate in it"))
  1830. return false;
  1831. int3 pos = t->visitablePos();
  1832. pos += h->getVisitableOffset();
  1833. stopHeroVisitCastle(from->id, hid);
  1834. moveHero(hid,pos,1);
  1835. heroVisitCastle(dstid, hid);
  1836. return true;
  1837. }
  1838. void CGameHandler::setOwner(int objid, ui8 owner)
  1839. {
  1840. ui8 oldOwner = getOwner(objid);
  1841. SetObjectProperty sop(objid,1,owner);
  1842. sendAndApply(&sop);
  1843. winLoseHandle(1<<owner | 1<<oldOwner);
  1844. if(owner < PLAYER_LIMIT && getTown(objid)) //town captured
  1845. {
  1846. const CGTownInstance * town = getTown(objid);
  1847. if (town->subID == 5 && vstd::contains(town->builtBuildings, 22))
  1848. setPortalDwelling(town, true, false);
  1849. if (!gs->getPlayer(owner)->towns.size())//player lost last town
  1850. {
  1851. InfoWindow iw;
  1852. iw.player = oldOwner;
  1853. iw.text.addTxt(MetaString::GENERAL_TXT, 6); //%s, you have lost your last town. If you do not conquer another town in the next week, you will be eliminated.
  1854. sendAndApply(&iw);
  1855. }
  1856. }
  1857. const CGObjectInstance * obj = getObj(objid);
  1858. const PlayerState * p = gs->getPlayer(owner);
  1859. if((obj->ID == 17 || obj->ID == 20 ) && p && p->dwellings.size()==1)//first dwelling captured
  1860. BOOST_FOREACH(const CGTownInstance *t, gs->getPlayer(owner)->towns)
  1861. if (t->subID == 5 && vstd::contains(t->builtBuildings, 22))
  1862. setPortalDwelling(t);//set initial creatures for all portals of summoning
  1863. }
  1864. void CGameHandler::setHoverName(int objid, MetaString* name)
  1865. {
  1866. SetHoverName shn(objid, *name);
  1867. sendAndApply(&shn);
  1868. }
  1869. void CGameHandler::showInfoDialog(InfoWindow *iw)
  1870. {
  1871. sendToAllClients(iw);
  1872. }
  1873. void CGameHandler::showBlockingDialog( BlockingDialog *iw, const CFunctionList<void(ui32)> &callback )
  1874. {
  1875. ask(iw,iw->player,callback);
  1876. }
  1877. ui32 CGameHandler::showBlockingDialog( BlockingDialog *iw )
  1878. {
  1879. //TODO
  1880. //gsm.lock();
  1881. //int query = QID++;
  1882. //states.addQuery(player,query);
  1883. //sendToAllClients(iw);
  1884. //gsm.unlock();
  1885. //ui32 ret = getQueryResult(iw->player, query);
  1886. //gsm.lock();
  1887. //states.removeQuery(player, query);
  1888. //gsm.unlock();
  1889. return 0;
  1890. }
  1891. int CGameHandler::getCurrentPlayer()
  1892. {
  1893. return gs->currentPlayer;
  1894. }
  1895. void CGameHandler::giveResource(int player, int which, int val)
  1896. {
  1897. if(!val) return; //don't waste time on empty call
  1898. SetResource sr;
  1899. sr.player = player;
  1900. sr.resid = which;
  1901. sr.val = gs->players.find(player)->second.resources[which]+val;
  1902. sendAndApply(&sr);
  1903. }
  1904. void CGameHandler::giveCreatures (int objid, const CGHeroInstance * h, CCreatureSet creatures)
  1905. {
  1906. if (creatures.stacksCount() <= 0)
  1907. return;
  1908. CCreatureSet heroArmy = h->getArmy();
  1909. while (creatures.stacksCount())
  1910. {
  1911. int slot = heroArmy.getSlotFor(creatures.Slots().begin()->second.type->idNumber);
  1912. if (slot < 0)
  1913. break;
  1914. heroArmy.addToSlot(slot, creatures.slots.begin()->second);
  1915. creatures.slots.erase (creatures.slots.begin());
  1916. }
  1917. if (creatures.stacksCount() == 0) //all creatures can be moved to hero army - do that
  1918. {
  1919. SetGarrisons sg;
  1920. sg.garrs[h->id] = heroArmy;
  1921. sendAndApply(&sg);
  1922. }
  1923. else //show garrison window and let player pick creatures
  1924. {
  1925. SetGarrisons sg;
  1926. sg.garrs[objid] = creatures;
  1927. sendAndApply (&sg);
  1928. showGarrisonDialog (objid, h->id, true, 0);
  1929. return;
  1930. }
  1931. }
  1932. void CGameHandler::takeCreatures (int objid, TSlots creatures) //probably we could use ArmedInstance as well
  1933. {
  1934. if (creatures.size() <= 0)
  1935. return;
  1936. const CArmedInstance* obj = static_cast<const CArmedInstance*>(getObj(objid));
  1937. CCreatureSet newArmy = obj->getArmy();
  1938. while (creatures.size())
  1939. {
  1940. int slot = newArmy.getSlotFor(creatures.begin()->second.type->idNumber);
  1941. if (slot < 0)
  1942. break;
  1943. newArmy.slots[slot].count -= creatures.begin()->second.count;
  1944. if (newArmy.getStack(slot).count < 1)
  1945. newArmy.eraseStack(slot);
  1946. creatures.erase (creatures.begin());
  1947. }
  1948. SetGarrisons sg;
  1949. sg.garrs[objid] = newArmy;
  1950. sendAndApply(&sg);
  1951. }
  1952. void CGameHandler::showCompInfo(ShowInInfobox * comp)
  1953. {
  1954. sendToAllClients(comp);
  1955. }
  1956. void CGameHandler::heroVisitCastle(int obj, int heroID)
  1957. {
  1958. HeroVisitCastle vc;
  1959. vc.hid = heroID;
  1960. vc.tid = obj;
  1961. vc.flags |= 1;
  1962. sendAndApply(&vc);
  1963. const CGHeroInstance *h = getHero(heroID);
  1964. vistiCastleObjects (getTown(obj), h);
  1965. giveSpells (getTown(obj), getHero(heroID));
  1966. if(gs->map->victoryCondition.condition == transportItem)
  1967. checkLossVictory(h->tempOwner); //transported artifact?
  1968. }
  1969. void CGameHandler::vistiCastleObjects (const CGTownInstance *t, const CGHeroInstance *h)
  1970. {
  1971. std::vector<CGTownBuilding*>::const_iterator i;
  1972. for (i = t->bonusingBuildings.begin(); i != t->bonusingBuildings.end(); i++)
  1973. (*i)->onHeroVisit (h);
  1974. }
  1975. void CGameHandler::stopHeroVisitCastle(int obj, int heroID)
  1976. {
  1977. HeroVisitCastle vc;
  1978. vc.hid = heroID;
  1979. vc.tid = obj;
  1980. sendAndApply(&vc);
  1981. }
  1982. void CGameHandler::giveHeroArtifact(int artid, int hid, int position) //pos==-1 - first free slot in backpack
  1983. {
  1984. const CGHeroInstance* h = getHero(hid);
  1985. const CArtifact &art = *VLC->arth->artifacts[artid];
  1986. SetHeroArtifacts sha;
  1987. sha.hid = hid;
  1988. sha.artifacts = h->artifacts;
  1989. sha.artifWorn = h->artifWorn;
  1990. if(position<0)
  1991. {
  1992. if(position == -2)
  1993. {
  1994. int i;
  1995. for(i=0; i<art.possibleSlots.size(); i++) //try to put artifact into first available slot
  1996. {
  1997. if( !vstd::contains(sha.artifWorn,art.possibleSlots[i]) )
  1998. {
  1999. //we've found a free suitable slot
  2000. VLC->arth->equipArtifact(sha.artifWorn, art.possibleSlots[i], artid);
  2001. break;
  2002. }
  2003. }
  2004. if(i == art.possibleSlots.size() && !art.isBig()) //if haven't find proper slot, use backpack or discard big artifact
  2005. sha.artifacts.push_back(artid);
  2006. }
  2007. else if (!art.isBig()) //should be -1 => put artifact into backpack
  2008. {
  2009. sha.artifacts.push_back(artid);
  2010. }
  2011. }
  2012. else
  2013. {
  2014. if(!vstd::contains(sha.artifWorn,ui16(position)))
  2015. {
  2016. VLC->arth->equipArtifact(sha.artifWorn, position, artid);
  2017. }
  2018. else if (!art.isBig())
  2019. {
  2020. sha.artifacts.push_back(artid);
  2021. }
  2022. }
  2023. sendAndApply(&sha);
  2024. }
  2025. bool CGameHandler::removeArtifact(int artid, int hid)
  2026. {
  2027. const CGHeroInstance* h = getHero(hid);
  2028. SetHeroArtifacts sha;
  2029. sha.hid = hid;
  2030. sha.artifacts = h->artifacts;
  2031. sha.artifWorn = h->artifWorn;
  2032. std::vector<ui32>::iterator it;
  2033. if ((it = std::find(sha.artifacts.begin(), sha.artifacts.end(), artid)) != sha.artifacts.end()) //it is in backpack
  2034. sha.artifacts.erase(it);
  2035. else //worn
  2036. {
  2037. std::map<ui16,ui32>::iterator itr;
  2038. for (itr = sha.artifWorn.begin(); itr != sha.artifWorn.end(); ++itr)
  2039. {
  2040. if (itr->second == artid)
  2041. {
  2042. VLC->arth->unequipArtifact(sha.artifWorn, itr->first);
  2043. break;
  2044. }
  2045. }
  2046. if(itr == sha.artifWorn.end())
  2047. {
  2048. tlog2 << "Cannot find artifact to remove!\n";
  2049. return false;
  2050. }
  2051. }
  2052. sendAndApply(&sha);
  2053. return true;
  2054. }
  2055. void CGameHandler::startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool creatureBank, boost::function<void(BattleResult*)> cb, const CGTownInstance *town) //use hero=NULL for no hero
  2056. {
  2057. engageIntoBattle(army1->tempOwner);
  2058. engageIntoBattle(army2->tempOwner);
  2059. //block engaged players
  2060. if(army2->tempOwner < PLAYER_LIMIT)
  2061. states.setFlag(army2->tempOwner,&PlayerStatus::engagedIntoBattle,true);
  2062. boost::thread(boost::bind(&CGameHandler::startBattle, this, army1, army2, tile, hero1, hero2, creatureBank, cb, town));
  2063. }
  2064. void CGameHandler::startBattleI( const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, boost::function<void(BattleResult*)> cb, bool creatureBank )
  2065. {
  2066. startBattleI(army1, army2, tile,
  2067. army1->ID == HEROI_TYPE ? static_cast<const CGHeroInstance*>(army1) : NULL,
  2068. army2->ID == HEROI_TYPE ? static_cast<const CGHeroInstance*>(army2) : NULL,
  2069. creatureBank, cb);
  2070. }
  2071. void CGameHandler::startBattleI( const CArmedInstance *army1, const CArmedInstance *army2, boost::function<void(BattleResult*)> cb, bool creatureBank)
  2072. {
  2073. startBattleI(army1, army2, army2->visitablePos(), cb, creatureBank);
  2074. }
  2075. //void CGameHandler::startBattleI(int heroID, CCreatureSet army, int3 tile, boost::function<void(BattleResult*)> cb) //for hero<=>neutral army
  2076. //{
  2077. // CGHeroInstance* h = const_cast<CGHeroInstance*>(getHero(heroID));
  2078. // startBattleI(&h->army,&army,tile,h,NULL,cb);
  2079. // //battle(&h->army,army,tile,h,NULL);
  2080. //}
  2081. void CGameHandler::changeSpells( int hid, bool give, const std::set<ui32> &spells )
  2082. {
  2083. ChangeSpells cs;
  2084. cs.hid = hid;
  2085. cs.spells = spells;
  2086. cs.learn = give;
  2087. sendAndApply(&cs);
  2088. }
  2089. int CGameHandler::getSelectedHero()
  2090. {
  2091. return IGameCallback::getSelectedHero(getCurrentPlayer())->id;
  2092. }
  2093. void CGameHandler::setObjProperty( int objid, int prop, si64 val )
  2094. {
  2095. SetObjectProperty sob;
  2096. sob.id = objid;
  2097. sob.what = prop;
  2098. sob.val = val;
  2099. sendAndApply(&sob);
  2100. }
  2101. void CGameHandler::sendMessageTo( CConnection &c, const std::string &message )
  2102. {
  2103. SystemMessage sm;
  2104. sm.text = message;
  2105. c << &sm;
  2106. }
  2107. void CGameHandler::giveHeroBonus( GiveBonus * bonus )
  2108. {
  2109. sendAndApply(bonus);
  2110. }
  2111. void CGameHandler::setMovePoints( SetMovePoints * smp )
  2112. {
  2113. sendAndApply(smp);
  2114. }
  2115. void CGameHandler::setManaPoints( int hid, int val )
  2116. {
  2117. SetMana sm;
  2118. sm.hid = hid;
  2119. sm.val = val;
  2120. sendAndApply(&sm);
  2121. }
  2122. void CGameHandler::giveHero( int id, int player )
  2123. {
  2124. GiveHero gh;
  2125. gh.id = id;
  2126. gh.player = player;
  2127. sendAndApply(&gh);
  2128. }
  2129. void CGameHandler::changeObjPos( int objid, int3 newPos, ui8 flags )
  2130. {
  2131. ChangeObjPos cop;
  2132. cop.objid = objid;
  2133. cop.nPos = newPos;
  2134. cop.flags = flags;
  2135. sendAndApply(&cop);
  2136. }
  2137. void CGameHandler::useScholarSkill(si32 fromHero, si32 toHero)
  2138. {
  2139. const CGHeroInstance * h1 = getHero(fromHero);
  2140. const CGHeroInstance * h2 = getHero(toHero);
  2141. if ( h1->getSecSkillLevel(18) < h2->getSecSkillLevel(18) )
  2142. {
  2143. std::swap (h1,h2);//1st hero need to have higher scholar level for correct message
  2144. std::swap(fromHero, toHero);
  2145. }
  2146. int ScholarLevel = h1->getSecSkillLevel(18);//heroes can trade up to this level
  2147. if (!ScholarLevel || !vstd::contains(h1->artifWorn,17) || !vstd::contains(h2->artifWorn,17) )
  2148. return;//no scholar skill or no spellbook
  2149. int h1Lvl = std::min(ScholarLevel+1, h1->getSecSkillLevel(7)+2),
  2150. h2Lvl = std::min(ScholarLevel+1, h2->getSecSkillLevel(7)+2);//heroes can receive this levels
  2151. ChangeSpells cs1;
  2152. cs1.learn = true;
  2153. cs1.hid = toHero;//giving spells to first hero
  2154. for(std::set<ui32>::const_iterator it=h1->spells.begin(); it!=h1->spells.end();it++)
  2155. if ( h2Lvl >= VLC->spellh->spells[*it].level && !vstd::contains(h2->spells, *it))//hero can learn it and don't have it yet
  2156. cs1.spells.insert(*it);//spell to learn
  2157. ChangeSpells cs2;
  2158. cs2.learn = true;
  2159. cs2.hid = fromHero;
  2160. for(std::set<ui32>::const_iterator it=h2->spells.begin(); it!=h2->spells.end();it++)
  2161. if ( h1Lvl >= VLC->spellh->spells[*it].level && !vstd::contains(h1->spells, *it))
  2162. cs2.spells.insert(*it);
  2163. if (cs1.spells.size() || cs2.spells.size())//create a message
  2164. {
  2165. InfoWindow iw;
  2166. iw.player = h1->tempOwner;
  2167. iw.components.push_back(Component(Component::SEC_SKILL, 18, ScholarLevel, 0));
  2168. iw.text.addTxt(MetaString::GENERAL_TXT, 139);//"%s, who has studied magic extensively,
  2169. iw.text.addReplacement(h1->name);
  2170. if (cs2.spells.size())//if found new spell - apply
  2171. {
  2172. iw.text.addTxt(MetaString::GENERAL_TXT, 140);//learns
  2173. int size = cs2.spells.size();
  2174. for(std::set<ui32>::const_iterator it=cs2.spells.begin(); it!=cs2.spells.end();it++)
  2175. {
  2176. iw.components.push_back(Component(Component::SPELL, (*it), 1, 0));
  2177. iw.text.addTxt(MetaString::SPELL_NAME, (*it));
  2178. switch (size--)
  2179. {
  2180. case 2: iw.text.addTxt(MetaString::GENERAL_TXT, 141);
  2181. case 1: break;
  2182. default: iw.text << ", ";
  2183. }
  2184. }
  2185. iw.text.addTxt(MetaString::GENERAL_TXT, 142);//from %s
  2186. iw.text.addReplacement(h2->name);
  2187. sendAndApply(&cs2);
  2188. }
  2189. if (cs1.spells.size() && cs2.spells.size() )
  2190. {
  2191. iw.text.addTxt(MetaString::GENERAL_TXT, 141);//and
  2192. }
  2193. if (cs1.spells.size())
  2194. {
  2195. iw.text.addTxt(MetaString::GENERAL_TXT, 147);//teaches
  2196. int size = cs1.spells.size();
  2197. for(std::set<ui32>::const_iterator it=cs1.spells.begin(); it!=cs1.spells.end();it++)
  2198. {
  2199. iw.components.push_back(Component(Component::SPELL, (*it), 1, 0));
  2200. iw.text.addTxt(MetaString::SPELL_NAME, (*it));
  2201. switch (size--)
  2202. {
  2203. case 2: iw.text.addTxt(MetaString::GENERAL_TXT, 141);
  2204. case 1: break;
  2205. default: iw.text << ", ";
  2206. } }
  2207. iw.text.addTxt(MetaString::GENERAL_TXT, 148);//from %s
  2208. iw.text.addReplacement(h2->name);
  2209. sendAndApply(&cs1);
  2210. }
  2211. sendAndApply(&iw);
  2212. }
  2213. }
  2214. void CGameHandler::heroExchange(si32 hero1, si32 hero2)
  2215. {
  2216. ui8 player1 = getHero(hero1)->tempOwner;
  2217. ui8 player2 = getHero(hero2)->tempOwner;
  2218. if( gameState()->getPlayerRelations( player1, player2))
  2219. {
  2220. OpenWindow hex;
  2221. hex.window = OpenWindow::EXCHANGE_WINDOW;
  2222. hex.id1 = hero1;
  2223. hex.id2 = hero2;
  2224. sendAndApply(&hex);
  2225. useScholarSkill(hero1,hero2);
  2226. }
  2227. }
  2228. void CGameHandler::applyAndAsk( Query * sel, ui8 player, boost::function<void(ui32)> &callback )
  2229. {
  2230. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  2231. sel->id = QID;
  2232. callbacks[QID] = callback;
  2233. states.addQuery(player,QID);
  2234. QID++;
  2235. sendAndApply(sel);
  2236. }
  2237. void CGameHandler::ask( Query * sel, ui8 player, const CFunctionList<void(ui32)> &callback )
  2238. {
  2239. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  2240. sel->id = QID;
  2241. callbacks[QID] = callback;
  2242. states.addQuery(player,QID);
  2243. sendToAllClients(sel);
  2244. QID++;
  2245. }
  2246. void CGameHandler::sendToAllClients( CPackForClient * info )
  2247. {
  2248. tlog5 << "Sending to all clients a package of type " << typeid(*info).name() << std::endl;
  2249. for(std::set<CConnection*>::iterator i=conns.begin(); i!=conns.end();i++)
  2250. {
  2251. (*i)->wmx->lock();
  2252. **i << info;
  2253. (*i)->wmx->unlock();
  2254. }
  2255. }
  2256. void CGameHandler::sendAndApply( CPackForClient * info )
  2257. {
  2258. gs->apply(info);
  2259. sendToAllClients(info);
  2260. }
  2261. void CGameHandler::sendAndApply( SetGarrisons * info )
  2262. {
  2263. sendAndApply((CPackForClient*)info);
  2264. if(gs->map->victoryCondition.condition == gatherTroop)
  2265. for(std::map<ui32,CCreatureSet>::const_iterator i = info->garrs.begin(); i != info->garrs.end(); i++)
  2266. checkLossVictory(getObj(i->first)->tempOwner);
  2267. }
  2268. void CGameHandler::sendAndApply( SetResource * info )
  2269. {
  2270. sendAndApply((CPackForClient*)info);
  2271. if(gs->map->victoryCondition.condition == gatherResource)
  2272. checkLossVictory(info->player);
  2273. }
  2274. void CGameHandler::sendAndApply( SetResources * info )
  2275. {
  2276. sendAndApply((CPackForClient*)info);
  2277. if(gs->map->victoryCondition.condition == gatherResource)
  2278. checkLossVictory(info->player);
  2279. }
  2280. void CGameHandler::sendAndApply( NewStructures * info )
  2281. {
  2282. sendAndApply((CPackForClient*)info);
  2283. if(gs->map->victoryCondition.condition == buildCity)
  2284. checkLossVictory(getTown(info->tid)->tempOwner);
  2285. }
  2286. void CGameHandler::save( const std::string &fname )
  2287. {
  2288. {
  2289. tlog0 << "Ordering clients to serialize...\n";
  2290. SaveGame sg(fname);
  2291. sendToAllClients(&sg);
  2292. }
  2293. {
  2294. tlog0 << "Serializing game info...\n";
  2295. CSaveFile save(GVCMIDirs.UserPath + "/Games/" + fname + ".vlgm1");
  2296. char hlp[8] = "VCMISVG";
  2297. save << hlp << static_cast<CMapHeader&>(*gs->map) << gs->scenarioOps << *VLC << gs;
  2298. }
  2299. {
  2300. tlog0 << "Serializing server info...\n";
  2301. CSaveFile save(GVCMIDirs.UserPath + "/Games/" + fname + ".vsgm1");
  2302. save << *this;
  2303. }
  2304. tlog0 << "Game has been successfully saved!\n";
  2305. }
  2306. void CGameHandler::close()
  2307. {
  2308. tlog0 << "We have been requested to close.\n";
  2309. //BOOST_FOREACH(CConnection *cc, conns)
  2310. // if(cc && cc->socket && cc->socket->is_open())
  2311. // cc->socket->close();
  2312. //exit(0);
  2313. }
  2314. bool CGameHandler::arrangeStacks( si32 id1, si32 id2, ui8 what, ui8 p1, ui8 p2, si32 val, ui8 player )
  2315. {
  2316. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id1]),
  2317. *s2 = static_cast<CArmedInstance*>(gs->map->objects[id2]);
  2318. CCreatureSet temp1 = s1->getArmy(), temp2 = s2->getArmy(),
  2319. &S1 = temp1, &S2 = (s1!=s2)?(temp2):(temp1);
  2320. if(!isAllowedExchange(id1,id2))
  2321. {
  2322. complain("Cannot exchange stacks between these two objects!\n");
  2323. return false;
  2324. }
  2325. if(what==1) //swap
  2326. {
  2327. if ( (s1->tempOwner != player && S1.slots[p1].count)
  2328. || (s2->tempOwner != player && S2.slots[p2].count))
  2329. {
  2330. complain("Can't take troops from another player!");
  2331. return false;
  2332. }
  2333. std::swap(S1.slots[p1],S2.slots[p2]); //swap slots
  2334. //if one of them is empty, remove entry
  2335. if(!S1.slots[p1].count)
  2336. S1.slots.erase(p1);
  2337. if(!S2.slots[p2].count)
  2338. S2.slots.erase(p2);
  2339. }
  2340. else if(what==2)//merge
  2341. {
  2342. if (( S1.slots[p1].type != S2.slots[p2].type && complain("Cannot merge different creatures stacks!"))
  2343. || (s1->tempOwner != player && S2.slots[p2].count) && complain("Can't take troops from another player!"))
  2344. return false;
  2345. S2.slots[p2].count += S1.slots[p1].count;
  2346. S1.slots.erase(p1);
  2347. }
  2348. else if(what==3) //split
  2349. {
  2350. //general conditions checking
  2351. if((!vstd::contains(S1.slots,p1) && complain("no creatures to split"))
  2352. || (val<1 && complain("no creatures to split")) )
  2353. {
  2354. return false;
  2355. }
  2356. if(vstd::contains(S2.slots,p2)) //dest. slot not free - it must be "rebalancing"...
  2357. {
  2358. int total = S1.slots[p1].count + S2.slots[p2].count;
  2359. if( (total < val && complain("Cannot split that stack, not enough creatures!"))
  2360. || (S2.slots[p2].type != S1.slots[p1].type && complain("Cannot rebalance different creatures stacks!"))
  2361. )
  2362. {
  2363. return false;
  2364. }
  2365. S2.slots[p2].count = val;
  2366. S1.slots[p1].count = total - val;
  2367. }
  2368. else //split one stack to the two
  2369. {
  2370. if(S1.slots[p1].count < val)//not enough creatures
  2371. {
  2372. complain("Cannot split that stack, not enough creatures!");
  2373. return false;
  2374. }
  2375. S2.slots[p2].type = S1.slots[p1].type;
  2376. S2.slots[p2].count = val;
  2377. S1.slots[p1].count -= val;
  2378. }
  2379. if ( (s1->tempOwner != player && S1.slots[p1].count < s1->getArmy().getAmount(p1) )
  2380. || (s2->tempOwner != player && S2.slots[p2].count < s2->getArmy().getAmount(p2) ) )
  2381. {
  2382. complain("Can't move troops of another player!");
  2383. return false;
  2384. }
  2385. if(!S1.slots[p1].count) //if we've moved all creatures
  2386. S1.slots.erase(p1);
  2387. }
  2388. if((s1->needsLastStack() && !S1.stacksCount()) //it's not allowed to take last stack from hero army!
  2389. || (s2->needsLastStack() && !S2.stacksCount())
  2390. )
  2391. {
  2392. complain("Cannot take the last stack!");
  2393. return false; //leave without applying changes to garrison
  2394. }
  2395. //apply changes
  2396. SetGarrisons sg;
  2397. sg.garrs[id1] = S1;
  2398. if(s1 != s2)
  2399. sg.garrs[id2] = S2;
  2400. sendAndApply(&sg);
  2401. return true;
  2402. }
  2403. int CGameHandler::getPlayerAt( CConnection *c ) const
  2404. {
  2405. std::set<int> all;
  2406. for(std::map<int,CConnection*>::const_iterator i=connections.begin(); i!=connections.end(); i++)
  2407. if(i->second == c)
  2408. all.insert(i->first);
  2409. switch(all.size())
  2410. {
  2411. case 0:
  2412. return 255;
  2413. case 1:
  2414. return *all.begin();
  2415. default:
  2416. {
  2417. //if we have more than one player at this connection, try to pick active one
  2418. if(vstd::contains(all,int(gs->currentPlayer)))
  2419. return gs->currentPlayer;
  2420. else
  2421. return 253; //cannot say which player is it
  2422. }
  2423. }
  2424. }
  2425. bool CGameHandler::disbandCreature( si32 id, ui8 pos )
  2426. {
  2427. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id]);
  2428. if(!vstd::contains(s1->slots,pos))
  2429. {
  2430. complain("Illegal call to disbandCreature - no such stack in army!");
  2431. return false;
  2432. }
  2433. s1->slots.erase(pos);
  2434. SetGarrisons sg;
  2435. sg.garrs[id] = s1->getArmy();
  2436. sendAndApply(&sg);
  2437. return true;
  2438. }
  2439. bool CGameHandler::buildStructure( si32 tid, si32 bid, bool force /*=false*/ )
  2440. {
  2441. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[tid]);
  2442. CBuilding * b = VLC->buildh->buildings[t->subID][bid];
  2443. if( !force && gs->canBuildStructure(t,bid) != 7)
  2444. {
  2445. complain("Cannot build that building!");
  2446. return false;
  2447. }
  2448. if( !force && bid == 26) //grail
  2449. {
  2450. if(!t->visitingHero || !t->visitingHero->hasArt(2))
  2451. {
  2452. complain("Cannot build grail - hero doesn't have it");
  2453. return false;
  2454. }
  2455. removeArtifact(2, t->visitingHero->id);
  2456. }
  2457. NewStructures ns;
  2458. ns.tid = tid;
  2459. if ( (bid == 18) && (vstd::contains(t->builtBuildings,(t->town->hordeLvl[0]+37))) )
  2460. ns.bid.insert(19);//we have upgr. dwelling, upgr. horde will be builded as well
  2461. else if ( (bid == 24) && (vstd::contains(t->builtBuildings,(t->town->hordeLvl[1]+37))) )
  2462. ns.bid.insert(25);
  2463. else if(bid>36) //upg dwelling
  2464. {
  2465. if ( (bid-37 == t->town->hordeLvl[0]) && (vstd::contains(t->builtBuildings,18)) )
  2466. ns.bid.insert(19);//we have horde, will be upgraded as well as dwelling
  2467. if ( (bid-37 == t->town->hordeLvl[1]) && (vstd::contains(t->builtBuildings,24)) )
  2468. ns.bid.insert(25);
  2469. SetAvailableCreatures ssi;
  2470. ssi.tid = tid;
  2471. ssi.creatures = t->creatures;
  2472. ssi.creatures[bid-37].second.push_back(t->town->upgradedCreatures[bid-37]);
  2473. sendAndApply(&ssi);
  2474. }
  2475. else if(bid >= 30) //bas. dwelling
  2476. {
  2477. int crid = t->town->basicCreatures[bid-30];
  2478. SetAvailableCreatures ssi;
  2479. ssi.tid = tid;
  2480. ssi.creatures = t->creatures;
  2481. ssi.creatures[bid-30].first = VLC->creh->creatures[crid]->growth;
  2482. ssi.creatures[bid-30].second.push_back(crid);
  2483. sendAndApply(&ssi);
  2484. }
  2485. else if(bid == 11)
  2486. ns.bid.insert(27);
  2487. else if(bid == 12)
  2488. ns.bid.insert(28);
  2489. else if(bid == 13)
  2490. ns.bid.insert(29);
  2491. else if (t->subID == 4 && bid == 17) //veil of darkness
  2492. {
  2493. GiveBonus gb(GiveBonus::TOWN);
  2494. gb.bonus.type = Bonus::DARKNESS;
  2495. gb.bonus.val = 20;
  2496. gb.id = t->id;
  2497. gb.bonus.duration = Bonus::PERMANENT;
  2498. gb.bonus.source = Bonus::TOWN_STRUCTURE;
  2499. gb.bonus.id = 17;
  2500. sendAndApply(&gb);
  2501. }
  2502. else if ( t->subID == 5 && bid == 22 )
  2503. {
  2504. setPortalDwelling(t);
  2505. }
  2506. ns.bid.insert(bid);
  2507. ns.builded = force?t->builded:(t->builded+1);
  2508. sendAndApply(&ns);
  2509. //reveal ground for lookout tower
  2510. FoWChange fw;
  2511. fw.player = t->tempOwner;
  2512. fw.mode = 1;
  2513. getTilesInRange(fw.tiles,t->pos,t->getSightRadious(),t->tempOwner,1);
  2514. sendAndApply(&fw);
  2515. if (!force)
  2516. {
  2517. SetResources sr;
  2518. sr.player = t->tempOwner;
  2519. sr.res = gs->getPlayer(t->tempOwner)->resources;
  2520. for(int i=0;i<b->resources.size();i++)
  2521. sr.res[i]-=b->resources[i];
  2522. sendAndApply(&sr);
  2523. }
  2524. if(bid<5) //it's mage guild
  2525. {
  2526. if(t->visitingHero)
  2527. giveSpells(t,t->visitingHero);
  2528. if(t->garrisonHero)
  2529. giveSpells(t,t->garrisonHero);
  2530. }
  2531. if(t->visitingHero)
  2532. vistiCastleObjects (t, t->visitingHero);
  2533. if(t->garrisonHero)
  2534. vistiCastleObjects (t, t->garrisonHero);
  2535. checkLossVictory(t->tempOwner);
  2536. return true;
  2537. }
  2538. bool CGameHandler::razeStructure (si32 tid, si32 bid)
  2539. {
  2540. ///incomplete, simply erases target building
  2541. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[tid]);
  2542. if (t->builtBuildings.find(bid) == t->builtBuildings.end())
  2543. return false;
  2544. RazeStructures rs;
  2545. rs.tid = tid;
  2546. rs.bid.insert(bid);
  2547. rs.destroyed = t->destroyed + 1;
  2548. sendAndApply(&rs);
  2549. //TODO: Remove dwellers
  2550. if (t->subID == 4 && bid == 17) //Veil of Darkness
  2551. {
  2552. RemoveBonus rb(RemoveBonus::TOWN);
  2553. rb.whoID = t->id;
  2554. rb.source = Bonus::TOWN_STRUCTURE;
  2555. rb.id = 17;
  2556. sendAndApply(&rb);
  2557. }
  2558. return true;
  2559. }
  2560. void CGameHandler::sendMessageToAll( const std::string &message )
  2561. {
  2562. SystemMessage sm;
  2563. sm.text = message;
  2564. sendToAllClients(&sm);
  2565. }
  2566. bool CGameHandler::recruitCreatures( si32 objid, ui32 crid, ui32 cram, si32 fromLvl )
  2567. {
  2568. const CGDwelling *dw = static_cast<CGDwelling*>(gs->map->objects[objid]);
  2569. const CArmedInstance *dst = NULL;
  2570. const CCreature *c = VLC->creh->creatures[crid];
  2571. bool warMachine = c->hasBonusOfType(Bonus::SIEGE_WEAPON);
  2572. //TODO: test for owning
  2573. if(dw->ID == TOWNI_TYPE)
  2574. dst = dw;
  2575. else if(dw->ID == 17 || dw->ID == 20 || dw->ID == 78) //advmap dwelling
  2576. dst = getHero(gs->getPlayer(dw->tempOwner)->currentSelection); //TODO: check if current hero is really visiting dwelling
  2577. else if(dw->ID == 106)
  2578. dst = dynamic_cast<const CGHeroInstance *>(getTile(dw->visitablePos())->visitableObjects.back());
  2579. assert(dw && dst);
  2580. //verify
  2581. bool found = false;
  2582. int level = 0;
  2583. typedef std::pair<const int,int> Parka;
  2584. for(; level < dw->creatures.size(); level++) //iterate through all levels
  2585. {
  2586. if ( (fromLvl != -1) && ( level !=fromLvl ) )
  2587. continue;
  2588. const std::pair<ui32, std::vector<ui32> > &cur = dw->creatures[level]; //current level info <amount, list of cr. ids>
  2589. int i = 0;
  2590. for(; i < cur.second.size(); i++) //look for crid among available creatures list on current level
  2591. if(cur.second[i] == crid)
  2592. break;
  2593. if(i < cur.second.size())
  2594. {
  2595. found = true;
  2596. cram = std::min(cram, cur.first); //reduce recruited amount up to available amount
  2597. break;
  2598. }
  2599. }
  2600. int slot = dst->getSlotFor(crid);
  2601. if(!found && complain("Cannot recruit: no such creatures!")
  2602. || cram > VLC->creh->creatures[crid]->maxAmount(gs->getPlayer(dst->tempOwner)->resources) && complain("Cannot recruit: lack of resources!")
  2603. || cram<=0 && complain("Cannot recruit: cram <= 0!")
  2604. || slot<0 && !warMachine && complain("Cannot recruit: no available slot!"))
  2605. {
  2606. return false;
  2607. }
  2608. //recruit
  2609. SetResources sr;
  2610. sr.player = dst->tempOwner;
  2611. for(int i=0;i<RESOURCE_QUANTITY;i++)
  2612. sr.res[i] = gs->getPlayer(dst->tempOwner)->resources[i] - (c->cost[i] * cram);
  2613. SetAvailableCreatures sac;
  2614. sac.tid = objid;
  2615. sac.creatures = dw->creatures;
  2616. sac.creatures[level].first -= cram;
  2617. sendAndApply(&sr);
  2618. sendAndApply(&sac);
  2619. if(warMachine)
  2620. {
  2621. switch(crid)
  2622. {
  2623. case 146:
  2624. giveHeroArtifact(4, dst->id, 13);
  2625. break;
  2626. case 147:
  2627. giveHeroArtifact(6, dst->id, 15);
  2628. break;
  2629. case 148:
  2630. giveHeroArtifact(5, dst->id, 14);
  2631. break;
  2632. default:
  2633. complain("This war machine cannot be recruited!");
  2634. return false;
  2635. }
  2636. }
  2637. else
  2638. {
  2639. SetGarrisons sg;
  2640. sg.garrs[dst->id] = dst->getArmy();
  2641. sg.garrs[dst->id] .addToSlot(slot, crid, cram);
  2642. sendAndApply(&sg);
  2643. }
  2644. return true;
  2645. }
  2646. bool CGameHandler::upgradeCreature( ui32 objid, ui8 pos, ui32 upgID )
  2647. {
  2648. CArmedInstance *obj = static_cast<CArmedInstance*>(gs->map->objects[objid]);
  2649. UpgradeInfo ui = gs->getUpgradeInfo(obj->getStack(pos));
  2650. int player = obj->tempOwner;
  2651. int crQuantity = obj->slots[pos].count;
  2652. int newIDpos= vstd::findPos(ui.newID, upgID);//get position of new id in UpgradeInfo
  2653. //check if upgrade is possible
  2654. if( (ui.oldID<0 || newIDpos == -1 ) && complain("That upgrade is not possible!"))
  2655. {
  2656. return false;
  2657. }
  2658. //check if player has enough resources
  2659. for (std::set<std::pair<int,int> >::iterator j=ui.cost[newIDpos].begin(); j!=ui.cost[newIDpos].end(); j++)
  2660. {
  2661. if(gs->getPlayer(player)->resources[j->first] < j->second*crQuantity)
  2662. {
  2663. complain("Cannot upgrade, not enough resources!");
  2664. return false;
  2665. }
  2666. }
  2667. //take resources
  2668. for (std::set<std::pair<int,int> >::iterator j=ui.cost[newIDpos].begin(); j!=ui.cost[newIDpos].end(); j++)
  2669. {
  2670. SetResource sr;
  2671. sr.player = player;
  2672. sr.resid = j->first;
  2673. sr.val = gs->getPlayer(player)->resources[j->first] - j->second*crQuantity;
  2674. sendAndApply(&sr);
  2675. }
  2676. //upgrade creature
  2677. SetGarrisons sg;
  2678. sg.garrs[objid] = obj->getArmy();
  2679. sg.garrs[objid].slots[pos].setType(upgID);
  2680. sendAndApply(&sg);
  2681. return true;
  2682. }
  2683. void CGameHandler::changeCreatureType (int objid, TSlot slot, TCreature creature)
  2684. {
  2685. CArmedInstance *obj = static_cast<CArmedInstance*>(gs->map->objects[objid]);
  2686. if (obj)
  2687. {
  2688. SetGarrisons sg;
  2689. sg.garrs[objid] = obj->getArmy();
  2690. sg.garrs[objid].slots[slot].setType(creature);
  2691. sendAndApply(&sg);
  2692. }
  2693. else
  2694. tlog2 <<"Illegal call of changeCreatureType for non-armed instance!\n";
  2695. }
  2696. bool CGameHandler::garrisonSwap( si32 tid )
  2697. {
  2698. CGTownInstance *town = gs->getTown(tid);
  2699. if(!town->garrisonHero && town->visitingHero) //visiting => garrison, merge armies: town army => hero army
  2700. {
  2701. CCreatureSet csn = town->visitingHero->getArmy(), cso = town->getArmy();
  2702. while(!cso.slots.empty())//while there are unmoved creatures
  2703. {
  2704. int pos = csn.getSlotFor(cso.slots.begin()->second.type->idNumber);
  2705. if(pos<0)
  2706. {
  2707. //try to merge two other stacks to make place
  2708. std::pair<TSlot, TSlot> toMerge;
  2709. if(csn.mergableStacks(toMerge, cso.slots.begin()->first))
  2710. {
  2711. //merge
  2712. csn.slots[toMerge.second].count += csn.slots[toMerge.first].count;
  2713. csn.slots[toMerge.first] = cso.slots.begin()->second;
  2714. }
  2715. else
  2716. {
  2717. complain("Cannot make garrison swap, not enough free slots!");
  2718. return false;
  2719. }
  2720. }
  2721. else if(csn.slots.find(pos) != csn.slots.end()) //add creatures to the existing stack
  2722. {
  2723. csn.slots[pos].count += cso.slots.begin()->second.count;
  2724. }
  2725. else //move stack on the free pos
  2726. {
  2727. csn.slots[pos].type = cso.slots.begin()->second.type;
  2728. csn.slots[pos].count = cso.slots.begin()->second.count;
  2729. }
  2730. cso.slots.erase(cso.slots.begin());
  2731. }
  2732. SetGarrisons sg;
  2733. sg.garrs[town->visitingHero->id] = csn;
  2734. sg.garrs[town->id] = csn;
  2735. sendAndApply(&sg);
  2736. SetHeroesInTown intown;
  2737. intown.tid = tid;
  2738. intown.visiting = -1;
  2739. intown.garrison = town->visitingHero->id;
  2740. sendAndApply(&intown);
  2741. return true;
  2742. }
  2743. else if (town->garrisonHero && !town->visitingHero) //move hero out of the garrison
  2744. {
  2745. //check if moving hero out of town will break 8 wandering heroes limit
  2746. if(getHeroCount(town->garrisonHero->tempOwner,false) >= 8)
  2747. {
  2748. complain("Cannot move hero out of the garrison, there are already 8 wandering heroes!");
  2749. return false;
  2750. }
  2751. SetHeroesInTown intown;
  2752. intown.tid = tid;
  2753. intown.garrison = -1;
  2754. intown.visiting = town->garrisonHero->id;
  2755. sendAndApply(&intown);
  2756. //town will be empty
  2757. SetGarrisons sg;
  2758. sg.garrs[tid] = CCreatureSet();
  2759. sendAndApply(&sg);
  2760. return true;
  2761. }
  2762. else if (town->garrisonHero && town->visitingHero) //swap visiting and garrison hero
  2763. {
  2764. SetGarrisons sg;
  2765. sg.garrs[town->id] = town->visitingHero->getArmy();;
  2766. sg.garrs[town->garrisonHero->id] = town->garrisonHero->getArmy();
  2767. SetHeroesInTown intown;
  2768. intown.tid = tid;
  2769. intown.garrison = town->visitingHero->id;
  2770. intown.visiting = town->garrisonHero->id;
  2771. sendAndApply(&intown);
  2772. sendAndApply(&sg);
  2773. return true;
  2774. }
  2775. else
  2776. {
  2777. complain("Cannot swap garrison hero!");
  2778. return false;
  2779. }
  2780. }
  2781. // With the amount of changes done to the function, it's more like transferArtifacts.
  2782. bool CGameHandler::swapArtifacts(si32 srcHeroID, si32 destHeroID, ui16 srcSlot, ui16 destSlot)
  2783. {
  2784. CGHeroInstance *srcHero = gs->getHero(srcHeroID);
  2785. CGHeroInstance *destHero = gs->getHero(destHeroID);
  2786. // Make sure exchange is even possible between the two heroes.
  2787. if (distance(srcHero->pos,destHero->pos) > 1.5 )
  2788. return false;
  2789. const CArtifact *srcArtifact = srcHero->getArt(srcSlot);
  2790. const CArtifact *destArtifact = destHero->getArt(destSlot);
  2791. if (srcArtifact == NULL)
  2792. {
  2793. complain("No artifact to swap!");
  2794. return false;
  2795. }
  2796. if (destArtifact && srcHero->tempOwner != destHero->tempOwner)
  2797. {
  2798. complain("Can't take artifact from hero of another player!");
  2799. return false;
  2800. }
  2801. SetHeroArtifacts sha;
  2802. sha.hid = srcHeroID;
  2803. sha.artifacts = srcHero->artifacts;
  2804. sha.artifWorn = srcHero->artifWorn;
  2805. // Combinational artifacts needs to be removed first so they don't get denied movement because of their own locks.
  2806. if (srcHeroID == destHeroID && srcSlot < 19 && destSlot < 19)
  2807. {
  2808. sha.setArtAtPos(srcSlot, -1);
  2809. if (!vstd::contains(sha.artifWorn, destSlot))
  2810. destArtifact = NULL;
  2811. }
  2812. // Check if src/dest slots are appropriate for the artifacts exchanged.
  2813. // Moving to the backpack is always allowed.
  2814. if ((!srcArtifact || destSlot < 19)
  2815. && (srcArtifact && !srcArtifact->fitsAt(srcHeroID == destHeroID ? sha.artifWorn : destHero->artifWorn, destSlot)))
  2816. {
  2817. complain("Cannot swap artifacts!");
  2818. return false;
  2819. }
  2820. if ((srcArtifact && srcArtifact->id == 145) || (destArtifact && destArtifact->id == 145))
  2821. {
  2822. complain("Cannot move artifact locks.");
  2823. return false;
  2824. }
  2825. if (destSlot >= 19 && srcArtifact->isBig())
  2826. {
  2827. complain("Cannot put big artifacts in backpack!");
  2828. return false;
  2829. }
  2830. if (srcSlot == 16 || destSlot == 16)
  2831. {
  2832. complain("Cannot move catapult!");
  2833. return false;
  2834. }
  2835. // If dest does not fit in src, put it in dest's backpack instead.
  2836. if (srcHeroID == destHeroID) // To avoid stumbling on own locks, remove artifact first.
  2837. sha.setArtAtPos(destSlot, -1);
  2838. const bool destFits = !destArtifact || srcSlot >= 19 || destSlot >= 19 || destArtifact->fitsAt(sha.artifWorn, srcSlot);
  2839. if (srcHeroID == destHeroID && destArtifact)
  2840. sha.setArtAtPos(destSlot, destArtifact->id);
  2841. sha.setArtAtPos(srcSlot, -1);
  2842. if (destSlot < 19 && (destArtifact || srcSlot < 19) && destFits)
  2843. sha.setArtAtPos(srcSlot, destArtifact ? destArtifact->id : -1);
  2844. // Internal hero artifact arrangement.
  2845. if(srcHero == destHero)
  2846. {
  2847. // Correction for destination from removing source artifact in backpack.
  2848. if (srcSlot >= 19 && destSlot >= 19 && srcSlot < destSlot)
  2849. destSlot--;
  2850. sha.setArtAtPos(destSlot, srcHero->getArtAtPos(srcSlot));
  2851. }
  2852. if (srcHeroID != destHeroID)
  2853. {
  2854. // Exchange between two different heroes.
  2855. SetHeroArtifacts sha2;
  2856. sha2.hid = destHeroID;
  2857. sha2.artifacts = destHero->artifacts;
  2858. sha2.artifWorn = destHero->artifWorn;
  2859. sha2.setArtAtPos(destSlot, srcArtifact ? srcArtifact->id : -1);
  2860. if (!destFits)
  2861. sha2.setArtAtPos(sha2.artifacts.size() + 19, destHero->getArtAtPos(destSlot));
  2862. sendAndApply(&sha2);
  2863. }
  2864. sendAndApply(&sha);
  2865. return true;
  2866. }
  2867. /**
  2868. * Assembles or disassembles a combination artifact.
  2869. * @param heroID ID of hero holding the artifact(s).
  2870. * @param artifactSlot The worn slot ID of the combination- or constituent artifact.
  2871. * @param assemble True for assembly operation, false for disassembly.
  2872. * @param assembleTo If assemble is true, this represents the artifact ID of the combination
  2873. * artifact to assemble to. Otherwise it's not used.
  2874. */
  2875. bool CGameHandler::assembleArtifacts (si32 heroID, ui16 artifactSlot, bool assemble, ui32 assembleTo)
  2876. {
  2877. if (artifactSlot < 0 || artifactSlot > 18) {
  2878. complain("Illegal artifact slot.");
  2879. return false;
  2880. }
  2881. CGHeroInstance *hero = gs->getHero(heroID);
  2882. const CArtifact *destArtifact = hero->getArt(artifactSlot);
  2883. SetHeroArtifacts sha;
  2884. sha.hid = heroID;
  2885. sha.artifacts = hero->artifacts;
  2886. sha.artifWorn = hero->artifWorn;
  2887. if (assemble) {
  2888. if (VLC->arth->artifacts.size() < assembleTo) {
  2889. complain("Illegal artifact to assemble to.");
  2890. return false;
  2891. }
  2892. if (!destArtifact->canBeAssembledTo(hero->artifWorn, assembleTo)) {
  2893. complain("Artifact cannot be assembled.");
  2894. return false;
  2895. }
  2896. const CArtifact &artifact = *VLC->arth->artifacts[assembleTo];
  2897. if (artifact.constituents == NULL) {
  2898. complain("Not a combinational artifact.");
  2899. return false;
  2900. }
  2901. // Perform assembly.
  2902. bool destConsumed = false; // Determines which constituent that will be counted for together with the artifact.
  2903. const bool destSpecific = vstd::contains(artifact.possibleSlots, artifactSlot); // Prefer the chosen slot as the location for the assembled artifact.
  2904. BOOST_FOREACH(ui32 constituentID, *artifact.constituents) {
  2905. if (destSpecific && constituentID == destArtifact->id) {
  2906. sha.artifWorn[artifactSlot] = assembleTo;
  2907. destConsumed = true;
  2908. continue;
  2909. }
  2910. bool found = false;
  2911. for (std::map<ui16, ui32>::iterator it = sha.artifWorn.begin(); it != sha.artifWorn.end(); ++it) {
  2912. if (it->second == constituentID) { // Found possible constituent to substitute.
  2913. if (destSpecific && !destConsumed && it->second == destArtifact->id) {
  2914. // Find the specified destination for assembled artifact.
  2915. if (it->first == artifactSlot) {
  2916. it->second = assembleTo;
  2917. destConsumed = true;
  2918. found = true;
  2919. break;
  2920. }
  2921. } else {
  2922. // Either put the assembled artifact in a fitting spot, or put a lock.
  2923. if (!destSpecific && !destConsumed && vstd::contains(artifact.possibleSlots, it->first)) {
  2924. it->second = assembleTo;
  2925. destConsumed = true;
  2926. } else {
  2927. it->second = 145;
  2928. }
  2929. found = true;
  2930. break;
  2931. }
  2932. }
  2933. }
  2934. if (!found) {
  2935. complain("Constituent missing.");
  2936. return false;
  2937. }
  2938. }
  2939. } else {
  2940. // Perform disassembly.
  2941. bool destConsumed = false; // Determines which constituent that will be counted for together with the artifact.
  2942. BOOST_FOREACH(ui32 constituentID, *destArtifact->constituents) {
  2943. const CArtifact &constituent = *VLC->arth->artifacts[constituentID];
  2944. if (!destConsumed && vstd::contains(constituent.possibleSlots, artifactSlot)) {
  2945. sha.artifWorn[artifactSlot] = constituentID;
  2946. destConsumed = true;
  2947. } else {
  2948. BOOST_REVERSE_FOREACH(ui16 slotID, constituent.possibleSlots) {
  2949. if (vstd::contains(sha.artifWorn, slotID) && sha.artifWorn[slotID] == 145) {
  2950. sha.artifWorn[slotID] = constituentID;
  2951. break;
  2952. }
  2953. }
  2954. }
  2955. }
  2956. }
  2957. sendAndApply(&sha);
  2958. return true;
  2959. }
  2960. bool CGameHandler::buyArtifact( ui32 hid, si32 aid )
  2961. {
  2962. CGHeroInstance *hero = gs->getHero(hid);
  2963. CGTownInstance *town = const_cast<CGTownInstance*>(hero->visitedTown);
  2964. if(aid==0) //spellbook
  2965. {
  2966. if(!vstd::contains(town->builtBuildings,si32(0)) && complain("Cannot buy a spellbook, no mage guild in the town!")
  2967. || getResource(hero->getOwner(),6)<500 && complain("Cannot buy a spellbook, not enough gold!")
  2968. || hero->getArt(17) && complain("Cannot buy a spellbook, hero already has a one!")
  2969. )
  2970. return false;
  2971. giveResource(hero->getOwner(),6,-500);
  2972. giveHeroArtifact(0,hid,17);
  2973. giveSpells(town,hero);
  2974. return true;
  2975. }
  2976. else if(aid < 7 && aid > 3) //war machine
  2977. {
  2978. int price = VLC->arth->artifacts[aid]->price;
  2979. if(vstd::contains(hero->artifWorn,ui16(9+aid)) && complain("Hero already has this machine!")
  2980. || !vstd::contains(town->builtBuildings,si32(16)) && complain("No blackismith!")
  2981. || gs->getPlayer(hero->getOwner())->resources[6] < price && complain("Not enough gold!") //no gold
  2982. || (!(town->subID == 6 && vstd::contains(town->builtBuildings,si32(22) ) )
  2983. && town->town->warMachine!= aid ) && complain("This machine is unavailable here!") )
  2984. {
  2985. return false;
  2986. }
  2987. giveResource(hero->getOwner(),6,-price);
  2988. giveHeroArtifact(aid,hid,9+aid);
  2989. return true;
  2990. }
  2991. return false;
  2992. }
  2993. bool CGameHandler::buyArtifact(const IMarket *m, const CGHeroInstance *h, int rid, int aid)
  2994. {
  2995. if(!vstd::contains(m->availableItemsIds(RESOURCE_ARTIFACT), aid))
  2996. COMPLAIN_RET("That artifact is unavailable!");
  2997. int b1, b2;
  2998. m->getOffer(rid, aid, b1, b2, RESOURCE_ARTIFACT);
  2999. if(getResource(h->tempOwner, rid) < b1)
  3000. COMPLAIN_RET("You can't afford to buy this artifact!");
  3001. SetResource sr;
  3002. sr.player = h->tempOwner;
  3003. sr.resid = rid;
  3004. sr.val = getResource(h->tempOwner, rid) - b1;
  3005. sendAndApply(&sr);
  3006. SetAvailableArtifacts saa;
  3007. if(m->o->ID == TOWNI_TYPE)
  3008. {
  3009. saa.id = -1;
  3010. saa.arts = CGTownInstance::merchantArtifacts;
  3011. }
  3012. else if(const CGBlackMarket *bm = dynamic_cast<const CGBlackMarket *>(m->o)) //black market
  3013. {
  3014. saa.id = bm->id;
  3015. saa.arts = bm->artifacts;
  3016. }
  3017. else
  3018. COMPLAIN_RET("Wrong marktet...");
  3019. bool found = false;
  3020. BOOST_FOREACH(const CArtifact *&art, saa.arts)
  3021. {
  3022. if(art && art->id == aid)
  3023. {
  3024. art = NULL;
  3025. found = true;
  3026. break;
  3027. }
  3028. }
  3029. if(!found)
  3030. COMPLAIN_RET("Cannot find selected artifact on the list");
  3031. sendAndApply(&saa);
  3032. giveHeroArtifact(aid, h->id, -2);
  3033. return true;
  3034. }
  3035. bool CGameHandler::buySecSkill( const IMarket *m, const CGHeroInstance *h, int skill)
  3036. {
  3037. if (!h)
  3038. COMPLAIN_RET("You need hero to buy a skill!");
  3039. if (h->getSecSkillLevel(skill))
  3040. COMPLAIN_RET("Hero already know this skill");
  3041. if (h->secSkills.size() >= SKILL_PER_HERO)//can't learn more skills
  3042. COMPLAIN_RET("Hero can't learn any more skills");
  3043. if (h->type->heroClass->proSec[skill]==0)//can't learn this skill (like necromancy for most of non-necros)
  3044. COMPLAIN_RET("The hero can't learn this skill!");
  3045. if(!vstd::contains(m->availableItemsIds(RESOURCE_SKILL), skill))
  3046. COMPLAIN_RET("That skill is unavailable!");
  3047. if(getResource(h->tempOwner, 6) < 2000)//TODO: remove hardcoded resource\summ?
  3048. COMPLAIN_RET("You can't afford to buy this skill");
  3049. SetResource sr;
  3050. sr.player = h->tempOwner;
  3051. sr.resid = 6;
  3052. sr.val = getResource(h->tempOwner, 6) - 2000;
  3053. sendAndApply(&sr);
  3054. changeSecSkill(h->id, skill, 1, true);
  3055. return true;
  3056. }
  3057. bool CGameHandler::tradeResources(const IMarket *market, ui32 val, ui8 player, ui32 id1, ui32 id2)
  3058. {
  3059. int r1 = gs->getPlayer(player)->resources[id1],
  3060. r2 = gs->getPlayer(player)->resources[id2];
  3061. amin(val, r1); //can't trade more resources than have
  3062. int b1, b2; //base quantities for trade
  3063. market->getOffer(id1, id2, b1, b2, RESOURCE_RESOURCE);
  3064. int units = val / b1; //how many base quantities we trade
  3065. if(val%b1) //all offered units of resource should be used, if not -> somewhere in calculations must be an error
  3066. {
  3067. //TODO: complain?
  3068. assert(0);
  3069. }
  3070. SetResource sr;
  3071. sr.player = player;
  3072. sr.resid = id1;
  3073. sr.val = r1 - b1 * units;
  3074. sendAndApply(&sr);
  3075. sr.resid = id2;
  3076. sr.val = r2 + b2 * units;
  3077. sendAndApply(&sr);
  3078. return true;
  3079. }
  3080. bool CGameHandler::sellCreatures(ui32 count, const IMarket *market, const CGHeroInstance * hero, ui32 slot, ui32 resourceID)
  3081. {
  3082. if(!vstd::contains(hero->Slots(), slot))
  3083. COMPLAIN_RET("Hero doesn't have any creature in that slot!");
  3084. const CStackInstance &s = hero->getStack(slot);
  3085. if(s.count < count //can't sell more creatures than have
  3086. || hero->Slots().size() == 1 && hero->needsLastStack() && s.count == count) //can't sell last stack
  3087. {
  3088. COMPLAIN_RET("Not enough creatures in army!");
  3089. }
  3090. int b1, b2; //base quantities for trade
  3091. market->getOffer(s.type->idNumber, resourceID, b1, b2, CREATURE_RESOURCE);
  3092. int units = count / b1; //how many base quantities we trade
  3093. if(count%b1) //all offered units of resource should be used, if not -> somewhere in calculations must be an error
  3094. {
  3095. //TODO: complain?
  3096. assert(0);
  3097. }
  3098. SetGarrisons sg;
  3099. sg.garrs[hero->id] = hero->getArmy();
  3100. if(s.count > count)
  3101. sg.garrs[hero->id].setStackCount(slot, s.count - count);
  3102. else
  3103. sg.garrs[hero->id].eraseStack(slot);
  3104. sendAndApply(&sg);
  3105. SetResource sr;
  3106. sr.player = hero->tempOwner;
  3107. sr.resid = resourceID;
  3108. sr.val = getResource(hero->tempOwner, resourceID) + b2 * units;
  3109. sendAndApply(&sr);
  3110. return true;
  3111. }
  3112. bool CGameHandler::transformInUndead(const IMarket *market, const CGHeroInstance * hero, ui32 slot)
  3113. {
  3114. const CArmedInstance *army = NULL;
  3115. if (hero)
  3116. army = hero;
  3117. else
  3118. {
  3119. army = dynamic_cast<const CGTownInstance *>(market->o);
  3120. }
  3121. if (!army)
  3122. COMPLAIN_RET("Incorrect call to transform in undead!");
  3123. if(!vstd::contains(army->Slots(), slot))
  3124. COMPLAIN_RET("Army doesn't have any creature in that slot!");
  3125. const CStackInstance &s = army->getStack(slot);
  3126. int resCreature;//resulting creature - bone dragons or skeletons
  3127. if (s.hasBonusOfType(Bonus::DRAGON_NATURE))
  3128. resCreature = 68;
  3129. else
  3130. resCreature = 56;
  3131. SetGarrisons sg;
  3132. sg.garrs[army->id] = army->getArmy();
  3133. sg.garrs[army->id].setCreature(slot, resCreature, s.count);
  3134. sendAndApply(&sg);
  3135. return true;
  3136. }
  3137. bool CGameHandler::sendResources(ui32 val, ui8 player, ui32 r1, ui32 r2)
  3138. {
  3139. const PlayerState *p2 = gs->getPlayer(r2, false);
  3140. if(!p2 || p2->status != PlayerState::INGAME)
  3141. {
  3142. complain("Dest player must be in game!");
  3143. return false;
  3144. }
  3145. si32 curRes1 = gs->getPlayer(player)->resources[r1], curRes2 = gs->getPlayer(r2)->resources[r1];
  3146. val = std::min(si32(val),curRes1);
  3147. SetResource sr;
  3148. sr.player = player;
  3149. sr.resid = r1;
  3150. sr.val = curRes1 - val;
  3151. sendAndApply(&sr);
  3152. sr.player = r2;
  3153. sr.val = curRes2 + val;
  3154. sendAndApply(&sr);
  3155. return true;
  3156. }
  3157. bool CGameHandler::setFormation( si32 hid, ui8 formation )
  3158. {
  3159. gs->getHero(hid)-> formation = formation;
  3160. return true;
  3161. }
  3162. bool CGameHandler::hireHero(const CGObjectInstance *obj, ui8 hid, ui8 player)
  3163. {
  3164. const PlayerState *p = gs->getPlayer(player);
  3165. const CGTownInstance *t = gs->getTown(obj->id);
  3166. //common prconditions
  3167. if( p->resources[6]<2500 && complain("Not enough gold for buying hero!")
  3168. || getHeroCount(player, false) >= 8 && complain("Cannot hire hero, only 8 wandering heroes are allowed!"))
  3169. return false;
  3170. if(t) //tavern in town
  3171. {
  3172. if(!vstd::contains(t->builtBuildings,5) && complain("No tavern!")
  3173. || t->visitingHero && complain("There is visiting hero - no place!"))
  3174. return false;
  3175. }
  3176. else if(obj->ID == 95) //Tavern on adv map
  3177. {
  3178. if(getTile(obj->visitablePos())->visitableObjects.back() != obj && complain("Tavern entry must be unoccupied!"))
  3179. return false;
  3180. }
  3181. CGHeroInstance *nh = p->availableHeroes[hid];
  3182. assert(nh);
  3183. HeroRecruited hr;
  3184. hr.tid = obj->id;
  3185. hr.hid = nh->subID;
  3186. hr.player = player;
  3187. hr.tile = obj->visitablePos() + nh->getVisitableOffset();
  3188. sendAndApply(&hr);
  3189. std::map<ui32,CGHeroInstance *> pool = gs->unusedHeroesFromPool();
  3190. const CGHeroInstance *theOtherHero = p->availableHeroes[!hid];
  3191. const CGHeroInstance *newHero = gs->hpool.pickHeroFor(false, player, getNativeTown(player), pool, theOtherHero->type->heroClass);
  3192. SetAvailableHeroes sah;
  3193. sah.player = player;
  3194. if(newHero)
  3195. {
  3196. sah.hid[hid] = newHero->subID;
  3197. sah.army[hid] = new CCreatureSet();
  3198. sah.army[hid]->addToSlot(0, VLC->creh->nameToID[newHero->type->refTypeStack[0]],1);
  3199. }
  3200. else
  3201. sah.hid[hid] = -1;
  3202. sah.hid[!hid] = theOtherHero ? theOtherHero->subID : -1;
  3203. sendAndApply(&sah);
  3204. SetResource sr;
  3205. sr.player = player;
  3206. sr.resid = 6;
  3207. sr.val = p->resources[6] - 2500;
  3208. sendAndApply(&sr);
  3209. if(t)
  3210. {
  3211. vistiCastleObjects (t, nh);
  3212. giveSpells (t,nh);
  3213. }
  3214. return true;
  3215. }
  3216. bool CGameHandler::queryReply( ui32 qid, ui32 answer )
  3217. {
  3218. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  3219. if(vstd::contains(callbacks,qid))
  3220. {
  3221. CFunctionList<void(ui32)> callb = callbacks[qid];
  3222. callbacks.erase(qid);
  3223. if(callb)
  3224. callb(answer);
  3225. }
  3226. else if(vstd::contains(garrisonCallbacks,qid))
  3227. {
  3228. if(garrisonCallbacks[qid])
  3229. garrisonCallbacks[qid]();
  3230. garrisonCallbacks.erase(qid);
  3231. allowedExchanges.erase(qid);
  3232. }
  3233. else
  3234. {
  3235. tlog1 << "Unknown query reply...\n";
  3236. return false;
  3237. }
  3238. return true;
  3239. }
  3240. bool CGameHandler::makeBattleAction( BattleAction &ba )
  3241. {
  3242. tlog1 << "\tMaking action of type " << ba.actionType << std::endl;
  3243. bool ok = true;
  3244. switch(ba.actionType)
  3245. {
  3246. case 2: //walk
  3247. {
  3248. sendAndApply(&StartAction(ba)); //start movement
  3249. moveStack(ba.stackNumber,ba.destinationTile); //move
  3250. sendAndApply(&EndAction());
  3251. break;
  3252. }
  3253. case 3: //defend
  3254. case 8: //wait
  3255. {
  3256. sendAndApply(&StartAction(ba));
  3257. sendAndApply(&EndAction());
  3258. break;
  3259. }
  3260. case 4: //retreat/flee
  3261. {
  3262. if( !gs->battleCanFlee(ba.side ? gs->curB->side2 : gs->curB->side1) )
  3263. break;
  3264. //TODO: remove retreating hero from map and place it in recruitment list
  3265. BattleResult *br = new BattleResult;
  3266. br->result = 1;
  3267. br->winner = !ba.side; //fleeing side loses
  3268. gs->curB->calculateCasualties(br->casualties);
  3269. giveExp(*br);
  3270. battleResult.set(br);
  3271. break;
  3272. }
  3273. case 6: //walk or attack
  3274. {
  3275. sendAndApply(&StartAction(ba)); //start movement and attack
  3276. int startingPos = gs->curB->getStack(ba.stackNumber)->position;
  3277. int distance = moveStack(ba.stackNumber, ba.destinationTile);
  3278. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  3279. *stackAtEnd = gs->curB->getStackT(ba.additionalInfo);
  3280. if(curStack->position != ba.destinationTile //we wasn't able to reach destination tile
  3281. && !(curStack->doubleWide()
  3282. && ( curStack->position == ba.destinationTile + (curStack->attackerOwned ? +1 : -1 ) )
  3283. ) //nor occupy specified hex
  3284. )
  3285. {
  3286. std::string problem = "We cannot move this stack to its destination " + curStack->type->namePl;
  3287. tlog3 << problem << std::endl;
  3288. complain(problem);
  3289. ok = false;
  3290. sendAndApply(&EndAction());
  3291. break;
  3292. }
  3293. if(curStack->ID == stackAtEnd->ID) //we should just move, it will be handled by following check
  3294. {
  3295. stackAtEnd = NULL;
  3296. }
  3297. if(!stackAtEnd)
  3298. {
  3299. std::ostringstream problem;
  3300. problem << "There is no stack on " << ba.additionalInfo << " tile (no attack)!";
  3301. std::string probl = problem.str();
  3302. tlog3 << probl << std::endl;
  3303. complain(probl);
  3304. ok = false;
  3305. sendAndApply(&EndAction());
  3306. break;
  3307. }
  3308. ui16 curpos = curStack->position,
  3309. enemypos = stackAtEnd->position;
  3310. if( !(
  3311. (BattleInfo::mutualPosition(curpos, enemypos) >= 0) //front <=> front
  3312. || (curStack->doubleWide() //back <=> front
  3313. && BattleInfo::mutualPosition(curpos + (curStack->attackerOwned ? -1 : 1), enemypos) >= 0)
  3314. || (stackAtEnd->doubleWide() //front <=> back
  3315. && BattleInfo::mutualPosition(curpos, enemypos + (stackAtEnd->attackerOwned ? -1 : 1)) >= 0)
  3316. || (stackAtEnd->doubleWide() && curStack->doubleWide()//back <=> back
  3317. && BattleInfo::mutualPosition(curpos + (curStack->attackerOwned ? -1 : 1), enemypos + (stackAtEnd->attackerOwned ? -1 : 1)) >= 0)
  3318. )
  3319. )
  3320. {
  3321. tlog3 << "Attack cannot be performed!";
  3322. sendAndApply(&EndAction());
  3323. ok = false;
  3324. }
  3325. //attack
  3326. BattleAttack bat;
  3327. prepareAttack(bat, curStack, stackAtEnd, distance);
  3328. sendAndApply(&bat);
  3329. handleAfterAttackCasting(bat);
  3330. //counterattack
  3331. if(!curStack->hasBonusOfType(Bonus::BLOCKS_RETALIATION)
  3332. && stackAtEnd->alive()
  3333. && ( stackAtEnd->counterAttacks > 0 || stackAtEnd->hasBonusOfType(Bonus::UNLIMITED_RETALIATIONS) )
  3334. && !stackAtEnd->hasBonusOfType(Bonus::SIEGE_WEAPON)
  3335. && !stackAtEnd->hasBonusOfType(Bonus::HYPNOTIZED))
  3336. {
  3337. prepareAttack(bat, stackAtEnd, curStack, 0);
  3338. bat.flags |= 2;
  3339. sendAndApply(&bat);
  3340. handleAfterAttackCasting(bat);
  3341. }
  3342. //second attack
  3343. if(curStack->valOfBonuses(Bonus::ADDITIONAL_ATTACK) > 0
  3344. && !curStack->hasBonusOfType(Bonus::SHOOTER)
  3345. && curStack->alive()
  3346. && stackAtEnd->alive() )
  3347. {
  3348. bat.flags = 0;
  3349. prepareAttack(bat, curStack, stackAtEnd, 0);
  3350. sendAndApply(&bat);
  3351. handleAfterAttackCasting(bat);
  3352. }
  3353. //return
  3354. if(curStack->hasBonusOfType(Bonus::RETURN_AFTER_STRIKE) && startingPos != curStack->position && curStack->alive())
  3355. {
  3356. moveStack(ba.stackNumber, startingPos);
  3357. //NOTE: curStack->ID == ba.stackNumber (rev 1431)
  3358. }
  3359. sendAndApply(&EndAction());
  3360. break;
  3361. }
  3362. case 7: //shoot
  3363. {
  3364. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  3365. *destStack= gs->curB->getStackT(ba.destinationTile);
  3366. if( !gs->battleCanShoot(ba.stackNumber, ba.destinationTile) )
  3367. break;
  3368. sendAndApply(&StartAction(ba)); //start shooting
  3369. BattleAttack bat;
  3370. bat.flags |= 1;
  3371. prepareAttack(bat, curStack, destStack, 0);
  3372. sendAndApply(&bat);
  3373. if(curStack->valOfBonuses(Bonus::ADDITIONAL_ATTACK) > 0 //if unit shots twice let's make another shot
  3374. && curStack->alive()
  3375. && destStack->alive()
  3376. && curStack->shots
  3377. )
  3378. {
  3379. prepareAttack(bat, curStack, destStack, 0);
  3380. sendAndApply(&bat);
  3381. handleAfterAttackCasting(bat);
  3382. }
  3383. sendAndApply(&EndAction());
  3384. break;
  3385. }
  3386. case 9: //catapult
  3387. {
  3388. sendAndApply(&StartAction(ba));
  3389. const CGHeroInstance * attackingHero = gs->curB->heroes[ba.side];
  3390. CHeroHandler::SBallisticsLevelInfo sbi = VLC->heroh->ballistics[attackingHero->getSecSkillLevel(10)]; //ballistics
  3391. int attackedPart = gs->curB->hexToWallPart(ba.destinationTile);
  3392. if(attackedPart == -1)
  3393. {
  3394. complain("catapult tried to attack non-catapultable hex!");
  3395. break;
  3396. }
  3397. int wallInitHP = gs->curB->si.wallState[attackedPart];
  3398. int dmgAlreadyDealt = 0; //in successive iterations damage is dealt but not yet substracted from wall's HPs
  3399. for(int g=0; g<sbi.shots; ++g)
  3400. {
  3401. if(wallInitHP + dmgAlreadyDealt == 3) //it's not destroyed
  3402. continue;
  3403. CatapultAttack ca; //package for clients
  3404. std::pair< std::pair< ui8, si16 >, ui8> attack; //<< attackedPart , destination tile >, damageDealt >
  3405. attack.first.first = attackedPart;
  3406. attack.first.second = ba.destinationTile;
  3407. attack.second = 0;
  3408. int chanceForHit = 0;
  3409. int dmgChance[3] = {sbi.noDmg, sbi.oneDmg, sbi.twoDmg}; //dmgChance[i] - chance for doing i dmg when hit is successful
  3410. switch(attackedPart)
  3411. {
  3412. case 0: //keep
  3413. chanceForHit = sbi.keep;
  3414. break;
  3415. case 1: //bottom tower
  3416. case 6: //upper tower
  3417. chanceForHit = sbi.tower;
  3418. break;
  3419. case 2: //bottom wall
  3420. case 3: //below gate
  3421. case 4: //over gate
  3422. case 5: //upper wall
  3423. chanceForHit = sbi.wall;
  3424. break;
  3425. case 7: //gate
  3426. chanceForHit = sbi.gate;
  3427. break;
  3428. }
  3429. if(rand()%100 <= chanceForHit) //hit is successful
  3430. {
  3431. int dmgRand = rand()%100;
  3432. //accumulating dmgChance
  3433. dmgChance[1] += dmgChance[0];
  3434. dmgChance[2] += dmgChance[1];
  3435. //calculating dealt damage
  3436. for(int v = 0; v < ARRAY_COUNT(dmgChance); ++v)
  3437. {
  3438. if(dmgRand <= dmgChance[v])
  3439. {
  3440. attack.second = std::min(3 - dmgAlreadyDealt - wallInitHP, v);
  3441. dmgAlreadyDealt += attack.second;
  3442. break;
  3443. }
  3444. }
  3445. //removing creatures in turrets / keep if one is destroyed
  3446. if(attack.second > 0 && (attackedPart == 0 || attackedPart == 1 || attackedPart == 6))
  3447. {
  3448. int posRemove = -1;
  3449. switch(attackedPart)
  3450. {
  3451. case 0: //keep
  3452. posRemove = -2;
  3453. break;
  3454. case 1: //bottom tower
  3455. posRemove = -3;
  3456. break;
  3457. case 6: //upper tower
  3458. posRemove = -4;
  3459. break;
  3460. }
  3461. BattleStacksRemoved bsr;
  3462. for(int g=0; g<gs->curB->stacks.size(); ++g)
  3463. {
  3464. if(gs->curB->stacks[g]->position == posRemove)
  3465. {
  3466. bsr.stackIDs.insert( gs->curB->stacks[g]->ID );
  3467. break;
  3468. }
  3469. }
  3470. sendAndApply(&bsr);
  3471. }
  3472. }
  3473. ca.attacker = ba.stackNumber;
  3474. ca.attackedParts.insert(attack);
  3475. sendAndApply(&ca);
  3476. }
  3477. sendAndApply(&EndAction());
  3478. break;
  3479. }
  3480. case 12: //healing
  3481. {
  3482. sendAndApply(&StartAction(ba));
  3483. const CGHeroInstance * attackingHero = gs->curB->heroes[ba.side];
  3484. CStack *healer = gs->curB->getStack(ba.stackNumber),
  3485. *destStack = gs->curB->getStackT(ba.destinationTile);
  3486. if(healer == NULL || destStack == NULL || !healer->hasBonusOfType(Bonus::HEALER))
  3487. {
  3488. complain("There is either no healer, no destination, or healer cannot heal :P");
  3489. }
  3490. int maxHealable = destStack->MaxHealth() - destStack->firstHPleft;
  3491. int maxiumHeal = std::max(10, attackingHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 27));
  3492. int healed = std::min(maxHealable, maxiumHeal);
  3493. if(healed == 0)
  3494. {
  3495. //nothing to heal.. should we complain?
  3496. }
  3497. else
  3498. {
  3499. StacksHealedOrResurrected shr;
  3500. shr.lifeDrain = false;
  3501. StacksHealedOrResurrected::HealInfo hi;
  3502. hi.healedHP = healed;
  3503. hi.lowLevelResurrection = 0;
  3504. hi.stackID = destStack->ID;
  3505. shr.healedStacks.push_back(hi);
  3506. sendAndApply(&shr);
  3507. }
  3508. sendAndApply(&EndAction());
  3509. break;
  3510. }
  3511. }
  3512. if(ba.stackNumber == gs->curB->activeStack || battleResult.get()) //active stack has moved or battle has finished
  3513. battleMadeAction.setn(true);
  3514. return ok;
  3515. }
  3516. void CGameHandler::playerMessage( ui8 player, const std::string &message )
  3517. {
  3518. bool cheated=true;
  3519. sendAndApply(&PlayerMessage(player,message));
  3520. if(message == "vcmiistari") //give all spells and 999 mana
  3521. {
  3522. SetMana sm;
  3523. ChangeSpells cs;
  3524. SetHeroArtifacts sha;
  3525. CGHeroInstance *h = gs->getHero(gs->getPlayer(player)->currentSelection);
  3526. if(!h && complain("Cannot realize cheat, no hero selected!")) return;
  3527. sm.hid = cs.hid = h->id;
  3528. //give all spells
  3529. cs.learn = 1;
  3530. for(int i=0;i<VLC->spellh->spells.size();i++)
  3531. {
  3532. if(!VLC->spellh->spells[i].creatureAbility)
  3533. cs.spells.insert(i);
  3534. }
  3535. //give mana
  3536. sm.val = 999;
  3537. if(!h->getArt(17)) //hero doesn't have spellbook
  3538. {
  3539. //give spellbook
  3540. sha.hid = h->id;
  3541. sha.artifacts = h->artifacts;
  3542. sha.artifWorn = h->artifWorn;
  3543. VLC->arth->equipArtifact(sha.artifWorn, 17, 0);
  3544. sendAndApply(&sha);
  3545. }
  3546. sendAndApply(&cs);
  3547. sendAndApply(&sm);
  3548. }
  3549. else if(message == "vcmiainur") //gives 5 archangels into each slot
  3550. {
  3551. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  3552. if(!hero) return;
  3553. SetGarrisons sg;
  3554. CCreatureSet &newArmy = sg.garrs[hero->id];
  3555. newArmy = hero->getArmy();
  3556. for(int i=0; i<ARMY_SIZE; i++)
  3557. if(newArmy.slotEmpty(i))
  3558. newArmy.addToSlot(i, CStackInstance(13,5));
  3559. sendAndApply(&sg);
  3560. }
  3561. else if(message == "vcmiangband") //gives 10 black knight into each slot
  3562. {
  3563. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  3564. if(!hero) return;
  3565. SetGarrisons sg;
  3566. CCreatureSet &newArmy = sg.garrs[hero->id];
  3567. newArmy = hero->getArmy();
  3568. for(int i=0; i<ARMY_SIZE; i++)
  3569. if(newArmy.slotEmpty(i))
  3570. newArmy.addToSlot(i, CStackInstance(66,10));
  3571. sendAndApply(&sg);
  3572. }
  3573. else if(message == "vcminoldor") //all war machines
  3574. {
  3575. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  3576. if(!hero) return;
  3577. SetHeroArtifacts sha;
  3578. sha.hid = hero->id;
  3579. sha.artifacts = hero->artifacts;
  3580. sha.artifWorn = hero->artifWorn;
  3581. VLC->arth->equipArtifact(sha.artifWorn, 13, 4);
  3582. VLC->arth->equipArtifact(sha.artifWorn, 14, 5);
  3583. VLC->arth->equipArtifact(sha.artifWorn, 15, 6);
  3584. sendAndApply(&sha);
  3585. }
  3586. else if(message == "vcminahar") //1000000 movement points
  3587. {
  3588. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  3589. if(!hero) return;
  3590. SetMovePoints smp;
  3591. smp.hid = hero->id;
  3592. smp.val = 1000000;
  3593. sendAndApply(&smp);
  3594. }
  3595. else if(message == "vcmiformenos") //give resources
  3596. {
  3597. SetResources sr;
  3598. sr.player = player;
  3599. sr.res = gs->getPlayer(player)->resources;
  3600. for(int i=0;i<7;i++)
  3601. sr.res[i] += 100;
  3602. sr.res[6] += 19900;
  3603. sendAndApply(&sr);
  3604. }
  3605. else if(message == "vcmieagles") //reveal FoW
  3606. {
  3607. FoWChange fc;
  3608. fc.mode = 1;
  3609. fc.player = player;
  3610. for(int i=0;i<gs->map->width;i++)
  3611. for(int j=0;j<gs->map->height;j++)
  3612. for(int k=0;k<gs->map->twoLevel+1;k++)
  3613. if(!gs->getPlayerTeam(fc.player)->fogOfWarMap[i][j][k])
  3614. fc.tiles.insert(int3(i,j,k));
  3615. sendAndApply(&fc);
  3616. }
  3617. else if(message == "vcmiglorfindel") //selected hero gains a new level
  3618. {
  3619. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  3620. changePrimSkill(hero->id,4,VLC->heroh->reqExp(hero->level+1) - VLC->heroh->reqExp(hero->level));
  3621. }
  3622. else if(message == "vcmisilmaril") //player wins
  3623. {
  3624. gs->getPlayer(player)->enteredWinningCheatCode = 1;
  3625. checkLossVictory(player);
  3626. }
  3627. else if(message == "vcmimelkor") //player looses
  3628. {
  3629. gs->getPlayer(player)->enteredLosingCheatCode = 1;
  3630. checkLossVictory(player);
  3631. }
  3632. else if (message == "vcmiforgeofnoldorking") //hero gets all artifacts except war machines, spell scrolls and spell book
  3633. {
  3634. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  3635. if(!hero) return;
  3636. SetHeroArtifacts sha;
  3637. sha.hid = hero->id;
  3638. sha.artifacts = hero->artifacts;
  3639. sha.artifWorn = hero->artifWorn;
  3640. sha.artifacts.push_back(2); //grail
  3641. for (int g=7; g<=140; ++g)
  3642. {
  3643. sha.artifacts.push_back(g);
  3644. }
  3645. sendAndApply(&sha);
  3646. }
  3647. else
  3648. cheated = false;
  3649. if(cheated)
  3650. {
  3651. sendAndApply(&SystemMessage(VLC->generaltexth->allTexts[260]));
  3652. }
  3653. }
  3654. static std::vector<ui32> calculateResistedStacks(const CSpell * sp, const CGHeroInstance * caster, const CGHeroInstance * hero2, const std::set<CStack*> affectedCreatures)
  3655. {
  3656. std::vector<ui32> ret;
  3657. for(std::set<CStack*>::const_iterator it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  3658. {
  3659. if (NBonus::hasOfType(caster, Bonus::NEGATE_ALL_NATURAL_IMMUNITIES) ||
  3660. NBonus::hasOfType(hero2, Bonus::NEGATE_ALL_NATURAL_IMMUNITIES))
  3661. {
  3662. //don't use natural immunities when one of heroes has this bonus
  3663. BonusList bl = (*it)->getBonuses(Selector::type(Bonus::SPELL_IMMUNITY)),
  3664. b2 = (*it)->getBonuses(Selector::type(Bonus::LEVEL_SPELL_IMMUNITY));
  3665. bl.insert(bl.end(), b2.begin(), b2.end());
  3666. BOOST_FOREACH(Bonus bb, bl)
  3667. {
  3668. if( (bb.type == Bonus::SPELL_IMMUNITY && bb.subtype == sp->id || //100% sure spell immunity
  3669. bb.type == Bonus::LEVEL_SPELL_IMMUNITY && bb.val >= sp->level) //some creature abilities have level 0
  3670. && bb.source != Bonus::CREATURE_ABILITY)
  3671. {
  3672. ret.push_back((*it)->ID);
  3673. continue;
  3674. }
  3675. }
  3676. }
  3677. else
  3678. {
  3679. if ((*it)->hasBonusOfType(Bonus::SPELL_IMMUNITY, sp->id) //100% sure spell immunity
  3680. || ( (*it)->hasBonusOfType(Bonus::LEVEL_SPELL_IMMUNITY) &&
  3681. (*it)->valOfBonuses(Bonus::LEVEL_SPELL_IMMUNITY) >= sp->level) ) //some creature abilities have level 0
  3682. {
  3683. ret.push_back((*it)->ID);
  3684. continue;
  3685. }
  3686. }
  3687. //non-negative spells on friendly stacks should always succeed, unless immune
  3688. if(sp->positiveness >= 0 && (*it)->owner == caster->tempOwner)
  3689. continue;
  3690. const CGHeroInstance * bonusHero; //hero we should take bonuses from
  3691. if(caster && (*it)->owner == caster->tempOwner)
  3692. bonusHero = caster;
  3693. else
  3694. bonusHero = hero2;
  3695. int prob = (*it)->valOfBonuses(Bonus::MAGIC_RESISTANCE); //probability of resistance in %
  3696. if(bonusHero)
  3697. {
  3698. //bonusHero's resistance support (secondary skils and artifacts)
  3699. prob += bonusHero->valOfBonuses(Bonus::MAGIC_RESISTANCE);
  3700. //resistance skill
  3701. prob += bonusHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 26) / 100.0f;
  3702. }
  3703. if(prob > 100) prob = 100;
  3704. if(rand()%100 < prob) //immunity from resistance
  3705. ret.push_back((*it)->ID);
  3706. }
  3707. if(sp->id == 60) //hypnotize
  3708. {
  3709. for(std::set<CStack*>::const_iterator it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  3710. {
  3711. if( (*it)->hasBonusOfType(Bonus::SPELL_IMMUNITY, sp->id) //100% sure spell immunity
  3712. || ( (*it)->count - 1 ) * (*it)->MaxHealth() + (*it)->firstHPleft
  3713. >
  3714. caster->getPrimSkillLevel(2) * 25 + sp->powers[caster->getSpellSchoolLevel(sp)]
  3715. )
  3716. {
  3717. ret.push_back((*it)->ID);
  3718. }
  3719. }
  3720. }
  3721. return ret;
  3722. }
  3723. void CGameHandler::handleSpellCasting( int spellID, int spellLvl, int destination, ui8 casterSide, ui8 casterColor,
  3724. const CGHeroInstance * caster, const CGHeroInstance * secHero, int usedSpellPower )
  3725. {
  3726. CSpell *spell = &VLC->spellh->spells[spellID];
  3727. BattleSpellCast sc;
  3728. sc.side = casterSide;
  3729. sc.id = spellID;
  3730. sc.skill = spellLvl;
  3731. sc.tile = destination;
  3732. sc.dmgToDisplay = 0;
  3733. sc.castedByHero = (bool)caster;
  3734. //calculating affected creatures for all spells
  3735. std::set<CStack*> attackedCres = gs->curB->getAttackedCreatures(spell, spellLvl, casterColor, destination);
  3736. for(std::set<CStack*>::const_iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  3737. {
  3738. sc.affectedCres.insert((*it)->ID);
  3739. }
  3740. //checking if creatures resist
  3741. sc.resisted = calculateResistedStacks(spell, caster, secHero, attackedCres);
  3742. //calculating dmg to display
  3743. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  3744. {
  3745. if(vstd::contains(sc.resisted, (*it)->ID)) //this creature resisted the spell
  3746. continue;
  3747. sc.dmgToDisplay += gs->curB->calculateSpellDmg(spell, caster, *it, spellLvl, usedSpellPower);
  3748. }
  3749. sendAndApply(&sc);
  3750. //applying effects
  3751. switch(spellID)
  3752. {
  3753. case 15: //magic arrow
  3754. case 16: //ice bolt
  3755. case 17: //lightning bolt
  3756. case 18: //implosion
  3757. case 20: //frost ring
  3758. case 21: //fireball
  3759. case 22: //inferno
  3760. case 23: //meteor shower
  3761. case 24: //death ripple
  3762. case 25: //destroy undead
  3763. case 26: //armageddon
  3764. case 77: //Thunderbolt (thunderbirds)
  3765. {
  3766. StacksInjured si;
  3767. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  3768. {
  3769. if(vstd::contains(sc.resisted, (*it)->ID)) //this creature resisted the spell
  3770. continue;
  3771. BattleStackAttacked bsa;
  3772. bsa.flags |= 2;
  3773. bsa.effect = spell->mainEffectAnim;
  3774. bsa.damageAmount = gs->curB->calculateSpellDmg(spell, caster, *it, spellLvl, usedSpellPower);
  3775. bsa.stackAttacked = (*it)->ID;
  3776. bsa.attackerID = -1;
  3777. prepareAttacked(bsa,*it);
  3778. si.stacks.push_back(bsa);
  3779. }
  3780. if(!si.stacks.empty())
  3781. sendAndApply(&si);
  3782. break;
  3783. }
  3784. case 27: //shield
  3785. case 28: //air shield
  3786. case 29: //fire shield
  3787. case 30: //protection from air
  3788. case 31: //protection from fire
  3789. case 32: //protection from water
  3790. case 33: //protection from earth
  3791. case 34: //anti-magic
  3792. case 41: //bless
  3793. case 42: //curse
  3794. case 43: //bloodlust
  3795. case 44: //precision
  3796. case 45: //weakness
  3797. case 46: //stone skin
  3798. case 47: //disrupting ray
  3799. case 48: //prayer
  3800. case 49: //mirth
  3801. case 50: //sorrow
  3802. case 51: //fortune
  3803. case 52: //misfortune
  3804. case 53: //haste
  3805. case 54: //slow
  3806. case 55: //slayer
  3807. case 56: //frenzy
  3808. case 58: //counterstrike
  3809. case 59: //berserk
  3810. case 60: //hypnotize
  3811. case 61: //forgetfulness
  3812. case 62: //blind
  3813. {
  3814. SetStackEffect sse;
  3815. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  3816. {
  3817. if(vstd::contains(sc.resisted, (*it)->ID)) //this creature resisted the spell
  3818. continue;
  3819. sse.stacks.push_back((*it)->ID);
  3820. }
  3821. sse.effect.id = spellID;
  3822. sse.effect.val = spellLvl;
  3823. sse.effect.turnsRemain = gs->curB->calculateSpellDuration(spell, caster, usedSpellPower);
  3824. if(!sse.stacks.empty())
  3825. sendAndApply(&sse);
  3826. break;
  3827. }
  3828. case 63: //teleport
  3829. {
  3830. BattleStackMoved bsm;
  3831. bsm.distance = -1;
  3832. bsm.stack = gs->curB->activeStack;
  3833. bsm.ending = true;
  3834. bsm.tile = destination;
  3835. bsm.teleporting = true;
  3836. sendAndApply(&bsm);
  3837. break;
  3838. }
  3839. case 37: //cure
  3840. case 38: //resurrection
  3841. case 39: //animate dead
  3842. {
  3843. StacksHealedOrResurrected shr;
  3844. shr.lifeDrain = false;
  3845. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  3846. {
  3847. if(vstd::contains(sc.resisted, (*it)->ID) //this creature resisted the spell
  3848. || (spellID == 39 && !(*it)->hasBonusOfType(Bonus::UNDEAD)) //we try to cast animate dead on living stack
  3849. )
  3850. continue;
  3851. StacksHealedOrResurrected::HealInfo hi;
  3852. hi.stackID = (*it)->ID;
  3853. hi.healedHP = gs->curB->calculateHealedHP(caster, spell, *it);
  3854. hi.lowLevelResurrection = spellLvl <= 1;
  3855. shr.healedStacks.push_back(hi);
  3856. }
  3857. if(!shr.healedStacks.empty())
  3858. sendAndApply(&shr);
  3859. break;
  3860. }
  3861. case 64: //remove obstacle
  3862. {
  3863. ObstaclesRemoved obr;
  3864. for(int g=0; g<gs->curB->obstacles.size(); ++g)
  3865. {
  3866. std::vector<int> blockedHexes = VLC->heroh->obstacles[gs->curB->obstacles[g].ID].getBlocked(gs->curB->obstacles[g].pos);
  3867. if(vstd::contains(blockedHexes, destination)) //this obstacle covers given hex
  3868. {
  3869. obr.obstacles.insert(gs->curB->obstacles[g].uniqueID);
  3870. }
  3871. }
  3872. if(!obr.obstacles.empty())
  3873. sendAndApply(&obr);
  3874. break;
  3875. }
  3876. }
  3877. }
  3878. bool CGameHandler::makeCustomAction( BattleAction &ba )
  3879. {
  3880. switch(ba.actionType)
  3881. {
  3882. case 1: //hero casts spell
  3883. {
  3884. const CGHeroInstance *h = gs->curB->heroes[ba.side];
  3885. const CGHeroInstance *secondHero = gs->curB->heroes[!ba.side];
  3886. if(!h)
  3887. {
  3888. tlog2 << "Wrong caster!\n";
  3889. return false;
  3890. }
  3891. if(ba.additionalInfo >= VLC->spellh->spells.size())
  3892. {
  3893. tlog2 << "Wrong spell id (" << ba.additionalInfo << ")!\n";
  3894. return false;
  3895. }
  3896. const CSpell *s = &VLC->spellh->spells[ba.additionalInfo];
  3897. ui8 skill = h->getSpellSchoolLevel(s); //skill level
  3898. if( !(h->canCastThisSpell(s)) //hero cannot cast this spell at all
  3899. || (h->mana < gs->curB->getSpellCost(s, h)) //not enough mana
  3900. || (ba.additionalInfo < 10) //it's adventure spell (not combat)
  3901. || (gs->curB->castSpells[ba.side]) //spell has been cast
  3902. || (NBonus::hasOfType(secondHero, Bonus::SPELL_IMMUNITY, s->id)) //non - casting hero provides immunity for this spell
  3903. || (gs->battleMaxSpellLevel() < s->level) //non - casting hero stops caster from casting this spell
  3904. )
  3905. {
  3906. tlog2 << "Spell cannot be cast!\n";
  3907. return false;
  3908. }
  3909. sendAndApply(&StartAction(ba)); //start spell casting
  3910. handleSpellCasting (ba.additionalInfo, skill, ba.destinationTile, ba.side, h->tempOwner, h, secondHero, h->getPrimSkillLevel(2));
  3911. sendAndApply(&EndAction());
  3912. if( !gs->curB->getStack(gs->curB->activeStack, false)->alive() )
  3913. {
  3914. battleMadeAction.setn(true);
  3915. }
  3916. checkForBattleEnd(gs->curB->stacks);
  3917. if(battleResult.get())
  3918. {
  3919. battleMadeAction.setn(true);
  3920. //battle will be ended by startBattle function
  3921. //endBattle(gs->curB->tile, gs->curB->heroes[0], gs->curB->heroes[1]);
  3922. }
  3923. return true;
  3924. }
  3925. }
  3926. return false;
  3927. }
  3928. void CGameHandler::handleTimeEvents()
  3929. {
  3930. gs->map->events.sort(evntCmp);
  3931. while(gs->map->events.size() && gs->map->events.front()->firstOccurence+1 == gs->day)
  3932. {
  3933. CMapEvent *ev = gs->map->events.front();
  3934. for(int player = 0; player < PLAYER_LIMIT; player++)
  3935. {
  3936. PlayerState *pinfo = gs->getPlayer(player);
  3937. if( pinfo //player exists
  3938. && (ev->players & 1<<player) //event is enabled to this player
  3939. && ((ev->computerAffected && !pinfo->human)
  3940. || (ev->humanAffected && pinfo->human)
  3941. )
  3942. )
  3943. {
  3944. //give resources
  3945. SetResources sr;
  3946. sr.player = player;
  3947. sr.res = pinfo->resources;
  3948. //prepare dialog
  3949. InfoWindow iw;
  3950. iw.player = player;
  3951. iw.text << ev->message;
  3952. for (int i=0; i<ev->resources.size(); i++)
  3953. {
  3954. if(ev->resources[i]) //if resource is changed, we add it to the dialog
  3955. {
  3956. // If removing too much resources, adjust the
  3957. // amount so the total doesn't become negative.
  3958. if (sr.res[i] + ev->resources[i] < 0)
  3959. ev->resources[i] = -sr.res[i];
  3960. if(ev->resources[i]) //if non-zero res change
  3961. {
  3962. iw.components.push_back(Component(Component::RESOURCE,i,ev->resources[i],0));
  3963. sr.res[i] += ev->resources[i];
  3964. }
  3965. }
  3966. }
  3967. if (iw.components.size())
  3968. {
  3969. sendAndApply(&sr); //update player resources if changed
  3970. }
  3971. sendAndApply(&iw); //show dialog
  3972. }
  3973. } //PLAYERS LOOP
  3974. if(ev->nextOccurence)
  3975. {
  3976. ev->firstOccurence += ev->nextOccurence;
  3977. gs->map->events.sort(evntCmp);
  3978. }
  3979. else
  3980. {
  3981. delete ev;
  3982. gs->map->events.pop_front();
  3983. }
  3984. }
  3985. }
  3986. void CGameHandler::handleTownEvents(CGTownInstance * town, NewTurn &n, std::map<si32, std::map<si32, si32> > &newCreas)
  3987. {
  3988. town->events.sort(evntCmp);
  3989. while(town->events.size() && town->events.front()->firstOccurence == gs->day)
  3990. {
  3991. ui8 player = town->tempOwner;
  3992. CCastleEvent *ev = town->events.front();
  3993. PlayerState *pinfo = gs->getPlayer(player);
  3994. if( pinfo //player exists
  3995. && (ev->players & 1<<player) //event is enabled to this player
  3996. && ((ev->computerAffected && !pinfo->human)
  3997. || (ev->humanAffected && pinfo->human) ) )
  3998. {
  3999. // dialog
  4000. InfoWindow iw;
  4001. iw.player = player;
  4002. iw.text << ev->message;
  4003. for (int i=0; i<ev->resources.size(); i++)
  4004. if(ev->resources[i]) //if resource had changed, we add it to the dialog
  4005. {
  4006. int was = n.res[player][i];
  4007. n.res[player][i] += ev->resources[i];
  4008. n.res[player][i] = std::max<si32>(n.res[player][i], 0);
  4009. if(pinfo->resources[i] != n.res[player][i]) //if non-zero res change
  4010. iw.components.push_back(Component(Component::RESOURCE,i,n.res[player][i]-was,0));
  4011. }
  4012. for(std::set<si32>::iterator i = ev->buildings.begin(); i!=ev->buildings.end();i++)
  4013. if ( !vstd::contains(town->builtBuildings, *i))
  4014. {
  4015. buildStructure(town->id, *i, true);
  4016. iw.components.push_back(Component(Component::BUILDING, town->subID, *i, 0));
  4017. }
  4018. for(si32 i=0;i<ev->creatures.size();i++) //creature growths
  4019. {
  4020. if(town->creatureDwelling(i) && ev->creatures[i])//there is dwelling
  4021. {
  4022. newCreas[town->id][i] += ev->creatures[i];
  4023. iw.components.push_back(Component(Component::CREATURE,
  4024. town->creatures[i].second.back(), ev->creatures[i], 0));
  4025. }
  4026. }
  4027. sendAndApply(&iw); //show dialog
  4028. }
  4029. if(ev->nextOccurence)
  4030. {
  4031. ev->firstOccurence += ev->nextOccurence;
  4032. town->events.sort(evntCmp);
  4033. }
  4034. else
  4035. {
  4036. delete ev;
  4037. town->events.pop_front();
  4038. }
  4039. }
  4040. }
  4041. bool CGameHandler::complain( const std::string &problem )
  4042. {
  4043. sendMessageToAll("Server encountered a problem: " + problem);
  4044. tlog1 << problem << std::endl;
  4045. return true;
  4046. }
  4047. ui32 CGameHandler::getQueryResult( ui8 player, int queryID )
  4048. {
  4049. //TODO: write
  4050. return 0;
  4051. }
  4052. void CGameHandler::showGarrisonDialog( int upobj, int hid, bool removableUnits, const boost::function<void()> &cb )
  4053. {
  4054. ui8 player = getOwner(hid);
  4055. GarrisonDialog gd;
  4056. gd.hid = hid;
  4057. gd.objid = upobj;
  4058. {
  4059. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  4060. gd.id = QID;
  4061. garrisonCallbacks[QID] = cb;
  4062. allowedExchanges[QID] = std::pair<si32,si32>(upobj,hid);
  4063. states.addQuery(player,QID);
  4064. QID++;
  4065. gd.removableUnits = removableUnits;
  4066. sendAndApply(&gd);
  4067. }
  4068. }
  4069. void CGameHandler::showThievesGuildWindow(int requestingObjId)
  4070. {
  4071. OpenWindow ow;
  4072. ow.window = OpenWindow::THIEVES_GUILD;
  4073. ow.id1 = requestingObjId;
  4074. sendAndApply(&ow);
  4075. }
  4076. bool CGameHandler::isAllowedExchange( int id1, int id2 )
  4077. {
  4078. if(id1 == id2)
  4079. return true;
  4080. {
  4081. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  4082. for(std::map<ui32, std::pair<si32,si32> >::const_iterator i = allowedExchanges.begin(); i!=allowedExchanges.end(); i++)
  4083. if(id1 == i->second.first && id2 == i->second.second || id2 == i->second.first && id1 == i->second.second)
  4084. return true;
  4085. }
  4086. const CGObjectInstance *o1 = getObj(id1), *o2 = getObj(id2);
  4087. if(o1->ID == TOWNI_TYPE)
  4088. {
  4089. const CGTownInstance *t = static_cast<const CGTownInstance*>(o1);
  4090. if(t->visitingHero == o2 || t->garrisonHero == o2)
  4091. return true;
  4092. }
  4093. if(o2->ID == TOWNI_TYPE)
  4094. {
  4095. const CGTownInstance *t = static_cast<const CGTownInstance*>(o2);
  4096. if(t->visitingHero == o1 || t->garrisonHero == o1)
  4097. return true;
  4098. }
  4099. if(o1->ID == HEROI_TYPE && o2->ID == HEROI_TYPE
  4100. && distance(o1->pos, o2->pos) < 2) //hero stands on the same tile or on the neighbouring tiles
  4101. {
  4102. //TODO: it's workaround, we should check if first hero visited second and player hasn't closed exchange window
  4103. //(to block moving stacks for free [without visiting] beteen heroes)
  4104. return true;
  4105. }
  4106. return false;
  4107. }
  4108. void CGameHandler::objectVisited( const CGObjectInstance * obj, const CGHeroInstance * h )
  4109. {
  4110. obj->onHeroVisit(h);
  4111. }
  4112. bool CGameHandler::buildBoat( ui32 objid )
  4113. {
  4114. const IShipyard *obj = IShipyard::castFrom(getObj(objid));
  4115. int boatType = 1;
  4116. if(obj->state())
  4117. {
  4118. complain("Cannot build boat in this shipyard!");
  4119. return false;
  4120. }
  4121. else if(obj->o->ID == TOWNI_TYPE
  4122. && !vstd::contains((static_cast<const CGTownInstance*>(obj))->builtBuildings,6))
  4123. {
  4124. complain("Cannot build boat in the town - no shipyard!");
  4125. return false;
  4126. }
  4127. //TODO use "real" cost via obj->getBoatCost
  4128. if(getResource(obj->o->tempOwner, 6) < 1000 || getResource(obj->o->tempOwner, 0) < 10)
  4129. {
  4130. complain("Not enough resources to build a boat!");
  4131. return false;
  4132. }
  4133. int3 tile = obj->bestLocation();
  4134. if(!gs->map->isInTheMap(tile))
  4135. {
  4136. complain("Cannot find appropriate tile for a boat!");
  4137. return false;
  4138. }
  4139. //take boat cost
  4140. SetResources sr;
  4141. sr.player = obj->o->tempOwner;
  4142. sr.res = gs->getPlayer(obj->o->tempOwner)->resources;
  4143. sr.res[0] -= 10;
  4144. sr.res[6] -= 1000;
  4145. sendAndApply(&sr);
  4146. //create boat
  4147. NewObject no;
  4148. no.ID = 8;
  4149. no.subID = obj->getBoatType();
  4150. no.pos = tile + int3(1,0,0);
  4151. sendAndApply(&no);
  4152. return true;
  4153. }
  4154. void CGameHandler::engageIntoBattle( ui8 player )
  4155. {
  4156. if(vstd::contains(states.players, player))
  4157. states.setFlag(player,&PlayerStatus::engagedIntoBattle,true);
  4158. //notify interfaces
  4159. PlayerBlocked pb;
  4160. pb.player = player;
  4161. pb.reason = PlayerBlocked::UPCOMING_BATTLE;
  4162. sendAndApply(&pb);
  4163. }
  4164. void CGameHandler::winLoseHandle(ui8 players )
  4165. {
  4166. for(size_t i = 0; i < PLAYER_LIMIT; i++)
  4167. {
  4168. if(players & 1<<i && gs->getPlayer(i))
  4169. {
  4170. checkLossVictory(i);
  4171. }
  4172. }
  4173. }
  4174. void CGameHandler::checkLossVictory( ui8 player )
  4175. {
  4176. const PlayerState *p = gs->getPlayer(player);
  4177. if(p->status) //player already won / lost
  4178. return;
  4179. int loss = gs->lossCheck(player);
  4180. int vic = gs->victoryCheck(player);
  4181. if(!loss && !vic)
  4182. return;
  4183. InfoWindow iw;
  4184. getLossVicMessage(player, vic ? vic : loss , vic, iw);
  4185. sendAndApply(&iw);
  4186. PlayerEndsGame peg;
  4187. peg.player = player;
  4188. peg.victory = vic;
  4189. sendAndApply(&peg);
  4190. if(vic > 0) //one player won -> all enemies lost
  4191. {
  4192. iw.text.localStrings.front().second++; //message about losing because enemy won first is just after victory message
  4193. for (std::map<ui8,PlayerState>::const_iterator i = gs->players.begin(); i!=gs->players.end(); i++)
  4194. {
  4195. if(i->first < PLAYER_LIMIT && i->first != player)//FIXME: skip already eliminated players?
  4196. {
  4197. iw.player = i->first;
  4198. sendAndApply(&iw);
  4199. peg.player = i->first;
  4200. peg.victory = gameState()->getPlayerRelations(player, i->first) == 1; // ally of winner
  4201. sendAndApply(&peg);
  4202. }
  4203. }
  4204. }
  4205. else //player lost -> all his objects become unflagged (neutral)
  4206. {
  4207. std::vector<CGHeroInstance*> hlp = p->heroes;
  4208. for (std::vector<CGHeroInstance*>::const_iterator i = hlp.begin(); i != hlp.end(); i++) //eliminate heroes
  4209. removeObject((*i)->id);
  4210. for (std::vector<CGObjectInstance*>::const_iterator i = gs->map->objects.begin(); i != gs->map->objects.end(); i++) //unflag objs
  4211. {
  4212. if(*i && (*i)->tempOwner == player)
  4213. setOwner((**i).id,NEUTRAL_PLAYER);
  4214. }
  4215. //eliminating one player may cause victory of another:
  4216. winLoseHandle(ALL_PLAYERS & ~(1<<player));
  4217. }
  4218. if(vic)
  4219. {
  4220. end2 = true;
  4221. if(gs->campaign)
  4222. {
  4223. std::vector<CGHeroInstance *> hes;
  4224. BOOST_FOREACH(CGHeroInstance * ghi, gs->map->heroes)
  4225. {
  4226. if (ghi->tempOwner == 0 /*TODO: insert human player's color*/)
  4227. {
  4228. hes.push_back(ghi);
  4229. }
  4230. }
  4231. gs->campaign->mapConquered(hes);
  4232. UpdateCampaignState ucs;
  4233. ucs.camp = gs->campaign;
  4234. sendAndApply(&ucs);
  4235. }
  4236. }
  4237. }
  4238. void CGameHandler::getLossVicMessage( ui8 player, ui8 standard, bool victory, InfoWindow &out ) const
  4239. {
  4240. const PlayerState *p = gs->getPlayer(player);
  4241. // if(!p->human)
  4242. // return; //AI doesn't need text info of loss
  4243. out.player = player;
  4244. if(victory)
  4245. {
  4246. if(standard < 0) //not std loss
  4247. {
  4248. switch(gs->map->victoryCondition.condition)
  4249. {
  4250. case artifact:
  4251. out.text.addTxt(MetaString::GENERAL_TXT, 280); //Congratulations! You have found the %s, and can claim victory!
  4252. out.text.addReplacement(MetaString::ART_NAMES,gs->map->victoryCondition.ID); //artifact name
  4253. break;
  4254. case gatherTroop:
  4255. out.text.addTxt(MetaString::GENERAL_TXT, 276); //Congratulations! You have over %d %s in your armies. Your enemies have no choice but to bow down before your power!
  4256. out.text.addReplacement(gs->map->victoryCondition.count);
  4257. out.text.addReplacement(MetaString::CRE_PL_NAMES, gs->map->victoryCondition.ID);
  4258. break;
  4259. case gatherResource:
  4260. out.text.addTxt(MetaString::GENERAL_TXT, 278); //Congratulations! You have collected over %d %s in your treasury. Victory is yours!
  4261. out.text.addReplacement(gs->map->victoryCondition.count);
  4262. out.text.addReplacement(MetaString::RES_NAMES, gs->map->victoryCondition.ID);
  4263. break;
  4264. case buildCity:
  4265. out.text.addTxt(MetaString::GENERAL_TXT, 282); //Congratulations! You have successfully upgraded your town, and can claim victory!
  4266. break;
  4267. case buildGrail:
  4268. out.text.addTxt(MetaString::GENERAL_TXT, 284); //Congratulations! You have constructed a permanent home for the Grail, and can claim victory!
  4269. break;
  4270. case beatHero:
  4271. {
  4272. out.text.addTxt(MetaString::GENERAL_TXT, 252); //Congratulations! You have completed your quest to defeat the enemy hero %s. Victory is yours!
  4273. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance*>(gs->map->victoryCondition.obj);
  4274. assert(h);
  4275. out.text.addReplacement(h->name);
  4276. }
  4277. break;
  4278. case captureCity:
  4279. {
  4280. out.text.addTxt(MetaString::GENERAL_TXT, 249); //Congratulations! You captured %s, and are victorious!
  4281. const CGTownInstance *t = dynamic_cast<const CGTownInstance*>(gs->map->victoryCondition.obj);
  4282. assert(t);
  4283. out.text.addReplacement(t->name);
  4284. }
  4285. break;
  4286. case beatMonster:
  4287. out.text.addTxt(MetaString::GENERAL_TXT, 286); //Congratulations! You have completed your quest to kill the fearsome beast, and can claim victory!
  4288. break;
  4289. case takeDwellings:
  4290. out.text.addTxt(MetaString::GENERAL_TXT, 288); //Congratulations! Your flag flies on the dwelling of every creature. Victory is yours!
  4291. break;
  4292. case takeMines:
  4293. out.text.addTxt(MetaString::GENERAL_TXT, 290); //Congratulations! Your flag flies on every mine. Victory is yours!
  4294. break;
  4295. case transportItem:
  4296. out.text.addTxt(MetaString::GENERAL_TXT, 292); //Congratulations! You have reached your destination, precious cargo intact, and can claim victory!
  4297. break;
  4298. }
  4299. }
  4300. else
  4301. {
  4302. out.text.addTxt(MetaString::GENERAL_TXT, 659); //Congratulations! You have reached your destination, precious cargo intact, and can claim victory!
  4303. }
  4304. }
  4305. else
  4306. {
  4307. if(standard < 0) //not std loss
  4308. {
  4309. switch(gs->map->lossCondition.typeOfLossCon)
  4310. {
  4311. case lossCastle:
  4312. {
  4313. out.text.addTxt(MetaString::GENERAL_TXT, 251); //The town of %s has fallen - all is lost!
  4314. const CGTownInstance *t = dynamic_cast<const CGTownInstance*>(gs->map->lossCondition.obj);
  4315. assert(t);
  4316. out.text.addReplacement(t->name);
  4317. }
  4318. break;
  4319. case lossHero:
  4320. {
  4321. out.text.addTxt(MetaString::GENERAL_TXT, 253); //The hero, %s, has suffered defeat - your quest is over!
  4322. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance*>(gs->map->lossCondition.obj);
  4323. assert(h);
  4324. out.text.addReplacement(h->name);
  4325. }
  4326. break;
  4327. case timeExpires:
  4328. out.text.addTxt(MetaString::GENERAL_TXT, 254); //Alas, time has run out on your quest. All is lost.
  4329. break;
  4330. }
  4331. }
  4332. else if(standard == 2)
  4333. {
  4334. out.text.addTxt(MetaString::GENERAL_TXT, 7);//%s, your heroes abandon you, and you are banished from this land.
  4335. out.text.addReplacement(MetaString::COLOR, player);
  4336. out.components.push_back(Component(Component::FLAG,player,0,0));
  4337. }
  4338. else //lost all towns and heroes
  4339. {
  4340. out.text.addTxt(MetaString::GENERAL_TXT, 660); //All your forces have been defeated, and you are banished from this land!
  4341. }
  4342. }
  4343. }
  4344. bool CGameHandler::dig( const CGHeroInstance *h )
  4345. {
  4346. for (std::vector<CGObjectInstance*>::const_iterator i = gs->map->objects.begin(); i != gs->map->objects.end(); i++) //unflag objs
  4347. {
  4348. if(*i && (*i)->ID == 124 && (*i)->pos == h->getPosition())
  4349. {
  4350. complain("Cannot dig - there is already a hole under the hero!");
  4351. return false;
  4352. }
  4353. }
  4354. NewObject no;
  4355. no.ID = 124;
  4356. no.pos = h->getPosition();
  4357. no.subID = getTile(no.pos)->tertype;
  4358. if(no.subID >= 8) //no digging on water / rock
  4359. {
  4360. complain("Cannot dig - wrong terrain type!");
  4361. return false;
  4362. }
  4363. sendAndApply(&no);
  4364. SetMovePoints smp;
  4365. smp.hid = h->id;
  4366. smp.val = 0;
  4367. sendAndApply(&smp);
  4368. InfoWindow iw;
  4369. iw.player = h->tempOwner;
  4370. if(gs->map->grailPos == h->getPosition())
  4371. {
  4372. iw.text.addTxt(MetaString::GENERAL_TXT, 58); //"Congratulations! After spending many hours digging here, your hero has uncovered the "
  4373. iw.text.addTxt(MetaString::ART_NAMES, 2);
  4374. iw.soundID = soundBase::ULTIMATEARTIFACT;
  4375. giveHeroArtifact(2, h->id, -1); //give grail
  4376. sendAndApply(&iw);
  4377. iw.text.clear();
  4378. iw.text.addTxt(MetaString::ART_DESCR, 2);
  4379. sendAndApply(&iw);
  4380. }
  4381. else
  4382. {
  4383. iw.text.addTxt(MetaString::GENERAL_TXT, 59); //"Nothing here. \n Where could it be?"
  4384. iw.soundID = soundBase::Dig;
  4385. sendAndApply(&iw);
  4386. }
  4387. return true;
  4388. }
  4389. void CGameHandler::handleAfterAttackCasting( const BattleAttack & bat )
  4390. {
  4391. const CStack * attacker = gs->curB->getStack(bat.stackAttacking);
  4392. if( attacker->hasBonusOfType(Bonus::SPELL_AFTER_ATTACK) )
  4393. {
  4394. BOOST_FOREACH(const Bonus & sf, attacker->getBonuses(Selector::type(Bonus::SPELL_AFTER_ATTACK)))
  4395. {
  4396. if (sf.type == Bonus::SPELL_AFTER_ATTACK)
  4397. {
  4398. const CStack * oneOfAttacked = NULL;
  4399. for(int g=0; g<bat.bsa.size(); ++g)
  4400. {
  4401. if (bat.bsa[g].newAmount > 0)
  4402. {
  4403. oneOfAttacked = gs->curB->getStack(bat.bsa[g].stackAttacked);
  4404. break;
  4405. }
  4406. }
  4407. if(oneOfAttacked == NULL) //all attacked creatures have been killed
  4408. return;
  4409. int spellID = sf.subtype;
  4410. int spellLevel = sf.val;
  4411. int chance = sf.additionalInfo % 1000;
  4412. int meleeRanged = sf.additionalInfo / 1000;
  4413. int destination = oneOfAttacked->position;
  4414. //check if spell should be casted (probability handling)
  4415. if( rand()%100 >= chance )
  4416. continue;
  4417. //casting
  4418. handleSpellCasting(spellID, spellLevel, destination, !attacker->attackerOwned, attacker->owner, NULL, NULL, attacker->count);
  4419. }
  4420. }
  4421. }
  4422. }
  4423. bool CGameHandler::castSpell(const CGHeroInstance *h, int spellID, const int3 &pos)
  4424. {
  4425. const CSpell *s = &VLC->spellh->spells[spellID];
  4426. int cost = h->getSpellCost(s);
  4427. int schoolLevel = h->getSpellSchoolLevel(s);
  4428. if(!h->canCastThisSpell(s))
  4429. COMPLAIN_RET("Hero cannot cast this spell!");
  4430. if(h->mana < cost)
  4431. COMPLAIN_RET("Hero doesn't have enough spell points to cast this spell!");
  4432. if(s->combatSpell)
  4433. COMPLAIN_RET("This function can be used only for adventure map spells!");
  4434. AdvmapSpellCast asc;
  4435. asc.caster = h;
  4436. asc.spellID = spellID;
  4437. sendAndApply(&asc);
  4438. using namespace Spells;
  4439. switch(spellID)
  4440. {
  4441. case SUMMON_BOAT: //Summon Boat
  4442. {
  4443. //check if spell works at all
  4444. if(rand() % 100 >= s->powers[schoolLevel]) //power is % chance of success
  4445. {
  4446. InfoWindow iw;
  4447. iw.player = h->tempOwner;
  4448. iw.text.addTxt(MetaString::GENERAL_TXT, 336); //%s tried to summon a boat, but failed.
  4449. iw.text.addReplacement(h->name);
  4450. sendAndApply(&iw);
  4451. return true; //TODO? or should it be false? request was correct and realized, but spell failed...
  4452. }
  4453. //try to find unoccupied boat to summon
  4454. const CGBoat *nearest = NULL;
  4455. double dist = 0;
  4456. int3 summonPos = h->bestLocation();
  4457. if(summonPos.x < 0)
  4458. COMPLAIN_RET("There is no water tile available!");
  4459. BOOST_FOREACH(const CGObjectInstance *obj, gs->map->objects)
  4460. {
  4461. if(obj && obj->ID == 8)
  4462. {
  4463. const CGBoat *b = static_cast<const CGBoat*>(obj);
  4464. if(b->hero) continue; //we're looking for unoccupied boat
  4465. double nDist = distance(b->pos, h->getPosition());
  4466. if(!nearest || nDist < dist) //it's first boat or closer than previous
  4467. {
  4468. nearest = b;
  4469. dist = nDist;
  4470. }
  4471. }
  4472. }
  4473. if(nearest) //we found boat to summon
  4474. {
  4475. ChangeObjPos cop;
  4476. cop.objid = nearest->id;
  4477. cop.nPos = summonPos + int3(1,0,0);;
  4478. cop.flags = 1;
  4479. sendAndApply(&cop);
  4480. }
  4481. else if(schoolLevel < 2) //none or basic level -> cannot create boat :(
  4482. {
  4483. InfoWindow iw;
  4484. iw.player = h->tempOwner;
  4485. iw.text.addTxt(MetaString::GENERAL_TXT, 335); //There are no boats to summon.
  4486. sendAndApply(&iw);
  4487. }
  4488. else //create boat
  4489. {
  4490. NewObject no;
  4491. no.ID = 8;
  4492. no.subID = h->getBoatType();
  4493. no.pos = summonPos + int3(1,0,0);;
  4494. sendAndApply(&no);
  4495. }
  4496. break;
  4497. }
  4498. case SCUTTLE_BOAT: //Scuttle Boat
  4499. {
  4500. //check if spell works at all
  4501. if(rand() % 100 >= s->powers[schoolLevel]) //power is % chance of success
  4502. {
  4503. InfoWindow iw;
  4504. iw.player = h->tempOwner;
  4505. iw.text.addTxt(MetaString::GENERAL_TXT, 337); //%s tried to scuttle the boat, but failed
  4506. iw.text.addReplacement(h->name);
  4507. sendAndApply(&iw);
  4508. return true; //TODO? or should it be false? request was correct and realized, but spell failed...
  4509. }
  4510. if(!gs->map->isInTheMap(pos))
  4511. COMPLAIN_RET("Invalid dst tile for scuttle!");
  4512. //TODO: test range, visibility
  4513. const TerrainTile *t = &gs->map->getTile(pos);
  4514. if(!t->visitableObjects.size() || t->visitableObjects.back()->ID != 8)
  4515. COMPLAIN_RET("There is no boat to scuttle!");
  4516. RemoveObject ro;
  4517. ro.id = t->visitableObjects.back()->id;
  4518. sendAndApply(&ro);
  4519. break;
  4520. }
  4521. case DIMENSION_DOOR: //Dimension Door
  4522. {
  4523. const TerrainTile *dest = getTile(pos);
  4524. const TerrainTile *curr = getTile(h->getSightCenter());
  4525. if(!dest)
  4526. COMPLAIN_RET("Destination tile doesn't exist!");
  4527. if(!h->movement)
  4528. COMPLAIN_RET("Hero needs movement points to cast Dimension Door!");
  4529. if(h->getBonusesCount(Bonus::CASTED_SPELL, Spells::DIMENSION_DOOR) >= s->powers[schoolLevel]) //limit casts per turn
  4530. {
  4531. InfoWindow iw;
  4532. iw.player = h->tempOwner;
  4533. iw.text.addTxt(MetaString::GENERAL_TXT, 338); //%s is not skilled enough to cast this spell again today.
  4534. iw.text.addReplacement(h->name);
  4535. sendAndApply(&iw);
  4536. break;
  4537. }
  4538. GiveBonus gb;
  4539. gb.id = h->id;
  4540. gb.bonus = Bonus(Bonus::ONE_DAY, Bonus::NONE, Bonus::CASTED_SPELL, 0, Spells::DIMENSION_DOOR);
  4541. sendAndApply(&gb);
  4542. if(!dest->isClear(curr)) //wrong dest tile
  4543. {
  4544. InfoWindow iw;
  4545. iw.player = h->tempOwner;
  4546. iw.text.addTxt(MetaString::GENERAL_TXT, 70); //Dimension Door failed!
  4547. sendAndApply(&iw);
  4548. break;
  4549. }
  4550. //we need obtain guard pos before moving hero, otherwise we get nothing, because tile will be "unguarded" by hero
  4551. int3 guardPos = gs->guardingCreaturePosition(pos);
  4552. TryMoveHero tmh;
  4553. tmh.id = h->id;
  4554. tmh.movePoints = std::max<int>(0, h->movement - 300);
  4555. tmh.result = TryMoveHero::TELEPORTATION;
  4556. tmh.start = h->pos;
  4557. tmh.end = pos + h->getVisitableOffset();
  4558. getTilesInRange(tmh.fowRevealed, pos, h->getSightRadious(), h->tempOwner,1);
  4559. sendAndApply(&tmh);
  4560. tryAttackingGuard(guardPos, h);
  4561. }
  4562. break;
  4563. case FLY: //Fly
  4564. {
  4565. int subtype = schoolLevel >= 2 ? 1 : 2; //adv or expert
  4566. GiveBonus gb;
  4567. gb.id = h->id;
  4568. gb.bonus = Bonus(Bonus::ONE_DAY, Bonus::FLYING_MOVEMENT, Bonus::CASTED_SPELL, 0, Spells::FLY, subtype);
  4569. sendAndApply(&gb);
  4570. }
  4571. break;
  4572. case WATER_WALK: //Water Walk
  4573. {
  4574. int subtype = schoolLevel >= 2 ? 1 : 2; //adv or expert
  4575. GiveBonus gb;
  4576. gb.id = h->id;
  4577. gb.bonus = Bonus(Bonus::ONE_DAY, Bonus::WATER_WALKING, Bonus::CASTED_SPELL, 0, Spells::FLY, subtype);
  4578. sendAndApply(&gb);
  4579. }
  4580. break;
  4581. case TOWN_PORTAL: //Town Portal
  4582. {
  4583. //TODO: check if given position is valid
  4584. moveHero(h->id,pos,1);
  4585. }
  4586. break;
  4587. case VISIONS: //Visions
  4588. case VIEW_EARTH: //View Earth
  4589. case DISGUISE: //Disguise
  4590. case VIEW_AIR: //View Air
  4591. default:
  4592. COMPLAIN_RET("This spell is not implemented yet!");
  4593. break;
  4594. }
  4595. SetMana sm;
  4596. sm.hid = h->id;
  4597. sm.val = h->mana - cost;
  4598. sendAndApply(&sm);
  4599. return true;
  4600. }
  4601. void CGameHandler::visitObjectOnTile(const TerrainTile &t, const CGHeroInstance * h)
  4602. {
  4603. //to prevent self-visiting heroes on space press
  4604. if(t.visitableObjects.back() != h)
  4605. objectVisited(t.visitableObjects.back(), h);
  4606. else if(t.visitableObjects.size() > 1)
  4607. objectVisited(*(t.visitableObjects.end()-2),h);
  4608. }
  4609. bool CGameHandler::tryAttackingGuard(const int3 &guardPos, const CGHeroInstance * h)
  4610. {
  4611. if(!gs->map->isInTheMap(guardPos))
  4612. return false;
  4613. const TerrainTile &guardTile = gs->map->terrain[guardPos.x][guardPos.y][guardPos.z];
  4614. objectVisited(guardTile.visitableObjects.back(), h);
  4615. visitObjectAfterVictory = true;
  4616. return true;
  4617. }
  4618. bool CGameHandler::sacrificeCreatures(const IMarket *market, const CGHeroInstance *hero, TSlot slot, ui32 count)
  4619. {
  4620. int oldCount = hero->getAmount(slot);
  4621. int newCount = oldCount - count;
  4622. if(oldCount < count)
  4623. COMPLAIN_RET("Not enough creatures to sacrifice!")
  4624. else if(oldCount == count && hero->Slots().size() == 1 && hero->needsLastStack())
  4625. COMPLAIN_RET("Cannot sacrifice last creature!");
  4626. int crid = hero->getStack(slot).type->idNumber;
  4627. SetGarrisons sg;
  4628. sg.garrs[hero->id] = hero->getArmy();
  4629. if(newCount)
  4630. sg.garrs[hero->id].setStackCount(slot, newCount);
  4631. else
  4632. sg.garrs[hero->id].eraseStack(slot);
  4633. sendAndApply(&sg);
  4634. int dump, exp;
  4635. market->getOffer(crid, 0, dump, exp, CREATURE_EXP);
  4636. exp *= count;
  4637. changePrimSkill (hero->id, 4, exp*(100+hero->getSecSkillLevel(21)*5)/100.0f);
  4638. return true;
  4639. }
  4640. bool CGameHandler::sacrificeArtifact(const IMarket * m, const CGHeroInstance * hero, ui32 artID)
  4641. {
  4642. if(!removeArtifact(artID, hero->id))
  4643. COMPLAIN_RET("Cannot find artifact to sacrifice!");
  4644. int dmp, expToGive;
  4645. m->getOffer(artID, 0, dmp, expToGive, ARTIFACT_EXP);
  4646. changePrimSkill(hero->id, 4, expToGive);
  4647. return true;
  4648. }