2
0

player.cpp 254 KB

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