CObjectHandler.cpp 199 KB

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