CObjectHandler.cpp 196 KB

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