CObjectHandler.cpp 209 KB

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