player.cpp 254 KB

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