player.cpp 232 KB

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