ScenePresence.cs 265 KB

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