CObjectHandler.cpp 198 KB

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