CGameHandler.cpp 172 KB

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