player.cpp 253 KB

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