2
0

CObjectHandler.cpp 193 KB

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