player.cpp 241 KB

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