CObjectHandler.cpp 196 KB

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