player.cpp 239 KB

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