player.cpp 256 KB

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