ScenePresence.cs 264 KB

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