player.cpp 239 KB

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