ScenePresence.cs 264 KB

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