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