player.cpp 237 KB

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