CObjectHandler.cpp 200 KB

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