CObjectHandler.cpp 181 KB

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