player.cpp 253 KB

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