ScenePresence.cs 277 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158
  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, IDisposable
  73. {
  74. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  75. // ~ScenePresence()
  76. // {
  77. // m_log.DebugFormat("[SCENE PRESENCE]: Destructor called on {0}", Name);
  78. // }
  79. public int EnvironmentVersion = -1;
  80. private ViewerEnvironment m_environment = null;
  81. public ViewerEnvironment Environment
  82. {
  83. get
  84. {
  85. return m_environment;
  86. }
  87. set
  88. {
  89. m_environment = value;
  90. if (value == null)
  91. EnvironmentVersion = -1;
  92. else
  93. {
  94. if(EnvironmentVersion <= 0)
  95. EnvironmentVersion = 0x7000000 | Util.RandomClass.Next();
  96. else
  97. ++EnvironmentVersion;
  98. m_environment.version = EnvironmentVersion;
  99. }
  100. }
  101. }
  102. public void TriggerScenePresenceUpdated()
  103. {
  104. if (m_scene != null)
  105. m_scene.EventManager.TriggerScenePresenceUpdated(this);
  106. }
  107. public bool IsNPC { get; private set; }
  108. // simple yes or no isGOD from god level >= 200
  109. // should only be set by GodController
  110. // we have two to suport legacy behaviour
  111. // IsViewerUIGod was controlled by viewer in older versions
  112. // IsGod may now be also controled by viewer acording to options
  113. public bool IsViewerUIGod { get; set; }
  114. public bool IsGod { get; set; }
  115. private bool m_gotRegionHandShake = false;
  116. private PresenceType m_presenceType;
  117. public PresenceType PresenceType
  118. {
  119. get {return m_presenceType;}
  120. private set
  121. {
  122. m_presenceType = value;
  123. IsNPC = (m_presenceType == PresenceType.Npc);
  124. }
  125. }
  126. private ScenePresenceStateMachine m_stateMachine;
  127. /// <summary>
  128. /// The current state of this presence. Governs only the existence lifecycle. See ScenePresenceStateMachine
  129. /// for more details.
  130. /// </summary>
  131. public ScenePresenceState LifecycleState
  132. {
  133. get
  134. {
  135. return m_stateMachine.GetState();
  136. }
  137. set
  138. {
  139. m_stateMachine.SetState(value);
  140. }
  141. }
  142. /// <summary>
  143. /// This exists to prevent race conditions between two CompleteMovement threads if the simulator is slow and
  144. /// the viewer fires these in quick succession.
  145. /// </summary>
  146. /// <remarks>
  147. /// TODO: The child -> agent transition should be folded into LifecycleState and the CompleteMovement
  148. /// regulation done there.
  149. /// </remarks>
  150. private readonly object m_completeMovementLock = new object();
  151. // private static readonly byte[] DEFAULT_TEXTURE = AvatarAppearance.GetDefaultTexture().GetBytes();
  152. private static readonly Array DIR_CONTROL_FLAGS = Enum.GetValues(typeof(Dir_ControlFlags));
  153. private static readonly Vector3 HEAD_ADJUSTMENT = new Vector3(0f, 0f, 0.3f);
  154. /// <summary>
  155. /// Experimentally determined "fudge factor" to make sit-target positions
  156. /// the same as in SecondLife. Fudge factor was tested for 36 different
  157. /// test cases including prims of type box, sphere, cylinder, and torus,
  158. /// with varying parameters for sit target location, prim size, prim
  159. /// rotation, prim cut, prim twist, prim taper, and prim shear. See mantis
  160. /// issue #1716
  161. /// </summary>
  162. public static readonly Vector3 SIT_TARGET_ADJUSTMENT = new Vector3(0.0f, 0.0f, 0.4f);
  163. public bool LegacySitOffsets = true;
  164. /// <summary>
  165. /// Movement updates for agents in neighboring regions are sent directly to clients.
  166. /// This value only affects how often agent positions are sent to neighbor regions
  167. /// for things such as distance-based update prioritization
  168. /// this are the square of real distances
  169. /// </summary>
  170. public static readonly float MOVEMENT = .25f;
  171. public static readonly float SIGNIFICANT_MOVEMENT = 16.0f;
  172. public static readonly float CHILDUPDATES_MOVEMENT = 100.0f;
  173. public static readonly float CHILDAGENTSCHECK_MOVEMENT = 1024f; // 32m
  174. public static readonly float CHILDUPDATES_TIME = 2000f; // min time between child updates (ms)
  175. private UUID m_previusParcelUUID = UUID.Zero;
  176. private UUID m_currentParcelUUID = UUID.Zero;
  177. private bool m_previusParcelHide = false;
  178. private bool m_currentParcelHide = false;
  179. private readonly object parcelLock = new Object();
  180. public double ParcelDwellTickMS;
  181. public UUID currentParcelUUID
  182. {
  183. get { return m_currentParcelUUID; }
  184. set
  185. {
  186. lock (parcelLock)
  187. {
  188. bool oldhide = m_currentParcelHide;
  189. bool checksame = true;
  190. if (value != m_currentParcelUUID)
  191. {
  192. ParcelDwellTickMS = Util.GetTimeStampMS();
  193. m_previusParcelHide = m_currentParcelHide;
  194. m_previusParcelUUID = m_currentParcelUUID;
  195. checksame = false;
  196. }
  197. m_currentParcelUUID = value;
  198. m_currentParcelHide = false;
  199. ILandObject land = m_scene.LandChannel.GetLandObject(AbsolutePosition.X, AbsolutePosition.Y);
  200. if (land != null)
  201. m_currentParcelHide = !land.LandData.SeeAVs;
  202. if (m_previusParcelUUID != UUID.Zero || checksame)
  203. ParcelCrossCheck(m_currentParcelUUID, m_previusParcelUUID, m_currentParcelHide, m_previusParcelHide, oldhide,checksame);
  204. }
  205. }
  206. }
  207. public void sitSOGmoved()
  208. {
  209. /*
  210. if (IsDeleted || !IsSatOnObject)
  211. //what me? nahh
  212. return;
  213. if (IsInTransit)
  214. return;
  215. ILandObject land = m_scene.LandChannel.GetLandObject(AbsolutePosition.X, AbsolutePosition.Y);
  216. if (land == null)
  217. return; //??
  218. UUID parcelID = land.LandData.GlobalID;
  219. if (m_currentParcelUUID != parcelID)
  220. currentParcelUUID = parcelID;
  221. */
  222. }
  223. public bool ParcelAllowThisAvatarSounds
  224. {
  225. get
  226. {
  227. try
  228. {
  229. lock (parcelLock)
  230. {
  231. ILandObject land = m_scene.LandChannel.GetLandObject(AbsolutePosition.X, AbsolutePosition.Y);
  232. if (land == null)
  233. return true;
  234. if (land.LandData.AnyAVSounds)
  235. return true;
  236. if (!land.LandData.GroupAVSounds)
  237. return false;
  238. return ControllingClient.IsGroupMember(land.LandData.GroupID);
  239. }
  240. }
  241. catch
  242. {
  243. return true;
  244. }
  245. }
  246. }
  247. public bool ParcelHideThisAvatar
  248. {
  249. get
  250. {
  251. return m_currentParcelHide;
  252. }
  253. }
  254. /// <value>
  255. /// The animator for this avatar
  256. /// </value>
  257. public ScenePresenceAnimator Animator { get; private set; }
  258. /// <value>
  259. /// Server Side Animation Override
  260. /// </value>
  261. public MovementAnimationOverrides Overrides { get; private set; }
  262. public String sitAnimation = "SIT";
  263. /// <summary>
  264. /// Attachments recorded on this avatar.
  265. /// </summary>
  266. /// <remarks>
  267. /// TODO: For some reason, we effectively have a list both here and in Appearance. Need to work out if this is
  268. /// necessary.
  269. /// </remarks>
  270. private List<SceneObjectGroup> m_attachments = new List<SceneObjectGroup>();
  271. public Object AttachmentsSyncLock { get; private set; }
  272. private Dictionary<UUID, ScriptControllers> scriptedcontrols = new Dictionary<UUID, ScriptControllers>();
  273. private ScriptControlled IgnoredControls = ScriptControlled.CONTROL_ZERO;
  274. private ScriptControlled LastCommands = ScriptControlled.CONTROL_ZERO;
  275. private bool MouseDown = false;
  276. public Vector3 lastKnownAllowedPosition;
  277. public bool sentMessageAboutRestrictedParcelFlyingDown;
  278. public Vector4 CollisionPlane = Vector4.UnitW;
  279. public Vector4 m_lastCollisionPlane = Vector4.UnitW;
  280. private byte m_lastState;
  281. private Vector3 m_lastPosition;
  282. private Quaternion m_lastRotation;
  283. private Vector3 m_lastVelocity;
  284. private Vector3 m_lastSize = new Vector3(0.45f,0.6f,1.9f);
  285. private int NeedInitialData = 1;
  286. private int m_userFlags;
  287. public int UserFlags
  288. {
  289. get { return m_userFlags; }
  290. }
  291. // Flying
  292. public bool Flying
  293. {
  294. get { return PhysicsActor != null && PhysicsActor.Flying; }
  295. set
  296. {
  297. if(PhysicsActor != null)
  298. PhysicsActor.Flying = value;
  299. }
  300. }
  301. public bool IsColliding
  302. {
  303. get { return PhysicsActor != null && PhysicsActor.IsColliding; }
  304. // We would expect setting IsColliding to be private but it's used by a hack in Scene
  305. set { PhysicsActor.IsColliding = value; }
  306. }
  307. private List<uint> m_lastColliders = new List<uint>();
  308. private bool m_lastLandCollide;
  309. private TeleportFlags m_teleportFlags;
  310. public TeleportFlags TeleportFlags
  311. {
  312. get { return m_teleportFlags; }
  313. set { m_teleportFlags = value; }
  314. }
  315. private uint m_requestedSitTargetID;
  316. private UUID m_requestedSitTargetUUID;
  317. /// <summary>
  318. /// Are we sitting on the ground?
  319. /// </summary>
  320. public bool SitGround { get; private set; }
  321. private SendCoarseLocationsMethod m_sendCoarseLocationsMethod;
  322. //private Vector3 m_requestedSitOffset = new Vector3();
  323. private Vector3 m_LastFinitePos;
  324. private float m_sitAvatarHeight = 2.0f;
  325. private bool m_childUpdatesBusy = false;
  326. private int m_lastChildUpdatesTime;
  327. private int m_lastChildAgentUpdateGodLevel;
  328. private float m_lastChildAgentUpdateDrawDistance;
  329. private float m_lastRegionsDrawDistance;
  330. private Vector3 m_lastChildAgentUpdatePosition;
  331. private Vector3 m_lastChildAgentCheckPosition;
  332. // private Vector3 m_lastChildAgentUpdateCamPosition;
  333. private Vector3 m_lastCameraRayCastCam;
  334. private Vector3 m_lastCameraRayCastPos;
  335. private float m_FOV = 1.04f;
  336. private const int LAND_VELOCITYMAG_MAX = 12;
  337. private const float FLY_ROLL_MAX_RADIANS = 1.1f;
  338. private const float FLY_ROLL_RADIANS_PER_UPDATE = 0.06f;
  339. private const float FLY_ROLL_RESET_RADIANS_PER_UPDATE = 0.02f;
  340. private float m_health = 100f;
  341. private float m_healRate = 1f;
  342. private float m_healRatePerFrame = 0.05f;
  343. private readonly Vector3[] Dir_Vectors = new Vector3[12];
  344. protected int m_reprioritizationLastTime;
  345. protected bool m_reprioritizationBusy;
  346. protected Vector3 m_reprioritizationLastPosition;
  347. protected float m_reprioritizationLastDrawDistance;
  348. private Quaternion m_headrotation = Quaternion.Identity;
  349. //PauPaw:Proper PID Controler for autopilot************
  350. private bool m_movingToTarget;
  351. public bool MovingToTarget
  352. {
  353. get {return m_movingToTarget;}
  354. private set {m_movingToTarget = value; }
  355. }
  356. private Vector3 m_moveToPositionTarget;
  357. public Vector3 MoveToPositionTarget
  358. {
  359. get {return m_moveToPositionTarget;}
  360. private set {m_moveToPositionTarget = value; }
  361. }
  362. private float m_moveToSpeed;
  363. public float MoveToSpeed
  364. {
  365. get {return m_moveToSpeed;}
  366. private set {m_moveToSpeed = value; }
  367. }
  368. private double m_delayedStop = -1.0;
  369. /// <summary>
  370. /// Controls whether an avatar automatically moving to a target will land when it gets there (if flying).
  371. /// </summary>
  372. public bool LandAtTarget { get; private set; }
  373. private bool CameraConstraintActive;
  374. private readonly object m_collisionEventLock = new Object();
  375. private int m_movementAnimationUpdateCounter = 0;
  376. public Vector3 PrevSitOffset { get; set; }
  377. protected AvatarAppearance m_appearance;
  378. public AvatarAppearance Appearance
  379. {
  380. get { return m_appearance; }
  381. set
  382. {
  383. m_appearance = value;
  384. // m_log.DebugFormat("[SCENE PRESENCE]: Set appearance for {0} to {1}", Name, value);
  385. }
  386. }
  387. /// <summary>
  388. /// Copy of the script states while the agent is in transit. This state may
  389. /// need to be placed back in case of transfer fail.
  390. /// </summary>
  391. public List<string> InTransitScriptStates
  392. {
  393. get { return m_InTransitScriptStates; }
  394. private set { m_InTransitScriptStates = value; }
  395. }
  396. private List<string> m_InTransitScriptStates = new List<string>();
  397. /// <summary>
  398. /// Implemented Control Flags
  399. /// </summary>
  400. private enum Dir_ControlFlags:uint
  401. {
  402. DIR_CONTROL_FLAG_FORWARD = AgentManager.ControlFlags.AGENT_CONTROL_AT_POS,
  403. DIR_CONTROL_FLAG_BACK = AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG,
  404. DIR_CONTROL_FLAG_LEFT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS,
  405. DIR_CONTROL_FLAG_RIGHT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG,
  406. DIR_CONTROL_FLAG_UP = AgentManager.ControlFlags.AGENT_CONTROL_UP_POS,
  407. DIR_CONTROL_FLAG_DOWN = AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG,
  408. DIR_CONTROL_FLAG_FORWARD_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS,
  409. DIR_CONTROL_FLAG_BACKWARD_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_NEG,
  410. DIR_CONTROL_FLAG_LEFT_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_POS,
  411. DIR_CONTROL_FLAG_RIGHT_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_NEG,
  412. DIR_CONTROL_FLAG_UP_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_POS,
  413. DIR_CONTROL_FLAG_DOWN_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG
  414. }
  415. /// <summary>
  416. /// Position at which a significant movement was made
  417. /// </summary>
  418. private Vector3 posLastSignificantMove;
  419. private Vector3 posLastMove;
  420. #region For teleports and crossings callbacks
  421. /// <summary>
  422. /// the destination simulator sends ReleaseAgent to this address, for very long range tps, HG.
  423. /// </summary>
  424. private string m_callbackURI; // to remove with v1 support
  425. private string m_newCallbackURI;
  426. /// <summary>
  427. /// Records the region from which this presence originated, if not from login.
  428. /// </summary>
  429. /// <remarks>
  430. /// Also acts as a signal in the teleport V2 process to release UpdateAgent after a viewer has triggered
  431. /// CompleteMovement and made the previous child agent a root agent.
  432. /// </remarks>
  433. private UUID m_originRegionID;
  434. /// <summary>
  435. /// This object is used as a lock before accessing m_originRegionID to make sure that every thread is seeing
  436. /// the very latest value and not using some cached version. Cannot make m_originRegionID itself volatite as
  437. /// it is a value type.
  438. /// </summary>
  439. private readonly object m_originRegionIDAccessLock = new object();
  440. private AutoResetEvent m_updateAgentReceivedAfterTransferEvent = new AutoResetEvent(false);
  441. /// <summary>
  442. /// Used by the entity transfer module to signal when the presence should not be closed because a subsequent
  443. /// teleport is reusing the connection.
  444. /// </summary>
  445. /// <remarks>May be refactored or move somewhere else soon.</remarks>
  446. public bool DoNotCloseAfterTeleport { get; set; }
  447. #endregion
  448. /// <value>
  449. /// Script engines present in the scene
  450. /// </value>
  451. private IScriptModule[] m_scriptEngines;
  452. private enum LandingPointBehavior
  453. {
  454. OS = 1,
  455. SL = 2
  456. }
  457. private readonly LandingPointBehavior m_LandingPointBehavior = LandingPointBehavior.OS;
  458. #region Properties
  459. /// <summary>
  460. /// Physical scene representation of this Avatar.
  461. /// </summary>
  462. PhysicsActor m_physActor;
  463. public PhysicsActor PhysicsActor
  464. {
  465. get
  466. {
  467. return m_physActor;
  468. }
  469. private set
  470. {
  471. m_physActor = value;
  472. }
  473. }
  474. /// <summary>
  475. /// Record user movement inputs.
  476. /// </summary>
  477. public uint MovementFlag { get; private set; }
  478. /// <summary>
  479. /// Is the agent stop control flag currently active?
  480. /// </summary>
  481. public bool AgentControlStopActive { get; private set; }
  482. private bool m_invulnerable = true;
  483. public bool Invulnerable
  484. {
  485. set
  486. {
  487. m_invulnerable = value;
  488. if(value && Health != 100.0f)
  489. Health = 100.0f;
  490. }
  491. get { return m_invulnerable; }
  492. }
  493. public GodController GodController { get; private set; }
  494. private ulong m_rootRegionHandle;
  495. private Vector3 m_rootRegionPosition = new Vector3();
  496. public ulong RegionHandle
  497. {
  498. get { return m_rootRegionHandle; }
  499. private set
  500. {
  501. m_rootRegionHandle = value;
  502. // position rounded to lower multiple of 256m
  503. m_rootRegionPosition.X = (float)((m_rootRegionHandle >> 32) & 0xffffff00);
  504. m_rootRegionPosition.Y = (float)(m_rootRegionHandle & 0xffffff00);
  505. }
  506. }
  507. #region Client Camera
  508. /// <summary>
  509. /// Position of agent's camera in world (region cordinates)
  510. /// </summary>
  511. // protected Vector3 m_lastCameraPosition;
  512. private Vector4 m_lastCameraCollisionPlane = new Vector4(0f, 0f, 0f, 1);
  513. private bool m_doingCamRayCast = false;
  514. public Vector3 CameraPosition { get; set; }
  515. public Quaternion CameraRotation { get; private set; }
  516. // Use these three vectors to figure out what the agent is looking at
  517. // Convert it to a Matrix and/or Quaternion
  518. //
  519. public Vector3 CameraAtAxis { get; set; }
  520. public Vector3 CameraLeftAxis { get; set; }
  521. public Vector3 CameraUpAxis { get; set; }
  522. public Vector3 Lookat
  523. {
  524. get
  525. {
  526. Vector3 a = new Vector3(CameraAtAxis.X, CameraAtAxis.Y, 0);
  527. a.Normalize();
  528. return a;
  529. }
  530. }
  531. #endregion
  532. public string Firstname { get; private set; }
  533. public string Lastname { get; private set; }
  534. public bool m_haveGroupInformation;
  535. public bool m_gotCrossUpdate;
  536. public byte m_crossingFlags;
  537. public string Grouptitle
  538. {
  539. get { return m_groupTitle; }
  540. set { m_groupTitle = value; }
  541. }
  542. private string m_groupTitle;
  543. // Agent's Draw distance.
  544. private float m_drawDistance = 255f;
  545. public float DrawDistance
  546. {
  547. get
  548. {
  549. return m_drawDistance;
  550. }
  551. set
  552. {
  553. m_drawDistance = Util.Clamp(value, 32f, m_scene.MaxDrawDistance);
  554. }
  555. }
  556. public float RegionViewDistance
  557. {
  558. get
  559. {
  560. return Util.Clamp(m_drawDistance + 64f, m_scene.MinRegionViewDistance, m_scene.MaxRegionViewDistance);
  561. }
  562. }
  563. public bool AllowMovement { get; set; }
  564. private bool m_setAlwaysRun;
  565. public bool SetAlwaysRun
  566. {
  567. get
  568. {
  569. if (PhysicsActor != null)
  570. {
  571. return PhysicsActor.SetAlwaysRun;
  572. }
  573. else
  574. {
  575. return m_setAlwaysRun;
  576. }
  577. }
  578. set
  579. {
  580. m_setAlwaysRun = value;
  581. if (PhysicsActor != null)
  582. {
  583. PhysicsActor.SetAlwaysRun = value;
  584. }
  585. }
  586. }
  587. public byte State { get; set; }
  588. private AgentManager.ControlFlags m_AgentControlFlags;
  589. public uint AgentControlFlags
  590. {
  591. get { return (uint)m_AgentControlFlags; }
  592. set { m_AgentControlFlags = (AgentManager.ControlFlags)value; }
  593. }
  594. public IClientAPI ControllingClient { get; set; }
  595. // dead end do not use
  596. public IClientCore ClientView
  597. {
  598. get { return (IClientCore)ControllingClient; }
  599. }
  600. //public UUID COF { get; set; }
  601. // public Vector3 ParentPosition { get; set; }
  602. /// <summary>
  603. /// Position of this avatar relative to the region the avatar is in
  604. /// </summary>
  605. public override Vector3 AbsolutePosition
  606. {
  607. get
  608. {
  609. if (PhysicsActor != null)
  610. {
  611. m_pos = PhysicsActor.Position;
  612. // m_log.DebugFormat(
  613. // "[SCENE PRESENCE]: Set position of {0} in {1} to {2} via getting AbsolutePosition!",
  614. // Name, Scene.Name, m_pos);
  615. }
  616. else
  617. {
  618. // m_log.DebugFormat("[SCENE PRESENCE]: Fetching abs pos where PhysicsActor == null and parent part {0} for {1}", Name, Scene.Name);
  619. // Obtain the correct position of a seated avatar.
  620. // In addition to providing the correct position while
  621. // the avatar is seated, this value will also
  622. // be used as the location to unsit to.
  623. //
  624. // If ParentID is not 0, assume we are a seated avatar
  625. // and we should return the position based on the sittarget
  626. // offset and rotation of the prim we are seated on.
  627. //
  628. // Generally, m_pos will contain the position of the avatar
  629. // in the sim unless the avatar is on a sit target. While
  630. // on a sit target, m_pos will contain the desired offset
  631. // without the parent rotation applied.
  632. if (ParentPart != null)
  633. {
  634. SceneObjectPart rootPart = ParentPart.ParentGroup.RootPart;
  635. // if (sitPart != null)
  636. // return sitPart.AbsolutePosition + (m_pos * sitPart.GetWorldRotation());
  637. if (rootPart != null)
  638. return rootPart.AbsolutePosition + (m_pos * rootPart.GetWorldRotation());
  639. }
  640. }
  641. return m_pos;
  642. }
  643. set
  644. {
  645. // m_log.DebugFormat("[SCENE PRESENCE]: Setting position of {0} to {1} in {2}", Name, value, Scene.Name);
  646. // Util.PrintCallStack();
  647. if (PhysicsActor != null)
  648. {
  649. try
  650. {
  651. PhysicsActor.Position = value;
  652. }
  653. catch (Exception e)
  654. {
  655. m_log.Error("[SCENE PRESENCE]: ABSOLUTE POSITION " + e.Message);
  656. }
  657. }
  658. // Don't update while sitting. The PhysicsActor above is null whilst sitting.
  659. if (ParentID == 0)
  660. m_pos = value;
  661. //m_log.DebugFormat(
  662. // "[ENTITY BASE]: In {0} set AbsolutePosition of {1} to {2}",
  663. // Scene.RegionInfo.RegionName, Name, m_pos);
  664. TriggerScenePresenceUpdated();
  665. }
  666. }
  667. /// <summary>
  668. /// If sitting, returns the offset position from the prim the avatar is sitting on.
  669. /// Otherwise, returns absolute position in the scene.
  670. /// </summary>
  671. public Vector3 OffsetPosition
  672. {
  673. get { return m_pos; }
  674. // Don't remove setter. It's not currently used in core but
  675. // upcoming Avination code needs it.
  676. set
  677. {
  678. // There is no offset position when not seated
  679. if (ParentID == 0)
  680. return;
  681. m_pos = value;
  682. TriggerScenePresenceUpdated();
  683. }
  684. }
  685. /// <summary>
  686. /// Current velocity of the avatar.
  687. /// </summary>
  688. public override Vector3 Velocity
  689. {
  690. get
  691. {
  692. if (PhysicsActor != null)
  693. {
  694. m_velocity = PhysicsActor.Velocity;
  695. // m_log.DebugFormat(
  696. // "[SCENE PRESENCE]: Set velocity {0} for {1} in {2} via getting Velocity!",
  697. // m_velocity, Name, Scene.RegionInfo.RegionName);
  698. }
  699. return m_velocity;
  700. }
  701. set
  702. {
  703. if (PhysicsActor != null)
  704. {
  705. try
  706. {
  707. PhysicsActor.TargetVelocity = value;
  708. }
  709. catch (Exception e)
  710. {
  711. m_log.Error("[SCENE PRESENCE]: VELOCITY " + e.Message);
  712. }
  713. }
  714. m_velocity = value;
  715. // m_log.DebugFormat(
  716. // "[SCENE PRESENCE]: In {0} set velocity of {1} to {2}",
  717. // Scene.RegionInfo.RegionName, Name, m_velocity);
  718. }
  719. }
  720. // requested Velocity for physics engines avatar motors
  721. // only makes sense if there is a physical rep
  722. public Vector3 TargetVelocity
  723. {
  724. get
  725. {
  726. if (PhysicsActor != null)
  727. return PhysicsActor.TargetVelocity;
  728. else
  729. return Vector3.Zero;
  730. }
  731. set
  732. {
  733. if (PhysicsActor != null)
  734. {
  735. try
  736. {
  737. PhysicsActor.TargetVelocity = value;
  738. }
  739. catch (Exception e)
  740. {
  741. m_log.Error("[SCENE PRESENCE]: TARGETVELOCITY " + e.Message);
  742. }
  743. }
  744. }
  745. }
  746. private Quaternion m_bodyRot = Quaternion.Identity;
  747. /// <summary>
  748. /// The rotation of the avatar.
  749. /// </summary>
  750. /// <remarks>
  751. /// If the avatar is not sitting, this is with respect to the world
  752. /// If the avatar is sitting, this is a with respect to the part that it's sitting upon (a local rotation).
  753. /// If you always want the world rotation, use GetWorldRotation()
  754. /// </remarks>
  755. public Quaternion Rotation
  756. {
  757. get
  758. {
  759. return m_bodyRot;
  760. }
  761. set
  762. {
  763. m_bodyRot = value;
  764. if (PhysicsActor != null)
  765. {
  766. try
  767. {
  768. PhysicsActor.Orientation = m_bodyRot;
  769. }
  770. catch (Exception e)
  771. {
  772. m_log.Error("[SCENE PRESENCE]: Orientation " + e.Message);
  773. }
  774. }
  775. // m_log.DebugFormat("[SCENE PRESENCE]: Body rot for {0} set to {1}", Name, m_bodyRot);
  776. }
  777. }
  778. // Used for limited viewer 'fake' user rotations.
  779. private Vector3 m_AngularVelocity = Vector3.Zero;
  780. public Vector3 AngularVelocity
  781. {
  782. get { return m_AngularVelocity; }
  783. }
  784. public bool IsChildAgent { get; set; }
  785. /// <summary>
  786. /// If the avatar is sitting, the local ID of the prim that it's sitting on. If not sitting then zero.
  787. /// </summary>
  788. public uint ParentID { get; set; }
  789. public UUID ParentUUID
  790. {
  791. get { return m_parentUUID; }
  792. set { m_parentUUID = value; }
  793. }
  794. private UUID m_parentUUID = UUID.Zero;
  795. /// <summary>
  796. /// Are we sitting on an object?
  797. /// </summary>
  798. /// <remarks>A more readable way of testing presence sit status than ParentID == 0</remarks>
  799. public bool IsSatOnObject { get { return ParentID != 0; } }
  800. public bool IsSitting { get {return SitGround || IsSatOnObject; }}
  801. /// <summary>
  802. /// If the avatar is sitting, the prim that it's sitting on. If not sitting then null.
  803. /// </summary>
  804. /// <remarks>
  805. /// If you use this property then you must take a reference since another thread could set it to null.
  806. /// </remarks>
  807. public SceneObjectPart ParentPart { get; set; }
  808. public float Health
  809. {
  810. get { return m_health; }
  811. set { m_health = value; }
  812. }
  813. public float HealRate
  814. {
  815. get { return m_healRate; }
  816. set
  817. {
  818. if(value > 100.0f)
  819. m_healRate = 100.0f;
  820. else if (value <= 0.0)
  821. m_healRate = 0.0f;
  822. else
  823. m_healRate = value;
  824. if(Scene != null)
  825. m_healRatePerFrame = m_healRate * Scene.FrameTime;
  826. else
  827. m_healRatePerFrame = 0.05f;
  828. }
  829. }
  830. /// <summary>
  831. /// Gets the world rotation of this presence.
  832. /// </summary>
  833. /// <remarks>
  834. /// Unlike Rotation, this returns the world rotation no matter whether the avatar is sitting on a prim or not.
  835. /// </remarks>
  836. /// <returns></returns>
  837. public Quaternion GetWorldRotation()
  838. {
  839. if (IsSatOnObject)
  840. {
  841. SceneObjectPart sitPart = ParentPart;
  842. if (sitPart != null)
  843. return sitPart.GetWorldRotation() * Rotation;
  844. }
  845. return Rotation;
  846. }
  847. /// <summary>
  848. /// Get velocity relative to the world.
  849. /// </summary>
  850. public Vector3 GetWorldVelocity()
  851. {
  852. SceneObjectPart sitPart = ParentPart;
  853. if (sitPart != null)
  854. return sitPart.ParentGroup.Velocity;
  855. return Velocity;
  856. }
  857. public void AdjustKnownSeeds()
  858. {
  859. Dictionary<ulong, string> seeds;
  860. if (Scene.CapsModule != null)
  861. seeds = Scene.CapsModule.GetChildrenSeeds(UUID);
  862. else
  863. seeds = new Dictionary<ulong, string>();
  864. KnownRegions = seeds;
  865. }
  866. public void DumpKnownRegions()
  867. {
  868. m_log.Info("================ KnownRegions "+Scene.RegionInfo.RegionName+" ================");
  869. foreach (KeyValuePair<ulong, string> kvp in KnownRegions)
  870. {
  871. Util.RegionHandleToRegionLoc(kvp.Key, out uint x, out uint y);
  872. m_log.Info(" >> "+x+", "+y+": "+kvp.Value);
  873. }
  874. }
  875. private bool m_mouseLook;
  876. private bool m_leftButtonDown;
  877. private bool m_inTransit;
  878. /// <summary>
  879. /// This signals whether the presence is in transit between neighbouring regions.
  880. /// </summary>
  881. /// <remarks>
  882. /// It is not set when the presence is teleporting or logging in/out directly to a region.
  883. /// </remarks>
  884. public bool IsInTransit
  885. {
  886. get { return m_inTransit; }
  887. set {
  888. if(value)
  889. {
  890. if (Flying)
  891. m_AgentControlFlags |= AgentManager.ControlFlags.AGENT_CONTROL_FLY;
  892. else
  893. m_AgentControlFlags &= ~AgentManager.ControlFlags.AGENT_CONTROL_FLY;
  894. }
  895. m_inTransit = value;
  896. }
  897. }
  898. // this is is only valid if IsInTransit is true
  899. // only false on HG tps
  900. // used work arounf viewers asking source region about destination user
  901. public bool IsInLocalTransit {get; set; }
  902. /// <summary>
  903. /// Modifier for agent movement if we get an AGENT_CONTROL_STOP whilst walking or running
  904. /// </summary>
  905. /// <remarks>
  906. /// AGENT_CONTRL_STOP comes about if user holds down space key on viewers.
  907. /// </remarks>
  908. private const float AgentControlStopSlowVel = 0.2f;
  909. // velocities
  910. public const float AgentControlNudgeVel = 1.0f; // setting this diferent from normal as no effect currently
  911. public const float AgentControlNormalVel = 1.0f;
  912. // old normal speed was tuned to match sl normal plus Fast modifiers
  913. // so we need to rescale it
  914. private float m_speedModifier = 1.0f;
  915. public float SpeedModifier
  916. {
  917. get { return m_speedModifier; }
  918. set { m_speedModifier = value; }
  919. }
  920. private bool m_forceFly;
  921. public bool ForceFly
  922. {
  923. get { return m_forceFly; }
  924. set { m_forceFly = value; }
  925. }
  926. private bool m_flyDisabled;
  927. public bool FlyDisabled
  928. {
  929. get { return m_flyDisabled; }
  930. set { m_flyDisabled = value; }
  931. }
  932. public string Viewer
  933. {
  934. get { return Util.GetViewerName(m_scene.AuthenticateHandler.GetAgentCircuitData(ControllingClient.CircuitCode)); }
  935. }
  936. #endregion
  937. #region Constructor(s)
  938. public ScenePresence(IClientAPI client, Scene world, AvatarAppearance appearance, PresenceType type)
  939. {
  940. m_scene = world;
  941. AttachmentsSyncLock = new Object();
  942. AllowMovement = true;
  943. IsChildAgent = true;
  944. m_sendCoarseLocationsMethod = SendCoarseLocationsDefault;
  945. Animator = new ScenePresenceAnimator(this);
  946. Overrides = new MovementAnimationOverrides();
  947. PresenceType = type;
  948. m_drawDistance = client.StartFar;
  949. if(m_drawDistance > 32)
  950. {
  951. if(m_drawDistance > world.MaxDrawDistance)
  952. m_drawDistance = world.MaxDrawDistance;
  953. }
  954. else
  955. m_drawDistance = world.DefaultDrawDistance;
  956. RegionHandle = world.RegionInfo.RegionHandle;
  957. ControllingClient = client;
  958. Firstname = ControllingClient.FirstName;
  959. Lastname = ControllingClient.LastName;
  960. Name = String.Format("{0} {1}", Firstname, Lastname);
  961. m_uuid = client.AgentId;
  962. LocalId = m_scene.AllocateLocalId();
  963. LegacySitOffsets = m_scene.LegacySitOffsets;
  964. IsInLocalTransit = true;
  965. UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, m_uuid);
  966. if (account != null)
  967. m_userFlags = account.UserFlags;
  968. else
  969. m_userFlags = 0;
  970. int userlevel = 0;
  971. if (account != null)
  972. userlevel = account.UserLevel;
  973. GodController = new GodController(world, this, userlevel);
  974. // IGroupsModule gm = m_scene.RequestModuleInterface<IGroupsModule>();
  975. // if (gm != null)
  976. // Grouptitle = gm.GetGroupTitle(m_uuid);
  977. m_scriptEngines = m_scene.RequestModuleInterfaces<IScriptModule>();
  978. AbsolutePosition = posLastMove = posLastSignificantMove = CameraPosition =
  979. m_reprioritizationLastPosition = ControllingClient.StartPos;
  980. m_reprioritizationLastDrawDistance = -1000;
  981. // disable updates workjobs for now
  982. m_childUpdatesBusy = true;
  983. m_reprioritizationBusy = true;
  984. AdjustKnownSeeds();
  985. RegisterToClientEvents();
  986. SetDirectionVectors();
  987. Appearance = appearance;
  988. m_stateMachine = new ScenePresenceStateMachine(this);
  989. HealRate = 0.5f;
  990. IConfig sconfig = m_scene.Config.Configs["EntityTransfer"];
  991. if (sconfig != null)
  992. {
  993. string lpb = sconfig.GetString("LandingPointBehavior", "LandingPointBehavior_OS");
  994. if (lpb == "LandingPointBehavior_SL")
  995. m_LandingPointBehavior = LandingPointBehavior.SL;
  996. }
  997. m_bandwidth = 100000;
  998. m_lastBandwithTime = Util.GetTimeStamp() + 0.1;
  999. IConfig cconfig = m_scene.Config.Configs["ClientStack.LindenCaps"];
  1000. if (cconfig != null)
  1001. {
  1002. m_capbandwidth = cconfig.GetInt("Cap_AssetThrottle", m_capbandwidth);
  1003. if(m_capbandwidth > 0)
  1004. {
  1005. m_bandwidth = m_capbandwidth;
  1006. if(m_bandwidth < 50000)
  1007. m_bandwidth = 50000;
  1008. }
  1009. }
  1010. m_bandwidthBurst = m_bandwidth / 5;
  1011. ControllingClient.RefreshGroupMembership();
  1012. }
  1013. ~ScenePresence()
  1014. {
  1015. Dispose(false);
  1016. }
  1017. private bool disposed = false;
  1018. public void Dispose()
  1019. {
  1020. Dispose(true);
  1021. GC.SuppressFinalize(this);
  1022. }
  1023. protected void Dispose(bool disposing)
  1024. {
  1025. // Check to see if Dispose has already been called.
  1026. if (!disposed)
  1027. {
  1028. disposed = true;
  1029. IsDeleted = true;
  1030. if (m_updateAgentReceivedAfterTransferEvent != null)
  1031. {
  1032. m_updateAgentReceivedAfterTransferEvent.Dispose();
  1033. m_updateAgentReceivedAfterTransferEvent = null;
  1034. }
  1035. RemoveFromPhysicalScene();
  1036. // Clear known regions
  1037. KnownRegions = null;
  1038. m_scene.EventManager.OnRegionHeartbeatEnd -= RegionHeartbeatEnd;
  1039. RemoveClientEvents();
  1040. Animator = null;
  1041. Appearance = null;
  1042. /* temporary out: timming issues
  1043. if(m_attachments != null)
  1044. {
  1045. foreach(SceneObjectGroup sog in m_attachments)
  1046. sog.Dispose();
  1047. m_attachments = null;
  1048. }
  1049. */
  1050. scriptedcontrols.Clear();
  1051. ControllingClient = null;
  1052. }
  1053. }
  1054. private float lastHealthSent = 0;
  1055. private void RegionHeartbeatEnd(Scene scene)
  1056. {
  1057. if (IsChildAgent)
  1058. return;
  1059. m_movementAnimationUpdateCounter ++;
  1060. if (m_movementAnimationUpdateCounter >= 2)
  1061. {
  1062. m_movementAnimationUpdateCounter = 0;
  1063. if (Animator != null)
  1064. {
  1065. // If the parentID == 0 we are not sitting
  1066. // if !SitGournd then we are not sitting on the ground
  1067. // Fairly straightforward, now here comes the twist
  1068. // if ParentUUID is NOT UUID.Zero, we are looking to
  1069. // be sat on an object that isn't there yet. Should
  1070. // be treated as if sat.
  1071. if(ParentID == 0 && !SitGround && ParentUUID == UUID.Zero) // skip it if sitting
  1072. Animator.UpdateMovementAnimations();
  1073. }
  1074. else
  1075. {
  1076. // m_scene.EventManager.OnRegionHeartbeatEnd -= RegionHeartbeatEnd;
  1077. }
  1078. }
  1079. if(m_healRatePerFrame != 0f && Health != 100.0f)
  1080. {
  1081. float last = Health;
  1082. Health += m_healRatePerFrame;
  1083. if(Health > 100.0f)
  1084. {
  1085. Health = 100.0f;
  1086. lastHealthSent = Health;
  1087. ControllingClient.SendHealth(Health);
  1088. }
  1089. else if(Math.Abs(Health - lastHealthSent) > 1.0)
  1090. {
  1091. lastHealthSent = Health;
  1092. ControllingClient.SendHealth(Health);
  1093. }
  1094. }
  1095. }
  1096. public void RegisterToClientEvents()
  1097. {
  1098. ControllingClient.OnCompleteMovementToRegion += CompleteMovement;
  1099. ControllingClient.OnAgentUpdate += HandleAgentUpdate;
  1100. ControllingClient.OnAgentCameraUpdate += HandleAgentCamerasUpdate;
  1101. ControllingClient.OnAgentRequestSit += HandleAgentRequestSit;
  1102. ControllingClient.OnAgentSit += HandleAgentSit;
  1103. ControllingClient.OnSetAlwaysRun += HandleSetAlwaysRun;
  1104. ControllingClient.OnStartAnim += HandleStartAnim;
  1105. ControllingClient.OnStopAnim += HandleStopAnim;
  1106. ControllingClient.OnChangeAnim += avnHandleChangeAnim;
  1107. ControllingClient.OnForceReleaseControls += HandleForceReleaseControls;
  1108. ControllingClient.OnAutoPilotGo += MoveToTargetHandle;
  1109. ControllingClient.OnUpdateThrottles += RaiseUpdateThrottles;
  1110. ControllingClient.OnRegionHandShakeReply += RegionHandShakeReply;
  1111. // ControllingClient.OnAgentFOV += HandleAgentFOV;
  1112. // ControllingClient.OnChildAgentStatus += new StatusChange(this.ChildStatusChange);
  1113. // ControllingClient.OnStopMovement += new GenericCall2(this.StopMovement);
  1114. }
  1115. public void RemoveClientEvents()
  1116. {
  1117. ControllingClient.OnCompleteMovementToRegion -= CompleteMovement;
  1118. ControllingClient.OnAgentUpdate -= HandleAgentUpdate;
  1119. ControllingClient.OnAgentCameraUpdate -= HandleAgentCamerasUpdate;
  1120. ControllingClient.OnAgentRequestSit -= HandleAgentRequestSit;
  1121. ControllingClient.OnAgentSit -= HandleAgentSit;
  1122. ControllingClient.OnSetAlwaysRun -= HandleSetAlwaysRun;
  1123. ControllingClient.OnStartAnim -= HandleStartAnim;
  1124. ControllingClient.OnStopAnim -= HandleStopAnim;
  1125. ControllingClient.OnChangeAnim -= avnHandleChangeAnim;
  1126. ControllingClient.OnForceReleaseControls -= HandleForceReleaseControls;
  1127. ControllingClient.OnAutoPilotGo -= MoveToTargetHandle;
  1128. ControllingClient.OnUpdateThrottles -= RaiseUpdateThrottles;
  1129. ControllingClient.OnRegionHandShakeReply -= RegionHandShakeReply;
  1130. // ControllingClient.OnAgentFOV += HandleAgentFOV;
  1131. }
  1132. private void SetDirectionVectors()
  1133. {
  1134. Dir_Vectors[0] = new Vector3(AgentControlNormalVel,0,0); //FORWARD
  1135. Dir_Vectors[1] = new Vector3(-AgentControlNormalVel,0,0);; //BACK
  1136. Dir_Vectors[2] = new Vector3(0,AgentControlNormalVel,0); //LEFT
  1137. Dir_Vectors[3] = new Vector3(0,-AgentControlNormalVel,0); //RIGHT
  1138. Dir_Vectors[4] = new Vector3(0,0,AgentControlNormalVel); //UP
  1139. Dir_Vectors[5] = new Vector3(0,0,-AgentControlNormalVel); //DOWN
  1140. Dir_Vectors[6] = new Vector3(AgentControlNudgeVel, 0f, 0f); //FORWARD_NUDGE
  1141. Dir_Vectors[7] = new Vector3(-AgentControlNudgeVel, 0f, 0f); //BACK_NUDGE
  1142. Dir_Vectors[8] = new Vector3(0f, AgentControlNudgeVel, 0f); //LEFT_NUDGE
  1143. Dir_Vectors[9] = new Vector3(0f, -AgentControlNudgeVel, 0f); //RIGHT_NUDGE
  1144. Dir_Vectors[10] = new Vector3(0f, 0f, AgentControlNudgeVel); //UP_Nudge
  1145. Dir_Vectors[11] = new Vector3(0f, 0f, -AgentControlNudgeVel); //DOWN_Nudge
  1146. }
  1147. #endregion
  1148. #region Status Methods
  1149. /// <summary>
  1150. /// Turns a child agent into a root agent.
  1151. /// </summary>
  1152. /// <remarks>
  1153. /// Child agents are logged into neighbouring sims largely to observe changes. Root agents exist when the
  1154. /// avatar is actual in the sim. They can perform all actions.
  1155. /// This change is made whenever an avatar enters a region, whether by crossing over from a neighbouring sim,
  1156. /// teleporting in or on initial login.
  1157. ///
  1158. /// This method is on the critical path for transferring an avatar from one region to another. Delay here
  1159. /// delays that crossing.
  1160. /// </remarks>
  1161. // constants for physics position search
  1162. const float PhysSearchHeight = 300f;
  1163. const float PhysMinSkipGap = 20f;
  1164. const float PhysSkipGapDelta = 30f;
  1165. const int PhysNumberCollisions = 30;
  1166. // only in use as part of completemovement
  1167. // other uses need fix
  1168. private bool MakeRootAgent(Vector3 pos, bool isFlying, ref Vector3 lookat)
  1169. {
  1170. //int ts = Util.EnvironmentTickCount();
  1171. lock (m_completeMovementLock)
  1172. {
  1173. if (!IsChildAgent)
  1174. return false;
  1175. //m_log.DebugFormat("[MakeRootAgent] enter lock: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1176. //m_log.DebugFormat("[SCENE]: known regions in {0}: {1}", Scene.RegionInfo.RegionName, KnownChildRegionHandles.Count);
  1177. // m_log.InfoFormat(
  1178. // "[SCENE]: Upgrading child to root agent for {0} in {1}",
  1179. // Name, m_scene.RegionInfo.RegionName);
  1180. if (ParentUUID != UUID.Zero)
  1181. {
  1182. m_log.DebugFormat("[SCENE PRESENCE]: Sitting avatar back on prim {0}", ParentUUID);
  1183. SceneObjectPart part = m_scene.GetSceneObjectPart(ParentUUID);
  1184. if (part == null)
  1185. {
  1186. m_log.ErrorFormat("[SCENE PRESENCE]: Can't find prim {0} to sit on", ParentUUID);
  1187. ParentID = 0;
  1188. ParentPart = null;
  1189. PrevSitOffset = Vector3.Zero;
  1190. HandleForceReleaseControls(ControllingClient, UUID); // needs testing
  1191. }
  1192. else
  1193. {
  1194. part.AddSittingAvatar(this);
  1195. // if not actually on the target invalidate it
  1196. if(m_gotCrossUpdate && (m_crossingFlags & 0x04) == 0)
  1197. part.SitTargetAvatar = UUID.Zero;
  1198. ParentID = part.LocalId;
  1199. ParentPart = part;
  1200. m_pos = PrevSitOffset;
  1201. pos = part.GetWorldPosition();
  1202. PhysicsActor partPhysActor = part.PhysActor;
  1203. if(partPhysActor != null)
  1204. {
  1205. partPhysActor.OnPhysicsRequestingCameraData -=
  1206. physActor_OnPhysicsRequestingCameraData;
  1207. partPhysActor.OnPhysicsRequestingCameraData +=
  1208. physActor_OnPhysicsRequestingCameraData;
  1209. }
  1210. }
  1211. ParentUUID = UUID.Zero;
  1212. }
  1213. IsChildAgent = false;
  1214. }
  1215. //m_log.DebugFormat("[MakeRootAgent] out lock: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1216. // Must reset this here so that a teleport to a region next to an existing region does not keep the flag
  1217. // set and prevent the close of the connection on a subsequent re-teleport.
  1218. // Should not be needed if we are not trying to tell this region to close
  1219. // DoNotCloseAfterTeleport = false;
  1220. RegionHandle = m_scene.RegionInfo.RegionHandle;
  1221. m_scene.EventManager.TriggerSetRootAgentScene(m_uuid, m_scene);
  1222. //m_log.DebugFormat("[MakeRootAgent] TriggerSetRootAgentScene: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1223. if (ParentID == 0)
  1224. {
  1225. bool positionChanged = false;
  1226. bool success = true;
  1227. if (m_LandingPointBehavior == LandingPointBehavior.OS)
  1228. success = CheckAndAdjustLandingPoint_OS(ref pos, ref lookat, ref positionChanged);
  1229. else
  1230. success = CheckAndAdjustLandingPoint_SL(ref pos, ref lookat, ref positionChanged);
  1231. if (!success)
  1232. m_log.DebugFormat("[SCENE PRESENCE MakeRootAgent]: houston we have a problem.. {0} ({1} got banned)", Name, UUID);
  1233. if (pos.X < 0f || pos.Y < 0f
  1234. || pos.X >= m_scene.RegionInfo.RegionSizeX
  1235. || pos.Y >= m_scene.RegionInfo.RegionSizeY)
  1236. {
  1237. m_log.WarnFormat(
  1238. "[SCENE PRESENCE]: MakeRootAgent() was given an illegal position of {0} for avatar {1}, {2}. Clamping",
  1239. pos, Name, UUID);
  1240. if (pos.X < 0f)
  1241. pos.X = 0.5f;
  1242. else if(pos.X >= m_scene.RegionInfo.RegionSizeX)
  1243. pos.X = m_scene.RegionInfo.RegionSizeX - 0.5f;
  1244. if (pos.Y < 0f)
  1245. pos.Y = 0.5f;
  1246. else if(pos.Y >= m_scene.RegionInfo.RegionSizeY)
  1247. pos.Y = m_scene.RegionInfo.RegionSizeY - 0.5f;
  1248. }
  1249. float groundHeight = m_scene.GetGroundHeight(pos.X, pos.Y) + .01f;
  1250. float physTestHeight;
  1251. if(PhysSearchHeight < groundHeight + 100f)
  1252. physTestHeight = groundHeight + 100f;
  1253. else
  1254. physTestHeight = PhysSearchHeight;
  1255. float localAVHalfHeight = 0.8f;
  1256. if (Appearance != null && Appearance.AvatarHeight > 0)
  1257. localAVHalfHeight = 0.5f * Appearance.AvatarHeight;
  1258. groundHeight += localAVHalfHeight;
  1259. if (groundHeight > pos.Z)
  1260. pos.Z = groundHeight;
  1261. bool checkPhysics = !positionChanged &&
  1262. m_scene.SupportsRayCastFiltered() &&
  1263. pos.Z < physTestHeight &&
  1264. ((m_teleportFlags & (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID)) ==
  1265. (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID)
  1266. || (m_teleportFlags & TeleportFlags.ViaLocation) != 0
  1267. || (m_teleportFlags & TeleportFlags.ViaHGLogin) != 0);
  1268. if(checkPhysics)
  1269. {
  1270. // land check was done above
  1271. RayFilterFlags rayfilter = RayFilterFlags.BackFaceCull;
  1272. rayfilter |= RayFilterFlags.PrimsNonPhantomAgents;
  1273. int physcount = PhysNumberCollisions;
  1274. float dist = physTestHeight - groundHeight + localAVHalfHeight;
  1275. Vector3 direction = new Vector3(0f, 0f, -1f);
  1276. Vector3 RayStart = pos;
  1277. RayStart.Z = physTestHeight;
  1278. List<ContactResult> physresults =
  1279. (List<ContactResult>)m_scene.RayCastFiltered(RayStart, direction, dist, physcount, rayfilter);
  1280. while (physresults != null && physresults.Count > 0)
  1281. {
  1282. float dest = physresults[0].Pos.Z;
  1283. if (dest - groundHeight > PhysMinSkipGap + PhysSkipGapDelta)
  1284. break;
  1285. if (physresults.Count > 1)
  1286. {
  1287. physresults.Sort(delegate(ContactResult a, ContactResult b)
  1288. {
  1289. return a.Depth.CompareTo(b.Depth);
  1290. });
  1291. int sel = 0;
  1292. int count = physresults.Count;
  1293. float curd = physresults[0].Depth;
  1294. float nextd = curd + PhysMinSkipGap;
  1295. float maxDepth = dist - pos.Z;
  1296. for(int i = 1; i < count; i++)
  1297. {
  1298. curd = physresults[i].Depth;
  1299. if(curd >= nextd)
  1300. {
  1301. sel = i;
  1302. if(curd >= maxDepth || curd >= nextd + PhysSkipGapDelta)
  1303. break;
  1304. }
  1305. nextd = curd + PhysMinSkipGap;
  1306. }
  1307. dest = physresults[sel].Pos.Z;
  1308. }
  1309. dest += localAVHalfHeight;
  1310. if(dest > pos.Z)
  1311. pos.Z = dest;
  1312. break;
  1313. }
  1314. }
  1315. AbsolutePosition = pos;
  1316. // m_log.DebugFormat(
  1317. // "Set pos {0}, vel {1} in {1} to {2} from input position of {3} on MakeRootAgent",
  1318. // Name, Scene.Name, AbsolutePosition, pos);
  1319. //
  1320. if (m_teleportFlags == TeleportFlags.Default)
  1321. {
  1322. Vector3 vel = Velocity;
  1323. AddToPhysicalScene(isFlying);
  1324. if (PhysicsActor != null)
  1325. PhysicsActor.SetMomentum(vel);
  1326. }
  1327. else
  1328. {
  1329. AddToPhysicalScene(isFlying);
  1330. // reset camera to avatar pos
  1331. CameraPosition = pos;
  1332. }
  1333. if (ForceFly)
  1334. {
  1335. Flying = true;
  1336. }
  1337. else if (FlyDisabled)
  1338. {
  1339. Flying = false;
  1340. }
  1341. }
  1342. //m_log.DebugFormat("[MakeRootAgent] position and physical: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1343. m_scene.SwapRootAgentCount(false);
  1344. // If we don't reset the movement flag here, an avatar that crosses to a neighbouring sim and returns will
  1345. // stall on the border crossing since the existing child agent will still have the last movement
  1346. // recorded, which stops the input from being processed.
  1347. MovementFlag = 0;
  1348. m_scene.AuthenticateHandler.UpdateAgentChildStatus(ControllingClient.CircuitCode, false);
  1349. m_scene.EventManager.TriggerOnMakeRootAgent(this);
  1350. //m_log.DebugFormat("[MakeRootAgent] TriggerOnMakeRootAgent and done: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1351. return true;
  1352. }
  1353. private void RestartAttachmentScripts()
  1354. {
  1355. // We need to restart scripts here so that they receive the correct changed events (CHANGED_TELEPORT
  1356. // and CHANGED_REGION) when the attachments have been rezzed in the new region. This cannot currently
  1357. // be done in AttachmentsModule.CopyAttachments(AgentData ad, IScenePresence sp) itself since we are
  1358. // not transporting the required data.
  1359. //
  1360. // We must take a copy of the attachments list here (rather than locking) to avoid a deadlock where a script in one of
  1361. // the attachments may start processing an event (which locks ScriptInstance.m_Script) that then calls a method here
  1362. // which needs to lock m_attachments. ResumeScripts() needs to take a ScriptInstance.m_Script lock to try to unset the Suspend status.
  1363. //
  1364. // FIXME: In theory, this deadlock should not arise since scripts should not be processing events until ResumeScripts().
  1365. // But XEngine starts all scripts unsuspended. Starting them suspended will not currently work because script rezzing
  1366. // is placed in an asynchronous queue in XEngine and so the ResumeScripts() call will almost certainly execute before the
  1367. // script is rezzed. This means the ResumeScripts() does absolutely nothing when using XEngine.
  1368. List<SceneObjectGroup> attachments = GetAttachments();
  1369. m_log.DebugFormat(
  1370. "[SCENE PRESENCE]: Restarting scripts in {0} attachments for {1} in {2}", attachments.Count, Name, Scene.Name);
  1371. // Resume scripts
  1372. foreach (SceneObjectGroup sog in attachments)
  1373. {
  1374. sog.RootPart.ParentGroup.CreateScriptInstances(0, false, m_scene.DefaultScriptEngine, GetStateSource());
  1375. sog.ResumeScripts();
  1376. sog.ScheduleGroupForFullUpdate();
  1377. }
  1378. }
  1379. private static bool IsRealLogin(TeleportFlags teleportFlags)
  1380. {
  1381. return (teleportFlags & (TeleportFlags.ViaLogin | TeleportFlags.ViaHGLogin)) == TeleportFlags.ViaLogin;
  1382. }
  1383. /// <summary>
  1384. /// Force viewers to show the avatar's current name.
  1385. /// </summary>
  1386. /// <remarks>
  1387. /// The avatar name that is shown above the avatar in the viewers is sent in ObjectUpdate packets,
  1388. /// and they get the name from the ScenePresence. Unfortunately, viewers have a bug (as of April 2014)
  1389. /// where they ignore changes to the avatar name. However, tey don't ignore changes to the avatar's
  1390. /// Group Title. So the following trick makes viewers update the avatar's name by briefly changing
  1391. /// the group title (to "(Loading)"), and then restoring it.
  1392. /// </remarks>
  1393. /*
  1394. public void ForceViewersUpdateName()
  1395. {
  1396. m_log.DebugFormat("[SCENE PRESENCE]: Forcing viewers to update the avatar name for " + Name);
  1397. UseFakeGroupTitle = true;
  1398. Util.FireAndForget(o =>
  1399. {
  1400. // Viewers only update the avatar name when idle. Therefore, we must wait long
  1401. // enough for the viewer to show the fake name that we had set above, and only
  1402. // then switch back to the true name. This delay was chosen because it has a high
  1403. // chance of succeeding (we don't want to choose a value that's too low).
  1404. Thread.Sleep(5000);
  1405. UseFakeGroupTitle = false;
  1406. SendAvatarDataToAllClients(false);
  1407. }, null, "Scenepresence.ForceViewersUpdateName");
  1408. }
  1409. */
  1410. public int GetStateSource()
  1411. {
  1412. return m_teleportFlags == TeleportFlags.Default ? 2 : 5; // StateSource.PrimCrossing : StateSource.Teleporting
  1413. }
  1414. /// <summary>
  1415. /// This turns a root agent into a child agent
  1416. /// </summary>
  1417. /// <remarks>
  1418. /// when an agent departs this region for a neighbor, this gets called.
  1419. ///
  1420. /// It doesn't get called for a teleport. Reason being, an agent that
  1421. /// teleports out may not end up anywhere near this region
  1422. /// </remarks>
  1423. public void MakeChildAgent(ulong newRegionHandle)
  1424. {
  1425. m_updateAgentReceivedAfterTransferEvent.Reset();
  1426. m_haveGroupInformation = false;
  1427. m_gotCrossUpdate = false;
  1428. m_crossingFlags = 0;
  1429. m_scene.EventManager.OnRegionHeartbeatEnd -= RegionHeartbeatEnd;
  1430. RegionHandle = newRegionHandle;
  1431. m_log.DebugFormat("[SCENE PRESENCE]: Making {0} a child agent in {1} from root region {2}",
  1432. Name, Scene.RegionInfo.RegionName, newRegionHandle);
  1433. // Reset the m_originRegionID as it has dual use as a flag to signal that the UpdateAgent() call orignating
  1434. // from the source simulator has completed on a V2 teleport.
  1435. lock (m_originRegionIDAccessLock)
  1436. m_originRegionID = UUID.Zero;
  1437. // Reset these so that teleporting in and walking out isn't seen
  1438. // as teleporting back
  1439. TeleportFlags = TeleportFlags.Default;
  1440. MovementFlag = 0;
  1441. // It looks like Animator is set to null somewhere, and MakeChild
  1442. // is called after that. Probably in aborted teleports.
  1443. if (Animator == null)
  1444. Animator = new ScenePresenceAnimator(this);
  1445. else
  1446. Animator.ResetAnimations();
  1447. Environment = null;
  1448. // m_log.DebugFormat(
  1449. // "[SCENE PRESENCE]: Downgrading root agent {0}, {1} to a child agent in {2}",
  1450. // Name, UUID, m_scene.RegionInfo.RegionName);
  1451. // Don't zero out the velocity since this can cause problems when an avatar is making a region crossing,
  1452. // depending on the exact timing. This shouldn't matter anyway since child agent positions are not updated.
  1453. //Velocity = new Vector3(0, 0, 0);
  1454. IsChildAgent = true;
  1455. m_scene.SwapRootAgentCount(true);
  1456. RemoveFromPhysicalScene();
  1457. ParentID = 0; // Child agents can't be sitting
  1458. // we dont have land information for child
  1459. m_previusParcelHide = false;
  1460. m_previusParcelUUID = UUID.Zero;
  1461. m_currentParcelHide = false;
  1462. m_currentParcelUUID = UUID.Zero;
  1463. CollisionPlane = Vector4.UnitW;
  1464. // we need to kill this on agents that do not see the new region
  1465. m_scene.ForEachRootScenePresence(delegate(ScenePresence p)
  1466. {
  1467. if (!p.knowsNeighbourRegion(newRegionHandle))
  1468. {
  1469. SendKillTo(p);
  1470. }
  1471. });
  1472. m_scene.AuthenticateHandler.UpdateAgentChildStatus(ControllingClient.CircuitCode, true);
  1473. m_scene.EventManager.TriggerOnMakeChildAgent(this);
  1474. }
  1475. /// <summary>
  1476. /// Removes physics plugin scene representation of this agent if it exists.
  1477. /// </summary>
  1478. public void RemoveFromPhysicalScene()
  1479. {
  1480. PhysicsActor pa = Interlocked.Exchange(ref m_physActor, null);
  1481. if (pa != null)
  1482. {
  1483. // PhysicsActor.OnRequestTerseUpdate -= SendTerseUpdateToAllClients;
  1484. pa.OnOutOfBounds -= OutOfBoundsCall;
  1485. pa.OnCollisionUpdate -= PhysicsCollisionUpdate;
  1486. pa.UnSubscribeEvents();
  1487. m_scene.PhysicsScene.RemoveAvatar(pa);
  1488. pa = null;
  1489. }
  1490. // else
  1491. // {
  1492. // m_log.ErrorFormat(
  1493. // "[SCENE PRESENCE]: Attempt to remove physics actor for {0} on {1} but this scene presence has no physics actor",
  1494. // Name, Scene.RegionInfo.RegionName);
  1495. // }
  1496. }
  1497. public void Teleport(Vector3 pos)
  1498. {
  1499. TeleportWithMomentum(pos, Vector3.Zero);
  1500. }
  1501. public void TeleportWithMomentum(Vector3 pos, Vector3? v)
  1502. {
  1503. if(!CheckLocalTPLandingPoint(ref pos))
  1504. return;
  1505. if (IsSitting)
  1506. StandUp(false);
  1507. bool isFlying = Flying;
  1508. Vector3 vel = Velocity;
  1509. RemoveFromPhysicalScene();
  1510. AbsolutePosition = pos;
  1511. AddToPhysicalScene(isFlying);
  1512. if (PhysicsActor != null)
  1513. {
  1514. if (v.HasValue)
  1515. PhysicsActor.SetMomentum((Vector3)v);
  1516. else
  1517. PhysicsActor.SetMomentum(vel);
  1518. }
  1519. SendTerseUpdateToAllClients();
  1520. }
  1521. public void TeleportOnEject(Vector3 pos)
  1522. {
  1523. if (IsSitting )
  1524. StandUp(false);
  1525. bool isFlying = Flying;
  1526. RemoveFromPhysicalScene();
  1527. AbsolutePosition = pos;
  1528. AddToPhysicalScene(isFlying);
  1529. SendTerseUpdateToAllClients();
  1530. }
  1531. public void LocalTeleport(Vector3 newpos, Vector3 newvel, Vector3 newlookat, int flags)
  1532. {
  1533. if (newpos.X <= 0)
  1534. {
  1535. newpos.X = 0.1f;
  1536. if (newvel.X < 0)
  1537. newvel.X = 0;
  1538. }
  1539. else if (newpos.X >= Scene.RegionInfo.RegionSizeX)
  1540. {
  1541. newpos.X = Scene.RegionInfo.RegionSizeX - 0.1f;
  1542. if (newvel.X > 0)
  1543. newvel.X = 0;
  1544. }
  1545. if (newpos.Y <= 0)
  1546. {
  1547. newpos.Y = 0.1f;
  1548. if (newvel.Y < 0)
  1549. newvel.Y = 0;
  1550. }
  1551. else if (newpos.Y >= Scene.RegionInfo.RegionSizeY)
  1552. {
  1553. newpos.Y = Scene.RegionInfo.RegionSizeY - 0.1f;
  1554. if (newvel.Y > 0)
  1555. newvel.Y = 0;
  1556. }
  1557. if (!m_scene.TestLandRestrictions(UUID, out string reason, ref newpos.X, ref newpos.Y))
  1558. return ;
  1559. if (IsSitting)
  1560. StandUp();
  1561. if(m_movingToTarget)
  1562. ResetMoveToTarget();
  1563. float localHalfAVHeight = 0.8f;
  1564. if (Appearance != null)
  1565. localHalfAVHeight = Appearance.AvatarHeight * 0.5f;
  1566. float posZLimit = (float)Scene.Heightmap[(int)newpos.X, (int)newpos.Y];
  1567. posZLimit += localHalfAVHeight + 0.1f;
  1568. if (newpos.Z < posZLimit)
  1569. newpos.Z = posZLimit;
  1570. if((flags & 0x1e) != 0)
  1571. {
  1572. if ((flags & 8) != 0)
  1573. Flying = true;
  1574. else if ((flags & 16) != 0)
  1575. Flying = false;
  1576. uint tpflags = (uint)TeleportFlags.ViaLocation;
  1577. if(Flying)
  1578. tpflags |= (uint)TeleportFlags.IsFlying;
  1579. Vector3 lookat = Lookat;
  1580. if ((flags & 2) != 0)
  1581. {
  1582. newlookat.Z = 0;
  1583. newlookat.Normalize();
  1584. if (Math.Abs(newlookat.X) > 0.001 || Math.Abs(newlookat.Y) > 0.001)
  1585. lookat = newlookat;
  1586. }
  1587. else if((flags & 4) != 0)
  1588. {
  1589. if((flags & 1) != 0)
  1590. newlookat = newvel;
  1591. else
  1592. newlookat = m_velocity;
  1593. newlookat.Z = 0;
  1594. newlookat.Normalize();
  1595. if (Math.Abs(newlookat.X) > 0.001 || Math.Abs(newlookat.Y) > 0.001)
  1596. lookat = newlookat;
  1597. }
  1598. AbsolutePosition = newpos;
  1599. ControllingClient.SendLocalTeleport(newpos, lookat, tpflags);
  1600. }
  1601. else
  1602. AbsolutePosition = newpos;
  1603. if ((flags & 1) != 0)
  1604. {
  1605. if (PhysicsActor != null)
  1606. PhysicsActor.SetMomentum(newvel);
  1607. m_velocity = newvel;
  1608. }
  1609. SendTerseUpdateToAllClients();
  1610. }
  1611. public void StopFlying()
  1612. {
  1613. if (IsInTransit)
  1614. return;
  1615. Vector3 pos = AbsolutePosition;
  1616. if (Appearance.AvatarHeight != 127.0f)
  1617. pos += new Vector3(0f, 0f, (Appearance.AvatarHeight / 6f));
  1618. else
  1619. pos += new Vector3(0f, 0f, (1.56f / 6f));
  1620. AbsolutePosition = pos;
  1621. // attach a suitable collision plane regardless of the actual situation to force the LLClient to land.
  1622. // Collision plane below the avatar's position a 6th of the avatar's height is suitable.
  1623. // Mind you, that this method doesn't get called if the avatar's velocity magnitude is greater then a
  1624. // certain amount.. because the LLClient wouldn't land in that situation anyway.
  1625. // why are we still testing for this really old height value default???
  1626. if (Appearance.AvatarHeight != 127.0f)
  1627. CollisionPlane = new Vector4(0, 0, 0, pos.Z - Appearance.AvatarHeight / 6f);
  1628. else
  1629. CollisionPlane = new Vector4(0, 0, 0, pos.Z - (1.56f / 6f));
  1630. SendAgentTerseUpdate(this);
  1631. }
  1632. /// <summary>
  1633. /// Applies a roll accumulator to the avatar's angular velocity for the avatar fly roll effect.
  1634. /// </summary>
  1635. /// <param name="amount">Postive or negative roll amount in radians</param>
  1636. private void ApplyFlyingRoll(float amount, bool PressingUp, bool PressingDown)
  1637. {
  1638. float rollAmount = Util.Clamp(m_AngularVelocity.Z + amount, -FLY_ROLL_MAX_RADIANS, FLY_ROLL_MAX_RADIANS);
  1639. m_AngularVelocity.Z = rollAmount;
  1640. // APPLY EXTRA consideration for flying up and flying down during this time.
  1641. // if we're turning left
  1642. if (amount > 0)
  1643. {
  1644. // If we're at the max roll and pressing up, we want to swing BACK a bit
  1645. // Automatically adds noise
  1646. if (PressingUp)
  1647. {
  1648. if (m_AngularVelocity.Z >= FLY_ROLL_MAX_RADIANS - 0.04f)
  1649. m_AngularVelocity.Z -= 0.9f;
  1650. }
  1651. // If we're at the max roll and pressing down, we want to swing MORE a bit
  1652. if (PressingDown)
  1653. {
  1654. if (m_AngularVelocity.Z >= FLY_ROLL_MAX_RADIANS && m_AngularVelocity.Z < FLY_ROLL_MAX_RADIANS + 0.6f)
  1655. m_AngularVelocity.Z += 0.6f;
  1656. }
  1657. }
  1658. else // we're turning right.
  1659. {
  1660. // If we're at the max roll and pressing up, we want to swing BACK a bit
  1661. // Automatically adds noise
  1662. if (PressingUp)
  1663. {
  1664. if (m_AngularVelocity.Z <= (-FLY_ROLL_MAX_RADIANS))
  1665. m_AngularVelocity.Z += 0.6f;
  1666. }
  1667. // If we're at the max roll and pressing down, we want to swing MORE a bit
  1668. if (PressingDown)
  1669. {
  1670. if (m_AngularVelocity.Z >= -FLY_ROLL_MAX_RADIANS - 0.6f)
  1671. m_AngularVelocity.Z -= 0.6f;
  1672. }
  1673. }
  1674. }
  1675. /// <summary>
  1676. /// incrementally sets roll amount to zero
  1677. /// </summary>
  1678. /// <param name="amount">Positive roll amount in radians</param>
  1679. /// <returns></returns>
  1680. private float CalculateFlyingRollResetToZero(float amount)
  1681. {
  1682. const float rollMinRadians = 0f;
  1683. if (m_AngularVelocity.Z > 0)
  1684. {
  1685. float leftOverToMin = m_AngularVelocity.Z - rollMinRadians;
  1686. if (amount > leftOverToMin)
  1687. return -leftOverToMin;
  1688. else
  1689. return -amount;
  1690. }
  1691. else
  1692. {
  1693. float leftOverToMin = -m_AngularVelocity.Z - rollMinRadians;
  1694. if (amount > leftOverToMin)
  1695. return leftOverToMin;
  1696. else
  1697. return amount;
  1698. }
  1699. }
  1700. // neighbouring regions we have enabled a child agent in
  1701. // holds the seed cap for the child agent in that region
  1702. private Dictionary<ulong, string> m_knownChildRegions = new Dictionary<ulong, string>();
  1703. struct spRegionSizeInfo
  1704. {
  1705. public int sizeX;
  1706. public int sizeY;
  1707. public spRegionSizeInfo(int x, int y)
  1708. {
  1709. sizeX = x;
  1710. sizeY = y;
  1711. }
  1712. }
  1713. private Dictionary<ulong, spRegionSizeInfo> m_knownChildRegionsSizeInfo = new Dictionary<ulong, spRegionSizeInfo>();
  1714. public void AddNeighbourRegion(GridRegion region, string capsPath)
  1715. {
  1716. lock (m_knownChildRegions)
  1717. {
  1718. ulong regionHandle = region.RegionHandle;
  1719. m_knownChildRegions[regionHandle] = capsPath;
  1720. m_knownChildRegionsSizeInfo[regionHandle] = new spRegionSizeInfo(region.RegionSizeX, region.RegionSizeY); ;
  1721. }
  1722. }
  1723. public void AddNeighbourRegionSizeInfo(GridRegion region)
  1724. {
  1725. lock (m_knownChildRegions)
  1726. {
  1727. m_knownChildRegionsSizeInfo[region.RegionHandle] = new spRegionSizeInfo(region.RegionSizeX, region.RegionSizeY);
  1728. }
  1729. }
  1730. public void SetNeighbourRegionSizeInfo(List<GridRegion> regionsList)
  1731. {
  1732. lock (m_knownChildRegions)
  1733. {
  1734. m_knownChildRegionsSizeInfo.Clear();
  1735. foreach (GridRegion region in regionsList)
  1736. {
  1737. m_knownChildRegionsSizeInfo[region.RegionHandle] = new spRegionSizeInfo(region.RegionSizeX, region.RegionSizeY);
  1738. }
  1739. }
  1740. }
  1741. public void RemoveNeighbourRegion(ulong regionHandle)
  1742. {
  1743. lock (m_knownChildRegions)
  1744. {
  1745. // Checking ContainsKey is redundant as Remove works either way and returns a bool
  1746. // This is here to allow the Debug output to be conditional on removal
  1747. //if (m_knownChildRegions.ContainsKey(regionHandle))
  1748. // m_log.DebugFormat(" !!! removing known region {0} in {1}. Count = {2}", regionHandle, Scene.RegionInfo.RegionName, m_knownChildRegions.Count);
  1749. m_knownChildRegions.Remove(regionHandle);
  1750. m_knownChildRegionsSizeInfo.Remove(regionHandle);
  1751. }
  1752. }
  1753. public bool knowsNeighbourRegion(ulong regionHandle)
  1754. {
  1755. lock (m_knownChildRegions)
  1756. return m_knownChildRegions.ContainsKey(regionHandle);
  1757. }
  1758. public void DropOldNeighbours(List<ulong> oldRegions)
  1759. {
  1760. foreach (ulong handle in oldRegions)
  1761. {
  1762. RemoveNeighbourRegion(handle);
  1763. Scene.CapsModule.DropChildSeed(UUID, handle);
  1764. }
  1765. }
  1766. public void DropThisRootRegionFromNeighbours()
  1767. {
  1768. ulong handle = m_scene.RegionInfo.RegionHandle;
  1769. RemoveNeighbourRegion(handle);
  1770. Scene.CapsModule.DropChildSeed(UUID, handle);
  1771. }
  1772. public Dictionary<ulong, string> KnownRegions
  1773. {
  1774. get
  1775. {
  1776. lock (m_knownChildRegions)
  1777. return new Dictionary<ulong, string>(m_knownChildRegions);
  1778. }
  1779. set
  1780. {
  1781. // Replacing the reference is atomic but we still need to lock on
  1782. // the original dictionary object which may be in use elsewhere
  1783. lock (m_knownChildRegions)
  1784. m_knownChildRegions = value;
  1785. }
  1786. }
  1787. public List<ulong> KnownRegionHandles
  1788. {
  1789. get
  1790. {
  1791. lock (m_knownChildRegions)
  1792. return new List<ulong>(m_knownChildRegions.Keys);
  1793. }
  1794. }
  1795. public int KnownRegionCount
  1796. {
  1797. get
  1798. {
  1799. lock (m_knownChildRegions)
  1800. return m_knownChildRegions.Count;
  1801. }
  1802. }
  1803. #endregion
  1804. #region Event Handlers
  1805. /// <summary>
  1806. /// Sets avatar height in the physics plugin
  1807. /// </summary>
  1808. /// <param name="height">New height of avatar</param>
  1809. public void SetHeight(float height)
  1810. {
  1811. if (PhysicsActor != null && !IsChildAgent)
  1812. PhysicsActor.Size = new Vector3(0.45f, 0.6f, height);
  1813. }
  1814. public void SetSize(Vector3 size, float feetoffset)
  1815. {
  1816. if (PhysicsActor != null && !IsChildAgent)
  1817. PhysicsActor.setAvatarSize(size, feetoffset);
  1818. }
  1819. private bool WaitForUpdateAgent(IClientAPI client)
  1820. {
  1821. // Before the source region executes UpdateAgent
  1822. // (which triggers Scene.IncomingUpdateChildAgent(AgentData cAgentData) here in the destination,
  1823. // m_originRegionID is UUID.Zero; after, it's non-Zero. The CompleteMovement sequence initiated from the
  1824. // viewer (in turn triggered by the source region sending it a TeleportFinish event) waits until it's non-zero
  1825. try
  1826. {
  1827. if(m_updateAgentReceivedAfterTransferEvent.WaitOne(10000))
  1828. {
  1829. UUID originID = UUID.Zero;
  1830. lock (m_originRegionIDAccessLock)
  1831. originID = m_originRegionID;
  1832. if (originID.Equals(UUID.Zero))
  1833. {
  1834. // Movement into region will fail
  1835. m_log.WarnFormat("[SCENE PRESENCE]: Update agent {0} at {1} got invalid origin region id ", client.Name, Scene.Name);
  1836. return false;
  1837. }
  1838. return true;
  1839. }
  1840. else
  1841. {
  1842. m_log.WarnFormat("[SCENE PRESENCE]: Update agent {0} at {1} did not receive agent update ", client.Name, Scene.Name);
  1843. return false;
  1844. }
  1845. }
  1846. catch { }
  1847. finally
  1848. {
  1849. m_updateAgentReceivedAfterTransferEvent?.Reset();
  1850. }
  1851. return false;
  1852. }
  1853. public void RotateToLookAt(Vector3 lookAt)
  1854. {
  1855. if(ParentID == 0)
  1856. {
  1857. float n = lookAt.X * lookAt.X + lookAt.Y * lookAt.Y;
  1858. if(n < 0.0001f)
  1859. {
  1860. Rotation = Quaternion.Identity;
  1861. return;
  1862. }
  1863. n = lookAt.X/(float)Math.Sqrt(n);
  1864. float angle = (float)Math.Acos(n);
  1865. angle *= 0.5f;
  1866. float s = (float)Math.Sin(angle);
  1867. if(lookAt.Y < 0)
  1868. s = -s;
  1869. Rotation = new Quaternion(
  1870. 0f,
  1871. 0f,
  1872. s,
  1873. (float)Math.Cos(angle)
  1874. );
  1875. }
  1876. }
  1877. /// <summary>
  1878. /// Complete Avatar's movement into the region.
  1879. /// </summary>
  1880. /// <param name="client"></param>
  1881. /// <param name="openChildAgents">
  1882. /// If true, send notification to neighbour regions to expect
  1883. /// a child agent from the client. These neighbours can be some distance away, depending right now on the
  1884. /// configuration of DefaultDrawDistance in the [Startup] section of config
  1885. /// </param>
  1886. public void CompleteMovement(IClientAPI client, bool openChildAgents)
  1887. {
  1888. int ts = Util.EnvironmentTickCount();
  1889. m_log.InfoFormat(
  1890. "[SCENE PRESENCE]: Completing movement of {0} into region {1} in position {2}",
  1891. client.Name, Scene.Name, AbsolutePosition);
  1892. m_inTransit = true;
  1893. try
  1894. {
  1895. // Make sure it's not a login agent. We don't want to wait for updates during login
  1896. if (!IsNPC && !IsRealLogin(m_teleportFlags))
  1897. {
  1898. // Let's wait until UpdateAgent (called by departing region) is done
  1899. if (!WaitForUpdateAgent(client))
  1900. // The sending region never sent the UpdateAgent data, we have to refuse
  1901. return;
  1902. }
  1903. //m_log.DebugFormat("[CompleteMovement] WaitForUpdateAgent: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1904. bool flying = ((m_AgentControlFlags & AgentManager.ControlFlags.AGENT_CONTROL_FLY) != 0);
  1905. Vector3 look = Lookat;
  1906. look.Z = 0f;
  1907. look.Normalize();
  1908. if ((Math.Abs(look.X) < 0.01) && (Math.Abs(look.Y) < 0.01))
  1909. {
  1910. look = Velocity;
  1911. look.Z = 0f;
  1912. look.Normalize();
  1913. if ((Math.Abs(look.X) < 0.01) && (Math.Abs(look.Y) < 0.01) )
  1914. look = new Vector3(0.99f, 0.042f, 0);
  1915. }
  1916. // Check Default Location (Also See EntityTransferModule.TeleportAgentWithinRegion)
  1917. if (AbsolutePosition.X == 128f && AbsolutePosition.Y == 128f && AbsolutePosition.Z == 22.5f)
  1918. AbsolutePosition = Scene.RegionInfo.DefaultLandingPoint;
  1919. if (!MakeRootAgent(AbsolutePosition, flying, ref look))
  1920. {
  1921. m_log.DebugFormat(
  1922. "[SCENE PRESENCE]: Aborting CompleteMovement call for {0} in {1} as they are already root",
  1923. Name, Scene.Name);
  1924. return;
  1925. }
  1926. if(IsChildAgent)
  1927. {
  1928. return; // how?
  1929. }
  1930. //m_log.DebugFormat("[CompleteMovement] MakeRootAgent: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1931. if (!IsNPC)
  1932. {
  1933. if (!m_haveGroupInformation)
  1934. {
  1935. IGroupsModule gm = m_scene.RequestModuleInterface<IGroupsModule>();
  1936. if (gm != null)
  1937. Grouptitle = gm.GetGroupTitle(m_uuid);
  1938. //m_log.DebugFormat("[CompleteMovement] Missing Grouptitle: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1939. /*
  1940. InventoryFolderBase cof = m_scene.InventoryService.GetFolderForType(client.AgentId, (FolderType)46);
  1941. if (cof == null)
  1942. COF = UUID.Zero;
  1943. else
  1944. COF = cof.ID;
  1945. m_log.DebugFormat("[CompleteMovement]: Missing COF for {0} is {1}", client.AgentId, COF);
  1946. */
  1947. }
  1948. }
  1949. if (m_teleportFlags > 0)
  1950. m_gotCrossUpdate = false; // sanity check
  1951. if (!m_gotCrossUpdate)
  1952. RotateToLookAt(look);
  1953. m_previusParcelHide = false;
  1954. m_previusParcelUUID = UUID.Zero;
  1955. m_currentParcelHide = false;
  1956. m_currentParcelUUID = UUID.Zero;
  1957. ParcelDwellTickMS = Util.GetTimeStampMS();
  1958. m_inTransit = false;
  1959. // Tell the client that we're ready to send rest
  1960. if (!m_gotCrossUpdate)
  1961. {
  1962. m_gotRegionHandShake = false; // allow it if not a crossing
  1963. ControllingClient.SendRegionHandshake();
  1964. }
  1965. ControllingClient.MoveAgentIntoRegion(m_scene.RegionInfo, AbsolutePosition, look);
  1966. bool isHGTP = (m_teleportFlags & TeleportFlags.ViaHGLogin) != 0;
  1967. if(!IsNPC)
  1968. {
  1969. if( ParentPart != null && (m_crossingFlags & 0x08) != 0)
  1970. {
  1971. ParentPart.ParentGroup.SendFullAnimUpdateToClient(ControllingClient);
  1972. }
  1973. // verify baked textures and cache
  1974. if (m_scene.AvatarFactory != null && !isHGTP)
  1975. {
  1976. if (!m_scene.AvatarFactory.ValidateBakedTextureCache(this))
  1977. m_scene.AvatarFactory.QueueAppearanceSave(UUID);
  1978. }
  1979. }
  1980. if(isHGTP)
  1981. {
  1982. // ControllingClient.SendNameReply(m_uuid, Firstname, Lastname);
  1983. m_log.DebugFormat("[CompleteMovement] HG");
  1984. }
  1985. if (!IsNPC)
  1986. {
  1987. GodController.SyncViewerState();
  1988. // start sending terrain patchs
  1989. if (!m_gotCrossUpdate)
  1990. Scene.SendLayerData(ControllingClient);
  1991. // send initial land overlay and parcel
  1992. ILandChannel landch = m_scene.LandChannel;
  1993. if (landch != null)
  1994. landch.sendClientInitialLandInfo(client, !m_gotCrossUpdate);
  1995. }
  1996. List<ScenePresence> allpresences = m_scene.GetScenePresences();
  1997. // send avatar object to all presences including us, so they cross it into region
  1998. // then hide if necessary
  1999. SendInitialAvatarDataToAllAgents(allpresences);
  2000. // send this look
  2001. if (!IsNPC)
  2002. SendAppearanceToAgent(this);
  2003. // send this animations
  2004. UUID[] animIDs = null;
  2005. int[] animseqs = null;
  2006. UUID[] animsobjs = null;
  2007. if (Animator != null)
  2008. Animator.GetArrays(out animIDs, out animseqs, out animsobjs);
  2009. bool haveAnims = (animIDs != null && animseqs != null && animsobjs != null);
  2010. if (!IsNPC && haveAnims)
  2011. SendAnimPackToAgent(this, animIDs, animseqs, animsobjs);
  2012. // send look and animations to others
  2013. // if not cached we send greys
  2014. // uncomented if will wait till avatar does baking
  2015. //if (cachedbaked)
  2016. {
  2017. foreach (ScenePresence p in allpresences)
  2018. {
  2019. if (p == this)
  2020. continue;
  2021. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  2022. continue;
  2023. SendAppearanceToAgentNF(p);
  2024. if (haveAnims)
  2025. SendAnimPackToAgentNF(p, animIDs, animseqs, animsobjs);
  2026. }
  2027. }
  2028. // attachments
  2029. if (IsNPC || IsRealLogin(m_teleportFlags))
  2030. {
  2031. if (Scene.AttachmentsModule != null)
  2032. {
  2033. if(IsNPC)
  2034. {
  2035. Util.FireAndForget(x =>
  2036. {
  2037. Scene.AttachmentsModule.RezAttachments(this);
  2038. });
  2039. }
  2040. else
  2041. Scene.AttachmentsModule.RezAttachments(this);
  2042. }
  2043. }
  2044. else
  2045. {
  2046. if (m_attachments.Count > 0)
  2047. {
  2048. foreach (SceneObjectGroup sog in m_attachments)
  2049. {
  2050. sog.RootPart.ParentGroup.CreateScriptInstances(0, false, m_scene.DefaultScriptEngine, GetStateSource());
  2051. sog.ResumeScripts();
  2052. }
  2053. foreach (ScenePresence p in allpresences)
  2054. {
  2055. if (p == this)
  2056. {
  2057. SendAttachmentsToAgentNF(this);
  2058. continue;
  2059. }
  2060. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  2061. continue;
  2062. SendAttachmentsToAgentNF(p);
  2063. }
  2064. }
  2065. }
  2066. if (!IsNPC)
  2067. {
  2068. if(m_gotCrossUpdate)
  2069. {
  2070. SendOtherAgentsAvatarFullToMe();
  2071. // Create child agents in neighbouring regions
  2072. IEntityTransferModule m_agentTransfer = m_scene.RequestModuleInterface<IEntityTransferModule>();
  2073. if (m_agentTransfer != null)
  2074. {
  2075. m_agentTransfer.EnableChildAgents(this);
  2076. }
  2077. m_lastChildUpdatesTime = Util.EnvironmentTickCount() + 10000;
  2078. m_lastChildAgentUpdatePosition = AbsolutePosition;
  2079. m_lastChildAgentCheckPosition = m_lastChildAgentUpdatePosition;
  2080. m_lastChildAgentUpdateDrawDistance = DrawDistance;
  2081. m_lastRegionsDrawDistance = RegionViewDistance;
  2082. m_lastChildAgentUpdateGodLevel = GodController.ViwerUIGodLevel;
  2083. m_childUpdatesBusy = false; // allow them
  2084. }
  2085. // send the rest of the world
  2086. //if (m_teleportFlags > 0 || m_currentParcelHide)
  2087. //SendInitialDataToMe();
  2088. //SendOtherAgentsAvatarFullToMe();
  2089. // priority uses avatar position only
  2090. // m_reprioritizationLastPosition = AbsolutePosition;
  2091. // m_reprioritizationLastDrawDistance = DrawDistance;
  2092. // m_reprioritizationLastTime = Util.EnvironmentTickCount() + 15000; // delay it
  2093. // m_reprioritizationBusy = false;
  2094. if (openChildAgents)
  2095. {
  2096. IFriendsModule friendsModule = m_scene.RequestModuleInterface<IFriendsModule>();
  2097. if (friendsModule != null)
  2098. {
  2099. if(m_gotCrossUpdate)
  2100. friendsModule.IsNowRoot(this);
  2101. else
  2102. friendsModule.SendFriendsOnlineIfNeeded(ControllingClient);
  2103. }
  2104. //m_log.DebugFormat("[CompleteMovement] friendsModule: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  2105. }
  2106. }
  2107. else
  2108. NeedInitialData = -1;
  2109. }
  2110. finally
  2111. {
  2112. m_haveGroupInformation = false;
  2113. m_gotCrossUpdate = false;
  2114. m_crossingFlags = 0;
  2115. m_inTransit = false;
  2116. }
  2117. m_scene.EventManager.OnRegionHeartbeatEnd += RegionHeartbeatEnd;
  2118. m_log.DebugFormat("[CompleteMovement] end: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  2119. }
  2120. /// <summary>
  2121. /// Callback for the Camera view block check. Gets called with the results of the camera view block test
  2122. /// hitYN is true when there's something in the way.
  2123. /// </summary>
  2124. /// <param name="hitYN"></param>
  2125. /// <param name="collisionPoint"></param>
  2126. /// <param name="localid"></param>
  2127. /// <param name="distance"></param>
  2128. ///
  2129. private void checkCameraCollision()
  2130. {
  2131. if(m_doingCamRayCast || !m_scene.PhysicsScene.SupportsRayCast())
  2132. return;
  2133. if(m_mouseLook || ParentID != 0)
  2134. {
  2135. if (CameraConstraintActive)
  2136. {
  2137. Vector4 plane = new Vector4(0.9f, 0.0f, 0.361f, -10000f); // not right...
  2138. UpdateCameraCollisionPlane(plane);
  2139. CameraConstraintActive = false;
  2140. }
  2141. return;
  2142. }
  2143. Vector3 posAdjusted = AbsolutePosition;
  2144. posAdjusted.Z += 1.0f; // viewer current camera focus point
  2145. if(posAdjusted.ApproxEquals(m_lastCameraRayCastPos, 0.2f) &&
  2146. CameraPosition.ApproxEquals(m_lastCameraRayCastCam, 0.2f))
  2147. return;
  2148. m_lastCameraRayCastCam = CameraPosition;
  2149. m_lastCameraRayCastPos = posAdjusted;
  2150. Vector3 tocam = CameraPosition - posAdjusted;
  2151. float distTocamlen = tocam.LengthSquared();
  2152. if (distTocamlen > 0.01f && distTocamlen < 400)
  2153. {
  2154. distTocamlen = (float)Math.Sqrt(distTocamlen);
  2155. tocam *= (1.0f / distTocamlen);
  2156. m_doingCamRayCast = true;
  2157. m_scene.PhysicsScene.RaycastWorld(posAdjusted, tocam, distTocamlen + 1.0f, RayCastCameraCallback);
  2158. return;
  2159. }
  2160. if (CameraConstraintActive)
  2161. {
  2162. Vector4 plane = new Vector4(0.9f, 0.0f, 0.361f, -10000f); // not right...
  2163. UpdateCameraCollisionPlane(plane);
  2164. CameraConstraintActive = false;
  2165. }
  2166. }
  2167. private void UpdateCameraCollisionPlane(Vector4 plane)
  2168. {
  2169. if (m_lastCameraCollisionPlane != plane)
  2170. {
  2171. m_lastCameraCollisionPlane = plane;
  2172. ControllingClient.SendCameraConstraint(plane);
  2173. }
  2174. }
  2175. public void RayCastCameraCallback(bool hitYN, Vector3 collisionPoint, uint localid, float distance, Vector3 pNormal)
  2176. {
  2177. if (hitYN && localid != LocalId)
  2178. {
  2179. if (localid != 0)
  2180. {
  2181. SceneObjectPart part = m_scene.GetSceneObjectPart(localid);
  2182. if (part != null && !part.VolumeDetectActive)
  2183. {
  2184. CameraConstraintActive = true;
  2185. pNormal.X = (float) Math.Round(pNormal.X, 2);
  2186. pNormal.Y = (float) Math.Round(pNormal.Y, 2);
  2187. pNormal.Z = (float) Math.Round(pNormal.Z, 2);
  2188. pNormal.Normalize();
  2189. collisionPoint.X = (float) Math.Round(collisionPoint.X, 1);
  2190. collisionPoint.Y = (float) Math.Round(collisionPoint.Y, 1);
  2191. collisionPoint.Z = (float) Math.Round(collisionPoint.Z, 1);
  2192. Vector4 plane = new Vector4(pNormal.X, pNormal.Y, pNormal.Z,
  2193. Vector3.Dot(collisionPoint, pNormal));
  2194. UpdateCameraCollisionPlane(plane);
  2195. }
  2196. }
  2197. else
  2198. {
  2199. CameraConstraintActive = true;
  2200. pNormal.X = (float) Math.Round(pNormal.X, 2);
  2201. pNormal.Y = (float) Math.Round(pNormal.Y, 2);
  2202. pNormal.Z = (float) Math.Round(pNormal.Z, 2);
  2203. pNormal.Normalize();
  2204. collisionPoint.X = (float) Math.Round(collisionPoint.X, 1);
  2205. collisionPoint.Y = (float) Math.Round(collisionPoint.Y, 1);
  2206. collisionPoint.Z = (float) Math.Round(collisionPoint.Z, 1);
  2207. Vector4 plane = new Vector4(pNormal.X, pNormal.Y, pNormal.Z,
  2208. Vector3.Dot(collisionPoint, pNormal));
  2209. UpdateCameraCollisionPlane(plane);
  2210. }
  2211. }
  2212. else if(CameraConstraintActive)
  2213. {
  2214. Vector4 plane = new Vector4(0.9f, 0.0f, 0.361f, -9000f); // not right...
  2215. UpdateCameraCollisionPlane(plane);
  2216. CameraConstraintActive = false;
  2217. }
  2218. m_doingCamRayCast = false;
  2219. }
  2220. /// <summary>
  2221. /// This is the event handler for client movement. If a client is moving, this event is triggering.
  2222. /// </summary>
  2223. public void HandleAgentUpdate(IClientAPI remoteClient, AgentUpdateArgs agentData)
  2224. {
  2225. // m_log.DebugFormat(
  2226. // "[SCENE PRESENCE]: In {0} received agent update from {1}, flags {2}",
  2227. // Scene.Name, remoteClient.Name, (AgentManager.ControlFlags)agentData.ControlFlags);
  2228. if (IsChildAgent)
  2229. {
  2230. // m_log.DebugFormat("DEBUG: HandleAgentUpdate: child agent in {0}", Scene.Name);
  2231. return;
  2232. }
  2233. if (IsInTransit)
  2234. return;
  2235. #region Sanity Checking
  2236. // This is irritating. Really.
  2237. if (!AbsolutePosition.IsFinite())
  2238. {
  2239. bool isphysical = PhysicsActor != null;
  2240. if(isphysical)
  2241. RemoveFromPhysicalScene();
  2242. m_log.Error("[AVATAR]: NonFinite Avatar position detected... Reset Position. Mantis this please. Error #9999902");
  2243. m_pos = m_LastFinitePos;
  2244. if (!m_pos.IsFinite())
  2245. {
  2246. m_pos.X = 127f;
  2247. m_pos.Y = 127f;
  2248. m_pos.Z = 127f;
  2249. m_log.Error("[AVATAR]: NonFinite Avatar on lastFiniteposition also. Reset Position. Mantis this please. Error #9999903");
  2250. }
  2251. if(isphysical)
  2252. AddToPhysicalScene(false);
  2253. }
  2254. else
  2255. {
  2256. m_LastFinitePos = m_pos;
  2257. }
  2258. #endregion Sanity Checking
  2259. #region Inputs
  2260. AgentManager.ControlFlags flags = (AgentManager.ControlFlags)agentData.ControlFlags;
  2261. // The Agent's Draw distance setting
  2262. // When we get to the point of re-computing neighbors everytime this
  2263. // changes, then start using the agent's drawdistance rather than the
  2264. // region's draw distance.
  2265. DrawDistance = agentData.Far;
  2266. m_mouseLook = (flags & AgentManager.ControlFlags.AGENT_CONTROL_MOUSELOOK) != 0;
  2267. // FIXME: This does not work as intended because the viewer only sends the lbutton down when the button
  2268. // is first pressed, not whilst it is held down. If this is required in the future then need to look
  2269. // for an AGENT_CONTROL_LBUTTON_UP event and make sure to handle cases where an initial DOWN is not
  2270. // received (e.g. on holding LMB down on the avatar in a viewer).
  2271. m_leftButtonDown = (flags & AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN) != 0;
  2272. #endregion Inputs
  2273. // // Make anims work for client side autopilot
  2274. // if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_AT_POS) != 0)
  2275. // m_updateCount = UPDATE_COUNT;
  2276. //
  2277. // // Make turning in place work
  2278. // if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS) != 0 ||
  2279. // (flags & AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG) != 0)
  2280. // m_updateCount = UPDATE_COUNT;
  2281. if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_STAND_UP) != 0)
  2282. {
  2283. StandUp();
  2284. }
  2285. // Raycast from the avatar's head to the camera to see if there's anything blocking the view
  2286. // this exclude checks may not be complete
  2287. if(agentData.NeedsCameraCollision) // condition parentID may be wrong
  2288. checkCameraCollision();
  2289. uint flagsForScripts = (uint)flags;
  2290. flags = RemoveIgnoredControls(flags, IgnoredControls);
  2291. if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_SIT_ON_GROUND) != 0)
  2292. HandleAgentSitOnGround();
  2293. // In the future, these values might need to go global.
  2294. // Here's where you get them.
  2295. m_AgentControlFlags = flags;
  2296. m_headrotation = agentData.HeadRotation;
  2297. byte oldState = State;
  2298. State = agentData.State;
  2299. // We need to send this back to the client in order to stop the edit beams
  2300. if ((oldState & (uint)AgentState.Editing) != 0 && State == (uint)AgentState.None)
  2301. SendAgentTerseUpdate(this);
  2302. PhysicsActor actor = PhysicsActor;
  2303. // This will be the case if the agent is sitting on the groudn or on an object.
  2304. if (actor == null)
  2305. {
  2306. SendControlsToScripts(flagsForScripts);
  2307. return;
  2308. }
  2309. if (AllowMovement && !SitGround)
  2310. {
  2311. // m_log.DebugFormat("[SCENE PRESENCE]: Initial body rotation {0} for {1}", agentData.BodyRotation, Name);
  2312. bool update_rotation = false;
  2313. if (!IsSatOnObject && agentData.BodyRotation != Rotation)
  2314. {
  2315. Rotation = agentData.BodyRotation;
  2316. update_rotation = true;
  2317. }
  2318. bool update_movementflag = false;
  2319. bool mvToTarget = m_movingToTarget;
  2320. if (agentData.UseClientAgentPosition)
  2321. {
  2322. m_movingToTarget = (agentData.ClientAgentPosition - AbsolutePosition).LengthSquared() > 0.04f;
  2323. m_moveToPositionTarget = agentData.ClientAgentPosition;
  2324. m_moveToSpeed = -1f;
  2325. }
  2326. int i = 0;
  2327. bool DCFlagKeyPressed = false;
  2328. Vector3 agent_control_v3 = Vector3.Zero;
  2329. bool newFlying = false;
  2330. if (ForceFly)
  2331. newFlying = true;
  2332. else if (FlyDisabled)
  2333. newFlying = false;
  2334. else if(mvToTarget)
  2335. newFlying = actor.Flying;
  2336. else
  2337. newFlying = ((flags & AgentManager.ControlFlags.AGENT_CONTROL_FLY) != 0);
  2338. if (actor.Flying != newFlying)
  2339. {
  2340. // Note: ScenePresence.Flying is actually fetched from the physical actor
  2341. // so setting PhysActor.Flying here also sets the ScenePresence's value.
  2342. actor.Flying = newFlying;
  2343. update_movementflag = true;
  2344. }
  2345. if (ParentID == 0)
  2346. {
  2347. bool bAllowUpdateMoveToPosition = false;
  2348. Vector3[] dirVectors;
  2349. // use camera up angle when in mouselook and not flying or when holding the left mouse button down and not flying
  2350. // this prevents 'jumping' in inappropriate situations.
  2351. // if (!Flying && (m_mouseLook || m_leftButtonDown))
  2352. // dirVectors = GetWalkDirectionVectors();
  2353. // else
  2354. dirVectors = Dir_Vectors;
  2355. // A DIR_CONTROL_FLAG occurs when the user is trying to move in a particular direction.
  2356. foreach (Dir_ControlFlags DCF in DIR_CONTROL_FLAGS)
  2357. {
  2358. if (((uint)flags & (uint)DCF) != 0)
  2359. {
  2360. DCFlagKeyPressed = true;
  2361. try
  2362. {
  2363. agent_control_v3 += Dir_Vectors[i];
  2364. //m_log.DebugFormat("[Motion]: {0}, {1}",i, dirVectors[i]);
  2365. }
  2366. catch (IndexOutOfRangeException)
  2367. {
  2368. // Why did I get this?
  2369. }
  2370. if (((MovementFlag & (uint)DCF) == 0))
  2371. {
  2372. //m_log.DebugFormat("[SCENE PRESENCE]: Updating MovementFlag for {0} with {1}", Name, DCF);
  2373. MovementFlag |= (uint)DCF;
  2374. update_movementflag = true;
  2375. }
  2376. }
  2377. else
  2378. {
  2379. if ((MovementFlag & (uint)DCF) != 0)
  2380. {
  2381. //m_log.DebugFormat("[SCENE PRESENCE]: Updating MovementFlag for {0} with lack of {1}", Name, DCF);
  2382. MovementFlag &= (uint)~DCF;
  2383. update_movementflag = true;
  2384. /*
  2385. if ((DCF == Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD_NUDGE || DCF == Dir_ControlFlags.DIR_CONTROL_FLAG_BACKWARD_NUDGE)
  2386. && ((MovementFlag & (byte)nudgehack) == nudgehack))
  2387. {
  2388. m_log.Debug("Removed Hack flag");
  2389. }
  2390. */
  2391. }
  2392. else
  2393. {
  2394. bAllowUpdateMoveToPosition = true;
  2395. }
  2396. }
  2397. i++;
  2398. }
  2399. // Detect AGENT_CONTROL_STOP state changes
  2400. if (AgentControlStopActive != ((flags & AgentManager.ControlFlags.AGENT_CONTROL_STOP) != 0))
  2401. {
  2402. AgentControlStopActive = !AgentControlStopActive;
  2403. update_movementflag = true;
  2404. }
  2405. if (m_movingToTarget)
  2406. {
  2407. // If the user has pressed a key then we want to cancel any move to target.
  2408. if (DCFlagKeyPressed)
  2409. {
  2410. ResetMoveToTarget();
  2411. update_movementflag = true;
  2412. }
  2413. else if (bAllowUpdateMoveToPosition)
  2414. {
  2415. // The UseClientAgentPosition is set if parcel ban is forcing the avatar to move to a
  2416. // certain position. It's only check for tolerance on returning to that position is 0.2
  2417. // rather than 1, at which point it removes its force target.
  2418. if (HandleMoveToTargetUpdate(agentData.UseClientAgentPosition ? 0.2f : 0.5f, ref agent_control_v3))
  2419. update_movementflag = true;
  2420. }
  2421. }
  2422. }
  2423. // Cause the avatar to stop flying if it's colliding
  2424. // with something with the down arrow pressed.
  2425. // Only do this if we're flying
  2426. if (Flying && !ForceFly)
  2427. {
  2428. // Need to stop in mid air if user holds down AGENT_CONTROL_STOP
  2429. // if (AgentControlStopActive)
  2430. // {
  2431. // agent_control_v3 = Vector3.Zero;
  2432. // }
  2433. // else
  2434. {
  2435. // Landing detection code
  2436. // Are the landing controls requirements filled?
  2437. bool controlland = (((flags & AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0) ||
  2438. ((flags & AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG) != 0));
  2439. //m_log.Debug("[CONTROL]: " +flags);
  2440. // Applies a satisfying roll effect to the avatar when flying.
  2441. if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_TURN_LEFT) != 0 && (flags & AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS) != 0)
  2442. {
  2443. ApplyFlyingRoll(
  2444. FLY_ROLL_RADIANS_PER_UPDATE,
  2445. (flags & AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) != 0,
  2446. (flags & AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0);
  2447. }
  2448. else if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_TURN_RIGHT) != 0 &&
  2449. (flags & AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG) != 0)
  2450. {
  2451. ApplyFlyingRoll(
  2452. -FLY_ROLL_RADIANS_PER_UPDATE,
  2453. (flags & AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) != 0,
  2454. (flags & AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0);
  2455. }
  2456. else
  2457. {
  2458. if (m_AngularVelocity.Z != 0)
  2459. m_AngularVelocity.Z += CalculateFlyingRollResetToZero(FLY_ROLL_RESET_RADIANS_PER_UPDATE);
  2460. }
  2461. /*
  2462. if (Flying && IsColliding && controlland)
  2463. {
  2464. // nesting this check because LengthSquared() is expensive and we don't
  2465. // want to do it every step when flying.
  2466. if ((Velocity.LengthSquared() <= LAND_VELOCITYMAG_MAX))
  2467. StopFlying();
  2468. }
  2469. */
  2470. }
  2471. }
  2472. else if (IsColliding && agent_control_v3.Z < 0f)
  2473. agent_control_v3.Z = 0;
  2474. // else if(AgentControlStopActive %% Velocity.Z <0.01f)
  2475. // m_log.DebugFormat("[SCENE PRESENCE]: MovementFlag {0} for {1}", MovementFlag, Name);
  2476. // If the agent update does move the avatar, then calculate the force ready for the velocity update,
  2477. // which occurs later in the main scene loop
  2478. // We also need to update if the user rotates their avatar whilst it is slow walking/running (if they
  2479. // held down AGENT_CONTROL_STOP whilst normal walking/running). However, we do not want to update
  2480. // if the user rotated whilst holding down AGENT_CONTROL_STOP when already still (which locks the
  2481. // avatar location in place).
  2482. if (update_movementflag
  2483. || (update_rotation && DCFlagKeyPressed && (!AgentControlStopActive || MovementFlag != 0)))
  2484. {
  2485. if (AgentControlStopActive)
  2486. {
  2487. // if (MovementFlag == 0 && Animator.Falling)
  2488. if (MovementFlag == 0 && Animator.currentControlState == ScenePresenceAnimator.motionControlStates.falling)
  2489. {
  2490. AddNewMovement(agent_control_v3, AgentControlStopSlowVel, true);
  2491. }
  2492. else
  2493. AddNewMovement(agent_control_v3, AgentControlStopSlowVel);
  2494. }
  2495. else
  2496. {
  2497. if(m_movingToTarget ||
  2498. (Animator.currentControlState != ScenePresenceAnimator.motionControlStates.flying &&
  2499. Animator.currentControlState != ScenePresenceAnimator.motionControlStates.onsurface)
  2500. )
  2501. AddNewMovement(agent_control_v3);
  2502. else
  2503. {
  2504. if (MovementFlag != 0)
  2505. AddNewMovement(agent_control_v3);
  2506. else
  2507. m_delayedStop = Util.GetTimeStampMS() + 200.0;
  2508. }
  2509. }
  2510. }
  2511. /*
  2512. if (update_movementflag && ParentID == 0 && m_delayedStop < 0)
  2513. {
  2514. // m_log.DebugFormat("[SCENE PRESENCE]: Updating movement animations for {0}", Name);
  2515. Animator.UpdateMovementAnimations();
  2516. }
  2517. */
  2518. SendControlsToScripts(flagsForScripts);
  2519. }
  2520. // We need to send this back to the client in order to see the edit beams
  2521. if ((State & (uint)AgentState.Editing) != 0)
  2522. SendAgentTerseUpdate(this);
  2523. // m_scene.EventManager.TriggerOnClientMovement(this);
  2524. }
  2525. private void HandleAgentFOV(IClientAPI remoteClient, float _fov)
  2526. {
  2527. m_FOV = _fov;
  2528. }
  2529. /// <summary>
  2530. /// This is the event handler for client cameras. If a client is moving, or moving the camera, this event is triggering.
  2531. /// </summary>
  2532. private void HandleAgentCamerasUpdate(IClientAPI remoteClient, AgentUpdateArgs agentData)
  2533. {
  2534. //m_log.DebugFormat(
  2535. // "[SCENE PRESENCE]: In {0} received agent camera update from {1}, flags {2}",
  2536. // Scene.RegionInfo.RegionName, remoteClient.Name, (AgentManager.ControlFlags)agentData.ControlFlags);
  2537. if (IsChildAgent)
  2538. return;
  2539. if(IsInTransit)
  2540. return;
  2541. // AgentManager.ControlFlags flags = (AgentManager.ControlFlags)agentData.ControlFlags;
  2542. // Camera location in world. We'll need to raytrace
  2543. // from this location from time to time.
  2544. CameraPosition = agentData.CameraCenter;
  2545. // Use these three vectors to figure out what the agent is looking at
  2546. // Convert it to a Matrix and/or Quaternion
  2547. // this may need lock
  2548. CameraAtAxis = agentData.CameraAtAxis;
  2549. CameraLeftAxis = agentData.CameraLeftAxis;
  2550. CameraUpAxis = agentData.CameraUpAxis;
  2551. DrawDistance = agentData.Far;
  2552. CameraAtAxis.Normalize();
  2553. CameraLeftAxis.Normalize();
  2554. CameraUpAxis.Normalize();
  2555. Quaternion camRot = Util.Axes2Rot(CameraAtAxis, CameraLeftAxis, CameraUpAxis);
  2556. CameraRotation = camRot;
  2557. if(agentData.NeedsCameraCollision)
  2558. checkCameraCollision();
  2559. TriggerScenePresenceUpdated();
  2560. }
  2561. /// <summary>
  2562. /// Calculate an update to move the presence to the set target.
  2563. /// </summary>
  2564. /// <remarks>
  2565. /// This doesn't actually perform the movement. Instead, it adds its vector to agent_control_v3.
  2566. /// </remarks>
  2567. /// <param value="agent_control_v3">Cumulative agent movement that this method will update.</param>
  2568. /// <returns>True if movement has been updated in some way. False otherwise.</returns>
  2569. public bool HandleMoveToTargetUpdate(float tolerance, ref Vector3 agent_control_v3)
  2570. {
  2571. // m_log.DebugFormat("[SCENE PRESENCE]: Called HandleMoveToTargetUpdate() for {0}", Name);
  2572. bool updated = false;
  2573. Vector3 LocalVectorToTarget3D = m_moveToPositionTarget - AbsolutePosition;
  2574. // m_log.DebugFormat(
  2575. // "[SCENE PRESENCE]: bAllowUpdateMoveToPosition {0}, m_moveToPositionInProgress {1}, m_autopilotMoving {2}",
  2576. // allowUpdate, m_moveToPositionInProgress, m_autopilotMoving);
  2577. float distanceToTarget;
  2578. if(Flying && !LandAtTarget)
  2579. distanceToTarget = LocalVectorToTarget3D.LengthSquared();
  2580. else
  2581. distanceToTarget = (LocalVectorToTarget3D.X * LocalVectorToTarget3D.X) + (LocalVectorToTarget3D.Y * LocalVectorToTarget3D.Y);
  2582. // m_log.DebugFormat(
  2583. // "[SCENE PRESENCE]: Abs pos of {0} is {1}, target {2}, distance {3}",
  2584. // Name, AbsolutePosition, MoveToPositionTarget, distanceToTarget);
  2585. // Check the error term of the current position in relation to the target position
  2586. if (distanceToTarget <= tolerance * tolerance)
  2587. {
  2588. // We are close enough to the target
  2589. Velocity = Vector3.Zero;
  2590. if (Flying)
  2591. {
  2592. if (LandAtTarget)
  2593. {
  2594. Flying = false;
  2595. // A horrible hack to stop the avatar dead in its tracks rather than having them overshoot
  2596. // the target if flying.
  2597. // We really need to be more subtle (slow the avatar as it approaches the target) or at
  2598. // least be able to set collision status once, rather than 5 times to give it enough
  2599. // weighting so that that PhysicsActor thinks it really is colliding.
  2600. for (int i = 0; i < 5; i++)
  2601. IsColliding = true;
  2602. }
  2603. }
  2604. else
  2605. m_moveToPositionTarget.Z = AbsolutePosition.Z;
  2606. AbsolutePosition = m_moveToPositionTarget;
  2607. ResetMoveToTarget();
  2608. return false;
  2609. }
  2610. if (m_moveToSpeed > 0 &&
  2611. distanceToTarget <= m_moveToSpeed * m_moveToSpeed * Scene.FrameTime * Scene.FrameTime)
  2612. m_moveToSpeed = (float)Math.Sqrt(distanceToTarget) / Scene.FrameTime;
  2613. try
  2614. {
  2615. // move avatar in 3D towards target, in avatar coordinate frame.
  2616. // This movement vector gets added to the velocity through AddNewMovement().
  2617. // Theoretically we might need a more complex PID approach here if other
  2618. // unknown forces are acting on the avatar and we need to adaptively respond
  2619. // to such forces, but the following simple approach seems to works fine.
  2620. float angle = 0.5f * (float)Math.Atan2(LocalVectorToTarget3D.Y, LocalVectorToTarget3D.X);
  2621. Quaternion rot = new Quaternion(0,0, (float)Math.Sin(angle),(float)Math.Cos(angle));
  2622. Rotation = rot;
  2623. LocalVectorToTarget3D = LocalVectorToTarget3D * Quaternion.Inverse(rot); // change to avatar coords
  2624. if(!Flying)
  2625. LocalVectorToTarget3D.Z = 0;
  2626. LocalVectorToTarget3D.Normalize();
  2627. // update avatar movement flags. the avatar coordinate system is as follows:
  2628. //
  2629. // +X (forward)
  2630. //
  2631. // ^
  2632. // |
  2633. // |
  2634. // |
  2635. // |
  2636. // (left) +Y <--------o--------> -Y
  2637. // avatar
  2638. // |
  2639. // |
  2640. // |
  2641. // |
  2642. // v
  2643. // -X
  2644. //
  2645. // based on the above avatar coordinate system, classify the movement into
  2646. // one of left/right/back/forward.
  2647. const uint noMovFlagsMask = (uint)(~(Dir_ControlFlags.DIR_CONTROL_FLAG_BACK |
  2648. Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD | Dir_ControlFlags.DIR_CONTROL_FLAG_LEFT |
  2649. Dir_ControlFlags.DIR_CONTROL_FLAG_RIGHT | Dir_ControlFlags.DIR_CONTROL_FLAG_UP |
  2650. Dir_ControlFlags.DIR_CONTROL_FLAG_DOWN));
  2651. MovementFlag &= noMovFlagsMask;
  2652. uint tmpAgentControlFlags = (uint)m_AgentControlFlags;
  2653. tmpAgentControlFlags &= noMovFlagsMask;
  2654. if (LocalVectorToTarget3D.X < 0) //MoveBack
  2655. {
  2656. MovementFlag |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_BACK;
  2657. tmpAgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_BACK;
  2658. updated = true;
  2659. }
  2660. else if (LocalVectorToTarget3D.X > 0) //Move Forward
  2661. {
  2662. MovementFlag |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD;
  2663. tmpAgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD;
  2664. updated = true;
  2665. }
  2666. if (LocalVectorToTarget3D.Y > 0) //MoveLeft
  2667. {
  2668. MovementFlag |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_LEFT;
  2669. tmpAgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_LEFT;
  2670. updated = true;
  2671. }
  2672. else if (LocalVectorToTarget3D.Y < 0) //MoveRight
  2673. {
  2674. MovementFlag |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_RIGHT;
  2675. tmpAgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_RIGHT;
  2676. updated = true;
  2677. }
  2678. if (LocalVectorToTarget3D.Z > 0) //Up
  2679. updated = true;
  2680. else if (LocalVectorToTarget3D.Z < 0) //Down
  2681. updated = true;
  2682. // m_log.DebugFormat(
  2683. // "[SCENE PRESENCE]: HandleMoveToTargetUpdate adding {0} to move vector {1} for {2}",
  2684. // LocalVectorToTarget3D, agent_control_v3, Name);
  2685. m_AgentControlFlags = (AgentManager.ControlFlags) tmpAgentControlFlags;
  2686. if(updated)
  2687. agent_control_v3 += LocalVectorToTarget3D;
  2688. }
  2689. catch (Exception e)
  2690. {
  2691. //Avoid system crash, can be slower but...
  2692. m_log.DebugFormat("Crash! {0}", e.ToString());
  2693. }
  2694. return updated;
  2695. // AddNewMovement(agent_control_v3);
  2696. }
  2697. public void MoveToTargetHandle(Vector3 pos, bool noFly, bool landAtTarget)
  2698. {
  2699. MoveToTarget(pos, noFly, landAtTarget, false);
  2700. }
  2701. /// <summary>
  2702. /// Move to the given target over time.
  2703. /// </summary>
  2704. /// <param name="pos"></param>
  2705. /// <param name="noFly">
  2706. /// If true, then don't allow the avatar to fly to the target, even if it's up in the air.
  2707. /// This is to allow movement to targets that are known to be on an elevated platform with a continuous path
  2708. /// from start to finish.
  2709. /// </param>
  2710. /// <param name="landAtTarget">
  2711. /// If true and the avatar starts flying during the move then land at the target.
  2712. /// </param>
  2713. public void MoveToTarget(Vector3 pos, bool noFly, bool landAtTarget, bool running, float tau = -1f)
  2714. {
  2715. m_delayedStop = -1;
  2716. if (IsSitting)
  2717. StandUp();
  2718. // m_log.DebugFormat(
  2719. // "[SCENE PRESENCE]: Avatar {0} received request to move to position {1} in {2}",
  2720. // Name, pos, m_scene.RegionInfo.RegionName);
  2721. // Allow move to another sub-region within a megaregion
  2722. Vector2 regionSize;
  2723. regionSize = new Vector2(m_scene.RegionInfo.RegionSizeX, m_scene.RegionInfo.RegionSizeY);
  2724. if (pos.X < 0.5f)
  2725. pos.X = 0.5f;
  2726. else if (pos.X > regionSize.X - 0.5f)
  2727. pos.X = regionSize.X - 0.5f;
  2728. if (pos.Y < 0.5f)
  2729. pos.Y = 0.5f;
  2730. else if (pos.Y > regionSize.Y - 0.5f)
  2731. pos.Y = regionSize.Y - 0.5f;
  2732. float terrainHeight;
  2733. Scene targetScene = m_scene;
  2734. terrainHeight = m_scene.GetGroundHeight(pos.X, pos.Y);
  2735. // dont try to land underground
  2736. terrainHeight += Appearance.AvatarHeight * 0.5f + 0.2f;
  2737. if(terrainHeight > pos.Z)
  2738. pos.Z = terrainHeight;
  2739. // m_log.DebugFormat(
  2740. // "[SCENE PRESENCE]: Avatar {0} set move to target {1} (terrain height {2}) in {3}",
  2741. // Name, pos, terrainHeight, m_scene.RegionInfo.RegionName);
  2742. bool shouldfly = true;
  2743. if(IsNPC)
  2744. {
  2745. if (!Flying)
  2746. shouldfly = noFly ? false : (pos.Z > terrainHeight + Appearance.AvatarHeight);
  2747. LandAtTarget = landAtTarget & shouldfly;
  2748. }
  2749. else
  2750. {
  2751. // we have no control on viewer fly state
  2752. shouldfly = Flying || (pos.Z > terrainHeight + Appearance.AvatarHeight);
  2753. LandAtTarget = false;
  2754. }
  2755. // m_log.DebugFormat("[SCENE PRESENCE]: Local vector to target is {0},[1}", localVectorToTarget3D.X,localVectorToTarget3D.Y);
  2756. m_movingToTarget = true;
  2757. m_moveToPositionTarget = pos;
  2758. if(tau > 0)
  2759. {
  2760. if(tau < Scene.FrameTime)
  2761. tau = Scene.FrameTime;
  2762. Vector3 localVectorToTarget3D = pos - AbsolutePosition;
  2763. if (!shouldfly)
  2764. localVectorToTarget3D.Z = 0;
  2765. m_moveToSpeed = localVectorToTarget3D.Length() / tau;
  2766. if(m_moveToSpeed < 0.5f) //to tune
  2767. m_moveToSpeed = 0.5f;
  2768. else if(m_moveToSpeed > 50f)
  2769. m_moveToSpeed = 50f;
  2770. }
  2771. else
  2772. m_moveToSpeed = 4.096f * m_speedModifier;
  2773. SetAlwaysRun = running;
  2774. Flying = shouldfly;
  2775. Vector3 control = Vector3.Zero;
  2776. if(HandleMoveToTargetUpdate(0.5f, ref control))
  2777. AddNewMovement(control);
  2778. }
  2779. /// <summary>
  2780. /// Reset the move to target.
  2781. /// </summary>
  2782. public void ResetMoveToTarget()
  2783. {
  2784. // m_log.DebugFormat("[SCENE PRESENCE]: Resetting move to target for {0}", Name);
  2785. m_movingToTarget = false;
  2786. m_moveToSpeed = -1f;
  2787. // MoveToPositionTarget = Vector3.Zero;
  2788. // lock(m_forceToApplyLock)
  2789. // m_forceToApplyValid = false; // cancel possible last action
  2790. // We need to reset the control flag as the ScenePresenceAnimator uses this to determine the correct
  2791. // resting animation (e.g. hover or stand). NPCs don't have a client that will quickly reset this flag.
  2792. // However, the line is here rather than in the NPC module since it also appears necessary to stop a
  2793. // viewer that uses "go here" from juddering on all subsequent avatar movements.
  2794. AgentControlFlags = (uint)AgentManager.ControlFlags.NONE;
  2795. if(IsNPC)
  2796. Animator.UpdateMovementAnimations();
  2797. }
  2798. /// <summary>
  2799. /// Perform the logic necessary to stand the avatar up. This method also executes
  2800. /// the stand animation.
  2801. /// </summary>
  2802. public void StandUp(bool addPhys = true)
  2803. {
  2804. // m_log.DebugFormat("[SCENE PRESENCE]: StandUp() for {0}", Name);
  2805. bool satOnObject = IsSatOnObject;
  2806. SceneObjectPart part = ParentPart;
  2807. SitGround = false;
  2808. if (satOnObject)
  2809. {
  2810. PrevSitOffset = m_pos; // Save sit offset
  2811. UnRegisterSeatControls(part.ParentGroup.UUID);
  2812. TaskInventoryDictionary taskIDict = part.TaskInventory;
  2813. if (taskIDict != null)
  2814. {
  2815. lock (taskIDict)
  2816. {
  2817. foreach (UUID taskID in taskIDict.Keys)
  2818. {
  2819. UnRegisterControlEventsToScript(LocalId, taskID);
  2820. taskIDict[taskID].PermsMask &= ~(
  2821. 2048 | //PERMISSION_CONTROL_CAMERA
  2822. 4); // PERMISSION_TAKE_CONTROLS
  2823. }
  2824. }
  2825. }
  2826. ControllingClient.SendClearFollowCamProperties(part.ParentUUID);
  2827. ParentID = 0;
  2828. ParentPart = null;
  2829. Quaternion standRotation = part.ParentGroup.RootPart.RotationOffset;
  2830. Vector3 sitWorldPosition = part.ParentGroup.AbsolutePosition + m_pos * standRotation;
  2831. standRotation = standRotation * m_bodyRot;
  2832. m_bodyRot = standRotation;
  2833. Quaternion standRotationZ;
  2834. Vector3 adjustmentForSitPose = part.StandOffset;
  2835. if (adjustmentForSitPose.X == 0 &&
  2836. adjustmentForSitPose.Y == 0 &&
  2837. adjustmentForSitPose.Z == 0)
  2838. {
  2839. standRotationZ = new Quaternion(0, 0, standRotation.Z, standRotation.W);
  2840. float t = standRotationZ.W * standRotationZ.W + standRotationZ.Z * standRotationZ.Z;
  2841. if (t > 0)
  2842. {
  2843. t = 1.0f / (float)Math.Sqrt(t);
  2844. standRotationZ.W *= t;
  2845. standRotationZ.Z *= t;
  2846. }
  2847. else
  2848. {
  2849. standRotationZ.W = 1.0f;
  2850. standRotationZ.Z = 0f;
  2851. }
  2852. adjustmentForSitPose = new Vector3(0.65f, 0, m_sitAvatarHeight * 0.5f + .1f) * standRotationZ;
  2853. }
  2854. else
  2855. {
  2856. sitWorldPosition = part.GetWorldPosition();
  2857. standRotation = part.GetWorldRotation();
  2858. standRotationZ = new Quaternion(0, 0, standRotation.Z, standRotation.W);
  2859. float t = standRotationZ.W * standRotationZ.W + standRotationZ.Z * standRotationZ.Z;
  2860. if (t > 0)
  2861. {
  2862. t = 1.0f / (float)Math.Sqrt(t);
  2863. standRotationZ.W *= t;
  2864. standRotationZ.Z *= t;
  2865. }
  2866. else
  2867. {
  2868. standRotationZ.W = 1.0f;
  2869. standRotationZ.Z = 0f;
  2870. }
  2871. adjustmentForSitPose *= standRotationZ;
  2872. if (Appearance != null && Appearance.AvatarHeight > 0)
  2873. adjustmentForSitPose.Z += 0.5f * Appearance.AvatarHeight + .1f;
  2874. else
  2875. adjustmentForSitPose.Z += .9f;
  2876. }
  2877. m_pos = sitWorldPosition + adjustmentForSitPose;
  2878. }
  2879. if (addPhys && PhysicsActor == null)
  2880. AddToPhysicalScene(false);
  2881. if (satOnObject)
  2882. {
  2883. m_requestedSitTargetID = 0;
  2884. part.RemoveSittingAvatar(this);
  2885. part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK);
  2886. SendAvatarDataToAllAgents();
  2887. m_scene.EventManager.TriggerParcelPrimCountTainted(); // update select/ sat on
  2888. }
  2889. // reset to default sitAnimation
  2890. sitAnimation = "SIT";
  2891. Animator.SetMovementAnimations("STAND");
  2892. TriggerScenePresenceUpdated();
  2893. }
  2894. private SceneObjectPart FindNextAvailableSitTarget(UUID targetID)
  2895. {
  2896. SceneObjectPart targetPart = m_scene.GetSceneObjectPart(targetID);
  2897. if (targetPart == null)
  2898. return null;
  2899. // If the primitive the player clicked on has a sit target and that sit target is not full, that sit target is used.
  2900. // 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.
  2901. // Get our own copy of the part array, and sort into the order we want to test
  2902. SceneObjectPart[] partArray = targetPart.ParentGroup.Parts;
  2903. Array.Sort(partArray, delegate(SceneObjectPart p1, SceneObjectPart p2)
  2904. {
  2905. // we want the originally selected part first, then the rest in link order -- so make the selected part link num (-1)
  2906. int linkNum1 = p1==targetPart ? -1 : p1.LinkNum;
  2907. int linkNum2 = p2==targetPart ? -1 : p2.LinkNum;
  2908. return linkNum1 - linkNum2;
  2909. }
  2910. );
  2911. //look for prims with explicit sit targets that are available
  2912. foreach (SceneObjectPart part in partArray)
  2913. {
  2914. if (part.IsSitTargetSet && part.SitTargetAvatar == UUID.Zero && part.SitActiveRange >= 0)
  2915. {
  2916. //switch the target to this prim
  2917. return part;
  2918. }
  2919. }
  2920. // no explicit sit target found - use original target
  2921. return targetPart;
  2922. }
  2923. private void SendSitResponse(UUID targetID, Vector3 offset, Quaternion sitOrientation)
  2924. {
  2925. Vector3 cameraEyeOffset = Vector3.Zero;
  2926. Vector3 cameraAtOffset = Vector3.Zero;
  2927. bool forceMouselook = false;
  2928. SceneObjectPart part = FindNextAvailableSitTarget(targetID);
  2929. if (part == null)
  2930. return;
  2931. float range = part.SitActiveRange;
  2932. if (range < 0)
  2933. return;
  2934. Vector3 pos = part.AbsolutePosition + offset;
  2935. if (range > 1e-5f)
  2936. {
  2937. if (Vector3.DistanceSquared(AbsolutePosition, pos) > range * range)
  2938. return;
  2939. }
  2940. if (PhysicsActor != null)
  2941. m_sitAvatarHeight = PhysicsActor.Size.Z * 0.5f;
  2942. if (part.IsSitTargetSet && part.SitTargetAvatar == UUID.Zero)
  2943. {
  2944. offset = part.SitTargetPosition;
  2945. sitOrientation = part.SitTargetOrientation;
  2946. }
  2947. else
  2948. {
  2949. if (PhysicsSit(part,offset)) // physics engine
  2950. return;
  2951. if (Vector3.DistanceSquared(AbsolutePosition, pos) > 100f)
  2952. return;
  2953. AbsolutePosition = pos + new Vector3(0.0f, 0.0f, m_sitAvatarHeight);
  2954. }
  2955. if (PhysicsActor != null)
  2956. RemoveFromPhysicalScene();
  2957. if (m_movingToTarget)
  2958. ResetMoveToTarget();
  2959. Velocity = Vector3.Zero;
  2960. m_AngularVelocity = Vector3.Zero;
  2961. part.AddSittingAvatar(this);
  2962. cameraAtOffset = part.GetCameraAtOffset();
  2963. cameraEyeOffset = part.GetCameraEyeOffset();
  2964. forceMouselook = part.GetForceMouselook();
  2965. if (!part.IsRoot)
  2966. {
  2967. sitOrientation = part.RotationOffset * sitOrientation;
  2968. offset = offset * part.RotationOffset;
  2969. offset += part.OffsetPosition;
  2970. if (cameraAtOffset == Vector3.Zero && cameraEyeOffset == Vector3.Zero)
  2971. {
  2972. cameraAtOffset = part.ParentGroup.RootPart.GetCameraAtOffset();
  2973. cameraEyeOffset = part.ParentGroup.RootPart.GetCameraEyeOffset();
  2974. }
  2975. else
  2976. {
  2977. cameraAtOffset = cameraAtOffset * part.RotationOffset;
  2978. cameraAtOffset += part.OffsetPosition;
  2979. cameraEyeOffset = cameraEyeOffset * part.RotationOffset;
  2980. cameraEyeOffset += part.OffsetPosition;
  2981. }
  2982. }
  2983. sitOrientation = part.ParentGroup.RootPart.RotationOffset * sitOrientation;
  2984. ControllingClient.SendSitResponse(
  2985. part.ParentGroup.UUID, offset, sitOrientation,
  2986. true, cameraAtOffset, cameraEyeOffset, forceMouselook);
  2987. m_requestedSitTargetUUID = part.UUID;
  2988. HandleAgentSit(ControllingClient, UUID);
  2989. // Moved here to avoid a race with default sit anim
  2990. // The script event needs to be raised after the default sit anim is set.
  2991. //part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK);
  2992. //m_scene.EventManager.TriggerParcelPrimCountTainted(); // update select/ sat on
  2993. }
  2994. public void HandleAgentRequestSit(IClientAPI remoteClient, UUID agentID, UUID targetID, Vector3 offset)
  2995. {
  2996. if (IsChildAgent)
  2997. return;
  2998. if (ParentID != 0)
  2999. {
  3000. if (ParentPart.UUID == targetID)
  3001. return; // already sitting here, ignore
  3002. StandUp();
  3003. }
  3004. else if(SitGround)
  3005. StandUp();
  3006. SceneObjectPart part = FindNextAvailableSitTarget(targetID);
  3007. if (part != null)
  3008. {
  3009. m_requestedSitTargetID = part.LocalId;
  3010. m_requestedSitTargetUUID = part.UUID;
  3011. }
  3012. else
  3013. {
  3014. m_log.Warn("Sit requested on unknown object: " + targetID.ToString());
  3015. }
  3016. SendSitResponse(targetID, offset, Quaternion.Identity);
  3017. }
  3018. // returns false if does not suport so older sit can be tried
  3019. public bool PhysicsSit(SceneObjectPart part, Vector3 offset)
  3020. {
  3021. if (part == null || part.ParentGroup.IsAttachment)
  3022. return true;
  3023. if ( m_scene.PhysicsScene == null)
  3024. return false;
  3025. if (part.PhysActor == null)
  3026. {
  3027. // none physics shape
  3028. if (part.PhysicsShapeType == (byte)PhysicsShapeType.None)
  3029. ControllingClient.SendAlertMessage(" There is no suitable surface to sit on, try another spot.");
  3030. else
  3031. { // non physical phantom TODO
  3032. //ControllingClient.SendAlertMessage(" There is no suitable surface to sit on, try another spot.");
  3033. return false;
  3034. }
  3035. return true;
  3036. }
  3037. if (m_scene.PhysicsScene.SitAvatar(part.PhysActor, AbsolutePosition, CameraPosition, offset, new Vector3(0.35f, 0, 0.65f), PhysicsSitResponse) != 0)
  3038. {
  3039. return true;
  3040. }
  3041. return false;
  3042. }
  3043. private bool CanEnterLandPosition(Vector3 testPos)
  3044. {
  3045. ILandObject land = m_scene.LandChannel.GetLandObject(testPos.X, testPos.Y);
  3046. if (land == null || land.LandData.Name == "NO_LAND")
  3047. return true;
  3048. return land.CanBeOnThisLand(UUID,testPos.Z);
  3049. }
  3050. // status
  3051. // < 0 ignore
  3052. // 0 bad sit spot
  3053. public void PhysicsSitResponse(int status, uint partID, Vector3 offset, Quaternion Orientation)
  3054. {
  3055. if (status < 0)
  3056. return;
  3057. if (status == 0)
  3058. {
  3059. ControllingClient.SendAlertMessage(" There is no suitable surface to sit on, try another spot.");
  3060. return;
  3061. }
  3062. SceneObjectPart part = m_scene.GetSceneObjectPart(partID);
  3063. if (part == null)
  3064. return;
  3065. Vector3 targetPos = part.GetWorldPosition() + offset * part.GetWorldRotation();
  3066. if(!CanEnterLandPosition(targetPos))
  3067. {
  3068. ControllingClient.SendAlertMessage(" Sit position on restricted land, try another spot");
  3069. return;
  3070. }
  3071. RemoveFromPhysicalScene();
  3072. if (m_movingToTarget)
  3073. ResetMoveToTarget();
  3074. Velocity = Vector3.Zero;
  3075. m_AngularVelocity = Vector3.Zero;
  3076. m_requestedSitTargetID = 0;
  3077. part.AddSittingAvatar(this);
  3078. ParentPart = part;
  3079. ParentID = part.LocalId;
  3080. Vector3 cameraAtOffset = part.GetCameraAtOffset();
  3081. Vector3 cameraEyeOffset = part.GetCameraEyeOffset();
  3082. if (!part.IsRoot)
  3083. {
  3084. Orientation = part.RotationOffset * Orientation;
  3085. offset = offset * part.RotationOffset;
  3086. offset += part.OffsetPosition;
  3087. if (cameraAtOffset == Vector3.Zero && cameraEyeOffset == Vector3.Zero)
  3088. {
  3089. cameraAtOffset = part.ParentGroup.RootPart.GetCameraAtOffset();
  3090. cameraEyeOffset = part.ParentGroup.RootPart.GetCameraEyeOffset();
  3091. }
  3092. else
  3093. {
  3094. cameraAtOffset = cameraAtOffset * part.RotationOffset;
  3095. cameraAtOffset += part.OffsetPosition;
  3096. cameraEyeOffset = cameraEyeOffset * part.RotationOffset;
  3097. cameraEyeOffset += part.OffsetPosition;
  3098. }
  3099. }
  3100. m_bodyRot = Orientation;
  3101. m_pos = offset;
  3102. Orientation = part.ParentGroup.RootPart.RotationOffset * Orientation;
  3103. ControllingClient.SendSitResponse(
  3104. part.ParentGroup.UUID, offset, Orientation, true, cameraAtOffset, cameraEyeOffset, part.GetForceMouselook());
  3105. SendAvatarDataToAllAgents();
  3106. if (status == 3)
  3107. sitAnimation = "SIT_GROUND";
  3108. else
  3109. sitAnimation = "SIT";
  3110. Animator.SetMovementAnimations("SIT");
  3111. part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK);
  3112. m_scene.EventManager.TriggerParcelPrimCountTainted(); // update select/ sat on
  3113. }
  3114. public void HandleAgentSit(IClientAPI remoteClient, UUID agentID)
  3115. {
  3116. if (IsChildAgent)
  3117. return;
  3118. if(IsSitting)
  3119. return;
  3120. SceneObjectPart part = m_scene.GetSceneObjectPart(m_requestedSitTargetID);
  3121. if (part != null)
  3122. {
  3123. if (part.ParentGroup.IsAttachment)
  3124. {
  3125. m_log.WarnFormat(
  3126. "[SCENE PRESENCE]: Avatar {0} tried to sit on part {1} from object {2} in {3} but this is an attachment for avatar id {4}",
  3127. Name, part.Name, part.ParentGroup.Name, Scene.Name, part.ParentGroup.AttachedAvatar);
  3128. return;
  3129. }
  3130. RemoveFromPhysicalScene();
  3131. if (part.SitTargetAvatar == UUID)
  3132. {
  3133. Vector3 sitTargetPos = part.SitTargetPosition;
  3134. Quaternion sitTargetOrient = part.SitTargetOrientation;
  3135. // m_log.DebugFormat(
  3136. // "[SCENE PRESENCE]: Sitting {0} at sit target {1}, {2} on {3} {4}",
  3137. // Name, sitTargetPos, sitTargetOrient, part.Name, part.LocalId);
  3138. double x, y, z, m;
  3139. Vector3 sitOffset;
  3140. Quaternion r = sitTargetOrient;
  3141. Vector3 newPos;
  3142. Quaternion newRot;
  3143. if (LegacySitOffsets)
  3144. {
  3145. double m1,m2;
  3146. m1 = r.X * r.X + r.Y * r.Y;
  3147. m2 = r.Z * r.Z + r.W * r.W;
  3148. // Rotate the vector <0, 0, 1>
  3149. x = 2 * (r.X * r.Z + r.Y * r.W);
  3150. y = 2 * (-r.X * r.W + r.Y * r.Z);
  3151. z = m2 - m1;
  3152. // Set m to be the square of the norm of r.
  3153. m = m1 + m2;
  3154. // This constant is emperically determined to be what is used in SL.
  3155. // See also http://opensimulator.org/mantis/view.php?id=7096
  3156. double offset = 0.05;
  3157. // Normally m will be ~ 1, but if someone passed a handcrafted quaternion
  3158. // to llSitTarget with values so small that squaring them is rounded off
  3159. // to zero, then m could be zero. The result of this floating point
  3160. // round off error (causing us to skip this impossible normalization)
  3161. // is only 5 cm.
  3162. if (m > 0.000001)
  3163. {
  3164. offset /= m;
  3165. }
  3166. Vector3 up = new Vector3((float)x, (float)y, (float)z);
  3167. sitOffset = up * (float)offset;
  3168. newPos = sitTargetPos - sitOffset + SIT_TARGET_ADJUSTMENT;
  3169. }
  3170. else
  3171. {
  3172. m = r.X * r.X + r.Y * r.Y + r.Z * r.Z + r.W * r.W;
  3173. if (Math.Abs(1.0 - m) > 0.000001)
  3174. {
  3175. if(m != 0)
  3176. {
  3177. m = 1.0 / Math.Sqrt(m);
  3178. r.X *= (float)m;
  3179. r.Y *= (float)m;
  3180. r.Z *= (float)m;
  3181. r.W *= (float)m;
  3182. }
  3183. else
  3184. {
  3185. r.X = 0.0f;
  3186. r.Y = 0.0f;
  3187. r.Z = 0.0f;
  3188. r.W = 1.0f;
  3189. m = 1.0f;
  3190. }
  3191. }
  3192. x = 2 * (r.X * r.Z + r.Y * r.W);
  3193. y = 2 * (-r.X * r.W + r.Y * r.Z);
  3194. z = -r.X * r.X - r.Y * r.Y + r.Z * r.Z + r.W * r.W;
  3195. Vector3 up = new Vector3((float)x, (float)y, (float)z);
  3196. sitOffset = up * Appearance.AvatarHeight * 0.02638f;
  3197. newPos = sitTargetPos + sitOffset + SIT_TARGET_ADJUSTMENT;
  3198. }
  3199. if (part.IsRoot)
  3200. {
  3201. newRot = sitTargetOrient;
  3202. }
  3203. else
  3204. {
  3205. newPos = newPos * part.RotationOffset;
  3206. newRot = part.RotationOffset * sitTargetOrient;
  3207. }
  3208. newPos += part.OffsetPosition;
  3209. m_pos = newPos;
  3210. Rotation = newRot;
  3211. // ParentPosition = part.AbsolutePosition;
  3212. }
  3213. else
  3214. {
  3215. // An viewer expects to specify sit positions as offsets to the root prim, even if a child prim is
  3216. // being sat upon.
  3217. m_pos -= part.GroupPosition;
  3218. }
  3219. part.AddSittingAvatar(this);
  3220. ParentPart = part;
  3221. ParentID = m_requestedSitTargetID;
  3222. m_AngularVelocity = Vector3.Zero;
  3223. Velocity = Vector3.Zero;
  3224. m_requestedSitTargetID = 0;
  3225. SendAvatarDataToAllAgents();
  3226. if (String.IsNullOrEmpty(part.SitAnimation))
  3227. sitAnimation = "SIT";
  3228. else
  3229. sitAnimation = part.SitAnimation;
  3230. Animator.SetMovementAnimations("SIT");
  3231. // TriggerScenePresenceUpdated();
  3232. part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK);
  3233. m_scene.EventManager.TriggerParcelPrimCountTainted(); // update select/ sat on
  3234. }
  3235. }
  3236. public void HandleAgentSitOnGround()
  3237. {
  3238. if (IsChildAgent)
  3239. return;
  3240. sitAnimation = "SIT_GROUND_CONSTRAINED";
  3241. SitGround = true;
  3242. RemoveFromPhysicalScene();
  3243. m_AngularVelocity = Vector3.Zero;
  3244. Velocity = Vector3.Zero;
  3245. Animator.SetMovementAnimations("SITGROUND");
  3246. TriggerScenePresenceUpdated();
  3247. }
  3248. /// <summary>
  3249. /// Event handler for the 'Always run' setting on the client
  3250. /// Tells the physics plugin to increase speed of movement.
  3251. /// </summary>
  3252. public void HandleSetAlwaysRun(IClientAPI remoteClient, bool pSetAlwaysRun)
  3253. {
  3254. SetAlwaysRun = pSetAlwaysRun;
  3255. }
  3256. public void HandleStartAnim(IClientAPI remoteClient, UUID animID)
  3257. {
  3258. Animator.AddAnimation(animID, UUID.Zero);
  3259. TriggerScenePresenceUpdated();
  3260. }
  3261. public void HandleStopAnim(IClientAPI remoteClient, UUID animID)
  3262. {
  3263. Animator.RemoveAnimation(animID, false);
  3264. TriggerScenePresenceUpdated();
  3265. }
  3266. public void avnHandleChangeAnim(UUID animID, bool addRemove,bool sendPack)
  3267. {
  3268. Animator.avnChangeAnim(animID, addRemove, sendPack);
  3269. }
  3270. /// <summary>
  3271. /// Rotate the avatar to the given rotation and apply a movement in the given relative vector
  3272. /// </summary>
  3273. /// <param name="vec">The vector in which to move. This is relative to the rotation argument</param>
  3274. /// <param name="thisAddSpeedModifier">
  3275. /// Optional additional speed modifier for this particular add. Default is 1</param>
  3276. public void AddNewMovement(Vector3 vec, float thisAddSpeedModifier = 1, bool breaking = false)
  3277. {
  3278. // m_log.DebugFormat(
  3279. // "[SCENE PRESENCE]: Adding new movement {0} with rotation {1}, thisAddSpeedModifier {2} for {3}",
  3280. // vec, Rotation, thisAddSpeedModifier, Name);
  3281. m_delayedStop = -1;
  3282. // rotate from avatar coord space to world
  3283. Quaternion rot = Rotation;
  3284. if (!Flying && PresenceType != PresenceType.Npc)
  3285. {
  3286. // force rotation to be around Z only, if not flying
  3287. // needed for mouselook
  3288. rot.X = 0;
  3289. rot.Y = 0;
  3290. }
  3291. Vector3 direc = vec * rot;
  3292. direc.Normalize();
  3293. if ((vec.Z == 0f) && !Flying)
  3294. direc.Z = 0f; // Prevent camera WASD up.
  3295. bool notmvtrgt = !m_movingToTarget || m_moveToSpeed <= 0;
  3296. // odd rescalings
  3297. if(notmvtrgt)
  3298. direc *= 4.096f * SpeedModifier * thisAddSpeedModifier;
  3299. else
  3300. direc *= m_moveToSpeed;
  3301. // m_log.DebugFormat("[SCENE PRESENCE]: Force to apply before modification was {0} for {1}", direc, Name);
  3302. if (Animator.currentControlState == ScenePresenceAnimator.motionControlStates.falling
  3303. && (PhysicsActor == null || !PhysicsActor.PIDHoverActive))
  3304. {
  3305. if (breaking)
  3306. direc.Z = -9999f; //hack to tell physics to stop on Z
  3307. else
  3308. direc = Vector3.Zero;
  3309. }
  3310. else if (Flying)
  3311. {
  3312. if (IsColliding && direc.Z < 0)
  3313. // landing situation, prevent avatar moving or it may fail to land
  3314. // animator will handle this condition and do the land
  3315. direc = Vector3.Zero;
  3316. else if(notmvtrgt)
  3317. direc *= 4.0f;
  3318. }
  3319. else if (IsColliding)
  3320. {
  3321. if (direc.Z > 2.0f && notmvtrgt) // reinforce jumps
  3322. {
  3323. direc.Z *= 2.6f;
  3324. }
  3325. else if (direc.Z < 0) // on a surface moving down (pg down) only changes animation
  3326. direc.Z = 0;
  3327. }
  3328. TargetVelocity = direc;
  3329. Animator.UpdateMovementAnimations();
  3330. }
  3331. #endregion
  3332. #region Overridden Methods
  3333. const float ROTATION_TOLERANCE = 0.01f;
  3334. const float VELOCITY_TOLERANCE = 0.1f;
  3335. const float LOWVELOCITYSQ = 0.1f;
  3336. const float POSITION_LARGETOLERANCE = 5f;
  3337. const float POSITION_SMALLTOLERANCE = 0.05f;
  3338. public override void Update()
  3339. {
  3340. if (IsDeleted)
  3341. return;
  3342. if (NeedInitialData > 0)
  3343. {
  3344. SendInitialData();
  3345. return;
  3346. }
  3347. if (IsChildAgent || IsInTransit)
  3348. return;
  3349. CheckForBorderCrossing();
  3350. if (m_movingToTarget)
  3351. {
  3352. m_delayedStop = -1;
  3353. Vector3 control = Vector3.Zero;
  3354. if(HandleMoveToTargetUpdate(0.5f, ref control))
  3355. AddNewMovement(control);
  3356. }
  3357. else if(m_delayedStop > 0)
  3358. {
  3359. if(IsSatOnObject)
  3360. m_delayedStop = -1;
  3361. else
  3362. if(Util.GetTimeStampMS() > m_delayedStop)
  3363. AddNewMovement(Vector3.Zero);
  3364. }
  3365. if (Appearance.AvatarSize != m_lastSize)
  3366. SendAvatarDataToAllAgents();
  3367. // Send terse position update if not sitting and position, velocity, or rotation
  3368. // has changed significantly from last sent update
  3369. if (!IsSatOnObject)
  3370. {
  3371. // this does need to be more complex later
  3372. Vector3 vel = Velocity;
  3373. Vector3 dpos = m_pos - m_lastPosition;
  3374. if( State != m_lastState ||
  3375. !vel.ApproxEquals(m_lastVelocity) ||
  3376. !m_bodyRot.ApproxEquals(m_lastRotation) ||
  3377. (vel == Vector3.Zero && m_lastVelocity != Vector3.Zero) ||
  3378. Math.Abs(dpos.X) > POSITION_LARGETOLERANCE ||
  3379. Math.Abs(dpos.Y) > POSITION_LARGETOLERANCE ||
  3380. Math.Abs(dpos.Z) > POSITION_LARGETOLERANCE ||
  3381. ( (Math.Abs(dpos.X) > POSITION_SMALLTOLERANCE ||
  3382. Math.Abs(dpos.Y) > POSITION_SMALLTOLERANCE ||
  3383. Math.Abs(dpos.Z) > POSITION_SMALLTOLERANCE)
  3384. && vel.LengthSquared() < LOWVELOCITYSQ
  3385. ) ||
  3386. Math.Abs(CollisionPlane.X - m_lastCollisionPlane.X) > POSITION_SMALLTOLERANCE ||
  3387. Math.Abs(CollisionPlane.Y - m_lastCollisionPlane.Y) > POSITION_SMALLTOLERANCE ||
  3388. Math.Abs(CollisionPlane.W - m_lastCollisionPlane.W) > POSITION_SMALLTOLERANCE
  3389. )
  3390. {
  3391. SendTerseUpdateToAllClients();
  3392. }
  3393. }
  3394. CheckForSignificantMovement();
  3395. }
  3396. #endregion
  3397. #region Update Client(s)
  3398. public void SendUpdateToAgent(ScenePresence p)
  3399. {
  3400. IClientAPI remoteClient = p.ControllingClient;
  3401. if (remoteClient.IsActive)
  3402. {
  3403. //m_log.DebugFormat("[SCENE PRESENCE]: " + Name + " sending TerseUpdate to " + remoteClient.Name + " : Pos={0} Rot={1} Vel={2}", m_pos, Rotation, m_velocity);
  3404. remoteClient.SendEntityUpdate(this, PrimUpdateFlags.FullUpdate);
  3405. m_scene.StatsReporter.AddAgentUpdates(1);
  3406. }
  3407. }
  3408. public void SendFullUpdateToClient(IClientAPI remoteClient)
  3409. {
  3410. if (remoteClient.IsActive)
  3411. {
  3412. //m_log.DebugFormat("[SCENE PRESENCE]: " + Name + " sending TerseUpdate to " + remoteClient.Name + " : Pos={0} Rot={1} Vel={2}", m_pos, Rotation, m_velocity);
  3413. remoteClient.SendEntityUpdate(this, PrimUpdateFlags.FullUpdate);
  3414. m_scene.StatsReporter.AddAgentUpdates(1);
  3415. }
  3416. }
  3417. // this is diferente from SendTerseUpdateToClient
  3418. // this sends bypassing entities updates
  3419. public void SendAgentTerseUpdate(ISceneEntity p)
  3420. {
  3421. ControllingClient.SendAgentTerseUpdate(p);
  3422. }
  3423. /// <summary>
  3424. /// Sends a location update to the client connected to this scenePresence
  3425. /// via entity updates
  3426. /// </summary>
  3427. /// <param name="remoteClient"></param>
  3428. public void SendTerseUpdateToClient(IClientAPI remoteClient)
  3429. {
  3430. // If the client is inactive, it's getting its updates from another
  3431. // server.
  3432. if (remoteClient.IsActive)
  3433. {
  3434. //m_log.DebugFormat("[SCENE PRESENCE]: " + Name + " sending TerseUpdate to " + remoteClient.Name + " : Pos={0} Rot={1} Vel={2}", m_pos, Rotation, m_velocity);
  3435. remoteClient.SendEntityUpdate(
  3436. this,
  3437. PrimUpdateFlags.Position | PrimUpdateFlags.Rotation | PrimUpdateFlags.Velocity
  3438. | PrimUpdateFlags.Acceleration | PrimUpdateFlags.AngularVelocity);
  3439. m_scene.StatsReporter.AddAgentUpdates(1);
  3440. }
  3441. }
  3442. public void SendTerseUpdateToAgent(ScenePresence p)
  3443. {
  3444. IClientAPI remoteClient = p.ControllingClient;
  3445. if (!remoteClient.IsActive)
  3446. return;
  3447. if (ParcelHideThisAvatar && p.currentParcelUUID != currentParcelUUID && !p.IsViewerUIGod)
  3448. return;
  3449. //m_log.DebugFormat("[SCENE PRESENCE]: " + Name + " sending TerseUpdate to " + remoteClient.Name + " : Pos={0} Rot={1} Vel={2}", m_pos, Rotation, m_velocity);
  3450. remoteClient.SendEntityUpdate(
  3451. this,
  3452. PrimUpdateFlags.Position | PrimUpdateFlags.Rotation | PrimUpdateFlags.Velocity
  3453. | PrimUpdateFlags.Acceleration | PrimUpdateFlags.AngularVelocity);
  3454. m_scene.StatsReporter.AddAgentUpdates(1);
  3455. }
  3456. public void SendTerseUpdateToAgentNF(ScenePresence p)
  3457. {
  3458. IClientAPI remoteClient = p.ControllingClient;
  3459. if (remoteClient.IsActive)
  3460. {
  3461. //m_log.DebugFormat("[SCENE PRESENCE]: " + Name + " sending TerseUpdate to " + remoteClient.Name + " : Pos={0} Rot={1} Vel={2}", m_pos, Rotation, m_velocity);
  3462. remoteClient.SendEntityUpdate(this,
  3463. PrimUpdateFlags.Position | PrimUpdateFlags.Rotation | PrimUpdateFlags.Velocity
  3464. | PrimUpdateFlags.Acceleration | PrimUpdateFlags.AngularVelocity);
  3465. m_scene.StatsReporter.AddAgentUpdates(1);
  3466. }
  3467. }
  3468. /// <summary>
  3469. /// Send a location/velocity/accelleration update to all agents in scene
  3470. /// </summary>
  3471. public void SendTerseUpdateToAllClients()
  3472. {
  3473. m_lastState = State;
  3474. m_lastPosition = m_pos;
  3475. m_lastRotation = m_bodyRot;
  3476. m_lastVelocity = Velocity;
  3477. m_lastCollisionPlane = CollisionPlane;
  3478. m_scene.ForEachScenePresence(SendTerseUpdateToAgent);
  3479. // Update the "last" values
  3480. TriggerScenePresenceUpdated();
  3481. }
  3482. public void SetSendCoarseLocationMethod(SendCoarseLocationsMethod d)
  3483. {
  3484. m_sendCoarseLocationsMethod = d;
  3485. }
  3486. public void SendCoarseLocations(List<Vector3> coarseLocations, List<UUID> avatarUUIDs)
  3487. {
  3488. m_sendCoarseLocationsMethod?.Invoke(m_scene.RegionInfo.originRegionID, this, coarseLocations, avatarUUIDs);
  3489. }
  3490. public void SendCoarseLocationsDefault(UUID sceneId, ScenePresence p, List<Vector3> coarseLocations, List<UUID> avatarUUIDs)
  3491. {
  3492. ControllingClient.SendCoarseLocationUpdate(avatarUUIDs, coarseLocations);
  3493. }
  3494. public void RegionHandShakeReply (IClientAPI client)
  3495. {
  3496. if(IsNPC)
  3497. return;
  3498. lock (m_completeMovementLock)
  3499. {
  3500. if(m_gotRegionHandShake)
  3501. return;
  3502. m_gotRegionHandShake = true;
  3503. NeedInitialData = 2;
  3504. }
  3505. }
  3506. private void SendInitialData()
  3507. {
  3508. //wait for region handshake
  3509. if (NeedInitialData < 2)
  3510. return;
  3511. uint flags = ControllingClient.GetViewerCaps();
  3512. if ((flags & 0x1000) == 0) // wait for seeds sending
  3513. return;
  3514. // give some extra time to make sure viewers did process seeds
  3515. if (++NeedInitialData < 6) // needs fix if update rate changes on heartbeat
  3516. return;
  3517. NeedInitialData = -1;
  3518. bool selfappearance = (flags & 4) != 0;
  3519. // this should enqueued on the client processing job to save threads
  3520. Util.FireAndForget(delegate
  3521. {
  3522. if(!IsChildAgent)
  3523. {
  3524. // close v1 sender region obsolete
  3525. if (!string.IsNullOrEmpty(m_callbackURI))
  3526. {
  3527. m_log.DebugFormat(
  3528. "[SCENE PRESENCE({0})]: Releasing {1} {2} with old callback to {3}",
  3529. Scene.RegionInfo.RegionName, Name, UUID, m_callbackURI);
  3530. UUID originID;
  3531. lock (m_originRegionIDAccessLock)
  3532. originID = m_originRegionID;
  3533. Scene.SimulationService.ReleaseAgent(originID, UUID, m_callbackURI);
  3534. m_callbackURI = null;
  3535. }
  3536. // v0.7 close HG sender region
  3537. else if (!string.IsNullOrEmpty(m_newCallbackURI))
  3538. {
  3539. m_log.DebugFormat(
  3540. "[SCENE PRESENCE({0})]: Releasing {1} {2} with callback to {3}",
  3541. Scene.RegionInfo.RegionName, Name, UUID, m_newCallbackURI);
  3542. UUID originID;
  3543. lock (m_originRegionIDAccessLock)
  3544. originID = m_originRegionID;
  3545. Scene.SimulationService.ReleaseAgent(originID, UUID, m_newCallbackURI);
  3546. m_newCallbackURI = null;
  3547. }
  3548. IEntityTransferModule m_agentTransfer = m_scene.RequestModuleInterface<IEntityTransferModule>();
  3549. if (m_agentTransfer != null)
  3550. {
  3551. m_agentTransfer.CloseOldChildAgents(this);
  3552. }
  3553. }
  3554. m_log.DebugFormat("[SCENE PRESENCE({0})]: SendInitialData for {1}", Scene.RegionInfo.RegionName, UUID);
  3555. if (m_teleportFlags <= 0)
  3556. {
  3557. Scene.SendLayerData(ControllingClient);
  3558. ILandChannel landch = m_scene.LandChannel;
  3559. if (landch != null)
  3560. landch.sendClientInitialLandInfo(ControllingClient, true);
  3561. }
  3562. SendOtherAgentsAvatarFullToMe();
  3563. if (m_scene.ObjectsCullingByDistance)
  3564. {
  3565. m_reprioritizationBusy = true;
  3566. m_reprioritizationLastPosition = AbsolutePosition;
  3567. m_reprioritizationLastDrawDistance = DrawDistance;
  3568. ControllingClient.ReprioritizeUpdates();
  3569. m_reprioritizationLastTime = Util.EnvironmentTickCount();
  3570. m_reprioritizationBusy = false;
  3571. }
  3572. else
  3573. {
  3574. //bool cacheCulling = (flags & 1) != 0;
  3575. bool cacheEmpty = (flags & 2) != 0;;
  3576. EntityBase[] entities = Scene.Entities.GetEntities();
  3577. if(cacheEmpty)
  3578. {
  3579. foreach (EntityBase e in entities)
  3580. {
  3581. if (e != null && e is SceneObjectGroup && !((SceneObjectGroup)e).IsAttachment)
  3582. ((SceneObjectGroup)e).SendFullAnimUpdateToClient(ControllingClient);
  3583. }
  3584. }
  3585. else
  3586. {
  3587. foreach (EntityBase e in entities)
  3588. {
  3589. if (e != null && e is SceneObjectGroup && !((SceneObjectGroup)e).IsAttachment)
  3590. {
  3591. SceneObjectGroup grp = e as SceneObjectGroup;
  3592. if(grp.IsViewerCachable)
  3593. grp.SendUpdateProbes(ControllingClient);
  3594. else
  3595. grp.SendFullAnimUpdateToClient(ControllingClient);
  3596. }
  3597. }
  3598. }
  3599. m_reprioritizationLastPosition = AbsolutePosition;
  3600. m_reprioritizationLastDrawDistance = DrawDistance;
  3601. m_reprioritizationLastTime = Util.EnvironmentTickCount() + 15000; // delay it
  3602. m_reprioritizationBusy = false;
  3603. }
  3604. if (!IsChildAgent)
  3605. {
  3606. // Create child agents in neighbouring regions
  3607. IEntityTransferModule m_agentTransfer = m_scene.RequestModuleInterface<IEntityTransferModule>();
  3608. if (m_agentTransfer != null)
  3609. {
  3610. m_agentTransfer.EnableChildAgents(this);
  3611. }
  3612. m_lastChildUpdatesTime = Util.EnvironmentTickCount() + 10000;
  3613. m_lastChildAgentUpdatePosition = AbsolutePosition;
  3614. m_lastChildAgentCheckPosition = m_lastChildAgentUpdatePosition;
  3615. m_lastChildAgentUpdateDrawDistance = DrawDistance;
  3616. m_lastRegionsDrawDistance = RegionViewDistance;
  3617. m_lastChildAgentUpdateGodLevel = GodController.ViwerUIGodLevel;
  3618. m_childUpdatesBusy = false; // allow them
  3619. }
  3620. });
  3621. }
  3622. /// <summary>
  3623. /// Send avatar full data appearance and animations for all other root agents to this agent, this agent
  3624. /// can be either a child or root
  3625. /// </summary>
  3626. public void SendOtherAgentsAvatarFullToMe()
  3627. {
  3628. int count = 0;
  3629. m_scene.ForEachRootScenePresence(delegate(ScenePresence p)
  3630. {
  3631. // only send information about other root agents
  3632. if (p.UUID == UUID)
  3633. return;
  3634. // get the avatar, then a kill if can't see it
  3635. p.SendInitialAvatarDataToAgent(this);
  3636. if (p.ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !IsViewerUIGod)
  3637. return;
  3638. p.SendAppearanceToAgentNF(this);
  3639. p.SendAnimPackToAgentNF(this);
  3640. p.SendAttachmentsToAgentNF(this);
  3641. count++;
  3642. });
  3643. m_scene.StatsReporter.AddAgentUpdates(count);
  3644. }
  3645. /// <summary>
  3646. /// Send this agent's avatar data to all other root and child agents in the scene
  3647. /// This agent must be root. This avatar will receive its own update.
  3648. /// </summary>
  3649. public void SendAvatarDataToAllAgents()
  3650. {
  3651. //m_log.DebugFormat("[SCENE PRESENCE] SendAvatarDataToAllAgents: {0} ({1})", Name, UUID);
  3652. // only send update from root agents to other clients; children are only "listening posts"
  3653. if (IsChildAgent)
  3654. {
  3655. m_log.WarnFormat(
  3656. "[SCENE PRESENCE]: Attempt to send avatar data from a child agent for {0} in {1}",
  3657. Name, Scene.RegionInfo.RegionName);
  3658. return;
  3659. }
  3660. m_lastSize = Appearance.AvatarSize;
  3661. int count = 0;
  3662. m_scene.ForEachScenePresence(delegate(ScenePresence scenePresence)
  3663. {
  3664. SendAvatarDataToAgent(scenePresence);
  3665. count++;
  3666. });
  3667. m_scene.StatsReporter.AddAgentUpdates(count);
  3668. }
  3669. // sends avatar object to all clients so they cross it into region
  3670. // then sends kills to hide
  3671. public void SendInitialAvatarDataToAllAgents(List<ScenePresence> presences)
  3672. {
  3673. m_lastSize = Appearance.AvatarSize;
  3674. int count = 0;
  3675. SceneObjectPart sitroot = null;
  3676. if (ParentID != 0 && ParentPart != null) // we need to send the sitting root prim
  3677. {
  3678. sitroot = ParentPart.ParentGroup.RootPart;
  3679. }
  3680. foreach (ScenePresence p in presences)
  3681. {
  3682. if (sitroot != null) // we need to send the sitting root prim
  3683. {
  3684. p.ControllingClient.SendEntityFullUpdateImmediate(ParentPart.ParentGroup.RootPart);
  3685. }
  3686. p.ControllingClient.SendEntityFullUpdateImmediate(this);
  3687. if (p != this && ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  3688. // either just kill the object
  3689. // p.ControllingClient.SendKillObject(new List<uint> {LocalId});
  3690. // or also attachments viewer may still know about
  3691. SendKillTo(p);
  3692. count++;
  3693. }
  3694. m_scene.StatsReporter.AddAgentUpdates(count);
  3695. }
  3696. public void SendInitialAvatarDataToAgent(ScenePresence p)
  3697. {
  3698. if(ParentID != 0 && ParentPart != null) // we need to send the sitting root prim
  3699. {
  3700. p.ControllingClient.SendEntityFullUpdateImmediate(ParentPart.ParentGroup.RootPart);
  3701. }
  3702. p.ControllingClient.SendEntityFullUpdateImmediate(this);
  3703. if (p != this && ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  3704. // either just kill the object
  3705. // p.ControllingClient.SendKillObject(new List<uint> {LocalId});
  3706. // or also attachments viewer may still know about
  3707. SendKillTo(p);
  3708. }
  3709. /// <summary>
  3710. /// Send avatar data to an agent.
  3711. /// </summary>
  3712. /// <param name="avatar"></param>
  3713. public void SendAvatarDataToAgent(ScenePresence avatar)
  3714. {
  3715. //m_log.DebugFormat("[SCENE PRESENCE] SendAvatarDataToAgent from {0} ({1}) to {2} ({3})", Name, UUID, avatar.Name, avatar.UUID);
  3716. if (ParcelHideThisAvatar && currentParcelUUID != avatar.currentParcelUUID && !avatar.IsViewerUIGod)
  3717. return;
  3718. avatar.ControllingClient.SendEntityFullUpdateImmediate(this);
  3719. }
  3720. public void SendAvatarDataToAgentNF(ScenePresence avatar)
  3721. {
  3722. avatar.ControllingClient.SendEntityFullUpdateImmediate(this);
  3723. }
  3724. /// <summary>
  3725. /// Send this agent's appearance to all other root and child agents in the scene
  3726. /// This agent must be root.
  3727. /// </summary>
  3728. public void SendAppearanceToAllOtherAgents()
  3729. {
  3730. // m_log.DebugFormat("[SCENE PRESENCE] SendAppearanceToAllOtherAgents: {0} {1}", Name, UUID);
  3731. // only send update from root agents to other clients; children are only "listening posts"
  3732. if (IsChildAgent)
  3733. {
  3734. m_log.WarnFormat(
  3735. "[SCENE PRESENCE]: Attempt to send avatar data from a child agent for {0} in {1}",
  3736. Name, Scene.RegionInfo.RegionName);
  3737. return;
  3738. }
  3739. int count = 0;
  3740. m_scene.ForEachScenePresence(delegate(ScenePresence scenePresence)
  3741. {
  3742. // only send information to other root agents
  3743. if (scenePresence.UUID == UUID)
  3744. return;
  3745. SendAppearanceToAgent(scenePresence);
  3746. count++;
  3747. });
  3748. m_scene.StatsReporter.AddAgentUpdates(count);
  3749. }
  3750. public void SendAppearanceToAgent(ScenePresence avatar)
  3751. {
  3752. // m_log.DebugFormat(
  3753. // "[SCENE PRESENCE]: Sending appearance data from {0} {1} to {2} {3}", Name, m_uuid, avatar.Name, avatar.UUID);
  3754. if (ParcelHideThisAvatar && currentParcelUUID != avatar.currentParcelUUID && !avatar.IsViewerUIGod)
  3755. return;
  3756. SendAppearanceToAgentNF(avatar);
  3757. }
  3758. public void SendAppearanceToAgentNF(ScenePresence avatar)
  3759. {
  3760. avatar.ControllingClient.SendAppearance(UUID, Appearance.VisualParams, Appearance.Texture.GetBakesBytes(), Appearance.AvatarPreferencesHoverZ);
  3761. }
  3762. public void SendAnimPackToAgent(ScenePresence p)
  3763. {
  3764. if (IsChildAgent || Animator == null)
  3765. return;
  3766. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  3767. return;
  3768. Animator.SendAnimPackToClient(p.ControllingClient);
  3769. }
  3770. public void SendAnimPackToAgent(ScenePresence p, UUID[] animations, int[] seqs, UUID[] objectIDs)
  3771. {
  3772. if (IsChildAgent)
  3773. return;
  3774. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  3775. return;
  3776. p.ControllingClient.SendAnimations(animations, seqs, ControllingClient.AgentId, objectIDs);
  3777. }
  3778. public void SendAnimPackToAgentNF(ScenePresence p)
  3779. {
  3780. if (IsChildAgent || Animator == null)
  3781. return;
  3782. Animator.SendAnimPackToClient(p.ControllingClient);
  3783. }
  3784. public void SendAnimPackToAgentNF(ScenePresence p, UUID[] animations, int[] seqs, UUID[] objectIDs)
  3785. {
  3786. p.ControllingClient.SendAnimations(animations, seqs, ControllingClient.AgentId, objectIDs);
  3787. }
  3788. public void SendAnimPack(UUID[] animations, int[] seqs, UUID[] objectIDs)
  3789. {
  3790. if (IsChildAgent)
  3791. return;
  3792. m_scene.ForEachScenePresence(delegate(ScenePresence p)
  3793. {
  3794. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  3795. return;
  3796. p.ControllingClient.SendAnimations(animations, seqs, ControllingClient.AgentId, objectIDs);
  3797. });
  3798. }
  3799. #endregion
  3800. #region Significant Movement Method
  3801. private void checkRePrioritization()
  3802. {
  3803. if(IsDeleted || !ControllingClient.IsActive)
  3804. return;
  3805. if(m_reprioritizationBusy)
  3806. return;
  3807. float limit = Scene.ReprioritizationDistance;
  3808. bool byDrawdistance = Scene.ObjectsCullingByDistance;
  3809. if(byDrawdistance)
  3810. {
  3811. float minregionSize = Scene.RegionInfo.RegionSizeX;
  3812. if(minregionSize > Scene.RegionInfo.RegionSizeY)
  3813. minregionSize = Scene.RegionInfo.RegionSizeY;
  3814. minregionSize *= 0.5f;
  3815. if(DrawDistance > minregionSize && m_reprioritizationLastDrawDistance > minregionSize)
  3816. byDrawdistance = false;
  3817. else
  3818. byDrawdistance = (Math.Abs(DrawDistance - m_reprioritizationLastDrawDistance) > 0.5f * limit);
  3819. }
  3820. int tdiff = Util.EnvironmentTickCountSubtract(m_reprioritizationLastTime);
  3821. if(!byDrawdistance && tdiff < Scene.ReprioritizationInterval)
  3822. return;
  3823. // priority uses avatar position
  3824. Vector3 pos = AbsolutePosition;
  3825. Vector3 diff = pos - m_reprioritizationLastPosition;
  3826. limit *= limit;
  3827. if (!byDrawdistance && diff.LengthSquared() < limit)
  3828. return;
  3829. m_reprioritizationBusy = true;
  3830. m_reprioritizationLastPosition = pos;
  3831. m_reprioritizationLastDrawDistance = DrawDistance;
  3832. Util.FireAndForget(
  3833. o =>
  3834. {
  3835. ControllingClient.ReprioritizeUpdates();
  3836. m_reprioritizationLastTime = Util.EnvironmentTickCount();
  3837. m_reprioritizationBusy = false;
  3838. }, null, "ScenePresence.Reprioritization");
  3839. }
  3840. /// <summary>
  3841. /// This checks for a significant movement and sends a coarselocationchange update
  3842. /// </summary>
  3843. protected void CheckForSignificantMovement()
  3844. {
  3845. Vector3 pos = AbsolutePosition;
  3846. Vector3 diff = pos - posLastMove;
  3847. if (diff.LengthSquared() > MOVEMENT)
  3848. {
  3849. posLastMove = pos;
  3850. m_scene.EventManager.TriggerOnClientMovement(this);
  3851. }
  3852. diff = pos - posLastSignificantMove;
  3853. if (diff.LengthSquared() > SIGNIFICANT_MOVEMENT)
  3854. {
  3855. posLastSignificantMove = pos;
  3856. m_scene.EventManager.TriggerSignificantClientMovement(this);
  3857. }
  3858. if(IsNPC)
  3859. return;
  3860. // updates priority recalc
  3861. checkRePrioritization();
  3862. if(m_childUpdatesBusy || RegionViewDistance == 0)
  3863. return;
  3864. int tdiff = Util.EnvironmentTickCountSubtract(m_lastChildUpdatesTime);
  3865. if (tdiff < CHILDUPDATES_TIME)
  3866. return;
  3867. bool viewchanged = Math.Abs(RegionViewDistance - m_lastRegionsDrawDistance) > 32.0f;
  3868. IEntityTransferModule m_agentTransfer = m_scene.RequestModuleInterface<IEntityTransferModule>();
  3869. float dx = pos.X - m_lastChildAgentCheckPosition.X;
  3870. float dy = pos.Y - m_lastChildAgentCheckPosition.Y;
  3871. if ((m_agentTransfer != null) && (viewchanged || ((dx * dx + dy * dy) > CHILDAGENTSCHECK_MOVEMENT)))
  3872. {
  3873. m_childUpdatesBusy = true;
  3874. m_lastChildAgentCheckPosition = pos;
  3875. m_lastChildAgentUpdatePosition = pos;
  3876. m_lastChildAgentUpdateGodLevel = GodController.ViwerUIGodLevel;
  3877. m_lastChildAgentUpdateDrawDistance = DrawDistance;
  3878. m_lastRegionsDrawDistance = RegionViewDistance;
  3879. // m_lastChildAgentUpdateCamPosition = CameraPosition;
  3880. Util.FireAndForget(
  3881. o =>
  3882. {
  3883. m_agentTransfer.EnableChildAgents(this);
  3884. m_lastChildUpdatesTime = Util.EnvironmentTickCount();
  3885. m_childUpdatesBusy = false;
  3886. }, null, "ScenePresence.CheckChildAgents");
  3887. }
  3888. else
  3889. {
  3890. //possible KnownRegionHandles always contains current region and this check is not needed
  3891. int minhandles = KnownRegionHandles.Contains(RegionHandle) ? 1 : 0;
  3892. if(KnownRegionHandles.Count > minhandles)
  3893. {
  3894. bool doUpdate = false;
  3895. if (m_lastChildAgentUpdateGodLevel != GodController.ViwerUIGodLevel)
  3896. doUpdate = true;
  3897. if (Math.Abs(DrawDistance - m_lastChildAgentUpdateDrawDistance) > 32.0f)
  3898. doUpdate = true;
  3899. if(!doUpdate)
  3900. {
  3901. diff = pos - m_lastChildAgentUpdatePosition;
  3902. if (diff.LengthSquared() > CHILDUPDATES_MOVEMENT)
  3903. doUpdate = true;
  3904. }
  3905. if (doUpdate)
  3906. {
  3907. m_childUpdatesBusy = true;
  3908. m_lastChildAgentUpdatePosition = pos;
  3909. m_lastChildAgentUpdateGodLevel = GodController.ViwerUIGodLevel;
  3910. m_lastChildAgentUpdateDrawDistance = DrawDistance;
  3911. // m_lastChildAgentUpdateCamPosition = CameraPosition;
  3912. AgentPosition agentpos = new AgentPosition()
  3913. {
  3914. AgentID = new UUID(UUID.Guid),
  3915. SessionID = ControllingClient.SessionId,
  3916. Size = Appearance.AvatarSize,
  3917. Center = CameraPosition,
  3918. Far = DrawDistance,
  3919. Position = AbsolutePosition,
  3920. Velocity = Velocity,
  3921. RegionHandle = RegionHandle,
  3922. GodData = GodController.State(),
  3923. Throttles = ControllingClient.GetThrottlesPacked(1)
  3924. };
  3925. // Let's get this out of the update loop
  3926. Util.FireAndForget(
  3927. o =>
  3928. {
  3929. m_scene.SendOutChildAgentUpdates(agentpos, this);
  3930. m_lastChildUpdatesTime = Util.EnvironmentTickCount();
  3931. m_childUpdatesBusy = false;
  3932. }, null, "ScenePresence.SendOutChildAgentUpdates");
  3933. }
  3934. }
  3935. }
  3936. }
  3937. #endregion
  3938. #region Border Crossing Methods
  3939. /// <summary>
  3940. /// Starts the process of moving an avatar into another region if they are crossing the border.
  3941. /// </summary>
  3942. /// <remarks>
  3943. /// Also removes the avatar from the physical scene if transit has started.
  3944. /// </remarks>
  3945. protected void CheckForBorderCrossing()
  3946. {
  3947. // Check that we we are not a child
  3948. if (IsChildAgent || IsInTransit)
  3949. return;
  3950. // If we don't have a PhysActor, we can't cross anyway
  3951. // Also don't do this while sat, sitting avatars cross with the
  3952. // object they sit on. ParentUUID denoted a pending sit, don't
  3953. // interfere with it.
  3954. if (ParentID != 0 || PhysicsActor == null || ParentUUID != UUID.Zero)
  3955. return;
  3956. Vector3 pos2 = AbsolutePosition;
  3957. Vector3 vel = Velocity;
  3958. float timeStep = 0.1f;
  3959. pos2.X += vel.X * timeStep;
  3960. pos2.Y += vel.Y * timeStep;
  3961. pos2.Z += vel.Z * timeStep;
  3962. // m_log.DebugFormat(
  3963. // "[SCENE PRESENCE]: Testing border check for projected position {0} of {1} in {2}",
  3964. // pos2, Name, Scene.Name);
  3965. if (Scene.PositionIsInCurrentRegion(pos2))
  3966. return;
  3967. if (!CrossToNewRegion() && m_requestedSitTargetUUID == UUID.Zero)
  3968. {
  3969. // we don't have entity transfer module
  3970. Vector3 pos = AbsolutePosition;
  3971. vel = Velocity;
  3972. float px = pos.X;
  3973. if (px < 0)
  3974. pos.X += vel.X * 2;
  3975. else if (px > m_scene.RegionInfo.RegionSizeX)
  3976. pos.X -= vel.X * 2;
  3977. float py = pos.Y;
  3978. if (py < 0)
  3979. pos.Y += vel.Y * 2;
  3980. else if (py > m_scene.RegionInfo.RegionSizeY)
  3981. pos.Y -= vel.Y * 2;
  3982. Velocity = Vector3.Zero;
  3983. m_AngularVelocity = Vector3.Zero;
  3984. AbsolutePosition = pos;
  3985. }
  3986. }
  3987. public void CrossToNewRegionFail()
  3988. {
  3989. if (m_requestedSitTargetUUID == UUID.Zero)
  3990. {
  3991. bool isFlying = Flying;
  3992. RemoveFromPhysicalScene();
  3993. Vector3 pos = AbsolutePosition;
  3994. Vector3 vel = Velocity;
  3995. float px = pos.X;
  3996. if (px < 0)
  3997. pos.X += vel.X * 2;
  3998. else if (px > m_scene.RegionInfo.RegionSizeX)
  3999. pos.X -= vel.X * 2;
  4000. float py = pos.Y;
  4001. if (py < 0)
  4002. pos.Y += vel.Y * 2;
  4003. else if (py > m_scene.RegionInfo.RegionSizeY)
  4004. pos.Y -= vel.Y * 2;
  4005. Velocity = Vector3.Zero;
  4006. m_AngularVelocity = Vector3.Zero;
  4007. AbsolutePosition = pos;
  4008. AddToPhysicalScene(isFlying);
  4009. }
  4010. }
  4011. /// <summary>
  4012. /// Moves the agent outside the region bounds
  4013. /// Tells neighbor region that we're crossing to it
  4014. /// If the neighbor accepts, remove the agent's viewable avatar from this scene
  4015. /// set them to a child agent.
  4016. /// </summary>
  4017. protected bool CrossToNewRegion()
  4018. {
  4019. bool result = false;
  4020. // parcelRegionCross(false);
  4021. try
  4022. {
  4023. result = m_scene.CrossAgentToNewRegion(this, Flying);
  4024. }
  4025. catch
  4026. {
  4027. // result = m_scene.CrossAgentToNewRegion(this, false);
  4028. return false;
  4029. }
  4030. // if(!result)
  4031. // parcelRegionCross(true);
  4032. return result;
  4033. }
  4034. /// <summary>
  4035. /// Computes which child agents to close when the scene presence moves to another region.
  4036. /// Removes those regions from m_knownRegions.
  4037. /// </summary>
  4038. /// <param name="newRegionHandle">The new region's handle</param>
  4039. /// <param name="newRegionSizeX">The new region's size x</param>
  4040. /// <param name="newRegionSizeY">The new region's size y</param>
  4041. /// <returns></returns>
  4042. public List<ulong> GetChildAgentsToClose(ulong newRegionHandle, int newRegionSizeX, int newRegionSizeY)
  4043. {
  4044. ulong curRegionHandle = m_scene.RegionInfo.RegionHandle;
  4045. List<ulong> byebyeRegions = new List<ulong>();
  4046. if(newRegionHandle == curRegionHandle) //??
  4047. return byebyeRegions;
  4048. List<ulong> knownRegions = KnownRegionHandles;
  4049. m_log.DebugFormat(
  4050. "[SCENE PRESENCE]: Closing child agents. Checking {0} regions in {1}",
  4051. knownRegions.Count, Scene.RegionInfo.RegionName);
  4052. Util.RegionHandleToRegionLoc(newRegionHandle, out uint newRegionX, out uint newRegionY);
  4053. foreach (ulong handle in knownRegions)
  4054. {
  4055. if(newRegionY == 0) // HG
  4056. byebyeRegions.Add(handle);
  4057. else if(handle == curRegionHandle)
  4058. {
  4059. continue;
  4060. /*
  4061. RegionInfo curreg = m_scene.RegionInfo;
  4062. if (Util.IsOutsideView(255, curreg.RegionLocX, newRegionX, curreg.RegionLocY, newRegionY,
  4063. (int)curreg.RegionSizeX, (int)curreg.RegionSizeX, newRegionSizeX, newRegionSizeY))
  4064. {
  4065. byebyeRegions.Add(handle);
  4066. }
  4067. */
  4068. }
  4069. else
  4070. {
  4071. Util.RegionHandleToRegionLoc(handle, out uint x, out uint y);
  4072. if (m_knownChildRegionsSizeInfo.TryGetValue(handle, out spRegionSizeInfo regInfo))
  4073. {
  4074. // if (Util.IsOutsideView(RegionViewDistance, x, newRegionX, y, newRegionY,
  4075. // for now need to close all but first order bc RegionViewDistance it the target value not ours
  4076. if (Util.IsOutsideView(255, x, newRegionX, y, newRegionY,
  4077. regInfo.sizeX, regInfo.sizeY, newRegionSizeX, newRegionSizeY))
  4078. {
  4079. byebyeRegions.Add(handle);
  4080. }
  4081. }
  4082. else
  4083. {
  4084. // if (Util.IsOutsideView(RegionViewDistance, x, newRegionX, y, newRegionY,
  4085. if (Util.IsOutsideView(255, x, newRegionX, y, newRegionY,
  4086. (int)Constants.RegionSize, (int)Constants.RegionSize, newRegionSizeX, newRegionSizeY))
  4087. {
  4088. byebyeRegions.Add(handle);
  4089. }
  4090. }
  4091. }
  4092. }
  4093. return byebyeRegions;
  4094. }
  4095. public void CloseChildAgents(List<ulong> byebyeRegions)
  4096. {
  4097. byebyeRegions.Remove(Scene.RegionInfo.RegionHandle);
  4098. if (byebyeRegions.Count > 0)
  4099. {
  4100. m_log.Debug("[SCENE PRESENCE]: Closing " + byebyeRegions.Count + " child agents");
  4101. AgentCircuitData acd = Scene.AuthenticateHandler.GetAgentCircuitData(UUID);
  4102. string auth = string.Empty;
  4103. if (acd != null)
  4104. auth = acd.SessionID.ToString();
  4105. m_scene.SceneGridService.SendCloseChildAgentConnections(ControllingClient.AgentId, auth, byebyeRegions);
  4106. }
  4107. foreach (ulong handle in byebyeRegions)
  4108. {
  4109. RemoveNeighbourRegion(handle);
  4110. Scene.CapsModule.DropChildSeed(UUID, handle);
  4111. }
  4112. }
  4113. public void closeAllChildAgents()
  4114. {
  4115. List<ulong> byebyeRegions = new List<ulong>();
  4116. List<ulong> knownRegions = KnownRegionHandles;
  4117. foreach (ulong handle in knownRegions)
  4118. {
  4119. if (handle != Scene.RegionInfo.RegionHandle)
  4120. {
  4121. byebyeRegions.Add(handle);
  4122. RemoveNeighbourRegion(handle);
  4123. Scene.CapsModule.DropChildSeed(UUID, handle);
  4124. }
  4125. }
  4126. if (byebyeRegions.Count > 0)
  4127. {
  4128. m_log.Debug("[SCENE PRESENCE]: Closing " + byebyeRegions.Count + " child agents");
  4129. AgentCircuitData acd = Scene.AuthenticateHandler.GetAgentCircuitData(UUID);
  4130. string auth = string.Empty;
  4131. if (acd != null)
  4132. auth = acd.SessionID.ToString();
  4133. m_scene.SceneGridService.SendCloseChildAgentConnections(ControllingClient.AgentId, auth, byebyeRegions);
  4134. }
  4135. }
  4136. #endregion
  4137. /// <summary>
  4138. /// handle god level requests.
  4139. /// </summary>
  4140. public void GrantGodlikePowers(UUID token, bool godStatus)
  4141. {
  4142. if (IsNPC)
  4143. return;
  4144. bool wasgod = IsViewerUIGod;
  4145. GodController.RequestGodMode(godStatus);
  4146. if (wasgod != IsViewerUIGod)
  4147. parcelGodCheck(m_currentParcelUUID);
  4148. }
  4149. #region Child Agent Updates
  4150. public void UpdateChildAgent(AgentData cAgentData)
  4151. {
  4152. // m_log.Debug(" >>> ChildAgentDataUpdate <<< " + Scene.RegionInfo.RegionName);
  4153. if (!IsChildAgent)
  4154. return;
  4155. CopyFrom(cAgentData);
  4156. m_updateAgentReceivedAfterTransferEvent.Set();
  4157. }
  4158. private static Vector3 marker = new Vector3(-1f, -1f, -1f);
  4159. private void RaiseUpdateThrottles()
  4160. {
  4161. if(m_capbandwidth > 0)
  4162. return;
  4163. m_bandwidth = 4 * ControllingClient.GetAgentThrottleSilent((int)ThrottleOutPacketType.Texture);
  4164. if(m_bandwidth < 50000)
  4165. m_bandwidth = 50000;
  4166. m_bandwidthBurst = m_bandwidth / 5;
  4167. }
  4168. /// <summary>
  4169. /// This updates important decision making data about a child agent
  4170. /// The main purpose is to figure out what objects to send to a child agent that's in a neighboring region
  4171. /// </summary>
  4172. public void UpdateChildAgent(AgentPosition cAgentData)
  4173. {
  4174. if (!IsChildAgent)
  4175. return;
  4176. GodController.SetState(cAgentData.GodData);
  4177. RegionHandle = cAgentData.RegionHandle;
  4178. uint rRegionX = (uint)(RegionHandle >> 40);
  4179. uint rRegionY = (((uint)RegionHandle) >> 8);
  4180. uint tRegionX = m_scene.RegionInfo.RegionLocX;
  4181. uint tRegionY = m_scene.RegionInfo.RegionLocY;
  4182. //m_log.Debug(" >>> ChildAgentPositionUpdate <<< " + rRegionX + "-" + rRegionY);
  4183. int shiftx = ((int)rRegionX - (int)tRegionX) * (int)Constants.RegionSize;
  4184. int shifty = ((int)rRegionY - (int)tRegionY) * (int)Constants.RegionSize;
  4185. Vector3 offset = new Vector3(shiftx, shifty, 0f);
  4186. DrawDistance = cAgentData.Far;
  4187. m_pos = cAgentData.Position + offset;
  4188. CameraPosition = cAgentData.Center + offset;
  4189. if (cAgentData.ChildrenCapSeeds != null && cAgentData.ChildrenCapSeeds.Count > 0)
  4190. {
  4191. if (Scene.CapsModule != null)
  4192. {
  4193. Scene.CapsModule.SetChildrenSeed(UUID, cAgentData.ChildrenCapSeeds);
  4194. }
  4195. KnownRegions = cAgentData.ChildrenCapSeeds;
  4196. }
  4197. if ((cAgentData.Throttles != null) && cAgentData.Throttles.Length > 0)
  4198. {
  4199. // some scaling factor
  4200. float x = m_pos.X;
  4201. if (x > m_scene.RegionInfo.RegionSizeX)
  4202. x -= m_scene.RegionInfo.RegionSizeX;
  4203. float y = m_pos.Y;
  4204. if (y > m_scene.RegionInfo.RegionSizeY)
  4205. y -= m_scene.RegionInfo.RegionSizeY;
  4206. x = x * x + y * y;
  4207. float factor = 1.0f - x * 0.3f / Constants.RegionSize / Constants.RegionSize;
  4208. if (factor < 0.2f)
  4209. factor = 0.2f;
  4210. ControllingClient.SetChildAgentThrottle(cAgentData.Throttles,factor);
  4211. }
  4212. //cAgentData.AVHeight;
  4213. //m_velocity = cAgentData.Velocity;
  4214. checkRePrioritization();
  4215. }
  4216. public void CopyTo(AgentData cAgent, bool isCrossUpdate)
  4217. {
  4218. cAgent.CallbackURI = m_callbackURI;
  4219. cAgent.NewCallbackURI = m_newCallbackURI;
  4220. cAgent.AgentID = UUID;
  4221. cAgent.RegionID = Scene.RegionInfo.RegionID;
  4222. cAgent.SessionID = ControllingClient.SessionId;
  4223. cAgent.Position = AbsolutePosition;
  4224. cAgent.Velocity = m_velocity;
  4225. cAgent.Center = CameraPosition;
  4226. cAgent.AtAxis = CameraAtAxis;
  4227. cAgent.LeftAxis = CameraLeftAxis;
  4228. cAgent.UpAxis = CameraUpAxis;
  4229. cAgent.Far = DrawDistance;
  4230. cAgent.GodData = GodController.State();
  4231. // Throttles
  4232. cAgent.Throttles = ControllingClient.GetThrottlesPacked(1);
  4233. cAgent.HeadRotation = m_headrotation;
  4234. cAgent.BodyRotation = Rotation;
  4235. cAgent.ControlFlags = (uint)m_AgentControlFlags;
  4236. cAgent.AlwaysRun = SetAlwaysRun;
  4237. // make clear we want the all thing
  4238. cAgent.Appearance = new AvatarAppearance(Appearance,true,true);
  4239. cAgent.ParentPart = ParentUUID;
  4240. cAgent.SitOffset = PrevSitOffset;
  4241. lock (scriptedcontrols)
  4242. {
  4243. ControllerData[] controls = new ControllerData[scriptedcontrols.Count];
  4244. int i = 0;
  4245. foreach (ScriptControllers c in scriptedcontrols.Values)
  4246. {
  4247. controls[i++] = new ControllerData(c.objectID, c.itemID, (uint)c.ignoreControls, (uint)c.eventControls);
  4248. }
  4249. cAgent.Controllers = controls;
  4250. }
  4251. // Animations
  4252. try
  4253. {
  4254. cAgent.Anims = Animator.Animations.ToArray();
  4255. }
  4256. catch { }
  4257. cAgent.DefaultAnim = Animator.Animations.DefaultAnimation;
  4258. cAgent.AnimState = Animator.Animations.ImplicitDefaultAnimation;
  4259. cAgent.MovementAnimationOverRides = Overrides.CloneAOPairs();
  4260. cAgent.MotionState = (byte)Animator.currentControlState;
  4261. if (Scene.AttachmentsModule != null)
  4262. Scene.AttachmentsModule.CopyAttachments(this, cAgent);
  4263. if(isCrossUpdate)
  4264. {
  4265. cAgent.CrossingFlags = m_crossingFlags;
  4266. cAgent.CrossingFlags |= 1;
  4267. cAgent.CrossExtraFlags = 0;
  4268. if((LastCommands & ScriptControlled.CONTROL_LBUTTON) != 0)
  4269. cAgent.CrossExtraFlags |= 1;
  4270. if((LastCommands & ScriptControlled.CONTROL_ML_LBUTTON) != 0)
  4271. cAgent.CrossExtraFlags |= 2;
  4272. }
  4273. else
  4274. cAgent.CrossingFlags = 0;
  4275. if(isCrossUpdate)
  4276. {
  4277. //cAgent.agentCOF = COF;
  4278. cAgent.ActiveGroupID = ControllingClient.ActiveGroupId;
  4279. cAgent.ActiveGroupName = ControllingClient.ActiveGroupName;
  4280. if(Grouptitle == null)
  4281. cAgent.ActiveGroupTitle = String.Empty;
  4282. else
  4283. cAgent.ActiveGroupTitle = Grouptitle;
  4284. }
  4285. }
  4286. private void CopyFrom(AgentData cAgent)
  4287. {
  4288. m_callbackURI = cAgent.CallbackURI;
  4289. m_newCallbackURI = cAgent.NewCallbackURI;
  4290. // m_log.DebugFormat(
  4291. // "[SCENE PRESENCE]: Set callback for {0} in {1} to {2} in CopyFrom()",
  4292. // Name, m_scene.RegionInfo.RegionName, m_callbackURI);
  4293. GodController.SetState(cAgent.GodData);
  4294. m_pos = cAgent.Position;
  4295. m_velocity = cAgent.Velocity;
  4296. CameraPosition = cAgent.Center;
  4297. CameraAtAxis = cAgent.AtAxis;
  4298. CameraLeftAxis = cAgent.LeftAxis;
  4299. CameraUpAxis = cAgent.UpAxis;
  4300. Quaternion camRot = Util.Axes2Rot(CameraAtAxis, CameraLeftAxis, CameraUpAxis);
  4301. CameraRotation = camRot;
  4302. ParentUUID = cAgent.ParentPart;
  4303. PrevSitOffset = cAgent.SitOffset;
  4304. // When we get to the point of re-computing neighbors everytime this
  4305. // changes, then start using the agent's drawdistance rather than the
  4306. // region's draw distance.
  4307. DrawDistance = cAgent.Far;
  4308. //DrawDistance = Scene.DefaultDrawDistance;
  4309. if (cAgent.ChildrenCapSeeds != null && cAgent.ChildrenCapSeeds.Count > 0)
  4310. {
  4311. if (Scene.CapsModule != null)
  4312. {
  4313. Scene.CapsModule.SetChildrenSeed(UUID, cAgent.ChildrenCapSeeds);
  4314. }
  4315. KnownRegions = cAgent.ChildrenCapSeeds;
  4316. }
  4317. if ((cAgent.Throttles != null) && cAgent.Throttles.Length > 0)
  4318. ControllingClient.SetChildAgentThrottle(cAgent.Throttles, 1.0f);
  4319. m_headrotation = cAgent.HeadRotation;
  4320. Rotation = cAgent.BodyRotation;
  4321. m_AgentControlFlags = (AgentManager.ControlFlags)cAgent.ControlFlags;
  4322. SetAlwaysRun = cAgent.AlwaysRun;
  4323. Appearance = new AvatarAppearance(cAgent.Appearance, true, true);
  4324. /*
  4325. bool isFlying = ((m_AgentControlFlags & AgentManager.ControlFlags.AGENT_CONTROL_FLY) != 0);
  4326. if (PhysicsActor != null)
  4327. {
  4328. RemoveFromPhysicalScene();
  4329. AddToPhysicalScene(isFlying);
  4330. }
  4331. */
  4332. if (Scene.AttachmentsModule != null)
  4333. Scene.AttachmentsModule.CopyAttachments(cAgent, this);
  4334. try
  4335. {
  4336. lock (scriptedcontrols)
  4337. {
  4338. if (cAgent.Controllers != null)
  4339. {
  4340. scriptedcontrols.Clear();
  4341. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  4342. foreach (ControllerData c in cAgent.Controllers)
  4343. {
  4344. ScriptControllers sc = new ScriptControllers()
  4345. {
  4346. objectID = c.ObjectID,
  4347. itemID = c.ItemID,
  4348. ignoreControls = (ScriptControlled)c.IgnoreControls,
  4349. eventControls = (ScriptControlled)c.EventControls
  4350. };
  4351. scriptedcontrols[sc.itemID] = sc;
  4352. IgnoredControls |= sc.ignoreControls; // this is not correct, aparently only last applied should count
  4353. }
  4354. }
  4355. }
  4356. }
  4357. catch { }
  4358. // we are losing animator somewhere
  4359. if (Animator == null)
  4360. Animator = new ScenePresenceAnimator(this);
  4361. else
  4362. Animator.ResetAnimations();
  4363. Overrides.CopyAOPairsFrom(cAgent.MovementAnimationOverRides);
  4364. int nanim = ControllingClient.NextAnimationSequenceNumber;
  4365. // FIXME: Why is this null check necessary? Where are the cases where we get a null Anims object?
  4366. if (cAgent.DefaultAnim != null)
  4367. {
  4368. if (cAgent.DefaultAnim.SequenceNum > nanim)
  4369. nanim = cAgent.DefaultAnim.SequenceNum;
  4370. Animator.Animations.SetDefaultAnimation(cAgent.DefaultAnim.AnimID, cAgent.DefaultAnim.SequenceNum, UUID.Zero);
  4371. }
  4372. if (cAgent.AnimState != null)
  4373. {
  4374. if (cAgent.AnimState.SequenceNum > nanim)
  4375. nanim = cAgent.AnimState.SequenceNum;
  4376. Animator.Animations.SetImplicitDefaultAnimation(cAgent.AnimState.AnimID, cAgent.AnimState.SequenceNum, UUID.Zero);
  4377. }
  4378. if (cAgent.Anims != null)
  4379. {
  4380. int canim = Animator.Animations.FromArray(cAgent.Anims);
  4381. if(canim > nanim)
  4382. nanim = canim;
  4383. }
  4384. ControllingClient.NextAnimationSequenceNumber = ++nanim;
  4385. if (cAgent.MotionState != 0)
  4386. Animator.currentControlState = (ScenePresenceAnimator.motionControlStates) cAgent.MotionState;
  4387. m_crossingFlags = cAgent.CrossingFlags;
  4388. m_gotCrossUpdate = (m_crossingFlags != 0);
  4389. if(m_gotCrossUpdate)
  4390. {
  4391. LastCommands &= ~(ScriptControlled.CONTROL_LBUTTON | ScriptControlled.CONTROL_ML_LBUTTON);
  4392. if((cAgent.CrossExtraFlags & 1) != 0)
  4393. LastCommands |= ScriptControlled.CONTROL_LBUTTON;
  4394. if((cAgent.CrossExtraFlags & 2) != 0)
  4395. LastCommands |= ScriptControlled.CONTROL_ML_LBUTTON;
  4396. MouseDown = (cAgent.CrossExtraFlags & 3) != 0;
  4397. }
  4398. m_haveGroupInformation = false;
  4399. // using this as protocol detection don't want to mess with the numbers for now
  4400. if(cAgent.ActiveGroupTitle != null)
  4401. {
  4402. m_haveGroupInformation = true;
  4403. //COF = cAgent.agentCOF;
  4404. if(ControllingClient.IsGroupMember(cAgent.ActiveGroupID))
  4405. {
  4406. ControllingClient.ActiveGroupId = cAgent.ActiveGroupID;
  4407. ControllingClient.ActiveGroupName = cAgent.ActiveGroupName;
  4408. Grouptitle = cAgent.ActiveGroupTitle;
  4409. ControllingClient.ActiveGroupPowers =
  4410. ControllingClient.GetGroupPowers(cAgent.ActiveGroupID);
  4411. }
  4412. else
  4413. {
  4414. // we got a unknown active group so get what groups thinks about us
  4415. IGroupsModule gm = m_scene.RequestModuleInterface<IGroupsModule>();
  4416. if (gm != null)
  4417. gm.SendAgentGroupDataUpdate(ControllingClient);
  4418. }
  4419. }
  4420. lock (m_originRegionIDAccessLock)
  4421. m_originRegionID = cAgent.RegionID;
  4422. }
  4423. public bool CopyAgent(out IAgentData agent)
  4424. {
  4425. agent = new CompleteAgentData();
  4426. CopyTo((AgentData)agent, false);
  4427. return true;
  4428. }
  4429. #endregion Child Agent Updates
  4430. /// <summary>
  4431. /// Handles part of the PID controller function for moving an avatar.
  4432. /// </summary>
  4433. public void UpdateMovement()
  4434. {
  4435. /*
  4436. if (IsInTransit)
  4437. return;
  4438. lock(m_forceToApplyLock)
  4439. {
  4440. if (m_forceToApplyValid)
  4441. {
  4442. Velocity = m_forceToApply;
  4443. m_forceToApplyValid = false;
  4444. TriggerScenePresenceUpdated();
  4445. }
  4446. }
  4447. */
  4448. }
  4449. /// <summary>
  4450. /// Adds a physical representation of the avatar to the Physics plugin
  4451. /// </summary>
  4452. public void AddToPhysicalScene(bool isFlying)
  4453. {
  4454. // m_log.DebugFormat(
  4455. // "[SCENE PRESENCE]: Adding physics actor for {0}, ifFlying = {1} in {2}",
  4456. // Name, isFlying, Scene.RegionInfo.RegionName);
  4457. if (PhysicsActor != null)
  4458. {
  4459. m_log.ErrorFormat(
  4460. "[SCENE PRESENCE]: Adding physics actor for {0} to {1} but this scene presence already has a physics actor",
  4461. Name, Scene.RegionInfo.RegionName);
  4462. }
  4463. if (Appearance.AvatarHeight == 0)
  4464. // Appearance.SetHeight();
  4465. Appearance.SetSize(new Vector3(0.45f,0.6f,1.9f));
  4466. // lock(m_forceToApplyLock)
  4467. // m_forceToApplyValid = false;
  4468. PhysicsScene scene = m_scene.PhysicsScene;
  4469. Vector3 pVec = AbsolutePosition;
  4470. PhysicsActor pa = scene.AddAvatar(
  4471. LocalId, Firstname + "." + Lastname, pVec,
  4472. Appearance.AvatarBoxSize,Appearance.AvatarFeetOffset, isFlying);
  4473. pa.Orientation = m_bodyRot;
  4474. //PhysicsActor.OnRequestTerseUpdate += SendTerseUpdateToAllClients;
  4475. pa.OnCollisionUpdate += PhysicsCollisionUpdate;
  4476. pa.OnOutOfBounds += OutOfBoundsCall; // Called for PhysicsActors when there's something wrong
  4477. pa.SubscribeEvents(100);
  4478. pa.LocalID = LocalId;
  4479. pa.SetAlwaysRun = m_setAlwaysRun;
  4480. PhysicsActor = pa;
  4481. }
  4482. private void OutOfBoundsCall(Vector3 pos)
  4483. {
  4484. //bool flying = Flying;
  4485. //RemoveFromPhysicalScene();
  4486. //AddToPhysicalScene(flying);
  4487. if (ControllingClient != null)
  4488. ControllingClient.SendAgentAlertMessage("Physics is having a problem with your avatar. You may not be able to move until you relog.", true);
  4489. }
  4490. /// <summary>
  4491. /// Event called by the physics plugin to tell the avatar about a collision.
  4492. /// </summary>
  4493. /// <remarks>
  4494. /// This function is called continuously, even when there are no collisions. If the avatar is walking on the
  4495. /// ground or a prim then there will be collision information between the avatar and the surface.
  4496. ///
  4497. /// FIXME: However, we can't safely avoid calling this yet where there are no collisions without analyzing whether
  4498. /// any part of this method is relying on an every-frame call.
  4499. /// </remarks>
  4500. /// <param name="e"></param>
  4501. public void PhysicsCollisionUpdate(EventArgs e)
  4502. {
  4503. if (IsChildAgent)
  4504. return;
  4505. if(IsInTransit)
  4506. return;
  4507. //if ((Math.Abs(Velocity.X) > 0.1e-9f) || (Math.Abs(Velocity.Y) > 0.1e-9f))
  4508. // The Physics Scene will send updates every 500 ms grep: PhysicsActor.SubscribeEvents(
  4509. // as of this comment the interval is set in AddToPhysicalScene
  4510. // if (m_updateCount > 0)
  4511. // {
  4512. // if (Animator != null && Animator.UpdateMovementAnimations())
  4513. // TriggerScenePresenceUpdated();
  4514. // m_updateCount--;
  4515. // }
  4516. CollisionEventUpdate collisionData = (CollisionEventUpdate)e;
  4517. Dictionary<uint, ContactPoint> coldata = collisionData.m_objCollisionList;
  4518. // // No collisions at all means we may be flying. Update always
  4519. // // to make falling work
  4520. // if (m_lastColCount != coldata.Count || coldata.Count == 0)
  4521. // {
  4522. // m_updateCount = UPDATE_COUNT;
  4523. // m_lastColCount = coldata.Count;
  4524. // }
  4525. if (coldata.Count != 0)
  4526. {
  4527. ContactPoint lowest;
  4528. lowest.SurfaceNormal = Vector3.Zero;
  4529. lowest.Position = Vector3.Zero;
  4530. lowest.Position.Z = float.MaxValue;
  4531. foreach (ContactPoint contact in coldata.Values)
  4532. {
  4533. if (contact.CharacterFeet && contact.Position.Z < lowest.Position.Z)
  4534. lowest = contact;
  4535. }
  4536. if (lowest.Position.Z != float.MaxValue)
  4537. {
  4538. lowest.SurfaceNormal = -lowest.SurfaceNormal;
  4539. CollisionPlane = new Vector4(lowest.SurfaceNormal, Vector3.Dot(lowest.Position, lowest.SurfaceNormal));
  4540. }
  4541. else
  4542. CollisionPlane = Vector4.UnitW;
  4543. }
  4544. else
  4545. CollisionPlane = Vector4.UnitW;
  4546. RaiseCollisionScriptEvents(coldata);
  4547. // Gods do not take damage and Invulnerable is set depending on parcel/region flags
  4548. if (Invulnerable || IsViewerUIGod)
  4549. return;
  4550. // The following may be better in the ICombatModule
  4551. // probably tweaking of the values for ground and normal prim collisions will be needed
  4552. float startHealth = Health;
  4553. if(coldata.Count > 0)
  4554. {
  4555. uint killerObj = 0;
  4556. SceneObjectPart part = null;
  4557. float rvel; // relative velocity, negative on approch
  4558. foreach (uint localid in coldata.Keys)
  4559. {
  4560. if (localid == 0)
  4561. {
  4562. // 0 is the ground
  4563. rvel = coldata[0].RelativeSpeed;
  4564. if(rvel < -5.0f)
  4565. Health -= 0.01f * rvel * rvel;
  4566. }
  4567. else
  4568. {
  4569. part = Scene.GetSceneObjectPart(localid);
  4570. if(part != null && !part.ParentGroup.IsVolumeDetect)
  4571. {
  4572. if (part.ParentGroup.Damage > 0.0f)
  4573. {
  4574. // Something with damage...
  4575. Health -= part.ParentGroup.Damage;
  4576. part.ParentGroup.Scene.DeleteSceneObject(part.ParentGroup, false);
  4577. }
  4578. else
  4579. {
  4580. // An ordinary prim
  4581. rvel = coldata[localid].RelativeSpeed;
  4582. if(rvel < -5.0f)
  4583. {
  4584. Health -= 0.005f * rvel * rvel;
  4585. }
  4586. }
  4587. }
  4588. else
  4589. {
  4590. }
  4591. }
  4592. if (Health <= 0.0f)
  4593. {
  4594. if (localid != 0)
  4595. killerObj = localid;
  4596. }
  4597. }
  4598. if (Health <= 0)
  4599. {
  4600. ControllingClient.SendHealth(Health);
  4601. m_scene.EventManager.TriggerAvatarKill(killerObj, this);
  4602. return;
  4603. }
  4604. }
  4605. if(Math.Abs(Health - startHealth) > 1.0)
  4606. ControllingClient.SendHealth(Health);
  4607. }
  4608. public void setHealthWithUpdate(float health)
  4609. {
  4610. Health = health;
  4611. ControllingClient.SendHealth(Health);
  4612. }
  4613. public void AddAttachment(SceneObjectGroup gobj)
  4614. {
  4615. lock (m_attachments)
  4616. {
  4617. // This may be true when the attachment comes back
  4618. // from serialization after login. Clear it.
  4619. gobj.IsDeleted = false;
  4620. m_attachments.Add(gobj);
  4621. }
  4622. IBakedTextureModule bakedModule = m_scene.RequestModuleInterface<IBakedTextureModule>();
  4623. if (bakedModule != null)
  4624. bakedModule.UpdateMeshAvatar(m_uuid);
  4625. }
  4626. public int GetAttachmentsCount()
  4627. {
  4628. return m_attachments.Count;
  4629. }
  4630. /// <summary>
  4631. /// Get all the presence's attachments.
  4632. /// </summary>
  4633. /// <returns>A copy of the list which contains the attachments.</returns>
  4634. public List<SceneObjectGroup> GetAttachments()
  4635. {
  4636. lock (m_attachments)
  4637. return new List<SceneObjectGroup>(m_attachments);
  4638. }
  4639. /// <summary>
  4640. /// Get the scene objects attached to the given point.
  4641. /// </summary>
  4642. /// <param name="attachmentPoint"></param>
  4643. /// <returns>Returns an empty list if there were no attachments at the point.</returns>
  4644. public List<SceneObjectGroup> GetAttachments(uint attachmentPoint)
  4645. {
  4646. List<SceneObjectGroup> attachments = new List<SceneObjectGroup>();
  4647. if (attachmentPoint >= 0)
  4648. {
  4649. lock (m_attachments)
  4650. {
  4651. foreach (SceneObjectGroup so in m_attachments)
  4652. {
  4653. if (attachmentPoint == so.AttachmentPoint)
  4654. attachments.Add(so);
  4655. }
  4656. }
  4657. }
  4658. return attachments;
  4659. }
  4660. public bool HasAttachments()
  4661. {
  4662. lock (m_attachments)
  4663. return m_attachments.Count > 0;
  4664. }
  4665. /// <summary>
  4666. /// Returns the total count of scripts in all parts inventories.
  4667. /// </summary>
  4668. public int ScriptCount()
  4669. {
  4670. int count = 0;
  4671. lock (m_attachments)
  4672. {
  4673. foreach (SceneObjectGroup gobj in m_attachments)
  4674. {
  4675. if (gobj != null)
  4676. {
  4677. count += gobj.ScriptCount();
  4678. }
  4679. }
  4680. }
  4681. return count;
  4682. }
  4683. /// <summary>
  4684. /// A float the value is a representative execution time in milliseconds of all scripts in all attachments.
  4685. /// </summary>
  4686. public float ScriptExecutionTime()
  4687. {
  4688. float time = 0.0f;
  4689. lock (m_attachments)
  4690. {
  4691. foreach (SceneObjectGroup gobj in m_attachments)
  4692. {
  4693. if (gobj != null)
  4694. {
  4695. time += gobj.ScriptExecutionTime();
  4696. }
  4697. }
  4698. }
  4699. return time;
  4700. }
  4701. /// <summary>
  4702. /// Returns the total count of running scripts in all parts.
  4703. /// </summary>
  4704. public int RunningScriptCount()
  4705. {
  4706. int count = 0;
  4707. lock (m_attachments)
  4708. {
  4709. foreach (SceneObjectGroup gobj in m_attachments)
  4710. {
  4711. if (gobj != null)
  4712. {
  4713. count += gobj.RunningScriptCount();
  4714. }
  4715. }
  4716. }
  4717. return count;
  4718. }
  4719. public bool HasScriptedAttachments()
  4720. {
  4721. lock (m_attachments)
  4722. {
  4723. foreach (SceneObjectGroup gobj in m_attachments)
  4724. {
  4725. if (gobj != null)
  4726. {
  4727. if (gobj.RootPart.Inventory.ContainsScripts())
  4728. return true;
  4729. }
  4730. }
  4731. }
  4732. return false;
  4733. }
  4734. public void RemoveAttachment(SceneObjectGroup gobj)
  4735. {
  4736. lock (m_attachments)
  4737. m_attachments.Remove(gobj);
  4738. }
  4739. /// <summary>
  4740. /// Clear all attachments
  4741. /// </summary>
  4742. public void ClearAttachments()
  4743. {
  4744. lock (m_attachments)
  4745. m_attachments.Clear();
  4746. }
  4747. /// <summary>
  4748. /// This is currently just being done for information.
  4749. /// </summary>
  4750. public bool ValidateAttachments()
  4751. {
  4752. bool validated = true;
  4753. lock (m_attachments)
  4754. {
  4755. // Validate
  4756. foreach (SceneObjectGroup gobj in m_attachments)
  4757. {
  4758. if (gobj == null)
  4759. {
  4760. m_log.WarnFormat(
  4761. "[SCENE PRESENCE]: Failed to validate an attachment for {0} since it was null. Continuing", Name);
  4762. validated = false;
  4763. }
  4764. else if (gobj.IsDeleted)
  4765. {
  4766. m_log.WarnFormat(
  4767. "[SCENE PRESENCE]: Failed to validate attachment {0} {1} for {2} since it had been deleted. Continuing",
  4768. gobj.Name, gobj.UUID, Name);
  4769. validated = false;
  4770. }
  4771. }
  4772. }
  4773. return validated;
  4774. }
  4775. /*
  4776. public void SendAttachmentsToAllAgents()
  4777. {
  4778. lock (m_attachments)
  4779. {
  4780. foreach (SceneObjectGroup sog in m_attachments)
  4781. {
  4782. m_scene.ForEachScenePresence(delegate(ScenePresence p)
  4783. {
  4784. if (p != this && sog.HasPrivateAttachmentPoint)
  4785. return;
  4786. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  4787. return;
  4788. SendTerseUpdateToAgentNF(p);
  4789. SendAttachmentFullUpdateToAgentNF(sog, p);
  4790. });
  4791. }
  4792. }
  4793. }
  4794. */
  4795. // send attachments to a client without filters except for huds
  4796. // for now they are checked in several places down the line...
  4797. public void SendAttachmentsToAgentNF(ScenePresence p)
  4798. {
  4799. SendTerseUpdateToAgentNF(p);
  4800. // SendAvatarDataToAgentNF(this);
  4801. lock (m_attachments)
  4802. {
  4803. foreach (SceneObjectGroup sog in m_attachments)
  4804. {
  4805. SendAttachmentFullUpdateToAgentNF(sog, p);
  4806. }
  4807. }
  4808. }
  4809. public void SendAttachmentFullUpdateToAgentNF(SceneObjectGroup sog, ScenePresence p)
  4810. {
  4811. if (p != this && sog.HasPrivateAttachmentPoint)
  4812. return;
  4813. SceneObjectPart[] parts = sog.Parts;
  4814. SceneObjectPart rootpart = sog.RootPart;
  4815. PrimUpdateFlags update = PrimUpdateFlags.FullUpdate;
  4816. if (rootpart.Shape.MeshFlagEntry)
  4817. update = PrimUpdateFlags.FullUpdatewithAnim;
  4818. p.ControllingClient.SendEntityUpdate(rootpart, update);
  4819. for (int i = 0; i < parts.Length; i++)
  4820. {
  4821. SceneObjectPart part = parts[i];
  4822. if (part == rootpart)
  4823. continue;
  4824. p.ControllingClient.SendEntityUpdate(part, update);
  4825. }
  4826. }
  4827. public void SendAttachmentScheduleUpdate(SceneObjectGroup sog)
  4828. {
  4829. if (IsChildAgent || IsInTransit)
  4830. return;
  4831. SceneObjectPart[] origparts = sog.Parts;
  4832. SceneObjectPart[] parts = new SceneObjectPart[origparts.Length];
  4833. PrimUpdateFlags[] flags = new PrimUpdateFlags[origparts.Length];
  4834. SceneObjectPart rootpart = sog.RootPart;
  4835. PrimUpdateFlags cur = sog.RootPart.GetAndClearUpdateFlag();
  4836. bool noanim = !rootpart.Shape.MeshFlagEntry;
  4837. int nparts = 0;
  4838. if (noanim || rootpart.Animations == null)
  4839. cur &= ~PrimUpdateFlags.Animations;
  4840. if (cur != PrimUpdateFlags.None)
  4841. {
  4842. flags[nparts] = cur;
  4843. parts[nparts] = rootpart;
  4844. ++nparts;
  4845. }
  4846. for (int i = 0; i < origparts.Length; i++)
  4847. {
  4848. if (origparts[i] == rootpart)
  4849. continue;
  4850. cur = origparts[i].GetAndClearUpdateFlag();
  4851. if (noanim || origparts[i].Animations == null)
  4852. cur &= ~PrimUpdateFlags.Animations;
  4853. if (cur == PrimUpdateFlags.None)
  4854. continue;
  4855. flags[nparts] = cur;
  4856. parts[nparts] = origparts[i];
  4857. ++nparts;
  4858. }
  4859. if (nparts == 0)
  4860. return;
  4861. for (int i = 0; i < nparts; i++)
  4862. ControllingClient.SendEntityUpdate(parts[i], flags[i]);
  4863. if (sog.HasPrivateAttachmentPoint)
  4864. return;
  4865. List<ScenePresence> allPresences = m_scene.GetScenePresences();
  4866. foreach (ScenePresence p in allPresences)
  4867. {
  4868. if (p == this)
  4869. continue;
  4870. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  4871. continue;
  4872. for (int i = 0; i < nparts; i++)
  4873. p.ControllingClient.SendEntityUpdate(parts[i], flags[i]);
  4874. }
  4875. }
  4876. public void SendAttachmentUpdate(SceneObjectGroup sog, PrimUpdateFlags update)
  4877. {
  4878. if (IsChildAgent || IsInTransit)
  4879. return;
  4880. SceneObjectPart[] origparts = sog.Parts;
  4881. SceneObjectPart[] parts = new SceneObjectPart[origparts.Length];
  4882. PrimUpdateFlags[] flags = new PrimUpdateFlags[origparts.Length];
  4883. SceneObjectPart rootpart = sog.RootPart;
  4884. bool noanim = !rootpart.Shape.MeshFlagEntry;
  4885. int nparts = 0;
  4886. PrimUpdateFlags cur = update;
  4887. if (noanim || rootpart.Animations == null)
  4888. cur &= ~PrimUpdateFlags.Animations;
  4889. if (cur != PrimUpdateFlags.None)
  4890. {
  4891. flags[nparts] = cur;
  4892. parts[nparts] = rootpart;
  4893. ++nparts;
  4894. }
  4895. for (int i = 0; i < origparts.Length; i++)
  4896. {
  4897. if (origparts[i] == rootpart)
  4898. continue;
  4899. cur = update;
  4900. if (noanim || origparts[i].Animations == null)
  4901. cur &= ~PrimUpdateFlags.Animations;
  4902. if (cur == PrimUpdateFlags.None)
  4903. continue;
  4904. flags[nparts] = cur;
  4905. parts[nparts] = origparts[i];
  4906. ++nparts;
  4907. }
  4908. if (nparts == 0)
  4909. return;
  4910. for(int i = 0; i < nparts; i++)
  4911. ControllingClient.SendEntityUpdate(parts[i], flags[i]);
  4912. if (sog.HasPrivateAttachmentPoint)
  4913. return;
  4914. List<ScenePresence> allPresences = m_scene.GetScenePresences();
  4915. foreach (ScenePresence p in allPresences)
  4916. {
  4917. if (p == this)
  4918. continue;
  4919. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  4920. continue;
  4921. p.ControllingClient.SendEntityUpdate(rootpart, update);
  4922. for (int i = 0; i < nparts; i++)
  4923. p.ControllingClient.SendEntityUpdate(parts[i], flags[i]);
  4924. }
  4925. }
  4926. public void SendAttachmentUpdate(SceneObjectPart part, PrimUpdateFlags update)
  4927. {
  4928. if (IsChildAgent || IsInTransit)
  4929. return;
  4930. if ((update & PrimUpdateFlags.Animations) != 0 && part.Animations == null)
  4931. {
  4932. update &= ~PrimUpdateFlags.Animations;
  4933. if (update == PrimUpdateFlags.None)
  4934. return;
  4935. }
  4936. ControllingClient.SendEntityUpdate(part, update);
  4937. if (part.ParentGroup.HasPrivateAttachmentPoint)
  4938. return;
  4939. List<ScenePresence> allPresences = m_scene.GetScenePresences();
  4940. foreach (ScenePresence p in allPresences)
  4941. {
  4942. if (p == this)
  4943. continue;
  4944. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  4945. continue;
  4946. p.ControllingClient.SendEntityUpdate(part, update);
  4947. }
  4948. }
  4949. public void SendScriptChangedEventToAttachments(Changed val)
  4950. {
  4951. lock (m_attachments)
  4952. {
  4953. foreach (SceneObjectGroup grp in m_attachments)
  4954. {
  4955. if ((grp.ScriptEvents & scriptEvents.changed) != 0)
  4956. {
  4957. foreach(SceneObjectPart sop in grp.Parts)
  4958. {
  4959. sop.TriggerScriptChangedEvent(val);
  4960. }
  4961. }
  4962. }
  4963. }
  4964. }
  4965. /// <summary>
  4966. /// Gets the mass.
  4967. /// </summary>
  4968. /// <returns>
  4969. /// The mass.
  4970. /// </returns>
  4971. public float GetMass()
  4972. {
  4973. PhysicsActor pa = PhysicsActor;
  4974. if (pa != null)
  4975. return pa.Mass;
  4976. else
  4977. return 0;
  4978. }
  4979. internal void PushForce(Vector3 impulse)
  4980. {
  4981. if (PhysicsActor != null)
  4982. {
  4983. PhysicsActor.AddForce(impulse,true);
  4984. }
  4985. }
  4986. CameraData physActor_OnPhysicsRequestingCameraData()
  4987. {
  4988. return new CameraData
  4989. {
  4990. Valid = true,
  4991. MouseLook = this.m_mouseLook,
  4992. CameraRotation = this.CameraRotation,
  4993. CameraAtAxis = this.CameraAtAxis
  4994. };
  4995. }
  4996. public void RegisterControlEventsToScript(int controls, int accept, int pass_on, uint Obj_localID, UUID Script_item_UUID)
  4997. {
  4998. SceneObjectPart part = m_scene.GetSceneObjectPart(Obj_localID);
  4999. if (part == null)
  5000. return;
  5001. ControllingClient.SendTakeControls(controls, false, false);
  5002. ControllingClient.SendTakeControls(controls, true, false);
  5003. ScriptControllers obj = new ScriptControllers()
  5004. {
  5005. ignoreControls = ScriptControlled.CONTROL_ZERO,
  5006. eventControls = ScriptControlled.CONTROL_ZERO,
  5007. objectID = part.ParentGroup.UUID,
  5008. itemID = Script_item_UUID
  5009. };
  5010. if (pass_on == 0 && accept == 0)
  5011. {
  5012. IgnoredControls |= (ScriptControlled)controls;
  5013. obj.ignoreControls = (ScriptControlled)controls;
  5014. }
  5015. if (pass_on == 0 && accept == 1)
  5016. {
  5017. IgnoredControls |= (ScriptControlled)controls;
  5018. obj.ignoreControls = (ScriptControlled)controls;
  5019. obj.eventControls = (ScriptControlled)controls;
  5020. }
  5021. if (pass_on == 1 && accept == 1)
  5022. {
  5023. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  5024. obj.eventControls = (ScriptControlled)controls;
  5025. obj.ignoreControls = ScriptControlled.CONTROL_ZERO;
  5026. }
  5027. lock (scriptedcontrols)
  5028. {
  5029. if (pass_on == 1 && accept == 0)
  5030. {
  5031. IgnoredControls &= ~(ScriptControlled)controls;
  5032. if (scriptedcontrols.ContainsKey(Script_item_UUID))
  5033. RemoveScriptFromControlNotifications(Script_item_UUID, part);
  5034. }
  5035. else
  5036. {
  5037. AddScriptToControlNotifications(Script_item_UUID, part, ref obj);
  5038. }
  5039. }
  5040. ControllingClient.SendTakeControls(controls, pass_on == 1 ? true : false, true);
  5041. }
  5042. private void AddScriptToControlNotifications(OpenMetaverse.UUID Script_item_UUID, SceneObjectPart part, ref ScriptControllers obj)
  5043. {
  5044. scriptedcontrols[Script_item_UUID] = obj;
  5045. PhysicsActor physActor = part.ParentGroup.RootPart.PhysActor;
  5046. if (physActor != null)
  5047. {
  5048. physActor.OnPhysicsRequestingCameraData -= physActor_OnPhysicsRequestingCameraData;
  5049. physActor.OnPhysicsRequestingCameraData += physActor_OnPhysicsRequestingCameraData;
  5050. }
  5051. }
  5052. private void RemoveScriptFromControlNotifications(OpenMetaverse.UUID Script_item_UUID, SceneObjectPart part)
  5053. {
  5054. scriptedcontrols.Remove(Script_item_UUID);
  5055. if (part != null)
  5056. {
  5057. PhysicsActor physActor = part.ParentGroup.RootPart.PhysActor;
  5058. if (physActor != null)
  5059. {
  5060. physActor.OnPhysicsRequestingCameraData -= physActor_OnPhysicsRequestingCameraData;
  5061. }
  5062. }
  5063. }
  5064. public void HandleForceReleaseControls(IClientAPI remoteClient, UUID agentID)
  5065. {
  5066. foreach (ScriptControllers c in scriptedcontrols.Values)
  5067. {
  5068. SceneObjectGroup sog = m_scene.GetSceneObjectGroup(c.objectID);
  5069. if(sog != null && !sog.IsDeleted && sog.RootPart.PhysActor != null)
  5070. sog.RootPart.PhysActor.OnPhysicsRequestingCameraData -= physActor_OnPhysicsRequestingCameraData;
  5071. }
  5072. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  5073. lock (scriptedcontrols)
  5074. {
  5075. scriptedcontrols.Clear();
  5076. }
  5077. ControllingClient.SendTakeControls(int.MaxValue, false, false);
  5078. }
  5079. public void HandleRevokePermissions(UUID objectID, uint permissions )
  5080. {
  5081. // still skeleton code
  5082. if((permissions & (16 | 0x8000 )) == 0) //PERMISSION_TRIGGER_ANIMATION | PERMISSION_OVERRIDE_ANIMATIONS
  5083. return;
  5084. if(objectID == m_scene.RegionInfo.RegionID) // for all objects
  5085. {
  5086. List<SceneObjectGroup> sogs = m_scene.GetSceneObjectGroups();
  5087. for(int i = 0; i < sogs.Count; ++i)
  5088. sogs[i].RemoveScriptsPermissions(this, (int)permissions);
  5089. }
  5090. else
  5091. {
  5092. SceneObjectPart part = m_scene.GetSceneObjectPart(objectID);
  5093. if(part != null)
  5094. {
  5095. part.Inventory.RemoveScriptsPermissions(this, (int)permissions);
  5096. }
  5097. }
  5098. }
  5099. public void ClearControls()
  5100. {
  5101. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  5102. lock (scriptedcontrols)
  5103. {
  5104. scriptedcontrols.Clear();
  5105. }
  5106. }
  5107. public void UnRegisterSeatControls(UUID obj)
  5108. {
  5109. List<UUID> takers = new List<UUID>();
  5110. foreach (ScriptControllers c in scriptedcontrols.Values)
  5111. {
  5112. if (c.objectID == obj)
  5113. takers.Add(c.itemID);
  5114. }
  5115. foreach (UUID t in takers)
  5116. {
  5117. UnRegisterControlEventsToScript(0, t);
  5118. }
  5119. }
  5120. public void UnRegisterControlEventsToScript(uint Obj_localID, UUID Script_item_UUID)
  5121. {
  5122. SceneObjectPart part = m_scene.GetSceneObjectPart(Obj_localID);
  5123. lock (scriptedcontrols)
  5124. {
  5125. if (scriptedcontrols.TryGetValue(Script_item_UUID, out ScriptControllers takecontrols))
  5126. {
  5127. ScriptControlled sctc = takecontrols.eventControls;
  5128. ControllingClient.SendTakeControls((int)sctc, false, false);
  5129. ControllingClient.SendTakeControls((int)sctc, true, false);
  5130. RemoveScriptFromControlNotifications(Script_item_UUID, part);
  5131. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  5132. foreach (ScriptControllers scData in scriptedcontrols.Values)
  5133. {
  5134. IgnoredControls |= scData.ignoreControls;
  5135. }
  5136. }
  5137. }
  5138. }
  5139. private void SendControlsToScripts(uint flags)
  5140. {
  5141. // Notify the scripts only after calling UpdateMovementAnimations(), so that if a script
  5142. // (e.g., a walking script) checks which animation is active it will be the correct animation.
  5143. lock (scriptedcontrols)
  5144. {
  5145. if (scriptedcontrols.Count <= 0)
  5146. return;
  5147. ScriptControlled allflags;
  5148. // convert mouse from edge to level
  5149. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_UP) != 0 ||
  5150. (flags & unchecked((uint)AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_UP)) != 0)
  5151. {
  5152. allflags = ScriptControlled.CONTROL_ZERO;
  5153. }
  5154. else // recover last state of mouse
  5155. allflags = LastCommands & (ScriptControlled.CONTROL_ML_LBUTTON | ScriptControlled.CONTROL_LBUTTON);
  5156. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_DOWN) != 0)
  5157. allflags |= ScriptControlled.CONTROL_ML_LBUTTON;
  5158. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN) != 0)
  5159. allflags |= ScriptControlled.CONTROL_LBUTTON;
  5160. // find all activated controls, whether the scripts are interested in them or not
  5161. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_AT_POS) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS) != 0)
  5162. {
  5163. allflags |= ScriptControlled.CONTROL_FWD;
  5164. }
  5165. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_NEG) != 0)
  5166. {
  5167. allflags |= ScriptControlled.CONTROL_BACK;
  5168. }
  5169. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_POS) != 0)
  5170. {
  5171. allflags |= ScriptControlled.CONTROL_UP;
  5172. }
  5173. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG) != 0)
  5174. {
  5175. allflags |= ScriptControlled.CONTROL_DOWN;
  5176. }
  5177. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_POS) != 0)
  5178. {
  5179. allflags |= ScriptControlled.CONTROL_LEFT;
  5180. }
  5181. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_NEG) != 0)
  5182. {
  5183. allflags |= ScriptControlled.CONTROL_RIGHT;
  5184. }
  5185. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG) != 0)
  5186. {
  5187. allflags |= ScriptControlled.CONTROL_ROT_RIGHT;
  5188. }
  5189. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS) != 0)
  5190. {
  5191. allflags |= ScriptControlled.CONTROL_ROT_LEFT;
  5192. }
  5193. // optimization; we have to check per script, but if nothing is pressed and nothing changed, we can skip that
  5194. if (allflags != ScriptControlled.CONTROL_ZERO || allflags != LastCommands)
  5195. {
  5196. foreach (KeyValuePair<UUID, ScriptControllers> kvp in scriptedcontrols)
  5197. {
  5198. UUID scriptUUID = kvp.Key;
  5199. ScriptControllers scriptControlData = kvp.Value;
  5200. ScriptControlled localHeld = allflags & scriptControlData.eventControls; // the flags interesting for us
  5201. ScriptControlled localLast = LastCommands & scriptControlData.eventControls; // the activated controls in the last cycle
  5202. ScriptControlled localChange = localHeld ^ localLast; // the changed bits
  5203. if (localHeld != ScriptControlled.CONTROL_ZERO || localChange != ScriptControlled.CONTROL_ZERO)
  5204. {
  5205. // only send if still pressed or just changed
  5206. m_scene.EventManager.TriggerControlEvent(scriptUUID, UUID, (uint)localHeld, (uint)localChange);
  5207. }
  5208. }
  5209. }
  5210. LastCommands = allflags;
  5211. MouseDown = (allflags & (ScriptControlled.CONTROL_ML_LBUTTON | ScriptControlled.CONTROL_LBUTTON)) != 0;
  5212. }
  5213. }
  5214. internal static AgentManager.ControlFlags RemoveIgnoredControls(AgentManager.ControlFlags flags, ScriptControlled ignored)
  5215. {
  5216. if (ignored == ScriptControlled.CONTROL_ZERO)
  5217. return flags;
  5218. if ((ignored & ScriptControlled.CONTROL_BACK) != 0)
  5219. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG | AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_NEG);
  5220. if ((ignored & ScriptControlled.CONTROL_FWD) != 0)
  5221. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS | AgentManager.ControlFlags.AGENT_CONTROL_AT_POS);
  5222. if ((ignored & ScriptControlled.CONTROL_DOWN) != 0)
  5223. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG | AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG);
  5224. if ((ignored & ScriptControlled.CONTROL_UP) != 0)
  5225. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_POS | AgentManager.ControlFlags.AGENT_CONTROL_UP_POS);
  5226. if ((ignored & ScriptControlled.CONTROL_LEFT) != 0)
  5227. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS | AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_POS);
  5228. if ((ignored & ScriptControlled.CONTROL_RIGHT) != 0)
  5229. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_NEG | AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG);
  5230. if ((ignored & ScriptControlled.CONTROL_ROT_LEFT) != 0)
  5231. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG);
  5232. if ((ignored & ScriptControlled.CONTROL_ROT_RIGHT) != 0)
  5233. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS);
  5234. if ((ignored & ScriptControlled.CONTROL_ML_LBUTTON) != 0)
  5235. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_DOWN);
  5236. if ((ignored & ScriptControlled.CONTROL_LBUTTON) != 0)
  5237. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_UP | AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN);
  5238. //DIR_CONTROL_FLAG_FORWARD = AgentManager.ControlFlags.AGENT_CONTROL_AT_POS,
  5239. //DIR_CONTROL_FLAG_BACK = AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG,
  5240. //DIR_CONTROL_FLAG_LEFT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS,
  5241. //DIR_CONTROL_FLAG_RIGHT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG,
  5242. //DIR_CONTROL_FLAG_UP = AgentManager.ControlFlags.AGENT_CONTROL_UP_POS,
  5243. //DIR_CONTROL_FLAG_DOWN = AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG,
  5244. //DIR_CONTROL_FLAG_DOWN_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG
  5245. return flags;
  5246. }
  5247. // returns true it local teleport allowed and sets the destiny position into pos
  5248. public bool CheckLocalTPLandingPoint(ref Vector3 pos)
  5249. {
  5250. // Never constrain lures
  5251. if ((TeleportFlags & TeleportFlags.ViaLure) != 0)
  5252. return true;
  5253. if (m_scene.RegionInfo.EstateSettings.AllowDirectTeleport)
  5254. return true;
  5255. // do not constrain gods and estate managers
  5256. if(m_scene.Permissions.IsGod(m_uuid) ||
  5257. m_scene.RegionInfo.EstateSettings.IsEstateManagerOrOwner(m_uuid))
  5258. return true;
  5259. // will teleport to a telehub spawn point or landpoint if that results in getting closer to target
  5260. // if not the local teleport fails.
  5261. float currDistanceSQ = Vector3.DistanceSquared(AbsolutePosition, pos);
  5262. // first check telehub
  5263. UUID TelehubObjectID = m_scene.RegionInfo.RegionSettings.TelehubObject;
  5264. if ( TelehubObjectID != UUID.Zero)
  5265. {
  5266. SceneObjectGroup telehubSOG = m_scene.GetSceneObjectGroup(TelehubObjectID);
  5267. if(telehubSOG != null)
  5268. {
  5269. Vector3 spawnPos;
  5270. float spawnDistSQ;
  5271. SpawnPoint[] spawnPoints = m_scene.RegionInfo.RegionSettings.SpawnPoints().ToArray();
  5272. if(spawnPoints.Length == 0)
  5273. {
  5274. spawnPos = new Vector3(128.0f, 128.0f, pos.Z);
  5275. spawnDistSQ = Vector3.DistanceSquared(spawnPos, pos);
  5276. }
  5277. else
  5278. {
  5279. Vector3 hubPos = telehubSOG.AbsolutePosition;
  5280. Quaternion hubRot = telehubSOG.GroupRotation;
  5281. spawnPos = spawnPoints[0].GetLocation(hubPos, hubRot);
  5282. spawnDistSQ = Vector3.DistanceSquared(spawnPos, pos);
  5283. float testDistSQ;
  5284. Vector3 testSpawnPos;
  5285. for(int i = 1; i< spawnPoints.Length; i++)
  5286. {
  5287. testSpawnPos = spawnPoints[i].GetLocation(hubPos, hubRot);
  5288. testDistSQ = Vector3.DistanceSquared(testSpawnPos, pos);
  5289. if(testDistSQ < spawnDistSQ)
  5290. {
  5291. spawnPos = testSpawnPos;
  5292. spawnDistSQ = testDistSQ;
  5293. }
  5294. }
  5295. }
  5296. if (currDistanceSQ < spawnDistSQ)
  5297. {
  5298. // we are already close
  5299. ControllingClient.SendAlertMessage("Can't teleport closer to destination");
  5300. return false;
  5301. }
  5302. else
  5303. {
  5304. pos = spawnPos;
  5305. return true;
  5306. }
  5307. }
  5308. }
  5309. ILandObject land = m_scene.LandChannel.GetLandObject(pos.X, pos.Y);
  5310. if (land.LandData.LandingType != (byte)LandingType.LandingPoint
  5311. || land.LandData.OwnerID == m_uuid)
  5312. return true;
  5313. Vector3 landLocation = land.LandData.UserLocation;
  5314. if(landLocation == Vector3.Zero)
  5315. return true;
  5316. if (currDistanceSQ < Vector3.DistanceSquared(landLocation, pos))
  5317. {
  5318. ControllingClient.SendAlertMessage("Can't teleport closer to destination");
  5319. return false;
  5320. }
  5321. pos = land.LandData.UserLocation;
  5322. return true;
  5323. }
  5324. const TeleportFlags TeleHubTPFlags = TeleportFlags.ViaLogin
  5325. | TeleportFlags.ViaHGLogin | TeleportFlags.ViaLocation;
  5326. private bool CheckAndAdjustTelehub(SceneObjectGroup telehub, ref Vector3 pos, ref bool positionChanged)
  5327. {
  5328. // forcing telehubs on any tp that reachs this
  5329. if ((m_teleportFlags & TeleHubTPFlags) != 0 ||
  5330. (m_scene.TelehubAllowLandmarks == true ? false : ((m_teleportFlags & TeleportFlags.ViaLandmark) != 0 )))
  5331. {
  5332. ILandObject land;
  5333. Vector3 teleHubPosition = telehub.AbsolutePosition;
  5334. SpawnPoint[] spawnPoints = m_scene.RegionInfo.RegionSettings.SpawnPoints().ToArray();
  5335. if(spawnPoints.Length == 0)
  5336. {
  5337. land = m_scene.LandChannel.GetLandObject(teleHubPosition.X,teleHubPosition.Y);
  5338. if(land != null)
  5339. {
  5340. pos = teleHubPosition;
  5341. if(land.IsEitherBannedOrRestricted(UUID))
  5342. return false;
  5343. positionChanged = true;
  5344. return true;
  5345. }
  5346. else
  5347. return false;
  5348. }
  5349. int index;
  5350. int tries;
  5351. bool selected = false;
  5352. bool validhub = false;
  5353. Vector3 spawnPosition;
  5354. Quaternion teleHubRotation = telehub.GroupRotation;
  5355. switch(m_scene.SpawnPointRouting)
  5356. {
  5357. case "random":
  5358. tries = spawnPoints.Length;
  5359. if(tries < 3) // no much sense in random with a few points when there same can have bans
  5360. goto case "sequence";
  5361. do
  5362. {
  5363. index = Util.RandomClass.Next(spawnPoints.Length - 1);
  5364. spawnPosition = spawnPoints[index].GetLocation(teleHubPosition, teleHubRotation);
  5365. land = m_scene.LandChannel.GetLandObject(spawnPosition.X,spawnPosition.Y);
  5366. if(land != null && !land.IsEitherBannedOrRestricted(UUID))
  5367. selected = true;
  5368. } while(selected == false && --tries > 0 );
  5369. if(tries <= 0)
  5370. goto case "sequence";
  5371. pos = spawnPosition;
  5372. return true;
  5373. case "sequence":
  5374. tries = spawnPoints.Length;
  5375. selected = false;
  5376. validhub = false;
  5377. do
  5378. {
  5379. index = m_scene.SpawnPoint();
  5380. spawnPosition = spawnPoints[index].GetLocation(teleHubPosition, teleHubRotation);
  5381. land = m_scene.LandChannel.GetLandObject(spawnPosition.X,spawnPosition.Y);
  5382. if(land != null)
  5383. {
  5384. validhub = true;
  5385. if(land.IsEitherBannedOrRestricted(UUID))
  5386. selected = false;
  5387. else
  5388. selected = true;
  5389. }
  5390. } while(selected == false && --tries > 0);
  5391. if(!validhub)
  5392. return false;
  5393. pos = spawnPosition;
  5394. if(!selected)
  5395. return false;
  5396. positionChanged = true;
  5397. return true;
  5398. default:
  5399. case "closest":
  5400. float distancesq = float.MaxValue;
  5401. int closest = -1;
  5402. validhub = false;
  5403. for(int i = 0; i < spawnPoints.Length; i++)
  5404. {
  5405. spawnPosition = spawnPoints[i].GetLocation(teleHubPosition, teleHubRotation);
  5406. Vector3 offset = spawnPosition - pos;
  5407. float dsq = offset.LengthSquared();
  5408. land = m_scene.LandChannel.GetLandObject(spawnPosition.X,spawnPosition.Y);
  5409. if(land == null)
  5410. continue;
  5411. validhub = true;
  5412. if(land.IsEitherBannedOrRestricted(UUID))
  5413. continue;
  5414. if(dsq >= distancesq)
  5415. continue;
  5416. distancesq = dsq;
  5417. closest = i;
  5418. }
  5419. if(!validhub)
  5420. return false;
  5421. if(closest < 0)
  5422. {
  5423. pos = spawnPoints[0].GetLocation(teleHubPosition, teleHubRotation);
  5424. positionChanged = true;
  5425. return false;
  5426. }
  5427. pos = spawnPoints[closest].GetLocation(teleHubPosition, teleHubRotation);
  5428. positionChanged = true;
  5429. return true;
  5430. }
  5431. }
  5432. return false;
  5433. }
  5434. const TeleportFlags adicionalLandPointFlags = TeleportFlags.ViaLandmark |
  5435. TeleportFlags.ViaLocation | TeleportFlags.ViaHGLogin;
  5436. // Modify landing point based on possible banning, telehubs or parcel restrictions.
  5437. // This is the behavior in OpenSim for a very long time, different from SL
  5438. private bool CheckAndAdjustLandingPoint_OS(ref Vector3 pos, ref Vector3 lookat, ref bool positionChanged)
  5439. {
  5440. // Honor bans
  5441. if (!m_scene.TestLandRestrictions(UUID, out string reason, ref pos.X, ref pos.Y))
  5442. return false;
  5443. SceneObjectGroup telehub = null;
  5444. if (m_scene.RegionInfo.RegionSettings.TelehubObject != UUID.Zero && (telehub = m_scene.GetSceneObjectGroup(m_scene.RegionInfo.RegionSettings.TelehubObject)) != null)
  5445. {
  5446. if (!m_scene.RegionInfo.EstateSettings.AllowDirectTeleport)
  5447. {
  5448. CheckAndAdjustTelehub(telehub, ref pos, ref positionChanged);
  5449. return true;
  5450. }
  5451. }
  5452. ILandObject land = m_scene.LandChannel.GetLandObject(pos.X, pos.Y);
  5453. if (land != null)
  5454. {
  5455. if (Scene.DebugTeleporting)
  5456. TeleportFlagsDebug();
  5457. // If we come in via login, landmark or map, we want to
  5458. // honor landing points. If we come in via Lure, we want
  5459. // to ignore them.
  5460. if ((m_teleportFlags & (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID)) ==
  5461. (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID) ||
  5462. (m_teleportFlags & adicionalLandPointFlags) != 0)
  5463. {
  5464. // Don't restrict gods, estate managers, or land owners to
  5465. // the TP point. This behaviour mimics agni.
  5466. if (land.LandData.LandingType == (byte)LandingType.LandingPoint &&
  5467. land.LandData.UserLocation != Vector3.Zero &&
  5468. !IsViewerUIGod &&
  5469. ((land.LandData.OwnerID != m_uuid &&
  5470. !m_scene.Permissions.IsGod(m_uuid) &&
  5471. !m_scene.RegionInfo.EstateSettings.IsEstateManagerOrOwner(m_uuid)) ||
  5472. (m_teleportFlags & TeleportFlags.ViaLocation) != 0 ||
  5473. (m_teleportFlags & Constants.TeleportFlags.ViaHGLogin) != 0))
  5474. {
  5475. pos = land.LandData.UserLocation;
  5476. positionChanged = true;
  5477. }
  5478. }
  5479. }
  5480. return true;
  5481. }
  5482. // Modify landing point based on telehubs or parcel restrictions.
  5483. // This is a behavior coming from AVN, somewhat mimicking SL
  5484. private bool CheckAndAdjustLandingPoint_SL(ref Vector3 pos, ref Vector3 lookat, ref bool positionChanged)
  5485. {
  5486. // dont mess with gods
  5487. if(IsGod)
  5488. return true;
  5489. // respect region owner and managers
  5490. // if(m_scene.RegionInfo.EstateSettings.IsEstateManagerOrOwner(m_uuid))
  5491. // return true;
  5492. if (!m_scene.RegionInfo.EstateSettings.AllowDirectTeleport)
  5493. {
  5494. SceneObjectGroup telehub = null;
  5495. if (m_scene.RegionInfo.RegionSettings.TelehubObject != UUID.Zero && (telehub = m_scene.GetSceneObjectGroup(m_scene.RegionInfo.RegionSettings.TelehubObject)) != null)
  5496. {
  5497. if(CheckAndAdjustTelehub(telehub, ref pos, ref positionChanged))
  5498. return true;
  5499. }
  5500. }
  5501. // Honor bans, actually we don't honour them
  5502. if (!m_scene.TestLandRestrictions(UUID, out string reason, ref pos.X, ref pos.Y))
  5503. return false;
  5504. ILandObject land = m_scene.LandChannel.GetLandObject(pos.X, pos.Y);
  5505. if (land != null)
  5506. {
  5507. if (Scene.DebugTeleporting)
  5508. TeleportFlagsDebug();
  5509. // If we come in via login, landmark or map, we want to
  5510. // honor landing points. If we come in via Lure, we want
  5511. // to ignore them.
  5512. if ((m_teleportFlags & (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID)) ==
  5513. (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID)
  5514. || (m_teleportFlags & adicionalLandPointFlags) != 0)
  5515. {
  5516. if (land.LandData.LandingType == (byte)LandingType.LandingPoint &&
  5517. land.LandData.UserLocation != Vector3.Zero )
  5518. // &&
  5519. // land.LandData.OwnerID != m_uuid )
  5520. {
  5521. pos = land.LandData.UserLocation;
  5522. if(land.LandData.UserLookAt != Vector3.Zero)
  5523. lookat = land.LandData.UserLookAt;
  5524. positionChanged = true;
  5525. }
  5526. }
  5527. }
  5528. return true;
  5529. }
  5530. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  5531. private DetectedObject CreateDetObject(SceneObjectPart obj)
  5532. {
  5533. return new DetectedObject()
  5534. {
  5535. keyUUID = obj.UUID,
  5536. nameStr = obj.Name,
  5537. ownerUUID = obj.OwnerID,
  5538. posVector = obj.AbsolutePosition,
  5539. rotQuat = obj.GetWorldRotation(),
  5540. velVector = obj.Velocity,
  5541. colliderType = 0,
  5542. groupUUID = obj.GroupID,
  5543. linkNumber = 0
  5544. };
  5545. }
  5546. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  5547. private DetectedObject CreateDetObject(ScenePresence av)
  5548. {
  5549. DetectedObject detobj = new DetectedObject()
  5550. {
  5551. keyUUID = av.UUID,
  5552. nameStr = av.ControllingClient.Name,
  5553. ownerUUID = av.UUID,
  5554. posVector = av.AbsolutePosition,
  5555. rotQuat = av.Rotation,
  5556. velVector = av.Velocity,
  5557. colliderType = av.IsNPC ? 0x20 : 0x1, // OpenSim\Region\ScriptEngine\Shared\Helpers.cs
  5558. groupUUID = av.ControllingClient.ActiveGroupId,
  5559. linkNumber = 0
  5560. };
  5561. if (av.IsSatOnObject)
  5562. detobj.colliderType |= 0x4; //passive
  5563. else if (detobj.velVector != Vector3.Zero)
  5564. detobj.colliderType |= 0x2; //active
  5565. return detobj;
  5566. }
  5567. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  5568. private DetectedObject CreateDetObjectForGround()
  5569. {
  5570. DetectedObject detobj = new DetectedObject()
  5571. {
  5572. keyUUID = UUID.Zero,
  5573. nameStr = "",
  5574. ownerUUID = UUID.Zero,
  5575. posVector = AbsolutePosition,
  5576. rotQuat = Quaternion.Identity,
  5577. velVector = Vector3.Zero,
  5578. colliderType = 0,
  5579. groupUUID = UUID.Zero,
  5580. linkNumber = 0
  5581. };
  5582. return detobj;
  5583. }
  5584. private ColliderArgs CreateColliderArgs(SceneObjectPart dest, List<uint> colliders)
  5585. {
  5586. ColliderArgs colliderArgs = new ColliderArgs();
  5587. List<DetectedObject> colliding = new List<DetectedObject>();
  5588. foreach (uint localId in colliders)
  5589. {
  5590. if (localId == 0)
  5591. continue;
  5592. SceneObjectPart obj = m_scene.GetSceneObjectPart(localId);
  5593. if (obj != null)
  5594. {
  5595. if (!dest.CollisionFilteredOut(obj.UUID, obj.Name))
  5596. colliding.Add(CreateDetObject(obj));
  5597. }
  5598. else
  5599. {
  5600. ScenePresence av = m_scene.GetScenePresence(localId);
  5601. if (av != null && (!av.IsChildAgent))
  5602. {
  5603. if (!dest.CollisionFilteredOut(av.UUID, av.Name))
  5604. colliding.Add(CreateDetObject(av));
  5605. }
  5606. }
  5607. }
  5608. colliderArgs.Colliders = colliding;
  5609. return colliderArgs;
  5610. }
  5611. private delegate void ScriptCollidingNotification(uint localID, ColliderArgs message);
  5612. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  5613. private void SendCollisionEvent(SceneObjectGroup dest, scriptEvents ev, List<uint> colliders, ScriptCollidingNotification notify)
  5614. {
  5615. if (colliders.Count > 0)
  5616. {
  5617. if ((dest.RootPart.ScriptEvents & ev) != 0)
  5618. {
  5619. ColliderArgs CollidingMessage = CreateColliderArgs(dest.RootPart, colliders);
  5620. if (CollidingMessage.Colliders.Count > 0)
  5621. notify(dest.RootPart.LocalId, CollidingMessage);
  5622. }
  5623. }
  5624. }
  5625. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  5626. private void SendLandCollisionEvent(SceneObjectGroup dest, scriptEvents ev, ScriptCollidingNotification notify)
  5627. {
  5628. if ((dest.RootPart.ScriptEvents & ev) != 0)
  5629. {
  5630. ColliderArgs LandCollidingMessage = new ColliderArgs();
  5631. List<DetectedObject> colliding = new List<DetectedObject>(){CreateDetObjectForGround()};
  5632. LandCollidingMessage.Colliders = colliding;
  5633. notify(dest.RootPart.LocalId, LandCollidingMessage);
  5634. }
  5635. }
  5636. private void RaiseCollisionScriptEvents(Dictionary<uint, ContactPoint> coldata)
  5637. {
  5638. int nattachments = m_attachments.Count;
  5639. if (!ParcelAllowThisAvatarSounds && nattachments == 0)
  5640. return;
  5641. try
  5642. {
  5643. List<SceneObjectGroup> attachements;
  5644. int numberCollisions = coldata.Count;
  5645. if (numberCollisions == 0)
  5646. {
  5647. if (m_lastColliders.Count == 0 && !m_lastLandCollide)
  5648. return; // nothing to do
  5649. if(m_attachments.Count > 0)
  5650. {
  5651. attachements = GetAttachments();
  5652. for (int j = 0; j < attachements.Count; ++j)
  5653. {
  5654. SceneObjectGroup att = attachements[j];
  5655. scriptEvents attev = att.RootPart.ScriptEvents;
  5656. if (m_lastLandCollide && (attev & scriptEvents.land_collision_end) != 0)
  5657. SendLandCollisionEvent(att, scriptEvents.land_collision_end, m_scene.EventManager.TriggerScriptLandCollidingEnd);
  5658. if ((attev & scriptEvents.collision_end) != 0)
  5659. SendCollisionEvent(att, scriptEvents.collision_end, m_lastColliders, m_scene.EventManager.TriggerScriptCollidingEnd);
  5660. }
  5661. }
  5662. m_lastLandCollide = false;
  5663. m_lastColliders.Clear();
  5664. return;
  5665. }
  5666. bool thisHitLand = false;
  5667. bool startLand = false;
  5668. List<uint> thisHitColliders = new List<uint>(numberCollisions);
  5669. List<uint> endedColliders = new List<uint>(m_lastColliders.Count);
  5670. List<uint> startedColliders = new List<uint>(numberCollisions);
  5671. if(ParcelAllowThisAvatarSounds)
  5672. {
  5673. List<CollisionForSoundInfo> soundinfolist = new List<CollisionForSoundInfo>();
  5674. CollisionForSoundInfo soundinfo;
  5675. ContactPoint curcontact;
  5676. foreach (uint id in coldata.Keys)
  5677. {
  5678. if(id == 0)
  5679. {
  5680. thisHitLand = true;
  5681. startLand = !m_lastLandCollide;
  5682. if (startLand)
  5683. {
  5684. startLand = true;
  5685. curcontact = coldata[id];
  5686. if (Math.Abs(curcontact.RelativeSpeed) > 0.2)
  5687. {
  5688. soundinfo = new CollisionForSoundInfo()
  5689. {
  5690. colliderID = id,
  5691. position = curcontact.Position,
  5692. relativeVel = curcontact.RelativeSpeed
  5693. };
  5694. soundinfolist.Add(soundinfo);
  5695. }
  5696. }
  5697. }
  5698. else
  5699. {
  5700. thisHitColliders.Add(id);
  5701. if (!m_lastColliders.Contains(id))
  5702. {
  5703. startedColliders.Add(id);
  5704. curcontact = coldata[id];
  5705. if (Math.Abs(curcontact.RelativeSpeed) > 0.2)
  5706. {
  5707. soundinfo = new CollisionForSoundInfo()
  5708. {
  5709. colliderID = id,
  5710. position = curcontact.Position,
  5711. relativeVel = curcontact.RelativeSpeed
  5712. };
  5713. soundinfolist.Add(soundinfo);
  5714. }
  5715. }
  5716. }
  5717. }
  5718. if (soundinfolist.Count > 0)
  5719. CollisionSounds.AvatarCollisionSound(this, soundinfolist);
  5720. }
  5721. else
  5722. {
  5723. foreach (uint id in coldata.Keys)
  5724. {
  5725. if (id == 0)
  5726. {
  5727. thisHitLand = true;
  5728. startLand = !m_lastLandCollide;
  5729. }
  5730. else
  5731. {
  5732. thisHitColliders.Add(id);
  5733. if (!m_lastColliders.Contains(id))
  5734. startedColliders.Add(id);
  5735. }
  5736. }
  5737. }
  5738. // calculate things that ended colliding
  5739. foreach (uint localID in m_lastColliders)
  5740. {
  5741. if (!thisHitColliders.Contains(localID))
  5742. {
  5743. endedColliders.Add(localID);
  5744. }
  5745. }
  5746. attachements = GetAttachments();
  5747. for (int i = 0; i < attachements.Count; ++i)
  5748. {
  5749. SceneObjectGroup att = attachements[i];
  5750. scriptEvents attev = att.RootPart.ScriptEvents;
  5751. if ((attev & scriptEvents.anyobjcollision) != 0)
  5752. {
  5753. SendCollisionEvent(att, scriptEvents.collision_start, startedColliders, m_scene.EventManager.TriggerScriptCollidingStart);
  5754. SendCollisionEvent(att, scriptEvents.collision , m_lastColliders , m_scene.EventManager.TriggerScriptColliding);
  5755. SendCollisionEvent(att, scriptEvents.collision_end , endedColliders , m_scene.EventManager.TriggerScriptCollidingEnd);
  5756. }
  5757. if ((attev & scriptEvents.anylandcollision) != 0)
  5758. {
  5759. if (thisHitLand)
  5760. {
  5761. if (startLand)
  5762. SendLandCollisionEvent(att, scriptEvents.land_collision_start, m_scene.EventManager.TriggerScriptLandCollidingStart);
  5763. SendLandCollisionEvent(att, scriptEvents.land_collision, m_scene.EventManager.TriggerScriptLandColliding);
  5764. }
  5765. else if (m_lastLandCollide)
  5766. SendLandCollisionEvent(att, scriptEvents.land_collision_end, m_scene.EventManager.TriggerScriptLandCollidingEnd);
  5767. }
  5768. }
  5769. m_lastLandCollide = thisHitLand;
  5770. m_lastColliders = thisHitColliders;
  5771. }
  5772. catch { }
  5773. }
  5774. private void TeleportFlagsDebug() {
  5775. // Some temporary debugging help to show all the TeleportFlags we have...
  5776. bool HG = false;
  5777. if((m_teleportFlags & TeleportFlags.ViaHGLogin) == TeleportFlags.ViaHGLogin)
  5778. HG = true;
  5779. m_log.InfoFormat("[SCENE PRESENCE]: TELEPORT ******************");
  5780. uint i = 0u;
  5781. for (int x = 0; x <= 30 ; x++, i = 1u << x)
  5782. {
  5783. i = 1u << x;
  5784. if((m_teleportFlags & (TeleportFlags)i) == (TeleportFlags)i)
  5785. if (HG == false)
  5786. m_log.InfoFormat("[SCENE PRESENCE]: Teleport Flags include {0}", ((TeleportFlags) i).ToString());
  5787. else
  5788. m_log.InfoFormat("[SCENE PRESENCE]: HG Teleport Flags include {0}", ((TeleportFlags)i).ToString());
  5789. }
  5790. m_log.InfoFormat("[SCENE PRESENCE]: TELEPORT ******************");
  5791. }
  5792. private void parcelGodCheck(UUID currentParcelID)
  5793. {
  5794. List<ScenePresence> allpresences = m_scene.GetScenePresences();
  5795. foreach (ScenePresence p in allpresences)
  5796. {
  5797. if (p.IsDeleted || p.IsChildAgent || p == this || p.ControllingClient == null || !p.ControllingClient.IsActive)
  5798. continue;
  5799. if (p.ParcelHideThisAvatar && p.currentParcelUUID != currentParcelID)
  5800. {
  5801. if (IsViewerUIGod)
  5802. p.SendViewTo(this);
  5803. else
  5804. p.SendKillTo(this);
  5805. }
  5806. }
  5807. }
  5808. private void ParcelCrossCheck(UUID currentParcelID,UUID previusParcelID,
  5809. bool currentParcelHide, bool previusParcelHide, bool oldhide, bool check)
  5810. {
  5811. List<ScenePresence> killsToSendto = new List<ScenePresence>();
  5812. List<ScenePresence> killsToSendme = new List<ScenePresence>();
  5813. List<ScenePresence> viewsToSendto = new List<ScenePresence>();
  5814. List<ScenePresence> viewsToSendme = new List<ScenePresence>();
  5815. List<ScenePresence> allpresences = null;
  5816. if (IsInTransit || IsChildAgent)
  5817. return;
  5818. if (check)
  5819. {
  5820. // check is relative to current parcel only
  5821. if (oldhide == currentParcelHide)
  5822. return;
  5823. allpresences = m_scene.GetScenePresences();
  5824. if (oldhide)
  5825. { // where private
  5826. foreach (ScenePresence p in allpresences)
  5827. {
  5828. if (p.IsDeleted || p == this || p.ControllingClient == null || !p.ControllingClient.IsActive)
  5829. continue;
  5830. // those on not on parcel see me
  5831. if (currentParcelID != p.currentParcelUUID)
  5832. {
  5833. viewsToSendto.Add(p); // they see me
  5834. }
  5835. }
  5836. } // where private end
  5837. else
  5838. { // where public
  5839. foreach (ScenePresence p in allpresences)
  5840. {
  5841. if (p.IsDeleted || p == this || p.ControllingClient == null || !p.ControllingClient.IsActive)
  5842. continue;
  5843. // those not on parcel dont see me
  5844. if (currentParcelID != p.currentParcelUUID && !p.IsViewerUIGod)
  5845. {
  5846. killsToSendto.Add(p); // they dont see me
  5847. }
  5848. }
  5849. } // where public end
  5850. allpresences.Clear();
  5851. }
  5852. else
  5853. {
  5854. if (currentParcelHide)
  5855. {
  5856. // now on a private parcel
  5857. allpresences = m_scene.GetScenePresences();
  5858. if (previusParcelHide && previusParcelID != UUID.Zero)
  5859. {
  5860. foreach (ScenePresence p in allpresences)
  5861. {
  5862. if (p.IsDeleted || p == this || p.ControllingClient == null || !p.ControllingClient.IsActive)
  5863. continue;
  5864. // only those on previous parcel need receive kills
  5865. if (previusParcelID == p.currentParcelUUID)
  5866. {
  5867. if(!p.IsViewerUIGod)
  5868. killsToSendto.Add(p); // they dont see me
  5869. if(!IsViewerUIGod)
  5870. killsToSendme.Add(p); // i dont see them
  5871. }
  5872. // only those on new parcel need see
  5873. if (currentParcelID == p.currentParcelUUID)
  5874. {
  5875. viewsToSendto.Add(p); // they see me
  5876. viewsToSendme.Add(p); // i see them
  5877. }
  5878. }
  5879. }
  5880. else
  5881. {
  5882. //was on a public area
  5883. allpresences = m_scene.GetScenePresences();
  5884. foreach (ScenePresence p in allpresences)
  5885. {
  5886. if (p.IsDeleted || p == this || p.ControllingClient == null || !p.ControllingClient.IsActive)
  5887. continue;
  5888. // those not on new parcel dont see me
  5889. if (currentParcelID != p.currentParcelUUID && !p.IsViewerUIGod)
  5890. {
  5891. killsToSendto.Add(p); // they dont see me
  5892. }
  5893. else
  5894. {
  5895. viewsToSendme.Add(p); // i see those on it
  5896. }
  5897. }
  5898. }
  5899. allpresences.Clear();
  5900. } // now on a private parcel end
  5901. else
  5902. {
  5903. // now on public parcel
  5904. if (previusParcelHide && previusParcelID != UUID.Zero)
  5905. {
  5906. // was on private area
  5907. allpresences = m_scene.GetScenePresences();
  5908. foreach (ScenePresence p in allpresences)
  5909. {
  5910. if (p.IsDeleted || p == this || p.ControllingClient == null || !p.ControllingClient.IsActive)
  5911. continue;
  5912. // only those old parcel need kills
  5913. if (previusParcelID == p.currentParcelUUID && !IsViewerUIGod)
  5914. {
  5915. killsToSendme.Add(p); // i dont see them
  5916. }
  5917. else
  5918. {
  5919. viewsToSendto.Add(p); // they see me
  5920. }
  5921. }
  5922. }
  5923. else
  5924. return; // was on a public area also
  5925. } // now on public parcel end
  5926. }
  5927. // send the things
  5928. if (killsToSendto.Count > 0)
  5929. {
  5930. foreach (ScenePresence p in killsToSendto)
  5931. {
  5932. // m_log.Debug("[AVATAR]: killTo: " + Lastname + " " + p.Lastname);
  5933. SendKillTo(p);
  5934. }
  5935. }
  5936. if (killsToSendme.Count > 0)
  5937. {
  5938. foreach (ScenePresence p in killsToSendme)
  5939. {
  5940. // m_log.Debug("[AVATAR]: killToMe: " + Lastname + " " + p.Lastname);
  5941. p.SendKillTo(this);
  5942. }
  5943. }
  5944. if (viewsToSendto.Count > 0)
  5945. {
  5946. foreach (ScenePresence p in viewsToSendto)
  5947. {
  5948. SendViewTo(p);
  5949. }
  5950. }
  5951. if (viewsToSendme.Count > 0 )
  5952. {
  5953. foreach (ScenePresence p in viewsToSendme)
  5954. {
  5955. if (p.IsChildAgent)
  5956. continue;
  5957. // m_log.Debug("[AVATAR]: viewMe: " + Lastname + "<-" + p.Lastname);
  5958. p.SendViewTo(this);
  5959. }
  5960. }
  5961. }
  5962. public void HasMovedAway(bool nearRegion)
  5963. {
  5964. if (nearRegion)
  5965. {
  5966. if (Scene.AttachmentsModule != null)
  5967. Scene.AttachmentsModule.DeleteAttachmentsFromScene(this, true);
  5968. if (!ParcelHideThisAvatar || IsViewerUIGod)
  5969. return;
  5970. List<ScenePresence> allpresences = m_scene.GetScenePresences();
  5971. foreach (ScenePresence p in allpresences)
  5972. {
  5973. if (p.IsDeleted || p == this || p.IsChildAgent || p.ControllingClient == null || !p.ControllingClient.IsActive)
  5974. continue;
  5975. if (p.currentParcelUUID == m_currentParcelUUID)
  5976. {
  5977. p.SendKillTo(this);
  5978. }
  5979. }
  5980. }
  5981. else
  5982. {
  5983. lock (m_completeMovementLock)
  5984. {
  5985. GodController.HasMovedAway();
  5986. NeedInitialData = -1;
  5987. m_gotRegionHandShake = false;
  5988. }
  5989. List<ScenePresence> allpresences = m_scene.GetScenePresences();
  5990. foreach (ScenePresence p in allpresences)
  5991. {
  5992. if (p == this)
  5993. continue;
  5994. SendKillTo(p);
  5995. if (!p.IsChildAgent)
  5996. p.SendKillTo(this);
  5997. }
  5998. if (Scene.AttachmentsModule != null)
  5999. Scene.AttachmentsModule.DeleteAttachmentsFromScene(this, true);
  6000. }
  6001. }
  6002. // kill with attachs root kills
  6003. public void SendKillTo(ScenePresence p)
  6004. {
  6005. List<uint> ids = new List<uint>(m_attachments.Count + 1);
  6006. foreach (SceneObjectGroup sog in m_attachments)
  6007. {
  6008. ids.Add(sog.RootPart.LocalId);
  6009. }
  6010. ids.Add(LocalId);
  6011. p.ControllingClient.SendKillObject(ids);
  6012. }
  6013. /*
  6014. // kill with hack
  6015. public void SendKillTo(ScenePresence p)
  6016. {
  6017. foreach (SceneObjectGroup sog in m_attachments)
  6018. p.ControllingClient.SendPartFullUpdate(sog.RootPart, LocalId + 1);
  6019. p.ControllingClient.SendKillObject(new List<uint> { LocalId });
  6020. }
  6021. */
  6022. public void SendViewTo(ScenePresence p)
  6023. {
  6024. SendAvatarDataToAgentNF(p);
  6025. SendAppearanceToAgent(p);
  6026. if (Animator != null)
  6027. Animator.SendAnimPackToClient(p.ControllingClient);
  6028. SendAttachmentsToAgentNF(p);
  6029. }
  6030. public void SetAnimationOverride(string animState, UUID animID)
  6031. {
  6032. Overrides.SetOverride(animState, animID);
  6033. // Animator.SendAnimPack();
  6034. Animator.ForceUpdateMovementAnimations();
  6035. }
  6036. public UUID GetAnimationOverride(string animState)
  6037. {
  6038. return Overrides.GetOverriddenAnimation(animState);
  6039. }
  6040. // http caps assets bandwidth control
  6041. private int m_capbandwidth = -1;
  6042. private int m_bandwidth = 100000;
  6043. private int m_bandwidthBurst = 20000;
  6044. private int m_bytesControl;
  6045. private double m_lastBandwithTime;
  6046. private readonly object m_throttleLock = new object();
  6047. public bool CapCanSendAsset(int type, int size)
  6048. {
  6049. if(size == 0)
  6050. return true;
  6051. lock (m_throttleLock)
  6052. {
  6053. if (type > 1)
  6054. {
  6055. // not texture or mesh
  6056. m_bytesControl -= size;
  6057. return true;
  6058. }
  6059. double currenttime = Util.GetTimeStamp();
  6060. double timeElapsed = currenttime - m_lastBandwithTime;
  6061. if (timeElapsed > .02)
  6062. {
  6063. m_lastBandwithTime = currenttime;
  6064. int add = (int)(m_bandwidth * timeElapsed);
  6065. m_bytesControl += add;
  6066. if (m_bytesControl > m_bandwidthBurst)
  6067. m_bytesControl = m_bandwidthBurst;
  6068. }
  6069. if (m_bytesControl > 0 )
  6070. {
  6071. m_bytesControl -= size;
  6072. return true;
  6073. }
  6074. }
  6075. return false;
  6076. }
  6077. }
  6078. }