CObjectHandler.cpp 193 KB

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