2
0

player.cpp 254 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  23. // Arcane-FX for MIT Licensed Open Source version of Torque 3D from GarageGames
  24. // Copyright (C) 2015 Faust Logic, Inc.
  25. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  26. #include "platform/platform.h"
  27. #include "T3D/player.h"
  28. #include "platform/profiler.h"
  29. #include "math/mMath.h"
  30. #include "math/mathIO.h"
  31. #include "core/resourceManager.h"
  32. #include "core/stringTable.h"
  33. #include "core/volume.h"
  34. #include "core/stream/bitStream.h"
  35. #include "console/consoleTypes.h"
  36. #include "console/engineAPI.h"
  37. #include "collision/extrudedPolyList.h"
  38. #include "collision/clippedPolyList.h"
  39. #include "collision/earlyOutPolyList.h"
  40. #include "ts/tsShapeInstance.h"
  41. #include "sfx/sfxSystem.h"
  42. #include "sfx/sfxTrack.h"
  43. #include "sfx/sfxSource.h"
  44. #include "sfx/sfxTypes.h"
  45. #include "scene/sceneManager.h"
  46. #include "scene/sceneRenderState.h"
  47. #include "T3D/gameBase/gameConnection.h"
  48. #include "T3D/trigger.h"
  49. #include "T3D/physicalZone.h"
  50. #include "T3D/item.h"
  51. #include "T3D/missionArea.h"
  52. #include "T3D/fx/particleEmitter.h"
  53. #include "T3D/fx/cameraFXMgr.h"
  54. #include "T3D/fx/splash.h"
  55. #include "T3D/tsStatic.h"
  56. #include "T3D/physics/physicsPlugin.h"
  57. #include "T3D/physics/physicsPlayer.h"
  58. #include "T3D/decal/decalManager.h"
  59. #include "T3D/decal/decalData.h"
  60. #include "materials/baseMatInstance.h"
  61. #include "math/mathUtils.h"
  62. #include "gfx/sim/debugDraw.h"
  63. #ifdef TORQUE_EXTENDED_MOVE
  64. #include "T3D/gameBase/extended/extendedMove.h"
  65. #endif
  66. #ifdef TORQUE_OPENVR
  67. #include "platform/input/openVR/openVRProvider.h"
  68. #include "platform/input/openVR/openVRTrackedObject.h"
  69. #endif
  70. // Amount of time if takes to transition to a new action sequence.
  71. static F32 sAnimationTransitionTime = 0.25f;
  72. static bool sUseAnimationTransitions = true;
  73. static F32 sLandReverseScale = 0.25f;
  74. static F32 sSlowStandThreshSquared = 1.69f;
  75. static S32 sRenderMyPlayer = true;
  76. static S32 sRenderMyItems = true;
  77. static bool sRenderPlayerCollision = false;
  78. // Chooses new action animations every n ticks.
  79. static const F32 sNewAnimationTickTime = 4.0f;
  80. static const F32 sMountPendingTickWait = 13.0f * F32(TickMs);
  81. // Number of ticks before we pick non-contact animations
  82. static const S32 sContactTickTime = 10;
  83. // Movement constants
  84. static F32 sVerticalStepDot = 0.173f; // 80
  85. static F32 sMinFaceDistance = 0.01f;
  86. static F32 sTractionDistance = 0.04f;
  87. static F32 sNormalElasticity = 0.01f;
  88. static U32 sMoveRetryCount = 5;
  89. static F32 sMaxImpulseVelocity = 200.0f;
  90. // Move triggers
  91. static S32 sJumpTrigger = 2;
  92. static S32 sCrouchTrigger = 3;
  93. static S32 sProneTrigger = 4;
  94. static S32 sSprintTrigger = 5;
  95. static S32 sImageTrigger0 = 0;
  96. static S32 sImageTrigger1 = 1;
  97. static S32 sJumpJetTrigger = 1;
  98. static S32 sVehicleDismountTrigger = 2;
  99. // Client prediction
  100. static F32 sMinWarpTicks = 0.5f; // Fraction of tick at which instant warp occurs
  101. static S32 sMaxWarpTicks = 3; // Max warp duration in ticks
  102. static S32 sMaxPredictionTicks = 30; // Number of ticks to predict
  103. S32 Player::smExtendedMoveHeadPosRotIndex = 0; // The ExtendedMove position/rotation index used for head movements
  104. //
  105. static U32 sCollisionMoveMask = TerrainObjectType |
  106. WaterObjectType |
  107. PlayerObjectType |
  108. StaticShapeObjectType |
  109. VehicleObjectType |
  110. PhysicalZoneObjectType |
  111. // PATHSHAPE
  112. PathShapeObjectType;
  113. // PATHSHAPE END
  114. static U32 sServerCollisionContactMask = sCollisionMoveMask |
  115. ItemObjectType |
  116. TriggerObjectType |
  117. CorpseObjectType;
  118. static U32 sClientCollisionContactMask = sCollisionMoveMask |
  119. TriggerObjectType;
  120. enum PlayerConstants {
  121. JumpSkipContactsMax = 8
  122. };
  123. //----------------------------------------------------------------------------
  124. // Player shape animation sequences:
  125. // Action Animations:
  126. PlayerData::ActionAnimationDef PlayerData::ActionAnimationList[NumTableActionAnims] =
  127. {
  128. // *** WARNING ***
  129. // This array is indexed using the enum values defined in player.h
  130. // Root is the default animation
  131. { "root" }, // RootAnim,
  132. // These are selected in the move state based on velocity
  133. { "run", { 0.0f, 1.0f, 0.0f } }, // RunForwardAnim,
  134. { "back", { 0.0f,-1.0f, 0.0f } }, // BackBackwardAnim
  135. { "side", {-1.0f, 0.0f, 0.0f } }, // SideLeftAnim,
  136. { "side_right", { 1.0f, 0.0f, 0.0f } }, // SideRightAnim,
  137. { "sprint_root" },
  138. { "sprint_forward", { 0.0f, 1.0f, 0.0f } },
  139. { "sprint_backward", { 0.0f,-1.0f, 0.0f } },
  140. { "sprint_side", {-1.0f, 0.0f, 0.0f } },
  141. { "sprint_right", { 1.0f, 0.0f, 0.0f } },
  142. { "crouch_root" },
  143. { "crouch_forward", { 0.0f, 1.0f, 0.0f } },
  144. { "crouch_backward", { 0.0f,-1.0f, 0.0f } },
  145. { "crouch_side", {-1.0f, 0.0f, 0.0f } },
  146. { "crouch_right", { 1.0f, 0.0f, 0.0f } },
  147. { "prone_root" },
  148. { "prone_forward", { 0.0f, 1.0f, 0.0f } },
  149. { "prone_backward", { 0.0f,-1.0f, 0.0f } },
  150. { "swim_root" },
  151. { "swim_forward", { 0.0f, 1.0f, 0.0f } },
  152. { "swim_backward", { 0.0f,-1.0f, 0.0f } },
  153. { "swim_left", {-1.0f, 0.0f, 0.0f } },
  154. { "swim_right", { 1.0f, 0.0f, 0.0f } },
  155. // These are set explicitly based on player actions
  156. { "fall" }, // FallAnim
  157. { "jump" }, // JumpAnim
  158. { "standjump" }, // StandJumpAnim
  159. { "land" }, // LandAnim
  160. { "jet" }, // JetAnim
  161. };
  162. //----------------------------------------------------------------------------
  163. //----------------------------------------------------------------------------
  164. //----------------------------------------------------------------------------
  165. IMPLEMENT_CO_DATABLOCK_V1(PlayerData);
  166. ConsoleDocClass( PlayerData,
  167. "@brief Defines properties for a Player object.\n\n"
  168. "@see Player\n"
  169. "@ingroup gameObjects\n"
  170. );
  171. IMPLEMENT_CALLBACK( PlayerData, onPoseChange, void, ( Player* obj, const char* oldPose, const char* newPose ), ( obj, oldPose, newPose ),
  172. "@brief Called when the player changes poses.\n\n"
  173. "@param obj The Player object\n"
  174. "@param oldPose The pose the player is switching from.\n"
  175. "@param newPose The pose the player is switching to.\n");
  176. IMPLEMENT_CALLBACK( PlayerData, onStartSwim, void, ( Player* obj ), ( obj ),
  177. "@brief Called when the player starts swimming.\n\n"
  178. "@param obj The Player object\n" );
  179. IMPLEMENT_CALLBACK( PlayerData, onStopSwim, void, ( Player* obj ), ( obj ),
  180. "@brief Called when the player stops swimming.\n\n"
  181. "@param obj The Player object\n" );
  182. IMPLEMENT_CALLBACK( PlayerData, onStartSprintMotion, void, ( Player* obj ), ( obj ),
  183. "@brief Called when the player starts moving while in a Sprint pose.\n\n"
  184. "@param obj The Player object\n" );
  185. IMPLEMENT_CALLBACK( PlayerData, onStopSprintMotion, void, ( Player* obj ), ( obj ),
  186. "@brief Called when the player stops moving while in a Sprint pose.\n\n"
  187. "@param obj The Player object\n" );
  188. IMPLEMENT_CALLBACK( PlayerData, doDismount, void, ( Player* obj ), ( obj ),
  189. "@brief Called when attempting to dismount the player from a vehicle.\n\n"
  190. "It is up to the doDismount() method to actually perform the dismount. Often "
  191. "there are some conditions that prevent this, such as the vehicle moving too fast.\n"
  192. "@param obj The Player object\n" );
  193. IMPLEMENT_CALLBACK( PlayerData, onEnterLiquid, void, ( Player* obj, F32 coverage, const char* type ), ( obj, coverage, type ),
  194. "@brief Called when the player enters a liquid.\n\n"
  195. "@param obj The Player object\n"
  196. "@param coverage Percentage of the player's bounding box covered by the liquid\n"
  197. "@param type The type of liquid the player has entered\n" );
  198. IMPLEMENT_CALLBACK( PlayerData, onLeaveLiquid, void, ( Player* obj, const char* type ), ( obj, type ),
  199. "@brief Called when the player leaves a liquid.\n\n"
  200. "@param obj The Player object\n"
  201. "@param type The type of liquid the player has left\n" );
  202. IMPLEMENT_CALLBACK( PlayerData, animationDone, void, ( Player* obj ), ( obj ),
  203. "@brief Called on the server when a scripted animation completes.\n\n"
  204. "@param obj The Player object\n"
  205. "@see Player::setActionThread() for setting a scripted animation and its 'hold' parameter to "
  206. "determine if this callback is used.\n" );
  207. IMPLEMENT_CALLBACK( PlayerData, onEnterMissionArea, void, ( Player* obj ), ( obj ),
  208. "@brief Called when the player enters the mission area.\n\n"
  209. "@param obj The Player object\n"
  210. "@see MissionArea\n" );
  211. IMPLEMENT_CALLBACK( PlayerData, onLeaveMissionArea, void, ( Player* obj ), ( obj ),
  212. "@brief Called when the player leaves the mission area.\n"
  213. "@param obj The Player object\n"
  214. "@see MissionArea\n" );
  215. PlayerData::PlayerData()
  216. {
  217. shadowEnable = true;
  218. shadowSize = 256;
  219. shadowProjectionDistance = 14.0f;
  220. renderFirstPerson = true;
  221. firstPersonShadows = false;
  222. // Used for third person image rendering
  223. imageAnimPrefix = StringTable->EmptyString();
  224. allowImageStateAnimation = false;
  225. // Used for first person image rendering
  226. imageAnimPrefixFP = StringTable->EmptyString();
  227. for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
  228. {
  229. shapeNameFP[i] = StringTable->EmptyString();
  230. mCRCFP[i] = 0;
  231. mValidShapeFP[i] = false;
  232. }
  233. pickupRadius = 0.0f;
  234. minLookAngle = -1.4f;
  235. maxLookAngle = 1.4f;
  236. maxFreelookAngle = 3.0f;
  237. maxTimeScale = 1.5f;
  238. mass = 9.0f; // from ShapeBase
  239. maxEnergy = 60.0f; // from ShapeBase
  240. drag = 0.3f; // from ShapeBase
  241. density = 1.1f; // from ShapeBase
  242. maxStepHeight = 1.0f;
  243. runSurfaceAngle = 80.0f;
  244. fallingSpeedThreshold = -10.0f;
  245. recoverDelay = 30;
  246. recoverRunForceScale = 1.0f;
  247. landSequenceTime = 0.0f;
  248. transitionToLand = false;
  249. // Running/Walking
  250. runForce = 40.0f * 9.0f;
  251. runEnergyDrain = 0.0f;
  252. minRunEnergy = 0.0f;
  253. maxForwardSpeed = 10.0f;
  254. maxBackwardSpeed = 10.0f;
  255. maxSideSpeed = 10.0f;
  256. // Jumping
  257. jumpForce = 75.0f;
  258. jumpEnergyDrain = 0.0f;
  259. minJumpEnergy = 0.0f;
  260. jumpSurfaceAngle = 78.0f;
  261. jumpSurfaceCos = mCos(mDegToRad(jumpSurfaceAngle));
  262. for (U32 i = 0; i < NumRecoilSequences; i++)
  263. recoilSequence[i] = -1;
  264. jumpDelay = 30;
  265. minJumpSpeed = 500.0f;
  266. maxJumpSpeed = 2.0f * minJumpSpeed;
  267. // Sprinting
  268. sprintForce = 50.0f * 9.0f;
  269. sprintEnergyDrain = 0.0f;
  270. minSprintEnergy = 0.0f;
  271. maxSprintForwardSpeed = 15.0f;
  272. maxSprintBackwardSpeed = 10.0f;
  273. maxSprintSideSpeed = 10.0f;
  274. sprintStrafeScale = 1.0f;
  275. sprintYawScale = 1.0f;
  276. sprintPitchScale = 1.0f;
  277. sprintCanJump = true;
  278. // Swimming
  279. swimForce = 55.0f * 9.0f;
  280. maxUnderwaterForwardSpeed = 6.0f;
  281. maxUnderwaterBackwardSpeed = 6.0f;
  282. maxUnderwaterSideSpeed = 6.0f;
  283. // Crouching
  284. crouchForce = 45.0f * 9.0f;
  285. maxCrouchForwardSpeed = 4.0f;
  286. maxCrouchBackwardSpeed = 4.0f;
  287. maxCrouchSideSpeed = 4.0f;
  288. // Prone
  289. proneForce = 45.0f * 9.0f;
  290. maxProneForwardSpeed = 2.0f;
  291. maxProneBackwardSpeed = 2.0f;
  292. maxProneSideSpeed = 0.0f;
  293. // Jetting
  294. jetJumpForce = 0;
  295. jetJumpEnergyDrain = 0;
  296. jetMinJumpEnergy = 0;
  297. jetJumpSurfaceAngle = 78;
  298. jetMinJumpSpeed = 20;
  299. jetMaxJumpSpeed = 100;
  300. horizMaxSpeed = 80.0f;
  301. horizResistSpeed = 38.0f;
  302. horizResistFactor = 1.0f;
  303. upMaxSpeed = 80.0f;
  304. upResistSpeed = 38.0f;
  305. upResistFactor = 1.0f;
  306. minImpactSpeed = 25.0f;
  307. minLateralImpactSpeed = 25.0f;
  308. decalData = NULL;
  309. decalID = 0;
  310. decalOffset = 0.0f;
  311. actionCount = 0;
  312. lookAction = 0;
  313. dMemset(spineNode, 0, sizeof(spineNode));
  314. pickupDelta = 0.0f;
  315. // size of bounding box
  316. boxSize.set(1.0f, 1.0f, 2.3f);
  317. crouchBoxSize.set(1.0f, 1.0f, 2.0f);
  318. proneBoxSize.set(1.0f, 2.3f, 1.0f);
  319. swimBoxSize.set(1.0f, 2.3f, 1.0f);
  320. // location of head, torso, legs
  321. boxHeadPercentage = 0.85f;
  322. boxTorsoPercentage = 0.55f;
  323. // damage locations
  324. boxHeadLeftPercentage = 0;
  325. boxHeadRightPercentage = 1;
  326. boxHeadBackPercentage = 0;
  327. boxHeadFrontPercentage = 1;
  328. for (S32 i = 0; i < MaxSounds; i++)
  329. sound[i] = NULL;
  330. footPuffEmitter = NULL;
  331. footPuffID = 0;
  332. footPuffNumParts = 15;
  333. footPuffRadius = .25f;
  334. dustEmitter = NULL;
  335. dustID = 0;
  336. splash = NULL;
  337. splashId = 0;
  338. splashVelocity = 1.0f;
  339. splashAngle = 45.0f;
  340. splashFreqMod = 300.0f;
  341. splashVelEpsilon = 0.25f;
  342. bubbleEmitTime = 0.4f;
  343. medSplashSoundVel = 2.0f;
  344. hardSplashSoundVel = 3.0f;
  345. exitSplashSoundVel = 2.0f;
  346. footSplashHeight = 0.1f;
  347. dMemset( splashEmitterList, 0, sizeof( splashEmitterList ) );
  348. dMemset( splashEmitterIDList, 0, sizeof( splashEmitterIDList ) );
  349. groundImpactMinSpeed = 10.0f;
  350. groundImpactShakeFreq.set( 10.0f, 10.0f, 10.0f );
  351. groundImpactShakeAmp.set( 20.0f, 20.0f, 20.0f );
  352. groundImpactShakeDuration = 1.0f;
  353. groundImpactShakeFalloff = 10.0f;
  354. // Air control
  355. airControl = 0.0f;
  356. jumpTowardsNormal = true;
  357. physicsPlayerType = StringTable->EmptyString();
  358. dMemset( actionList, 0, sizeof(actionList) );
  359. }
  360. bool PlayerData::preload(bool server, String &errorStr)
  361. {
  362. if(!Parent::preload(server, errorStr))
  363. return false;
  364. // Resolve objects transmitted from server
  365. if( !server )
  366. {
  367. for( U32 i = 0; i < MaxSounds; ++ i )
  368. {
  369. String sfxErrorStr;
  370. if( !sfxResolve( &sound[ i ], sfxErrorStr ) )
  371. Con::errorf( "PlayerData::preload: %s", sfxErrorStr.c_str() );
  372. }
  373. }
  374. //
  375. runSurfaceCos = mCos(mDegToRad(runSurfaceAngle));
  376. jumpSurfaceCos = mCos(mDegToRad(jumpSurfaceAngle));
  377. if (minJumpEnergy < jumpEnergyDrain)
  378. minJumpEnergy = jumpEnergyDrain;
  379. // Jetting
  380. if (jetMinJumpEnergy < jetJumpEnergyDrain)
  381. jetMinJumpEnergy = jetJumpEnergyDrain;
  382. // Validate some of the data
  383. if (fallingSpeedThreshold > 0.0f)
  384. Con::printf("PlayerData:: Falling speed threshold should be downwards (negative)");
  385. if (recoverDelay > (1 << RecoverDelayBits) - 1) {
  386. recoverDelay = (1 << RecoverDelayBits) - 1;
  387. Con::printf("PlayerData:: Recover delay exceeds range (0-%d)",recoverDelay);
  388. }
  389. if (jumpDelay > (1 << JumpDelayBits) - 1) {
  390. jumpDelay = (1 << JumpDelayBits) - 1;
  391. Con::printf("PlayerData:: Jump delay exceeds range (0-%d)",jumpDelay);
  392. }
  393. // If we don't have a shape don't crash out trying to
  394. // setup animations and sequences.
  395. if ( mShape )
  396. {
  397. // Go ahead a pre-load the player shape
  398. TSShapeInstance* si = new TSShapeInstance(mShape, false);
  399. TSThread* thread = si->addThread();
  400. // Extract ground transform velocity from animations
  401. // Get the named ones first so they can be indexed directly.
  402. ActionAnimation *dp = &actionList[0];
  403. for (S32 i = 0; i < NumTableActionAnims; i++,dp++)
  404. {
  405. ActionAnimationDef *sp = &ActionAnimationList[i];
  406. dp->name = sp->name;
  407. dp->dir.set(sp->dir.x,sp->dir.y,sp->dir.z);
  408. dp->sequence = mShape->findSequence(sp->name);
  409. // If this is a sprint action and is missing a sequence, attempt to use
  410. // the standard run ones.
  411. if(dp->sequence == -1 && i >= SprintRootAnim && i <= SprintRightAnim)
  412. {
  413. S32 offset = i-SprintRootAnim;
  414. ActionAnimationDef *standDef = &ActionAnimationList[RootAnim+offset];
  415. dp->sequence = mShape->findSequence(standDef->name);
  416. }
  417. dp->velocityScale = true;
  418. dp->death = false;
  419. if (dp->sequence != -1)
  420. getGroundInfo(si,thread,dp);
  421. }
  422. for (S32 b = 0; b < mShape->sequences.size(); b++)
  423. {
  424. if (!isTableSequence(b))
  425. {
  426. dp->sequence = b;
  427. dp->name = mShape->getName(mShape->sequences[b].nameIndex);
  428. dp->velocityScale = false;
  429. getGroundInfo(si,thread,dp++);
  430. }
  431. }
  432. actionCount = dp - actionList;
  433. AssertFatal(actionCount <= NumActionAnims, "Too many action animations!");
  434. delete si;
  435. // Resolve lookAction index
  436. dp = &actionList[0];
  437. String lookName("look");
  438. for (S32 c = 0; c < actionCount; c++,dp++)
  439. if( dStricmp( dp->name, lookName ) == 0 )
  440. lookAction = c;
  441. // Resolve spine
  442. spineNode[0] = mShape->findNode("Bip01 Pelvis");
  443. spineNode[1] = mShape->findNode("Bip01 Spine");
  444. spineNode[2] = mShape->findNode("Bip01 Spine1");
  445. spineNode[3] = mShape->findNode("Bip01 Spine2");
  446. spineNode[4] = mShape->findNode("Bip01 Neck");
  447. spineNode[5] = mShape->findNode("Bip01 Head");
  448. // Recoil animations
  449. recoilSequence[0] = mShape->findSequence("light_recoil");
  450. recoilSequence[1] = mShape->findSequence("medium_recoil");
  451. recoilSequence[2] = mShape->findSequence("heavy_recoil");
  452. }
  453. // Convert pickupRadius to a delta of boundingBox
  454. //
  455. // NOTE: it is not really correct to precalculate a pickupRadius based
  456. // on boxSize since the actual player's bounds can vary by "pose".
  457. //
  458. F32 dr = (boxSize.x > boxSize.y)? boxSize.x: boxSize.y;
  459. if (pickupRadius < dr)
  460. pickupRadius = dr;
  461. else
  462. if (pickupRadius > 2.0f * dr)
  463. pickupRadius = 2.0f * dr;
  464. pickupDelta = (S32)(pickupRadius - dr);
  465. // Validate jump speed
  466. if (maxJumpSpeed <= minJumpSpeed)
  467. maxJumpSpeed = minJumpSpeed + 0.1f;
  468. // Load up all the emitters
  469. if (!footPuffEmitter && footPuffID != 0)
  470. if (!Sim::findObject(footPuffID, footPuffEmitter))
  471. Con::errorf(ConsoleLogEntry::General, "PlayerData::preload - Invalid packet, bad datablockId(footPuffEmitter): 0x%x", footPuffID);
  472. if (!decalData && decalID != 0 )
  473. if (!Sim::findObject(decalID, decalData))
  474. Con::errorf(ConsoleLogEntry::General, "PlayerData::preload Invalid packet, bad datablockId(decalData): 0x%x", decalID);
  475. if (!dustEmitter && dustID != 0 )
  476. if (!Sim::findObject(dustID, dustEmitter))
  477. Con::errorf(ConsoleLogEntry::General, "PlayerData::preload - Invalid packet, bad datablockId(dustEmitter): 0x%x", dustID);
  478. for (S32 i=0; i<NUM_SPLASH_EMITTERS; i++)
  479. if( !splashEmitterList[i] && splashEmitterIDList[i] != 0 )
  480. if( Sim::findObject( splashEmitterIDList[i], splashEmitterList[i] ) == false)
  481. Con::errorf(ConsoleLogEntry::General, "PlayerData::onAdd - Invalid packet, bad datablockId(particle emitter): 0x%x", splashEmitterIDList[i]);
  482. // First person mounted image shapes.
  483. for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
  484. {
  485. bool shapeError = false;
  486. if (shapeNameFP[i] && shapeNameFP[i][0])
  487. {
  488. mShapeFP[i] = ResourceManager::get().load(shapeNameFP[i]);
  489. if (bool(mShapeFP[i]) == false)
  490. {
  491. errorStr = String::ToString("PlayerData: Couldn't load mounted image %d shape \"%s\"",i,shapeNameFP[i]);
  492. return false;
  493. }
  494. if(!server && !mShapeFP[i]->preloadMaterialList(mShapeFP[i].getPath()) && NetConnection::filesWereDownloaded())
  495. shapeError = true;
  496. if(computeCRC)
  497. {
  498. Con::printf("Validation required for mounted image %d shape: %s", i, shapeNameFP[i]);
  499. Torque::FS::FileNodeRef fileRef = Torque::FS::GetFileNode(mShapeFP[i].getPath());
  500. if (!fileRef)
  501. {
  502. errorStr = String::ToString("PlayerData: Mounted image %d loading failed, shape \"%s\" is not found.",i,mShapeFP[i].getPath().getFullPath().c_str());
  503. return false;
  504. }
  505. if(server)
  506. mCRCFP[i] = fileRef->getChecksum();
  507. else if(mCRCFP[i] != fileRef->getChecksum())
  508. {
  509. errorStr = String::ToString("PlayerData: Mounted image %d shape \"%s\" does not match version on server.",i,shapeNameFP[i]);
  510. return false;
  511. }
  512. }
  513. mValidShapeFP[i] = true;
  514. }
  515. }
  516. return true;
  517. }
  518. void PlayerData::getGroundInfo(TSShapeInstance* si, TSThread* thread,ActionAnimation *dp)
  519. {
  520. dp->death = !dStrnicmp(dp->name, "death", 5);
  521. if (dp->death)
  522. {
  523. // Death animations use roll frame-to-frame changes in ground transform into position
  524. dp->speed = 0.0f;
  525. dp->dir.set(0.0f, 0.0f, 0.0f);
  526. // Death animations MUST define ground transforms, so add dummy ones if required
  527. if (si->getShape()->sequences[dp->sequence].numGroundFrames == 0)
  528. si->getShape()->setSequenceGroundSpeed(dp->name, Point3F(0, 0, 0), Point3F(0, 0, 0));
  529. }
  530. else
  531. {
  532. VectorF save = dp->dir;
  533. si->setSequence(thread,dp->sequence,0);
  534. si->animate();
  535. si->advanceTime(1);
  536. si->animateGround();
  537. si->getGroundTransform().getColumn(3,&dp->dir);
  538. if ((dp->speed = dp->dir.len()) < 0.01f)
  539. {
  540. // No ground displacement... In this case we'll use the
  541. // default table entry, if there is one.
  542. if (save.len() > 0.01f)
  543. {
  544. dp->dir = save;
  545. dp->speed = 1.0f;
  546. dp->velocityScale = false;
  547. }
  548. else
  549. dp->speed = 0.0f;
  550. }
  551. else
  552. dp->dir *= 1.0f / dp->speed;
  553. }
  554. }
  555. bool PlayerData::isTableSequence(S32 seq)
  556. {
  557. // The sequences from the table must already have
  558. // been loaded for this to work.
  559. for (S32 i = 0; i < NumTableActionAnims; i++)
  560. if (actionList[i].sequence == seq)
  561. return true;
  562. return false;
  563. }
  564. bool PlayerData::isJumpAction(U32 action)
  565. {
  566. return (action == JumpAnim || action == StandJumpAnim);
  567. }
  568. void PlayerData::initPersistFields()
  569. {
  570. addField( "pickupRadius", TypeF32, Offset(pickupRadius, PlayerData),
  571. "@brief Radius around the player to collide with Items in the scene (on server).\n\n"
  572. "Internally the pickupRadius is added to the larger side of the initial bounding box "
  573. "to determine the actual distance, to a maximum of 2 times the bounding box size. The "
  574. "initial bounding box is that used for the root pose, and therefore doesn't take into "
  575. "account the change in pose.\n");
  576. addField( "maxTimeScale", TypeF32, Offset(maxTimeScale, PlayerData),
  577. "@brief Maximum time scale for action animations.\n\n"
  578. "If an action animation has a defined ground frame, it is automatically scaled to match the "
  579. "player's ground velocity. This field limits the maximum time scale used even if "
  580. "the player's velocity exceeds it." );
  581. addGroup( "Camera" );
  582. addField( "renderFirstPerson", TypeBool, Offset(renderFirstPerson, PlayerData),
  583. "@brief Flag controlling whether to render the player shape in first person view.\n\n" );
  584. addField( "firstPersonShadows", TypeBool, Offset(firstPersonShadows, PlayerData),
  585. "@brief Forces shadows to be rendered in first person when renderFirstPerson is disabled. Defaults to false.\n\n" );
  586. addField( "minLookAngle", TypeF32, Offset(minLookAngle, PlayerData),
  587. "@brief Lowest angle (in radians) the player can look.\n\n"
  588. "@note An angle of zero is straight ahead, with positive up and negative down." );
  589. addField( "maxLookAngle", TypeF32, Offset(maxLookAngle, PlayerData),
  590. "@brief Highest angle (in radians) the player can look.\n\n"
  591. "@note An angle of zero is straight ahead, with positive up and negative down." );
  592. addField( "maxFreelookAngle", TypeF32, Offset(maxFreelookAngle, PlayerData),
  593. "@brief Defines the maximum left and right angles (in radians) the player can "
  594. "look in freelook mode.\n\n" );
  595. endGroup( "Camera" );
  596. addGroup( "Movement" );
  597. addField( "maxStepHeight", TypeF32, Offset(maxStepHeight, PlayerData),
  598. "@brief Maximum height the player can step up.\n\n"
  599. "The player will automatically step onto changes in ground height less "
  600. "than maxStepHeight. The player will collide with ground height changes "
  601. "greater than this." );
  602. addField( "runForce", TypeF32, Offset(runForce, PlayerData),
  603. "@brief Force used to accelerate the player when running.\n\n" );
  604. addField( "runEnergyDrain", TypeF32, Offset(runEnergyDrain, PlayerData),
  605. "@brief Energy value drained each tick that the player is moving.\n\n"
  606. "The player will not be able to move when his energy falls below "
  607. "minRunEnergy.\n"
  608. "@note Setting this to zero will disable any energy drain.\n"
  609. "@see minRunEnergy\n");
  610. addField( "minRunEnergy", TypeF32, Offset(minRunEnergy, PlayerData),
  611. "@brief Minimum energy level required to run or swim.\n\n"
  612. "@see runEnergyDrain\n");
  613. addField( "maxForwardSpeed", TypeF32, Offset(maxForwardSpeed, PlayerData),
  614. "@brief Maximum forward speed when running." );
  615. addField( "maxBackwardSpeed", TypeF32, Offset(maxBackwardSpeed, PlayerData),
  616. "@brief Maximum backward speed when running." );
  617. addField( "maxSideSpeed", TypeF32, Offset(maxSideSpeed, PlayerData),
  618. "@brief Maximum sideways speed when running." );
  619. addField( "runSurfaceAngle", TypeF32, Offset(runSurfaceAngle, PlayerData),
  620. "@brief Maximum angle from vertical (in degrees) the player can run up.\n\n" );
  621. addField( "minImpactSpeed", TypeF32, Offset(minImpactSpeed, PlayerData),
  622. "@brief Minimum impact speed to apply falling damage.\n\n"
  623. "This field also sets the minimum speed for the onImpact callback "
  624. "to be invoked.\n"
  625. "@see ShapeBaseData::onImpact()\n");
  626. addField( "minLateralImpactSpeed", TypeF32, Offset(minLateralImpactSpeed, PlayerData),
  627. "@brief Minimum impact speed to apply non-falling damage.\n\n"
  628. "This field also sets the minimum speed for the onLateralImpact callback "
  629. "to be invoked.\n"
  630. "@see ShapeBaseData::onLateralImpact()\n");
  631. addField( "horizMaxSpeed", TypeF32, Offset(horizMaxSpeed, PlayerData),
  632. "@brief Maximum horizontal speed.\n\n"
  633. "@note This limit is only enforced if the player's horizontal speed "
  634. "exceeds horizResistSpeed.\n"
  635. "@see horizResistSpeed\n"
  636. "@see horizResistFactor\n" );
  637. addField( "horizResistSpeed", TypeF32, Offset(horizResistSpeed, PlayerData),
  638. "@brief Horizontal speed at which resistence will take place.\n\n"
  639. "@see horizMaxSpeed\n"
  640. "@see horizResistFactor\n" );
  641. addField( "horizResistFactor", TypeF32, Offset(horizResistFactor, PlayerData),
  642. "@brief Factor of resistence once horizResistSpeed has been reached.\n\n"
  643. "@see horizMaxSpeed\n"
  644. "@see horizResistSpeed\n" );
  645. addField( "upMaxSpeed", TypeF32, Offset(upMaxSpeed, PlayerData),
  646. "@brief Maximum upwards speed.\n\n"
  647. "@note This limit is only enforced if the player's upward speed exceeds "
  648. "upResistSpeed.\n"
  649. "@see upResistSpeed\n"
  650. "@see upResistFactor\n" );
  651. addField( "upResistSpeed", TypeF32, Offset(upResistSpeed, PlayerData),
  652. "@brief Upwards speed at which resistence will take place.\n\n"
  653. "@see upMaxSpeed\n"
  654. "@see upResistFactor\n" );
  655. addField( "upResistFactor", TypeF32, Offset(upResistFactor, PlayerData),
  656. "@brief Factor of resistence once upResistSpeed has been reached.\n\n"
  657. "@see upMaxSpeed\n"
  658. "@see upResistSpeed\n" );
  659. endGroup( "Movement" );
  660. addGroup( "Movement: Jumping" );
  661. addField( "jumpForce", TypeF32, Offset(jumpForce, PlayerData),
  662. "@brief Force used to accelerate the player when a jump is initiated.\n\n" );
  663. addField( "jumpEnergyDrain", TypeF32, Offset(jumpEnergyDrain, PlayerData),
  664. "@brief Energy level drained each time the player jumps.\n\n"
  665. "@note Setting this to zero will disable any energy drain\n"
  666. "@see minJumpEnergy\n");
  667. addField( "minJumpEnergy", TypeF32, Offset(minJumpEnergy, PlayerData),
  668. "@brief Minimum energy level required to jump.\n\n"
  669. "@see jumpEnergyDrain\n");
  670. addField( "minJumpSpeed", TypeF32, Offset(minJumpSpeed, PlayerData),
  671. "@brief Minimum speed needed to jump.\n\n"
  672. "If the player's own z velocity is greater than this, then it is used to scale "
  673. "the jump speed, up to maxJumpSpeed.\n"
  674. "@see maxJumpSpeed\n");
  675. addField( "maxJumpSpeed", TypeF32, Offset(maxJumpSpeed, PlayerData),
  676. "@brief Maximum vertical speed before the player can no longer jump.\n\n" );
  677. addField( "jumpSurfaceAngle", TypeF32, Offset(jumpSurfaceAngle, PlayerData),
  678. "@brief Angle from vertical (in degrees) where the player can jump.\n\n" );
  679. addField( "jumpDelay", TypeS32, Offset(jumpDelay, PlayerData),
  680. "@brief Delay time in number of ticks ticks between jumps.\n\n" );
  681. addField( "airControl", TypeF32, Offset(airControl, PlayerData),
  682. "@brief Amount of movement control the player has when in the air.\n\n"
  683. "This is applied as a multiplier to the player's x and y motion.\n");
  684. addField( "jumpTowardsNormal", TypeBool, Offset(jumpTowardsNormal, PlayerData),
  685. "@brief Controls the direction of the jump impulse.\n"
  686. "When false, jumps are always in the vertical (+Z) direction. When true "
  687. "jumps are in the direction of the ground normal so long as the player is not "
  688. "directly facing the surface. If the player is directly facing the surface, then "
  689. "they will jump straight up.\n" );
  690. endGroup( "Movement: Jumping" );
  691. addGroup( "Movement: Sprinting" );
  692. addField( "sprintForce", TypeF32, Offset(sprintForce, PlayerData),
  693. "@brief Force used to accelerate the player when sprinting.\n\n" );
  694. addField( "sprintEnergyDrain", TypeF32, Offset(sprintEnergyDrain, PlayerData),
  695. "@brief Energy value drained each tick that the player is sprinting.\n\n"
  696. "The player will not be able to move when his energy falls below "
  697. "sprintEnergyDrain.\n"
  698. "@note Setting this to zero will disable any energy drain.\n"
  699. "@see minSprintEnergy\n");
  700. addField( "minSprintEnergy", TypeF32, Offset(minSprintEnergy, PlayerData),
  701. "@brief Minimum energy level required to sprint.\n\n"
  702. "@see sprintEnergyDrain\n");
  703. addField( "maxSprintForwardSpeed", TypeF32, Offset(maxSprintForwardSpeed, PlayerData),
  704. "@brief Maximum forward speed when sprinting." );
  705. addField( "maxSprintBackwardSpeed", TypeF32, Offset(maxSprintBackwardSpeed, PlayerData),
  706. "@brief Maximum backward speed when sprinting." );
  707. addField( "maxSprintSideSpeed", TypeF32, Offset(maxSprintSideSpeed, PlayerData),
  708. "@brief Maximum sideways speed when sprinting." );
  709. addField( "sprintStrafeScale", TypeF32, Offset(sprintStrafeScale, PlayerData),
  710. "@brief Amount to scale strafing motion vector while sprinting." );
  711. addField( "sprintYawScale", TypeF32, Offset(sprintYawScale, PlayerData),
  712. "@brief Amount to scale yaw motion while sprinting." );
  713. addField( "sprintPitchScale", TypeF32, Offset(sprintPitchScale, PlayerData),
  714. "@brief Amount to scale pitch motion while sprinting." );
  715. addField( "sprintCanJump", TypeBool, Offset(sprintCanJump, PlayerData),
  716. "@brief Can the player jump while sprinting." );
  717. endGroup( "Movement: Sprinting" );
  718. addGroup( "Movement: Swimming" );
  719. addField( "swimForce", TypeF32, Offset(swimForce, PlayerData),
  720. "@brief Force used to accelerate the player when swimming.\n\n" );
  721. addField( "maxUnderwaterForwardSpeed", TypeF32, Offset(maxUnderwaterForwardSpeed, PlayerData),
  722. "@brief Maximum forward speed when underwater.\n\n" );
  723. addField( "maxUnderwaterBackwardSpeed", TypeF32, Offset(maxUnderwaterBackwardSpeed, PlayerData),
  724. "@brief Maximum backward speed when underwater.\n\n" );
  725. addField( "maxUnderwaterSideSpeed", TypeF32, Offset(maxUnderwaterSideSpeed, PlayerData),
  726. "@brief Maximum sideways speed when underwater.\n\n" );
  727. endGroup( "Movement: Swimming" );
  728. addGroup( "Movement: Crouching" );
  729. addField( "crouchForce", TypeF32, Offset(crouchForce, PlayerData),
  730. "@brief Force used to accelerate the player when crouching.\n\n" );
  731. addField( "maxCrouchForwardSpeed", TypeF32, Offset(maxCrouchForwardSpeed, PlayerData),
  732. "@brief Maximum forward speed when crouching.\n\n" );
  733. addField( "maxCrouchBackwardSpeed", TypeF32, Offset(maxCrouchBackwardSpeed, PlayerData),
  734. "@brief Maximum backward speed when crouching.\n\n" );
  735. addField( "maxCrouchSideSpeed", TypeF32, Offset(maxCrouchSideSpeed, PlayerData),
  736. "@brief Maximum sideways speed when crouching.\n\n" );
  737. endGroup( "Movement: Crouching" );
  738. addGroup( "Movement: Prone" );
  739. addField( "proneForce", TypeF32, Offset(proneForce, PlayerData),
  740. "@brief Force used to accelerate the player when prone (laying down).\n\n" );
  741. addField( "maxProneForwardSpeed", TypeF32, Offset(maxProneForwardSpeed, PlayerData),
  742. "@brief Maximum forward speed when prone (laying down).\n\n" );
  743. addField( "maxProneBackwardSpeed", TypeF32, Offset(maxProneBackwardSpeed, PlayerData),
  744. "@brief Maximum backward speed when prone (laying down).\n\n" );
  745. addField( "maxProneSideSpeed", TypeF32, Offset(maxProneSideSpeed, PlayerData),
  746. "@brief Maximum sideways speed when prone (laying down).\n\n" );
  747. endGroup( "Movement: Prone" );
  748. addGroup( "Movement: Jetting" );
  749. addField( "jetJumpForce", TypeF32, Offset(jetJumpForce, PlayerData),
  750. "@brief Force used to accelerate the player when a jet jump is initiated.\n\n" );
  751. addField( "jetJumpEnergyDrain", TypeF32, Offset(jetJumpEnergyDrain, PlayerData),
  752. "@brief Energy level drained each time the player jet jumps.\n\n"
  753. "@note Setting this to zero will disable any energy drain\n"
  754. "@see jetMinJumpEnergy\n");
  755. addField( "jetMinJumpEnergy", TypeF32, Offset(jetMinJumpEnergy, PlayerData),
  756. "@brief Minimum energy level required to jet jump.\n\n"
  757. "@see jetJumpEnergyDrain\n");
  758. addField( "jetMinJumpSpeed", TypeF32, Offset(jetMinJumpSpeed, PlayerData),
  759. "@brief Minimum speed needed to jet jump.\n\n"
  760. "If the player's own z velocity is greater than this, then it is used to scale "
  761. "the jet jump speed, up to jetMaxJumpSpeed.\n"
  762. "@see jetMaxJumpSpeed\n");
  763. addField( "jetMaxJumpSpeed", TypeF32, Offset(jetMaxJumpSpeed, PlayerData),
  764. "@brief Maximum vertical speed before the player can no longer jet jump.\n\n" );
  765. addField( "jetJumpSurfaceAngle", TypeF32, Offset(jetJumpSurfaceAngle, PlayerData),
  766. "@brief Angle from vertical (in degrees) where the player can jet jump.\n\n" );
  767. endGroup( "Movement: Jetting" );
  768. addGroup( "Falling" );
  769. addField( "fallingSpeedThreshold", TypeF32, Offset(fallingSpeedThreshold, PlayerData),
  770. "@brief Downward speed at which we consider the player falling.\n\n" );
  771. addField( "recoverDelay", TypeS32, Offset(recoverDelay, PlayerData),
  772. "@brief Number of ticks for the player to recover from falling.\n\n" );
  773. addField( "recoverRunForceScale", TypeF32, Offset(recoverRunForceScale, PlayerData),
  774. "@brief Scale factor applied to runForce while in the recover state.\n\n"
  775. "This can be used to temporarily slow the player's movement after a fall, or "
  776. "prevent the player from moving at all if set to zero.\n" );
  777. addField( "landSequenceTime", TypeF32, Offset(landSequenceTime, PlayerData),
  778. "@brief Time of land sequence play back when using new recover system.\n\n"
  779. "If greater than 0 then the legacy fall recovery system will be bypassed "
  780. "in favour of just playing the player's land sequence. The time to "
  781. "recover from a fall then becomes this parameter's time and the land "
  782. "sequence's playback will be scaled to match.\n"
  783. "@see transitionToLand\n" );
  784. addField( "transitionToLand", TypeBool, Offset(transitionToLand, PlayerData),
  785. "@brief When going from a fall to a land, should we transition between the two.\n\n"
  786. "@note Only takes affect when landSequenceTime is greater than 0.\n"
  787. "@see landSequenceTime\n" );
  788. endGroup( "Falling" );
  789. addGroup( "Collision" );
  790. addField( "boundingBox", TypePoint3F, Offset(boxSize, PlayerData),
  791. "@brief Size of the bounding box used by the player for collision.\n\n"
  792. "Dimensions are given as \"width depth height\"." );
  793. addField( "crouchBoundingBox", TypePoint3F, Offset(crouchBoxSize, PlayerData),
  794. "@brief Collision bounding box used when the player is crouching.\n\n"
  795. "@see boundingBox" );
  796. addField( "proneBoundingBox", TypePoint3F, Offset(proneBoxSize, PlayerData),
  797. "@brief Collision bounding box used when the player is prone (laying down).\n\n"
  798. "@see boundingBox" );
  799. addField( "swimBoundingBox", TypePoint3F, Offset(swimBoxSize, PlayerData),
  800. "@brief Collision bounding box used when the player is swimming.\n\n"
  801. "@see boundingBox" );
  802. addField( "boxHeadPercentage", TypeF32, Offset(boxHeadPercentage, PlayerData),
  803. "@brief Percentage of the player's bounding box height that represents the head.\n\n"
  804. "Used when computing the damage location.\n"
  805. "@see Player::getDamageLocation" );
  806. addField( "boxTorsoPercentage", TypeF32, Offset(boxTorsoPercentage, PlayerData),
  807. "@brief Percentage of the player's bounding box height that represents the torso.\n\n"
  808. "Used when computing the damage location.\n"
  809. "@see Player::getDamageLocation" );
  810. addField( "boxHeadLeftPercentage", TypeF32, Offset(boxHeadLeftPercentage, PlayerData),
  811. "@brief Percentage of the player's bounding box width that represents the left side of the head.\n\n"
  812. "Used when computing the damage location.\n"
  813. "@see Player::getDamageLocation" );
  814. addField( "boxHeadRightPercentage", TypeF32, Offset(boxHeadRightPercentage, PlayerData),
  815. "@brief Percentage of the player's bounding box width that represents the right side of the head.\n\n"
  816. "Used when computing the damage location.\n"
  817. "@see Player::getDamageLocation" );
  818. addField( "boxHeadBackPercentage", TypeF32, Offset(boxHeadBackPercentage, PlayerData),
  819. "@brief Percentage of the player's bounding box depth that represents the back side of the head.\n\n"
  820. "Used when computing the damage location.\n"
  821. "@see Player::getDamageLocation" );
  822. addField( "boxHeadFrontPercentage", TypeF32, Offset(boxHeadFrontPercentage, PlayerData),
  823. "@brief Percentage of the player's bounding box depth that represents the front side of the head.\n\n"
  824. "Used when computing the damage location.\n"
  825. "@see Player::getDamageLocation" );
  826. endGroup( "Collision" );
  827. addGroup( "Interaction: Footsteps" );
  828. addField( "footPuffEmitter", TYPEID< ParticleEmitterData >(), Offset(footPuffEmitter, PlayerData),
  829. "@brief Particle emitter used to generate footpuffs (particles created as the player "
  830. "walks along the ground).\n\n"
  831. "@note The generation of foot puffs requires the appropriate triggeres to be defined in the "
  832. "player's animation sequences. Without these, no foot puffs will be generated.\n");
  833. addField( "footPuffNumParts", TypeS32, Offset(footPuffNumParts, PlayerData),
  834. "@brief Number of footpuff particles to generate each step.\n\n"
  835. "Each foot puff is randomly placed within the defined foot puff radius. This "
  836. "includes having footPuffNumParts set to one.\n"
  837. "@see footPuffRadius\n");
  838. addField( "footPuffRadius", TypeF32, Offset(footPuffRadius, PlayerData),
  839. "@brief Particle creation radius for footpuff particles.\n\n"
  840. "This is applied to each foot puff particle, even if footPuffNumParts is set to one. So "
  841. "set this value to zero if you want a single foot puff placed at exactly the same location "
  842. "under the player each time.\n");
  843. addField( "dustEmitter", TYPEID< ParticleEmitterData >(), Offset(dustEmitter, PlayerData),
  844. "@brief Emitter used to generate dust particles.\n\n"
  845. "@note Currently unused." );
  846. addField( "decalData", TYPEID< DecalData >(), Offset(decalData, PlayerData),
  847. "@brief Decal to place on the ground for player footsteps.\n\n" );
  848. addField( "decalOffset",TypeF32, Offset(decalOffset, PlayerData),
  849. "@brief Distance from the center of the model to the right foot.\n\n"
  850. "While this defines the distance to the right foot, it is also used to place "
  851. "the left foot decal as well. Just on the opposite side of the player." );
  852. endGroup( "Interaction: Footsteps" );
  853. addGroup( "Interaction: Sounds" );
  854. addField( "FootSoftSound", TypeSFXTrackName, Offset(sound[FootSoft], PlayerData),
  855. "@brief Sound to play when walking on a surface with Material footstepSoundId 0.\n\n" );
  856. addField( "FootHardSound", TypeSFXTrackName, Offset(sound[FootHard], PlayerData),
  857. "@brief Sound to play when walking on a surface with Material footstepSoundId 1.\n\n" );
  858. addField( "FootMetalSound", TypeSFXTrackName, Offset(sound[FootMetal], PlayerData),
  859. "@brief Sound to play when walking on a surface with Material footstepSoundId 2.\n\n" );
  860. addField( "FootSnowSound", TypeSFXTrackName, Offset(sound[FootSnow], PlayerData),
  861. "@brief Sound to play when walking on a surface with Material footstepSoundId 3.\n\n" );
  862. addField( "FootShallowSound", TypeSFXTrackName, Offset(sound[FootShallowSplash], PlayerData),
  863. "@brief Sound to play when walking in water and coverage is less than "
  864. "footSplashHeight.\n\n"
  865. "@see footSplashHeight\n" );
  866. addField( "FootWadingSound", TypeSFXTrackName, Offset(sound[FootWading], PlayerData),
  867. "@brief Sound to play when walking in water and coverage is less than 1, "
  868. "but > footSplashHeight.\n\n"
  869. "@see footSplashHeight\n" );
  870. addField( "FootUnderwaterSound", TypeSFXTrackName, Offset(sound[FootUnderWater], PlayerData),
  871. "@brief Sound to play when walking in water and coverage equals 1.0 "
  872. "(fully underwater).\n\n" );
  873. addField( "FootBubblesSound", TypeSFXTrackName, Offset(sound[FootBubbles], PlayerData),
  874. "@brief Sound to play when walking in water and coverage equals 1.0 "
  875. "(fully underwater).\n\n" );
  876. addField( "movingBubblesSound", TypeSFXTrackName, Offset(sound[MoveBubbles], PlayerData),
  877. "@brief Sound to play when in water and coverage equals 1.0 (fully underwater).\n\n"
  878. "Note that unlike FootUnderwaterSound, this sound plays even if the "
  879. "player is not moving around in the water.\n" );
  880. addField( "waterBreathSound", TypeSFXTrackName, Offset(sound[WaterBreath], PlayerData),
  881. "@brief Sound to play when in water and coverage equals 1.0 (fully underwater).\n\n"
  882. "Note that unlike FootUnderwaterSound, this sound plays even if the "
  883. "player is not moving around in the water.\n" );
  884. addField( "impactSoftSound", TypeSFXTrackName, Offset(sound[ImpactSoft], PlayerData),
  885. "@brief Sound to play after falling on a surface with Material footstepSoundId 0.\n\n" );
  886. addField( "impactHardSound", TypeSFXTrackName, Offset(sound[ImpactHard], PlayerData),
  887. "@brief Sound to play after falling on a surface with Material footstepSoundId 1.\n\n" );
  888. addField( "impactMetalSound", TypeSFXTrackName, Offset(sound[ImpactMetal], PlayerData),
  889. "@brief Sound to play after falling on a surface with Material footstepSoundId 2.\n\n" );
  890. addField( "impactSnowSound", TypeSFXTrackName, Offset(sound[ImpactSnow], PlayerData),
  891. "@brief Sound to play after falling on a surface with Material footstepSoundId 3.\n\n" );
  892. addField( "impactWaterEasy", TypeSFXTrackName, Offset(sound[ImpactWaterEasy], PlayerData),
  893. "@brief Sound to play when entering the water with velocity < "
  894. "mediumSplashSoundVelocity.\n\n"
  895. "@see mediumSplashSoundVelocity\n");
  896. addField( "impactWaterMedium", TypeSFXTrackName, Offset(sound[ImpactWaterMedium], PlayerData),
  897. "@brief Sound to play when entering the water with velocity >= "
  898. "mediumSplashSoundVelocity and < hardSplashSoundVelocity.\n\n"
  899. "@see mediumSplashSoundVelocity\n"
  900. "@see hardSplashSoundVelocity\n");
  901. addField( "impactWaterHard", TypeSFXTrackName, Offset(sound[ImpactWaterHard], PlayerData),
  902. "@brief Sound to play when entering the water with velocity >= "
  903. "hardSplashSoundVelocity.\n\n"
  904. "@see hardSplashSoundVelocity\n");
  905. addField( "exitingWater", TypeSFXTrackName, Offset(sound[ExitWater], PlayerData),
  906. "@brief Sound to play when exiting the water with velocity >= exitSplashSoundVelocity.\n\n"
  907. "@see exitSplashSoundVelocity\n");
  908. endGroup( "Interaction: Sounds" );
  909. addGroup( "Interaction: Splashes" );
  910. addField( "splash", TYPEID< SplashData >(), Offset(splash, PlayerData),
  911. "@brief SplashData datablock used to create splashes when the player moves "
  912. "through water.\n\n" );
  913. addField( "splashVelocity", TypeF32, Offset(splashVelocity, PlayerData),
  914. "@brief Minimum velocity when moving through water to generate splashes.\n\n" );
  915. addField( "splashAngle", TypeF32, Offset(splashAngle, PlayerData),
  916. "@brief Maximum angle (in degrees) from pure vertical movement in water to "
  917. "generate splashes.\n\n" );
  918. addField( "splashFreqMod", TypeF32, Offset(splashFreqMod, PlayerData),
  919. "@brief Multipled by speed to determine the number of splash particles to generate.\n\n" );
  920. addField( "splashVelEpsilon", TypeF32, Offset(splashVelEpsilon, PlayerData),
  921. "@brief Minimum speed to generate splash particles.\n\n" );
  922. addField( "bubbleEmitTime", TypeF32, Offset(bubbleEmitTime, PlayerData),
  923. "@brief Time in seconds to generate bubble particles after entering the water.\n\n" );
  924. addField( "splashEmitter", TYPEID< ParticleEmitterData >(), Offset(splashEmitterList, PlayerData), NUM_SPLASH_EMITTERS,
  925. "@brief Particle emitters used to generate splash particles.\n\n" );
  926. addField( "footstepSplashHeight", TypeF32, Offset(footSplashHeight, PlayerData),
  927. "@brief Water coverage level to choose between FootShallowSound and FootWadingSound.\n\n"
  928. "@see FootShallowSound\n"
  929. "@see FootWadingSound\n");
  930. addField( "mediumSplashSoundVelocity", TypeF32, Offset(medSplashSoundVel, PlayerData),
  931. "@brief Minimum velocity when entering the water for choosing between the impactWaterEasy and "
  932. "impactWaterMedium sounds to play.\n\n"
  933. "@see impactWaterEasy\n"
  934. "@see impactWaterMedium\n" );
  935. addField( "hardSplashSoundVelocity", TypeF32, Offset(hardSplashSoundVel, PlayerData),
  936. "@brief Minimum velocity when entering the water for choosing between the impactWaterMedium and "
  937. "impactWaterHard sound to play.\n\n"
  938. "@see impactWaterMedium\n"
  939. "@see impactWaterHard\n" );
  940. addField( "exitSplashSoundVelocity", TypeF32, Offset(exitSplashSoundVel, PlayerData),
  941. "@brief Minimum velocity when leaving the water for the exitingWater sound to "
  942. "play.\n\n"
  943. "@see exitingWater");
  944. endGroup( "Interaction: Splashes" );
  945. addGroup( "Interaction: Ground Impact" );
  946. addField( "groundImpactMinSpeed", TypeF32, Offset(groundImpactMinSpeed, PlayerData),
  947. "@brief Minimum falling impact speed to apply damage and initiate the camera "
  948. "shaking effect.\n\n" );
  949. addField( "groundImpactShakeFreq", TypePoint3F, Offset(groundImpactShakeFreq, PlayerData),
  950. "@brief Frequency of the camera shake effect after falling.\n\n"
  951. "This is how fast to shake the camera.\n");
  952. addField( "groundImpactShakeAmp", TypePoint3F, Offset(groundImpactShakeAmp, PlayerData),
  953. "@brief Amplitude of the camera shake effect after falling.\n\n"
  954. "This is how much to shake the camera.\n");
  955. addField( "groundImpactShakeDuration", TypeF32, Offset(groundImpactShakeDuration, PlayerData),
  956. "@brief Duration (in seconds) of the camera shake effect after falling.\n\n"
  957. "This is how long to shake the camera.\n");
  958. addField( "groundImpactShakeFalloff", TypeF32, Offset(groundImpactShakeFalloff, PlayerData),
  959. "@brief Falloff factor of the camera shake effect after falling.\n\n"
  960. "This is how to fade the camera shake over the duration.\n");
  961. endGroup( "Interaction: Ground Impact" );
  962. addGroup( "Physics" );
  963. // PhysicsPlayer
  964. addField( "physicsPlayerType", TypeString, Offset(physicsPlayerType, PlayerData),
  965. "@brief Specifies the type of physics used by the player.\n\n"
  966. "This depends on the physics module used. An example is 'Capsule'.\n"
  967. "@note Not current used.\n");
  968. endGroup( "Physics" );
  969. addGroup( "First Person Arms" );
  970. addField( "imageAnimPrefixFP", TypeCaseString, Offset(imageAnimPrefixFP, PlayerData),
  971. "@brief Optional prefix to all mounted image animation sequences in first person.\n\n"
  972. "This defines a prefix that will be added when looking up mounted image "
  973. "animation sequences while in first person. It allows for the customization "
  974. "of a first person image based on the type of player.\n");
  975. // Mounted images arrays
  976. addArray( "Mounted Images", ShapeBase::MaxMountedImages );
  977. addField( "shapeNameFP", TypeShapeFilename, Offset(shapeNameFP, PlayerData), ShapeBase::MaxMountedImages,
  978. "@brief File name of this player's shape that will be used in conjunction with the corresponding mounted image.\n\n"
  979. "These optional parameters correspond to each mounted image slot to indicate a shape that is rendered "
  980. "in addition to the mounted image shape. Typically these are a player's arms (or arm) that is "
  981. "animated along with the mounted image's state animation sequences.\n");
  982. endArray( "Mounted Images" );
  983. endGroup( "First Person Arms" );
  984. addGroup( "Third Person" );
  985. addField( "imageAnimPrefix", TypeCaseString, Offset(imageAnimPrefix, PlayerData),
  986. "@brief Optional prefix to all mounted image animation sequences in third person.\n\n"
  987. "This defines a prefix that will be added when looking up mounted image "
  988. "animation sequences while in third person. It allows for the customization "
  989. "of a third person image based on the type of player.\n");
  990. addField( "allowImageStateAnimation", TypeBool, Offset(allowImageStateAnimation, PlayerData),
  991. "@brief Allow mounted images to request a sequence be played on the Player.\n\n"
  992. "When true a new thread is added to the player to allow for "
  993. "mounted images to request a sequence be played on the player "
  994. "through the image's state machine. It is only optional so "
  995. "that we don't create a TSThread on the player if we don't "
  996. "need to.\n");
  997. endGroup( "Third Person" );
  998. Parent::initPersistFields();
  999. }
  1000. void PlayerData::packData(BitStream* stream)
  1001. {
  1002. Parent::packData(stream);
  1003. stream->writeFlag(renderFirstPerson);
  1004. stream->writeFlag(firstPersonShadows);
  1005. stream->write(minLookAngle);
  1006. stream->write(maxLookAngle);
  1007. stream->write(maxFreelookAngle);
  1008. stream->write(maxTimeScale);
  1009. stream->write(mass);
  1010. stream->write(maxEnergy);
  1011. stream->write(drag);
  1012. stream->write(density);
  1013. stream->write(maxStepHeight);
  1014. stream->write(runForce);
  1015. stream->write(runEnergyDrain);
  1016. stream->write(minRunEnergy);
  1017. stream->write(maxForwardSpeed);
  1018. stream->write(maxBackwardSpeed);
  1019. stream->write(maxSideSpeed);
  1020. stream->write(runSurfaceAngle);
  1021. stream->write(fallingSpeedThreshold);
  1022. stream->write(recoverDelay);
  1023. stream->write(recoverRunForceScale);
  1024. stream->write(landSequenceTime);
  1025. stream->write(transitionToLand);
  1026. // Jumping
  1027. stream->write(jumpForce);
  1028. stream->write(jumpEnergyDrain);
  1029. stream->write(minJumpEnergy);
  1030. stream->write(minJumpSpeed);
  1031. stream->write(maxJumpSpeed);
  1032. stream->write(jumpSurfaceAngle);
  1033. stream->writeInt(jumpDelay,JumpDelayBits);
  1034. // Sprinting
  1035. stream->write(sprintForce);
  1036. stream->write(sprintEnergyDrain);
  1037. stream->write(minSprintEnergy);
  1038. stream->write(maxSprintForwardSpeed);
  1039. stream->write(maxSprintBackwardSpeed);
  1040. stream->write(maxSprintSideSpeed);
  1041. stream->write(sprintStrafeScale);
  1042. stream->write(sprintYawScale);
  1043. stream->write(sprintPitchScale);
  1044. stream->writeFlag(sprintCanJump);
  1045. // Swimming
  1046. stream->write(swimForce);
  1047. stream->write(maxUnderwaterForwardSpeed);
  1048. stream->write(maxUnderwaterBackwardSpeed);
  1049. stream->write(maxUnderwaterSideSpeed);
  1050. // Crouching
  1051. stream->write(crouchForce);
  1052. stream->write(maxCrouchForwardSpeed);
  1053. stream->write(maxCrouchBackwardSpeed);
  1054. stream->write(maxCrouchSideSpeed);
  1055. // Prone
  1056. stream->write(proneForce);
  1057. stream->write(maxProneForwardSpeed);
  1058. stream->write(maxProneBackwardSpeed);
  1059. stream->write(maxProneSideSpeed);
  1060. // Jetting
  1061. stream->write(jetJumpForce);
  1062. stream->write(jetJumpEnergyDrain);
  1063. stream->write(jetMinJumpEnergy);
  1064. stream->write(jetMinJumpSpeed);
  1065. stream->write(jetMaxJumpSpeed);
  1066. stream->write(jetJumpSurfaceAngle);
  1067. stream->write(horizMaxSpeed);
  1068. stream->write(horizResistSpeed);
  1069. stream->write(horizResistFactor);
  1070. stream->write(upMaxSpeed);
  1071. stream->write(upResistSpeed);
  1072. stream->write(upResistFactor);
  1073. stream->write(splashVelocity);
  1074. stream->write(splashAngle);
  1075. stream->write(splashFreqMod);
  1076. stream->write(splashVelEpsilon);
  1077. stream->write(bubbleEmitTime);
  1078. stream->write(medSplashSoundVel);
  1079. stream->write(hardSplashSoundVel);
  1080. stream->write(exitSplashSoundVel);
  1081. stream->write(footSplashHeight);
  1082. // Don't need damage scale on the client
  1083. stream->write(minImpactSpeed);
  1084. stream->write(minLateralImpactSpeed);
  1085. for( U32 i = 0; i < MaxSounds; i++)
  1086. sfxWrite( stream, sound[ i ] );
  1087. mathWrite(*stream, boxSize);
  1088. mathWrite(*stream, crouchBoxSize);
  1089. mathWrite(*stream, proneBoxSize);
  1090. mathWrite(*stream, swimBoxSize);
  1091. if( stream->writeFlag( footPuffEmitter ) )
  1092. {
  1093. stream->writeRangedU32( footPuffEmitter->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast );
  1094. }
  1095. stream->write( footPuffNumParts );
  1096. stream->write( footPuffRadius );
  1097. if( stream->writeFlag( decalData ) )
  1098. {
  1099. stream->writeRangedU32( decalData->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast );
  1100. }
  1101. stream->write(decalOffset);
  1102. if( stream->writeFlag( dustEmitter ) )
  1103. {
  1104. stream->writeRangedU32( dustEmitter->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast );
  1105. }
  1106. if (stream->writeFlag( splash ))
  1107. {
  1108. stream->writeRangedU32(splash->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast);
  1109. }
  1110. for( U32 i=0; i<NUM_SPLASH_EMITTERS; i++ )
  1111. {
  1112. if( stream->writeFlag( splashEmitterList[i] != NULL ) )
  1113. {
  1114. stream->writeRangedU32( splashEmitterList[i]->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast );
  1115. }
  1116. }
  1117. stream->write(groundImpactMinSpeed);
  1118. stream->write(groundImpactShakeFreq.x);
  1119. stream->write(groundImpactShakeFreq.y);
  1120. stream->write(groundImpactShakeFreq.z);
  1121. stream->write(groundImpactShakeAmp.x);
  1122. stream->write(groundImpactShakeAmp.y);
  1123. stream->write(groundImpactShakeAmp.z);
  1124. stream->write(groundImpactShakeDuration);
  1125. stream->write(groundImpactShakeFalloff);
  1126. // Air control
  1127. stream->write(airControl);
  1128. // Jump off at normal
  1129. stream->writeFlag(jumpTowardsNormal);
  1130. stream->writeString(physicsPlayerType);
  1131. // Third person mounted image shapes
  1132. stream->writeString(imageAnimPrefix);
  1133. stream->writeFlag(allowImageStateAnimation);
  1134. // First person mounted image shapes
  1135. stream->writeString(imageAnimPrefixFP);
  1136. for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
  1137. {
  1138. stream->writeString(shapeNameFP[i]);
  1139. // computeCRC is handled in ShapeBaseData
  1140. if (computeCRC)
  1141. {
  1142. stream->write(mCRCFP[i]);
  1143. }
  1144. }
  1145. }
  1146. void PlayerData::unpackData(BitStream* stream)
  1147. {
  1148. Parent::unpackData(stream);
  1149. renderFirstPerson = stream->readFlag();
  1150. firstPersonShadows = stream->readFlag();
  1151. stream->read(&minLookAngle);
  1152. stream->read(&maxLookAngle);
  1153. stream->read(&maxFreelookAngle);
  1154. stream->read(&maxTimeScale);
  1155. stream->read(&mass);
  1156. stream->read(&maxEnergy);
  1157. stream->read(&drag);
  1158. stream->read(&density);
  1159. stream->read(&maxStepHeight);
  1160. stream->read(&runForce);
  1161. stream->read(&runEnergyDrain);
  1162. stream->read(&minRunEnergy);
  1163. stream->read(&maxForwardSpeed);
  1164. stream->read(&maxBackwardSpeed);
  1165. stream->read(&maxSideSpeed);
  1166. stream->read(&runSurfaceAngle);
  1167. stream->read(&fallingSpeedThreshold);
  1168. stream->read(&recoverDelay);
  1169. stream->read(&recoverRunForceScale);
  1170. stream->read(&landSequenceTime);
  1171. stream->read(&transitionToLand);
  1172. // Jumping
  1173. stream->read(&jumpForce);
  1174. stream->read(&jumpEnergyDrain);
  1175. stream->read(&minJumpEnergy);
  1176. stream->read(&minJumpSpeed);
  1177. stream->read(&maxJumpSpeed);
  1178. stream->read(&jumpSurfaceAngle);
  1179. jumpDelay = stream->readInt(JumpDelayBits);
  1180. // Sprinting
  1181. stream->read(&sprintForce);
  1182. stream->read(&sprintEnergyDrain);
  1183. stream->read(&minSprintEnergy);
  1184. stream->read(&maxSprintForwardSpeed);
  1185. stream->read(&maxSprintBackwardSpeed);
  1186. stream->read(&maxSprintSideSpeed);
  1187. stream->read(&sprintStrafeScale);
  1188. stream->read(&sprintYawScale);
  1189. stream->read(&sprintPitchScale);
  1190. sprintCanJump = stream->readFlag();
  1191. // Swimming
  1192. stream->read(&swimForce);
  1193. stream->read(&maxUnderwaterForwardSpeed);
  1194. stream->read(&maxUnderwaterBackwardSpeed);
  1195. stream->read(&maxUnderwaterSideSpeed);
  1196. // Crouching
  1197. stream->read(&crouchForce);
  1198. stream->read(&maxCrouchForwardSpeed);
  1199. stream->read(&maxCrouchBackwardSpeed);
  1200. stream->read(&maxCrouchSideSpeed);
  1201. // Prone
  1202. stream->read(&proneForce);
  1203. stream->read(&maxProneForwardSpeed);
  1204. stream->read(&maxProneBackwardSpeed);
  1205. stream->read(&maxProneSideSpeed);
  1206. // Jetting
  1207. stream->read(&jetJumpForce);
  1208. stream->read(&jetJumpEnergyDrain);
  1209. stream->read(&jetMinJumpEnergy);
  1210. stream->read(&jetMinJumpSpeed);
  1211. stream->read(&jetMaxJumpSpeed);
  1212. stream->read(&jetJumpSurfaceAngle);
  1213. stream->read(&horizMaxSpeed);
  1214. stream->read(&horizResistSpeed);
  1215. stream->read(&horizResistFactor);
  1216. stream->read(&upMaxSpeed);
  1217. stream->read(&upResistSpeed);
  1218. stream->read(&upResistFactor);
  1219. stream->read(&splashVelocity);
  1220. stream->read(&splashAngle);
  1221. stream->read(&splashFreqMod);
  1222. stream->read(&splashVelEpsilon);
  1223. stream->read(&bubbleEmitTime);
  1224. stream->read(&medSplashSoundVel);
  1225. stream->read(&hardSplashSoundVel);
  1226. stream->read(&exitSplashSoundVel);
  1227. stream->read(&footSplashHeight);
  1228. stream->read(&minImpactSpeed);
  1229. stream->read(&minLateralImpactSpeed);
  1230. for( U32 i = 0; i < MaxSounds; i++)
  1231. sfxRead( stream, &sound[ i ] );
  1232. mathRead(*stream, &boxSize);
  1233. mathRead(*stream, &crouchBoxSize);
  1234. mathRead(*stream, &proneBoxSize);
  1235. mathRead(*stream, &swimBoxSize);
  1236. if( stream->readFlag() )
  1237. {
  1238. footPuffID = (S32) stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  1239. }
  1240. stream->read(&footPuffNumParts);
  1241. stream->read(&footPuffRadius);
  1242. if( stream->readFlag() )
  1243. {
  1244. decalID = (S32) stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  1245. }
  1246. stream->read(&decalOffset);
  1247. if( stream->readFlag() )
  1248. {
  1249. dustID = (S32) stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  1250. }
  1251. if (stream->readFlag())
  1252. {
  1253. splashId = stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast );
  1254. }
  1255. for( U32 i=0; i<NUM_SPLASH_EMITTERS; i++ )
  1256. {
  1257. if( stream->readFlag() )
  1258. {
  1259. splashEmitterIDList[i] = stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast );
  1260. }
  1261. }
  1262. stream->read(&groundImpactMinSpeed);
  1263. stream->read(&groundImpactShakeFreq.x);
  1264. stream->read(&groundImpactShakeFreq.y);
  1265. stream->read(&groundImpactShakeFreq.z);
  1266. stream->read(&groundImpactShakeAmp.x);
  1267. stream->read(&groundImpactShakeAmp.y);
  1268. stream->read(&groundImpactShakeAmp.z);
  1269. stream->read(&groundImpactShakeDuration);
  1270. stream->read(&groundImpactShakeFalloff);
  1271. // Air control
  1272. stream->read(&airControl);
  1273. // Jump off at normal
  1274. jumpTowardsNormal = stream->readFlag();
  1275. physicsPlayerType = stream->readSTString();
  1276. // Third person mounted image shapes
  1277. imageAnimPrefix = stream->readSTString();
  1278. allowImageStateAnimation = stream->readFlag();
  1279. // First person mounted image shapes
  1280. imageAnimPrefixFP = stream->readSTString();
  1281. for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
  1282. {
  1283. shapeNameFP[i] = stream->readSTString();
  1284. // computeCRC is handled in ShapeBaseData
  1285. if (computeCRC)
  1286. {
  1287. stream->read(&(mCRCFP[i]));
  1288. }
  1289. }
  1290. }
  1291. //----------------------------------------------------------------------------
  1292. //----------------------------------------------------------------------------
  1293. ImplementEnumType( PlayerPose,
  1294. "@brief The pose of the Player.\n\n"
  1295. "@ingroup gameObjects\n\n")
  1296. { Player::StandPose, "Stand", "Standard movement pose.\n" },
  1297. { Player::SprintPose, "Sprint", "Sprinting pose.\n" },
  1298. { Player::CrouchPose, "Crouch", "Crouch pose.\n" },
  1299. { Player::PronePose, "Prone", "Prone pose.\n" },
  1300. { Player::SwimPose, "Swim", "Swimming pose.\n" },
  1301. EndImplementEnumType;
  1302. //----------------------------------------------------------------------------
  1303. IMPLEMENT_CO_NETOBJECT_V1(Player);
  1304. ConsoleDocClass( Player,
  1305. "@ingroup gameObjects\n"
  1306. );
  1307. F32 Player::mGravity = -20;
  1308. //----------------------------------------------------------------------------
  1309. Player::Player()
  1310. {
  1311. mTypeMask |= PlayerObjectType | DynamicShapeObjectType;
  1312. mDelta.pos = mAnchorPoint = Point3F(0,0,100);
  1313. mDelta.rot = mDelta.head = Point3F(0,0,0);
  1314. mDelta.rotOffset.set(0.0f,0.0f,0.0f);
  1315. mDelta.warpOffset.set(0.0f,0.0f,0.0f);
  1316. mDelta.posVec.set(0.0f,0.0f,0.0f);
  1317. mDelta.rotVec.set(0.0f,0.0f,0.0f);
  1318. mDelta.headVec.set(0.0f,0.0f,0.0f);
  1319. mDelta.warpTicks = 0;
  1320. mDelta.dt = 1.0f;
  1321. mDelta.move = NullMove;
  1322. mPredictionCount = sMaxPredictionTicks;
  1323. mObjToWorld.setColumn(3, mDelta.pos);
  1324. mRot = mDelta.rot;
  1325. mHead = mDelta.head;
  1326. mVelocity.set(0.0f, 0.0f, 0.0f);
  1327. mDataBlock = 0;
  1328. mHeadHThread = mHeadVThread = mRecoilThread = mImageStateThread = 0;
  1329. mArmAnimation.action = PlayerData::NullAnimation;
  1330. mArmAnimation.thread = 0;
  1331. mActionAnimation.action = PlayerData::NullAnimation;
  1332. mActionAnimation.thread = 0;
  1333. mActionAnimation.delayTicks = 0;
  1334. mActionAnimation.forward = true;
  1335. mActionAnimation.firstPerson = false;
  1336. //mActionAnimation.time = 1.0f; //ActionAnimation::Scale;
  1337. mActionAnimation.waitForEnd = false;
  1338. mActionAnimation.holdAtEnd = false;
  1339. mActionAnimation.animateOnServer = false;
  1340. mActionAnimation.atEnd = false;
  1341. mState = MoveState;
  1342. mJetting = false;
  1343. mFalling = false;
  1344. mSwimming = false;
  1345. mInWater = false;
  1346. mPose = StandPose;
  1347. mContactTimer = 0;
  1348. mJumpDelay = 0;
  1349. mJumpSurfaceLastContact = 0;
  1350. mJumpSurfaceNormal.set(0.0f, 0.0f, 1.0f);
  1351. mControlObject = 0;
  1352. dMemset( mSplashEmitter, 0, sizeof( mSplashEmitter ) );
  1353. mUseHeadZCalc = true;
  1354. allowAllPoses();
  1355. mImpactSound = 0;
  1356. mRecoverTicks = 0;
  1357. mReversePending = 0;
  1358. mLastPos.set( 0.0f, 0.0f, 0.0f );
  1359. mMoveBubbleSound = 0;
  1360. mWaterBreathSound = 0;
  1361. mConvex.init(this);
  1362. mWorkingQueryBox.minExtents.set(-1e9f, -1e9f, -1e9f);
  1363. mWorkingQueryBox.maxExtents.set(-1e9f, -1e9f, -1e9f);
  1364. mWeaponBackFraction = 0.0f;
  1365. mInMissionArea = true;
  1366. mBubbleEmitterTime = 10.0;
  1367. mLastWaterPos.set( 0.0, 0.0, 0.0 );
  1368. mMountPending = 0;
  1369. mPhysicsRep = NULL;
  1370. for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
  1371. {
  1372. mShapeFPInstance[i] = 0;
  1373. mShapeFPAmbientThread[i] = 0;
  1374. mShapeFPVisThread[i] = 0;
  1375. mShapeFPAnimThread[i] = 0;
  1376. mShapeFPFlashThread[i] = 0;
  1377. mShapeFPSpinThread[i] = 0;
  1378. }
  1379. mLastAbsoluteYaw = 0.0f;
  1380. mLastAbsolutePitch = 0.0f;
  1381. mLastAbsoluteRoll = 0.0f;
  1382. afx_init();
  1383. }
  1384. Player::~Player()
  1385. {
  1386. for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
  1387. {
  1388. delete mShapeFPInstance[i];
  1389. mShapeFPInstance[i] = 0;
  1390. }
  1391. }
  1392. //----------------------------------------------------------------------------
  1393. bool Player::onAdd()
  1394. {
  1395. ActionAnimation serverAnim = mActionAnimation;
  1396. if(!Parent::onAdd() || !mDataBlock)
  1397. return false;
  1398. mWorkingQueryBox.minExtents.set(-1e9f, -1e9f, -1e9f);
  1399. mWorkingQueryBox.maxExtents.set(-1e9f, -1e9f, -1e9f);
  1400. addToScene();
  1401. // Make sure any state and animation passed from the server
  1402. // in the initial update is set correctly.
  1403. ActionState state = mState;
  1404. mState = NullState;
  1405. setState(state);
  1406. setPose(StandPose);
  1407. if (serverAnim.action != PlayerData::NullAnimation)
  1408. {
  1409. setActionThread(serverAnim.action, true, serverAnim.holdAtEnd, true, false, true);
  1410. if (serverAnim.atEnd)
  1411. {
  1412. mShapeInstance->clearTransition(mActionAnimation.thread);
  1413. mShapeInstance->setPos(mActionAnimation.thread,
  1414. mActionAnimation.forward ? 1.0f : 0.0f);
  1415. if (inDeathAnim())
  1416. mDeath.lastPos = 1.0f;
  1417. }
  1418. // We have to leave them sitting for a while since mounts don't come through right
  1419. // away (and sometimes not for a while). Still going to let this time out because
  1420. // I'm not sure if we're guaranteed another anim will come through and cancel.
  1421. if (!isServerObject() && inSittingAnim())
  1422. mMountPending = (S32) sMountPendingTickWait;
  1423. else
  1424. mMountPending = 0;
  1425. }
  1426. if (mArmAnimation.action != PlayerData::NullAnimation)
  1427. setArmThread(mArmAnimation.action);
  1428. //
  1429. if (isServerObject())
  1430. {
  1431. scriptOnAdd();
  1432. }
  1433. else
  1434. {
  1435. U32 i;
  1436. for( i=0; i<PlayerData::NUM_SPLASH_EMITTERS; i++ )
  1437. {
  1438. if ( mDataBlock->splashEmitterList[i] )
  1439. {
  1440. mSplashEmitter[i] = new ParticleEmitter;
  1441. mSplashEmitter[i]->onNewDataBlock( mDataBlock->splashEmitterList[i], false );
  1442. if( !mSplashEmitter[i]->registerObject() )
  1443. {
  1444. Con::warnf( ConsoleLogEntry::General, "Could not register splash emitter for class: %s", mDataBlock->getName() );
  1445. mSplashEmitter[i].getPointer()->destroySelf();
  1446. mSplashEmitter[i] = NULL;
  1447. }
  1448. }
  1449. }
  1450. mLastWaterPos = getPosition();
  1451. // clear out all camera effects
  1452. gCamFXMgr.clear();
  1453. }
  1454. if ( PHYSICSMGR )
  1455. {
  1456. PhysicsWorld *world = PHYSICSMGR->getWorld( isServerObject() ? "server" : "client" );
  1457. mPhysicsRep = PHYSICSMGR->createPlayer();
  1458. mPhysicsRep->init( mDataBlock->physicsPlayerType,
  1459. mDataBlock->boxSize,
  1460. mDataBlock->runSurfaceCos,
  1461. mDataBlock->maxStepHeight,
  1462. this,
  1463. world );
  1464. mPhysicsRep->setTransform( getTransform() );
  1465. }
  1466. return true;
  1467. }
  1468. void Player::onRemove()
  1469. {
  1470. setControlObject(0);
  1471. scriptOnRemove();
  1472. removeFromScene();
  1473. if ( isGhost() )
  1474. {
  1475. SFX_DELETE( mMoveBubbleSound );
  1476. SFX_DELETE( mWaterBreathSound );
  1477. }
  1478. U32 i;
  1479. for( i=0; i<PlayerData::NUM_SPLASH_EMITTERS; i++ )
  1480. {
  1481. if( mSplashEmitter[i] )
  1482. {
  1483. mSplashEmitter[i]->deleteWhenEmpty();
  1484. mSplashEmitter[i] = NULL;
  1485. }
  1486. }
  1487. mWorkingQueryBox.minExtents.set(-1e9f, -1e9f, -1e9f);
  1488. mWorkingQueryBox.maxExtents.set(-1e9f, -1e9f, -1e9f);
  1489. SAFE_DELETE( mPhysicsRep );
  1490. Parent::onRemove();
  1491. }
  1492. void Player::onScaleChanged()
  1493. {
  1494. const Point3F& scale = getScale();
  1495. mScaledBox = mObjBox;
  1496. mScaledBox.minExtents.convolve( scale );
  1497. mScaledBox.maxExtents.convolve( scale );
  1498. }
  1499. //----------------------------------------------------------------------------
  1500. bool Player::onNewDataBlock( GameBaseData *dptr, bool reload )
  1501. {
  1502. PlayerData* prevData = mDataBlock;
  1503. mDataBlock = dynamic_cast<PlayerData*>(dptr);
  1504. if ( !mDataBlock || !Parent::onNewDataBlock( dptr, reload ) )
  1505. return false;
  1506. // Player requires a shape instance.
  1507. if ( mShapeInstance == NULL )
  1508. return false;
  1509. // Initialize arm thread, preserve arm sequence from last datablock.
  1510. // Arm animation can be from last datablock, or sent from the server.
  1511. U32 prevAction = mArmAnimation.action;
  1512. mArmAnimation.action = PlayerData::NullAnimation;
  1513. if (mDataBlock->lookAction) {
  1514. mArmAnimation.thread = mShapeInstance->addThread();
  1515. mShapeInstance->setTimeScale(mArmAnimation.thread,0);
  1516. if (prevData) {
  1517. if (prevAction != prevData->lookAction && prevAction != PlayerData::NullAnimation)
  1518. setArmThread(prevData->actionList[prevAction].name);
  1519. prevAction = PlayerData::NullAnimation;
  1520. }
  1521. if (mArmAnimation.action == PlayerData::NullAnimation) {
  1522. mArmAnimation.action = (prevAction != PlayerData::NullAnimation)?
  1523. prevAction: mDataBlock->lookAction;
  1524. mShapeInstance->setSequence(mArmAnimation.thread,
  1525. mDataBlock->actionList[mArmAnimation.action].sequence,0);
  1526. }
  1527. }
  1528. else
  1529. mArmAnimation.thread = 0;
  1530. // Initialize head look thread
  1531. TSShape const* shape = mShapeInstance->getShape();
  1532. S32 headSeq = shape->findSequence("head");
  1533. if (headSeq != -1) {
  1534. mHeadVThread = mShapeInstance->addThread();
  1535. mShapeInstance->setSequence(mHeadVThread,headSeq,0);
  1536. mShapeInstance->setTimeScale(mHeadVThread,0);
  1537. }
  1538. else
  1539. mHeadVThread = 0;
  1540. headSeq = shape->findSequence("headside");
  1541. if (headSeq != -1) {
  1542. mHeadHThread = mShapeInstance->addThread();
  1543. mShapeInstance->setSequence(mHeadHThread,headSeq,0);
  1544. mShapeInstance->setTimeScale(mHeadHThread,0);
  1545. }
  1546. else
  1547. mHeadHThread = 0;
  1548. // Create Recoil thread if any recoil sequences are specified.
  1549. // Note that the server player does not play this animation.
  1550. mRecoilThread = 0;
  1551. if (isGhost())
  1552. for (U32 s = 0; s < PlayerData::NumRecoilSequences; s++)
  1553. if (mDataBlock->recoilSequence[s] != -1) {
  1554. mRecoilThread = mShapeInstance->addThread();
  1555. mShapeInstance->setSequence(mRecoilThread, mDataBlock->recoilSequence[s], 0);
  1556. mShapeInstance->setTimeScale(mRecoilThread, 0);
  1557. break;
  1558. }
  1559. // Reset the image state driven animation thread. This will be properly built
  1560. // in onImageStateAnimation() when needed.
  1561. mImageStateThread = 0;
  1562. // Initialize the primary thread, the actual sequence is
  1563. // set later depending on player actions.
  1564. mActionAnimation.action = PlayerData::NullAnimation;
  1565. mActionAnimation.thread = mShapeInstance->addThread();
  1566. updateAnimationTree(!isGhost());
  1567. // First person mounted image shapes. Only on client.
  1568. if ( isGhost() )
  1569. {
  1570. for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
  1571. {
  1572. if (bool(mDataBlock->mShapeFP[i]))
  1573. {
  1574. mShapeFPInstance[i] = new TSShapeInstance(mDataBlock->mShapeFP[i], isClientObject());
  1575. mShapeFPInstance[i]->cloneMaterialList();
  1576. // Ambient animation
  1577. if (mShapeFPAmbientThread[i])
  1578. {
  1579. S32 seq = mShapeFPInstance[i]->getShape()->findSequence("ambient");
  1580. if (seq != -1)
  1581. {
  1582. mShapeFPAmbientThread[i] = mShapeFPInstance[i]->addThread();
  1583. mShapeFPInstance[i]->setTimeScale(mShapeFPAmbientThread[i], 1);
  1584. mShapeFPInstance[i]->setSequence(mShapeFPAmbientThread[i], seq, 0);
  1585. }
  1586. }
  1587. // Standard state animation
  1588. mShapeFPAnimThread[i] = mShapeFPInstance[i]->addThread();
  1589. if (mShapeFPAnimThread[i])
  1590. {
  1591. mShapeFPInstance[i]->setTimeScale(mShapeFPAnimThread[i],0);
  1592. }
  1593. }
  1594. }
  1595. }
  1596. if ( isGhost() )
  1597. {
  1598. // Create the sounds ahead of time. This reduces runtime
  1599. // costs and makes the system easier to understand.
  1600. SFX_DELETE( mMoveBubbleSound );
  1601. SFX_DELETE( mWaterBreathSound );
  1602. if ( mDataBlock->sound[PlayerData::MoveBubbles] )
  1603. mMoveBubbleSound = SFX->createSource( mDataBlock->sound[PlayerData::MoveBubbles] );
  1604. if ( mDataBlock->sound[PlayerData::WaterBreath] )
  1605. mWaterBreathSound = SFX->createSource( mDataBlock->sound[PlayerData::WaterBreath] );
  1606. }
  1607. mObjBox.maxExtents.x = mDataBlock->boxSize.x * 0.5f;
  1608. mObjBox.maxExtents.y = mDataBlock->boxSize.y * 0.5f;
  1609. mObjBox.maxExtents.z = mDataBlock->boxSize.z;
  1610. mObjBox.minExtents.x = -mObjBox.maxExtents.x;
  1611. mObjBox.minExtents.y = -mObjBox.maxExtents.y;
  1612. mObjBox.minExtents.z = 0.0f;
  1613. // Setup the box for our convex object...
  1614. mObjBox.getCenter(&mConvex.mCenter);
  1615. mConvex.mSize.x = mObjBox.len_x() / 2.0f;
  1616. mConvex.mSize.y = mObjBox.len_y() / 2.0f;
  1617. mConvex.mSize.z = mObjBox.len_z() / 2.0f;
  1618. // Initialize our scaled attributes as well
  1619. onScaleChanged();
  1620. resetWorldBox();
  1621. scriptOnNewDataBlock();
  1622. return true;
  1623. }
  1624. //----------------------------------------------------------------------------
  1625. void Player::reSkin()
  1626. {
  1627. if ( isGhost() && mShapeInstance && mSkinNameHandle.isValidString() )
  1628. {
  1629. mShapeInstance->resetMaterialList();
  1630. Vector<String> skins;
  1631. String(mSkinNameHandle.getString()).split( ";", skins );
  1632. for ( S32 i = 0; i < skins.size(); i++ )
  1633. {
  1634. String oldSkin( mAppliedSkinName.c_str() );
  1635. String newSkin( skins[i] );
  1636. // Check if the skin handle contains an explicit "old" base string. This
  1637. // allows all models to support skinning, even if they don't follow the
  1638. // "base_xxx" material naming convention.
  1639. S32 split = newSkin.find( '=' ); // "old=new" format skin?
  1640. if ( split != String::NPos )
  1641. {
  1642. oldSkin = newSkin.substr( 0, split );
  1643. newSkin = newSkin.erase( 0, split+1 );
  1644. }
  1645. // Apply skin to both 3rd person and 1st person shape instances
  1646. mShapeInstance->reSkin( newSkin, oldSkin );
  1647. for ( S32 j = 0; j < ShapeBase::MaxMountedImages; j++ )
  1648. {
  1649. if (mShapeFPInstance[j])
  1650. mShapeFPInstance[j]->reSkin( newSkin, oldSkin );
  1651. }
  1652. mAppliedSkinName = newSkin;
  1653. }
  1654. }
  1655. }
  1656. //----------------------------------------------------------------------------
  1657. void Player::setControllingClient(GameConnection* client)
  1658. {
  1659. Parent::setControllingClient(client);
  1660. if (mControlObject)
  1661. mControlObject->setControllingClient(client);
  1662. }
  1663. void Player::setControlObject(ShapeBase* obj)
  1664. {
  1665. if (mControlObject == obj)
  1666. return;
  1667. if (mControlObject) {
  1668. mControlObject->setControllingObject(0);
  1669. mControlObject->setControllingClient(0);
  1670. }
  1671. if (obj == this || obj == 0)
  1672. mControlObject = 0;
  1673. else {
  1674. if (ShapeBase* coo = obj->getControllingObject())
  1675. coo->setControlObject(0);
  1676. if (GameConnection* con = obj->getControllingClient())
  1677. con->setControlObject(0);
  1678. mControlObject = obj;
  1679. mControlObject->setControllingObject(this);
  1680. mControlObject->setControllingClient(getControllingClient());
  1681. }
  1682. }
  1683. void Player::onCameraScopeQuery(NetConnection *connection, CameraScopeQuery *query)
  1684. {
  1685. // First, we are certainly in scope, and whatever we're riding is too...
  1686. if(mControlObject.isNull() || mControlObject == mMount.object)
  1687. Parent::onCameraScopeQuery(connection, query);
  1688. else
  1689. {
  1690. connection->objectInScope(this);
  1691. if (isMounted())
  1692. connection->objectInScope(mMount.object);
  1693. mControlObject->onCameraScopeQuery(connection, query);
  1694. }
  1695. }
  1696. ShapeBase* Player::getControlObject()
  1697. {
  1698. return mControlObject;
  1699. }
  1700. void Player::processTick(const Move* move)
  1701. {
  1702. PROFILE_SCOPE(Player_ProcessTick);
  1703. bool prevMoveMotion = mMoveMotion;
  1704. Pose prevPose = getPose();
  1705. // If we're not being controlled by a client, let the
  1706. // AI sub-module get a chance at producing a move.
  1707. Move aiMove;
  1708. if (!move && isServerObject() && getAIMove(&aiMove))
  1709. move = &aiMove;
  1710. // Manage the control object and filter moves for the player
  1711. Move pMove,cMove;
  1712. if (mControlObject) {
  1713. if (!move)
  1714. mControlObject->processTick(0);
  1715. else {
  1716. pMove = NullMove;
  1717. cMove = *move;
  1718. //if (isMounted()) {
  1719. // Filter Jump trigger if mounted
  1720. //pMove.trigger[2] = move->trigger[2];
  1721. //cMove.trigger[2] = false;
  1722. //}
  1723. if (move->freeLook) {
  1724. // Filter yaw/picth/roll when freelooking.
  1725. pMove.yaw = move->yaw;
  1726. pMove.pitch = move->pitch;
  1727. pMove.roll = move->roll;
  1728. pMove.freeLook = true;
  1729. cMove.freeLook = false;
  1730. cMove.yaw = cMove.pitch = cMove.roll = 0.0f;
  1731. }
  1732. mControlObject->processTick((mDamageState == Enabled)? &cMove: &NullMove);
  1733. move = &pMove;
  1734. }
  1735. }
  1736. Parent::processTick(move);
  1737. // Check for state changes in the standard move triggers and
  1738. // set bits for any triggers that switched on this tick in
  1739. // the fx_s_triggers mask. Flag any changes to be packed to
  1740. // clients.
  1741. if (isServerObject())
  1742. {
  1743. fx_s_triggers = 0;
  1744. if (move)
  1745. {
  1746. U8 on_bits = 0;
  1747. for (S32 i = 0; i < MaxTriggerKeys; i++)
  1748. if (move->trigger[i])
  1749. on_bits |= BIT(i);
  1750. if (on_bits != move_trigger_states)
  1751. {
  1752. U8 switched_on_bits = (on_bits & ~move_trigger_states);
  1753. if (switched_on_bits)
  1754. {
  1755. fx_s_triggers |= (U32)switched_on_bits;
  1756. setMaskBits(TriggerMask);
  1757. }
  1758. move_trigger_states = on_bits;
  1759. }
  1760. }
  1761. }
  1762. // Warp to catch up to server
  1763. if (mDelta.warpTicks > 0) {
  1764. mDelta.warpTicks--;
  1765. // Set new pos
  1766. getTransform().getColumn(3, &mDelta.pos);
  1767. mDelta.pos += mDelta.warpOffset;
  1768. mDelta.rot += mDelta.rotOffset;
  1769. // Wrap yaw to +/-PI
  1770. if (mDelta.rot.z < - M_PI_F)
  1771. mDelta.rot.z += M_2PI_F;
  1772. else if (mDelta.rot.z > M_PI_F)
  1773. mDelta.rot.z -= M_2PI_F;
  1774. if (!ignore_updates)
  1775. {
  1776. setPosition(mDelta.pos, mDelta.rot);
  1777. }
  1778. updateDeathOffsets();
  1779. updateLookAnimation();
  1780. // Backstepping
  1781. mDelta.posVec = -mDelta.warpOffset;
  1782. mDelta.rotVec = -mDelta.rotOffset;
  1783. }
  1784. else {
  1785. // If there is no move, the player is either an
  1786. // unattached player on the server, or a player's
  1787. // client ghost.
  1788. if (!move) {
  1789. if (isGhost()) {
  1790. // If we haven't run out of prediction time,
  1791. // predict using the last known move.
  1792. if (mPredictionCount-- <= 0)
  1793. return;
  1794. move = &mDelta.move;
  1795. }
  1796. else
  1797. move = &NullMove;
  1798. }
  1799. if (!isGhost())
  1800. updateAnimation(TickSec);
  1801. PROFILE_START(Player_PhysicsSection);
  1802. if ( isServerObject() || didRenderLastRender() || getControllingClient() )
  1803. {
  1804. if ( !mPhysicsRep )
  1805. {
  1806. if ( isMounted() )
  1807. {
  1808. // If we're mounted then do not perform any collision checks
  1809. // and clear our previous working list.
  1810. mConvex.clearWorkingList();
  1811. }
  1812. else
  1813. {
  1814. updateWorkingCollisionSet();
  1815. }
  1816. }
  1817. updateState();
  1818. updateMove(move);
  1819. updateLookAnimation();
  1820. updateDeathOffsets();
  1821. updatePos();
  1822. }
  1823. PROFILE_END();
  1824. if (!isGhost())
  1825. {
  1826. // Animations are advanced based on frame rate on the
  1827. // client and must be ticked on the server.
  1828. updateActionThread();
  1829. updateAnimationTree(true);
  1830. // Check for sprinting motion changes
  1831. Pose currentPose = getPose();
  1832. // Player has just switched into Sprint pose and is moving
  1833. if (currentPose == SprintPose && prevPose != SprintPose && mMoveMotion)
  1834. {
  1835. mDataBlock->onStartSprintMotion_callback( this );
  1836. }
  1837. // Player has just switched out of Sprint pose and is moving, or was just moving
  1838. else if (currentPose != SprintPose && prevPose == SprintPose && (mMoveMotion || prevMoveMotion))
  1839. {
  1840. mDataBlock->onStopSprintMotion_callback( this );
  1841. }
  1842. // Player is in Sprint pose and has modified their motion
  1843. else if (currentPose == SprintPose && prevMoveMotion != mMoveMotion)
  1844. {
  1845. if (mMoveMotion)
  1846. {
  1847. mDataBlock->onStartSprintMotion_callback( this );
  1848. }
  1849. else
  1850. {
  1851. mDataBlock->onStopSprintMotion_callback( this );
  1852. }
  1853. }
  1854. }
  1855. }
  1856. // PATHSHAPE
  1857. if (!isGhost()) updateAttachment();
  1858. // PATHSHAPE END
  1859. }
  1860. void Player::interpolateTick(F32 dt)
  1861. {
  1862. if (mControlObject)
  1863. mControlObject->interpolateTick(dt);
  1864. // Client side interpolation
  1865. Parent::interpolateTick(dt);
  1866. Point3F pos = mDelta.pos + mDelta.posVec * dt;
  1867. Point3F rot = mDelta.rot + mDelta.rotVec * dt;
  1868. if (!ignore_updates)
  1869. setRenderPosition(pos,rot,dt);
  1870. /*
  1871. // apply camera effects - is this the best place? - bramage
  1872. GameConnection* connection = GameConnection::getConnectionToServer();
  1873. if( connection->isFirstPerson() )
  1874. {
  1875. ShapeBase *obj = dynamic_cast<ShapeBase*>(connection->getControlObject());
  1876. if( obj == this )
  1877. {
  1878. MatrixF curTrans = getRenderTransform();
  1879. curTrans.mul( gCamFXMgr.getTrans() );
  1880. Parent::setRenderTransform( curTrans );
  1881. }
  1882. }
  1883. */
  1884. updateLookAnimation(dt);
  1885. mDelta.dt = dt;
  1886. // PATHSHAPE
  1887. updateRenderChangesByParent();
  1888. // PATHSHAPE END
  1889. }
  1890. void Player::advanceTime(F32 dt)
  1891. {
  1892. // Client side animations
  1893. Parent::advanceTime(dt);
  1894. // Increment timer for triggering idle events.
  1895. if (idle_timer >= 0.0f)
  1896. idle_timer += dt;
  1897. updateActionThread();
  1898. updateAnimation(dt);
  1899. updateSplash();
  1900. updateFroth(dt);
  1901. updateWaterSounds(dt);
  1902. mLastPos = getPosition();
  1903. if (mImpactSound)
  1904. playImpactSound();
  1905. // update camera effects. Definitely need to find better place for this - bramage
  1906. if( isControlObject() )
  1907. {
  1908. if( mDamageState == Disabled || mDamageState == Destroyed )
  1909. {
  1910. // clear out all camera effects being applied to player if dead
  1911. gCamFXMgr.clear();
  1912. }
  1913. }
  1914. }
  1915. bool Player::getAIMove(Move* move)
  1916. {
  1917. return false;
  1918. }
  1919. void Player::setState(ActionState state, U32 recoverTicks)
  1920. {
  1921. if (state != mState) {
  1922. // Skip initialization if there is no manager, the state
  1923. // will get reset when the object is added to a manager.
  1924. if (isProperlyAdded()) {
  1925. switch (state) {
  1926. case RecoverState: {
  1927. if (mDataBlock->landSequenceTime > 0.0f)
  1928. {
  1929. // Use the land sequence as the basis for the recovery
  1930. setActionThread(PlayerData::LandAnim, true, false, true, true);
  1931. F32 timeScale = mShapeInstance->getDuration(mActionAnimation.thread) / mDataBlock->landSequenceTime;
  1932. mShapeInstance->setTimeScale(mActionAnimation.thread,timeScale);
  1933. mRecoverDelay = mDataBlock->landSequenceTime;
  1934. }
  1935. else
  1936. {
  1937. // Legacy recover system
  1938. mRecoverTicks = recoverTicks;
  1939. mReversePending = U32(F32(mRecoverTicks) / sLandReverseScale);
  1940. setActionThread(PlayerData::LandAnim, true, false, true, true);
  1941. }
  1942. break;
  1943. }
  1944. default:
  1945. break;
  1946. }
  1947. }
  1948. mState = state;
  1949. }
  1950. }
  1951. void Player::updateState()
  1952. {
  1953. switch (mState)
  1954. {
  1955. case RecoverState:
  1956. if (mDataBlock->landSequenceTime > 0.0f)
  1957. {
  1958. // Count down the land time
  1959. mRecoverDelay -= TickSec;
  1960. if (mRecoverDelay <= 0.0f)
  1961. {
  1962. setState(MoveState);
  1963. }
  1964. }
  1965. else
  1966. {
  1967. // Legacy recover system
  1968. if (mRecoverTicks-- <= 0)
  1969. {
  1970. if (mReversePending && mActionAnimation.action != PlayerData::NullAnimation)
  1971. {
  1972. // this serves and counter, and direction state
  1973. mRecoverTicks = mReversePending;
  1974. mActionAnimation.forward = false;
  1975. S32 seq = mDataBlock->actionList[mActionAnimation.action].sequence;
  1976. S32 imageBasedSeq = convertActionToImagePrefix(mActionAnimation.action);
  1977. if (imageBasedSeq != -1)
  1978. seq = imageBasedSeq;
  1979. F32 pos = mShapeInstance->getPos(mActionAnimation.thread);
  1980. mShapeInstance->setTimeScale(mActionAnimation.thread, -sLandReverseScale);
  1981. mShapeInstance->transitionToSequence(mActionAnimation.thread,
  1982. seq, pos, sAnimationTransitionTime, true);
  1983. mReversePending = 0;
  1984. }
  1985. else
  1986. {
  1987. setState(MoveState);
  1988. }
  1989. } // Stand back up slowly only if not moving much-
  1990. else if (!mReversePending && mVelocity.lenSquared() > sSlowStandThreshSquared)
  1991. {
  1992. mActionAnimation.waitForEnd = false;
  1993. setState(MoveState);
  1994. }
  1995. }
  1996. break;
  1997. default:
  1998. break;
  1999. }
  2000. }
  2001. const char* Player::getStateName()
  2002. {
  2003. if (mDamageState != Enabled)
  2004. return "Dead";
  2005. if (isMounted())
  2006. return "Mounted";
  2007. if (mState == RecoverState)
  2008. return "Recover";
  2009. return "Move";
  2010. }
  2011. void Player::getDamageLocation(const Point3F& in_rPos, const char *&out_rpVert, const char *&out_rpQuad)
  2012. {
  2013. // TODO: This will be WRONG when player is prone or swimming!
  2014. Point3F newPoint;
  2015. mWorldToObj.mulP(in_rPos, &newPoint);
  2016. Point3F boxSize = mObjBox.getExtents();
  2017. F32 zHeight = boxSize.z;
  2018. F32 zTorso = mDataBlock->boxTorsoPercentage;
  2019. F32 zHead = mDataBlock->boxHeadPercentage;
  2020. zTorso *= zHeight;
  2021. zHead *= zHeight;
  2022. if (newPoint.z <= zTorso)
  2023. out_rpVert = "legs";
  2024. else if (newPoint.z <= zHead)
  2025. out_rpVert = "torso";
  2026. else
  2027. out_rpVert = "head";
  2028. if(dStrcmp(out_rpVert, "head") != 0)
  2029. {
  2030. if (newPoint.y >= 0.0f)
  2031. {
  2032. if (newPoint.x <= 0.0f)
  2033. out_rpQuad = "front_left";
  2034. else
  2035. out_rpQuad = "front_right";
  2036. }
  2037. else
  2038. {
  2039. if (newPoint.x <= 0.0f)
  2040. out_rpQuad = "back_left";
  2041. else
  2042. out_rpQuad = "back_right";
  2043. }
  2044. }
  2045. else
  2046. {
  2047. F32 backToFront = boxSize.x;
  2048. F32 leftToRight = boxSize.y;
  2049. F32 backPoint = backToFront * mDataBlock->boxHeadBackPercentage;
  2050. F32 frontPoint = backToFront * mDataBlock->boxHeadFrontPercentage;
  2051. F32 leftPoint = leftToRight * mDataBlock->boxHeadLeftPercentage;
  2052. F32 rightPoint = leftToRight * mDataBlock->boxHeadRightPercentage;
  2053. S32 index = 0;
  2054. if (newPoint.y < backPoint)
  2055. index += 0;
  2056. else if (newPoint.y >= frontPoint)
  2057. index += 3;
  2058. else
  2059. index += 6;
  2060. if (newPoint.x < leftPoint)
  2061. index += 0;
  2062. else if (newPoint.x >= rightPoint)
  2063. index += 1;
  2064. else
  2065. index += 2;
  2066. switch (index)
  2067. {
  2068. case 0: out_rpQuad = "left_back"; break;
  2069. case 1: out_rpQuad = "middle_back"; break;
  2070. case 2: out_rpQuad = "right_back"; break;
  2071. case 3: out_rpQuad = "left_middle"; break;
  2072. case 4: out_rpQuad = "middle_middle"; break;
  2073. case 5: out_rpQuad = "right_middle"; break;
  2074. case 6: out_rpQuad = "left_front"; break;
  2075. case 7: out_rpQuad = "middle_front"; break;
  2076. case 8: out_rpQuad = "right_front"; break;
  2077. default:
  2078. AssertFatal(0, "Bad non-tant index");
  2079. };
  2080. }
  2081. }
  2082. const char* Player::getPoseName() const
  2083. {
  2084. return EngineMarshallData< PlayerPose >(getPose());
  2085. }
  2086. void Player::setPose( Pose pose )
  2087. {
  2088. // Already the set pose, return.
  2089. if ( pose == mPose )
  2090. return;
  2091. Pose oldPose = mPose;
  2092. mPose = pose;
  2093. // Not added yet, just assign the pose and return.
  2094. if ( !isProperlyAdded() )
  2095. return;
  2096. Point3F boxSize(1,1,1);
  2097. // Resize the player boxes
  2098. switch (pose)
  2099. {
  2100. case StandPose:
  2101. case SprintPose:
  2102. boxSize = mDataBlock->boxSize;
  2103. break;
  2104. case CrouchPose:
  2105. boxSize = mDataBlock->crouchBoxSize;
  2106. break;
  2107. case PronePose:
  2108. boxSize = mDataBlock->proneBoxSize;
  2109. break;
  2110. case SwimPose:
  2111. boxSize = mDataBlock->swimBoxSize;
  2112. break;
  2113. }
  2114. // Object and World Boxes...
  2115. mObjBox.maxExtents.x = boxSize.x * 0.5f;
  2116. mObjBox.maxExtents.y = boxSize.y * 0.5f;
  2117. mObjBox.maxExtents.z = boxSize.z;
  2118. mObjBox.minExtents.x = -mObjBox.maxExtents.x;
  2119. mObjBox.minExtents.y = -mObjBox.maxExtents.y;
  2120. mObjBox.minExtents.z = 0.0f;
  2121. resetWorldBox();
  2122. // Setup the box for our convex object...
  2123. mObjBox.getCenter(&mConvex.mCenter);
  2124. mConvex.mSize.x = mObjBox.len_x() / 2.0f;
  2125. mConvex.mSize.y = mObjBox.len_y() / 2.0f;
  2126. mConvex.mSize.z = mObjBox.len_z() / 2.0f;
  2127. // Initialize our scaled attributes as well...
  2128. onScaleChanged();
  2129. // Resize the PhysicsPlayer rep. should we have one
  2130. if ( mPhysicsRep )
  2131. mPhysicsRep->setSpacials( getPosition(), boxSize );
  2132. if ( isServerObject() )
  2133. mDataBlock->onPoseChange_callback( this, EngineMarshallData< PlayerPose >(oldPose), EngineMarshallData< PlayerPose >(mPose));
  2134. }
  2135. void Player::allowAllPoses()
  2136. {
  2137. mAllowJumping = true;
  2138. mAllowJetJumping = true;
  2139. mAllowSprinting = true;
  2140. mAllowCrouching = true;
  2141. mAllowProne = true;
  2142. mAllowSwimming = true;
  2143. }
  2144. AngAxisF gPlayerMoveRot;
  2145. void Player::updateMove(const Move* move)
  2146. {
  2147. struct Move my_move;
  2148. if (override_movement && movement_op < 3)
  2149. {
  2150. my_move = *move;
  2151. switch (movement_op)
  2152. {
  2153. case 0: // add
  2154. my_move.x += movement_data.x;
  2155. my_move.y += movement_data.y;
  2156. my_move.z += movement_data.z;
  2157. break;
  2158. case 1: // mult
  2159. my_move.x *= movement_data.x;
  2160. my_move.y *= movement_data.y;
  2161. my_move.z *= movement_data.z;
  2162. break;
  2163. case 2: // replace
  2164. my_move.x = movement_data.x;
  2165. my_move.y = movement_data.y;
  2166. my_move.z = movement_data.z;
  2167. break;
  2168. }
  2169. move = &my_move;
  2170. }
  2171. mDelta.move = *move;
  2172. #ifdef TORQUE_OPENVR
  2173. if (mControllers[0])
  2174. {
  2175. mControllers[0]->processTick(move);
  2176. }
  2177. if (mControllers[1])
  2178. {
  2179. mControllers[1]->processTick(move);
  2180. }
  2181. #endif
  2182. // Is waterCoverage high enough to be 'swimming'?
  2183. {
  2184. bool swimming = mWaterCoverage > 0.65f && canSwim();
  2185. if ( swimming != mSwimming )
  2186. {
  2187. if ( !isGhost() )
  2188. {
  2189. if ( swimming )
  2190. mDataBlock->onStartSwim_callback( this );
  2191. else
  2192. mDataBlock->onStopSwim_callback( this );
  2193. }
  2194. mSwimming = swimming;
  2195. }
  2196. }
  2197. // Trigger images
  2198. if (mDamageState == Enabled)
  2199. {
  2200. setImageTriggerState( 0, move->trigger[sImageTrigger0] );
  2201. // If you have a secondary mounted image then
  2202. // send the second trigger to it. Else give it
  2203. // to the first image as an alt fire.
  2204. if ( getMountedImage( 1 ) )
  2205. setImageTriggerState( 1, move->trigger[sImageTrigger1] );
  2206. else
  2207. setImageAltTriggerState( 0, move->trigger[sImageTrigger1] );
  2208. }
  2209. // Update current orientation
  2210. if (mDamageState == Enabled) {
  2211. F32 prevZRot = mRot.z;
  2212. mDelta.headVec = mHead;
  2213. bool doStandardMove = true;
  2214. bool absoluteDelta = false;
  2215. GameConnection* con = getControllingClient();
  2216. #ifdef TORQUE_EXTENDED_MOVE
  2217. // Work with an absolute rotation from the ExtendedMove class?
  2218. if(con && con->getControlSchemeAbsoluteRotation())
  2219. {
  2220. doStandardMove = false;
  2221. const ExtendedMove* emove = dynamic_cast<const ExtendedMove*>(move);
  2222. U32 emoveIndex = smExtendedMoveHeadPosRotIndex;
  2223. if(emoveIndex >= ExtendedMove::MaxPositionsRotations)
  2224. emoveIndex = 0;
  2225. if(emove->EulerBasedRotation[emoveIndex])
  2226. {
  2227. // Head pitch
  2228. mHead.x += (emove->rotX[emoveIndex] - mLastAbsolutePitch);
  2229. // Do we also include the relative yaw value?
  2230. if(con->getControlSchemeAddPitchToAbsRot())
  2231. {
  2232. F32 x = move->pitch;
  2233. if (x > M_PI_F)
  2234. x -= M_2PI_F;
  2235. mHead.x += x;
  2236. }
  2237. // Constrain the range of mHead.x
  2238. while (mHead.x < -M_PI_F)
  2239. mHead.x += M_2PI_F;
  2240. while (mHead.x > M_PI_F)
  2241. mHead.x -= M_2PI_F;
  2242. // Rotate (heading) head or body?
  2243. if (move->freeLook && ((isMounted() && getMountNode() == 0) || (con && !con->isFirstPerson())))
  2244. {
  2245. // Rotate head
  2246. mHead.z += (emove->rotZ[emoveIndex] - mLastAbsoluteYaw);
  2247. // Do we also include the relative yaw value?
  2248. if(con->getControlSchemeAddYawToAbsRot())
  2249. {
  2250. F32 z = move->yaw;
  2251. if (z > M_PI_F)
  2252. z -= M_2PI_F;
  2253. mHead.z += z;
  2254. }
  2255. // Constrain the range of mHead.z
  2256. while (mHead.z < 0.0f)
  2257. mHead.z += M_2PI_F;
  2258. while (mHead.z > M_2PI_F)
  2259. mHead.z -= M_2PI_F;
  2260. }
  2261. else
  2262. {
  2263. // Rotate body
  2264. mRot.z += (emove->rotZ[emoveIndex] - mLastAbsoluteYaw);
  2265. // Do we also include the relative yaw value?
  2266. if(con->getControlSchemeAddYawToAbsRot())
  2267. {
  2268. F32 z = move->yaw;
  2269. if (z > M_PI_F)
  2270. z -= M_2PI_F;
  2271. mRot.z += z;
  2272. }
  2273. // Constrain the range of mRot.z
  2274. while (mRot.z < 0.0f)
  2275. mRot.z += M_2PI_F;
  2276. while (mRot.z > M_2PI_F)
  2277. mRot.z -= M_2PI_F;
  2278. }
  2279. mLastAbsoluteYaw = emove->rotZ[emoveIndex];
  2280. mLastAbsolutePitch = emove->rotX[emoveIndex];
  2281. mLastAbsoluteRoll = emove->rotY[emoveIndex];
  2282. // Head bank
  2283. mHead.y = emove->rotY[emoveIndex];
  2284. // Constrain the range of mHead.y
  2285. while (mHead.y > M_PI_F)
  2286. mHead.y -= M_2PI_F;
  2287. }
  2288. else
  2289. {
  2290. // Orient the player so we are looking towards the required position, ignoring any banking
  2291. AngAxisF moveRot(Point3F(emove->rotX[emoveIndex], emove->rotY[emoveIndex], emove->rotZ[emoveIndex]), emove->rotW[emoveIndex]);
  2292. MatrixF trans(1);
  2293. moveRot.setMatrix(&trans);
  2294. trans.inverse();
  2295. Point3F vecForward(0, 10, 0);
  2296. Point3F viewAngle;
  2297. Point3F orient;
  2298. EulerF rot;
  2299. trans.mulV(vecForward);
  2300. viewAngle = vecForward;
  2301. vecForward.z = 0; // flatten
  2302. vecForward.normalizeSafe();
  2303. F32 yawAng;
  2304. F32 pitchAng;
  2305. MathUtils::getAnglesFromVector(vecForward, yawAng, pitchAng);
  2306. mRot = EulerF(0);
  2307. mRot.z = yawAng;
  2308. mHead = EulerF(0);
  2309. while (mRot.z < 0.0f)
  2310. mRot.z += M_2PI_F;
  2311. while (mRot.z > M_2PI_F)
  2312. mRot.z -= M_2PI_F;
  2313. absoluteDelta = true;
  2314. }
  2315. }
  2316. #endif
  2317. if(doStandardMove)
  2318. {
  2319. F32 p = move->pitch * (mPose == SprintPose ? mDataBlock->sprintPitchScale : 1.0f);
  2320. if (p > M_PI_F)
  2321. p -= M_2PI_F;
  2322. mHead.x = mClampF(mHead.x + p,mDataBlock->minLookAngle,
  2323. mDataBlock->maxLookAngle);
  2324. F32 y = move->yaw * (mPose == SprintPose ? mDataBlock->sprintYawScale : 1.0f);
  2325. if (y > M_PI_F)
  2326. y -= M_2PI_F;
  2327. if (move->freeLook && ((isMounted() && getMountNode() == 0) || (con && !con->isFirstPerson())))
  2328. {
  2329. mHead.z = mClampF(mHead.z + y,
  2330. -mDataBlock->maxFreelookAngle,
  2331. mDataBlock->maxFreelookAngle);
  2332. }
  2333. else
  2334. {
  2335. mRot.z += y;
  2336. // Rotate the head back to the front, center horizontal
  2337. // as well if we're controlling another object.
  2338. mHead.z *= 0.5f;
  2339. if (mControlObject)
  2340. mHead.x *= 0.5f;
  2341. }
  2342. // constrain the range of mRot.z
  2343. while (mRot.z < 0.0f)
  2344. mRot.z += M_2PI_F;
  2345. while (mRot.z > M_2PI_F)
  2346. mRot.z -= M_2PI_F;
  2347. }
  2348. mDelta.rot = mRot;
  2349. mDelta.rotVec.x = mDelta.rotVec.y = 0.0f;
  2350. mDelta.rotVec.z = prevZRot - mRot.z;
  2351. if (mDelta.rotVec.z > M_PI_F)
  2352. mDelta.rotVec.z -= M_2PI_F;
  2353. else if (mDelta.rotVec.z < -M_PI_F)
  2354. mDelta.rotVec.z += M_2PI_F;
  2355. mDelta.head = mHead;
  2356. mDelta.headVec -= mHead;
  2357. if (absoluteDelta)
  2358. {
  2359. mDelta.headVec = Point3F(0, 0, 0);
  2360. mDelta.rotVec = Point3F(0, 0, 0);
  2361. }
  2362. for(U32 i=0; i<3; ++i)
  2363. {
  2364. if (mDelta.headVec[i] > M_PI_F)
  2365. mDelta.headVec[i] -= M_2PI_F;
  2366. else if (mDelta.headVec[i] < -M_PI_F)
  2367. mDelta.headVec[i] += M_2PI_F;
  2368. }
  2369. }
  2370. MatrixF zRot;
  2371. zRot.set(EulerF(0.0f, 0.0f, mRot.z));
  2372. // Desired move direction & speed
  2373. VectorF moveVec;
  2374. F32 moveSpeed;
  2375. // If BLOCK_USER_CONTROL is set in anim_clip_flags, the user won't be able to
  2376. // resume control over the player character. This generally happens for
  2377. // short periods of time synchronized with script driven animation at places
  2378. // where it makes sense that user motion is prohibited, such as when the
  2379. // player is lifted off the ground or knocked down.
  2380. if ((mState == MoveState || (mState == RecoverState && mDataBlock->recoverRunForceScale > 0.0f)) && mDamageState == Enabled && !isAnimationLocked())
  2381. {
  2382. zRot.getColumn(0,&moveVec);
  2383. moveVec *= (move->x * (mPose == SprintPose ? mDataBlock->sprintStrafeScale : 1.0f));
  2384. VectorF tv;
  2385. zRot.getColumn(1,&tv);
  2386. moveVec += tv * move->y;
  2387. // Clamp water movement
  2388. if (move->y > 0.0f)
  2389. {
  2390. if ( mSwimming )
  2391. moveSpeed = getMax(mDataBlock->maxUnderwaterForwardSpeed * move->y,
  2392. mDataBlock->maxUnderwaterSideSpeed * mFabs(move->x));
  2393. else if ( mPose == PronePose )
  2394. moveSpeed = getMax(mDataBlock->maxProneForwardSpeed * move->y,
  2395. mDataBlock->maxProneSideSpeed * mFabs(move->x));
  2396. else if ( mPose == CrouchPose )
  2397. moveSpeed = getMax(mDataBlock->maxCrouchForwardSpeed * move->y,
  2398. mDataBlock->maxCrouchSideSpeed * mFabs(move->x));
  2399. else if ( mPose == SprintPose )
  2400. moveSpeed = getMax(mDataBlock->maxSprintForwardSpeed * move->y,
  2401. mDataBlock->maxSprintSideSpeed * mFabs(move->x));
  2402. else // StandPose
  2403. moveSpeed = getMax(mDataBlock->maxForwardSpeed * move->y,
  2404. mDataBlock->maxSideSpeed * mFabs(move->x));
  2405. }
  2406. else
  2407. {
  2408. if ( mSwimming )
  2409. moveSpeed = getMax(mDataBlock->maxUnderwaterBackwardSpeed * mFabs(move->y),
  2410. mDataBlock->maxUnderwaterSideSpeed * mFabs(move->x));
  2411. else if ( mPose == PronePose )
  2412. moveSpeed = getMax(mDataBlock->maxProneBackwardSpeed * mFabs(move->y),
  2413. mDataBlock->maxProneSideSpeed * mFabs(move->x));
  2414. else if ( mPose == CrouchPose )
  2415. moveSpeed = getMax(mDataBlock->maxCrouchBackwardSpeed * mFabs(move->y),
  2416. mDataBlock->maxCrouchSideSpeed * mFabs(move->x));
  2417. else if ( mPose == SprintPose )
  2418. moveSpeed = getMax(mDataBlock->maxSprintBackwardSpeed * mFabs(move->y),
  2419. mDataBlock->maxSprintSideSpeed * mFabs(move->x));
  2420. else // StandPose
  2421. moveSpeed = getMax(mDataBlock->maxBackwardSpeed * mFabs(move->y),
  2422. mDataBlock->maxSideSpeed * mFabs(move->x));
  2423. }
  2424. // Cancel any script driven animations if we are going to move.
  2425. if (moveVec.x + moveVec.y + moveVec.z != 0.0f &&
  2426. (mActionAnimation.action >= PlayerData::NumTableActionAnims
  2427. || mActionAnimation.action == PlayerData::LandAnim))
  2428. mActionAnimation.action = PlayerData::NullAnimation;
  2429. }
  2430. else
  2431. {
  2432. moveVec.set(0.0f, 0.0f, 0.0f);
  2433. moveSpeed = 0.0f;
  2434. }
  2435. // apply speed bias here.
  2436. speed_bias = speed_bias + (speed_bias_goal - speed_bias)*0.1f;
  2437. moveSpeed *= speed_bias;
  2438. // Acceleration due to gravity
  2439. VectorF acc(0.0f, 0.0f, mGravity * mGravityMod * TickSec);
  2440. // Determine ground contact normal. Only look for contacts if
  2441. // we can move and aren't mounted.
  2442. VectorF contactNormal(0,0,0);
  2443. bool jumpSurface = false, runSurface = false;
  2444. if ( !isMounted() )
  2445. findContact( &runSurface, &jumpSurface, &contactNormal );
  2446. if ( jumpSurface )
  2447. mJumpSurfaceNormal = contactNormal;
  2448. // If we don't have a runSurface but we do have a contactNormal,
  2449. // then we are standing on something that is too steep.
  2450. // Deflect the force of gravity by the normal so we slide.
  2451. // We could also try aligning it to the runSurface instead,
  2452. // but this seems to work well.
  2453. if ( !runSurface && !contactNormal.isZero() )
  2454. acc = ( acc - 2 * contactNormal * mDot( acc, contactNormal ) );
  2455. // Acceleration on run surface
  2456. if (runSurface && !mSwimming) {
  2457. mContactTimer = 0;
  2458. // Remove acc into contact surface (should only be gravity)
  2459. // Clear out floating point acc errors, this will allow
  2460. // the player to "rest" on the ground.
  2461. // However, no need to do that if we're using a physics library.
  2462. // It will take care of itself.
  2463. if (!mPhysicsRep)
  2464. {
  2465. F32 vd = -mDot(acc,contactNormal);
  2466. if (vd > 0.0f) {
  2467. VectorF dv = contactNormal * (vd + 0.002f);
  2468. acc += dv;
  2469. if (acc.len() < 0.0001f)
  2470. acc.set(0.0f, 0.0f, 0.0f);
  2471. }
  2472. }
  2473. // Force a 0 move if there is no energy, and only drain
  2474. // move energy if we're moving.
  2475. VectorF pv;
  2476. if (mPose == SprintPose && mEnergy >= mDataBlock->minSprintEnergy) {
  2477. if (moveSpeed)
  2478. mEnergy -= mDataBlock->sprintEnergyDrain;
  2479. pv = moveVec;
  2480. }
  2481. else if (mEnergy >= mDataBlock->minRunEnergy) {
  2482. if (moveSpeed)
  2483. mEnergy -= mDataBlock->runEnergyDrain;
  2484. pv = moveVec;
  2485. }
  2486. else
  2487. pv.set(0.0f, 0.0f, 0.0f);
  2488. // Adjust the player's requested dir. to be parallel
  2489. // to the contact surface.
  2490. F32 pvl = pv.len();
  2491. if(mJetting)
  2492. {
  2493. pvl = moveVec.len();
  2494. if (pvl)
  2495. {
  2496. VectorF nn;
  2497. mCross(pv,VectorF(0.0f, 0.0f, 0.0f),&nn);
  2498. nn *= 1 / pvl;
  2499. VectorF cv(0.0f, 0.0f, 0.0f);
  2500. cv -= nn * mDot(nn,cv);
  2501. pv -= cv * mDot(pv,cv);
  2502. pvl = pv.len();
  2503. }
  2504. }
  2505. else if (!mPhysicsRep)
  2506. {
  2507. // We only do this if we're not using a physics library. The
  2508. // library will take care of itself.
  2509. if (pvl)
  2510. {
  2511. VectorF nn;
  2512. mCross(pv,VectorF(0.0f, 0.0f, 1.0f),&nn);
  2513. nn *= 1.0f / pvl;
  2514. VectorF cv = contactNormal;
  2515. cv -= nn * mDot(nn,cv);
  2516. pv -= cv * mDot(pv,cv);
  2517. pvl = pv.len();
  2518. }
  2519. }
  2520. // Convert to acceleration
  2521. if ( pvl )
  2522. pv *= moveSpeed / pvl;
  2523. VectorF runAcc = pv - (mVelocity + acc);
  2524. F32 runSpeed = runAcc.len();
  2525. // Clamp acceleration, player also accelerates faster when
  2526. // in his hard landing recover state.
  2527. F32 maxAcc;
  2528. if (mPose == SprintPose)
  2529. {
  2530. maxAcc = (mDataBlock->sprintForce / getMass()) * TickSec;
  2531. }
  2532. else
  2533. {
  2534. maxAcc = (mDataBlock->runForce / getMass()) * TickSec;
  2535. }
  2536. if (mState == RecoverState)
  2537. maxAcc *= mDataBlock->recoverRunForceScale;
  2538. if (runSpeed > maxAcc)
  2539. runAcc *= maxAcc / runSpeed;
  2540. acc += runAcc;
  2541. // If we are running on the ground, then we're not jumping
  2542. if (mDataBlock->isJumpAction(mActionAnimation.action))
  2543. mActionAnimation.action = PlayerData::NullAnimation;
  2544. }
  2545. else if (!mSwimming && mDataBlock->airControl > 0.0f)
  2546. {
  2547. VectorF pv;
  2548. pv = moveVec;
  2549. F32 pvl = pv.len();
  2550. if (pvl)
  2551. pv *= moveSpeed / pvl;
  2552. VectorF runAcc = pv - (mVelocity + acc);
  2553. runAcc.z = 0;
  2554. runAcc.x = runAcc.x * mDataBlock->airControl;
  2555. runAcc.y = runAcc.y * mDataBlock->airControl;
  2556. F32 runSpeed = runAcc.len();
  2557. // We don't test for sprinting when performing air control
  2558. F32 maxAcc = (mDataBlock->runForce / getMass()) * TickSec * 0.3f;
  2559. if (runSpeed > maxAcc)
  2560. runAcc *= maxAcc / runSpeed;
  2561. acc += runAcc;
  2562. // There are no special air control animations
  2563. // so... increment this unless you really want to
  2564. // play the run anims in the air.
  2565. mContactTimer++;
  2566. }
  2567. else if (mSwimming)
  2568. {
  2569. // Remove acc into contact surface (should only be gravity)
  2570. // Clear out floating point acc errors, this will allow
  2571. // the player to "rest" on the ground.
  2572. F32 vd = -mDot(acc,contactNormal);
  2573. if (vd > 0.0f) {
  2574. VectorF dv = contactNormal * (vd + 0.002f);
  2575. acc += dv;
  2576. if (acc.len() < 0.0001f)
  2577. acc.set(0.0f, 0.0f, 0.0f);
  2578. }
  2579. // get the head pitch and add it to the moveVec
  2580. // This more accurate swim vector calc comes from Matt Fairfax
  2581. MatrixF xRot;
  2582. xRot.set(EulerF(mHead.x, 0, 0));
  2583. zRot.set(EulerF(0, 0, mRot.z));
  2584. MatrixF rot;
  2585. rot.mul(zRot, xRot);
  2586. rot.getColumn(0,&moveVec);
  2587. moveVec *= move->x;
  2588. VectorF tv;
  2589. rot.getColumn(1,&tv);
  2590. moveVec += tv * move->y;
  2591. rot.getColumn(2,&tv);
  2592. moveVec += tv * move->z;
  2593. // Force a 0 move if there is no energy, and only drain
  2594. // move energy if we're moving.
  2595. VectorF swimVec;
  2596. if (mEnergy >= mDataBlock->minRunEnergy) {
  2597. if (moveSpeed)
  2598. mEnergy -= mDataBlock->runEnergyDrain;
  2599. swimVec = moveVec;
  2600. }
  2601. else
  2602. swimVec.set(0.0f, 0.0f, 0.0f);
  2603. // If we are swimming but close enough to the shore/ground
  2604. // we can still have a surface-normal. In this case align the
  2605. // velocity to the normal to make getting out of water easier.
  2606. moveVec.normalize();
  2607. F32 isSwimUp = mDot( moveVec, contactNormal );
  2608. if ( !contactNormal.isZero() && isSwimUp < 0.1f )
  2609. {
  2610. F32 pvl = swimVec.len();
  2611. if ( true && pvl )
  2612. {
  2613. VectorF nn;
  2614. mCross(swimVec,VectorF(0.0f, 0.0f, 1.0f),&nn);
  2615. nn *= 1.0f / pvl;
  2616. VectorF cv = contactNormal;
  2617. cv -= nn * mDot(nn,cv);
  2618. swimVec -= cv * mDot(swimVec,cv);
  2619. }
  2620. }
  2621. F32 swimVecLen = swimVec.len();
  2622. // Convert to acceleration.
  2623. if ( swimVecLen )
  2624. swimVec *= moveSpeed / swimVecLen;
  2625. VectorF swimAcc = swimVec - (mVelocity + acc);
  2626. F32 swimSpeed = swimAcc.len();
  2627. // Clamp acceleration.
  2628. F32 maxAcc = (mDataBlock->swimForce / getMass()) * TickSec;
  2629. if ( swimSpeed > maxAcc )
  2630. swimAcc *= maxAcc / swimSpeed;
  2631. acc += swimAcc;
  2632. mContactTimer++;
  2633. }
  2634. else
  2635. mContactTimer++;
  2636. // Acceleration from Jumping
  2637. // While BLOCK_USER_CONTROL is set in anim_clip_flags, the user won't be able to
  2638. // make the player character jump.
  2639. if (move->trigger[sJumpTrigger] && canJump() && !isAnimationLocked())
  2640. {
  2641. // Scale the jump impulse base on maxJumpSpeed
  2642. F32 zSpeedScale = mVelocity.z;
  2643. if (zSpeedScale <= mDataBlock->maxJumpSpeed)
  2644. {
  2645. zSpeedScale = (zSpeedScale <= mDataBlock->minJumpSpeed)? 1:
  2646. 1 - (zSpeedScale - mDataBlock->minJumpSpeed) /
  2647. (mDataBlock->maxJumpSpeed - mDataBlock->minJumpSpeed);
  2648. // Desired jump direction
  2649. VectorF pv = moveVec;
  2650. F32 len = pv.len();
  2651. if (len > 0)
  2652. pv *= 1 / len;
  2653. // We want to scale the jump size by the player size, somewhat
  2654. // in reduced ratio so a smaller player can jump higher in
  2655. // proportion to his size, than a larger player.
  2656. F32 scaleZ = (getScale().z * 0.25) + 0.75;
  2657. // Calculate our jump impulse
  2658. F32 impulse = mDataBlock->jumpForce / getMass();
  2659. if (mDataBlock->jumpTowardsNormal)
  2660. {
  2661. // If we are facing into the surface jump up, otherwise
  2662. // jump away from surface.
  2663. F32 dot = mDot(pv,mJumpSurfaceNormal);
  2664. if (dot <= 0)
  2665. acc.z += mJumpSurfaceNormal.z * scaleZ * impulse * zSpeedScale;
  2666. else
  2667. {
  2668. acc.x += pv.x * impulse * dot;
  2669. acc.y += pv.y * impulse * dot;
  2670. acc.z += mJumpSurfaceNormal.z * scaleZ * impulse * zSpeedScale;
  2671. }
  2672. }
  2673. else
  2674. acc.z += scaleZ * impulse * zSpeedScale;
  2675. mJumpDelay = mDataBlock->jumpDelay;
  2676. mEnergy -= mDataBlock->jumpEnergyDrain;
  2677. // If we don't have a StandJumpAnim, just play the JumpAnim...
  2678. S32 seq = (mVelocity.len() < 0.5) ? PlayerData::StandJumpAnim: PlayerData::JumpAnim;
  2679. if ( mDataBlock->actionList[seq].sequence == -1 )
  2680. seq = PlayerData::JumpAnim;
  2681. setActionThread( seq, true, false, true );
  2682. mJumpSurfaceLastContact = JumpSkipContactsMax;
  2683. // Flag the jump event trigger.
  2684. fx_s_triggers |= PLAYER_JUMP_S_TRIGGER;
  2685. setMaskBits(TriggerMask);
  2686. }
  2687. }
  2688. else
  2689. {
  2690. if (jumpSurface)
  2691. {
  2692. if (mJumpDelay > 0)
  2693. mJumpDelay--;
  2694. mJumpSurfaceLastContact = 0;
  2695. }
  2696. else
  2697. mJumpSurfaceLastContact++;
  2698. }
  2699. if (move->trigger[sJumpJetTrigger] && !isMounted() && canJetJump())
  2700. {
  2701. mJetting = true;
  2702. // Scale the jump impulse base on maxJumpSpeed
  2703. F32 zSpeedScale = mVelocity.z;
  2704. if (zSpeedScale <= mDataBlock->jetMaxJumpSpeed)
  2705. {
  2706. zSpeedScale = (zSpeedScale <= mDataBlock->jetMinJumpSpeed)? 1:
  2707. 1 - (zSpeedScale - mDataBlock->jetMinJumpSpeed) / (mDataBlock->jetMaxJumpSpeed - mDataBlock->jetMinJumpSpeed);
  2708. // Desired jump direction
  2709. VectorF pv = moveVec;
  2710. F32 len = pv.len();
  2711. if (len > 0.0f)
  2712. pv *= 1 / len;
  2713. // If we are facing into the surface jump up, otherwise
  2714. // jump away from surface.
  2715. F32 dot = mDot(pv,mJumpSurfaceNormal);
  2716. F32 impulse = mDataBlock->jetJumpForce / getMass();
  2717. if (dot <= 0)
  2718. acc.z += mJumpSurfaceNormal.z * impulse * zSpeedScale;
  2719. else
  2720. {
  2721. acc.x += pv.x * impulse * dot;
  2722. acc.y += pv.y * impulse * dot;
  2723. acc.z += mJumpSurfaceNormal.z * impulse * zSpeedScale;
  2724. }
  2725. mEnergy -= mDataBlock->jetJumpEnergyDrain;
  2726. }
  2727. }
  2728. else
  2729. {
  2730. mJetting = false;
  2731. }
  2732. // Add in force from physical zones...
  2733. acc += (mAppliedForce / getMass()) * TickSec;
  2734. // Adjust velocity with all the move & gravity acceleration
  2735. // TG: I forgot why doesn't the TickSec multiply happen here...
  2736. mVelocity += acc;
  2737. // apply horizontal air resistance
  2738. F32 hvel = mSqrt(mVelocity.x * mVelocity.x + mVelocity.y * mVelocity.y);
  2739. if(hvel > mDataBlock->horizResistSpeed)
  2740. {
  2741. F32 speedCap = hvel;
  2742. if(speedCap > mDataBlock->horizMaxSpeed)
  2743. speedCap = mDataBlock->horizMaxSpeed;
  2744. speedCap -= mDataBlock->horizResistFactor * TickSec * (speedCap - mDataBlock->horizResistSpeed);
  2745. F32 scale = speedCap / hvel;
  2746. mVelocity.x *= scale;
  2747. mVelocity.y *= scale;
  2748. }
  2749. if(mVelocity.z > mDataBlock->upResistSpeed)
  2750. {
  2751. if(mVelocity.z > mDataBlock->upMaxSpeed)
  2752. mVelocity.z = mDataBlock->upMaxSpeed;
  2753. mVelocity.z -= mDataBlock->upResistFactor * TickSec * (mVelocity.z - mDataBlock->upResistSpeed);
  2754. }
  2755. // Container buoyancy & drag
  2756. /* Commented out until the buoyancy calculation can be reworked so that a container and
  2757. ** player with the same density will result in neutral buoyancy.
  2758. if (mBuoyancy != 0)
  2759. {
  2760. // Applying buoyancy when standing still causing some jitters-
  2761. if (mBuoyancy > 1.0 || !mVelocity.isZero() || !runSurface)
  2762. {
  2763. // A little hackery to prevent oscillation
  2764. // based on http://reinot.blogspot.com/2005/11/oh-yes-they-float-georgie-they-all.html
  2765. F32 buoyancyForce = mBuoyancy * mGravity * mGravityMod * TickSec;
  2766. F32 currHeight = getPosition().z;
  2767. const F32 C = 2.0f;
  2768. const F32 M = 0.1f;
  2769. if ( currHeight + mVelocity.z * TickSec * C > mLiquidHeight )
  2770. buoyancyForce *= M;
  2771. mVelocity.z -= buoyancyForce;
  2772. }
  2773. }
  2774. */
  2775. // Apply drag
  2776. if ( mSwimming )
  2777. mVelocity -= mVelocity * mDrag * TickSec * ( mVelocity.len() / mDataBlock->maxUnderwaterForwardSpeed );
  2778. else
  2779. mVelocity -= mVelocity * mDrag * TickSec;
  2780. // Clamp very small velocity to zero
  2781. if ( mVelocity.isZero() )
  2782. mVelocity = Point3F::Zero;
  2783. // If we are not touching anything and have sufficient -z vel,
  2784. // we are falling.
  2785. if (runSurface)
  2786. mFalling = false;
  2787. else
  2788. {
  2789. VectorF vel;
  2790. mWorldToObj.mulV(mVelocity,&vel);
  2791. mFalling = vel.z < mDataBlock->fallingSpeedThreshold;
  2792. }
  2793. // Vehicle Dismount
  2794. if ( !isGhost() && move->trigger[sVehicleDismountTrigger] && canJump())
  2795. mDataBlock->doDismount_callback( this );
  2796. // Enter/Leave Liquid
  2797. if ( !mInWater && mWaterCoverage > 0.0f )
  2798. {
  2799. mInWater = true;
  2800. if ( !isGhost() )
  2801. mDataBlock->onEnterLiquid_callback( this, mWaterCoverage, mLiquidType.c_str() );
  2802. }
  2803. else if ( mInWater && mWaterCoverage <= 0.0f )
  2804. {
  2805. mInWater = false;
  2806. if ( !isGhost() )
  2807. mDataBlock->onLeaveLiquid_callback( this, mLiquidType.c_str() );
  2808. else
  2809. {
  2810. // exit-water splash sound happens for client only
  2811. if ( getSpeed() >= mDataBlock->exitSplashSoundVel && !isMounted() )
  2812. SFX->playOnce( mDataBlock->sound[PlayerData::ExitWater], &getTransform() );
  2813. }
  2814. }
  2815. // Update the PlayerPose
  2816. Pose desiredPose = mPose;
  2817. if ( !mIsAiControlled )
  2818. {
  2819. if ( mSwimming )
  2820. desiredPose = SwimPose;
  2821. else if ( runSurface && move->trigger[sCrouchTrigger] && canCrouch() )
  2822. desiredPose = CrouchPose;
  2823. else if ( runSurface && move->trigger[sProneTrigger] && canProne() )
  2824. desiredPose = PronePose;
  2825. else if ( move->trigger[sSprintTrigger] && canSprint() )
  2826. desiredPose = SprintPose;
  2827. else if ( canStand() )
  2828. desiredPose = StandPose;
  2829. setPose( desiredPose );
  2830. }
  2831. }
  2832. //----------------------------------------------------------------------------
  2833. bool Player::checkDismountPosition(const MatrixF& oldMat, const MatrixF& mat)
  2834. {
  2835. AssertFatal(getContainer() != NULL, "Error, must have a container!");
  2836. AssertFatal(getObjectMount() != NULL, "Error, must be mounted!");
  2837. Point3F pos;
  2838. Point3F oldPos;
  2839. mat.getColumn(3, &pos);
  2840. oldMat.getColumn(3, &oldPos);
  2841. RayInfo info;
  2842. disableCollision();
  2843. getObjectMount()->disableCollision();
  2844. if (getContainer()->castRay(oldPos, pos, sCollisionMoveMask, &info))
  2845. {
  2846. enableCollision();
  2847. getObjectMount()->enableCollision();
  2848. return false;
  2849. }
  2850. Box3F wBox = mObjBox;
  2851. wBox.minExtents += pos;
  2852. wBox.maxExtents += pos;
  2853. EarlyOutPolyList polyList;
  2854. polyList.mNormal.set(0.0f, 0.0f, 0.0f);
  2855. polyList.mPlaneList.clear();
  2856. polyList.mPlaneList.setSize(6);
  2857. polyList.mPlaneList[0].set(wBox.minExtents,VectorF(-1.0f, 0.0f, 0.0f));
  2858. polyList.mPlaneList[1].set(wBox.maxExtents,VectorF(0.0f, 1.0f, 0.0f));
  2859. polyList.mPlaneList[2].set(wBox.maxExtents,VectorF(1.0f, 0.0f, 0.0f));
  2860. polyList.mPlaneList[3].set(wBox.minExtents,VectorF(0.0f, -1.0f, 0.0f));
  2861. polyList.mPlaneList[4].set(wBox.minExtents,VectorF(0.0f, 0.0f, -1.0f));
  2862. polyList.mPlaneList[5].set(wBox.maxExtents,VectorF(0.0f, 0.0f, 1.0f));
  2863. if (getContainer()->buildPolyList(PLC_Collision, wBox, sCollisionMoveMask, &polyList))
  2864. {
  2865. enableCollision();
  2866. getObjectMount()->enableCollision();
  2867. return false;
  2868. }
  2869. enableCollision();
  2870. getObjectMount()->enableCollision();
  2871. return true;
  2872. }
  2873. //----------------------------------------------------------------------------
  2874. bool Player::canJump()
  2875. {
  2876. return mAllowJumping && mState == MoveState && mDamageState == Enabled && !isMounted() && !mJumpDelay && mEnergy >= mDataBlock->minJumpEnergy && mJumpSurfaceLastContact < JumpSkipContactsMax && !mSwimming && (mPose != SprintPose || mDataBlock->sprintCanJump);
  2877. }
  2878. bool Player::canJetJump()
  2879. {
  2880. return mAllowJetJumping && mState == MoveState && mDamageState == Enabled && !isMounted() && mEnergy >= mDataBlock->jetMinJumpEnergy && mDataBlock->jetJumpForce != 0.0f;
  2881. }
  2882. bool Player::canSwim()
  2883. {
  2884. // Not used!
  2885. //return mState == MoveState && mDamageState == Enabled && !isMounted() && mEnergy >= mDataBlock->minSwimEnergy && mWaterCoverage >= 0.8f;
  2886. return mAllowSwimming;
  2887. }
  2888. bool Player::canCrouch()
  2889. {
  2890. if (!mAllowCrouching)
  2891. return false;
  2892. if ( mState != MoveState ||
  2893. mDamageState != Enabled ||
  2894. isMounted() ||
  2895. mSwimming ||
  2896. mFalling )
  2897. return false;
  2898. // Can't crouch if no crouch animation!
  2899. if ( mDataBlock->actionList[PlayerData::CrouchRootAnim].sequence == -1 )
  2900. return false;
  2901. // We are already in this pose, so don't test it again...
  2902. if ( mPose == CrouchPose )
  2903. return true;
  2904. // Do standard Torque physics test here!
  2905. if ( !mPhysicsRep )
  2906. {
  2907. F32 radius;
  2908. if ( mPose == PronePose )
  2909. radius = mDataBlock->proneBoxSize.z;
  2910. else
  2911. return true;
  2912. // use our X and Y dimentions on our boxsize as the radii for our search, and the difference between a standing position
  2913. // and the position we currently are in.
  2914. Point3F extent( mDataBlock->crouchBoxSize.x / 2, mDataBlock->crouchBoxSize.y / 2, mDataBlock->crouchBoxSize.z - radius );
  2915. Point3F position = getPosition();
  2916. position.z += radius;
  2917. // Use these radii to create a box that represents the difference between a standing position and the position
  2918. // we want to move into.
  2919. Box3F B(position - extent, position + extent, true);
  2920. EarlyOutPolyList polyList;
  2921. polyList.mPlaneList.clear();
  2922. polyList.mNormal.set( 0,0,0 );
  2923. polyList.mPlaneList.setSize( 6 );
  2924. polyList.mPlaneList[0].set( B.minExtents, VectorF( -1,0,0 ) );
  2925. polyList.mPlaneList[1].set( B.maxExtents, VectorF( 0,1,0 ) );
  2926. polyList.mPlaneList[2].set( B.maxExtents, VectorF( 1,0,0 ) );
  2927. polyList.mPlaneList[3].set( B.minExtents, VectorF( 0,-1,0 ) );
  2928. polyList.mPlaneList[4].set( B.minExtents, VectorF( 0,0,-1 ) );
  2929. polyList.mPlaneList[5].set( B.maxExtents, VectorF( 0,0,1 ) );
  2930. // If an object exists in this space, we must stay prone. Otherwise we are free to crouch.
  2931. return !getContainer()->buildPolyList( PLC_Collision, B, StaticShapeObjectType, &polyList );
  2932. }
  2933. return mPhysicsRep->testSpacials( getPosition(), mDataBlock->crouchBoxSize );
  2934. }
  2935. bool Player::canStand()
  2936. {
  2937. if ( mState != MoveState ||
  2938. mDamageState != Enabled ||
  2939. isMounted() ||
  2940. mSwimming )
  2941. return false;
  2942. // We are already in this pose, so don't test it again...
  2943. if ( mPose == StandPose )
  2944. return true;
  2945. // Do standard Torque physics test here!
  2946. if ( !mPhysicsRep )
  2947. {
  2948. F32 radius;
  2949. if (mPose == CrouchPose)
  2950. radius = mDataBlock->crouchBoxSize.z;
  2951. else if (mPose == PronePose)
  2952. radius = mDataBlock->proneBoxSize.z;
  2953. else
  2954. return true;
  2955. // use our X and Y dimentions on our boxsize as the radii for our search, and the difference between a standing position
  2956. // and the position we currently are in.
  2957. Point3F extent( mDataBlock->boxSize.x / 2, mDataBlock->boxSize.y / 2, mDataBlock->boxSize.z - radius );
  2958. Point3F position = getPosition();
  2959. position.z += radius;
  2960. // Use these radii to create a box that represents the difference between a standing position and the position
  2961. // we want to move into.
  2962. Box3F B(position - extent, position + extent, true);
  2963. EarlyOutPolyList polyList;
  2964. polyList.mPlaneList.clear();
  2965. polyList.mNormal.set(0,0,0);
  2966. polyList.mPlaneList.setSize(6);
  2967. polyList.mPlaneList[0].set(B.minExtents, VectorF(-1,0,0));
  2968. polyList.mPlaneList[1].set(B.maxExtents, VectorF(0,1,0));
  2969. polyList.mPlaneList[2].set(B.maxExtents, VectorF(1,0,0));
  2970. polyList.mPlaneList[3].set(B.minExtents, VectorF(0,-1,0));
  2971. polyList.mPlaneList[4].set(B.minExtents, VectorF(0,0,-1));
  2972. polyList.mPlaneList[5].set(B.maxExtents, VectorF(0,0,1));
  2973. // If an object exists in this space, we must stay crouched/prone. Otherwise we are free to stand.
  2974. return !getContainer()->buildPolyList(PLC_Collision, B, StaticShapeObjectType, &polyList);
  2975. }
  2976. return mPhysicsRep->testSpacials( getPosition(), mDataBlock->boxSize );
  2977. }
  2978. bool Player::canProne()
  2979. {
  2980. if (!mAllowProne)
  2981. return false;
  2982. if ( mState != MoveState ||
  2983. mDamageState != Enabled ||
  2984. isMounted() ||
  2985. mSwimming ||
  2986. mFalling )
  2987. return false;
  2988. // Can't go prone if no prone animation!
  2989. if ( mDataBlock->actionList[PlayerData::ProneRootAnim].sequence == -1 )
  2990. return false;
  2991. // Do standard Torque physics test here!
  2992. if ( !mPhysicsRep )
  2993. return true;
  2994. // We are already in this pose, so don't test it again...
  2995. if ( mPose == PronePose )
  2996. return true;
  2997. return mPhysicsRep->testSpacials( getPosition(), mDataBlock->proneBoxSize );
  2998. }
  2999. bool Player::canSprint()
  3000. {
  3001. return mAllowSprinting && mState == MoveState && mDamageState == Enabled && !isMounted() && mEnergy >= mDataBlock->minSprintEnergy && !mSwimming;
  3002. }
  3003. //----------------------------------------------------------------------------
  3004. void Player::updateDamageLevel()
  3005. {
  3006. if (!isGhost())
  3007. setDamageState((mDamage >= mDataBlock->maxDamage)? Disabled: Enabled);
  3008. if (mDamageThread)
  3009. mShapeInstance->setPos(mDamageThread, mDamage / mDataBlock->destroyedLevel);
  3010. }
  3011. void Player::updateDamageState()
  3012. {
  3013. // Become a corpse when we're disabled (dead).
  3014. if (mDamageState == Enabled) {
  3015. mTypeMask &= ~CorpseObjectType;
  3016. mTypeMask |= PlayerObjectType;
  3017. }
  3018. else {
  3019. mTypeMask &= ~PlayerObjectType;
  3020. mTypeMask |= CorpseObjectType;
  3021. }
  3022. Parent::updateDamageState();
  3023. }
  3024. //----------------------------------------------------------------------------
  3025. void Player::updateLookAnimation(F32 dt)
  3026. {
  3027. // If the preference setting overrideLookAnimation is true, the player's
  3028. // arm and head no longer animate according to the view direction. They
  3029. // are instead given fixed positions.
  3030. if (overrideLookAnimation)
  3031. {
  3032. if (mArmAnimation.thread)
  3033. mShapeInstance->setPos(mArmAnimation.thread, armLookOverridePos);
  3034. if (mHeadVThread)
  3035. mShapeInstance->setPos(mHeadVThread, headVLookOverridePos);
  3036. if (mHeadHThread)
  3037. mShapeInstance->setPos(mHeadHThread, headHLookOverridePos);
  3038. return;
  3039. }
  3040. // Calculate our interpolated head position.
  3041. Point3F renderHead = mDelta.head + mDelta.headVec * dt;
  3042. // Adjust look pos. This assumes that the animations match
  3043. // the min and max look angles provided in the datablock.
  3044. if (mArmAnimation.thread)
  3045. {
  3046. if(mControlObject)
  3047. {
  3048. mShapeInstance->setPos(mArmAnimation.thread,0.5f);
  3049. }
  3050. else
  3051. {
  3052. F32 d = mDataBlock->maxLookAngle - mDataBlock->minLookAngle;
  3053. F32 tp = (renderHead.x - mDataBlock->minLookAngle) / d;
  3054. mShapeInstance->setPos(mArmAnimation.thread,mClampF(tp,0,1));
  3055. }
  3056. }
  3057. if (mHeadVThread)
  3058. {
  3059. F32 d = mDataBlock->maxLookAngle - mDataBlock->minLookAngle;
  3060. F32 tp = (renderHead.x - mDataBlock->minLookAngle) / d;
  3061. mShapeInstance->setPos(mHeadVThread,mClampF(tp,0,1));
  3062. }
  3063. if (mHeadHThread)
  3064. {
  3065. F32 d = 2 * mDataBlock->maxFreelookAngle;
  3066. F32 tp = (renderHead.z + mDataBlock->maxFreelookAngle) / d;
  3067. mShapeInstance->setPos(mHeadHThread,mClampF(tp,0,1));
  3068. }
  3069. }
  3070. //----------------------------------------------------------------------------
  3071. // Methods to get delta (as amount to affect velocity by)
  3072. bool Player::inDeathAnim()
  3073. {
  3074. if ((anim_clip_flags & ANIM_OVERRIDDEN) != 0 && (anim_clip_flags & IS_DEATH_ANIM) == 0)
  3075. return false;
  3076. if (mActionAnimation.thread && mActionAnimation.action >= 0)
  3077. if (mActionAnimation.action < mDataBlock->actionCount)
  3078. return mDataBlock->actionList[mActionAnimation.action].death;
  3079. return false;
  3080. }
  3081. // Get change from mLastDeathPos - return current pos. Assumes we're in death anim.
  3082. F32 Player::deathDelta(Point3F & delta)
  3083. {
  3084. // Get ground delta from the last time we offset this.
  3085. MatrixF mat;
  3086. F32 pos = mShapeInstance->getPos(mActionAnimation.thread);
  3087. mShapeInstance->deltaGround1(mActionAnimation.thread, mDeath.lastPos, pos, mat);
  3088. mat.getColumn(3, & delta);
  3089. return pos;
  3090. }
  3091. // Called before updatePos() to prepare it's needed change to velocity, which
  3092. // must roll over. Should be updated on tick, this is where we remember last
  3093. // position of animation that was used to roll into velocity.
  3094. void Player::updateDeathOffsets()
  3095. {
  3096. if (inDeathAnim())
  3097. // Get ground delta from the last time we offset this.
  3098. mDeath.lastPos = deathDelta(mDeath.posAdd);
  3099. else
  3100. mDeath.clear();
  3101. }
  3102. //----------------------------------------------------------------------------
  3103. // PATHSHAPE
  3104. static const U32 sPlayerConformMask = StaticShapeObjectType | StaticObjectType |
  3105. TerrainObjectType | PathShapeObjectType;
  3106. // PATHSHAPE END
  3107. static void accel(F32& from, F32 to, F32 rate)
  3108. {
  3109. if (from < to)
  3110. from = getMin(from += rate, to);
  3111. else
  3112. from = getMax(from -= rate, to);
  3113. }
  3114. // if (dt == -1)
  3115. // normal tick, so we advance.
  3116. // else
  3117. // interpolate with dt as % of tick, don't advance
  3118. //
  3119. MatrixF * Player::Death::fallToGround(F32 dt, const Point3F& loc, F32 curZ, F32 boxRad)
  3120. {
  3121. static const F32 sConformCheckDown = 4.0f;
  3122. RayInfo coll;
  3123. bool conformToStairs = false;
  3124. Point3F pos(loc.x, loc.y, loc.z + 0.1f);
  3125. Point3F below(pos.x, pos.y, loc.z - sConformCheckDown);
  3126. MatrixF * retVal = NULL;
  3127. PROFILE_SCOPE(ConformToGround);
  3128. if (gClientContainer.castRay(pos, below, sPlayerConformMask, &coll))
  3129. {
  3130. F32 adjust, height = (loc.z - coll.point.z), sink = curSink;
  3131. VectorF desNormal = coll.normal;
  3132. VectorF normal = curNormal;
  3133. // dt >= 0 means we're interpolating and don't accel the numbers
  3134. if (dt >= 0.0f)
  3135. adjust = dt * TickSec;
  3136. else
  3137. adjust = TickSec;
  3138. // Try to get them to conform to stairs by doing several LOS calls. We do this if
  3139. // normal is within about 5 deg. of vertical.
  3140. if (desNormal.z > 0.995f)
  3141. {
  3142. Point3F corners[3], downpts[3];
  3143. S32 c;
  3144. for (c = 0; c < 3; c++) { // Build 3 corners to cast down from-
  3145. corners[c].set(loc.x - boxRad, loc.y - boxRad, loc.z + 1.0f);
  3146. if (c) // add (0,boxWidth) and (boxWidth,0)
  3147. corners[c][c - 1] += (boxRad * 2.0f);
  3148. downpts[c].set(corners[c].x, corners[c].y, loc.z - sConformCheckDown);
  3149. }
  3150. // Do the three casts-
  3151. for (c = 0; c < 3; c++)
  3152. if (gClientContainer.castRay(corners[c], downpts[c], sPlayerConformMask, &coll))
  3153. downpts[c] = coll.point;
  3154. else
  3155. break;
  3156. // Do the math if everything hit below-
  3157. if (c == 3) {
  3158. mCross(downpts[1] - downpts[0], downpts[2] - downpts[1], &desNormal);
  3159. AssertFatal(desNormal.z > 0, "Abnormality in Player::Death::fallToGround()");
  3160. downpts[2] = downpts[2] - downpts[1];
  3161. downpts[1] = downpts[1] - downpts[0];
  3162. desNormal.normalize();
  3163. conformToStairs = true;
  3164. }
  3165. }
  3166. // Move normal in direction we want-
  3167. F32 * cur = normal, * des = desNormal;
  3168. for (S32 i = 0; i < 3; i++)
  3169. accel(*cur++, *des++, adjust * 0.25f);
  3170. if (mFabs(height) < 2.2f && !normal.isZero() && desNormal.z > 0.01f)
  3171. {
  3172. VectorF upY(0.0f, 1.0f, 0.0f), ahead;
  3173. VectorF sideVec;
  3174. MatrixF mat(true);
  3175. normal.normalize();
  3176. mat.set(EulerF (0.0f, 0.0f, curZ));
  3177. mat.mulV(upY, & ahead);
  3178. mCross(ahead, normal, &sideVec);
  3179. sideVec.normalize();
  3180. mCross(normal, sideVec, &ahead);
  3181. static MatrixF resMat(true);
  3182. resMat.setColumn(0, sideVec);
  3183. resMat.setColumn(1, ahead);
  3184. resMat.setColumn(2, normal);
  3185. // Adjust Z down to account for box offset on slope. Figure out how
  3186. // much we want to sink, and gradually accel to this amount. Don't do if
  3187. // we're conforming to stairs though
  3188. F32 xy = mSqrt(desNormal.x * desNormal.x + desNormal.y * desNormal.y);
  3189. F32 desiredSink = (boxRad * xy / desNormal.z);
  3190. if (conformToStairs)
  3191. desiredSink *= 0.5f;
  3192. accel(sink, desiredSink, adjust * 0.15f);
  3193. Point3F position(pos);
  3194. position.z -= sink;
  3195. resMat.setColumn(3, position);
  3196. if (dt < 0.0f)
  3197. { // we're moving, so update normal and sink amount
  3198. curNormal = normal;
  3199. curSink = sink;
  3200. }
  3201. retVal = &resMat;
  3202. }
  3203. }
  3204. return retVal;
  3205. }
  3206. //-------------------------------------------------------------------------------------
  3207. // This is called ::onAdd() to see if we're in a sitting animation. These then
  3208. // can use a longer tick delay for the mount to get across.
  3209. bool Player::inSittingAnim()
  3210. {
  3211. U32 action = mActionAnimation.action;
  3212. if (mActionAnimation.thread && action < mDataBlock->actionCount) {
  3213. const char * name = mDataBlock->actionList[action].name;
  3214. if (!dStricmp(name, "Sitting") || !dStricmp(name, "Scoutroot"))
  3215. return true;
  3216. }
  3217. return false;
  3218. }
  3219. //----------------------------------------------------------------------------
  3220. const String& Player::getArmThread() const
  3221. {
  3222. if (mArmAnimation.thread && mArmAnimation.thread->hasSequence())
  3223. {
  3224. return mArmAnimation.thread->getSequenceName();
  3225. }
  3226. return String::EmptyString;
  3227. }
  3228. bool Player::setArmThread(const char* sequence)
  3229. {
  3230. // The arm sequence must be in the action list.
  3231. for (U32 i = 1; i < mDataBlock->actionCount; i++)
  3232. if (!dStricmp(mDataBlock->actionList[i].name,sequence))
  3233. return setArmThread(i);
  3234. return false;
  3235. }
  3236. bool Player::setArmThread(U32 action)
  3237. {
  3238. PlayerData::ActionAnimation &anim = mDataBlock->actionList[action];
  3239. if (anim.sequence != -1 &&
  3240. anim.sequence != mShapeInstance->getSequence(mArmAnimation.thread))
  3241. {
  3242. mShapeInstance->setSequence(mArmAnimation.thread,anim.sequence,0);
  3243. mArmAnimation.action = action;
  3244. setMaskBits(ActionMask);
  3245. return true;
  3246. }
  3247. return false;
  3248. }
  3249. //----------------------------------------------------------------------------
  3250. bool Player::setActionThread(const char* sequence,bool hold,bool wait,bool fsp)
  3251. {
  3252. if (anim_clip_flags & ANIM_OVERRIDDEN)
  3253. return false;
  3254. for (U32 i = 1; i < mDataBlock->actionCount; i++)
  3255. {
  3256. PlayerData::ActionAnimation &anim = mDataBlock->actionList[i];
  3257. if (!dStricmp(anim.name,sequence))
  3258. {
  3259. setActionThread(i,true,hold,wait,fsp);
  3260. setMaskBits(ActionMask);
  3261. return true;
  3262. }
  3263. }
  3264. return false;
  3265. }
  3266. void Player::setActionThread(U32 action,bool forward,bool hold,bool wait,bool fsp, bool forceSet)
  3267. {
  3268. if (!mDataBlock || !mDataBlock->actionCount || (mActionAnimation.action == action && mActionAnimation.forward == forward && !forceSet))
  3269. return;
  3270. if (action >= PlayerData::NumActionAnims)
  3271. {
  3272. Con::errorf("Player::setActionThread(%d): Player action out of range", action);
  3273. return;
  3274. }
  3275. if (isClientObject())
  3276. {
  3277. mark_idle = (action == PlayerData::RootAnim);
  3278. idle_timer = (mark_idle) ? 0.0f : -1.0f;
  3279. }
  3280. PlayerData::ActionAnimation &anim = mDataBlock->actionList[action];
  3281. if (anim.sequence != -1)
  3282. {
  3283. U32 lastAction = mActionAnimation.action;
  3284. mActionAnimation.action = action;
  3285. mActionAnimation.forward = forward;
  3286. mActionAnimation.firstPerson = fsp;
  3287. mActionAnimation.holdAtEnd = hold;
  3288. mActionAnimation.waitForEnd = hold? true: wait;
  3289. mActionAnimation.animateOnServer = fsp;
  3290. mActionAnimation.atEnd = false;
  3291. mActionAnimation.delayTicks = (S32)sNewAnimationTickTime;
  3292. mActionAnimation.atEnd = false;
  3293. if (sUseAnimationTransitions && (action != PlayerData::LandAnim || !(mDataBlock->landSequenceTime > 0.0f && !mDataBlock->transitionToLand)) && (isGhost()/* || mActionAnimation.animateOnServer*/))
  3294. {
  3295. // The transition code needs the timeScale to be set in the
  3296. // right direction to know which way to go.
  3297. F32 transTime = sAnimationTransitionTime;
  3298. if (mDataBlock && mDataBlock->isJumpAction(action))
  3299. transTime = 0.15f;
  3300. F32 timeScale = mActionAnimation.forward ? 1.0f : -1.0f;
  3301. if (mDataBlock && mDataBlock->isJumpAction(action))
  3302. timeScale *= 1.5f;
  3303. mShapeInstance->setTimeScale(mActionAnimation.thread,timeScale);
  3304. S32 seq = anim.sequence;
  3305. S32 imageBasedSeq = convertActionToImagePrefix(mActionAnimation.action);
  3306. if (imageBasedSeq != -1)
  3307. seq = imageBasedSeq;
  3308. // If we're transitioning into the same sequence (an action may use the
  3309. // same sequence as a previous action) then we want to start at the same
  3310. // position.
  3311. F32 pos = mActionAnimation.forward ? 0.0f : 1.0f;
  3312. PlayerData::ActionAnimation &lastAnim = mDataBlock->actionList[lastAction];
  3313. if (lastAnim.sequence == anim.sequence)
  3314. {
  3315. pos = mShapeInstance->getPos(mActionAnimation.thread);
  3316. }
  3317. mShapeInstance->transitionToSequence(mActionAnimation.thread,seq,
  3318. pos, transTime, true);
  3319. }
  3320. else
  3321. {
  3322. S32 seq = anim.sequence;
  3323. S32 imageBasedSeq = convertActionToImagePrefix(mActionAnimation.action);
  3324. if (imageBasedSeq != -1)
  3325. seq = imageBasedSeq;
  3326. mShapeInstance->setSequence(mActionAnimation.thread,seq,
  3327. mActionAnimation.forward ? 0.0f : 1.0f);
  3328. }
  3329. }
  3330. }
  3331. void Player::updateActionThread()
  3332. {
  3333. PROFILE_START(UpdateActionThread);
  3334. // Select an action animation sequence, this assumes that
  3335. // this function is called once per tick.
  3336. if(mActionAnimation.action != PlayerData::NullAnimation)
  3337. {
  3338. if (mActionAnimation.forward)
  3339. mActionAnimation.atEnd = mShapeInstance->getPos(mActionAnimation.thread) == 1;
  3340. else
  3341. mActionAnimation.atEnd = mShapeInstance->getPos(mActionAnimation.thread) == 0;
  3342. }
  3343. // Only need to deal with triggers on the client
  3344. if( isGhost() )
  3345. {
  3346. bool triggeredLeft = false;
  3347. bool triggeredRight = false;
  3348. F32 offset = 0.0f;
  3349. if( mShapeInstance->getTriggerState( 1 ) )
  3350. {
  3351. triggeredLeft = true;
  3352. offset = -mDataBlock->decalOffset * getScale().x;
  3353. }
  3354. else if(mShapeInstance->getTriggerState( 2 ) )
  3355. {
  3356. triggeredRight = true;
  3357. offset = mDataBlock->decalOffset * getScale().x;
  3358. }
  3359. process_client_triggers(triggeredLeft, triggeredRight);
  3360. if ((triggeredLeft || triggeredRight) && !noFootfallFX)
  3361. {
  3362. Point3F rot, pos;
  3363. RayInfo rInfo;
  3364. MatrixF mat = getRenderTransform();
  3365. mat.getColumn( 1, &rot );
  3366. mat.mulP( Point3F( offset, 0.0f, 0.0f), &pos );
  3367. if( gClientContainer.castRay( Point3F( pos.x, pos.y, pos.z + 0.01f ),
  3368. Point3F( pos.x, pos.y, pos.z - 2.0f ),
  3369. STATIC_COLLISION_TYPEMASK | VehicleObjectType, &rInfo ) )
  3370. {
  3371. Material* material = ( rInfo.material ? dynamic_cast< Material* >( rInfo.material->getMaterial() ) : 0 );
  3372. // Put footprints on surface, if appropriate for material.
  3373. if( material && material->mShowFootprints
  3374. && mDataBlock->decalData && !footfallDecalOverride )
  3375. {
  3376. Point3F normal;
  3377. Point3F tangent;
  3378. mObjToWorld.getColumn( 0, &tangent );
  3379. mObjToWorld.getColumn( 2, &normal );
  3380. gDecalManager->addDecal( rInfo.point, normal, tangent, mDataBlock->decalData, getScale().y );
  3381. }
  3382. // Emit footpuffs.
  3383. if (!footfallDustOverride && rInfo.t <= 0.5f && mWaterCoverage == 0.0f
  3384. && material && material->mShowDust )
  3385. {
  3386. // New emitter every time for visibility reasons
  3387. ParticleEmitter * emitter = new ParticleEmitter;
  3388. emitter->onNewDataBlock( mDataBlock->footPuffEmitter, false );
  3389. LinearColorF colorList[ ParticleData::PDC_NUM_KEYS];
  3390. for( U32 x = 0; x < getMin( Material::NUM_EFFECT_COLOR_STAGES, ParticleData::PDC_NUM_KEYS ); ++ x )
  3391. colorList[ x ].set( material->mEffectColor[ x ].red,
  3392. material->mEffectColor[ x ].green,
  3393. material->mEffectColor[ x ].blue,
  3394. material->mEffectColor[ x ].alpha );
  3395. for( U32 x = Material::NUM_EFFECT_COLOR_STAGES; x < ParticleData::PDC_NUM_KEYS; ++ x )
  3396. colorList[ x ].set( 1.0, 1.0, 1.0, 0.0 );
  3397. emitter->setColors( colorList );
  3398. if( !emitter->registerObject() )
  3399. {
  3400. Con::warnf( ConsoleLogEntry::General, "Could not register emitter for particle of class: %s", mDataBlock->getName() );
  3401. delete emitter;
  3402. emitter = NULL;
  3403. }
  3404. else
  3405. {
  3406. emitter->emitParticles( pos, Point3F( 0.0, 0.0, 1.0 ), mDataBlock->footPuffRadius,
  3407. Point3F( 0, 0, 0 ), mDataBlock->footPuffNumParts );
  3408. emitter->deleteWhenEmpty();
  3409. }
  3410. }
  3411. // Play footstep sound.
  3412. if (footfallSoundOverride <= 0)
  3413. playFootstepSound( triggeredLeft, material, rInfo.object );
  3414. }
  3415. }
  3416. }
  3417. // Mount pending variable puts a hold on the delayTicks below so players don't
  3418. // inadvertently stand up because their mount has not come over yet.
  3419. if (mMountPending)
  3420. mMountPending = (isMounted() ? 0 : (mMountPending - 1));
  3421. if ((mActionAnimation.action == PlayerData::NullAnimation) ||
  3422. ((!mActionAnimation.waitForEnd || mActionAnimation.atEnd) &&
  3423. (!mActionAnimation.holdAtEnd && (mActionAnimation.delayTicks -= !mMountPending) <= 0)))
  3424. {
  3425. //The scripting language will get a call back when a script animation has finished...
  3426. // example: When the chat menu animations are done playing...
  3427. if ( isServerObject() && mActionAnimation.action >= PlayerData::NumTableActionAnims )
  3428. mDataBlock->animationDone_callback( this );
  3429. pickActionAnimation();
  3430. }
  3431. // prevent scaling of AFX picked actions
  3432. if ( (mActionAnimation.action != PlayerData::LandAnim) &&
  3433. (mActionAnimation.action != PlayerData::NullAnimation) &&
  3434. !(anim_clip_flags & ANIM_OVERRIDDEN))
  3435. {
  3436. // Update action animation time scale to match ground velocity
  3437. PlayerData::ActionAnimation &anim =
  3438. mDataBlock->actionList[mActionAnimation.action];
  3439. F32 scale = 1;
  3440. if (anim.velocityScale && anim.speed) {
  3441. VectorF vel;
  3442. mWorldToObj.mulV(mVelocity,&vel);
  3443. scale = mFabs(mDot(vel, anim.dir) / anim.speed);
  3444. if (scale > mDataBlock->maxTimeScale)
  3445. scale = mDataBlock->maxTimeScale;
  3446. }
  3447. mShapeInstance->setTimeScale(mActionAnimation.thread,
  3448. mActionAnimation.forward? scale: -scale);
  3449. }
  3450. PROFILE_END();
  3451. }
  3452. void Player::pickBestMoveAction(U32 startAnim, U32 endAnim, U32 * action, bool * forward) const
  3453. {
  3454. *action = startAnim;
  3455. *forward = false;
  3456. VectorF vel;
  3457. mWorldToObj.mulV(mVelocity,&vel);
  3458. if (vel.lenSquared() > 0.01f)
  3459. {
  3460. // Bias the velocity towards picking the forward/backward anims over
  3461. // the sideways ones to prevent oscillation between anims.
  3462. vel *= VectorF(0.5f, 1.0f, 0.5f);
  3463. // Pick animation that is the best fit for our current (local) velocity.
  3464. // Assumes that the root (stationary) animation is at startAnim.
  3465. F32 curMax = -0.1f;
  3466. for (U32 i = startAnim+1; i <= endAnim; i++)
  3467. {
  3468. const PlayerData::ActionAnimation &anim = mDataBlock->actionList[i];
  3469. if (anim.sequence != -1 && anim.speed)
  3470. {
  3471. F32 d = mDot(vel, anim.dir);
  3472. if (d > curMax)
  3473. {
  3474. curMax = d;
  3475. *action = i;
  3476. *forward = true;
  3477. }
  3478. else
  3479. {
  3480. // Check if reversing this animation would fit (bias against this
  3481. // so that when moving right, the real right anim is still chosen,
  3482. // but if not present, the reversed left anim will be used instead)
  3483. d *= -0.75f;
  3484. if (d > curMax)
  3485. {
  3486. curMax = d;
  3487. *action = i;
  3488. *forward = false;
  3489. }
  3490. }
  3491. }
  3492. }
  3493. }
  3494. }
  3495. void Player::pickActionAnimation()
  3496. {
  3497. // Only select animations in our normal move state.
  3498. if (mState != MoveState || mDamageState != Enabled)
  3499. return;
  3500. if (isMounted() || mMountPending)
  3501. {
  3502. // Go into root position unless something was set explicitly
  3503. // from a script.
  3504. if (mActionAnimation.action != PlayerData::RootAnim &&
  3505. mActionAnimation.action < PlayerData::NumTableActionAnims)
  3506. setActionThread(PlayerData::RootAnim,true,false,false);
  3507. return;
  3508. }
  3509. bool forward = true;
  3510. U32 action = PlayerData::RootAnim;
  3511. bool fsp = false;
  3512. // Jetting overrides the fall animation condition
  3513. if (mJetting)
  3514. {
  3515. // Play the jetting animation
  3516. action = PlayerData::JetAnim;
  3517. }
  3518. else if (mFalling)
  3519. {
  3520. // Not in contact with any surface and falling
  3521. action = PlayerData::FallAnim;
  3522. }
  3523. else if ( mSwimming )
  3524. {
  3525. pickBestMoveAction(PlayerData::SwimRootAnim, PlayerData::SwimRightAnim, &action, &forward);
  3526. }
  3527. else if ( mPose == StandPose )
  3528. {
  3529. if (mContactTimer >= sContactTickTime)
  3530. {
  3531. // Nothing under our feet
  3532. action = PlayerData::RootAnim;
  3533. }
  3534. else
  3535. {
  3536. // Our feet are on something
  3537. pickBestMoveAction(PlayerData::RootAnim, PlayerData::SideRightAnim, &action, &forward);
  3538. }
  3539. }
  3540. else if ( mPose == CrouchPose )
  3541. {
  3542. pickBestMoveAction(PlayerData::CrouchRootAnim, PlayerData::CrouchRightAnim, &action, &forward);
  3543. }
  3544. else if ( mPose == PronePose )
  3545. {
  3546. pickBestMoveAction(PlayerData::ProneRootAnim, PlayerData::ProneBackwardAnim, &action, &forward);
  3547. }
  3548. else if ( mPose == SprintPose )
  3549. {
  3550. pickBestMoveAction(PlayerData::SprintRootAnim, PlayerData::SprintRightAnim, &action, &forward);
  3551. }
  3552. setActionThread(action,forward,false,false,fsp);
  3553. }
  3554. void Player::onImage(U32 imageSlot, bool unmount)
  3555. {
  3556. // Update 3rd person sequences based on images used. Start be getting a
  3557. // list of all possible image prefix sequences.
  3558. String prefixPaths[ShapeBase::MaxMountedImages];
  3559. buildImagePrefixPaths(prefixPaths);
  3560. // Clear out any previous image state animation
  3561. if (mImageStateThread)
  3562. {
  3563. mShapeInstance->destroyThread(mImageStateThread);
  3564. mImageStateThread = 0;
  3565. }
  3566. // Attempt to update the action thread
  3567. U32 action = mActionAnimation.action;
  3568. if (action != PlayerData::NullAnimation)
  3569. {
  3570. String actionSeq = mDataBlock->actionList[action].name;
  3571. if (actionSeq.isNotEmpty())
  3572. {
  3573. S32 seqIndex = mDataBlock->actionList[action].sequence;
  3574. S32 prefixIndex = findPrefixSequence(prefixPaths, actionSeq);
  3575. if (prefixIndex != -1)
  3576. {
  3577. seqIndex = prefixIndex;
  3578. }
  3579. // Only change the sequence if it isn't already playing.
  3580. if (seqIndex != mShapeInstance->getSequence(mActionAnimation.thread))
  3581. {
  3582. F32 pos = mShapeInstance->getPos(mActionAnimation.thread);
  3583. mShapeInstance->setSequence(mActionAnimation.thread, seqIndex, pos);
  3584. }
  3585. }
  3586. }
  3587. // Attempt to update the arm thread
  3588. U32 armAction = getArmAction();
  3589. if (armAction != PlayerData::NullAnimation)
  3590. {
  3591. String armSeq = mDataBlock->actionList[armAction].name;
  3592. if (armSeq.isNotEmpty())
  3593. {
  3594. S32 seqIndex = mDataBlock->actionList[armAction].sequence;
  3595. S32 prefixIndex = findPrefixSequence(prefixPaths, armSeq);
  3596. if (prefixIndex != -1)
  3597. {
  3598. seqIndex = prefixIndex;
  3599. }
  3600. // Only change the sequence if it isn't already playing.
  3601. if (seqIndex != mShapeInstance->getSequence(mArmAnimation.thread))
  3602. {
  3603. F32 pos = mShapeInstance->getPos(mArmAnimation.thread);
  3604. mShapeInstance->setSequence(mArmAnimation.thread, seqIndex, pos);
  3605. }
  3606. }
  3607. }
  3608. // Attempt to update the head threads
  3609. if (mHeadVThread)
  3610. {
  3611. TSShape const* shape = mShapeInstance->getShape();
  3612. S32 seqIndex = shape->findSequence("head");
  3613. S32 prefixIndex = findPrefixSequence(prefixPaths, "head");
  3614. if (prefixIndex != -1)
  3615. {
  3616. seqIndex = prefixIndex;
  3617. }
  3618. // Only change the sequence if it isn't already playing.
  3619. if (seqIndex != mShapeInstance->getSequence(mHeadVThread))
  3620. {
  3621. F32 pos = mShapeInstance->getPos(mHeadVThread);
  3622. mShapeInstance->setSequence(mHeadVThread, seqIndex, pos);
  3623. }
  3624. }
  3625. if (mHeadHThread)
  3626. {
  3627. TSShape const* shape = mShapeInstance->getShape();
  3628. S32 seqIndex = shape->findSequence("headside");
  3629. S32 prefixIndex = findPrefixSequence(prefixPaths, "headside");
  3630. if (prefixIndex != -1)
  3631. {
  3632. seqIndex = prefixIndex;
  3633. }
  3634. // Only change the sequence if it isn't already playing.
  3635. if (seqIndex != mShapeInstance->getSequence(mHeadHThread))
  3636. {
  3637. F32 pos = mShapeInstance->getPos(mHeadHThread);
  3638. mShapeInstance->setSequence(mHeadHThread, seqIndex, pos);
  3639. }
  3640. }
  3641. }
  3642. void Player::buildImagePrefixPaths(String* prefixPaths)
  3643. {
  3644. // We begin obtaining the anim prefix for each image.
  3645. String prefix[ShapeBase::MaxMountedImages];
  3646. for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
  3647. {
  3648. MountedImage& image = mMountedImageList[i];
  3649. if (image.dataBlock && image.dataBlock->imageAnimPrefix && image.dataBlock->imageAnimPrefix[0])
  3650. {
  3651. prefix[i] = String(image.dataBlock->imageAnimPrefix);
  3652. }
  3653. }
  3654. // Build out the full prefix names we will be searching for.
  3655. S32 counter = ShapeBase::MaxMountedImages-1;
  3656. for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
  3657. {
  3658. // Only build out the prefix path for images that have a defined prefix.
  3659. if (prefix[i].isNotEmpty())
  3660. {
  3661. bool start = true;
  3662. for (U32 j=0; j<=i; ++j)
  3663. {
  3664. if (prefix[j].isNotEmpty())
  3665. {
  3666. if (!start)
  3667. {
  3668. prefixPaths[counter] += "_";
  3669. }
  3670. else
  3671. {
  3672. start = false;
  3673. }
  3674. prefixPaths[counter] += prefix[j];
  3675. }
  3676. }
  3677. }
  3678. -- counter;
  3679. }
  3680. }
  3681. S32 Player::findPrefixSequence(String* prefixPaths, const String& baseSeq)
  3682. {
  3683. // Go through the prefix list. If we find a match then return the sequence
  3684. // index.
  3685. for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
  3686. {
  3687. if (prefixPaths[i].isNotEmpty())
  3688. {
  3689. String seq = prefixPaths[i] + "_" + baseSeq;
  3690. S32 seqIndex = mShapeInstance->getShape()->findSequence(seq);
  3691. if (seqIndex != -1)
  3692. {
  3693. return seqIndex;
  3694. }
  3695. }
  3696. }
  3697. return -1;
  3698. }
  3699. S32 Player::convertActionToImagePrefix(U32 action)
  3700. {
  3701. String prefixPaths[ShapeBase::MaxMountedImages];
  3702. buildImagePrefixPaths(prefixPaths);
  3703. if (action != PlayerData::NullAnimation)
  3704. {
  3705. String actionSeq;
  3706. S32 seq = -1;
  3707. // We'll first attempt to find the action sequence by name
  3708. // as defined within the action list.
  3709. actionSeq = mDataBlock->actionList[action].name;
  3710. if (actionSeq.isNotEmpty())
  3711. {
  3712. seq = findPrefixSequence(prefixPaths, actionSeq);
  3713. }
  3714. if (seq == -1)
  3715. {
  3716. // Couldn't find a valid sequence. If this is a sprint action
  3717. // then we also need to search through the standard movement
  3718. // sequences.
  3719. if (action >= PlayerData::SprintRootAnim && action <= PlayerData::SprintRightAnim)
  3720. {
  3721. U32 standardAction = action - PlayerData::SprintRootAnim;
  3722. actionSeq = mDataBlock->actionList[standardAction].name;
  3723. if (actionSeq.isNotEmpty())
  3724. {
  3725. seq = findPrefixSequence(prefixPaths, actionSeq);
  3726. }
  3727. }
  3728. }
  3729. return seq;
  3730. }
  3731. return -1;
  3732. }
  3733. void Player::onImageRecoil( U32, ShapeBaseImageData::StateData::RecoilState state )
  3734. {
  3735. if ( mRecoilThread )
  3736. {
  3737. if ( state != ShapeBaseImageData::StateData::NoRecoil )
  3738. {
  3739. S32 stateIndex = state - ShapeBaseImageData::StateData::LightRecoil;
  3740. if ( mDataBlock->recoilSequence[stateIndex] != -1 )
  3741. {
  3742. mShapeInstance->setSequence( mRecoilThread, mDataBlock->recoilSequence[stateIndex], 0 );
  3743. mShapeInstance->setTimeScale( mRecoilThread, 1 );
  3744. }
  3745. }
  3746. }
  3747. }
  3748. void Player::onImageStateAnimation(U32 imageSlot, const char* seqName, bool direction, bool scaleToState, F32 stateTimeOutValue)
  3749. {
  3750. if (mDataBlock->allowImageStateAnimation && isGhost())
  3751. {
  3752. MountedImage& image = mMountedImageList[imageSlot];
  3753. // Just as with onImageAnimThreadChange we're going to apply various prefixes to determine the final sequence to use.
  3754. // Here is the order:
  3755. // imageBasePrefix_scriptPrefix_baseAnimName
  3756. // imageBasePrefix_baseAnimName
  3757. // scriptPrefix_baseAnimName
  3758. // baseAnimName
  3759. // Collect the prefixes
  3760. const char* imageBasePrefix = "";
  3761. bool hasImageBasePrefix = image.dataBlock && image.dataBlock->imageAnimPrefix && image.dataBlock->imageAnimPrefix[0];
  3762. if (hasImageBasePrefix)
  3763. imageBasePrefix = image.dataBlock->imageAnimPrefix;
  3764. const char* scriptPrefix = getImageScriptAnimPrefix(imageSlot).getString();
  3765. bool hasScriptPrefix = scriptPrefix && scriptPrefix[0];
  3766. S32 seqIndex = mShapeInstance->getShape()->findSequence(seqName);
  3767. // Find the final sequence based on the prefix combinations
  3768. if (hasImageBasePrefix || hasScriptPrefix)
  3769. {
  3770. bool found = false;
  3771. String baseSeqName(seqName);
  3772. if (!found && hasImageBasePrefix && hasScriptPrefix)
  3773. {
  3774. String comboSeqName = String(imageBasePrefix) + String("_") + String(scriptPrefix) + String("_") + baseSeqName;
  3775. S32 index = mShapeInstance->getShape()->findSequence(comboSeqName);
  3776. if (index != -1)
  3777. {
  3778. seqIndex = index;
  3779. found = true;
  3780. }
  3781. }
  3782. if (!found && hasImageBasePrefix)
  3783. {
  3784. String imgSeqName = String(imageBasePrefix) + String("_") + baseSeqName;
  3785. S32 index = mShapeInstance->getShape()->findSequence(imgSeqName);
  3786. if (index != -1)
  3787. {
  3788. seqIndex = index;
  3789. found = true;
  3790. }
  3791. }
  3792. if (!found && hasScriptPrefix)
  3793. {
  3794. String scriptSeqName = String(scriptPrefix) + String("_") + baseSeqName;
  3795. S32 index = mShapeInstance->getShape()->findSequence(scriptSeqName);
  3796. if (index != -1)
  3797. {
  3798. seqIndex = index;
  3799. found = true;
  3800. }
  3801. }
  3802. }
  3803. if (seqIndex != -1)
  3804. {
  3805. if (!mImageStateThread)
  3806. {
  3807. mImageStateThread = mShapeInstance->addThread();
  3808. }
  3809. mShapeInstance->setSequence( mImageStateThread, seqIndex, 0 );
  3810. F32 timeScale = (scaleToState && stateTimeOutValue) ?
  3811. mShapeInstance->getDuration(mImageStateThread) / stateTimeOutValue : 1.0f;
  3812. mShapeInstance->setTimeScale( mImageStateThread, direction ? timeScale : -timeScale );
  3813. }
  3814. }
  3815. }
  3816. const char* Player::getImageAnimPrefix(U32 imageSlot, S32 imageShapeIndex)
  3817. {
  3818. if (!mDataBlock)
  3819. return "";
  3820. switch (imageShapeIndex)
  3821. {
  3822. case ShapeBaseImageData::StandardImageShape:
  3823. {
  3824. return mDataBlock->imageAnimPrefix;
  3825. }
  3826. case ShapeBaseImageData::FirstPersonImageShape:
  3827. {
  3828. return mDataBlock->imageAnimPrefixFP;
  3829. }
  3830. default:
  3831. {
  3832. return "";
  3833. }
  3834. }
  3835. }
  3836. void Player::onImageAnimThreadChange(U32 imageSlot, S32 imageShapeIndex, ShapeBaseImageData::StateData* lastState, const char* anim, F32 pos, F32 timeScale, bool reset)
  3837. {
  3838. if (!mShapeFPInstance[imageSlot] || !mShapeFPAnimThread[imageSlot])
  3839. return;
  3840. MountedImage& image = mMountedImageList[imageSlot];
  3841. ShapeBaseImageData::StateData& stateData = *image.state;
  3842. if (reset)
  3843. {
  3844. // Reset cyclic sequences back to the first frame to turn it off
  3845. // (the first key frame should be it's off state).
  3846. if (mShapeFPAnimThread[imageSlot]->getSequence()->isCyclic() && (stateData.sequenceNeverTransition || !(stateData.sequenceTransitionIn || (lastState && lastState->sequenceTransitionOut))) )
  3847. {
  3848. mShapeFPInstance[imageSlot]->setPos(mShapeFPAnimThread[imageSlot],0);
  3849. mShapeFPInstance[imageSlot]->setTimeScale(mShapeFPAnimThread[imageSlot],0);
  3850. }
  3851. return;
  3852. }
  3853. // Just as with ShapeBase::udpateAnimThread we're going to apply various prefixes to determine the final sequence to use.
  3854. // Here is the order:
  3855. // imageBasePrefix_scriptPrefix_baseAnimName
  3856. // imageBasePrefix_baseAnimName
  3857. // scriptPrefix_baseAnimName
  3858. // baseAnimName
  3859. // Collect the prefixes
  3860. const char* imageBasePrefix = "";
  3861. bool hasImageBasePrefix = image.dataBlock && image.dataBlock->imageAnimPrefixFP && image.dataBlock->imageAnimPrefixFP[0];
  3862. if (hasImageBasePrefix)
  3863. imageBasePrefix = image.dataBlock->imageAnimPrefixFP;
  3864. const char* scriptPrefix = getImageScriptAnimPrefix(imageSlot).getString();
  3865. bool hasScriptPrefix = scriptPrefix && scriptPrefix[0];
  3866. S32 seqIndex = mShapeFPInstance[imageSlot]->getShape()->findSequence(anim);
  3867. // Find the final sequence based on the prefix combinations
  3868. if (hasImageBasePrefix || hasScriptPrefix)
  3869. {
  3870. bool found = false;
  3871. String baseSeqName(anim);
  3872. if (!found && hasImageBasePrefix && hasScriptPrefix)
  3873. {
  3874. String seqName = String(imageBasePrefix) + String("_") + String(scriptPrefix) + String("_") + baseSeqName;
  3875. S32 index = mShapeFPInstance[imageSlot]->getShape()->findSequence(seqName);
  3876. if (index != -1)
  3877. {
  3878. seqIndex = index;
  3879. found = true;
  3880. }
  3881. }
  3882. if (!found && hasImageBasePrefix)
  3883. {
  3884. String seqName = String(imageBasePrefix) + String("_") + baseSeqName;
  3885. S32 index = mShapeFPInstance[imageSlot]->getShape()->findSequence(seqName);
  3886. if (index != -1)
  3887. {
  3888. seqIndex = index;
  3889. found = true;
  3890. }
  3891. }
  3892. if (!found && hasScriptPrefix)
  3893. {
  3894. String seqName = String(scriptPrefix) + String("_") + baseSeqName;
  3895. S32 index = mShapeFPInstance[imageSlot]->getShape()->findSequence(seqName);
  3896. if (index != -1)
  3897. {
  3898. seqIndex = index;
  3899. found = true;
  3900. }
  3901. }
  3902. }
  3903. if (seqIndex != -1)
  3904. {
  3905. if (!lastState)
  3906. {
  3907. // No lastState indicates that we are just switching animation sequences, not states. Transition into this new sequence, but only
  3908. // if it is different than what we're currently playing.
  3909. S32 prevSeq = -1;
  3910. if (mShapeFPAnimThread[imageSlot]->hasSequence())
  3911. {
  3912. prevSeq = mShapeFPInstance[imageSlot]->getSequence(mShapeFPAnimThread[imageSlot]);
  3913. }
  3914. if (seqIndex != prevSeq)
  3915. {
  3916. mShapeFPInstance[imageSlot]->transitionToSequence(mShapeFPAnimThread[imageSlot], seqIndex, pos, image.dataBlock->scriptAnimTransitionTime, true);
  3917. }
  3918. }
  3919. else if (!stateData.sequenceNeverTransition && stateData.sequenceTransitionTime && (stateData.sequenceTransitionIn || (lastState && lastState->sequenceTransitionOut)) )
  3920. {
  3921. mShapeFPInstance[imageSlot]->transitionToSequence(mShapeFPAnimThread[imageSlot], seqIndex, pos, stateData.sequenceTransitionTime, true);
  3922. }
  3923. else
  3924. {
  3925. mShapeFPInstance[imageSlot]->setSequence(mShapeFPAnimThread[imageSlot], seqIndex, pos);
  3926. }
  3927. mShapeFPInstance[imageSlot]->setTimeScale(mShapeFPAnimThread[imageSlot], timeScale);
  3928. }
  3929. }
  3930. void Player::onImageAnimThreadUpdate(U32 imageSlot, S32 imageShapeIndex, F32 dt)
  3931. {
  3932. if (!mShapeFPInstance[imageSlot])
  3933. return;
  3934. if (mShapeFPAmbientThread[imageSlot] && mShapeFPAmbientThread[imageSlot]->hasSequence())
  3935. {
  3936. mShapeFPInstance[imageSlot]->advanceTime(dt,mShapeFPAmbientThread[imageSlot]);
  3937. }
  3938. if (mShapeFPAnimThread[imageSlot] && mShapeFPAnimThread[imageSlot]->hasSequence())
  3939. {
  3940. mShapeFPInstance[imageSlot]->advanceTime(dt,mShapeFPAnimThread[imageSlot]);
  3941. }
  3942. }
  3943. void Player::onUnmount( SceneObject *obj, S32 node )
  3944. {
  3945. // Reset back to root position during dismount.
  3946. setActionThread(PlayerData::RootAnim,true,false,false);
  3947. // Re-orient the player straight up
  3948. Point3F pos,vec;
  3949. getTransform().getColumn(1,&vec);
  3950. getTransform().getColumn(3,&pos);
  3951. Point3F rot(0.0f,0.0f,-mAtan2(-vec.x,vec.y));
  3952. setPosition(pos,rot);
  3953. // Parent function will call script
  3954. Parent::onUnmount( obj, node );
  3955. }
  3956. void Player::unmount()
  3957. {
  3958. // Reset back to root position during dismount. This copies what is
  3959. // done on the server and corrects the fact that the RootAnim change
  3960. // is not sent across to the client using the standard ActionMask.
  3961. setActionThread(PlayerData::RootAnim,true,false,false);
  3962. Parent::unmount();
  3963. }
  3964. //----------------------------------------------------------------------------
  3965. void Player::updateAnimation(F32 dt)
  3966. {
  3967. // If dead then remove any image animations
  3968. if ((mDamageState == Disabled || mDamageState == Destroyed) && mImageStateThread)
  3969. {
  3970. // Remove the image state animation
  3971. mShapeInstance->destroyThread(mImageStateThread);
  3972. mImageStateThread = 0;
  3973. }
  3974. if ((isGhost() || mActionAnimation.animateOnServer) && mActionAnimation.thread)
  3975. mShapeInstance->advanceTime(dt,mActionAnimation.thread);
  3976. if (mRecoilThread)
  3977. mShapeInstance->advanceTime(dt,mRecoilThread);
  3978. if (mImageStateThread)
  3979. mShapeInstance->advanceTime(dt,mImageStateThread);
  3980. // update any active blend clips
  3981. if (isGhost())
  3982. for (S32 i = 0; i < blend_clips.size(); i++)
  3983. mShapeInstance->advanceTime(dt, blend_clips[i].thread);
  3984. // If we are the client's player on this machine, then we need
  3985. // to make sure the transforms are up to date as they are used
  3986. // to setup the camera.
  3987. if (isGhost())
  3988. {
  3989. if (getControllingClient())
  3990. {
  3991. updateAnimationTree(isFirstPerson());
  3992. mShapeInstance->animate();
  3993. }
  3994. else
  3995. {
  3996. updateAnimationTree(false);
  3997. // This addition forces recently visible players to animate their
  3998. // skeleton now rather than in pre-render so that constrained effects
  3999. // get up-to-date node transforms.
  4000. if (didRenderLastRender())
  4001. mShapeInstance->animate();
  4002. }
  4003. }
  4004. }
  4005. void Player::updateAnimationTree(bool firstPerson)
  4006. {
  4007. S32 mode = 0;
  4008. if (firstPerson)
  4009. {
  4010. if (mActionAnimation.firstPerson)
  4011. mode = 0;
  4012. // TSShapeInstance::MaskNodeRotation;
  4013. // TSShapeInstance::MaskNodePosX |
  4014. // TSShapeInstance::MaskNodePosY;
  4015. else
  4016. mode = TSShapeInstance::MaskNodeAllButBlend;
  4017. }
  4018. for (U32 i = 0; i < PlayerData::NumSpineNodes; i++)
  4019. if (mDataBlock->spineNode[i] != -1)
  4020. mShapeInstance->setNodeAnimationState(mDataBlock->spineNode[i],mode);
  4021. }
  4022. //----------------------------------------------------------------------------
  4023. bool Player::step(Point3F *pos,F32 *maxStep,F32 time)
  4024. {
  4025. const Point3F& scale = getScale();
  4026. Box3F box;
  4027. VectorF offset = mVelocity * time;
  4028. box.minExtents = mObjBox.minExtents + offset + *pos;
  4029. box.maxExtents = mObjBox.maxExtents + offset + *pos;
  4030. box.maxExtents.z += mDataBlock->maxStepHeight * scale.z + sMinFaceDistance;
  4031. SphereF sphere;
  4032. sphere.center = (box.minExtents + box.maxExtents) * 0.5f;
  4033. VectorF bv = box.maxExtents - sphere.center;
  4034. sphere.radius = bv.len();
  4035. ClippedPolyList polyList;
  4036. polyList.mPlaneList.clear();
  4037. polyList.mNormal.set(0.0f, 0.0f, 0.0f);
  4038. polyList.mPlaneList.setSize(6);
  4039. polyList.mPlaneList[0].set(box.minExtents,VectorF(-1.0f, 0.0f, 0.0f));
  4040. polyList.mPlaneList[1].set(box.maxExtents,VectorF(0.0f, 1.0f, 0.0f));
  4041. polyList.mPlaneList[2].set(box.maxExtents,VectorF(1.0f, 0.0f, 0.0f));
  4042. polyList.mPlaneList[3].set(box.minExtents,VectorF(0.0f, -1.0f, 0.0f));
  4043. polyList.mPlaneList[4].set(box.minExtents,VectorF(0.0f, 0.0f, -1.0f));
  4044. polyList.mPlaneList[5].set(box.maxExtents,VectorF(0.0f, 0.0f, 1.0f));
  4045. CollisionWorkingList& rList = mConvex.getWorkingList();
  4046. CollisionWorkingList* pList = rList.wLink.mNext;
  4047. while (pList != &rList) {
  4048. Convex* pConvex = pList->mConvex;
  4049. // Alright, here's the deal... a polysoup mesh really needs to be
  4050. // designed with stepping in mind. If there are too many smallish polygons
  4051. // the stepping system here gets confused and allows you to run up walls
  4052. // or on the edges/seams of meshes.
  4053. TSStatic *st = dynamic_cast<TSStatic *> (pConvex->getObject());
  4054. bool skip = false;
  4055. if (st && !st->allowPlayerStep())
  4056. skip = true;
  4057. if ((pConvex->getObject()->getTypeMask() & StaticObjectType) != 0 && !skip)
  4058. {
  4059. Box3F convexBox = pConvex->getBoundingBox();
  4060. if (box.isOverlapped(convexBox))
  4061. pConvex->getPolyList(&polyList);
  4062. }
  4063. pList = pList->wLink.mNext;
  4064. }
  4065. // Find max step height
  4066. F32 stepHeight = pos->z - sMinFaceDistance;
  4067. U32* vp = polyList.mIndexList.begin();
  4068. U32* ep = polyList.mIndexList.end();
  4069. for (; vp != ep; vp++) {
  4070. F32 h = polyList.mVertexList[*vp].point.z + sMinFaceDistance;
  4071. if (h > stepHeight)
  4072. stepHeight = h;
  4073. }
  4074. F32 step = stepHeight - pos->z;
  4075. if (stepHeight > pos->z && step < *maxStep) {
  4076. // Go ahead and step
  4077. pos->z = stepHeight;
  4078. *maxStep -= step;
  4079. return true;
  4080. }
  4081. return false;
  4082. }
  4083. // PATHSHAPE
  4084. // This Function does a ray cast down to see if a pathshape object is below
  4085. // If so, it will attempt to attach to it.
  4086. void Player::updateAttachment(){
  4087. Point3F rot, pos;
  4088. RayInfo rInfo;
  4089. MatrixF mat = getTransform();
  4090. mat.getColumn(3, &pos);
  4091. if (gServerContainer.castRay(Point3F(pos.x, pos.y, pos.z + 0.1f),
  4092. Point3F(pos.x, pos.y, pos.z - 1.0f ),
  4093. PathShapeObjectType, &rInfo))
  4094. {
  4095. if( rInfo.object->getTypeMask() & PathShapeObjectType) //Ramen
  4096. {
  4097. if (getParent() == NULL)
  4098. { // ONLY do this if we are not parented
  4099. //Con::printf("I'm on a pathshape object. Going to attempt attachment.");
  4100. ShapeBase* col = static_cast<ShapeBase*>(rInfo.object);
  4101. if (!isGhost())
  4102. {
  4103. this->attachToParent(col);
  4104. }
  4105. }
  4106. }
  4107. else
  4108. {
  4109. //Con::printf("object %i",rInfo.object->getId());
  4110. }
  4111. }
  4112. else
  4113. {
  4114. if (getParent() !=NULL)
  4115. {
  4116. clearProcessAfter();
  4117. attachToParent(NULL);
  4118. }
  4119. }
  4120. }
  4121. // PATHSHAPE END
  4122. //----------------------------------------------------------------------------
  4123. inline Point3F createInterpPos(const Point3F& s, const Point3F& e, const F32 t, const F32 d)
  4124. {
  4125. Point3F ret;
  4126. ret.interpolate(s, e, t/d);
  4127. return ret;
  4128. }
  4129. Point3F Player::_move( const F32 travelTime, Collision *outCol )
  4130. {
  4131. // Try and move to new pos
  4132. F32 totalMotion = 0.0f;
  4133. // TODO: not used?
  4134. //F32 initialSpeed = mVelocity.len();
  4135. Point3F start;
  4136. Point3F initialPosition;
  4137. getTransform().getColumn(3,&start);
  4138. initialPosition = start;
  4139. static CollisionList collisionList;
  4140. static CollisionList physZoneCollisionList;
  4141. collisionList.clear();
  4142. physZoneCollisionList.clear();
  4143. MatrixF collisionMatrix(true);
  4144. collisionMatrix.setColumn(3, start);
  4145. VectorF firstNormal(0.0f, 0.0f, 0.0f);
  4146. F32 maxStep = mDataBlock->maxStepHeight;
  4147. F32 time = travelTime;
  4148. U32 count = 0;
  4149. const Point3F& scale = getScale();
  4150. static Polyhedron sBoxPolyhedron;
  4151. static ExtrudedPolyList sExtrudedPolyList;
  4152. static ExtrudedPolyList sPhysZonePolyList;
  4153. for (; count < sMoveRetryCount; count++) {
  4154. F32 speed = mVelocity.len();
  4155. if (!speed && !mDeath.haveVelocity())
  4156. break;
  4157. Point3F end = start + mVelocity * time;
  4158. if (mDeath.haveVelocity()) {
  4159. // Add in death movement-
  4160. VectorF deathVel = mDeath.getPosAdd();
  4161. VectorF resVel;
  4162. getTransform().mulV(deathVel, & resVel);
  4163. end += resVel;
  4164. }
  4165. Point3F distance = end - start;
  4166. if (mFabs(distance.x) < mScaledBox.len_x() &&
  4167. mFabs(distance.y) < mScaledBox.len_y() &&
  4168. mFabs(distance.z) < mScaledBox.len_z())
  4169. {
  4170. // We can potentially early out of this. If there are no polys in the clipped polylist at our
  4171. // end position, then we can bail, and just set start = end;
  4172. Box3F wBox = mScaledBox;
  4173. wBox.minExtents += end;
  4174. wBox.maxExtents += end;
  4175. static EarlyOutPolyList eaPolyList;
  4176. eaPolyList.clear();
  4177. eaPolyList.mNormal.set(0.0f, 0.0f, 0.0f);
  4178. eaPolyList.mPlaneList.clear();
  4179. eaPolyList.mPlaneList.setSize(6);
  4180. eaPolyList.mPlaneList[0].set(wBox.minExtents,VectorF(-1.0f, 0.0f, 0.0f));
  4181. eaPolyList.mPlaneList[1].set(wBox.maxExtents,VectorF(0.0f, 1.0f, 0.0f));
  4182. eaPolyList.mPlaneList[2].set(wBox.maxExtents,VectorF(1.0f, 0.0f, 0.0f));
  4183. eaPolyList.mPlaneList[3].set(wBox.minExtents,VectorF(0.0f, -1.0f, 0.0f));
  4184. eaPolyList.mPlaneList[4].set(wBox.minExtents,VectorF(0.0f, 0.0f, -1.0f));
  4185. eaPolyList.mPlaneList[5].set(wBox.maxExtents,VectorF(0.0f, 0.0f, 1.0f));
  4186. // Build list from convex states here...
  4187. CollisionWorkingList& rList = mConvex.getWorkingList();
  4188. CollisionWorkingList* pList = rList.wLink.mNext;
  4189. while (pList != &rList) {
  4190. Convex* pConvex = pList->mConvex;
  4191. if (pConvex->getObject()->getTypeMask() & sCollisionMoveMask) {
  4192. Box3F convexBox = pConvex->getBoundingBox();
  4193. if (wBox.isOverlapped(convexBox))
  4194. {
  4195. // No need to separate out the physical zones here, we want those
  4196. // to cause a fallthrough as well...
  4197. pConvex->getPolyList(&eaPolyList);
  4198. }
  4199. }
  4200. pList = pList->wLink.mNext;
  4201. }
  4202. if (eaPolyList.isEmpty())
  4203. {
  4204. totalMotion += (end - start).len();
  4205. start = end;
  4206. break;
  4207. }
  4208. }
  4209. collisionMatrix.setColumn(3, start);
  4210. sBoxPolyhedron.buildBox(collisionMatrix, mScaledBox, true);
  4211. // Setup the bounding box for the extrudedPolyList
  4212. Box3F plistBox = mScaledBox;
  4213. collisionMatrix.mul(plistBox);
  4214. Point3F oldMin = plistBox.minExtents;
  4215. Point3F oldMax = plistBox.maxExtents;
  4216. plistBox.minExtents.setMin(oldMin + (mVelocity * time) - Point3F(0.1f, 0.1f, 0.1f));
  4217. plistBox.maxExtents.setMax(oldMax + (mVelocity * time) + Point3F(0.1f, 0.1f, 0.1f));
  4218. // Build extruded polyList...
  4219. VectorF vector = end - start;
  4220. sExtrudedPolyList.extrude(sBoxPolyhedron,vector);
  4221. sExtrudedPolyList.setVelocity(mVelocity);
  4222. sExtrudedPolyList.setCollisionList(&collisionList);
  4223. sPhysZonePolyList.extrude(sBoxPolyhedron,vector);
  4224. sPhysZonePolyList.setVelocity(mVelocity);
  4225. sPhysZonePolyList.setCollisionList(&physZoneCollisionList);
  4226. // Build list from convex states here...
  4227. CollisionWorkingList& rList = mConvex.getWorkingList();
  4228. CollisionWorkingList* pList = rList.wLink.mNext;
  4229. while (pList != &rList) {
  4230. Convex* pConvex = pList->mConvex;
  4231. if (pConvex->getObject()->getTypeMask() & sCollisionMoveMask) {
  4232. Box3F convexBox = pConvex->getBoundingBox();
  4233. if (plistBox.isOverlapped(convexBox))
  4234. {
  4235. if (pConvex->getObject()->getTypeMask() & PhysicalZoneObjectType)
  4236. pConvex->getPolyList(&sPhysZonePolyList);
  4237. else
  4238. pConvex->getPolyList(&sExtrudedPolyList);
  4239. }
  4240. }
  4241. pList = pList->wLink.mNext;
  4242. }
  4243. // Take into account any physical zones...
  4244. for (U32 j = 0; j < physZoneCollisionList.getCount(); j++)
  4245. {
  4246. AssertFatal(dynamic_cast<PhysicalZone*>(physZoneCollisionList[j].object), "Bad phys zone!");
  4247. const PhysicalZone* pZone = (PhysicalZone*)physZoneCollisionList[j].object;
  4248. if (pZone->isActive())
  4249. mVelocity *= pZone->getVelocityMod();
  4250. }
  4251. if (collisionList.getCount() != 0 && collisionList.getTime() < 1.0f)
  4252. {
  4253. // Set to collision point
  4254. F32 velLen = mVelocity.len();
  4255. F32 dt = time * getMin(collisionList.getTime(), 1.0f);
  4256. start += mVelocity * dt;
  4257. time -= dt;
  4258. totalMotion += velLen * dt;
  4259. bool wasFalling = mFalling;
  4260. mFalling = false;
  4261. // Back off...
  4262. if ( velLen > 0.f ) {
  4263. F32 newT = getMin(0.01f / velLen, dt);
  4264. start -= mVelocity * newT;
  4265. totalMotion -= velLen * newT;
  4266. }
  4267. // Try stepping if there is a vertical surface
  4268. if (collisionList.getMaxHeight() < start.z + mDataBlock->maxStepHeight * scale.z)
  4269. {
  4270. bool stepped = false;
  4271. for (U32 c = 0; c < collisionList.getCount(); c++)
  4272. {
  4273. const Collision& cp = collisionList[c];
  4274. // if (mFabs(mDot(cp.normal,VectorF(0,0,1))) < sVerticalStepDot)
  4275. // Dot with (0,0,1) just extracts Z component [lh]-
  4276. if (mFabs(cp.normal.z) < sVerticalStepDot)
  4277. {
  4278. stepped = step(&start,&maxStep,time);
  4279. break;
  4280. }
  4281. }
  4282. if (stepped)
  4283. {
  4284. continue;
  4285. }
  4286. }
  4287. // Pick the surface most parallel to the face that was hit.
  4288. const Collision *collision = &collisionList[0];
  4289. const Collision *cp = collision + 1;
  4290. const Collision *ep = collision + collisionList.getCount();
  4291. for (; cp != ep; cp++)
  4292. {
  4293. if (cp->faceDot > collision->faceDot)
  4294. collision = cp;
  4295. }
  4296. F32 bd = _doCollisionImpact( collision, wasFalling );
  4297. // Copy this collision out so
  4298. // we can use it to do impacts
  4299. // and query collision.
  4300. *outCol = *collision;
  4301. if (isServerObject() && bd > 6.8f && collision->normal.z > 0.7f)
  4302. {
  4303. fx_s_triggers |= PLAYER_LANDING_S_TRIGGER;
  4304. setMaskBits(TriggerMask);
  4305. }
  4306. // Subtract out velocity
  4307. VectorF dv = collision->normal * (bd + sNormalElasticity);
  4308. mVelocity += dv;
  4309. if (count == 0)
  4310. {
  4311. firstNormal = collision->normal;
  4312. }
  4313. else
  4314. {
  4315. if (count == 1)
  4316. {
  4317. // Re-orient velocity along the crease.
  4318. if (mDot(dv,firstNormal) < 0.0f &&
  4319. mDot(collision->normal,firstNormal) < 0.0f)
  4320. {
  4321. VectorF nv;
  4322. mCross(collision->normal,firstNormal,&nv);
  4323. F32 nvl = nv.len();
  4324. if (nvl)
  4325. {
  4326. if (mDot(nv,mVelocity) < 0.0f)
  4327. nvl = -nvl;
  4328. nv *= mVelocity.len() / nvl;
  4329. mVelocity = nv;
  4330. }
  4331. }
  4332. }
  4333. }
  4334. }
  4335. else
  4336. {
  4337. totalMotion += (end - start).len();
  4338. start = end;
  4339. break;
  4340. }
  4341. }
  4342. if (count == sMoveRetryCount)
  4343. {
  4344. // Failed to move
  4345. start = initialPosition;
  4346. mVelocity.set(0.0f, 0.0f, 0.0f);
  4347. }
  4348. return start;
  4349. }
  4350. F32 Player::_doCollisionImpact( const Collision *collision, bool fallingCollision)
  4351. {
  4352. F32 bd = -mDot( mVelocity, collision->normal);
  4353. // shake camera on ground impact
  4354. if( bd > mDataBlock->groundImpactMinSpeed && isControlObject() )
  4355. {
  4356. F32 ampScale = (bd - mDataBlock->groundImpactMinSpeed) / mDataBlock->minImpactSpeed;
  4357. CameraShake *groundImpactShake = new CameraShake;
  4358. groundImpactShake->setDuration( mDataBlock->groundImpactShakeDuration );
  4359. groundImpactShake->setFrequency( mDataBlock->groundImpactShakeFreq );
  4360. VectorF shakeAmp = mDataBlock->groundImpactShakeAmp * ampScale;
  4361. groundImpactShake->setAmplitude( shakeAmp );
  4362. groundImpactShake->setFalloff( mDataBlock->groundImpactShakeFalloff );
  4363. groundImpactShake->init();
  4364. gCamFXMgr.addFX( groundImpactShake );
  4365. }
  4366. if ( ((bd > mDataBlock->minImpactSpeed && fallingCollision) || bd > mDataBlock->minLateralImpactSpeed)
  4367. && !mMountPending )
  4368. {
  4369. if ( !isGhost() )
  4370. onImpact( collision->object, collision->normal * bd );
  4371. if (mDamageState == Enabled && mState != RecoverState)
  4372. {
  4373. // Scale how long we're down for
  4374. if (mDataBlock->landSequenceTime > 0.0f)
  4375. {
  4376. // Recover time is based on the land sequence
  4377. setState(RecoverState);
  4378. }
  4379. else
  4380. {
  4381. // Legacy recover system
  4382. F32 value = (bd - mDataBlock->minImpactSpeed);
  4383. F32 range = (mDataBlock->minImpactSpeed * 0.9f);
  4384. U32 recover = mDataBlock->recoverDelay;
  4385. if (value < range)
  4386. recover = 1 + S32(mFloor( F32(recover) * value / range) );
  4387. //Con::printf("Used %d recover ticks", recover);
  4388. //Con::printf(" minImpact = %g, this one = %g", mDataBlock->minImpactSpeed, bd);
  4389. setState(RecoverState, recover);
  4390. }
  4391. }
  4392. }
  4393. if ( isServerObject() &&
  4394. (bd > (mDataBlock->minImpactSpeed / 3.0f) || bd > (mDataBlock->minLateralImpactSpeed / 3.0f )) )
  4395. {
  4396. mImpactSound = PlayerData::ImpactNormal;
  4397. setMaskBits(ImpactMask);
  4398. }
  4399. return bd;
  4400. }
  4401. void Player::_handleCollision( const Collision &collision )
  4402. {
  4403. // Track collisions
  4404. if ( !isGhost() &&
  4405. collision.object &&
  4406. collision.object != mContactInfo.contactObject )
  4407. queueCollision( collision.object, mVelocity - collision.object->getVelocity() );
  4408. }
  4409. bool Player::updatePos(const F32 travelTime)
  4410. {
  4411. PROFILE_SCOPE(Player_UpdatePos);
  4412. getTransform().getColumn(3,&mDelta.posVec);
  4413. // When mounted to another object, only Z rotation used.
  4414. if (isMounted()) {
  4415. mVelocity = mMount.object->getVelocity();
  4416. setPosition(Point3F(0.0f, 0.0f, 0.0f), mRot);
  4417. setMaskBits(MoveMask);
  4418. return true;
  4419. }
  4420. Point3F newPos;
  4421. Collision col;
  4422. dMemset( &col, 0, sizeof( col ) );
  4423. // DEBUG:
  4424. //Point3F savedVelocity = mVelocity;
  4425. if ( mPhysicsRep )
  4426. {
  4427. static CollisionList collisionList;
  4428. collisionList.clear();
  4429. newPos = mPhysicsRep->move( mVelocity * travelTime, collisionList );
  4430. bool haveCollisions = false;
  4431. bool wasFalling = mFalling;
  4432. if (collisionList.getCount() > 0)
  4433. {
  4434. mFalling = false;
  4435. haveCollisions = true;
  4436. }
  4437. if (haveCollisions)
  4438. {
  4439. // Pick the collision that most closely matches our direction
  4440. VectorF velNormal = mVelocity;
  4441. velNormal.normalizeSafe();
  4442. const Collision *collision = &collisionList[0];
  4443. F32 collisionDot = mDot(velNormal, collision->normal);
  4444. const Collision *cp = collision + 1;
  4445. const Collision *ep = collision + collisionList.getCount();
  4446. for (; cp != ep; cp++)
  4447. {
  4448. F32 dp = mDot(velNormal, cp->normal);
  4449. if (dp < collisionDot)
  4450. {
  4451. collisionDot = dp;
  4452. collision = cp;
  4453. }
  4454. }
  4455. _doCollisionImpact( collision, wasFalling );
  4456. // Modify our velocity based on collisions
  4457. for (U32 i=0; i<collisionList.getCount(); ++i)
  4458. {
  4459. F32 bd = -mDot( mVelocity, collisionList[i].normal );
  4460. VectorF dv = collisionList[i].normal * (bd + sNormalElasticity);
  4461. mVelocity += dv;
  4462. }
  4463. // Store the last collision for use later on. The handle collision
  4464. // code only expects a single collision object.
  4465. if (collisionList.getCount() > 0)
  4466. col = collisionList[collisionList.getCount() - 1];
  4467. // We'll handle any player-to-player collision, and the last collision
  4468. // with other obejct types.
  4469. for (U32 i=0; i<collisionList.getCount(); ++i)
  4470. {
  4471. Collision& colCheck = collisionList[i];
  4472. if (colCheck.object)
  4473. {
  4474. SceneObject* obj = static_cast<SceneObject*>(col.object);
  4475. if (obj->getTypeMask() & PlayerObjectType)
  4476. {
  4477. _handleCollision( colCheck );
  4478. }
  4479. else
  4480. {
  4481. col = colCheck;
  4482. }
  4483. }
  4484. }
  4485. _handleCollision( col );
  4486. }
  4487. }
  4488. else
  4489. {
  4490. if ( mVelocity.isZero() )
  4491. newPos = mDelta.posVec;
  4492. else
  4493. newPos = _move( travelTime, &col );
  4494. _handleCollision( col );
  4495. }
  4496. // DEBUG:
  4497. //if ( isClientObject() )
  4498. // Con::printf( "(client) vel: %g %g %g", mVelocity.x, mVelocity.y, mVelocity.z );
  4499. //else
  4500. // Con::printf( "(server) vel: %g %g %g", mVelocity.x, mVelocity.y, mVelocity.z );
  4501. // Set new position
  4502. // If on the client, calc delta for backstepping
  4503. if (isClientObject())
  4504. {
  4505. mDelta.pos = newPos;
  4506. mDelta.posVec = mDelta.posVec - mDelta.pos;
  4507. mDelta.dt = 1.0f;
  4508. }
  4509. setPosition( newPos, mRot );
  4510. setMaskBits( MoveMask );
  4511. updateContainer();
  4512. if (!isGhost())
  4513. {
  4514. // Collisions are only queued on the server and can be
  4515. // generated by either updateMove or updatePos
  4516. notifyCollision();
  4517. // Do mission area callbacks on the server as well
  4518. checkMissionArea();
  4519. }
  4520. // Check the total distance moved. If it is more than 1000th of the velocity, then
  4521. // we moved a fair amount...
  4522. //if (totalMotion >= (0.001f * initialSpeed))
  4523. return true;
  4524. //else
  4525. //return false;
  4526. }
  4527. //----------------------------------------------------------------------------
  4528. void Player::_findContact( SceneObject **contactObject,
  4529. VectorF *contactNormal,
  4530. Vector<SceneObject*> *outOverlapObjects )
  4531. {
  4532. Point3F pos;
  4533. getTransform().getColumn(3,&pos);
  4534. Box3F wBox;
  4535. Point3F exp(0,0,sTractionDistance);
  4536. wBox.minExtents = pos + mScaledBox.minExtents - exp;
  4537. wBox.maxExtents.x = pos.x + mScaledBox.maxExtents.x;
  4538. wBox.maxExtents.y = pos.y + mScaledBox.maxExtents.y;
  4539. wBox.maxExtents.z = pos.z + mScaledBox.minExtents.z + sTractionDistance;
  4540. static ClippedPolyList polyList;
  4541. polyList.clear();
  4542. polyList.doConstruct();
  4543. polyList.mNormal.set(0.0f, 0.0f, 0.0f);
  4544. polyList.setInterestNormal(Point3F(0.0f, 0.0f, -1.0f));
  4545. polyList.mPlaneList.setSize(6);
  4546. polyList.mPlaneList[0].setYZ(wBox.minExtents, -1.0f);
  4547. polyList.mPlaneList[1].setXZ(wBox.maxExtents, 1.0f);
  4548. polyList.mPlaneList[2].setYZ(wBox.maxExtents, 1.0f);
  4549. polyList.mPlaneList[3].setXZ(wBox.minExtents, -1.0f);
  4550. polyList.mPlaneList[4].setXY(wBox.minExtents, -1.0f);
  4551. polyList.mPlaneList[5].setXY(wBox.maxExtents, 1.0f);
  4552. Box3F plistBox = wBox;
  4553. // Expand build box as it will be used to collide with items.
  4554. // PickupRadius will be at least the size of the box.
  4555. F32 pd = (F32)mDataBlock->pickupDelta;
  4556. wBox.minExtents.x -= pd; wBox.minExtents.y -= pd;
  4557. wBox.maxExtents.x += pd; wBox.maxExtents.y += pd;
  4558. wBox.maxExtents.z = pos.z + mScaledBox.maxExtents.z;
  4559. // Build list from convex states here...
  4560. CollisionWorkingList& rList = mConvex.getWorkingList();
  4561. CollisionWorkingList* pList = rList.wLink.mNext;
  4562. while (pList != &rList)
  4563. {
  4564. Convex* pConvex = pList->mConvex;
  4565. U32 objectMask = pConvex->getObject()->getTypeMask();
  4566. if ( ( objectMask & sCollisionMoveMask ) &&
  4567. !( objectMask & PhysicalZoneObjectType ) )
  4568. {
  4569. Box3F convexBox = pConvex->getBoundingBox();
  4570. if (plistBox.isOverlapped(convexBox))
  4571. pConvex->getPolyList(&polyList);
  4572. }
  4573. else
  4574. outOverlapObjects->push_back( pConvex->getObject() );
  4575. pList = pList->wLink.mNext;
  4576. }
  4577. if (!polyList.isEmpty())
  4578. {
  4579. // Pick flattest surface
  4580. F32 bestVd = -1.0f;
  4581. ClippedPolyList::Poly* poly = polyList.mPolyList.begin();
  4582. ClippedPolyList::Poly* end = polyList.mPolyList.end();
  4583. for (; poly != end; poly++)
  4584. {
  4585. F32 vd = poly->plane.z; // i.e. mDot(Point3F(0,0,1), poly->plane);
  4586. if (vd > bestVd)
  4587. {
  4588. bestVd = vd;
  4589. *contactObject = poly->object;
  4590. *contactNormal = poly->plane;
  4591. }
  4592. }
  4593. }
  4594. }
  4595. void Player::findContact( bool *run, bool *jump, VectorF *contactNormal )
  4596. {
  4597. SceneObject *contactObject = NULL;
  4598. Vector<SceneObject*> overlapObjects;
  4599. if ( mPhysicsRep )
  4600. mPhysicsRep->findContact( &contactObject, contactNormal, &overlapObjects );
  4601. else
  4602. _findContact( &contactObject, contactNormal, &overlapObjects );
  4603. // Check for triggers, corpses and items.
  4604. const U32 filterMask = isGhost() ? sClientCollisionContactMask : sServerCollisionContactMask;
  4605. for ( U32 i=0; i < overlapObjects.size(); i++ )
  4606. {
  4607. SceneObject *obj = overlapObjects[i];
  4608. U32 objectMask = obj->getTypeMask();
  4609. if ( !( objectMask & filterMask ) )
  4610. continue;
  4611. // Check: triggers, corpses and items...
  4612. //
  4613. if (objectMask & TriggerObjectType)
  4614. {
  4615. Trigger* pTrigger = static_cast<Trigger*>( obj );
  4616. pTrigger->potentialEnterObject(this);
  4617. }
  4618. else if (objectMask & CorpseObjectType)
  4619. {
  4620. // If we've overlapped the worldbounding boxes, then that's it...
  4621. if ( getWorldBox().isOverlapped( obj->getWorldBox() ) )
  4622. {
  4623. ShapeBase* col = static_cast<ShapeBase*>( obj );
  4624. queueCollision(col,getVelocity() - col->getVelocity());
  4625. }
  4626. }
  4627. else if (objectMask & ItemObjectType)
  4628. {
  4629. // If we've overlapped the worldbounding boxes, then that's it...
  4630. Item* item = static_cast<Item*>( obj );
  4631. if ( getWorldBox().isOverlapped(item->getWorldBox()) &&
  4632. item->getCollisionObject() != this &&
  4633. !item->isHidden() )
  4634. queueCollision(item,getVelocity() - item->getVelocity());
  4635. }
  4636. }
  4637. F32 vd = (*contactNormal).z;
  4638. *run = vd > mDataBlock->runSurfaceCos;
  4639. *jump = vd > mDataBlock->jumpSurfaceCos;
  4640. mContactInfo.clear();
  4641. mContactInfo.contacted = contactObject != NULL;
  4642. mContactInfo.contactObject = contactObject;
  4643. if ( mContactInfo.contacted )
  4644. mContactInfo.contactNormal = *contactNormal;
  4645. mContactInfo.run = *run;
  4646. mContactInfo.jump = *jump;
  4647. }
  4648. //----------------------------------------------------------------------------
  4649. void Player::checkMissionArea()
  4650. {
  4651. // Checks to see if the player is in the Mission Area...
  4652. Point3F pos;
  4653. MissionArea * obj = MissionArea::getServerObject();
  4654. if(!obj)
  4655. return;
  4656. const RectI &area = obj->getArea();
  4657. getTransform().getColumn(3, &pos);
  4658. if ((pos.x < area.point.x || pos.x > area.point.x + area.extent.x ||
  4659. pos.y < area.point.y || pos.y > area.point.y + area.extent.y)) {
  4660. if(mInMissionArea) {
  4661. mInMissionArea = false;
  4662. mDataBlock->onLeaveMissionArea_callback( this );
  4663. }
  4664. }
  4665. else if(!mInMissionArea)
  4666. {
  4667. mInMissionArea = true;
  4668. mDataBlock->onEnterMissionArea_callback( this );
  4669. }
  4670. }
  4671. //----------------------------------------------------------------------------
  4672. bool Player::isDisplacable() const
  4673. {
  4674. return true;
  4675. }
  4676. Point3F Player::getMomentum() const
  4677. {
  4678. return mVelocity * getMass();
  4679. }
  4680. void Player::setMomentum(const Point3F& newMomentum)
  4681. {
  4682. Point3F newVelocity = newMomentum / getMass();
  4683. mVelocity = newVelocity;
  4684. }
  4685. #define LH_HACK 1
  4686. // Hack for short-term soln to Training crash -
  4687. #if LH_HACK
  4688. static U32 sBalance;
  4689. bool Player::displaceObject(const Point3F& displacement)
  4690. {
  4691. F32 vellen = mVelocity.len();
  4692. if (vellen < 0.001f || sBalance > 16) {
  4693. mVelocity.set(0.0f, 0.0f, 0.0f);
  4694. return false;
  4695. }
  4696. F32 dt = displacement.len() / vellen;
  4697. sBalance++;
  4698. bool result = updatePos(dt);
  4699. sBalance--;
  4700. getTransform().getColumn(3, &mDelta.pos);
  4701. mDelta.posVec.set(0.0f, 0.0f, 0.0f);
  4702. return result;
  4703. }
  4704. #else
  4705. bool Player::displaceObject(const Point3F& displacement)
  4706. {
  4707. F32 vellen = mVelocity.len();
  4708. if (vellen < 0.001f) {
  4709. mVelocity.set(0.0f, 0.0f, 0.0f);
  4710. return false;
  4711. }
  4712. F32 dt = displacement.len() / vellen;
  4713. bool result = updatePos(dt);
  4714. mObjToWorld.getColumn(3, &mDelta.pos);
  4715. mDelta.posVec.set(0.0f, 0.0f, 0.0f);
  4716. return result;
  4717. }
  4718. #endif
  4719. //----------------------------------------------------------------------------
  4720. void Player::setPosition(const Point3F& pos,const Point3F& rot)
  4721. {
  4722. MatrixF mat;
  4723. if (isMounted()) {
  4724. // Use transform from mounted object
  4725. //MatrixF nmat,zrot;
  4726. mMount.object->getMountTransform( mMount.node, mMount.xfm, &mat );
  4727. //zrot.set(EulerF(0.0f, 0.0f, rot.z));
  4728. //mat.mul(nmat,zrot);
  4729. }
  4730. else {
  4731. mat.set(EulerF(0.0f, 0.0f, rot.z));
  4732. mat.setColumn(3,pos);
  4733. }
  4734. Parent::setTransform(mat);
  4735. mRot = rot;
  4736. if ( mPhysicsRep )
  4737. mPhysicsRep->setTransform( mat );
  4738. }
  4739. void Player::setRenderPosition(const Point3F& pos, const Point3F& rot, F32 dt)
  4740. {
  4741. MatrixF mat;
  4742. if (isMounted()) {
  4743. // Use transform from mounted object
  4744. //MatrixF nmat,zrot;
  4745. mMount.object->getRenderMountTransform( dt, mMount.node, mMount.xfm, &mat );
  4746. //zrot.set(EulerF(0.0f, 0.0f, rot.z));
  4747. //mat.mul(nmat,zrot);
  4748. }
  4749. else {
  4750. EulerF orient(0.0f, 0.0f, rot.z);
  4751. mat.set(orient);
  4752. mat.setColumn(3, pos);
  4753. if (inDeathAnim()) {
  4754. F32 boxRad = (mDataBlock->boxSize.x * 0.5f);
  4755. if (MatrixF * fallMat = mDeath.fallToGround(dt, pos, rot.z, boxRad))
  4756. mat = * fallMat;
  4757. }
  4758. else
  4759. mDeath.initFall();
  4760. }
  4761. Parent::setRenderTransform(mat);
  4762. }
  4763. //----------------------------------------------------------------------------
  4764. void Player::setTransform(const MatrixF& mat)
  4765. {
  4766. // This method should never be called on the client.
  4767. // This currently converts all rotation in the mat into
  4768. // rotations around the z axis.
  4769. Point3F pos,vec;
  4770. mat.getColumn(1,&vec);
  4771. mat.getColumn(3,&pos);
  4772. Point3F rot(0.0f, 0.0f, -mAtan2(-vec.x,vec.y));
  4773. setPosition(pos,rot);
  4774. setMaskBits(MoveMask | NoWarpMask);
  4775. }
  4776. void Player::getEyeTransform(MatrixF* mat)
  4777. {
  4778. getEyeBaseTransform(mat, true);
  4779. // The shape instance is animated in getEyeBaseTransform() so we're
  4780. // good here when attempting to get the eye node position on the server.
  4781. S32 imageIndex = -1;
  4782. S32 shapeIndex = -1;
  4783. MountedImage* image = NULL;
  4784. ShapeBaseImageData* data = NULL;
  4785. for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
  4786. {
  4787. image = &(mMountedImageList[i]);
  4788. if (image->dataBlock)
  4789. {
  4790. data = image->dataBlock;
  4791. shapeIndex = getImageShapeIndex(*image);
  4792. if ( data->useEyeNode && (data->animateOnServer || isGhost()) && isFirstPerson() && data->eyeMountNode[shapeIndex] != -1 && data->eyeNode[shapeIndex] != -1 )
  4793. {
  4794. imageIndex = i;
  4795. break;
  4796. }
  4797. }
  4798. }
  4799. if (imageIndex >= 0)
  4800. {
  4801. // Get the image's eye node's position relative to the eye mount node
  4802. MatrixF mountTransform = image->shapeInstance[shapeIndex]->mNodeTransforms[data->eyeMountNode[shapeIndex]];
  4803. Point3F eyeMountNodePos = mountTransform.getPosition();
  4804. mountTransform = image->shapeInstance[shapeIndex]->mNodeTransforms[data->eyeNode[shapeIndex]];
  4805. Point3F eyeNodePos = mountTransform.getPosition() - eyeMountNodePos;
  4806. // Now transform to the image's eye node (position only)
  4807. MatrixF xfm(true);
  4808. xfm.setPosition(eyeNodePos);
  4809. mat->mul(xfm);
  4810. }
  4811. }
  4812. void Player::getEyeBaseTransform(MatrixF* mat, bool includeBank)
  4813. {
  4814. // Eye transform in world space. We only use the eye position
  4815. // from the animation and supply our own rotation.
  4816. MatrixF pmat,xmat,zmat;
  4817. if(!isGhost())
  4818. mShapeInstance->animate();
  4819. xmat.set(EulerF(mHead.x, 0.0f, 0.0f));
  4820. if (mUseHeadZCalc)
  4821. zmat.set(EulerF(0.0f, 0.0f, mHead.z));
  4822. else
  4823. zmat.identity();
  4824. if(includeBank && mDataBlock->cameraCanBank)
  4825. {
  4826. // Take mHead.y into account to bank the camera
  4827. MatrixF imat;
  4828. imat.mul(zmat, xmat);
  4829. MatrixF ymat;
  4830. ymat.set(EulerF(0.0f, mHead.y, 0.0f));
  4831. pmat.mul(imat, ymat);
  4832. }
  4833. else
  4834. {
  4835. pmat.mul(zmat,xmat);
  4836. }
  4837. F32 *dp = pmat;
  4838. F32* sp;
  4839. MatrixF eyeMat(true);
  4840. if (mDataBlock->eyeNode != -1)
  4841. {
  4842. sp = mShapeInstance->mNodeTransforms[mDataBlock->eyeNode];
  4843. }
  4844. else
  4845. {
  4846. Point3F center;
  4847. mObjBox.getCenter(&center);
  4848. eyeMat.setPosition(center);
  4849. sp = eyeMat;
  4850. }
  4851. const Point3F& scale = getScale();
  4852. dp[3] = sp[3] * scale.x;
  4853. dp[7] = sp[7] * scale.y;
  4854. dp[11] = sp[11] * scale.z;
  4855. mat->mul(getTransform(),pmat);
  4856. }
  4857. void Player::getRenderEyeTransform(MatrixF* mat)
  4858. {
  4859. getRenderEyeBaseTransform(mat, true);
  4860. // Use the first image that is set to use the eye node
  4861. for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
  4862. {
  4863. MountedImage& image = mMountedImageList[i];
  4864. if (image.dataBlock)
  4865. {
  4866. ShapeBaseImageData& data = *image.dataBlock;
  4867. U32 shapeIndex = getImageShapeIndex(image);
  4868. if ( data.useEyeNode && isFirstPerson() && data.eyeMountNode[shapeIndex] != -1 && data.eyeNode[shapeIndex] != -1 )
  4869. {
  4870. // Get the eye node's position relative to the eye mount node
  4871. MatrixF mountTransform = image.shapeInstance[shapeIndex]->mNodeTransforms[data.eyeMountNode[shapeIndex]];
  4872. Point3F eyeMountNodePos = mountTransform.getPosition();
  4873. mountTransform = image.shapeInstance[shapeIndex]->mNodeTransforms[data.eyeNode[shapeIndex]];
  4874. Point3F eyeNodePos = mountTransform.getPosition() - eyeMountNodePos;
  4875. // Now transform to the image's eye node (position only)
  4876. MatrixF xfm(true);
  4877. xfm.setPosition(eyeNodePos);
  4878. mat->mul(xfm);
  4879. return;
  4880. }
  4881. }
  4882. }
  4883. }
  4884. void Player::getRenderEyeBaseTransform(MatrixF* mat, bool includeBank)
  4885. {
  4886. // Eye transform in world space. We only use the eye position
  4887. // from the animation and supply our own rotation.
  4888. MatrixF pmat,xmat,zmat;
  4889. xmat.set(EulerF(mDelta.head.x + mDelta.headVec.x * mDelta.dt, 0.0f, 0.0f));
  4890. if (mUseHeadZCalc)
  4891. zmat.set(EulerF(0.0f, 0.0f, mDelta.head.z + mDelta.headVec.z * mDelta.dt));
  4892. else
  4893. zmat.identity();
  4894. if(includeBank && mDataBlock->cameraCanBank)
  4895. {
  4896. // Take mHead.y delta into account to bank the camera
  4897. MatrixF imat;
  4898. imat.mul(zmat, xmat);
  4899. MatrixF ymat;
  4900. ymat.set(EulerF(0.0f, mDelta.head.y + mDelta.headVec.y * mDelta.dt, 0.0f));
  4901. pmat.mul(imat, ymat);
  4902. }
  4903. else
  4904. {
  4905. pmat.mul(zmat,xmat);
  4906. }
  4907. F32 *dp = pmat;
  4908. F32* sp;
  4909. MatrixF eyeMat(true);
  4910. if (mDataBlock->eyeNode != -1)
  4911. {
  4912. sp = mShapeInstance->mNodeTransforms[mDataBlock->eyeNode];
  4913. }
  4914. else
  4915. {
  4916. // Use the center of the Player's bounding box for the eye position.
  4917. Point3F center;
  4918. mObjBox.getCenter(&center);
  4919. eyeMat.setPosition(center);
  4920. sp = eyeMat;
  4921. }
  4922. // Only use position of eye node, and take Player's scale
  4923. // into account.
  4924. const Point3F& scale = getScale();
  4925. dp[3] = sp[3] * scale.x;
  4926. dp[7] = sp[7] * scale.y;
  4927. dp[11] = sp[11] * scale.z;
  4928. mat->mul(getRenderTransform(), pmat);
  4929. }
  4930. void Player::getMuzzleTransform(U32 imageSlot,MatrixF* mat)
  4931. {
  4932. disableHeadZCalc();
  4933. MatrixF nmat;
  4934. Parent::getRetractionTransform(imageSlot,&nmat);
  4935. MatrixF smat;
  4936. Parent::getImageTransform(imageSlot,&smat);
  4937. disableCollision();
  4938. // See if we are pushed into a wall...
  4939. if (getDamageState() == Enabled) {
  4940. Point3F start, end;
  4941. smat.getColumn(3, &start);
  4942. nmat.getColumn(3, &end);
  4943. RayInfo rinfo;
  4944. if (getContainer()->castRay(start, end, sCollisionMoveMask, &rinfo)) {
  4945. Point3F finalPoint;
  4946. finalPoint.interpolate(start, end, rinfo.t);
  4947. nmat.setColumn(3, finalPoint);
  4948. }
  4949. else
  4950. Parent::getMuzzleTransform(imageSlot,&nmat);
  4951. }
  4952. else
  4953. Parent::getMuzzleTransform(imageSlot,&nmat);
  4954. enableCollision();
  4955. enableHeadZCalc();
  4956. *mat = nmat;
  4957. }
  4958. void Player::getRenderMuzzleTransform(U32 imageSlot,MatrixF* mat)
  4959. {
  4960. disableHeadZCalc();
  4961. MatrixF nmat;
  4962. Parent::getRenderRetractionTransform(imageSlot,&nmat);
  4963. MatrixF smat;
  4964. Parent::getRenderImageTransform(imageSlot,&smat);
  4965. disableCollision();
  4966. // See if we are pushed into a wall...
  4967. if (getDamageState() == Enabled)
  4968. {
  4969. Point3F start, end;
  4970. smat.getColumn(3, &start);
  4971. nmat.getColumn(3, &end);
  4972. RayInfo rinfo;
  4973. if (getContainer()->castRay(start, end, sCollisionMoveMask, &rinfo)) {
  4974. Point3F finalPoint;
  4975. finalPoint.interpolate(start, end, rinfo.t);
  4976. nmat.setColumn(3, finalPoint);
  4977. }
  4978. else
  4979. {
  4980. Parent::getRenderMuzzleTransform(imageSlot,&nmat);
  4981. }
  4982. }
  4983. else
  4984. {
  4985. Parent::getRenderMuzzleTransform(imageSlot,&nmat);
  4986. }
  4987. enableCollision();
  4988. enableHeadZCalc();
  4989. *mat = nmat;
  4990. }
  4991. void Player::getMuzzleVector(U32 imageSlot,VectorF* vec)
  4992. {
  4993. MatrixF mat;
  4994. getMuzzleTransform(imageSlot,&mat);
  4995. GameConnection * gc = getControllingClient();
  4996. if (gc && !gc->isAIControlled())
  4997. {
  4998. MountedImage& image = mMountedImageList[imageSlot];
  4999. bool fp = gc->isFirstPerson();
  5000. if ((fp && image.dataBlock->correctMuzzleVector) ||
  5001. (!fp && image.dataBlock->correctMuzzleVectorTP))
  5002. {
  5003. disableHeadZCalc();
  5004. if (getCorrectedAim(mat, vec))
  5005. {
  5006. enableHeadZCalc();
  5007. return;
  5008. }
  5009. enableHeadZCalc();
  5010. }
  5011. }
  5012. mat.getColumn(1,vec);
  5013. }
  5014. void Player::renderMountedImage( U32 imageSlot, TSRenderState &rstate, SceneRenderState *state )
  5015. {
  5016. GFX->pushWorldMatrix();
  5017. MatrixF world;
  5018. MountedImage& image = mMountedImageList[imageSlot];
  5019. ShapeBaseImageData& data = *image.dataBlock;
  5020. U32 imageShapeIndex;
  5021. if ( state->isShadowPass() )
  5022. {
  5023. // Force the standard image shapes for the shadow pass.
  5024. imageShapeIndex = ShapeBaseImageData::StandardImageShape;
  5025. }
  5026. else
  5027. {
  5028. imageShapeIndex = getImageShapeIndex(image);
  5029. }
  5030. if ( !state->isShadowPass() && isFirstPerson() && (data.useEyeOffset || (data.useEyeNode && data.eyeMountNode[imageShapeIndex] != -1)) )
  5031. {
  5032. if (data.useEyeNode && data.eyeMountNode[imageShapeIndex] != -1)
  5033. {
  5034. MatrixF nmat;
  5035. getRenderEyeBaseTransform(&nmat, mDataBlock->mountedImagesBank);
  5036. MatrixF offsetMat = image.shapeInstance[imageShapeIndex]->mNodeTransforms[data.eyeMountNode[imageShapeIndex]];
  5037. offsetMat.affineInverse();
  5038. world.mul(nmat,offsetMat);
  5039. }
  5040. else
  5041. {
  5042. MatrixF nmat;
  5043. getRenderEyeBaseTransform(&nmat, mDataBlock->mountedImagesBank);
  5044. world.mul(nmat,data.eyeOffset);
  5045. }
  5046. if ( imageSlot == 0 )
  5047. {
  5048. MatrixF nmat;
  5049. MatrixF smat;
  5050. getRenderRetractionTransform(0,&nmat);
  5051. getRenderImageTransform(0,&smat);
  5052. // See if we are pushed into a wall...
  5053. Point3F start, end;
  5054. smat.getColumn(3, &start);
  5055. nmat.getColumn(3, &end);
  5056. Point3F displace = (start - end) * mWeaponBackFraction;
  5057. world.setPosition( world.getPosition() + displace );
  5058. }
  5059. }
  5060. else
  5061. {
  5062. MatrixF nmat;
  5063. getRenderMountTransform( 0.0f, data.mountPoint, MatrixF::Identity, &nmat);
  5064. world.mul(nmat,data.mountTransform[imageShapeIndex]);
  5065. }
  5066. GFX->setWorldMatrix( world );
  5067. image.shapeInstance[imageShapeIndex]->animate();
  5068. image.shapeInstance[imageShapeIndex]->render( rstate );
  5069. // Render the first person mount image shape?
  5070. if (!state->isShadowPass() && imageShapeIndex == ShapeBaseImageData::FirstPersonImageShape && mShapeFPInstance[imageSlot])
  5071. {
  5072. mShapeFPInstance[imageSlot]->animate();
  5073. mShapeFPInstance[imageSlot]->render( rstate );
  5074. }
  5075. GFX->popWorldMatrix();
  5076. }
  5077. // Bot aiming code calls this frequently and will work fine without the check
  5078. // for being pushed into a wall, which shows up on profile at ~ 3% (eight bots)
  5079. void Player::getMuzzlePointAI(U32 imageSlot, Point3F* point)
  5080. {
  5081. MatrixF nmat;
  5082. Parent::getMuzzleTransform(imageSlot, &nmat);
  5083. // If we are in one of the standard player animations, adjust the
  5084. // muzzle to point in the direction we are looking.
  5085. if (mActionAnimation.action < PlayerData::NumTableActionAnims)
  5086. {
  5087. MatrixF xmat;
  5088. xmat.set(EulerF(mHead.x, 0, 0));
  5089. MatrixF result;
  5090. result.mul(getTransform(), xmat);
  5091. F32 *sp = nmat, *dp = result;
  5092. dp[3] = sp[3]; dp[7] = sp[7]; dp[11] = sp[11];
  5093. result.getColumn(3, point);
  5094. }
  5095. else
  5096. nmat.getColumn(3, point);
  5097. }
  5098. void Player::getCameraParameters(F32 *min,F32* max,Point3F* off,MatrixF* rot)
  5099. {
  5100. if (!mControlObject.isNull() && mControlObject == getObjectMount()) {
  5101. mControlObject->getCameraParameters(min,max,off,rot);
  5102. return;
  5103. }
  5104. const Point3F& scale = getScale();
  5105. *min = mDataBlock->cameraMinDist * scale.y;
  5106. *max = mDataBlock->cameraMaxDist * scale.y;
  5107. off->set(0.0f, 0.0f, 0.0f);
  5108. rot->identity();
  5109. }
  5110. //----------------------------------------------------------------------------
  5111. Point3F Player::getVelocity() const
  5112. {
  5113. return mVelocity;
  5114. }
  5115. F32 Player::getSpeed() const
  5116. {
  5117. return mVelocity.len();
  5118. }
  5119. void Player::setVelocity(const VectorF& vel)
  5120. {
  5121. AssertFatal( !mIsNaN( vel ), "Player::setVelocity() - The velocity is NaN!" );
  5122. mVelocity = vel;
  5123. setMaskBits(MoveMask);
  5124. }
  5125. void Player::applyImpulse(const Point3F&,const VectorF& vec)
  5126. {
  5127. AssertFatal( !mIsNaN( vec ), "Player::applyImpulse() - The vector is NaN!" );
  5128. // Players ignore angular velocity
  5129. VectorF vel;
  5130. vel.x = vec.x / getMass();
  5131. vel.y = vec.y / getMass();
  5132. vel.z = vec.z / getMass();
  5133. // Make sure the impulse isn't too big
  5134. F32 len = vel.magnitudeSafe();
  5135. if (len > sMaxImpulseVelocity)
  5136. {
  5137. Point3F excess = vel * ( 1.0f - (sMaxImpulseVelocity / len ) );
  5138. vel -= excess;
  5139. }
  5140. setVelocity(mVelocity + vel);
  5141. }
  5142. //----------------------------------------------------------------------------
  5143. bool Player::castRay(const Point3F &start, const Point3F &end, RayInfo* info)
  5144. {
  5145. // In standard Torque there's a rather brute force culling of all
  5146. // non-enabled players (corpses) from the ray cast. But, to
  5147. // demonstrate a resurrection spell, we need corpses to be
  5148. // selectable, so this code change allows consideration of corpses
  5149. // in the ray cast if corpsesHiddenFromRayCast is set to false.
  5150. if (sCorpsesHiddenFromRayCast && getDamageState() != Enabled)
  5151. return false;
  5152. // Collide against bounding box. Need at least this for the editor.
  5153. F32 st,et,fst = 0.0f,fet = 1.0f;
  5154. F32 *bmin = &mObjBox.minExtents.x;
  5155. F32 *bmax = &mObjBox.maxExtents.x;
  5156. F32 const *si = &start.x;
  5157. F32 const *ei = &end.x;
  5158. for (S32 i = 0; i < 3; i++) {
  5159. if (*si < *ei) {
  5160. if (*si > *bmax || *ei < *bmin)
  5161. return false;
  5162. F32 di = *ei - *si;
  5163. st = (*si < *bmin)? (*bmin - *si) / di: 0.0f;
  5164. et = (*ei > *bmax)? (*bmax - *si) / di: 1.0f;
  5165. }
  5166. else {
  5167. if (*ei > *bmax || *si < *bmin)
  5168. return false;
  5169. F32 di = *ei - *si;
  5170. st = (*si > *bmax)? (*bmax - *si) / di: 0.0f;
  5171. et = (*ei < *bmin)? (*bmin - *si) / di: 1.0f;
  5172. }
  5173. if (st > fst) fst = st;
  5174. if (et < fet) fet = et;
  5175. if (fet < fst)
  5176. return false;
  5177. bmin++; bmax++;
  5178. si++; ei++;
  5179. }
  5180. info->normal = start - end;
  5181. info->normal.normalizeSafe();
  5182. getTransform().mulV( info->normal );
  5183. info->t = fst;
  5184. info->object = this;
  5185. info->point.interpolate(start,end,fst);
  5186. info->material = 0;
  5187. return true;
  5188. }
  5189. //----------------------------------------------------------------------------
  5190. static MatrixF IMat(1);
  5191. bool Player::buildPolyList(PolyListContext, AbstractPolyList* polyList, const Box3F&, const SphereF&)
  5192. {
  5193. // Collision with the player is always against the player's object
  5194. // space bounding box axis aligned in world space.
  5195. Point3F pos;
  5196. getTransform().getColumn(3,&pos);
  5197. IMat.setColumn(3,pos);
  5198. polyList->setTransform(&IMat, Point3F(1.0f,1.0f,1.0f));
  5199. polyList->setObject(this);
  5200. polyList->addBox(mObjBox);
  5201. return true;
  5202. }
  5203. void Player::buildConvex(const Box3F& box, Convex* convex)
  5204. {
  5205. if (mShapeInstance == NULL)
  5206. return;
  5207. // These should really come out of a pool
  5208. mConvexList->collectGarbage();
  5209. Box3F realBox = box;
  5210. mWorldToObj.mul(realBox);
  5211. realBox.minExtents.convolveInverse(mObjScale);
  5212. realBox.maxExtents.convolveInverse(mObjScale);
  5213. if (realBox.isOverlapped(getObjBox()) == false)
  5214. return;
  5215. Convex* cc = 0;
  5216. CollisionWorkingList& wl = convex->getWorkingList();
  5217. for (CollisionWorkingList* itr = wl.wLink.mNext; itr != &wl; itr = itr->wLink.mNext) {
  5218. if (itr->mConvex->getType() == BoxConvexType &&
  5219. itr->mConvex->getObject() == this) {
  5220. cc = itr->mConvex;
  5221. break;
  5222. }
  5223. }
  5224. if (cc)
  5225. return;
  5226. // Create a new convex.
  5227. BoxConvex* cp = new OrthoBoxConvex;
  5228. mConvexList->registerObject(cp);
  5229. convex->addToWorkingList(cp);
  5230. cp->init(this);
  5231. mObjBox.getCenter(&cp->mCenter);
  5232. cp->mSize.x = mObjBox.len_x() / 2.0f;
  5233. cp->mSize.y = mObjBox.len_y() / 2.0f;
  5234. cp->mSize.z = mObjBox.len_z() / 2.0f;
  5235. }
  5236. //----------------------------------------------------------------------------
  5237. void Player::updateWorkingCollisionSet()
  5238. {
  5239. // First, we need to adjust our velocity for possible acceleration. It is assumed
  5240. // that we will never accelerate more than 20 m/s for gravity, plus 10 m/s for
  5241. // jetting, and an equivalent 10 m/s for jumping. We also assume that the
  5242. // working list is updated on a Tick basis, which means we only expand our
  5243. // box by the possible movement in that tick.
  5244. Point3F scaledVelocity = mVelocity * TickSec;
  5245. F32 len = scaledVelocity.len();
  5246. F32 newLen = len + (10.0f * TickSec);
  5247. // Check to see if it is actually necessary to construct the new working list,
  5248. // or if we can use the cached version from the last query. We use the x
  5249. // component of the min member of the mWorkingQueryBox, which is lame, but
  5250. // it works ok.
  5251. bool updateSet = false;
  5252. Box3F convexBox = mConvex.getBoundingBox(getTransform(), getScale());
  5253. F32 l = (newLen * 1.1f) + 0.1f; // from Convex::updateWorkingList
  5254. const Point3F lPoint( l, l, l );
  5255. convexBox.minExtents -= lPoint;
  5256. convexBox.maxExtents += lPoint;
  5257. // Check containment
  5258. if (mWorkingQueryBox.minExtents.x != -1e9f)
  5259. {
  5260. if (mWorkingQueryBox.isContained(convexBox) == false)
  5261. // Needed region is outside the cached region. Update it.
  5262. updateSet = true;
  5263. }
  5264. else
  5265. {
  5266. // Must update
  5267. updateSet = true;
  5268. }
  5269. // Actually perform the query, if necessary
  5270. if (updateSet == true) {
  5271. const Point3F twolPoint( 2.0f * l, 2.0f * l, 2.0f * l );
  5272. mWorkingQueryBox = convexBox;
  5273. mWorkingQueryBox.minExtents -= twolPoint;
  5274. mWorkingQueryBox.maxExtents += twolPoint;
  5275. disableCollision();
  5276. //We temporarily disable the collisions of anything mounted to us so we don't accidentally walk into things we've attached to us
  5277. for (SceneObject *ptr = mMount.list; ptr; ptr = ptr->getMountLink())
  5278. {
  5279. ptr->disableCollision();
  5280. }
  5281. mConvex.updateWorkingList(mWorkingQueryBox,
  5282. isGhost() ? sClientCollisionContactMask : sServerCollisionContactMask);
  5283. //And now re-enable the collisions of the mounted things
  5284. for (SceneObject *ptr = mMount.list; ptr; ptr = ptr->getMountLink())
  5285. {
  5286. ptr->enableCollision();
  5287. }
  5288. enableCollision();
  5289. }
  5290. }
  5291. //----------------------------------------------------------------------------
  5292. void Player::writePacketData(GameConnection *connection, BitStream *stream)
  5293. {
  5294. Parent::writePacketData(connection, stream);
  5295. stream->writeInt(mState,NumStateBits);
  5296. if (stream->writeFlag(mState == RecoverState))
  5297. stream->writeInt(mRecoverTicks,PlayerData::RecoverDelayBits);
  5298. if (stream->writeFlag(mJumpDelay > 0))
  5299. stream->writeInt(mJumpDelay,PlayerData::JumpDelayBits);
  5300. Point3F pos;
  5301. getTransform().getColumn(3,&pos);
  5302. if (stream->writeFlag(!isMounted())) {
  5303. // Will get position from mount
  5304. stream->setCompressionPoint(pos);
  5305. stream->write(pos.x);
  5306. stream->write(pos.y);
  5307. stream->write(pos.z);
  5308. stream->write(mVelocity.x);
  5309. stream->write(mVelocity.y);
  5310. stream->write(mVelocity.z);
  5311. stream->writeInt(mJumpSurfaceLastContact > 15 ? 15 : mJumpSurfaceLastContact, 4);
  5312. if (stream->writeFlag(!mAllowSprinting || !mAllowCrouching || !mAllowProne || !mAllowJumping || !mAllowJetJumping || !mAllowSwimming))
  5313. {
  5314. stream->writeFlag(mAllowJumping);
  5315. stream->writeFlag(mAllowJetJumping);
  5316. stream->writeFlag(mAllowSprinting);
  5317. stream->writeFlag(mAllowCrouching);
  5318. stream->writeFlag(mAllowProne);
  5319. stream->writeFlag(mAllowSwimming);
  5320. }
  5321. }
  5322. stream->write(mHead.x);
  5323. if(stream->writeFlag(mDataBlock->cameraCanBank))
  5324. {
  5325. // Include mHead.y to allow for camera banking
  5326. stream->write(mHead.y);
  5327. }
  5328. stream->write(mHead.z);
  5329. stream->write(mRot.z);
  5330. if (mControlObject) {
  5331. S32 gIndex = connection->getGhostIndex(mControlObject);
  5332. if (stream->writeFlag(gIndex != -1)) {
  5333. stream->writeInt(gIndex,NetConnection::GhostIdBitSize);
  5334. mControlObject->writePacketData(connection, stream);
  5335. }
  5336. }
  5337. else
  5338. stream->writeFlag(false);
  5339. }
  5340. void Player::readPacketData(GameConnection *connection, BitStream *stream)
  5341. {
  5342. Parent::readPacketData(connection, stream);
  5343. mState = (ActionState)stream->readInt(NumStateBits);
  5344. if (stream->readFlag())
  5345. mRecoverTicks = stream->readInt(PlayerData::RecoverDelayBits);
  5346. if (stream->readFlag())
  5347. mJumpDelay = stream->readInt(PlayerData::JumpDelayBits);
  5348. else
  5349. mJumpDelay = 0;
  5350. Point3F pos,rot;
  5351. if (stream->readFlag()) {
  5352. // Only written if we are not mounted
  5353. stream->read(&pos.x);
  5354. stream->read(&pos.y);
  5355. stream->read(&pos.z);
  5356. stream->read(&mVelocity.x);
  5357. stream->read(&mVelocity.y);
  5358. stream->read(&mVelocity.z);
  5359. stream->setCompressionPoint(pos);
  5360. mDelta.pos = pos;
  5361. mJumpSurfaceLastContact = stream->readInt(4);
  5362. if (stream->readFlag())
  5363. {
  5364. mAllowJumping = stream->readFlag();
  5365. mAllowJetJumping = stream->readFlag();
  5366. mAllowSprinting = stream->readFlag();
  5367. mAllowCrouching = stream->readFlag();
  5368. mAllowProne = stream->readFlag();
  5369. mAllowSwimming = stream->readFlag();
  5370. }
  5371. else
  5372. {
  5373. mAllowJumping = true;
  5374. mAllowJetJumping = true;
  5375. mAllowSprinting = true;
  5376. mAllowCrouching = true;
  5377. mAllowProne = true;
  5378. mAllowSwimming = true;
  5379. }
  5380. }
  5381. else
  5382. pos = mDelta.pos;
  5383. stream->read(&mHead.x);
  5384. if(stream->readFlag())
  5385. {
  5386. // Include mHead.y to allow for camera banking
  5387. stream->read(&mHead.y);
  5388. }
  5389. stream->read(&mHead.z);
  5390. stream->read(&rot.z);
  5391. rot.x = rot.y = 0;
  5392. if (!ignore_updates)
  5393. setPosition(pos,rot);
  5394. mDelta.head = mHead;
  5395. mDelta.rot = rot;
  5396. if (stream->readFlag()) {
  5397. S32 gIndex = stream->readInt(NetConnection::GhostIdBitSize);
  5398. ShapeBase* obj = static_cast<ShapeBase*>(connection->resolveGhost(gIndex));
  5399. setControlObject(obj);
  5400. obj->readPacketData(connection, stream);
  5401. }
  5402. else
  5403. setControlObject(0);
  5404. }
  5405. U32 Player::packUpdate(NetConnection *con, U32 mask, BitStream *stream)
  5406. {
  5407. U32 retMask = Parent::packUpdate(con, mask, stream);
  5408. if (stream->writeFlag((mask & ImpactMask) && !(mask & InitialUpdateMask)))
  5409. stream->writeInt(mImpactSound, PlayerData::ImpactBits);
  5410. if (stream->writeFlag(mask & ActionMask &&
  5411. mActionAnimation.action != PlayerData::NullAnimation &&
  5412. mActionAnimation.action >= PlayerData::NumTableActionAnims)) {
  5413. stream->writeInt(mActionAnimation.action,PlayerData::ActionAnimBits);
  5414. stream->writeFlag(mActionAnimation.holdAtEnd);
  5415. stream->writeFlag(mActionAnimation.atEnd);
  5416. stream->writeFlag(mActionAnimation.firstPerson);
  5417. if (!mActionAnimation.atEnd) {
  5418. // If somewhere in middle on initial update, must send position-
  5419. F32 where = mShapeInstance->getPos(mActionAnimation.thread);
  5420. if (stream->writeFlag((mask & InitialUpdateMask) != 0 && where > 0))
  5421. stream->writeSignedFloat(where, 6);
  5422. }
  5423. }
  5424. if (stream->writeFlag(mask & ActionMask &&
  5425. mArmAnimation.action != PlayerData::NullAnimation &&
  5426. (!(mask & InitialUpdateMask) ||
  5427. mArmAnimation.action != mDataBlock->lookAction))) {
  5428. stream->writeInt(mArmAnimation.action,PlayerData::ActionAnimBits);
  5429. }
  5430. retMask = afx_packUpdate(con, mask, stream, retMask);
  5431. // The rest of the data is part of the control object packet update.
  5432. // If we're controlled by this client, we don't need to send it.
  5433. // we only need to send it if this is the initial update - in that case,
  5434. // the client won't know this is the control object yet.
  5435. if(stream->writeFlag(getControllingClient() == con && !(mask & InitialUpdateMask)))
  5436. return(retMask);
  5437. if (stream->writeFlag(mask & MoveMask))
  5438. {
  5439. stream->writeFlag(mFalling);
  5440. stream->writeFlag(mSwimming);
  5441. stream->writeFlag(mJetting);
  5442. stream->writeInt(mPose, NumPoseBits);
  5443. stream->writeInt(mState,NumStateBits);
  5444. if (stream->writeFlag(mState == RecoverState))
  5445. stream->writeInt(mRecoverTicks,PlayerData::RecoverDelayBits);
  5446. Point3F pos;
  5447. getTransform().getColumn(3,&pos);
  5448. stream->writeCompressedPoint(pos);
  5449. F32 len = mVelocity.len();
  5450. if(stream->writeFlag(len > 0.02f))
  5451. {
  5452. Point3F outVel = mVelocity;
  5453. outVel *= 1.0f/len;
  5454. stream->writeNormalVector(outVel, 10);
  5455. len *= 32.0f; // 5 bits of fraction
  5456. if(len > 8191)
  5457. len = 8191;
  5458. stream->writeInt((S32)len, 13);
  5459. // constrain the range of mRot.z
  5460. while (mRot.z < 0.0f)
  5461. mRot.z += M_2PI_F;
  5462. while (mRot.z > M_2PI_F)
  5463. mRot.z -= M_2PI_F;
  5464. }
  5465. stream->writeFloat(mRot.z / M_2PI_F, 7);
  5466. stream->writeSignedFloat(mHead.x / (mDataBlock->maxLookAngle - mDataBlock->minLookAngle), 6);
  5467. stream->writeSignedFloat(mHead.z / mDataBlock->maxFreelookAngle, 6);
  5468. mDelta.move.pack(stream);
  5469. stream->writeFlag(!(mask & NoWarpMask));
  5470. }
  5471. // Ghost need energy to predict reliably
  5472. if (mDataBlock->maxEnergy > 0.f)
  5473. stream->writeFloat(getEnergyLevel() / mDataBlock->maxEnergy, EnergyLevelBits);
  5474. else
  5475. stream->writeFloat(0.f, EnergyLevelBits);
  5476. return retMask;
  5477. }
  5478. void Player::unpackUpdate(NetConnection *con, BitStream *stream)
  5479. {
  5480. Parent::unpackUpdate(con,stream);
  5481. if (stream->readFlag())
  5482. mImpactSound = stream->readInt(PlayerData::ImpactBits);
  5483. // Server specified action animation
  5484. if (stream->readFlag()) {
  5485. U32 action = stream->readInt(PlayerData::ActionAnimBits);
  5486. bool hold = stream->readFlag();
  5487. bool atEnd = stream->readFlag();
  5488. bool fsp = stream->readFlag();
  5489. F32 animPos = -1.0f;
  5490. if (!atEnd && stream->readFlag())
  5491. animPos = stream->readSignedFloat(6);
  5492. if (isProperlyAdded()) {
  5493. setActionThread(action,true,hold,true,fsp);
  5494. bool inDeath = inDeathAnim();
  5495. if (atEnd)
  5496. {
  5497. mShapeInstance->clearTransition(mActionAnimation.thread);
  5498. mShapeInstance->setPos(mActionAnimation.thread,
  5499. mActionAnimation.forward? 1: 0);
  5500. if (inDeath)
  5501. mDeath.lastPos = 1.0f;
  5502. }
  5503. else if (animPos > 0) {
  5504. mShapeInstance->setPos(mActionAnimation.thread, animPos);
  5505. if (inDeath)
  5506. mDeath.lastPos = animPos;
  5507. }
  5508. // mMountPending suppresses tickDelay countdown so players will sit until
  5509. // their mount, or another animation, comes through (or 13 seconds elapses).
  5510. mMountPending = (S32) (inSittingAnim() ? sMountPendingTickWait : 0);
  5511. }
  5512. else {
  5513. mActionAnimation.action = action;
  5514. mActionAnimation.holdAtEnd = hold;
  5515. mActionAnimation.atEnd = atEnd;
  5516. mActionAnimation.firstPerson = fsp;
  5517. }
  5518. }
  5519. // Server specified arm animation
  5520. if (stream->readFlag()) {
  5521. U32 action = stream->readInt(PlayerData::ActionAnimBits);
  5522. if (isProperlyAdded())
  5523. setArmThread(action);
  5524. else
  5525. mArmAnimation.action = action;
  5526. }
  5527. afx_unpackUpdate(con, stream);
  5528. // Done if controlled by client ( and not initial update )
  5529. if(stream->readFlag())
  5530. return;
  5531. // MoveMask
  5532. if (stream->readFlag()) {
  5533. mPredictionCount = sMaxPredictionTicks;
  5534. mFalling = stream->readFlag();
  5535. mSwimming = stream->readFlag();
  5536. mJetting = stream->readFlag();
  5537. mPose = (Pose)(stream->readInt(NumPoseBits));
  5538. ActionState actionState = (ActionState)stream->readInt(NumStateBits);
  5539. if (stream->readFlag()) {
  5540. mRecoverTicks = stream->readInt(PlayerData::RecoverDelayBits);
  5541. setState(actionState, mRecoverTicks);
  5542. }
  5543. else
  5544. setState(actionState);
  5545. Point3F pos,rot;
  5546. stream->readCompressedPoint(&pos);
  5547. F32 speed = mVelocity.len();
  5548. if(stream->readFlag())
  5549. {
  5550. stream->readNormalVector(&mVelocity, 10);
  5551. mVelocity *= stream->readInt(13) / 32.0f;
  5552. }
  5553. else
  5554. {
  5555. mVelocity.set(0.0f, 0.0f, 0.0f);
  5556. }
  5557. rot.y = rot.x = 0.0f;
  5558. rot.z = stream->readFloat(7) * M_2PI_F;
  5559. mHead.x = stream->readSignedFloat(6) * (mDataBlock->maxLookAngle - mDataBlock->minLookAngle);
  5560. mHead.z = stream->readSignedFloat(6) * mDataBlock->maxFreelookAngle;
  5561. mDelta.move.unpack(stream);
  5562. mDelta.head = mHead;
  5563. mDelta.headVec.set(0.0f, 0.0f, 0.0f);
  5564. if (stream->readFlag() && isProperlyAdded())
  5565. {
  5566. // Determine number of ticks to warp based on the average
  5567. // of the client and server velocities.
  5568. mDelta.warpOffset = pos - mDelta.pos;
  5569. F32 as = (speed + mVelocity.len()) * 0.5f * TickSec;
  5570. F32 dt = (as > 0.00001f) ? mDelta.warpOffset.len() / as: sMaxWarpTicks;
  5571. mDelta.warpTicks = (S32)((dt > sMinWarpTicks) ? getMax(mFloor(dt + 0.5f), 1.0f) : 0.0f);
  5572. if (mDelta.warpTicks)
  5573. {
  5574. // Setup the warp to start on the next tick.
  5575. if (mDelta.warpTicks > sMaxWarpTicks)
  5576. mDelta.warpTicks = sMaxWarpTicks;
  5577. mDelta.warpOffset /= (F32)mDelta.warpTicks;
  5578. mDelta.rotOffset = rot - mDelta.rot;
  5579. // Ignore small rotation differences
  5580. if (mFabs(mDelta.rotOffset.z) < 0.001f)
  5581. mDelta.rotOffset.z = 0;
  5582. // Wrap rotation to +/-PI
  5583. if(mDelta.rotOffset.z < - M_PI_F)
  5584. mDelta.rotOffset.z += M_2PI_F;
  5585. else if(mDelta.rotOffset.z > M_PI_F)
  5586. mDelta.rotOffset.z -= M_2PI_F;
  5587. mDelta.rotOffset /= (F32)mDelta.warpTicks;
  5588. }
  5589. else
  5590. {
  5591. // Going to skip the warp, server and client are real close.
  5592. // Adjust the frame interpolation to move smoothly to the
  5593. // new position within the current tick.
  5594. Point3F cp = mDelta.pos + mDelta.posVec * mDelta.dt;
  5595. if (mDelta.dt == 0)
  5596. {
  5597. mDelta.posVec.set(0.0f, 0.0f, 0.0f);
  5598. mDelta.rotVec.set(0.0f, 0.0f, 0.0f);
  5599. }
  5600. else
  5601. {
  5602. F32 dti = 1.0f / mDelta.dt;
  5603. mDelta.posVec = (cp - pos) * dti;
  5604. mDelta.rotVec.z = mRot.z - rot.z;
  5605. if(mDelta.rotVec.z > M_PI_F)
  5606. mDelta.rotVec.z -= M_2PI_F;
  5607. else if(mDelta.rotVec.z < -M_PI_F)
  5608. mDelta.rotVec.z += M_2PI_F;
  5609. mDelta.rotVec.z *= dti;
  5610. }
  5611. mDelta.pos = pos;
  5612. mDelta.rot = rot;
  5613. if (!ignore_updates)
  5614. setPosition(pos,rot);
  5615. }
  5616. }
  5617. else
  5618. {
  5619. // Set the player to the server position
  5620. mDelta.pos = pos;
  5621. mDelta.rot = rot;
  5622. mDelta.posVec.set(0.0f, 0.0f, 0.0f);
  5623. mDelta.rotVec.set(0.0f, 0.0f, 0.0f);
  5624. mDelta.warpTicks = 0;
  5625. mDelta.dt = 0.0f;
  5626. if (!ignore_updates)
  5627. setPosition(pos,rot);
  5628. }
  5629. }
  5630. F32 energy = stream->readFloat(EnergyLevelBits) * mDataBlock->maxEnergy;
  5631. setEnergyLevel(energy);
  5632. }
  5633. //----------------------------------------------------------------------------
  5634. DefineEngineMethod( Player, getPose, const char*, (),,
  5635. "@brief Get the name of the player's current pose.\n\n"
  5636. "The pose is one of the following:\n\n<ul>"
  5637. "<li>Stand - Standard movement pose.</li>"
  5638. "<li>Sprint - Sprinting pose.</li>"
  5639. "<li>Crouch - Crouch pose.</li>"
  5640. "<li>Prone - Prone pose.</li>"
  5641. "<li>Swim - Swimming pose.</li></ul>\n"
  5642. "@return The current pose; one of: \"Stand\", \"Sprint\", \"Crouch\", \"Prone\", \"Swim\"\n" )
  5643. {
  5644. return object->getPoseName();
  5645. }
  5646. DefineEngineMethod( Player, allowAllPoses, void, (),,
  5647. "@brief Allow all poses a chance to occur.\n\n"
  5648. "This method resets any poses that have manually been blocked from occuring. "
  5649. "This includes the regular pose states such as sprinting, crouch, being prone "
  5650. "and swimming. It also includes being able to jump and jet jump. While this "
  5651. "is allowing these poses to occur it doesn't mean that they all can due to other "
  5652. "conditions. We're just not manually blocking them from being allowed.\n"
  5653. "@see allowJumping()\n"
  5654. "@see allowJetJumping()\n"
  5655. "@see allowSprinting()\n"
  5656. "@see allowCrouching()\n"
  5657. "@see allowProne()\n"
  5658. "@see allowSwimming()\n" )
  5659. {
  5660. object->allowAllPoses();
  5661. }
  5662. DefineEngineMethod( Player, allowJumping, void, (bool state),,
  5663. "@brief Set if the Player is allowed to jump.\n\n"
  5664. "The default is to allow jumping unless there are other environmental concerns "
  5665. "that prevent it. This method is mainly used to explicitly disallow jumping "
  5666. "at any time.\n"
  5667. "@param state Set to true to allow jumping, false to disable it.\n"
  5668. "@see allowAllPoses()\n" )
  5669. {
  5670. object->allowJumping(state);
  5671. }
  5672. DefineEngineMethod( Player, allowJetJumping, void, (bool state),,
  5673. "@brief Set if the Player is allowed to jet jump.\n\n"
  5674. "The default is to allow jet jumping unless there are other environmental concerns "
  5675. "that prevent it. This method is mainly used to explicitly disallow jet jumping "
  5676. "at any time.\n"
  5677. "@param state Set to true to allow jet jumping, false to disable it.\n"
  5678. "@see allowAllPoses()\n" )
  5679. {
  5680. object->allowJetJumping(state);
  5681. }
  5682. DefineEngineMethod( Player, allowSprinting, void, (bool state),,
  5683. "@brief Set if the Player is allowed to sprint.\n\n"
  5684. "The default is to allow sprinting unless there are other environmental concerns "
  5685. "that prevent it. This method is mainly used to explicitly disallow sprinting "
  5686. "at any time.\n"
  5687. "@param state Set to true to allow sprinting, false to disable it.\n"
  5688. "@see allowAllPoses()\n" )
  5689. {
  5690. object->allowSprinting(state);
  5691. }
  5692. DefineEngineMethod( Player, allowCrouching, void, (bool state),,
  5693. "@brief Set if the Player is allowed to crouch.\n\n"
  5694. "The default is to allow crouching unless there are other environmental concerns "
  5695. "that prevent it. This method is mainly used to explicitly disallow crouching "
  5696. "at any time.\n"
  5697. "@param state Set to true to allow crouching, false to disable it.\n"
  5698. "@see allowAllPoses()\n" )
  5699. {
  5700. object->allowCrouching(state);
  5701. }
  5702. DefineEngineMethod( Player, allowProne, void, (bool state),,
  5703. "@brief Set if the Player is allowed to go prone.\n\n"
  5704. "The default is to allow being prone unless there are other environmental concerns "
  5705. "that prevent it. This method is mainly used to explicitly disallow going prone "
  5706. "at any time.\n"
  5707. "@param state Set to true to allow being prone, false to disable it.\n"
  5708. "@see allowAllPoses()\n" )
  5709. {
  5710. object->allowProne(state);
  5711. }
  5712. DefineEngineMethod( Player, allowSwimming, void, (bool state),,
  5713. "@brief Set if the Player is allowed to swim.\n\n"
  5714. "The default is to allow swimming unless there are other environmental concerns "
  5715. "that prevent it. This method is mainly used to explicitly disallow swimming "
  5716. "at any time.\n"
  5717. "@param state Set to true to allow swimming, false to disable it.\n"
  5718. "@see allowAllPoses()\n" )
  5719. {
  5720. object->allowSwimming(state);
  5721. }
  5722. //----------------------------------------------------------------------------
  5723. DefineEngineMethod( Player, getState, const char*, (),,
  5724. "@brief Get the name of the player's current state.\n\n"
  5725. "The state is one of the following:\n\n<ul>"
  5726. "<li>Dead - The Player is dead.</li>"
  5727. "<li>Mounted - The Player is mounted to an object such as a vehicle.</li>"
  5728. "<li>Move - The Player is free to move. The usual state.</li>"
  5729. "<li>Recover - The Player is recovering from a fall. See PlayerData::recoverDelay.</li></ul>\n"
  5730. "@return The current state; one of: \"Dead\", \"Mounted\", \"Move\", \"Recover\"\n" )
  5731. {
  5732. return object->getStateName();
  5733. }
  5734. DefineEngineMethod( Player, getDamageLocation, const char*, ( Point3F pos ),,
  5735. "@brief Get the named damage location and modifier for a given world position.\n\n"
  5736. "the Player object can simulate different hit locations based on a pre-defined set "
  5737. "of PlayerData defined percentages. These hit percentages divide up the Player's "
  5738. "bounding box into different regions. The diagram below demonstrates how the various "
  5739. "PlayerData properties split up the bounding volume:\n\n"
  5740. "<img src=\"images/player_damageloc.png\">\n\n"
  5741. "While you may pass in any world position and getDamageLocation() will provide a best-fit "
  5742. "location, you should be aware that this can produce some interesting results. For example, "
  5743. "any position that is above PlayerData::boxHeadPercentage will be considered a 'head' hit, even "
  5744. "if the world position is high in the sky. Therefore it may be wise to keep the passed in point "
  5745. "to somewhere on the surface of, or within, the Player's bounding volume.\n\n"
  5746. "@note This method will not return an accurate location when the player is "
  5747. "prone or swimming.\n\n"
  5748. "@param pos A world position for which to retrieve a body region on this player.\n"
  5749. "@return a string containing two words (space separated strings), where the "
  5750. "first is a location and the second is a modifier.\n\n"
  5751. "Posible locations:<ul>"
  5752. "<li>head</li>"
  5753. "<li>torso</li>"
  5754. "<li>legs</li></ul>\n"
  5755. "Head modifiers:<ul>"
  5756. "<li>left_back</li>"
  5757. "<li>middle_back</li>"
  5758. "<li>right_back</li>"
  5759. "<li>left_middle</li>"
  5760. "<li>middle_middle</li>"
  5761. "<li>right_middle</li>"
  5762. "<li>left_front</li>"
  5763. "<li>middle_front</li>"
  5764. "<li>right_front</li></ul>\n"
  5765. "Legs/Torso modifiers:<ul>"
  5766. "<li>front_left</li>"
  5767. "<li>front_right</li>"
  5768. "<li>back_left</li>"
  5769. "<li>back_right</li></ul>\n"
  5770. "@see PlayerData::boxHeadPercentage\n"
  5771. "@see PlayerData::boxHeadFrontPercentage\n"
  5772. "@see PlayerData::boxHeadBackPercentage\n"
  5773. "@see PlayerData::boxHeadLeftPercentage\n"
  5774. "@see PlayerData::boxHeadRightPercentage\n"
  5775. "@see PlayerData::boxTorsoPercentage\n"
  5776. )
  5777. {
  5778. const char *buffer1;
  5779. const char *buffer2;
  5780. object->getDamageLocation(pos, buffer1, buffer2);
  5781. static const U32 bufSize = 128;
  5782. char *buff = Con::getReturnBuffer(bufSize);
  5783. dSprintf(buff, bufSize, "%s %s", buffer1, buffer2);
  5784. return buff;
  5785. }
  5786. DefineEngineMethod( Player, setArmThread, bool, ( const char* name ),,
  5787. "@brief Set the sequence that controls the player's arms (dynamically adjusted "
  5788. "to match look direction).\n\n"
  5789. "@param name Name of the sequence to play on the player's arms.\n"
  5790. "@return true if successful, false if failed.\n"
  5791. "@note By default the 'look' sequence is used, if available.\n")
  5792. {
  5793. return object->setArmThread( name );
  5794. }
  5795. DefineEngineMethod( Player, setActionThread, bool, ( const char* name, bool hold, bool fsp ), ( false, true ),
  5796. "@brief Set the main action sequence to play for this player.\n\n"
  5797. "@param name Name of the action sequence to set\n"
  5798. "@param hold Set to false to get a callback on the datablock when the sequence ends (PlayerData::animationDone()). "
  5799. "When set to true no callback is made.\n"
  5800. "@param fsp True if first person and none of the spine nodes in the shape should animate. False will allow the shape's "
  5801. "spine nodes to animate.\n"
  5802. "@return True if succesful, false if failed\n"
  5803. "@note The spine nodes for the Player's shape are named as follows:\n\n<ul>"
  5804. "<li>Bip01 Pelvis</li>"
  5805. "<li>Bip01 Spine</li>"
  5806. "<li>Bip01 Spine1</li>"
  5807. "<li>Bip01 Spine2</li>"
  5808. "<li>Bip01 Neck</li>"
  5809. "<li>Bip01 Head</li></ul>\n\n"
  5810. "You cannot use setActionThread() to have the Player play one of the motion "
  5811. "determined action animation sequences. These sequences are chosen based on how "
  5812. "the Player moves and the Player's current pose. The names of these sequences are:\n\n<ul>"
  5813. "<li>root</li>"
  5814. "<li>run</li>"
  5815. "<li>side</li>"
  5816. "<li>side_right</li>"
  5817. "<li>crouch_root</li>"
  5818. "<li>crouch_forward</li>"
  5819. "<li>crouch_backward</li>"
  5820. "<li>crouch_side</li>"
  5821. "<li>crouch_right</li>"
  5822. "<li>prone_root</li>"
  5823. "<li>prone_forward</li>"
  5824. "<li>prone_backward</li>"
  5825. "<li>swim_root</li>"
  5826. "<li>swim_forward</li>"
  5827. "<li>swim_backward</li>"
  5828. "<li>swim_left</li>"
  5829. "<li>swim_right</li>"
  5830. "<li>fall</li>"
  5831. "<li>jump</li>"
  5832. "<li>standjump</li>"
  5833. "<li>land</li>"
  5834. "<li>jet</li></ul>\n\n"
  5835. "If the player moves in any direction then the animation sequence set using this "
  5836. "method will be cancelled and the chosen mation-based sequence will take over. This makes "
  5837. "great for times when the Player cannot move, such as when mounted, or when it doesn't matter "
  5838. "if the action sequence changes, such as waving and saluting.\n"
  5839. "@tsexample\n"
  5840. "// Place the player in a sitting position after being mounted\n"
  5841. "%player.setActionThread( \"sitting\", true, true );\n"
  5842. "@endtsexample\n")
  5843. {
  5844. return object->setActionThread( name, hold, true, fsp);
  5845. }
  5846. DefineEngineMethod( Player, setControlObject, bool, ( ShapeBase* obj ),,
  5847. "@brief Set the object to be controlled by this player\n\n"
  5848. "It is possible to have the moves sent to the Player object from the "
  5849. "GameConnection to be passed along to another object. This happens, for example "
  5850. "when a player is mounted to a vehicle. The move commands pass through the Player "
  5851. "and on to the vehicle (while the player remains stationary within the vehicle). "
  5852. "With setControlObject() you can have the Player pass along its moves to any object. "
  5853. "One possible use is for a player to move a remote controlled vehicle. In this case "
  5854. "the player does not mount the vehicle directly, but still wants to be able to control it.\n"
  5855. "@param obj Object to control with this player\n"
  5856. "@return True if the object is valid, false if not\n"
  5857. "@see getControlObject()\n"
  5858. "@see clearControlObject()\n"
  5859. "@see GameConnection::setControlObject()")
  5860. {
  5861. if (obj) {
  5862. object->setControlObject(obj);
  5863. return true;
  5864. }
  5865. else
  5866. object->setControlObject(0);
  5867. return false;
  5868. }
  5869. DefineEngineMethod( Player, getControlObject, S32, (),,
  5870. "@brief Get the current object we are controlling.\n\n"
  5871. "@return ID of the ShapeBase object we control, or 0 if not controlling an "
  5872. "object.\n"
  5873. "@see setControlObject()\n"
  5874. "@see clearControlObject()")
  5875. {
  5876. ShapeBase* controlObject = object->getControlObject();
  5877. return controlObject ? controlObject->getId(): 0;
  5878. }
  5879. DefineEngineMethod( Player, clearControlObject, void, (),,
  5880. "@brief Clears the player's current control object.\n\n"
  5881. "Returns control to the player. This internally calls "
  5882. "Player::setControlObject(0).\n"
  5883. "@tsexample\n"
  5884. "%player.clearControlObject();\n"
  5885. "echo(%player.getControlObject()); //<-- Returns 0, player assumes control\n"
  5886. "%player.setControlObject(%vehicle);\n"
  5887. "echo(%player.getControlObject()); //<-- Returns %vehicle, player controls the vehicle now.\n"
  5888. "@endtsexample\n"
  5889. "@note If the player does not have a control object, the player will receive all moves "
  5890. "from its GameConnection. If you're looking to remove control from the player itself "
  5891. "(i.e. stop sending moves to the player) use GameConnection::setControlObject() to transfer "
  5892. "control to another object, such as a camera.\n"
  5893. "@see setControlObject()\n"
  5894. "@see getControlObject()\n"
  5895. "@see GameConnection::setControlObject()\n")
  5896. {
  5897. object->setControlObject(0);
  5898. }
  5899. DefineEngineMethod( Player, checkDismountPoint, bool, ( Point3F oldPos, Point3F pos ),,
  5900. "@brief Check if it is safe to dismount at this position.\n\n"
  5901. "Internally this method casts a ray from oldPos to pos to determine if it hits the "
  5902. "terrain, an interior object, a water object, another player, a static shape, "
  5903. "a vehicle (exluding the one currently mounted), or physical zone. If this ray "
  5904. "is in the clear, then the player's bounding box is also checked for a collision at "
  5905. "the pos position. If this displaced bounding box is also in the clear, then "
  5906. "checkDismountPoint() returns true.\n"
  5907. "@param oldPos The player's current position\n"
  5908. "@param pos The dismount position to check\n"
  5909. "@return True if the dismount position is clear, false if not\n"
  5910. "@note The player must be already mounted for this method to not assert.\n")
  5911. {
  5912. MatrixF oldPosMat(true);
  5913. oldPosMat.setColumn(3, oldPos);
  5914. MatrixF posMat(true);
  5915. posMat.setColumn(3, pos);
  5916. return object->checkDismountPosition(oldPosMat, posMat);
  5917. }
  5918. DefineEngineMethod( Player, getNumDeathAnimations, S32, ( ),,
  5919. "@brief Get the number of death animations available to this player.\n\n"
  5920. "Death animations are assumed to be named death1-N using consecutive indices." )
  5921. {
  5922. S32 count = 0;
  5923. const PlayerData * db = dynamic_cast<PlayerData*>( object->getDataBlock() );
  5924. if ( db )
  5925. {
  5926. for ( S32 i = 0; i < db->actionCount; i++ )
  5927. if ( db->actionList[i].death )
  5928. count++;
  5929. }
  5930. return count;
  5931. }
  5932. //----------------------------------------------------------------------------
  5933. void Player::consoleInit()
  5934. {
  5935. Con::addVariable("$player::renderMyPlayer",TypeBool, &sRenderMyPlayer,
  5936. "@brief Determines if the player is rendered or not.\n\n"
  5937. "Used on the client side to disable the rendering of all Player objects. This is "
  5938. "mainly for the tools or debugging.\n"
  5939. "@ingroup GameObjects\n");
  5940. Con::addVariable("$player::renderMyItems",TypeBool, &sRenderMyItems,
  5941. "@brief Determines if mounted shapes are rendered or not.\n\n"
  5942. "Used on the client side to disable the rendering of all Player mounted objects. This is "
  5943. "mainly used for the tools or debugging.\n"
  5944. "@ingroup GameObjects\n");
  5945. Con::addVariable("$player::renderCollision", TypeBool, &sRenderPlayerCollision,
  5946. "@brief Determines if the player's collision mesh should be rendered.\n\n"
  5947. "This is mainly used for the tools and debugging.\n"
  5948. "@ingroup GameObjects\n");
  5949. Con::addVariable("$player::minWarpTicks",TypeF32,&sMinWarpTicks,
  5950. "@brief Fraction of tick at which instant warp occures on the client.\n\n"
  5951. "@ingroup GameObjects\n");
  5952. Con::addVariable("$player::maxWarpTicks",TypeS32,&sMaxWarpTicks,
  5953. "@brief When a warp needs to occur due to the client being too far off from the server, this is the "
  5954. "maximum number of ticks we'll allow the client to warp to catch up.\n\n"
  5955. "@ingroup GameObjects\n");
  5956. Con::addVariable("$player::maxPredictionTicks",TypeS32,&sMaxPredictionTicks,
  5957. "@brief Maximum number of ticks to predict on the client from the last known move obtained from the server.\n\n"
  5958. "@ingroup GameObjects\n");
  5959. Con::addVariable("$player::maxImpulseVelocity", TypeF32, &sMaxImpulseVelocity,
  5960. "@brief The maximum velocity allowed due to a single impulse.\n\n"
  5961. "@ingroup GameObjects\n");
  5962. // Move triggers
  5963. Con::addVariable("$player::jumpTrigger", TypeS32, &sJumpTrigger,
  5964. "@brief The move trigger index used for player jumping.\n\n"
  5965. "@ingroup GameObjects\n");
  5966. Con::addVariable("$player::crouchTrigger", TypeS32, &sCrouchTrigger,
  5967. "@brief The move trigger index used for player crouching.\n\n"
  5968. "@ingroup GameObjects\n");
  5969. Con::addVariable("$player::proneTrigger", TypeS32, &sProneTrigger,
  5970. "@brief The move trigger index used for player prone pose.\n\n"
  5971. "@ingroup GameObjects\n");
  5972. Con::addVariable("$player::sprintTrigger", TypeS32, &sSprintTrigger,
  5973. "@brief The move trigger index used for player sprinting.\n\n"
  5974. "@ingroup GameObjects\n");
  5975. Con::addVariable("$player::imageTrigger0", TypeS32, &sImageTrigger0,
  5976. "@brief The move trigger index used to trigger mounted image 0.\n\n"
  5977. "@ingroup GameObjects\n");
  5978. Con::addVariable("$player::imageTrigger1", TypeS32, &sImageTrigger1,
  5979. "@brief The move trigger index used to trigger mounted image 1 or alternate fire "
  5980. "on mounted image 0.\n\n"
  5981. "@ingroup GameObjects\n");
  5982. Con::addVariable("$player::jumpJetTrigger", TypeS32, &sJumpJetTrigger,
  5983. "@brief The move trigger index used for player jump jetting.\n\n"
  5984. "@ingroup GameObjects\n");
  5985. Con::addVariable("$player::vehicleDismountTrigger", TypeS32, &sVehicleDismountTrigger,
  5986. "@brief The move trigger index used to dismount player.\n\n"
  5987. "@ingroup GameObjects\n");
  5988. // ExtendedMove support
  5989. Con::addVariable("$player::extendedMoveHeadPosRotIndex", TypeS32, &smExtendedMoveHeadPosRotIndex,
  5990. "@brief The ExtendedMove position/rotation index used for head movements.\n\n"
  5991. "@ingroup GameObjects\n");
  5992. afx_consoleInit();
  5993. }
  5994. //--------------------------------------------------------------------------
  5995. void Player::calcClassRenderData()
  5996. {
  5997. Parent::calcClassRenderData();
  5998. // If nothing is mounted do not perform the calculations below. Otherwise,
  5999. // we'll end up with a bad ray cast as both nmat and smat will be the
  6000. // Player's transform.
  6001. MountedImage& image = mMountedImageList[0];
  6002. if (!image.dataBlock)
  6003. {
  6004. mWeaponBackFraction = 0.0f;
  6005. return;
  6006. }
  6007. disableCollision();
  6008. MatrixF nmat;
  6009. MatrixF smat;
  6010. Parent::getRetractionTransform(0,&nmat);
  6011. Parent::getImageTransform(0, &smat);
  6012. // See if we are pushed into a wall...
  6013. Point3F start, end;
  6014. smat.getColumn(3, &start);
  6015. nmat.getColumn(3, &end);
  6016. RayInfo rinfo;
  6017. if (getContainer()->castRay(start, end, sCollisionMoveMask & ~(WaterObjectType|PhysicalZoneObjectType|MarkerObjectType), &rinfo)) {
  6018. if (rinfo.t < 1.0f)
  6019. mWeaponBackFraction = 1.0f - rinfo.t;
  6020. else
  6021. mWeaponBackFraction = 0.0f;
  6022. } else {
  6023. mWeaponBackFraction = 0.0f;
  6024. }
  6025. enableCollision();
  6026. }
  6027. //-----------------------------------------------------------------------------
  6028. void Player::playFootstepSound( bool triggeredLeft, Material* contactMaterial, SceneObject* contactObject )
  6029. {
  6030. if (footfallSoundOverride > 0)
  6031. return;
  6032. MatrixF footMat = getTransform();
  6033. if( mWaterCoverage > 0.0 )
  6034. {
  6035. // Treading water.
  6036. if ( mWaterCoverage < mDataBlock->footSplashHeight )
  6037. SFX->playOnce( mDataBlock->sound[ PlayerData::FootShallowSplash ], &footMat );
  6038. else
  6039. {
  6040. if ( mWaterCoverage < 1.0 )
  6041. SFX->playOnce( mDataBlock->sound[ PlayerData::FootWading ], &footMat );
  6042. else
  6043. {
  6044. if ( triggeredLeft )
  6045. {
  6046. SFX->playOnce( mDataBlock->sound[ PlayerData::FootUnderWater ], &footMat );
  6047. SFX->playOnce( mDataBlock->sound[ PlayerData::FootBubbles ], &footMat );
  6048. }
  6049. }
  6050. }
  6051. }
  6052. else if( contactMaterial && contactMaterial->mFootstepSoundCustom )
  6053. {
  6054. // Footstep sound defined on material.
  6055. SFX->playOnce( contactMaterial->mFootstepSoundCustom, &footMat );
  6056. }
  6057. else
  6058. {
  6059. // Play default sound.
  6060. S32 sound = -1;
  6061. if (contactMaterial && (contactMaterial->mFootstepSoundId>-1 && contactMaterial->mFootstepSoundId<PlayerData::MaxSoundOffsets))
  6062. sound = contactMaterial->mFootstepSoundId;
  6063. else if( contactObject && contactObject->getTypeMask() & VehicleObjectType )
  6064. sound = 2;
  6065. if (sound>=0)
  6066. SFX->playOnce(mDataBlock->sound[sound], &footMat);
  6067. }
  6068. }
  6069. void Player:: playImpactSound()
  6070. {
  6071. if( mWaterCoverage == 0.0f )
  6072. {
  6073. Point3F pos;
  6074. RayInfo rInfo;
  6075. MatrixF mat = getTransform();
  6076. mat.mulP(Point3F(mDataBlock->decalOffset,0.0f,0.0f), &pos);
  6077. if( gClientContainer.castRay( Point3F( pos.x, pos.y, pos.z + 0.01f ),
  6078. Point3F( pos.x, pos.y, pos.z - 2.0f ),
  6079. STATIC_COLLISION_TYPEMASK | VehicleObjectType,
  6080. &rInfo ) )
  6081. {
  6082. Material* material = ( rInfo.material ? dynamic_cast< Material* >( rInfo.material->getMaterial() ) : 0 );
  6083. if( material && material->mImpactSoundCustom )
  6084. SFX->playOnce( material->mImpactSoundCustom, &getTransform() );
  6085. else
  6086. {
  6087. S32 sound = -1;
  6088. if (material && (material->mImpactSoundId>-1 && material->mImpactSoundId<PlayerData::MaxSoundOffsets))
  6089. sound = material->mImpactSoundId;
  6090. else if( rInfo.object->getTypeMask() & VehicleObjectType )
  6091. sound = 2; // Play metal;
  6092. if (sound >= 0)
  6093. SFX->playOnce(mDataBlock->sound[PlayerData::ImpactStart + sound], &getTransform());
  6094. }
  6095. }
  6096. }
  6097. mImpactSound = 0;
  6098. }
  6099. //--------------------------------------------------------------------------
  6100. // Update splash
  6101. //--------------------------------------------------------------------------
  6102. void Player::updateSplash()
  6103. {
  6104. F32 speed = getVelocity().len();
  6105. if( speed < mDataBlock->splashVelocity || isMounted() ) return;
  6106. Point3F curPos = getPosition();
  6107. if ( curPos.equal( mLastPos ) )
  6108. return;
  6109. if (pointInWater( curPos )) {
  6110. if (!pointInWater( mLastPos )) {
  6111. Point3F norm = getVelocity();
  6112. norm.normalize();
  6113. // make sure player is moving vertically at good pace before playing splash
  6114. F32 splashAng = mDataBlock->splashAngle / 360.0;
  6115. if( mDot( norm, Point3F(0.0, 0.0, -1.0) ) < splashAng )
  6116. return;
  6117. RayInfo rInfo;
  6118. if (gClientContainer.castRay(mLastPos, curPos,
  6119. WaterObjectType, &rInfo)) {
  6120. createSplash( rInfo.point, speed );
  6121. mBubbleEmitterTime = 0.0;
  6122. }
  6123. }
  6124. }
  6125. }
  6126. //--------------------------------------------------------------------------
  6127. void Player::updateFroth( F32 dt )
  6128. {
  6129. // update bubbles
  6130. Point3F moveDir = getVelocity();
  6131. mBubbleEmitterTime += dt;
  6132. if (mBubbleEmitterTime < mDataBlock->bubbleEmitTime) {
  6133. if (mSplashEmitter[PlayerData::BUBBLE_EMITTER]) {
  6134. Point3F emissionPoint = getRenderPosition();
  6135. U32 emitNum = PlayerData::BUBBLE_EMITTER;
  6136. mSplashEmitter[emitNum]->emitParticles(mLastPos, emissionPoint,
  6137. Point3F( 0.0, 0.0, 1.0 ), moveDir, (U32)(dt * 1000.0));
  6138. }
  6139. }
  6140. Point3F contactPoint;
  6141. if (!collidingWithWater(contactPoint)) {
  6142. mLastWaterPos = mLastPos;
  6143. return;
  6144. }
  6145. F32 speed = moveDir.len();
  6146. if ( speed < mDataBlock->splashVelEpsilon )
  6147. speed = 0.0;
  6148. U32 emitRate = (U32) (speed * mDataBlock->splashFreqMod * dt);
  6149. // If we're in the water, swimming, but not
  6150. // moving, then lets emit some particles because
  6151. // we're treading water.
  6152. if ( mSwimming && speed == 0.0 )
  6153. {
  6154. emitRate = (U32) (2.0f * mDataBlock->splashFreqMod * dt);
  6155. }
  6156. U32 i;
  6157. for ( i=0; i<PlayerData::BUBBLE_EMITTER; i++ ) {
  6158. if (mSplashEmitter[i] )
  6159. mSplashEmitter[i]->emitParticles( mLastWaterPos,
  6160. contactPoint, Point3F( 0.0, 0.0, 1.0 ),
  6161. moveDir, emitRate );
  6162. }
  6163. mLastWaterPos = contactPoint;
  6164. }
  6165. void Player::updateWaterSounds(F32 dt)
  6166. {
  6167. if ( mWaterCoverage < 1.0f || mDamageState != Enabled )
  6168. {
  6169. // Stop everything
  6170. if ( mMoveBubbleSound )
  6171. mMoveBubbleSound->stop();
  6172. if ( mWaterBreathSound )
  6173. mWaterBreathSound->stop();
  6174. return;
  6175. }
  6176. if ( mMoveBubbleSound )
  6177. {
  6178. // We're under water and still alive, so let's play something
  6179. if ( mVelocity.len() > 1.0f )
  6180. {
  6181. if ( !mMoveBubbleSound->isPlaying() )
  6182. mMoveBubbleSound->play();
  6183. mMoveBubbleSound->setTransform( getTransform() );
  6184. }
  6185. else
  6186. mMoveBubbleSound->stop();
  6187. }
  6188. if ( mWaterBreathSound )
  6189. {
  6190. if ( !mWaterBreathSound->isPlaying() )
  6191. mWaterBreathSound->play();
  6192. mWaterBreathSound->setTransform( getTransform() );
  6193. }
  6194. }
  6195. //--------------------------------------------------------------------------
  6196. // Returns true if player is intersecting a water surface
  6197. //--------------------------------------------------------------------------
  6198. bool Player::collidingWithWater( Point3F &waterHeight )
  6199. {
  6200. if ( !mCurrentWaterObject )
  6201. return false;
  6202. Point3F curPos = getPosition();
  6203. if ( mWorldBox.maxExtents.z < mLiquidHeight )
  6204. return false;
  6205. curPos.z = mLiquidHeight;
  6206. waterHeight = getPosition();
  6207. waterHeight.z = mLiquidHeight;
  6208. return true;
  6209. }
  6210. //--------------------------------------------------------------------------
  6211. void Player::createSplash( Point3F &pos, F32 speed )
  6212. {
  6213. if ( speed >= mDataBlock->hardSplashSoundVel )
  6214. SFX->playOnce( mDataBlock->sound[PlayerData::ImpactWaterHard], &getTransform() );
  6215. else if ( speed >= mDataBlock->medSplashSoundVel )
  6216. SFX->playOnce( mDataBlock->sound[PlayerData::ImpactWaterMedium], &getTransform() );
  6217. else
  6218. SFX->playOnce( mDataBlock->sound[PlayerData::ImpactWaterEasy], &getTransform() );
  6219. if( mDataBlock->splash )
  6220. {
  6221. MatrixF trans = getTransform();
  6222. trans.setPosition( pos );
  6223. Splash *splash = new Splash;
  6224. splash->onNewDataBlock( mDataBlock->splash, false );
  6225. splash->setTransform( trans );
  6226. splash->setInitialState( trans.getPosition(), Point3F( 0.0, 0.0, 1.0 ) );
  6227. if (!splash->registerObject())
  6228. delete splash;
  6229. }
  6230. }
  6231. bool Player::isControlObject()
  6232. {
  6233. GameConnection* connection = GameConnection::getConnectionToServer();
  6234. if( !connection ) return false;
  6235. ShapeBase *obj = dynamic_cast<ShapeBase*>(connection->getControlObject());
  6236. return ( obj == this );
  6237. }
  6238. void Player::prepRenderImage( SceneRenderState* state )
  6239. {
  6240. bool renderPlayer = true;
  6241. bool renderItems = true;
  6242. /*
  6243. if ( mPhysicsRep && Con::getBoolVariable("$PhysicsPlayer::DebugRender",false) )
  6244. {
  6245. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  6246. ri->renderDelegate.bind( mPhysicsRep, &PhysicsPlayer::renderDebug );
  6247. ri->objectIndex = -1;
  6248. ri->type = RenderPassManager::RIT_Editor;
  6249. state->getRenderPass()->addInst( ri );
  6250. }
  6251. */
  6252. // Debug rendering for all convexes in the Players working list.
  6253. if ( sRenderPlayerCollision )
  6254. {
  6255. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  6256. ri->renderDelegate.bind( this, &Player::renderConvex );
  6257. ri->objectIndex = -1;
  6258. ri->type = RenderPassManager::RIT_Editor;
  6259. state->getRenderPass()->addInst( ri );
  6260. }
  6261. GameConnection* connection = GameConnection::getConnectionToServer();
  6262. if( connection && connection->getControlObject() == this && connection->isFirstPerson() )
  6263. {
  6264. // If we're first person and we are not rendering the player
  6265. // then disable all shadow rendering... a floating gun shadow sucks.
  6266. if ( state->isShadowPass() && !mDataBlock->renderFirstPerson && !mDataBlock->firstPersonShadows )
  6267. return;
  6268. renderPlayer = mDataBlock->renderFirstPerson || !state->isDiffusePass();
  6269. if( !sRenderMyPlayer )
  6270. renderPlayer = false;
  6271. if( !sRenderMyItems )
  6272. renderItems = false;
  6273. }
  6274. // Call the protected base class to do the work
  6275. // now that we know if we're rendering the player
  6276. // and mounted shapes.
  6277. return ShapeBase::_prepRenderImage( state,
  6278. renderPlayer,
  6279. renderItems );
  6280. }
  6281. void Player::renderConvex( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat )
  6282. {
  6283. GFX->enterDebugEvent( ColorI(255,0,255), "Player_renderConvex" );
  6284. mConvex.renderWorkingList();
  6285. GFX->leaveDebugEvent();
  6286. }
  6287. // static
  6288. bool Player::sCorpsesHiddenFromRayCast = true; // this default matches stock Torque behavior.
  6289. // static
  6290. void Player::afx_consoleInit()
  6291. {
  6292. Con::addVariable("pref::Player::corpsesHiddenFromRayCast", TypeBool, &sCorpsesHiddenFromRayCast);
  6293. }
  6294. void Player::afx_init()
  6295. {
  6296. overrideLookAnimation = false;
  6297. armLookOverridePos = 0.5f;
  6298. headVLookOverridePos = 0.5f;
  6299. headHLookOverridePos = 0.5f;
  6300. ignore_updates = false;
  6301. fx_c_triggers = 0;
  6302. mark_fx_c_triggers = 0;
  6303. fx_s_triggers = 0;
  6304. move_trigger_states = 0;
  6305. z_velocity = 0.0f;
  6306. mark_idle = false;
  6307. idle_timer = 0.0f;
  6308. mark_s_landing = false;
  6309. speed_bias = 1.0f;
  6310. speed_bias_goal = 1.0f;
  6311. override_movement = 0;
  6312. movement_data.zero();
  6313. movement_op = 1;
  6314. last_movement_tag = 0;
  6315. footfallDecalOverride = 0;
  6316. footfallSoundOverride = 0;
  6317. footfallDustOverride = 0;
  6318. noFootfallFX = false;
  6319. }
  6320. U32 Player::afx_packUpdate(NetConnection* con, U32 mask, BitStream* stream, U32 retMask)
  6321. {
  6322. #if 0
  6323. if (stream->writeFlag(mask & LookOverrideMask))
  6324. #else
  6325. if (stream->writeFlag(mask & ActionMask))
  6326. #endif
  6327. stream->writeFlag(overrideLookAnimation);
  6328. if (stream->writeFlag(mask & TriggerMask))
  6329. stream->write(fx_s_triggers);
  6330. return retMask;
  6331. }
  6332. void Player::afx_unpackUpdate(NetConnection* con, BitStream* stream)
  6333. {
  6334. if (stream->readFlag()) // LookOverrideMask
  6335. overrideLookAnimation = stream->readFlag();
  6336. if (stream->readFlag()) // TriggerMask
  6337. {
  6338. U32 mask;
  6339. stream->read(&mask);
  6340. mark_fx_c_triggers = mask;
  6341. }
  6342. }
  6343. // Code for overriding player's animation with sequences selected by the
  6344. // anim-clip component effect.
  6345. void Player::restoreAnimation(U32 tag)
  6346. {
  6347. // check if this is a blended clip
  6348. if ((tag & BLENDED_CLIP) != 0)
  6349. {
  6350. restoreBlendAnimation(tag);
  6351. return;
  6352. }
  6353. if (tag != 0 && tag == last_anim_tag)
  6354. {
  6355. bool is_death_anim = ((anim_clip_flags & IS_DEATH_ANIM) != 0);
  6356. anim_clip_flags &= ~(ANIM_OVERRIDDEN | IS_DEATH_ANIM);
  6357. if (isClientObject())
  6358. {
  6359. if (mDamageState != Enabled)
  6360. {
  6361. if (!is_death_anim)
  6362. {
  6363. // this is a bit hardwired and desperate,
  6364. // but if he's dead he needs to look like it.
  6365. setActionThread("death10", false, false, false);
  6366. }
  6367. }
  6368. else if (mState != MoveState)
  6369. {
  6370. // not sure what happens here
  6371. }
  6372. else
  6373. {
  6374. pickActionAnimation();
  6375. }
  6376. }
  6377. last_anim_tag = 0;
  6378. last_anim_id = -1;
  6379. }
  6380. }
  6381. U32 Player::getAnimationID(const char* name)
  6382. {
  6383. for (U32 i = 0; i < mDataBlock->actionCount; i++)
  6384. {
  6385. PlayerData::ActionAnimation &anim = mDataBlock->actionList[i];
  6386. if (dStricmp(anim.name, name) == 0)
  6387. return i;
  6388. }
  6389. Con::errorf("Player::getAnimationID() -- Player does not contain a sequence that matches the name, %s.", name);
  6390. return BAD_ANIM_ID;
  6391. }
  6392. U32 Player::playAnimationByID(U32 anim_id, F32 pos, F32 rate, F32 trans, bool hold, bool wait, bool is_death_anim)
  6393. {
  6394. if (anim_id == BAD_ANIM_ID)
  6395. return 0;
  6396. S32 seq_id = mDataBlock->actionList[anim_id].sequence;
  6397. if (seq_id == -1)
  6398. {
  6399. Con::errorf("Player::playAnimation() problem. BAD_SEQ_ID");
  6400. return 0;
  6401. }
  6402. if (mShapeInstance->getShape()->sequences[seq_id].isBlend())
  6403. return playBlendAnimation(seq_id, pos, rate);
  6404. if (isClientObject())
  6405. {
  6406. PlayerData::ActionAnimation &anim = mDataBlock->actionList[anim_id];
  6407. if (anim.sequence != -1)
  6408. {
  6409. mActionAnimation.action = anim_id;
  6410. mActionAnimation.forward = (rate >= 0);
  6411. mActionAnimation.firstPerson = false;
  6412. mActionAnimation.holdAtEnd = hold;
  6413. mActionAnimation.waitForEnd = hold? true: wait;
  6414. mActionAnimation.animateOnServer = false;
  6415. mActionAnimation.atEnd = false;
  6416. mActionAnimation.delayTicks = (S32)sNewAnimationTickTime;
  6417. F32 transTime = (trans < 0) ? sAnimationTransitionTime : trans;
  6418. mShapeInstance->setTimeScale(mActionAnimation.thread, rate);
  6419. mShapeInstance->transitionToSequence(mActionAnimation.thread,anim.sequence,
  6420. pos, transTime, true);
  6421. }
  6422. }
  6423. if (is_death_anim)
  6424. anim_clip_flags |= IS_DEATH_ANIM;
  6425. else
  6426. anim_clip_flags &= ~IS_DEATH_ANIM;
  6427. anim_clip_flags |= ANIM_OVERRIDDEN;
  6428. last_anim_tag = unique_anim_tag_counter++;
  6429. last_anim_id = anim_id;
  6430. return last_anim_tag;
  6431. }
  6432. F32 Player::getAnimationDurationByID(U32 anim_id)
  6433. {
  6434. if (anim_id == BAD_ANIM_ID)
  6435. return 0.0f;
  6436. S32 seq_id = mDataBlock->actionList[anim_id].sequence;
  6437. if (seq_id >= 0 && seq_id < mDataBlock->mShape->sequences.size())
  6438. return mDataBlock->mShape->sequences[seq_id].duration;
  6439. return 0.0f;
  6440. }
  6441. bool Player::isBlendAnimation(const char* name)
  6442. {
  6443. U32 anim_id = getAnimationID(name);
  6444. if (anim_id == BAD_ANIM_ID)
  6445. return false;
  6446. S32 seq_id = mDataBlock->actionList[anim_id].sequence;
  6447. if (seq_id >= 0 && seq_id < mDataBlock->mShape->sequences.size())
  6448. return mDataBlock->mShape->sequences[seq_id].isBlend();
  6449. return false;
  6450. }
  6451. const char* Player::getLastClipName(U32 clip_tag)
  6452. {
  6453. if (clip_tag != last_anim_tag || last_anim_id >= PlayerData::NumActionAnims)
  6454. return "";
  6455. return mDataBlock->actionList[last_anim_id].name;
  6456. }
  6457. void Player::unlockAnimation(U32 tag, bool force)
  6458. {
  6459. if ((tag != 0 && tag == last_anim_lock_tag) || force)
  6460. anim_clip_flags &= ~BLOCK_USER_CONTROL;
  6461. }
  6462. U32 Player::lockAnimation()
  6463. {
  6464. anim_clip_flags |= BLOCK_USER_CONTROL;
  6465. last_anim_lock_tag = unique_anim_tag_counter++;
  6466. return last_anim_lock_tag;
  6467. }
  6468. DefineEngineMethod(Player, isAnimationLocked, bool, (),, "")
  6469. {
  6470. return object->isAnimationLocked();
  6471. }
  6472. void Player::setLookAnimationOverride(bool flag)
  6473. {
  6474. overrideLookAnimation = flag;
  6475. #if 0
  6476. setMaskBits(LookOverrideMask);
  6477. #else
  6478. setMaskBits(ActionMask);
  6479. #endif
  6480. }
  6481. DefineEngineMethod(Player, setLookAnimationOverride, void, (bool flag),, "")
  6482. {
  6483. object->setLookAnimationOverride(flag);
  6484. }
  6485. DefineEngineMethod(Player, copyHeadRotation, void, (Player* other_player),, "")
  6486. {
  6487. if (other_player)
  6488. object->copyHeadRotation(other_player);
  6489. }
  6490. void Player::process_client_triggers(bool triggeredLeft, bool triggeredRight)
  6491. {
  6492. bool mark_landing = false;
  6493. Point3F my_vel = getVelocity();
  6494. if (my_vel.z > 5.0f)
  6495. z_velocity = 1;
  6496. else if (my_vel.z < -5.0f)
  6497. z_velocity = -1;
  6498. else
  6499. {
  6500. if (z_velocity < 0)
  6501. mark_landing = true;
  6502. z_velocity = 0.0f;
  6503. }
  6504. fx_c_triggers = mark_fx_c_triggers;
  6505. if (triggeredLeft)
  6506. fx_c_triggers |= PLAYER_LF_FOOT_C_TRIGGER;
  6507. if (triggeredRight)
  6508. fx_c_triggers |= PLAYER_RT_FOOT_C_TRIGGER;
  6509. if (mark_landing)
  6510. fx_c_triggers |= PLAYER_LANDING_C_TRIGGER;
  6511. if (idle_timer > 10.0f)
  6512. {
  6513. fx_c_triggers |= PLAYER_IDLE_C_TRIGGER;
  6514. idle_timer = 0.0f;
  6515. }
  6516. if (fx_c_triggers & PLAYER_LANDING_S_TRIGGER)
  6517. {
  6518. fx_c_triggers &= ~(PLAYER_LANDING_S_TRIGGER);
  6519. }
  6520. }
  6521. U32 Player::unique_movement_tag_counter = 1;
  6522. void Player::setMovementSpeedBias(F32 bias)
  6523. {
  6524. speed_bias_goal = bias;
  6525. }
  6526. U32 Player::setMovementOverride(F32 bias, const Point3F* mov, U32 op)
  6527. {
  6528. if (mov)
  6529. {
  6530. movement_data = *mov;
  6531. override_movement = true;
  6532. movement_op = (U8)op;
  6533. }
  6534. else
  6535. override_movement = false;
  6536. speed_bias_goal = bias;
  6537. last_movement_tag = unique_movement_tag_counter++;
  6538. return last_movement_tag;
  6539. }
  6540. void Player::restoreMovement(U32 tag)
  6541. {
  6542. if (tag != 0 && tag == last_movement_tag)
  6543. {
  6544. speed_bias_goal = 1.0;
  6545. override_movement = false;
  6546. }
  6547. }
  6548. DefineEngineMethod(Player, setMovementSpeedBias, void, (F32 bias),, "setMovementSpeedBias(F32 bias)")
  6549. {
  6550. object->setMovementSpeedBias(bias);
  6551. }
  6552. void Player::overrideFootfallFX(bool decals, bool sounds, bool dust)
  6553. {
  6554. if (decals)
  6555. footfallDecalOverride++;
  6556. if (sounds)
  6557. footfallSoundOverride++;
  6558. if (dust)
  6559. footfallDustOverride++;
  6560. noFootfallFX = (footfallDecalOverride > 0 && footfallSoundOverride > 0 && footfallDustOverride > 0);
  6561. }
  6562. void Player::restoreFootfallFX(bool decals, bool sounds, bool dust)
  6563. {
  6564. if (decals && footfallDecalOverride)
  6565. footfallDecalOverride--;
  6566. if (sounds && footfallSoundOverride)
  6567. footfallSoundOverride--;
  6568. if (dust && footfallDustOverride)
  6569. footfallDustOverride--;
  6570. noFootfallFX = (footfallDecalOverride > 0 && footfallSoundOverride > 0 && footfallDustOverride > 0);
  6571. }
  6572. #ifdef TORQUE_OPENVR
  6573. void Player::setControllers(Vector<OpenVRTrackedObject*> controllerList)
  6574. {
  6575. mControllers[0] = controllerList.size() > 0 ? controllerList[0] : NULL;
  6576. mControllers[1] = controllerList.size() > 1 ? controllerList[1] : NULL;
  6577. }
  6578. DefineEngineMethod(Player, setVRControllers, void, (OpenVRTrackedObject* controllerL, OpenVRTrackedObject* controllerR,, "")
  6579. {
  6580. Vector<OpenVRTrackedObject*> list;
  6581. if (controllerL)
  6582. {
  6583. list.push_back(controllerL);
  6584. }
  6585. else
  6586. {
  6587. list.push_back(NULL);
  6588. }
  6589. if (controllerR)
  6590. {
  6591. list.push_back(controllerR);
  6592. }
  6593. else
  6594. {
  6595. list.push_back(NULL);
  6596. }
  6597. object->setControllers(list);
  6598. }
  6599. #endif