player.cpp 252 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671
  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. delta.pos = mAnchorPoint = Point3F(0,0,100);
  1305. delta.rot = delta.head = Point3F(0,0,0);
  1306. delta.rotOffset.set(0.0f,0.0f,0.0f);
  1307. delta.warpOffset.set(0.0f,0.0f,0.0f);
  1308. delta.posVec.set(0.0f,0.0f,0.0f);
  1309. delta.rotVec.set(0.0f,0.0f,0.0f);
  1310. delta.headVec.set(0.0f,0.0f,0.0f);
  1311. delta.warpTicks = 0;
  1312. delta.dt = 1.0f;
  1313. delta.move = NullMove;
  1314. mPredictionCount = sMaxPredictionTicks;
  1315. mObjToWorld.setColumn(3,delta.pos);
  1316. mRot = delta.rot;
  1317. mHead = delta.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. Vector<String> skins;
  1622. String(mSkinNameHandle.getString()).split( ";", skins );
  1623. for ( S32 i = 0; i < skins.size(); i++ )
  1624. {
  1625. String oldSkin( mAppliedSkinName.c_str() );
  1626. String newSkin( skins[i] );
  1627. // Check if the skin handle contains an explicit "old" base string. This
  1628. // allows all models to support skinning, even if they don't follow the
  1629. // "base_xxx" material naming convention.
  1630. S32 split = newSkin.find( '=' ); // "old=new" format skin?
  1631. if ( split != String::NPos )
  1632. {
  1633. oldSkin = newSkin.substr( 0, split );
  1634. newSkin = newSkin.erase( 0, split+1 );
  1635. }
  1636. // Apply skin to both 3rd person and 1st person shape instances
  1637. mShapeInstance->reSkin( newSkin, oldSkin );
  1638. for ( S32 j = 0; j < ShapeBase::MaxMountedImages; j++ )
  1639. {
  1640. if (mShapeFPInstance[j])
  1641. mShapeFPInstance[j]->reSkin( newSkin, oldSkin );
  1642. }
  1643. mAppliedSkinName = newSkin;
  1644. }
  1645. }
  1646. }
  1647. //----------------------------------------------------------------------------
  1648. void Player::setControllingClient(GameConnection* client)
  1649. {
  1650. Parent::setControllingClient(client);
  1651. if (mControlObject)
  1652. mControlObject->setControllingClient(client);
  1653. }
  1654. void Player::setControlObject(ShapeBase* obj)
  1655. {
  1656. if (mControlObject == obj)
  1657. return;
  1658. if (mControlObject) {
  1659. mControlObject->setControllingObject(0);
  1660. mControlObject->setControllingClient(0);
  1661. }
  1662. if (obj == this || obj == 0)
  1663. mControlObject = 0;
  1664. else {
  1665. if (ShapeBase* coo = obj->getControllingObject())
  1666. coo->setControlObject(0);
  1667. if (GameConnection* con = obj->getControllingClient())
  1668. con->setControlObject(0);
  1669. mControlObject = obj;
  1670. mControlObject->setControllingObject(this);
  1671. mControlObject->setControllingClient(getControllingClient());
  1672. }
  1673. }
  1674. void Player::onCameraScopeQuery(NetConnection *connection, CameraScopeQuery *query)
  1675. {
  1676. // First, we are certainly in scope, and whatever we're riding is too...
  1677. if(mControlObject.isNull() || mControlObject == mMount.object)
  1678. Parent::onCameraScopeQuery(connection, query);
  1679. else
  1680. {
  1681. connection->objectInScope(this);
  1682. if (isMounted())
  1683. connection->objectInScope(mMount.object);
  1684. mControlObject->onCameraScopeQuery(connection, query);
  1685. }
  1686. }
  1687. ShapeBase* Player::getControlObject()
  1688. {
  1689. return mControlObject;
  1690. }
  1691. void Player::processTick(const Move* move)
  1692. {
  1693. PROFILE_SCOPE(Player_ProcessTick);
  1694. bool prevMoveMotion = mMoveMotion;
  1695. Pose prevPose = getPose();
  1696. // If we're not being controlled by a client, let the
  1697. // AI sub-module get a chance at producing a move.
  1698. Move aiMove;
  1699. if (!move && isServerObject() && getAIMove(&aiMove))
  1700. move = &aiMove;
  1701. // Manage the control object and filter moves for the player
  1702. Move pMove,cMove;
  1703. if (mControlObject) {
  1704. if (!move)
  1705. mControlObject->processTick(0);
  1706. else {
  1707. pMove = NullMove;
  1708. cMove = *move;
  1709. //if (isMounted()) {
  1710. // Filter Jump trigger if mounted
  1711. //pMove.trigger[2] = move->trigger[2];
  1712. //cMove.trigger[2] = false;
  1713. //}
  1714. if (move->freeLook) {
  1715. // Filter yaw/picth/roll when freelooking.
  1716. pMove.yaw = move->yaw;
  1717. pMove.pitch = move->pitch;
  1718. pMove.roll = move->roll;
  1719. pMove.freeLook = true;
  1720. cMove.freeLook = false;
  1721. cMove.yaw = cMove.pitch = cMove.roll = 0.0f;
  1722. }
  1723. mControlObject->processTick((mDamageState == Enabled)? &cMove: &NullMove);
  1724. move = &pMove;
  1725. }
  1726. }
  1727. Parent::processTick(move);
  1728. // Check for state changes in the standard move triggers and
  1729. // set bits for any triggers that switched on this tick in
  1730. // the fx_s_triggers mask. Flag any changes to be packed to
  1731. // clients.
  1732. if (isServerObject())
  1733. {
  1734. fx_s_triggers = 0;
  1735. if (move)
  1736. {
  1737. U8 on_bits = 0;
  1738. for (S32 i = 0; i < MaxTriggerKeys; i++)
  1739. if (move->trigger[i])
  1740. on_bits |= BIT(i);
  1741. if (on_bits != move_trigger_states)
  1742. {
  1743. U8 switched_on_bits = (on_bits & ~move_trigger_states);
  1744. if (switched_on_bits)
  1745. {
  1746. fx_s_triggers |= (U32)switched_on_bits;
  1747. setMaskBits(TriggerMask);
  1748. }
  1749. move_trigger_states = on_bits;
  1750. }
  1751. }
  1752. }
  1753. // Warp to catch up to server
  1754. if (delta.warpTicks > 0) {
  1755. delta.warpTicks--;
  1756. // Set new pos
  1757. getTransform().getColumn(3, &delta.pos);
  1758. delta.pos += delta.warpOffset;
  1759. delta.rot += delta.rotOffset;
  1760. // Wrap yaw to +/-PI
  1761. if (delta.rot.z < - M_PI_F)
  1762. delta.rot.z += M_2PI_F;
  1763. else if (delta.rot.z > M_PI_F)
  1764. delta.rot.z -= M_2PI_F;
  1765. if (!ignore_updates)
  1766. {
  1767. setPosition(delta.pos,delta.rot);
  1768. }
  1769. updateDeathOffsets();
  1770. updateLookAnimation();
  1771. // Backstepping
  1772. delta.posVec = -delta.warpOffset;
  1773. delta.rotVec = -delta.rotOffset;
  1774. }
  1775. else {
  1776. // If there is no move, the player is either an
  1777. // unattached player on the server, or a player's
  1778. // client ghost.
  1779. if (!move) {
  1780. if (isGhost()) {
  1781. // If we haven't run out of prediction time,
  1782. // predict using the last known move.
  1783. if (mPredictionCount-- <= 0)
  1784. return;
  1785. move = &delta.move;
  1786. }
  1787. else
  1788. move = &NullMove;
  1789. }
  1790. if (!isGhost())
  1791. updateAnimation(TickSec);
  1792. PROFILE_START(Player_PhysicsSection);
  1793. if ( isServerObject() || didRenderLastRender() || getControllingClient() )
  1794. {
  1795. if ( !mPhysicsRep )
  1796. {
  1797. if ( isMounted() )
  1798. {
  1799. // If we're mounted then do not perform any collision checks
  1800. // and clear our previous working list.
  1801. mConvex.clearWorkingList();
  1802. }
  1803. else
  1804. {
  1805. updateWorkingCollisionSet();
  1806. }
  1807. }
  1808. updateState();
  1809. updateMove(move);
  1810. updateLookAnimation();
  1811. updateDeathOffsets();
  1812. updatePos();
  1813. }
  1814. PROFILE_END();
  1815. if (!isGhost())
  1816. {
  1817. // Animations are advanced based on frame rate on the
  1818. // client and must be ticked on the server.
  1819. updateActionThread();
  1820. updateAnimationTree(true);
  1821. // Check for sprinting motion changes
  1822. Pose currentPose = getPose();
  1823. // Player has just switched into Sprint pose and is moving
  1824. if (currentPose == SprintPose && prevPose != SprintPose && mMoveMotion)
  1825. {
  1826. mDataBlock->onStartSprintMotion_callback( this );
  1827. }
  1828. // Player has just switched out of Sprint pose and is moving, or was just moving
  1829. else if (currentPose != SprintPose && prevPose == SprintPose && (mMoveMotion || prevMoveMotion))
  1830. {
  1831. mDataBlock->onStopSprintMotion_callback( this );
  1832. }
  1833. // Player is in Sprint pose and has modified their motion
  1834. else if (currentPose == SprintPose && prevMoveMotion != mMoveMotion)
  1835. {
  1836. if (mMoveMotion)
  1837. {
  1838. mDataBlock->onStartSprintMotion_callback( this );
  1839. }
  1840. else
  1841. {
  1842. mDataBlock->onStopSprintMotion_callback( this );
  1843. }
  1844. }
  1845. }
  1846. }
  1847. }
  1848. void Player::interpolateTick(F32 dt)
  1849. {
  1850. if (mControlObject)
  1851. mControlObject->interpolateTick(dt);
  1852. // Client side interpolation
  1853. Parent::interpolateTick(dt);
  1854. Point3F pos = delta.pos + delta.posVec * dt;
  1855. Point3F rot = delta.rot + delta.rotVec * dt;
  1856. if (!ignore_updates)
  1857. setRenderPosition(pos,rot,dt);
  1858. /*
  1859. // apply camera effects - is this the best place? - bramage
  1860. GameConnection* connection = GameConnection::getConnectionToServer();
  1861. if( connection->isFirstPerson() )
  1862. {
  1863. ShapeBase *obj = dynamic_cast<ShapeBase*>(connection->getControlObject());
  1864. if( obj == this )
  1865. {
  1866. MatrixF curTrans = getRenderTransform();
  1867. curTrans.mul( gCamFXMgr.getTrans() );
  1868. Parent::setRenderTransform( curTrans );
  1869. }
  1870. }
  1871. */
  1872. updateLookAnimation(dt);
  1873. delta.dt = dt;
  1874. }
  1875. void Player::advanceTime(F32 dt)
  1876. {
  1877. // Client side animations
  1878. Parent::advanceTime(dt);
  1879. // Increment timer for triggering idle events.
  1880. if (idle_timer >= 0.0f)
  1881. idle_timer += dt;
  1882. updateActionThread();
  1883. updateAnimation(dt);
  1884. updateSplash();
  1885. updateFroth(dt);
  1886. updateWaterSounds(dt);
  1887. mLastPos = getPosition();
  1888. if (mImpactSound)
  1889. playImpactSound();
  1890. // update camera effects. Definitely need to find better place for this - bramage
  1891. if( isControlObject() )
  1892. {
  1893. if( mDamageState == Disabled || mDamageState == Destroyed )
  1894. {
  1895. // clear out all camera effects being applied to player if dead
  1896. gCamFXMgr.clear();
  1897. }
  1898. }
  1899. }
  1900. bool Player::getAIMove(Move* move)
  1901. {
  1902. return false;
  1903. }
  1904. void Player::setState(ActionState state, U32 recoverTicks)
  1905. {
  1906. if (state != mState) {
  1907. // Skip initialization if there is no manager, the state
  1908. // will get reset when the object is added to a manager.
  1909. if (isProperlyAdded()) {
  1910. switch (state) {
  1911. case RecoverState: {
  1912. if (mDataBlock->landSequenceTime > 0.0f)
  1913. {
  1914. // Use the land sequence as the basis for the recovery
  1915. setActionThread(PlayerData::LandAnim, true, false, true, true);
  1916. F32 timeScale = mShapeInstance->getDuration(mActionAnimation.thread) / mDataBlock->landSequenceTime;
  1917. mShapeInstance->setTimeScale(mActionAnimation.thread,timeScale);
  1918. mRecoverDelay = mDataBlock->landSequenceTime;
  1919. }
  1920. else
  1921. {
  1922. // Legacy recover system
  1923. mRecoverTicks = recoverTicks;
  1924. mReversePending = U32(F32(mRecoverTicks) / sLandReverseScale);
  1925. setActionThread(PlayerData::LandAnim, true, false, true, true);
  1926. }
  1927. break;
  1928. }
  1929. default:
  1930. break;
  1931. }
  1932. }
  1933. mState = state;
  1934. }
  1935. }
  1936. void Player::updateState()
  1937. {
  1938. switch (mState)
  1939. {
  1940. case RecoverState:
  1941. if (mDataBlock->landSequenceTime > 0.0f)
  1942. {
  1943. // Count down the land time
  1944. mRecoverDelay -= TickSec;
  1945. if (mRecoverDelay <= 0.0f)
  1946. {
  1947. setState(MoveState);
  1948. }
  1949. }
  1950. else
  1951. {
  1952. // Legacy recover system
  1953. if (mRecoverTicks-- <= 0)
  1954. {
  1955. if (mReversePending && mActionAnimation.action != PlayerData::NullAnimation)
  1956. {
  1957. // this serves and counter, and direction state
  1958. mRecoverTicks = mReversePending;
  1959. mActionAnimation.forward = false;
  1960. S32 seq = mDataBlock->actionList[mActionAnimation.action].sequence;
  1961. S32 imageBasedSeq = convertActionToImagePrefix(mActionAnimation.action);
  1962. if (imageBasedSeq != -1)
  1963. seq = imageBasedSeq;
  1964. F32 pos = mShapeInstance->getPos(mActionAnimation.thread);
  1965. mShapeInstance->setTimeScale(mActionAnimation.thread, -sLandReverseScale);
  1966. mShapeInstance->transitionToSequence(mActionAnimation.thread,
  1967. seq, pos, sAnimationTransitionTime, true);
  1968. mReversePending = 0;
  1969. }
  1970. else
  1971. {
  1972. setState(MoveState);
  1973. }
  1974. } // Stand back up slowly only if not moving much-
  1975. else if (!mReversePending && mVelocity.lenSquared() > sSlowStandThreshSquared)
  1976. {
  1977. mActionAnimation.waitForEnd = false;
  1978. setState(MoveState);
  1979. }
  1980. }
  1981. break;
  1982. default:
  1983. break;
  1984. }
  1985. }
  1986. const char* Player::getStateName()
  1987. {
  1988. if (mDamageState != Enabled)
  1989. return "Dead";
  1990. if (isMounted())
  1991. return "Mounted";
  1992. if (mState == RecoverState)
  1993. return "Recover";
  1994. return "Move";
  1995. }
  1996. void Player::getDamageLocation(const Point3F& in_rPos, const char *&out_rpVert, const char *&out_rpQuad)
  1997. {
  1998. // TODO: This will be WRONG when player is prone or swimming!
  1999. Point3F newPoint;
  2000. mWorldToObj.mulP(in_rPos, &newPoint);
  2001. Point3F boxSize = mObjBox.getExtents();
  2002. F32 zHeight = boxSize.z;
  2003. F32 zTorso = mDataBlock->boxTorsoPercentage;
  2004. F32 zHead = mDataBlock->boxHeadPercentage;
  2005. zTorso *= zHeight;
  2006. zHead *= zHeight;
  2007. if (newPoint.z <= zTorso)
  2008. out_rpVert = "legs";
  2009. else if (newPoint.z <= zHead)
  2010. out_rpVert = "torso";
  2011. else
  2012. out_rpVert = "head";
  2013. if(dStrcmp(out_rpVert, "head") != 0)
  2014. {
  2015. if (newPoint.y >= 0.0f)
  2016. {
  2017. if (newPoint.x <= 0.0f)
  2018. out_rpQuad = "front_left";
  2019. else
  2020. out_rpQuad = "front_right";
  2021. }
  2022. else
  2023. {
  2024. if (newPoint.x <= 0.0f)
  2025. out_rpQuad = "back_left";
  2026. else
  2027. out_rpQuad = "back_right";
  2028. }
  2029. }
  2030. else
  2031. {
  2032. F32 backToFront = boxSize.x;
  2033. F32 leftToRight = boxSize.y;
  2034. F32 backPoint = backToFront * mDataBlock->boxHeadBackPercentage;
  2035. F32 frontPoint = backToFront * mDataBlock->boxHeadFrontPercentage;
  2036. F32 leftPoint = leftToRight * mDataBlock->boxHeadLeftPercentage;
  2037. F32 rightPoint = leftToRight * mDataBlock->boxHeadRightPercentage;
  2038. S32 index = 0;
  2039. if (newPoint.y < backPoint)
  2040. index += 0;
  2041. else if (newPoint.y >= frontPoint)
  2042. index += 3;
  2043. else
  2044. index += 6;
  2045. if (newPoint.x < leftPoint)
  2046. index += 0;
  2047. else if (newPoint.x >= rightPoint)
  2048. index += 1;
  2049. else
  2050. index += 2;
  2051. switch (index)
  2052. {
  2053. case 0: out_rpQuad = "left_back"; break;
  2054. case 1: out_rpQuad = "middle_back"; break;
  2055. case 2: out_rpQuad = "right_back"; break;
  2056. case 3: out_rpQuad = "left_middle"; break;
  2057. case 4: out_rpQuad = "middle_middle"; break;
  2058. case 5: out_rpQuad = "right_middle"; break;
  2059. case 6: out_rpQuad = "left_front"; break;
  2060. case 7: out_rpQuad = "middle_front"; break;
  2061. case 8: out_rpQuad = "right_front"; break;
  2062. default:
  2063. AssertFatal(0, "Bad non-tant index");
  2064. };
  2065. }
  2066. }
  2067. const char* Player::getPoseName() const
  2068. {
  2069. return EngineMarshallData< PlayerPose >(getPose());
  2070. }
  2071. void Player::setPose( Pose pose )
  2072. {
  2073. // Already the set pose, return.
  2074. if ( pose == mPose )
  2075. return;
  2076. Pose oldPose = mPose;
  2077. mPose = pose;
  2078. // Not added yet, just assign the pose and return.
  2079. if ( !isProperlyAdded() )
  2080. return;
  2081. Point3F boxSize(1,1,1);
  2082. // Resize the player boxes
  2083. switch (pose)
  2084. {
  2085. case StandPose:
  2086. case SprintPose:
  2087. boxSize = mDataBlock->boxSize;
  2088. break;
  2089. case CrouchPose:
  2090. boxSize = mDataBlock->crouchBoxSize;
  2091. break;
  2092. case PronePose:
  2093. boxSize = mDataBlock->proneBoxSize;
  2094. break;
  2095. case SwimPose:
  2096. boxSize = mDataBlock->swimBoxSize;
  2097. break;
  2098. }
  2099. // Object and World Boxes...
  2100. mObjBox.maxExtents.x = boxSize.x * 0.5f;
  2101. mObjBox.maxExtents.y = boxSize.y * 0.5f;
  2102. mObjBox.maxExtents.z = boxSize.z;
  2103. mObjBox.minExtents.x = -mObjBox.maxExtents.x;
  2104. mObjBox.minExtents.y = -mObjBox.maxExtents.y;
  2105. mObjBox.minExtents.z = 0.0f;
  2106. resetWorldBox();
  2107. // Setup the box for our convex object...
  2108. mObjBox.getCenter(&mConvex.mCenter);
  2109. mConvex.mSize.x = mObjBox.len_x() / 2.0f;
  2110. mConvex.mSize.y = mObjBox.len_y() / 2.0f;
  2111. mConvex.mSize.z = mObjBox.len_z() / 2.0f;
  2112. // Initialize our scaled attributes as well...
  2113. onScaleChanged();
  2114. // Resize the PhysicsPlayer rep. should we have one
  2115. if ( mPhysicsRep )
  2116. mPhysicsRep->setSpacials( getPosition(), boxSize );
  2117. if ( isServerObject() )
  2118. mDataBlock->onPoseChange_callback( this, EngineMarshallData< PlayerPose >(oldPose), EngineMarshallData< PlayerPose >(mPose));
  2119. }
  2120. void Player::allowAllPoses()
  2121. {
  2122. mAllowJumping = true;
  2123. mAllowJetJumping = true;
  2124. mAllowSprinting = true;
  2125. mAllowCrouching = true;
  2126. mAllowProne = true;
  2127. mAllowSwimming = true;
  2128. }
  2129. AngAxisF gPlayerMoveRot;
  2130. void Player::updateMove(const Move* move)
  2131. {
  2132. struct Move my_move;
  2133. if (override_movement && movement_op < 3)
  2134. {
  2135. my_move = *move;
  2136. switch (movement_op)
  2137. {
  2138. case 0: // add
  2139. my_move.x += movement_data.x;
  2140. my_move.y += movement_data.y;
  2141. my_move.z += movement_data.z;
  2142. break;
  2143. case 1: // mult
  2144. my_move.x *= movement_data.x;
  2145. my_move.y *= movement_data.y;
  2146. my_move.z *= movement_data.z;
  2147. break;
  2148. case 2: // replace
  2149. my_move.x = movement_data.x;
  2150. my_move.y = movement_data.y;
  2151. my_move.z = movement_data.z;
  2152. break;
  2153. }
  2154. move = &my_move;
  2155. }
  2156. delta.move = *move;
  2157. #ifdef TORQUE_OPENVR
  2158. if (mControllers[0])
  2159. {
  2160. mControllers[0]->processTick(move);
  2161. }
  2162. if (mControllers[1])
  2163. {
  2164. mControllers[1]->processTick(move);
  2165. }
  2166. #endif
  2167. // Is waterCoverage high enough to be 'swimming'?
  2168. {
  2169. bool swimming = mWaterCoverage > 0.65f && canSwim();
  2170. if ( swimming != mSwimming )
  2171. {
  2172. if ( !isGhost() )
  2173. {
  2174. if ( swimming )
  2175. mDataBlock->onStartSwim_callback( this );
  2176. else
  2177. mDataBlock->onStopSwim_callback( this );
  2178. }
  2179. mSwimming = swimming;
  2180. }
  2181. }
  2182. // Trigger images
  2183. if (mDamageState == Enabled)
  2184. {
  2185. setImageTriggerState( 0, move->trigger[sImageTrigger0] );
  2186. // If you have a secondary mounted image then
  2187. // send the second trigger to it. Else give it
  2188. // to the first image as an alt fire.
  2189. if ( getMountedImage( 1 ) )
  2190. setImageTriggerState( 1, move->trigger[sImageTrigger1] );
  2191. else
  2192. setImageAltTriggerState( 0, move->trigger[sImageTrigger1] );
  2193. }
  2194. // Update current orientation
  2195. if (mDamageState == Enabled) {
  2196. F32 prevZRot = mRot.z;
  2197. delta.headVec = mHead;
  2198. bool doStandardMove = true;
  2199. bool absoluteDelta = false;
  2200. GameConnection* con = getControllingClient();
  2201. #ifdef TORQUE_EXTENDED_MOVE
  2202. // Work with an absolute rotation from the ExtendedMove class?
  2203. if(con && con->getControlSchemeAbsoluteRotation())
  2204. {
  2205. doStandardMove = false;
  2206. const ExtendedMove* emove = dynamic_cast<const ExtendedMove*>(move);
  2207. U32 emoveIndex = smExtendedMoveHeadPosRotIndex;
  2208. if(emoveIndex >= ExtendedMove::MaxPositionsRotations)
  2209. emoveIndex = 0;
  2210. if(emove->EulerBasedRotation[emoveIndex])
  2211. {
  2212. // Head pitch
  2213. mHead.x += (emove->rotX[emoveIndex] - mLastAbsolutePitch);
  2214. // Do we also include the relative yaw value?
  2215. if(con->getControlSchemeAddPitchToAbsRot())
  2216. {
  2217. F32 x = move->pitch;
  2218. if (x > M_PI_F)
  2219. x -= M_2PI_F;
  2220. mHead.x += x;
  2221. }
  2222. // Constrain the range of mHead.x
  2223. while (mHead.x < -M_PI_F)
  2224. mHead.x += M_2PI_F;
  2225. while (mHead.x > M_PI_F)
  2226. mHead.x -= M_2PI_F;
  2227. // Rotate (heading) head or body?
  2228. if (move->freeLook && ((isMounted() && getMountNode() == 0) || (con && !con->isFirstPerson())))
  2229. {
  2230. // Rotate head
  2231. mHead.z += (emove->rotZ[emoveIndex] - mLastAbsoluteYaw);
  2232. // Do we also include the relative yaw value?
  2233. if(con->getControlSchemeAddYawToAbsRot())
  2234. {
  2235. F32 z = move->yaw;
  2236. if (z > M_PI_F)
  2237. z -= M_2PI_F;
  2238. mHead.z += z;
  2239. }
  2240. // Constrain the range of mHead.z
  2241. while (mHead.z < 0.0f)
  2242. mHead.z += M_2PI_F;
  2243. while (mHead.z > M_2PI_F)
  2244. mHead.z -= M_2PI_F;
  2245. }
  2246. else
  2247. {
  2248. // Rotate body
  2249. mRot.z += (emove->rotZ[emoveIndex] - mLastAbsoluteYaw);
  2250. // Do we also include the relative yaw value?
  2251. if(con->getControlSchemeAddYawToAbsRot())
  2252. {
  2253. F32 z = move->yaw;
  2254. if (z > M_PI_F)
  2255. z -= M_2PI_F;
  2256. mRot.z += z;
  2257. }
  2258. // Constrain the range of mRot.z
  2259. while (mRot.z < 0.0f)
  2260. mRot.z += M_2PI_F;
  2261. while (mRot.z > M_2PI_F)
  2262. mRot.z -= M_2PI_F;
  2263. }
  2264. mLastAbsoluteYaw = emove->rotZ[emoveIndex];
  2265. mLastAbsolutePitch = emove->rotX[emoveIndex];
  2266. mLastAbsoluteRoll = emove->rotY[emoveIndex];
  2267. // Head bank
  2268. mHead.y = emove->rotY[emoveIndex];
  2269. // Constrain the range of mHead.y
  2270. while (mHead.y > M_PI_F)
  2271. mHead.y -= M_2PI_F;
  2272. }
  2273. else
  2274. {
  2275. // Orient the player so we are looking towards the required position, ignoring any banking
  2276. AngAxisF moveRot(Point3F(emove->rotX[emoveIndex], emove->rotY[emoveIndex], emove->rotZ[emoveIndex]), emove->rotW[emoveIndex]);
  2277. MatrixF trans(1);
  2278. moveRot.setMatrix(&trans);
  2279. trans.inverse();
  2280. Point3F vecForward(0, 10, 0);
  2281. Point3F viewAngle;
  2282. Point3F orient;
  2283. EulerF rot;
  2284. trans.mulV(vecForward);
  2285. viewAngle = vecForward;
  2286. vecForward.z = 0; // flatten
  2287. vecForward.normalizeSafe();
  2288. F32 yawAng;
  2289. F32 pitchAng;
  2290. MathUtils::getAnglesFromVector(vecForward, yawAng, pitchAng);
  2291. mRot = EulerF(0);
  2292. mRot.z = yawAng;
  2293. mHead = EulerF(0);
  2294. while (mRot.z < 0.0f)
  2295. mRot.z += M_2PI_F;
  2296. while (mRot.z > M_2PI_F)
  2297. mRot.z -= M_2PI_F;
  2298. absoluteDelta = true;
  2299. }
  2300. }
  2301. #endif
  2302. if(doStandardMove)
  2303. {
  2304. F32 p = move->pitch * (mPose == SprintPose ? mDataBlock->sprintPitchScale : 1.0f);
  2305. if (p > M_PI_F)
  2306. p -= M_2PI_F;
  2307. mHead.x = mClampF(mHead.x + p,mDataBlock->minLookAngle,
  2308. mDataBlock->maxLookAngle);
  2309. F32 y = move->yaw * (mPose == SprintPose ? mDataBlock->sprintYawScale : 1.0f);
  2310. if (y > M_PI_F)
  2311. y -= M_2PI_F;
  2312. if (move->freeLook && ((isMounted() && getMountNode() == 0) || (con && !con->isFirstPerson())))
  2313. {
  2314. mHead.z = mClampF(mHead.z + y,
  2315. -mDataBlock->maxFreelookAngle,
  2316. mDataBlock->maxFreelookAngle);
  2317. }
  2318. else
  2319. {
  2320. mRot.z += y;
  2321. // Rotate the head back to the front, center horizontal
  2322. // as well if we're controlling another object.
  2323. mHead.z *= 0.5f;
  2324. if (mControlObject)
  2325. mHead.x *= 0.5f;
  2326. }
  2327. // constrain the range of mRot.z
  2328. while (mRot.z < 0.0f)
  2329. mRot.z += M_2PI_F;
  2330. while (mRot.z > M_2PI_F)
  2331. mRot.z -= M_2PI_F;
  2332. }
  2333. delta.rot = mRot;
  2334. delta.rotVec.x = delta.rotVec.y = 0.0f;
  2335. delta.rotVec.z = prevZRot - mRot.z;
  2336. if (delta.rotVec.z > M_PI_F)
  2337. delta.rotVec.z -= M_2PI_F;
  2338. else if (delta.rotVec.z < -M_PI_F)
  2339. delta.rotVec.z += M_2PI_F;
  2340. delta.head = mHead;
  2341. delta.headVec -= mHead;
  2342. if (absoluteDelta)
  2343. {
  2344. delta.headVec = Point3F(0, 0, 0);
  2345. delta.rotVec = Point3F(0, 0, 0);
  2346. }
  2347. for(U32 i=0; i<3; ++i)
  2348. {
  2349. if (delta.headVec[i] > M_PI_F)
  2350. delta.headVec[i] -= M_2PI_F;
  2351. else if (delta.headVec[i] < -M_PI_F)
  2352. delta.headVec[i] += M_2PI_F;
  2353. }
  2354. }
  2355. MatrixF zRot;
  2356. zRot.set(EulerF(0.0f, 0.0f, mRot.z));
  2357. // Desired move direction & speed
  2358. VectorF moveVec;
  2359. F32 moveSpeed;
  2360. // If BLOCK_USER_CONTROL is set in anim_clip_flags, the user won't be able to
  2361. // resume control over the player character. This generally happens for
  2362. // short periods of time synchronized with script driven animation at places
  2363. // where it makes sense that user motion is prohibited, such as when the
  2364. // player is lifted off the ground or knocked down.
  2365. if ((mState == MoveState || (mState == RecoverState && mDataBlock->recoverRunForceScale > 0.0f)) && mDamageState == Enabled && !isAnimationLocked())
  2366. {
  2367. zRot.getColumn(0,&moveVec);
  2368. moveVec *= (move->x * (mPose == SprintPose ? mDataBlock->sprintStrafeScale : 1.0f));
  2369. VectorF tv;
  2370. zRot.getColumn(1,&tv);
  2371. moveVec += tv * move->y;
  2372. // Clamp water movement
  2373. if (move->y > 0.0f)
  2374. {
  2375. if ( mSwimming )
  2376. moveSpeed = getMax(mDataBlock->maxUnderwaterForwardSpeed * move->y,
  2377. mDataBlock->maxUnderwaterSideSpeed * mFabs(move->x));
  2378. else if ( mPose == PronePose )
  2379. moveSpeed = getMax(mDataBlock->maxProneForwardSpeed * move->y,
  2380. mDataBlock->maxProneSideSpeed * mFabs(move->x));
  2381. else if ( mPose == CrouchPose )
  2382. moveSpeed = getMax(mDataBlock->maxCrouchForwardSpeed * move->y,
  2383. mDataBlock->maxCrouchSideSpeed * mFabs(move->x));
  2384. else if ( mPose == SprintPose )
  2385. moveSpeed = getMax(mDataBlock->maxSprintForwardSpeed * move->y,
  2386. mDataBlock->maxSprintSideSpeed * mFabs(move->x));
  2387. else // StandPose
  2388. moveSpeed = getMax(mDataBlock->maxForwardSpeed * move->y,
  2389. mDataBlock->maxSideSpeed * mFabs(move->x));
  2390. }
  2391. else
  2392. {
  2393. if ( mSwimming )
  2394. moveSpeed = getMax(mDataBlock->maxUnderwaterBackwardSpeed * mFabs(move->y),
  2395. mDataBlock->maxUnderwaterSideSpeed * mFabs(move->x));
  2396. else if ( mPose == PronePose )
  2397. moveSpeed = getMax(mDataBlock->maxProneBackwardSpeed * mFabs(move->y),
  2398. mDataBlock->maxProneSideSpeed * mFabs(move->x));
  2399. else if ( mPose == CrouchPose )
  2400. moveSpeed = getMax(mDataBlock->maxCrouchBackwardSpeed * mFabs(move->y),
  2401. mDataBlock->maxCrouchSideSpeed * mFabs(move->x));
  2402. else if ( mPose == SprintPose )
  2403. moveSpeed = getMax(mDataBlock->maxSprintBackwardSpeed * mFabs(move->y),
  2404. mDataBlock->maxSprintSideSpeed * mFabs(move->x));
  2405. else // StandPose
  2406. moveSpeed = getMax(mDataBlock->maxBackwardSpeed * mFabs(move->y),
  2407. mDataBlock->maxSideSpeed * mFabs(move->x));
  2408. }
  2409. // Cancel any script driven animations if we are going to move.
  2410. if (moveVec.x + moveVec.y + moveVec.z != 0.0f &&
  2411. (mActionAnimation.action >= PlayerData::NumTableActionAnims
  2412. || mActionAnimation.action == PlayerData::LandAnim))
  2413. mActionAnimation.action = PlayerData::NullAnimation;
  2414. }
  2415. else
  2416. {
  2417. moveVec.set(0.0f, 0.0f, 0.0f);
  2418. moveSpeed = 0.0f;
  2419. }
  2420. // apply speed bias here.
  2421. speed_bias = speed_bias + (speed_bias_goal - speed_bias)*0.1f;
  2422. moveSpeed *= speed_bias;
  2423. // Acceleration due to gravity
  2424. VectorF acc(0.0f, 0.0f, mGravity * mGravityMod * TickSec);
  2425. // Determine ground contact normal. Only look for contacts if
  2426. // we can move and aren't mounted.
  2427. VectorF contactNormal(0,0,0);
  2428. bool jumpSurface = false, runSurface = false;
  2429. if ( !isMounted() )
  2430. findContact( &runSurface, &jumpSurface, &contactNormal );
  2431. if ( jumpSurface )
  2432. mJumpSurfaceNormal = contactNormal;
  2433. // If we don't have a runSurface but we do have a contactNormal,
  2434. // then we are standing on something that is too steep.
  2435. // Deflect the force of gravity by the normal so we slide.
  2436. // We could also try aligning it to the runSurface instead,
  2437. // but this seems to work well.
  2438. if ( !runSurface && !contactNormal.isZero() )
  2439. acc = ( acc - 2 * contactNormal * mDot( acc, contactNormal ) );
  2440. // Acceleration on run surface
  2441. if (runSurface && !mSwimming) {
  2442. mContactTimer = 0;
  2443. // Remove acc into contact surface (should only be gravity)
  2444. // Clear out floating point acc errors, this will allow
  2445. // the player to "rest" on the ground.
  2446. // However, no need to do that if we're using a physics library.
  2447. // It will take care of itself.
  2448. if (!mPhysicsRep)
  2449. {
  2450. F32 vd = -mDot(acc,contactNormal);
  2451. if (vd > 0.0f) {
  2452. VectorF dv = contactNormal * (vd + 0.002f);
  2453. acc += dv;
  2454. if (acc.len() < 0.0001f)
  2455. acc.set(0.0f, 0.0f, 0.0f);
  2456. }
  2457. }
  2458. // Force a 0 move if there is no energy, and only drain
  2459. // move energy if we're moving.
  2460. VectorF pv;
  2461. if (mPose == SprintPose && mEnergy >= mDataBlock->minSprintEnergy) {
  2462. if (moveSpeed)
  2463. mEnergy -= mDataBlock->sprintEnergyDrain;
  2464. pv = moveVec;
  2465. }
  2466. else if (mEnergy >= mDataBlock->minRunEnergy) {
  2467. if (moveSpeed)
  2468. mEnergy -= mDataBlock->runEnergyDrain;
  2469. pv = moveVec;
  2470. }
  2471. else
  2472. pv.set(0.0f, 0.0f, 0.0f);
  2473. // Adjust the player's requested dir. to be parallel
  2474. // to the contact surface.
  2475. F32 pvl = pv.len();
  2476. if(mJetting)
  2477. {
  2478. pvl = moveVec.len();
  2479. if (pvl)
  2480. {
  2481. VectorF nn;
  2482. mCross(pv,VectorF(0.0f, 0.0f, 0.0f),&nn);
  2483. nn *= 1 / pvl;
  2484. VectorF cv(0.0f, 0.0f, 0.0f);
  2485. cv -= nn * mDot(nn,cv);
  2486. pv -= cv * mDot(pv,cv);
  2487. pvl = pv.len();
  2488. }
  2489. }
  2490. else if (!mPhysicsRep)
  2491. {
  2492. // We only do this if we're not using a physics library. The
  2493. // library will take care of itself.
  2494. if (pvl)
  2495. {
  2496. VectorF nn;
  2497. mCross(pv,VectorF(0.0f, 0.0f, 1.0f),&nn);
  2498. nn *= 1.0f / pvl;
  2499. VectorF cv = contactNormal;
  2500. cv -= nn * mDot(nn,cv);
  2501. pv -= cv * mDot(pv,cv);
  2502. pvl = pv.len();
  2503. }
  2504. }
  2505. // Convert to acceleration
  2506. if ( pvl )
  2507. pv *= moveSpeed / pvl;
  2508. VectorF runAcc = pv - (mVelocity + acc);
  2509. F32 runSpeed = runAcc.len();
  2510. // Clamp acceleration, player also accelerates faster when
  2511. // in his hard landing recover state.
  2512. F32 maxAcc;
  2513. if (mPose == SprintPose)
  2514. {
  2515. maxAcc = (mDataBlock->sprintForce / getMass()) * TickSec;
  2516. }
  2517. else
  2518. {
  2519. maxAcc = (mDataBlock->runForce / getMass()) * TickSec;
  2520. }
  2521. if (mState == RecoverState)
  2522. maxAcc *= mDataBlock->recoverRunForceScale;
  2523. if (runSpeed > maxAcc)
  2524. runAcc *= maxAcc / runSpeed;
  2525. acc += runAcc;
  2526. // If we are running on the ground, then we're not jumping
  2527. if (mDataBlock->isJumpAction(mActionAnimation.action))
  2528. mActionAnimation.action = PlayerData::NullAnimation;
  2529. }
  2530. else if (!mSwimming && mDataBlock->airControl > 0.0f)
  2531. {
  2532. VectorF pv;
  2533. pv = moveVec;
  2534. F32 pvl = pv.len();
  2535. if (pvl)
  2536. pv *= moveSpeed / pvl;
  2537. VectorF runAcc = pv - (mVelocity + acc);
  2538. runAcc.z = 0;
  2539. runAcc.x = runAcc.x * mDataBlock->airControl;
  2540. runAcc.y = runAcc.y * mDataBlock->airControl;
  2541. F32 runSpeed = runAcc.len();
  2542. // We don't test for sprinting when performing air control
  2543. F32 maxAcc = (mDataBlock->runForce / getMass()) * TickSec * 0.3f;
  2544. if (runSpeed > maxAcc)
  2545. runAcc *= maxAcc / runSpeed;
  2546. acc += runAcc;
  2547. // There are no special air control animations
  2548. // so... increment this unless you really want to
  2549. // play the run anims in the air.
  2550. mContactTimer++;
  2551. }
  2552. else if (mSwimming)
  2553. {
  2554. // Remove acc into contact surface (should only be gravity)
  2555. // Clear out floating point acc errors, this will allow
  2556. // the player to "rest" on the ground.
  2557. F32 vd = -mDot(acc,contactNormal);
  2558. if (vd > 0.0f) {
  2559. VectorF dv = contactNormal * (vd + 0.002f);
  2560. acc += dv;
  2561. if (acc.len() < 0.0001f)
  2562. acc.set(0.0f, 0.0f, 0.0f);
  2563. }
  2564. // get the head pitch and add it to the moveVec
  2565. // This more accurate swim vector calc comes from Matt Fairfax
  2566. MatrixF xRot, zRot;
  2567. xRot.set(EulerF(mHead.x, 0, 0));
  2568. zRot.set(EulerF(0, 0, mRot.z));
  2569. MatrixF rot;
  2570. rot.mul(zRot, xRot);
  2571. rot.getColumn(0,&moveVec);
  2572. moveVec *= move->x;
  2573. VectorF tv;
  2574. rot.getColumn(1,&tv);
  2575. moveVec += tv * move->y;
  2576. rot.getColumn(2,&tv);
  2577. moveVec += tv * move->z;
  2578. // Force a 0 move if there is no energy, and only drain
  2579. // move energy if we're moving.
  2580. VectorF swimVec;
  2581. if (mEnergy >= mDataBlock->minRunEnergy) {
  2582. if (moveSpeed)
  2583. mEnergy -= mDataBlock->runEnergyDrain;
  2584. swimVec = moveVec;
  2585. }
  2586. else
  2587. swimVec.set(0.0f, 0.0f, 0.0f);
  2588. // If we are swimming but close enough to the shore/ground
  2589. // we can still have a surface-normal. In this case align the
  2590. // velocity to the normal to make getting out of water easier.
  2591. moveVec.normalize();
  2592. F32 isSwimUp = mDot( moveVec, contactNormal );
  2593. if ( !contactNormal.isZero() && isSwimUp < 0.1f )
  2594. {
  2595. F32 pvl = swimVec.len();
  2596. if ( true && pvl )
  2597. {
  2598. VectorF nn;
  2599. mCross(swimVec,VectorF(0.0f, 0.0f, 1.0f),&nn);
  2600. nn *= 1.0f / pvl;
  2601. VectorF cv = contactNormal;
  2602. cv -= nn * mDot(nn,cv);
  2603. swimVec -= cv * mDot(swimVec,cv);
  2604. }
  2605. }
  2606. F32 swimVecLen = swimVec.len();
  2607. // Convert to acceleration.
  2608. if ( swimVecLen )
  2609. swimVec *= moveSpeed / swimVecLen;
  2610. VectorF swimAcc = swimVec - (mVelocity + acc);
  2611. F32 swimSpeed = swimAcc.len();
  2612. // Clamp acceleration.
  2613. F32 maxAcc = (mDataBlock->swimForce / getMass()) * TickSec;
  2614. if ( swimSpeed > maxAcc )
  2615. swimAcc *= maxAcc / swimSpeed;
  2616. acc += swimAcc;
  2617. mContactTimer++;
  2618. }
  2619. else
  2620. mContactTimer++;
  2621. // Acceleration from Jumping
  2622. // While BLOCK_USER_CONTROL is set in anim_clip_flags, the user won't be able to
  2623. // make the player character jump.
  2624. if (move->trigger[sJumpTrigger] && canJump() && !isAnimationLocked())
  2625. {
  2626. // Scale the jump impulse base on maxJumpSpeed
  2627. F32 zSpeedScale = mVelocity.z;
  2628. if (zSpeedScale <= mDataBlock->maxJumpSpeed)
  2629. {
  2630. zSpeedScale = (zSpeedScale <= mDataBlock->minJumpSpeed)? 1:
  2631. 1 - (zSpeedScale - mDataBlock->minJumpSpeed) /
  2632. (mDataBlock->maxJumpSpeed - mDataBlock->minJumpSpeed);
  2633. // Desired jump direction
  2634. VectorF pv = moveVec;
  2635. F32 len = pv.len();
  2636. if (len > 0)
  2637. pv *= 1 / len;
  2638. // We want to scale the jump size by the player size, somewhat
  2639. // in reduced ratio so a smaller player can jump higher in
  2640. // proportion to his size, than a larger player.
  2641. F32 scaleZ = (getScale().z * 0.25) + 0.75;
  2642. // Calculate our jump impulse
  2643. F32 impulse = mDataBlock->jumpForce / getMass();
  2644. if (mDataBlock->jumpTowardsNormal)
  2645. {
  2646. // If we are facing into the surface jump up, otherwise
  2647. // jump away from surface.
  2648. F32 dot = mDot(pv,mJumpSurfaceNormal);
  2649. if (dot <= 0)
  2650. acc.z += mJumpSurfaceNormal.z * scaleZ * impulse * zSpeedScale;
  2651. else
  2652. {
  2653. acc.x += pv.x * impulse * dot;
  2654. acc.y += pv.y * impulse * dot;
  2655. acc.z += mJumpSurfaceNormal.z * scaleZ * impulse * zSpeedScale;
  2656. }
  2657. }
  2658. else
  2659. acc.z += scaleZ * impulse * zSpeedScale;
  2660. mJumpDelay = mDataBlock->jumpDelay;
  2661. mEnergy -= mDataBlock->jumpEnergyDrain;
  2662. // If we don't have a StandJumpAnim, just play the JumpAnim...
  2663. S32 seq = (mVelocity.len() < 0.5) ? PlayerData::StandJumpAnim: PlayerData::JumpAnim;
  2664. if ( mDataBlock->actionList[seq].sequence == -1 )
  2665. seq = PlayerData::JumpAnim;
  2666. setActionThread( seq, true, false, true );
  2667. mJumpSurfaceLastContact = JumpSkipContactsMax;
  2668. // Flag the jump event trigger.
  2669. fx_s_triggers |= PLAYER_JUMP_S_TRIGGER;
  2670. setMaskBits(TriggerMask);
  2671. }
  2672. }
  2673. else
  2674. {
  2675. if (jumpSurface)
  2676. {
  2677. if (mJumpDelay > 0)
  2678. mJumpDelay--;
  2679. mJumpSurfaceLastContact = 0;
  2680. }
  2681. else
  2682. mJumpSurfaceLastContact++;
  2683. }
  2684. if (move->trigger[sJumpJetTrigger] && !isMounted() && canJetJump())
  2685. {
  2686. mJetting = true;
  2687. // Scale the jump impulse base on maxJumpSpeed
  2688. F32 zSpeedScale = mVelocity.z;
  2689. if (zSpeedScale <= mDataBlock->jetMaxJumpSpeed)
  2690. {
  2691. zSpeedScale = (zSpeedScale <= mDataBlock->jetMinJumpSpeed)? 1:
  2692. 1 - (zSpeedScale - mDataBlock->jetMinJumpSpeed) / (mDataBlock->jetMaxJumpSpeed - mDataBlock->jetMinJumpSpeed);
  2693. // Desired jump direction
  2694. VectorF pv = moveVec;
  2695. F32 len = pv.len();
  2696. if (len > 0.0f)
  2697. pv *= 1 / len;
  2698. // If we are facing into the surface jump up, otherwise
  2699. // jump away from surface.
  2700. F32 dot = mDot(pv,mJumpSurfaceNormal);
  2701. F32 impulse = mDataBlock->jetJumpForce / getMass();
  2702. if (dot <= 0)
  2703. acc.z += mJumpSurfaceNormal.z * impulse * zSpeedScale;
  2704. else
  2705. {
  2706. acc.x += pv.x * impulse * dot;
  2707. acc.y += pv.y * impulse * dot;
  2708. acc.z += mJumpSurfaceNormal.z * impulse * zSpeedScale;
  2709. }
  2710. mEnergy -= mDataBlock->jetJumpEnergyDrain;
  2711. }
  2712. }
  2713. else
  2714. {
  2715. mJetting = false;
  2716. }
  2717. // Add in force from physical zones...
  2718. acc += (mAppliedForce / getMass()) * TickSec;
  2719. // Adjust velocity with all the move & gravity acceleration
  2720. // TG: I forgot why doesn't the TickSec multiply happen here...
  2721. mVelocity += acc;
  2722. // apply horizontal air resistance
  2723. F32 hvel = mSqrt(mVelocity.x * mVelocity.x + mVelocity.y * mVelocity.y);
  2724. if(hvel > mDataBlock->horizResistSpeed)
  2725. {
  2726. F32 speedCap = hvel;
  2727. if(speedCap > mDataBlock->horizMaxSpeed)
  2728. speedCap = mDataBlock->horizMaxSpeed;
  2729. speedCap -= mDataBlock->horizResistFactor * TickSec * (speedCap - mDataBlock->horizResistSpeed);
  2730. F32 scale = speedCap / hvel;
  2731. mVelocity.x *= scale;
  2732. mVelocity.y *= scale;
  2733. }
  2734. if(mVelocity.z > mDataBlock->upResistSpeed)
  2735. {
  2736. if(mVelocity.z > mDataBlock->upMaxSpeed)
  2737. mVelocity.z = mDataBlock->upMaxSpeed;
  2738. mVelocity.z -= mDataBlock->upResistFactor * TickSec * (mVelocity.z - mDataBlock->upResistSpeed);
  2739. }
  2740. // Container buoyancy & drag
  2741. /* Commented out until the buoyancy calculation can be reworked so that a container and
  2742. ** player with the same density will result in neutral buoyancy.
  2743. if (mBuoyancy != 0)
  2744. {
  2745. // Applying buoyancy when standing still causing some jitters-
  2746. if (mBuoyancy > 1.0 || !mVelocity.isZero() || !runSurface)
  2747. {
  2748. // A little hackery to prevent oscillation
  2749. // based on http://reinot.blogspot.com/2005/11/oh-yes-they-float-georgie-they-all.html
  2750. F32 buoyancyForce = mBuoyancy * mGravity * mGravityMod * TickSec;
  2751. F32 currHeight = getPosition().z;
  2752. const F32 C = 2.0f;
  2753. const F32 M = 0.1f;
  2754. if ( currHeight + mVelocity.z * TickSec * C > mLiquidHeight )
  2755. buoyancyForce *= M;
  2756. mVelocity.z -= buoyancyForce;
  2757. }
  2758. }
  2759. */
  2760. // Apply drag
  2761. if ( mSwimming )
  2762. mVelocity -= mVelocity * mDrag * TickSec * ( mVelocity.len() / mDataBlock->maxUnderwaterForwardSpeed );
  2763. else
  2764. mVelocity -= mVelocity * mDrag * TickSec;
  2765. // Clamp very small velocity to zero
  2766. if ( mVelocity.isZero() )
  2767. mVelocity = Point3F::Zero;
  2768. // If we are not touching anything and have sufficient -z vel,
  2769. // we are falling.
  2770. if (runSurface)
  2771. mFalling = false;
  2772. else
  2773. {
  2774. VectorF vel;
  2775. mWorldToObj.mulV(mVelocity,&vel);
  2776. mFalling = vel.z < mDataBlock->fallingSpeedThreshold;
  2777. }
  2778. // Vehicle Dismount
  2779. if ( !isGhost() && move->trigger[sVehicleDismountTrigger] && canJump())
  2780. mDataBlock->doDismount_callback( this );
  2781. // Enter/Leave Liquid
  2782. if ( !mInWater && mWaterCoverage > 0.0f )
  2783. {
  2784. mInWater = true;
  2785. if ( !isGhost() )
  2786. mDataBlock->onEnterLiquid_callback( this, mWaterCoverage, mLiquidType.c_str() );
  2787. }
  2788. else if ( mInWater && mWaterCoverage <= 0.0f )
  2789. {
  2790. mInWater = false;
  2791. if ( !isGhost() )
  2792. mDataBlock->onLeaveLiquid_callback( this, mLiquidType.c_str() );
  2793. else
  2794. {
  2795. // exit-water splash sound happens for client only
  2796. if ( getSpeed() >= mDataBlock->exitSplashSoundVel && !isMounted() )
  2797. SFX->playOnce( mDataBlock->sound[PlayerData::ExitWater], &getTransform() );
  2798. }
  2799. }
  2800. // Update the PlayerPose
  2801. Pose desiredPose = mPose;
  2802. if ( !mIsAiControlled )
  2803. {
  2804. if ( mSwimming )
  2805. desiredPose = SwimPose;
  2806. else if ( runSurface && move->trigger[sCrouchTrigger] && canCrouch() )
  2807. desiredPose = CrouchPose;
  2808. else if ( runSurface && move->trigger[sProneTrigger] && canProne() )
  2809. desiredPose = PronePose;
  2810. else if ( move->trigger[sSprintTrigger] && canSprint() )
  2811. desiredPose = SprintPose;
  2812. else if ( canStand() )
  2813. desiredPose = StandPose;
  2814. setPose( desiredPose );
  2815. }
  2816. }
  2817. //----------------------------------------------------------------------------
  2818. bool Player::checkDismountPosition(const MatrixF& oldMat, const MatrixF& mat)
  2819. {
  2820. AssertFatal(getContainer() != NULL, "Error, must have a container!");
  2821. AssertFatal(getObjectMount() != NULL, "Error, must be mounted!");
  2822. Point3F pos;
  2823. Point3F oldPos;
  2824. mat.getColumn(3, &pos);
  2825. oldMat.getColumn(3, &oldPos);
  2826. RayInfo info;
  2827. disableCollision();
  2828. getObjectMount()->disableCollision();
  2829. if (getContainer()->castRay(oldPos, pos, sCollisionMoveMask, &info))
  2830. {
  2831. enableCollision();
  2832. getObjectMount()->enableCollision();
  2833. return false;
  2834. }
  2835. Box3F wBox = mObjBox;
  2836. wBox.minExtents += pos;
  2837. wBox.maxExtents += pos;
  2838. EarlyOutPolyList polyList;
  2839. polyList.mNormal.set(0.0f, 0.0f, 0.0f);
  2840. polyList.mPlaneList.clear();
  2841. polyList.mPlaneList.setSize(6);
  2842. polyList.mPlaneList[0].set(wBox.minExtents,VectorF(-1.0f, 0.0f, 0.0f));
  2843. polyList.mPlaneList[1].set(wBox.maxExtents,VectorF(0.0f, 1.0f, 0.0f));
  2844. polyList.mPlaneList[2].set(wBox.maxExtents,VectorF(1.0f, 0.0f, 0.0f));
  2845. polyList.mPlaneList[3].set(wBox.minExtents,VectorF(0.0f, -1.0f, 0.0f));
  2846. polyList.mPlaneList[4].set(wBox.minExtents,VectorF(0.0f, 0.0f, -1.0f));
  2847. polyList.mPlaneList[5].set(wBox.maxExtents,VectorF(0.0f, 0.0f, 1.0f));
  2848. if (getContainer()->buildPolyList(PLC_Collision, wBox, sCollisionMoveMask, &polyList))
  2849. {
  2850. enableCollision();
  2851. getObjectMount()->enableCollision();
  2852. return false;
  2853. }
  2854. enableCollision();
  2855. getObjectMount()->enableCollision();
  2856. return true;
  2857. }
  2858. //----------------------------------------------------------------------------
  2859. bool Player::canJump()
  2860. {
  2861. return mAllowJumping && mState == MoveState && mDamageState == Enabled && !isMounted() && !mJumpDelay && mEnergy >= mDataBlock->minJumpEnergy && mJumpSurfaceLastContact < JumpSkipContactsMax && !mSwimming && (mPose != SprintPose || mDataBlock->sprintCanJump);
  2862. }
  2863. bool Player::canJetJump()
  2864. {
  2865. return mAllowJetJumping && mState == MoveState && mDamageState == Enabled && !isMounted() && mEnergy >= mDataBlock->jetMinJumpEnergy && mDataBlock->jetJumpForce != 0.0f;
  2866. }
  2867. bool Player::canSwim()
  2868. {
  2869. // Not used!
  2870. //return mState == MoveState && mDamageState == Enabled && !isMounted() && mEnergy >= mDataBlock->minSwimEnergy && mWaterCoverage >= 0.8f;
  2871. return mAllowSwimming;
  2872. }
  2873. bool Player::canCrouch()
  2874. {
  2875. if (!mAllowCrouching)
  2876. return false;
  2877. if ( mState != MoveState ||
  2878. mDamageState != Enabled ||
  2879. isMounted() ||
  2880. mSwimming ||
  2881. mFalling )
  2882. return false;
  2883. // Can't crouch if no crouch animation!
  2884. if ( mDataBlock->actionList[PlayerData::CrouchRootAnim].sequence == -1 )
  2885. return false;
  2886. // We are already in this pose, so don't test it again...
  2887. if ( mPose == CrouchPose )
  2888. return true;
  2889. // Do standard Torque physics test here!
  2890. if ( !mPhysicsRep )
  2891. {
  2892. F32 radius;
  2893. if ( mPose == PronePose )
  2894. radius = mDataBlock->proneBoxSize.z;
  2895. else
  2896. return true;
  2897. // use our X and Y dimentions on our boxsize as the radii for our search, and the difference between a standing position
  2898. // and the position we currently are in.
  2899. Point3F extent( mDataBlock->crouchBoxSize.x / 2, mDataBlock->crouchBoxSize.y / 2, mDataBlock->crouchBoxSize.z - radius );
  2900. Point3F position = getPosition();
  2901. position.z += radius;
  2902. // Use these radii to create a box that represents the difference between a standing position and the position
  2903. // we want to move into.
  2904. Box3F B(position - extent, position + extent, true);
  2905. EarlyOutPolyList polyList;
  2906. polyList.mPlaneList.clear();
  2907. polyList.mNormal.set( 0,0,0 );
  2908. polyList.mPlaneList.setSize( 6 );
  2909. polyList.mPlaneList[0].set( B.minExtents, VectorF( -1,0,0 ) );
  2910. polyList.mPlaneList[1].set( B.maxExtents, VectorF( 0,1,0 ) );
  2911. polyList.mPlaneList[2].set( B.maxExtents, VectorF( 1,0,0 ) );
  2912. polyList.mPlaneList[3].set( B.minExtents, VectorF( 0,-1,0 ) );
  2913. polyList.mPlaneList[4].set( B.minExtents, VectorF( 0,0,-1 ) );
  2914. polyList.mPlaneList[5].set( B.maxExtents, VectorF( 0,0,1 ) );
  2915. // If an object exists in this space, we must stay prone. Otherwise we are free to crouch.
  2916. return !getContainer()->buildPolyList( PLC_Collision, B, StaticShapeObjectType, &polyList );
  2917. }
  2918. return mPhysicsRep->testSpacials( getPosition(), mDataBlock->crouchBoxSize );
  2919. }
  2920. bool Player::canStand()
  2921. {
  2922. if ( mState != MoveState ||
  2923. mDamageState != Enabled ||
  2924. isMounted() ||
  2925. mSwimming )
  2926. return false;
  2927. // We are already in this pose, so don't test it again...
  2928. if ( mPose == StandPose )
  2929. return true;
  2930. // Do standard Torque physics test here!
  2931. if ( !mPhysicsRep )
  2932. {
  2933. F32 radius;
  2934. if (mPose == CrouchPose)
  2935. radius = mDataBlock->crouchBoxSize.z;
  2936. else if (mPose == PronePose)
  2937. radius = mDataBlock->proneBoxSize.z;
  2938. else
  2939. return true;
  2940. // use our X and Y dimentions on our boxsize as the radii for our search, and the difference between a standing position
  2941. // and the position we currently are in.
  2942. Point3F extent( mDataBlock->boxSize.x / 2, mDataBlock->boxSize.y / 2, mDataBlock->boxSize.z - radius );
  2943. Point3F position = getPosition();
  2944. position.z += radius;
  2945. // Use these radii to create a box that represents the difference between a standing position and the position
  2946. // we want to move into.
  2947. Box3F B(position - extent, position + extent, true);
  2948. EarlyOutPolyList polyList;
  2949. polyList.mPlaneList.clear();
  2950. polyList.mNormal.set(0,0,0);
  2951. polyList.mPlaneList.setSize(6);
  2952. polyList.mPlaneList[0].set(B.minExtents, VectorF(-1,0,0));
  2953. polyList.mPlaneList[1].set(B.maxExtents, VectorF(0,1,0));
  2954. polyList.mPlaneList[2].set(B.maxExtents, VectorF(1,0,0));
  2955. polyList.mPlaneList[3].set(B.minExtents, VectorF(0,-1,0));
  2956. polyList.mPlaneList[4].set(B.minExtents, VectorF(0,0,-1));
  2957. polyList.mPlaneList[5].set(B.maxExtents, VectorF(0,0,1));
  2958. // If an object exists in this space, we must stay crouched/prone. Otherwise we are free to stand.
  2959. return !getContainer()->buildPolyList(PLC_Collision, B, StaticShapeObjectType, &polyList);
  2960. }
  2961. return mPhysicsRep->testSpacials( getPosition(), mDataBlock->boxSize );
  2962. }
  2963. bool Player::canProne()
  2964. {
  2965. if (!mAllowProne)
  2966. return false;
  2967. if ( mState != MoveState ||
  2968. mDamageState != Enabled ||
  2969. isMounted() ||
  2970. mSwimming ||
  2971. mFalling )
  2972. return false;
  2973. // Can't go prone if no prone animation!
  2974. if ( mDataBlock->actionList[PlayerData::ProneRootAnim].sequence == -1 )
  2975. return false;
  2976. // Do standard Torque physics test here!
  2977. if ( !mPhysicsRep )
  2978. return true;
  2979. // We are already in this pose, so don't test it again...
  2980. if ( mPose == PronePose )
  2981. return true;
  2982. return mPhysicsRep->testSpacials( getPosition(), mDataBlock->proneBoxSize );
  2983. }
  2984. bool Player::canSprint()
  2985. {
  2986. return mAllowSprinting && mState == MoveState && mDamageState == Enabled && !isMounted() && mEnergy >= mDataBlock->minSprintEnergy && !mSwimming;
  2987. }
  2988. //----------------------------------------------------------------------------
  2989. void Player::updateDamageLevel()
  2990. {
  2991. if (!isGhost())
  2992. setDamageState((mDamage >= mDataBlock->maxDamage)? Disabled: Enabled);
  2993. if (mDamageThread)
  2994. mShapeInstance->setPos(mDamageThread, mDamage / mDataBlock->destroyedLevel);
  2995. }
  2996. void Player::updateDamageState()
  2997. {
  2998. // Become a corpse when we're disabled (dead).
  2999. if (mDamageState == Enabled) {
  3000. mTypeMask &= ~CorpseObjectType;
  3001. mTypeMask |= PlayerObjectType;
  3002. }
  3003. else {
  3004. mTypeMask &= ~PlayerObjectType;
  3005. mTypeMask |= CorpseObjectType;
  3006. }
  3007. Parent::updateDamageState();
  3008. }
  3009. //----------------------------------------------------------------------------
  3010. void Player::updateLookAnimation(F32 dt)
  3011. {
  3012. // If the preference setting overrideLookAnimation is true, the player's
  3013. // arm and head no longer animate according to the view direction. They
  3014. // are instead given fixed positions.
  3015. if (overrideLookAnimation)
  3016. {
  3017. if (mArmAnimation.thread)
  3018. mShapeInstance->setPos(mArmAnimation.thread, armLookOverridePos);
  3019. if (mHeadVThread)
  3020. mShapeInstance->setPos(mHeadVThread, headVLookOverridePos);
  3021. if (mHeadHThread)
  3022. mShapeInstance->setPos(mHeadHThread, headHLookOverridePos);
  3023. return;
  3024. }
  3025. // Calculate our interpolated head position.
  3026. Point3F renderHead = delta.head + delta.headVec * dt;
  3027. // Adjust look pos. This assumes that the animations match
  3028. // the min and max look angles provided in the datablock.
  3029. if (mArmAnimation.thread)
  3030. {
  3031. if(mControlObject)
  3032. {
  3033. mShapeInstance->setPos(mArmAnimation.thread,0.5f);
  3034. }
  3035. else
  3036. {
  3037. F32 d = mDataBlock->maxLookAngle - mDataBlock->minLookAngle;
  3038. F32 tp = (renderHead.x - mDataBlock->minLookAngle) / d;
  3039. mShapeInstance->setPos(mArmAnimation.thread,mClampF(tp,0,1));
  3040. }
  3041. }
  3042. if (mHeadVThread)
  3043. {
  3044. F32 d = mDataBlock->maxLookAngle - mDataBlock->minLookAngle;
  3045. F32 tp = (renderHead.x - mDataBlock->minLookAngle) / d;
  3046. mShapeInstance->setPos(mHeadVThread,mClampF(tp,0,1));
  3047. }
  3048. if (mHeadHThread)
  3049. {
  3050. F32 d = 2 * mDataBlock->maxFreelookAngle;
  3051. F32 tp = (renderHead.z + mDataBlock->maxFreelookAngle) / d;
  3052. mShapeInstance->setPos(mHeadHThread,mClampF(tp,0,1));
  3053. }
  3054. }
  3055. //----------------------------------------------------------------------------
  3056. // Methods to get delta (as amount to affect velocity by)
  3057. bool Player::inDeathAnim()
  3058. {
  3059. if ((anim_clip_flags & ANIM_OVERRIDDEN) != 0 && (anim_clip_flags & IS_DEATH_ANIM) == 0)
  3060. return false;
  3061. if (mActionAnimation.thread && mActionAnimation.action >= 0)
  3062. if (mActionAnimation.action < mDataBlock->actionCount)
  3063. return mDataBlock->actionList[mActionAnimation.action].death;
  3064. return false;
  3065. }
  3066. // Get change from mLastDeathPos - return current pos. Assumes we're in death anim.
  3067. F32 Player::deathDelta(Point3F & delta)
  3068. {
  3069. // Get ground delta from the last time we offset this.
  3070. MatrixF mat;
  3071. F32 pos = mShapeInstance->getPos(mActionAnimation.thread);
  3072. mShapeInstance->deltaGround1(mActionAnimation.thread, mDeath.lastPos, pos, mat);
  3073. mat.getColumn(3, & delta);
  3074. return pos;
  3075. }
  3076. // Called before updatePos() to prepare it's needed change to velocity, which
  3077. // must roll over. Should be updated on tick, this is where we remember last
  3078. // position of animation that was used to roll into velocity.
  3079. void Player::updateDeathOffsets()
  3080. {
  3081. if (inDeathAnim())
  3082. // Get ground delta from the last time we offset this.
  3083. mDeath.lastPos = deathDelta(mDeath.posAdd);
  3084. else
  3085. mDeath.clear();
  3086. }
  3087. //----------------------------------------------------------------------------
  3088. static const U32 sPlayerConformMask = StaticShapeObjectType | StaticObjectType | TerrainObjectType;
  3089. static void accel(F32& from, F32 to, F32 rate)
  3090. {
  3091. if (from < to)
  3092. from = getMin(from += rate, to);
  3093. else
  3094. from = getMax(from -= rate, to);
  3095. }
  3096. // if (dt == -1)
  3097. // normal tick, so we advance.
  3098. // else
  3099. // interpolate with dt as % of tick, don't advance
  3100. //
  3101. MatrixF * Player::Death::fallToGround(F32 dt, const Point3F& loc, F32 curZ, F32 boxRad)
  3102. {
  3103. static const F32 sConformCheckDown = 4.0f;
  3104. RayInfo coll;
  3105. bool conformToStairs = false;
  3106. Point3F pos(loc.x, loc.y, loc.z + 0.1f);
  3107. Point3F below(pos.x, pos.y, loc.z - sConformCheckDown);
  3108. MatrixF * retVal = NULL;
  3109. PROFILE_SCOPE(ConformToGround);
  3110. if (gClientContainer.castRay(pos, below, sPlayerConformMask, &coll))
  3111. {
  3112. F32 adjust, height = (loc.z - coll.point.z), sink = curSink;
  3113. VectorF desNormal = coll.normal;
  3114. VectorF normal = curNormal;
  3115. // dt >= 0 means we're interpolating and don't accel the numbers
  3116. if (dt >= 0.0f)
  3117. adjust = dt * TickSec;
  3118. else
  3119. adjust = TickSec;
  3120. // Try to get them to conform to stairs by doing several LOS calls. We do this if
  3121. // normal is within about 5 deg. of vertical.
  3122. if (desNormal.z > 0.995f)
  3123. {
  3124. Point3F corners[3], downpts[3];
  3125. S32 c;
  3126. for (c = 0; c < 3; c++) { // Build 3 corners to cast down from-
  3127. corners[c].set(loc.x - boxRad, loc.y - boxRad, loc.z + 1.0f);
  3128. if (c) // add (0,boxWidth) and (boxWidth,0)
  3129. corners[c][c - 1] += (boxRad * 2.0f);
  3130. downpts[c].set(corners[c].x, corners[c].y, loc.z - sConformCheckDown);
  3131. }
  3132. // Do the three casts-
  3133. for (c = 0; c < 3; c++)
  3134. if (gClientContainer.castRay(corners[c], downpts[c], sPlayerConformMask, &coll))
  3135. downpts[c] = coll.point;
  3136. else
  3137. break;
  3138. // Do the math if everything hit below-
  3139. if (c == 3) {
  3140. mCross(downpts[1] - downpts[0], downpts[2] - downpts[1], &desNormal);
  3141. AssertFatal(desNormal.z > 0, "Abnormality in Player::Death::fallToGround()");
  3142. downpts[2] = downpts[2] - downpts[1];
  3143. downpts[1] = downpts[1] - downpts[0];
  3144. desNormal.normalize();
  3145. conformToStairs = true;
  3146. }
  3147. }
  3148. // Move normal in direction we want-
  3149. F32 * cur = normal, * des = desNormal;
  3150. for (S32 i = 0; i < 3; i++)
  3151. accel(*cur++, *des++, adjust * 0.25f);
  3152. if (mFabs(height) < 2.2f && !normal.isZero() && desNormal.z > 0.01f)
  3153. {
  3154. VectorF upY(0.0f, 1.0f, 0.0f), ahead;
  3155. VectorF sideVec;
  3156. MatrixF mat(true);
  3157. normal.normalize();
  3158. mat.set(EulerF (0.0f, 0.0f, curZ));
  3159. mat.mulV(upY, & ahead);
  3160. mCross(ahead, normal, &sideVec);
  3161. sideVec.normalize();
  3162. mCross(normal, sideVec, &ahead);
  3163. static MatrixF resMat(true);
  3164. resMat.setColumn(0, sideVec);
  3165. resMat.setColumn(1, ahead);
  3166. resMat.setColumn(2, normal);
  3167. // Adjust Z down to account for box offset on slope. Figure out how
  3168. // much we want to sink, and gradually accel to this amount. Don't do if
  3169. // we're conforming to stairs though
  3170. F32 xy = mSqrt(desNormal.x * desNormal.x + desNormal.y * desNormal.y);
  3171. F32 desiredSink = (boxRad * xy / desNormal.z);
  3172. if (conformToStairs)
  3173. desiredSink *= 0.5f;
  3174. accel(sink, desiredSink, adjust * 0.15f);
  3175. Point3F position(pos);
  3176. position.z -= sink;
  3177. resMat.setColumn(3, position);
  3178. if (dt < 0.0f)
  3179. { // we're moving, so update normal and sink amount
  3180. curNormal = normal;
  3181. curSink = sink;
  3182. }
  3183. retVal = &resMat;
  3184. }
  3185. }
  3186. return retVal;
  3187. }
  3188. //-------------------------------------------------------------------------------------
  3189. // This is called ::onAdd() to see if we're in a sitting animation. These then
  3190. // can use a longer tick delay for the mount to get across.
  3191. bool Player::inSittingAnim()
  3192. {
  3193. U32 action = mActionAnimation.action;
  3194. if (mActionAnimation.thread && action < mDataBlock->actionCount) {
  3195. const char * name = mDataBlock->actionList[action].name;
  3196. if (!dStricmp(name, "Sitting") || !dStricmp(name, "Scoutroot"))
  3197. return true;
  3198. }
  3199. return false;
  3200. }
  3201. //----------------------------------------------------------------------------
  3202. const String& Player::getArmThread() const
  3203. {
  3204. if (mArmAnimation.thread && mArmAnimation.thread->hasSequence())
  3205. {
  3206. return mArmAnimation.thread->getSequenceName();
  3207. }
  3208. return String::EmptyString;
  3209. }
  3210. bool Player::setArmThread(const char* sequence)
  3211. {
  3212. // The arm sequence must be in the action list.
  3213. for (U32 i = 1; i < mDataBlock->actionCount; i++)
  3214. if (!dStricmp(mDataBlock->actionList[i].name,sequence))
  3215. return setArmThread(i);
  3216. return false;
  3217. }
  3218. bool Player::setArmThread(U32 action)
  3219. {
  3220. PlayerData::ActionAnimation &anim = mDataBlock->actionList[action];
  3221. if (anim.sequence != -1 &&
  3222. anim.sequence != mShapeInstance->getSequence(mArmAnimation.thread))
  3223. {
  3224. mShapeInstance->setSequence(mArmAnimation.thread,anim.sequence,0);
  3225. mArmAnimation.action = action;
  3226. setMaskBits(ActionMask);
  3227. return true;
  3228. }
  3229. return false;
  3230. }
  3231. //----------------------------------------------------------------------------
  3232. bool Player::setActionThread(const char* sequence,bool hold,bool wait,bool fsp)
  3233. {
  3234. if (anim_clip_flags & ANIM_OVERRIDDEN)
  3235. return false;
  3236. for (U32 i = 1; i < mDataBlock->actionCount; i++)
  3237. {
  3238. PlayerData::ActionAnimation &anim = mDataBlock->actionList[i];
  3239. if (!dStricmp(anim.name,sequence))
  3240. {
  3241. setActionThread(i,true,hold,wait,fsp);
  3242. setMaskBits(ActionMask);
  3243. return true;
  3244. }
  3245. }
  3246. return false;
  3247. }
  3248. void Player::setActionThread(U32 action,bool forward,bool hold,bool wait,bool fsp, bool forceSet)
  3249. {
  3250. if (!mDataBlock || !mDataBlock->actionCount || (mActionAnimation.action == action && mActionAnimation.forward == forward && !forceSet))
  3251. return;
  3252. if (action >= PlayerData::NumActionAnims)
  3253. {
  3254. Con::errorf("Player::setActionThread(%d): Player action out of range", action);
  3255. return;
  3256. }
  3257. if (isClientObject())
  3258. {
  3259. mark_idle = (action == PlayerData::RootAnim);
  3260. idle_timer = (mark_idle) ? 0.0f : -1.0f;
  3261. }
  3262. PlayerData::ActionAnimation &anim = mDataBlock->actionList[action];
  3263. if (anim.sequence != -1)
  3264. {
  3265. U32 lastAction = mActionAnimation.action;
  3266. mActionAnimation.action = action;
  3267. mActionAnimation.forward = forward;
  3268. mActionAnimation.firstPerson = fsp;
  3269. mActionAnimation.holdAtEnd = hold;
  3270. mActionAnimation.waitForEnd = hold? true: wait;
  3271. mActionAnimation.animateOnServer = fsp;
  3272. mActionAnimation.atEnd = false;
  3273. mActionAnimation.delayTicks = (S32)sNewAnimationTickTime;
  3274. mActionAnimation.atEnd = false;
  3275. if (sUseAnimationTransitions && (action != PlayerData::LandAnim || !(mDataBlock->landSequenceTime > 0.0f && !mDataBlock->transitionToLand)) && (isGhost()/* || mActionAnimation.animateOnServer*/))
  3276. {
  3277. // The transition code needs the timeScale to be set in the
  3278. // right direction to know which way to go.
  3279. F32 transTime = sAnimationTransitionTime;
  3280. if (mDataBlock && mDataBlock->isJumpAction(action))
  3281. transTime = 0.15f;
  3282. F32 timeScale = mActionAnimation.forward ? 1.0f : -1.0f;
  3283. if (mDataBlock && mDataBlock->isJumpAction(action))
  3284. timeScale *= 1.5f;
  3285. mShapeInstance->setTimeScale(mActionAnimation.thread,timeScale);
  3286. S32 seq = anim.sequence;
  3287. S32 imageBasedSeq = convertActionToImagePrefix(mActionAnimation.action);
  3288. if (imageBasedSeq != -1)
  3289. seq = imageBasedSeq;
  3290. // If we're transitioning into the same sequence (an action may use the
  3291. // same sequence as a previous action) then we want to start at the same
  3292. // position.
  3293. F32 pos = mActionAnimation.forward ? 0.0f : 1.0f;
  3294. PlayerData::ActionAnimation &lastAnim = mDataBlock->actionList[lastAction];
  3295. if (lastAnim.sequence == anim.sequence)
  3296. {
  3297. pos = mShapeInstance->getPos(mActionAnimation.thread);
  3298. }
  3299. mShapeInstance->transitionToSequence(mActionAnimation.thread,seq,
  3300. pos, transTime, true);
  3301. }
  3302. else
  3303. {
  3304. S32 seq = anim.sequence;
  3305. S32 imageBasedSeq = convertActionToImagePrefix(mActionAnimation.action);
  3306. if (imageBasedSeq != -1)
  3307. seq = imageBasedSeq;
  3308. mShapeInstance->setSequence(mActionAnimation.thread,seq,
  3309. mActionAnimation.forward ? 0.0f : 1.0f);
  3310. }
  3311. }
  3312. }
  3313. void Player::updateActionThread()
  3314. {
  3315. PROFILE_START(UpdateActionThread);
  3316. // Select an action animation sequence, this assumes that
  3317. // this function is called once per tick.
  3318. if(mActionAnimation.action != PlayerData::NullAnimation)
  3319. {
  3320. if (mActionAnimation.forward)
  3321. mActionAnimation.atEnd = mShapeInstance->getPos(mActionAnimation.thread) == 1;
  3322. else
  3323. mActionAnimation.atEnd = mShapeInstance->getPos(mActionAnimation.thread) == 0;
  3324. }
  3325. // Only need to deal with triggers on the client
  3326. if( isGhost() )
  3327. {
  3328. bool triggeredLeft = false;
  3329. bool triggeredRight = false;
  3330. F32 offset = 0.0f;
  3331. if( mShapeInstance->getTriggerState( 1 ) )
  3332. {
  3333. triggeredLeft = true;
  3334. offset = -mDataBlock->decalOffset * getScale().x;
  3335. }
  3336. else if(mShapeInstance->getTriggerState( 2 ) )
  3337. {
  3338. triggeredRight = true;
  3339. offset = mDataBlock->decalOffset * getScale().x;
  3340. }
  3341. process_client_triggers(triggeredLeft, triggeredRight);
  3342. if ((triggeredLeft || triggeredRight) && !noFootfallFX)
  3343. {
  3344. Point3F rot, pos;
  3345. RayInfo rInfo;
  3346. MatrixF mat = getRenderTransform();
  3347. mat.getColumn( 1, &rot );
  3348. mat.mulP( Point3F( offset, 0.0f, 0.0f), &pos );
  3349. if( gClientContainer.castRay( Point3F( pos.x, pos.y, pos.z + 0.01f ),
  3350. Point3F( pos.x, pos.y, pos.z - 2.0f ),
  3351. STATIC_COLLISION_TYPEMASK | VehicleObjectType, &rInfo ) )
  3352. {
  3353. Material* material = ( rInfo.material ? dynamic_cast< Material* >( rInfo.material->getMaterial() ) : 0 );
  3354. // Put footprints on surface, if appropriate for material.
  3355. if( material && material->mShowFootprints
  3356. && mDataBlock->decalData && !footfallDecalOverride )
  3357. {
  3358. Point3F normal;
  3359. Point3F tangent;
  3360. mObjToWorld.getColumn( 0, &tangent );
  3361. mObjToWorld.getColumn( 2, &normal );
  3362. gDecalManager->addDecal( rInfo.point, normal, tangent, mDataBlock->decalData, getScale().y );
  3363. }
  3364. // Emit footpuffs.
  3365. if (!footfallDustOverride && rInfo.t <= 0.5f && mWaterCoverage == 0.0f
  3366. && material && material->mShowDust )
  3367. {
  3368. // New emitter every time for visibility reasons
  3369. ParticleEmitter * emitter = new ParticleEmitter;
  3370. emitter->onNewDataBlock( mDataBlock->footPuffEmitter, false );
  3371. LinearColorF colorList[ ParticleData::PDC_NUM_KEYS];
  3372. for( U32 x = 0; x < getMin( Material::NUM_EFFECT_COLOR_STAGES, ParticleData::PDC_NUM_KEYS ); ++ x )
  3373. colorList[ x ].set( material->mEffectColor[ x ].red,
  3374. material->mEffectColor[ x ].green,
  3375. material->mEffectColor[ x ].blue,
  3376. material->mEffectColor[ x ].alpha );
  3377. for( U32 x = Material::NUM_EFFECT_COLOR_STAGES; x < ParticleData::PDC_NUM_KEYS; ++ x )
  3378. colorList[ x ].set( 1.0, 1.0, 1.0, 0.0 );
  3379. emitter->setColors( colorList );
  3380. if( !emitter->registerObject() )
  3381. {
  3382. Con::warnf( ConsoleLogEntry::General, "Could not register emitter for particle of class: %s", mDataBlock->getName() );
  3383. delete emitter;
  3384. emitter = NULL;
  3385. }
  3386. else
  3387. {
  3388. emitter->emitParticles( pos, Point3F( 0.0, 0.0, 1.0 ), mDataBlock->footPuffRadius,
  3389. Point3F( 0, 0, 0 ), mDataBlock->footPuffNumParts );
  3390. emitter->deleteWhenEmpty();
  3391. }
  3392. }
  3393. // Play footstep sound.
  3394. if (footfallSoundOverride <= 0)
  3395. playFootstepSound( triggeredLeft, material, rInfo.object );
  3396. }
  3397. }
  3398. }
  3399. // Mount pending variable puts a hold on the delayTicks below so players don't
  3400. // inadvertently stand up because their mount has not come over yet.
  3401. if (mMountPending)
  3402. mMountPending = (isMounted() ? 0 : (mMountPending - 1));
  3403. if ((mActionAnimation.action == PlayerData::NullAnimation) ||
  3404. ((!mActionAnimation.waitForEnd || mActionAnimation.atEnd) &&
  3405. (!mActionAnimation.holdAtEnd && (mActionAnimation.delayTicks -= !mMountPending) <= 0)))
  3406. {
  3407. //The scripting language will get a call back when a script animation has finished...
  3408. // example: When the chat menu animations are done playing...
  3409. if ( isServerObject() && mActionAnimation.action >= PlayerData::NumTableActionAnims )
  3410. mDataBlock->animationDone_callback( this );
  3411. pickActionAnimation();
  3412. }
  3413. // prevent scaling of AFX picked actions
  3414. if ( (mActionAnimation.action != PlayerData::LandAnim) &&
  3415. (mActionAnimation.action != PlayerData::NullAnimation) &&
  3416. !(anim_clip_flags & ANIM_OVERRIDDEN))
  3417. {
  3418. // Update action animation time scale to match ground velocity
  3419. PlayerData::ActionAnimation &anim =
  3420. mDataBlock->actionList[mActionAnimation.action];
  3421. F32 scale = 1;
  3422. if (anim.velocityScale && anim.speed) {
  3423. VectorF vel;
  3424. mWorldToObj.mulV(mVelocity,&vel);
  3425. scale = mFabs(mDot(vel, anim.dir) / anim.speed);
  3426. if (scale > mDataBlock->maxTimeScale)
  3427. scale = mDataBlock->maxTimeScale;
  3428. }
  3429. mShapeInstance->setTimeScale(mActionAnimation.thread,
  3430. mActionAnimation.forward? scale: -scale);
  3431. }
  3432. PROFILE_END();
  3433. }
  3434. void Player::pickBestMoveAction(U32 startAnim, U32 endAnim, U32 * action, bool * forward) const
  3435. {
  3436. *action = startAnim;
  3437. *forward = false;
  3438. VectorF vel;
  3439. mWorldToObj.mulV(mVelocity,&vel);
  3440. if (vel.lenSquared() > 0.01f)
  3441. {
  3442. // Bias the velocity towards picking the forward/backward anims over
  3443. // the sideways ones to prevent oscillation between anims.
  3444. vel *= VectorF(0.5f, 1.0f, 0.5f);
  3445. // Pick animation that is the best fit for our current (local) velocity.
  3446. // Assumes that the root (stationary) animation is at startAnim.
  3447. F32 curMax = -0.1f;
  3448. for (U32 i = startAnim+1; i <= endAnim; i++)
  3449. {
  3450. const PlayerData::ActionAnimation &anim = mDataBlock->actionList[i];
  3451. if (anim.sequence != -1 && anim.speed)
  3452. {
  3453. F32 d = mDot(vel, anim.dir);
  3454. if (d > curMax)
  3455. {
  3456. curMax = d;
  3457. *action = i;
  3458. *forward = true;
  3459. }
  3460. else
  3461. {
  3462. // Check if reversing this animation would fit (bias against this
  3463. // so that when moving right, the real right anim is still chosen,
  3464. // but if not present, the reversed left anim will be used instead)
  3465. d *= -0.75f;
  3466. if (d > curMax)
  3467. {
  3468. curMax = d;
  3469. *action = i;
  3470. *forward = false;
  3471. }
  3472. }
  3473. }
  3474. }
  3475. }
  3476. }
  3477. void Player::pickActionAnimation()
  3478. {
  3479. // Only select animations in our normal move state.
  3480. if (mState != MoveState || mDamageState != Enabled)
  3481. return;
  3482. if (isMounted() || mMountPending)
  3483. {
  3484. // Go into root position unless something was set explicitly
  3485. // from a script.
  3486. if (mActionAnimation.action != PlayerData::RootAnim &&
  3487. mActionAnimation.action < PlayerData::NumTableActionAnims)
  3488. setActionThread(PlayerData::RootAnim,true,false,false);
  3489. return;
  3490. }
  3491. bool forward = true;
  3492. U32 action = PlayerData::RootAnim;
  3493. bool fsp = false;
  3494. // Jetting overrides the fall animation condition
  3495. if (mJetting)
  3496. {
  3497. // Play the jetting animation
  3498. action = PlayerData::JetAnim;
  3499. }
  3500. else if (mFalling)
  3501. {
  3502. // Not in contact with any surface and falling
  3503. action = PlayerData::FallAnim;
  3504. }
  3505. else if ( mSwimming )
  3506. {
  3507. pickBestMoveAction(PlayerData::SwimRootAnim, PlayerData::SwimRightAnim, &action, &forward);
  3508. }
  3509. else if ( mPose == StandPose )
  3510. {
  3511. if (mContactTimer >= sContactTickTime)
  3512. {
  3513. // Nothing under our feet
  3514. action = PlayerData::RootAnim;
  3515. }
  3516. else
  3517. {
  3518. // Our feet are on something
  3519. pickBestMoveAction(PlayerData::RootAnim, PlayerData::SideRightAnim, &action, &forward);
  3520. }
  3521. }
  3522. else if ( mPose == CrouchPose )
  3523. {
  3524. pickBestMoveAction(PlayerData::CrouchRootAnim, PlayerData::CrouchRightAnim, &action, &forward);
  3525. }
  3526. else if ( mPose == PronePose )
  3527. {
  3528. pickBestMoveAction(PlayerData::ProneRootAnim, PlayerData::ProneBackwardAnim, &action, &forward);
  3529. }
  3530. else if ( mPose == SprintPose )
  3531. {
  3532. pickBestMoveAction(PlayerData::SprintRootAnim, PlayerData::SprintRightAnim, &action, &forward);
  3533. }
  3534. setActionThread(action,forward,false,false,fsp);
  3535. }
  3536. void Player::onImage(U32 imageSlot, bool unmount)
  3537. {
  3538. // Update 3rd person sequences based on images used. Start be getting a
  3539. // list of all possible image prefix sequences.
  3540. String prefixPaths[ShapeBase::MaxMountedImages];
  3541. buildImagePrefixPaths(prefixPaths);
  3542. // Clear out any previous image state animation
  3543. if (mImageStateThread)
  3544. {
  3545. mShapeInstance->destroyThread(mImageStateThread);
  3546. mImageStateThread = 0;
  3547. }
  3548. // Attempt to update the action thread
  3549. U32 action = mActionAnimation.action;
  3550. if (action != PlayerData::NullAnimation)
  3551. {
  3552. String actionSeq = mDataBlock->actionList[action].name;
  3553. if (actionSeq.isNotEmpty())
  3554. {
  3555. S32 seqIndex = mDataBlock->actionList[action].sequence;
  3556. S32 prefixIndex = findPrefixSequence(prefixPaths, actionSeq);
  3557. if (prefixIndex != -1)
  3558. {
  3559. seqIndex = prefixIndex;
  3560. }
  3561. // Only change the sequence if it isn't already playing.
  3562. if (seqIndex != mShapeInstance->getSequence(mActionAnimation.thread))
  3563. {
  3564. F32 pos = mShapeInstance->getPos(mActionAnimation.thread);
  3565. mShapeInstance->setSequence(mActionAnimation.thread, seqIndex, pos);
  3566. }
  3567. }
  3568. }
  3569. // Attempt to update the arm thread
  3570. U32 armAction = getArmAction();
  3571. if (armAction != PlayerData::NullAnimation)
  3572. {
  3573. String armSeq = mDataBlock->actionList[armAction].name;
  3574. if (armSeq.isNotEmpty())
  3575. {
  3576. S32 seqIndex = mDataBlock->actionList[armAction].sequence;
  3577. S32 prefixIndex = findPrefixSequence(prefixPaths, armSeq);
  3578. if (prefixIndex != -1)
  3579. {
  3580. seqIndex = prefixIndex;
  3581. }
  3582. // Only change the sequence if it isn't already playing.
  3583. if (seqIndex != mShapeInstance->getSequence(mArmAnimation.thread))
  3584. {
  3585. F32 pos = mShapeInstance->getPos(mArmAnimation.thread);
  3586. mShapeInstance->setSequence(mArmAnimation.thread, seqIndex, pos);
  3587. }
  3588. }
  3589. }
  3590. // Attempt to update the head threads
  3591. if (mHeadVThread)
  3592. {
  3593. TSShape const* shape = mShapeInstance->getShape();
  3594. S32 seqIndex = shape->findSequence("head");
  3595. S32 prefixIndex = findPrefixSequence(prefixPaths, "head");
  3596. if (prefixIndex != -1)
  3597. {
  3598. seqIndex = prefixIndex;
  3599. }
  3600. // Only change the sequence if it isn't already playing.
  3601. if (seqIndex != mShapeInstance->getSequence(mHeadVThread))
  3602. {
  3603. F32 pos = mShapeInstance->getPos(mHeadVThread);
  3604. mShapeInstance->setSequence(mHeadVThread, seqIndex, pos);
  3605. }
  3606. }
  3607. if (mHeadHThread)
  3608. {
  3609. TSShape const* shape = mShapeInstance->getShape();
  3610. S32 seqIndex = shape->findSequence("headside");
  3611. S32 prefixIndex = findPrefixSequence(prefixPaths, "headside");
  3612. if (prefixIndex != -1)
  3613. {
  3614. seqIndex = prefixIndex;
  3615. }
  3616. // Only change the sequence if it isn't already playing.
  3617. if (seqIndex != mShapeInstance->getSequence(mHeadHThread))
  3618. {
  3619. F32 pos = mShapeInstance->getPos(mHeadHThread);
  3620. mShapeInstance->setSequence(mHeadHThread, seqIndex, pos);
  3621. }
  3622. }
  3623. }
  3624. void Player::buildImagePrefixPaths(String* prefixPaths)
  3625. {
  3626. // We begin obtaining the anim prefix for each image.
  3627. String prefix[ShapeBase::MaxMountedImages];
  3628. for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
  3629. {
  3630. MountedImage& image = mMountedImageList[i];
  3631. if (image.dataBlock && image.dataBlock->imageAnimPrefix && image.dataBlock->imageAnimPrefix[0])
  3632. {
  3633. prefix[i] = String(image.dataBlock->imageAnimPrefix);
  3634. }
  3635. }
  3636. // Build out the full prefix names we will be searching for.
  3637. S32 counter = ShapeBase::MaxMountedImages-1;
  3638. for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
  3639. {
  3640. // Only build out the prefix path for images that have a defined prefix.
  3641. if (prefix[i].isNotEmpty())
  3642. {
  3643. bool start = true;
  3644. for (U32 j=0; j<=i; ++j)
  3645. {
  3646. if (prefix[j].isNotEmpty())
  3647. {
  3648. if (!start)
  3649. {
  3650. prefixPaths[counter] += "_";
  3651. }
  3652. else
  3653. {
  3654. start = false;
  3655. }
  3656. prefixPaths[counter] += prefix[j];
  3657. }
  3658. }
  3659. }
  3660. -- counter;
  3661. }
  3662. }
  3663. S32 Player::findPrefixSequence(String* prefixPaths, const String& baseSeq)
  3664. {
  3665. // Go through the prefix list. If we find a match then return the sequence
  3666. // index.
  3667. for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
  3668. {
  3669. if (prefixPaths[i].isNotEmpty())
  3670. {
  3671. String seq = prefixPaths[i] + "_" + baseSeq;
  3672. S32 seqIndex = mShapeInstance->getShape()->findSequence(seq);
  3673. if (seqIndex != -1)
  3674. {
  3675. return seqIndex;
  3676. }
  3677. }
  3678. }
  3679. return -1;
  3680. }
  3681. S32 Player::convertActionToImagePrefix(U32 action)
  3682. {
  3683. String prefixPaths[ShapeBase::MaxMountedImages];
  3684. buildImagePrefixPaths(prefixPaths);
  3685. if (action != PlayerData::NullAnimation)
  3686. {
  3687. String actionSeq;
  3688. S32 seq = -1;
  3689. // We'll first attempt to find the action sequence by name
  3690. // as defined within the action list.
  3691. actionSeq = mDataBlock->actionList[action].name;
  3692. if (actionSeq.isNotEmpty())
  3693. {
  3694. seq = findPrefixSequence(prefixPaths, actionSeq);
  3695. }
  3696. if (seq == -1)
  3697. {
  3698. // Couldn't find a valid sequence. If this is a sprint action
  3699. // then we also need to search through the standard movement
  3700. // sequences.
  3701. if (action >= PlayerData::SprintRootAnim && action <= PlayerData::SprintRightAnim)
  3702. {
  3703. U32 standardAction = action - PlayerData::SprintRootAnim;
  3704. actionSeq = mDataBlock->actionList[standardAction].name;
  3705. if (actionSeq.isNotEmpty())
  3706. {
  3707. seq = findPrefixSequence(prefixPaths, actionSeq);
  3708. }
  3709. }
  3710. }
  3711. return seq;
  3712. }
  3713. return -1;
  3714. }
  3715. void Player::onImageRecoil( U32, ShapeBaseImageData::StateData::RecoilState state )
  3716. {
  3717. if ( mRecoilThread )
  3718. {
  3719. if ( state != ShapeBaseImageData::StateData::NoRecoil )
  3720. {
  3721. S32 stateIndex = state - ShapeBaseImageData::StateData::LightRecoil;
  3722. if ( mDataBlock->recoilSequence[stateIndex] != -1 )
  3723. {
  3724. mShapeInstance->setSequence( mRecoilThread, mDataBlock->recoilSequence[stateIndex], 0 );
  3725. mShapeInstance->setTimeScale( mRecoilThread, 1 );
  3726. }
  3727. }
  3728. }
  3729. }
  3730. void Player::onImageStateAnimation(U32 imageSlot, const char* seqName, bool direction, bool scaleToState, F32 stateTimeOutValue)
  3731. {
  3732. if (mDataBlock->allowImageStateAnimation && isGhost())
  3733. {
  3734. MountedImage& image = mMountedImageList[imageSlot];
  3735. // Just as with onImageAnimThreadChange we're going to apply various prefixes to determine the final sequence to use.
  3736. // Here is the order:
  3737. // imageBasePrefix_scriptPrefix_baseAnimName
  3738. // imageBasePrefix_baseAnimName
  3739. // scriptPrefix_baseAnimName
  3740. // baseAnimName
  3741. // Collect the prefixes
  3742. const char* imageBasePrefix = "";
  3743. bool hasImageBasePrefix = image.dataBlock && image.dataBlock->imageAnimPrefix && image.dataBlock->imageAnimPrefix[0];
  3744. if (hasImageBasePrefix)
  3745. imageBasePrefix = image.dataBlock->imageAnimPrefix;
  3746. const char* scriptPrefix = getImageScriptAnimPrefix(imageSlot).getString();
  3747. bool hasScriptPrefix = scriptPrefix && scriptPrefix[0];
  3748. S32 seqIndex = mShapeInstance->getShape()->findSequence(seqName);
  3749. // Find the final sequence based on the prefix combinations
  3750. if (hasImageBasePrefix || hasScriptPrefix)
  3751. {
  3752. bool found = false;
  3753. String baseSeqName(seqName);
  3754. if (!found && hasImageBasePrefix && hasScriptPrefix)
  3755. {
  3756. String seqName = String(imageBasePrefix) + String("_") + String(scriptPrefix) + String("_") + baseSeqName;
  3757. S32 index = mShapeInstance->getShape()->findSequence(seqName);
  3758. if (index != -1)
  3759. {
  3760. seqIndex = index;
  3761. found = true;
  3762. }
  3763. }
  3764. if (!found && hasImageBasePrefix)
  3765. {
  3766. String seqName = String(imageBasePrefix) + String("_") + baseSeqName;
  3767. S32 index = mShapeInstance->getShape()->findSequence(seqName);
  3768. if (index != -1)
  3769. {
  3770. seqIndex = index;
  3771. found = true;
  3772. }
  3773. }
  3774. if (!found && hasScriptPrefix)
  3775. {
  3776. String seqName = String(scriptPrefix) + String("_") + baseSeqName;
  3777. S32 index = mShapeInstance->getShape()->findSequence(seqName);
  3778. if (index != -1)
  3779. {
  3780. seqIndex = index;
  3781. found = true;
  3782. }
  3783. }
  3784. }
  3785. if (seqIndex != -1)
  3786. {
  3787. if (!mImageStateThread)
  3788. {
  3789. mImageStateThread = mShapeInstance->addThread();
  3790. }
  3791. mShapeInstance->setSequence( mImageStateThread, seqIndex, 0 );
  3792. F32 timeScale = (scaleToState && stateTimeOutValue) ?
  3793. mShapeInstance->getDuration(mImageStateThread) / stateTimeOutValue : 1.0f;
  3794. mShapeInstance->setTimeScale( mImageStateThread, direction ? timeScale : -timeScale );
  3795. }
  3796. }
  3797. }
  3798. const char* Player::getImageAnimPrefix(U32 imageSlot, S32 imageShapeIndex)
  3799. {
  3800. if (!mDataBlock)
  3801. return "";
  3802. switch (imageShapeIndex)
  3803. {
  3804. case ShapeBaseImageData::StandardImageShape:
  3805. {
  3806. return mDataBlock->imageAnimPrefix;
  3807. }
  3808. case ShapeBaseImageData::FirstPersonImageShape:
  3809. {
  3810. return mDataBlock->imageAnimPrefixFP;
  3811. }
  3812. default:
  3813. {
  3814. return "";
  3815. }
  3816. }
  3817. }
  3818. void Player::onImageAnimThreadChange(U32 imageSlot, S32 imageShapeIndex, ShapeBaseImageData::StateData* lastState, const char* anim, F32 pos, F32 timeScale, bool reset)
  3819. {
  3820. if (!mShapeFPInstance[imageSlot] || !mShapeFPAnimThread[imageSlot])
  3821. return;
  3822. MountedImage& image = mMountedImageList[imageSlot];
  3823. ShapeBaseImageData::StateData& stateData = *image.state;
  3824. if (reset)
  3825. {
  3826. // Reset cyclic sequences back to the first frame to turn it off
  3827. // (the first key frame should be it's off state).
  3828. if (mShapeFPAnimThread[imageSlot]->getSequence()->isCyclic() && (stateData.sequenceNeverTransition || !(stateData.sequenceTransitionIn || (lastState && lastState->sequenceTransitionOut))) )
  3829. {
  3830. mShapeFPInstance[imageSlot]->setPos(mShapeFPAnimThread[imageSlot],0);
  3831. mShapeFPInstance[imageSlot]->setTimeScale(mShapeFPAnimThread[imageSlot],0);
  3832. }
  3833. return;
  3834. }
  3835. // Just as with ShapeBase::udpateAnimThread we're going to apply various prefixes to determine the final sequence to use.
  3836. // Here is the order:
  3837. // imageBasePrefix_scriptPrefix_baseAnimName
  3838. // imageBasePrefix_baseAnimName
  3839. // scriptPrefix_baseAnimName
  3840. // baseAnimName
  3841. // Collect the prefixes
  3842. const char* imageBasePrefix = "";
  3843. bool hasImageBasePrefix = image.dataBlock && image.dataBlock->imageAnimPrefixFP && image.dataBlock->imageAnimPrefixFP[0];
  3844. if (hasImageBasePrefix)
  3845. imageBasePrefix = image.dataBlock->imageAnimPrefixFP;
  3846. const char* scriptPrefix = getImageScriptAnimPrefix(imageSlot).getString();
  3847. bool hasScriptPrefix = scriptPrefix && scriptPrefix[0];
  3848. S32 seqIndex = mShapeFPInstance[imageSlot]->getShape()->findSequence(anim);
  3849. // Find the final sequence based on the prefix combinations
  3850. if (hasImageBasePrefix || hasScriptPrefix)
  3851. {
  3852. bool found = false;
  3853. String baseSeqName(anim);
  3854. if (!found && hasImageBasePrefix && hasScriptPrefix)
  3855. {
  3856. String seqName = String(imageBasePrefix) + String("_") + String(scriptPrefix) + String("_") + baseSeqName;
  3857. S32 index = mShapeFPInstance[imageSlot]->getShape()->findSequence(seqName);
  3858. if (index != -1)
  3859. {
  3860. seqIndex = index;
  3861. found = true;
  3862. }
  3863. }
  3864. if (!found && hasImageBasePrefix)
  3865. {
  3866. String seqName = String(imageBasePrefix) + String("_") + baseSeqName;
  3867. S32 index = mShapeFPInstance[imageSlot]->getShape()->findSequence(seqName);
  3868. if (index != -1)
  3869. {
  3870. seqIndex = index;
  3871. found = true;
  3872. }
  3873. }
  3874. if (!found && hasScriptPrefix)
  3875. {
  3876. String seqName = String(scriptPrefix) + String("_") + baseSeqName;
  3877. S32 index = mShapeFPInstance[imageSlot]->getShape()->findSequence(seqName);
  3878. if (index != -1)
  3879. {
  3880. seqIndex = index;
  3881. found = true;
  3882. }
  3883. }
  3884. }
  3885. if (seqIndex != -1)
  3886. {
  3887. if (!lastState)
  3888. {
  3889. // No lastState indicates that we are just switching animation sequences, not states. Transition into this new sequence, but only
  3890. // if it is different than what we're currently playing.
  3891. S32 prevSeq = -1;
  3892. if (mShapeFPAnimThread[imageSlot]->hasSequence())
  3893. {
  3894. prevSeq = mShapeFPInstance[imageSlot]->getSequence(mShapeFPAnimThread[imageSlot]);
  3895. }
  3896. if (seqIndex != prevSeq)
  3897. {
  3898. mShapeFPInstance[imageSlot]->transitionToSequence(mShapeFPAnimThread[imageSlot], seqIndex, pos, image.dataBlock->scriptAnimTransitionTime, true);
  3899. }
  3900. }
  3901. else if (!stateData.sequenceNeverTransition && stateData.sequenceTransitionTime && (stateData.sequenceTransitionIn || (lastState && lastState->sequenceTransitionOut)) )
  3902. {
  3903. mShapeFPInstance[imageSlot]->transitionToSequence(mShapeFPAnimThread[imageSlot], seqIndex, pos, stateData.sequenceTransitionTime, true);
  3904. }
  3905. else
  3906. {
  3907. mShapeFPInstance[imageSlot]->setSequence(mShapeFPAnimThread[imageSlot], seqIndex, pos);
  3908. }
  3909. mShapeFPInstance[imageSlot]->setTimeScale(mShapeFPAnimThread[imageSlot], timeScale);
  3910. }
  3911. }
  3912. void Player::onImageAnimThreadUpdate(U32 imageSlot, S32 imageShapeIndex, F32 dt)
  3913. {
  3914. if (!mShapeFPInstance[imageSlot])
  3915. return;
  3916. if (mShapeFPAmbientThread[imageSlot] && mShapeFPAmbientThread[imageSlot]->hasSequence())
  3917. {
  3918. mShapeFPInstance[imageSlot]->advanceTime(dt,mShapeFPAmbientThread[imageSlot]);
  3919. }
  3920. if (mShapeFPAnimThread[imageSlot] && mShapeFPAnimThread[imageSlot]->hasSequence())
  3921. {
  3922. mShapeFPInstance[imageSlot]->advanceTime(dt,mShapeFPAnimThread[imageSlot]);
  3923. }
  3924. }
  3925. void Player::onUnmount( SceneObject *obj, S32 node )
  3926. {
  3927. // Reset back to root position during dismount.
  3928. setActionThread(PlayerData::RootAnim,true,false,false);
  3929. // Re-orient the player straight up
  3930. Point3F pos,vec;
  3931. getTransform().getColumn(1,&vec);
  3932. getTransform().getColumn(3,&pos);
  3933. Point3F rot(0.0f,0.0f,-mAtan2(-vec.x,vec.y));
  3934. setPosition(pos,rot);
  3935. // Parent function will call script
  3936. Parent::onUnmount( obj, node );
  3937. }
  3938. void Player::unmount()
  3939. {
  3940. // Reset back to root position during dismount. This copies what is
  3941. // done on the server and corrects the fact that the RootAnim change
  3942. // is not sent across to the client using the standard ActionMask.
  3943. setActionThread(PlayerData::RootAnim,true,false,false);
  3944. Parent::unmount();
  3945. }
  3946. //----------------------------------------------------------------------------
  3947. void Player::updateAnimation(F32 dt)
  3948. {
  3949. // If dead then remove any image animations
  3950. if ((mDamageState == Disabled || mDamageState == Destroyed) && mImageStateThread)
  3951. {
  3952. // Remove the image state animation
  3953. mShapeInstance->destroyThread(mImageStateThread);
  3954. mImageStateThread = 0;
  3955. }
  3956. if ((isGhost() || mActionAnimation.animateOnServer) && mActionAnimation.thread)
  3957. mShapeInstance->advanceTime(dt,mActionAnimation.thread);
  3958. if (mRecoilThread)
  3959. mShapeInstance->advanceTime(dt,mRecoilThread);
  3960. if (mImageStateThread)
  3961. mShapeInstance->advanceTime(dt,mImageStateThread);
  3962. // update any active blend clips
  3963. if (isGhost())
  3964. for (S32 i = 0; i < blend_clips.size(); i++)
  3965. mShapeInstance->advanceTime(dt, blend_clips[i].thread);
  3966. // If we are the client's player on this machine, then we need
  3967. // to make sure the transforms are up to date as they are used
  3968. // to setup the camera.
  3969. if (isGhost())
  3970. {
  3971. if (getControllingClient())
  3972. {
  3973. updateAnimationTree(isFirstPerson());
  3974. mShapeInstance->animate();
  3975. }
  3976. else
  3977. {
  3978. updateAnimationTree(false);
  3979. // This addition forces recently visible players to animate their
  3980. // skeleton now rather than in pre-render so that constrained effects
  3981. // get up-to-date node transforms.
  3982. if (didRenderLastRender())
  3983. mShapeInstance->animate();
  3984. }
  3985. }
  3986. }
  3987. void Player::updateAnimationTree(bool firstPerson)
  3988. {
  3989. S32 mode = 0;
  3990. if (firstPerson)
  3991. {
  3992. if (mActionAnimation.firstPerson)
  3993. mode = 0;
  3994. // TSShapeInstance::MaskNodeRotation;
  3995. // TSShapeInstance::MaskNodePosX |
  3996. // TSShapeInstance::MaskNodePosY;
  3997. else
  3998. mode = TSShapeInstance::MaskNodeAllButBlend;
  3999. }
  4000. for (U32 i = 0; i < PlayerData::NumSpineNodes; i++)
  4001. if (mDataBlock->spineNode[i] != -1)
  4002. mShapeInstance->setNodeAnimationState(mDataBlock->spineNode[i],mode);
  4003. }
  4004. //----------------------------------------------------------------------------
  4005. bool Player::step(Point3F *pos,F32 *maxStep,F32 time)
  4006. {
  4007. const Point3F& scale = getScale();
  4008. Box3F box;
  4009. VectorF offset = mVelocity * time;
  4010. box.minExtents = mObjBox.minExtents + offset + *pos;
  4011. box.maxExtents = mObjBox.maxExtents + offset + *pos;
  4012. box.maxExtents.z += mDataBlock->maxStepHeight * scale.z + sMinFaceDistance;
  4013. SphereF sphere;
  4014. sphere.center = (box.minExtents + box.maxExtents) * 0.5f;
  4015. VectorF bv = box.maxExtents - sphere.center;
  4016. sphere.radius = bv.len();
  4017. ClippedPolyList polyList;
  4018. polyList.mPlaneList.clear();
  4019. polyList.mNormal.set(0.0f, 0.0f, 0.0f);
  4020. polyList.mPlaneList.setSize(6);
  4021. polyList.mPlaneList[0].set(box.minExtents,VectorF(-1.0f, 0.0f, 0.0f));
  4022. polyList.mPlaneList[1].set(box.maxExtents,VectorF(0.0f, 1.0f, 0.0f));
  4023. polyList.mPlaneList[2].set(box.maxExtents,VectorF(1.0f, 0.0f, 0.0f));
  4024. polyList.mPlaneList[3].set(box.minExtents,VectorF(0.0f, -1.0f, 0.0f));
  4025. polyList.mPlaneList[4].set(box.minExtents,VectorF(0.0f, 0.0f, -1.0f));
  4026. polyList.mPlaneList[5].set(box.maxExtents,VectorF(0.0f, 0.0f, 1.0f));
  4027. CollisionWorkingList& rList = mConvex.getWorkingList();
  4028. CollisionWorkingList* pList = rList.wLink.mNext;
  4029. while (pList != &rList) {
  4030. Convex* pConvex = pList->mConvex;
  4031. // Alright, here's the deal... a polysoup mesh really needs to be
  4032. // designed with stepping in mind. If there are too many smallish polygons
  4033. // the stepping system here gets confused and allows you to run up walls
  4034. // or on the edges/seams of meshes.
  4035. TSStatic *st = dynamic_cast<TSStatic *> (pConvex->getObject());
  4036. bool skip = false;
  4037. if (st && !st->allowPlayerStep())
  4038. skip = true;
  4039. if ((pConvex->getObject()->getTypeMask() & StaticObjectType) != 0 && !skip)
  4040. {
  4041. Box3F convexBox = pConvex->getBoundingBox();
  4042. if (box.isOverlapped(convexBox))
  4043. pConvex->getPolyList(&polyList);
  4044. }
  4045. pList = pList->wLink.mNext;
  4046. }
  4047. // Find max step height
  4048. F32 stepHeight = pos->z - sMinFaceDistance;
  4049. U32* vp = polyList.mIndexList.begin();
  4050. U32* ep = polyList.mIndexList.end();
  4051. for (; vp != ep; vp++) {
  4052. F32 h = polyList.mVertexList[*vp].point.z + sMinFaceDistance;
  4053. if (h > stepHeight)
  4054. stepHeight = h;
  4055. }
  4056. F32 step = stepHeight - pos->z;
  4057. if (stepHeight > pos->z && step < *maxStep) {
  4058. // Go ahead and step
  4059. pos->z = stepHeight;
  4060. *maxStep -= step;
  4061. return true;
  4062. }
  4063. return false;
  4064. }
  4065. //----------------------------------------------------------------------------
  4066. inline Point3F createInterpPos(const Point3F& s, const Point3F& e, const F32 t, const F32 d)
  4067. {
  4068. Point3F ret;
  4069. ret.interpolate(s, e, t/d);
  4070. return ret;
  4071. }
  4072. Point3F Player::_move( const F32 travelTime, Collision *outCol )
  4073. {
  4074. // Try and move to new pos
  4075. F32 totalMotion = 0.0f;
  4076. // TODO: not used?
  4077. //F32 initialSpeed = mVelocity.len();
  4078. Point3F start;
  4079. Point3F initialPosition;
  4080. getTransform().getColumn(3,&start);
  4081. initialPosition = start;
  4082. static CollisionList collisionList;
  4083. static CollisionList physZoneCollisionList;
  4084. collisionList.clear();
  4085. physZoneCollisionList.clear();
  4086. MatrixF collisionMatrix(true);
  4087. collisionMatrix.setColumn(3, start);
  4088. VectorF firstNormal(0.0f, 0.0f, 0.0f);
  4089. F32 maxStep = mDataBlock->maxStepHeight;
  4090. F32 time = travelTime;
  4091. U32 count = 0;
  4092. const Point3F& scale = getScale();
  4093. static Polyhedron sBoxPolyhedron;
  4094. static ExtrudedPolyList sExtrudedPolyList;
  4095. static ExtrudedPolyList sPhysZonePolyList;
  4096. for (; count < sMoveRetryCount; count++) {
  4097. F32 speed = mVelocity.len();
  4098. if (!speed && !mDeath.haveVelocity())
  4099. break;
  4100. Point3F end = start + mVelocity * time;
  4101. if (mDeath.haveVelocity()) {
  4102. // Add in death movement-
  4103. VectorF deathVel = mDeath.getPosAdd();
  4104. VectorF resVel;
  4105. getTransform().mulV(deathVel, & resVel);
  4106. end += resVel;
  4107. }
  4108. Point3F distance = end - start;
  4109. if (mFabs(distance.x) < mScaledBox.len_x() &&
  4110. mFabs(distance.y) < mScaledBox.len_y() &&
  4111. mFabs(distance.z) < mScaledBox.len_z())
  4112. {
  4113. // We can potentially early out of this. If there are no polys in the clipped polylist at our
  4114. // end position, then we can bail, and just set start = end;
  4115. Box3F wBox = mScaledBox;
  4116. wBox.minExtents += end;
  4117. wBox.maxExtents += end;
  4118. static EarlyOutPolyList eaPolyList;
  4119. eaPolyList.clear();
  4120. eaPolyList.mNormal.set(0.0f, 0.0f, 0.0f);
  4121. eaPolyList.mPlaneList.clear();
  4122. eaPolyList.mPlaneList.setSize(6);
  4123. eaPolyList.mPlaneList[0].set(wBox.minExtents,VectorF(-1.0f, 0.0f, 0.0f));
  4124. eaPolyList.mPlaneList[1].set(wBox.maxExtents,VectorF(0.0f, 1.0f, 0.0f));
  4125. eaPolyList.mPlaneList[2].set(wBox.maxExtents,VectorF(1.0f, 0.0f, 0.0f));
  4126. eaPolyList.mPlaneList[3].set(wBox.minExtents,VectorF(0.0f, -1.0f, 0.0f));
  4127. eaPolyList.mPlaneList[4].set(wBox.minExtents,VectorF(0.0f, 0.0f, -1.0f));
  4128. eaPolyList.mPlaneList[5].set(wBox.maxExtents,VectorF(0.0f, 0.0f, 1.0f));
  4129. // Build list from convex states here...
  4130. CollisionWorkingList& rList = mConvex.getWorkingList();
  4131. CollisionWorkingList* pList = rList.wLink.mNext;
  4132. while (pList != &rList) {
  4133. Convex* pConvex = pList->mConvex;
  4134. if (pConvex->getObject()->getTypeMask() & sCollisionMoveMask) {
  4135. Box3F convexBox = pConvex->getBoundingBox();
  4136. if (wBox.isOverlapped(convexBox))
  4137. {
  4138. // No need to separate out the physical zones here, we want those
  4139. // to cause a fallthrough as well...
  4140. pConvex->getPolyList(&eaPolyList);
  4141. }
  4142. }
  4143. pList = pList->wLink.mNext;
  4144. }
  4145. if (eaPolyList.isEmpty())
  4146. {
  4147. totalMotion += (end - start).len();
  4148. start = end;
  4149. break;
  4150. }
  4151. }
  4152. collisionMatrix.setColumn(3, start);
  4153. sBoxPolyhedron.buildBox(collisionMatrix, mScaledBox, true);
  4154. // Setup the bounding box for the extrudedPolyList
  4155. Box3F plistBox = mScaledBox;
  4156. collisionMatrix.mul(plistBox);
  4157. Point3F oldMin = plistBox.minExtents;
  4158. Point3F oldMax = plistBox.maxExtents;
  4159. plistBox.minExtents.setMin(oldMin + (mVelocity * time) - Point3F(0.1f, 0.1f, 0.1f));
  4160. plistBox.maxExtents.setMax(oldMax + (mVelocity * time) + Point3F(0.1f, 0.1f, 0.1f));
  4161. // Build extruded polyList...
  4162. VectorF vector = end - start;
  4163. sExtrudedPolyList.extrude(sBoxPolyhedron,vector);
  4164. sExtrudedPolyList.setVelocity(mVelocity);
  4165. sExtrudedPolyList.setCollisionList(&collisionList);
  4166. sPhysZonePolyList.extrude(sBoxPolyhedron,vector);
  4167. sPhysZonePolyList.setVelocity(mVelocity);
  4168. sPhysZonePolyList.setCollisionList(&physZoneCollisionList);
  4169. // Build list from convex states here...
  4170. CollisionWorkingList& rList = mConvex.getWorkingList();
  4171. CollisionWorkingList* pList = rList.wLink.mNext;
  4172. while (pList != &rList) {
  4173. Convex* pConvex = pList->mConvex;
  4174. if (pConvex->getObject()->getTypeMask() & sCollisionMoveMask) {
  4175. Box3F convexBox = pConvex->getBoundingBox();
  4176. if (plistBox.isOverlapped(convexBox))
  4177. {
  4178. if (pConvex->getObject()->getTypeMask() & PhysicalZoneObjectType)
  4179. pConvex->getPolyList(&sPhysZonePolyList);
  4180. else
  4181. pConvex->getPolyList(&sExtrudedPolyList);
  4182. }
  4183. }
  4184. pList = pList->wLink.mNext;
  4185. }
  4186. // Take into account any physical zones...
  4187. for (U32 j = 0; j < physZoneCollisionList.getCount(); j++)
  4188. {
  4189. AssertFatal(dynamic_cast<PhysicalZone*>(physZoneCollisionList[j].object), "Bad phys zone!");
  4190. const PhysicalZone* pZone = (PhysicalZone*)physZoneCollisionList[j].object;
  4191. if (pZone->isActive())
  4192. mVelocity *= pZone->getVelocityMod();
  4193. }
  4194. if (collisionList.getCount() != 0 && collisionList.getTime() < 1.0f)
  4195. {
  4196. // Set to collision point
  4197. F32 velLen = mVelocity.len();
  4198. F32 dt = time * getMin(collisionList.getTime(), 1.0f);
  4199. start += mVelocity * dt;
  4200. time -= dt;
  4201. totalMotion += velLen * dt;
  4202. bool wasFalling = mFalling;
  4203. mFalling = false;
  4204. // Back off...
  4205. if ( velLen > 0.f ) {
  4206. F32 newT = getMin(0.01f / velLen, dt);
  4207. start -= mVelocity * newT;
  4208. totalMotion -= velLen * newT;
  4209. }
  4210. // Try stepping if there is a vertical surface
  4211. if (collisionList.getMaxHeight() < start.z + mDataBlock->maxStepHeight * scale.z)
  4212. {
  4213. bool stepped = false;
  4214. for (U32 c = 0; c < collisionList.getCount(); c++)
  4215. {
  4216. const Collision& cp = collisionList[c];
  4217. // if (mFabs(mDot(cp.normal,VectorF(0,0,1))) < sVerticalStepDot)
  4218. // Dot with (0,0,1) just extracts Z component [lh]-
  4219. if (mFabs(cp.normal.z) < sVerticalStepDot)
  4220. {
  4221. stepped = step(&start,&maxStep,time);
  4222. break;
  4223. }
  4224. }
  4225. if (stepped)
  4226. {
  4227. continue;
  4228. }
  4229. }
  4230. // Pick the surface most parallel to the face that was hit.
  4231. const Collision *collision = &collisionList[0];
  4232. const Collision *cp = collision + 1;
  4233. const Collision *ep = collision + collisionList.getCount();
  4234. for (; cp != ep; cp++)
  4235. {
  4236. if (cp->faceDot > collision->faceDot)
  4237. collision = cp;
  4238. }
  4239. F32 bd = _doCollisionImpact( collision, wasFalling );
  4240. // Copy this collision out so
  4241. // we can use it to do impacts
  4242. // and query collision.
  4243. *outCol = *collision;
  4244. if (isServerObject() && bd > 6.8f && collision->normal.z > 0.7f)
  4245. {
  4246. fx_s_triggers |= PLAYER_LANDING_S_TRIGGER;
  4247. setMaskBits(TriggerMask);
  4248. }
  4249. // Subtract out velocity
  4250. VectorF dv = collision->normal * (bd + sNormalElasticity);
  4251. mVelocity += dv;
  4252. if (count == 0)
  4253. {
  4254. firstNormal = collision->normal;
  4255. }
  4256. else
  4257. {
  4258. if (count == 1)
  4259. {
  4260. // Re-orient velocity along the crease.
  4261. if (mDot(dv,firstNormal) < 0.0f &&
  4262. mDot(collision->normal,firstNormal) < 0.0f)
  4263. {
  4264. VectorF nv;
  4265. mCross(collision->normal,firstNormal,&nv);
  4266. F32 nvl = nv.len();
  4267. if (nvl)
  4268. {
  4269. if (mDot(nv,mVelocity) < 0.0f)
  4270. nvl = -nvl;
  4271. nv *= mVelocity.len() / nvl;
  4272. mVelocity = nv;
  4273. }
  4274. }
  4275. }
  4276. }
  4277. }
  4278. else
  4279. {
  4280. totalMotion += (end - start).len();
  4281. start = end;
  4282. break;
  4283. }
  4284. }
  4285. if (count == sMoveRetryCount)
  4286. {
  4287. // Failed to move
  4288. start = initialPosition;
  4289. mVelocity.set(0.0f, 0.0f, 0.0f);
  4290. }
  4291. return start;
  4292. }
  4293. F32 Player::_doCollisionImpact( const Collision *collision, bool fallingCollision)
  4294. {
  4295. F32 bd = -mDot( mVelocity, collision->normal);
  4296. // shake camera on ground impact
  4297. if( bd > mDataBlock->groundImpactMinSpeed && isControlObject() )
  4298. {
  4299. F32 ampScale = (bd - mDataBlock->groundImpactMinSpeed) / mDataBlock->minImpactSpeed;
  4300. CameraShake *groundImpactShake = new CameraShake;
  4301. groundImpactShake->setDuration( mDataBlock->groundImpactShakeDuration );
  4302. groundImpactShake->setFrequency( mDataBlock->groundImpactShakeFreq );
  4303. VectorF shakeAmp = mDataBlock->groundImpactShakeAmp * ampScale;
  4304. groundImpactShake->setAmplitude( shakeAmp );
  4305. groundImpactShake->setFalloff( mDataBlock->groundImpactShakeFalloff );
  4306. groundImpactShake->init();
  4307. gCamFXMgr.addFX( groundImpactShake );
  4308. }
  4309. if ( ((bd > mDataBlock->minImpactSpeed && fallingCollision) || bd > mDataBlock->minLateralImpactSpeed)
  4310. && !mMountPending )
  4311. {
  4312. if ( !isGhost() )
  4313. onImpact( collision->object, collision->normal * bd );
  4314. if (mDamageState == Enabled && mState != RecoverState)
  4315. {
  4316. // Scale how long we're down for
  4317. if (mDataBlock->landSequenceTime > 0.0f)
  4318. {
  4319. // Recover time is based on the land sequence
  4320. setState(RecoverState);
  4321. }
  4322. else
  4323. {
  4324. // Legacy recover system
  4325. F32 value = (bd - mDataBlock->minImpactSpeed);
  4326. F32 range = (mDataBlock->minImpactSpeed * 0.9f);
  4327. U32 recover = mDataBlock->recoverDelay;
  4328. if (value < range)
  4329. recover = 1 + S32(mFloor( F32(recover) * value / range) );
  4330. //Con::printf("Used %d recover ticks", recover);
  4331. //Con::printf(" minImpact = %g, this one = %g", mDataBlock->minImpactSpeed, bd);
  4332. setState(RecoverState, recover);
  4333. }
  4334. }
  4335. }
  4336. if ( isServerObject() &&
  4337. (bd > (mDataBlock->minImpactSpeed / 3.0f) || bd > (mDataBlock->minLateralImpactSpeed / 3.0f )) )
  4338. {
  4339. mImpactSound = PlayerData::ImpactNormal;
  4340. setMaskBits(ImpactMask);
  4341. }
  4342. return bd;
  4343. }
  4344. void Player::_handleCollision( const Collision &collision )
  4345. {
  4346. // Track collisions
  4347. if ( !isGhost() &&
  4348. collision.object &&
  4349. collision.object != mContactInfo.contactObject )
  4350. queueCollision( collision.object, mVelocity - collision.object->getVelocity() );
  4351. }
  4352. bool Player::updatePos(const F32 travelTime)
  4353. {
  4354. PROFILE_SCOPE(Player_UpdatePos);
  4355. getTransform().getColumn(3,&delta.posVec);
  4356. // When mounted to another object, only Z rotation used.
  4357. if (isMounted()) {
  4358. mVelocity = mMount.object->getVelocity();
  4359. setPosition(Point3F(0.0f, 0.0f, 0.0f), mRot);
  4360. setMaskBits(MoveMask);
  4361. return true;
  4362. }
  4363. Point3F newPos;
  4364. Collision col;
  4365. dMemset( &col, 0, sizeof( col ) );
  4366. // DEBUG:
  4367. //Point3F savedVelocity = mVelocity;
  4368. if ( mPhysicsRep )
  4369. {
  4370. static CollisionList collisionList;
  4371. collisionList.clear();
  4372. newPos = mPhysicsRep->move( mVelocity * travelTime, collisionList );
  4373. bool haveCollisions = false;
  4374. bool wasFalling = mFalling;
  4375. if (collisionList.getCount() > 0)
  4376. {
  4377. mFalling = false;
  4378. haveCollisions = true;
  4379. }
  4380. if (haveCollisions)
  4381. {
  4382. // Pick the collision that most closely matches our direction
  4383. VectorF velNormal = mVelocity;
  4384. velNormal.normalizeSafe();
  4385. const Collision *collision = &collisionList[0];
  4386. F32 collisionDot = mDot(velNormal, collision->normal);
  4387. const Collision *cp = collision + 1;
  4388. const Collision *ep = collision + collisionList.getCount();
  4389. for (; cp != ep; cp++)
  4390. {
  4391. F32 dp = mDot(velNormal, cp->normal);
  4392. if (dp < collisionDot)
  4393. {
  4394. collisionDot = dp;
  4395. collision = cp;
  4396. }
  4397. }
  4398. _doCollisionImpact( collision, wasFalling );
  4399. // Modify our velocity based on collisions
  4400. for (U32 i=0; i<collisionList.getCount(); ++i)
  4401. {
  4402. F32 bd = -mDot( mVelocity, collisionList[i].normal );
  4403. VectorF dv = collisionList[i].normal * (bd + sNormalElasticity);
  4404. mVelocity += dv;
  4405. }
  4406. // Store the last collision for use later on. The handle collision
  4407. // code only expects a single collision object.
  4408. if (collisionList.getCount() > 0)
  4409. col = collisionList[collisionList.getCount() - 1];
  4410. // We'll handle any player-to-player collision, and the last collision
  4411. // with other obejct types.
  4412. for (U32 i=0; i<collisionList.getCount(); ++i)
  4413. {
  4414. Collision& colCheck = collisionList[i];
  4415. if (colCheck.object)
  4416. {
  4417. SceneObject* obj = static_cast<SceneObject*>(col.object);
  4418. if (obj->getTypeMask() & PlayerObjectType)
  4419. {
  4420. _handleCollision( colCheck );
  4421. }
  4422. else
  4423. {
  4424. col = colCheck;
  4425. }
  4426. }
  4427. }
  4428. _handleCollision( col );
  4429. }
  4430. }
  4431. else
  4432. {
  4433. if ( mVelocity.isZero() )
  4434. newPos = delta.posVec;
  4435. else
  4436. newPos = _move( travelTime, &col );
  4437. _handleCollision( col );
  4438. }
  4439. // DEBUG:
  4440. //if ( isClientObject() )
  4441. // Con::printf( "(client) vel: %g %g %g", mVelocity.x, mVelocity.y, mVelocity.z );
  4442. //else
  4443. // Con::printf( "(server) vel: %g %g %g", mVelocity.x, mVelocity.y, mVelocity.z );
  4444. // Set new position
  4445. // If on the client, calc delta for backstepping
  4446. if (isClientObject())
  4447. {
  4448. delta.pos = newPos;
  4449. delta.posVec = delta.posVec - delta.pos;
  4450. delta.dt = 1.0f;
  4451. }
  4452. setPosition( newPos, mRot );
  4453. setMaskBits( MoveMask );
  4454. updateContainer();
  4455. if (!isGhost())
  4456. {
  4457. // Collisions are only queued on the server and can be
  4458. // generated by either updateMove or updatePos
  4459. notifyCollision();
  4460. // Do mission area callbacks on the server as well
  4461. checkMissionArea();
  4462. }
  4463. // Check the total distance moved. If it is more than 1000th of the velocity, then
  4464. // we moved a fair amount...
  4465. //if (totalMotion >= (0.001f * initialSpeed))
  4466. return true;
  4467. //else
  4468. //return false;
  4469. }
  4470. //----------------------------------------------------------------------------
  4471. void Player::_findContact( SceneObject **contactObject,
  4472. VectorF *contactNormal,
  4473. Vector<SceneObject*> *outOverlapObjects )
  4474. {
  4475. Point3F pos;
  4476. getTransform().getColumn(3,&pos);
  4477. Box3F wBox;
  4478. Point3F exp(0,0,sTractionDistance);
  4479. wBox.minExtents = pos + mScaledBox.minExtents - exp;
  4480. wBox.maxExtents.x = pos.x + mScaledBox.maxExtents.x;
  4481. wBox.maxExtents.y = pos.y + mScaledBox.maxExtents.y;
  4482. wBox.maxExtents.z = pos.z + mScaledBox.minExtents.z + sTractionDistance;
  4483. static ClippedPolyList polyList;
  4484. polyList.clear();
  4485. polyList.doConstruct();
  4486. polyList.mNormal.set(0.0f, 0.0f, 0.0f);
  4487. polyList.setInterestNormal(Point3F(0.0f, 0.0f, -1.0f));
  4488. polyList.mPlaneList.setSize(6);
  4489. polyList.mPlaneList[0].setYZ(wBox.minExtents, -1.0f);
  4490. polyList.mPlaneList[1].setXZ(wBox.maxExtents, 1.0f);
  4491. polyList.mPlaneList[2].setYZ(wBox.maxExtents, 1.0f);
  4492. polyList.mPlaneList[3].setXZ(wBox.minExtents, -1.0f);
  4493. polyList.mPlaneList[4].setXY(wBox.minExtents, -1.0f);
  4494. polyList.mPlaneList[5].setXY(wBox.maxExtents, 1.0f);
  4495. Box3F plistBox = wBox;
  4496. // Expand build box as it will be used to collide with items.
  4497. // PickupRadius will be at least the size of the box.
  4498. F32 pd = (F32)mDataBlock->pickupDelta;
  4499. wBox.minExtents.x -= pd; wBox.minExtents.y -= pd;
  4500. wBox.maxExtents.x += pd; wBox.maxExtents.y += pd;
  4501. wBox.maxExtents.z = pos.z + mScaledBox.maxExtents.z;
  4502. // Build list from convex states here...
  4503. CollisionWorkingList& rList = mConvex.getWorkingList();
  4504. CollisionWorkingList* pList = rList.wLink.mNext;
  4505. while (pList != &rList)
  4506. {
  4507. Convex* pConvex = pList->mConvex;
  4508. U32 objectMask = pConvex->getObject()->getTypeMask();
  4509. if ( ( objectMask & sCollisionMoveMask ) &&
  4510. !( objectMask & PhysicalZoneObjectType ) )
  4511. {
  4512. Box3F convexBox = pConvex->getBoundingBox();
  4513. if (plistBox.isOverlapped(convexBox))
  4514. pConvex->getPolyList(&polyList);
  4515. }
  4516. else
  4517. outOverlapObjects->push_back( pConvex->getObject() );
  4518. pList = pList->wLink.mNext;
  4519. }
  4520. if (!polyList.isEmpty())
  4521. {
  4522. // Pick flattest surface
  4523. F32 bestVd = -1.0f;
  4524. ClippedPolyList::Poly* poly = polyList.mPolyList.begin();
  4525. ClippedPolyList::Poly* end = polyList.mPolyList.end();
  4526. for (; poly != end; poly++)
  4527. {
  4528. F32 vd = poly->plane.z; // i.e. mDot(Point3F(0,0,1), poly->plane);
  4529. if (vd > bestVd)
  4530. {
  4531. bestVd = vd;
  4532. *contactObject = poly->object;
  4533. *contactNormal = poly->plane;
  4534. }
  4535. }
  4536. }
  4537. }
  4538. void Player::findContact( bool *run, bool *jump, VectorF *contactNormal )
  4539. {
  4540. SceneObject *contactObject = NULL;
  4541. Vector<SceneObject*> overlapObjects;
  4542. if ( mPhysicsRep )
  4543. mPhysicsRep->findContact( &contactObject, contactNormal, &overlapObjects );
  4544. else
  4545. _findContact( &contactObject, contactNormal, &overlapObjects );
  4546. // Check for triggers, corpses and items.
  4547. const U32 filterMask = isGhost() ? sClientCollisionContactMask : sServerCollisionContactMask;
  4548. for ( U32 i=0; i < overlapObjects.size(); i++ )
  4549. {
  4550. SceneObject *obj = overlapObjects[i];
  4551. U32 objectMask = obj->getTypeMask();
  4552. if ( !( objectMask & filterMask ) )
  4553. continue;
  4554. // Check: triggers, corpses and items...
  4555. //
  4556. if (objectMask & TriggerObjectType)
  4557. {
  4558. Trigger* pTrigger = static_cast<Trigger*>( obj );
  4559. pTrigger->potentialEnterObject(this);
  4560. }
  4561. else if (objectMask & CorpseObjectType)
  4562. {
  4563. // If we've overlapped the worldbounding boxes, then that's it...
  4564. if ( getWorldBox().isOverlapped( obj->getWorldBox() ) )
  4565. {
  4566. ShapeBase* col = static_cast<ShapeBase*>( obj );
  4567. queueCollision(col,getVelocity() - col->getVelocity());
  4568. }
  4569. }
  4570. else if (objectMask & ItemObjectType)
  4571. {
  4572. // If we've overlapped the worldbounding boxes, then that's it...
  4573. Item* item = static_cast<Item*>( obj );
  4574. if ( getWorldBox().isOverlapped(item->getWorldBox()) &&
  4575. item->getCollisionObject() != this &&
  4576. !item->isHidden() )
  4577. queueCollision(item,getVelocity() - item->getVelocity());
  4578. }
  4579. }
  4580. F32 vd = (*contactNormal).z;
  4581. *run = vd > mDataBlock->runSurfaceCos;
  4582. *jump = vd > mDataBlock->jumpSurfaceCos;
  4583. mContactInfo.clear();
  4584. mContactInfo.contacted = contactObject != NULL;
  4585. mContactInfo.contactObject = contactObject;
  4586. if ( mContactInfo.contacted )
  4587. mContactInfo.contactNormal = *contactNormal;
  4588. mContactInfo.run = *run;
  4589. mContactInfo.jump = *jump;
  4590. }
  4591. //----------------------------------------------------------------------------
  4592. void Player::checkMissionArea()
  4593. {
  4594. // Checks to see if the player is in the Mission Area...
  4595. Point3F pos;
  4596. MissionArea * obj = MissionArea::getServerObject();
  4597. if(!obj)
  4598. return;
  4599. const RectI &area = obj->getArea();
  4600. getTransform().getColumn(3, &pos);
  4601. if ((pos.x < area.point.x || pos.x > area.point.x + area.extent.x ||
  4602. pos.y < area.point.y || pos.y > area.point.y + area.extent.y)) {
  4603. if(mInMissionArea) {
  4604. mInMissionArea = false;
  4605. mDataBlock->onLeaveMissionArea_callback( this );
  4606. }
  4607. }
  4608. else if(!mInMissionArea)
  4609. {
  4610. mInMissionArea = true;
  4611. mDataBlock->onEnterMissionArea_callback( this );
  4612. }
  4613. }
  4614. //----------------------------------------------------------------------------
  4615. bool Player::isDisplacable() const
  4616. {
  4617. return true;
  4618. }
  4619. Point3F Player::getMomentum() const
  4620. {
  4621. return mVelocity * getMass();
  4622. }
  4623. void Player::setMomentum(const Point3F& newMomentum)
  4624. {
  4625. Point3F newVelocity = newMomentum / getMass();
  4626. mVelocity = newVelocity;
  4627. }
  4628. #define LH_HACK 1
  4629. // Hack for short-term soln to Training crash -
  4630. #if LH_HACK
  4631. static U32 sBalance;
  4632. bool Player::displaceObject(const Point3F& displacement)
  4633. {
  4634. F32 vellen = mVelocity.len();
  4635. if (vellen < 0.001f || sBalance > 16) {
  4636. mVelocity.set(0.0f, 0.0f, 0.0f);
  4637. return false;
  4638. }
  4639. F32 dt = displacement.len() / vellen;
  4640. sBalance++;
  4641. bool result = updatePos(dt);
  4642. sBalance--;
  4643. getTransform().getColumn(3, &delta.pos);
  4644. delta.posVec.set(0.0f, 0.0f, 0.0f);
  4645. return result;
  4646. }
  4647. #else
  4648. bool Player::displaceObject(const Point3F& displacement)
  4649. {
  4650. F32 vellen = mVelocity.len();
  4651. if (vellen < 0.001f) {
  4652. mVelocity.set(0.0f, 0.0f, 0.0f);
  4653. return false;
  4654. }
  4655. F32 dt = displacement.len() / vellen;
  4656. bool result = updatePos(dt);
  4657. mObjToWorld.getColumn(3, &delta.pos);
  4658. delta.posVec.set(0.0f, 0.0f, 0.0f);
  4659. return result;
  4660. }
  4661. #endif
  4662. //----------------------------------------------------------------------------
  4663. void Player::setPosition(const Point3F& pos,const Point3F& rot)
  4664. {
  4665. MatrixF mat;
  4666. if (isMounted()) {
  4667. // Use transform from mounted object
  4668. //MatrixF nmat,zrot;
  4669. mMount.object->getMountTransform( mMount.node, mMount.xfm, &mat );
  4670. //zrot.set(EulerF(0.0f, 0.0f, rot.z));
  4671. //mat.mul(nmat,zrot);
  4672. }
  4673. else {
  4674. mat.set(EulerF(0.0f, 0.0f, rot.z));
  4675. mat.setColumn(3,pos);
  4676. }
  4677. Parent::setTransform(mat);
  4678. mRot = rot;
  4679. if ( mPhysicsRep )
  4680. mPhysicsRep->setTransform( mat );
  4681. }
  4682. void Player::setRenderPosition(const Point3F& pos, const Point3F& rot, F32 dt)
  4683. {
  4684. MatrixF mat;
  4685. if (isMounted()) {
  4686. // Use transform from mounted object
  4687. //MatrixF nmat,zrot;
  4688. mMount.object->getRenderMountTransform( dt, mMount.node, mMount.xfm, &mat );
  4689. //zrot.set(EulerF(0.0f, 0.0f, rot.z));
  4690. //mat.mul(nmat,zrot);
  4691. }
  4692. else {
  4693. EulerF orient(0.0f, 0.0f, rot.z);
  4694. mat.set(orient);
  4695. mat.setColumn(3, pos);
  4696. if (inDeathAnim()) {
  4697. F32 boxRad = (mDataBlock->boxSize.x * 0.5f);
  4698. if (MatrixF * fallMat = mDeath.fallToGround(dt, pos, rot.z, boxRad))
  4699. mat = * fallMat;
  4700. }
  4701. else
  4702. mDeath.initFall();
  4703. }
  4704. Parent::setRenderTransform(mat);
  4705. }
  4706. //----------------------------------------------------------------------------
  4707. void Player::setTransform(const MatrixF& mat)
  4708. {
  4709. // This method should never be called on the client.
  4710. // This currently converts all rotation in the mat into
  4711. // rotations around the z axis.
  4712. Point3F pos,vec;
  4713. mat.getColumn(1,&vec);
  4714. mat.getColumn(3,&pos);
  4715. Point3F rot(0.0f, 0.0f, -mAtan2(-vec.x,vec.y));
  4716. setPosition(pos,rot);
  4717. setMaskBits(MoveMask | NoWarpMask);
  4718. }
  4719. void Player::getEyeTransform(MatrixF* mat)
  4720. {
  4721. getEyeBaseTransform(mat, true);
  4722. // The shape instance is animated in getEyeBaseTransform() so we're
  4723. // good here when attempting to get the eye node position on the server.
  4724. S32 imageIndex = -1;
  4725. S32 shapeIndex = -1;
  4726. MountedImage* image = NULL;
  4727. ShapeBaseImageData* data = NULL;
  4728. for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
  4729. {
  4730. image = &(mMountedImageList[i]);
  4731. if (image->dataBlock)
  4732. {
  4733. data = image->dataBlock;
  4734. shapeIndex = getImageShapeIndex(*image);
  4735. if ( data->useEyeNode && (data->animateOnServer || isGhost()) && isFirstPerson() && data->eyeMountNode[shapeIndex] != -1 && data->eyeNode[shapeIndex] != -1 )
  4736. {
  4737. imageIndex = i;
  4738. break;
  4739. }
  4740. }
  4741. }
  4742. if (imageIndex >= 0)
  4743. {
  4744. // Get the image's eye node's position relative to the eye mount node
  4745. MatrixF mountTransform = image->shapeInstance[shapeIndex]->mNodeTransforms[data->eyeMountNode[shapeIndex]];
  4746. Point3F eyeMountNodePos = mountTransform.getPosition();
  4747. mountTransform = image->shapeInstance[shapeIndex]->mNodeTransforms[data->eyeNode[shapeIndex]];
  4748. Point3F eyeNodePos = mountTransform.getPosition() - eyeMountNodePos;
  4749. // Now transform to the image's eye node (position only)
  4750. MatrixF xfm(true);
  4751. xfm.setPosition(eyeNodePos);
  4752. mat->mul(xfm);
  4753. }
  4754. }
  4755. void Player::getEyeBaseTransform(MatrixF* mat, bool includeBank)
  4756. {
  4757. // Eye transform in world space. We only use the eye position
  4758. // from the animation and supply our own rotation.
  4759. MatrixF pmat,xmat,zmat;
  4760. if(!isGhost())
  4761. mShapeInstance->animate();
  4762. xmat.set(EulerF(mHead.x, 0.0f, 0.0f));
  4763. if (mUseHeadZCalc)
  4764. zmat.set(EulerF(0.0f, 0.0f, mHead.z));
  4765. else
  4766. zmat.identity();
  4767. if(includeBank && mDataBlock->cameraCanBank)
  4768. {
  4769. // Take mHead.y into account to bank the camera
  4770. MatrixF imat;
  4771. imat.mul(zmat, xmat);
  4772. MatrixF ymat;
  4773. ymat.set(EulerF(0.0f, mHead.y, 0.0f));
  4774. pmat.mul(imat, ymat);
  4775. }
  4776. else
  4777. {
  4778. pmat.mul(zmat,xmat);
  4779. }
  4780. F32 *dp = pmat;
  4781. F32* sp;
  4782. MatrixF eyeMat(true);
  4783. if (mDataBlock->eyeNode != -1)
  4784. {
  4785. sp = mShapeInstance->mNodeTransforms[mDataBlock->eyeNode];
  4786. }
  4787. else
  4788. {
  4789. Point3F center;
  4790. mObjBox.getCenter(&center);
  4791. eyeMat.setPosition(center);
  4792. sp = eyeMat;
  4793. }
  4794. const Point3F& scale = getScale();
  4795. dp[3] = sp[3] * scale.x;
  4796. dp[7] = sp[7] * scale.y;
  4797. dp[11] = sp[11] * scale.z;
  4798. mat->mul(getTransform(),pmat);
  4799. }
  4800. void Player::getRenderEyeTransform(MatrixF* mat)
  4801. {
  4802. getRenderEyeBaseTransform(mat, true);
  4803. // Use the first image that is set to use the eye node
  4804. for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
  4805. {
  4806. MountedImage& image = mMountedImageList[i];
  4807. if (image.dataBlock)
  4808. {
  4809. ShapeBaseImageData& data = *image.dataBlock;
  4810. U32 shapeIndex = getImageShapeIndex(image);
  4811. if ( data.useEyeNode && isFirstPerson() && data.eyeMountNode[shapeIndex] != -1 && data.eyeNode[shapeIndex] != -1 )
  4812. {
  4813. // Get the eye node's position relative to the eye mount node
  4814. MatrixF mountTransform = image.shapeInstance[shapeIndex]->mNodeTransforms[data.eyeMountNode[shapeIndex]];
  4815. Point3F eyeMountNodePos = mountTransform.getPosition();
  4816. mountTransform = image.shapeInstance[shapeIndex]->mNodeTransforms[data.eyeNode[shapeIndex]];
  4817. Point3F eyeNodePos = mountTransform.getPosition() - eyeMountNodePos;
  4818. // Now transform to the image's eye node (position only)
  4819. MatrixF xfm(true);
  4820. xfm.setPosition(eyeNodePos);
  4821. mat->mul(xfm);
  4822. return;
  4823. }
  4824. }
  4825. }
  4826. }
  4827. void Player::getRenderEyeBaseTransform(MatrixF* mat, bool includeBank)
  4828. {
  4829. // Eye transform in world space. We only use the eye position
  4830. // from the animation and supply our own rotation.
  4831. MatrixF pmat,xmat,zmat;
  4832. xmat.set(EulerF(delta.head.x + delta.headVec.x * delta.dt, 0.0f, 0.0f));
  4833. if (mUseHeadZCalc)
  4834. zmat.set(EulerF(0.0f, 0.0f, delta.head.z + delta.headVec.z * delta.dt));
  4835. else
  4836. zmat.identity();
  4837. if(includeBank && mDataBlock->cameraCanBank)
  4838. {
  4839. // Take mHead.y delta into account to bank the camera
  4840. MatrixF imat;
  4841. imat.mul(zmat, xmat);
  4842. MatrixF ymat;
  4843. ymat.set(EulerF(0.0f, delta.head.y + delta.headVec.y * delta.dt, 0.0f));
  4844. pmat.mul(imat, ymat);
  4845. }
  4846. else
  4847. {
  4848. pmat.mul(zmat,xmat);
  4849. }
  4850. F32 *dp = pmat;
  4851. F32* sp;
  4852. MatrixF eyeMat(true);
  4853. if (mDataBlock->eyeNode != -1)
  4854. {
  4855. sp = mShapeInstance->mNodeTransforms[mDataBlock->eyeNode];
  4856. }
  4857. else
  4858. {
  4859. // Use the center of the Player's bounding box for the eye position.
  4860. Point3F center;
  4861. mObjBox.getCenter(&center);
  4862. eyeMat.setPosition(center);
  4863. sp = eyeMat;
  4864. }
  4865. // Only use position of eye node, and take Player's scale
  4866. // into account.
  4867. const Point3F& scale = getScale();
  4868. dp[3] = sp[3] * scale.x;
  4869. dp[7] = sp[7] * scale.y;
  4870. dp[11] = sp[11] * scale.z;
  4871. mat->mul(getRenderTransform(), pmat);
  4872. }
  4873. void Player::getMuzzleTransform(U32 imageSlot,MatrixF* mat)
  4874. {
  4875. disableHeadZCalc();
  4876. MatrixF nmat;
  4877. Parent::getRetractionTransform(imageSlot,&nmat);
  4878. MatrixF smat;
  4879. Parent::getImageTransform(imageSlot,&smat);
  4880. disableCollision();
  4881. // See if we are pushed into a wall...
  4882. if (getDamageState() == Enabled) {
  4883. Point3F start, end;
  4884. smat.getColumn(3, &start);
  4885. nmat.getColumn(3, &end);
  4886. RayInfo rinfo;
  4887. if (getContainer()->castRay(start, end, sCollisionMoveMask, &rinfo)) {
  4888. Point3F finalPoint;
  4889. finalPoint.interpolate(start, end, rinfo.t);
  4890. nmat.setColumn(3, finalPoint);
  4891. }
  4892. else
  4893. Parent::getMuzzleTransform(imageSlot,&nmat);
  4894. }
  4895. else
  4896. Parent::getMuzzleTransform(imageSlot,&nmat);
  4897. enableCollision();
  4898. enableHeadZCalc();
  4899. *mat = nmat;
  4900. }
  4901. void Player::getRenderMuzzleTransform(U32 imageSlot,MatrixF* mat)
  4902. {
  4903. disableHeadZCalc();
  4904. MatrixF nmat;
  4905. Parent::getRenderRetractionTransform(imageSlot,&nmat);
  4906. MatrixF smat;
  4907. Parent::getRenderImageTransform(imageSlot,&smat);
  4908. disableCollision();
  4909. // See if we are pushed into a wall...
  4910. if (getDamageState() == Enabled)
  4911. {
  4912. Point3F start, end;
  4913. smat.getColumn(3, &start);
  4914. nmat.getColumn(3, &end);
  4915. RayInfo rinfo;
  4916. if (getContainer()->castRay(start, end, sCollisionMoveMask, &rinfo)) {
  4917. Point3F finalPoint;
  4918. finalPoint.interpolate(start, end, rinfo.t);
  4919. nmat.setColumn(3, finalPoint);
  4920. }
  4921. else
  4922. {
  4923. Parent::getRenderMuzzleTransform(imageSlot,&nmat);
  4924. }
  4925. }
  4926. else
  4927. {
  4928. Parent::getRenderMuzzleTransform(imageSlot,&nmat);
  4929. }
  4930. enableCollision();
  4931. enableHeadZCalc();
  4932. *mat = nmat;
  4933. }
  4934. void Player::getMuzzleVector(U32 imageSlot,VectorF* vec)
  4935. {
  4936. MatrixF mat;
  4937. getMuzzleTransform(imageSlot,&mat);
  4938. GameConnection * gc = getControllingClient();
  4939. if (gc && !gc->isAIControlled())
  4940. {
  4941. MountedImage& image = mMountedImageList[imageSlot];
  4942. bool fp = gc->isFirstPerson();
  4943. if ((fp && image.dataBlock->correctMuzzleVector) ||
  4944. (!fp && image.dataBlock->correctMuzzleVectorTP))
  4945. {
  4946. disableHeadZCalc();
  4947. if (getCorrectedAim(mat, vec))
  4948. {
  4949. enableHeadZCalc();
  4950. return;
  4951. }
  4952. enableHeadZCalc();
  4953. }
  4954. }
  4955. mat.getColumn(1,vec);
  4956. }
  4957. void Player::renderMountedImage( U32 imageSlot, TSRenderState &rstate, SceneRenderState *state )
  4958. {
  4959. GFX->pushWorldMatrix();
  4960. MatrixF world;
  4961. MountedImage& image = mMountedImageList[imageSlot];
  4962. ShapeBaseImageData& data = *image.dataBlock;
  4963. U32 imageShapeIndex;
  4964. if ( state->isShadowPass() )
  4965. {
  4966. // Force the standard image shapes for the shadow pass.
  4967. imageShapeIndex = ShapeBaseImageData::StandardImageShape;
  4968. }
  4969. else
  4970. {
  4971. imageShapeIndex = getImageShapeIndex(image);
  4972. }
  4973. if ( !state->isShadowPass() && isFirstPerson() && (data.useEyeOffset || (data.useEyeNode && data.eyeMountNode[imageShapeIndex] != -1)) )
  4974. {
  4975. if (data.useEyeNode && data.eyeMountNode[imageShapeIndex] != -1)
  4976. {
  4977. MatrixF nmat;
  4978. getRenderEyeBaseTransform(&nmat, mDataBlock->mountedImagesBank);
  4979. MatrixF offsetMat = image.shapeInstance[imageShapeIndex]->mNodeTransforms[data.eyeMountNode[imageShapeIndex]];
  4980. offsetMat.affineInverse();
  4981. world.mul(nmat,offsetMat);
  4982. }
  4983. else
  4984. {
  4985. MatrixF nmat;
  4986. getRenderEyeBaseTransform(&nmat, mDataBlock->mountedImagesBank);
  4987. world.mul(nmat,data.eyeOffset);
  4988. }
  4989. if ( imageSlot == 0 )
  4990. {
  4991. MatrixF nmat;
  4992. MatrixF smat;
  4993. getRenderRetractionTransform(0,&nmat);
  4994. getRenderImageTransform(0,&smat);
  4995. // See if we are pushed into a wall...
  4996. Point3F start, end;
  4997. smat.getColumn(3, &start);
  4998. nmat.getColumn(3, &end);
  4999. Point3F displace = (start - end) * mWeaponBackFraction;
  5000. world.setPosition( world.getPosition() + displace );
  5001. }
  5002. }
  5003. else
  5004. {
  5005. MatrixF nmat;
  5006. getRenderMountTransform( 0.0f, data.mountPoint, MatrixF::Identity, &nmat);
  5007. world.mul(nmat,data.mountTransform[imageShapeIndex]);
  5008. }
  5009. GFX->setWorldMatrix( world );
  5010. image.shapeInstance[imageShapeIndex]->animate();
  5011. image.shapeInstance[imageShapeIndex]->render( rstate );
  5012. // Render the first person mount image shape?
  5013. if (!state->isShadowPass() && imageShapeIndex == ShapeBaseImageData::FirstPersonImageShape && mShapeFPInstance[imageSlot])
  5014. {
  5015. mShapeFPInstance[imageSlot]->animate();
  5016. mShapeFPInstance[imageSlot]->render( rstate );
  5017. }
  5018. GFX->popWorldMatrix();
  5019. }
  5020. // Bot aiming code calls this frequently and will work fine without the check
  5021. // for being pushed into a wall, which shows up on profile at ~ 3% (eight bots)
  5022. void Player::getMuzzlePointAI(U32 imageSlot, Point3F* point)
  5023. {
  5024. MatrixF nmat;
  5025. Parent::getMuzzleTransform(imageSlot, &nmat);
  5026. // If we are in one of the standard player animations, adjust the
  5027. // muzzle to point in the direction we are looking.
  5028. if (mActionAnimation.action < PlayerData::NumTableActionAnims)
  5029. {
  5030. MatrixF xmat;
  5031. xmat.set(EulerF(mHead.x, 0, 0));
  5032. MatrixF result;
  5033. result.mul(getTransform(), xmat);
  5034. F32 *sp = nmat, *dp = result;
  5035. dp[3] = sp[3]; dp[7] = sp[7]; dp[11] = sp[11];
  5036. result.getColumn(3, point);
  5037. }
  5038. else
  5039. nmat.getColumn(3, point);
  5040. }
  5041. void Player::getCameraParameters(F32 *min,F32* max,Point3F* off,MatrixF* rot)
  5042. {
  5043. if (!mControlObject.isNull() && mControlObject == getObjectMount()) {
  5044. mControlObject->getCameraParameters(min,max,off,rot);
  5045. return;
  5046. }
  5047. const Point3F& scale = getScale();
  5048. *min = mDataBlock->cameraMinDist * scale.y;
  5049. *max = mDataBlock->cameraMaxDist * scale.y;
  5050. off->set(0.0f, 0.0f, 0.0f);
  5051. rot->identity();
  5052. }
  5053. //----------------------------------------------------------------------------
  5054. Point3F Player::getVelocity() const
  5055. {
  5056. return mVelocity;
  5057. }
  5058. F32 Player::getSpeed() const
  5059. {
  5060. return mVelocity.len();
  5061. }
  5062. void Player::setVelocity(const VectorF& vel)
  5063. {
  5064. AssertFatal( !mIsNaN( vel ), "Player::setVelocity() - The velocity is NaN!" );
  5065. mVelocity = vel;
  5066. setMaskBits(MoveMask);
  5067. }
  5068. void Player::applyImpulse(const Point3F&,const VectorF& vec)
  5069. {
  5070. AssertFatal( !mIsNaN( vec ), "Player::applyImpulse() - The vector is NaN!" );
  5071. // Players ignore angular velocity
  5072. VectorF vel;
  5073. vel.x = vec.x / getMass();
  5074. vel.y = vec.y / getMass();
  5075. vel.z = vec.z / getMass();
  5076. // Make sure the impulse isn't too big
  5077. F32 len = vel.magnitudeSafe();
  5078. if (len > sMaxImpulseVelocity)
  5079. {
  5080. Point3F excess = vel * ( 1.0f - (sMaxImpulseVelocity / len ) );
  5081. vel -= excess;
  5082. }
  5083. setVelocity(mVelocity + vel);
  5084. }
  5085. //----------------------------------------------------------------------------
  5086. bool Player::castRay(const Point3F &start, const Point3F &end, RayInfo* info)
  5087. {
  5088. // In standard Torque there's a rather brute force culling of all
  5089. // non-enabled players (corpses) from the ray cast. But, to
  5090. // demonstrate a resurrection spell, we need corpses to be
  5091. // selectable, so this code change allows consideration of corpses
  5092. // in the ray cast if corpsesHiddenFromRayCast is set to false.
  5093. if (sCorpsesHiddenFromRayCast && getDamageState() != Enabled)
  5094. return false;
  5095. // Collide against bounding box. Need at least this for the editor.
  5096. F32 st,et,fst = 0.0f,fet = 1.0f;
  5097. F32 *bmin = &mObjBox.minExtents.x;
  5098. F32 *bmax = &mObjBox.maxExtents.x;
  5099. F32 const *si = &start.x;
  5100. F32 const *ei = &end.x;
  5101. for (S32 i = 0; i < 3; i++) {
  5102. if (*si < *ei) {
  5103. if (*si > *bmax || *ei < *bmin)
  5104. return false;
  5105. F32 di = *ei - *si;
  5106. st = (*si < *bmin)? (*bmin - *si) / di: 0.0f;
  5107. et = (*ei > *bmax)? (*bmax - *si) / di: 1.0f;
  5108. }
  5109. else {
  5110. if (*ei > *bmax || *si < *bmin)
  5111. return false;
  5112. F32 di = *ei - *si;
  5113. st = (*si > *bmax)? (*bmax - *si) / di: 0.0f;
  5114. et = (*ei < *bmin)? (*bmin - *si) / di: 1.0f;
  5115. }
  5116. if (st > fst) fst = st;
  5117. if (et < fet) fet = et;
  5118. if (fet < fst)
  5119. return false;
  5120. bmin++; bmax++;
  5121. si++; ei++;
  5122. }
  5123. info->normal = start - end;
  5124. info->normal.normalizeSafe();
  5125. getTransform().mulV( info->normal );
  5126. info->t = fst;
  5127. info->object = this;
  5128. info->point.interpolate(start,end,fst);
  5129. info->material = 0;
  5130. return true;
  5131. }
  5132. //----------------------------------------------------------------------------
  5133. static MatrixF IMat(1);
  5134. bool Player::buildPolyList(PolyListContext, AbstractPolyList* polyList, const Box3F&, const SphereF&)
  5135. {
  5136. // Collision with the player is always against the player's object
  5137. // space bounding box axis aligned in world space.
  5138. Point3F pos;
  5139. getTransform().getColumn(3,&pos);
  5140. IMat.setColumn(3,pos);
  5141. polyList->setTransform(&IMat, Point3F(1.0f,1.0f,1.0f));
  5142. polyList->setObject(this);
  5143. polyList->addBox(mObjBox);
  5144. return true;
  5145. }
  5146. void Player::buildConvex(const Box3F& box, Convex* convex)
  5147. {
  5148. if (mShapeInstance == NULL)
  5149. return;
  5150. // These should really come out of a pool
  5151. mConvexList->collectGarbage();
  5152. Box3F realBox = box;
  5153. mWorldToObj.mul(realBox);
  5154. realBox.minExtents.convolveInverse(mObjScale);
  5155. realBox.maxExtents.convolveInverse(mObjScale);
  5156. if (realBox.isOverlapped(getObjBox()) == false)
  5157. return;
  5158. Convex* cc = 0;
  5159. CollisionWorkingList& wl = convex->getWorkingList();
  5160. for (CollisionWorkingList* itr = wl.wLink.mNext; itr != &wl; itr = itr->wLink.mNext) {
  5161. if (itr->mConvex->getType() == BoxConvexType &&
  5162. itr->mConvex->getObject() == this) {
  5163. cc = itr->mConvex;
  5164. break;
  5165. }
  5166. }
  5167. if (cc)
  5168. return;
  5169. // Create a new convex.
  5170. BoxConvex* cp = new OrthoBoxConvex;
  5171. mConvexList->registerObject(cp);
  5172. convex->addToWorkingList(cp);
  5173. cp->init(this);
  5174. mObjBox.getCenter(&cp->mCenter);
  5175. cp->mSize.x = mObjBox.len_x() / 2.0f;
  5176. cp->mSize.y = mObjBox.len_y() / 2.0f;
  5177. cp->mSize.z = mObjBox.len_z() / 2.0f;
  5178. }
  5179. //----------------------------------------------------------------------------
  5180. void Player::updateWorkingCollisionSet()
  5181. {
  5182. // First, we need to adjust our velocity for possible acceleration. It is assumed
  5183. // that we will never accelerate more than 20 m/s for gravity, plus 10 m/s for
  5184. // jetting, and an equivalent 10 m/s for jumping. We also assume that the
  5185. // working list is updated on a Tick basis, which means we only expand our
  5186. // box by the possible movement in that tick.
  5187. Point3F scaledVelocity = mVelocity * TickSec;
  5188. F32 len = scaledVelocity.len();
  5189. F32 newLen = len + (10.0f * TickSec);
  5190. // Check to see if it is actually necessary to construct the new working list,
  5191. // or if we can use the cached version from the last query. We use the x
  5192. // component of the min member of the mWorkingQueryBox, which is lame, but
  5193. // it works ok.
  5194. bool updateSet = false;
  5195. Box3F convexBox = mConvex.getBoundingBox(getTransform(), getScale());
  5196. F32 l = (newLen * 1.1f) + 0.1f; // from Convex::updateWorkingList
  5197. const Point3F lPoint( l, l, l );
  5198. convexBox.minExtents -= lPoint;
  5199. convexBox.maxExtents += lPoint;
  5200. // Check containment
  5201. if (mWorkingQueryBox.minExtents.x != -1e9f)
  5202. {
  5203. if (mWorkingQueryBox.isContained(convexBox) == false)
  5204. // Needed region is outside the cached region. Update it.
  5205. updateSet = true;
  5206. }
  5207. else
  5208. {
  5209. // Must update
  5210. updateSet = true;
  5211. }
  5212. // Actually perform the query, if necessary
  5213. if (updateSet == true) {
  5214. const Point3F twolPoint( 2.0f * l, 2.0f * l, 2.0f * l );
  5215. mWorkingQueryBox = convexBox;
  5216. mWorkingQueryBox.minExtents -= twolPoint;
  5217. mWorkingQueryBox.maxExtents += twolPoint;
  5218. disableCollision();
  5219. mConvex.updateWorkingList(mWorkingQueryBox,
  5220. isGhost() ? sClientCollisionContactMask : sServerCollisionContactMask);
  5221. enableCollision();
  5222. }
  5223. }
  5224. //----------------------------------------------------------------------------
  5225. void Player::writePacketData(GameConnection *connection, BitStream *stream)
  5226. {
  5227. Parent::writePacketData(connection, stream);
  5228. stream->writeInt(mState,NumStateBits);
  5229. if (stream->writeFlag(mState == RecoverState))
  5230. stream->writeInt(mRecoverTicks,PlayerData::RecoverDelayBits);
  5231. if (stream->writeFlag(mJumpDelay > 0))
  5232. stream->writeInt(mJumpDelay,PlayerData::JumpDelayBits);
  5233. Point3F pos;
  5234. getTransform().getColumn(3,&pos);
  5235. if (stream->writeFlag(!isMounted())) {
  5236. // Will get position from mount
  5237. stream->setCompressionPoint(pos);
  5238. stream->write(pos.x);
  5239. stream->write(pos.y);
  5240. stream->write(pos.z);
  5241. stream->write(mVelocity.x);
  5242. stream->write(mVelocity.y);
  5243. stream->write(mVelocity.z);
  5244. stream->writeInt(mJumpSurfaceLastContact > 15 ? 15 : mJumpSurfaceLastContact, 4);
  5245. if (stream->writeFlag(!mAllowSprinting || !mAllowCrouching || !mAllowProne || !mAllowJumping || !mAllowJetJumping || !mAllowSwimming))
  5246. {
  5247. stream->writeFlag(mAllowJumping);
  5248. stream->writeFlag(mAllowJetJumping);
  5249. stream->writeFlag(mAllowSprinting);
  5250. stream->writeFlag(mAllowCrouching);
  5251. stream->writeFlag(mAllowProne);
  5252. stream->writeFlag(mAllowSwimming);
  5253. }
  5254. }
  5255. stream->write(mHead.x);
  5256. if(stream->writeFlag(mDataBlock->cameraCanBank))
  5257. {
  5258. // Include mHead.y to allow for camera banking
  5259. stream->write(mHead.y);
  5260. }
  5261. stream->write(mHead.z);
  5262. stream->write(mRot.z);
  5263. if (mControlObject) {
  5264. S32 gIndex = connection->getGhostIndex(mControlObject);
  5265. if (stream->writeFlag(gIndex != -1)) {
  5266. stream->writeInt(gIndex,NetConnection::GhostIdBitSize);
  5267. mControlObject->writePacketData(connection, stream);
  5268. }
  5269. }
  5270. else
  5271. stream->writeFlag(false);
  5272. }
  5273. void Player::readPacketData(GameConnection *connection, BitStream *stream)
  5274. {
  5275. Parent::readPacketData(connection, stream);
  5276. mState = (ActionState)stream->readInt(NumStateBits);
  5277. if (stream->readFlag())
  5278. mRecoverTicks = stream->readInt(PlayerData::RecoverDelayBits);
  5279. if (stream->readFlag())
  5280. mJumpDelay = stream->readInt(PlayerData::JumpDelayBits);
  5281. else
  5282. mJumpDelay = 0;
  5283. Point3F pos,rot;
  5284. if (stream->readFlag()) {
  5285. // Only written if we are not mounted
  5286. stream->read(&pos.x);
  5287. stream->read(&pos.y);
  5288. stream->read(&pos.z);
  5289. stream->read(&mVelocity.x);
  5290. stream->read(&mVelocity.y);
  5291. stream->read(&mVelocity.z);
  5292. stream->setCompressionPoint(pos);
  5293. delta.pos = pos;
  5294. mJumpSurfaceLastContact = stream->readInt(4);
  5295. if (stream->readFlag())
  5296. {
  5297. mAllowJumping = stream->readFlag();
  5298. mAllowJetJumping = stream->readFlag();
  5299. mAllowSprinting = stream->readFlag();
  5300. mAllowCrouching = stream->readFlag();
  5301. mAllowProne = stream->readFlag();
  5302. mAllowSwimming = stream->readFlag();
  5303. }
  5304. else
  5305. {
  5306. mAllowJumping = true;
  5307. mAllowJetJumping = true;
  5308. mAllowSprinting = true;
  5309. mAllowCrouching = true;
  5310. mAllowProne = true;
  5311. mAllowSwimming = true;
  5312. }
  5313. }
  5314. else
  5315. pos = delta.pos;
  5316. stream->read(&mHead.x);
  5317. if(stream->readFlag())
  5318. {
  5319. // Include mHead.y to allow for camera banking
  5320. stream->read(&mHead.y);
  5321. }
  5322. stream->read(&mHead.z);
  5323. stream->read(&rot.z);
  5324. rot.x = rot.y = 0;
  5325. if (!ignore_updates)
  5326. setPosition(pos,rot);
  5327. delta.head = mHead;
  5328. delta.rot = rot;
  5329. if (stream->readFlag()) {
  5330. S32 gIndex = stream->readInt(NetConnection::GhostIdBitSize);
  5331. ShapeBase* obj = static_cast<ShapeBase*>(connection->resolveGhost(gIndex));
  5332. setControlObject(obj);
  5333. obj->readPacketData(connection, stream);
  5334. }
  5335. else
  5336. setControlObject(0);
  5337. }
  5338. U32 Player::packUpdate(NetConnection *con, U32 mask, BitStream *stream)
  5339. {
  5340. U32 retMask = Parent::packUpdate(con, mask, stream);
  5341. if (stream->writeFlag((mask & ImpactMask) && !(mask & InitialUpdateMask)))
  5342. stream->writeInt(mImpactSound, PlayerData::ImpactBits);
  5343. if (stream->writeFlag(mask & ActionMask &&
  5344. mActionAnimation.action != PlayerData::NullAnimation &&
  5345. mActionAnimation.action >= PlayerData::NumTableActionAnims)) {
  5346. stream->writeInt(mActionAnimation.action,PlayerData::ActionAnimBits);
  5347. stream->writeFlag(mActionAnimation.holdAtEnd);
  5348. stream->writeFlag(mActionAnimation.atEnd);
  5349. stream->writeFlag(mActionAnimation.firstPerson);
  5350. if (!mActionAnimation.atEnd) {
  5351. // If somewhere in middle on initial update, must send position-
  5352. F32 where = mShapeInstance->getPos(mActionAnimation.thread);
  5353. if (stream->writeFlag((mask & InitialUpdateMask) != 0 && where > 0))
  5354. stream->writeSignedFloat(where, 6);
  5355. }
  5356. }
  5357. if (stream->writeFlag(mask & ActionMask &&
  5358. mArmAnimation.action != PlayerData::NullAnimation &&
  5359. (!(mask & InitialUpdateMask) ||
  5360. mArmAnimation.action != mDataBlock->lookAction))) {
  5361. stream->writeInt(mArmAnimation.action,PlayerData::ActionAnimBits);
  5362. }
  5363. retMask = afx_packUpdate(con, mask, stream, retMask);
  5364. // The rest of the data is part of the control object packet update.
  5365. // If we're controlled by this client, we don't need to send it.
  5366. // we only need to send it if this is the initial update - in that case,
  5367. // the client won't know this is the control object yet.
  5368. if(stream->writeFlag(getControllingClient() == con && !(mask & InitialUpdateMask)))
  5369. return(retMask);
  5370. if (stream->writeFlag(mask & MoveMask))
  5371. {
  5372. stream->writeFlag(mFalling);
  5373. stream->writeFlag(mSwimming);
  5374. stream->writeFlag(mJetting);
  5375. stream->writeInt(mPose, NumPoseBits);
  5376. stream->writeInt(mState,NumStateBits);
  5377. if (stream->writeFlag(mState == RecoverState))
  5378. stream->writeInt(mRecoverTicks,PlayerData::RecoverDelayBits);
  5379. Point3F pos;
  5380. getTransform().getColumn(3,&pos);
  5381. stream->writeCompressedPoint(pos);
  5382. F32 len = mVelocity.len();
  5383. if(stream->writeFlag(len > 0.02f))
  5384. {
  5385. Point3F outVel = mVelocity;
  5386. outVel *= 1.0f/len;
  5387. stream->writeNormalVector(outVel, 10);
  5388. len *= 32.0f; // 5 bits of fraction
  5389. if(len > 8191)
  5390. len = 8191;
  5391. stream->writeInt((S32)len, 13);
  5392. }
  5393. stream->writeFloat(mRot.z / M_2PI_F, 7);
  5394. stream->writeSignedFloat(mHead.x / (mDataBlock->maxLookAngle - mDataBlock->minLookAngle), 6);
  5395. stream->writeSignedFloat(mHead.z / mDataBlock->maxFreelookAngle, 6);
  5396. delta.move.pack(stream);
  5397. stream->writeFlag(!(mask & NoWarpMask));
  5398. }
  5399. // Ghost need energy to predict reliably
  5400. if (mDataBlock->maxEnergy > 0.f)
  5401. stream->writeFloat(getEnergyLevel() / mDataBlock->maxEnergy, EnergyLevelBits);
  5402. else
  5403. stream->writeFloat(0.f, EnergyLevelBits);
  5404. return retMask;
  5405. }
  5406. void Player::unpackUpdate(NetConnection *con, BitStream *stream)
  5407. {
  5408. Parent::unpackUpdate(con,stream);
  5409. if (stream->readFlag())
  5410. mImpactSound = stream->readInt(PlayerData::ImpactBits);
  5411. // Server specified action animation
  5412. if (stream->readFlag()) {
  5413. U32 action = stream->readInt(PlayerData::ActionAnimBits);
  5414. bool hold = stream->readFlag();
  5415. bool atEnd = stream->readFlag();
  5416. bool fsp = stream->readFlag();
  5417. F32 animPos = -1.0f;
  5418. if (!atEnd && stream->readFlag())
  5419. animPos = stream->readSignedFloat(6);
  5420. if (isProperlyAdded()) {
  5421. setActionThread(action,true,hold,true,fsp);
  5422. bool inDeath = inDeathAnim();
  5423. if (atEnd)
  5424. {
  5425. mShapeInstance->clearTransition(mActionAnimation.thread);
  5426. mShapeInstance->setPos(mActionAnimation.thread,
  5427. mActionAnimation.forward? 1: 0);
  5428. if (inDeath)
  5429. mDeath.lastPos = 1.0f;
  5430. }
  5431. else if (animPos > 0) {
  5432. mShapeInstance->setPos(mActionAnimation.thread, animPos);
  5433. if (inDeath)
  5434. mDeath.lastPos = animPos;
  5435. }
  5436. // mMountPending suppresses tickDelay countdown so players will sit until
  5437. // their mount, or another animation, comes through (or 13 seconds elapses).
  5438. mMountPending = (S32) (inSittingAnim() ? sMountPendingTickWait : 0);
  5439. }
  5440. else {
  5441. mActionAnimation.action = action;
  5442. mActionAnimation.holdAtEnd = hold;
  5443. mActionAnimation.atEnd = atEnd;
  5444. mActionAnimation.firstPerson = fsp;
  5445. }
  5446. }
  5447. // Server specified arm animation
  5448. if (stream->readFlag()) {
  5449. U32 action = stream->readInt(PlayerData::ActionAnimBits);
  5450. if (isProperlyAdded())
  5451. setArmThread(action);
  5452. else
  5453. mArmAnimation.action = action;
  5454. }
  5455. afx_unpackUpdate(con, stream);
  5456. // Done if controlled by client ( and not initial update )
  5457. if(stream->readFlag())
  5458. return;
  5459. // MoveMask
  5460. if (stream->readFlag()) {
  5461. mPredictionCount = sMaxPredictionTicks;
  5462. mFalling = stream->readFlag();
  5463. mSwimming = stream->readFlag();
  5464. mJetting = stream->readFlag();
  5465. mPose = (Pose)(stream->readInt(NumPoseBits));
  5466. ActionState actionState = (ActionState)stream->readInt(NumStateBits);
  5467. if (stream->readFlag()) {
  5468. mRecoverTicks = stream->readInt(PlayerData::RecoverDelayBits);
  5469. setState(actionState, mRecoverTicks);
  5470. }
  5471. else
  5472. setState(actionState);
  5473. Point3F pos,rot;
  5474. stream->readCompressedPoint(&pos);
  5475. F32 speed = mVelocity.len();
  5476. if(stream->readFlag())
  5477. {
  5478. stream->readNormalVector(&mVelocity, 10);
  5479. mVelocity *= stream->readInt(13) / 32.0f;
  5480. }
  5481. else
  5482. {
  5483. mVelocity.set(0.0f, 0.0f, 0.0f);
  5484. }
  5485. rot.y = rot.x = 0.0f;
  5486. rot.z = stream->readFloat(7) * M_2PI_F;
  5487. mHead.x = stream->readSignedFloat(6) * (mDataBlock->maxLookAngle - mDataBlock->minLookAngle);
  5488. mHead.z = stream->readSignedFloat(6) * mDataBlock->maxFreelookAngle;
  5489. delta.move.unpack(stream);
  5490. delta.head = mHead;
  5491. delta.headVec.set(0.0f, 0.0f, 0.0f);
  5492. if (stream->readFlag() && isProperlyAdded())
  5493. {
  5494. // Determine number of ticks to warp based on the average
  5495. // of the client and server velocities.
  5496. delta.warpOffset = pos - delta.pos;
  5497. F32 as = (speed + mVelocity.len()) * 0.5f * TickSec;
  5498. F32 dt = (as > 0.00001f) ? delta.warpOffset.len() / as: sMaxWarpTicks;
  5499. delta.warpTicks = (S32)((dt > sMinWarpTicks) ? getMax(mFloor(dt + 0.5f), 1.0f) : 0.0f);
  5500. if (delta.warpTicks)
  5501. {
  5502. // Setup the warp to start on the next tick.
  5503. if (delta.warpTicks > sMaxWarpTicks)
  5504. delta.warpTicks = sMaxWarpTicks;
  5505. delta.warpOffset /= (F32)delta.warpTicks;
  5506. delta.rotOffset = rot - delta.rot;
  5507. // Ignore small rotation differences
  5508. if (mFabs(delta.rotOffset.z) < 0.001f)
  5509. delta.rotOffset.z = 0;
  5510. // Wrap rotation to +/-PI
  5511. if(delta.rotOffset.z < - M_PI_F)
  5512. delta.rotOffset.z += M_2PI_F;
  5513. else if(delta.rotOffset.z > M_PI_F)
  5514. delta.rotOffset.z -= M_2PI_F;
  5515. delta.rotOffset /= (F32)delta.warpTicks;
  5516. }
  5517. else
  5518. {
  5519. // Going to skip the warp, server and client are real close.
  5520. // Adjust the frame interpolation to move smoothly to the
  5521. // new position within the current tick.
  5522. Point3F cp = delta.pos + delta.posVec * delta.dt;
  5523. if (delta.dt == 0)
  5524. {
  5525. delta.posVec.set(0.0f, 0.0f, 0.0f);
  5526. delta.rotVec.set(0.0f, 0.0f, 0.0f);
  5527. }
  5528. else
  5529. {
  5530. F32 dti = 1.0f / delta.dt;
  5531. delta.posVec = (cp - pos) * dti;
  5532. delta.rotVec.z = mRot.z - rot.z;
  5533. if(delta.rotVec.z > M_PI_F)
  5534. delta.rotVec.z -= M_2PI_F;
  5535. else if(delta.rotVec.z < -M_PI_F)
  5536. delta.rotVec.z += M_2PI_F;
  5537. delta.rotVec.z *= dti;
  5538. }
  5539. delta.pos = pos;
  5540. delta.rot = rot;
  5541. if (!ignore_updates)
  5542. setPosition(pos,rot);
  5543. }
  5544. }
  5545. else
  5546. {
  5547. // Set the player to the server position
  5548. delta.pos = pos;
  5549. delta.rot = rot;
  5550. delta.posVec.set(0.0f, 0.0f, 0.0f);
  5551. delta.rotVec.set(0.0f, 0.0f, 0.0f);
  5552. delta.warpTicks = 0;
  5553. delta.dt = 0.0f;
  5554. if (!ignore_updates)
  5555. setPosition(pos,rot);
  5556. }
  5557. }
  5558. F32 energy = stream->readFloat(EnergyLevelBits) * mDataBlock->maxEnergy;
  5559. setEnergyLevel(energy);
  5560. }
  5561. //----------------------------------------------------------------------------
  5562. DefineEngineMethod( Player, getPose, const char*, (),,
  5563. "@brief Get the name of the player's current pose.\n\n"
  5564. "The pose is one of the following:\n\n<ul>"
  5565. "<li>Stand - Standard movement pose.</li>"
  5566. "<li>Sprint - Sprinting pose.</li>"
  5567. "<li>Crouch - Crouch pose.</li>"
  5568. "<li>Prone - Prone pose.</li>"
  5569. "<li>Swim - Swimming pose.</li></ul>\n"
  5570. "@return The current pose; one of: \"Stand\", \"Sprint\", \"Crouch\", \"Prone\", \"Swim\"\n" )
  5571. {
  5572. return object->getPoseName();
  5573. }
  5574. DefineEngineMethod( Player, allowAllPoses, void, (),,
  5575. "@brief Allow all poses a chance to occur.\n\n"
  5576. "This method resets any poses that have manually been blocked from occuring. "
  5577. "This includes the regular pose states such as sprinting, crouch, being prone "
  5578. "and swimming. It also includes being able to jump and jet jump. While this "
  5579. "is allowing these poses to occur it doesn't mean that they all can due to other "
  5580. "conditions. We're just not manually blocking them from being allowed.\n"
  5581. "@see allowJumping()\n"
  5582. "@see allowJetJumping()\n"
  5583. "@see allowSprinting()\n"
  5584. "@see allowCrouching()\n"
  5585. "@see allowProne()\n"
  5586. "@see allowSwimming()\n" )
  5587. {
  5588. object->allowAllPoses();
  5589. }
  5590. DefineEngineMethod( Player, allowJumping, void, (bool state),,
  5591. "@brief Set if the Player is allowed to jump.\n\n"
  5592. "The default is to allow jumping unless there are other environmental concerns "
  5593. "that prevent it. This method is mainly used to explicitly disallow jumping "
  5594. "at any time.\n"
  5595. "@param state Set to true to allow jumping, false to disable it.\n"
  5596. "@see allowAllPoses()\n" )
  5597. {
  5598. object->allowJumping(state);
  5599. }
  5600. DefineEngineMethod( Player, allowJetJumping, void, (bool state),,
  5601. "@brief Set if the Player is allowed to jet jump.\n\n"
  5602. "The default is to allow jet jumping unless there are other environmental concerns "
  5603. "that prevent it. This method is mainly used to explicitly disallow jet jumping "
  5604. "at any time.\n"
  5605. "@param state Set to true to allow jet jumping, false to disable it.\n"
  5606. "@see allowAllPoses()\n" )
  5607. {
  5608. object->allowJetJumping(state);
  5609. }
  5610. DefineEngineMethod( Player, allowSprinting, void, (bool state),,
  5611. "@brief Set if the Player is allowed to sprint.\n\n"
  5612. "The default is to allow sprinting unless there are other environmental concerns "
  5613. "that prevent it. This method is mainly used to explicitly disallow sprinting "
  5614. "at any time.\n"
  5615. "@param state Set to true to allow sprinting, false to disable it.\n"
  5616. "@see allowAllPoses()\n" )
  5617. {
  5618. object->allowSprinting(state);
  5619. }
  5620. DefineEngineMethod( Player, allowCrouching, void, (bool state),,
  5621. "@brief Set if the Player is allowed to crouch.\n\n"
  5622. "The default is to allow crouching unless there are other environmental concerns "
  5623. "that prevent it. This method is mainly used to explicitly disallow crouching "
  5624. "at any time.\n"
  5625. "@param state Set to true to allow crouching, false to disable it.\n"
  5626. "@see allowAllPoses()\n" )
  5627. {
  5628. object->allowCrouching(state);
  5629. }
  5630. DefineEngineMethod( Player, allowProne, void, (bool state),,
  5631. "@brief Set if the Player is allowed to go prone.\n\n"
  5632. "The default is to allow being prone unless there are other environmental concerns "
  5633. "that prevent it. This method is mainly used to explicitly disallow going prone "
  5634. "at any time.\n"
  5635. "@param state Set to true to allow being prone, false to disable it.\n"
  5636. "@see allowAllPoses()\n" )
  5637. {
  5638. object->allowProne(state);
  5639. }
  5640. DefineEngineMethod( Player, allowSwimming, void, (bool state),,
  5641. "@brief Set if the Player is allowed to swim.\n\n"
  5642. "The default is to allow swimming unless there are other environmental concerns "
  5643. "that prevent it. This method is mainly used to explicitly disallow swimming "
  5644. "at any time.\n"
  5645. "@param state Set to true to allow swimming, false to disable it.\n"
  5646. "@see allowAllPoses()\n" )
  5647. {
  5648. object->allowSwimming(state);
  5649. }
  5650. //----------------------------------------------------------------------------
  5651. DefineEngineMethod( Player, getState, const char*, (),,
  5652. "@brief Get the name of the player's current state.\n\n"
  5653. "The state is one of the following:\n\n<ul>"
  5654. "<li>Dead - The Player is dead.</li>"
  5655. "<li>Mounted - The Player is mounted to an object such as a vehicle.</li>"
  5656. "<li>Move - The Player is free to move. The usual state.</li>"
  5657. "<li>Recover - The Player is recovering from a fall. See PlayerData::recoverDelay.</li></ul>\n"
  5658. "@return The current state; one of: \"Dead\", \"Mounted\", \"Move\", \"Recover\"\n" )
  5659. {
  5660. return object->getStateName();
  5661. }
  5662. DefineEngineMethod( Player, getDamageLocation, const char*, ( Point3F pos ),,
  5663. "@brief Get the named damage location and modifier for a given world position.\n\n"
  5664. "the Player object can simulate different hit locations based on a pre-defined set "
  5665. "of PlayerData defined percentages. These hit percentages divide up the Player's "
  5666. "bounding box into different regions. The diagram below demonstrates how the various "
  5667. "PlayerData properties split up the bounding volume:\n\n"
  5668. "<img src=\"images/player_damageloc.png\">\n\n"
  5669. "While you may pass in any world position and getDamageLocation() will provide a best-fit "
  5670. "location, you should be aware that this can produce some interesting results. For example, "
  5671. "any position that is above PlayerData::boxHeadPercentage will be considered a 'head' hit, even "
  5672. "if the world position is high in the sky. Therefore it may be wise to keep the passed in point "
  5673. "to somewhere on the surface of, or within, the Player's bounding volume.\n\n"
  5674. "@note This method will not return an accurate location when the player is "
  5675. "prone or swimming.\n\n"
  5676. "@param pos A world position for which to retrieve a body region on this player.\n"
  5677. "@return a string containing two words (space separated strings), where the "
  5678. "first is a location and the second is a modifier.\n\n"
  5679. "Posible locations:<ul>"
  5680. "<li>head</li>"
  5681. "<li>torso</li>"
  5682. "<li>legs</li></ul>\n"
  5683. "Head modifiers:<ul>"
  5684. "<li>left_back</li>"
  5685. "<li>middle_back</li>"
  5686. "<li>right_back</li>"
  5687. "<li>left_middle</li>"
  5688. "<li>middle_middle</li>"
  5689. "<li>right_middle</li>"
  5690. "<li>left_front</li>"
  5691. "<li>middle_front</li>"
  5692. "<li>right_front</li></ul>\n"
  5693. "Legs/Torso modifiers:<ul>"
  5694. "<li>front_left</li>"
  5695. "<li>front_right</li>"
  5696. "<li>back_left</li>"
  5697. "<li>back_right</li></ul>\n"
  5698. "@see PlayerData::boxHeadPercentage\n"
  5699. "@see PlayerData::boxHeadFrontPercentage\n"
  5700. "@see PlayerData::boxHeadBackPercentage\n"
  5701. "@see PlayerData::boxHeadLeftPercentage\n"
  5702. "@see PlayerData::boxHeadRightPercentage\n"
  5703. "@see PlayerData::boxTorsoPercentage\n"
  5704. )
  5705. {
  5706. const char *buffer1;
  5707. const char *buffer2;
  5708. object->getDamageLocation(pos, buffer1, buffer2);
  5709. static const U32 bufSize = 128;
  5710. char *buff = Con::getReturnBuffer(bufSize);
  5711. dSprintf(buff, bufSize, "%s %s", buffer1, buffer2);
  5712. return buff;
  5713. }
  5714. DefineEngineMethod( Player, setArmThread, bool, ( const char* name ),,
  5715. "@brief Set the sequence that controls the player's arms (dynamically adjusted "
  5716. "to match look direction).\n\n"
  5717. "@param name Name of the sequence to play on the player's arms.\n"
  5718. "@return true if successful, false if failed.\n"
  5719. "@note By default the 'look' sequence is used, if available.\n")
  5720. {
  5721. return object->setArmThread( name );
  5722. }
  5723. DefineEngineMethod( Player, setActionThread, bool, ( const char* name, bool hold, bool fsp ), ( false, true ),
  5724. "@brief Set the main action sequence to play for this player.\n\n"
  5725. "@param name Name of the action sequence to set\n"
  5726. "@param hold Set to false to get a callback on the datablock when the sequence ends (PlayerData::animationDone()). "
  5727. "When set to true no callback is made.\n"
  5728. "@param fsp True if first person and none of the spine nodes in the shape should animate. False will allow the shape's "
  5729. "spine nodes to animate.\n"
  5730. "@return True if succesful, false if failed\n"
  5731. "@note The spine nodes for the Player's shape are named as follows:\n\n<ul>"
  5732. "<li>Bip01 Pelvis</li>"
  5733. "<li>Bip01 Spine</li>"
  5734. "<li>Bip01 Spine1</li>"
  5735. "<li>Bip01 Spine2</li>"
  5736. "<li>Bip01 Neck</li>"
  5737. "<li>Bip01 Head</li></ul>\n\n"
  5738. "You cannot use setActionThread() to have the Player play one of the motion "
  5739. "determined action animation sequences. These sequences are chosen based on how "
  5740. "the Player moves and the Player's current pose. The names of these sequences are:\n\n<ul>"
  5741. "<li>root</li>"
  5742. "<li>run</li>"
  5743. "<li>side</li>"
  5744. "<li>side_right</li>"
  5745. "<li>crouch_root</li>"
  5746. "<li>crouch_forward</li>"
  5747. "<li>crouch_backward</li>"
  5748. "<li>crouch_side</li>"
  5749. "<li>crouch_right</li>"
  5750. "<li>prone_root</li>"
  5751. "<li>prone_forward</li>"
  5752. "<li>prone_backward</li>"
  5753. "<li>swim_root</li>"
  5754. "<li>swim_forward</li>"
  5755. "<li>swim_backward</li>"
  5756. "<li>swim_left</li>"
  5757. "<li>swim_right</li>"
  5758. "<li>fall</li>"
  5759. "<li>jump</li>"
  5760. "<li>standjump</li>"
  5761. "<li>land</li>"
  5762. "<li>jet</li></ul>\n\n"
  5763. "If the player moves in any direction then the animation sequence set using this "
  5764. "method will be cancelled and the chosen mation-based sequence will take over. This makes "
  5765. "great for times when the Player cannot move, such as when mounted, or when it doesn't matter "
  5766. "if the action sequence changes, such as waving and saluting.\n"
  5767. "@tsexample\n"
  5768. "// Place the player in a sitting position after being mounted\n"
  5769. "%player.setActionThread( \"sitting\", true, true );\n"
  5770. "@endtsexample\n")
  5771. {
  5772. return object->setActionThread( name, hold, true, fsp);
  5773. }
  5774. DefineEngineMethod( Player, setControlObject, bool, ( ShapeBase* obj ),,
  5775. "@brief Set the object to be controlled by this player\n\n"
  5776. "It is possible to have the moves sent to the Player object from the "
  5777. "GameConnection to be passed along to another object. This happens, for example "
  5778. "when a player is mounted to a vehicle. The move commands pass through the Player "
  5779. "and on to the vehicle (while the player remains stationary within the vehicle). "
  5780. "With setControlObject() you can have the Player pass along its moves to any object. "
  5781. "One possible use is for a player to move a remote controlled vehicle. In this case "
  5782. "the player does not mount the vehicle directly, but still wants to be able to control it.\n"
  5783. "@param obj Object to control with this player\n"
  5784. "@return True if the object is valid, false if not\n"
  5785. "@see getControlObject()\n"
  5786. "@see clearControlObject()\n"
  5787. "@see GameConnection::setControlObject()")
  5788. {
  5789. if (obj) {
  5790. object->setControlObject(obj);
  5791. return true;
  5792. }
  5793. else
  5794. object->setControlObject(0);
  5795. return false;
  5796. }
  5797. DefineEngineMethod( Player, getControlObject, S32, (),,
  5798. "@brief Get the current object we are controlling.\n\n"
  5799. "@return ID of the ShapeBase object we control, or 0 if not controlling an "
  5800. "object.\n"
  5801. "@see setControlObject()\n"
  5802. "@see clearControlObject()")
  5803. {
  5804. ShapeBase* controlObject = object->getControlObject();
  5805. return controlObject ? controlObject->getId(): 0;
  5806. }
  5807. DefineEngineMethod( Player, clearControlObject, void, (),,
  5808. "@brief Clears the player's current control object.\n\n"
  5809. "Returns control to the player. This internally calls "
  5810. "Player::setControlObject(0).\n"
  5811. "@tsexample\n"
  5812. "%player.clearControlObject();\n"
  5813. "echo(%player.getControlObject()); //<-- Returns 0, player assumes control\n"
  5814. "%player.setControlObject(%vehicle);\n"
  5815. "echo(%player.getControlObject()); //<-- Returns %vehicle, player controls the vehicle now.\n"
  5816. "@endtsexample\n"
  5817. "@note If the player does not have a control object, the player will receive all moves "
  5818. "from its GameConnection. If you're looking to remove control from the player itself "
  5819. "(i.e. stop sending moves to the player) use GameConnection::setControlObject() to transfer "
  5820. "control to another object, such as a camera.\n"
  5821. "@see setControlObject()\n"
  5822. "@see getControlObject()\n"
  5823. "@see GameConnection::setControlObject()\n")
  5824. {
  5825. object->setControlObject(0);
  5826. }
  5827. DefineEngineMethod( Player, checkDismountPoint, bool, ( Point3F oldPos, Point3F pos ),,
  5828. "@brief Check if it is safe to dismount at this position.\n\n"
  5829. "Internally this method casts a ray from oldPos to pos to determine if it hits the "
  5830. "terrain, an interior object, a water object, another player, a static shape, "
  5831. "a vehicle (exluding the one currently mounted), or physical zone. If this ray "
  5832. "is in the clear, then the player's bounding box is also checked for a collision at "
  5833. "the pos position. If this displaced bounding box is also in the clear, then "
  5834. "checkDismountPoint() returns true.\n"
  5835. "@param oldPos The player's current position\n"
  5836. "@param pos The dismount position to check\n"
  5837. "@return True if the dismount position is clear, false if not\n"
  5838. "@note The player must be already mounted for this method to not assert.\n")
  5839. {
  5840. MatrixF oldPosMat(true);
  5841. oldPosMat.setColumn(3, oldPos);
  5842. MatrixF posMat(true);
  5843. posMat.setColumn(3, pos);
  5844. return object->checkDismountPosition(oldPosMat, posMat);
  5845. }
  5846. DefineEngineMethod( Player, getNumDeathAnimations, S32, ( ),,
  5847. "@brief Get the number of death animations available to this player.\n\n"
  5848. "Death animations are assumed to be named death1-N using consecutive indices." )
  5849. {
  5850. S32 count = 0;
  5851. const PlayerData * db = dynamic_cast<PlayerData*>( object->getDataBlock() );
  5852. if ( db )
  5853. {
  5854. for ( S32 i = 0; i < db->actionCount; i++ )
  5855. if ( db->actionList[i].death )
  5856. count++;
  5857. }
  5858. return count;
  5859. }
  5860. //----------------------------------------------------------------------------
  5861. void Player::consoleInit()
  5862. {
  5863. Con::addVariable("$player::renderMyPlayer",TypeBool, &sRenderMyPlayer,
  5864. "@brief Determines if the player is rendered or not.\n\n"
  5865. "Used on the client side to disable the rendering of all Player objects. This is "
  5866. "mainly for the tools or debugging.\n"
  5867. "@ingroup GameObjects\n");
  5868. Con::addVariable("$player::renderMyItems",TypeBool, &sRenderMyItems,
  5869. "@brief Determines if mounted shapes are rendered or not.\n\n"
  5870. "Used on the client side to disable the rendering of all Player mounted objects. This is "
  5871. "mainly used for the tools or debugging.\n"
  5872. "@ingroup GameObjects\n");
  5873. Con::addVariable("$player::renderCollision", TypeBool, &sRenderPlayerCollision,
  5874. "@brief Determines if the player's collision mesh should be rendered.\n\n"
  5875. "This is mainly used for the tools and debugging.\n"
  5876. "@ingroup GameObjects\n");
  5877. Con::addVariable("$player::minWarpTicks",TypeF32,&sMinWarpTicks,
  5878. "@brief Fraction of tick at which instant warp occures on the client.\n\n"
  5879. "@ingroup GameObjects\n");
  5880. Con::addVariable("$player::maxWarpTicks",TypeS32,&sMaxWarpTicks,
  5881. "@brief When a warp needs to occur due to the client being too far off from the server, this is the "
  5882. "maximum number of ticks we'll allow the client to warp to catch up.\n\n"
  5883. "@ingroup GameObjects\n");
  5884. Con::addVariable("$player::maxPredictionTicks",TypeS32,&sMaxPredictionTicks,
  5885. "@brief Maximum number of ticks to predict on the client from the last known move obtained from the server.\n\n"
  5886. "@ingroup GameObjects\n");
  5887. Con::addVariable("$player::maxImpulseVelocity", TypeF32, &sMaxImpulseVelocity,
  5888. "@brief The maximum velocity allowed due to a single impulse.\n\n"
  5889. "@ingroup GameObjects\n");
  5890. // Move triggers
  5891. Con::addVariable("$player::jumpTrigger", TypeS32, &sJumpTrigger,
  5892. "@brief The move trigger index used for player jumping.\n\n"
  5893. "@ingroup GameObjects\n");
  5894. Con::addVariable("$player::crouchTrigger", TypeS32, &sCrouchTrigger,
  5895. "@brief The move trigger index used for player crouching.\n\n"
  5896. "@ingroup GameObjects\n");
  5897. Con::addVariable("$player::proneTrigger", TypeS32, &sProneTrigger,
  5898. "@brief The move trigger index used for player prone pose.\n\n"
  5899. "@ingroup GameObjects\n");
  5900. Con::addVariable("$player::sprintTrigger", TypeS32, &sSprintTrigger,
  5901. "@brief The move trigger index used for player sprinting.\n\n"
  5902. "@ingroup GameObjects\n");
  5903. Con::addVariable("$player::imageTrigger0", TypeS32, &sImageTrigger0,
  5904. "@brief The move trigger index used to trigger mounted image 0.\n\n"
  5905. "@ingroup GameObjects\n");
  5906. Con::addVariable("$player::imageTrigger1", TypeS32, &sImageTrigger1,
  5907. "@brief The move trigger index used to trigger mounted image 1 or alternate fire "
  5908. "on mounted image 0.\n\n"
  5909. "@ingroup GameObjects\n");
  5910. Con::addVariable("$player::jumpJetTrigger", TypeS32, &sJumpJetTrigger,
  5911. "@brief The move trigger index used for player jump jetting.\n\n"
  5912. "@ingroup GameObjects\n");
  5913. Con::addVariable("$player::vehicleDismountTrigger", TypeS32, &sVehicleDismountTrigger,
  5914. "@brief The move trigger index used to dismount player.\n\n"
  5915. "@ingroup GameObjects\n");
  5916. // ExtendedMove support
  5917. Con::addVariable("$player::extendedMoveHeadPosRotIndex", TypeS32, &smExtendedMoveHeadPosRotIndex,
  5918. "@brief The ExtendedMove position/rotation index used for head movements.\n\n"
  5919. "@ingroup GameObjects\n");
  5920. afx_consoleInit();
  5921. }
  5922. //--------------------------------------------------------------------------
  5923. void Player::calcClassRenderData()
  5924. {
  5925. Parent::calcClassRenderData();
  5926. // If nothing is mounted do not perform the calculations below. Otherwise,
  5927. // we'll end up with a bad ray cast as both nmat and smat will be the
  5928. // Player's transform.
  5929. MountedImage& image = mMountedImageList[0];
  5930. if (!image.dataBlock)
  5931. {
  5932. mWeaponBackFraction = 0.0f;
  5933. return;
  5934. }
  5935. disableCollision();
  5936. MatrixF nmat;
  5937. MatrixF smat;
  5938. Parent::getRetractionTransform(0,&nmat);
  5939. Parent::getImageTransform(0, &smat);
  5940. // See if we are pushed into a wall...
  5941. Point3F start, end;
  5942. smat.getColumn(3, &start);
  5943. nmat.getColumn(3, &end);
  5944. RayInfo rinfo;
  5945. if (getContainer()->castRay(start, end, sCollisionMoveMask & ~(WaterObjectType|PhysicalZoneObjectType|MarkerObjectType), &rinfo)) {
  5946. if (rinfo.t < 1.0f)
  5947. mWeaponBackFraction = 1.0f - rinfo.t;
  5948. else
  5949. mWeaponBackFraction = 0.0f;
  5950. } else {
  5951. mWeaponBackFraction = 0.0f;
  5952. }
  5953. enableCollision();
  5954. }
  5955. //-----------------------------------------------------------------------------
  5956. void Player::playFootstepSound( bool triggeredLeft, Material* contactMaterial, SceneObject* contactObject )
  5957. {
  5958. if (footfallSoundOverride > 0)
  5959. return;
  5960. MatrixF footMat = getTransform();
  5961. if( mWaterCoverage > 0.0 )
  5962. {
  5963. // Treading water.
  5964. if ( mWaterCoverage < mDataBlock->footSplashHeight )
  5965. SFX->playOnce( mDataBlock->sound[ PlayerData::FootShallowSplash ], &footMat );
  5966. else
  5967. {
  5968. if ( mWaterCoverage < 1.0 )
  5969. SFX->playOnce( mDataBlock->sound[ PlayerData::FootWading ], &footMat );
  5970. else
  5971. {
  5972. if ( triggeredLeft )
  5973. {
  5974. SFX->playOnce( mDataBlock->sound[ PlayerData::FootUnderWater ], &footMat );
  5975. SFX->playOnce( mDataBlock->sound[ PlayerData::FootBubbles ], &footMat );
  5976. }
  5977. }
  5978. }
  5979. }
  5980. else if( contactMaterial && contactMaterial->mFootstepSoundCustom )
  5981. {
  5982. // Footstep sound defined on material.
  5983. SFX->playOnce( contactMaterial->mFootstepSoundCustom, &footMat );
  5984. }
  5985. else
  5986. {
  5987. // Play default sound.
  5988. S32 sound = -1;
  5989. if (contactMaterial && (contactMaterial->mFootstepSoundId>-1 && contactMaterial->mFootstepSoundId<PlayerData::MaxSoundOffsets))
  5990. sound = contactMaterial->mFootstepSoundId;
  5991. else if( contactObject && contactObject->getTypeMask() & VehicleObjectType )
  5992. sound = 2;
  5993. if (sound>=0)
  5994. SFX->playOnce(mDataBlock->sound[sound], &footMat);
  5995. }
  5996. }
  5997. void Player:: playImpactSound()
  5998. {
  5999. if( mWaterCoverage == 0.0f )
  6000. {
  6001. Point3F pos;
  6002. RayInfo rInfo;
  6003. MatrixF mat = getTransform();
  6004. mat.mulP(Point3F(mDataBlock->decalOffset,0.0f,0.0f), &pos);
  6005. if( gClientContainer.castRay( Point3F( pos.x, pos.y, pos.z + 0.01f ),
  6006. Point3F( pos.x, pos.y, pos.z - 2.0f ),
  6007. STATIC_COLLISION_TYPEMASK | VehicleObjectType,
  6008. &rInfo ) )
  6009. {
  6010. Material* material = ( rInfo.material ? dynamic_cast< Material* >( rInfo.material->getMaterial() ) : 0 );
  6011. if( material && material->mImpactSoundCustom )
  6012. SFX->playOnce( material->mImpactSoundCustom, &getTransform() );
  6013. else
  6014. {
  6015. S32 sound = -1;
  6016. if (material && (material->mImpactSoundId>-1 && material->mImpactSoundId<PlayerData::MaxSoundOffsets))
  6017. sound = material->mImpactSoundId;
  6018. else if( rInfo.object->getTypeMask() & VehicleObjectType )
  6019. sound = 2; // Play metal;
  6020. if (sound >= 0)
  6021. SFX->playOnce(mDataBlock->sound[PlayerData::ImpactStart + sound], &getTransform());
  6022. }
  6023. }
  6024. }
  6025. mImpactSound = 0;
  6026. }
  6027. //--------------------------------------------------------------------------
  6028. // Update splash
  6029. //--------------------------------------------------------------------------
  6030. void Player::updateSplash()
  6031. {
  6032. F32 speed = getVelocity().len();
  6033. if( speed < mDataBlock->splashVelocity || isMounted() ) return;
  6034. Point3F curPos = getPosition();
  6035. if ( curPos.equal( mLastPos ) )
  6036. return;
  6037. if (pointInWater( curPos )) {
  6038. if (!pointInWater( mLastPos )) {
  6039. Point3F norm = getVelocity();
  6040. norm.normalize();
  6041. // make sure player is moving vertically at good pace before playing splash
  6042. F32 splashAng = mDataBlock->splashAngle / 360.0;
  6043. if( mDot( norm, Point3F(0.0, 0.0, -1.0) ) < splashAng )
  6044. return;
  6045. RayInfo rInfo;
  6046. if (gClientContainer.castRay(mLastPos, curPos,
  6047. WaterObjectType, &rInfo)) {
  6048. createSplash( rInfo.point, speed );
  6049. mBubbleEmitterTime = 0.0;
  6050. }
  6051. }
  6052. }
  6053. }
  6054. //--------------------------------------------------------------------------
  6055. void Player::updateFroth( F32 dt )
  6056. {
  6057. // update bubbles
  6058. Point3F moveDir = getVelocity();
  6059. mBubbleEmitterTime += dt;
  6060. if (mBubbleEmitterTime < mDataBlock->bubbleEmitTime) {
  6061. if (mSplashEmitter[PlayerData::BUBBLE_EMITTER]) {
  6062. Point3F emissionPoint = getRenderPosition();
  6063. U32 emitNum = PlayerData::BUBBLE_EMITTER;
  6064. mSplashEmitter[emitNum]->emitParticles(mLastPos, emissionPoint,
  6065. Point3F( 0.0, 0.0, 1.0 ), moveDir, (U32)(dt * 1000.0));
  6066. }
  6067. }
  6068. Point3F contactPoint;
  6069. if (!collidingWithWater(contactPoint)) {
  6070. mLastWaterPos = mLastPos;
  6071. return;
  6072. }
  6073. F32 speed = moveDir.len();
  6074. if ( speed < mDataBlock->splashVelEpsilon )
  6075. speed = 0.0;
  6076. U32 emitRate = (U32) (speed * mDataBlock->splashFreqMod * dt);
  6077. // If we're in the water, swimming, but not
  6078. // moving, then lets emit some particles because
  6079. // we're treading water.
  6080. if ( mSwimming && speed == 0.0 )
  6081. {
  6082. emitRate = (U32) (2.0f * mDataBlock->splashFreqMod * dt);
  6083. }
  6084. U32 i;
  6085. for ( i=0; i<PlayerData::BUBBLE_EMITTER; i++ ) {
  6086. if (mSplashEmitter[i] )
  6087. mSplashEmitter[i]->emitParticles( mLastWaterPos,
  6088. contactPoint, Point3F( 0.0, 0.0, 1.0 ),
  6089. moveDir, emitRate );
  6090. }
  6091. mLastWaterPos = contactPoint;
  6092. }
  6093. void Player::updateWaterSounds(F32 dt)
  6094. {
  6095. if ( mWaterCoverage < 1.0f || mDamageState != Enabled )
  6096. {
  6097. // Stop everything
  6098. if ( mMoveBubbleSound )
  6099. mMoveBubbleSound->stop();
  6100. if ( mWaterBreathSound )
  6101. mWaterBreathSound->stop();
  6102. return;
  6103. }
  6104. if ( mMoveBubbleSound )
  6105. {
  6106. // We're under water and still alive, so let's play something
  6107. if ( mVelocity.len() > 1.0f )
  6108. {
  6109. if ( !mMoveBubbleSound->isPlaying() )
  6110. mMoveBubbleSound->play();
  6111. mMoveBubbleSound->setTransform( getTransform() );
  6112. }
  6113. else
  6114. mMoveBubbleSound->stop();
  6115. }
  6116. if ( mWaterBreathSound )
  6117. {
  6118. if ( !mWaterBreathSound->isPlaying() )
  6119. mWaterBreathSound->play();
  6120. mWaterBreathSound->setTransform( getTransform() );
  6121. }
  6122. }
  6123. //--------------------------------------------------------------------------
  6124. // Returns true if player is intersecting a water surface
  6125. //--------------------------------------------------------------------------
  6126. bool Player::collidingWithWater( Point3F &waterHeight )
  6127. {
  6128. if ( !mCurrentWaterObject )
  6129. return false;
  6130. Point3F curPos = getPosition();
  6131. if ( mWorldBox.maxExtents.z < mLiquidHeight )
  6132. return false;
  6133. curPos.z = mLiquidHeight;
  6134. waterHeight = getPosition();
  6135. waterHeight.z = mLiquidHeight;
  6136. return true;
  6137. }
  6138. //--------------------------------------------------------------------------
  6139. void Player::createSplash( Point3F &pos, F32 speed )
  6140. {
  6141. if ( speed >= mDataBlock->hardSplashSoundVel )
  6142. SFX->playOnce( mDataBlock->sound[PlayerData::ImpactWaterHard], &getTransform() );
  6143. else if ( speed >= mDataBlock->medSplashSoundVel )
  6144. SFX->playOnce( mDataBlock->sound[PlayerData::ImpactWaterMedium], &getTransform() );
  6145. else
  6146. SFX->playOnce( mDataBlock->sound[PlayerData::ImpactWaterEasy], &getTransform() );
  6147. if( mDataBlock->splash )
  6148. {
  6149. MatrixF trans = getTransform();
  6150. trans.setPosition( pos );
  6151. Splash *splash = new Splash;
  6152. splash->onNewDataBlock( mDataBlock->splash, false );
  6153. splash->setTransform( trans );
  6154. splash->setInitialState( trans.getPosition(), Point3F( 0.0, 0.0, 1.0 ) );
  6155. if (!splash->registerObject())
  6156. delete splash;
  6157. }
  6158. }
  6159. bool Player::isControlObject()
  6160. {
  6161. GameConnection* connection = GameConnection::getConnectionToServer();
  6162. if( !connection ) return false;
  6163. ShapeBase *obj = dynamic_cast<ShapeBase*>(connection->getControlObject());
  6164. return ( obj == this );
  6165. }
  6166. void Player::prepRenderImage( SceneRenderState* state )
  6167. {
  6168. bool renderPlayer = true;
  6169. bool renderItems = true;
  6170. /*
  6171. if ( mPhysicsRep && Con::getBoolVariable("$PhysicsPlayer::DebugRender",false) )
  6172. {
  6173. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  6174. ri->renderDelegate.bind( mPhysicsRep, &PhysicsPlayer::renderDebug );
  6175. ri->objectIndex = -1;
  6176. ri->type = RenderPassManager::RIT_Editor;
  6177. state->getRenderPass()->addInst( ri );
  6178. }
  6179. */
  6180. // Debug rendering for all convexes in the Players working list.
  6181. if ( sRenderPlayerCollision )
  6182. {
  6183. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  6184. ri->renderDelegate.bind( this, &Player::renderConvex );
  6185. ri->objectIndex = -1;
  6186. ri->type = RenderPassManager::RIT_Editor;
  6187. state->getRenderPass()->addInst( ri );
  6188. }
  6189. GameConnection* connection = GameConnection::getConnectionToServer();
  6190. if( connection && connection->getControlObject() == this && connection->isFirstPerson() )
  6191. {
  6192. // If we're first person and we are not rendering the player
  6193. // then disable all shadow rendering... a floating gun shadow sucks.
  6194. if ( state->isShadowPass() && !mDataBlock->renderFirstPerson && !mDataBlock->firstPersonShadows )
  6195. return;
  6196. renderPlayer = mDataBlock->renderFirstPerson || !state->isDiffusePass();
  6197. if( !sRenderMyPlayer )
  6198. renderPlayer = false;
  6199. if( !sRenderMyItems )
  6200. renderItems = false;
  6201. }
  6202. // Call the protected base class to do the work
  6203. // now that we know if we're rendering the player
  6204. // and mounted shapes.
  6205. return ShapeBase::_prepRenderImage( state,
  6206. renderPlayer,
  6207. renderItems );
  6208. }
  6209. void Player::renderConvex( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat )
  6210. {
  6211. GFX->enterDebugEvent( ColorI(255,0,255), "Player_renderConvex" );
  6212. mConvex.renderWorkingList();
  6213. GFX->leaveDebugEvent();
  6214. }
  6215. // static
  6216. bool Player::sCorpsesHiddenFromRayCast = true; // this default matches stock Torque behavior.
  6217. // static
  6218. void Player::afx_consoleInit()
  6219. {
  6220. Con::addVariable("pref::Player::corpsesHiddenFromRayCast", TypeBool, &sCorpsesHiddenFromRayCast);
  6221. }
  6222. void Player::afx_init()
  6223. {
  6224. overrideLookAnimation = false;
  6225. armLookOverridePos = 0.5f;
  6226. headVLookOverridePos = 0.5f;
  6227. headHLookOverridePos = 0.5f;
  6228. ignore_updates = false;
  6229. fx_c_triggers = 0;
  6230. mark_fx_c_triggers = 0;
  6231. fx_s_triggers = 0;
  6232. move_trigger_states = 0;
  6233. z_velocity = 0.0f;
  6234. mark_idle = false;
  6235. idle_timer = 0.0f;
  6236. mark_s_landing = false;
  6237. speed_bias = 1.0f;
  6238. speed_bias_goal = 1.0f;
  6239. override_movement = 0;
  6240. movement_data.zero();
  6241. movement_op = 1;
  6242. last_movement_tag = 0;
  6243. footfallDecalOverride = 0;
  6244. footfallSoundOverride = 0;
  6245. footfallDustOverride = 0;
  6246. noFootfallFX = false;
  6247. }
  6248. U32 Player::afx_packUpdate(NetConnection* con, U32 mask, BitStream* stream, U32 retMask)
  6249. {
  6250. #if 0
  6251. if (stream->writeFlag(mask & LookOverrideMask))
  6252. #else
  6253. if (stream->writeFlag(mask & ActionMask))
  6254. #endif
  6255. stream->writeFlag(overrideLookAnimation);
  6256. if (stream->writeFlag(mask & TriggerMask))
  6257. stream->write(fx_s_triggers);
  6258. return retMask;
  6259. }
  6260. void Player::afx_unpackUpdate(NetConnection* con, BitStream* stream)
  6261. {
  6262. if (stream->readFlag()) // LookOverrideMask
  6263. overrideLookAnimation = stream->readFlag();
  6264. if (stream->readFlag()) // TriggerMask
  6265. {
  6266. U32 mask;
  6267. stream->read(&mask);
  6268. mark_fx_c_triggers = mask;
  6269. }
  6270. }
  6271. // Code for overriding player's animation with sequences selected by the
  6272. // anim-clip component effect.
  6273. void Player::restoreAnimation(U32 tag)
  6274. {
  6275. // check if this is a blended clip
  6276. if ((tag & BLENDED_CLIP) != 0)
  6277. {
  6278. restoreBlendAnimation(tag);
  6279. return;
  6280. }
  6281. if (tag != 0 && tag == last_anim_tag)
  6282. {
  6283. bool is_death_anim = ((anim_clip_flags & IS_DEATH_ANIM) != 0);
  6284. anim_clip_flags &= ~(ANIM_OVERRIDDEN | IS_DEATH_ANIM);
  6285. if (isClientObject())
  6286. {
  6287. if (mDamageState != Enabled)
  6288. {
  6289. if (!is_death_anim)
  6290. {
  6291. // this is a bit hardwired and desperate,
  6292. // but if he's dead he needs to look like it.
  6293. setActionThread("death10", false, false, false);
  6294. }
  6295. }
  6296. else if (mState != MoveState)
  6297. {
  6298. // not sure what happens here
  6299. }
  6300. else
  6301. {
  6302. pickActionAnimation();
  6303. }
  6304. }
  6305. last_anim_tag = 0;
  6306. last_anim_id = -1;
  6307. }
  6308. }
  6309. U32 Player::getAnimationID(const char* name)
  6310. {
  6311. for (U32 i = 0; i < mDataBlock->actionCount; i++)
  6312. {
  6313. PlayerData::ActionAnimation &anim = mDataBlock->actionList[i];
  6314. if (dStricmp(anim.name, name) == 0)
  6315. return i;
  6316. }
  6317. Con::errorf("Player::getAnimationID() -- Player does not contain a sequence that matches the name, %s.", name);
  6318. return BAD_ANIM_ID;
  6319. }
  6320. U32 Player::playAnimationByID(U32 anim_id, F32 pos, F32 rate, F32 trans, bool hold, bool wait, bool is_death_anim)
  6321. {
  6322. if (anim_id == BAD_ANIM_ID)
  6323. return 0;
  6324. S32 seq_id = mDataBlock->actionList[anim_id].sequence;
  6325. if (seq_id == -1)
  6326. {
  6327. Con::errorf("Player::playAnimation() problem. BAD_SEQ_ID");
  6328. return 0;
  6329. }
  6330. if (mShapeInstance->getShape()->sequences[seq_id].isBlend())
  6331. return playBlendAnimation(seq_id, pos, rate);
  6332. if (isClientObject())
  6333. {
  6334. PlayerData::ActionAnimation &anim = mDataBlock->actionList[anim_id];
  6335. if (anim.sequence != -1)
  6336. {
  6337. mActionAnimation.action = anim_id;
  6338. mActionAnimation.forward = (rate >= 0);
  6339. mActionAnimation.firstPerson = false;
  6340. mActionAnimation.holdAtEnd = hold;
  6341. mActionAnimation.waitForEnd = hold? true: wait;
  6342. mActionAnimation.animateOnServer = false;
  6343. mActionAnimation.atEnd = false;
  6344. mActionAnimation.delayTicks = (S32)sNewAnimationTickTime;
  6345. F32 transTime = (trans < 0) ? sAnimationTransitionTime : trans;
  6346. mShapeInstance->setTimeScale(mActionAnimation.thread, rate);
  6347. mShapeInstance->transitionToSequence(mActionAnimation.thread,anim.sequence,
  6348. pos, transTime, true);
  6349. }
  6350. }
  6351. if (is_death_anim)
  6352. anim_clip_flags |= IS_DEATH_ANIM;
  6353. else
  6354. anim_clip_flags &= ~IS_DEATH_ANIM;
  6355. anim_clip_flags |= ANIM_OVERRIDDEN;
  6356. last_anim_tag = unique_anim_tag_counter++;
  6357. last_anim_id = anim_id;
  6358. return last_anim_tag;
  6359. }
  6360. F32 Player::getAnimationDurationByID(U32 anim_id)
  6361. {
  6362. if (anim_id == BAD_ANIM_ID)
  6363. return 0.0f;
  6364. S32 seq_id = mDataBlock->actionList[anim_id].sequence;
  6365. if (seq_id >= 0 && seq_id < mDataBlock->mShape->sequences.size())
  6366. return mDataBlock->mShape->sequences[seq_id].duration;
  6367. return 0.0f;
  6368. }
  6369. bool Player::isBlendAnimation(const char* name)
  6370. {
  6371. U32 anim_id = getAnimationID(name);
  6372. if (anim_id == BAD_ANIM_ID)
  6373. return false;
  6374. S32 seq_id = mDataBlock->actionList[anim_id].sequence;
  6375. if (seq_id >= 0 && seq_id < mDataBlock->mShape->sequences.size())
  6376. return mDataBlock->mShape->sequences[seq_id].isBlend();
  6377. return false;
  6378. }
  6379. const char* Player::getLastClipName(U32 clip_tag)
  6380. {
  6381. if (clip_tag != last_anim_tag || last_anim_id >= PlayerData::NumActionAnims)
  6382. return "";
  6383. return mDataBlock->actionList[last_anim_id].name;
  6384. }
  6385. void Player::unlockAnimation(U32 tag, bool force)
  6386. {
  6387. if ((tag != 0 && tag == last_anim_lock_tag) || force)
  6388. anim_clip_flags &= ~BLOCK_USER_CONTROL;
  6389. }
  6390. U32 Player::lockAnimation()
  6391. {
  6392. anim_clip_flags |= BLOCK_USER_CONTROL;
  6393. last_anim_lock_tag = unique_anim_tag_counter++;
  6394. return last_anim_lock_tag;
  6395. }
  6396. ConsoleMethod(Player, isAnimationLocked, bool, 2, 2, "isAnimationLocked()")
  6397. {
  6398. return object->isAnimationLocked();
  6399. }
  6400. void Player::setLookAnimationOverride(bool flag)
  6401. {
  6402. overrideLookAnimation = flag;
  6403. #if 0
  6404. setMaskBits(LookOverrideMask);
  6405. #else
  6406. setMaskBits(ActionMask);
  6407. #endif
  6408. }
  6409. ConsoleMethod(Player, setLookAnimationOverride, void, 3, 3, "setLookAnimationOverride(flag)")
  6410. {
  6411. object->setLookAnimationOverride(dAtob(argv[2]));
  6412. }
  6413. ConsoleMethod(Player, copyHeadRotation, void, 3, 3, "copyHeadRotation(other_player)")
  6414. {
  6415. Player* other_player = dynamic_cast<Player*>(Sim::findObject(argv[2]));
  6416. if (other_player)
  6417. object->copyHeadRotation(other_player);
  6418. }
  6419. void Player::process_client_triggers(bool triggeredLeft, bool triggeredRight)
  6420. {
  6421. bool mark_landing = false;
  6422. Point3F my_vel = getVelocity();
  6423. if (my_vel.z > 5.0f)
  6424. z_velocity = 1;
  6425. else if (my_vel.z < -5.0f)
  6426. z_velocity = -1;
  6427. else
  6428. {
  6429. if (z_velocity < 0)
  6430. mark_landing = true;
  6431. z_velocity = 0.0f;
  6432. }
  6433. fx_c_triggers = mark_fx_c_triggers;
  6434. if (triggeredLeft)
  6435. fx_c_triggers |= PLAYER_LF_FOOT_C_TRIGGER;
  6436. if (triggeredRight)
  6437. fx_c_triggers |= PLAYER_RT_FOOT_C_TRIGGER;
  6438. if (mark_landing)
  6439. fx_c_triggers |= PLAYER_LANDING_C_TRIGGER;
  6440. if (idle_timer > 10.0f)
  6441. {
  6442. fx_c_triggers |= PLAYER_IDLE_C_TRIGGER;
  6443. idle_timer = 0.0f;
  6444. }
  6445. if (fx_c_triggers & PLAYER_LANDING_S_TRIGGER)
  6446. {
  6447. fx_c_triggers &= ~(PLAYER_LANDING_S_TRIGGER);
  6448. }
  6449. }
  6450. U32 Player::unique_movement_tag_counter = 1;
  6451. void Player::setMovementSpeedBias(F32 bias)
  6452. {
  6453. speed_bias_goal = bias;
  6454. }
  6455. U32 Player::setMovementOverride(F32 bias, const Point3F* mov, U32 op)
  6456. {
  6457. if (mov)
  6458. {
  6459. movement_data = *mov;
  6460. override_movement = true;
  6461. movement_op = (U8)op;
  6462. }
  6463. else
  6464. override_movement = false;
  6465. speed_bias_goal = bias;
  6466. last_movement_tag = unique_movement_tag_counter++;
  6467. return last_movement_tag;
  6468. }
  6469. void Player::restoreMovement(U32 tag)
  6470. {
  6471. if (tag != 0 && tag == last_movement_tag)
  6472. {
  6473. speed_bias_goal = 1.0;
  6474. override_movement = false;
  6475. }
  6476. }
  6477. ConsoleMethod(Player, setMovementSpeedBias, void, 3, 3, "setMovementSpeedBias(F32 bias)")
  6478. {
  6479. object->setMovementSpeedBias(dAtof(argv[2]));
  6480. }
  6481. void Player::overrideFootfallFX(bool decals, bool sounds, bool dust)
  6482. {
  6483. if (decals)
  6484. footfallDecalOverride++;
  6485. if (sounds)
  6486. footfallSoundOverride++;
  6487. if (dust)
  6488. footfallDustOverride++;
  6489. noFootfallFX = (footfallDecalOverride > 0 && footfallSoundOverride > 0 && footfallDustOverride > 0);
  6490. }
  6491. void Player::restoreFootfallFX(bool decals, bool sounds, bool dust)
  6492. {
  6493. if (decals && footfallDecalOverride)
  6494. footfallDecalOverride--;
  6495. if (sounds && footfallSoundOverride)
  6496. footfallSoundOverride--;
  6497. if (dust && footfallDustOverride)
  6498. footfallDustOverride--;
  6499. noFootfallFX = (footfallDecalOverride > 0 && footfallSoundOverride > 0 && footfallDustOverride > 0);
  6500. }
  6501. #ifdef TORQUE_OPENVR
  6502. void Player::setControllers(Vector<OpenVRTrackedObject*> controllerList)
  6503. {
  6504. mControllers[0] = controllerList.size() > 0 ? controllerList[0] : NULL;
  6505. mControllers[1] = controllerList.size() > 1 ? controllerList[1] : NULL;
  6506. }
  6507. ConsoleMethod(Player, setVRControllers, void, 4, 4, "")
  6508. {
  6509. OpenVRTrackedObject *controllerL, *controllerR;
  6510. Vector<OpenVRTrackedObject*> list;
  6511. if (Sim::findObject(argv[2], controllerL))
  6512. {
  6513. list.push_back(controllerL);
  6514. }
  6515. else
  6516. {
  6517. list.push_back(NULL);
  6518. }
  6519. if (Sim::findObject(argv[3], controllerR))
  6520. {
  6521. list.push_back(controllerR);
  6522. }
  6523. else
  6524. {
  6525. list.push_back(NULL);
  6526. }
  6527. object->setControllers(list);
  6528. }
  6529. #endif