player.cpp 239 KB

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