CObjectHandler.cpp 209 KB

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