2
0

CObjectHandler.cpp 203 KB

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