ScenePresence.cs 240 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Xml;
  29. using System.Collections.Generic;
  30. using System.Reflection;
  31. using System.Threading;
  32. using System.Timers;
  33. using Timer = System.Timers.Timer;
  34. using OpenMetaverse;
  35. using log4net;
  36. using Nini.Config;
  37. using OpenSim.Framework;
  38. using OpenSim.Framework.Client;
  39. using OpenSim.Framework.Monitoring;
  40. using OpenSim.Region.Framework.Interfaces;
  41. using OpenSim.Region.Framework.Scenes.Animation;
  42. using OpenSim.Region.Framework.Scenes.Types;
  43. using OpenSim.Region.PhysicsModules.SharedBase;
  44. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  45. using OpenSim.Services.Interfaces;
  46. using TeleportFlags = OpenSim.Framework.Constants.TeleportFlags;
  47. namespace OpenSim.Region.Framework.Scenes
  48. {
  49. [Flags]
  50. enum ScriptControlled : uint
  51. {
  52. CONTROL_ZERO = 0,
  53. CONTROL_FWD = 1,
  54. CONTROL_BACK = 2,
  55. CONTROL_LEFT = 4,
  56. CONTROL_RIGHT = 8,
  57. CONTROL_UP = 16,
  58. CONTROL_DOWN = 32,
  59. CONTROL_ROT_LEFT = 256,
  60. CONTROL_ROT_RIGHT = 512,
  61. CONTROL_LBUTTON = 268435456,
  62. CONTROL_ML_LBUTTON = 1073741824
  63. }
  64. struct ScriptControllers
  65. {
  66. public UUID objectID;
  67. public UUID itemID;
  68. public ScriptControlled ignoreControls;
  69. public ScriptControlled eventControls;
  70. }
  71. public delegate void SendCoarseLocationsMethod(UUID scene, ScenePresence presence, List<Vector3> coarseLocations, List<UUID> avatarUUIDs);
  72. public class ScenePresence : EntityBase, IScenePresence
  73. {
  74. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  75. private static readonly String LogHeader = "[SCENE PRESENCE]";
  76. // ~ScenePresence()
  77. // {
  78. // m_log.DebugFormat("[SCENE PRESENCE]: Destructor called on {0}", Name);
  79. // }
  80. public void TriggerScenePresenceUpdated()
  81. {
  82. if (m_scene != null)
  83. m_scene.EventManager.TriggerScenePresenceUpdated(this);
  84. }
  85. public bool isNPC { get; private set; }
  86. private PresenceType m_presenceType;
  87. public PresenceType PresenceType {
  88. get {return m_presenceType;}
  89. private set
  90. {
  91. m_presenceType = value;
  92. isNPC = (m_presenceType == PresenceType.Npc);
  93. }
  94. }
  95. private ScenePresenceStateMachine m_stateMachine;
  96. /// <summary>
  97. /// The current state of this presence. Governs only the existence lifecycle. See ScenePresenceStateMachine
  98. /// for more details.
  99. /// </summary>
  100. public ScenePresenceState LifecycleState
  101. {
  102. get
  103. {
  104. return m_stateMachine.GetState();
  105. }
  106. set
  107. {
  108. m_stateMachine.SetState(value);
  109. }
  110. }
  111. /// <summary>
  112. /// This exists to prevent race conditions between two CompleteMovement threads if the simulator is slow and
  113. /// the viewer fires these in quick succession.
  114. /// </summary>
  115. /// <remarks>
  116. /// TODO: The child -> agent transition should be folded into LifecycleState and the CompleteMovement
  117. /// regulation done there.
  118. /// </remarks>
  119. private object m_completeMovementLock = new object();
  120. // private static readonly byte[] DEFAULT_TEXTURE = AvatarAppearance.GetDefaultTexture().GetBytes();
  121. private static readonly Array DIR_CONTROL_FLAGS = Enum.GetValues(typeof(Dir_ControlFlags));
  122. private static readonly Vector3 HEAD_ADJUSTMENT = new Vector3(0f, 0f, 0.3f);
  123. /// <summary>
  124. /// Experimentally determined "fudge factor" to make sit-target positions
  125. /// the same as in SecondLife. Fudge factor was tested for 36 different
  126. /// test cases including prims of type box, sphere, cylinder, and torus,
  127. /// with varying parameters for sit target location, prim size, prim
  128. /// rotation, prim cut, prim twist, prim taper, and prim shear. See mantis
  129. /// issue #1716
  130. /// </summary>
  131. public static readonly Vector3 SIT_TARGET_ADJUSTMENT = new Vector3(0.0f, 0.0f, 0.4f);
  132. /// <summary>
  133. /// Movement updates for agents in neighboring regions are sent directly to clients.
  134. /// This value only affects how often agent positions are sent to neighbor regions
  135. /// for things such as distance-based update prioritization
  136. /// </summary>
  137. public static readonly float SIGNIFICANT_MOVEMENT = 2.0f;
  138. private UUID m_previusParcelUUID = UUID.Zero;
  139. private UUID m_currentParcelUUID = UUID.Zero;
  140. private bool m_previusParcelHide = false;
  141. private bool m_currentParcelHide = false;
  142. private object parcelLock = new Object();
  143. public UUID currentParcelUUID
  144. {
  145. get { return m_currentParcelUUID; }
  146. set
  147. {
  148. lock (parcelLock)
  149. {
  150. bool oldhide = m_currentParcelHide;
  151. bool checksame = true;
  152. if (value != m_currentParcelUUID)
  153. {
  154. m_previusParcelHide = m_currentParcelHide;
  155. m_previusParcelUUID = m_currentParcelUUID;
  156. checksame = false;
  157. }
  158. m_currentParcelUUID = value;
  159. m_currentParcelHide = false;
  160. ILandObject land = m_scene.LandChannel.GetLandObject(AbsolutePosition.X, AbsolutePosition.Y);
  161. if (land != null && !land.LandData.SeeAVs)
  162. m_currentParcelHide = true;
  163. if (m_previusParcelUUID != UUID.Zero || checksame)
  164. ParcelCrossCheck(m_currentParcelUUID,m_previusParcelUUID,m_currentParcelHide, m_previusParcelHide, oldhide,checksame);
  165. }
  166. }
  167. }
  168. public void sitSOGmoved()
  169. {
  170. if (IsDeleted || !IsSatOnObject)
  171. //what me? nahh
  172. return;
  173. if (IsInTransit)
  174. return;
  175. ILandObject land = m_scene.LandChannel.GetLandObject(AbsolutePosition.X, AbsolutePosition.Y);
  176. if (land == null)
  177. return; //??
  178. UUID parcelID = land.LandData.GlobalID;
  179. if (m_currentParcelUUID != parcelID)
  180. currentParcelUUID = parcelID;
  181. }
  182. public bool ParcelAllowThisAvatarSounds
  183. {
  184. get
  185. {
  186. try
  187. {
  188. lock (parcelLock)
  189. {
  190. ILandObject land = m_scene.LandChannel.GetLandObject(AbsolutePosition.X, AbsolutePosition.Y);
  191. if (land == null)
  192. return true;
  193. if (land.LandData.AnyAVSounds)
  194. return true;
  195. if (!land.LandData.GroupAVSounds)
  196. return false;
  197. return land.LandData.GroupID == ControllingClient.ActiveGroupId;
  198. }
  199. }
  200. catch
  201. {
  202. return true;
  203. }
  204. }
  205. }
  206. public bool ParcelHideThisAvatar
  207. {
  208. get
  209. {
  210. return m_currentParcelHide;
  211. }
  212. }
  213. /// <value>
  214. /// The animator for this avatar
  215. /// </value>
  216. public ScenePresenceAnimator Animator { get; private set; }
  217. /// <value>
  218. /// Server Side Animation Override
  219. /// </value>
  220. public MovementAnimationOverrides Overrides { get; private set; }
  221. public String sitAnimation = "SIT";
  222. /// <summary>
  223. /// Attachments recorded on this avatar.
  224. /// </summary>
  225. /// <remarks>
  226. /// TODO: For some reason, we effectively have a list both here and in Appearance. Need to work out if this is
  227. /// necessary.
  228. /// </remarks>
  229. private List<SceneObjectGroup> m_attachments = new List<SceneObjectGroup>();
  230. public Object AttachmentsSyncLock { get; private set; }
  231. private Dictionary<UUID, ScriptControllers> scriptedcontrols = new Dictionary<UUID, ScriptControllers>();
  232. private ScriptControlled IgnoredControls = ScriptControlled.CONTROL_ZERO;
  233. private ScriptControlled LastCommands = ScriptControlled.CONTROL_ZERO;
  234. private bool MouseDown = false;
  235. // private SceneObjectGroup proxyObjectGroup;
  236. //private SceneObjectPart proxyObjectPart = null;
  237. public Vector3 lastKnownAllowedPosition;
  238. public bool sentMessageAboutRestrictedParcelFlyingDown;
  239. public Vector4 CollisionPlane = Vector4.UnitW;
  240. private Vector3 m_lastPosition;
  241. private Quaternion m_lastRotation;
  242. private Vector3 m_lastVelocity;
  243. private Vector3 m_lastSize = new Vector3(0.45f,0.6f,1.9f);
  244. private bool m_followCamAuto = false;
  245. private Vector3? m_forceToApply;
  246. private int m_userFlags;
  247. public int UserFlags
  248. {
  249. get { return m_userFlags; }
  250. }
  251. // Flying
  252. public bool Flying
  253. {
  254. get { return PhysicsActor != null && PhysicsActor.Flying; }
  255. set { PhysicsActor.Flying = value; }
  256. }
  257. public bool IsColliding
  258. {
  259. get { return PhysicsActor != null && PhysicsActor.IsColliding; }
  260. // We would expect setting IsColliding to be private but it's used by a hack in Scene
  261. set { PhysicsActor.IsColliding = value; }
  262. }
  263. // private int m_lastColCount = -1; //KF: Look for Collision chnages
  264. // private int m_updateCount = 0; //KF: Update Anims for a while
  265. // private static readonly int UPDATE_COUNT = 10; // how many frames to update for
  266. private List<uint> m_lastColliders = new List<uint>();
  267. private TeleportFlags m_teleportFlags;
  268. public TeleportFlags TeleportFlags
  269. {
  270. get { return m_teleportFlags; }
  271. set { m_teleportFlags = value; }
  272. }
  273. private uint m_requestedSitTargetID;
  274. private UUID m_requestedSitTargetUUID;
  275. /// <summary>
  276. /// Are we sitting on the ground?
  277. /// </summary>
  278. public bool SitGround { get; private set; }
  279. private SendCoarseLocationsMethod m_sendCoarseLocationsMethod;
  280. //private Vector3 m_requestedSitOffset = new Vector3();
  281. private Vector3 m_LastFinitePos;
  282. private float m_sitAvatarHeight = 2.0f;
  283. private Vector3 m_lastChildAgentUpdatePosition;
  284. // private Vector3 m_lastChildAgentUpdateCamPosition;
  285. private const int LAND_VELOCITYMAG_MAX = 12;
  286. private const float FLY_ROLL_MAX_RADIANS = 1.1f;
  287. private const float FLY_ROLL_RADIANS_PER_UPDATE = 0.06f;
  288. private const float FLY_ROLL_RESET_RADIANS_PER_UPDATE = 0.02f;
  289. private float m_health = 100f;
  290. protected ulong crossingFromRegion;
  291. private readonly Vector3[] Dir_Vectors = new Vector3[12];
  292. protected Timer m_reprioritization_timer;
  293. protected bool m_reprioritizing;
  294. protected bool m_reprioritization_called;
  295. private Quaternion m_headrotation = Quaternion.Identity;
  296. //PauPaw:Proper PID Controler for autopilot************
  297. public bool MovingToTarget { get; private set; }
  298. public Vector3 MoveToPositionTarget { get; private set; }
  299. /// <summary>
  300. /// Controls whether an avatar automatically moving to a target will land when it gets there (if flying).
  301. /// </summary>
  302. public bool LandAtTarget { get; private set; }
  303. private int m_movementUpdateCount;
  304. private const int NumMovementsBetweenRayCast = 5;
  305. private bool CameraConstraintActive;
  306. //private int m_moveToPositionStateStatus;
  307. //*****************************************************
  308. private bool m_collisionEventFlag = false;
  309. private object m_collisionEventLock = new Object();
  310. private int m_movementAnimationUpdateCounter = 0;
  311. public Vector3 PrevSitOffset { get; set; }
  312. protected AvatarAppearance m_appearance;
  313. public AvatarAppearance Appearance
  314. {
  315. get { return m_appearance; }
  316. set
  317. {
  318. m_appearance = value;
  319. // m_log.DebugFormat("[SCENE PRESENCE]: Set appearance for {0} to {1}", Name, value);
  320. }
  321. }
  322. /// <summary>
  323. /// Copy of the script states while the agent is in transit. This state may
  324. /// need to be placed back in case of transfer fail.
  325. /// </summary>
  326. public List<string> InTransitScriptStates
  327. {
  328. get { return m_InTransitScriptStates; }
  329. private set { m_InTransitScriptStates = value; }
  330. }
  331. private List<string> m_InTransitScriptStates = new List<string>();
  332. /// <summary>
  333. /// Implemented Control Flags
  334. /// </summary>
  335. private enum Dir_ControlFlags:uint
  336. {
  337. DIR_CONTROL_FLAG_FORWARD = AgentManager.ControlFlags.AGENT_CONTROL_AT_POS,
  338. DIR_CONTROL_FLAG_BACK = AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG,
  339. DIR_CONTROL_FLAG_LEFT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS,
  340. DIR_CONTROL_FLAG_RIGHT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG,
  341. DIR_CONTROL_FLAG_UP = AgentManager.ControlFlags.AGENT_CONTROL_UP_POS,
  342. DIR_CONTROL_FLAG_DOWN = AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG,
  343. DIR_CONTROL_FLAG_FORWARD_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS,
  344. DIR_CONTROL_FLAG_BACKWARD_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_NEG,
  345. DIR_CONTROL_FLAG_LEFT_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_POS,
  346. DIR_CONTROL_FLAG_RIGHT_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_NEG,
  347. DIR_CONTROL_FLAG_UP_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_POS,
  348. DIR_CONTROL_FLAG_DOWN_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG
  349. }
  350. /// <summary>
  351. /// Position at which a significant movement was made
  352. /// </summary>
  353. private Vector3 posLastSignificantMove;
  354. #region For teleports and crossings callbacks
  355. /// <summary>
  356. /// In the V1 teleport protocol, the destination simulator sends ReleaseAgent to this address.
  357. /// </summary>
  358. private string m_callbackURI;
  359. /// <summary>
  360. /// Records the region from which this presence originated, if not from login.
  361. /// </summary>
  362. /// <remarks>
  363. /// Also acts as a signal in the teleport V2 process to release UpdateAgent after a viewer has triggered
  364. /// CompleteMovement and made the previous child agent a root agent.
  365. /// </remarks>
  366. private UUID m_originRegionID;
  367. /// <summary>
  368. /// This object is used as a lock before accessing m_originRegionID to make sure that every thread is seeing
  369. /// the very latest value and not using some cached version. Cannot make m_originRegionID itself volatite as
  370. /// it is a value type.
  371. /// </summary>
  372. private object m_originRegionIDAccessLock = new object();
  373. /// <summary>
  374. /// Used by the entity transfer module to signal when the presence should not be closed because a subsequent
  375. /// teleport is reusing the connection.
  376. /// </summary>
  377. /// <remarks>May be refactored or move somewhere else soon.</remarks>
  378. public bool DoNotCloseAfterTeleport { get; set; }
  379. #endregion
  380. /// <value>
  381. /// Script engines present in the scene
  382. /// </value>
  383. private IScriptModule[] m_scriptEngines;
  384. #region Properties
  385. /// <summary>
  386. /// Physical scene representation of this Avatar.
  387. /// </summary>
  388. public PhysicsActor PhysicsActor { get; private set; }
  389. /// <summary>
  390. /// Record user movement inputs.
  391. /// </summary>
  392. public uint MovementFlag { get; private set; }
  393. /// <summary>
  394. /// Is the agent stop control flag currently active?
  395. /// </summary>
  396. public bool AgentControlStopActive { get; private set; }
  397. private bool m_invulnerable = true;
  398. public bool Invulnerable
  399. {
  400. set { m_invulnerable = value; }
  401. get { return m_invulnerable; }
  402. }
  403. private int m_userLevel;
  404. public int UserLevel
  405. {
  406. get { return m_userLevel; }
  407. private set { m_userLevel = value; }
  408. }
  409. private int m_godLevel;
  410. public int GodLevel
  411. {
  412. get { return m_godLevel; }
  413. private set { m_godLevel = value; }
  414. }
  415. private ulong m_rootRegionHandle;
  416. private Vector3 m_rootRegionPosition = new Vector3();
  417. public ulong RegionHandle
  418. {
  419. get { return m_rootRegionHandle; }
  420. private set
  421. {
  422. m_rootRegionHandle = value;
  423. // position rounded to lower multiple of 256m
  424. m_rootRegionPosition.X = (float)((m_rootRegionHandle >> 32) & 0xffffff00);
  425. m_rootRegionPosition.Y = (float)(m_rootRegionHandle & 0xffffff00);
  426. }
  427. }
  428. #region Client Camera
  429. /// <summary>
  430. /// Position of agent's camera in world (region cordinates)
  431. /// </summary>
  432. protected Vector3 m_lastCameraPosition;
  433. private Vector4 m_lastCameraCollisionPlane = new Vector4(0f, 0f, 0f, 1);
  434. private bool m_doingCamRayCast = false;
  435. public Vector3 CameraPosition { get; set; }
  436. public Quaternion CameraRotation
  437. {
  438. get { return Util.Axes2Rot(CameraAtAxis, CameraLeftAxis, CameraUpAxis); }
  439. }
  440. // Use these three vectors to figure out what the agent is looking at
  441. // Convert it to a Matrix and/or Quaternion
  442. //
  443. public Vector3 CameraAtAxis { get; set; }
  444. public Vector3 CameraLeftAxis { get; set; }
  445. public Vector3 CameraUpAxis { get; set; }
  446. public Vector3 Lookat
  447. {
  448. get
  449. {
  450. Vector3 a = new Vector3(CameraAtAxis.X, CameraAtAxis.Y, 0);
  451. a.Normalize();
  452. return a;
  453. }
  454. }
  455. #endregion
  456. public string Firstname { get; private set; }
  457. public string Lastname { get; private set; }
  458. public string Grouptitle
  459. {
  460. get { return UseFakeGroupTitle ? "(Loading)" : m_groupTitle; }
  461. set { m_groupTitle = value; }
  462. }
  463. private string m_groupTitle;
  464. /// <summary>
  465. /// When this is 'true', return a dummy group title instead of the real group title. This is
  466. /// used as part of a hack to force viewers to update the displayed avatar name.
  467. /// </summary>
  468. public bool UseFakeGroupTitle { get; set; }
  469. // Agent's Draw distance.
  470. public float DrawDistance { get; set; }
  471. public bool AllowMovement { get; set; }
  472. private bool m_setAlwaysRun;
  473. public bool SetAlwaysRun
  474. {
  475. get
  476. {
  477. if (PhysicsActor != null)
  478. {
  479. return PhysicsActor.SetAlwaysRun;
  480. }
  481. else
  482. {
  483. return m_setAlwaysRun;
  484. }
  485. }
  486. set
  487. {
  488. m_setAlwaysRun = value;
  489. if (PhysicsActor != null)
  490. {
  491. PhysicsActor.SetAlwaysRun = value;
  492. }
  493. }
  494. }
  495. public byte State { get; set; }
  496. private AgentManager.ControlFlags m_AgentControlFlags;
  497. public uint AgentControlFlags
  498. {
  499. get { return (uint)m_AgentControlFlags; }
  500. set { m_AgentControlFlags = (AgentManager.ControlFlags)value; }
  501. }
  502. public IClientAPI ControllingClient { get; set; }
  503. public IClientCore ClientView
  504. {
  505. get { return (IClientCore)ControllingClient; }
  506. }
  507. public UUID COF { get; set; }
  508. // public Vector3 ParentPosition { get; set; }
  509. /// <summary>
  510. /// Position of this avatar relative to the region the avatar is in
  511. /// </summary>
  512. public override Vector3 AbsolutePosition
  513. {
  514. get
  515. {
  516. if (PhysicsActor != null)
  517. {
  518. m_pos = PhysicsActor.Position;
  519. // m_log.DebugFormat(
  520. // "[SCENE PRESENCE]: Set position of {0} in {1} to {2} via getting AbsolutePosition!",
  521. // Name, Scene.Name, m_pos);
  522. }
  523. else
  524. {
  525. // m_log.DebugFormat("[SCENE PRESENCE]: Fetching abs pos where PhysicsActor == null and parent part {0} for {1}", Name, Scene.Name);
  526. // Obtain the correct position of a seated avatar.
  527. // In addition to providing the correct position while
  528. // the avatar is seated, this value will also
  529. // be used as the location to unsit to.
  530. //
  531. // If ParentID is not 0, assume we are a seated avatar
  532. // and we should return the position based on the sittarget
  533. // offset and rotation of the prim we are seated on.
  534. //
  535. // Generally, m_pos will contain the position of the avatar
  536. // in the sim unless the avatar is on a sit target. While
  537. // on a sit target, m_pos will contain the desired offset
  538. // without the parent rotation applied.
  539. if (ParentPart != null)
  540. {
  541. SceneObjectPart rootPart = ParentPart.ParentGroup.RootPart;
  542. // if (sitPart != null)
  543. // return sitPart.AbsolutePosition + (m_pos * sitPart.GetWorldRotation());
  544. if (rootPart != null)
  545. return rootPart.AbsolutePosition + (m_pos * rootPart.GetWorldRotation());
  546. }
  547. }
  548. return m_pos;
  549. }
  550. set
  551. {
  552. // m_log.DebugFormat("[SCENE PRESENCE]: Setting position of {0} to {1} in {2}", Name, value, Scene.Name);
  553. // Util.PrintCallStack();
  554. if (PhysicsActor != null)
  555. {
  556. try
  557. {
  558. PhysicsActor.Position = value;
  559. }
  560. catch (Exception e)
  561. {
  562. m_log.Error("[SCENE PRESENCE]: ABSOLUTE POSITION " + e.Message);
  563. }
  564. }
  565. // Don't update while sitting. The PhysicsActor above is null whilst sitting.
  566. if (ParentID == 0)
  567. m_pos = value;
  568. //m_log.DebugFormat(
  569. // "[ENTITY BASE]: In {0} set AbsolutePosition of {1} to {2}",
  570. // Scene.RegionInfo.RegionName, Name, m_pos);
  571. TriggerScenePresenceUpdated();
  572. }
  573. }
  574. /// <summary>
  575. /// If sitting, returns the offset position from the prim the avatar is sitting on.
  576. /// Otherwise, returns absolute position in the scene.
  577. /// </summary>
  578. public Vector3 OffsetPosition
  579. {
  580. get { return m_pos; }
  581. // Don't remove setter. It's not currently used in core but
  582. // upcoming Avination code needs it.
  583. set
  584. {
  585. // There is no offset position when not seated
  586. if (ParentID == 0)
  587. return;
  588. m_pos = value;
  589. TriggerScenePresenceUpdated();
  590. }
  591. }
  592. /// <summary>
  593. /// Current velocity of the avatar.
  594. /// </summary>
  595. public override Vector3 Velocity
  596. {
  597. get
  598. {
  599. if (PhysicsActor != null)
  600. {
  601. m_velocity = PhysicsActor.Velocity;
  602. // m_log.DebugFormat(
  603. // "[SCENE PRESENCE]: Set velocity {0} for {1} in {2} via getting Velocity!",
  604. // m_velocity, Name, Scene.RegionInfo.RegionName);
  605. }
  606. return m_velocity;
  607. }
  608. set
  609. {
  610. if (PhysicsActor != null)
  611. {
  612. try
  613. {
  614. PhysicsActor.TargetVelocity = value;
  615. }
  616. catch (Exception e)
  617. {
  618. m_log.Error("[SCENE PRESENCE]: VELOCITY " + e.Message);
  619. }
  620. }
  621. m_velocity = value;
  622. // m_log.DebugFormat(
  623. // "[SCENE PRESENCE]: In {0} set velocity of {1} to {2}",
  624. // Scene.RegionInfo.RegionName, Name, m_velocity);
  625. }
  626. }
  627. private Quaternion m_bodyRot = Quaternion.Identity;
  628. /// <summary>
  629. /// The rotation of the avatar.
  630. /// </summary>
  631. /// <remarks>
  632. /// If the avatar is not sitting, this is with respect to the world
  633. /// If the avatar is sitting, this is a with respect to the part that it's sitting upon (a local rotation).
  634. /// If you always want the world rotation, use GetWorldRotation()
  635. /// </remarks>
  636. public Quaternion Rotation
  637. {
  638. get
  639. {
  640. return m_bodyRot;
  641. }
  642. set
  643. {
  644. m_bodyRot = value;
  645. if (PhysicsActor != null)
  646. {
  647. try
  648. {
  649. PhysicsActor.Orientation = m_bodyRot;
  650. }
  651. catch (Exception e)
  652. {
  653. m_log.Error("[SCENE PRESENCE]: Orientation " + e.Message);
  654. }
  655. }
  656. // m_log.DebugFormat("[SCENE PRESENCE]: Body rot for {0} set to {1}", Name, m_bodyRot);
  657. }
  658. }
  659. // Used for limited viewer 'fake' user rotations.
  660. private Vector3 m_AngularVelocity = Vector3.Zero;
  661. public Vector3 AngularVelocity
  662. {
  663. get { return m_AngularVelocity; }
  664. }
  665. public bool IsChildAgent { get; set; }
  666. public bool IsLoggingIn { get; set; }
  667. /// <summary>
  668. /// If the avatar is sitting, the local ID of the prim that it's sitting on. If not sitting then zero.
  669. /// </summary>
  670. public uint ParentID { get; set; }
  671. public UUID ParentUUID
  672. {
  673. get { return m_parentUUID; }
  674. set { m_parentUUID = value; }
  675. }
  676. private UUID m_parentUUID = UUID.Zero;
  677. /// <summary>
  678. /// Are we sitting on an object?
  679. /// </summary>
  680. /// <remarks>A more readable way of testing presence sit status than ParentID == 0</remarks>
  681. public bool IsSatOnObject { get { return ParentID != 0; } }
  682. /// <summary>
  683. /// If the avatar is sitting, the prim that it's sitting on. If not sitting then null.
  684. /// </summary>
  685. /// <remarks>
  686. /// If you use this property then you must take a reference since another thread could set it to null.
  687. /// </remarks>
  688. public SceneObjectPart ParentPart { get; set; }
  689. public float Health
  690. {
  691. get { return m_health; }
  692. set { m_health = value; }
  693. }
  694. /// <summary>
  695. /// Gets the world rotation of this presence.
  696. /// </summary>
  697. /// <remarks>
  698. /// Unlike Rotation, this returns the world rotation no matter whether the avatar is sitting on a prim or not.
  699. /// </remarks>
  700. /// <returns></returns>
  701. public Quaternion GetWorldRotation()
  702. {
  703. if (IsSatOnObject)
  704. {
  705. SceneObjectPart sitPart = ParentPart;
  706. if (sitPart != null)
  707. return sitPart.GetWorldRotation() * Rotation;
  708. }
  709. return Rotation;
  710. }
  711. /// <summary>
  712. /// Get velocity relative to the world.
  713. /// </summary>
  714. public Vector3 GetWorldVelocity()
  715. {
  716. SceneObjectPart sitPart = ParentPart;
  717. if (sitPart != null)
  718. return sitPart.ParentGroup.Velocity;
  719. return Velocity;
  720. }
  721. public void AdjustKnownSeeds()
  722. {
  723. Dictionary<ulong, string> seeds;
  724. if (Scene.CapsModule != null)
  725. seeds = Scene.CapsModule.GetChildrenSeeds(UUID);
  726. else
  727. seeds = new Dictionary<ulong, string>();
  728. /* we can't do this anymore
  729. List<ulong> old = new List<ulong>();
  730. foreach (ulong handle in seeds.Keys)
  731. {
  732. uint x, y;
  733. Util.RegionHandleToRegionLoc(handle, out x, out y);
  734. // if (Util.IsOutsideView(DrawDistance, x, Scene.RegionInfo.RegionLocX, y, Scene.RegionInfo.RegionLocY,))
  735. {
  736. old.Add(handle);
  737. }
  738. }
  739. DropOldNeighbours(old);
  740. if (Scene.CapsModule != null)
  741. Scene.CapsModule.SetChildrenSeed(UUID, seeds);
  742. */
  743. KnownRegions = seeds;
  744. //m_log.Debug(" ++++++++++AFTER+++++++++++++ ");
  745. //DumpKnownRegions();
  746. }
  747. public void DumpKnownRegions()
  748. {
  749. m_log.Info("================ KnownRegions "+Scene.RegionInfo.RegionName+" ================");
  750. foreach (KeyValuePair<ulong, string> kvp in KnownRegions)
  751. {
  752. uint x, y;
  753. Util.RegionHandleToRegionLoc(kvp.Key, out x, out y);
  754. m_log.Info(" >> "+x+", "+y+": "+kvp.Value);
  755. }
  756. }
  757. private bool m_mouseLook;
  758. private bool m_leftButtonDown;
  759. private bool m_inTransit;
  760. /// <summary>
  761. /// This signals whether the presence is in transit between neighbouring regions.
  762. /// </summary>
  763. /// <remarks>
  764. /// It is not set when the presence is teleporting or logging in/out directly to a region.
  765. /// </remarks>
  766. public bool IsInTransit
  767. {
  768. get { return m_inTransit; }
  769. set {
  770. if(value)
  771. {
  772. if (Flying)
  773. m_AgentControlFlags |= AgentManager.ControlFlags.AGENT_CONTROL_FLY;
  774. else
  775. m_AgentControlFlags &= ~AgentManager.ControlFlags.AGENT_CONTROL_FLY;
  776. }
  777. m_inTransit = value;
  778. }
  779. }
  780. /// <summary>
  781. /// Modifier for agent movement if we get an AGENT_CONTROL_STOP whilst walking or running
  782. /// </summary>
  783. /// <remarks>
  784. /// AGENT_CONTRL_STOP comes about if user holds down space key on viewers.
  785. /// </remarks>
  786. private const float AgentControlStopSlowVel = 0.2f;
  787. // velocities
  788. public const float AgentControlNudgeVel = 1.0f; // setting this diferent from normal as no effect currently
  789. public const float AgentControlNormalVel = 1.0f;
  790. // old normal speed was tuned to match sl normal plus Fast modifiers
  791. // so we need to rescale it
  792. private float m_speedModifier = 1.0f;
  793. public float SpeedModifier
  794. {
  795. get { return m_speedModifier; }
  796. set { m_speedModifier = value; }
  797. }
  798. private bool m_forceFly;
  799. public bool ForceFly
  800. {
  801. get { return m_forceFly; }
  802. set { m_forceFly = value; }
  803. }
  804. private bool m_flyDisabled;
  805. public bool FlyDisabled
  806. {
  807. get { return m_flyDisabled; }
  808. set { m_flyDisabled = value; }
  809. }
  810. public string Viewer
  811. {
  812. get { return Util.GetViewerName(m_scene.AuthenticateHandler.GetAgentCircuitData(ControllingClient.CircuitCode)); }
  813. }
  814. #endregion
  815. #region Constructor(s)
  816. public ScenePresence(
  817. IClientAPI client, Scene world, AvatarAppearance appearance, PresenceType type)
  818. {
  819. AttachmentsSyncLock = new Object();
  820. AllowMovement = true;
  821. IsChildAgent = true;
  822. IsLoggingIn = false;
  823. m_sendCoarseLocationsMethod = SendCoarseLocationsDefault;
  824. Animator = new ScenePresenceAnimator(this);
  825. Overrides = new MovementAnimationOverrides();
  826. PresenceType = type;
  827. DrawDistance = world.DefaultDrawDistance;
  828. RegionHandle = world.RegionInfo.RegionHandle;
  829. ControllingClient = client;
  830. Firstname = ControllingClient.FirstName;
  831. Lastname = ControllingClient.LastName;
  832. m_name = String.Format("{0} {1}", Firstname, Lastname);
  833. m_scene = world;
  834. m_uuid = client.AgentId;
  835. LocalId = m_scene.AllocateLocalId();
  836. UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, m_uuid);
  837. if (account != null)
  838. m_userFlags = account.UserFlags;
  839. else
  840. m_userFlags = 0;
  841. if (account != null)
  842. UserLevel = account.UserLevel;
  843. IGroupsModule gm = m_scene.RequestModuleInterface<IGroupsModule>();
  844. if (gm != null)
  845. Grouptitle = gm.GetGroupTitle(m_uuid);
  846. m_scriptEngines = m_scene.RequestModuleInterfaces<IScriptModule>();
  847. AbsolutePosition = posLastSignificantMove = CameraPosition =
  848. m_lastCameraPosition = ControllingClient.StartPos;
  849. m_reprioritization_timer = new Timer(world.ReprioritizationInterval);
  850. m_reprioritization_timer.Elapsed += new ElapsedEventHandler(Reprioritize);
  851. m_reprioritization_timer.AutoReset = false;
  852. AdjustKnownSeeds();
  853. RegisterToEvents();
  854. SetDirectionVectors();
  855. Appearance = appearance;
  856. m_stateMachine = new ScenePresenceStateMachine(this);
  857. }
  858. private void RegionHeartbeatEnd(Scene scene)
  859. {
  860. if (IsChildAgent)
  861. return;
  862. m_movementAnimationUpdateCounter ++;
  863. if (m_movementAnimationUpdateCounter >= 2)
  864. {
  865. m_movementAnimationUpdateCounter = 0;
  866. if (Animator != null)
  867. {
  868. // If the parentID == 0 we are not sitting
  869. // if !SitGournd then we are not sitting on the ground
  870. // Fairly straightforward, now here comes the twist
  871. // if ParentUUID is NOT UUID.Zero, we are looking to
  872. // be sat on an object that isn't there yet. Should
  873. // be treated as if sat.
  874. if(ParentID == 0 && !SitGround && ParentUUID == UUID.Zero) // skip it if sitting
  875. Animator.UpdateMovementAnimations();
  876. }
  877. else
  878. {
  879. m_scene.EventManager.OnRegionHeartbeatEnd -= RegionHeartbeatEnd;
  880. }
  881. }
  882. }
  883. public void RegisterToEvents()
  884. {
  885. ControllingClient.OnCompleteMovementToRegion += CompleteMovement;
  886. ControllingClient.OnAgentUpdate += HandleAgentUpdate;
  887. ControllingClient.OnAgentCameraUpdate += HandleAgentCamerasUpdate;
  888. ControllingClient.OnAgentRequestSit += HandleAgentRequestSit;
  889. ControllingClient.OnAgentSit += HandleAgentSit;
  890. ControllingClient.OnSetAlwaysRun += HandleSetAlwaysRun;
  891. ControllingClient.OnStartAnim += HandleStartAnim;
  892. ControllingClient.OnStopAnim += HandleStopAnim;
  893. ControllingClient.OnChangeAnim += avnHandleChangeAnim;
  894. ControllingClient.OnForceReleaseControls += HandleForceReleaseControls;
  895. ControllingClient.OnAutoPilotGo += MoveToTarget;
  896. ControllingClient.OnUpdateThrottles += RaiseUpdateThrottles;
  897. // ControllingClient.OnChildAgentStatus += new StatusChange(this.ChildStatusChange);
  898. // ControllingClient.OnStopMovement += new GenericCall2(this.StopMovement);
  899. }
  900. private void SetDirectionVectors()
  901. {
  902. Dir_Vectors[0] = new Vector3(AgentControlNormalVel,0,0); //FORWARD
  903. Dir_Vectors[1] = new Vector3(-AgentControlNormalVel,0,0);; //BACK
  904. Dir_Vectors[2] = new Vector3(0,AgentControlNormalVel,0); //LEFT
  905. Dir_Vectors[3] = new Vector3(0,-AgentControlNormalVel,0); //RIGHT
  906. Dir_Vectors[4] = new Vector3(0,0,AgentControlNormalVel); //UP
  907. Dir_Vectors[5] = new Vector3(0,0,-AgentControlNormalVel); //DOWN
  908. Dir_Vectors[6] = new Vector3(AgentControlNudgeVel, 0f, 0f); //FORWARD_NUDGE
  909. Dir_Vectors[7] = new Vector3(-AgentControlNudgeVel, 0f, 0f); //BACK_NUDGE
  910. Dir_Vectors[8] = new Vector3(0f, AgentControlNudgeVel, 0f); //LEFT_NUDGE
  911. Dir_Vectors[9] = new Vector3(0f, -AgentControlNudgeVel, 0f); //RIGHT_NUDGE
  912. Dir_Vectors[10] = new Vector3(0f, 0f, AgentControlNudgeVel); //UP_Nudge
  913. Dir_Vectors[11] = new Vector3(0f, 0f, -AgentControlNudgeVel); //DOWN_Nudge
  914. }
  915. #endregion
  916. #region Status Methods
  917. /// <summary>
  918. /// Turns a child agent into a root agent.
  919. /// </summary>
  920. /// <remarks>
  921. /// Child agents are logged into neighbouring sims largely to observe changes. Root agents exist when the
  922. /// avatar is actual in the sim. They can perform all actions.
  923. /// This change is made whenever an avatar enters a region, whether by crossing over from a neighbouring sim,
  924. /// teleporting in or on initial login.
  925. ///
  926. /// This method is on the critical path for transferring an avatar from one region to another. Delay here
  927. /// delays that crossing.
  928. /// </remarks>
  929. // only in use as part of completemovement
  930. // other uses need fix
  931. private bool MakeRootAgent(Vector3 pos, bool isFlying)
  932. {
  933. int ts = Util.EnvironmentTickCount();
  934. lock (m_completeMovementLock)
  935. {
  936. if (!IsChildAgent)
  937. return false;
  938. m_log.DebugFormat("[MakeRootAgent] enter lock: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  939. //m_log.DebugFormat("[SCENE]: known regions in {0}: {1}", Scene.RegionInfo.RegionName, KnownChildRegionHandles.Count);
  940. // m_log.InfoFormat(
  941. // "[SCENE]: Upgrading child to root agent for {0} in {1}",
  942. // Name, m_scene.RegionInfo.RegionName);
  943. if (ParentUUID != UUID.Zero)
  944. {
  945. m_log.DebugFormat("[SCENE PRESENCE]: Sitting avatar back on prim {0}", ParentUUID);
  946. SceneObjectPart part = m_scene.GetSceneObjectPart(ParentUUID);
  947. if (part == null)
  948. {
  949. m_log.ErrorFormat("[SCENE PRESENCE]: Can't find prim {0} to sit on", ParentUUID);
  950. ParentID = 0;
  951. ParentPart = null;
  952. PrevSitOffset = Vector3.Zero;
  953. HandleForceReleaseControls(ControllingClient, UUID); // needs testing
  954. IsLoggingIn = false;
  955. }
  956. else
  957. {
  958. part.AddSittingAvatar(this);
  959. if (part.SitTargetPosition != Vector3.Zero)
  960. part.SitTargetAvatar = UUID;
  961. ParentID = part.LocalId;
  962. ParentPart = part;
  963. m_pos = PrevSitOffset;
  964. pos = part.GetWorldPosition();
  965. }
  966. ParentUUID = UUID.Zero;
  967. }
  968. else
  969. {
  970. IsLoggingIn = false;
  971. }
  972. IsChildAgent = false;
  973. }
  974. m_log.DebugFormat("[MakeRootAgent] out lock: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  975. // Must reset this here so that a teleport to a region next to an existing region does not keep the flag
  976. // set and prevent the close of the connection on a subsequent re-teleport.
  977. // Should not be needed if we are not trying to tell this region to close
  978. // DoNotCloseAfterTeleport = false;
  979. IGroupsModule gm = m_scene.RequestModuleInterface<IGroupsModule>();
  980. if (gm != null)
  981. Grouptitle = gm.GetGroupTitle(m_uuid);
  982. if ((m_teleportFlags & TeleportFlags.ViaHGLogin) != 0)
  983. {
  984. // The avatar is arriving from another grid. This means that we may have changed the
  985. // avatar's name to or from the special Hypergrid format ("First.Last @grid.example.com").
  986. // Unfortunately, due to a viewer bug, viewers don't always show the new name.
  987. // But we have a trick that can force them to update the name anyway.
  988. // ForceViewersUpdateName();
  989. }
  990. m_log.DebugFormat("[MakeRootAgent] Grouptitle: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  991. RegionHandle = m_scene.RegionInfo.RegionHandle;
  992. m_scene.EventManager.TriggerSetRootAgentScene(m_uuid, m_scene);
  993. m_log.DebugFormat("[MakeRootAgent] TriggerSetRootAgentScene: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  994. if (ParentID == 0)
  995. {
  996. CheckAndAdjustLandingPoint(ref pos);
  997. if (pos.X < 0f || pos.Y < 0f || pos.Z < 0f)
  998. {
  999. m_log.WarnFormat(
  1000. "[SCENE PRESENCE]: MakeRootAgent() was given an illegal position of {0} for avatar {1}, {2}. Clamping",
  1001. pos, Name, UUID);
  1002. if (pos.X < 0f) pos.X = 0f;
  1003. if (pos.Y < 0f) pos.Y = 0f;
  1004. if (pos.Z < 0f) pos.Z = 0f;
  1005. }
  1006. float localAVHeight = 1.56f;
  1007. if (Appearance.AvatarHeight > 0)
  1008. localAVHeight = Appearance.AvatarHeight;
  1009. float posZLimit = 0;
  1010. if (pos.X < m_scene.RegionInfo.RegionSizeX && pos.Y < m_scene.RegionInfo.RegionSizeY)
  1011. posZLimit = (float)m_scene.Heightmap[(int)pos.X, (int)pos.Y];
  1012. float newPosZ = posZLimit + localAVHeight / 2;
  1013. if (posZLimit >= (pos.Z - (localAVHeight / 2)) && !(Single.IsInfinity(newPosZ) || Single.IsNaN(newPosZ)))
  1014. {
  1015. pos.Z = newPosZ;
  1016. }
  1017. AbsolutePosition = pos;
  1018. // m_log.DebugFormat(
  1019. // "Set pos {0}, vel {1} in {1} to {2} from input position of {3} on MakeRootAgent",
  1020. // Name, Scene.Name, AbsolutePosition, pos);
  1021. //
  1022. if (m_teleportFlags == TeleportFlags.Default)
  1023. {
  1024. Vector3 vel = Velocity;
  1025. AddToPhysicalScene(isFlying);
  1026. if (PhysicsActor != null)
  1027. PhysicsActor.SetMomentum(vel);
  1028. }
  1029. else
  1030. {
  1031. AddToPhysicalScene(isFlying);
  1032. // reset camera to avatar pos
  1033. CameraPosition = pos;
  1034. }
  1035. if (ForceFly)
  1036. {
  1037. Flying = true;
  1038. }
  1039. else if (FlyDisabled)
  1040. {
  1041. Flying = false;
  1042. }
  1043. // XXX: This is to trigger any secondary teleport needed for a megaregion when the user has teleported to a
  1044. // location outside the 'root region' (the south-west 256x256 corner). This is the earlist we can do it
  1045. // since it requires a physics actor to be present. If it is left any later, then physics appears to reset
  1046. // the value to a negative position which does not trigger the border cross.
  1047. // This may not be the best location for this.
  1048. // its not
  1049. // CheckForBorderCrossing();
  1050. }
  1051. m_log.DebugFormat("[MakeRootAgent] position and physical: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1052. m_scene.SwapRootAgentCount(false);
  1053. // If we don't reset the movement flag here, an avatar that crosses to a neighbouring sim and returns will
  1054. // stall on the border crossing since the existing child agent will still have the last movement
  1055. // recorded, which stops the input from being processed.
  1056. MovementFlag = 0;
  1057. m_scene.EventManager.TriggerOnMakeRootAgent(this);
  1058. m_log.DebugFormat("[MakeRootAgent] TriggerOnMakeRootAgent and done: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1059. return true;
  1060. }
  1061. private void RestartAttachmentScripts()
  1062. {
  1063. // We need to restart scripts here so that they receive the correct changed events (CHANGED_TELEPORT
  1064. // and CHANGED_REGION) when the attachments have been rezzed in the new region. This cannot currently
  1065. // be done in AttachmentsModule.CopyAttachments(AgentData ad, IScenePresence sp) itself since we are
  1066. // not transporting the required data.
  1067. //
  1068. // We must take a copy of the attachments list here (rather than locking) to avoid a deadlock where a script in one of
  1069. // the attachments may start processing an event (which locks ScriptInstance.m_Script) that then calls a method here
  1070. // which needs to lock m_attachments. ResumeScripts() needs to take a ScriptInstance.m_Script lock to try to unset the Suspend status.
  1071. //
  1072. // FIXME: In theory, this deadlock should not arise since scripts should not be processing events until ResumeScripts().
  1073. // But XEngine starts all scripts unsuspended. Starting them suspended will not currently work because script rezzing
  1074. // is placed in an asynchronous queue in XEngine and so the ResumeScripts() call will almost certainly execute before the
  1075. // script is rezzed. This means the ResumeScripts() does absolutely nothing when using XEngine.
  1076. List<SceneObjectGroup> attachments = GetAttachments();
  1077. m_log.DebugFormat(
  1078. "[SCENE PRESENCE]: Restarting scripts in {0} attachments for {1} in {2}", attachments.Count, Name, Scene.Name);
  1079. // Resume scripts
  1080. foreach (SceneObjectGroup sog in attachments)
  1081. {
  1082. sog.ScheduleGroupForFullUpdate();
  1083. sog.RootPart.ParentGroup.CreateScriptInstances(0, false, m_scene.DefaultScriptEngine, GetStateSource());
  1084. sog.ResumeScripts();
  1085. }
  1086. }
  1087. private static bool IsRealLogin(TeleportFlags teleportFlags)
  1088. {
  1089. return ((teleportFlags & TeleportFlags.ViaLogin) != 0) && ((teleportFlags & TeleportFlags.ViaHGLogin) == 0);
  1090. }
  1091. /// <summary>
  1092. /// Force viewers to show the avatar's current name.
  1093. /// </summary>
  1094. /// <remarks>
  1095. /// The avatar name that is shown above the avatar in the viewers is sent in ObjectUpdate packets,
  1096. /// and they get the name from the ScenePresence. Unfortunately, viewers have a bug (as of April 2014)
  1097. /// where they ignore changes to the avatar name. However, tey don't ignore changes to the avatar's
  1098. /// Group Title. So the following trick makes viewers update the avatar's name by briefly changing
  1099. /// the group title (to "(Loading)"), and then restoring it.
  1100. /// </remarks>
  1101. /*
  1102. public void ForceViewersUpdateName()
  1103. {
  1104. m_log.DebugFormat("[SCENE PRESENCE]: Forcing viewers to update the avatar name for " + Name);
  1105. UseFakeGroupTitle = true;
  1106. Util.FireAndForget(o =>
  1107. {
  1108. // Viewers only update the avatar name when idle. Therefore, we must wait long
  1109. // enough for the viewer to show the fake name that we had set above, and only
  1110. // then switch back to the true name. This delay was chosen because it has a high
  1111. // chance of succeeding (we don't want to choose a value that's too low).
  1112. Thread.Sleep(5000);
  1113. UseFakeGroupTitle = false;
  1114. SendAvatarDataToAllClients(false);
  1115. }, null, "Scenepresence.ForceViewersUpdateName");
  1116. }
  1117. */
  1118. public int GetStateSource()
  1119. {
  1120. AgentCircuitData aCircuit = m_scene.AuthenticateHandler.GetAgentCircuitData(UUID);
  1121. if (aCircuit != null && (aCircuit.teleportFlags != (uint)TeleportFlags.Default))
  1122. {
  1123. // This will get your attention
  1124. //m_log.Error("[XXX] Triggering CHANGED_TELEPORT");
  1125. return 5; // StateSource.Teleporting
  1126. }
  1127. return 2; // StateSource.PrimCrossing
  1128. }
  1129. /// <summary>
  1130. /// This turns a root agent into a child agent
  1131. /// </summary>
  1132. /// <remarks>
  1133. /// when an agent departs this region for a neighbor, this gets called.
  1134. ///
  1135. /// It doesn't get called for a teleport. Reason being, an agent that
  1136. /// teleports out may not end up anywhere near this region
  1137. /// </remarks>
  1138. public void MakeChildAgent(ulong newRegionHandle)
  1139. {
  1140. m_scene.EventManager.OnRegionHeartbeatEnd -= RegionHeartbeatEnd;
  1141. RegionHandle = newRegionHandle;
  1142. m_log.DebugFormat("[SCENE PRESENCE]: Making {0} a child agent in {1} from root region {2}",
  1143. Name, Scene.RegionInfo.RegionName, newRegionHandle);
  1144. // Reset the m_originRegionID as it has dual use as a flag to signal that the UpdateAgent() call orignating
  1145. // from the source simulator has completed on a V2 teleport.
  1146. lock (m_originRegionIDAccessLock)
  1147. m_originRegionID = UUID.Zero;
  1148. // Reset these so that teleporting in and walking out isn't seen
  1149. // as teleporting back
  1150. TeleportFlags = TeleportFlags.Default;
  1151. MovementFlag = 0;
  1152. // It looks like Animator is set to null somewhere, and MakeChild
  1153. // is called after that. Probably in aborted teleports.
  1154. if (Animator == null)
  1155. Animator = new ScenePresenceAnimator(this);
  1156. else
  1157. Animator.ResetAnimations();
  1158. // m_log.DebugFormat(
  1159. // "[SCENE PRESENCE]: Downgrading root agent {0}, {1} to a child agent in {2}",
  1160. // Name, UUID, m_scene.RegionInfo.RegionName);
  1161. // Don't zero out the velocity since this can cause problems when an avatar is making a region crossing,
  1162. // depending on the exact timing. This shouldn't matter anyway since child agent positions are not updated.
  1163. //Velocity = new Vector3(0, 0, 0);
  1164. IsChildAgent = true;
  1165. m_scene.SwapRootAgentCount(true);
  1166. RemoveFromPhysicalScene();
  1167. ParentID = 0; // Child agents can't be sitting
  1168. // we dont have land information for child
  1169. m_previusParcelHide = false;
  1170. m_previusParcelUUID = UUID.Zero;
  1171. m_currentParcelHide = false;
  1172. m_currentParcelUUID = UUID.Zero;
  1173. // FIXME: Set RegionHandle to the region handle of the scene this agent is moving into
  1174. CollisionPlane = Vector4.UnitW;
  1175. m_scene.EventManager.TriggerOnMakeChildAgent(this);
  1176. }
  1177. /// <summary>
  1178. /// Removes physics plugin scene representation of this agent if it exists.
  1179. /// </summary>
  1180. public void RemoveFromPhysicalScene()
  1181. {
  1182. if (PhysicsActor != null)
  1183. {
  1184. // PhysicsActor.OnRequestTerseUpdate -= SendTerseUpdateToAllClients;
  1185. PhysicsActor.OnOutOfBounds -= OutOfBoundsCall;
  1186. PhysicsActor.OnCollisionUpdate -= PhysicsCollisionUpdate;
  1187. PhysicsActor.UnSubscribeEvents();
  1188. m_scene.PhysicsScene.RemoveAvatar(PhysicsActor);
  1189. PhysicsActor = null;
  1190. }
  1191. // else
  1192. // {
  1193. // m_log.ErrorFormat(
  1194. // "[SCENE PRESENCE]: Attempt to remove physics actor for {0} on {1} but this scene presence has no physics actor",
  1195. // Name, Scene.RegionInfo.RegionName);
  1196. // }
  1197. }
  1198. /// <summary>
  1199. /// Do not call this directly. Call Scene.RequestTeleportLocation() instead.
  1200. /// </summary>
  1201. /// <param name="pos"></param>
  1202. public void Teleport(Vector3 pos)
  1203. {
  1204. TeleportWithMomentum(pos, Vector3.Zero);
  1205. }
  1206. public void TeleportWithMomentum(Vector3 pos, Vector3? v)
  1207. {
  1208. if (ParentID != (uint)0)
  1209. StandUp();
  1210. bool isFlying = Flying;
  1211. Vector3 vel = Velocity;
  1212. RemoveFromPhysicalScene();
  1213. CheckLandingPoint(ref pos);
  1214. AbsolutePosition = pos;
  1215. AddToPhysicalScene(isFlying);
  1216. if (PhysicsActor != null)
  1217. {
  1218. if (v.HasValue)
  1219. PhysicsActor.SetMomentum((Vector3)v);
  1220. else
  1221. PhysicsActor.SetMomentum(vel);
  1222. }
  1223. SendTerseUpdateToAllClients();
  1224. }
  1225. public void avnLocalTeleport(Vector3 newpos, Vector3? newvel, bool rotateToVelXY)
  1226. {
  1227. CheckLandingPoint(ref newpos);
  1228. AbsolutePosition = newpos;
  1229. if (newvel.HasValue)
  1230. {
  1231. if ((Vector3)newvel == Vector3.Zero)
  1232. {
  1233. if (PhysicsActor != null)
  1234. PhysicsActor.SetMomentum(Vector3.Zero);
  1235. m_velocity = Vector3.Zero;
  1236. }
  1237. else
  1238. {
  1239. if (PhysicsActor != null)
  1240. PhysicsActor.SetMomentum((Vector3)newvel);
  1241. m_velocity = (Vector3)newvel;
  1242. if (rotateToVelXY)
  1243. {
  1244. Vector3 lookAt = (Vector3)newvel;
  1245. lookAt.Z = 0;
  1246. lookAt.Normalize();
  1247. ControllingClient.SendLocalTeleport(newpos, lookAt, (uint)TeleportFlags.ViaLocation);
  1248. return;
  1249. }
  1250. }
  1251. }
  1252. SendTerseUpdateToAllClients();
  1253. }
  1254. public void StopFlying()
  1255. {
  1256. if (IsInTransit)
  1257. return;
  1258. Vector3 pos = AbsolutePosition;
  1259. if (Appearance.AvatarHeight != 127.0f)
  1260. pos += new Vector3(0f, 0f, (Appearance.AvatarHeight / 6f));
  1261. else
  1262. pos += new Vector3(0f, 0f, (1.56f / 6f));
  1263. AbsolutePosition = pos;
  1264. // attach a suitable collision plane regardless of the actual situation to force the LLClient to land.
  1265. // Collision plane below the avatar's position a 6th of the avatar's height is suitable.
  1266. // Mind you, that this method doesn't get called if the avatar's velocity magnitude is greater then a
  1267. // certain amount.. because the LLClient wouldn't land in that situation anyway.
  1268. // why are we still testing for this really old height value default???
  1269. if (Appearance.AvatarHeight != 127.0f)
  1270. CollisionPlane = new Vector4(0, 0, 0, pos.Z - Appearance.AvatarHeight / 6f);
  1271. else
  1272. CollisionPlane = new Vector4(0, 0, 0, pos.Z - (1.56f / 6f));
  1273. SendAgentTerseUpdate(this);
  1274. }
  1275. /// <summary>
  1276. /// Applies a roll accumulator to the avatar's angular velocity for the avatar fly roll effect.
  1277. /// </summary>
  1278. /// <param name="amount">Postive or negative roll amount in radians</param>
  1279. private void ApplyFlyingRoll(float amount, bool PressingUp, bool PressingDown)
  1280. {
  1281. float rollAmount = Util.Clamp(m_AngularVelocity.Z + amount, -FLY_ROLL_MAX_RADIANS, FLY_ROLL_MAX_RADIANS);
  1282. m_AngularVelocity.Z = rollAmount;
  1283. // APPLY EXTRA consideration for flying up and flying down during this time.
  1284. // if we're turning left
  1285. if (amount > 0)
  1286. {
  1287. // If we're at the max roll and pressing up, we want to swing BACK a bit
  1288. // Automatically adds noise
  1289. if (PressingUp)
  1290. {
  1291. if (m_AngularVelocity.Z >= FLY_ROLL_MAX_RADIANS - 0.04f)
  1292. m_AngularVelocity.Z -= 0.9f;
  1293. }
  1294. // If we're at the max roll and pressing down, we want to swing MORE a bit
  1295. if (PressingDown)
  1296. {
  1297. if (m_AngularVelocity.Z >= FLY_ROLL_MAX_RADIANS && m_AngularVelocity.Z < FLY_ROLL_MAX_RADIANS + 0.6f)
  1298. m_AngularVelocity.Z += 0.6f;
  1299. }
  1300. }
  1301. else // we're turning right.
  1302. {
  1303. // If we're at the max roll and pressing up, we want to swing BACK a bit
  1304. // Automatically adds noise
  1305. if (PressingUp)
  1306. {
  1307. if (m_AngularVelocity.Z <= (-FLY_ROLL_MAX_RADIANS))
  1308. m_AngularVelocity.Z += 0.6f;
  1309. }
  1310. // If we're at the max roll and pressing down, we want to swing MORE a bit
  1311. if (PressingDown)
  1312. {
  1313. if (m_AngularVelocity.Z >= -FLY_ROLL_MAX_RADIANS - 0.6f)
  1314. m_AngularVelocity.Z -= 0.6f;
  1315. }
  1316. }
  1317. }
  1318. /// <summary>
  1319. /// incrementally sets roll amount to zero
  1320. /// </summary>
  1321. /// <param name="amount">Positive roll amount in radians</param>
  1322. /// <returns></returns>
  1323. private float CalculateFlyingRollResetToZero(float amount)
  1324. {
  1325. const float rollMinRadians = 0f;
  1326. if (m_AngularVelocity.Z > 0)
  1327. {
  1328. float leftOverToMin = m_AngularVelocity.Z - rollMinRadians;
  1329. if (amount > leftOverToMin)
  1330. return -leftOverToMin;
  1331. else
  1332. return -amount;
  1333. }
  1334. else
  1335. {
  1336. float leftOverToMin = -m_AngularVelocity.Z - rollMinRadians;
  1337. if (amount > leftOverToMin)
  1338. return leftOverToMin;
  1339. else
  1340. return amount;
  1341. }
  1342. }
  1343. // neighbouring regions we have enabled a child agent in
  1344. // holds the seed cap for the child agent in that region
  1345. private Dictionary<ulong, string> m_knownChildRegions = new Dictionary<ulong, string>();
  1346. struct spRegionSizeInfo
  1347. {
  1348. public int sizeX;
  1349. public int sizeY;
  1350. }
  1351. private Dictionary<ulong, spRegionSizeInfo> m_knownChildRegionsSizeInfo = new Dictionary<ulong, spRegionSizeInfo>();
  1352. public void AddNeighbourRegionSizeInfo(GridRegion region)
  1353. {
  1354. lock (m_knownChildRegions)
  1355. {
  1356. spRegionSizeInfo sizeInfo = new spRegionSizeInfo();
  1357. sizeInfo.sizeX = region.RegionSizeX;
  1358. sizeInfo.sizeY = region.RegionSizeY;
  1359. ulong regionHandle = region.RegionHandle;
  1360. if (!m_knownChildRegionsSizeInfo.ContainsKey(regionHandle))
  1361. {
  1362. m_knownChildRegionsSizeInfo.Add(regionHandle, sizeInfo);
  1363. }
  1364. else
  1365. m_knownChildRegionsSizeInfo[regionHandle] = sizeInfo;
  1366. }
  1367. }
  1368. public void SetNeighbourRegionSizeInfo(List<GridRegion> regionsList)
  1369. {
  1370. lock (m_knownChildRegions)
  1371. {
  1372. m_knownChildRegionsSizeInfo.Clear();
  1373. foreach (GridRegion region in regionsList)
  1374. {
  1375. spRegionSizeInfo sizeInfo = new spRegionSizeInfo();
  1376. sizeInfo.sizeX = region.RegionSizeX;
  1377. sizeInfo.sizeY = region.RegionSizeY;
  1378. ulong regionHandle = region.RegionHandle;
  1379. m_knownChildRegionsSizeInfo.Add(regionHandle, sizeInfo);
  1380. }
  1381. }
  1382. }
  1383. public void RemoveNeighbourRegion(ulong regionHandle)
  1384. {
  1385. lock (m_knownChildRegions)
  1386. {
  1387. // Checking ContainsKey is redundant as Remove works either way and returns a bool
  1388. // This is here to allow the Debug output to be conditional on removal
  1389. //if (m_knownChildRegions.ContainsKey(regionHandle))
  1390. // m_log.DebugFormat(" !!! removing known region {0} in {1}. Count = {2}", regionHandle, Scene.RegionInfo.RegionName, m_knownChildRegions.Count);
  1391. m_knownChildRegions.Remove(regionHandle);
  1392. m_knownChildRegionsSizeInfo.Remove(regionHandle);
  1393. }
  1394. }
  1395. public void DropOldNeighbours(List<ulong> oldRegions)
  1396. {
  1397. foreach (ulong handle in oldRegions)
  1398. {
  1399. RemoveNeighbourRegion(handle);
  1400. Scene.CapsModule.DropChildSeed(UUID, handle);
  1401. }
  1402. }
  1403. public void DropThisRootRegionFromNeighbours()
  1404. {
  1405. ulong handle = m_scene.RegionInfo.RegionHandle;
  1406. RemoveNeighbourRegion(handle);
  1407. Scene.CapsModule.DropChildSeed(UUID, handle);
  1408. }
  1409. public Dictionary<ulong, string> KnownRegions
  1410. {
  1411. get
  1412. {
  1413. lock (m_knownChildRegions)
  1414. return new Dictionary<ulong, string>(m_knownChildRegions);
  1415. }
  1416. set
  1417. {
  1418. // Replacing the reference is atomic but we still need to lock on
  1419. // the original dictionary object which may be in use elsewhere
  1420. lock (m_knownChildRegions)
  1421. m_knownChildRegions = value;
  1422. }
  1423. }
  1424. public List<ulong> KnownRegionHandles
  1425. {
  1426. get
  1427. {
  1428. return new List<ulong>(KnownRegions.Keys);
  1429. }
  1430. }
  1431. public int KnownRegionCount
  1432. {
  1433. get
  1434. {
  1435. lock (m_knownChildRegions)
  1436. return m_knownChildRegions.Count;
  1437. }
  1438. }
  1439. #endregion
  1440. #region Event Handlers
  1441. /// <summary>
  1442. /// Sets avatar height in the physics plugin
  1443. /// </summary>
  1444. /// <param name="height">New height of avatar</param>
  1445. public void SetHeight(float height)
  1446. {
  1447. if (PhysicsActor != null && !IsChildAgent)
  1448. PhysicsActor.Size = new Vector3(0.45f, 0.6f, height);
  1449. }
  1450. public void SetSize(Vector3 size, float feetoffset)
  1451. {
  1452. if (PhysicsActor != null && !IsChildAgent)
  1453. PhysicsActor.setAvatarSize(size, feetoffset);
  1454. }
  1455. private bool WaitForUpdateAgent(IClientAPI client)
  1456. {
  1457. // Before the source region executes UpdateAgent
  1458. // (which triggers Scene.IncomingUpdateChildAgent(AgentData cAgentData) here in the destination,
  1459. // m_originRegionID is UUID.Zero; after, it's non-Zero. The CompleteMovement sequence initiated from the
  1460. // viewer (in turn triggered by the source region sending it a TeleportFinish event) waits until it's non-zero
  1461. // m_updateAgentReceivedAfterTransferEvent.WaitOne(10000);
  1462. int count = 50;
  1463. UUID originID = UUID.Zero;
  1464. lock (m_originRegionIDAccessLock)
  1465. originID = m_originRegionID;
  1466. while (originID.Equals(UUID.Zero) && count-- > 0)
  1467. {
  1468. lock (m_originRegionIDAccessLock)
  1469. originID = m_originRegionID;
  1470. m_log.DebugFormat("[SCENE PRESENCE]: Agent {0} waiting for update in {1}", client.Name, Scene.Name);
  1471. Thread.Sleep(200);
  1472. }
  1473. if (originID.Equals(UUID.Zero))
  1474. {
  1475. // Movement into region will fail
  1476. m_log.WarnFormat("[SCENE PRESENCE]: Update agent {0} never arrived in {1}", client.Name, Scene.Name);
  1477. return false;
  1478. }
  1479. return true;
  1480. }
  1481. /// <summary>
  1482. /// Complete Avatar's movement into the region.
  1483. /// </summary>
  1484. /// <param name="client"></param>
  1485. /// <param name="openChildAgents">
  1486. /// If true, send notification to neighbour regions to expect
  1487. /// a child agent from the client. These neighbours can be some distance away, depending right now on the
  1488. /// configuration of DefaultDrawDistance in the [Startup] section of config
  1489. /// </param>
  1490. public void CompleteMovement(IClientAPI client, bool openChildAgents)
  1491. {
  1492. int ts = Util.EnvironmentTickCount();
  1493. m_log.InfoFormat(
  1494. "[SCENE PRESENCE]: Completing movement of {0} into region {1} in position {2}",
  1495. client.Name, Scene.Name, AbsolutePosition);
  1496. m_inTransit = true;
  1497. try
  1498. {
  1499. // Make sure it's not a login agent. We don't want to wait for updates during login
  1500. if (!isNPC && !IsRealLogin(m_teleportFlags))
  1501. {
  1502. // Let's wait until UpdateAgent (called by departing region) is done
  1503. if (!WaitForUpdateAgent(client))
  1504. // The sending region never sent the UpdateAgent data, we have to refuse
  1505. return;
  1506. }
  1507. m_log.DebugFormat("[CompleteMovement] WaitForUpdateAgent: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1508. bool flying = ((m_AgentControlFlags & AgentManager.ControlFlags.AGENT_CONTROL_FLY) != 0);
  1509. if (!MakeRootAgent(AbsolutePosition, flying))
  1510. {
  1511. m_log.DebugFormat(
  1512. "[SCENE PRESENCE]: Aborting CompleteMovement call for {0} in {1} as they are already root",
  1513. Name, Scene.Name);
  1514. return;
  1515. }
  1516. m_log.DebugFormat("[CompleteMovement] MakeRootAgent: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1517. Vector3 look = Lookat;
  1518. if ((Math.Abs(look.X) < 0.01) && (Math.Abs(look.Y) < 0.01))
  1519. {
  1520. look = Velocity;
  1521. look.Z = 0;
  1522. look.Normalize();
  1523. if ((Math.Abs(look.X) < 0.01) && (Math.Abs(look.Y) < 0.01) )
  1524. look = new Vector3(0.99f, 0.042f, 0);
  1525. }
  1526. // start sending terrain patchs
  1527. if (!isNPC)
  1528. Scene.SendLayerData(ControllingClient);
  1529. if (!IsChildAgent && !isNPC)
  1530. {
  1531. InventoryFolderBase cof = m_scene.InventoryService.GetFolderForType(client.AgentId, (FolderType)46);
  1532. if (cof == null)
  1533. COF = UUID.Zero;
  1534. else
  1535. COF = cof.ID;
  1536. m_log.DebugFormat("[ScenePresence]: CompleteMovement COF for {0} is {1}", client.AgentId, COF);
  1537. }
  1538. // Tell the client that we're totally ready
  1539. ControllingClient.MoveAgentIntoRegion(m_scene.RegionInfo, AbsolutePosition, look);
  1540. m_log.DebugFormat("[CompleteMovement] MoveAgentIntoRegion: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1541. if (!string.IsNullOrEmpty(m_callbackURI))
  1542. {
  1543. // We cannot sleep here since this would hold up the inbound packet processing thread, as
  1544. // CompleteMovement() is executed synchronously. However, it might be better to delay the release
  1545. // here until we know for sure that the agent is active in this region. Sending AgentMovementComplete
  1546. // is not enough for Imprudence clients - there appears to be a small delay (<200ms, <500ms) until they regard this
  1547. // region as the current region, meaning that a close sent before then will fail the teleport.
  1548. // System.Threading.Thread.Sleep(2000);
  1549. m_log.DebugFormat(
  1550. "[SCENE PRESENCE]: Releasing {0} {1} with callback to {2}",
  1551. client.Name, client.AgentId, m_callbackURI);
  1552. UUID originID;
  1553. lock (m_originRegionIDAccessLock)
  1554. originID = m_originRegionID;
  1555. Scene.SimulationService.ReleaseAgent(originID, UUID, m_callbackURI);
  1556. m_callbackURI = null;
  1557. }
  1558. // else
  1559. // {
  1560. // m_log.DebugFormat(
  1561. // "[SCENE PRESENCE]: No callback provided on CompleteMovement of {0} {1} to {2}",
  1562. // client.Name, client.AgentId, m_scene.RegionInfo.RegionName);
  1563. // }
  1564. m_log.DebugFormat("[CompleteMovement] ReleaseAgent: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1565. m_previusParcelHide = false;
  1566. m_previusParcelUUID = UUID.Zero;
  1567. m_currentParcelHide = false;
  1568. m_currentParcelUUID = UUID.Zero;
  1569. // send initial land overlay and parcel
  1570. ILandChannel landch = m_scene.LandChannel;
  1571. if (landch != null)
  1572. landch.sendClientInitialLandInfo(client);
  1573. if (!IsChildAgent)
  1574. {
  1575. // ValidateAndSendAppearanceAndAgentData();
  1576. // do it here in line
  1577. // so sequence is clear
  1578. // verify baked textures and cache
  1579. bool cachedbaked = false;
  1580. if (isNPC)
  1581. cachedbaked = true;
  1582. else
  1583. {
  1584. if (m_scene.AvatarFactory != null)
  1585. cachedbaked = m_scene.AvatarFactory.ValidateBakedTextureCache(this);
  1586. // not sure we need this
  1587. if (!cachedbaked)
  1588. {
  1589. if (m_scene.AvatarFactory != null)
  1590. m_scene.AvatarFactory.QueueAppearanceSave(UUID);
  1591. }
  1592. }
  1593. List<ScenePresence> allpresences = m_scene.GetScenePresences();
  1594. // send avatar object to all presences including us, so they cross it into region
  1595. // then hide if necessary
  1596. SendInitialAvatarDataToAllAgents(allpresences);
  1597. // send this look
  1598. SendAppearanceToAgent(this);
  1599. // send this animations
  1600. UUID[] animIDs = null;
  1601. int[] animseqs = null;
  1602. UUID[] animsobjs = null;
  1603. if (Animator != null)
  1604. Animator.GetArrays(out animIDs, out animseqs, out animsobjs);
  1605. bool haveAnims = (animIDs != null && animseqs != null && animsobjs != null);
  1606. if (haveAnims)
  1607. SendAnimPackToAgent(this, animIDs, animseqs, animsobjs);
  1608. // we should be able to receive updates, etc
  1609. // so release them
  1610. m_inTransit = false;
  1611. // send look and animations to others
  1612. // if not cached we send greys
  1613. // uncomented if will wait till avatar does baking
  1614. //if (cachedbaked)
  1615. {
  1616. foreach (ScenePresence p in allpresences)
  1617. {
  1618. if (p == this)
  1619. continue;
  1620. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && p.GodLevel < 200)
  1621. continue;
  1622. SendAppearanceToAgentNF(p);
  1623. if (haveAnims)
  1624. SendAnimPackToAgentNF(p, animIDs, animseqs, animsobjs);
  1625. }
  1626. } // greys if
  1627. m_log.DebugFormat("[CompleteMovement] ValidateAndSendAppearanceAndAgentData: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1628. // attachments
  1629. if (isNPC || IsRealLogin(m_teleportFlags))
  1630. {
  1631. if (Scene.AttachmentsModule != null)
  1632. // Util.FireAndForget(
  1633. // o =>
  1634. // {
  1635. if (!isNPC)
  1636. Scene.AttachmentsModule.RezAttachments(this);
  1637. else
  1638. Util.FireAndForget(x =>
  1639. {
  1640. Scene.AttachmentsModule.RezAttachments(this);
  1641. });
  1642. // });
  1643. }
  1644. else
  1645. {
  1646. if (m_attachments.Count > 0)
  1647. {
  1648. m_log.DebugFormat(
  1649. "[SCENE PRESENCE]: Restarting scripts in attachments for {0} in {1}", Name, Scene.Name);
  1650. foreach (SceneObjectGroup sog in m_attachments)
  1651. {
  1652. sog.RootPart.ParentGroup.CreateScriptInstances(0, false, m_scene.DefaultScriptEngine, GetStateSource());
  1653. sog.ResumeScripts();
  1654. }
  1655. foreach (ScenePresence p in allpresences)
  1656. {
  1657. if (p == this)
  1658. {
  1659. SendTerseUpdateToAgentNF(this);
  1660. SendAttachmentsToAgentNF(this);
  1661. continue;
  1662. }
  1663. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && p.GodLevel < 200)
  1664. continue;
  1665. SendTerseUpdateToAgentNF(p);
  1666. SendAttachmentsToAgentNF(p);
  1667. }
  1668. }
  1669. }
  1670. m_log.DebugFormat("[CompleteMovement] attachments: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1671. if (openChildAgents)
  1672. {
  1673. // Create child agents in neighbouring regions
  1674. IEntityTransferModule m_agentTransfer = m_scene.RequestModuleInterface<IEntityTransferModule>();
  1675. if (m_agentTransfer != null)
  1676. {
  1677. m_agentTransfer.EnableChildAgents(this);
  1678. }
  1679. }
  1680. }
  1681. m_log.DebugFormat("[CompleteMovement] openChildAgents: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1682. // send the rest of the world
  1683. if (m_teleportFlags > 0 && !isNPC || m_currentParcelHide)
  1684. SendInitialDataToMe();
  1685. m_log.DebugFormat("[CompleteMovement] SendInitialDataToMe: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1686. if (!IsChildAgent && openChildAgents)
  1687. {
  1688. IFriendsModule friendsModule = m_scene.RequestModuleInterface<IFriendsModule>();
  1689. // if (friendsModule != null)
  1690. // friendsModule.SendFriendsOnlineIfNeeded(ControllingClient);
  1691. m_log.DebugFormat("[CompleteMovement] friendsModule: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1692. }
  1693. }
  1694. finally
  1695. {
  1696. m_inTransit = false;
  1697. }
  1698. // if hide force a check
  1699. // if (!IsChildAgent && newhide)
  1700. // {
  1701. // ParcelLoginCheck(m_currentParcelUUID);
  1702. // m_currentParcelHide = newhide;
  1703. // }
  1704. m_scene.EventManager.OnRegionHeartbeatEnd += RegionHeartbeatEnd;
  1705. m_log.DebugFormat("[CompleteMovement] end: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1706. }
  1707. /// <summary>
  1708. /// Callback for the Camera view block check. Gets called with the results of the camera view block test
  1709. /// hitYN is true when there's something in the way.
  1710. /// </summary>
  1711. /// <param name="hitYN"></param>
  1712. /// <param name="collisionPoint"></param>
  1713. /// <param name="localid"></param>
  1714. /// <param name="distance"></param>
  1715. ///
  1716. private void UpdateCameraCollisionPlane(Vector4 plane)
  1717. {
  1718. if (m_lastCameraCollisionPlane != plane)
  1719. {
  1720. m_lastCameraCollisionPlane = plane;
  1721. ControllingClient.SendCameraConstraint(plane);
  1722. }
  1723. }
  1724. public void RayCastCameraCallback(bool hitYN, Vector3 collisionPoint, uint localid, float distance, Vector3 pNormal)
  1725. {
  1726. const float POSITION_TOLERANCE = 0.02f;
  1727. const float ROTATION_TOLERANCE = 0.02f;
  1728. m_doingCamRayCast = false;
  1729. if (hitYN && localid != LocalId)
  1730. {
  1731. SceneObjectGroup group = m_scene.GetGroupByPrim(localid);
  1732. bool IsPrim = group != null;
  1733. if (IsPrim)
  1734. {
  1735. SceneObjectPart part = group.GetPart(localid);
  1736. if (part != null && !part.VolumeDetectActive)
  1737. {
  1738. CameraConstraintActive = true;
  1739. pNormal.X = (float) Math.Round(pNormal.X, 2);
  1740. pNormal.Y = (float) Math.Round(pNormal.Y, 2);
  1741. pNormal.Z = (float) Math.Round(pNormal.Z, 2);
  1742. pNormal.Normalize();
  1743. collisionPoint.X = (float) Math.Round(collisionPoint.X, 1);
  1744. collisionPoint.Y = (float) Math.Round(collisionPoint.Y, 1);
  1745. collisionPoint.Z = (float) Math.Round(collisionPoint.Z, 1);
  1746. Vector4 plane = new Vector4(pNormal.X, pNormal.Y, pNormal.Z,
  1747. Vector3.Dot(collisionPoint, pNormal));
  1748. UpdateCameraCollisionPlane(plane);
  1749. }
  1750. }
  1751. else
  1752. {
  1753. CameraConstraintActive = true;
  1754. pNormal.X = (float) Math.Round(pNormal.X, 2);
  1755. pNormal.Y = (float) Math.Round(pNormal.Y, 2);
  1756. pNormal.Z = (float) Math.Round(pNormal.Z, 2);
  1757. pNormal.Normalize();
  1758. collisionPoint.X = (float) Math.Round(collisionPoint.X, 1);
  1759. collisionPoint.Y = (float) Math.Round(collisionPoint.Y, 1);
  1760. collisionPoint.Z = (float) Math.Round(collisionPoint.Z, 1);
  1761. Vector4 plane = new Vector4(pNormal.X, pNormal.Y, pNormal.Z,
  1762. Vector3.Dot(collisionPoint, pNormal));
  1763. UpdateCameraCollisionPlane(plane);
  1764. }
  1765. }
  1766. else if (!m_pos.ApproxEquals(m_lastPosition, POSITION_TOLERANCE) ||
  1767. !Rotation.ApproxEquals(m_lastRotation, ROTATION_TOLERANCE))
  1768. {
  1769. Vector4 plane = new Vector4(0.9f, 0.0f, 0.361f, -9000f); // not right...
  1770. UpdateCameraCollisionPlane(plane);
  1771. CameraConstraintActive = false;
  1772. }
  1773. }
  1774. /// <summary>
  1775. /// This is the event handler for client movement. If a client is moving, this event is triggering.
  1776. /// </summary>
  1777. public void HandleAgentUpdate(IClientAPI remoteClient, AgentUpdateArgs agentData)
  1778. {
  1779. // m_log.DebugFormat(
  1780. // "[SCENE PRESENCE]: In {0} received agent update from {1}, flags {2}",
  1781. // Scene.Name, remoteClient.Name, (AgentManager.ControlFlags)agentData.ControlFlags);
  1782. if (IsChildAgent)
  1783. {
  1784. // m_log.DebugFormat("DEBUG: HandleAgentUpdate: child agent in {0}", Scene.Name);
  1785. return;
  1786. }
  1787. if (IsInTransit)
  1788. return;
  1789. #region Sanity Checking
  1790. // This is irritating. Really.
  1791. if (!AbsolutePosition.IsFinite())
  1792. {
  1793. RemoveFromPhysicalScene();
  1794. m_log.Error("[AVATAR]: NonFinite Avatar position detected... Reset Position. Mantis this please. Error #9999902");
  1795. m_pos = m_LastFinitePos;
  1796. if (!m_pos.IsFinite())
  1797. {
  1798. m_pos.X = 127f;
  1799. m_pos.Y = 127f;
  1800. m_pos.Z = 127f;
  1801. m_log.Error("[AVATAR]: NonFinite Avatar position detected... Reset Position. Mantis this please. Error #9999903");
  1802. }
  1803. AddToPhysicalScene(false);
  1804. }
  1805. else
  1806. {
  1807. m_LastFinitePos = m_pos;
  1808. }
  1809. #endregion Sanity Checking
  1810. #region Inputs
  1811. AgentManager.ControlFlags flags = (AgentManager.ControlFlags)agentData.ControlFlags;
  1812. // The Agent's Draw distance setting
  1813. // When we get to the point of re-computing neighbors everytime this
  1814. // changes, then start using the agent's drawdistance rather than the
  1815. // region's draw distance.
  1816. DrawDistance = Util.Clamp(agentData.Far, 32, m_scene.MaxDrawDistance);
  1817. m_mouseLook = (flags & AgentManager.ControlFlags.AGENT_CONTROL_MOUSELOOK) != 0;
  1818. // FIXME: This does not work as intended because the viewer only sends the lbutton down when the button
  1819. // is first pressed, not whilst it is held down. If this is required in the future then need to look
  1820. // for an AGENT_CONTROL_LBUTTON_UP event and make sure to handle cases where an initial DOWN is not
  1821. // received (e.g. on holding LMB down on the avatar in a viewer).
  1822. m_leftButtonDown = (flags & AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN) != 0;
  1823. #endregion Inputs
  1824. // // Make anims work for client side autopilot
  1825. // if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_AT_POS) != 0)
  1826. // m_updateCount = UPDATE_COUNT;
  1827. //
  1828. // // Make turning in place work
  1829. // if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS) != 0 ||
  1830. // (flags & AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG) != 0)
  1831. // m_updateCount = UPDATE_COUNT;
  1832. if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_STAND_UP) != 0)
  1833. {
  1834. StandUp();
  1835. }
  1836. // Raycast from the avatar's head to the camera to see if there's anything blocking the view
  1837. // this exclude checks may not be complete
  1838. if (m_movementUpdateCount % NumMovementsBetweenRayCast == 0 && m_scene.PhysicsScene.SupportsRayCast())
  1839. {
  1840. if (!m_doingCamRayCast && !m_mouseLook && ParentID == 0)
  1841. {
  1842. Vector3 posAdjusted = AbsolutePosition;
  1843. // posAdjusted.Z += 0.5f * Appearance.AvatarSize.Z - 0.5f;
  1844. posAdjusted.Z += 1.0f; // viewer current camera focus point
  1845. Vector3 tocam = CameraPosition - posAdjusted;
  1846. tocam.X = (float)Math.Round(tocam.X, 1);
  1847. tocam.Y = (float)Math.Round(tocam.Y, 1);
  1848. tocam.Z = (float)Math.Round(tocam.Z, 1);
  1849. float distTocamlen = tocam.Length();
  1850. if (distTocamlen > 0.3f)
  1851. {
  1852. tocam *= (1.0f / distTocamlen);
  1853. posAdjusted.X = (float)Math.Round(posAdjusted.X, 1);
  1854. posAdjusted.Y = (float)Math.Round(posAdjusted.Y, 1);
  1855. posAdjusted.Z = (float)Math.Round(posAdjusted.Z, 1);
  1856. m_doingCamRayCast = true;
  1857. m_scene.PhysicsScene.RaycastWorld(posAdjusted, tocam, distTocamlen + 1.0f, RayCastCameraCallback);
  1858. }
  1859. }
  1860. else if (CameraConstraintActive && (m_mouseLook || ParentID != 0))
  1861. {
  1862. Vector4 plane = new Vector4(0.9f, 0.0f, 0.361f, -10000f); // not right...
  1863. UpdateCameraCollisionPlane(plane);
  1864. CameraConstraintActive = false;
  1865. }
  1866. }
  1867. uint flagsForScripts = (uint)flags;
  1868. flags = RemoveIgnoredControls(flags, IgnoredControls);
  1869. if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_SIT_ON_GROUND) != 0)
  1870. HandleAgentSitOnGround();
  1871. // In the future, these values might need to go global.
  1872. // Here's where you get them.
  1873. m_AgentControlFlags = flags;
  1874. m_headrotation = agentData.HeadRotation;
  1875. byte oldState = State;
  1876. State = agentData.State;
  1877. // We need to send this back to the client in order to stop the edit beams
  1878. if ((oldState & (uint)AgentState.Editing) != 0 && State == (uint)AgentState.None)
  1879. SendAgentTerseUpdate(this);
  1880. PhysicsActor actor = PhysicsActor;
  1881. // This will be the case if the agent is sitting on the groudn or on an object.
  1882. if (actor == null)
  1883. {
  1884. SendControlsToScripts(flagsForScripts);
  1885. return;
  1886. }
  1887. if (AllowMovement && !SitGround)
  1888. {
  1889. // m_log.DebugFormat("[SCENE PRESENCE]: Initial body rotation {0} for {1}", agentData.BodyRotation, Name);
  1890. bool update_rotation = false;
  1891. if (agentData.BodyRotation != Rotation)
  1892. {
  1893. Rotation = agentData.BodyRotation;
  1894. update_rotation = true;
  1895. }
  1896. bool update_movementflag = false;
  1897. if (agentData.UseClientAgentPosition)
  1898. {
  1899. MovingToTarget = (agentData.ClientAgentPosition - AbsolutePosition).Length() > 0.2f;
  1900. MoveToPositionTarget = agentData.ClientAgentPosition;
  1901. }
  1902. int i = 0;
  1903. bool DCFlagKeyPressed = false;
  1904. Vector3 agent_control_v3 = Vector3.Zero;
  1905. bool newFlying = false;
  1906. if (ForceFly)
  1907. newFlying = true;
  1908. else if (FlyDisabled)
  1909. newFlying = false;
  1910. else
  1911. newFlying = ((flags & AgentManager.ControlFlags.AGENT_CONTROL_FLY) != 0);
  1912. if (actor.Flying != newFlying)
  1913. {
  1914. // Note: ScenePresence.Flying is actually fetched from the physical actor
  1915. // so setting PhysActor.Flying here also sets the ScenePresence's value.
  1916. actor.Flying = newFlying;
  1917. update_movementflag = true;
  1918. }
  1919. if (ParentID == 0)
  1920. {
  1921. bool bAllowUpdateMoveToPosition = false;
  1922. Vector3[] dirVectors;
  1923. // use camera up angle when in mouselook and not flying or when holding the left mouse button down and not flying
  1924. // this prevents 'jumping' in inappropriate situations.
  1925. // if (!Flying && (m_mouseLook || m_leftButtonDown))
  1926. // dirVectors = GetWalkDirectionVectors();
  1927. // else
  1928. dirVectors = Dir_Vectors;
  1929. // A DIR_CONTROL_FLAG occurs when the user is trying to move in a particular direction.
  1930. foreach (Dir_ControlFlags DCF in DIR_CONTROL_FLAGS)
  1931. {
  1932. if (((uint)flags & (uint)DCF) != 0)
  1933. {
  1934. DCFlagKeyPressed = true;
  1935. try
  1936. {
  1937. agent_control_v3 += Dir_Vectors[i];
  1938. //m_log.DebugFormat("[Motion]: {0}, {1}",i, dirVectors[i]);
  1939. }
  1940. catch (IndexOutOfRangeException)
  1941. {
  1942. // Why did I get this?
  1943. }
  1944. if (((MovementFlag & (uint)DCF) == 0))
  1945. {
  1946. //m_log.DebugFormat("[SCENE PRESENCE]: Updating MovementFlag for {0} with {1}", Name, DCF);
  1947. MovementFlag |= (uint)DCF;
  1948. update_movementflag = true;
  1949. }
  1950. }
  1951. else
  1952. {
  1953. if ((MovementFlag & (uint)DCF) != 0)
  1954. {
  1955. //m_log.DebugFormat("[SCENE PRESENCE]: Updating MovementFlag for {0} with lack of {1}", Name, DCF);
  1956. MovementFlag &= (uint)~DCF;
  1957. update_movementflag = true;
  1958. /*
  1959. if ((DCF == Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD_NUDGE || DCF == Dir_ControlFlags.DIR_CONTROL_FLAG_BACKWARD_NUDGE)
  1960. && ((MovementFlag & (byte)nudgehack) == nudgehack))
  1961. {
  1962. m_log.Debug("Removed Hack flag");
  1963. }
  1964. */
  1965. }
  1966. else
  1967. {
  1968. bAllowUpdateMoveToPosition = true;
  1969. }
  1970. }
  1971. i++;
  1972. }
  1973. // Detect AGENT_CONTROL_STOP state changes
  1974. if (AgentControlStopActive != ((flags & AgentManager.ControlFlags.AGENT_CONTROL_STOP) != 0))
  1975. {
  1976. AgentControlStopActive = !AgentControlStopActive;
  1977. update_movementflag = true;
  1978. }
  1979. if (MovingToTarget)
  1980. {
  1981. // If the user has pressed a key then we want to cancel any move to target.
  1982. if (DCFlagKeyPressed)
  1983. {
  1984. ResetMoveToTarget();
  1985. update_movementflag = true;
  1986. }
  1987. else if (bAllowUpdateMoveToPosition)
  1988. {
  1989. // The UseClientAgentPosition is set if parcel ban is forcing the avatar to move to a
  1990. // certain position. It's only check for tolerance on returning to that position is 0.2
  1991. // rather than 1, at which point it removes its force target.
  1992. if (HandleMoveToTargetUpdate(agentData.UseClientAgentPosition ? 0.2 : 1, ref agent_control_v3))
  1993. update_movementflag = true;
  1994. }
  1995. }
  1996. }
  1997. // Cause the avatar to stop flying if it's colliding
  1998. // with something with the down arrow pressed.
  1999. // Only do this if we're flying
  2000. if (Flying && !ForceFly)
  2001. {
  2002. // Need to stop in mid air if user holds down AGENT_CONTROL_STOP
  2003. // if (AgentControlStopActive)
  2004. // {
  2005. // agent_control_v3 = Vector3.Zero;
  2006. // }
  2007. // else
  2008. {
  2009. // Landing detection code
  2010. // Are the landing controls requirements filled?
  2011. bool controlland = (((flags & AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0) ||
  2012. ((flags & AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG) != 0));
  2013. //m_log.Debug("[CONTROL]: " +flags);
  2014. // Applies a satisfying roll effect to the avatar when flying.
  2015. if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_TURN_LEFT) != 0 && (flags & AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS) != 0)
  2016. {
  2017. ApplyFlyingRoll(
  2018. FLY_ROLL_RADIANS_PER_UPDATE,
  2019. (flags & AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) != 0,
  2020. (flags & AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0);
  2021. }
  2022. else if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_TURN_RIGHT) != 0 &&
  2023. (flags & AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG) != 0)
  2024. {
  2025. ApplyFlyingRoll(
  2026. -FLY_ROLL_RADIANS_PER_UPDATE,
  2027. (flags & AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) != 0,
  2028. (flags & AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0);
  2029. }
  2030. else
  2031. {
  2032. if (m_AngularVelocity.Z != 0)
  2033. m_AngularVelocity.Z += CalculateFlyingRollResetToZero(FLY_ROLL_RESET_RADIANS_PER_UPDATE);
  2034. }
  2035. /*
  2036. if (Flying && IsColliding && controlland)
  2037. {
  2038. // nesting this check because LengthSquared() is expensive and we don't
  2039. // want to do it every step when flying.
  2040. if ((Velocity.LengthSquared() <= LAND_VELOCITYMAG_MAX))
  2041. StopFlying();
  2042. }
  2043. */
  2044. }
  2045. }
  2046. else if (IsColliding && agent_control_v3.Z < 0f)
  2047. agent_control_v3.Z = 0;
  2048. // else if(AgentControlStopActive %% Velocity.Z <0.01f)
  2049. // m_log.DebugFormat("[SCENE PRESENCE]: MovementFlag {0} for {1}", MovementFlag, Name);
  2050. // If the agent update does move the avatar, then calculate the force ready for the velocity update,
  2051. // which occurs later in the main scene loop
  2052. // We also need to update if the user rotates their avatar whilst it is slow walking/running (if they
  2053. // held down AGENT_CONTROL_STOP whilst normal walking/running). However, we do not want to update
  2054. // if the user rotated whilst holding down AGENT_CONTROL_STOP when already still (which locks the
  2055. // avatar location in place).
  2056. if (update_movementflag
  2057. || (update_rotation && DCFlagKeyPressed && (!AgentControlStopActive || MovementFlag != 0)))
  2058. {
  2059. if (AgentControlStopActive)
  2060. {
  2061. // if (MovementFlag == 0 && Animator.Falling)
  2062. if (MovementFlag == 0 && Animator.currentControlState == ScenePresenceAnimator.motionControlStates.falling)
  2063. {
  2064. AddNewMovement(agent_control_v3, AgentControlStopSlowVel, true);
  2065. }
  2066. else
  2067. AddNewMovement(agent_control_v3, AgentControlStopSlowVel);
  2068. }
  2069. else
  2070. {
  2071. AddNewMovement(agent_control_v3);
  2072. }
  2073. }
  2074. if (update_movementflag && ParentID == 0)
  2075. {
  2076. // m_log.DebugFormat("[SCENE PRESENCE]: Updating movement animations for {0}", Name);
  2077. Animator.UpdateMovementAnimations();
  2078. }
  2079. SendControlsToScripts(flagsForScripts);
  2080. }
  2081. // We need to send this back to the client in order to see the edit beams
  2082. if ((State & (uint)AgentState.Editing) != 0)
  2083. SendAgentTerseUpdate(this);
  2084. m_scene.EventManager.TriggerOnClientMovement(this);
  2085. }
  2086. /// <summary>
  2087. /// This is the event handler for client cameras. If a client is moving, or moving the camera, this event is triggering.
  2088. /// </summary>
  2089. private void HandleAgentCamerasUpdate(IClientAPI remoteClient, AgentUpdateArgs agentData)
  2090. {
  2091. //m_log.DebugFormat(
  2092. // "[SCENE PRESENCE]: In {0} received agent camera update from {1}, flags {2}",
  2093. // Scene.RegionInfo.RegionName, remoteClient.Name, (AgentManager.ControlFlags)agentData.ControlFlags);
  2094. if (IsChildAgent)
  2095. {
  2096. // // m_log.Debug("DEBUG: HandleAgentUpdate: child agent");
  2097. return;
  2098. }
  2099. ++m_movementUpdateCount;
  2100. if (m_movementUpdateCount < 1)
  2101. m_movementUpdateCount = 1;
  2102. // AgentManager.ControlFlags flags = (AgentManager.ControlFlags)agentData.ControlFlags;
  2103. // Camera location in world. We'll need to raytrace
  2104. // from this location from time to time.
  2105. CameraPosition = agentData.CameraCenter;
  2106. if (Vector3.Distance(m_lastCameraPosition, CameraPosition) >= Scene.RootReprioritizationDistance)
  2107. {
  2108. ReprioritizeUpdates();
  2109. m_lastCameraPosition = CameraPosition;
  2110. }
  2111. // Use these three vectors to figure out what the agent is looking at
  2112. // Convert it to a Matrix and/or Quaternion
  2113. CameraAtAxis = agentData.CameraAtAxis;
  2114. CameraLeftAxis = agentData.CameraLeftAxis;
  2115. CameraUpAxis = agentData.CameraUpAxis;
  2116. // The Agent's Draw distance setting
  2117. // When we get to the point of re-computing neighbors everytime this
  2118. // changes, then start using the agent's drawdistance rather than the
  2119. // region's draw distance.
  2120. DrawDistance = Util.Clamp(agentData.Far, 32, m_scene.MaxDrawDistance);
  2121. // Check if Client has camera in 'follow cam' or 'build' mode.
  2122. Vector3 camdif = (Vector3.One * Rotation - Vector3.One * CameraRotation);
  2123. m_followCamAuto = ((CameraUpAxis.Z > 0.959f && CameraUpAxis.Z < 0.98f)
  2124. && (Math.Abs(camdif.X) < 0.4f && Math.Abs(camdif.Y) < 0.4f)) ? true : false;
  2125. //m_log.DebugFormat("[FollowCam]: {0}", m_followCamAuto);
  2126. // Raycast from the avatar's head to the camera to see if there's anything blocking the view
  2127. if ((m_movementUpdateCount % NumMovementsBetweenRayCast) == 0 && m_scene.PhysicsScene.SupportsRayCast())
  2128. {
  2129. if (m_followCamAuto)
  2130. {
  2131. Vector3 posAdjusted = m_pos + HEAD_ADJUSTMENT;
  2132. m_scene.PhysicsScene.RaycastWorld(m_pos, Vector3.Normalize(CameraPosition - posAdjusted), Vector3.Distance(CameraPosition, posAdjusted) + 0.3f, RayCastCameraCallback);
  2133. }
  2134. }
  2135. TriggerScenePresenceUpdated();
  2136. }
  2137. /// <summary>
  2138. /// Calculate an update to move the presence to the set target.
  2139. /// </summary>
  2140. /// <remarks>
  2141. /// This doesn't actually perform the movement. Instead, it adds its vector to agent_control_v3.
  2142. /// </remarks>
  2143. /// <param value="agent_control_v3">Cumulative agent movement that this method will update.</param>
  2144. /// <returns>True if movement has been updated in some way. False otherwise.</returns>
  2145. public bool HandleMoveToTargetUpdate(double tolerance, ref Vector3 agent_control_v3)
  2146. {
  2147. // m_log.DebugFormat("[SCENE PRESENCE]: Called HandleMoveToTargetUpdate() for {0}", Name);
  2148. bool updated = false;
  2149. Vector3 LocalVectorToTarget3D = MoveToPositionTarget - AbsolutePosition;
  2150. // m_log.DebugFormat(
  2151. // "[SCENE PRESENCE]: bAllowUpdateMoveToPosition {0}, m_moveToPositionInProgress {1}, m_autopilotMoving {2}",
  2152. // allowUpdate, m_moveToPositionInProgress, m_autopilotMoving);
  2153. double distanceToTarget = LocalVectorToTarget3D.Length();
  2154. // m_log.DebugFormat(
  2155. // "[SCENE PRESENCE]: Abs pos of {0} is {1}, target {2}, distance {3}",
  2156. // Name, AbsolutePosition, MoveToPositionTarget, distanceToTarget);
  2157. // Check the error term of the current position in relation to the target position
  2158. if (distanceToTarget <= tolerance)
  2159. {
  2160. // We are close enough to the target
  2161. AbsolutePosition = MoveToPositionTarget;
  2162. ResetMoveToTarget();
  2163. updated = true;
  2164. }
  2165. else
  2166. {
  2167. try
  2168. {
  2169. // move avatar in 3D at one meter/second towards target, in avatar coordinate frame.
  2170. // This movement vector gets added to the velocity through AddNewMovement().
  2171. // Theoretically we might need a more complex PID approach here if other
  2172. // unknown forces are acting on the avatar and we need to adaptively respond
  2173. // to such forces, but the following simple approach seems to works fine.
  2174. LocalVectorToTarget3D = LocalVectorToTarget3D * Quaternion.Inverse(Rotation); // change to avatar coords
  2175. // Ignore z component of vector
  2176. // Vector3 LocalVectorToTarget2D = new Vector3((float)(LocalVectorToTarget3D.X), (float)(LocalVectorToTarget3D.Y), 0f);
  2177. LocalVectorToTarget3D.Normalize();
  2178. // update avatar movement flags. the avatar coordinate system is as follows:
  2179. //
  2180. // +X (forward)
  2181. //
  2182. // ^
  2183. // |
  2184. // |
  2185. // |
  2186. // |
  2187. // (left) +Y <--------o--------> -Y
  2188. // avatar
  2189. // |
  2190. // |
  2191. // |
  2192. // |
  2193. // v
  2194. // -X
  2195. //
  2196. // based on the above avatar coordinate system, classify the movement into
  2197. // one of left/right/back/forward.
  2198. const uint noMovFlagsMask = (uint)(~(Dir_ControlFlags.DIR_CONTROL_FLAG_BACK |
  2199. Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD | Dir_ControlFlags.DIR_CONTROL_FLAG_LEFT |
  2200. Dir_ControlFlags.DIR_CONTROL_FLAG_RIGHT | Dir_ControlFlags.DIR_CONTROL_FLAG_UP |
  2201. Dir_ControlFlags.DIR_CONTROL_FLAG_DOWN));
  2202. MovementFlag &= noMovFlagsMask;
  2203. AgentControlFlags &= noMovFlagsMask;
  2204. if (LocalVectorToTarget3D.X < 0) //MoveBack
  2205. {
  2206. MovementFlag |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_BACK;
  2207. AgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_BACK;
  2208. updated = true;
  2209. }
  2210. else if (LocalVectorToTarget3D.X > 0) //Move Forward
  2211. {
  2212. MovementFlag |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD;
  2213. AgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD;
  2214. updated = true;
  2215. }
  2216. if (LocalVectorToTarget3D.Y > 0) //MoveLeft
  2217. {
  2218. MovementFlag |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_LEFT;
  2219. AgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_LEFT;
  2220. updated = true;
  2221. }
  2222. else if (LocalVectorToTarget3D.Y < 0) //MoveRight
  2223. {
  2224. MovementFlag |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_RIGHT;
  2225. AgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_RIGHT;
  2226. updated = true;
  2227. }
  2228. if (LocalVectorToTarget3D.Z > 0) //Up
  2229. {
  2230. // Don't set these flags for up or down - doing so will make the avatar crouch or
  2231. // keep trying to jump even if walking along level ground
  2232. //MovementFlag += (byte)(uint)Dir_ControlFlags.DIR_CONTROL_FLAG_UP;
  2233. //AgentControlFlags
  2234. //AgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_UP;
  2235. updated = true;
  2236. }
  2237. else if (LocalVectorToTarget3D.Z < 0) //Down
  2238. {
  2239. //MovementFlag += (byte)(uint)Dir_ControlFlags.DIR_CONTROL_FLAG_DOWN;
  2240. //AgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_DOWN;
  2241. updated = true;
  2242. }
  2243. // m_log.DebugFormat(
  2244. // "[SCENE PRESENCE]: HandleMoveToTargetUpdate adding {0} to move vector {1} for {2}",
  2245. // LocalVectorToTarget3D, agent_control_v3, Name);
  2246. agent_control_v3 += LocalVectorToTarget3D;
  2247. }
  2248. catch (Exception e)
  2249. {
  2250. //Avoid system crash, can be slower but...
  2251. m_log.DebugFormat("Crash! {0}", e.ToString());
  2252. }
  2253. }
  2254. return updated;
  2255. }
  2256. /// <summary>
  2257. /// Move to the given target over time.
  2258. /// </summary>
  2259. /// <param name="pos"></param>
  2260. /// <param name="noFly">
  2261. /// If true, then don't allow the avatar to fly to the target, even if it's up in the air.
  2262. /// This is to allow movement to targets that are known to be on an elevated platform with a continuous path
  2263. /// from start to finish.
  2264. /// </param>
  2265. /// <param name="landAtTarget">
  2266. /// If true and the avatar starts flying during the move then land at the target.
  2267. /// </param>
  2268. public void MoveToTarget(Vector3 pos, bool noFly, bool landAtTarget)
  2269. {
  2270. if (SitGround)
  2271. StandUp();
  2272. // m_log.DebugFormat(
  2273. // "[SCENE PRESENCE]: Avatar {0} received request to move to position {1} in {2}",
  2274. // Name, pos, m_scene.RegionInfo.RegionName);
  2275. // Allow move to another sub-region within a megaregion
  2276. Vector2 regionSize;
  2277. IRegionCombinerModule regionCombinerModule = m_scene.RequestModuleInterface<IRegionCombinerModule>();
  2278. if (regionCombinerModule != null)
  2279. regionSize = regionCombinerModule.GetSizeOfMegaregion(m_scene.RegionInfo.RegionID);
  2280. else
  2281. regionSize = new Vector2(m_scene.RegionInfo.RegionSizeX, m_scene.RegionInfo.RegionSizeY);
  2282. if (pos.X < 0 || pos.X >= regionSize.X
  2283. || pos.Y < 0 || pos.Y >= regionSize.Y
  2284. || pos.Z < 0)
  2285. return;
  2286. Scene targetScene = m_scene;
  2287. // Get terrain height for sub-region in a megaregion if necessary
  2288. if (regionCombinerModule != null)
  2289. {
  2290. int X = (int)((m_scene.RegionInfo.WorldLocX) + pos.X);
  2291. int Y = (int)((m_scene.RegionInfo.WorldLocY) + pos.Y);
  2292. GridRegion target_region = m_scene.GridService.GetRegionByPosition(m_scene.RegionInfo.ScopeID, X, Y);
  2293. // If X and Y is NaN, target_region will be null
  2294. if (target_region == null)
  2295. return;
  2296. UUID target_regionID = target_region.RegionID;
  2297. SceneManager.Instance.TryGetScene(target_region.RegionID, out targetScene);
  2298. }
  2299. float terrainHeight = (float)targetScene.Heightmap[(int)(pos.X % regionSize.X), (int)(pos.Y % regionSize.Y)];
  2300. // dont try to land underground
  2301. terrainHeight += Appearance.AvatarHeight / 2;
  2302. pos.Z = Math.Max(terrainHeight, pos.Z);
  2303. // Fudge factor. It appears that if one clicks "go here" on a piece of ground, the go here request is
  2304. // always slightly higher than the actual terrain height.
  2305. // FIXME: This constrains NPC movements as well, so should be somewhere else.
  2306. if (pos.Z - terrainHeight < 0.2)
  2307. pos.Z = terrainHeight;
  2308. // m_log.DebugFormat(
  2309. // "[SCENE PRESENCE]: Avatar {0} set move to target {1} (terrain height {2}) in {3}",
  2310. // Name, pos, terrainHeight, m_scene.RegionInfo.RegionName);
  2311. if (noFly)
  2312. Flying = false;
  2313. else if (pos.Z > terrainHeight + Appearance.AvatarHeight / 2 || Flying)
  2314. Flying = true;
  2315. LandAtTarget = landAtTarget;
  2316. MovingToTarget = true;
  2317. MoveToPositionTarget = pos;
  2318. // Rotate presence around the z-axis to point in same direction as movement.
  2319. // Ignore z component of vector
  2320. Vector3 localVectorToTarget3D = pos - AbsolutePosition;
  2321. Vector3 localVectorToTarget2D = new Vector3((float)(localVectorToTarget3D.X), (float)(localVectorToTarget3D.Y), 0f);
  2322. // m_log.DebugFormat("[SCENE PRESENCE]: Local vector to target is {0}", localVectorToTarget2D);
  2323. // Calculate the yaw.
  2324. Vector3 angle = new Vector3(0, 0, (float)(Math.Atan2(localVectorToTarget2D.Y, localVectorToTarget2D.X)));
  2325. // m_log.DebugFormat("[SCENE PRESENCE]: Angle is {0}", angle);
  2326. Rotation = Quaternion.CreateFromEulers(angle);
  2327. // m_log.DebugFormat("[SCENE PRESENCE]: Body rot for {0} set to {1}", Name, Rotation);
  2328. Vector3 agent_control_v3 = new Vector3();
  2329. HandleMoveToTargetUpdate(1, ref agent_control_v3);
  2330. AddNewMovement(agent_control_v3);
  2331. }
  2332. /// <summary>
  2333. /// Reset the move to target.
  2334. /// </summary>
  2335. public void ResetMoveToTarget()
  2336. {
  2337. // m_log.DebugFormat("[SCENE PRESENCE]: Resetting move to target for {0}", Name);
  2338. MovingToTarget = false;
  2339. // MoveToPositionTarget = Vector3.Zero;
  2340. m_forceToApply = null; // cancel possible last action
  2341. // We need to reset the control flag as the ScenePresenceAnimator uses this to determine the correct
  2342. // resting animation (e.g. hover or stand). NPCs don't have a client that will quickly reset this flag.
  2343. // However, the line is here rather than in the NPC module since it also appears necessary to stop a
  2344. // viewer that uses "go here" from juddering on all subsequent avatar movements.
  2345. AgentControlFlags = (uint)AgentManager.ControlFlags.NONE;
  2346. }
  2347. /// <summary>
  2348. /// Perform the logic necessary to stand the avatar up. This method also executes
  2349. /// the stand animation.
  2350. /// </summary>
  2351. public void StandUp()
  2352. {
  2353. // m_log.DebugFormat("[SCENE PRESENCE]: StandUp() for {0}", Name);
  2354. bool satOnObject = IsSatOnObject;
  2355. SceneObjectPart part = ParentPart;
  2356. SitGround = false;
  2357. if (satOnObject)
  2358. {
  2359. PrevSitOffset = m_pos; // Save sit offset
  2360. UnRegisterSeatControls(part.ParentGroup.UUID);
  2361. TaskInventoryDictionary taskIDict = part.TaskInventory;
  2362. if (taskIDict != null)
  2363. {
  2364. lock (taskIDict)
  2365. {
  2366. foreach (UUID taskID in taskIDict.Keys)
  2367. {
  2368. UnRegisterControlEventsToScript(LocalId, taskID);
  2369. taskIDict[taskID].PermsMask &= ~(
  2370. 2048 | //PERMISSION_CONTROL_CAMERA
  2371. 4); // PERMISSION_TAKE_CONTROLS
  2372. }
  2373. }
  2374. }
  2375. // part.ParentGroup.DeleteAvatar(UUID);
  2376. Quaternion standRotation = part.ParentGroup.RootPart.RotationOffset;
  2377. Vector3 sitPartWorldPosition = part.ParentGroup.AbsolutePosition + m_pos * standRotation;
  2378. ControllingClient.SendClearFollowCamProperties(part.ParentUUID);
  2379. ParentID = 0;
  2380. ParentPart = null;
  2381. if (part.SitTargetAvatar == UUID)
  2382. standRotation = standRotation * part.SitTargetOrientation;
  2383. else
  2384. standRotation = standRotation * m_bodyRot;
  2385. m_bodyRot = standRotation;
  2386. Quaternion standRotationZ = new Quaternion(0,0,standRotation.Z,standRotation.W);
  2387. float t = standRotationZ.W * standRotationZ.W + standRotationZ.Z * standRotationZ.Z;
  2388. if (t > 0)
  2389. {
  2390. t = 1.0f / (float)Math.Sqrt(t);
  2391. standRotationZ.W *= t;
  2392. standRotationZ.Z *= t;
  2393. }
  2394. else
  2395. {
  2396. standRotationZ.W = 1.0f;
  2397. standRotationZ.Z = 0f;
  2398. }
  2399. Vector3 adjustmentForSitPose = new Vector3(0.75f, 0, m_sitAvatarHeight + .3f) * standRotationZ;
  2400. Vector3 standPos = sitPartWorldPosition + adjustmentForSitPose;
  2401. m_pos = standPos;
  2402. }
  2403. // We need to wait until we have calculated proper stand positions before sitting up the physical
  2404. // avatar to avoid race conditions.
  2405. if (PhysicsActor == null)
  2406. AddToPhysicalScene(false);
  2407. if (satOnObject)
  2408. {
  2409. m_requestedSitTargetID = 0;
  2410. part.RemoveSittingAvatar(this);
  2411. part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK);
  2412. SendAvatarDataToAllAgents();
  2413. }
  2414. // reset to default sitAnimation
  2415. sitAnimation = "SIT";
  2416. // Animator.TrySetMovementAnimation("STAND");
  2417. Animator.SetMovementAnimations("STAND");
  2418. TriggerScenePresenceUpdated();
  2419. }
  2420. private SceneObjectPart FindNextAvailableSitTarget(UUID targetID)
  2421. {
  2422. SceneObjectPart targetPart = m_scene.GetSceneObjectPart(targetID);
  2423. if (targetPart == null)
  2424. return null;
  2425. // If the primitive the player clicked on has a sit target and that sit target is not full, that sit target is used.
  2426. // If the primitive the player clicked on has no sit target, and one or more other linked objects have sit targets that are not full, the sit target of the object with the lowest link number will be used.
  2427. // Get our own copy of the part array, and sort into the order we want to test
  2428. SceneObjectPart[] partArray = targetPart.ParentGroup.Parts;
  2429. Array.Sort(partArray, delegate(SceneObjectPart p1, SceneObjectPart p2)
  2430. {
  2431. // we want the originally selected part first, then the rest in link order -- so make the selected part link num (-1)
  2432. int linkNum1 = p1==targetPart ? -1 : p1.LinkNum;
  2433. int linkNum2 = p2==targetPart ? -1 : p2.LinkNum;
  2434. return linkNum1 - linkNum2;
  2435. }
  2436. );
  2437. //look for prims with explicit sit targets that are available
  2438. foreach (SceneObjectPart part in partArray)
  2439. {
  2440. if (part.IsSitTargetSet && part.SitTargetAvatar == UUID.Zero)
  2441. {
  2442. //switch the target to this prim
  2443. return part;
  2444. }
  2445. }
  2446. // no explicit sit target found - use original target
  2447. return targetPart;
  2448. }
  2449. private void SendSitResponse(UUID targetID, Vector3 offset, Quaternion sitOrientation)
  2450. {
  2451. Vector3 cameraEyeOffset = Vector3.Zero;
  2452. Vector3 cameraAtOffset = Vector3.Zero;
  2453. bool forceMouselook = false;
  2454. SceneObjectPart part = FindNextAvailableSitTarget(targetID);
  2455. if (part == null)
  2456. return;
  2457. if (PhysicsActor != null)
  2458. m_sitAvatarHeight = PhysicsActor.Size.Z * 0.5f;
  2459. bool canSit = false;
  2460. if (part.IsSitTargetSet && part.SitTargetAvatar == UUID.Zero)
  2461. {
  2462. offset = part.SitTargetPosition;
  2463. sitOrientation = part.SitTargetOrientation;
  2464. canSit = true;
  2465. }
  2466. else
  2467. {
  2468. if (PhysicsSit(part,offset)) // physics engine
  2469. return;
  2470. Vector3 pos = part.AbsolutePosition + offset;
  2471. if (Util.GetDistanceTo(AbsolutePosition, pos) <= 10)
  2472. {
  2473. AbsolutePosition = pos + new Vector3(0.0f, 0.0f, m_sitAvatarHeight);
  2474. canSit = true;
  2475. }
  2476. }
  2477. if (canSit)
  2478. {
  2479. if (PhysicsActor != null)
  2480. {
  2481. // We can remove the physicsActor until they stand up.
  2482. RemoveFromPhysicalScene();
  2483. }
  2484. if (MovingToTarget)
  2485. ResetMoveToTarget();
  2486. Velocity = Vector3.Zero;
  2487. part.AddSittingAvatar(this);
  2488. cameraAtOffset = part.GetCameraAtOffset();
  2489. cameraEyeOffset = part.GetCameraEyeOffset();
  2490. forceMouselook = part.GetForceMouselook();
  2491. if (!part.IsRoot)
  2492. {
  2493. sitOrientation = part.RotationOffset * sitOrientation;
  2494. offset = offset * part.RotationOffset;
  2495. offset += part.OffsetPosition;
  2496. if (CameraAtAxis == Vector3.Zero && cameraEyeOffset == Vector3.Zero)
  2497. {
  2498. CameraAtAxis = part.ParentGroup.RootPart.GetCameraAtOffset();
  2499. cameraEyeOffset = part.ParentGroup.RootPart.GetCameraEyeOffset();
  2500. }
  2501. else
  2502. {
  2503. cameraAtOffset = cameraAtOffset * part.RotationOffset;
  2504. cameraAtOffset += part.OffsetPosition;
  2505. cameraEyeOffset = cameraEyeOffset * part.RotationOffset;
  2506. cameraEyeOffset += part.OffsetPosition;
  2507. }
  2508. }
  2509. ControllingClient.SendSitResponse(
  2510. part.ParentGroup.UUID, offset, sitOrientation, false, cameraAtOffset, cameraEyeOffset, forceMouselook);
  2511. m_requestedSitTargetUUID = part.UUID;
  2512. HandleAgentSit(ControllingClient, UUID);
  2513. // Moved here to avoid a race with default sit anim
  2514. // The script event needs to be raised after the default sit anim is set.
  2515. part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK);
  2516. }
  2517. }
  2518. public void HandleAgentRequestSit(IClientAPI remoteClient, UUID agentID, UUID targetID, Vector3 offset)
  2519. {
  2520. if (IsChildAgent)
  2521. return;
  2522. if (ParentID != 0)
  2523. {
  2524. if (ParentPart.UUID == targetID)
  2525. return; // already sitting here, ignore
  2526. StandUp();
  2527. }
  2528. SceneObjectPart part = FindNextAvailableSitTarget(targetID);
  2529. if (part != null)
  2530. {
  2531. m_requestedSitTargetID = part.LocalId;
  2532. m_requestedSitTargetUUID = part.UUID;
  2533. }
  2534. else
  2535. {
  2536. m_log.Warn("Sit requested on unknown object: " + targetID.ToString());
  2537. }
  2538. SendSitResponse(targetID, offset, Quaternion.Identity);
  2539. }
  2540. // returns false if does not suport so older sit can be tried
  2541. public bool PhysicsSit(SceneObjectPart part, Vector3 offset)
  2542. {
  2543. if (part == null || part.ParentGroup.IsAttachment)
  2544. return true;
  2545. if ( m_scene.PhysicsScene == null)
  2546. return false;
  2547. if (part.PhysActor == null)
  2548. {
  2549. // none physcis shape
  2550. if (part.PhysicsShapeType == (byte)PhysicsShapeType.None)
  2551. ControllingClient.SendAlertMessage(" There is no suitable surface to sit on, try another spot.");
  2552. else
  2553. { // non physical phantom TODO
  2554. ControllingClient.SendAlertMessage(" There is no suitable surface to sit on, try another spot.");
  2555. return false;
  2556. }
  2557. return true;
  2558. }
  2559. if (m_scene.PhysicsScene.SitAvatar(part.PhysActor, AbsolutePosition, CameraPosition, offset, new Vector3(0.35f, 0, 0.65f), PhysicsSitResponse) != 0)
  2560. {
  2561. return true;
  2562. }
  2563. return false;
  2564. }
  2565. private bool CanEnterLandPosition(Vector3 testPos)
  2566. {
  2567. ILandObject land = m_scene.LandChannel.GetLandObject(testPos.X, testPos.Y);
  2568. if (land == null || land.LandData.Name == "NO_LAND")
  2569. return true;
  2570. return land.CanBeOnThisLand(UUID,testPos.Z);
  2571. }
  2572. // status
  2573. // < 0 ignore
  2574. // 0 bad sit spot
  2575. public void PhysicsSitResponse(int status, uint partID, Vector3 offset, Quaternion Orientation)
  2576. {
  2577. if (status < 0)
  2578. return;
  2579. if (status == 0)
  2580. {
  2581. ControllingClient.SendAlertMessage(" There is no suitable surface to sit on, try another spot.");
  2582. return;
  2583. }
  2584. SceneObjectPart part = m_scene.GetSceneObjectPart(partID);
  2585. if (part == null)
  2586. return;
  2587. Vector3 targetPos = part.GetWorldPosition() + offset * part.GetWorldRotation();
  2588. if(!CanEnterLandPosition(targetPos))
  2589. {
  2590. ControllingClient.SendAlertMessage(" Sit position on restricted land, try another spot");
  2591. return;
  2592. }
  2593. RemoveFromPhysicalScene();
  2594. if (MovingToTarget)
  2595. ResetMoveToTarget();
  2596. Velocity = Vector3.Zero;
  2597. m_AngularVelocity = Vector3.Zero;
  2598. Vector3 cameraAtOffset = part.GetCameraAtOffset();
  2599. Vector3 cameraEyeOffset = part.GetCameraEyeOffset();
  2600. bool forceMouselook = part.GetForceMouselook();
  2601. m_bodyRot = Orientation;
  2602. if (!part.IsRoot)
  2603. {
  2604. Orientation = part.RotationOffset * Orientation;
  2605. offset = offset * part.RotationOffset;
  2606. offset += part.OffsetPosition;
  2607. if (CameraAtAxis == Vector3.Zero && cameraEyeOffset == Vector3.Zero)
  2608. {
  2609. CameraAtAxis = part.ParentGroup.RootPart.GetCameraAtOffset();
  2610. cameraEyeOffset = part.ParentGroup.RootPart.GetCameraEyeOffset();
  2611. }
  2612. else
  2613. {
  2614. cameraAtOffset = cameraAtOffset * part.RotationOffset;
  2615. cameraAtOffset += part.OffsetPosition;
  2616. cameraEyeOffset = cameraEyeOffset * part.RotationOffset;
  2617. cameraEyeOffset += part.OffsetPosition;
  2618. }
  2619. }
  2620. m_pos = offset;
  2621. ControllingClient.SendSitResponse(
  2622. part.ParentGroup.UUID, offset, Orientation, true, cameraAtOffset, cameraEyeOffset, forceMouselook);
  2623. m_requestedSitTargetID = 0;
  2624. part.AddSittingAvatar(this);
  2625. ParentPart = part;
  2626. ParentID = part.LocalId;
  2627. SendAvatarDataToAllAgents();
  2628. if (status == 3)
  2629. sitAnimation = "SIT_GROUND";
  2630. else
  2631. sitAnimation = "SIT";
  2632. Animator.SetMovementAnimations("SIT");
  2633. part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK);
  2634. }
  2635. public void HandleAgentSit(IClientAPI remoteClient, UUID agentID)
  2636. {
  2637. if (IsChildAgent)
  2638. return;
  2639. SceneObjectPart part = m_scene.GetSceneObjectPart(m_requestedSitTargetID);
  2640. if (part != null)
  2641. {
  2642. if (part.ParentGroup.IsAttachment)
  2643. {
  2644. m_log.WarnFormat(
  2645. "[SCENE PRESENCE]: Avatar {0} tried to sit on part {1} from object {2} in {3} but this is an attachment for avatar id {4}",
  2646. Name, part.Name, part.ParentGroup.Name, Scene.Name, part.ParentGroup.AttachedAvatar);
  2647. return;
  2648. }
  2649. if (part.SitTargetAvatar == UUID)
  2650. {
  2651. Vector3 sitTargetPos = part.SitTargetPosition;
  2652. Quaternion sitTargetOrient = part.SitTargetOrientation;
  2653. // m_log.DebugFormat(
  2654. // "[SCENE PRESENCE]: Sitting {0} at sit target {1}, {2} on {3} {4}",
  2655. // Name, sitTargetPos, sitTargetOrient, part.Name, part.LocalId);
  2656. //Quaternion vq = new Quaternion(sitTargetPos.X, sitTargetPos.Y+0.2f, sitTargetPos.Z+0.2f, 0);
  2657. //Quaternion nq = new Quaternion(-sitTargetOrient.X, -sitTargetOrient.Y, -sitTargetOrient.Z, sitTargetOrient.w);
  2658. //Quaternion result = (sitTargetOrient * vq) * nq;
  2659. double x, y, z, m;
  2660. Quaternion r = sitTargetOrient;
  2661. m = r.X * r.X + r.Y * r.Y + r.Z * r.Z + r.W * r.W;
  2662. if (Math.Abs(1.0 - m) > 0.000001)
  2663. {
  2664. m = 1.0 / Math.Sqrt(m);
  2665. r.X *= (float)m;
  2666. r.Y *= (float)m;
  2667. r.Z *= (float)m;
  2668. r.W *= (float)m;
  2669. }
  2670. x = 2 * (r.X * r.Z + r.Y * r.W);
  2671. y = 2 * (-r.X * r.W + r.Y * r.Z);
  2672. z = -r.X * r.X - r.Y * r.Y + r.Z * r.Z + r.W * r.W;
  2673. Vector3 up = new Vector3((float)x, (float)y, (float)z);
  2674. Vector3 sitOffset = up * Appearance.AvatarHeight * 0.02638f;
  2675. Vector3 newPos = sitTargetPos + sitOffset + SIT_TARGET_ADJUSTMENT;
  2676. Quaternion newRot;
  2677. if (part.IsRoot)
  2678. {
  2679. newRot = sitTargetOrient;
  2680. }
  2681. else
  2682. {
  2683. newPos = newPos * part.RotationOffset;
  2684. newRot = part.RotationOffset * sitTargetOrient;
  2685. }
  2686. newPos += part.OffsetPosition;
  2687. m_pos = newPos;
  2688. Rotation = newRot;
  2689. // ParentPosition = part.AbsolutePosition;
  2690. }
  2691. else
  2692. {
  2693. // An viewer expects to specify sit positions as offsets to the root prim, even if a child prim is
  2694. // being sat upon.
  2695. m_pos -= part.GroupPosition;
  2696. // ParentPosition = part.AbsolutePosition;
  2697. // m_log.DebugFormat(
  2698. // "[SCENE PRESENCE]: Sitting {0} at position {1} ({2} + {3}) on part {4} {5} without sit target",
  2699. // Name, part.AbsolutePosition, m_pos, ParentPosition, part.Name, part.LocalId);
  2700. }
  2701. part.AddSittingAvatar(this);
  2702. ParentPart = m_scene.GetSceneObjectPart(m_requestedSitTargetID);
  2703. ParentID = m_requestedSitTargetID;
  2704. m_AngularVelocity = Vector3.Zero;
  2705. Velocity = Vector3.Zero;
  2706. RemoveFromPhysicalScene();
  2707. SendAvatarDataToAllAgents();
  2708. sitAnimation = "SIT";
  2709. if (!String.IsNullOrEmpty(part.SitAnimation))
  2710. {
  2711. sitAnimation = part.SitAnimation;
  2712. }
  2713. // Animator.TrySetMovementAnimation(sitAnimation);
  2714. Animator.SetMovementAnimations("SIT");
  2715. TriggerScenePresenceUpdated();
  2716. }
  2717. }
  2718. public void HandleAgentSitOnGround()
  2719. {
  2720. if (IsChildAgent)
  2721. return;
  2722. // m_updateCount = 0; // Kill animation update burst so that the SIT_G.. will stick..
  2723. m_AngularVelocity = Vector3.Zero;
  2724. sitAnimation = "SIT_GROUND_CONSTRAINED";
  2725. // Animator.TrySetMovementAnimation("SIT_GROUND_CONSTRAINED");
  2726. // TriggerScenePresenceUpdated();
  2727. SitGround = true;
  2728. RemoveFromPhysicalScene();
  2729. Animator.SetMovementAnimations("SITGROUND");
  2730. TriggerScenePresenceUpdated();
  2731. }
  2732. /// <summary>
  2733. /// Event handler for the 'Always run' setting on the client
  2734. /// Tells the physics plugin to increase speed of movement.
  2735. /// </summary>
  2736. public void HandleSetAlwaysRun(IClientAPI remoteClient, bool pSetAlwaysRun)
  2737. {
  2738. SetAlwaysRun = pSetAlwaysRun;
  2739. }
  2740. public void HandleStartAnim(IClientAPI remoteClient, UUID animID)
  2741. {
  2742. Animator.AddAnimation(animID, UUID.Zero);
  2743. TriggerScenePresenceUpdated();
  2744. }
  2745. public void HandleStopAnim(IClientAPI remoteClient, UUID animID)
  2746. {
  2747. Animator.RemoveAnimation(animID, false);
  2748. TriggerScenePresenceUpdated();
  2749. }
  2750. public void avnHandleChangeAnim(UUID animID, bool addRemove,bool sendPack)
  2751. {
  2752. Animator.avnChangeAnim(animID, addRemove, sendPack);
  2753. }
  2754. /// <summary>
  2755. /// Rotate the avatar to the given rotation and apply a movement in the given relative vector
  2756. /// </summary>
  2757. /// <param name="vec">The vector in which to move. This is relative to the rotation argument</param>
  2758. /// <param name="thisAddSpeedModifier">
  2759. /// Optional additional speed modifier for this particular add. Default is 1</param>
  2760. public void AddNewMovement(Vector3 vec, float thisAddSpeedModifier = 1, bool breaking = false)
  2761. {
  2762. // m_log.DebugFormat(
  2763. // "[SCENE PRESENCE]: Adding new movement {0} with rotation {1}, thisAddSpeedModifier {2} for {3}",
  2764. // vec, Rotation, thisAddSpeedModifier, Name);
  2765. // rotate from avatar coord space to world
  2766. // for now all controls assume this is only a rotation around Z
  2767. // if not all checks below need to be done before this rotation
  2768. Vector3 direc = vec * Rotation;
  2769. direc.Normalize();
  2770. // mouse look situation ?
  2771. if ((vec.Z == 0f) && !Flying)
  2772. direc.Z = 0f; // Prevent camera WASD up.
  2773. // odd rescalings
  2774. direc *= 0.03f * 128f * SpeedModifier * thisAddSpeedModifier;
  2775. // m_log.DebugFormat("[SCENE PRESENCE]: Force to apply before modification was {0} for {1}", direc, Name);
  2776. if (Animator.currentControlState == ScenePresenceAnimator.motionControlStates.falling)
  2777. {
  2778. if (breaking)
  2779. direc.Z = -9999f; //hack to tell physics to stop on Z
  2780. else
  2781. direc = Vector3.Zero;
  2782. }
  2783. else if (Flying)
  2784. {
  2785. if (IsColliding && direc.Z < 0)
  2786. // landing situation, prevent avatar moving or it may fail to land
  2787. // animator will handle this condition and do the land
  2788. direc = Vector3.Zero;
  2789. else
  2790. direc *= 4.0f;
  2791. }
  2792. else if (IsColliding)
  2793. {
  2794. if (direc.Z > 2.0f) // reinforce jumps
  2795. {
  2796. direc.Z *= 2.6f;
  2797. }
  2798. else if (direc.Z < 0) // on a surface moving down (pg down) only changes animation
  2799. direc.Z = 0;
  2800. }
  2801. // m_log.DebugFormat("[SCENE PRESENCE]: Setting force to apply to {0} for {1}", direc, Name);
  2802. m_forceToApply = direc;
  2803. Animator.UpdateMovementAnimations();
  2804. }
  2805. #endregion
  2806. #region Overridden Methods
  2807. public override void Update()
  2808. {
  2809. const float ROTATION_TOLERANCE = 0.01f;
  2810. const float VELOCITY_TOLERANCE = 0.001f;
  2811. const float POSITION_TOLERANCE = 0.05f;
  2812. if (IsChildAgent == false)
  2813. {
  2814. CheckForBorderCrossing();
  2815. if (IsInTransit)
  2816. return;
  2817. // NOTE: Velocity is not the same as m_velocity. Velocity will attempt to
  2818. // grab the latest PhysicsActor velocity, whereas m_velocity is often
  2819. // storing a requested force instead of an actual traveling velocity
  2820. if (Appearance.AvatarSize != m_lastSize && !IsLoggingIn)
  2821. SendAvatarDataToAllAgents();
  2822. if (!Rotation.ApproxEquals(m_lastRotation, ROTATION_TOLERANCE) ||
  2823. !Velocity.ApproxEquals(m_lastVelocity, VELOCITY_TOLERANCE) ||
  2824. !m_pos.ApproxEquals(m_lastPosition, POSITION_TOLERANCE))
  2825. {
  2826. SendTerseUpdateToAllClients();
  2827. // Update the "last" values
  2828. m_lastPosition = m_pos;
  2829. m_lastRotation = Rotation;
  2830. m_lastVelocity = Velocity;
  2831. }
  2832. CheckForSignificantMovement(); // sends update to the modules.
  2833. }
  2834. }
  2835. #endregion
  2836. #region Update Client(s)
  2837. public void SendUpdateToAgent(ScenePresence p)
  2838. {
  2839. IClientAPI remoteClient = p.ControllingClient;
  2840. if (remoteClient.IsActive)
  2841. {
  2842. //m_log.DebugFormat("[SCENE PRESENCE]: " + Name + " sending TerseUpdate to " + remoteClient.Name + " : Pos={0} Rot={1} Vel={2}", m_pos, Rotation, m_velocity);
  2843. remoteClient.SendEntityUpdate(this, PrimUpdateFlags.FullUpdate);
  2844. m_scene.StatsReporter.AddAgentUpdates(1);
  2845. }
  2846. }
  2847. public void SendFullUpdateToClient(IClientAPI remoteClient)
  2848. {
  2849. if (remoteClient.IsActive)
  2850. {
  2851. //m_log.DebugFormat("[SCENE PRESENCE]: " + Name + " sending TerseUpdate to " + remoteClient.Name + " : Pos={0} Rot={1} Vel={2}", m_pos, Rotation, m_velocity);
  2852. remoteClient.SendEntityUpdate(this, PrimUpdateFlags.FullUpdate);
  2853. m_scene.StatsReporter.AddAgentUpdates(1);
  2854. }
  2855. }
  2856. // this is diferente from SendTerseUpdateToClient
  2857. // this sends bypassing entities updates
  2858. public void SendAgentTerseUpdate(ISceneEntity p)
  2859. {
  2860. ControllingClient.SendAgentTerseUpdate(p);
  2861. }
  2862. /// <summary>
  2863. /// Sends a location update to the client connected to this scenePresence
  2864. /// via entity updates
  2865. /// </summary>
  2866. /// <param name="remoteClient"></param>
  2867. public void SendTerseUpdateToClient(IClientAPI remoteClient)
  2868. {
  2869. // If the client is inactive, it's getting its updates from another
  2870. // server.
  2871. if (remoteClient.IsActive)
  2872. {
  2873. //m_log.DebugFormat("[SCENE PRESENCE]: " + Name + " sending TerseUpdate to " + remoteClient.Name + " : Pos={0} Rot={1} Vel={2}", m_pos, Rotation, m_velocity);
  2874. remoteClient.SendEntityUpdate(
  2875. this,
  2876. PrimUpdateFlags.Position | PrimUpdateFlags.Rotation | PrimUpdateFlags.Velocity
  2877. | PrimUpdateFlags.Acceleration | PrimUpdateFlags.AngularVelocity);
  2878. m_scene.StatsReporter.AddAgentUpdates(1);
  2879. }
  2880. }
  2881. public void SendTerseUpdateToAgent(ScenePresence p)
  2882. {
  2883. IClientAPI remoteClient = p.ControllingClient;
  2884. if (!remoteClient.IsActive)
  2885. return;
  2886. if (ParcelHideThisAvatar && p.currentParcelUUID != currentParcelUUID && p.GodLevel < 200)
  2887. return;
  2888. //m_log.DebugFormat("[SCENE PRESENCE]: " + Name + " sending TerseUpdate to " + remoteClient.Name + " : Pos={0} Rot={1} Vel={2}", m_pos, Rotation, m_velocity);
  2889. remoteClient.SendEntityUpdate(
  2890. this,
  2891. PrimUpdateFlags.Position | PrimUpdateFlags.Rotation | PrimUpdateFlags.Velocity
  2892. | PrimUpdateFlags.Acceleration | PrimUpdateFlags.AngularVelocity);
  2893. m_scene.StatsReporter.AddAgentUpdates(1);
  2894. }
  2895. public void SendTerseUpdateToAgentNF(ScenePresence p)
  2896. {
  2897. IClientAPI remoteClient = p.ControllingClient;
  2898. if (remoteClient.IsActive)
  2899. {
  2900. //m_log.DebugFormat("[SCENE PRESENCE]: " + Name + " sending TerseUpdate to " + remoteClient.Name + " : Pos={0} Rot={1} Vel={2}", m_pos, Rotation, m_velocity);
  2901. remoteClient.SendEntityUpdate(this,
  2902. PrimUpdateFlags.Position | PrimUpdateFlags.Rotation | PrimUpdateFlags.Velocity
  2903. | PrimUpdateFlags.Acceleration | PrimUpdateFlags.AngularVelocity);
  2904. m_scene.StatsReporter.AddAgentUpdates(1);
  2905. }
  2906. }
  2907. // vars to support reduced update frequency when velocity is unchanged
  2908. private Vector3 lastVelocitySentToAllClients = Vector3.Zero;
  2909. private Vector3 lastPositionSentToAllClients = Vector3.Zero;
  2910. private int lastTerseUpdateToAllClientsTick = Util.EnvironmentTickCount();
  2911. /// <summary>
  2912. /// Send a location/velocity/accelleration update to all agents in scene
  2913. /// </summary>
  2914. public void SendTerseUpdateToAllClients()
  2915. {
  2916. int currentTick = Util.EnvironmentTickCount();
  2917. // Decrease update frequency when avatar is moving but velocity is
  2918. // not changing.
  2919. // If there is a mismatch between distance travelled and expected
  2920. // distance based on last velocity sent and velocity hasnt changed,
  2921. // then send a new terse update
  2922. float timeSinceLastUpdate = (currentTick - lastTerseUpdateToAllClientsTick) * 0.001f;
  2923. Vector3 expectedPosition = lastPositionSentToAllClients + lastVelocitySentToAllClients * timeSinceLastUpdate;
  2924. float distanceError = Vector3.Distance(OffsetPosition, expectedPosition);
  2925. float speed = Velocity.Length();
  2926. float velocityDiff = Vector3.Distance(lastVelocitySentToAllClients, Velocity);
  2927. // assuming 5 ms. worst case precision for timer, use 2x that
  2928. // for distance error threshold
  2929. float distanceErrorThreshold = speed * 0.01f;
  2930. if (speed < 0.01f // allow rotation updates if avatar position is unchanged
  2931. || Math.Abs(distanceError) > distanceErrorThreshold
  2932. || velocityDiff > 0.01f) // did velocity change from last update?
  2933. {
  2934. lastVelocitySentToAllClients = Velocity;
  2935. lastTerseUpdateToAllClientsTick = currentTick;
  2936. lastPositionSentToAllClients = OffsetPosition;
  2937. // Console.WriteLine("Scheduled update for {0} in {1}", Name, Scene.Name);
  2938. // m_scene.ForEachClient(SendTerseUpdateToClient);
  2939. m_scene.ForEachScenePresence(SendTerseUpdateToAgent);
  2940. }
  2941. TriggerScenePresenceUpdated();
  2942. }
  2943. public void SendCoarseLocations(List<Vector3> coarseLocations, List<UUID> avatarUUIDs)
  2944. {
  2945. SendCoarseLocationsMethod d = m_sendCoarseLocationsMethod;
  2946. if (d != null)
  2947. {
  2948. d.Invoke(m_scene.RegionInfo.originRegionID, this, coarseLocations, avatarUUIDs);
  2949. }
  2950. }
  2951. public void SetSendCoarseLocationMethod(SendCoarseLocationsMethod d)
  2952. {
  2953. if (d != null)
  2954. m_sendCoarseLocationsMethod = d;
  2955. }
  2956. public void SendCoarseLocationsDefault(UUID sceneId, ScenePresence p, List<Vector3> coarseLocations, List<UUID> avatarUUIDs)
  2957. {
  2958. ControllingClient.SendCoarseLocationUpdate(avatarUUIDs, coarseLocations);
  2959. }
  2960. public void SendInitialDataToMe()
  2961. {
  2962. // Send all scene object to the new client
  2963. Util.FireAndForget(delegate
  2964. {
  2965. // we created a new ScenePresence (a new child agent) in a fresh region.
  2966. // Request info about all the (root) agents in this region
  2967. // Note: This won't send data *to* other clients in that region (children don't send)
  2968. if (m_teleportFlags <= 0)
  2969. {
  2970. Scene.SendLayerData(ControllingClient);
  2971. ILandChannel landch = m_scene.LandChannel;
  2972. if (landch != null)
  2973. {
  2974. landch.sendClientInitialLandInfo(ControllingClient);
  2975. }
  2976. }
  2977. SendOtherAgentsAvatarFullToMe();
  2978. EntityBase[] entities = Scene.Entities.GetEntities();
  2979. foreach (EntityBase e in entities)
  2980. {
  2981. if (e != null && e is SceneObjectGroup && !((SceneObjectGroup)e).IsAttachment)
  2982. ((SceneObjectGroup)e).SendFullUpdateToClient(ControllingClient);
  2983. }
  2984. });
  2985. }
  2986. /// <summary>
  2987. /// Do everything required once a client completes its movement into a region and becomes
  2988. /// a root agent.
  2989. /// </summary>
  2990. ///
  2991. /* only called from on place, do done inline there
  2992. private void ValidateAndSendAppearanceAndAgentData()
  2993. {
  2994. //m_log.DebugFormat("[SCENE PRESENCE] SendInitialData: {0} ({1})", Name, UUID);
  2995. // Moved this into CompleteMovement to ensure that Appearance is initialized before
  2996. // the inventory arrives
  2997. // m_scene.GetAvatarAppearance(ControllingClient, out Appearance);
  2998. bool cachedappearance = false;
  2999. // We have an appearance but we may not have the baked textures. Check the asset cache
  3000. // to see if all the baked textures are already here.
  3001. if (m_scene.AvatarFactory != null)
  3002. cachedappearance = m_scene.AvatarFactory.ValidateBakedTextureCache(this);
  3003. // If we aren't using a cached appearance, then clear out the baked textures
  3004. if (!cachedappearance)
  3005. {
  3006. if (m_scene.AvatarFactory != null)
  3007. m_scene.AvatarFactory.QueueAppearanceSave(UUID);
  3008. }
  3009. // send avatar object to all viewers so they cross it into region
  3010. bool newhide = m_currentParcelHide;
  3011. m_currentParcelHide = false;
  3012. SendAvatarDataToAllAgents();
  3013. // now hide
  3014. if (newhide)
  3015. {
  3016. ParcelLoginCheck(m_currentParcelUUID);
  3017. m_currentParcelHide = true;
  3018. }
  3019. SendAppearanceToAgent(this);
  3020. m_inTransit = false;
  3021. SendAppearanceToAllOtherAgents();
  3022. if(Animator!= null)
  3023. Animator.SendAnimPack();
  3024. }
  3025. */
  3026. /// <summary>
  3027. /// Send avatar full data appearance and animations for all other root agents to this agent, this agent
  3028. /// can be either a child or root
  3029. /// </summary>
  3030. public void SendOtherAgentsAvatarFullToMe()
  3031. {
  3032. int count = 0;
  3033. m_scene.ForEachRootScenePresence(delegate(ScenePresence p)
  3034. {
  3035. // only send information about other root agents
  3036. if (p.UUID == UUID)
  3037. return;
  3038. // get the avatar, then a kill if can't see it
  3039. p.SendInitialAvatarDataToAgent(this);
  3040. if (p.ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && GodLevel < 200)
  3041. return;
  3042. p.SendAppearanceToAgentNF(this);
  3043. p.SendAnimPackToAgentNF(this);
  3044. p.SendAttachmentsToAgentNF(this);
  3045. count++;
  3046. });
  3047. m_scene.StatsReporter.AddAgentUpdates(count);
  3048. }
  3049. /// <summary>
  3050. /// Send this agent's avatar data to all other root and child agents in the scene
  3051. /// This agent must be root. This avatar will receive its own update.
  3052. /// </summary>
  3053. public void SendAvatarDataToAllAgents()
  3054. {
  3055. //m_log.DebugFormat("[SCENE PRESENCE] SendAvatarDataToAllAgents: {0} ({1})", Name, UUID);
  3056. // only send update from root agents to other clients; children are only "listening posts"
  3057. if (IsChildAgent)
  3058. {
  3059. m_log.WarnFormat(
  3060. "[SCENE PRESENCE]: Attempt to send avatar data from a child agent for {0} in {1}",
  3061. Name, Scene.RegionInfo.RegionName);
  3062. return;
  3063. }
  3064. m_lastSize = Appearance.AvatarSize;
  3065. int count = 0;
  3066. m_scene.ForEachScenePresence(delegate(ScenePresence scenePresence)
  3067. {
  3068. SendAvatarDataToAgent(scenePresence);
  3069. count++;
  3070. });
  3071. m_scene.StatsReporter.AddAgentUpdates(count);
  3072. }
  3073. // sends avatar object to all clients so they cross it into region
  3074. // then sends kills to hide
  3075. public void SendInitialAvatarDataToAllAgents(List<ScenePresence> presences)
  3076. {
  3077. m_lastSize = Appearance.AvatarSize;
  3078. int count = 0;
  3079. foreach (ScenePresence p in presences)
  3080. {
  3081. p.ControllingClient.SendAvatarDataImmediate(this);
  3082. if (p != this && ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && p.GodLevel < 200)
  3083. // either just kill the object
  3084. // p.ControllingClient.SendKillObject(new List<uint> {LocalId});
  3085. // or also attachments viewer may still know about
  3086. SendKillTo(p);
  3087. count++;
  3088. }
  3089. m_scene.StatsReporter.AddAgentUpdates(count);
  3090. }
  3091. public void SendInitialAvatarDataToAgent(ScenePresence p)
  3092. {
  3093. p.ControllingClient.SendAvatarDataImmediate(this);
  3094. if (p != this && ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && p.GodLevel < 200)
  3095. // either just kill the object
  3096. // p.ControllingClient.SendKillObject(new List<uint> {LocalId});
  3097. // or also attachments viewer may still know about
  3098. SendKillTo(p);
  3099. }
  3100. /// <summary>
  3101. /// Send avatar data to an agent.
  3102. /// </summary>
  3103. /// <param name="avatar"></param>
  3104. public void SendAvatarDataToAgent(ScenePresence avatar)
  3105. {
  3106. //m_log.DebugFormat("[SCENE PRESENCE] SendAvatarDataToAgent from {0} ({1}) to {2} ({3})", Name, UUID, avatar.Name, avatar.UUID);
  3107. if (ParcelHideThisAvatar && currentParcelUUID != avatar.currentParcelUUID && avatar.GodLevel < 200)
  3108. return;
  3109. avatar.ControllingClient.SendAvatarDataImmediate(this);
  3110. }
  3111. public void SendAvatarDataToAgentNF(ScenePresence avatar)
  3112. {
  3113. avatar.ControllingClient.SendAvatarDataImmediate(this);
  3114. }
  3115. /// <summary>
  3116. /// Send this agent's appearance to all other root and child agents in the scene
  3117. /// This agent must be root.
  3118. /// </summary>
  3119. public void SendAppearanceToAllOtherAgents()
  3120. {
  3121. // m_log.DebugFormat("[SCENE PRESENCE] SendAppearanceToAllOtherAgents: {0} {1}", Name, UUID);
  3122. // only send update from root agents to other clients; children are only "listening posts"
  3123. if (IsChildAgent)
  3124. {
  3125. m_log.WarnFormat(
  3126. "[SCENE PRESENCE]: Attempt to send avatar data from a child agent for {0} in {1}",
  3127. Name, Scene.RegionInfo.RegionName);
  3128. return;
  3129. }
  3130. int count = 0;
  3131. m_scene.ForEachScenePresence(delegate(ScenePresence scenePresence)
  3132. {
  3133. // only send information to other root agents
  3134. if (scenePresence.UUID == UUID)
  3135. return;
  3136. SendAppearanceToAgent(scenePresence);
  3137. count++;
  3138. });
  3139. m_scene.StatsReporter.AddAgentUpdates(count);
  3140. }
  3141. public void SendAppearanceToAgent(ScenePresence avatar)
  3142. {
  3143. // m_log.DebugFormat(
  3144. // "[SCENE PRESENCE]: Sending appearance data from {0} {1} to {2} {3}", Name, m_uuid, avatar.Name, avatar.UUID);
  3145. if (ParcelHideThisAvatar && currentParcelUUID != avatar.currentParcelUUID && avatar.GodLevel < 200)
  3146. return;
  3147. SendAppearanceToAgentNF(avatar);
  3148. }
  3149. public void SendAppearanceToAgentNF(ScenePresence avatar)
  3150. {
  3151. avatar.ControllingClient.SendAppearance(
  3152. UUID, Appearance.VisualParams, Appearance.Texture.GetBytes());
  3153. }
  3154. public void SendAnimPackToAgent(ScenePresence p)
  3155. {
  3156. if (IsChildAgent || Animator == null)
  3157. return;
  3158. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && p.GodLevel < 200)
  3159. return;
  3160. Animator.SendAnimPackToClient(p.ControllingClient);
  3161. }
  3162. public void SendAnimPackToAgent(ScenePresence p, UUID[] animations, int[] seqs, UUID[] objectIDs)
  3163. {
  3164. if (IsChildAgent)
  3165. return;
  3166. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && p.GodLevel < 200)
  3167. return;
  3168. p.ControllingClient.SendAnimations(animations, seqs, ControllingClient.AgentId, objectIDs);
  3169. }
  3170. public void SendAnimPackToAgentNF(ScenePresence p)
  3171. {
  3172. if (IsChildAgent || Animator == null)
  3173. return;
  3174. Animator.SendAnimPackToClient(p.ControllingClient);
  3175. }
  3176. public void SendAnimPackToAgentNF(ScenePresence p, UUID[] animations, int[] seqs, UUID[] objectIDs)
  3177. {
  3178. p.ControllingClient.SendAnimations(animations, seqs, ControllingClient.AgentId, objectIDs);
  3179. }
  3180. public void SendAnimPack(UUID[] animations, int[] seqs, UUID[] objectIDs)
  3181. {
  3182. if (IsChildAgent)
  3183. return;
  3184. m_scene.ForEachScenePresence(delegate(ScenePresence p)
  3185. {
  3186. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && p.GodLevel < 200)
  3187. return;
  3188. p.ControllingClient.SendAnimations(animations, seqs, ControllingClient.AgentId, objectIDs);
  3189. });
  3190. }
  3191. #endregion
  3192. #region Significant Movement Method
  3193. /// <summary>
  3194. /// This checks for a significant movement and sends a coarselocationchange update
  3195. /// </summary>
  3196. protected void CheckForSignificantMovement()
  3197. {
  3198. if (Util.GetDistanceTo(AbsolutePosition, posLastSignificantMove) > SIGNIFICANT_MOVEMENT)
  3199. {
  3200. posLastSignificantMove = AbsolutePosition;
  3201. m_scene.EventManager.TriggerSignificantClientMovement(this);
  3202. }
  3203. // Minimum Draw distance is 64 meters, the Radius of the draw distance sphere is 32m
  3204. if (Util.GetDistanceTo(AbsolutePosition, m_lastChildAgentUpdatePosition) >= Scene.ChildReprioritizationDistance)
  3205. {
  3206. m_lastChildAgentUpdatePosition = AbsolutePosition;
  3207. // m_lastChildAgentUpdateCamPosition = CameraPosition;
  3208. /* cadu is not used
  3209. ChildAgentDataUpdate cadu = new ChildAgentDataUpdate();
  3210. cadu.ActiveGroupID = UUID.Zero.Guid;
  3211. cadu.AgentID = UUID.Guid;
  3212. cadu.alwaysrun = SetAlwaysRun;
  3213. cadu.AVHeight = Appearance.AvatarHeight;
  3214. cadu.cameraPosition = CameraPosition;
  3215. cadu.drawdistance = DrawDistance;
  3216. cadu.GroupAccess = 0;
  3217. cadu.Position = AbsolutePosition;
  3218. cadu.regionHandle = RegionHandle;
  3219. // Throttles
  3220. float multiplier = 1;
  3221. int childRegions = KnownRegionCount;
  3222. if (childRegions != 0)
  3223. multiplier = 1f / childRegions;
  3224. // Minimum throttle for a child region is 1/4 of the root region throttle
  3225. if (multiplier <= 0.25f)
  3226. multiplier = 0.25f;
  3227. cadu.throttles = ControllingClient.GetThrottlesPacked(multiplier);
  3228. cadu.Velocity = Velocity;
  3229. */
  3230. AgentPosition agentpos = new AgentPosition();
  3231. // agentpos.CopyFrom(cadu, ControllingClient.SessionId);
  3232. agentpos.AgentID = new UUID(UUID.Guid);
  3233. agentpos.SessionID = ControllingClient.SessionId;
  3234. agentpos.Size = Appearance.AvatarSize;
  3235. agentpos.Center = CameraPosition;
  3236. agentpos.Far = DrawDistance;
  3237. agentpos.Position = AbsolutePosition;
  3238. agentpos.Velocity = Velocity;
  3239. agentpos.RegionHandle = RegionHandle;
  3240. agentpos.Throttles = ControllingClient.GetThrottlesPacked(1);
  3241. // Let's get this out of the update loop
  3242. Util.FireAndForget(
  3243. o => m_scene.SendOutChildAgentUpdates(agentpos, this), null, "ScenePresence.SendOutChildAgentUpdates");
  3244. }
  3245. }
  3246. #endregion
  3247. #region Border Crossing Methods
  3248. /// <summary>
  3249. /// Starts the process of moving an avatar into another region if they are crossing the border.
  3250. /// </summary>
  3251. /// <remarks>
  3252. /// Also removes the avatar from the physical scene if transit has started.
  3253. /// </remarks>
  3254. protected void CheckForBorderCrossing()
  3255. {
  3256. // Check that we we are not a child
  3257. if (IsChildAgent || IsInTransit)
  3258. return;
  3259. // If we don't have a PhysActor, we can't cross anyway
  3260. // Also don't do this while sat, sitting avatars cross with the
  3261. // object they sit on. ParentUUID denoted a pending sit, don't
  3262. // interfere with it.
  3263. if (ParentID != 0 || PhysicsActor == null || ParentUUID != UUID.Zero)
  3264. return;
  3265. Vector3 pos2 = AbsolutePosition;
  3266. Vector3 vel = Velocity;
  3267. float timeStep = 0.1f;
  3268. pos2.X += vel.X * timeStep;
  3269. pos2.Y += vel.Y * timeStep;
  3270. pos2.Z += vel.Z * timeStep;
  3271. // m_log.DebugFormat(
  3272. // "[SCENE PRESENCE]: Testing border check for projected position {0} of {1} in {2}",
  3273. // pos2, Name, Scene.Name);
  3274. if (Scene.PositionIsInCurrentRegion(pos2))
  3275. return;
  3276. if (!CrossToNewRegion() && m_requestedSitTargetUUID == UUID.Zero)
  3277. {
  3278. // we don't have entity transfer module
  3279. Vector3 pos = AbsolutePosition;
  3280. float px = pos.X;
  3281. if (px < 0)
  3282. pos.X += Velocity.X * 2;
  3283. else if (px > m_scene.RegionInfo.RegionSizeX)
  3284. pos.X -= Velocity.X * 2;
  3285. float py = pos.Y;
  3286. if (py < 0)
  3287. pos.Y += Velocity.Y * 2;
  3288. else if (py > m_scene.RegionInfo.RegionSizeY)
  3289. pos.Y -= Velocity.Y * 2;
  3290. Velocity = Vector3.Zero;
  3291. AbsolutePosition = pos;
  3292. }
  3293. }
  3294. public void CrossToNewRegionFail()
  3295. {
  3296. if (m_requestedSitTargetUUID == UUID.Zero)
  3297. {
  3298. bool isFlying = Flying;
  3299. RemoveFromPhysicalScene();
  3300. Vector3 pos = AbsolutePosition;
  3301. float px = pos.X;
  3302. if (px < 0)
  3303. pos.X += Velocity.X * 2;
  3304. else if (px > m_scene.RegionInfo.RegionSizeX)
  3305. pos.X -= Velocity.X * 2;
  3306. float py = pos.Y;
  3307. if (py < 0)
  3308. pos.Y += Velocity.Y * 2;
  3309. else if (py > m_scene.RegionInfo.RegionSizeY)
  3310. pos.Y -= Velocity.Y * 2;
  3311. Velocity = Vector3.Zero;
  3312. AbsolutePosition = pos;
  3313. AddToPhysicalScene(isFlying);
  3314. }
  3315. }
  3316. /// <summary>
  3317. /// Moves the agent outside the region bounds
  3318. /// Tells neighbor region that we're crossing to it
  3319. /// If the neighbor accepts, remove the agent's viewable avatar from this scene
  3320. /// set them to a child agent.
  3321. /// </summary>
  3322. protected bool CrossToNewRegion()
  3323. {
  3324. bool result = false;
  3325. // parcelRegionCross(false);
  3326. try
  3327. {
  3328. result = m_scene.CrossAgentToNewRegion(this, Flying);
  3329. }
  3330. catch
  3331. {
  3332. // result = m_scene.CrossAgentToNewRegion(this, false);
  3333. return false;
  3334. }
  3335. // if(!result)
  3336. // parcelRegionCross(true);
  3337. return result;
  3338. }
  3339. /* useless. Either use MakeChild or delete the presence
  3340. public void Reset()
  3341. {
  3342. // m_log.DebugFormat("[SCENE PRESENCE]: Resetting {0} in {1}", Name, Scene.RegionInfo.RegionName);
  3343. // Put the child agent back at the center
  3344. AbsolutePosition
  3345. = new Vector3(((float)m_scene.RegionInfo.RegionSizeX * 0.5f), ((float)m_scene.RegionInfo.RegionSizeY * 0.5f), 70);
  3346. Animator.ResetAnimations();
  3347. }
  3348. */
  3349. /// <summary>
  3350. /// Computes which child agents to close when the scene presence moves to another region.
  3351. /// Removes those regions from m_knownRegions.
  3352. /// </summary>
  3353. /// <param name="newRegionX">The new region's x on the map</param>
  3354. /// <param name="newRegionY">The new region's y on the map</param>
  3355. /// <returns></returns>
  3356. public void CloseChildAgents(bool logout, ulong newRegionHandle, int newRegionSizeX, int newRegionSizeY)
  3357. {
  3358. uint newRegionX, newRegionY;
  3359. List<ulong> byebyeRegions = new List<ulong>();
  3360. List<ulong> knownRegions = KnownRegionHandles;
  3361. m_log.DebugFormat(
  3362. "[SCENE PRESENCE]: Closing child agents. Checking {0} regions in {1}",
  3363. knownRegions.Count, Scene.RegionInfo.RegionName);
  3364. //DumpKnownRegions();
  3365. Util.RegionHandleToRegionLoc(newRegionHandle, out newRegionX, out newRegionY);
  3366. uint x, y;
  3367. spRegionSizeInfo regInfo;
  3368. foreach (ulong handle in knownRegions)
  3369. {
  3370. // Don't close the agent on this region yet
  3371. if (handle != Scene.RegionInfo.RegionHandle)
  3372. {
  3373. if (logout)
  3374. byebyeRegions.Add(handle);
  3375. else
  3376. {
  3377. Util.RegionHandleToRegionLoc(handle, out x, out y);
  3378. if (m_knownChildRegionsSizeInfo.TryGetValue(handle, out regInfo))
  3379. {
  3380. // m_log.Debug("---> x: " + x + "; newx:" + newRegionX + "; Abs:" + (int)Math.Abs((int)(x - newRegionX)));
  3381. // m_log.Debug("---> y: " + y + "; newy:" + newRegionY + "; Abs:" + (int)Math.Abs((int)(y - newRegionY)));
  3382. if (Util.IsOutsideView(DrawDistance, x, newRegionX, y, newRegionY,
  3383. regInfo.sizeX, regInfo.sizeY, newRegionSizeX, newRegionSizeY))
  3384. {
  3385. byebyeRegions.Add(handle);
  3386. }
  3387. }
  3388. else
  3389. {
  3390. if (Util.IsOutsideView(DrawDistance, x, newRegionX, y, newRegionY,
  3391. (int)Constants.RegionSize, (int)Constants.RegionSize, newRegionSizeX, newRegionSizeY))
  3392. {
  3393. byebyeRegions.Add(handle);
  3394. }
  3395. }
  3396. }
  3397. }
  3398. }
  3399. if (byebyeRegions.Count > 0)
  3400. {
  3401. m_log.Debug("[SCENE PRESENCE]: Closing " + byebyeRegions.Count + " child agents");
  3402. AgentCircuitData acd = Scene.AuthenticateHandler.GetAgentCircuitData(UUID);
  3403. string auth = string.Empty;
  3404. if (acd != null)
  3405. auth = acd.SessionID.ToString();
  3406. m_scene.SceneGridService.SendCloseChildAgentConnections(ControllingClient.AgentId, auth, byebyeRegions);
  3407. }
  3408. foreach (ulong handle in byebyeRegions)
  3409. {
  3410. RemoveNeighbourRegion(handle);
  3411. Scene.CapsModule.DropChildSeed(UUID, handle);
  3412. }
  3413. }
  3414. #endregion
  3415. /// <summary>
  3416. /// This allows the Sim owner the abiility to kick users from their sim currently.
  3417. /// It tells the client that the agent has permission to do so.
  3418. /// </summary>
  3419. public void GrantGodlikePowers(UUID agentID, UUID sessionID, UUID token, bool godStatus)
  3420. {
  3421. int oldgodlevel = GodLevel;
  3422. if (godStatus)
  3423. {
  3424. // For now, assign god level 200 to anyone
  3425. // who is granted god powers, but has no god level set.
  3426. //
  3427. UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, agentID);
  3428. if (account != null)
  3429. {
  3430. if (account.UserLevel > 0)
  3431. GodLevel = account.UserLevel;
  3432. else
  3433. GodLevel = 200;
  3434. }
  3435. }
  3436. else
  3437. {
  3438. GodLevel = 0;
  3439. }
  3440. ControllingClient.SendAdminResponse(token, (uint)GodLevel);
  3441. if(oldgodlevel != GodLevel)
  3442. parcelGodCheck(m_currentParcelUUID, GodLevel >= 200);
  3443. }
  3444. #region Child Agent Updates
  3445. public void UpdateChildAgent(AgentData cAgentData)
  3446. {
  3447. // m_log.Debug(" >>> ChildAgentDataUpdate <<< " + Scene.RegionInfo.RegionName);
  3448. if (!IsChildAgent)
  3449. return;
  3450. CopyFrom(cAgentData);
  3451. }
  3452. private static Vector3 marker = new Vector3(-1f, -1f, -1f);
  3453. private void RaiseUpdateThrottles()
  3454. {
  3455. m_scene.EventManager.TriggerThrottleUpdate(this);
  3456. }
  3457. /// <summary>
  3458. /// This updates important decision making data about a child agent
  3459. /// The main purpose is to figure out what objects to send to a child agent that's in a neighboring region
  3460. /// </summary>
  3461. public void UpdateChildAgent(AgentPosition cAgentData, uint tRegionX, uint tRegionY, uint rRegionX, uint rRegionY)
  3462. {
  3463. if (!IsChildAgent)
  3464. return;
  3465. RegionHandle = cAgentData.RegionHandle;
  3466. //m_log.Debug(" >>> ChildAgentPositionUpdate <<< " + rRegionX + "-" + rRegionY);
  3467. int shiftx = ((int)rRegionX - (int)tRegionX) * (int)Constants.RegionSize;
  3468. int shifty = ((int)rRegionY - (int)tRegionY) * (int)Constants.RegionSize;
  3469. Vector3 offset = new Vector3(shiftx, shifty, 0f);
  3470. // When we get to the point of re-computing neighbors everytime this
  3471. // changes, then start using the agent's drawdistance rather than the
  3472. // region's draw distance.
  3473. DrawDistance = cAgentData.Far;
  3474. // DrawDistance = Scene.DefaultDrawDistance;
  3475. if (cAgentData.Position != marker) // UGH!!
  3476. m_pos = cAgentData.Position + offset;
  3477. if (Vector3.Distance(AbsolutePosition, posLastSignificantMove) >= Scene.ChildReprioritizationDistance)
  3478. {
  3479. posLastSignificantMove = AbsolutePosition;
  3480. ReprioritizeUpdates();
  3481. }
  3482. CameraPosition = cAgentData.Center + offset;
  3483. if ((cAgentData.Throttles != null) && cAgentData.Throttles.Length > 0)
  3484. {
  3485. // some scaling factor
  3486. float x = m_pos.X;
  3487. if (x > m_scene.RegionInfo.RegionSizeX)
  3488. x -= m_scene.RegionInfo.RegionSizeX;
  3489. float y = m_pos.Y;
  3490. if (y > m_scene.RegionInfo.RegionSizeY)
  3491. y -= m_scene.RegionInfo.RegionSizeY;
  3492. x = x * x + y * y;
  3493. const float distScale = 0.4f / Constants.RegionSize / Constants.RegionSize;
  3494. float factor = 1.0f - distScale * x;
  3495. if (factor < 0.2f)
  3496. factor = 0.2f;
  3497. ControllingClient.SetChildAgentThrottle(cAgentData.Throttles,factor);
  3498. }
  3499. if(cAgentData.ChildrenCapSeeds != null && cAgentData.ChildrenCapSeeds.Count >0)
  3500. {
  3501. if (Scene.CapsModule != null)
  3502. {
  3503. Scene.CapsModule.SetChildrenSeed(UUID, cAgentData.ChildrenCapSeeds);
  3504. }
  3505. KnownRegions = cAgentData.ChildrenCapSeeds;
  3506. }
  3507. //cAgentData.AVHeight;
  3508. //m_velocity = cAgentData.Velocity;
  3509. }
  3510. public void CopyTo(AgentData cAgent)
  3511. {
  3512. cAgent.CallbackURI = m_callbackURI;
  3513. cAgent.AgentID = UUID;
  3514. cAgent.RegionID = Scene.RegionInfo.RegionID;
  3515. cAgent.SessionID = ControllingClient.SessionId;
  3516. cAgent.Position = AbsolutePosition;
  3517. cAgent.Velocity = m_velocity;
  3518. cAgent.Center = CameraPosition;
  3519. cAgent.AtAxis = CameraAtAxis;
  3520. cAgent.LeftAxis = CameraLeftAxis;
  3521. cAgent.UpAxis = CameraUpAxis;
  3522. cAgent.Far = DrawDistance;
  3523. // Throttles
  3524. cAgent.Throttles = ControllingClient.GetThrottlesPacked(1);
  3525. cAgent.HeadRotation = m_headrotation;
  3526. cAgent.BodyRotation = Rotation;
  3527. cAgent.ControlFlags = (uint)m_AgentControlFlags;
  3528. if (m_scene.Permissions.IsGod(new UUID(cAgent.AgentID)))
  3529. cAgent.GodLevel = (byte)GodLevel;
  3530. else
  3531. cAgent.GodLevel = (byte) 0;
  3532. cAgent.AlwaysRun = SetAlwaysRun;
  3533. // make clear we want the all thing
  3534. cAgent.Appearance = new AvatarAppearance(Appearance,true,true);
  3535. cAgent.ParentPart = ParentUUID;
  3536. cAgent.SitOffset = PrevSitOffset;
  3537. lock (scriptedcontrols)
  3538. {
  3539. ControllerData[] controls = new ControllerData[scriptedcontrols.Count];
  3540. int i = 0;
  3541. foreach (ScriptControllers c in scriptedcontrols.Values)
  3542. {
  3543. controls[i++] = new ControllerData(c.objectID, c.itemID, (uint)c.ignoreControls, (uint)c.eventControls);
  3544. }
  3545. cAgent.Controllers = controls;
  3546. }
  3547. // Animations
  3548. try
  3549. {
  3550. cAgent.Anims = Animator.Animations.ToArray();
  3551. }
  3552. catch { }
  3553. cAgent.DefaultAnim = Animator.Animations.DefaultAnimation;
  3554. cAgent.AnimState = Animator.Animations.ImplicitDefaultAnimation;
  3555. cAgent.MovementAnimationOverRides = Overrides.CloneAOPairs();
  3556. cAgent.MotionState = (byte)Animator.currentControlState;
  3557. if (Scene.AttachmentsModule != null)
  3558. Scene.AttachmentsModule.CopyAttachments(this, cAgent);
  3559. }
  3560. private void CopyFrom(AgentData cAgent)
  3561. {
  3562. m_callbackURI = cAgent.CallbackURI;
  3563. // m_log.DebugFormat(
  3564. // "[SCENE PRESENCE]: Set callback for {0} in {1} to {2} in CopyFrom()",
  3565. // Name, m_scene.RegionInfo.RegionName, m_callbackURI);
  3566. m_pos = cAgent.Position;
  3567. m_velocity = cAgent.Velocity;
  3568. CameraPosition = cAgent.Center;
  3569. CameraAtAxis = cAgent.AtAxis;
  3570. CameraLeftAxis = cAgent.LeftAxis;
  3571. CameraUpAxis = cAgent.UpAxis;
  3572. ParentUUID = cAgent.ParentPart;
  3573. PrevSitOffset = cAgent.SitOffset;
  3574. // When we get to the point of re-computing neighbors everytime this
  3575. // changes, then start using the agent's drawdistance rather than the
  3576. // region's draw distance.
  3577. DrawDistance = cAgent.Far;
  3578. //DrawDistance = Scene.DefaultDrawDistance;
  3579. if (cAgent.ChildrenCapSeeds != null && cAgent.ChildrenCapSeeds.Count > 0)
  3580. {
  3581. if (Scene.CapsModule != null)
  3582. {
  3583. Scene.CapsModule.SetChildrenSeed(UUID, cAgent.ChildrenCapSeeds);
  3584. }
  3585. KnownRegions = cAgent.ChildrenCapSeeds;
  3586. }
  3587. if ((cAgent.Throttles != null) && cAgent.Throttles.Length > 0)
  3588. ControllingClient.SetChildAgentThrottle(cAgent.Throttles);
  3589. m_headrotation = cAgent.HeadRotation;
  3590. Rotation = cAgent.BodyRotation;
  3591. m_AgentControlFlags = (AgentManager.ControlFlags)cAgent.ControlFlags;
  3592. if (m_scene.Permissions.IsGod(new UUID(cAgent.AgentID)))
  3593. GodLevel = cAgent.GodLevel;
  3594. SetAlwaysRun = cAgent.AlwaysRun;
  3595. Appearance = new AvatarAppearance(cAgent.Appearance);
  3596. /*
  3597. bool isFlying = ((m_AgentControlFlags & AgentManager.ControlFlags.AGENT_CONTROL_FLY) != 0);
  3598. if (PhysicsActor != null)
  3599. {
  3600. RemoveFromPhysicalScene();
  3601. AddToPhysicalScene(isFlying);
  3602. }
  3603. */
  3604. try
  3605. {
  3606. lock (scriptedcontrols)
  3607. {
  3608. if (cAgent.Controllers != null)
  3609. {
  3610. scriptedcontrols.Clear();
  3611. foreach (ControllerData c in cAgent.Controllers)
  3612. {
  3613. ScriptControllers sc = new ScriptControllers();
  3614. sc.objectID = c.ObjectID;
  3615. sc.itemID = c.ItemID;
  3616. sc.ignoreControls = (ScriptControlled)c.IgnoreControls;
  3617. sc.eventControls = (ScriptControlled)c.EventControls;
  3618. scriptedcontrols[sc.itemID] = sc;
  3619. }
  3620. }
  3621. }
  3622. }
  3623. catch { }
  3624. Animator.ResetAnimations();
  3625. Overrides.CopyAOPairsFrom(cAgent.MovementAnimationOverRides);
  3626. // FIXME: Why is this null check necessary? Where are the cases where we get a null Anims object?
  3627. if (cAgent.DefaultAnim != null)
  3628. Animator.Animations.SetDefaultAnimation(cAgent.DefaultAnim.AnimID, cAgent.DefaultAnim.SequenceNum, UUID.Zero);
  3629. if (cAgent.AnimState != null)
  3630. Animator.Animations.SetImplicitDefaultAnimation(cAgent.AnimState.AnimID, cAgent.AnimState.SequenceNum, UUID.Zero);
  3631. if (cAgent.Anims != null)
  3632. Animator.Animations.FromArray(cAgent.Anims);
  3633. if (cAgent.MotionState != 0)
  3634. Animator.currentControlState = (ScenePresenceAnimator.motionControlStates) cAgent.MotionState;
  3635. if (Scene.AttachmentsModule != null)
  3636. Scene.AttachmentsModule.CopyAttachments(cAgent, this);
  3637. lock (m_originRegionIDAccessLock)
  3638. m_originRegionID = cAgent.RegionID;
  3639. }
  3640. public bool CopyAgent(out IAgentData agent)
  3641. {
  3642. agent = new CompleteAgentData();
  3643. CopyTo((AgentData)agent);
  3644. return true;
  3645. }
  3646. #endregion Child Agent Updates
  3647. /// <summary>
  3648. /// Handles part of the PID controller function for moving an avatar.
  3649. /// </summary>
  3650. public void UpdateMovement()
  3651. {
  3652. if (IsInTransit)
  3653. return;
  3654. if (m_forceToApply.HasValue)
  3655. {
  3656. Vector3 force = m_forceToApply.Value;
  3657. Velocity = force;
  3658. m_forceToApply = null;
  3659. TriggerScenePresenceUpdated();
  3660. }
  3661. }
  3662. /// <summary>
  3663. /// Adds a physical representation of the avatar to the Physics plugin
  3664. /// </summary>
  3665. public void AddToPhysicalScene(bool isFlying)
  3666. {
  3667. // m_log.DebugFormat(
  3668. // "[SCENE PRESENCE]: Adding physics actor for {0}, ifFlying = {1} in {2}",
  3669. // Name, isFlying, Scene.RegionInfo.RegionName);
  3670. if (PhysicsActor != null)
  3671. {
  3672. m_log.ErrorFormat(
  3673. "[SCENE PRESENCE]: Adding physics actor for {0} to {1} but this scene presence already has a physics actor",
  3674. Name, Scene.RegionInfo.RegionName);
  3675. }
  3676. if (Appearance.AvatarHeight == 0)
  3677. // Appearance.SetHeight();
  3678. Appearance.SetSize(new Vector3(0.45f,0.6f,1.9f));
  3679. PhysicsScene scene = m_scene.PhysicsScene;
  3680. Vector3 pVec = AbsolutePosition;
  3681. PhysicsActor = scene.AddAvatar(
  3682. LocalId, Firstname + "." + Lastname, pVec,
  3683. Appearance.AvatarBoxSize,Appearance.AvatarFeetOffset, isFlying);
  3684. PhysicsActor.Orientation = m_bodyRot;
  3685. //PhysicsActor.OnRequestTerseUpdate += SendTerseUpdateToAllClients;
  3686. PhysicsActor.OnCollisionUpdate += PhysicsCollisionUpdate;
  3687. PhysicsActor.OnOutOfBounds += OutOfBoundsCall; // Called for PhysicsActors when there's something wrong
  3688. PhysicsActor.SubscribeEvents(100);
  3689. PhysicsActor.LocalID = LocalId;
  3690. }
  3691. private void OutOfBoundsCall(Vector3 pos)
  3692. {
  3693. //bool flying = Flying;
  3694. //RemoveFromPhysicalScene();
  3695. //AddToPhysicalScene(flying);
  3696. if (ControllingClient != null)
  3697. ControllingClient.SendAgentAlertMessage("Physics is having a problem with your avatar. You may not be able to move until you relog.", true);
  3698. }
  3699. /// <summary>
  3700. /// Event called by the physics plugin to tell the avatar about a collision.
  3701. /// </summary>
  3702. /// <remarks>
  3703. /// This function is called continuously, even when there are no collisions. If the avatar is walking on the
  3704. /// ground or a prim then there will be collision information between the avatar and the surface.
  3705. ///
  3706. /// FIXME: However, we can't safely avoid calling this yet where there are no collisions without analyzing whether
  3707. /// any part of this method is relying on an every-frame call.
  3708. /// </remarks>
  3709. /// <param name="e"></param>
  3710. public void PhysicsCollisionUpdate(EventArgs e)
  3711. {
  3712. if (IsChildAgent || Animator == null)
  3713. return;
  3714. if(IsInTransit)
  3715. return;
  3716. //if ((Math.Abs(Velocity.X) > 0.1e-9f) || (Math.Abs(Velocity.Y) > 0.1e-9f))
  3717. // The Physics Scene will send updates every 500 ms grep: PhysicsActor.SubscribeEvents(
  3718. // as of this comment the interval is set in AddToPhysicalScene
  3719. // if (m_updateCount > 0)
  3720. // {
  3721. if (Animator.UpdateMovementAnimations())
  3722. TriggerScenePresenceUpdated();
  3723. // m_updateCount--;
  3724. // }
  3725. CollisionEventUpdate collisionData = (CollisionEventUpdate)e;
  3726. Dictionary<uint, ContactPoint> coldata = collisionData.m_objCollisionList;
  3727. // // No collisions at all means we may be flying. Update always
  3728. // // to make falling work
  3729. // if (m_lastColCount != coldata.Count || coldata.Count == 0)
  3730. // {
  3731. // m_updateCount = UPDATE_COUNT;
  3732. // m_lastColCount = coldata.Count;
  3733. // }
  3734. if (coldata.Count != 0)
  3735. {
  3736. /*
  3737. switch (Animator.CurrentMovementAnimation)
  3738. {
  3739. case "STAND":
  3740. case "WALK":
  3741. case "RUN":
  3742. case "CROUCH":
  3743. case "CROUCHWALK":
  3744. {
  3745. */
  3746. ContactPoint lowest;
  3747. lowest.SurfaceNormal = Vector3.Zero;
  3748. lowest.Position = Vector3.Zero;
  3749. lowest.Position.Z = float.MaxValue;
  3750. foreach (ContactPoint contact in coldata.Values)
  3751. {
  3752. if (contact.CharacterFeet && contact.Position.Z < lowest.Position.Z)
  3753. {
  3754. lowest = contact;
  3755. }
  3756. }
  3757. if (lowest.Position.Z != float.MaxValue)
  3758. {
  3759. lowest.SurfaceNormal = -lowest.SurfaceNormal;
  3760. CollisionPlane = new Vector4(lowest.SurfaceNormal, Vector3.Dot(lowest.Position, lowest.SurfaceNormal));
  3761. }
  3762. else
  3763. CollisionPlane = Vector4.UnitW;
  3764. /*
  3765. }
  3766. break;
  3767. }
  3768. */
  3769. }
  3770. else
  3771. CollisionPlane = Vector4.UnitW;
  3772. RaiseCollisionScriptEvents(coldata);
  3773. // Gods do not take damage and Invulnerable is set depending on parcel/region flags
  3774. if (Invulnerable || GodLevel > 0)
  3775. return;
  3776. // The following may be better in the ICombatModule
  3777. // probably tweaking of the values for ground and normal prim collisions will be needed
  3778. float starthealth = Health;
  3779. uint killerObj = 0;
  3780. SceneObjectPart part = null;
  3781. foreach (uint localid in coldata.Keys)
  3782. {
  3783. if (localid == 0)
  3784. {
  3785. part = null;
  3786. }
  3787. else
  3788. {
  3789. part = Scene.GetSceneObjectPart(localid);
  3790. }
  3791. if (part != null)
  3792. {
  3793. // Ignore if it has been deleted or volume detect
  3794. if (!part.ParentGroup.IsDeleted && !part.ParentGroup.IsVolumeDetect)
  3795. {
  3796. if (part.ParentGroup.Damage > 0.0f)
  3797. {
  3798. // Something with damage...
  3799. Health -= part.ParentGroup.Damage;
  3800. part.ParentGroup.Scene.DeleteSceneObject(part.ParentGroup, false);
  3801. }
  3802. else
  3803. {
  3804. // An ordinary prim
  3805. if (coldata[localid].PenetrationDepth >= 0.10f)
  3806. Health -= coldata[localid].PenetrationDepth * 5.0f;
  3807. }
  3808. }
  3809. }
  3810. else
  3811. {
  3812. // 0 is the ground
  3813. // what about collisions with other avatars?
  3814. if (localid == 0 && coldata[localid].PenetrationDepth >= 0.10f)
  3815. Health -= coldata[localid].PenetrationDepth * 5.0f;
  3816. }
  3817. if (Health <= 0.0f)
  3818. {
  3819. if (localid != 0)
  3820. killerObj = localid;
  3821. }
  3822. //m_log.Debug("[AVATAR]: Collision with localid: " + localid.ToString() + " at depth: " + coldata[localid].ToString());
  3823. }
  3824. //Health = 100;
  3825. if (!Invulnerable)
  3826. {
  3827. if (starthealth != Health)
  3828. {
  3829. ControllingClient.SendHealth(Health);
  3830. }
  3831. if (Health <= 0)
  3832. {
  3833. m_scene.EventManager.TriggerAvatarKill(killerObj, this);
  3834. }
  3835. if (starthealth == Health && Health < 100.0f)
  3836. {
  3837. Health += 0.03f;
  3838. if (Health > 100.0f)
  3839. Health = 100.0f;
  3840. ControllingClient.SendHealth(Health);
  3841. }
  3842. }
  3843. }
  3844. public void setHealthWithUpdate(float health)
  3845. {
  3846. Health = health;
  3847. ControllingClient.SendHealth(Health);
  3848. }
  3849. protected internal void Close()
  3850. {
  3851. // Clear known regions
  3852. KnownRegions = new Dictionary<ulong, string>();
  3853. lock (m_reprioritization_timer)
  3854. {
  3855. m_reprioritization_timer.Enabled = false;
  3856. m_reprioritization_timer.Elapsed -= new ElapsedEventHandler(Reprioritize);
  3857. }
  3858. // I don't get it but mono crashes when you try to dispose of this timer,
  3859. // unsetting the elapsed callback should be enough to allow for cleanup however.
  3860. // m_reprioritizationTimer.Dispose();
  3861. RemoveFromPhysicalScene();
  3862. m_scene.EventManager.OnRegionHeartbeatEnd -= RegionHeartbeatEnd;
  3863. // if (Animator != null)
  3864. // Animator.Close();
  3865. Animator = null;
  3866. LifecycleState = ScenePresenceState.Removed;
  3867. }
  3868. public void AddAttachment(SceneObjectGroup gobj)
  3869. {
  3870. lock (m_attachments)
  3871. {
  3872. // This may be true when the attachment comes back
  3873. // from serialization after login. Clear it.
  3874. gobj.IsDeleted = false;
  3875. m_attachments.Add(gobj);
  3876. }
  3877. IBakedTextureModule bakedModule = m_scene.RequestModuleInterface<IBakedTextureModule>();
  3878. if (bakedModule != null)
  3879. bakedModule.UpdateMeshAvatar(m_uuid);
  3880. }
  3881. /// <summary>
  3882. /// Get all the presence's attachments.
  3883. /// </summary>
  3884. /// <returns>A copy of the list which contains the attachments.</returns>
  3885. public List<SceneObjectGroup> GetAttachments()
  3886. {
  3887. lock (m_attachments)
  3888. return new List<SceneObjectGroup>(m_attachments);
  3889. }
  3890. /// <summary>
  3891. /// Get the scene objects attached to the given point.
  3892. /// </summary>
  3893. /// <param name="attachmentPoint"></param>
  3894. /// <returns>Returns an empty list if there were no attachments at the point.</returns>
  3895. public List<SceneObjectGroup> GetAttachments(uint attachmentPoint)
  3896. {
  3897. List<SceneObjectGroup> attachments = new List<SceneObjectGroup>();
  3898. if (attachmentPoint >= 0)
  3899. {
  3900. lock (m_attachments)
  3901. {
  3902. foreach (SceneObjectGroup so in m_attachments)
  3903. {
  3904. if (attachmentPoint == so.AttachmentPoint)
  3905. attachments.Add(so);
  3906. }
  3907. }
  3908. }
  3909. return attachments;
  3910. }
  3911. public bool HasAttachments()
  3912. {
  3913. lock (m_attachments)
  3914. return m_attachments.Count > 0;
  3915. }
  3916. /// <summary>
  3917. /// Returns the total count of scripts in all parts inventories.
  3918. /// </summary>
  3919. public int ScriptCount()
  3920. {
  3921. int count = 0;
  3922. lock (m_attachments)
  3923. {
  3924. foreach (SceneObjectGroup gobj in m_attachments)
  3925. {
  3926. if (gobj != null)
  3927. {
  3928. count += gobj.ScriptCount();
  3929. }
  3930. }
  3931. }
  3932. return count;
  3933. }
  3934. /// <summary>
  3935. /// A float the value is a representative execution time in milliseconds of all scripts in all attachments.
  3936. /// </summary>
  3937. public float ScriptExecutionTime()
  3938. {
  3939. float time = 0.0f;
  3940. lock (m_attachments)
  3941. {
  3942. foreach (SceneObjectGroup gobj in m_attachments)
  3943. {
  3944. if (gobj != null)
  3945. {
  3946. time += gobj.ScriptExecutionTime();
  3947. }
  3948. }
  3949. }
  3950. return time;
  3951. }
  3952. /// <summary>
  3953. /// Returns the total count of running scripts in all parts.
  3954. /// </summary>
  3955. public int RunningScriptCount()
  3956. {
  3957. int count = 0;
  3958. lock (m_attachments)
  3959. {
  3960. foreach (SceneObjectGroup gobj in m_attachments)
  3961. {
  3962. if (gobj != null)
  3963. {
  3964. count += gobj.RunningScriptCount();
  3965. }
  3966. }
  3967. }
  3968. return count;
  3969. }
  3970. public bool HasScriptedAttachments()
  3971. {
  3972. lock (m_attachments)
  3973. {
  3974. foreach (SceneObjectGroup gobj in m_attachments)
  3975. {
  3976. if (gobj != null)
  3977. {
  3978. if (gobj.RootPart.Inventory.ContainsScripts())
  3979. return true;
  3980. }
  3981. }
  3982. }
  3983. return false;
  3984. }
  3985. public void RemoveAttachment(SceneObjectGroup gobj)
  3986. {
  3987. lock (m_attachments)
  3988. m_attachments.Remove(gobj);
  3989. }
  3990. /// <summary>
  3991. /// Clear all attachments
  3992. /// </summary>
  3993. public void ClearAttachments()
  3994. {
  3995. lock (m_attachments)
  3996. m_attachments.Clear();
  3997. }
  3998. /// <summary>
  3999. /// This is currently just being done for information.
  4000. /// </summary>
  4001. public bool ValidateAttachments()
  4002. {
  4003. bool validated = true;
  4004. lock (m_attachments)
  4005. {
  4006. // Validate
  4007. foreach (SceneObjectGroup gobj in m_attachments)
  4008. {
  4009. if (gobj == null)
  4010. {
  4011. m_log.WarnFormat(
  4012. "[SCENE PRESENCE]: Failed to validate an attachment for {0} since it was null. Continuing", Name);
  4013. validated = false;
  4014. }
  4015. else if (gobj.IsDeleted)
  4016. {
  4017. m_log.WarnFormat(
  4018. "[SCENE PRESENCE]: Failed to validate attachment {0} {1} for {2} since it had been deleted. Continuing",
  4019. gobj.Name, gobj.UUID, Name);
  4020. validated = false;
  4021. }
  4022. }
  4023. }
  4024. return validated;
  4025. }
  4026. public void SendAttachmentsToAllAgents()
  4027. {
  4028. lock (m_attachments)
  4029. {
  4030. foreach (SceneObjectGroup sog in m_attachments)
  4031. {
  4032. m_scene.ForEachScenePresence(delegate(ScenePresence p)
  4033. {
  4034. if (p != this && sog.HasPrivateAttachmentPoint)
  4035. return;
  4036. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && p.GodLevel < 200)
  4037. return;
  4038. SendTerseUpdateToAgentNF(p);
  4039. SendAttachmentFullUpdateToAgentNF(sog, p);
  4040. });
  4041. }
  4042. }
  4043. }
  4044. // send attachments to a client without filters except for huds
  4045. // for now they are checked in several places down the line...
  4046. public void SendAttachmentsToAgentNF(ScenePresence p)
  4047. {
  4048. SendTerseUpdateToAgentNF(p);
  4049. lock (m_attachments)
  4050. {
  4051. foreach (SceneObjectGroup sog in m_attachments)
  4052. {
  4053. SendAttachmentFullUpdateToAgentNF(sog, p);
  4054. }
  4055. }
  4056. }
  4057. public void SendAttachmentFullUpdateToAgentNF(SceneObjectGroup sog, ScenePresence p)
  4058. {
  4059. if (p != this && sog.HasPrivateAttachmentPoint)
  4060. return;
  4061. SceneObjectPart[] parts = sog.Parts;
  4062. SceneObjectPart rootpart = sog.RootPart;
  4063. p.ControllingClient.SendEntityUpdate(rootpart, PrimUpdateFlags.FullUpdate);
  4064. for (int i = 0; i < parts.Length; i++)
  4065. {
  4066. SceneObjectPart part = parts[i];
  4067. if (part == rootpart)
  4068. continue;
  4069. p.ControllingClient.SendEntityUpdate(part, PrimUpdateFlags.FullUpdate);
  4070. }
  4071. }
  4072. public void SendAttachmentScheduleUpdate(SceneObjectGroup sog)
  4073. {
  4074. if (IsChildAgent || IsInTransit)
  4075. return;
  4076. SceneObjectPart[] origparts = sog.Parts;
  4077. SceneObjectPart[] parts = new SceneObjectPart[origparts.Length];
  4078. PrimUpdateFlags[] flags = new PrimUpdateFlags[origparts.Length];
  4079. SceneObjectPart rootpart = sog.RootPart;
  4080. UpdateRequired rootreq = sog.RootPart.UpdateFlag;
  4081. int j = 0;
  4082. bool allterse = true;
  4083. for (int i = 0; i < origparts.Length; i++)
  4084. {
  4085. if (origparts[i] != rootpart)
  4086. {
  4087. switch (origparts[i].UpdateFlag)
  4088. {
  4089. case UpdateRequired.NONE:
  4090. break;
  4091. case UpdateRequired.TERSE:
  4092. flags[j] = PrimUpdateFlags.Position | PrimUpdateFlags.Rotation | PrimUpdateFlags.Velocity
  4093. | PrimUpdateFlags.Acceleration | PrimUpdateFlags.AngularVelocity;
  4094. parts[j] = origparts[i];
  4095. j++;
  4096. break;
  4097. case UpdateRequired.FULL:
  4098. flags[j] = PrimUpdateFlags.FullUpdate;
  4099. allterse = false;
  4100. parts[j] = origparts[i];
  4101. j++;
  4102. break;
  4103. }
  4104. }
  4105. origparts[i].UpdateFlag = 0;
  4106. }
  4107. if (j == 0 && rootreq == UpdateRequired.NONE)
  4108. return;
  4109. PrimUpdateFlags rootflag = PrimUpdateFlags.FullUpdate;
  4110. if (rootreq != UpdateRequired.FULL && allterse)
  4111. {
  4112. rootflag = PrimUpdateFlags.Position | PrimUpdateFlags.Rotation | PrimUpdateFlags.Velocity
  4113. | PrimUpdateFlags.Acceleration | PrimUpdateFlags.AngularVelocity;
  4114. }
  4115. int nparts = j;
  4116. ControllingClient.SendEntityUpdate(rootpart, rootflag);
  4117. for (int i = 0; i < nparts; i++)
  4118. {
  4119. ControllingClient.SendEntityUpdate(parts[i], flags[i]);
  4120. }
  4121. if (sog.HasPrivateAttachmentPoint)
  4122. return;
  4123. List<ScenePresence> allPresences = m_scene.GetScenePresences();
  4124. foreach (ScenePresence p in allPresences)
  4125. {
  4126. if (p == this)
  4127. continue;
  4128. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && p.GodLevel < 200)
  4129. continue;
  4130. p.ControllingClient.SendEntityUpdate(rootpart, rootflag);
  4131. for (int i = 0; i < nparts; i++)
  4132. {
  4133. p.ControllingClient.SendEntityUpdate(parts[i], flags[i]);
  4134. }
  4135. }
  4136. }
  4137. public void SendAttachmentUpdate(SceneObjectGroup sog, UpdateRequired UpdateFlag)
  4138. {
  4139. if (IsChildAgent || IsInTransit)
  4140. return;
  4141. PrimUpdateFlags flag;
  4142. switch (UpdateFlag)
  4143. {
  4144. case UpdateRequired.TERSE:
  4145. flag = PrimUpdateFlags.Position | PrimUpdateFlags.Rotation | PrimUpdateFlags.Velocity
  4146. | PrimUpdateFlags.Acceleration | PrimUpdateFlags.AngularVelocity;
  4147. break;
  4148. case UpdateRequired.FULL:
  4149. flag = PrimUpdateFlags.FullUpdate;
  4150. break;
  4151. default:
  4152. return;
  4153. }
  4154. SceneObjectPart[] parts = sog.Parts;
  4155. SceneObjectPart rootpart = sog.RootPart;
  4156. // rootpart.UpdateFlag = 0;
  4157. ControllingClient.SendEntityUpdate(rootpart, flag);
  4158. for (int i = 0; i < parts.Length; i++)
  4159. {
  4160. SceneObjectPart part = parts[i];
  4161. if (part == rootpart)
  4162. continue;
  4163. ControllingClient.SendEntityUpdate(part, flag);
  4164. // part.UpdateFlag = 0;
  4165. }
  4166. if (sog.HasPrivateAttachmentPoint)
  4167. return;
  4168. List<ScenePresence> allPresences = m_scene.GetScenePresences();
  4169. foreach (ScenePresence p in allPresences)
  4170. {
  4171. if (p == this)
  4172. continue;
  4173. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && p.GodLevel < 200)
  4174. continue;
  4175. p.ControllingClient.SendEntityUpdate(rootpart, flag);
  4176. for (int i = 0; i < parts.Length; i++)
  4177. {
  4178. SceneObjectPart part = parts[i];
  4179. if (part == rootpart)
  4180. continue;
  4181. p.ControllingClient.SendEntityUpdate(part, flag);
  4182. }
  4183. }
  4184. }
  4185. public void SendAttachmentScheduleUpdate(SceneObjectPart part)
  4186. {
  4187. if (IsChildAgent || IsInTransit)
  4188. return;
  4189. PrimUpdateFlags flag;
  4190. switch (part.UpdateFlag)
  4191. {
  4192. case UpdateRequired.TERSE:
  4193. flag = PrimUpdateFlags.Position | PrimUpdateFlags.Rotation | PrimUpdateFlags.Velocity
  4194. | PrimUpdateFlags.Acceleration | PrimUpdateFlags.AngularVelocity;
  4195. break;
  4196. case UpdateRequired.FULL:
  4197. flag = PrimUpdateFlags.FullUpdate;
  4198. break;
  4199. default:
  4200. return;
  4201. }
  4202. part.UpdateFlag = 0;
  4203. ControllingClient.SendEntityUpdate(part, flag);
  4204. if (part.ParentGroup.HasPrivateAttachmentPoint)
  4205. return;
  4206. List<ScenePresence> allPresences = m_scene.GetScenePresences();
  4207. foreach (ScenePresence p in allPresences)
  4208. {
  4209. if (p == this)
  4210. continue;
  4211. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && p.GodLevel < 200)
  4212. continue;
  4213. p.ControllingClient.SendEntityUpdate(part, flag);
  4214. }
  4215. }
  4216. public void SendAttachmentUpdate(SceneObjectPart part, UpdateRequired UpdateFlag)
  4217. {
  4218. if (IsChildAgent || IsInTransit)
  4219. return;
  4220. PrimUpdateFlags flag;
  4221. switch (UpdateFlag)
  4222. {
  4223. case UpdateRequired.TERSE:
  4224. flag = PrimUpdateFlags.Position | PrimUpdateFlags.Rotation | PrimUpdateFlags.Velocity
  4225. | PrimUpdateFlags.Acceleration | PrimUpdateFlags.AngularVelocity;
  4226. break;
  4227. case UpdateRequired.FULL:
  4228. flag = PrimUpdateFlags.FullUpdate;
  4229. break;
  4230. default:
  4231. return;
  4232. }
  4233. // part.UpdateFlag = 0;
  4234. ControllingClient.SendEntityUpdate(part, flag);
  4235. if (part.ParentGroup.HasPrivateAttachmentPoint)
  4236. return;
  4237. List<ScenePresence> allPresences = m_scene.GetScenePresences();
  4238. foreach (ScenePresence p in allPresences)
  4239. {
  4240. if (p == this)
  4241. continue;
  4242. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && p.GodLevel < 200)
  4243. continue;
  4244. p.ControllingClient.SendEntityUpdate(part, flag);
  4245. }
  4246. }
  4247. /// <summary>
  4248. /// Send a script event to this scene presence's attachments
  4249. /// </summary>
  4250. /// <param name="eventName">The name of the event</param>
  4251. /// <param name="args">The arguments for the event</param>
  4252. public void SendScriptEventToAttachments(string eventName, Object[] args)
  4253. {
  4254. Util.FireAndForget(delegate(object x)
  4255. {
  4256. if (m_scriptEngines.Length == 0)
  4257. return;
  4258. lock (m_attachments)
  4259. {
  4260. foreach (SceneObjectGroup grp in m_attachments)
  4261. {
  4262. // 16384 is CHANGED_ANIMATION
  4263. //
  4264. // Send this to all attachment root prims
  4265. //
  4266. foreach (IScriptModule m in m_scriptEngines)
  4267. {
  4268. if (m == null) // No script engine loaded
  4269. continue;
  4270. m.PostObjectEvent(grp.RootPart.UUID, "changed", new Object[] { (int)Changed.ANIMATION });
  4271. }
  4272. }
  4273. }
  4274. }, null, "ScenePresence.SendScriptEventToAttachments");
  4275. }
  4276. /// <summary>
  4277. /// Gets the mass.
  4278. /// </summary>
  4279. /// <returns>
  4280. /// The mass.
  4281. /// </returns>
  4282. public float GetMass()
  4283. {
  4284. PhysicsActor pa = PhysicsActor;
  4285. if (pa != null)
  4286. return pa.Mass;
  4287. else
  4288. return 0;
  4289. }
  4290. internal void PushForce(Vector3 impulse)
  4291. {
  4292. if (PhysicsActor != null)
  4293. {
  4294. PhysicsActor.AddForce(impulse,true);
  4295. }
  4296. }
  4297. public void RegisterControlEventsToScript(int controls, int accept, int pass_on, uint Obj_localID, UUID Script_item_UUID)
  4298. {
  4299. SceneObjectPart p = m_scene.GetSceneObjectPart(Obj_localID);
  4300. if (p == null)
  4301. return;
  4302. ControllingClient.SendTakeControls(controls, false, false);
  4303. ControllingClient.SendTakeControls(controls, true, false);
  4304. ScriptControllers obj = new ScriptControllers();
  4305. obj.ignoreControls = ScriptControlled.CONTROL_ZERO;
  4306. obj.eventControls = ScriptControlled.CONTROL_ZERO;
  4307. obj.objectID = p.ParentGroup.UUID;
  4308. obj.itemID = Script_item_UUID;
  4309. if (pass_on == 0 && accept == 0)
  4310. {
  4311. IgnoredControls |= (ScriptControlled)controls;
  4312. obj.ignoreControls = (ScriptControlled)controls;
  4313. }
  4314. if (pass_on == 0 && accept == 1)
  4315. {
  4316. IgnoredControls |= (ScriptControlled)controls;
  4317. obj.ignoreControls = (ScriptControlled)controls;
  4318. obj.eventControls = (ScriptControlled)controls;
  4319. }
  4320. if (pass_on == 1 && accept == 1)
  4321. {
  4322. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  4323. obj.eventControls = (ScriptControlled)controls;
  4324. obj.ignoreControls = ScriptControlled.CONTROL_ZERO;
  4325. }
  4326. lock (scriptedcontrols)
  4327. {
  4328. if (pass_on == 1 && accept == 0)
  4329. {
  4330. IgnoredControls &= ~(ScriptControlled)controls;
  4331. if (scriptedcontrols.ContainsKey(Script_item_UUID))
  4332. scriptedcontrols.Remove(Script_item_UUID);
  4333. }
  4334. else
  4335. {
  4336. scriptedcontrols[Script_item_UUID] = obj;
  4337. }
  4338. }
  4339. ControllingClient.SendTakeControls(controls, pass_on == 1 ? true : false, true);
  4340. }
  4341. public void HandleForceReleaseControls(IClientAPI remoteClient, UUID agentID)
  4342. {
  4343. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  4344. lock (scriptedcontrols)
  4345. {
  4346. scriptedcontrols.Clear();
  4347. }
  4348. ControllingClient.SendTakeControls(int.MaxValue, false, false);
  4349. }
  4350. public void ClearControls()
  4351. {
  4352. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  4353. lock (scriptedcontrols)
  4354. {
  4355. scriptedcontrols.Clear();
  4356. }
  4357. }
  4358. public void UnRegisterSeatControls(UUID obj)
  4359. {
  4360. List<UUID> takers = new List<UUID>();
  4361. foreach (ScriptControllers c in scriptedcontrols.Values)
  4362. {
  4363. if (c.objectID == obj)
  4364. takers.Add(c.itemID);
  4365. }
  4366. foreach (UUID t in takers)
  4367. {
  4368. UnRegisterControlEventsToScript(0, t);
  4369. }
  4370. }
  4371. public void UnRegisterControlEventsToScript(uint Obj_localID, UUID Script_item_UUID)
  4372. {
  4373. ScriptControllers takecontrols;
  4374. lock (scriptedcontrols)
  4375. {
  4376. if (scriptedcontrols.TryGetValue(Script_item_UUID, out takecontrols))
  4377. {
  4378. ScriptControlled sctc = takecontrols.eventControls;
  4379. ControllingClient.SendTakeControls((int)sctc, false, false);
  4380. ControllingClient.SendTakeControls((int)sctc, true, false);
  4381. scriptedcontrols.Remove(Script_item_UUID);
  4382. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  4383. foreach (ScriptControllers scData in scriptedcontrols.Values)
  4384. {
  4385. IgnoredControls |= scData.ignoreControls;
  4386. }
  4387. }
  4388. }
  4389. }
  4390. private void SendControlsToScripts(uint flags)
  4391. {
  4392. // Notify the scripts only after calling UpdateMovementAnimations(), so that if a script
  4393. // (e.g., a walking script) checks which animation is active it will be the correct animation.
  4394. lock (scriptedcontrols)
  4395. {
  4396. if (scriptedcontrols.Count <= 0)
  4397. return;
  4398. ScriptControlled allflags = ScriptControlled.CONTROL_ZERO;
  4399. if (MouseDown)
  4400. {
  4401. allflags = LastCommands & (ScriptControlled.CONTROL_ML_LBUTTON | ScriptControlled.CONTROL_LBUTTON);
  4402. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_UP) != 0 || (flags & unchecked((uint)AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_UP)) != 0)
  4403. {
  4404. allflags = ScriptControlled.CONTROL_ZERO;
  4405. MouseDown = true;
  4406. }
  4407. }
  4408. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_DOWN) != 0)
  4409. {
  4410. allflags |= ScriptControlled.CONTROL_ML_LBUTTON;
  4411. MouseDown = true;
  4412. }
  4413. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN) != 0)
  4414. {
  4415. allflags |= ScriptControlled.CONTROL_LBUTTON;
  4416. MouseDown = true;
  4417. }
  4418. // find all activated controls, whether the scripts are interested in them or not
  4419. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_AT_POS) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS) != 0)
  4420. {
  4421. allflags |= ScriptControlled.CONTROL_FWD;
  4422. }
  4423. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_NEG) != 0)
  4424. {
  4425. allflags |= ScriptControlled.CONTROL_BACK;
  4426. }
  4427. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_POS) != 0)
  4428. {
  4429. allflags |= ScriptControlled.CONTROL_UP;
  4430. }
  4431. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG) != 0)
  4432. {
  4433. allflags |= ScriptControlled.CONTROL_DOWN;
  4434. }
  4435. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_POS) != 0)
  4436. {
  4437. allflags |= ScriptControlled.CONTROL_LEFT;
  4438. }
  4439. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_NEG) != 0)
  4440. {
  4441. allflags |= ScriptControlled.CONTROL_RIGHT;
  4442. }
  4443. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG) != 0)
  4444. {
  4445. allflags |= ScriptControlled.CONTROL_ROT_RIGHT;
  4446. }
  4447. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS) != 0)
  4448. {
  4449. allflags |= ScriptControlled.CONTROL_ROT_LEFT;
  4450. }
  4451. // optimization; we have to check per script, but if nothing is pressed and nothing changed, we can skip that
  4452. if (allflags != ScriptControlled.CONTROL_ZERO || allflags != LastCommands)
  4453. {
  4454. foreach (KeyValuePair<UUID, ScriptControllers> kvp in scriptedcontrols)
  4455. {
  4456. UUID scriptUUID = kvp.Key;
  4457. ScriptControllers scriptControlData = kvp.Value;
  4458. ScriptControlled localHeld = allflags & scriptControlData.eventControls; // the flags interesting for us
  4459. ScriptControlled localLast = LastCommands & scriptControlData.eventControls; // the activated controls in the last cycle
  4460. ScriptControlled localChange = localHeld ^ localLast; // the changed bits
  4461. if (localHeld != ScriptControlled.CONTROL_ZERO || localChange != ScriptControlled.CONTROL_ZERO)
  4462. {
  4463. // only send if still pressed or just changed
  4464. m_scene.EventManager.TriggerControlEvent(scriptUUID, UUID, (uint)localHeld, (uint)localChange);
  4465. }
  4466. }
  4467. }
  4468. LastCommands = allflags;
  4469. }
  4470. }
  4471. internal static AgentManager.ControlFlags RemoveIgnoredControls(AgentManager.ControlFlags flags, ScriptControlled ignored)
  4472. {
  4473. if (ignored == ScriptControlled.CONTROL_ZERO)
  4474. return flags;
  4475. if ((ignored & ScriptControlled.CONTROL_BACK) != 0)
  4476. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG | AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_NEG);
  4477. if ((ignored & ScriptControlled.CONTROL_FWD) != 0)
  4478. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS | AgentManager.ControlFlags.AGENT_CONTROL_AT_POS);
  4479. if ((ignored & ScriptControlled.CONTROL_DOWN) != 0)
  4480. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG | AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG);
  4481. if ((ignored & ScriptControlled.CONTROL_UP) != 0)
  4482. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_POS | AgentManager.ControlFlags.AGENT_CONTROL_UP_POS);
  4483. if ((ignored & ScriptControlled.CONTROL_LEFT) != 0)
  4484. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS | AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_POS);
  4485. if ((ignored & ScriptControlled.CONTROL_RIGHT) != 0)
  4486. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_NEG | AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG);
  4487. if ((ignored & ScriptControlled.CONTROL_ROT_LEFT) != 0)
  4488. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG);
  4489. if ((ignored & ScriptControlled.CONTROL_ROT_RIGHT) != 0)
  4490. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS);
  4491. if ((ignored & ScriptControlled.CONTROL_ML_LBUTTON) != 0)
  4492. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_DOWN);
  4493. if ((ignored & ScriptControlled.CONTROL_LBUTTON) != 0)
  4494. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_UP | AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN);
  4495. //DIR_CONTROL_FLAG_FORWARD = AgentManager.ControlFlags.AGENT_CONTROL_AT_POS,
  4496. //DIR_CONTROL_FLAG_BACK = AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG,
  4497. //DIR_CONTROL_FLAG_LEFT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS,
  4498. //DIR_CONTROL_FLAG_RIGHT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG,
  4499. //DIR_CONTROL_FLAG_UP = AgentManager.ControlFlags.AGENT_CONTROL_UP_POS,
  4500. //DIR_CONTROL_FLAG_DOWN = AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG,
  4501. //DIR_CONTROL_FLAG_DOWN_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG
  4502. return flags;
  4503. }
  4504. private void ReprioritizeUpdates()
  4505. {
  4506. if (Scene.IsReprioritizationEnabled && Scene.UpdatePrioritizationScheme != UpdatePrioritizationSchemes.Time)
  4507. {
  4508. lock (m_reprioritization_timer)
  4509. {
  4510. if (!m_reprioritizing)
  4511. m_reprioritization_timer.Enabled = m_reprioritizing = true;
  4512. else
  4513. m_reprioritization_called = true;
  4514. }
  4515. }
  4516. }
  4517. private void Reprioritize(object sender, ElapsedEventArgs e)
  4518. {
  4519. ControllingClient.ReprioritizeUpdates();
  4520. lock (m_reprioritization_timer)
  4521. {
  4522. m_reprioritization_timer.Enabled = m_reprioritizing = m_reprioritization_called;
  4523. m_reprioritization_called = false;
  4524. }
  4525. }
  4526. private void CheckLandingPoint(ref Vector3 pos)
  4527. {
  4528. // Never constrain lures
  4529. if ((TeleportFlags & TeleportFlags.ViaLure) != 0)
  4530. return;
  4531. if (m_scene.RegionInfo.EstateSettings.AllowDirectTeleport)
  4532. return;
  4533. ILandObject land = m_scene.LandChannel.GetLandObject(pos.X, pos.Y);
  4534. if (land.LandData.LandingType == (byte)LandingType.LandingPoint &&
  4535. land.LandData.UserLocation != Vector3.Zero &&
  4536. land.LandData.OwnerID != m_uuid &&
  4537. (!m_scene.Permissions.IsGod(m_uuid)) &&
  4538. (!m_scene.RegionInfo.EstateSettings.IsEstateManagerOrOwner(m_uuid)))
  4539. {
  4540. float curr = Vector3.Distance(AbsolutePosition, pos);
  4541. if (Vector3.Distance(land.LandData.UserLocation, pos) < curr)
  4542. pos = land.LandData.UserLocation;
  4543. else
  4544. ControllingClient.SendAlertMessage("Can't teleport closer to destination");
  4545. }
  4546. }
  4547. private void CheckAndAdjustTelehub(SceneObjectGroup telehub, ref Vector3 pos)
  4548. {
  4549. if ((m_teleportFlags & (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID)) ==
  4550. (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID) ||
  4551. (m_scene.TelehubAllowLandmarks == true ? false : ((m_teleportFlags & TeleportFlags.ViaLandmark) != 0 )) ||
  4552. (m_teleportFlags & TeleportFlags.ViaLocation) != 0 ||
  4553. (m_teleportFlags & Constants.TeleportFlags.ViaHGLogin) != 0)
  4554. {
  4555. if (GodLevel < 200 &&
  4556. ((!m_scene.Permissions.IsGod(m_uuid) &&
  4557. !m_scene.RegionInfo.EstateSettings.IsEstateManagerOrOwner(m_uuid)) ||
  4558. (m_teleportFlags & TeleportFlags.ViaLocation) != 0 ||
  4559. (m_teleportFlags & Constants.TeleportFlags.ViaHGLogin) != 0))
  4560. {
  4561. SpawnPoint[] spawnPoints = m_scene.RegionInfo.RegionSettings.SpawnPoints().ToArray();
  4562. if (spawnPoints.Length == 0)
  4563. {
  4564. pos.X = 128.0f;
  4565. pos.Y = 128.0f;
  4566. return;
  4567. }
  4568. int index;
  4569. bool selected = false;
  4570. switch (m_scene.SpawnPointRouting)
  4571. {
  4572. case "random":
  4573. if (spawnPoints.Length == 0)
  4574. return;
  4575. do
  4576. {
  4577. index = Util.RandomClass.Next(spawnPoints.Length - 1);
  4578. Vector3 spawnPosition = spawnPoints[index].GetLocation(
  4579. telehub.AbsolutePosition,
  4580. telehub.GroupRotation
  4581. );
  4582. // SpawnPoint sp = spawnPoints[index];
  4583. ILandObject land = m_scene.LandChannel.GetLandObject(spawnPosition.X, spawnPosition.Y);
  4584. if (land == null || land.IsEitherBannedOrRestricted(UUID))
  4585. selected = false;
  4586. else
  4587. selected = true;
  4588. } while ( selected == false);
  4589. pos = spawnPoints[index].GetLocation(
  4590. telehub.AbsolutePosition,
  4591. telehub.GroupRotation
  4592. );
  4593. return;
  4594. case "sequence":
  4595. do
  4596. {
  4597. index = m_scene.SpawnPoint();
  4598. Vector3 spawnPosition = spawnPoints[index].GetLocation(
  4599. telehub.AbsolutePosition,
  4600. telehub.GroupRotation
  4601. );
  4602. // SpawnPoint sp = spawnPoints[index];
  4603. ILandObject land = m_scene.LandChannel.GetLandObject(spawnPosition.X, spawnPosition.Y);
  4604. if (land == null || land.IsEitherBannedOrRestricted(UUID))
  4605. selected = false;
  4606. else
  4607. selected = true;
  4608. } while (selected == false);
  4609. pos = spawnPoints[index].GetLocation(telehub.AbsolutePosition, telehub.GroupRotation);
  4610. ;
  4611. return;
  4612. default:
  4613. case "closest":
  4614. float distance = 9999;
  4615. int closest = -1;
  4616. for (int i = 0; i < spawnPoints.Length; i++)
  4617. {
  4618. Vector3 spawnPosition = spawnPoints[i].GetLocation(
  4619. telehub.AbsolutePosition,
  4620. telehub.GroupRotation
  4621. );
  4622. Vector3 offset = spawnPosition - pos;
  4623. float d = Vector3.Mag(offset);
  4624. if (d >= distance)
  4625. continue;
  4626. ILandObject land = m_scene.LandChannel.GetLandObject(spawnPosition.X, spawnPosition.Y);
  4627. if (land == null)
  4628. continue;
  4629. if (land.IsEitherBannedOrRestricted(UUID))
  4630. continue;
  4631. distance = d;
  4632. closest = i;
  4633. }
  4634. if (closest == -1)
  4635. return;
  4636. pos = spawnPoints[closest].GetLocation(telehub.AbsolutePosition, telehub.GroupRotation);
  4637. return;
  4638. }
  4639. }
  4640. }
  4641. }
  4642. // Modify landing point based on possible banning, telehubs or parcel restrictions.
  4643. private void CheckAndAdjustLandingPoint(ref Vector3 pos)
  4644. {
  4645. string reason;
  4646. // Honor bans
  4647. if (!m_scene.TestLandRestrictions(UUID, out reason, ref pos.X, ref pos.Y))
  4648. return;
  4649. SceneObjectGroup telehub = null;
  4650. if (m_scene.RegionInfo.RegionSettings.TelehubObject != UUID.Zero && (telehub = m_scene.GetSceneObjectGroup(m_scene.RegionInfo.RegionSettings.TelehubObject)) != null)
  4651. {
  4652. if (!m_scene.RegionInfo.EstateSettings.AllowDirectTeleport)
  4653. {
  4654. CheckAndAdjustTelehub(telehub, ref pos);
  4655. return;
  4656. }
  4657. }
  4658. ILandObject land = m_scene.LandChannel.GetLandObject(pos.X, pos.Y);
  4659. if (land != null)
  4660. {
  4661. if (Scene.DebugTeleporting)
  4662. TeleportFlagsDebug();
  4663. // If we come in via login, landmark or map, we want to
  4664. // honor landing points. If we come in via Lure, we want
  4665. // to ignore them.
  4666. if ((m_teleportFlags & (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID)) ==
  4667. (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID) ||
  4668. (m_teleportFlags & TeleportFlags.ViaLandmark) != 0 ||
  4669. (m_teleportFlags & TeleportFlags.ViaLocation) != 0 ||
  4670. (m_teleportFlags & Constants.TeleportFlags.ViaHGLogin) != 0)
  4671. {
  4672. // Don't restrict gods, estate managers, or land owners to
  4673. // the TP point. This behaviour mimics agni.
  4674. if (land.LandData.LandingType == (byte)LandingType.LandingPoint &&
  4675. land.LandData.UserLocation != Vector3.Zero &&
  4676. GodLevel < 200 &&
  4677. ((land.LandData.OwnerID != m_uuid &&
  4678. !m_scene.Permissions.IsGod(m_uuid) &&
  4679. !m_scene.RegionInfo.EstateSettings.IsEstateManagerOrOwner(m_uuid)) ||
  4680. (m_teleportFlags & TeleportFlags.ViaLocation) != 0 ||
  4681. (m_teleportFlags & Constants.TeleportFlags.ViaHGLogin) != 0))
  4682. {
  4683. pos = land.LandData.UserLocation;
  4684. }
  4685. }
  4686. // this is now done in completeMovement for all cases and not just this
  4687. // land.SendLandUpdateToClient(ControllingClient);
  4688. }
  4689. }
  4690. private DetectedObject CreateDetObject(SceneObjectPart obj)
  4691. {
  4692. DetectedObject detobj = new DetectedObject();
  4693. detobj.keyUUID = obj.UUID;
  4694. detobj.nameStr = obj.Name;
  4695. detobj.ownerUUID = obj.OwnerID;
  4696. detobj.posVector = obj.AbsolutePosition;
  4697. detobj.rotQuat = obj.GetWorldRotation();
  4698. detobj.velVector = obj.Velocity;
  4699. detobj.colliderType = 0;
  4700. detobj.groupUUID = obj.GroupID;
  4701. detobj.linkNumber = 0;
  4702. return detobj;
  4703. }
  4704. private DetectedObject CreateDetObject(ScenePresence av)
  4705. {
  4706. DetectedObject detobj = new DetectedObject();
  4707. detobj.keyUUID = av.UUID;
  4708. detobj.nameStr = av.ControllingClient.Name;
  4709. detobj.ownerUUID = av.UUID;
  4710. detobj.posVector = av.AbsolutePosition;
  4711. detobj.rotQuat = av.Rotation;
  4712. detobj.velVector = av.Velocity;
  4713. detobj.colliderType = 0;
  4714. detobj.groupUUID = av.ControllingClient.ActiveGroupId;
  4715. detobj.linkNumber = 0;
  4716. return detobj;
  4717. }
  4718. private DetectedObject CreateDetObjectForGround()
  4719. {
  4720. DetectedObject detobj = new DetectedObject();
  4721. detobj.keyUUID = UUID.Zero;
  4722. detobj.nameStr = "";
  4723. detobj.ownerUUID = UUID.Zero;
  4724. detobj.posVector = AbsolutePosition;
  4725. detobj.rotQuat = Quaternion.Identity;
  4726. detobj.velVector = Vector3.Zero;
  4727. detobj.colliderType = 0;
  4728. detobj.groupUUID = UUID.Zero;
  4729. detobj.linkNumber = 0;
  4730. return detobj;
  4731. }
  4732. private ColliderArgs CreateColliderArgs(SceneObjectPart dest, List<uint> colliders)
  4733. {
  4734. ColliderArgs colliderArgs = new ColliderArgs();
  4735. List<DetectedObject> colliding = new List<DetectedObject>();
  4736. foreach (uint localId in colliders)
  4737. {
  4738. if (localId == 0)
  4739. continue;
  4740. SceneObjectPart obj = m_scene.GetSceneObjectPart(localId);
  4741. if (obj != null)
  4742. {
  4743. if (!dest.CollisionFilteredOut(obj.UUID, obj.Name))
  4744. colliding.Add(CreateDetObject(obj));
  4745. }
  4746. else
  4747. {
  4748. ScenePresence av = m_scene.GetScenePresence(localId);
  4749. if (av != null && (!av.IsChildAgent))
  4750. {
  4751. if (!dest.CollisionFilteredOut(av.UUID, av.Name))
  4752. colliding.Add(CreateDetObject(av));
  4753. }
  4754. }
  4755. }
  4756. colliderArgs.Colliders = colliding;
  4757. return colliderArgs;
  4758. }
  4759. private delegate void ScriptCollidingNotification(uint localID, ColliderArgs message);
  4760. private void SendCollisionEvent(SceneObjectGroup dest, scriptEvents ev, List<uint> colliders, ScriptCollidingNotification notify)
  4761. {
  4762. ColliderArgs CollidingMessage;
  4763. if (colliders.Count > 0)
  4764. {
  4765. if ((dest.RootPart.ScriptEvents & ev) != 0)
  4766. {
  4767. CollidingMessage = CreateColliderArgs(dest.RootPart, colliders);
  4768. if (CollidingMessage.Colliders.Count > 0)
  4769. notify(dest.RootPart.LocalId, CollidingMessage);
  4770. }
  4771. }
  4772. }
  4773. private void SendLandCollisionEvent(SceneObjectGroup dest, scriptEvents ev, ScriptCollidingNotification notify)
  4774. {
  4775. if ((dest.RootPart.ScriptEvents & ev) != 0)
  4776. {
  4777. ColliderArgs LandCollidingMessage = new ColliderArgs();
  4778. List<DetectedObject> colliding = new List<DetectedObject>();
  4779. colliding.Add(CreateDetObjectForGround());
  4780. LandCollidingMessage.Colliders = colliding;
  4781. notify(dest.RootPart.LocalId, LandCollidingMessage);
  4782. }
  4783. }
  4784. private void RaiseCollisionScriptEvents(Dictionary<uint, ContactPoint> coldata)
  4785. {
  4786. try
  4787. {
  4788. List<uint> thisHitColliders = new List<uint>();
  4789. List<uint> endedColliders = new List<uint>();
  4790. List<uint> startedColliders = new List<uint>();
  4791. List<CollisionForSoundInfo> soundinfolist = new List<CollisionForSoundInfo>();
  4792. CollisionForSoundInfo soundinfo;
  4793. ContactPoint curcontact;
  4794. if (coldata.Count == 0)
  4795. {
  4796. if (m_lastColliders.Count == 0)
  4797. return; // nothing to do
  4798. foreach (uint localID in m_lastColliders)
  4799. {
  4800. endedColliders.Add(localID);
  4801. }
  4802. m_lastColliders.Clear();
  4803. }
  4804. else
  4805. {
  4806. bool candoparcelSound = ParcelAllowThisAvatarSounds;
  4807. foreach (uint id in coldata.Keys)
  4808. {
  4809. thisHitColliders.Add(id);
  4810. if (!m_lastColliders.Contains(id))
  4811. {
  4812. startedColliders.Add(id);
  4813. curcontact = coldata[id];
  4814. if (candoparcelSound && Math.Abs(curcontact.RelativeSpeed) > 0.2)
  4815. {
  4816. soundinfo = new CollisionForSoundInfo();
  4817. soundinfo.colliderID = id;
  4818. soundinfo.position = curcontact.Position;
  4819. soundinfo.relativeVel = curcontact.RelativeSpeed;
  4820. soundinfolist.Add(soundinfo);
  4821. }
  4822. }
  4823. //m_log.Debug("[SCENE PRESENCE]: Collided with:" + localid.ToString() + " at depth of: " + collissionswith[localid].ToString());
  4824. }
  4825. // calculate things that ended colliding
  4826. foreach (uint localID in m_lastColliders)
  4827. {
  4828. if (!thisHitColliders.Contains(localID))
  4829. {
  4830. endedColliders.Add(localID);
  4831. }
  4832. }
  4833. //add the items that started colliding this time to the last colliders list.
  4834. foreach (uint localID in startedColliders)
  4835. {
  4836. m_lastColliders.Add(localID);
  4837. }
  4838. // remove things that ended colliding from the last colliders list
  4839. foreach (uint localID in endedColliders)
  4840. {
  4841. m_lastColliders.Remove(localID);
  4842. }
  4843. if (soundinfolist.Count > 0)
  4844. CollisionSounds.AvatarCollisionSound(this, soundinfolist);
  4845. }
  4846. foreach (SceneObjectGroup att in GetAttachments())
  4847. {
  4848. SendCollisionEvent(att, scriptEvents.collision_start, startedColliders, m_scene.EventManager.TriggerScriptCollidingStart);
  4849. SendCollisionEvent(att, scriptEvents.collision , m_lastColliders , m_scene.EventManager.TriggerScriptColliding);
  4850. SendCollisionEvent(att, scriptEvents.collision_end , endedColliders , m_scene.EventManager.TriggerScriptCollidingEnd);
  4851. if (startedColliders.Contains(0))
  4852. SendLandCollisionEvent(att, scriptEvents.land_collision_start, m_scene.EventManager.TriggerScriptLandCollidingStart);
  4853. if (m_lastColliders.Contains(0))
  4854. SendLandCollisionEvent(att, scriptEvents.land_collision, m_scene.EventManager.TriggerScriptLandColliding);
  4855. if (endedColliders.Contains(0))
  4856. SendLandCollisionEvent(att, scriptEvents.land_collision_end, m_scene.EventManager.TriggerScriptLandCollidingEnd);
  4857. }
  4858. }
  4859. finally
  4860. {
  4861. m_collisionEventFlag = false;
  4862. }
  4863. }
  4864. private void TeleportFlagsDebug() {
  4865. // Some temporary debugging help to show all the TeleportFlags we have...
  4866. bool HG = false;
  4867. if((m_teleportFlags & TeleportFlags.ViaHGLogin) == TeleportFlags.ViaHGLogin)
  4868. HG = true;
  4869. m_log.InfoFormat("[SCENE PRESENCE]: TELEPORT ******************");
  4870. uint i = 0u;
  4871. for (int x = 0; x <= 30 ; x++, i = 1u << x)
  4872. {
  4873. i = 1u << x;
  4874. if((m_teleportFlags & (TeleportFlags)i) == (TeleportFlags)i)
  4875. if (HG == false)
  4876. m_log.InfoFormat("[SCENE PRESENCE]: Teleport Flags include {0}", ((TeleportFlags) i).ToString());
  4877. else
  4878. m_log.InfoFormat("[SCENE PRESENCE]: HG Teleport Flags include {0}", ((TeleportFlags)i).ToString());
  4879. }
  4880. m_log.InfoFormat("[SCENE PRESENCE]: TELEPORT ******************");
  4881. }
  4882. private void parcelGodCheck(UUID currentParcelID, bool isGod)
  4883. {
  4884. List<ScenePresence> allpresences = m_scene.GetScenePresences();
  4885. foreach (ScenePresence p in allpresences)
  4886. {
  4887. if (p.IsDeleted || p.IsChildAgent || p == this || p.ControllingClient == null || !p.ControllingClient.IsActive)
  4888. continue;
  4889. if (p.ParcelHideThisAvatar && p.currentParcelUUID != currentParcelID)
  4890. {
  4891. if (isGod)
  4892. p.SendViewTo(this);
  4893. else
  4894. p.SendKillTo(this);
  4895. }
  4896. }
  4897. }
  4898. private void ParcelCrossCheck(UUID currentParcelID,UUID previusParcelID,
  4899. bool currentParcelHide, bool previusParcelHide, bool oldhide,bool check)
  4900. {
  4901. List<ScenePresence> killsToSendto = new List<ScenePresence>();
  4902. List<ScenePresence> killsToSendme = new List<ScenePresence>();
  4903. List<ScenePresence> viewsToSendto = new List<ScenePresence>();
  4904. List<ScenePresence> viewsToSendme = new List<ScenePresence>();
  4905. List<ScenePresence> allpresences = null;
  4906. if (IsInTransit || IsChildAgent)
  4907. return;
  4908. if (check)
  4909. {
  4910. // check is relative to current parcel only
  4911. if (currentParcelUUID == null || oldhide == currentParcelHide)
  4912. return;
  4913. allpresences = m_scene.GetScenePresences();
  4914. if (oldhide)
  4915. { // where private
  4916. foreach (ScenePresence p in allpresences)
  4917. {
  4918. if (p.IsDeleted || p == this || p.ControllingClient == null || !p.ControllingClient.IsActive)
  4919. continue;
  4920. // those on not on parcel see me
  4921. if (currentParcelID != p.currentParcelUUID)
  4922. {
  4923. viewsToSendto.Add(p); // they see me
  4924. }
  4925. }
  4926. } // where private end
  4927. else
  4928. { // where public
  4929. foreach (ScenePresence p in allpresences)
  4930. {
  4931. if (p.IsDeleted || p == this || p.ControllingClient == null || !p.ControllingClient.IsActive)
  4932. continue;
  4933. // those not on parcel dont see me
  4934. if (currentParcelID != p.currentParcelUUID && p.GodLevel < 200)
  4935. {
  4936. killsToSendto.Add(p); // they dont see me
  4937. }
  4938. }
  4939. } // where public end
  4940. allpresences.Clear();
  4941. }
  4942. else
  4943. {
  4944. if (currentParcelHide)
  4945. {
  4946. // now on a private parcel
  4947. allpresences = m_scene.GetScenePresences();
  4948. if (previusParcelHide && previusParcelID != UUID.Zero)
  4949. {
  4950. foreach (ScenePresence p in allpresences)
  4951. {
  4952. if (p.IsDeleted || p == this || p.ControllingClient == null || !p.ControllingClient.IsActive)
  4953. continue;
  4954. // only those on previus parcel need receive kills
  4955. if (previusParcelID == p.currentParcelUUID)
  4956. {
  4957. if(p.GodLevel < 200)
  4958. killsToSendto.Add(p); // they dont see me
  4959. if(GodLevel < 200)
  4960. killsToSendme.Add(p); // i dont see them
  4961. }
  4962. // only those on new parcel need see
  4963. if (currentParcelID == p.currentParcelUUID)
  4964. {
  4965. viewsToSendto.Add(p); // they see me
  4966. viewsToSendme.Add(p); // i see them
  4967. }
  4968. }
  4969. }
  4970. else
  4971. {
  4972. //was on a public area
  4973. allpresences = m_scene.GetScenePresences();
  4974. foreach (ScenePresence p in allpresences)
  4975. {
  4976. if (p.IsDeleted || p == this || p.ControllingClient == null || !p.ControllingClient.IsActive)
  4977. continue;
  4978. // those not on new parcel dont see me
  4979. if (currentParcelID != p.currentParcelUUID && p.GodLevel < 200)
  4980. {
  4981. killsToSendto.Add(p); // they dont see me
  4982. }
  4983. else
  4984. {
  4985. viewsToSendme.Add(p); // i see those on it
  4986. }
  4987. }
  4988. }
  4989. allpresences.Clear();
  4990. } // now on a private parcel end
  4991. else
  4992. {
  4993. // now on public parcel
  4994. if (previusParcelHide && previusParcelID != UUID.Zero)
  4995. {
  4996. // was on private area
  4997. allpresences = m_scene.GetScenePresences();
  4998. foreach (ScenePresence p in allpresences)
  4999. {
  5000. if (p.IsDeleted || p == this || p.ControllingClient == null || !p.ControllingClient.IsActive)
  5001. continue;
  5002. // only those old parcel need kills
  5003. if (previusParcelID == p.currentParcelUUID && GodLevel < 200)
  5004. {
  5005. killsToSendme.Add(p); // i dont see them
  5006. }
  5007. else
  5008. {
  5009. viewsToSendto.Add(p); // they see me
  5010. }
  5011. }
  5012. }
  5013. else
  5014. return; // was on a public area also
  5015. } // now on public parcel end
  5016. }
  5017. // send the things
  5018. if (killsToSendto.Count > 0)
  5019. {
  5020. foreach (ScenePresence p in killsToSendto)
  5021. {
  5022. m_log.Debug("[AVATAR]: killTo: " + Lastname + " " + p.Lastname);
  5023. SendKillTo(p);
  5024. }
  5025. }
  5026. if (killsToSendme.Count > 0)
  5027. {
  5028. foreach (ScenePresence p in killsToSendme)
  5029. {
  5030. m_log.Debug("[AVATAR]: killToMe: " + Lastname + " " + p.Lastname);
  5031. p.SendKillTo(this);
  5032. }
  5033. }
  5034. if (viewsToSendto.Count > 0)
  5035. {
  5036. foreach (ScenePresence p in viewsToSendto)
  5037. {
  5038. SendViewTo(p);
  5039. }
  5040. }
  5041. if (viewsToSendme.Count > 0 )
  5042. {
  5043. foreach (ScenePresence p in viewsToSendme)
  5044. {
  5045. if (p.IsChildAgent)
  5046. continue;
  5047. // m_log.Debug("[AVATAR]: viewMe: " + Lastname + "<-" + p.Lastname);
  5048. p.SendViewTo(this);
  5049. }
  5050. }
  5051. }
  5052. public void HasMovedAway(bool nearRegion)
  5053. {
  5054. if (nearRegion)
  5055. {
  5056. if (Scene.AttachmentsModule != null)
  5057. Scene.AttachmentsModule.DeleteAttachmentsFromScene(this, true);
  5058. if (!ParcelHideThisAvatar || GodLevel >= 200)
  5059. return;
  5060. List<ScenePresence> allpresences = m_scene.GetScenePresences();
  5061. foreach (ScenePresence p in allpresences)
  5062. {
  5063. if (p.IsDeleted || p == this || p.IsChildAgent || p.ControllingClient == null || !p.ControllingClient.IsActive)
  5064. continue;
  5065. if (p.currentParcelUUID == m_currentParcelUUID)
  5066. {
  5067. p.SendKillTo(this);
  5068. }
  5069. }
  5070. }
  5071. else
  5072. {
  5073. List<ScenePresence> allpresences = m_scene.GetScenePresences();
  5074. foreach (ScenePresence p in allpresences)
  5075. {
  5076. if (p == this)
  5077. continue;
  5078. SendKillTo(p);
  5079. if (!p.IsChildAgent)
  5080. p.SendKillTo(this);
  5081. }
  5082. if (Scene.AttachmentsModule != null)
  5083. Scene.AttachmentsModule.DeleteAttachmentsFromScene(this, true);
  5084. }
  5085. }
  5086. // kill with attachs root kills
  5087. public void SendKillTo(ScenePresence p)
  5088. {
  5089. List<uint> ids = new List<uint>(m_attachments.Count + 1);
  5090. foreach (SceneObjectGroup sog in m_attachments)
  5091. {
  5092. ids.Add(sog.RootPart.LocalId);
  5093. }
  5094. ids.Add(LocalId);
  5095. p.ControllingClient.SendKillObject(ids);
  5096. }
  5097. /*
  5098. // kill with hack
  5099. public void SendKillTo(ScenePresence p)
  5100. {
  5101. foreach (SceneObjectGroup sog in m_attachments)
  5102. p.ControllingClient.SendPartFullUpdate(sog.RootPart, LocalId + 1);
  5103. p.ControllingClient.SendKillObject(new List<uint> { LocalId });
  5104. }
  5105. */
  5106. public void SendViewTo(ScenePresence p)
  5107. {
  5108. SendAvatarDataToAgentNF(p);
  5109. SendAppearanceToAgent(p);
  5110. if (Animator != null)
  5111. Animator.SendAnimPackToClient(p.ControllingClient);
  5112. SendAttachmentsToAgentNF(p);
  5113. }
  5114. public void SetAnimationOverride(string animState, UUID animID)
  5115. {
  5116. Overrides.SetOverride(animState, animID);
  5117. // Animator.SendAnimPack();
  5118. Animator.ForceUpdateMovementAnimations();
  5119. }
  5120. public UUID GetAnimationOverride(string animState)
  5121. {
  5122. return Overrides.GetOverriddenAnimation(animState);
  5123. }
  5124. }
  5125. }