player.cpp 254 KB

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