CObjectHandler.cpp 194 KB

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