player.cpp 252 KB

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