player.cpp 252 KB

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