CObjectHandler.cpp 198 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473
  1. /*
  2. * CObjectHandler.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CObjectHandler.h"
  12. #include "CDefObjInfoHandler.h"
  13. #include "CGeneralTextHandler.h"
  14. #include "CDefObjInfoHandler.h"
  15. #include "CHeroHandler.h"
  16. #include "CSpellHandler.h"
  17. #include "CModHandler.h"
  18. #include "../client/CSoundBase.h"
  19. #include "CTownHandler.h"
  20. #include "CCreatureHandler.h"
  21. #include "VCMI_Lib.h"
  22. #include "IGameCallback.h"
  23. #include "CGameState.h"
  24. #include "NetPacks.h"
  25. #include "StartInfo.h"
  26. #include "mapping/CMap.h"
  27. #include <SDL_stdinc.h>
  28. #include "CBuildingHandler.h"
  29. #include "JsonNode.h"
  30. #include "filesystem/Filesystem.h"
  31. using namespace boost::assign;
  32. // It looks that we can't rely on shadowCoverage correctness (Mantis #866). This may result
  33. // in notable performance decrease (SDL blit with custom alpha blit) not notable on my system (Ivan)
  34. #define USE_COVERAGE_MAP 0
  35. std::map<Obj, std::map<int, std::vector<ObjectInstanceID> > > CGTeleport::objs;
  36. std::vector<std::pair<ObjectInstanceID, ObjectInstanceID> > CGTeleport::gates;
  37. IGameCallback * IObjectInterface::cb = nullptr;
  38. extern std::minstd_rand ran;
  39. std::map <PlayerColor, std::set <ui8> > CGKeys::playerKeyMap;
  40. std::map <si32, std::vector<ObjectInstanceID> > CGMagi::eyelist;
  41. ui8 CGObelisk::obeliskCount; //how many obelisks are on map
  42. std::map<TeamID, ui8> CGObelisk::visited; //map: team_id => how many obelisks has been visited
  43. std::vector<const CArtifact *> CGTownInstance::merchantArtifacts;
  44. std::vector<int> CGTownInstance::universitySkills;
  45. ///helpers
  46. static void openWindow(const OpenWindow::EWindow type, const int id1, const int id2 = -1)
  47. {
  48. OpenWindow ow;
  49. ow.window = type;
  50. ow.id1 = id1;
  51. ow.id2 = id2;
  52. IObjectInterface::cb->sendAndApply(&ow);
  53. }
  54. static void showInfoDialog(const PlayerColor playerID, const ui32 txtID, const ui16 soundID)
  55. {
  56. InfoWindow iw;
  57. iw.soundID = soundID;
  58. iw.player = playerID;
  59. iw.text.addTxt(MetaString::ADVOB_TXT,txtID);
  60. IObjectInterface::cb->sendAndApply(&iw);
  61. }
  62. /*static void showInfoDialog(const ObjectInstanceID heroID, const ui32 txtID, const ui16 soundID)
  63. {
  64. const PlayerColor playerID = IObjectInterface::cb->getOwner(heroID);
  65. showInfoDialog(playerID,txtID,soundID);
  66. }*/
  67. static void showInfoDialog(const CGHeroInstance* h, const ui32 txtID, const ui16 soundID)
  68. {
  69. const PlayerColor playerID = h->getOwner();
  70. showInfoDialog(playerID,txtID,soundID);
  71. }
  72. static std::string & visitedTxt(const bool visited)
  73. {
  74. int id = visited ? 352 : 353;
  75. return VLC->generaltexth->allTexts[id];
  76. }
  77. ///IObjectInterface
  78. void IObjectInterface::onHeroVisit(const CGHeroInstance * h) const
  79. {}
  80. void IObjectInterface::onHeroLeave(const CGHeroInstance * h) const
  81. {}
  82. void IObjectInterface::newTurn () const
  83. {}
  84. IObjectInterface::~IObjectInterface()
  85. {}
  86. IObjectInterface::IObjectInterface()
  87. {}
  88. void IObjectInterface::initObj()
  89. {}
  90. void IObjectInterface::setProperty( ui8 what, ui32 val )
  91. {}
  92. bool IObjectInterface::wasVisited (PlayerColor player) const
  93. {
  94. return false;
  95. }
  96. bool IObjectInterface::wasVisited (const CGHeroInstance * h) const
  97. {
  98. return false;
  99. }
  100. void IObjectInterface::postInit()
  101. {}
  102. void IObjectInterface::preInit()
  103. {}
  104. void IObjectInterface::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  105. {
  106. }
  107. void IObjectInterface::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  108. {
  109. }
  110. void IObjectInterface::garrisonDialogClosed(const CGHeroInstance *hero) const
  111. {
  112. }
  113. void IObjectInterface::heroLevelUpDone(const CGHeroInstance *hero) const
  114. {
  115. }
  116. void CPlayersVisited::setPropertyDer( ui8 what, ui32 val )
  117. {
  118. if(what == 10)
  119. players.insert(PlayerColor(val));
  120. }
  121. bool CPlayersVisited::wasVisited( PlayerColor player ) const
  122. {
  123. return vstd::contains(players,player);
  124. }
  125. bool CPlayersVisited::wasVisited( TeamID team ) const
  126. {
  127. for(auto i : players)
  128. {
  129. if(cb->getPlayer(i)->team == team)
  130. return true;
  131. }
  132. return false;
  133. }
  134. // Bank helper. Find the creature ID and their number, and store the
  135. // result in storage (either guards or reward creatures).
  136. static void readCreatures(const JsonNode &creature, std::vector< std::pair <CreatureID, ui32> > &storage)
  137. {
  138. std::pair<CreatureID, si32> creInfo = std::make_pair(CreatureID::NONE, 0);
  139. //TODO: replace numeric id's with mod-friendly string id's
  140. creInfo.second = creature["number"].Float();
  141. creInfo.first = CreatureID((si32)creature["id"].Float());
  142. storage.push_back(creInfo);
  143. }
  144. // Bank helper. Process a bank level.
  145. static void readBankLevel(const JsonNode &level, BankConfig &bc)
  146. {
  147. int idx;
  148. bc.chance = level["chance"].Float();
  149. for(const JsonNode &creature : level["guards"].Vector())
  150. {
  151. readCreatures(creature, bc.guards);
  152. }
  153. bc.upgradeChance = level["upgrade_chance"].Float();
  154. bc.combatValue = level["combat_value"].Float();
  155. bc.resources = Res::ResourceSet(level["reward_resources"]);
  156. for(const JsonNode &creature : level["reward_creatures"].Vector())
  157. {
  158. readCreatures(creature, bc.creatures);
  159. }
  160. bc.artifacts.resize(4);
  161. idx = 0;
  162. for(const JsonNode &artifact : level["reward_artifacts"].Vector())
  163. {
  164. bc.artifacts[idx] = artifact.Float();
  165. idx ++;
  166. }
  167. bc.value = level["value"].Float();
  168. bc.rewardDifficulty = level["profitability"].Float();
  169. bc.easiest = level["easiest"].Float();
  170. }
  171. CObjectHandler::CObjectHandler()
  172. {
  173. logGlobal->traceStream() << "\t\tReading cregens ";
  174. const JsonNode config(ResourceID("config/dwellings.json"));
  175. for(const JsonNode &dwelling : config["dwellings"].Vector())
  176. {
  177. cregens[dwelling["dwelling"].Float()] = CreatureID((si32)dwelling["creature"].Float());
  178. }
  179. logGlobal->traceStream() << "\t\tDone loading cregens!";
  180. logGlobal->traceStream() << "\t\tReading resources prices ";
  181. const JsonNode config2(ResourceID("config/resources.json"));
  182. for(const JsonNode &price : config2["resources_prices"].Vector())
  183. {
  184. resVals.push_back(price.Float());
  185. }
  186. logGlobal->traceStream() << "\t\tDone loading resource prices!";
  187. logGlobal->traceStream() << "\t\tReading banks configs";
  188. const JsonNode config3(ResourceID("config/bankconfig.json"));
  189. int bank_num = 0;
  190. for(const JsonNode &bank : config3["banks"].Vector())
  191. {
  192. creBanksNames[bank_num] = bank["name"].String();
  193. int level_num = 0;
  194. for(const JsonNode &level : bank["levels"].Vector())
  195. {
  196. banksInfo[bank_num].push_back(new BankConfig);
  197. BankConfig &bc = *banksInfo[bank_num].back();
  198. bc.level = level_num;
  199. readBankLevel(level, bc);
  200. level_num ++;
  201. }
  202. bank_num ++;
  203. }
  204. logGlobal->traceStream() << "\t\tDone loading banks configs";
  205. }
  206. CObjectHandler::~CObjectHandler()
  207. {
  208. for(auto & mapEntry : banksInfo)
  209. {
  210. for(auto & vecEntry : mapEntry.second)
  211. {
  212. vecEntry.dellNull();
  213. }
  214. }
  215. }
  216. int CObjectHandler::bankObjToIndex (const CGObjectInstance * obj)
  217. {
  218. switch (obj->ID) //find appriopriate key
  219. {
  220. case Obj::CREATURE_BANK:
  221. return obj->subID;
  222. case Obj::DERELICT_SHIP:
  223. return 8;
  224. case Obj::DRAGON_UTOPIA:
  225. return 10;
  226. case Obj::CRYPT:
  227. return 9;
  228. case Obj::SHIPWRECK:
  229. return 7;
  230. default:
  231. logGlobal->warnStream() << "Unrecognized Bank indetifier!";
  232. return 0;
  233. }
  234. }
  235. PlayerColor CGObjectInstance::getOwner() const
  236. {
  237. //if (state)
  238. // return state->owner;
  239. //else
  240. return tempOwner; //won't have owner
  241. }
  242. CGObjectInstance::CGObjectInstance()
  243. {
  244. pos = int3(-1,-1,-1);
  245. //state = new CLuaObjectScript();
  246. ID = Obj::NO_OBJ;
  247. subID = -1;
  248. defInfo = nullptr;
  249. tempOwner = PlayerColor::UNFLAGGABLE;
  250. blockVisit = false;
  251. }
  252. CGObjectInstance::~CGObjectInstance()
  253. {
  254. //if (state)
  255. // delete state;
  256. //state=nullptr;
  257. }
  258. const std::string & CGObjectInstance::getHoverText() const
  259. {
  260. return hoverName;
  261. }
  262. void CGObjectInstance::setOwner(PlayerColor ow)
  263. {
  264. //if (state)
  265. // state->owner = ow;
  266. //else
  267. tempOwner = ow;
  268. }
  269. int CGObjectInstance::getWidth() const//returns width of object graphic in tiles
  270. {
  271. return defInfo->width;
  272. }
  273. int CGObjectInstance::getHeight() const //returns height of object graphic in tiles
  274. {
  275. return defInfo->height;
  276. }
  277. bool CGObjectInstance::visitableAt(int x, int y) const //returns true if object is visitable at location (x, y) form left top tile of image (x, y in tiles)
  278. {
  279. if(defInfo==nullptr)
  280. {
  281. logGlobal->warnStream() << "Warning: VisitableAt for obj "<< id.getNum() <<": nullptr defInfo!";
  282. return false;
  283. }
  284. if((defInfo->visitMap[y] >> (7-x) ) & 1)
  285. {
  286. return true;
  287. }
  288. return false;
  289. }
  290. bool CGObjectInstance::blockingAt(int x, int y) const
  291. {
  292. if(x<0 || y<0 || x>=getWidth() || y>=getHeight() || defInfo==nullptr)
  293. return false;
  294. if((defInfo->blockMap[y+6-getHeight()] >> (7-(8-getWidth()+x) )) & 1)
  295. return false;
  296. return true;
  297. }
  298. bool CGObjectInstance::coveringAt(int x, int y) const
  299. {
  300. //input coordinates are always negative
  301. x = -x;
  302. y = -y;
  303. #if USE_COVERAGE_MAP
  304. //NOTE: this code may be broken
  305. if((defInfo->coverageMap[y] >> (7-(x) )) & 1
  306. || (defInfo->shadowCoverage[y] >> (7-(x) )) & 1)
  307. return true;
  308. return false;
  309. #else
  310. return x >= 0 && y >= 0 && x < getWidth() && y < getHeight();
  311. #endif
  312. }
  313. bool CGObjectInstance::hasShadowAt( int x, int y ) const
  314. {
  315. #if USE_COVERAGE_MAP
  316. //NOTE: this code may be broken
  317. if( (defInfo->shadowCoverage[y] >> (7-(x) )) & 1 )
  318. return true;
  319. return false;
  320. #else
  321. return coveringAt(x,y);// ignore unreliable shadowCoverage map
  322. #endif
  323. }
  324. std::set<int3> CGObjectInstance::getBlockedPos() const
  325. {
  326. std::set<int3> ret;
  327. for(int w=0; w<getWidth(); ++w)
  328. {
  329. for(int h=0; h<getHeight(); ++h)
  330. {
  331. if(blockingAt(w, h))
  332. ret.insert(int3(pos.x - getWidth() + w + 1, pos.y - getHeight() + h + 1, pos.z));
  333. }
  334. }
  335. return ret;
  336. }
  337. bool CGObjectInstance::operator<(const CGObjectInstance & cmp) const //screen printing priority comparing
  338. {
  339. if(defInfo->printPriority==1 && cmp.defInfo->printPriority==0)
  340. return true;
  341. if(cmp.defInfo->printPriority==1 && defInfo->printPriority==0)
  342. return false;
  343. if(this->pos.y<cmp.pos.y)
  344. return true;
  345. if(this->pos.y>cmp.pos.y)
  346. return false;
  347. if(cmp.ID==Obj::HERO && ID!=Obj::HERO)
  348. return true;
  349. if(cmp.ID!=Obj::HERO && ID==Obj::HERO)
  350. return false;
  351. if(!defInfo->isVisitable() && cmp.defInfo->isVisitable())
  352. return true;
  353. if(!cmp.defInfo->isVisitable() && defInfo->isVisitable())
  354. return false;
  355. if(this->pos.x<cmp.pos.x)
  356. return true;
  357. return false;
  358. }
  359. void CGObjectInstance::initObj()
  360. {
  361. switch(ID)
  362. {
  363. case Obj::TAVERN:
  364. blockVisit = true;
  365. break;
  366. }
  367. }
  368. void CGObjectInstance::setProperty( ui8 what, ui32 val )
  369. {
  370. switch(what)
  371. {
  372. case ObjProperty::OWNER:
  373. tempOwner = PlayerColor(val);
  374. break;
  375. case ObjProperty::BLOCKVIS:
  376. blockVisit = val;
  377. break;
  378. case ObjProperty::ID:
  379. ID = Obj(val);
  380. break;
  381. case ObjProperty::SUBID:
  382. subID = val;
  383. break;
  384. }
  385. setPropertyDer(what, val);
  386. }
  387. void CGObjectInstance::setPropertyDer( ui8 what, ui32 val )
  388. {}
  389. int3 CGObjectInstance::getSightCenter() const
  390. {
  391. //return vistiable tile if possible
  392. for(int i=0; i < 8; i++)
  393. for(int j=0; j < 6; j++)
  394. if(visitableAt(i,j))
  395. return(pos + int3(i-7, j-5, 0));
  396. return pos;
  397. }
  398. int CGObjectInstance::getSightRadious() const
  399. {
  400. return 3;
  401. }
  402. void CGObjectInstance::getSightTiles(std::unordered_set<int3, ShashInt3> &tiles) const //returns reference to the set
  403. {
  404. cb->getTilesInRange(tiles, getSightCenter(), getSightRadious(), tempOwner, 1);
  405. }
  406. void CGObjectInstance::hideTiles(PlayerColor ourplayer, int radius) const
  407. {
  408. for (auto i = cb->gameState()->teams.begin(); i != cb->gameState()->teams.end(); i++)
  409. {
  410. if ( !vstd::contains(i->second.players, ourplayer ))//another team
  411. {
  412. for (auto & elem : i->second.players)
  413. if ( cb->getPlayer(elem)->status == EPlayerStatus::INGAME )//seek for living player (if any)
  414. {
  415. FoWChange fw;
  416. fw.mode = 0;
  417. fw.player = elem;
  418. cb->getTilesInRange (fw.tiles, pos, radius, (elem), -1);
  419. cb->sendAndApply (&fw);
  420. break;
  421. }
  422. }
  423. }
  424. }
  425. int3 CGObjectInstance::getVisitableOffset() const
  426. {
  427. for(int y = 0; y < 6; y++)
  428. for (int x = 0; x < 8; x++)
  429. if((defInfo->visitMap[5-y] >> x) & 1)
  430. return int3(x,y,0);
  431. logGlobal->warnStream() << "Warning: getVisitableOffset called on non-visitable obj!";
  432. return int3(-1,-1,-1);
  433. }
  434. void CGObjectInstance::getNameVis( std::string &hname ) const
  435. {
  436. const CGHeroInstance *h = cb->getSelectedHero(cb->getCurrentPlayer());
  437. hname = VLC->generaltexth->names[ID];
  438. if(h)
  439. {
  440. const bool visited = h->hasBonusFrom(Bonus::OBJECT,ID);
  441. hname + " " + visitedTxt(visited);
  442. }
  443. }
  444. void CGObjectInstance::giveDummyBonus(ObjectInstanceID heroID, ui8 duration) const
  445. {
  446. GiveBonus gbonus;
  447. gbonus.bonus.type = Bonus::NONE;
  448. gbonus.id = heroID.getNum();
  449. gbonus.bonus.duration = duration;
  450. gbonus.bonus.source = Bonus::OBJECT;
  451. gbonus.bonus.sid = ID;
  452. cb->giveHeroBonus(&gbonus);
  453. }
  454. void CGObjectInstance::onHeroVisit( const CGHeroInstance * h ) const
  455. {
  456. switch(ID)
  457. {
  458. case Obj::HILL_FORT:
  459. {
  460. openWindow(OpenWindow::HILL_FORT_WINDOW,id.getNum(),h->id.getNum());
  461. }
  462. break;
  463. case Obj::SANCTUARY:
  464. {
  465. //You enter the sanctuary and immediately feel as if a great weight has been lifted off your shoulders. You feel safe here.
  466. showInfoDialog(h,114,soundBase::GETPROTECTION);
  467. }
  468. break;
  469. case Obj::TAVERN:
  470. {
  471. openWindow(OpenWindow::TAVERN_WINDOW,h->id.getNum(),id.getNum());
  472. }
  473. break;
  474. }
  475. }
  476. ui8 CGObjectInstance::getPassableness() const
  477. {
  478. return 0;
  479. }
  480. int3 CGObjectInstance::visitablePos() const
  481. {
  482. return pos - getVisitableOffset();
  483. }
  484. bool CGObjectInstance::isVisitable() const
  485. {
  486. for(int g=0; g<ARRAY_COUNT(defInfo->visitMap); ++g)
  487. {
  488. if(defInfo->visitMap[g] != 0)
  489. {
  490. return true;
  491. }
  492. }
  493. return false;
  494. }
  495. bool CGObjectInstance::passableFor(PlayerColor color) const
  496. {
  497. return getPassableness() & 1<<color.getNum();
  498. }
  499. static int lowestSpeed(const CGHeroInstance * chi)
  500. {
  501. if(!chi->Slots().size())
  502. {
  503. logGlobal->errorStream() << "Error! Hero " << chi->id.getNum() << " ("<<chi->name<<") has no army!";
  504. return 20;
  505. }
  506. auto i = chi->Slots().begin();
  507. //TODO? should speed modifiers (eg from artifacts) affect hero movement?
  508. int ret = (i++)->second->valOfBonuses(Bonus::STACKS_SPEED);
  509. for (;i!=chi->Slots().end();i++)
  510. {
  511. ret = std::min(ret, i->second->valOfBonuses(Bonus::STACKS_SPEED));
  512. }
  513. return ret;
  514. }
  515. ui32 CGHeroInstance::getTileCost(const TerrainTile &dest, const TerrainTile &from) const
  516. {
  517. //base move cost
  518. unsigned ret = 100;
  519. //if there is road both on dest and src tiles - use road movement cost
  520. if(dest.roadType != ERoadType::NO_ROAD && from.roadType != ERoadType::NO_ROAD)
  521. {
  522. int road = std::min(dest.roadType,from.roadType); //used road ID
  523. switch(road)
  524. {
  525. case ERoadType::DIRT_ROAD:
  526. ret = 75;
  527. break;
  528. case ERoadType::GRAVEL_ROAD:
  529. ret = 65;
  530. break;
  531. case ERoadType::COBBLESTONE_ROAD:
  532. ret = 50;
  533. break;
  534. default:
  535. logGlobal->errorStream() << "Unknown road type: " << road << "... Something wrong!";
  536. break;
  537. }
  538. }
  539. else
  540. {
  541. //FIXME: in H3 presence of Nomad in army will remove terrain penalty for sand. Bonus not implemented in VCMI
  542. // NOTE: in H3 neutral stacks will ignore terrain penalty only if placed as topmost stack(s) in hero army.
  543. // This is clearly bug in H3 however intended behaviour is not clear.
  544. // Current VCMI behaviour will ignore neutrals in calculations so army in VCMI
  545. // will always have best penalty without any influence from player-defined stacks order
  546. bool nativeArmy = true;
  547. for(auto stack : stacks)
  548. {
  549. int nativeTerrain = VLC->townh->factions[stack.second->type->faction]->nativeTerrain;
  550. if (nativeTerrain != -1 && nativeTerrain != from.terType)
  551. {
  552. nativeArmy = false;
  553. break;
  554. }
  555. }
  556. if (!nativeArmy)
  557. ret = VLC->heroh->terrCosts[from.terType];
  558. }
  559. return ret;
  560. }
  561. int3 CGHeroInstance::convertPosition(int3 src, bool toh3m) //toh3m=true: manifest->h3m; toh3m=false: h3m->manifest
  562. {
  563. if (toh3m)
  564. {
  565. src.x+=1;
  566. return src;
  567. }
  568. else
  569. {
  570. src.x-=1;
  571. return src;
  572. }
  573. }
  574. int3 CGHeroInstance::getPosition(bool h3m) const //h3m=true - returns position of hero object; h3m=false - returns position of hero 'manifestation'
  575. {
  576. if (h3m)
  577. {
  578. return pos;
  579. }
  580. else
  581. {
  582. return convertPosition(pos,false);
  583. }
  584. }
  585. bool CGHeroInstance::canWalkOnSea() const
  586. {
  587. return hasBonusOfType(Bonus::FLYING_MOVEMENT) || hasBonusOfType(Bonus::WATER_WALKING);
  588. }
  589. ui8 CGHeroInstance::getSecSkillLevel(SecondarySkill skill) const
  590. {
  591. for(auto & elem : secSkills)
  592. if(elem.first == skill)
  593. return elem.second;
  594. return 0;
  595. }
  596. void CGHeroInstance::setSecSkillLevel(SecondarySkill which, int val, bool abs)
  597. {
  598. if(getSecSkillLevel(which) == 0)
  599. {
  600. secSkills.push_back(std::pair<SecondarySkill,ui8>(which, val));
  601. updateSkill(which, val);
  602. }
  603. else
  604. {
  605. for (auto & elem : secSkills)
  606. {
  607. if(elem.first == which)
  608. {
  609. if(abs)
  610. elem.second = val;
  611. else
  612. elem.second += val;
  613. if(elem.second > 3) //workaround to avoid crashes when same sec skill is given more than once
  614. {
  615. logGlobal->warnStream() << "Warning: Skill " << which << " increased over limit! Decreasing to Expert.";
  616. elem.second = 3;
  617. }
  618. updateSkill(which, elem.second); //when we know final value
  619. }
  620. }
  621. }
  622. }
  623. bool CGHeroInstance::canLearnSkill() const
  624. {
  625. return secSkills.size() < GameConstants::SKILL_PER_HERO;
  626. }
  627. int CGHeroInstance::maxMovePoints(bool onLand) const
  628. {
  629. int base;
  630. if(onLand)
  631. {
  632. // used function is f(x) = 66.6x + 1300, rounded to second digit, where x is lowest speed in army
  633. static const int baseSpeed = 1300; // base speed from creature with 0 speed
  634. int armySpeed = lowestSpeed(this) * 20 / 3;
  635. base = armySpeed * 10 + baseSpeed; // separate *10 is intentional to receive same rounding as in h3
  636. vstd::abetween(base, 1500, 2000); // base speed is limited by these values
  637. }
  638. else
  639. {
  640. base = 1500; //on water base movement is always 1500 (speed of army doesn't matter)
  641. }
  642. const Bonus::BonusType bt = onLand ? Bonus::LAND_MOVEMENT : Bonus::SEA_MOVEMENT;
  643. const int bonus = valOfBonuses(Bonus::MOVEMENT) + valOfBonuses(bt);
  644. const int subtype = onLand ? SecondarySkill::LOGISTICS : SecondarySkill::NAVIGATION;
  645. const double modifier = valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, subtype) / 100.0;
  646. return int(base* (1+modifier)) + bonus;
  647. }
  648. CGHeroInstance::CGHeroInstance()
  649. : IBoatGenerator(this)
  650. {
  651. setNodeType(HERO);
  652. ID = Obj::HERO;
  653. tacticFormationEnabled = inTownGarrison = false;
  654. mana = movement = portrait = level = -1;
  655. isStanding = true;
  656. moveDir = 4;
  657. exp = 0xffffffff;
  658. visitedTown = nullptr;
  659. type = nullptr;
  660. boat = nullptr;
  661. commander = nullptr;
  662. sex = 0xff;
  663. secSkills.push_back(std::make_pair(SecondarySkill::DEFAULT, -1));
  664. }
  665. void CGHeroInstance::initHero(HeroTypeID SUBID)
  666. {
  667. subID = SUBID.getNum();
  668. initHero();
  669. }
  670. void CGHeroInstance::initHero()
  671. {
  672. assert(validTypes(true));
  673. if(ID == Obj::HERO)
  674. initHeroDefInfo();
  675. if(!type)
  676. type = VLC->heroh->heroes[subID];
  677. if(!vstd::contains(spells, SpellID::PRESET)) //hero starts with a spell
  678. {
  679. for(auto spellID : type->spells)
  680. spells.insert(spellID);
  681. }
  682. else //remove placeholder
  683. spells -= SpellID::PRESET;
  684. if(!getArt(ArtifactPosition::MACH4) && !getArt(ArtifactPosition::SPELLBOOK) && type->haveSpellBook) //no catapult means we haven't read pre-existent set -> use default rules for spellbook
  685. putArtifact(ArtifactPosition::SPELLBOOK, CArtifactInstance::createNewArtifactInstance(0));
  686. if(!getArt(ArtifactPosition::MACH4))
  687. putArtifact(ArtifactPosition::MACH4, CArtifactInstance::createNewArtifactInstance(3)); //everyone has a catapult
  688. if(portrait < 0 || portrait == 255)
  689. portrait = type->imageIndex;
  690. if(!hasBonus(Selector::sourceType(Bonus::HERO_BASE_SKILL)))
  691. {
  692. for(int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  693. {
  694. pushPrimSkill(static_cast<PrimarySkill::PrimarySkill>(g), type->heroClass->primarySkillInitial[g]);
  695. }
  696. }
  697. if(secSkills.size() == 1 && secSkills[0] == std::pair<SecondarySkill,ui8>(SecondarySkill::DEFAULT, -1)) //set secondary skills to default
  698. secSkills = type->secSkillsInit;
  699. if (!name.length())
  700. name = type->name;
  701. if (sex == 0xFF)//sex is default
  702. sex = type->sex;
  703. setFormation(false);
  704. if (!stacksCount()) //standard army//initial army
  705. {
  706. initArmy();
  707. }
  708. assert(validTypes());
  709. if (exp == 0xffffffff)
  710. {
  711. initExp();
  712. }
  713. else if (ID != Obj::PRISON)
  714. {
  715. level = VLC->heroh->level(exp);
  716. }
  717. else //warp hero at the beginning of next turn
  718. {
  719. level = 1;
  720. }
  721. if (VLC->modh->modules.COMMANDERS && !commander)
  722. {
  723. commander = new CCommanderInstance (VLC->townh->factions[type->heroClass->faction]->commander);
  724. commander->setArmyObj (castToArmyObj()); //TODO: separate function for setting commanders
  725. commander->giveStackExp (exp); //after our exp is set
  726. }
  727. hoverName = VLC->generaltexth->allTexts[15];
  728. boost::algorithm::replace_first(hoverName,"%s",name);
  729. boost::algorithm::replace_first(hoverName,"%s", type->heroClass->name);
  730. if (mana < 0)
  731. mana = manaLimit();
  732. }
  733. void CGHeroInstance::initArmy(IArmyDescriptor *dst /*= nullptr*/)
  734. {
  735. if(!dst)
  736. dst = this;
  737. int howManyStacks = 0; //how many stacks will hero receives <1 - 3>
  738. int pom = ran()%100;
  739. int warMachinesGiven = 0;
  740. if(pom < 9)
  741. howManyStacks = 1;
  742. else if(pom < 79)
  743. howManyStacks = 2;
  744. else
  745. howManyStacks = 3;
  746. vstd::amin(howManyStacks, type->initialArmy.size());
  747. for(int stackNo=0; stackNo < howManyStacks; stackNo++)
  748. {
  749. auto & stack = type->initialArmy[stackNo];
  750. int range = stack.maxAmount - stack.minAmount;
  751. int count = ran()%(range+1) + stack.minAmount;
  752. if(stack.creature >= CreatureID::CATAPULT &&
  753. stack.creature <= CreatureID::ARROW_TOWERS) //war machine
  754. {
  755. warMachinesGiven++;
  756. if(dst != this)
  757. continue;
  758. int slot = -1;
  759. ArtifactID aid = ArtifactID::NONE;
  760. switch (stack.creature)
  761. {
  762. case CreatureID::CATAPULT:
  763. slot = ArtifactPosition::MACH4;
  764. aid = ArtifactID::CATAPULT;
  765. break;
  766. default:
  767. aid = CArtHandler::creatureToMachineID(stack.creature);
  768. slot = 9 + aid;
  769. break;
  770. }
  771. auto convSlot = ArtifactPosition(slot);
  772. if(!getArt(convSlot))
  773. putArtifact(convSlot, CArtifactInstance::createNewArtifactInstance(aid));
  774. else
  775. logGlobal->warnStream() << "Hero " << name << " already has artifact at " << slot << ", omitting giving " << aid;
  776. }
  777. else
  778. dst->setCreature(SlotID(stackNo-warMachinesGiven), stack.creature, count);
  779. }
  780. }
  781. void CGHeroInstance::initHeroDefInfo()
  782. {
  783. if(!defInfo || defInfo->id != Obj::HERO)
  784. {
  785. defInfo = new CGDefInfo();
  786. defInfo->id = Obj::HERO;
  787. defInfo->subid = subID;
  788. defInfo->printPriority = 0;
  789. defInfo->visitDir = 0xff;
  790. }
  791. for(int i=0;i<6;i++)
  792. {
  793. defInfo->blockMap[i] = 255;
  794. defInfo->visitMap[i] = 0;
  795. defInfo->coverageMap[i] = 0;
  796. defInfo->shadowCoverage[i] = 0;
  797. }
  798. defInfo->blockMap[5] = 253;
  799. defInfo->visitMap[5] = 2;
  800. defInfo->coverageMap[4] = defInfo->coverageMap[5] = 224;
  801. }
  802. CGHeroInstance::~CGHeroInstance()
  803. {
  804. commander.dellNull();
  805. }
  806. bool CGHeroInstance::needsLastStack() const
  807. {
  808. return true;
  809. }
  810. void CGHeroInstance::onHeroVisit(const CGHeroInstance * h) const
  811. {
  812. if(h == this) return; //exclude potential self-visiting
  813. if (ID == Obj::HERO)
  814. {
  815. if( cb->gameState()->getPlayerRelations(tempOwner, h->tempOwner)) //our or ally hero
  816. {
  817. //exchange
  818. cb->heroExchange(h->id, id);
  819. }
  820. else //battle
  821. {
  822. if(visitedTown) //we're in town
  823. visitedTown->onHeroVisit(h); //town will handle attacking
  824. else
  825. cb->startBattleI(h, this);
  826. }
  827. }
  828. else if(ID == Obj::PRISON)
  829. {
  830. int txt_id;
  831. if(cb->getHeroCount(h->tempOwner,false) < GameConstants::MAX_HEROES_PER_PLAYER) //free hero slot
  832. {
  833. cb->changeObjPos(id,pos+int3(1,0,0),0);
  834. //update hero parameters
  835. SetMovePoints smp;
  836. smp.hid = id;
  837. smp.val = maxMovePoints (true); //TODO: hota prison on water?
  838. cb->setMovePoints (&smp);
  839. cb->setManaPoints (id, manaLimit());
  840. cb->setObjProperty(id, ObjProperty::ID, Obj::HERO); //set ID to 34
  841. cb->giveHero(id,h->tempOwner); //recreates def and adds hero to player
  842. txt_id = 102;
  843. }
  844. else //already 8 wandering heroes
  845. {
  846. txt_id = 103;
  847. }
  848. showInfoDialog(h,txt_id,soundBase::ROGUE);
  849. }
  850. }
  851. const std::string & CGHeroInstance::getBiography() const
  852. {
  853. if (biography.length())
  854. return biography;
  855. return type->biography;
  856. }
  857. void CGHeroInstance::initObj() //TODO: use bonus system
  858. {
  859. blockVisit = true;
  860. auto hs = new HeroSpecial();
  861. hs->setNodeType(CBonusSystemNode::specialty);
  862. attachTo(hs); //do we ever need to detach it?
  863. if(!type)
  864. initHero(); //TODO: set up everything for prison before specialties are configured
  865. for(const auto &spec : type->spec) //TODO: unfity with bonus system
  866. {
  867. auto bonus = new Bonus();
  868. bonus->val = spec.val;
  869. bonus->sid = id.getNum(); //from the hero, specialty has no unique id
  870. bonus->duration = Bonus::PERMANENT;
  871. bonus->source = Bonus::HERO_SPECIAL;
  872. switch (spec.type)
  873. {
  874. case 1:// creature specialty
  875. {
  876. hs->growsWithLevel = true;
  877. const CCreature &specCreature = *VLC->creh->creatures[spec.additionalinfo]; //creature in which we have specialty
  878. int creLevel = specCreature.level;
  879. if(!creLevel)
  880. {
  881. if(spec.additionalinfo == 146)
  882. creLevel = 5; //treat ballista as 5-level
  883. else
  884. {
  885. logGlobal->warnStream() << "Warning: unknown level of " << specCreature.namePl;
  886. continue;
  887. }
  888. }
  889. //bonus->additionalInfo = spec.additionalinfo; //creature id, should not be used again - this works only with limiter
  890. bonus->limiter.reset(new CCreatureTypeLimiter (specCreature, true)); //with upgrades
  891. bonus->type = Bonus::PRIMARY_SKILL;
  892. bonus->valType = Bonus::ADDITIVE_VALUE;
  893. bonus->subtype = PrimarySkill::ATTACK;
  894. hs->addNewBonus(bonus);
  895. bonus = new Bonus(*bonus);
  896. bonus->subtype = PrimarySkill::DEFENSE;
  897. hs->addNewBonus(bonus);
  898. //values will be calculated later
  899. bonus = new Bonus(*bonus);
  900. bonus->type = Bonus::STACKS_SPEED;
  901. bonus->val = 1; //+1 speed
  902. hs->addNewBonus(bonus);
  903. }
  904. break;
  905. case 2://secondary skill
  906. hs->growsWithLevel = true;
  907. bonus->type = Bonus::SPECIAL_SECONDARY_SKILL; //needs to be recalculated with level, based on this value
  908. bonus->valType = Bonus::BASE_NUMBER; // to receive nonzero value
  909. bonus->subtype = spec.subtype; //skill id
  910. bonus->val = spec.val; //value per level, in percent
  911. hs->addNewBonus(bonus);
  912. bonus = new Bonus(*bonus);
  913. switch (spec.additionalinfo)
  914. {
  915. case 0: //normal
  916. bonus->valType = Bonus::PERCENT_TO_BASE;
  917. break;
  918. case 1: //when it's navigation or there's no 'base' at all
  919. bonus->valType = Bonus::PERCENT_TO_ALL;
  920. break;
  921. }
  922. bonus->type = Bonus::SECONDARY_SKILL_PREMY; //value will be calculated later
  923. hs->addNewBonus(bonus);
  924. break;
  925. case 3://spell damage bonus, level dependent but calculated elsewhere
  926. bonus->type = Bonus::SPECIAL_SPELL_LEV;
  927. bonus->subtype = spec.subtype;
  928. hs->addNewBonus(bonus);
  929. break;
  930. case 4://creature stat boost
  931. switch (spec.subtype)
  932. {
  933. case 1://attack
  934. bonus->type = Bonus::PRIMARY_SKILL;
  935. bonus->subtype = PrimarySkill::ATTACK;
  936. break;
  937. case 2://defense
  938. bonus->type = Bonus::PRIMARY_SKILL;
  939. bonus->subtype = PrimarySkill::DEFENSE;
  940. break;
  941. case 3:
  942. bonus->type = Bonus::CREATURE_DAMAGE;
  943. bonus->subtype = 0; //both min and max
  944. break;
  945. case 4://hp
  946. bonus->type = Bonus::STACK_HEALTH;
  947. break;
  948. case 5:
  949. bonus->type = Bonus::STACKS_SPEED;
  950. break;
  951. default:
  952. continue;
  953. }
  954. bonus->additionalInfo = spec.additionalinfo; //creature id
  955. bonus->valType = Bonus::ADDITIVE_VALUE;
  956. bonus->limiter.reset(new CCreatureTypeLimiter (*VLC->creh->creatures[spec.additionalinfo], true));
  957. hs->addNewBonus(bonus);
  958. break;
  959. case 5://spell damage bonus in percent
  960. bonus->type = Bonus::SPECIFIC_SPELL_DAMAGE;
  961. bonus->valType = Bonus::BASE_NUMBER; // current spell system is screwed
  962. bonus->subtype = spec.subtype; //spell id
  963. hs->addNewBonus(bonus);
  964. break;
  965. case 6://damage bonus for bless (Adela)
  966. bonus->type = Bonus::SPECIAL_BLESS_DAMAGE;
  967. bonus->subtype = spec.subtype; //spell id if you ever wanted to use it otherwise
  968. bonus->additionalInfo = spec.additionalinfo; //damage factor
  969. hs->addNewBonus(bonus);
  970. break;
  971. case 7://maxed mastery for spell
  972. bonus->type = Bonus::MAXED_SPELL;
  973. bonus->subtype = spec.subtype; //spell i
  974. hs->addNewBonus(bonus);
  975. break;
  976. case 8://peculiar spells - enchantments
  977. bonus->type = Bonus::SPECIAL_PECULIAR_ENCHANT;
  978. bonus->subtype = spec.subtype; //spell id
  979. bonus->additionalInfo = spec.additionalinfo;//0, 1 for Coronius
  980. hs->addNewBonus(bonus);
  981. break;
  982. case 9://upgrade creatures
  983. {
  984. const auto &creatures = VLC->creh->creatures;
  985. bonus->type = Bonus::SPECIAL_UPGRADE;
  986. bonus->subtype = spec.subtype; //base id
  987. bonus->additionalInfo = spec.additionalinfo; //target id
  988. hs->addNewBonus(bonus);
  989. bonus = new Bonus(*bonus);
  990. for(auto cre_id : creatures[spec.subtype]->upgrades)
  991. {
  992. bonus->subtype = cre_id; //propagate for regular upgrades of base creature
  993. hs->addNewBonus(bonus);
  994. bonus = new Bonus(*bonus);
  995. }
  996. vstd::clear_pointer(bonus);
  997. break;
  998. }
  999. case 10://resource generation
  1000. bonus->type = Bonus::GENERATE_RESOURCE;
  1001. bonus->subtype = spec.subtype;
  1002. hs->addNewBonus(bonus);
  1003. break;
  1004. case 11://starting skill with mastery (Adrienne)
  1005. cb->changeSecSkill(this, SecondarySkill(spec.val), spec.additionalinfo); //simply give it and forget
  1006. break;
  1007. case 12://army speed
  1008. bonus->type = Bonus::STACKS_SPEED;
  1009. hs->addNewBonus(bonus);
  1010. break;
  1011. case 13://Dragon bonuses (Mutare)
  1012. bonus->type = Bonus::PRIMARY_SKILL;
  1013. bonus->valType = Bonus::ADDITIVE_VALUE;
  1014. switch (spec.subtype)
  1015. {
  1016. case 1:
  1017. bonus->subtype = PrimarySkill::ATTACK;
  1018. break;
  1019. case 2:
  1020. bonus->subtype = PrimarySkill::DEFENSE;
  1021. break;
  1022. }
  1023. bonus->limiter.reset(new HasAnotherBonusLimiter(Bonus::DRAGON_NATURE));
  1024. hs->addNewBonus(bonus);
  1025. break;
  1026. default:
  1027. logGlobal->warnStream() << "Unexpected hero specialty " << type;
  1028. }
  1029. }
  1030. specialty.push_back(hs); //will it work?
  1031. for (auto hs2 : type->specialty) //copy active (probably growing) bonuses from hero prootype to hero object
  1032. {
  1033. auto hs = new HeroSpecial();
  1034. attachTo(hs); //do we ever need to detach it?
  1035. hs->setNodeType(CBonusSystemNode::specialty);
  1036. for (auto bonus : hs2.bonuses)
  1037. {
  1038. hs->addNewBonus (bonus);
  1039. }
  1040. hs->growsWithLevel = hs2.growsWithLevel;
  1041. specialty.push_back(hs); //will it work?
  1042. }
  1043. //initialize bonuses
  1044. for(auto skill_info : secSkills)
  1045. updateSkill(SecondarySkill(skill_info.first), skill_info.second);
  1046. Updatespecialty();
  1047. mana = manaLimit(); //after all bonuses are taken into account, make sure this line is the last one
  1048. type->name = name;
  1049. }
  1050. void CGHeroInstance::Updatespecialty() //TODO: calculate special value of bonuses on-the-fly?
  1051. {
  1052. for (auto hs : specialty)
  1053. {
  1054. if (hs->growsWithLevel)
  1055. {
  1056. //const auto &creatures = VLC->creh->creatures;
  1057. for(Bonus * b : hs->getBonusList())
  1058. {
  1059. switch (b->type)
  1060. {
  1061. case Bonus::SECONDARY_SKILL_PREMY:
  1062. b->val = (hs->valOfBonuses(Bonus::SPECIAL_SECONDARY_SKILL, b->subtype) * level);
  1063. break; //use only hero skills as bonuses to avoid feedback loop
  1064. case Bonus::PRIMARY_SKILL: //for creatures, that is
  1065. {
  1066. const CCreature * cre = nullptr;
  1067. int creLevel = 0;
  1068. if (auto creatureLimiter = std::dynamic_pointer_cast<CCreatureTypeLimiter>(b->limiter)) //TODO: more general eveluation of bonuses?
  1069. {
  1070. cre = creatureLimiter->creature;
  1071. creLevel = cre->level;
  1072. if (!creLevel)
  1073. {
  1074. creLevel = 5; //treat ballista as tier 5
  1075. }
  1076. }
  1077. else //no creature found, can't calculate value
  1078. {
  1079. logGlobal->warnStream() << "Primary skill specialty growth supported only with creature type limiters";
  1080. break;
  1081. }
  1082. double primSkillModifier = (int)(level / creLevel) / 20.0;
  1083. int param;
  1084. switch (b->subtype)
  1085. {
  1086. case PrimarySkill::ATTACK:
  1087. param = cre->Attack();
  1088. break;
  1089. case PrimarySkill::DEFENSE:
  1090. param = cre->Defense();
  1091. break;
  1092. default:
  1093. continue;
  1094. }
  1095. b->val = ceil(param * (1 + primSkillModifier)) - param; //yep, overcomplicated but matches original
  1096. break;
  1097. }
  1098. }
  1099. }
  1100. }
  1101. }
  1102. }
  1103. void CGHeroInstance::updateSkill(SecondarySkill which, int val)
  1104. {
  1105. if(which == SecondarySkill::LEADERSHIP || which == SecondarySkill::LUCK)
  1106. { //luck-> VLC->generaltexth->arraytxt[73+luckSkill]; VLC->generaltexth->arraytxt[104+moraleSkill]
  1107. bool luck = which == SecondarySkill::LUCK;
  1108. Bonus::BonusType type[] = {Bonus::MORALE, Bonus::LUCK};
  1109. Bonus *b = getBonusLocalFirst(Selector::type(type[luck]).And(Selector::sourceType(Bonus::SECONDARY_SKILL)));
  1110. if(!b)
  1111. {
  1112. b = new Bonus(Bonus::PERMANENT, type[luck], Bonus::SECONDARY_SKILL, +val, which, which, Bonus::BASE_NUMBER);
  1113. addNewBonus(b);
  1114. }
  1115. else
  1116. b->val = +val;
  1117. }
  1118. else if(which == SecondarySkill::DIPLOMACY) //surrender discount: 20% per level
  1119. {
  1120. if(Bonus *b = getBonusLocalFirst(Selector::type(Bonus::SURRENDER_DISCOUNT).And(Selector::sourceType(Bonus::SECONDARY_SKILL))))
  1121. b->val = +val;
  1122. else
  1123. addNewBonus(new Bonus(Bonus::PERMANENT, Bonus::SURRENDER_DISCOUNT, Bonus::SECONDARY_SKILL, val * 20, which));
  1124. }
  1125. int skillVal = 0;
  1126. switch (which)
  1127. {
  1128. case SecondarySkill::ARCHERY:
  1129. switch (val)
  1130. {
  1131. case 1:
  1132. skillVal = 10; break;
  1133. case 2:
  1134. skillVal = 25; break;
  1135. case 3:
  1136. skillVal = 50; break;
  1137. }
  1138. break;
  1139. case SecondarySkill::LOGISTICS:
  1140. skillVal = 10 * val; break;
  1141. case SecondarySkill::NAVIGATION:
  1142. skillVal = 50 * val; break;
  1143. case SecondarySkill::MYSTICISM:
  1144. skillVal = val; break;
  1145. case SecondarySkill::EAGLE_EYE:
  1146. skillVal = 30 + 10 * val; break;
  1147. case SecondarySkill::NECROMANCY:
  1148. skillVal = 10 * val; break;
  1149. case SecondarySkill::LEARNING:
  1150. skillVal = 5 * val; break;
  1151. case SecondarySkill::OFFENCE:
  1152. skillVal = 10 * val; break;
  1153. case SecondarySkill::ARMORER:
  1154. skillVal = 5 * val; break;
  1155. case SecondarySkill::INTELLIGENCE:
  1156. skillVal = 25 << (val-1); break;
  1157. case SecondarySkill::SORCERY:
  1158. skillVal = 5 * val; break;
  1159. case SecondarySkill::RESISTANCE:
  1160. skillVal = 5 << (val-1); break;
  1161. case SecondarySkill::FIRST_AID:
  1162. skillVal = 25 + 25*val; break;
  1163. case SecondarySkill::ESTATES:
  1164. skillVal = 125 << (val-1); break;
  1165. }
  1166. Bonus::ValueType skillValType = skillVal ? Bonus::BASE_NUMBER : Bonus::INDEPENDENT_MIN;
  1167. if(Bonus * b = getBonusList().getFirst(Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, which)
  1168. .And(Selector::sourceType(Bonus::SECONDARY_SKILL)))) //only local hero bonus
  1169. {
  1170. b->val = skillVal;
  1171. b->valType = skillValType;
  1172. }
  1173. else
  1174. {
  1175. auto bonus = new Bonus(Bonus::PERMANENT, Bonus::SECONDARY_SKILL_PREMY, Bonus::SECONDARY_SKILL, skillVal, id.getNum(), which, skillValType);
  1176. bonus->source = Bonus::SECONDARY_SKILL;
  1177. addNewBonus(bonus);
  1178. }
  1179. }
  1180. void CGHeroInstance::setPropertyDer( ui8 what, ui32 val )
  1181. {
  1182. if(what == ObjProperty::PRIMARY_STACK_COUNT)
  1183. setStackCount(SlotID(0), val);
  1184. }
  1185. double CGHeroInstance::getHeroStrength() const
  1186. {
  1187. return sqrt((1.0 + 0.05*getPrimSkillLevel(PrimarySkill::ATTACK)) * (1.0 + 0.05*getPrimSkillLevel(PrimarySkill::DEFENSE)));
  1188. }
  1189. ui64 CGHeroInstance::getTotalStrength() const
  1190. {
  1191. double ret = getHeroStrength() * getArmyStrength();
  1192. return (ui64) ret;
  1193. }
  1194. TExpType CGHeroInstance::calculateXp(TExpType exp) const
  1195. {
  1196. return exp * (100 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::LEARNING))/100.0;
  1197. }
  1198. ui8 CGHeroInstance::getSpellSchoolLevel(const CSpell * spell, int *outSelectedSchool) const
  1199. {
  1200. si16 skill = -1; //skill level
  1201. #define TRY_SCHOOL(schoolName, schoolMechanicsId, schoolOutId) \
  1202. if(spell-> schoolName) \
  1203. { \
  1204. int thisSchool = std::max<int>(getSecSkillLevel( \
  1205. SecondarySkill(14 + (schoolMechanicsId))), \
  1206. valOfBonuses(Bonus::MAGIC_SCHOOL_SKILL, 1 << (schoolMechanicsId))); \
  1207. if(thisSchool > skill) \
  1208. { \
  1209. skill = thisSchool; \
  1210. if(outSelectedSchool) \
  1211. *outSelectedSchool = schoolOutId; \
  1212. } \
  1213. }
  1214. TRY_SCHOOL(fire, 0, 1)
  1215. TRY_SCHOOL(air, 1, 0)
  1216. TRY_SCHOOL(water, 2, 2)
  1217. TRY_SCHOOL(earth, 3, 3)
  1218. #undef TRY_SCHOOL
  1219. vstd::amax(skill, valOfBonuses(Bonus::MAGIC_SCHOOL_SKILL, 0)); //any school bonus
  1220. vstd::amax(skill, valOfBonuses(Bonus::SPELL, spell->id.toEnum())); //given by artifact or other effect
  1221. if (hasBonusOfType(Bonus::MAXED_SPELL, spell->id))//hero specialty (Daremyth, Melodia)
  1222. skill = 3;
  1223. assert(skill >= 0 && skill <= 3);
  1224. return skill;
  1225. }
  1226. bool CGHeroInstance::canCastThisSpell(const CSpell * spell) const
  1227. {
  1228. if(!getArt(ArtifactPosition::SPELLBOOK)) //if hero has no spellbook
  1229. return false;
  1230. if(vstd::contains(spells, spell->id) //hero has this spell in spellbook
  1231. || (spell->air && hasBonusOfType(Bonus::AIR_SPELLS)) // this is air spell and hero can cast all air spells
  1232. || (spell->fire && hasBonusOfType(Bonus::FIRE_SPELLS)) // this is fire spell and hero can cast all fire spells
  1233. || (spell->water && hasBonusOfType(Bonus::WATER_SPELLS)) // this is water spell and hero can cast all water spells
  1234. || (spell->earth && hasBonusOfType(Bonus::EARTH_SPELLS)) // this is earth spell and hero can cast all earth spells
  1235. || hasBonusOfType(Bonus::SPELL, spell->id)
  1236. || hasBonusOfType(Bonus::SPELLS_OF_LEVEL, spell->level)
  1237. )
  1238. return true;
  1239. return false;
  1240. }
  1241. /**
  1242. * Calculates what creatures and how many to be raised from a battle.
  1243. * @param battleResult The results of the battle.
  1244. * @return Returns a pair with the first value indicating the ID of the creature
  1245. * type and second value the amount. Both values are returned as -1 if necromancy
  1246. * could not be applied.
  1247. */
  1248. CStackBasicDescriptor CGHeroInstance::calculateNecromancy (const BattleResult &battleResult) const
  1249. {
  1250. const ui8 necromancyLevel = getSecSkillLevel(SecondarySkill::NECROMANCY);
  1251. // Hero knows necromancy or has Necromancer Cloak
  1252. if (necromancyLevel > 0 || hasBonusOfType(Bonus::IMPROVED_NECROMANCY))
  1253. {
  1254. double necromancySkill = valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::NECROMANCY)/100.0;
  1255. vstd::amin(necromancySkill, 1.0); //it's impossible to raise more creatures than all...
  1256. const std::map<ui32,si32> &casualties = battleResult.casualties[!battleResult.winner];
  1257. ui32 raisedUnits = 0;
  1258. // Figure out what to raise and how many.
  1259. const CreatureID creatureTypes[] = {CreatureID::SKELETON, CreatureID::WALKING_DEAD, CreatureID::WIGHTS, CreatureID::LICHES};
  1260. const bool improvedNecromancy = hasBonusOfType(Bonus::IMPROVED_NECROMANCY);
  1261. const CCreature *raisedUnitType = VLC->creh->creatures[creatureTypes[improvedNecromancy ? necromancyLevel : 0]];
  1262. const ui32 raisedUnitHP = raisedUnitType->valOfBonuses(Bonus::STACK_HEALTH);
  1263. //calculate creatures raised from each defeated stack
  1264. for (auto & casualtie : casualties)
  1265. {
  1266. // Get lost enemy hit points convertible to units.
  1267. CCreature * c = VLC->creh->creatures[casualtie.first];
  1268. const ui32 raisedHP = c->valOfBonuses(Bonus::STACK_HEALTH) * casualtie.second * necromancySkill;
  1269. raisedUnits += std::min<ui32>(raisedHP / raisedUnitHP, casualtie.second * necromancySkill); //limit to % of HP and % of original stack count
  1270. }
  1271. // Make room for new units.
  1272. SlotID slot = getSlotFor(raisedUnitType->idNumber);
  1273. if (slot == SlotID())
  1274. {
  1275. // If there's no room for unit, try it's upgraded version 2/3rds the size.
  1276. raisedUnitType = VLC->creh->creatures[*raisedUnitType->upgrades.begin()];
  1277. raisedUnits = (raisedUnits*2)/3;
  1278. slot = getSlotFor(raisedUnitType->idNumber);
  1279. }
  1280. if (raisedUnits <= 0)
  1281. raisedUnits = 1;
  1282. return CStackBasicDescriptor(raisedUnitType->idNumber, raisedUnits);
  1283. }
  1284. return CStackBasicDescriptor();
  1285. }
  1286. /**
  1287. * Show the necromancy dialog with information about units raised.
  1288. * @param raisedStack Pair where the first element represents ID of the raised creature
  1289. * and the second element the amount.
  1290. */
  1291. void CGHeroInstance::showNecromancyDialog(const CStackBasicDescriptor &raisedStack) const
  1292. {
  1293. InfoWindow iw;
  1294. iw.soundID = soundBase::pickup01 + ran() % 7;
  1295. iw.player = tempOwner;
  1296. iw.components.push_back(Component(raisedStack));
  1297. if (raisedStack.count > 1) // Practicing the dark arts of necromancy, ... (plural)
  1298. {
  1299. iw.text.addTxt(MetaString::GENERAL_TXT, 145);
  1300. iw.text.addReplacement(raisedStack.count);
  1301. }
  1302. else // Practicing the dark arts of necromancy, ... (singular)
  1303. {
  1304. iw.text.addTxt(MetaString::GENERAL_TXT, 146);
  1305. }
  1306. iw.text.addReplacement(raisedStack);
  1307. cb->showInfoDialog(&iw);
  1308. }
  1309. int3 CGHeroInstance::getSightCenter() const
  1310. {
  1311. return getPosition(false);
  1312. }
  1313. int CGHeroInstance::getSightRadious() const
  1314. {
  1315. return 5 + getSecSkillLevel(SecondarySkill::SCOUTING) + valOfBonuses(Bonus::SIGHT_RADIOUS); //default + scouting
  1316. }
  1317. si32 CGHeroInstance::manaRegain() const
  1318. {
  1319. if (hasBonusOfType(Bonus::FULL_MANA_REGENERATION))
  1320. return manaLimit();
  1321. return 1 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 8) + valOfBonuses(Bonus::MANA_REGENERATION); //1 + Mysticism level
  1322. }
  1323. // /**
  1324. // * Places an artifact in hero's backpack. If it's a big artifact equips it
  1325. // * or discards it if it cannot be equipped.
  1326. // */
  1327. // void CGHeroInstance::giveArtifact (ui32 aid) //use only for fixed artifacts
  1328. // {
  1329. // CArtifact * const artifact = VLC->arth->artifacts[aid]; //pointer to constant object
  1330. // CArtifactInstance *ai = CArtifactInstance::createNewArtifactInstance(artifact);
  1331. // ai->putAt(this, ai->firstAvailableSlot(this));
  1332. // }
  1333. int CGHeroInstance::getBoatType() const
  1334. {
  1335. switch(type->heroClass->getAlignment())
  1336. {
  1337. case EAlignment::GOOD:
  1338. return 1;
  1339. case EAlignment::EVIL:
  1340. return 0;
  1341. case EAlignment::NEUTRAL:
  1342. return 2;
  1343. default:
  1344. throw std::runtime_error("Wrong alignment!");
  1345. }
  1346. }
  1347. void CGHeroInstance::getOutOffsets(std::vector<int3> &offsets) const
  1348. {
  1349. static int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0), int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  1350. for (auto & dir : dirs)
  1351. offsets += dir;
  1352. }
  1353. int CGHeroInstance::getSpellCost(const CSpell *sp) const
  1354. {
  1355. return sp->costs[getSpellSchoolLevel(sp)];
  1356. }
  1357. void CGHeroInstance::pushPrimSkill( PrimarySkill::PrimarySkill which, int val )
  1358. {
  1359. assert(!hasBonus(Selector::typeSubtype(Bonus::PRIMARY_SKILL, which)
  1360. .And(Selector::sourceType(Bonus::HERO_BASE_SKILL))));
  1361. addNewBonus(new Bonus(Bonus::PERMANENT, Bonus::PRIMARY_SKILL, Bonus::HERO_BASE_SKILL, val, id.getNum(), which));
  1362. }
  1363. EAlignment::EAlignment CGHeroInstance::getAlignment() const
  1364. {
  1365. return type->heroClass->getAlignment();
  1366. }
  1367. void CGHeroInstance::initExp()
  1368. {
  1369. exp=40+ (ran()) % 50;
  1370. level = 1;
  1371. }
  1372. std::string CGHeroInstance::nodeName() const
  1373. {
  1374. return "Hero " + name;
  1375. }
  1376. void CGHeroInstance::putArtifact(ArtifactPosition pos, CArtifactInstance *art)
  1377. {
  1378. assert(!getArt(pos));
  1379. art->putAt(ArtifactLocation(this, pos));
  1380. }
  1381. void CGHeroInstance::putInBackpack(CArtifactInstance *art)
  1382. {
  1383. putArtifact(art->firstBackpackSlot(this), art);
  1384. }
  1385. bool CGHeroInstance::hasSpellbook() const
  1386. {
  1387. return getArt(ArtifactPosition::SPELLBOOK);
  1388. }
  1389. void CGHeroInstance::deserializationFix()
  1390. {
  1391. artDeserializationFix(this);
  1392. //for (auto hs : specialty)
  1393. //{
  1394. // attachTo (hs);
  1395. //}
  1396. }
  1397. CBonusSystemNode * CGHeroInstance::whereShouldBeAttached(CGameState *gs)
  1398. {
  1399. if(visitedTown)
  1400. {
  1401. if(inTownGarrison)
  1402. return visitedTown;
  1403. else
  1404. return &visitedTown->townAndVis;
  1405. }
  1406. else
  1407. return CArmedInstance::whereShouldBeAttached(gs);
  1408. }
  1409. int CGHeroInstance::movementPointsAfterEmbark(int MPsBefore, int basicCost, bool disembark /*= false*/) const
  1410. {
  1411. if(hasBonusOfType(Bonus::FREE_SHIP_BOARDING))
  1412. return (MPsBefore - basicCost) * static_cast<double>(maxMovePoints(disembark)) / maxMovePoints(!disembark);
  1413. return 0; //take all MPs otherwise
  1414. }
  1415. CGHeroInstance::ECanDig CGHeroInstance::diggingStatus() const
  1416. {
  1417. if(movement < maxMovePoints(true))
  1418. return LACK_OF_MOVEMENT;
  1419. else if(cb->getTile(getPosition(false))->terType == ETerrainType::WATER)
  1420. return WRONG_TERRAIN;
  1421. else
  1422. {
  1423. const TerrainTile *t = cb->getTile(getPosition());
  1424. //TODO look for hole
  1425. //CGI->mh->getTerrainDescr(h->getPosition(false), hlp, false);
  1426. if(/*hlp.length() || */t->blockingObjects.size() > 1)
  1427. return TILE_OCCUPIED;
  1428. else
  1429. return CAN_DIG;
  1430. }
  1431. }
  1432. ArtBearer::ArtBearer CGHeroInstance::bearerType() const
  1433. {
  1434. return ArtBearer::HERO;
  1435. }
  1436. std::vector<SecondarySkill> CGHeroInstance::levelUpProposedSkills() const
  1437. {
  1438. std::vector<SecondarySkill> skills;
  1439. //picking sec. skills for choice
  1440. std::set<SecondarySkill> basicAndAdv, expert, none;
  1441. for(int i=0;i<GameConstants::SKILL_QUANTITY;i++)
  1442. if (cb->isAllowed(2,i))
  1443. none.insert(SecondarySkill(i));
  1444. for(auto & elem : secSkills)
  1445. {
  1446. if(elem.second < 3)
  1447. basicAndAdv.insert(elem.first);
  1448. else
  1449. expert.insert(elem.first);
  1450. none.erase(elem.first);
  1451. }
  1452. //first offered skill
  1453. if(basicAndAdv.size())
  1454. {
  1455. SecondarySkill s = type->heroClass->chooseSecSkill(basicAndAdv);//upgrade existing
  1456. skills.push_back(s);
  1457. basicAndAdv.erase(s);
  1458. }
  1459. else if(none.size() && canLearnSkill())
  1460. {
  1461. skills.push_back(type->heroClass->chooseSecSkill(none)); //give new skill
  1462. none.erase(skills.back());
  1463. }
  1464. //second offered skill
  1465. if(none.size() && canLearnSkill()) //hero have free skill slot
  1466. {
  1467. skills.push_back(type->heroClass->chooseSecSkill(none)); //new skill
  1468. }
  1469. else if(basicAndAdv.size())
  1470. {
  1471. skills.push_back(type->heroClass->chooseSecSkill(basicAndAdv)); //upgrade existing
  1472. }
  1473. return skills;
  1474. }
  1475. bool CGHeroInstance::gainsLevel() const
  1476. {
  1477. return exp >= VLC->heroh->reqExp(level+1);
  1478. }
  1479. void CGDwelling::initObj()
  1480. {
  1481. switch(ID)
  1482. {
  1483. case Obj::CREATURE_GENERATOR1:
  1484. {
  1485. CreatureID crid = VLC->objh->cregens[subID];
  1486. const CCreature *crs = VLC->creh->creatures[crid];
  1487. creatures.resize(1);
  1488. creatures[0].second.push_back(crid);
  1489. if (subID >= VLC->generaltexth->creGens.size()) //very messy workaround
  1490. {
  1491. auto & dwellingNames = VLC->townh->factions[crs->faction]->town->dwellingNames;
  1492. assert (!dwellingNames.empty());
  1493. hoverName = dwellingNames[VLC->creh->creatures[subID]->level - 1];
  1494. }
  1495. else
  1496. hoverName = VLC->generaltexth->creGens[subID];
  1497. if(crs->level > 4)
  1498. putStack(SlotID(0), new CStackInstance(crs, (crs->growth) * 3));
  1499. if (getOwner() != PlayerColor::NEUTRAL)
  1500. cb->gameState()->players[getOwner()].dwellings.push_back (this);
  1501. }
  1502. break;
  1503. case Obj::CREATURE_GENERATOR4:
  1504. creatures.resize(4);
  1505. if(subID == 1) //Golem Factory
  1506. {
  1507. creatures[0].second.push_back(CreatureID::STONE_GOLEM);
  1508. creatures[1].second.push_back(CreatureID::IRON_GOLEM);
  1509. creatures[2].second.push_back(CreatureID::GOLD_GOLEM);
  1510. creatures[3].second.push_back(CreatureID::DIAMOND_GOLEM);
  1511. //guards
  1512. putStack(SlotID(0), new CStackInstance(CreatureID::GOLD_GOLEM, 9));
  1513. putStack(SlotID(1), new CStackInstance(CreatureID::DIAMOND_GOLEM, 6));
  1514. }
  1515. else if(subID == 0) // Elemental Conflux
  1516. {
  1517. creatures[0].second.push_back(CreatureID::AIR_ELEMENTAL);
  1518. creatures[1].second.push_back(CreatureID::FIRE_ELEMENTAL);
  1519. creatures[2].second.push_back(CreatureID::EARTH_ELEMENTAL);
  1520. creatures[3].second.push_back(CreatureID::WATER_ELEMENTAL);
  1521. //guards
  1522. putStack(SlotID(0), new CStackInstance(CreatureID::EARTH_ELEMENTAL, 12));
  1523. }
  1524. else
  1525. {
  1526. assert(0);
  1527. }
  1528. hoverName = VLC->generaltexth->creGens4[subID];
  1529. break;
  1530. case Obj::REFUGEE_CAMP:
  1531. //is handled within newturn func
  1532. break;
  1533. case Obj::WAR_MACHINE_FACTORY:
  1534. creatures.resize(3);
  1535. creatures[0].second.push_back(CreatureID::BALLISTA);
  1536. creatures[1].second.push_back(CreatureID::FIRST_AID_TENT);
  1537. creatures[2].second.push_back(CreatureID::AMMO_CART);
  1538. break;
  1539. default:
  1540. assert(0);
  1541. break;
  1542. }
  1543. }
  1544. void CGDwelling::setProperty(ui8 what, ui32 val)
  1545. {
  1546. switch (what)
  1547. {
  1548. case ObjProperty::OWNER: //change owner
  1549. if (ID == Obj::CREATURE_GENERATOR1) //single generators
  1550. {
  1551. if (tempOwner != PlayerColor::NEUTRAL)
  1552. {
  1553. std::vector<ConstTransitivePtr<CGDwelling> >* dwellings = &cb->gameState()->players[tempOwner].dwellings;
  1554. dwellings->erase (std::find(dwellings->begin(), dwellings->end(), this));
  1555. }
  1556. if (PlayerColor(val) != PlayerColor::NEUTRAL) //can new owner be neutral?
  1557. cb->gameState()->players[PlayerColor(val)].dwellings.push_back (this);
  1558. }
  1559. break;
  1560. case ObjProperty::AVAILABLE_CREATURE:
  1561. creatures.resize(1);
  1562. creatures[0].second.resize(1);
  1563. creatures[0].second[0] = CreatureID(val);
  1564. break;
  1565. }
  1566. CGObjectInstance::setProperty(what,val);
  1567. }
  1568. void CGDwelling::onHeroVisit( const CGHeroInstance * h ) const
  1569. {
  1570. if(ID == Obj::REFUGEE_CAMP && !creatures[0].first) //Refugee Camp, no available cres
  1571. {
  1572. InfoWindow iw;
  1573. iw.player = h->tempOwner;
  1574. iw.text.addTxt(MetaString::ADVOB_TXT, 44); //{%s} \n\n The camp is deserted. Perhaps you should try next week.
  1575. iw.text.addReplacement(MetaString::OBJ_NAMES, ID);
  1576. cb->sendAndApply(&iw);
  1577. return;
  1578. }
  1579. PlayerRelations::PlayerRelations relations = cb->gameState()->getPlayerRelations( h->tempOwner, tempOwner );
  1580. if ( relations == PlayerRelations::ALLIES )
  1581. return;//do not allow recruiting or capturing
  1582. if( !relations && stacksCount() > 0) //object is guarded, owned by enemy
  1583. {
  1584. BlockingDialog bd(true,false);
  1585. bd.player = h->tempOwner;
  1586. bd.text.addTxt(MetaString::GENERAL_TXT, 421); //Much to your dismay, the %s is guarded by %s %s. Do you wish to fight the guards?
  1587. bd.text.addReplacement(ID == Obj::CREATURE_GENERATOR1 ? MetaString::CREGENS : MetaString::CREGENS4, subID);
  1588. bd.text.addReplacement(MetaString::ARRAY_TXT, 176 + Slots().begin()->second->getQuantityID()*3);
  1589. bd.text.addReplacement(*Slots().begin()->second);
  1590. cb->showBlockingDialog(&bd);
  1591. return;
  1592. }
  1593. if(!relations && ID != Obj::WAR_MACHINE_FACTORY)
  1594. {
  1595. cb->setOwner(this, h->tempOwner);
  1596. }
  1597. BlockingDialog bd (true,false);
  1598. bd.player = h->tempOwner;
  1599. if(ID == Obj::CREATURE_GENERATOR1 || ID == Obj::CREATURE_GENERATOR4)
  1600. {
  1601. bd.text.addTxt(MetaString::ADVOB_TXT, ID == Obj::CREATURE_GENERATOR1 ? 35 : 36); //{%s} Would you like to recruit %s? / {%s} Would you like to recruit %s, %s, %s, or %s?
  1602. bd.text.addReplacement(ID == Obj::CREATURE_GENERATOR1 ? MetaString::CREGENS : MetaString::CREGENS4, subID);
  1603. for(auto & elem : creatures)
  1604. bd.text.addReplacement(MetaString::CRE_PL_NAMES, elem.second[0]);
  1605. }
  1606. else if(ID == Obj::REFUGEE_CAMP)
  1607. {
  1608. bd.text.addTxt(MetaString::ADVOB_TXT, 35); //{%s} Would you like to recruit %s?
  1609. bd.text.addReplacement(MetaString::OBJ_NAMES, ID);
  1610. for(auto & elem : creatures)
  1611. bd.text.addReplacement(MetaString::CRE_PL_NAMES, elem.second[0]);
  1612. }
  1613. else if(ID == Obj::WAR_MACHINE_FACTORY)
  1614. bd.text.addTxt(MetaString::ADVOB_TXT, 157); //{War Machine Factory} Would you like to purchase War Machines?
  1615. else
  1616. throw std::runtime_error("Illegal dwelling!");
  1617. cb->showBlockingDialog(&bd);
  1618. }
  1619. void CGDwelling::newTurn() const
  1620. {
  1621. if(cb->getDate(Date::DAY_OF_WEEK) != 1) //not first day of week
  1622. return;
  1623. //town growths and War Machines Factories are handled separately
  1624. if(ID == Obj::TOWN || ID == Obj::WAR_MACHINE_FACTORY)
  1625. return;
  1626. if(ID == Obj::REFUGEE_CAMP) //if it's a refugee camp, we need to pick an available creature
  1627. {
  1628. cb->setObjProperty(id, ObjProperty::AVAILABLE_CREATURE, VLC->creh->pickRandomMonster());
  1629. }
  1630. bool change = false;
  1631. SetAvailableCreatures sac;
  1632. sac.creatures = creatures;
  1633. sac.tid = id;
  1634. for (size_t i = 0; i < creatures.size(); i++)
  1635. {
  1636. if(creatures[i].second.size())
  1637. {
  1638. CCreature *cre = VLC->creh->creatures[creatures[i].second[0]];
  1639. TQuantity amount = cre->growth * (1 + cre->valOfBonuses(Bonus::CREATURE_GROWTH_PERCENT)/100) + cre->valOfBonuses(Bonus::CREATURE_GROWTH);
  1640. if (VLC->modh->settings.DWELLINGS_ACCUMULATE_CREATURES && ID != Obj::REFUGEE_CAMP) //camp should not try to accumulate different kinds of creatures
  1641. sac.creatures[i].first += amount;
  1642. else
  1643. sac.creatures[i].first = amount;
  1644. change = true;
  1645. }
  1646. }
  1647. if(change)
  1648. cb->sendAndApply(&sac);
  1649. }
  1650. void CGDwelling::heroAcceptsCreatures( const CGHeroInstance *h) const
  1651. {
  1652. CreatureID crid = creatures[0].second[0];
  1653. CCreature *crs = VLC->creh->creatures[crid];
  1654. TQuantity count = creatures[0].first;
  1655. if(crs->level == 1 && ID != Obj::REFUGEE_CAMP) //first level - creatures are for free
  1656. {
  1657. if(count) //there are available creatures
  1658. {
  1659. SlotID slot = h->getSlotFor(crid);
  1660. if(!slot.validSlot()) //no available slot
  1661. {
  1662. InfoWindow iw;
  1663. iw.player = h->tempOwner;
  1664. iw.text.addTxt(MetaString::GENERAL_TXT, 425);//The %s would join your hero, but there aren't enough provisions to support them.
  1665. iw.text.addReplacement(MetaString::CRE_PL_NAMES, crid);
  1666. cb->showInfoDialog(&iw);
  1667. }
  1668. else //give creatures
  1669. {
  1670. SetAvailableCreatures sac;
  1671. sac.tid = id;
  1672. sac.creatures = creatures;
  1673. sac.creatures[0].first = 0;
  1674. InfoWindow iw;
  1675. iw.player = h->tempOwner;
  1676. iw.text.addTxt(MetaString::GENERAL_TXT, 423); //%d %s join your army.
  1677. iw.text.addReplacement(count);
  1678. iw.text.addReplacement(MetaString::CRE_PL_NAMES, crid);
  1679. cb->showInfoDialog(&iw);
  1680. cb->sendAndApply(&sac);
  1681. cb->addToSlot(StackLocation(h, slot), crs, count);
  1682. }
  1683. }
  1684. else //there no creatures
  1685. {
  1686. InfoWindow iw;
  1687. iw.text.addTxt(MetaString::GENERAL_TXT, 422); //There are no %s here to recruit.
  1688. iw.text.addReplacement(MetaString::CRE_PL_NAMES, crid);
  1689. iw.player = h->tempOwner;
  1690. cb->sendAndApply(&iw);
  1691. }
  1692. }
  1693. else
  1694. {
  1695. if(ID == Obj::WAR_MACHINE_FACTORY) //pick available War Machines
  1696. {
  1697. //there is 1 war machine available to recruit if hero doesn't have one
  1698. SetAvailableCreatures sac;
  1699. sac.tid = id;
  1700. sac.creatures = creatures;
  1701. sac.creatures[0].first = !h->getArt(ArtifactPosition::MACH1); //ballista
  1702. sac.creatures[1].first = !h->getArt(ArtifactPosition::MACH3); //first aid tent
  1703. sac.creatures[2].first = !h->getArt(ArtifactPosition::MACH2); //ammo cart
  1704. cb->sendAndApply(&sac);
  1705. }
  1706. OpenWindow ow;
  1707. ow.id1 = id.getNum();
  1708. ow.id2 = h->id.getNum();
  1709. ow.window = (ID == Obj::CREATURE_GENERATOR1 || ID == Obj::REFUGEE_CAMP)
  1710. ? OpenWindow::RECRUITMENT_FIRST
  1711. : OpenWindow::RECRUITMENT_ALL;
  1712. cb->sendAndApply(&ow);
  1713. }
  1714. }
  1715. void CGDwelling::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  1716. {
  1717. if (result.winner == 0)
  1718. {
  1719. onHeroVisit(hero);
  1720. }
  1721. }
  1722. void CGDwelling::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  1723. {
  1724. auto relations = cb->getPlayerRelations(getOwner(), hero->getOwner());
  1725. if(stacksCount() > 0 && relations == PlayerRelations::ENEMIES) //guards present
  1726. {
  1727. if(answer)
  1728. cb->startBattleI(hero, this);
  1729. }
  1730. else if(answer)
  1731. {
  1732. heroAcceptsCreatures(hero);
  1733. }
  1734. }
  1735. int CGTownInstance::getSightRadious() const //returns sight distance
  1736. {
  1737. if (subID == ETownType::TOWER)
  1738. {
  1739. if (hasBuilt(BuildingID::GRAIL)) //skyship
  1740. return -1; //entire map
  1741. if (hasBuilt(BuildingID::LOOKOUT_TOWER)) //lookout tower
  1742. return 20;
  1743. }
  1744. return 5;
  1745. }
  1746. void CGTownInstance::setPropertyDer(ui8 what, ui32 val)
  1747. {
  1748. ///this is freakin' overcomplicated solution
  1749. switch (what)
  1750. {
  1751. case ObjProperty::STRUCTURE_ADD_VISITING_HERO:
  1752. bonusingBuildings[val]->setProperty (ObjProperty::VISITORS, visitingHero->id.getNum());
  1753. break;
  1754. case ObjProperty::STRUCTURE_CLEAR_VISITORS:
  1755. bonusingBuildings[val]->setProperty (ObjProperty::STRUCTURE_CLEAR_VISITORS, 0);
  1756. break;
  1757. case ObjProperty::STRUCTURE_ADD_GARRISONED_HERO: //add garrisoned hero to visitors
  1758. bonusingBuildings[val]->setProperty (ObjProperty::VISITORS, garrisonHero->id.getNum());
  1759. break;
  1760. case ObjProperty::BONUS_VALUE_FIRST:
  1761. bonusValue.first = val;
  1762. break;
  1763. case ObjProperty::BONUS_VALUE_SECOND:
  1764. bonusValue.second = val;
  1765. break;
  1766. }
  1767. }
  1768. CGTownInstance::EFortLevel CGTownInstance::fortLevel() const //0 - none, 1 - fort, 2 - citadel, 3 - castle
  1769. {
  1770. if (hasBuilt(BuildingID::CASTLE))
  1771. return CASTLE;
  1772. if (hasBuilt(BuildingID::CITADEL))
  1773. return CITADEL;
  1774. if (hasBuilt(BuildingID::FORT))
  1775. return FORT;
  1776. return NONE;
  1777. }
  1778. int CGTownInstance::hallLevel() const // -1 - none, 0 - village, 1 - town, 2 - city, 3 - capitol
  1779. {
  1780. if (hasBuilt(BuildingID::CAPITOL))
  1781. return 3;
  1782. if (hasBuilt(BuildingID::CITY_HALL))
  1783. return 2;
  1784. if (hasBuilt(BuildingID::TOWN_HALL))
  1785. return 1;
  1786. if (hasBuilt(BuildingID::VILLAGE_HALL))
  1787. return 0;
  1788. return -1;
  1789. }
  1790. int CGTownInstance::mageGuildLevel() const
  1791. {
  1792. if (hasBuilt(BuildingID::MAGES_GUILD_5))
  1793. return 5;
  1794. if (hasBuilt(BuildingID::MAGES_GUILD_4))
  1795. return 4;
  1796. if (hasBuilt(BuildingID::MAGES_GUILD_3))
  1797. return 3;
  1798. if (hasBuilt(BuildingID::MAGES_GUILD_2))
  1799. return 2;
  1800. if (hasBuilt(BuildingID::MAGES_GUILD_1))
  1801. return 1;
  1802. return 0;
  1803. }
  1804. int CGTownInstance::creatureDwellingLevel(int dwelling) const
  1805. {
  1806. if ( dwelling<0 || dwelling >= GameConstants::CREATURES_PER_TOWN )
  1807. return -1;
  1808. for (int i=0; ; i++)
  1809. {
  1810. if (!hasBuilt(BuildingID(BuildingID::DWELL_FIRST+dwelling+i*GameConstants::CREATURES_PER_TOWN)))
  1811. return i-1;
  1812. }
  1813. }
  1814. int CGTownInstance::getHordeLevel(const int & HID) const//HID - 0 or 1; returns creature level or -1 if that horde structure is not present
  1815. {
  1816. return town->hordeLvl[HID];
  1817. }
  1818. int CGTownInstance::creatureGrowth(const int & level) const
  1819. {
  1820. return getGrowthInfo(level).totalGrowth();
  1821. }
  1822. GrowthInfo CGTownInstance::getGrowthInfo(int level) const
  1823. {
  1824. GrowthInfo ret;
  1825. if (level<0 || level >=GameConstants::CREATURES_PER_TOWN)
  1826. return ret;
  1827. if (!hasBuilt(BuildingID(BuildingID::DWELL_FIRST+level)))
  1828. return ret; //no dwelling
  1829. const CCreature *creature = VLC->creh->creatures[creatures[level].second.back()];
  1830. const int base = creature->growth;
  1831. int castleBonus = 0;
  1832. ret.entries.push_back(GrowthInfo::Entry(VLC->generaltexth->allTexts[590], base));// \n\nBasic growth %d"
  1833. if (hasBuilt(BuildingID::CASTLE))
  1834. ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::CASTLE, castleBonus = base));
  1835. else if (hasBuilt(BuildingID::CITADEL))
  1836. ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::CITADEL, castleBonus = base / 2));
  1837. if(town->hordeLvl[0] == level)//horde 1
  1838. if(hasBuilt(BuildingID::HORDE_1))
  1839. ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::HORDE_1, creature->hordeGrowth));
  1840. if(town->hordeLvl[1] == level)//horde 2
  1841. if(hasBuilt(BuildingID::HORDE_2))
  1842. ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::HORDE_2, creature->hordeGrowth));
  1843. int dwellingBonus = 0;
  1844. if(const PlayerState *p = cb->getPlayer(tempOwner, false))
  1845. {
  1846. for(const CGDwelling *dwelling : p->dwellings)
  1847. if(vstd::contains(creatures[level].second, dwelling->creatures[0].second[0]))
  1848. dwellingBonus++;
  1849. }
  1850. if(dwellingBonus)
  1851. ret.entries.push_back(GrowthInfo::Entry(VLC->generaltexth->allTexts[591], dwellingBonus));// \nExternal dwellings %+d
  1852. //other *-of-legion-like bonuses (%d to growth cumulative with grail)
  1853. TBonusListPtr bonuses = getBonuses(Selector::type(Bonus::CREATURE_GROWTH).And(Selector::subtype(level)));
  1854. for(const Bonus *b : *bonuses)
  1855. ret.entries.push_back(GrowthInfo::Entry(b->Description() + " %+d", b->val));
  1856. //statue-of-legion-like bonus: % to base+castle
  1857. TBonusListPtr bonuses2 = getBonuses(Selector::type(Bonus::CREATURE_GROWTH_PERCENT));
  1858. for(const Bonus *b : *bonuses2)
  1859. ret.entries.push_back(GrowthInfo::Entry(b->Description() + " %+d", b->val * (base + castleBonus) / 100));
  1860. if(hasBuilt(BuildingID::GRAIL)) //grail - +50% to ALL (so far added) growth
  1861. ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::GRAIL, ret.totalGrowth() / 2));
  1862. return ret;
  1863. }
  1864. int CGTownInstance::dailyIncome() const
  1865. {
  1866. int ret = 0;
  1867. if (hasBuilt(BuildingID::GRAIL))
  1868. ret+=5000;
  1869. if (hasBuilt(BuildingID::CAPITOL))
  1870. ret+=4000;
  1871. else if (hasBuilt(BuildingID::CITY_HALL))
  1872. ret+=2000;
  1873. else if (hasBuilt(BuildingID::TOWN_HALL))
  1874. ret+=1000;
  1875. else if (hasBuilt(BuildingID::VILLAGE_HALL))
  1876. ret+=500;
  1877. return ret;
  1878. }
  1879. bool CGTownInstance::hasFort() const
  1880. {
  1881. return hasBuilt(BuildingID::FORT);
  1882. }
  1883. bool CGTownInstance::hasCapitol() const
  1884. {
  1885. return hasBuilt(BuildingID::CAPITOL);
  1886. }
  1887. CGTownInstance::CGTownInstance()
  1888. :IShipyard(this), IMarket(this), town(nullptr), builded(0), destroyed(0), identifier(0), alignment(0xff)
  1889. {
  1890. }
  1891. CGTownInstance::~CGTownInstance()
  1892. {
  1893. for (auto & elem : bonusingBuildings)
  1894. delete elem;
  1895. }
  1896. int CGTownInstance::spellsAtLevel(int level, bool checkGuild) const
  1897. {
  1898. if(checkGuild && mageGuildLevel() < level)
  1899. return 0;
  1900. int ret = 6 - level; //how many spells are available at this level
  1901. if (hasBuilt(BuildingID::LIBRARY, ETownType::TOWER))
  1902. ret++;
  1903. return ret;
  1904. }
  1905. bool CGTownInstance::needsLastStack() const
  1906. {
  1907. if(garrisonHero)
  1908. return true;
  1909. else return false;
  1910. }
  1911. void CGTownInstance::onHeroVisit(const CGHeroInstance * h) const
  1912. {
  1913. if( !cb->gameState()->getPlayerRelations( getOwner(), h->getOwner() ))//if this is enemy
  1914. {
  1915. if(armedGarrison() || visitingHero)
  1916. {
  1917. const CGHeroInstance *defendingHero = nullptr;
  1918. const CArmedInstance *defendingArmy = this;
  1919. if(visitingHero)
  1920. defendingHero = visitingHero;
  1921. else if(garrisonHero)
  1922. defendingHero = garrisonHero;
  1923. if(defendingHero)
  1924. defendingArmy = defendingHero;
  1925. bool outsideTown = (defendingHero == visitingHero && garrisonHero);
  1926. //TODO
  1927. //"borrowing" army from garrison to visiting hero
  1928. cb->startBattlePrimary(h, defendingArmy, getSightCenter(), h, defendingHero, false, (outsideTown ? nullptr : this));
  1929. }
  1930. else
  1931. {
  1932. cb->setOwner(this, h->tempOwner);
  1933. removeCapitols(h->getOwner());
  1934. cb->heroVisitCastle(this, h);
  1935. }
  1936. }
  1937. else if(h->visitablePos() == visitablePos())
  1938. {
  1939. if (h->commander && !h->commander->alive) //rise commander. TODO: interactive script
  1940. {
  1941. SetCommanderProperty scp;
  1942. scp.heroid = h->id;
  1943. scp.which = SetCommanderProperty::ALIVE;
  1944. scp.amount = 1;
  1945. cb->sendAndApply (&scp);
  1946. }
  1947. cb->heroVisitCastle(this, h);
  1948. }
  1949. else
  1950. {
  1951. logGlobal->errorStream() << h->name << " visits allied town of " << name << " from different pos?";
  1952. }
  1953. }
  1954. void CGTownInstance::onHeroLeave(const CGHeroInstance * h) const
  1955. {
  1956. cb->stopHeroVisitCastle(this, h);
  1957. }
  1958. void CGTownInstance::initObj()
  1959. ///initialize town structures
  1960. {
  1961. blockVisit = true;
  1962. hoverName = name + ", " + town->faction->name;
  1963. if (subID == ETownType::DUNGEON)
  1964. creatures.resize(GameConstants::CREATURES_PER_TOWN+1);//extra dwelling for Dungeon
  1965. else
  1966. creatures.resize(GameConstants::CREATURES_PER_TOWN);
  1967. for (int i = 0; i < GameConstants::CREATURES_PER_TOWN; i++)
  1968. {
  1969. int dwellingLevel = creatureDwellingLevel(i);
  1970. int creaturesTotal = town->creatures[i].size();
  1971. for (int j=0; j< std::min(dwellingLevel + 1, creaturesTotal); j++)
  1972. creatures[i].second.push_back(town->creatures[i][j]);
  1973. }
  1974. switch (subID)
  1975. { //add new visitable objects
  1976. case 0:
  1977. bonusingBuildings.push_back (new COPWBonus(BuildingID::STABLES, this));
  1978. break;
  1979. case 5:
  1980. bonusingBuildings.push_back (new COPWBonus(BuildingID::MANA_VORTEX, this));
  1981. case 2: case 3: case 6:
  1982. bonusingBuildings.push_back (new CTownBonus(BuildingID::SPECIAL_4, this));
  1983. break;
  1984. case 7:
  1985. bonusingBuildings.push_back (new CTownBonus(BuildingID::SPECIAL_1, this));
  1986. break;
  1987. }
  1988. //add special bonuses from buildings
  1989. recreateBuildingsBonuses();
  1990. }
  1991. void CGTownInstance::newTurn() const
  1992. {
  1993. if (cb->getDate(Date::DAY_OF_WEEK) == 1) //reset on new week
  1994. {
  1995. //give resources for Rampart, Mystic Pond
  1996. if (hasBuilt(BuildingID::MYSTIC_POND, ETownType::RAMPART)
  1997. && cb->getDate(Date::DAY) != 1 && (tempOwner < PlayerColor::PLAYER_LIMIT))
  1998. {
  1999. int resID = rand()%4+2;//bonus to random rare resource
  2000. resID = (resID==2)?1:resID;
  2001. int resVal = rand()%4+1;//with size 1..4
  2002. cb->giveResource(tempOwner, static_cast<Res::ERes>(resID), resVal);
  2003. cb->setObjProperty (id, ObjProperty::BONUS_VALUE_FIRST, resID);
  2004. cb->setObjProperty (id, ObjProperty::BONUS_VALUE_SECOND, resVal);
  2005. }
  2006. if ( subID == ETownType::DUNGEON )
  2007. for (auto & elem : bonusingBuildings)
  2008. {
  2009. if ((elem)->ID == BuildingID::MANA_VORTEX)
  2010. cb->setObjProperty (id, ObjProperty::STRUCTURE_CLEAR_VISITORS, (elem)->id); //reset visitors for Mana Vortex
  2011. }
  2012. if (tempOwner == PlayerColor::NEUTRAL) //garrison growth for neutral towns
  2013. {
  2014. std::vector<SlotID> nativeCrits; //slots
  2015. for (auto & elem : Slots())
  2016. {
  2017. if (elem.second->type->faction == subID) //native
  2018. {
  2019. nativeCrits.push_back(elem.first); //collect matching slots
  2020. }
  2021. }
  2022. if (nativeCrits.size())
  2023. {
  2024. SlotID pos = nativeCrits[rand() % nativeCrits.size()];
  2025. StackLocation sl(this, pos);
  2026. const CCreature *c = getCreature(pos);
  2027. if (rand()%100 < 90 || c->upgrades.empty()) //increase number if no upgrade available
  2028. {
  2029. cb->changeStackCount(sl, c->growth);
  2030. }
  2031. else //upgrade
  2032. {
  2033. cb->changeStackType(sl, VLC->creh->creatures[*c->upgrades.begin()]);
  2034. }
  2035. }
  2036. if ((stacksCount() < GameConstants::ARMY_SIZE && rand()%100 < 25) || Slots().empty()) //add new stack
  2037. {
  2038. int i = rand() % std::min (GameConstants::ARMY_SIZE, cb->getDate(Date::MONTH)<<1);
  2039. CreatureID c = town->creatures[i][0];
  2040. SlotID n;
  2041. TQuantity count = creatureGrowth(i);
  2042. if (!count) // no dwelling
  2043. count = VLC->creh->creatures[c]->growth;
  2044. {//no lower tiers or above current month
  2045. if ((n = getSlotFor(c)).validSlot())
  2046. {
  2047. StackLocation sl(this, n);
  2048. if (slotEmpty(n))
  2049. cb->insertNewStack(sl, VLC->creh->creatures[c], count);
  2050. else //add to existing
  2051. cb->changeStackCount(sl, count);
  2052. }
  2053. }
  2054. }
  2055. }
  2056. }
  2057. }
  2058. int3 CGTownInstance::getSightCenter() const
  2059. {
  2060. return pos - int3(2,0,0);
  2061. }
  2062. ui8 CGTownInstance::getPassableness() const
  2063. {
  2064. if (!armedGarrison())//empty castle - anyone can visit
  2065. return GameConstants::ALL_PLAYERS;
  2066. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  2067. return 0;
  2068. ui8 mask = 0;
  2069. TeamState * ts = cb->gameState()->getPlayerTeam(tempOwner);
  2070. for(PlayerColor it : ts->players)
  2071. mask |= 1<<it.getNum();//allies - add to possible visitors
  2072. return mask;
  2073. }
  2074. void CGTownInstance::getOutOffsets( std::vector<int3> &offsets ) const
  2075. {
  2076. offsets += int3(-1,2,0), int3(-3,2,0);
  2077. }
  2078. void CGTownInstance::removeCapitols (PlayerColor owner) const
  2079. {
  2080. if (hasCapitol()) // search if there's an older capitol
  2081. {
  2082. PlayerState* state = cb->gameState()->getPlayer (owner); //get all towns owned by player
  2083. for (auto i = state->towns.cbegin(); i < state->towns.cend(); ++i)
  2084. {
  2085. if (*i != this && (*i)->hasCapitol())
  2086. {
  2087. RazeStructures rs;
  2088. rs.tid = id;
  2089. rs.bid.insert(BuildingID::CAPITOL);
  2090. rs.destroyed = destroyed;
  2091. cb->sendAndApply(&rs);
  2092. return;
  2093. }
  2094. }
  2095. }
  2096. }
  2097. int CGTownInstance::getBoatType() const
  2098. {
  2099. switch (town->faction->alignment)
  2100. {
  2101. case EAlignment::EVIL : return 0;
  2102. case EAlignment::GOOD : return 1;
  2103. case EAlignment::NEUTRAL : return 2;
  2104. }
  2105. assert(0);
  2106. return -1;
  2107. }
  2108. int CGTownInstance::getMarketEfficiency() const
  2109. {
  2110. if (!hasBuilt(BuildingID::MARKETPLACE))
  2111. return 0;
  2112. const PlayerState *p = cb->getPlayer(tempOwner);
  2113. assert(p);
  2114. int marketCount = 0;
  2115. for(const CGTownInstance *t : p->towns)
  2116. if(t->hasBuilt(BuildingID::MARKETPLACE))
  2117. marketCount++;
  2118. return marketCount;
  2119. }
  2120. bool CGTownInstance::allowsTrade(EMarketMode::EMarketMode mode) const
  2121. {
  2122. switch(mode)
  2123. {
  2124. case EMarketMode::RESOURCE_RESOURCE:
  2125. case EMarketMode::RESOURCE_PLAYER:
  2126. return hasBuilt(BuildingID::MARKETPLACE);
  2127. case EMarketMode::ARTIFACT_RESOURCE:
  2128. case EMarketMode::RESOURCE_ARTIFACT:
  2129. return hasBuilt(BuildingID::ARTIFACT_MERCHANT, ETownType::TOWER)
  2130. || hasBuilt(BuildingID::ARTIFACT_MERCHANT, ETownType::DUNGEON)
  2131. || hasBuilt(BuildingID::ARTIFACT_MERCHANT, ETownType::CONFLUX);
  2132. case EMarketMode::CREATURE_RESOURCE:
  2133. return hasBuilt(BuildingID::FREELANCERS_GUILD, ETownType::STRONGHOLD);
  2134. case EMarketMode::CREATURE_UNDEAD:
  2135. return hasBuilt(BuildingID::SKELETON_TRANSFORMER, ETownType::NECROPOLIS);
  2136. case EMarketMode::RESOURCE_SKILL:
  2137. return hasBuilt(BuildingID::MAGIC_UNIVERSITY, ETownType::CONFLUX);
  2138. default:
  2139. assert(0);
  2140. return false;
  2141. }
  2142. }
  2143. std::vector<int> CGTownInstance::availableItemsIds(EMarketMode::EMarketMode mode) const
  2144. {
  2145. if(mode == EMarketMode::RESOURCE_ARTIFACT)
  2146. {
  2147. std::vector<int> ret;
  2148. for(const CArtifact *a : merchantArtifacts)
  2149. if(a)
  2150. ret.push_back(a->id);
  2151. else
  2152. ret.push_back(-1);
  2153. return ret;
  2154. }
  2155. else if ( mode == EMarketMode::RESOURCE_SKILL )
  2156. {
  2157. return universitySkills;
  2158. }
  2159. else
  2160. return IMarket::availableItemsIds(mode);
  2161. }
  2162. std::string CGTownInstance::nodeName() const
  2163. {
  2164. return "Town (" + (town ? town->faction->name : "unknown") + ") of " + name;
  2165. }
  2166. void CGTownInstance::deserializationFix()
  2167. {
  2168. attachTo(&townAndVis);
  2169. //Hero is already handled by CGameState::attachArmedObjects
  2170. // if(visitingHero)
  2171. // visitingHero->attachTo(&townAndVis);
  2172. // if(garrisonHero)
  2173. // garrisonHero->attachTo(this);
  2174. }
  2175. void CGTownInstance::updateMoraleBonusFromArmy()
  2176. {
  2177. Bonus *b = getBonusList().getFirst(Selector::sourceType(Bonus::ARMY).And(Selector::type(Bonus::MORALE)));
  2178. if(!b)
  2179. {
  2180. b = new Bonus(Bonus::PERMANENT, Bonus::MORALE, Bonus::ARMY, 0, -1);
  2181. addNewBonus(b);
  2182. }
  2183. if (garrisonHero)
  2184. b->val = 0;
  2185. else
  2186. CArmedInstance::updateMoraleBonusFromArmy();
  2187. }
  2188. void CGTownInstance::recreateBuildingsBonuses()
  2189. {
  2190. static TPropagatorPtr playerProp(new CPropagatorNodeType(PLAYER));
  2191. BonusList bl;
  2192. getExportedBonusList().getBonuses(bl, Selector::sourceType(Bonus::TOWN_STRUCTURE));
  2193. for(Bonus *b : bl)
  2194. removeBonus(b);
  2195. //tricky! -> checks tavern only if no bratherhood of sword or not a castle
  2196. if(subID != ETownType::CASTLE || !addBonusIfBuilt(BuildingID::BROTHERHOOD, Bonus::MORALE, +2))
  2197. addBonusIfBuilt(BuildingID::TAVERN, Bonus::MORALE, +1);
  2198. if(subID == ETownType::CASTLE) //castle
  2199. {
  2200. addBonusIfBuilt(BuildingID::LIGHTHOUSE, Bonus::SEA_MOVEMENT, +500, playerProp);
  2201. addBonusIfBuilt(BuildingID::GRAIL, Bonus::MORALE, +2, playerProp); //colossus
  2202. }
  2203. else if(subID == ETownType::RAMPART) //rampart
  2204. {
  2205. addBonusIfBuilt(BuildingID::FOUNTAIN_OF_FORTUNE, Bonus::LUCK, +2); //fountain of fortune
  2206. addBonusIfBuilt(BuildingID::GRAIL, Bonus::LUCK, +2, playerProp); //guardian spirit
  2207. }
  2208. else if(subID == ETownType::TOWER) //tower
  2209. {
  2210. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +15, PrimarySkill::KNOWLEDGE); //grail
  2211. }
  2212. else if(subID == ETownType::INFERNO) //Inferno
  2213. {
  2214. addBonusIfBuilt(BuildingID::STORMCLOUDS, Bonus::PRIMARY_SKILL, +2, PrimarySkill::SPELL_POWER); //Brimstone Clouds
  2215. }
  2216. else if(subID == ETownType::NECROPOLIS) //necropolis
  2217. {
  2218. addBonusIfBuilt(BuildingID::COVER_OF_DARKNESS, Bonus::DARKNESS, +20);
  2219. addBonusIfBuilt(BuildingID::NECROMANCY_AMPLIFIER, Bonus::SECONDARY_SKILL_PREMY, +10, playerProp, SecondarySkill::NECROMANCY); //necromancy amplifier
  2220. addBonusIfBuilt(BuildingID::GRAIL, Bonus::SECONDARY_SKILL_PREMY, +20, playerProp, SecondarySkill::NECROMANCY); //Soul prison
  2221. }
  2222. else if(subID == ETownType::DUNGEON) //Dungeon
  2223. {
  2224. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +12, PrimarySkill::SPELL_POWER); //grail
  2225. }
  2226. else if(subID == ETownType::STRONGHOLD) //Stronghold
  2227. {
  2228. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +20, PrimarySkill::ATTACK); //grail
  2229. }
  2230. else if(subID == ETownType::FORTRESS) //Fortress
  2231. {
  2232. addBonusIfBuilt(BuildingID::GLYPHS_OF_FEAR, Bonus::PRIMARY_SKILL, +2, PrimarySkill::DEFENSE); //Glyphs of Fear
  2233. addBonusIfBuilt(BuildingID::BLOOD_OBELISK, Bonus::PRIMARY_SKILL, +2, PrimarySkill::ATTACK); //Blood Obelisk
  2234. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +10, PrimarySkill::ATTACK); //grail
  2235. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +10, PrimarySkill::DEFENSE); //grail
  2236. }
  2237. else if(subID == ETownType::CONFLUX)
  2238. {
  2239. }
  2240. }
  2241. bool CGTownInstance::addBonusIfBuilt(BuildingID building, Bonus::BonusType type, int val, int subtype /*= -1*/)
  2242. {
  2243. static auto emptyPropagator = TPropagatorPtr();
  2244. return addBonusIfBuilt(building, type, val, emptyPropagator, subtype);
  2245. }
  2246. bool CGTownInstance::addBonusIfBuilt(BuildingID building, Bonus::BonusType type, int val, TPropagatorPtr & prop, int subtype /*= -1*/)
  2247. {
  2248. if(hasBuilt(building))
  2249. {
  2250. std::ostringstream descr;
  2251. descr << town->buildings[building]->Name() << " ";
  2252. if(val > 0)
  2253. descr << "+";
  2254. else if(val < 0)
  2255. descr << "-";
  2256. descr << val;
  2257. Bonus *b = new Bonus(Bonus::PERMANENT, type, Bonus::TOWN_STRUCTURE, val, building, descr.str(), subtype);
  2258. if(prop)
  2259. b->addPropagator(prop);
  2260. addNewBonus(b);
  2261. return true;
  2262. }
  2263. return false;
  2264. }
  2265. void CGTownInstance::setVisitingHero(CGHeroInstance *h)
  2266. {
  2267. assert(!!visitingHero == !h);
  2268. if(h)
  2269. {
  2270. PlayerState *p = cb->gameState()->getPlayer(h->tempOwner);
  2271. assert(p);
  2272. h->detachFrom(p);
  2273. h->attachTo(&townAndVis);
  2274. visitingHero = h;
  2275. h->visitedTown = this;
  2276. h->inTownGarrison = false;
  2277. }
  2278. else
  2279. {
  2280. PlayerState *p = cb->gameState()->getPlayer(visitingHero->tempOwner);
  2281. visitingHero->visitedTown = nullptr;
  2282. visitingHero->detachFrom(&townAndVis);
  2283. visitingHero->attachTo(p);
  2284. visitingHero = nullptr;
  2285. }
  2286. }
  2287. void CGTownInstance::setGarrisonedHero(CGHeroInstance *h)
  2288. {
  2289. assert(!!garrisonHero == !h);
  2290. if(h)
  2291. {
  2292. PlayerState *p = cb->gameState()->getPlayer(h->tempOwner);
  2293. assert(p);
  2294. h->detachFrom(p);
  2295. h->attachTo(this);
  2296. garrisonHero = h;
  2297. h->visitedTown = this;
  2298. h->inTownGarrison = true;
  2299. }
  2300. else
  2301. {
  2302. PlayerState *p = cb->gameState()->getPlayer(garrisonHero->tempOwner);
  2303. garrisonHero->visitedTown = nullptr;
  2304. garrisonHero->inTownGarrison = false;
  2305. garrisonHero->detachFrom(this);
  2306. garrisonHero->attachTo(p);
  2307. garrisonHero = nullptr;
  2308. }
  2309. updateMoraleBonusFromArmy(); //avoid giving morale bonus for same army twice
  2310. }
  2311. bool CGTownInstance::armedGarrison() const
  2312. {
  2313. return stacksCount() || garrisonHero;
  2314. }
  2315. int CGTownInstance::getTownLevel() const
  2316. {
  2317. // count all buildings that are not upgrades
  2318. return boost::range::count_if(builtBuildings, [&](const BuildingID & build)
  2319. {
  2320. return town->buildings[build] && town->buildings[build]->upgrade == -1;
  2321. });
  2322. }
  2323. CBonusSystemNode * CGTownInstance::whatShouldBeAttached()
  2324. {
  2325. return &townAndVis;
  2326. }
  2327. const CArmedInstance * CGTownInstance::getUpperArmy() const
  2328. {
  2329. if(garrisonHero)
  2330. return garrisonHero;
  2331. return this;
  2332. }
  2333. bool CGTownInstance::hasBuilt(BuildingID buildingID, int townID) const
  2334. {
  2335. if (townID == town->faction->index || townID == ETownType::ANY)
  2336. return hasBuilt(buildingID);
  2337. return false;
  2338. }
  2339. bool CGTownInstance::hasBuilt(BuildingID buildingID) const
  2340. {
  2341. return vstd::contains(builtBuildings, buildingID);
  2342. }
  2343. void CGTownInstance::addHeroToStructureVisitors( const CGHeroInstance *h, si32 structureInstanceID ) const
  2344. {
  2345. if(visitingHero == h)
  2346. cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_VISITING_HERO, structureInstanceID); //add to visitors
  2347. else if(garrisonHero == h)
  2348. cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_GARRISONED_HERO, structureInstanceID); //then it must be garrisoned hero
  2349. else
  2350. {
  2351. //should never ever happen
  2352. logGlobal->errorStream() << "Cannot add hero " << h->name << " to visitors of structure #" << structureInstanceID;
  2353. assert(0);
  2354. }
  2355. }
  2356. void CGTownInstance::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  2357. {
  2358. if(result.winner == 0)
  2359. {
  2360. removeCapitols(hero->getOwner());
  2361. cb->setOwner (this, hero->tempOwner); //give control after checkout is done
  2362. FoWChange fw;
  2363. fw.player = hero->tempOwner;
  2364. fw.mode = 1;
  2365. getSightTiles (fw.tiles); //update visibility for castle structures
  2366. cb->sendAndApply (&fw);
  2367. }
  2368. }
  2369. bool CGVisitableOPH::wasVisited (const CGHeroInstance * h) const
  2370. {
  2371. return vstd::contains(visitors, h->id);
  2372. }
  2373. void CGVisitableOPH::onHeroVisit( const CGHeroInstance * h ) const
  2374. {
  2375. if(!vstd::contains(visitors, h->id))
  2376. {
  2377. onNAHeroVisit (h, false);
  2378. switch(ID)
  2379. {
  2380. case Obj::TREE_OF_KNOWLEDGE:
  2381. case Obj::ARENA:
  2382. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  2383. case Obj::SCHOOL_OF_MAGIC:
  2384. case Obj::SCHOOL_OF_WAR:
  2385. break;
  2386. default:
  2387. cb->setObjProperty(id, ObjProperty::VISITORS, h->id.getNum()); //add to the visitors
  2388. break;
  2389. }
  2390. }
  2391. else
  2392. {
  2393. onNAHeroVisit(h, true);
  2394. }
  2395. }
  2396. void CGVisitableOPH::initObj()
  2397. {
  2398. if(ID==Obj::TREE_OF_KNOWLEDGE)
  2399. {
  2400. switch (ran() % 3)
  2401. {
  2402. case 1:
  2403. treePrice[Res::GOLD] = 2000;
  2404. break;
  2405. case 2:
  2406. treePrice[Res::GEMS] = 10;
  2407. break;
  2408. default:
  2409. break;
  2410. }
  2411. }
  2412. }
  2413. void CGVisitableOPH::treeSelected (const CGHeroInstance * h, ui32 result) const
  2414. {
  2415. if(result) //player agreed to give res for exp
  2416. {
  2417. si64 expToGive = VLC->heroh->reqExp(h->level+1) - VLC->heroh->reqExp(h->level);;
  2418. cb->giveResources (h->getOwner(), -treePrice);
  2419. cb->changePrimSkill (h, PrimarySkill::EXPERIENCE, expToGive);
  2420. cb->setObjProperty (id, ObjProperty::VISITORS, h->id.getNum()); //add to the visitors
  2421. }
  2422. }
  2423. void CGVisitableOPH::onNAHeroVisit (const CGHeroInstance * h, bool alreadyVisited) const
  2424. {
  2425. Component::EComponentType c_id = Component::PRIM_SKILL; //most used here
  2426. int subid=0, ot=0, sound = 0;
  2427. TExpType val=1;
  2428. switch(ID)
  2429. {
  2430. case Obj::ARENA:
  2431. sound = soundBase::NOMAD;
  2432. ot = 0;
  2433. break;
  2434. case Obj::MERCENARY_CAMP:
  2435. sound = soundBase::NOMAD;
  2436. subid=PrimarySkill::ATTACK;
  2437. ot=80;
  2438. break;
  2439. case Obj::MARLETTO_TOWER:
  2440. sound = soundBase::NOMAD;
  2441. subid=PrimarySkill::DEFENSE;
  2442. ot=39;
  2443. break;
  2444. case Obj::STAR_AXIS:
  2445. sound = soundBase::gazebo;
  2446. subid=PrimarySkill::SPELL_POWER;
  2447. ot=100;
  2448. break;
  2449. case Obj::GARDEN_OF_REVELATION:
  2450. sound = soundBase::GETPROTECTION;
  2451. subid=PrimarySkill::KNOWLEDGE;
  2452. ot=59;
  2453. break;
  2454. case Obj::LEARNING_STONE:
  2455. sound = soundBase::gazebo;
  2456. c_id=Component::EXPERIENCE;
  2457. ot=143;
  2458. val=1000;
  2459. break;
  2460. case Obj::TREE_OF_KNOWLEDGE:
  2461. sound = soundBase::gazebo;
  2462. c_id = Component::EXPERIENCE;
  2463. subid = 1;
  2464. ot = 147;
  2465. val = 1;
  2466. break;
  2467. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  2468. sound = soundBase::gazebo;
  2469. ot = 66;
  2470. break;
  2471. case Obj::SCHOOL_OF_MAGIC:
  2472. sound = soundBase::faerie;
  2473. ot = 71;
  2474. break;
  2475. case Obj::SCHOOL_OF_WAR:
  2476. c_id=Component::PRIM_SKILL;
  2477. sound = soundBase::MILITARY;
  2478. ot = 158;
  2479. break;
  2480. }
  2481. if (!alreadyVisited)
  2482. {
  2483. switch (ID)
  2484. {
  2485. case Obj::ARENA:
  2486. {
  2487. BlockingDialog sd(false,true);
  2488. sd.soundID = sound;
  2489. sd.text.addTxt(MetaString::ADVOB_TXT,ot);
  2490. sd.components.push_back(Component(c_id, PrimarySkill::ATTACK, 2, 0));
  2491. sd.components.push_back(Component(c_id, PrimarySkill::DEFENSE, 2, 0));
  2492. sd.player = h->getOwner();
  2493. cb->showBlockingDialog(&sd);
  2494. return;
  2495. }
  2496. case Obj::MERCENARY_CAMP:
  2497. case Obj::MARLETTO_TOWER:
  2498. case Obj::STAR_AXIS:
  2499. case Obj::GARDEN_OF_REVELATION:
  2500. {
  2501. cb->changePrimSkill (h, static_cast<PrimarySkill::PrimarySkill>(subid), val);
  2502. InfoWindow iw;
  2503. iw.soundID = sound;
  2504. iw.components.push_back(Component(c_id, subid, val, 0));
  2505. iw.text.addTxt(MetaString::ADVOB_TXT,ot);
  2506. iw.player = h->getOwner();
  2507. cb->showInfoDialog(&iw);
  2508. break;
  2509. }
  2510. case Obj::LEARNING_STONE: //give exp
  2511. {
  2512. val = h->calculateXp(val);
  2513. InfoWindow iw;
  2514. iw.soundID = sound;
  2515. iw.components.push_back (Component(c_id,subid,val,0));
  2516. iw.player = h->getOwner();
  2517. iw.text.addTxt(MetaString::ADVOB_TXT,ot);
  2518. cb->showInfoDialog(&iw);
  2519. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, val);
  2520. break;
  2521. }
  2522. case Obj::TREE_OF_KNOWLEDGE:
  2523. {
  2524. val = VLC->heroh->reqExp (h->level + val) - VLC->heroh->reqExp(h->level);
  2525. if(!treePrice.nonZero())
  2526. {
  2527. cb->setObjProperty (id, ObjProperty::VISITORS, h->id.getNum()); //add to the visitors
  2528. InfoWindow iw;
  2529. iw.soundID = sound;
  2530. iw.components.push_back (Component(c_id,subid,1,0));
  2531. iw.player = h->getOwner();
  2532. iw.text.addTxt (MetaString::ADVOB_TXT,148);
  2533. cb->showInfoDialog (&iw);
  2534. cb->changePrimSkill (h, PrimarySkill::EXPERIENCE, val);
  2535. break;
  2536. }
  2537. else
  2538. {
  2539. if(treePrice[Res::GOLD] > 0)
  2540. ot = 149;
  2541. else
  2542. ot = 151;
  2543. if(!cb->getPlayer(h->tempOwner)->resources.canAfford(treePrice)) //not enough resources
  2544. {
  2545. ot++;
  2546. showInfoDialog(h,ot,sound);
  2547. return;
  2548. }
  2549. BlockingDialog sd (true, false);
  2550. sd.soundID = sound;
  2551. sd.player = h->getOwner();
  2552. sd.text.addTxt (MetaString::ADVOB_TXT,ot);
  2553. sd.addResourceComponents (treePrice);
  2554. cb->showBlockingDialog (&sd);
  2555. }
  2556. break;
  2557. }
  2558. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  2559. {
  2560. int txt_id = 66;
  2561. if(h->level < 10 - 2*h->getSecSkillLevel(SecondarySkill::DIPLOMACY)) //not enough level
  2562. {
  2563. txt_id += 2;
  2564. }
  2565. else
  2566. {
  2567. cb->setObjProperty(id, ObjProperty::VISITORS, h->id.getNum()); //add to the visitors
  2568. cb->changePrimSkill (h, PrimarySkill::ATTACK, 2);
  2569. cb->changePrimSkill (h, PrimarySkill::DEFENSE, 2);
  2570. cb->changePrimSkill (h, PrimarySkill::KNOWLEDGE, 2);
  2571. cb->changePrimSkill (h, PrimarySkill::SPELL_POWER, 2);
  2572. }
  2573. showInfoDialog(h,txt_id,sound);
  2574. break;
  2575. }
  2576. case Obj::SCHOOL_OF_MAGIC:
  2577. case Obj::SCHOOL_OF_WAR:
  2578. {
  2579. int skill = (ID==Obj::SCHOOL_OF_MAGIC ? 2 : 0);
  2580. if (cb->getResource (h->getOwner(), Res::GOLD) < 1000) //not enough resources
  2581. {
  2582. showInfoDialog (h->getOwner(), ot+2, sound);
  2583. }
  2584. else
  2585. {
  2586. BlockingDialog sd(true,true);
  2587. sd.soundID = sound;
  2588. sd.player = h->getOwner();
  2589. sd.text.addTxt(MetaString::ADVOB_TXT,ot);
  2590. sd.components.push_back(Component(c_id, skill, +1, 0));
  2591. sd.components.push_back(Component(c_id, skill+1, +1, 0));
  2592. cb->showBlockingDialog(&sd);
  2593. }
  2594. }
  2595. break;
  2596. }
  2597. }
  2598. else
  2599. {
  2600. ot++;
  2601. showInfoDialog (h->getOwner(),ot,sound);
  2602. }
  2603. }
  2604. const std::string & CGVisitableOPH::getHoverText() const
  2605. {
  2606. int pom = -1;
  2607. switch(ID)
  2608. {
  2609. case Obj::ARENA:
  2610. pom = -1;
  2611. break;
  2612. case Obj::MERCENARY_CAMP:
  2613. pom = 8;
  2614. break;
  2615. case Obj::MARLETTO_TOWER:
  2616. pom = 7;
  2617. break;
  2618. case Obj::STAR_AXIS:
  2619. pom = 11;
  2620. break;
  2621. case Obj::GARDEN_OF_REVELATION:
  2622. pom = 4;
  2623. break;
  2624. case Obj::LEARNING_STONE:
  2625. pom = 5;
  2626. break;
  2627. case Obj::TREE_OF_KNOWLEDGE:
  2628. pom = 18;
  2629. break;
  2630. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  2631. break;
  2632. case Obj::SCHOOL_OF_MAGIC:
  2633. pom = 9;
  2634. break;
  2635. case Obj::SCHOOL_OF_WAR:
  2636. pom = 10;
  2637. break;
  2638. default:
  2639. throw std::runtime_error("Wrong CGVisitableOPH object ID!\n");
  2640. }
  2641. hoverName = VLC->generaltexth->names[ID];
  2642. if(pom >= 0)
  2643. hoverName += ("\n" + VLC->generaltexth->xtrainfo[pom]);
  2644. const CGHeroInstance *h = cb->getSelectedHero (cb->getCurrentPlayer());
  2645. if(h)
  2646. {
  2647. hoverName += "\n\n";
  2648. bool visited = vstd::contains (visitors, h->id);
  2649. hoverName += visitedTxt (visited);
  2650. }
  2651. return hoverName;
  2652. }
  2653. void CGVisitableOPH::arenaSelected(const CGHeroInstance * h, int primSkill ) const
  2654. {
  2655. cb->setObjProperty(id, ObjProperty::VISITORS, h->id.getNum()); //add to the visitors
  2656. cb->changePrimSkill(h, static_cast<PrimarySkill::PrimarySkill>(primSkill-1), 2);
  2657. }
  2658. void CGVisitableOPH::setPropertyDer( ui8 what, ui32 val )
  2659. {
  2660. if(what == ObjProperty::VISITORS)
  2661. visitors.insert(ObjectInstanceID(val));
  2662. }
  2663. void CGVisitableOPH::schoolSelected(const CGHeroInstance * h, ui32 which) const
  2664. {
  2665. if(!which) //player refused to pay
  2666. return;
  2667. int base = (ID == Obj::SCHOOL_OF_MAGIC ? 2 : 0);
  2668. cb->setObjProperty (id, ObjProperty::VISITORS, h->id.getNum()); //add to the visitors
  2669. cb->giveResource (h->getOwner(),Res::GOLD,-1000); //take 1000 gold
  2670. cb->changePrimSkill (h, static_cast<PrimarySkill::PrimarySkill>(base + which-1), +1); //give appropriate skill
  2671. }
  2672. void CGVisitableOPH::blockingDialogAnswered(const CGHeroInstance *h, ui32 answer) const
  2673. {
  2674. switch (ID)
  2675. {
  2676. case Obj::ARENA:
  2677. arenaSelected(h, answer);
  2678. break;
  2679. case Obj::TREE_OF_KNOWLEDGE:
  2680. treeSelected(h, answer);
  2681. break;
  2682. case Obj::SCHOOL_OF_MAGIC:
  2683. case Obj::SCHOOL_OF_WAR:
  2684. schoolSelected(h, answer);
  2685. break;
  2686. default:
  2687. assert(0);
  2688. break;
  2689. }
  2690. }
  2691. COPWBonus::COPWBonus (BuildingID index, CGTownInstance *TOWN)
  2692. {
  2693. ID = index;
  2694. town = TOWN;
  2695. id = town->bonusingBuildings.size();
  2696. }
  2697. void COPWBonus::setProperty(ui8 what, ui32 val)
  2698. {
  2699. switch (what)
  2700. {
  2701. case ObjProperty::VISITORS:
  2702. visitors.insert(val);
  2703. break;
  2704. case ObjProperty::STRUCTURE_CLEAR_VISITORS:
  2705. visitors.clear();
  2706. break;
  2707. }
  2708. }
  2709. void COPWBonus::onHeroVisit (const CGHeroInstance * h) const
  2710. {
  2711. ObjectInstanceID heroID = h->id;
  2712. if (town->hasBuilt(ID))
  2713. {
  2714. InfoWindow iw;
  2715. iw.player = h->tempOwner;
  2716. switch (town->subID)
  2717. {
  2718. case ETownType::CASTLE: //Stables
  2719. if (!h->hasBonusFrom(Bonus::OBJECT, Obj::STABLES)) //does not stack with advMap Stables
  2720. {
  2721. GiveBonus gb;
  2722. gb.bonus = Bonus(Bonus::ONE_WEEK, Bonus::LAND_MOVEMENT, Bonus::OBJECT, 600, 94, VLC->generaltexth->arraytxt[100]);
  2723. gb.id = heroID.getNum();
  2724. cb->giveHeroBonus(&gb);
  2725. iw.text << VLC->generaltexth->allTexts[580];
  2726. cb->showInfoDialog(&iw);
  2727. }
  2728. break;
  2729. case ETownType::DUNGEON: //Mana Vortex
  2730. if (visitors.empty() && h->mana <= h->manaLimit() * 2)
  2731. {
  2732. cb->setManaPoints (heroID, 2 * h->manaLimit());
  2733. //TODO: investigate line below
  2734. //cb->setObjProperty (town->id, ObjProperty::VISITED, true);
  2735. iw.text << VLC->generaltexth->allTexts[579];
  2736. cb->showInfoDialog(&iw);
  2737. town->addHeroToStructureVisitors(h, id);
  2738. }
  2739. break;
  2740. }
  2741. }
  2742. }
  2743. CTownBonus::CTownBonus (BuildingID index, CGTownInstance *TOWN)
  2744. {
  2745. ID = index;
  2746. town = TOWN;
  2747. id = town->bonusingBuildings.size();
  2748. }
  2749. void CTownBonus::setProperty (ui8 what, ui32 val)
  2750. {
  2751. if(what == ObjProperty::VISITORS)
  2752. visitors.insert(ObjectInstanceID(val));
  2753. }
  2754. void CTownBonus::onHeroVisit (const CGHeroInstance * h) const
  2755. {
  2756. ObjectInstanceID heroID = h->id;
  2757. if (town->hasBuilt(ID) && visitors.find(heroID) == visitors.end())
  2758. {
  2759. InfoWindow iw;
  2760. PrimarySkill::PrimarySkill what = PrimarySkill::ATTACK;
  2761. int val=0, mid=0;
  2762. switch (ID)
  2763. {
  2764. case BuildingID::SPECIAL_4:
  2765. switch(town->subID)
  2766. {
  2767. case ETownType::TOWER: //wall
  2768. what = PrimarySkill::KNOWLEDGE;
  2769. val = 1;
  2770. mid = 581;
  2771. iw.components.push_back (Component(Component::PRIM_SKILL, 3, 1, 0));
  2772. break;
  2773. case ETownType::INFERNO: //order of fire
  2774. what = PrimarySkill::SPELL_POWER;
  2775. val = 1;
  2776. mid = 582;
  2777. iw.components.push_back (Component(Component::PRIM_SKILL, 2, 1, 0));
  2778. break;
  2779. case ETownType::STRONGHOLD://hall of Valhalla
  2780. what = PrimarySkill::ATTACK;
  2781. val = 1;
  2782. mid = 584;
  2783. iw.components.push_back (Component(Component::PRIM_SKILL, 0, 1, 0));
  2784. break;
  2785. case ETownType::DUNGEON://academy of battle scholars
  2786. what = PrimarySkill::EXPERIENCE;
  2787. val = h->calculateXp(1000);
  2788. mid = 583;
  2789. iw.components.push_back (Component(Component::EXPERIENCE, 0, val, 0));
  2790. break;
  2791. }
  2792. break;
  2793. case BuildingID::SPECIAL_1:
  2794. switch(town->subID)
  2795. {
  2796. case ETownType::FORTRESS: //cage of warlords
  2797. what = PrimarySkill::DEFENSE;
  2798. val = 1;
  2799. mid = 585;
  2800. iw.components.push_back (Component(Component::PRIM_SKILL, 1, 1, 0));
  2801. break;
  2802. }
  2803. break;
  2804. }
  2805. assert(mid);
  2806. iw.player = cb->getOwner(heroID);
  2807. iw.text << VLC->generaltexth->allTexts[mid];
  2808. cb->showInfoDialog(&iw);
  2809. cb->changePrimSkill (cb->getHero(heroID), what, val);
  2810. town->addHeroToStructureVisitors(h, id);
  2811. }
  2812. }
  2813. const std::string & CGCreature::getHoverText() const
  2814. {
  2815. if(stacks.empty())
  2816. {
  2817. static const std::string errorValue("!!!INVALID_STACK!!!");
  2818. //should not happen...
  2819. logGlobal->errorStream() << "Invalid stack at tile " << pos << ": subID=" << subID << "; id=" << id;
  2820. return errorValue; // references to temporary are illegal - use pre-constructed string
  2821. }
  2822. MetaString ms;
  2823. int pom = stacks.begin()->second->getQuantityID();
  2824. pom = 172 + 3*pom;
  2825. ms.addTxt(MetaString::ARRAY_TXT,pom);
  2826. ms << " " ;
  2827. ms.addTxt(MetaString::CRE_PL_NAMES,subID);
  2828. ms.toString(hoverName);
  2829. if(const CGHeroInstance *selHero = cb->getSelectedHero(cb->getCurrentPlayer()))
  2830. {
  2831. std::vector<std::string> * texts = &VLC->generaltexth->threat;
  2832. hoverName += "\n\n ";
  2833. hoverName += (*texts)[0];
  2834. int choice;
  2835. double ratio = ((double)getArmyStrength() / selHero->getTotalStrength());
  2836. if (ratio < 0.1) choice = 1;
  2837. else if (ratio < 0.25) choice = 2;
  2838. else if (ratio < 0.6) choice = 3;
  2839. else if (ratio < 0.9) choice = 4;
  2840. else if (ratio < 1.1) choice = 5;
  2841. else if (ratio < 1.3) choice = 6;
  2842. else if (ratio < 1.8) choice = 7;
  2843. else if (ratio < 2.5) choice = 8;
  2844. else if (ratio < 4) choice = 9;
  2845. else if (ratio < 8) choice = 10;
  2846. else if (ratio < 20) choice = 11;
  2847. else choice = 12;
  2848. hoverName += (*texts)[choice];
  2849. }
  2850. return hoverName;
  2851. }
  2852. void CGCreature::onHeroVisit( const CGHeroInstance * h ) const
  2853. {
  2854. int action = takenAction(h);
  2855. switch( action ) //decide what we do...
  2856. {
  2857. case FIGHT:
  2858. fight(h);
  2859. break;
  2860. case FLEE: //flee
  2861. {
  2862. flee(h);
  2863. break;
  2864. }
  2865. case JOIN_FOR_FREE: //join for free
  2866. {
  2867. BlockingDialog ynd(true,false);
  2868. ynd.player = h->tempOwner;
  2869. ynd.text.addTxt(MetaString::ADVOB_TXT, 86);
  2870. ynd.text.addReplacement(MetaString::CRE_PL_NAMES, subID);
  2871. cb->showBlockingDialog(&ynd);
  2872. break;
  2873. }
  2874. default: //join for gold
  2875. {
  2876. assert(action > 0);
  2877. //ask if player agrees to pay gold
  2878. BlockingDialog ynd(true,false);
  2879. ynd.player = h->tempOwner;
  2880. std::string tmp = VLC->generaltexth->advobtxt[90];
  2881. boost::algorithm::replace_first(tmp,"%d",boost::lexical_cast<std::string>(getStackCount(SlotID(0))));
  2882. boost::algorithm::replace_first(tmp,"%d",boost::lexical_cast<std::string>(action));
  2883. boost::algorithm::replace_first(tmp,"%s",VLC->creh->creatures[subID]->namePl);
  2884. ynd.text << tmp;
  2885. cb->showBlockingDialog(&ynd);
  2886. break;
  2887. }
  2888. }
  2889. }
  2890. void CGCreature::initObj()
  2891. {
  2892. blockVisit = true;
  2893. switch(character)
  2894. {
  2895. case 0:
  2896. character = -4;
  2897. break;
  2898. case 1:
  2899. character = 1 + ran()%7;
  2900. break;
  2901. case 2:
  2902. character = 1 + ran()%10;
  2903. break;
  2904. case 3:
  2905. character = 4 + ran()%7;
  2906. break;
  2907. case 4:
  2908. character = 10;
  2909. break;
  2910. }
  2911. stacks[SlotID(0)]->setType(CreatureID(subID));
  2912. TQuantity &amount = stacks[SlotID(0)]->count;
  2913. CCreature &c = *VLC->creh->creatures[subID];
  2914. if(!amount)
  2915. {
  2916. if(c.ammMax == c.ammMin)
  2917. amount = c.ammMax;
  2918. else
  2919. amount = c.ammMin + (ran() % (c.ammMax - c.ammMin));
  2920. if(!amount) //armies with 0 creatures are illegal
  2921. {
  2922. logGlobal->warnStream() << "Problem: stack " << nodeName() << " cannot have 0 creatures. Check properties of " << c.nodeName();
  2923. amount = 1;
  2924. }
  2925. }
  2926. formation.randomFormation = rand();
  2927. temppower = stacks[SlotID(0)]->count * 1000;
  2928. refusedJoining = false;
  2929. }
  2930. void CGCreature::newTurn() const
  2931. {//Works only for stacks of single type of size up to 2 millions
  2932. if (stacks.begin()->second->count < VLC->modh->settings.CREEP_SIZE && cb->getDate(Date::DAY_OF_WEEK) == 1 && cb->getDate(Date::DAY) > 1)
  2933. {
  2934. ui32 power = temppower * (100 + VLC->modh->settings.WEEKLY_GROWTH)/100;
  2935. cb->setObjProperty(id, ObjProperty::MONSTER_COUNT, std::min (power/1000 , (ui32)VLC->modh->settings.CREEP_SIZE)); //set new amount
  2936. cb->setObjProperty(id, ObjProperty::MONSTER_POWER, power); //increase temppower
  2937. }
  2938. if (VLC->modh->modules.STACK_EXP)
  2939. cb->setObjProperty(id, ObjProperty::MONSTER_EXP, VLC->modh->settings.NEUTRAL_STACK_EXP); //for testing purpose
  2940. }
  2941. void CGCreature::setPropertyDer(ui8 what, ui32 val)
  2942. {
  2943. switch (what)
  2944. {
  2945. case ObjProperty::MONSTER_COUNT:
  2946. stacks[SlotID(0)]->count = val;
  2947. break;
  2948. case ObjProperty::MONSTER_POWER:
  2949. temppower = val;
  2950. break;
  2951. case ObjProperty::MONSTER_EXP:
  2952. giveStackExp(val);
  2953. break;
  2954. case ObjProperty::MONSTER_RESTORE_TYPE:
  2955. formation.basicType = val;
  2956. break;
  2957. case ObjProperty::MONSTER_REFUSED_JOIN:
  2958. refusedJoining = val;
  2959. break;
  2960. }
  2961. }
  2962. int CGCreature::takenAction(const CGHeroInstance *h, bool allowJoin) const
  2963. {
  2964. //calculate relative strength of hero and creatures armies
  2965. double relStrength = double(h->getTotalStrength()) / getArmyStrength();
  2966. int powerFactor;
  2967. if(relStrength >= 7)
  2968. powerFactor = 11;
  2969. else if(relStrength >= 1)
  2970. powerFactor = (int)(2*(relStrength-1));
  2971. else if(relStrength >= 0.5)
  2972. powerFactor = -1;
  2973. else if(relStrength >= 0.333)
  2974. powerFactor = -2;
  2975. else
  2976. powerFactor = -3;
  2977. std::set<CreatureID> myKindCres; //what creatures are the same kind as we
  2978. const CCreature * myCreature = VLC->creh->creatures[subID];
  2979. myKindCres.insert(myCreature->idNumber); //we
  2980. myKindCres.insert(myCreature->upgrades.begin(), myCreature->upgrades.end()); //our upgrades
  2981. for(ConstTransitivePtr<CCreature> &crea : VLC->creh->creatures)
  2982. {
  2983. if(vstd::contains(crea->upgrades, myCreature->idNumber)) //it's our base creatures
  2984. myKindCres.insert(crea->idNumber);
  2985. }
  2986. int count = 0, //how many creatures of similar kind has hero
  2987. totalCount = 0;
  2988. for (auto & elem : h->Slots())
  2989. {
  2990. if(vstd::contains(myKindCres,elem.second->type->idNumber))
  2991. count += elem.second->count;
  2992. totalCount += elem.second->count;
  2993. }
  2994. int sympathy = 0; // 0 if hero have no similar creatures
  2995. if(count)
  2996. sympathy++; // 1 - if hero have at least 1 similar creature
  2997. if(count*2 > totalCount)
  2998. sympathy++; // 2 - hero have similar creatures more that 50%
  2999. int charisma = powerFactor + h->getSecSkillLevel(SecondarySkill::DIPLOMACY) + sympathy;
  3000. if(charisma < character) //creatures will fight
  3001. return -2;
  3002. if (allowJoin)
  3003. {
  3004. if(h->getSecSkillLevel(SecondarySkill::DIPLOMACY) + sympathy + 1 >= character)
  3005. return 0; //join for free
  3006. else if(h->getSecSkillLevel(SecondarySkill::DIPLOMACY) * 2 + sympathy + 1 >= character)
  3007. return VLC->creh->creatures[subID]->cost[6] * getStackCount(SlotID(0)); //join for gold
  3008. }
  3009. //we are still here - creatures have not joined hero, flee or fight
  3010. if (charisma > character)
  3011. return -1; //flee
  3012. else
  3013. return -2; //fight
  3014. }
  3015. void CGCreature::fleeDecision(const CGHeroInstance *h, ui32 pursue) const
  3016. {
  3017. if(refusedJoining)
  3018. cb->setObjProperty(id, ObjProperty::MONSTER_REFUSED_JOIN, false);
  3019. if(pursue)
  3020. {
  3021. fight(h);
  3022. }
  3023. else
  3024. {
  3025. cb->removeObject(this);
  3026. }
  3027. }
  3028. void CGCreature::joinDecision(const CGHeroInstance *h, int cost, ui32 accept) const
  3029. {
  3030. if(!accept)
  3031. {
  3032. if(takenAction(h,false) == -1) //they flee
  3033. {
  3034. cb->setObjProperty(id, ObjProperty::MONSTER_REFUSED_JOIN, true);
  3035. flee(h);
  3036. }
  3037. else //they fight
  3038. {
  3039. showInfoDialog(h,87,0);//Insulted by your refusal of their offer, the monsters attack!
  3040. fight(h);
  3041. }
  3042. }
  3043. else //accepted
  3044. {
  3045. if (cb->getResource(h->tempOwner, Res::GOLD) < cost) //player don't have enough gold!
  3046. {
  3047. InfoWindow iw;
  3048. iw.player = h->tempOwner;
  3049. iw.text << std::pair<ui8,ui32>(1,29); //You don't have enough gold
  3050. cb->showInfoDialog(&iw);
  3051. //act as if player refused
  3052. joinDecision(h,cost,false);
  3053. return;
  3054. }
  3055. //take gold
  3056. if(cost)
  3057. cb->giveResource(h->tempOwner,Res::GOLD,-cost);
  3058. cb->tryJoiningArmy(this, h, true, true);
  3059. }
  3060. }
  3061. void CGCreature::fight( const CGHeroInstance *h ) const
  3062. {
  3063. //split stacks
  3064. //TODO: multiple creature types in a stack?
  3065. int basicType = stacks.begin()->second->type->idNumber;
  3066. cb->setObjProperty(id, ObjProperty::MONSTER_RESTORE_TYPE, basicType); //store info about creature stack
  3067. double relativePower = static_cast<double>(h->getTotalStrength()) / getArmyStrength();
  3068. int stacksCount;
  3069. //TODO: number depends on tile type
  3070. if (relativePower < 0.5)
  3071. {
  3072. stacksCount = 7;
  3073. }
  3074. else if (relativePower < 0.67)
  3075. {
  3076. stacksCount = 7;
  3077. }
  3078. else if (relativePower < 1)
  3079. {
  3080. stacksCount = 6;
  3081. }
  3082. else if (relativePower < 1.5)
  3083. {
  3084. stacksCount = 5;
  3085. }
  3086. else if (relativePower < 2)
  3087. {
  3088. stacksCount = 4;
  3089. }
  3090. else
  3091. {
  3092. stacksCount = 3;
  3093. }
  3094. int stackSize;
  3095. SlotID sourceSlot = stacks.begin()->first;
  3096. SlotID destSlot;
  3097. for (int stacksLeft = stacksCount; stacksLeft > 1; --stacksLeft)
  3098. {
  3099. stackSize = stacks.begin()->second->count / stacksLeft;
  3100. if (stackSize)
  3101. {
  3102. if ((destSlot = getFreeSlot()).validSlot())
  3103. cb->moveStack(StackLocation(this, sourceSlot), StackLocation(this, destSlot), stackSize);
  3104. else
  3105. {
  3106. logGlobal->warnStream() <<"Warning! Not enough empty slots to split stack!";
  3107. break;
  3108. }
  3109. }
  3110. else break;
  3111. }
  3112. if (stacksCount > 1)
  3113. {
  3114. if (formation.randomFormation % 100 < 50) //upgrade
  3115. {
  3116. SlotID slotId = SlotID(stacks.size() / 2);
  3117. if(ui32 upgradesSize = getStack(slotId).type->upgrades.size())
  3118. {
  3119. auto it = getStack(slotId).type->upgrades.cbegin(); //pick random in case there are more
  3120. std::advance (it, rand() % upgradesSize);
  3121. cb->changeStackType(StackLocation(this, slotId), VLC->creh->creatures[*it]);
  3122. }
  3123. }
  3124. }
  3125. cb->startBattleI(h, this);
  3126. }
  3127. void CGCreature::flee( const CGHeroInstance * h ) const
  3128. {
  3129. BlockingDialog ynd(true,false);
  3130. ynd.player = h->tempOwner;
  3131. ynd.text.addTxt(MetaString::ADVOB_TXT,91);
  3132. ynd.text.addReplacement(MetaString::CRE_PL_NAMES, subID);
  3133. cb->showBlockingDialog(&ynd);
  3134. }
  3135. void CGCreature::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  3136. {
  3137. if(result.winner==0)
  3138. {
  3139. cb->removeObject(this);
  3140. }
  3141. else
  3142. {
  3143. //int killedAmount=0;
  3144. //for(std::set<std::pair<ui32,si32> >::iterator i=result->casualties[1].begin(); i!=result->casualties[1].end(); i++)
  3145. // if(i->first == subID)
  3146. // killedAmount += i->second;
  3147. //cb->setAmount(id, slots.find(0)->second.second - killedAmount);
  3148. /*
  3149. MetaString ms;
  3150. int pom = slots.find(0)->second.getQuantityID();
  3151. pom = 174 + 3*pom + 1;
  3152. ms << std::pair<ui8,ui32>(6,pom) << " " << std::pair<ui8,ui32>(7,subID);
  3153. cb->setHoverName(id,&ms);
  3154. cb->setObjProperty(id, 11, slots.begin()->second.count * 1000);
  3155. */
  3156. //merge stacks into one
  3157. TSlots::const_iterator i;
  3158. CCreature * cre = VLC->creh->creatures[formation.basicType];
  3159. for (i = stacks.begin(); i != stacks.end(); i++)
  3160. {
  3161. if (cre->isMyUpgrade(i->second->type))
  3162. {
  3163. cb->changeStackType (StackLocation(this, i->first), cre); //un-upgrade creatures
  3164. }
  3165. }
  3166. //first stack has to be at slot 0 -> if original one got killed, move there first remaining stack
  3167. if(!hasStackAtSlot(SlotID(0)))
  3168. cb->moveStack(StackLocation(this, stacks.begin()->first), StackLocation(this, SlotID(0)), stacks.begin()->second->count);
  3169. while (stacks.size() > 1) //hopefully that's enough
  3170. {
  3171. // TODO it's either overcomplicated (if we assume there'll be only one stack) or buggy (if we allow multiple stacks... but that'll also cause troubles elsewhere)
  3172. i = stacks.end();
  3173. i--;
  3174. SlotID slot = getSlotFor(i->second->type);
  3175. if (slot == i->first) //no reason to move stack to its own slot
  3176. break;
  3177. else
  3178. cb->moveStack (StackLocation(this, i->first), StackLocation(this, slot), i->second->count);
  3179. }
  3180. cb->setObjProperty(id, ObjProperty::MONSTER_POWER, stacks.begin()->second->count * 1000); //remember casualties
  3181. }
  3182. }
  3183. void CGCreature::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  3184. {
  3185. auto action = takenAction(hero);
  3186. if(!refusedJoining && action >= JOIN_FOR_FREE) //higher means price
  3187. joinDecision(hero, action, answer);
  3188. else if(action != FIGHT)
  3189. fleeDecision(hero, answer);
  3190. else
  3191. assert(0);
  3192. }
  3193. void CGMine::onHeroVisit( const CGHeroInstance * h ) const
  3194. {
  3195. int relations = cb->gameState()->getPlayerRelations(h->tempOwner, tempOwner);
  3196. if(relations == 2) //we're visiting our mine
  3197. {
  3198. cb->showGarrisonDialog(id,h->id,true);
  3199. return;
  3200. }
  3201. else if (relations == 1)//ally
  3202. return;
  3203. if(stacksCount()) //Mine is guarded
  3204. {
  3205. BlockingDialog ynd(true,false);
  3206. ynd.player = h->tempOwner;
  3207. ynd.text.addTxt(MetaString::ADVOB_TXT, subID == 7 ? 84 : 187);
  3208. cb->showBlockingDialog(&ynd);
  3209. return;
  3210. }
  3211. flagMine(h->tempOwner);
  3212. }
  3213. void CGMine::newTurn() const
  3214. {
  3215. if(cb->getDate() == 1)
  3216. return;
  3217. if (tempOwner == PlayerColor::NEUTRAL)
  3218. return;
  3219. cb->giveResource(tempOwner, producedResource, producedQuantity);
  3220. }
  3221. void CGMine::initObj()
  3222. {
  3223. if(subID >= 7) //Abandoned Mine
  3224. {
  3225. //set guardians
  3226. int howManyTroglodytes = 100 + ran()%100;
  3227. auto troglodytes = new CStackInstance(CreatureID::TROGLODYTES, howManyTroglodytes);
  3228. putStack(SlotID(0), troglodytes);
  3229. //after map reading tempOwner placeholds bitmask for allowed resources
  3230. std::vector<Res::ERes> possibleResources;
  3231. for (int i = 0; i < PlayerColor::PLAYER_LIMIT_I; i++)
  3232. if(tempOwner.getNum() & 1<<i) //NOTE: reuse of tempOwner
  3233. possibleResources.push_back(static_cast<Res::ERes>(i));
  3234. assert(possibleResources.size());
  3235. producedResource = possibleResources[ran()%possibleResources.size()];
  3236. tempOwner = PlayerColor::NEUTRAL;
  3237. hoverName = VLC->generaltexth->mines[7].first + "\n" + VLC->generaltexth->allTexts[202] + " " + troglodytes->getQuantityTXT(false) + " " + troglodytes->type->namePl;
  3238. }
  3239. else
  3240. {
  3241. producedResource = static_cast<Res::ERes>(subID);
  3242. MetaString ms;
  3243. ms << std::pair<ui8,ui32>(9,producedResource);
  3244. if(tempOwner >= PlayerColor::PLAYER_LIMIT)
  3245. tempOwner = PlayerColor::NEUTRAL;
  3246. else
  3247. ms << " (" << std::pair<ui8,ui32>(6,23+tempOwner.getNum()) << ")";
  3248. ms.toString(hoverName);
  3249. }
  3250. producedQuantity = defaultResProduction();
  3251. }
  3252. void CGMine::flagMine(PlayerColor player) const
  3253. {
  3254. assert(tempOwner != player);
  3255. cb->setOwner(this, player); //not ours? flag it!
  3256. MetaString ms;
  3257. ms << std::pair<ui8,ui32>(9,subID) << "\n(" << std::pair<ui8,ui32>(6,23+player.getNum()) << ")";
  3258. if(subID == 7)
  3259. {
  3260. ms << "(%s)";
  3261. ms.addReplacement(MetaString::RES_NAMES, producedResource);
  3262. }
  3263. cb->setHoverName(this,&ms);
  3264. InfoWindow iw;
  3265. iw.soundID = soundBase::FLAGMINE;
  3266. iw.text.addTxt(MetaString::MINE_EVNTS,producedResource); //not use subID, abandoned mines uses default mine texts
  3267. iw.player = player;
  3268. iw.components.push_back(Component(Component::RESOURCE,producedResource,producedQuantity,-1));
  3269. cb->showInfoDialog(&iw);
  3270. }
  3271. ui32 CGMine::defaultResProduction()
  3272. {
  3273. switch(producedResource)
  3274. {
  3275. case Res::WOOD:
  3276. case Res::ORE:
  3277. return 2;
  3278. case Res::GOLD:
  3279. return 1000;
  3280. default:
  3281. return 1;
  3282. }
  3283. }
  3284. void CGMine::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  3285. {
  3286. if(result.winner == 0) //attacker won
  3287. {
  3288. if(subID == 7)
  3289. {
  3290. showInfoDialog(hero->tempOwner, 85, 0);
  3291. }
  3292. flagMine(hero->tempOwner);
  3293. }
  3294. }
  3295. void CGMine::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  3296. {
  3297. if(answer)
  3298. cb->startBattleI(hero, this);
  3299. }
  3300. void CGResource::initObj()
  3301. {
  3302. blockVisit = true;
  3303. hoverName = VLC->generaltexth->restypes[subID];
  3304. if(!amount)
  3305. {
  3306. switch(subID)
  3307. {
  3308. case 6:
  3309. amount = 500 + (ran()%6)*100;
  3310. break;
  3311. case 0: case 2:
  3312. amount = 6 + (ran()%5);
  3313. break;
  3314. default:
  3315. amount = 3 + (ran()%3);
  3316. break;
  3317. }
  3318. }
  3319. }
  3320. void CGResource::onHeroVisit( const CGHeroInstance * h ) const
  3321. {
  3322. if(stacksCount())
  3323. {
  3324. if(message.size())
  3325. {
  3326. BlockingDialog ynd(true,false);
  3327. ynd.player = h->getOwner();
  3328. ynd.text << message;
  3329. cb->showBlockingDialog(&ynd);
  3330. }
  3331. else
  3332. {
  3333. blockingDialogAnswered(h, true); //behave as if player accepted battle
  3334. }
  3335. }
  3336. else
  3337. {
  3338. if(message.length())
  3339. {
  3340. InfoWindow iw;
  3341. iw.player = h->tempOwner;
  3342. iw.text << message;
  3343. cb->showInfoDialog(&iw);
  3344. }
  3345. collectRes(h->getOwner());
  3346. }
  3347. }
  3348. void CGResource::collectRes( PlayerColor player ) const
  3349. {
  3350. cb->giveResource(player, static_cast<Res::ERes>(subID), amount);
  3351. ShowInInfobox sii;
  3352. sii.player = player;
  3353. sii.c = Component(Component::RESOURCE,subID,amount,0);
  3354. sii.text.addTxt(MetaString::ADVOB_TXT,113);
  3355. sii.text.addReplacement(MetaString::RES_NAMES, subID);
  3356. cb->showCompInfo(&sii);
  3357. cb->removeObject(this);
  3358. }
  3359. void CGResource::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  3360. {
  3361. if(result.winner == 0) //attacker won
  3362. collectRes(hero->getOwner());
  3363. }
  3364. void CGResource::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  3365. {
  3366. if(answer)
  3367. cb->startBattleI(hero, this);
  3368. }
  3369. void CGVisitableOPW::newTurn() const
  3370. {
  3371. if (cb->getDate(Date::DAY_OF_WEEK) == 1) //first day of week = 1
  3372. {
  3373. cb->setObjProperty(id, ObjProperty::VISITED, false);
  3374. MetaString ms; //set text to "not visited"
  3375. ms << std::pair<ui8,ui32>(3,ID) << " " << std::pair<ui8,ui32>(1,353);
  3376. cb->setHoverName(this,&ms);
  3377. }
  3378. }
  3379. bool CGVisitableOPW::wasVisited(PlayerColor player) const
  3380. {
  3381. return visited; //TODO: other players should see object as unvisited
  3382. }
  3383. void CGVisitableOPW::onHeroVisit( const CGHeroInstance * h ) const
  3384. {
  3385. int mid=0, sound = 0;
  3386. switch (ID)
  3387. {
  3388. case Obj::MYSTICAL_GARDEN:
  3389. sound = soundBase::experience;
  3390. mid = 92;
  3391. break;
  3392. case Obj::WINDMILL:
  3393. sound = soundBase::GENIE;
  3394. mid = 170;
  3395. break;
  3396. case Obj::WATER_WHEEL:
  3397. sound = soundBase::GENIE;
  3398. mid = 164;
  3399. break;
  3400. default:
  3401. assert(0);
  3402. }
  3403. if (visited)
  3404. {
  3405. if (ID!=Obj::WINDMILL)
  3406. mid++;
  3407. else
  3408. mid--;
  3409. showInfoDialog(h,mid,sound);
  3410. }
  3411. else
  3412. {
  3413. Component::EComponentType type = Component::RESOURCE;
  3414. Res::ERes sub=Res::WOOD;
  3415. int val=0;
  3416. switch (ID)
  3417. {
  3418. case Obj::MYSTICAL_GARDEN:
  3419. if (rand()%2)
  3420. {
  3421. sub = Res::GEMS;
  3422. val = 5;
  3423. }
  3424. else
  3425. {
  3426. sub = Res::GOLD;
  3427. val = 500;
  3428. }
  3429. break;
  3430. case Obj::WINDMILL:
  3431. mid = 170;
  3432. sub = static_cast<Res::ERes>((rand() % 5) + 1);
  3433. val = (rand() % 4) + 3;
  3434. break;
  3435. case Obj::WATER_WHEEL:
  3436. mid = 164;
  3437. sub = Res::GOLD;
  3438. if(cb->getDate(Date::DAY)<8)
  3439. val = 500;
  3440. else
  3441. val = 1000;
  3442. }
  3443. cb->giveResource(h->tempOwner, sub, val);
  3444. InfoWindow iw;
  3445. iw.soundID = sound;
  3446. iw.player = h->tempOwner;
  3447. iw.components.push_back(Component(type,sub,val,0));
  3448. iw.text.addTxt(MetaString::ADVOB_TXT,mid);
  3449. cb->showInfoDialog(&iw);
  3450. cb->setObjProperty(id, ObjProperty::VISITED, true);
  3451. MetaString ms; //set text to "visited"
  3452. ms.addTxt(MetaString::OBJ_NAMES,ID); ms << " "; ms.addTxt(MetaString::GENERAL_TXT,352);
  3453. cb->setHoverName(this,&ms);
  3454. }
  3455. }
  3456. void CGVisitableOPW::setPropertyDer( ui8 what, ui32 val )
  3457. {
  3458. if(what == ObjProperty::VISITED)
  3459. visited = val;
  3460. }
  3461. void CGTeleport::onHeroVisit( const CGHeroInstance * h ) const
  3462. {
  3463. ObjectInstanceID destinationid;
  3464. switch(ID)
  3465. {
  3466. case Obj::MONOLITH1: //one way - find corresponding exit monolith
  3467. if(vstd::contains(objs,Obj::MONOLITH2) && vstd::contains(objs[Obj::MONOLITH2],subID) && objs[Obj::MONOLITH2][subID].size())
  3468. destinationid = objs[Obj::MONOLITH2][subID][rand()%objs[Obj::MONOLITH2][subID].size()];
  3469. else
  3470. logGlobal->warnStream() << "Cannot find corresponding exit monolith for "<< id;
  3471. break;
  3472. case Obj::MONOLITH3://two way monolith - pick any other one
  3473. case Obj::WHIRLPOOL: //Whirlpool
  3474. if(vstd::contains(objs,ID) && vstd::contains(objs[ID],subID) && objs[ID][subID].size()>1)
  3475. {
  3476. while ((destinationid = objs[ID][subID][rand()%objs[ID][subID].size()]) == id); //choose another exit
  3477. if (ID == Obj::WHIRLPOOL)
  3478. {
  3479. if (!h->hasBonusOfType(Bonus::WHIRLPOOL_PROTECTION))
  3480. {
  3481. if (h->Slots().size() > 1 || h->Slots().begin()->second->count > 1)
  3482. { //we can't remove last unit
  3483. SlotID targetstack = h->Slots().begin()->first; //slot numbers may vary
  3484. for(auto i = h->Slots().rbegin(); i != h->Slots().rend(); i++)
  3485. {
  3486. if (h->getPower(targetstack) > h->getPower(i->first))
  3487. {
  3488. targetstack = (i->first);
  3489. }
  3490. }
  3491. TQuantity countToTake = h->getStackCount(targetstack) * 0.5;
  3492. vstd::amax(countToTake, 1);
  3493. InfoWindow iw;
  3494. iw.player = h->tempOwner;
  3495. iw.text.addTxt (MetaString::ADVOB_TXT, 168);
  3496. iw.components.push_back (Component(CStackBasicDescriptor(h->getCreature(targetstack), countToTake)));
  3497. cb->showInfoDialog(&iw);
  3498. cb->changeStackCount(StackLocation(h, targetstack), -countToTake);
  3499. }
  3500. }
  3501. }
  3502. }
  3503. else
  3504. logGlobal->warnStream() << "Cannot find corresponding exit monolith for "<< id;
  3505. break;
  3506. case Obj::SUBTERRANEAN_GATE: //find nearest subterranean gate on the other level
  3507. {
  3508. destinationid = getMatchingGate(id);
  3509. if(destinationid == ObjectInstanceID()) //no exit
  3510. {
  3511. showInfoDialog(h,153,0);//Just inside the entrance you find a large pile of rubble blocking the tunnel. You leave discouraged.
  3512. }
  3513. break;
  3514. }
  3515. }
  3516. if(destinationid == ObjectInstanceID())
  3517. {
  3518. logGlobal->warnStream() << "Cannot find exit... (obj at " << pos << ") :( ";
  3519. return;
  3520. }
  3521. if (ID == Obj::WHIRLPOOL)
  3522. {
  3523. std::set<int3> tiles = cb->getObj(destinationid)->getBlockedPos();
  3524. auto it = tiles.begin();
  3525. std::advance (it, rand() % tiles.size()); //picking random element of set is tiring
  3526. cb->moveHero (h->id, *it + int3(1,0,0), true);
  3527. }
  3528. else
  3529. cb->moveHero (h->id,CGHeroInstance::convertPosition(cb->getObj(destinationid)->pos,true) - getVisitableOffset(), true);
  3530. }
  3531. void CGTeleport::initObj()
  3532. {
  3533. int si = subID;
  3534. switch (ID)
  3535. {
  3536. case Obj::SUBTERRANEAN_GATE://ignore subterranean gates subid
  3537. case Obj::WHIRLPOOL:
  3538. {
  3539. si = 0;
  3540. break;
  3541. }
  3542. default:
  3543. break;
  3544. }
  3545. objs[ID][si].push_back(id);
  3546. }
  3547. void CGTeleport::postInit() //matches subterranean gates into pairs
  3548. {
  3549. //split on underground and surface gates
  3550. std::vector<const CGObjectInstance *> gatesSplit[2]; //surface and underground gates
  3551. for(auto & elem : objs[Obj::SUBTERRANEAN_GATE][0])
  3552. {
  3553. const CGObjectInstance *hlp = cb->getObj(elem);
  3554. gatesSplit[hlp->pos.z].push_back(hlp);
  3555. }
  3556. //sort by position
  3557. std::sort(gatesSplit[0].begin(), gatesSplit[0].end(), [](const CGObjectInstance * a, const CGObjectInstance * b)
  3558. {
  3559. return a->pos < b->pos;
  3560. });
  3561. for(size_t i = 0; i < gatesSplit[0].size(); i++)
  3562. {
  3563. const CGObjectInstance *cur = gatesSplit[0][i];
  3564. //find nearest underground exit
  3565. std::pair<int,double> best(-1,150000); //pair<pos_in_vector, distance>
  3566. for(int j = 0; j < gatesSplit[1].size(); j++)
  3567. {
  3568. const CGObjectInstance *checked = gatesSplit[1][j];
  3569. if(!checked)
  3570. continue;
  3571. double hlp = checked->pos.dist2d(cur->pos);
  3572. if(hlp < best.second)
  3573. {
  3574. best.first = j;
  3575. best.second = hlp;
  3576. }
  3577. }
  3578. if(best.first >= 0) //found pair
  3579. {
  3580. gates.push_back(std::make_pair(cur->id, gatesSplit[1][best.first]->id));
  3581. gatesSplit[1][best.first] = nullptr;
  3582. }
  3583. else
  3584. {
  3585. gates.push_back(std::make_pair(cur->id, ObjectInstanceID()));
  3586. }
  3587. }
  3588. objs.erase(Obj::SUBTERRANEAN_GATE);
  3589. }
  3590. ObjectInstanceID CGTeleport::getMatchingGate(ObjectInstanceID id)
  3591. {
  3592. for(auto & gate : gates)
  3593. {
  3594. if(gate.first == id)
  3595. return gate.second;
  3596. if(gate.second == id)
  3597. return gate.first;
  3598. }
  3599. return ObjectInstanceID();
  3600. }
  3601. void CGArtifact::initObj()
  3602. {
  3603. blockVisit = true;
  3604. if(ID == Obj::ARTIFACT)
  3605. {
  3606. hoverName = VLC->arth->artifacts[subID]->Name();
  3607. if(!storedArtifact->artType)
  3608. storedArtifact->setType(VLC->arth->artifacts[subID]);
  3609. }
  3610. if(ID == Obj::SPELL_SCROLL)
  3611. subID = 1;
  3612. assert(storedArtifact->artType);
  3613. assert(storedArtifact->getParentNodes().size());
  3614. //assert(storedArtifact->artType->id == subID); //this does not stop desync
  3615. }
  3616. void CGArtifact::onHeroVisit( const CGHeroInstance * h ) const
  3617. {
  3618. if(!stacksCount())
  3619. {
  3620. InfoWindow iw;
  3621. iw.player = h->tempOwner;
  3622. switch(ID)
  3623. {
  3624. case Obj::ARTIFACT:
  3625. {
  3626. iw.soundID = soundBase::treasure; //play sound only for non-scroll arts
  3627. iw.components.push_back(Component(Component::ARTIFACT,subID,0,0));
  3628. if(message.length())
  3629. iw.text << message;
  3630. else
  3631. {
  3632. if (VLC->arth->artifacts[subID]->EventText().size())
  3633. iw.text << std::pair<ui8, ui32> (MetaString::ART_EVNTS, subID);
  3634. else //fix for mod artifacts with no event text
  3635. {
  3636. iw.text.addTxt (MetaString::ADVOB_TXT, 183); //% has found treasure
  3637. iw.text.addReplacement (h->name);
  3638. }
  3639. }
  3640. }
  3641. break;
  3642. case Obj::SPELL_SCROLL:
  3643. {
  3644. int spellID = storedArtifact->getGivenSpellID();
  3645. iw.components.push_back (Component(Component::SPELL, spellID,0,0));
  3646. iw.text.addTxt (MetaString::ADVOB_TXT,135);
  3647. iw.text.addReplacement(MetaString::SPELL_NAME, spellID);
  3648. }
  3649. break;
  3650. }
  3651. cb->showInfoDialog(&iw);
  3652. pick(h);
  3653. }
  3654. else
  3655. {
  3656. if(message.size())
  3657. {
  3658. BlockingDialog ynd(true,false);
  3659. ynd.player = h->getOwner();
  3660. ynd.text << message;
  3661. cb->showBlockingDialog(&ynd);
  3662. }
  3663. else
  3664. {
  3665. blockingDialogAnswered(h, true);
  3666. }
  3667. }
  3668. }
  3669. void CGArtifact::pick(const CGHeroInstance * h) const
  3670. {
  3671. cb->giveHeroArtifact(h, storedArtifact, ArtifactPosition::FIRST_AVAILABLE);
  3672. cb->removeObject(this);
  3673. }
  3674. void CGArtifact::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  3675. {
  3676. if(result.winner == 0) //attacker won
  3677. pick(hero);
  3678. }
  3679. void CGArtifact::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  3680. {
  3681. if(answer)
  3682. cb->startBattleI(hero, this);
  3683. }
  3684. void CGPickable::initObj()
  3685. {
  3686. blockVisit = true;
  3687. switch(ID)
  3688. {
  3689. case Obj::CAMPFIRE:
  3690. val2 = (ran()%3) + 4; //4 - 6
  3691. val1 = val2 * 100;
  3692. type = ran()%6; //given resource
  3693. break;
  3694. case Obj::FLOTSAM:
  3695. switch(type = ran()%4)
  3696. {
  3697. case 0:
  3698. val1 = val2 = 0;
  3699. break;
  3700. case 1:
  3701. val1 = 5;
  3702. val2 = 0;
  3703. break;
  3704. case 2:
  3705. val1 = 5;
  3706. val2 = 200;
  3707. break;
  3708. case 3:
  3709. val1 = 10;
  3710. val2 = 500;
  3711. break;
  3712. }
  3713. break;
  3714. case Obj::SEA_CHEST:
  3715. {
  3716. int hlp = ran()%100;
  3717. if(hlp < 20)
  3718. {
  3719. val1 = 0;
  3720. type = 0;
  3721. }
  3722. else if(hlp < 90)
  3723. {
  3724. val1 = 1500;
  3725. type = 2;
  3726. }
  3727. else
  3728. {
  3729. val1 = 1000;
  3730. val2 = cb->getRandomArt (CArtifact::ART_TREASURE);
  3731. type = 1;
  3732. }
  3733. }
  3734. break;
  3735. case Obj::SHIPWRECK_SURVIVOR:
  3736. {
  3737. int hlp = ran()%100;
  3738. if(hlp < 55)
  3739. val1 = cb->getRandomArt (CArtifact::ART_TREASURE);
  3740. else if(hlp < 75)
  3741. val1 = cb->getRandomArt (CArtifact::ART_MINOR);
  3742. else if(hlp < 95)
  3743. val1 = cb->getRandomArt (CArtifact::ART_MAJOR);
  3744. else
  3745. val1 = cb->getRandomArt (CArtifact::ART_RELIC);
  3746. }
  3747. break;
  3748. case Obj::TREASURE_CHEST:
  3749. {
  3750. int hlp = ran()%100;
  3751. if(hlp >= 95)
  3752. {
  3753. type = 1;
  3754. val1 = cb->getRandomArt (CArtifact::ART_TREASURE);
  3755. return;
  3756. }
  3757. else if (hlp >= 65)
  3758. {
  3759. val1 = 2000;
  3760. }
  3761. else if(hlp >= 33)
  3762. {
  3763. val1 = 1500;
  3764. }
  3765. else
  3766. {
  3767. val1 = 1000;
  3768. }
  3769. val2 = val1 - 500;
  3770. type = 0;
  3771. break;
  3772. }
  3773. }
  3774. }
  3775. void CGPickable::onHeroVisit( const CGHeroInstance * h ) const
  3776. {
  3777. switch(ID)
  3778. {
  3779. case Obj::CAMPFIRE:
  3780. {
  3781. cb->giveResource(h->tempOwner,static_cast<Res::ERes>(type),val2); //non-gold resource
  3782. cb->giveResource(h->tempOwner,Res::GOLD,val1);//gold
  3783. InfoWindow iw;
  3784. iw.soundID = soundBase::experience;
  3785. iw.player = h->tempOwner;
  3786. iw.components.push_back(Component(Component::RESOURCE,Res::GOLD,val1,0));
  3787. iw.components.push_back(Component(Component::RESOURCE,type,val2,0));
  3788. iw.text.addTxt(MetaString::ADVOB_TXT,23);
  3789. cb->showInfoDialog(&iw);
  3790. break;
  3791. }
  3792. case Obj::FLOTSAM:
  3793. {
  3794. cb->giveResource(h->tempOwner,Res::WOOD,val1); //wood
  3795. cb->giveResource(h->tempOwner,Res::GOLD,val2);//gold
  3796. InfoWindow iw;
  3797. iw.soundID = soundBase::GENIE;
  3798. iw.player = h->tempOwner;
  3799. if(val1)
  3800. iw.components.push_back(Component(Component::RESOURCE,Res::WOOD,val1,0));
  3801. if(val2)
  3802. iw.components.push_back(Component(Component::RESOURCE,Res::GOLD,val2,0));
  3803. iw.text.addTxt(MetaString::ADVOB_TXT, 51+type);
  3804. cb->showInfoDialog(&iw);
  3805. break;
  3806. }
  3807. case Obj::SEA_CHEST:
  3808. {
  3809. InfoWindow iw;
  3810. iw.soundID = soundBase::chest;
  3811. iw.player = h->tempOwner;
  3812. iw.text.addTxt(MetaString::ADVOB_TXT, 116 + type);
  3813. if(val1) //there is gold
  3814. {
  3815. iw.components.push_back(Component(Component::RESOURCE,Res::GOLD,val1,0));
  3816. cb->giveResource(h->tempOwner,Res::GOLD,val1);
  3817. }
  3818. if(type == 1) //art
  3819. {
  3820. //TODO: what if no space in backpack?
  3821. iw.components.push_back(Component(Component::ARTIFACT, val2, 1, 0));
  3822. iw.text.addReplacement(MetaString::ART_NAMES, val2);
  3823. cb->giveHeroNewArtifact(h, VLC->arth->artifacts[val2],ArtifactPosition::FIRST_AVAILABLE);
  3824. }
  3825. cb->showInfoDialog(&iw);
  3826. break;
  3827. }
  3828. case Obj::SHIPWRECK_SURVIVOR:
  3829. {
  3830. InfoWindow iw;
  3831. iw.soundID = soundBase::experience;
  3832. iw.player = h->tempOwner;
  3833. iw.components.push_back(Component(Component::ARTIFACT,val1,1,0));
  3834. iw.text.addTxt(MetaString::ADVOB_TXT, 125);
  3835. iw.text.addReplacement(MetaString::ART_NAMES, val1);
  3836. cb->giveHeroNewArtifact(h, VLC->arth->artifacts[val1],ArtifactPosition::FIRST_AVAILABLE);
  3837. cb->showInfoDialog(&iw);
  3838. break;
  3839. }
  3840. case Obj::TREASURE_CHEST:
  3841. {
  3842. if (subID) //not OH3 treasure chest
  3843. {
  3844. logGlobal->warnStream() << "Not supported WoG treasure chest!";
  3845. return;
  3846. }
  3847. if(type) //there is an artifact
  3848. {
  3849. cb->giveHeroNewArtifact(h, VLC->arth->artifacts[val1],ArtifactPosition::FIRST_AVAILABLE);
  3850. InfoWindow iw;
  3851. iw.soundID = soundBase::treasure;
  3852. iw.player = h->tempOwner;
  3853. iw.components.push_back(Component(Component::ARTIFACT,val1,1,0));
  3854. iw.text.addTxt(MetaString::ADVOB_TXT,145);
  3855. iw.text.addReplacement(MetaString::ART_NAMES, val1);
  3856. cb->showInfoDialog(&iw);
  3857. break;
  3858. }
  3859. else
  3860. {
  3861. BlockingDialog sd(false,true);
  3862. sd.player = h->tempOwner;
  3863. sd.text.addTxt(MetaString::ADVOB_TXT,146);
  3864. sd.components.push_back(Component(Component::RESOURCE,Res::GOLD,val1,0));
  3865. TExpType expVal = h->calculateXp(val2);
  3866. sd.components.push_back(Component(Component::EXPERIENCE,0,expVal, 0));
  3867. sd.soundID = soundBase::chest;
  3868. cb->showBlockingDialog(&sd);
  3869. return;
  3870. }
  3871. }
  3872. }
  3873. cb->removeObject(this);
  3874. }
  3875. void CGPickable::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  3876. {
  3877. switch(answer)
  3878. {
  3879. case 1: //player pick gold
  3880. cb->giveResource(hero->tempOwner, Res::GOLD, val1);
  3881. break;
  3882. case 2: //player pick exp
  3883. cb->changePrimSkill(hero, PrimarySkill::EXPERIENCE, hero->calculateXp(val2));
  3884. break;
  3885. default:
  3886. throw std::runtime_error("Unhandled treasure choice");
  3887. }
  3888. cb->removeObject(this);
  3889. }
  3890. bool CQuest::checkQuest (const CGHeroInstance * h) const
  3891. {
  3892. switch (missionType)
  3893. {
  3894. case MISSION_NONE:
  3895. return true;
  3896. case MISSION_LEVEL:
  3897. if (m13489val <= h->level)
  3898. return true;
  3899. return false;
  3900. case MISSION_PRIMARY_STAT:
  3901. for (int i = 0; i < GameConstants::PRIMARY_SKILLS; ++i)
  3902. {
  3903. if (h->getPrimSkillLevel(static_cast<PrimarySkill::PrimarySkill>(i)) < m2stats[i])
  3904. return false;
  3905. }
  3906. return true;
  3907. case MISSION_KILL_HERO:
  3908. case MISSION_KILL_CREATURE:
  3909. if (!h->cb->getObjByQuestIdentifier(m13489val))
  3910. return true;
  3911. return false;
  3912. case MISSION_ART:
  3913. for (auto & elem : m5arts)
  3914. {
  3915. if (h->hasArt(elem))
  3916. continue;
  3917. return false; //if the artifact was not found
  3918. }
  3919. return true;
  3920. case MISSION_ARMY:
  3921. {
  3922. std::vector<CStackBasicDescriptor>::const_iterator cre;
  3923. TSlots::const_iterator it;
  3924. ui32 count;
  3925. for (cre = m6creatures.begin(); cre != m6creatures.end(); ++cre)
  3926. {
  3927. for (count = 0, it = h->Slots().begin(); it != h->Slots().end(); ++it)
  3928. {
  3929. if (it->second->type == cre->type)
  3930. count += it->second->count;
  3931. }
  3932. if (count < cre->count) //not enough creatures of this kind
  3933. return false;
  3934. }
  3935. }
  3936. return true;
  3937. case MISSION_RESOURCES:
  3938. for (Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, +1)) //including Mithril ?
  3939. { //Quest has no direct access to callback
  3940. if (h->cb->getResource (h->tempOwner, i) < m7resources[i])
  3941. return false;
  3942. }
  3943. return true;
  3944. case MISSION_HERO:
  3945. if (m13489val == h->type->ID.getNum())
  3946. return true;
  3947. return false;
  3948. case MISSION_PLAYER:
  3949. if (m13489val == h->getOwner().getNum())
  3950. return true;
  3951. return false;
  3952. default:
  3953. return false;
  3954. }
  3955. }
  3956. void CQuest::getVisitText (MetaString &iwText, std::vector<Component> &components, bool isCustom, bool firstVisit, const CGHeroInstance * h) const
  3957. {
  3958. std::string text;
  3959. bool failRequirements = (h ? !checkQuest(h) : true);
  3960. if (firstVisit)
  3961. {
  3962. isCustom = isCustomFirst;
  3963. iwText << (text = firstVisitText);
  3964. }
  3965. else if (failRequirements)
  3966. {
  3967. isCustom = isCustomNext;
  3968. iwText << (text = nextVisitText);
  3969. }
  3970. switch (missionType)
  3971. {
  3972. case MISSION_LEVEL:
  3973. components.push_back(Component (Component::EXPERIENCE, 0, m13489val, 0));
  3974. if (!isCustom)
  3975. iwText.addReplacement(m13489val);
  3976. break;
  3977. case MISSION_PRIMARY_STAT:
  3978. {
  3979. MetaString loot;
  3980. for (int i = 0; i < 4; ++i)
  3981. {
  3982. if (m2stats[i])
  3983. {
  3984. components.push_back(Component (Component::PRIM_SKILL, i, m2stats[i], 0));
  3985. loot << "%d %s";
  3986. loot.addReplacement(m2stats[i]);
  3987. loot.addReplacement(VLC->generaltexth->primarySkillNames[i]);
  3988. }
  3989. }
  3990. if (!isCustom)
  3991. iwText.addReplacement(loot.buildList());
  3992. }
  3993. break;
  3994. case MISSION_KILL_HERO:
  3995. components.push_back(Component(Component::HERO, heroPortrait, 0, 0));
  3996. if (!isCustom)
  3997. addReplacements(iwText, text);
  3998. break;
  3999. case MISSION_HERO:
  4000. components.push_back(Component (Component::HERO, m13489val, 0, 0));
  4001. if (!isCustom)
  4002. iwText.addReplacement(VLC->heroh->heroes[m13489val]->name);
  4003. break;
  4004. case MISSION_KILL_CREATURE:
  4005. {
  4006. components.push_back(Component(stackToKill));
  4007. if (!isCustom)
  4008. {
  4009. addReplacements(iwText, text);
  4010. }
  4011. }
  4012. break;
  4013. case MISSION_ART:
  4014. {
  4015. MetaString loot;
  4016. for (auto & elem : m5arts)
  4017. {
  4018. components.push_back(Component (Component::ARTIFACT, elem, 0, 0));
  4019. loot << "%s";
  4020. loot.addReplacement(MetaString::ART_NAMES, elem);
  4021. }
  4022. if (!isCustom)
  4023. iwText.addReplacement(loot.buildList());
  4024. }
  4025. break;
  4026. case MISSION_ARMY:
  4027. {
  4028. MetaString loot;
  4029. for (auto & elem : m6creatures)
  4030. {
  4031. components.push_back(Component(elem));
  4032. loot << "%s";
  4033. loot.addReplacement(elem);
  4034. }
  4035. if (!isCustom)
  4036. iwText.addReplacement(loot.buildList());
  4037. }
  4038. break;
  4039. case MISSION_RESOURCES:
  4040. {
  4041. MetaString loot;
  4042. for (int i = 0; i < 7; ++i)
  4043. {
  4044. if (m7resources[i])
  4045. {
  4046. components.push_back(Component (Component::RESOURCE, i, m7resources[i], 0));
  4047. loot << "%d %s";
  4048. loot.addReplacement(m7resources[i]);
  4049. loot.addReplacement(MetaString::RES_NAMES, i);
  4050. }
  4051. }
  4052. if (!isCustom)
  4053. iwText.addReplacement(loot.buildList());
  4054. }
  4055. break;
  4056. case MISSION_PLAYER:
  4057. components.push_back(Component (Component::FLAG, m13489val, 0, 0));
  4058. if (!isCustom)
  4059. iwText.addReplacement(VLC->generaltexth->colors[m13489val]);
  4060. break;
  4061. }
  4062. }
  4063. void CQuest::getRolloverText (MetaString &ms, bool onHover) const
  4064. {
  4065. if (onHover)
  4066. ms << "\n\n";
  4067. ms << VLC->generaltexth->quests[missionType-1][onHover ? 3 : 4][textOption];
  4068. switch (missionType)
  4069. {
  4070. case MISSION_LEVEL:
  4071. ms.addReplacement(m13489val);
  4072. break;
  4073. case MISSION_PRIMARY_STAT:
  4074. {
  4075. MetaString loot;
  4076. for (int i = 0; i < 4; ++i)
  4077. {
  4078. if (m2stats[i])
  4079. {
  4080. loot << "%d %s";
  4081. loot.addReplacement(m2stats[i]);
  4082. loot.addReplacement(VLC->generaltexth->primarySkillNames[i]);
  4083. }
  4084. }
  4085. ms.addReplacement(loot.buildList());
  4086. }
  4087. break;
  4088. case MISSION_KILL_HERO:
  4089. ms.addReplacement(heroName);
  4090. break;
  4091. case MISSION_KILL_CREATURE:
  4092. ms.addReplacement(stackToKill);
  4093. break;
  4094. case MISSION_ART:
  4095. {
  4096. MetaString loot;
  4097. for (auto & elem : m5arts)
  4098. {
  4099. loot << "%s";
  4100. loot.addReplacement(MetaString::ART_NAMES, elem);
  4101. }
  4102. ms.addReplacement(loot.buildList());
  4103. }
  4104. break;
  4105. case MISSION_ARMY:
  4106. {
  4107. MetaString loot;
  4108. for (auto & elem : m6creatures)
  4109. {
  4110. loot << "%s";
  4111. loot.addReplacement(elem);
  4112. }
  4113. ms.addReplacement(loot.buildList());
  4114. }
  4115. break;
  4116. case MISSION_RESOURCES:
  4117. {
  4118. MetaString loot;
  4119. for (int i = 0; i < 7; ++i)
  4120. {
  4121. if (m7resources[i])
  4122. {
  4123. loot << "%d %s";
  4124. loot.addReplacement(m7resources[i]);
  4125. loot.addReplacement(MetaString::RES_NAMES, i);
  4126. }
  4127. }
  4128. ms.addReplacement(loot.buildList());
  4129. }
  4130. break;
  4131. case MISSION_HERO:
  4132. ms.addReplacement(VLC->heroh->heroes[m13489val]->name);
  4133. break;
  4134. case MISSION_PLAYER:
  4135. ms.addReplacement(VLC->generaltexth->colors[m13489val]);
  4136. break;
  4137. default:
  4138. break;
  4139. }
  4140. }
  4141. void CQuest::getCompletionText (MetaString &iwText, std::vector<Component> &components, bool isCustom, const CGHeroInstance * h) const
  4142. {
  4143. iwText << completedText;
  4144. switch (missionType)
  4145. {
  4146. case CQuest::MISSION_LEVEL:
  4147. if (!isCustomComplete)
  4148. iwText.addReplacement(m13489val);
  4149. break;
  4150. case CQuest::MISSION_PRIMARY_STAT:
  4151. if (vstd::contains (completedText,'%')) //there's one case when there's nothing to replace
  4152. {
  4153. MetaString loot;
  4154. for (int i = 0; i < 4; ++i)
  4155. {
  4156. if (m2stats[i])
  4157. {
  4158. loot << "%d %s";
  4159. loot.addReplacement(m2stats[i]);
  4160. loot.addReplacement(VLC->generaltexth->primarySkillNames[i]);
  4161. }
  4162. }
  4163. if (!isCustomComplete)
  4164. iwText.addReplacement(loot.buildList());
  4165. }
  4166. break;
  4167. case CQuest::MISSION_ART:
  4168. {
  4169. MetaString loot;
  4170. for (auto & elem : m5arts)
  4171. {
  4172. loot << "%s";
  4173. loot.addReplacement(MetaString::ART_NAMES, elem);
  4174. }
  4175. if (!isCustomComplete)
  4176. iwText.addReplacement(loot.buildList());
  4177. }
  4178. break;
  4179. case CQuest::MISSION_ARMY:
  4180. {
  4181. MetaString loot;
  4182. for (auto & elem : m6creatures)
  4183. {
  4184. loot << "%s";
  4185. loot.addReplacement(elem);
  4186. }
  4187. if (!isCustomComplete)
  4188. iwText.addReplacement(loot.buildList());
  4189. }
  4190. break;
  4191. case CQuest::MISSION_RESOURCES:
  4192. {
  4193. MetaString loot;
  4194. for (int i = 0; i < 7; ++i)
  4195. {
  4196. if (m7resources[i])
  4197. {
  4198. loot << "%d %s";
  4199. loot.addReplacement(m7resources[i]);
  4200. loot.addReplacement(MetaString::RES_NAMES, i);
  4201. }
  4202. }
  4203. if (!isCustomComplete)
  4204. iwText.addReplacement(loot.buildList());
  4205. }
  4206. break;
  4207. case MISSION_KILL_HERO:
  4208. case MISSION_KILL_CREATURE:
  4209. if (!isCustomComplete)
  4210. addReplacements(iwText, completedText);
  4211. break;
  4212. case MISSION_HERO:
  4213. if (!isCustomComplete)
  4214. iwText.addReplacement(VLC->heroh->heroes[m13489val]->name);
  4215. break;
  4216. case MISSION_PLAYER:
  4217. if (!isCustomComplete)
  4218. iwText.addReplacement(VLC->generaltexth->colors[m13489val]);
  4219. break;
  4220. }
  4221. }
  4222. void CGSeerHut::setObjToKill()
  4223. {
  4224. if (quest->missionType == CQuest::MISSION_KILL_CREATURE)
  4225. {
  4226. quest->stackToKill = getCreatureToKill(false)->getStack(SlotID(0)); //FIXME: stacks tend to dissapear (desync?) on server :?
  4227. assert(quest->stackToKill.type);
  4228. quest->stackToKill.count = 0; //no count in info window
  4229. quest->stackDirection = checkDirection();
  4230. }
  4231. else if (quest->missionType == CQuest::MISSION_KILL_HERO)
  4232. {
  4233. quest->heroName = getHeroToKill(false)->name;
  4234. quest->heroPortrait = getHeroToKill(false)->portrait;
  4235. }
  4236. }
  4237. void CGSeerHut::init()
  4238. {
  4239. seerName = VLC->generaltexth->seerNames[ran()%VLC->generaltexth->seerNames.size()];
  4240. quest->textOption = ran() % 3;
  4241. }
  4242. void CGSeerHut::initObj()
  4243. {
  4244. init();
  4245. quest->progress = CQuest::NOT_ACTIVE;
  4246. if (quest->missionType)
  4247. {
  4248. if (!quest->isCustomFirst)
  4249. quest->firstVisitText = VLC->generaltexth->quests[quest->missionType-1][0][quest->textOption];
  4250. if (!quest->isCustomNext)
  4251. quest->nextVisitText = VLC->generaltexth->quests[quest->missionType-1][1][quest->textOption];
  4252. if (!quest->isCustomComplete)
  4253. quest->completedText = VLC->generaltexth->quests[quest->missionType-1][2][quest->textOption];
  4254. }
  4255. else
  4256. {
  4257. quest->progress = CQuest::COMPLETE;
  4258. quest->firstVisitText = VLC->generaltexth->seerEmpty[quest->textOption];
  4259. }
  4260. }
  4261. void CGSeerHut::getRolloverText (MetaString &text, bool onHover) const
  4262. {
  4263. quest->getRolloverText (text, onHover);//TODO: simplify?
  4264. if (!onHover)
  4265. text.addReplacement(seerName);
  4266. }
  4267. const std::string & CGSeerHut::getHoverText() const
  4268. {
  4269. switch (ID)
  4270. {
  4271. case Obj::SEER_HUT:
  4272. if (quest->progress != CQuest::NOT_ACTIVE)
  4273. {
  4274. hoverName = VLC->generaltexth->allTexts[347];
  4275. boost::algorithm::replace_first(hoverName,"%s", seerName);
  4276. }
  4277. else //just seer hut
  4278. hoverName = VLC->generaltexth->names[ID];
  4279. break;
  4280. case Obj::QUEST_GUARD:
  4281. hoverName = VLC->generaltexth->names[ID];
  4282. break;
  4283. default:
  4284. logGlobal->debugStream() << "unrecognized quest object";
  4285. }
  4286. if (quest->progress & quest->missionType) //rollover when the quest is active
  4287. {
  4288. MetaString ms;
  4289. getRolloverText (ms, true);
  4290. hoverName += ms.toString();
  4291. }
  4292. return hoverName;
  4293. }
  4294. void CQuest::addReplacements(MetaString &out, const std::string &base) const
  4295. {
  4296. switch(missionType)
  4297. {
  4298. case MISSION_KILL_CREATURE:
  4299. out.addReplacement(stackToKill);
  4300. if (std::count(base.begin(), base.end(), '%') == 2) //say where is placed monster
  4301. {
  4302. out.addReplacement(VLC->generaltexth->arraytxt[147+stackDirection]);
  4303. }
  4304. break;
  4305. case MISSION_KILL_HERO:
  4306. out.addReplacement(heroName);
  4307. break;
  4308. }
  4309. }
  4310. bool IQuestObject::checkQuest(const CGHeroInstance* h) const
  4311. {
  4312. return quest->checkQuest(h);
  4313. }
  4314. void IQuestObject::getVisitText (MetaString &text, std::vector<Component> &components, bool isCustom, bool FirstVisit, const CGHeroInstance * h) const
  4315. {
  4316. quest->getVisitText (text,components, isCustom, FirstVisit, h);
  4317. }
  4318. void CGSeerHut::getCompletionText(MetaString &text, std::vector<Component> &components, bool isCustom, const CGHeroInstance * h) const
  4319. {
  4320. quest->getCompletionText (text, components, isCustom, h);
  4321. switch (rewardType)
  4322. {
  4323. case EXPERIENCE: components.push_back(Component (Component::EXPERIENCE, 0, h->calculateXp(rVal), 0));
  4324. break;
  4325. case MANA_POINTS: components.push_back(Component (Component::PRIM_SKILL, 5, rVal, 0));
  4326. break;
  4327. case MORALE_BONUS: components.push_back(Component (Component::MORALE, 0, rVal, 0));
  4328. break;
  4329. case LUCK_BONUS: components.push_back(Component (Component::LUCK, 0, rVal, 0));
  4330. break;
  4331. case RESOURCES: components.push_back(Component (Component::RESOURCE, rID, rVal, 0));
  4332. break;
  4333. case PRIMARY_SKILL: components.push_back(Component (Component::PRIM_SKILL, rID, rVal, 0));
  4334. break;
  4335. case SECONDARY_SKILL: components.push_back(Component (Component::SEC_SKILL, rID, rVal, 0));
  4336. break;
  4337. case ARTIFACT: components.push_back(Component (Component::ARTIFACT, rID, 0, 0));
  4338. break;
  4339. case SPELL: components.push_back(Component (Component::SPELL, rID, 0, 0));
  4340. break;
  4341. case CREATURE: components.push_back(Component (Component::CREATURE, rID, rVal, 0));
  4342. break;
  4343. }
  4344. }
  4345. void CGSeerHut::setPropertyDer (ui8 what, ui32 val)
  4346. {
  4347. switch (what)
  4348. {
  4349. case 10:
  4350. quest->progress = static_cast<CQuest::Eprogress>(val);
  4351. break;
  4352. }
  4353. }
  4354. void CGSeerHut::newTurn() const
  4355. {
  4356. if (quest->lastDay >= 0 && quest->lastDay < cb->getDate()-1) //time is up
  4357. {
  4358. cb->setObjProperty (id, 10, CQuest::COMPLETE);
  4359. }
  4360. }
  4361. void CGSeerHut::onHeroVisit( const CGHeroInstance * h ) const
  4362. {
  4363. InfoWindow iw;
  4364. iw.player = h->getOwner();
  4365. if (quest->progress < CQuest::COMPLETE)
  4366. {
  4367. bool firstVisit = !quest->progress;
  4368. bool failRequirements = !checkQuest(h);
  4369. bool isCustom=false;
  4370. if (firstVisit)
  4371. {
  4372. isCustom = quest->isCustomFirst;
  4373. cb->setObjProperty (id, 10, CQuest::IN_PROGRESS);
  4374. AddQuest aq;
  4375. aq.quest = QuestInfo (quest, this, visitablePos());
  4376. aq.player = h->tempOwner;
  4377. cb->sendAndApply (&aq); //TODO: merge with setObjProperty?
  4378. }
  4379. else if (failRequirements)
  4380. {
  4381. isCustom = quest->isCustomNext;
  4382. }
  4383. if (firstVisit || failRequirements)
  4384. {
  4385. getVisitText (iw.text, iw.components, isCustom, firstVisit, h);
  4386. cb->showInfoDialog(&iw);
  4387. }
  4388. if (!failRequirements) // propose completion, also on first visit
  4389. {
  4390. BlockingDialog bd (true, false);
  4391. bd.player = h->getOwner();
  4392. bd.soundID = soundBase::QUEST;
  4393. getCompletionText (bd.text, bd.components, isCustom, h);
  4394. cb->showBlockingDialog (&bd);
  4395. return;
  4396. }
  4397. }
  4398. else
  4399. {
  4400. iw.text << VLC->generaltexth->seerEmpty[quest->textOption];
  4401. if (ID == Obj::SEER_HUT)
  4402. iw.text.addReplacement(seerName);
  4403. cb->showInfoDialog(&iw);
  4404. }
  4405. }
  4406. int CGSeerHut::checkDirection() const
  4407. {
  4408. int3 cord = getCreatureToKill()->pos;
  4409. if ((double)cord.x/(double)cb->getMapSize().x < 0.34) //north
  4410. {
  4411. if ((double)cord.y/(double)cb->getMapSize().y < 0.34) //northwest
  4412. return 8;
  4413. else if ((double)cord.y/(double)cb->getMapSize().y < 0.67) //north
  4414. return 1;
  4415. else //northeast
  4416. return 2;
  4417. }
  4418. else if ((double)cord.x/(double)cb->getMapSize().x < 0.67) //horizontal
  4419. {
  4420. if ((double)cord.y/(double)cb->getMapSize().y < 0.34) //west
  4421. return 7;
  4422. else if ((double)cord.y/(double)cb->getMapSize().y < 0.67) //central
  4423. return 9;
  4424. else //east
  4425. return 3;
  4426. }
  4427. else //south
  4428. {
  4429. if ((double)cord.y/(double)cb->getMapSize().y < 0.34) //southwest
  4430. return 6;
  4431. else if ((double)cord.y/(double)cb->getMapSize().y < 0.67) //south
  4432. return 5;
  4433. else //southeast
  4434. return 4;
  4435. }
  4436. }
  4437. void CGSeerHut::finishQuest(const CGHeroInstance * h, ui32 accept) const
  4438. {
  4439. if (accept)
  4440. {
  4441. switch (quest->missionType)
  4442. {
  4443. case CQuest::MISSION_ART:
  4444. for (auto & elem : quest->m5arts)
  4445. {
  4446. cb->removeArtifact(ArtifactLocation(h, h->getArtPos(elem, false)));
  4447. }
  4448. break;
  4449. case CQuest::MISSION_ARMY:
  4450. cb->takeCreatures(h->id, quest->m6creatures);
  4451. break;
  4452. case CQuest::MISSION_RESOURCES:
  4453. for (int i = 0; i < 7; ++i)
  4454. {
  4455. cb->giveResource(h->getOwner(), static_cast<Res::ERes>(i), -quest->m7resources[i]);
  4456. }
  4457. break;
  4458. default:
  4459. break;
  4460. }
  4461. cb->setObjProperty (id, 10, CQuest::COMPLETE); //mission complete
  4462. completeQuest(h); //make sure to remove QuestGuard at the very end
  4463. }
  4464. }
  4465. void CGSeerHut::completeQuest (const CGHeroInstance * h) const //reward
  4466. {
  4467. switch (rewardType)
  4468. {
  4469. case EXPERIENCE:
  4470. {
  4471. TExpType expVal = h->calculateXp(rVal);
  4472. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, expVal, false);
  4473. break;
  4474. }
  4475. case MANA_POINTS:
  4476. {
  4477. cb->setManaPoints(h->id, h->mana+rVal);
  4478. break;
  4479. }
  4480. case MORALE_BONUS: case LUCK_BONUS:
  4481. {
  4482. Bonus hb(Bonus::ONE_WEEK, (rewardType == 3 ? Bonus::MORALE : Bonus::LUCK),
  4483. Bonus::OBJECT, rVal, h->id.getNum(), "", -1);
  4484. GiveBonus gb;
  4485. gb.id = h->id.getNum();
  4486. gb.bonus = hb;
  4487. cb->giveHeroBonus(&gb);
  4488. }
  4489. break;
  4490. case RESOURCES:
  4491. cb->giveResource(h->getOwner(), static_cast<Res::ERes>(rID), rVal);
  4492. break;
  4493. case PRIMARY_SKILL:
  4494. cb->changePrimSkill(h, static_cast<PrimarySkill::PrimarySkill>(rID), rVal, false);
  4495. break;
  4496. case SECONDARY_SKILL:
  4497. cb->changeSecSkill(h, SecondarySkill(rID), rVal, false);
  4498. break;
  4499. case ARTIFACT:
  4500. cb->giveHeroNewArtifact(h, VLC->arth->artifacts[rID],ArtifactPosition::FIRST_AVAILABLE);
  4501. break;
  4502. case SPELL:
  4503. {
  4504. std::set<SpellID> spell;
  4505. spell.insert (SpellID(rID));
  4506. cb->changeSpells(h, true, spell);
  4507. }
  4508. break;
  4509. case CREATURE:
  4510. {
  4511. CCreatureSet creatures;
  4512. creatures.setCreature(SlotID(0), CreatureID(rID), rVal);
  4513. cb->giveCreatures(this, h, creatures, false);
  4514. }
  4515. break;
  4516. default:
  4517. break;
  4518. }
  4519. }
  4520. const CGHeroInstance * CGSeerHut::getHeroToKill(bool allowNull) const
  4521. {
  4522. const CGObjectInstance *o = cb->getObjByQuestIdentifier(quest->m13489val);
  4523. if(allowNull && !o)
  4524. return nullptr;
  4525. assert(o && (o->ID == Obj::HERO || o->ID == Obj::PRISON));
  4526. return static_cast<const CGHeroInstance*>(o);
  4527. }
  4528. const CGCreature * CGSeerHut::getCreatureToKill(bool allowNull) const
  4529. {
  4530. const CGObjectInstance *o = cb->getObjByQuestIdentifier(quest->m13489val);
  4531. if(allowNull && !o)
  4532. return nullptr;
  4533. assert(o && o->ID == Obj::MONSTER);
  4534. return static_cast<const CGCreature*>(o);
  4535. }
  4536. void CGSeerHut::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  4537. {
  4538. finishQuest(hero, answer);
  4539. }
  4540. void CGQuestGuard::init()
  4541. {
  4542. blockVisit = true;
  4543. quest->textOption = (ran() % 3) + 3; //3-5
  4544. }
  4545. void CGQuestGuard::completeQuest(const CGHeroInstance *h) const
  4546. {
  4547. cb->removeObject(this);
  4548. }
  4549. void CGWitchHut::initObj()
  4550. {
  4551. ability = allowedAbilities[ran()%allowedAbilities.size()];
  4552. }
  4553. void CGWitchHut::onHeroVisit( const CGHeroInstance * h ) const
  4554. {
  4555. InfoWindow iw;
  4556. iw.soundID = soundBase::gazebo;
  4557. iw.player = h->getOwner();
  4558. if(!wasVisited(h->tempOwner))
  4559. cb->setObjProperty(id, 10, h->tempOwner.getNum());
  4560. ui32 txt_id;
  4561. if(h->getSecSkillLevel(SecondarySkill(ability))) //you already know this skill
  4562. {
  4563. txt_id =172;
  4564. }
  4565. else if(!h->canLearnSkill()) //already all skills slots used
  4566. {
  4567. txt_id = 173;
  4568. }
  4569. else //give sec skill
  4570. {
  4571. iw.components.push_back(Component(Component::SEC_SKILL, ability, 1, 0));
  4572. txt_id = 171;
  4573. cb->changeSecSkill(h, SecondarySkill(ability), 1, true);
  4574. }
  4575. iw.text.addTxt(MetaString::ADVOB_TXT,txt_id);
  4576. iw.text.addReplacement(MetaString::SEC_SKILL_NAME, ability);
  4577. cb->showInfoDialog(&iw);
  4578. }
  4579. const std::string & CGWitchHut::getHoverText() const
  4580. {
  4581. hoverName = VLC->generaltexth->names[ID];
  4582. if(wasVisited(cb->getLocalPlayer()))
  4583. {
  4584. hoverName += "\n" + VLC->generaltexth->allTexts[356]; // + (learn %s)
  4585. boost::algorithm::replace_first(hoverName,"%s",VLC->generaltexth->skillName[ability]);
  4586. const CGHeroInstance *h = cb->getSelectedHero(cb->getCurrentPlayer());
  4587. if(h && h->getSecSkillLevel(SecondarySkill(ability))) //hero knows that ability
  4588. hoverName += "\n\n" + VLC->generaltexth->allTexts[357]; // (Already learned)
  4589. }
  4590. return hoverName;
  4591. }
  4592. bool CGBonusingObject::wasVisited (const CGHeroInstance * h) const
  4593. {
  4594. return h->hasBonusFrom(Bonus::OBJECT, ID);
  4595. }
  4596. void CGBonusingObject::onHeroVisit( const CGHeroInstance * h ) const
  4597. {
  4598. bool visited = h->hasBonusFrom(Bonus::OBJECT,ID);
  4599. int messageID=0;
  4600. int bonusMove = 0;
  4601. ui32 descr_id = 0;
  4602. InfoWindow iw;
  4603. iw.player = h->tempOwner;
  4604. GiveBonus gbonus;
  4605. gbonus.id = h->id.getNum();
  4606. gbonus.bonus.duration = Bonus::ONE_BATTLE;
  4607. gbonus.bonus.source = Bonus::OBJECT;
  4608. gbonus.bonus.sid = ID;
  4609. bool second = false;
  4610. Bonus secondBonus;
  4611. switch(ID)
  4612. {
  4613. case Obj::BUOY:
  4614. messageID = 21;
  4615. iw.soundID = soundBase::MORALE;
  4616. gbonus.bonus.type = Bonus::MORALE;
  4617. gbonus.bonus.val = +1;
  4618. descr_id = 94;
  4619. break;
  4620. case Obj::SWAN_POND:
  4621. messageID = 29;
  4622. iw.soundID = soundBase::LUCK;
  4623. gbonus.bonus.type = Bonus::LUCK;
  4624. gbonus.bonus.val = 2;
  4625. descr_id = 67;
  4626. bonusMove = -h->movement;
  4627. break;
  4628. case Obj::FAERIE_RING:
  4629. messageID = 49;
  4630. iw.soundID = soundBase::LUCK;
  4631. gbonus.bonus.type = Bonus::LUCK;
  4632. gbonus.bonus.val = 1;
  4633. descr_id = 71;
  4634. break;
  4635. case Obj::FOUNTAIN_OF_FORTUNE:
  4636. messageID = 55;
  4637. iw.soundID = soundBase::LUCK;
  4638. gbonus.bonus.type = Bonus::LUCK;
  4639. gbonus.bonus.val = rand()%5 - 1;
  4640. descr_id = 69;
  4641. gbonus.bdescr.addReplacement((gbonus.bonus.val<0 ? "-" : "+") + boost::lexical_cast<std::string>(gbonus.bonus.val));
  4642. break;
  4643. case Obj::IDOL_OF_FORTUNE:
  4644. messageID = 62;
  4645. iw.soundID = soundBase::experience;
  4646. gbonus.bonus.val = 1;
  4647. descr_id = 68;
  4648. if(cb->getDate(Date::DAY_OF_WEEK) == 7) //7th day of week
  4649. {
  4650. gbonus.bonus.type = Bonus::MORALE;
  4651. second = true;
  4652. secondBonus = gbonus.bonus;
  4653. secondBonus.type = Bonus::LUCK;
  4654. }
  4655. else
  4656. {
  4657. gbonus.bonus.type = (cb->getDate(Date::DAY_OF_WEEK)%2) ? Bonus::LUCK : Bonus::MORALE;
  4658. }
  4659. break;
  4660. case Obj::MERMAID:
  4661. messageID = 83;
  4662. iw.soundID = soundBase::LUCK;
  4663. gbonus.bonus.type = Bonus::LUCK;
  4664. gbonus.bonus.val = 1;
  4665. descr_id = 72;
  4666. break;
  4667. case Obj::RALLY_FLAG:
  4668. iw.soundID = soundBase::MORALE;
  4669. messageID = 111;
  4670. gbonus.bonus.type = Bonus::MORALE;
  4671. gbonus.bonus.val = 1;
  4672. descr_id = 102;
  4673. second = true;
  4674. secondBonus = gbonus.bonus;
  4675. secondBonus.type = Bonus::LUCK;
  4676. bonusMove = 400;
  4677. break;
  4678. case Obj::OASIS:
  4679. iw.soundID = soundBase::MORALE;
  4680. messageID = 95;
  4681. gbonus.bonus.type = Bonus::MORALE;
  4682. gbonus.bonus.val = 1;
  4683. descr_id = 95;
  4684. bonusMove = 800;
  4685. break;
  4686. case Obj::TEMPLE:
  4687. messageID = 140;
  4688. iw.soundID = soundBase::temple;
  4689. gbonus.bonus.type = Bonus::MORALE;
  4690. if(cb->getDate(Date::DAY_OF_WEEK)==7) //sunday
  4691. {
  4692. gbonus.bonus.val = 2;
  4693. descr_id = 97;
  4694. }
  4695. else
  4696. {
  4697. gbonus.bonus.val = 1;
  4698. descr_id = 96;
  4699. }
  4700. break;
  4701. case Obj::WATERING_HOLE:
  4702. iw.soundID = soundBase::MORALE;
  4703. messageID = 166;
  4704. gbonus.bonus.type = Bonus::MORALE;
  4705. gbonus.bonus.val = 1;
  4706. descr_id = 100;
  4707. bonusMove = 400;
  4708. break;
  4709. case Obj::FOUNTAIN_OF_YOUTH:
  4710. iw.soundID = soundBase::MORALE;
  4711. messageID = 57;
  4712. gbonus.bonus.type = Bonus::MORALE;
  4713. gbonus.bonus.val = 1;
  4714. descr_id = 103;
  4715. bonusMove = 400;
  4716. break;
  4717. case Obj::STABLES:
  4718. iw.soundID = soundBase::STORE;
  4719. bool someUpgradeDone = false;
  4720. for (auto i = h->Slots().begin(); i != h->Slots().end(); ++i)
  4721. {
  4722. if(i->second->type->idNumber == CreatureID::CAVALIER)
  4723. {
  4724. cb->changeStackType(StackLocation(h, i->first), VLC->creh->creatures[CreatureID::CHAMPION]);
  4725. someUpgradeDone = true;
  4726. }
  4727. }
  4728. if (someUpgradeDone)
  4729. {
  4730. messageID = 138;
  4731. iw.components.push_back(Component(Component::CREATURE,11,0,1));
  4732. }
  4733. else
  4734. messageID = 137;
  4735. gbonus.bonus.type = Bonus::LAND_MOVEMENT;
  4736. gbonus.bonus.val = 600;
  4737. bonusMove = 600;
  4738. gbonus.bonus.duration = Bonus::ONE_WEEK;
  4739. //gbonus.bdescr << std::pair<ui8,ui32>(6, 100);
  4740. break;
  4741. }
  4742. if (descr_id != 0)
  4743. gbonus.bdescr.addTxt(MetaString::ARRAY_TXT,descr_id);
  4744. assert(messageID);
  4745. if(visited)
  4746. {
  4747. if(ID==Obj::RALLY_FLAG || ID==Obj::OASIS || ID==Obj::MERMAID || ID==Obj::STABLES)
  4748. messageID--;
  4749. else
  4750. messageID++;
  4751. }
  4752. else
  4753. {
  4754. //TODO: fix if second bonus val != main bonus val
  4755. if(gbonus.bonus.type == Bonus::MORALE || secondBonus.type == Bonus::MORALE)
  4756. iw.components.push_back(Component(Component::MORALE,0,gbonus.bonus.val,0));
  4757. if(gbonus.bonus.type == Bonus::LUCK || secondBonus.type == Bonus::LUCK)
  4758. iw.components.push_back(Component(Component::LUCK,0,gbonus.bonus.val,0));
  4759. cb->giveHeroBonus(&gbonus);
  4760. if(second)
  4761. {
  4762. gbonus.bonus = secondBonus;
  4763. cb->giveHeroBonus(&gbonus);
  4764. }
  4765. if(bonusMove) //swan pond - take all move points, stables - give move point this day
  4766. {
  4767. SetMovePoints smp;
  4768. smp.hid = h->id;
  4769. smp.val = h->movement + bonusMove;
  4770. cb->setMovePoints(&smp);
  4771. }
  4772. }
  4773. iw.text.addTxt(MetaString::ADVOB_TXT,messageID);
  4774. cb->showInfoDialog(&iw);
  4775. }
  4776. const std::string & CGBonusingObject::getHoverText() const
  4777. {
  4778. const CGHeroInstance *h = cb->getSelectedHero(cb->getCurrentPlayer());
  4779. hoverName = VLC->generaltexth->names[ID];
  4780. if(h)
  4781. {
  4782. bool visited = h->hasBonusFrom(Bonus::OBJECT,ID);
  4783. hoverName += " " + visitedTxt(visited);
  4784. }
  4785. return hoverName;
  4786. }
  4787. void CGBonusingObject::initObj()
  4788. {
  4789. if(ID == Obj::BUOY || ID == Obj::MERMAID)
  4790. {
  4791. blockVisit = true;
  4792. }
  4793. }
  4794. void CGMagicSpring::onHeroVisit(const CGHeroInstance * h) const
  4795. {
  4796. int messageID;
  4797. if (!visited)
  4798. {
  4799. if (h->mana > h->manaLimit())
  4800. messageID = 76;
  4801. else
  4802. {
  4803. messageID = 74;
  4804. cb->setManaPoints (h->id, 2 * h->manaLimit());
  4805. cb->setObjProperty (id, ObjProperty::VISITED, true);
  4806. }
  4807. }
  4808. else
  4809. messageID = 75;
  4810. showInfoDialog(h,messageID,soundBase::GENIE);
  4811. }
  4812. const std::string & CGMagicSpring::getHoverText() const
  4813. {
  4814. hoverName = VLC->generaltexth->names[ID] + " " + visitedTxt(visited);
  4815. return hoverName;
  4816. }
  4817. void CGMagicWell::onHeroVisit( const CGHeroInstance * h ) const
  4818. {
  4819. int message;
  4820. if(h->hasBonusFrom(Bonus::OBJECT,ID)) //has already visited Well today
  4821. {
  4822. message = 78;//"A second drink at the well in one day will not help you."
  4823. }
  4824. else if(h->mana < h->manaLimit())
  4825. {
  4826. giveDummyBonus(h->id);
  4827. cb->setManaPoints(h->id,h->manaLimit());
  4828. message = 77;
  4829. }
  4830. else
  4831. {
  4832. message = 79;
  4833. }
  4834. showInfoDialog(h,message,soundBase::faerie);
  4835. }
  4836. const std::string & CGMagicWell::getHoverText() const
  4837. {
  4838. getNameVis(hoverName);
  4839. return hoverName;
  4840. }
  4841. void CGPandoraBox::initObj()
  4842. {
  4843. blockVisit = (ID==Obj::PANDORAS_BOX); //block only if it's really pandora's box (events also derive from that class)
  4844. hasGuardians = stacks.size();
  4845. }
  4846. void CGPandoraBox::onHeroVisit(const CGHeroInstance * h) const
  4847. {
  4848. BlockingDialog bd (true, false);
  4849. bd.player = h->getOwner();
  4850. bd.soundID = soundBase::QUEST;
  4851. bd.text.addTxt (MetaString::ADVOB_TXT, 14);
  4852. cb->showBlockingDialog (&bd);
  4853. }
  4854. void CGPandoraBox::giveContentsUpToExp(const CGHeroInstance *h) const
  4855. {
  4856. cb->removeAfterVisit(this);
  4857. InfoWindow iw;
  4858. iw.player = h->getOwner();
  4859. bool changesPrimSkill = false;
  4860. for (auto & elem : primskills)
  4861. {
  4862. if(elem)
  4863. {
  4864. changesPrimSkill = true;
  4865. break;
  4866. }
  4867. }
  4868. if(gainedExp || changesPrimSkill || abilities.size())
  4869. {
  4870. TExpType expVal = h->calculateXp(gainedExp);
  4871. //getText(iw,afterBattle,175,h); //wtf?
  4872. iw.text.addTxt(MetaString::ADVOB_TXT, 175); //%s learns something
  4873. iw.text.addReplacement(h->name);
  4874. if(expVal)
  4875. iw.components.push_back(Component(Component::EXPERIENCE,0,expVal,0));
  4876. for(int i=0; i<primskills.size(); i++)
  4877. if(primskills[i])
  4878. iw.components.push_back(Component(Component::PRIM_SKILL,i,primskills[i],0));
  4879. for(int i=0; i<abilities.size(); i++)
  4880. iw.components.push_back(Component(Component::SEC_SKILL,abilities[i],abilityLevels[i],0));
  4881. cb->showInfoDialog(&iw);
  4882. //give sec skills
  4883. for(int i=0; i<abilities.size(); i++)
  4884. {
  4885. int curLev = h->getSecSkillLevel(abilities[i]);
  4886. if( (curLev && curLev < abilityLevels[i]) || (h->canLearnSkill() ))
  4887. {
  4888. cb->changeSecSkill(h,abilities[i],abilityLevels[i],true);
  4889. }
  4890. }
  4891. //give prim skills
  4892. for(int i=0; i<primskills.size(); i++)
  4893. if(primskills[i])
  4894. cb->changePrimSkill(h,static_cast<PrimarySkill::PrimarySkill>(i),primskills[i],false);
  4895. assert(!cb->isVisitCoveredByAnotherQuery(this, h));
  4896. //give exp
  4897. if(expVal)
  4898. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, expVal, false);
  4899. }
  4900. if(!cb->isVisitCoveredByAnotherQuery(this, h))
  4901. giveContentsAfterExp(h);
  4902. //Otherwise continuation occurs via post-level-up callback.
  4903. }
  4904. void CGPandoraBox::giveContentsAfterExp(const CGHeroInstance *h) const
  4905. {
  4906. bool hadGuardians = hasGuardians; //copy, because flag will be emptied after issuing first post-battle message
  4907. std::string msg = message; //in case box is removed in the meantime
  4908. InfoWindow iw;
  4909. iw.player = h->getOwner();
  4910. if(spells.size())
  4911. {
  4912. std::set<SpellID> spellsToGive;
  4913. iw.components.clear();
  4914. if (spells.size() > 1)
  4915. {
  4916. iw.text.addTxt(MetaString::ADVOB_TXT, 188); //%s learns spells
  4917. }
  4918. else
  4919. {
  4920. iw.text.addTxt(MetaString::ADVOB_TXT, 184); //%s learns a spell
  4921. }
  4922. iw.text.addReplacement(h->name);
  4923. std::vector<ConstTransitivePtr<CSpell> > * sp = &VLC->spellh->spells;
  4924. for(auto i=spells.cbegin(); i != spells.cend(); i++)
  4925. {
  4926. if ((*sp)[*i]->level <= h->getSecSkillLevel(SecondarySkill::WISDOM) + 2) //enough wisdom
  4927. {
  4928. iw.components.push_back(Component(Component::SPELL,*i,0,0));
  4929. spellsToGive.insert(*i);
  4930. }
  4931. }
  4932. if(spellsToGive.size())
  4933. {
  4934. cb->changeSpells(h,true,spellsToGive);
  4935. cb->showInfoDialog(&iw);
  4936. }
  4937. }
  4938. if(manaDiff)
  4939. {
  4940. getText(iw,hadGuardians,manaDiff,176,177,h);
  4941. iw.components.push_back(Component(Component::PRIM_SKILL,5,manaDiff,0));
  4942. cb->showInfoDialog(&iw);
  4943. cb->setManaPoints(h->id, h->mana + manaDiff);
  4944. }
  4945. if(moraleDiff)
  4946. {
  4947. getText(iw,hadGuardians,moraleDiff,178,179,h);
  4948. iw.components.push_back(Component(Component::MORALE,0,moraleDiff,0));
  4949. cb->showInfoDialog(&iw);
  4950. GiveBonus gb;
  4951. gb.bonus = Bonus(Bonus::ONE_BATTLE,Bonus::MORALE,Bonus::OBJECT,moraleDiff,id.getNum(),"");
  4952. gb.id = h->id.getNum();
  4953. cb->giveHeroBonus(&gb);
  4954. }
  4955. if(luckDiff)
  4956. {
  4957. getText(iw,hadGuardians,luckDiff,180,181,h);
  4958. iw.components.push_back(Component(Component::LUCK,0,luckDiff,0));
  4959. cb->showInfoDialog(&iw);
  4960. GiveBonus gb;
  4961. gb.bonus = Bonus(Bonus::ONE_BATTLE,Bonus::LUCK,Bonus::OBJECT,luckDiff,id.getNum(),"");
  4962. gb.id = h->id.getNum();
  4963. cb->giveHeroBonus(&gb);
  4964. }
  4965. iw.components.clear();
  4966. iw.text.clear();
  4967. for(int i=0; i<resources.size(); i++)
  4968. {
  4969. if(resources[i] < 0)
  4970. iw.components.push_back(Component(Component::RESOURCE,i,resources[i],0));
  4971. }
  4972. if(iw.components.size())
  4973. {
  4974. getText(iw,hadGuardians,182,h);
  4975. cb->showInfoDialog(&iw);
  4976. }
  4977. iw.components.clear();
  4978. iw.text.clear();
  4979. for(int i=0; i<resources.size(); i++)
  4980. {
  4981. if(resources[i] > 0)
  4982. iw.components.push_back(Component(Component::RESOURCE,i,resources[i],0));
  4983. }
  4984. if(iw.components.size())
  4985. {
  4986. getText(iw,hadGuardians,183,h);
  4987. cb->showInfoDialog(&iw);
  4988. }
  4989. iw.components.clear();
  4990. // getText(iw,afterBattle,183,h);
  4991. iw.text.addTxt(MetaString::ADVOB_TXT, 183); //% has found treasure
  4992. iw.text.addReplacement(h->name);
  4993. for(auto & elem : artifacts)
  4994. {
  4995. iw.components.push_back(Component(Component::ARTIFACT,elem,0,0));
  4996. if(iw.components.size() >= 14)
  4997. {
  4998. cb->showInfoDialog(&iw);
  4999. iw.components.clear();
  5000. iw.text.addTxt(MetaString::ADVOB_TXT, 183); //% has found treasure - once more?
  5001. iw.text.addReplacement(h->name);
  5002. }
  5003. }
  5004. if(iw.components.size())
  5005. {
  5006. cb->showInfoDialog(&iw);
  5007. }
  5008. for(int i=0; i<resources.size(); i++)
  5009. if(resources[i])
  5010. cb->giveResource(h->getOwner(),static_cast<Res::ERes>(i),resources[i]);
  5011. for(auto & elem : artifacts)
  5012. cb->giveHeroNewArtifact(h, VLC->arth->artifacts[elem],ArtifactPosition::FIRST_AVAILABLE);
  5013. iw.components.clear();
  5014. iw.text.clear();
  5015. if (creatures.Slots().size())
  5016. { //this part is taken straight from creature bank
  5017. MetaString loot;
  5018. for(auto & elem : creatures.Slots())
  5019. { //build list of joined creatures
  5020. iw.components.push_back(Component(*elem.second));
  5021. loot << "%s";
  5022. loot.addReplacement(*elem.second);
  5023. }
  5024. if (creatures.Slots().size() == 1 && creatures.Slots().begin()->second->count == 1)
  5025. iw.text.addTxt(MetaString::ADVOB_TXT, 185);
  5026. else
  5027. iw.text.addTxt(MetaString::ADVOB_TXT, 186);
  5028. iw.text.addReplacement(loot.buildList());
  5029. iw.text.addReplacement(h->name);
  5030. cb->showInfoDialog(&iw);
  5031. cb->giveCreatures(this, h, creatures, true);
  5032. }
  5033. if(!hasGuardians && msg.size())
  5034. {
  5035. iw.text << msg;
  5036. cb->showInfoDialog(&iw);
  5037. }
  5038. }
  5039. void CGPandoraBox::getText( InfoWindow &iw, bool &afterBattle, int text, const CGHeroInstance * h ) const
  5040. {
  5041. if(afterBattle || !message.size())
  5042. {
  5043. iw.text.addTxt(MetaString::ADVOB_TXT,text);//%s has lost treasure.
  5044. iw.text.addReplacement(h->name);
  5045. }
  5046. else
  5047. {
  5048. iw.text << message;
  5049. afterBattle = true;
  5050. }
  5051. }
  5052. void CGPandoraBox::getText( InfoWindow &iw, bool &afterBattle, int val, int negative, int positive, const CGHeroInstance * h ) const
  5053. {
  5054. iw.components.clear();
  5055. iw.text.clear();
  5056. if(afterBattle || !message.size())
  5057. {
  5058. iw.text.addTxt(MetaString::ADVOB_TXT,val < 0 ? negative : positive); //%s's luck takes a turn for the worse / %s's luck increases
  5059. iw.text.addReplacement(h->name);
  5060. }
  5061. else
  5062. {
  5063. iw.text << message;
  5064. afterBattle = true;
  5065. }
  5066. }
  5067. void CGPandoraBox::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  5068. {
  5069. if(result.winner)
  5070. return;
  5071. giveContentsUpToExp(hero);
  5072. }
  5073. void CGPandoraBox::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  5074. {
  5075. if (answer)
  5076. {
  5077. if (stacksCount() > 0) //if pandora's box is protected by army
  5078. {
  5079. showInfoDialog(hero,16,0);
  5080. cb->startBattleI(hero, this); //grants things after battle
  5081. }
  5082. else if (message.size() == 0 && resources.size() == 0
  5083. && primskills.size() == 0 && abilities.size() == 0
  5084. && abilityLevels.size() == 0 && artifacts.size() == 0
  5085. && spells.size() == 0 && creatures.Slots().size() > 0
  5086. && gainedExp == 0 && manaDiff == 0 && moraleDiff == 0 && luckDiff == 0) //if it gives nothing without battle
  5087. {
  5088. showInfoDialog(hero,15,0);
  5089. cb->removeObject(this);
  5090. }
  5091. else //if it gives something without battle
  5092. {
  5093. giveContentsUpToExp(hero);
  5094. }
  5095. }
  5096. }
  5097. void CGPandoraBox::heroLevelUpDone(const CGHeroInstance *hero) const
  5098. {
  5099. giveContentsAfterExp(hero);
  5100. }
  5101. void CGEvent::onHeroVisit( const CGHeroInstance * h ) const
  5102. {
  5103. if(!(availableFor & (1 << h->tempOwner.getNum())))
  5104. return;
  5105. if(cb->getPlayerSettings(h->tempOwner)->playerID)
  5106. {
  5107. if(humanActivate)
  5108. activated(h);
  5109. }
  5110. else if(computerActivate)
  5111. activated(h);
  5112. }
  5113. void CGEvent::activated( const CGHeroInstance * h ) const
  5114. {
  5115. if(stacksCount() > 0)
  5116. {
  5117. InfoWindow iw;
  5118. iw.player = h->tempOwner;
  5119. if(message.size())
  5120. iw.text << message;
  5121. else
  5122. iw.text.addTxt(MetaString::ADVOB_TXT, 16);
  5123. cb->showInfoDialog(&iw);
  5124. cb->startBattleI(h, this);
  5125. }
  5126. else
  5127. {
  5128. giveContentsUpToExp(h);
  5129. }
  5130. }
  5131. void CGObservatory::onHeroVisit( const CGHeroInstance * h ) const
  5132. {
  5133. InfoWindow iw;
  5134. iw.player = h->tempOwner;
  5135. switch (ID)
  5136. {
  5137. case Obj::REDWOOD_OBSERVATORY:
  5138. case Obj::PILLAR_OF_FIRE:
  5139. {
  5140. iw.soundID = soundBase::LIGHTHOUSE;
  5141. iw.text.addTxt(MetaString::ADVOB_TXT,98 + (ID==Obj::PILLAR_OF_FIRE));
  5142. FoWChange fw;
  5143. fw.player = h->tempOwner;
  5144. fw.mode = 1;
  5145. cb->getTilesInRange (fw.tiles, pos, 20, h->tempOwner, 1);
  5146. cb->sendAndApply (&fw);
  5147. break;
  5148. }
  5149. case Obj::COVER_OF_DARKNESS:
  5150. {
  5151. iw.text.addTxt (MetaString::ADVOB_TXT, 31);
  5152. hideTiles(h->tempOwner, 20);
  5153. break;
  5154. }
  5155. }
  5156. cb->showInfoDialog(&iw);
  5157. }
  5158. void CGShrine::onHeroVisit( const CGHeroInstance * h ) const
  5159. {
  5160. if(spell == SpellID::NONE)
  5161. {
  5162. logGlobal->errorStream() << "Not initialized shrine visited!";
  5163. return;
  5164. }
  5165. if(!wasVisited(h->tempOwner))
  5166. cb->setObjProperty(id, 10, h->tempOwner.getNum());
  5167. InfoWindow iw;
  5168. iw.soundID = soundBase::temple;
  5169. iw.player = h->getOwner();
  5170. iw.text.addTxt(MetaString::ADVOB_TXT,127 + ID - 88);
  5171. iw.text.addTxt(MetaString::SPELL_NAME,spell);
  5172. iw.text << ".";
  5173. if(!h->getArt(ArtifactPosition::SPELLBOOK))
  5174. {
  5175. iw.text.addTxt(MetaString::ADVOB_TXT,131);
  5176. }
  5177. else if(ID == Obj::SHRINE_OF_MAGIC_THOUGHT && !h->getSecSkillLevel(SecondarySkill::WISDOM)) //it's third level spell and hero doesn't have wisdom
  5178. {
  5179. iw.text.addTxt(MetaString::ADVOB_TXT,130);
  5180. }
  5181. else if(vstd::contains(h->spells,spell))//hero already knows the spell
  5182. {
  5183. iw.text.addTxt(MetaString::ADVOB_TXT,174);
  5184. }
  5185. else //give spell
  5186. {
  5187. std::set<SpellID> spells;
  5188. spells.insert(spell);
  5189. cb->changeSpells(h, true, spells);
  5190. iw.components.push_back(Component(Component::SPELL,spell,0,0));
  5191. }
  5192. cb->showInfoDialog(&iw);
  5193. }
  5194. void CGShrine::initObj()
  5195. {
  5196. if(spell == SpellID::NONE) //spell not set
  5197. {
  5198. int level = ID-87;
  5199. std::vector<SpellID> possibilities;
  5200. cb->getAllowedSpells (possibilities, level);
  5201. if(!possibilities.size())
  5202. {
  5203. logGlobal->errorStream() << "Error: cannot init shrine, no allowed spells!";
  5204. return;
  5205. }
  5206. spell = possibilities[ran() % possibilities.size()];
  5207. }
  5208. }
  5209. const std::string & CGShrine::getHoverText() const
  5210. {
  5211. hoverName = VLC->generaltexth->names[ID];
  5212. if(wasVisited(cb->getCurrentPlayer())) //TODO: use local player, not current
  5213. {
  5214. hoverName += "\n" + VLC->generaltexth->allTexts[355]; // + (learn %s)
  5215. boost::algorithm::replace_first(hoverName,"%s", spell.toSpell()->name);
  5216. const CGHeroInstance *h = cb->getSelectedHero(cb->getCurrentPlayer());
  5217. if(h && vstd::contains(h->spells,spell)) //hero knows that ability
  5218. hoverName += "\n\n" + VLC->generaltexth->allTexts[354]; // (Already learned)
  5219. }
  5220. return hoverName;
  5221. }
  5222. void CGSignBottle::initObj()
  5223. {
  5224. //if no text is set than we pick random from the predefined ones
  5225. if(!message.size())
  5226. message = VLC->generaltexth->randsign[ran()%VLC->generaltexth->randsign.size()];
  5227. if(ID == Obj::OCEAN_BOTTLE)
  5228. {
  5229. blockVisit = true;
  5230. }
  5231. }
  5232. void CGSignBottle::onHeroVisit( const CGHeroInstance * h ) const
  5233. {
  5234. InfoWindow iw;
  5235. iw.soundID = soundBase::STORE;
  5236. iw.player = h->getOwner();
  5237. iw.text << message;
  5238. cb->showInfoDialog(&iw);
  5239. if(ID == Obj::OCEAN_BOTTLE)
  5240. cb->removeObject(this);
  5241. }
  5242. //TODO: remove
  5243. //void CGScholar::giveAnyBonus( const CGHeroInstance * h ) const
  5244. //{
  5245. //
  5246. //}
  5247. void CGScholar::onHeroVisit( const CGHeroInstance * h ) const
  5248. {
  5249. EBonusType type = bonusType;
  5250. int bid = bonusID;
  5251. //check if the bonus if applicable, if not - give primary skill (always possible)
  5252. int ssl = h->getSecSkillLevel(SecondarySkill(bid)); //current sec skill level, used if bonusType == 1
  5253. if((type == SECONDARY_SKILL
  5254. && ((ssl == 3) || (!ssl && !h->canLearnSkill()))) ////hero already has expert level in the skill or (don't know skill and doesn't have free slot)
  5255. || (type == SPELL && (!h->getArt(ArtifactPosition::SPELLBOOK) || vstd::contains(h->spells, (ui32) bid)
  5256. || ( SpellID(bid).toSpell()->level > h->getSecSkillLevel(SecondarySkill::WISDOM) + 2)
  5257. ))) //hero doesn't have a spellbook or already knows the spell or doesn't have Wisdom
  5258. {
  5259. type = PRIM_SKILL;
  5260. bid = ran() % GameConstants::PRIMARY_SKILLS;
  5261. }
  5262. InfoWindow iw;
  5263. iw.soundID = soundBase::gazebo;
  5264. iw.player = h->getOwner();
  5265. iw.text.addTxt(MetaString::ADVOB_TXT,115);
  5266. switch (type)
  5267. {
  5268. case PRIM_SKILL:
  5269. cb->changePrimSkill(h,static_cast<PrimarySkill::PrimarySkill>(bid),+1);
  5270. iw.components.push_back(Component(Component::PRIM_SKILL,bid,+1,0));
  5271. break;
  5272. case SECONDARY_SKILL:
  5273. cb->changeSecSkill(h,SecondarySkill(bid),+1);
  5274. iw.components.push_back(Component(Component::SEC_SKILL,bid,ssl+1,0));
  5275. break;
  5276. case SPELL:
  5277. {
  5278. std::set<SpellID> hlp;
  5279. hlp.insert(SpellID(bid));
  5280. cb->changeSpells(h,true,hlp);
  5281. iw.components.push_back(Component(Component::SPELL,bid,0,0));
  5282. }
  5283. break;
  5284. default:
  5285. logGlobal->errorStream() << "Error: wrong bonus type (" << (int)type << ") for Scholar!\n";
  5286. return;
  5287. }
  5288. cb->showInfoDialog(&iw);
  5289. cb->removeObject(this);
  5290. }
  5291. void CGScholar::initObj()
  5292. {
  5293. blockVisit = true;
  5294. if(bonusType == RANDOM)
  5295. {
  5296. bonusType = static_cast<EBonusType>(ran()%3);
  5297. switch(bonusType)
  5298. {
  5299. case PRIM_SKILL:
  5300. bonusID = ran() % GameConstants::PRIMARY_SKILLS;
  5301. break;
  5302. case SECONDARY_SKILL:
  5303. bonusID = ran() % GameConstants::SKILL_QUANTITY;
  5304. break;
  5305. case SPELL:
  5306. std::vector<SpellID> possibilities;
  5307. for (int i = 1; i < 6; ++i)
  5308. cb->getAllowedSpells (possibilities, i);
  5309. bonusID = possibilities[ran() % possibilities.size()];
  5310. break;
  5311. }
  5312. }
  5313. }
  5314. void CGGarrison::onHeroVisit (const CGHeroInstance *h) const
  5315. {
  5316. int ally = cb->gameState()->getPlayerRelations(h->tempOwner, tempOwner);
  5317. if (!ally && stacksCount() > 0) {
  5318. //TODO: Find a way to apply magic garrison effects in battle.
  5319. cb->startBattleI(h, this);
  5320. return;
  5321. }
  5322. //New owner.
  5323. if (!ally)
  5324. cb->setOwner(this, h->tempOwner);
  5325. cb->showGarrisonDialog(id, h->id, removableUnits);
  5326. }
  5327. ui8 CGGarrison::getPassableness() const
  5328. {
  5329. if ( !stacksCount() )//empty - anyone can visit
  5330. return GameConstants::ALL_PLAYERS;
  5331. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  5332. return 0;
  5333. ui8 mask = 0;
  5334. TeamState * ts = cb->gameState()->getPlayerTeam(tempOwner);
  5335. for(PlayerColor it : ts->players)
  5336. mask |= 1<<it.getNum(); //allies - add to possible visitors
  5337. return mask;
  5338. }
  5339. void CGGarrison::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  5340. {
  5341. if (result.winner == 0)
  5342. onHeroVisit(hero);
  5343. }
  5344. void CGOnceVisitable::onHeroVisit( const CGHeroInstance * h ) const
  5345. {
  5346. int sound = soundBase::sound_todo;
  5347. int txtid;
  5348. switch(ID)
  5349. {
  5350. case Obj::CORPSE:
  5351. txtid = 37;
  5352. sound = soundBase::MYSTERY;
  5353. break;
  5354. case Obj::LEAN_TO:
  5355. sound = soundBase::GENIE;
  5356. txtid = 64;
  5357. break;
  5358. case Obj::WAGON:
  5359. sound = soundBase::GENIE;
  5360. txtid = 154;
  5361. break;
  5362. case Obj::WARRIORS_TOMB:
  5363. {
  5364. //ask if player wants to search the Tomb
  5365. BlockingDialog bd(true, false);
  5366. bd.soundID = soundBase::GRAVEYARD;
  5367. bd.player = h->getOwner();
  5368. bd.text.addTxt(MetaString::ADVOB_TXT,161);
  5369. cb->showBlockingDialog(&bd);
  5370. return;
  5371. }
  5372. break;
  5373. default:
  5374. logGlobal->errorStream() << "Error: Unknown object (" << ID <<") treated as CGOnceVisitable!";
  5375. return;
  5376. }
  5377. InfoWindow iw;
  5378. iw.soundID = sound;
  5379. iw.player = h->getOwner();
  5380. if(players.size()) //we have been already visited...
  5381. {
  5382. txtid++;
  5383. if(ID == Obj::WAGON) //wagon has extra text (for finding art) we need to omit
  5384. txtid++;
  5385. iw.text.addTxt(MetaString::ADVOB_TXT, txtid);
  5386. }
  5387. else //first visit - give bonus!
  5388. {
  5389. switch(artOrRes)
  5390. {
  5391. case 0: // first visit but empty
  5392. if (ID == Obj::CORPSE)
  5393. ++txtid;
  5394. else
  5395. txtid+=2;
  5396. iw.text.addTxt(MetaString::ADVOB_TXT, txtid);
  5397. break;
  5398. case 1: //art
  5399. iw.components.push_back(Component(Component::ARTIFACT,bonusType,0,0));
  5400. cb->giveHeroNewArtifact(h, VLC->arth->artifacts[bonusType],ArtifactPosition::FIRST_AVAILABLE);
  5401. iw.text.addTxt(MetaString::ADVOB_TXT, txtid);
  5402. if (ID == Obj::CORPSE)
  5403. {
  5404. iw.text << "%s";
  5405. iw.text.addReplacement(MetaString::ART_NAMES, bonusType);
  5406. }
  5407. break;
  5408. case 2: //res
  5409. iw.text.addTxt(MetaString::ADVOB_TXT, txtid);
  5410. iw.components.push_back (Component(Component::RESOURCE, bonusType, bonusVal, 0));
  5411. cb->giveResource(h->getOwner(), static_cast<Res::ERes>(bonusType), bonusVal);
  5412. break;
  5413. }
  5414. if(ID == Obj::WAGON && artOrRes == 1)
  5415. {
  5416. iw.text.localStrings.back().second++;
  5417. iw.text.addReplacement(MetaString::ART_NAMES, bonusType);
  5418. }
  5419. }
  5420. cb->showInfoDialog(&iw);
  5421. cb->setObjProperty(id, 10, h->getOwner().getNum());
  5422. }
  5423. const std::string & CGOnceVisitable::getHoverText() const
  5424. {
  5425. const bool visited = wasVisited(cb->getCurrentPlayer());
  5426. hoverName = VLC->generaltexth->names[ID] + " " + visitedTxt(visited);
  5427. return hoverName;
  5428. }
  5429. void CGOnceVisitable::initObj()
  5430. {
  5431. switch(ID)
  5432. {
  5433. case Obj::CORPSE:
  5434. {
  5435. blockVisit = true;
  5436. int hlp = ran()%100;
  5437. if(hlp < 20)
  5438. {
  5439. artOrRes = 1;
  5440. bonusType = cb->getRandomArt (CArtifact::ART_TREASURE | CArtifact::ART_MINOR | CArtifact::ART_MAJOR);
  5441. }
  5442. else
  5443. {
  5444. artOrRes = 0;
  5445. }
  5446. }
  5447. break;
  5448. case Obj::LEAN_TO:
  5449. {
  5450. artOrRes = 2;
  5451. bonusType = ran()%6; //any basic resource without gold
  5452. bonusVal = ran()%4 + 1;
  5453. }
  5454. break;
  5455. case Obj::WARRIORS_TOMB:
  5456. {
  5457. artOrRes = 1;
  5458. int hlp = ran()%100;
  5459. if(hlp < 30)
  5460. bonusType = cb->getRandomArt (CArtifact::ART_TREASURE);
  5461. else if(hlp < 80)
  5462. bonusType = cb->getRandomArt (CArtifact::ART_MINOR);
  5463. else if(hlp < 95)
  5464. bonusType = cb->getRandomArt (CArtifact::ART_MAJOR);
  5465. else
  5466. bonusType = cb->getRandomArt (CArtifact::ART_RELIC);
  5467. }
  5468. break;
  5469. case Obj::WAGON:
  5470. {
  5471. int hlp = ran()%100;
  5472. if(hlp < 10)
  5473. {
  5474. artOrRes = 0; // nothing... :(
  5475. }
  5476. else if(hlp < 50) //minor or treasure art
  5477. {
  5478. artOrRes = 1;
  5479. bonusType = cb->getRandomArt (CArtifact::ART_TREASURE | CArtifact::ART_MINOR);
  5480. }
  5481. else //2 - 5 of non-gold resource
  5482. {
  5483. artOrRes = 2;
  5484. bonusType = ran()%6;
  5485. bonusVal = ran()%4 + 2;
  5486. }
  5487. }
  5488. break;
  5489. }
  5490. }
  5491. void CGOnceVisitable::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  5492. {
  5493. //must have been Tomb
  5494. if(answer)
  5495. {
  5496. InfoWindow iw;
  5497. iw.player = hero->getOwner();
  5498. iw.components.push_back(Component(Component::MORALE,0,-3,0));
  5499. if(players.size()) //we've been already visited, player found nothing
  5500. {
  5501. iw.text.addTxt(MetaString::ADVOB_TXT,163);
  5502. }
  5503. else //first visit - give artifact
  5504. {
  5505. iw.text.addTxt(MetaString::ADVOB_TXT,162);
  5506. iw.components.push_back(Component(Component::ARTIFACT,bonusType,0,0));
  5507. iw.text.addReplacement(MetaString::ART_NAMES, bonusType);
  5508. cb->giveHeroNewArtifact(hero, VLC->arth->artifacts[bonusType],ArtifactPosition::FIRST_AVAILABLE);
  5509. }
  5510. if(!hero->hasBonusFrom(Bonus::OBJECT,ID)) //we don't have modifier from this object yet
  5511. {
  5512. //ruin morale
  5513. GiveBonus gb;
  5514. gb.id = hero->id.getNum();
  5515. gb.bonus = Bonus(Bonus::ONE_BATTLE,Bonus::MORALE,Bonus::OBJECT,-3,id.getNum(),"");
  5516. gb.bdescr.addTxt(MetaString::ARRAY_TXT,104); //Warrior Tomb Visited -3
  5517. cb->giveHeroBonus(&gb);
  5518. }
  5519. cb->showInfoDialog(&iw);
  5520. cb->setObjProperty(id, 10, hero->getOwner().getNum());
  5521. }
  5522. }
  5523. void CBank::initObj()
  5524. {
  5525. index = VLC->objh->bankObjToIndex(this);
  5526. bc = nullptr;
  5527. daycounter = 0;
  5528. multiplier = 1;
  5529. }
  5530. const std::string & CBank::getHoverText() const
  5531. {
  5532. bool visited = (bc == nullptr);
  5533. hoverName = VLC->objh->creBanksNames[index] + " " + visitedTxt(visited);
  5534. return hoverName;
  5535. }
  5536. void CBank::reset(ui16 var1) //prevents desync
  5537. {
  5538. ui8 chance = 0;
  5539. for (auto & elem : VLC->objh->banksInfo[index])
  5540. {
  5541. if (var1 < (chance += elem->chance))
  5542. {
  5543. bc = elem;
  5544. break;
  5545. }
  5546. }
  5547. artifacts.clear();
  5548. }
  5549. void CBank::initialize() const
  5550. {
  5551. cb->setObjProperty (id, ObjProperty::BANK_RESET, ran()); //synchronous reset
  5552. for (ui8 i = 0; i <= 3; i++)
  5553. {
  5554. for (ui8 n = 0; n < bc->artifacts[i]; n++)
  5555. {
  5556. CArtifact::EartClass artClass;
  5557. switch(i)
  5558. {
  5559. case 0: artClass = CArtifact::ART_TREASURE; break;
  5560. case 1: artClass = CArtifact::ART_MINOR; break;
  5561. case 2: artClass = CArtifact::ART_MAJOR; break;
  5562. case 3: artClass = CArtifact::ART_RELIC; break;
  5563. default: assert(0); continue;
  5564. }
  5565. int artID = cb->getArtSync(ran(), artClass, true);
  5566. cb->setObjProperty(id, ObjProperty::BANK_ADD_ARTIFACT, artID);
  5567. }
  5568. }
  5569. cb->setObjProperty (id, ObjProperty::BANK_INIT_ARMY, ran()); //get army
  5570. }
  5571. void CBank::setPropertyDer (ui8 what, ui32 val)
  5572. /// random values are passed as arguments and processed identically on all clients
  5573. {
  5574. switch (what)
  5575. {
  5576. case ObjProperty::BANK_DAYCOUNTER: //daycounter
  5577. if (val == 0)
  5578. daycounter = 1; //yes, 1
  5579. else
  5580. daycounter++;
  5581. break;
  5582. case ObjProperty::BANK_MULTIPLIER: //multiplier, in percent
  5583. multiplier = val / 100.0;
  5584. break;
  5585. case 13: //bank preset
  5586. bc = VLC->objh->banksInfo[index][val];
  5587. break;
  5588. case ObjProperty::BANK_RESET:
  5589. reset (val%100);
  5590. break;
  5591. case ObjProperty::BANK_CLEAR_CONFIG:
  5592. bc = nullptr;
  5593. break;
  5594. case ObjProperty::BANK_CLEAR_ARTIFACTS: //remove rewards from Derelict Ship
  5595. artifacts.clear();
  5596. break;
  5597. case ObjProperty::BANK_INIT_ARMY: //set ArmedInstance army
  5598. {
  5599. int upgraded = 0;
  5600. if (val%100 < bc->upgradeChance) //once again anti-desync
  5601. upgraded = 1;
  5602. switch (bc->guards.size())
  5603. {
  5604. case 1:
  5605. for (int i = 0; i < 4; ++i)
  5606. setCreature (SlotID(i), bc->guards[0].first, bc->guards[0].second / 5 );
  5607. setCreature (SlotID(4), CreatureID(bc->guards[0].first + upgraded), bc->guards[0].second / 5 );
  5608. break;
  5609. case 4:
  5610. {
  5611. if (bc->guards.back().second) //all stacks are present
  5612. {
  5613. for (auto & elem : bc->guards)
  5614. {
  5615. setCreature (SlotID(stacksCount()), elem.first, elem.second);
  5616. }
  5617. }
  5618. else if (bc->guards[2].second)//Wraiths are present, split two stacks in Crypt
  5619. {
  5620. setCreature (SlotID(0), bc->guards[0].first, bc->guards[0].second / 2 );
  5621. setCreature (SlotID(1), bc->guards[1].first, bc->guards[1].second / 2);
  5622. setCreature (SlotID(2), CreatureID(bc->guards[2].first + upgraded), bc->guards[2].second);
  5623. setCreature (SlotID(3), bc->guards[1].first, bc->guards[1].second / 2 );
  5624. setCreature (SlotID(4), bc->guards[0].first, bc->guards[0].second - (bc->guards[0].second / 2) );
  5625. }
  5626. else //split both stacks
  5627. {
  5628. for (int i = 0; i < 3; ++i) //skellies
  5629. setCreature (SlotID(2*i), bc->guards[0].first, bc->guards[0].second / 3);
  5630. for (int i = 0; i < 2; ++i) //zombies
  5631. setCreature (SlotID(2*i+1), bc->guards[1].first, bc->guards[1].second / 2);
  5632. }
  5633. }
  5634. break;
  5635. default:
  5636. logGlobal->warnStream() << "Error: Unexpected army data: " << bc->guards.size() <<" items found";
  5637. return;
  5638. }
  5639. }
  5640. break;
  5641. case ObjProperty::BANK_ADD_ARTIFACT: //add Artifact
  5642. {
  5643. artifacts.push_back (val);
  5644. break;
  5645. }
  5646. }
  5647. }
  5648. void CBank::newTurn() const
  5649. {
  5650. if (bc == nullptr)
  5651. {
  5652. if (cb->getDate() == 1)
  5653. initialize(); //initialize on first day
  5654. else if (daycounter >= 28 && (subID < 13 || subID > 16)) //no reset for Emissaries
  5655. {
  5656. initialize();
  5657. cb->setObjProperty (id, ObjProperty::BANK_DAYCOUNTER, 0); //daycounter 0
  5658. if (ID == Obj::DERELICT_SHIP && cb->getDate() > 1)
  5659. {
  5660. cb->setObjProperty (id, ObjProperty::BANK_MULTIPLIER, 0);//ugly hack to make derelict ships usable only once
  5661. cb->setObjProperty (id, ObjProperty::BANK_CLEAR_ARTIFACTS, 0);
  5662. }
  5663. }
  5664. else
  5665. cb->setObjProperty (id, ObjProperty::BANK_DAYCOUNTER, 1); //daycounter++
  5666. }
  5667. }
  5668. bool CBank::wasVisited (PlayerColor player) const
  5669. {
  5670. return !bc;
  5671. }
  5672. void CBank::onHeroVisit (const CGHeroInstance * h) const
  5673. {
  5674. if (bc)
  5675. {
  5676. int banktext = 0;
  5677. switch (ID)
  5678. {
  5679. case Obj::CREATURE_BANK:
  5680. banktext = 32;
  5681. break;
  5682. case Obj::DERELICT_SHIP:
  5683. banktext = 41;
  5684. break;
  5685. case Obj::DRAGON_UTOPIA:
  5686. banktext = 47;
  5687. break;
  5688. case Obj::CRYPT:
  5689. banktext = 119;
  5690. break;
  5691. case Obj::SHIPWRECK:
  5692. banktext = 122;
  5693. break;
  5694. }
  5695. BlockingDialog bd (true, false);
  5696. bd.player = h->getOwner();
  5697. bd.soundID = soundBase::ROGUE;
  5698. bd.text.addTxt(MetaString::ADVOB_TXT,banktext);
  5699. if (ID == Obj::CREATURE_BANK)
  5700. bd.text.addReplacement(VLC->objh->creBanksNames[index]);
  5701. cb->showBlockingDialog (&bd);
  5702. }
  5703. else
  5704. {
  5705. InfoWindow iw;
  5706. iw.soundID = soundBase::GRAVEYARD;
  5707. iw.player = h->getOwner();
  5708. if (ID == Obj::CRYPT) //morale penalty for empty Crypt
  5709. {
  5710. GiveBonus gbonus;
  5711. gbonus.id = h->id.getNum();
  5712. gbonus.bonus.duration = Bonus::ONE_BATTLE;
  5713. gbonus.bonus.source = Bonus::OBJECT;
  5714. gbonus.bonus.sid = ID;
  5715. gbonus.bdescr << "\n" << VLC->generaltexth->arraytxt[98];
  5716. gbonus.bonus.type = Bonus::MORALE;
  5717. gbonus.bonus.val = -1;
  5718. cb->giveHeroBonus(&gbonus);
  5719. iw.text << VLC->generaltexth->advobtxt[120];
  5720. iw.components.push_back (Component (Component::MORALE, 0 , -1, 0));
  5721. }
  5722. else
  5723. {
  5724. iw.text << VLC->generaltexth->advobtxt[33];
  5725. iw.text.addReplacement(VLC->objh->creBanksNames[index]);
  5726. }
  5727. cb->showInfoDialog(&iw);
  5728. }
  5729. }
  5730. void CBank::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  5731. {
  5732. if (result.winner == 0)
  5733. {
  5734. int textID = -1;
  5735. InfoWindow iw;
  5736. iw.player = hero->getOwner();
  5737. MetaString loot;
  5738. switch (ID)
  5739. {
  5740. case Obj::CREATURE_BANK: case Obj::DRAGON_UTOPIA:
  5741. textID = 34;
  5742. break;
  5743. case Obj::DERELICT_SHIP:
  5744. if (multiplier)
  5745. textID = 43;
  5746. else
  5747. {
  5748. GiveBonus gbonus;
  5749. gbonus.id = hero->id.getNum();
  5750. gbonus.bonus.duration = Bonus::ONE_BATTLE;
  5751. gbonus.bonus.source = Bonus::OBJECT;
  5752. gbonus.bonus.sid = ID;
  5753. gbonus.bdescr << "\n" << VLC->generaltexth->arraytxt[101];
  5754. gbonus.bonus.type = Bonus::MORALE;
  5755. gbonus.bonus.val = -1;
  5756. cb->giveHeroBonus(&gbonus);
  5757. textID = 42;
  5758. iw.components.push_back (Component (Component::MORALE, 0 , -1, 0));
  5759. }
  5760. break;
  5761. case Obj::CRYPT:
  5762. if (bc->resources.size() != 0)
  5763. textID = 121;
  5764. else
  5765. {
  5766. iw.components.push_back (Component (Component::MORALE, 0 , -1, 0));
  5767. GiveBonus gbonus;
  5768. gbonus.id = hero->id.getNum();
  5769. gbonus.bonus.duration = Bonus::ONE_BATTLE;
  5770. gbonus.bonus.source = Bonus::OBJECT;
  5771. gbonus.bonus.sid = ID;
  5772. gbonus.bdescr << "\n" << VLC->generaltexth->arraytxt[ID];
  5773. gbonus.bonus.type = Bonus::MORALE;
  5774. gbonus.bonus.val = -1;
  5775. cb->giveHeroBonus(&gbonus);
  5776. textID = 120;
  5777. iw.components.push_back (Component (Component::MORALE, 0 , -1, 0));
  5778. }
  5779. break;
  5780. case Obj::SHIPWRECK:
  5781. if (bc->resources.size())
  5782. textID = 124;
  5783. else
  5784. textID = 123;
  5785. break;
  5786. }
  5787. //grant resources
  5788. if (textID != 42) //empty derelict ship gives no cash
  5789. {
  5790. for (int it = 0; it < bc->resources.size(); it++)
  5791. {
  5792. if (bc->resources[it] != 0)
  5793. {
  5794. iw.components.push_back (Component (Component::RESOURCE, it, bc->resources[it], 0));
  5795. loot << "%d %s";
  5796. loot.addReplacement(iw.components.back().val);
  5797. loot.addReplacement(MetaString::RES_NAMES, iw.components.back().subtype);
  5798. cb->giveResource (hero->getOwner(), static_cast<Res::ERes>(it), bc->resources[it]);
  5799. }
  5800. }
  5801. }
  5802. //grant artifacts
  5803. for (auto & elem : artifacts)
  5804. {
  5805. iw.components.push_back (Component (Component::ARTIFACT, elem, 0, 0));
  5806. loot << "%s";
  5807. loot.addReplacement(MetaString::ART_NAMES, elem);
  5808. cb->giveHeroNewArtifact (hero, VLC->arth->artifacts[elem], ArtifactPosition::FIRST_AVAILABLE);
  5809. }
  5810. //display loot
  5811. if (!iw.components.empty())
  5812. {
  5813. iw.text.addTxt (MetaString::ADVOB_TXT, textID);
  5814. if (textID == 34)
  5815. {
  5816. iw.text.addReplacement(MetaString::CRE_PL_NAMES, result.casualties[1].begin()->first);
  5817. iw.text.addReplacement(loot.buildList());
  5818. }
  5819. cb->showInfoDialog(&iw);
  5820. }
  5821. loot.clear();
  5822. iw.components.clear();
  5823. iw.text.clear();
  5824. //grant creatures
  5825. CCreatureSet ourArmy;
  5826. for (auto it = bc->creatures.cbegin(); it != bc->creatures.cend(); it++)
  5827. {
  5828. SlotID slot = ourArmy.getSlotFor(it->first);
  5829. ourArmy.addToSlot(slot, it->first, it->second);
  5830. }
  5831. for (auto & elem : ourArmy.Slots())
  5832. {
  5833. iw.components.push_back(Component(*elem.second));
  5834. loot << "%s";
  5835. loot.addReplacement(*elem.second);
  5836. }
  5837. if (ourArmy.Slots().size())
  5838. {
  5839. if (ourArmy.Slots().size() == 1 && ourArmy.Slots().begin()->second->count == 1)
  5840. iw.text.addTxt (MetaString::ADVOB_TXT, 185);
  5841. else
  5842. iw.text.addTxt (MetaString::ADVOB_TXT, 186);
  5843. iw.text.addReplacement(loot.buildList());
  5844. iw.text.addReplacement(hero->name);
  5845. cb->showInfoDialog(&iw);
  5846. cb->giveCreatures(this, hero, ourArmy, false);
  5847. }
  5848. cb->setObjProperty (id, ObjProperty::BANK_CLEAR_CONFIG, 0); //bc = nullptr
  5849. }
  5850. }
  5851. void CBank::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  5852. {
  5853. if (answer)
  5854. {
  5855. cb->startBattleI(hero, this, true);
  5856. }
  5857. }
  5858. void CGPyramid::initObj()
  5859. {
  5860. std::vector<SpellID> available;
  5861. cb->getAllowedSpells (available, 5);
  5862. if (available.size())
  5863. {
  5864. bc = VLC->objh->banksInfo[21].front(); //TODO: remove hardcoded value?
  5865. spell = (available[ran()%available.size()]);
  5866. }
  5867. else
  5868. {
  5869. logGlobal->errorStream() <<"No spells available for Pyramid! Object set to empty.";
  5870. }
  5871. setPropertyDer (ObjProperty::BANK_INIT_ARMY,ran()); //set guards at game start
  5872. }
  5873. const std::string & CGPyramid::getHoverText() const
  5874. {
  5875. hoverName = VLC->objh->creBanksNames[21]+ " " + visitedTxt((bc==nullptr));
  5876. return hoverName;
  5877. }
  5878. void CGPyramid::onHeroVisit (const CGHeroInstance * h) const
  5879. {
  5880. if (bc)
  5881. {
  5882. BlockingDialog bd (true, false);
  5883. bd.player = h->getOwner();
  5884. bd.soundID = soundBase::MYSTERY;
  5885. bd.text << VLC->generaltexth->advobtxt[105];
  5886. cb->showBlockingDialog(&bd);
  5887. }
  5888. else
  5889. {
  5890. InfoWindow iw;
  5891. iw.player = h->getOwner();
  5892. iw.text << VLC->generaltexth->advobtxt[107];
  5893. iw.components.push_back (Component (Component::LUCK, 0 , -2, 0));
  5894. GiveBonus gb;
  5895. gb.bonus = Bonus(Bonus::ONE_BATTLE,Bonus::LUCK,Bonus::OBJECT,-2,id.getNum(),VLC->generaltexth->arraytxt[70]);
  5896. gb.id = h->id.getNum();
  5897. cb->giveHeroBonus(&gb);
  5898. cb->showInfoDialog(&iw);
  5899. }
  5900. }
  5901. void CGPyramid::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  5902. {
  5903. if (result.winner == 0)
  5904. {
  5905. InfoWindow iw;
  5906. iw.player = hero->getOwner();
  5907. iw.text.addTxt (MetaString::ADVOB_TXT, 106);
  5908. iw.text.addTxt (MetaString::SPELL_NAME, spell);
  5909. if (!hero->getArt(ArtifactPosition::SPELLBOOK))
  5910. iw.text.addTxt (MetaString::ADVOB_TXT, 109); //no spellbook
  5911. else if (hero->getSecSkillLevel(SecondarySkill::WISDOM) < 3)
  5912. iw.text.addTxt (MetaString::ADVOB_TXT, 108); //no expert Wisdom
  5913. else
  5914. {
  5915. std::set<SpellID> spells;
  5916. spells.insert (SpellID(spell));
  5917. cb->changeSpells (hero, true, spells);
  5918. iw.components.push_back(Component (Component::SPELL, spell, 0, 0));
  5919. }
  5920. cb->showInfoDialog(&iw);
  5921. cb->setObjProperty (id, ObjProperty::BANK_CLEAR_CONFIG, 0);
  5922. }
  5923. }
  5924. void CGKeys::setPropertyDer (ui8 what, ui32 val) //101-108 - enable key for player 1-8
  5925. {
  5926. if (what >= 101 && what <= (100 + PlayerColor::PLAYER_LIMIT_I))
  5927. playerKeyMap.find(PlayerColor(what-101))->second.insert((ui8)val);
  5928. }
  5929. bool CGKeys::wasMyColorVisited (PlayerColor player) const
  5930. {
  5931. if (vstd::contains(playerKeyMap[player], subID)) //creates set if it's not there
  5932. return true;
  5933. else
  5934. return false;
  5935. }
  5936. const std::string& CGKeys::getHoverText() const
  5937. {
  5938. bool visited = wasMyColorVisited (cb->getLocalPlayer());
  5939. hoverName = getName() + "\n" + visitedTxt(visited);
  5940. return hoverName;
  5941. }
  5942. const std::string CGKeys::getName() const
  5943. {
  5944. std::string name;
  5945. name = VLC->generaltexth->tentColors[subID] + " " + VLC->generaltexth->names[ID];
  5946. return name;
  5947. }
  5948. bool CGKeymasterTent::wasVisited (PlayerColor player) const
  5949. {
  5950. return wasMyColorVisited (player);
  5951. }
  5952. void CGKeymasterTent::onHeroVisit( const CGHeroInstance * h ) const
  5953. {
  5954. int txt_id;
  5955. if (!wasMyColorVisited (h->getOwner()) )
  5956. {
  5957. cb->setObjProperty(id, h->tempOwner.getNum()+101, subID);
  5958. txt_id=19;
  5959. }
  5960. else
  5961. txt_id=20;
  5962. showInfoDialog(h,txt_id,soundBase::CAVEHEAD);
  5963. }
  5964. void CGBorderGuard::initObj()
  5965. {
  5966. //ui32 m13489val = subID; //store color as quest info
  5967. blockVisit = true;
  5968. }
  5969. void CGBorderGuard::getVisitText (MetaString &text, std::vector<Component> &components, bool isCustom, bool FirstVisit, const CGHeroInstance * h) const
  5970. {
  5971. text << std::pair<ui8,ui32>(11,18);
  5972. }
  5973. void CGBorderGuard::getRolloverText (MetaString &text, bool onHover) const
  5974. {
  5975. if (!onHover)
  5976. text << VLC->generaltexth->tentColors[subID] << " " << VLC->generaltexth->names[Obj::KEYMASTER];
  5977. }
  5978. bool CGBorderGuard::checkQuest (const CGHeroInstance * h) const
  5979. {
  5980. return wasMyColorVisited (h->tempOwner);
  5981. }
  5982. void CGBorderGuard::onHeroVisit( const CGHeroInstance * h ) const
  5983. {
  5984. if (wasMyColorVisited (h->getOwner()) )
  5985. {
  5986. BlockingDialog bd (true, false);
  5987. bd.player = h->getOwner();
  5988. bd.soundID = soundBase::QUEST;
  5989. bd.text.addTxt (MetaString::ADVOB_TXT, 17);
  5990. cb->showBlockingDialog (&bd);
  5991. }
  5992. else
  5993. {
  5994. showInfoDialog(h,18,soundBase::CAVEHEAD);
  5995. AddQuest aq;
  5996. aq.quest = QuestInfo (quest, this, visitablePos());
  5997. aq.player = h->tempOwner;
  5998. cb->sendAndApply (&aq);
  5999. //TODO: add this quest only once OR check for multiple instances later
  6000. }
  6001. }
  6002. void CGBorderGuard::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  6003. {
  6004. if (answer)
  6005. cb->removeObject(this);
  6006. }
  6007. void CGBorderGate::onHeroVisit( const CGHeroInstance * h ) const //TODO: passability
  6008. {
  6009. if (!wasMyColorVisited (h->getOwner()) )
  6010. {
  6011. showInfoDialog(h,18,0);
  6012. AddQuest aq;
  6013. aq.quest = QuestInfo (quest, this, visitablePos());
  6014. aq.player = h->tempOwner;
  6015. cb->sendAndApply (&aq);
  6016. }
  6017. }
  6018. ui8 CGBorderGate::getPassableness() const
  6019. {
  6020. ui8 ret = 0;
  6021. for (int i = 0; i < PlayerColor::PLAYER_LIMIT_I; i++)
  6022. ret |= wasMyColorVisited(PlayerColor(i))<<i;
  6023. return ret;
  6024. }
  6025. void CGMagi::initObj()
  6026. {
  6027. if (ID == Obj::EYE_OF_MAGI)
  6028. {
  6029. blockVisit = true;
  6030. eyelist[subID].push_back(id);
  6031. }
  6032. }
  6033. void CGMagi::onHeroVisit(const CGHeroInstance * h) const
  6034. {
  6035. if (ID == Obj::HUT_OF_MAGI)
  6036. {
  6037. showInfoDialog(h, 61, soundBase::LIGHTHOUSE);
  6038. if (!eyelist[subID].empty())
  6039. {
  6040. CenterView cv;
  6041. cv.player = h->tempOwner;
  6042. cv.focusTime = 2000;
  6043. FoWChange fw;
  6044. fw.player = h->tempOwner;
  6045. fw.mode = 1;
  6046. for(auto it : eyelist[subID])
  6047. {
  6048. const CGObjectInstance *eye = cb->getObj(it);
  6049. cb->getTilesInRange (fw.tiles, eye->pos, 10, h->tempOwner, 1);
  6050. cb->sendAndApply(&fw);
  6051. cv.pos = eye->pos;
  6052. cb->sendAndApply(&cv);
  6053. }
  6054. cv.pos = h->getPosition(false);
  6055. cb->sendAndApply(&cv);
  6056. }
  6057. }
  6058. else if (ID == Obj::EYE_OF_MAGI)
  6059. {
  6060. showInfoDialog(h,48,soundBase::invalid);
  6061. }
  6062. }
  6063. void CGBoat::initObj()
  6064. {
  6065. hero = nullptr;
  6066. }
  6067. void CGSirens::initObj()
  6068. {
  6069. blockVisit = true;
  6070. }
  6071. const std::string & CGSirens::getHoverText() const
  6072. {
  6073. getNameVis(hoverName);
  6074. return hoverName;
  6075. }
  6076. void CGSirens::onHeroVisit( const CGHeroInstance * h ) const
  6077. {
  6078. InfoWindow iw;
  6079. iw.soundID = soundBase::DANGER;
  6080. iw.player = h->tempOwner;
  6081. if(h->hasBonusFrom(Bonus::OBJECT,ID)) //has already visited Sirens
  6082. {
  6083. iw.text.addTxt(MetaString::ADVOB_TXT,133);
  6084. }
  6085. else
  6086. {
  6087. giveDummyBonus(h->id, Bonus::ONE_BATTLE);
  6088. TExpType xp = 0;
  6089. for (auto i = h->Slots().begin(); i != h->Slots().end(); i++)
  6090. {
  6091. TQuantity drown = i->second->count * 0.3;
  6092. if(drown)
  6093. {
  6094. cb->changeStackCount(StackLocation(h, i->first), -drown);
  6095. xp += drown * i->second->type->valOfBonuses(Bonus::STACK_HEALTH);
  6096. }
  6097. }
  6098. if(xp)
  6099. {
  6100. xp = h->calculateXp(xp);
  6101. iw.text.addTxt(MetaString::ADVOB_TXT,132);
  6102. iw.text.addReplacement(xp);
  6103. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, xp, false);
  6104. }
  6105. else
  6106. {
  6107. iw.text.addTxt(MetaString::ADVOB_TXT,134);
  6108. }
  6109. }
  6110. cb->showInfoDialog(&iw);
  6111. }
  6112. //bool IShipyard::validLocation() const
  6113. //{
  6114. // std::vector<int3> offsets;
  6115. // getOutOffsets(offsets);
  6116. //
  6117. // TerrainTile *tile;
  6118. // for(int i = 0; i < offsets.size(); i++)
  6119. // if((tile = IObjectInterface::cb->getTile(o->pos + offsets[i])) && tile->terType == TerrainTile::water) //tile is in the map and is water
  6120. // return true;
  6121. // return false;
  6122. //}
  6123. int3 IBoatGenerator::bestLocation() const
  6124. {
  6125. std::vector<int3> offsets;
  6126. getOutOffsets(offsets);
  6127. for (auto & offset : offsets)
  6128. {
  6129. if (const TerrainTile *tile = IObjectInterface::cb->getTile(o->pos + offset, false)) //tile is in the map
  6130. {
  6131. if (tile->terType == ETerrainType::WATER && (!tile->blocked || tile->blockingObjects.front()->ID == 8)) //and is water and is not blocked or is blocked by boat
  6132. return o->pos + offset;
  6133. }
  6134. }
  6135. return int3 (-1,-1,-1);
  6136. }
  6137. IBoatGenerator::EGeneratorState IBoatGenerator::shipyardStatus() const
  6138. {
  6139. int3 tile = bestLocation();
  6140. const TerrainTile *t = IObjectInterface::cb->getTile(tile);
  6141. if(!t)
  6142. return TILE_BLOCKED; //no available water
  6143. else if(!t->blockingObjects.size())
  6144. return GOOD; //OK
  6145. else if(t->blockingObjects.front()->ID == Obj::BOAT)
  6146. return BOAT_ALREADY_BUILT; //blocked with boat
  6147. else
  6148. return TILE_BLOCKED; //blocked
  6149. }
  6150. int IBoatGenerator::getBoatType() const
  6151. {
  6152. //We make good ships by default
  6153. return 1;
  6154. }
  6155. IBoatGenerator::IBoatGenerator(const CGObjectInstance *O)
  6156. : o(O)
  6157. {
  6158. }
  6159. void IBoatGenerator::getProblemText(MetaString &out, const CGHeroInstance *visitor) const
  6160. {
  6161. switch(shipyardStatus())
  6162. {
  6163. case BOAT_ALREADY_BUILT:
  6164. out.addTxt(MetaString::GENERAL_TXT, 51);
  6165. break;
  6166. case TILE_BLOCKED:
  6167. if(visitor)
  6168. {
  6169. out.addTxt(MetaString::GENERAL_TXT, 134);
  6170. out.addReplacement(visitor->name);
  6171. }
  6172. else
  6173. out.addTxt(MetaString::ADVOB_TXT, 189);
  6174. break;
  6175. case NO_WATER:
  6176. logGlobal->errorStream() << "Shipyard without water!!! " << o->pos << "\t" << o->id;
  6177. return;
  6178. }
  6179. }
  6180. void IShipyard::getBoatCost( std::vector<si32> &cost ) const
  6181. {
  6182. cost.resize(GameConstants::RESOURCE_QUANTITY);
  6183. cost[Res::WOOD] = 10;
  6184. cost[Res::GOLD] = 1000;
  6185. }
  6186. IShipyard::IShipyard(const CGObjectInstance *O)
  6187. : IBoatGenerator(O)
  6188. {
  6189. }
  6190. IShipyard * IShipyard::castFrom( CGObjectInstance *obj )
  6191. {
  6192. if(!obj)
  6193. return nullptr;
  6194. if(obj->ID == Obj::TOWN)
  6195. {
  6196. return static_cast<CGTownInstance*>(obj);
  6197. }
  6198. else if(obj->ID == Obj::SHIPYARD)
  6199. {
  6200. return static_cast<CGShipyard*>(obj);
  6201. }
  6202. else
  6203. {
  6204. return nullptr;
  6205. }
  6206. }
  6207. const IShipyard * IShipyard::castFrom( const CGObjectInstance *obj )
  6208. {
  6209. return castFrom(const_cast<CGObjectInstance*>(obj));
  6210. }
  6211. CGShipyard::CGShipyard()
  6212. :IShipyard(this)
  6213. {
  6214. }
  6215. void CGShipyard::getOutOffsets( std::vector<int3> &offsets ) const
  6216. {
  6217. // H J L K I
  6218. // A x S x B
  6219. // C E G F D
  6220. offsets += int3(-3,0,0), int3(1,0,0), //AB
  6221. int3(-3,1,0), int3(1,1,0), int3(-2,1,0), int3(0,1,0), int3(-1,1,0), //CDEFG
  6222. int3(-3,-1,0), int3(1,-1,0), int3(-2,-1,0), int3(0,-1,0), int3(-1,-1,0); //HIJKL
  6223. }
  6224. void CGShipyard::onHeroVisit( const CGHeroInstance * h ) const
  6225. {
  6226. if(!cb->gameState()->getPlayerRelations(tempOwner, h->tempOwner))
  6227. cb->setOwner(this, h->tempOwner);
  6228. auto s = shipyardStatus();
  6229. if(s != IBoatGenerator::GOOD)
  6230. {
  6231. InfoWindow iw;
  6232. iw.player = tempOwner;
  6233. getProblemText(iw.text, h);
  6234. cb->showInfoDialog(&iw);
  6235. }
  6236. else
  6237. {
  6238. openWindow(OpenWindow::SHIPYARD_WINDOW,id.getNum(),h->id.getNum());
  6239. }
  6240. }
  6241. void CCartographer::onHeroVisit( const CGHeroInstance * h ) const
  6242. {
  6243. if (!wasVisited (h->getOwner()) ) //if hero has not visited yet this cartographer
  6244. {
  6245. if (cb->getResource(h->tempOwner, Res::GOLD) >= 1000) //if he can afford a map
  6246. {
  6247. //ask if he wants to buy one
  6248. int text=0;
  6249. switch (subID)
  6250. {
  6251. case 0:
  6252. text = 25;
  6253. break;
  6254. case 1:
  6255. text = 26;
  6256. break;
  6257. case 2:
  6258. text = 27;
  6259. break;
  6260. default:
  6261. logGlobal->warnStream() << "Unrecognized subtype of cartographer";
  6262. }
  6263. assert(text);
  6264. BlockingDialog bd (true, false);
  6265. bd.player = h->getOwner();
  6266. bd.soundID = soundBase::LIGHTHOUSE;
  6267. bd.text.addTxt (MetaString::ADVOB_TXT, text);
  6268. cb->showBlockingDialog (&bd);
  6269. }
  6270. else //if he cannot afford
  6271. {
  6272. showInfoDialog(h,28,soundBase::CAVEHEAD);
  6273. }
  6274. }
  6275. else //if he already visited carographer
  6276. {
  6277. showInfoDialog(h,24,soundBase::CAVEHEAD);
  6278. }
  6279. }
  6280. void CCartographer::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  6281. {
  6282. if (answer) //if hero wants to buy map
  6283. {
  6284. cb->giveResource (hero->tempOwner, Res::GOLD, -1000);
  6285. FoWChange fw;
  6286. fw.mode = 1;
  6287. fw.player = hero->tempOwner;
  6288. //subIDs of different types of cartographers:
  6289. //water = 0; land = 1; underground = 2;
  6290. cb->getAllTiles (fw.tiles, hero->tempOwner, subID - 1, !subID + 1); //reveal appropriate tiles
  6291. cb->sendAndApply (&fw);
  6292. cb->setObjProperty (id, 10, hero->tempOwner.getNum());
  6293. }
  6294. }
  6295. void CGDenOfthieves::onHeroVisit (const CGHeroInstance * h) const
  6296. {
  6297. cb->showThievesGuildWindow(h->tempOwner, id);
  6298. }
  6299. void CGObelisk::onHeroVisit( const CGHeroInstance * h ) const
  6300. {
  6301. InfoWindow iw;
  6302. iw.player = h->tempOwner;
  6303. TeamState *ts = cb->gameState()->getPlayerTeam(h->tempOwner);
  6304. assert(ts);
  6305. TeamID team = ts->id;
  6306. if(!wasVisited(team))
  6307. {
  6308. iw.text.addTxt(MetaString::ADVOB_TXT, 96);
  6309. cb->sendAndApply(&iw);
  6310. cb->setObjProperty(id, 20, h->tempOwner.getNum()); //increment general visited obelisks counter
  6311. openWindow(OpenWindow::PUZZLE_MAP, h->tempOwner.getNum());
  6312. cb->setObjProperty(id, 10, h->tempOwner.getNum()); //mark that particular obelisk as visited
  6313. }
  6314. else
  6315. {
  6316. iw.text.addTxt(MetaString::ADVOB_TXT, 97);
  6317. cb->sendAndApply(&iw);
  6318. }
  6319. }
  6320. void CGObelisk::initObj()
  6321. {
  6322. obeliskCount++;
  6323. }
  6324. const std::string & CGObelisk::getHoverText() const
  6325. {
  6326. bool visited = wasVisited(cb->getLocalPlayer());
  6327. hoverName = VLC->generaltexth->names[ID] + " " + visitedTxt(visited);
  6328. return hoverName;
  6329. }
  6330. void CGObelisk::setPropertyDer( ui8 what, ui32 val )
  6331. {
  6332. CPlayersVisited::setPropertyDer(what, val);
  6333. switch(what)
  6334. {
  6335. case 20:
  6336. assert(val < PlayerColor::PLAYER_LIMIT_I);
  6337. visited[TeamID(val)]++;
  6338. if(visited[TeamID(val)] > obeliskCount)
  6339. {
  6340. logGlobal->errorStream() << "Error: Visited " << visited[TeamID(val)] << "\t\t" << obeliskCount;
  6341. assert(0);
  6342. }
  6343. break;
  6344. }
  6345. }
  6346. void CGLighthouse::onHeroVisit( const CGHeroInstance * h ) const
  6347. {
  6348. if(h->tempOwner != tempOwner)
  6349. {
  6350. PlayerColor oldOwner = tempOwner;
  6351. cb->setOwner(this,h->tempOwner); //not ours? flag it!
  6352. showInfoDialog(h,69,soundBase::LIGHTHOUSE);
  6353. giveBonusTo(h->tempOwner);
  6354. if(oldOwner < PlayerColor::PLAYER_LIMIT) //remove bonus from old owner
  6355. {
  6356. RemoveBonus rb(RemoveBonus::PLAYER);
  6357. rb.whoID = oldOwner.getNum();
  6358. rb.source = Bonus::OBJECT;
  6359. rb.id = id.getNum();
  6360. cb->sendAndApply(&rb);
  6361. }
  6362. }
  6363. }
  6364. void CGLighthouse::initObj()
  6365. {
  6366. if(tempOwner < PlayerColor::PLAYER_LIMIT)
  6367. {
  6368. giveBonusTo(tempOwner);
  6369. }
  6370. }
  6371. const std::string & CGLighthouse::getHoverText() const
  6372. {
  6373. hoverName = VLC->generaltexth->names[ID];
  6374. //TODO: owned by %s player
  6375. return hoverName;
  6376. }
  6377. void CGLighthouse::giveBonusTo( PlayerColor player ) const
  6378. {
  6379. GiveBonus gb(GiveBonus::PLAYER);
  6380. gb.bonus.type = Bonus::SEA_MOVEMENT;
  6381. gb.bonus.val = 500;
  6382. gb.id = player.getNum();
  6383. gb.bonus.duration = Bonus::PERMANENT;
  6384. gb.bonus.source = Bonus::OBJECT;
  6385. gb.bonus.sid = id.getNum();
  6386. cb->sendAndApply(&gb);
  6387. }
  6388. void CArmedInstance::randomizeArmy(int type)
  6389. {
  6390. int max = VLC->creh->creatures.size();
  6391. for (auto & elem : stacks)
  6392. {
  6393. int randID = elem.second->idRand;
  6394. if(randID > max)
  6395. {
  6396. int level = (randID-VLC->creh->creatures.size()) / 2 -1;
  6397. bool upgrade = !(randID % 2);
  6398. elem.second->setType(VLC->townh->factions[type]->town->creatures[level][upgrade]);
  6399. randID = -1;
  6400. }
  6401. assert(elem.second->armyObj == this);
  6402. }
  6403. return;
  6404. }
  6405. CArmedInstance::CArmedInstance()
  6406. {
  6407. battle = nullptr;
  6408. }
  6409. //int CArmedInstance::valOfGlobalBonuses(CSelector selector) const
  6410. //{
  6411. //// if (tempOwner != NEUTRAL_PLAYER)
  6412. // return cb->gameState()->players[tempOwner].valOfBonuses(selector);
  6413. //}
  6414. void CArmedInstance::updateMoraleBonusFromArmy()
  6415. {
  6416. if(!validTypes(false)) //object not randomized, don't bother
  6417. return;
  6418. Bonus *b = getBonusList().getFirst(Selector::sourceType(Bonus::ARMY).And(Selector::type(Bonus::MORALE)));
  6419. if(!b)
  6420. {
  6421. b = new Bonus(Bonus::PERMANENT, Bonus::MORALE, Bonus::ARMY, 0, -1);
  6422. addNewBonus(b);
  6423. }
  6424. //number of alignments and presence of undead
  6425. std::set<TFaction> factions;
  6426. bool hasUndead = false;
  6427. for(auto slot : Slots())
  6428. {
  6429. const CStackInstance * inst = slot.second;
  6430. const CCreature * creature = VLC->creh->creatures[inst->getCreatureID()];
  6431. factions.insert(creature->faction);
  6432. // Check for undead flag instead of faction (undead mummies are neutral)
  6433. hasUndead |= inst->hasBonusOfType(Bonus::UNDEAD);
  6434. }
  6435. size_t factionsInArmy = factions.size(); //town garrison seems to take both sets into account
  6436. // Take Angelic Alliance troop-mixing freedom of non-evil units into account.
  6437. if (hasBonusOfType(Bonus::NONEVIL_ALIGNMENT_MIX))
  6438. {
  6439. size_t mixableFactions = 0;
  6440. for(TFaction f : factions)
  6441. {
  6442. if (VLC->townh->factions[f]->alignment != EAlignment::EVIL)
  6443. mixableFactions++;
  6444. }
  6445. if (mixableFactions > 0)
  6446. factionsInArmy -= mixableFactions - 1;
  6447. }
  6448. if(factionsInArmy == 1)
  6449. {
  6450. b->val = +1;
  6451. b->description = VLC->generaltexth->arraytxt[115]; //All troops of one alignment +1
  6452. }
  6453. else if (factions.size()) // no bonus from empty garrison
  6454. {
  6455. b->val = 2 - factionsInArmy;
  6456. b->description = boost::str(boost::format(VLC->generaltexth->arraytxt[114]) % factionsInArmy % b->val); //Troops of %d alignments %d
  6457. }
  6458. boost::algorithm::trim(b->description);
  6459. //-1 modifier for any Undead unit in army
  6460. const ui8 UNDEAD_MODIFIER_ID = -2;
  6461. Bonus *undeadModifier = getBonusList().getFirst(Selector::source(Bonus::ARMY, UNDEAD_MODIFIER_ID));
  6462. if(hasUndead)
  6463. {
  6464. if(!undeadModifier)
  6465. addNewBonus(new Bonus(Bonus::PERMANENT, Bonus::MORALE, Bonus::ARMY, -1, UNDEAD_MODIFIER_ID, VLC->generaltexth->arraytxt[116]));
  6466. }
  6467. else if(undeadModifier)
  6468. removeBonus(undeadModifier);
  6469. }
  6470. void CArmedInstance::armyChanged()
  6471. {
  6472. updateMoraleBonusFromArmy();
  6473. }
  6474. CBonusSystemNode * CArmedInstance::whereShouldBeAttached(CGameState *gs)
  6475. {
  6476. if(tempOwner < PlayerColor::PLAYER_LIMIT)
  6477. return gs->getPlayer(tempOwner);
  6478. else
  6479. return &gs->globalEffects;
  6480. }
  6481. CBonusSystemNode * CArmedInstance::whatShouldBeAttached()
  6482. {
  6483. return this;
  6484. }
  6485. bool IMarket::getOffer(int id1, int id2, int &val1, int &val2, EMarketMode::EMarketMode mode) const
  6486. {
  6487. switch(mode)
  6488. {
  6489. case EMarketMode::RESOURCE_RESOURCE:
  6490. {
  6491. double effectiveness = std::min((getMarketEfficiency() + 1.0) / 20.0, 0.5);
  6492. double r = VLC->objh->resVals[id1], //value of given resource
  6493. g = VLC->objh->resVals[id2] / effectiveness; //value of wanted resource
  6494. if(r>g) //if given resource is more expensive than wanted
  6495. {
  6496. val2 = ceil(r / g);
  6497. val1 = 1;
  6498. }
  6499. else //if wanted resource is more expensive
  6500. {
  6501. val1 = (g / r) + 0.5;
  6502. val2 = 1;
  6503. }
  6504. }
  6505. break;
  6506. case EMarketMode::CREATURE_RESOURCE:
  6507. {
  6508. const double effectivenessArray[] = {0.0, 0.3, 0.45, 0.50, 0.65, 0.7, 0.85, 0.9, 1.0};
  6509. double effectiveness = effectivenessArray[std::min(getMarketEfficiency(), 8)];
  6510. double r = VLC->creh->creatures[id1]->cost[6], //value of given creature in gold
  6511. g = VLC->objh->resVals[id2] / effectiveness; //value of wanted resource
  6512. if(r>g) //if given resource is more expensive than wanted
  6513. {
  6514. val2 = ceil(r / g);
  6515. val1 = 1;
  6516. }
  6517. else //if wanted resource is more expensive
  6518. {
  6519. val1 = (g / r) + 0.5;
  6520. val2 = 1;
  6521. }
  6522. }
  6523. break;
  6524. case EMarketMode::RESOURCE_PLAYER:
  6525. val1 = 1;
  6526. val2 = 1;
  6527. break;
  6528. case EMarketMode::RESOURCE_ARTIFACT:
  6529. {
  6530. double effectiveness = std::min((getMarketEfficiency() + 3.0) / 20.0, 0.6);
  6531. double r = VLC->objh->resVals[id1], //value of offered resource
  6532. g = VLC->arth->artifacts[id2]->price / effectiveness; //value of bought artifact in gold
  6533. if(id1 != 6) //non-gold prices are doubled
  6534. r /= 2;
  6535. val1 = std::max(1, (int)((g / r) + 0.5)); //don't sell arts for less than 1 resource
  6536. val2 = 1;
  6537. }
  6538. break;
  6539. case EMarketMode::ARTIFACT_RESOURCE:
  6540. {
  6541. double effectiveness = std::min((getMarketEfficiency() + 3.0) / 20.0, 0.6);
  6542. double r = VLC->arth->artifacts[id1]->price * effectiveness,
  6543. g = VLC->objh->resVals[id2];
  6544. // if(id2 != 6) //non-gold prices are doubled
  6545. // r /= 2;
  6546. val1 = 1;
  6547. val2 = std::max(1, (int)((r / g) + 0.5)); //at least one resource is given in return
  6548. }
  6549. break;
  6550. case EMarketMode::CREATURE_EXP:
  6551. {
  6552. val1 = 1;
  6553. val2 = (VLC->creh->creatures[id1]->AIValue / 40) * 5;
  6554. }
  6555. break;
  6556. case EMarketMode::ARTIFACT_EXP:
  6557. {
  6558. val1 = 1;
  6559. int givenClass = VLC->arth->artifacts[id1]->getArtClassSerial();
  6560. if(givenClass < 0 || givenClass > 3)
  6561. {
  6562. val2 = 0;
  6563. return false;
  6564. }
  6565. static const int expPerClass[] = {1000, 1500, 3000, 6000};
  6566. val2 = expPerClass[givenClass];
  6567. }
  6568. break;
  6569. default:
  6570. assert(0);
  6571. return false;
  6572. }
  6573. return true;
  6574. }
  6575. bool IMarket::allowsTrade(EMarketMode::EMarketMode mode) const
  6576. {
  6577. return false;
  6578. }
  6579. int IMarket::availableUnits(EMarketMode::EMarketMode mode, int marketItemSerial) const
  6580. {
  6581. switch(mode)
  6582. {
  6583. case EMarketMode::RESOURCE_RESOURCE:
  6584. case EMarketMode::ARTIFACT_RESOURCE:
  6585. case EMarketMode::CREATURE_RESOURCE:
  6586. return -1;
  6587. default:
  6588. return 1;
  6589. }
  6590. }
  6591. std::vector<int> IMarket::availableItemsIds(EMarketMode::EMarketMode mode) const
  6592. {
  6593. std::vector<int> ret;
  6594. switch(mode)
  6595. {
  6596. case EMarketMode::RESOURCE_RESOURCE:
  6597. case EMarketMode::ARTIFACT_RESOURCE:
  6598. case EMarketMode::CREATURE_RESOURCE:
  6599. for (int i = 0; i < 7; i++)
  6600. ret.push_back(i);
  6601. default:
  6602. break;
  6603. }
  6604. return ret;
  6605. }
  6606. const IMarket * IMarket::castFrom(const CGObjectInstance *obj, bool verbose /*= true*/)
  6607. {
  6608. switch(obj->ID)
  6609. {
  6610. case Obj::TOWN:
  6611. return static_cast<const CGTownInstance*>(obj);
  6612. case Obj::ALTAR_OF_SACRIFICE:
  6613. case Obj::BLACK_MARKET:
  6614. case Obj::TRADING_POST:
  6615. case Obj::TRADING_POST_SNOW:
  6616. case Obj::FREELANCERS_GUILD:
  6617. return static_cast<const CGMarket*>(obj);
  6618. case Obj::UNIVERSITY:
  6619. return static_cast<const CGUniversity*>(obj);
  6620. default:
  6621. if(verbose)
  6622. logGlobal->errorStream() << "Cannot cast to IMarket object with ID " << obj->ID;
  6623. return nullptr;
  6624. }
  6625. }
  6626. IMarket::IMarket(const CGObjectInstance *O)
  6627. :o(O)
  6628. {
  6629. }
  6630. std::vector<EMarketMode::EMarketMode> IMarket::availableModes() const
  6631. {
  6632. std::vector<EMarketMode::EMarketMode> ret;
  6633. for (int i = 0; i < EMarketMode::MARTKET_AFTER_LAST_PLACEHOLDER; i++)
  6634. if(allowsTrade((EMarketMode::EMarketMode)i))
  6635. ret.push_back((EMarketMode::EMarketMode)i);
  6636. return ret;
  6637. }
  6638. void CGMarket::onHeroVisit(const CGHeroInstance * h) const
  6639. {
  6640. openWindow(OpenWindow::MARKET_WINDOW,id.getNum(),h->id.getNum());
  6641. }
  6642. int CGMarket::getMarketEfficiency() const
  6643. {
  6644. return 5;
  6645. }
  6646. bool CGMarket::allowsTrade(EMarketMode::EMarketMode mode) const
  6647. {
  6648. switch(mode)
  6649. {
  6650. case EMarketMode::RESOURCE_RESOURCE:
  6651. case EMarketMode::RESOURCE_PLAYER:
  6652. switch(ID)
  6653. {
  6654. case Obj::TRADING_POST:
  6655. case Obj::TRADING_POST_SNOW:
  6656. return true;
  6657. default:
  6658. return false;
  6659. }
  6660. case EMarketMode::CREATURE_RESOURCE:
  6661. return ID == Obj::FREELANCERS_GUILD;
  6662. //case ARTIFACT_RESOURCE:
  6663. case EMarketMode::RESOURCE_ARTIFACT:
  6664. return ID == Obj::BLACK_MARKET;
  6665. case EMarketMode::ARTIFACT_EXP:
  6666. case EMarketMode::CREATURE_EXP:
  6667. return ID == Obj::ALTAR_OF_SACRIFICE; //TODO? check here for alignment of visiting hero? - would not be coherent with other checks here
  6668. case EMarketMode::RESOURCE_SKILL:
  6669. return ID == Obj::UNIVERSITY;
  6670. default:
  6671. return false;
  6672. }
  6673. }
  6674. int CGMarket::availableUnits(EMarketMode::EMarketMode mode, int marketItemSerial) const
  6675. {
  6676. return -1;
  6677. }
  6678. std::vector<int> CGMarket::availableItemsIds(EMarketMode::EMarketMode mode) const
  6679. {
  6680. switch(mode)
  6681. {
  6682. case EMarketMode::RESOURCE_RESOURCE:
  6683. case EMarketMode::RESOURCE_PLAYER:
  6684. return IMarket::availableItemsIds(mode);
  6685. default:
  6686. return std::vector<int>();
  6687. }
  6688. }
  6689. CGMarket::CGMarket()
  6690. :IMarket(this)
  6691. {
  6692. }
  6693. std::vector<int> CGBlackMarket::availableItemsIds(EMarketMode::EMarketMode mode) const
  6694. {
  6695. switch(mode)
  6696. {
  6697. case EMarketMode::ARTIFACT_RESOURCE:
  6698. return IMarket::availableItemsIds(mode);
  6699. case EMarketMode::RESOURCE_ARTIFACT:
  6700. {
  6701. std::vector<int> ret;
  6702. for(const CArtifact *a : artifacts)
  6703. if(a)
  6704. ret.push_back(a->id);
  6705. else
  6706. ret.push_back(-1);
  6707. return ret;
  6708. }
  6709. default:
  6710. return std::vector<int>();
  6711. }
  6712. }
  6713. void CGBlackMarket::newTurn() const
  6714. {
  6715. if(cb->getDate(Date::DAY_OF_MONTH) != 1) //new month
  6716. return;
  6717. SetAvailableArtifacts saa;
  6718. saa.id = id.getNum();
  6719. cb->pickAllowedArtsSet(saa.arts);
  6720. cb->sendAndApply(&saa);
  6721. }
  6722. void CGUniversity::initObj()
  6723. {
  6724. std::vector <int> toChoose;
  6725. for (int i=0; i<GameConstants::SKILL_QUANTITY; i++)
  6726. if (cb->isAllowed(2,i))
  6727. toChoose.push_back(i);
  6728. if (toChoose.size() < 4)
  6729. {
  6730. logGlobal->warnStream()<<"Warning: less then 4 available skills was found by University initializer!";
  6731. return;
  6732. }
  6733. for (int i=0; i<4; i++)//get 4 skills
  6734. {
  6735. int skillPos = ran()%toChoose.size();
  6736. skills.push_back(toChoose[skillPos]);//move it to selected
  6737. toChoose.erase(toChoose.begin()+skillPos);//remove from list
  6738. }
  6739. }
  6740. std::vector<int> CGUniversity::availableItemsIds(EMarketMode::EMarketMode mode) const
  6741. {
  6742. switch (mode)
  6743. {
  6744. case EMarketMode::RESOURCE_SKILL:
  6745. return skills;
  6746. default:
  6747. return std::vector <int> ();
  6748. }
  6749. }
  6750. void CGUniversity::onHeroVisit(const CGHeroInstance * h) const
  6751. {
  6752. openWindow(OpenWindow::UNIVERSITY_WINDOW,id.getNum(),h->id.getNum());
  6753. }
  6754. GrowthInfo::Entry::Entry(const std::string &format, int _count)
  6755. : count(_count)
  6756. {
  6757. description = boost::str(boost::format(format) % count);
  6758. }
  6759. GrowthInfo::Entry::Entry(int subID, BuildingID building, int _count)
  6760. : count(_count)
  6761. {
  6762. description = boost::str(boost::format("%s %+d") % VLC->townh->factions[subID]->town->buildings[building]->Name() % count);
  6763. }
  6764. CTownAndVisitingHero::CTownAndVisitingHero()
  6765. {
  6766. setNodeType(TOWN_AND_VISITOR);
  6767. }
  6768. int GrowthInfo::totalGrowth() const
  6769. {
  6770. int ret = 0;
  6771. for(const Entry &entry : entries)
  6772. ret += entry.count;
  6773. return ret;
  6774. }