Scene.cs 260 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454
  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.Collections.Generic;
  29. using System.Diagnostics;
  30. using System.Drawing;
  31. using System.Drawing.Imaging;
  32. using System.IO;
  33. using System.Text;
  34. using System.Threading;
  35. using System.Timers;
  36. using System.Xml;
  37. using Nini.Config;
  38. using OpenMetaverse;
  39. using OpenMetaverse.Packets;
  40. using OpenMetaverse.Imaging;
  41. using OpenMetaverse.StructuredData;
  42. using OpenSim.Framework;
  43. using OpenSim.Framework.Monitoring;
  44. using OpenSim.Services.Interfaces;
  45. using OpenSim.Framework.Console;
  46. using OpenSim.Region.Framework.Interfaces;
  47. using OpenSim.Region.Framework.Scenes.Scripting;
  48. using OpenSim.Region.Framework.Scenes.Serialization;
  49. using OpenSim.Region.PhysicsModules.SharedBase;
  50. using Timer = System.Timers.Timer;
  51. using TPFlags = OpenSim.Framework.Constants.TeleportFlags;
  52. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  53. using PermissionMask = OpenSim.Framework.PermissionMask;
  54. namespace OpenSim.Region.Framework.Scenes
  55. {
  56. public delegate bool FilterAvatarList(ScenePresence avatar);
  57. public partial class Scene : SceneBase
  58. {
  59. private const long DEFAULT_MIN_TIME_FOR_PERSISTENCE = 60L;
  60. private const long DEFAULT_MAX_TIME_FOR_PERSISTENCE = 600L;
  61. public delegate void SynchronizeSceneHandler(Scene scene);
  62. #region Fields
  63. /// <summary>
  64. /// Show debug information about animations.
  65. /// </summary>
  66. public bool DebugAnimations { get; set; }
  67. /// <summary>
  68. /// Show debug information about teleports.
  69. /// </summary>
  70. public bool DebugTeleporting { get; set; }
  71. /// <summary>
  72. /// Show debug information about the scene loop.
  73. /// </summary>
  74. public bool DebugUpdates { get; set; }
  75. /// <summary>
  76. /// If true then the scene is saved to persistent storage periodically, every m_update_backup frames and
  77. /// if objects meet required conditions (m_dontPersistBefore and m_dontPersistAfter).
  78. /// </summary>
  79. /// <remarks>
  80. /// Even if false, the scene will still be saved on clean shutdown.
  81. /// FIXME: Currently, setting this to false will mean that objects are not periodically returned from parcels.
  82. /// This needs to be fixed.
  83. /// </remarks>
  84. public bool PeriodicBackup { get; set; }
  85. /// <summary>
  86. /// If false then the scene is never saved to persistence storage even if PeriodicBackup == true and even
  87. /// if the scene is being shut down for the final time.
  88. /// </summary>
  89. public bool UseBackup { get; set; }
  90. /// <summary>
  91. /// If false then physical objects are disabled, though collisions will continue as normal.
  92. /// </summary>
  93. public bool PhysicsEnabled
  94. {
  95. get
  96. {
  97. return m_physicsEnabled;
  98. }
  99. set
  100. {
  101. m_physicsEnabled = value;
  102. if (PhysicsScene != null)
  103. {
  104. IPhysicsParameters physScene = PhysicsScene as IPhysicsParameters;
  105. if (physScene != null)
  106. physScene.SetPhysicsParameter(
  107. "Active", m_physicsEnabled.ToString(), PhysParameterEntry.APPLY_TO_NONE);
  108. }
  109. }
  110. }
  111. private bool m_physicsEnabled;
  112. /// <summary>
  113. /// If false then scripts are not enabled on the smiulator
  114. /// </summary>
  115. public bool ScriptsEnabled
  116. {
  117. get { return m_scripts_enabled; }
  118. set
  119. {
  120. if (m_scripts_enabled != value)
  121. {
  122. if (!value)
  123. {
  124. m_log.Info("Stopping all Scripts in Scene");
  125. EntityBase[] entities = Entities.GetEntities();
  126. foreach (EntityBase ent in entities)
  127. {
  128. if (ent is SceneObjectGroup)
  129. ((SceneObjectGroup)ent).RemoveScriptInstances(false);
  130. }
  131. }
  132. else
  133. {
  134. m_log.Info("Starting all Scripts in Scene");
  135. EntityBase[] entities = Entities.GetEntities();
  136. foreach (EntityBase ent in entities)
  137. {
  138. if (ent is SceneObjectGroup)
  139. {
  140. SceneObjectGroup sog = (SceneObjectGroup)ent;
  141. sog.CreateScriptInstances(0, false, DefaultScriptEngine, 0);
  142. sog.ResumeScripts();
  143. }
  144. }
  145. }
  146. m_scripts_enabled = value;
  147. }
  148. }
  149. }
  150. private bool m_scripts_enabled;
  151. public bool ClampNegativeZ
  152. {
  153. get { return m_clampNegativeZ; }
  154. }
  155. private bool m_clampNegativeZ = false;
  156. /// <summary>
  157. /// Used to prevent simultaneous calls to code that adds and removes agents.
  158. /// </summary>
  159. private object m_removeClientLock = new object();
  160. /// <summary>
  161. /// Statistical information for this scene.
  162. /// </summary>
  163. public SimStatsReporter StatsReporter { get; private set; }
  164. /// <summary>
  165. /// Controls whether physics can be applied to prims. Even if false, prims still have entries in a
  166. /// PhysicsScene in order to perform collision detection
  167. /// </summary>
  168. public bool PhysicalPrims { get; private set; }
  169. /// <summary>
  170. /// Controls whether prims can be collided with.
  171. /// </summary>
  172. /// <remarks>
  173. /// If this is set to false then prims cannot be subject to physics either.
  174. /// </summary>
  175. public bool CollidablePrims { get; private set; }
  176. /// <summary>
  177. /// Minimum value of the size of a non-physical prim in each axis
  178. /// </summary>
  179. public float m_minNonphys = 0.001f;
  180. /// <summary>
  181. /// Maximum value of the size of a non-physical prim in each axis
  182. /// </summary>
  183. public float m_maxNonphys = 256;
  184. /// <summary>
  185. /// Minimum value of the size of a physical prim in each axis
  186. /// </summary>
  187. public float m_minPhys = 0.01f;
  188. /// <summary>
  189. /// Maximum value of the size of a physical prim in each axis
  190. /// </summary>
  191. public float m_maxPhys = 10;
  192. /// <summary>
  193. /// Max prims an object will hold
  194. /// </summary>
  195. public int m_linksetCapacity = 0;
  196. public bool m_clampPrimSize;
  197. public bool m_trustBinaries;
  198. public bool m_allowScriptCrossings = true;
  199. /// <summary>
  200. /// use legacy sittarget offsets to avoid contents breaks
  201. /// to compensate for SL bug
  202. /// </summary>
  203. public bool LegacySitOffsets = true;
  204. /// <summary>
  205. /// Can avatars cross from and to this region?
  206. /// </summary>
  207. public bool AllowAvatarCrossing { get; set; }
  208. /// Max prims an Physical object will hold
  209. /// </summary>
  210. ///
  211. public int m_linksetPhysCapacity = 0;
  212. /// <summary>
  213. /// When placed outside the region's border, do we transfer the objects or
  214. /// do we keep simulating them here?
  215. /// </summary>
  216. public bool DisableObjectTransfer { get; set; }
  217. public bool m_useFlySlow;
  218. public bool m_useTrashOnDelete = true;
  219. protected float m_defaultDrawDistance = 255f;
  220. protected float m_defaultCullingDrawDistance = 16f;
  221. public float DefaultDrawDistance
  222. {
  223. get { return ObjectsCullingByDistance?m_defaultCullingDrawDistance:m_defaultDrawDistance; }
  224. }
  225. protected float m_maxDrawDistance = 512.0f;
  226. // protected float m_maxDrawDistance = 256.0f;
  227. public float MaxDrawDistance
  228. {
  229. get { return m_maxDrawDistance; }
  230. }
  231. protected float m_maxRegionViewDistance = 255f;
  232. public float MaxRegionViewDistance
  233. {
  234. get { return m_maxRegionViewDistance; }
  235. }
  236. protected float m_minRegionViewDistance = 96f;
  237. public float MinRegionViewDistance
  238. {
  239. get { return m_minRegionViewDistance; }
  240. }
  241. private List<string> m_AllowedViewers = new List<string>();
  242. private List<string> m_BannedViewers = new List<string>();
  243. // TODO: need to figure out how allow client agents but deny
  244. // root agents when ACL denies access to root agent
  245. public bool m_strictAccessControl = true;
  246. public bool m_seeIntoBannedRegion = false;
  247. public int MaxUndoCount = 5;
  248. public bool SeeIntoRegion { get; set; }
  249. // Using this for RegionReady module to prevent LoginsDisabled from changing under our feet;
  250. public bool LoginLock = false;
  251. public bool StartDisabled = false;
  252. public bool LoadingPrims;
  253. public IXfer XferManager;
  254. // the minimum time that must elapse before a changed object will be considered for persisted
  255. public long m_dontPersistBefore = DEFAULT_MIN_TIME_FOR_PERSISTENCE * 10000000L;
  256. // the maximum time that must elapse before a changed object will be considered for persisted
  257. public long m_persistAfter = DEFAULT_MAX_TIME_FOR_PERSISTENCE * 10000000L;
  258. protected int m_splitRegionID;
  259. protected Timer m_restartWaitTimer = new Timer();
  260. protected Timer m_timerWatchdog = new Timer();
  261. protected List<RegionInfo> m_regionRestartNotifyList = new List<RegionInfo>();
  262. protected List<RegionInfo> m_neighbours = new List<RegionInfo>();
  263. protected string m_simulatorVersion = "OpenSimulator Server";
  264. protected AgentCircuitManager m_authenticateHandler;
  265. protected SceneCommunicationService m_sceneGridService;
  266. protected ISnmpModule m_snmpService = null;
  267. protected ISimulationDataService m_SimulationDataService;
  268. protected IEstateDataService m_EstateDataService;
  269. protected IAssetService m_AssetService;
  270. protected IAuthorizationService m_AuthorizationService;
  271. protected IInventoryService m_InventoryService;
  272. protected IGridService m_GridService;
  273. protected ILibraryService m_LibraryService;
  274. protected ISimulationService m_simulationService;
  275. protected IAuthenticationService m_AuthenticationService;
  276. protected IPresenceService m_PresenceService;
  277. protected IUserAccountService m_UserAccountService;
  278. protected IAvatarService m_AvatarService;
  279. protected IGridUserService m_GridUserService;
  280. protected IAgentPreferencesService m_AgentPreferencesService;
  281. protected IXMLRPC m_xmlrpcModule;
  282. protected IWorldComm m_worldCommModule;
  283. protected IAvatarFactoryModule m_AvatarFactory;
  284. protected IConfigSource m_config;
  285. protected IRegionSerialiserModule m_serialiser;
  286. protected IDialogModule m_dialogModule;
  287. protected ICapabilitiesModule m_capsModule;
  288. protected IGroupsModule m_groupsModule;
  289. private Dictionary<string, string> m_extraSettings;
  290. /// <summary>
  291. /// Current scene frame number
  292. /// </summary>
  293. public uint Frame
  294. {
  295. get;
  296. protected set;
  297. }
  298. /// <summary>
  299. /// Frame time
  300. /// </remarks>
  301. public float FrameTime { get; private set; }
  302. public int FrameTimeWarnPercent { get; private set; }
  303. public int FrameTimeCritPercent { get; private set; }
  304. // Normalize the frame related stats to nominal 55fps for viewer and scripts option
  305. // see SimStatsReporter.cs
  306. public bool Normalized55FPS { get; private set; }
  307. private int m_update_physics = 1;
  308. private int m_update_entitymovement = 1;
  309. private int m_update_objects = 1;
  310. private int m_update_presences = 1; // Update scene presence movements
  311. private int m_update_events = 1;
  312. private int m_update_backup = 200;
  313. private int m_update_terrain = 1000;
  314. private int m_update_coarse_locations = 5;
  315. private int m_update_temp_cleaning = 180;
  316. private float agentMS;
  317. private float frameMS;
  318. private float physicsMS2;
  319. private float physicsMS;
  320. private float otherMS;
  321. private float tempOnRezMS;
  322. private float eventMS;
  323. private float backupMS;
  324. private float terrainMS;
  325. private float landMS;
  326. /// <summary>
  327. /// Tick at which the last frame was processed.
  328. /// </summary>
  329. private int m_lastFrameTick;
  330. /// <summary>
  331. /// Total script execution time (in Stopwatch Ticks) since the last frame
  332. /// </summary>
  333. private long m_scriptExecutionTime = 0;
  334. /// <summary>
  335. /// Signals whether temporary objects are currently being cleaned up. Needed because this is launched
  336. /// asynchronously from the update loop.
  337. /// </summary>
  338. private bool m_cleaningTemps = false;
  339. private bool m_sendingCoarseLocations = false; // same for async course locations sending
  340. /// <summary>
  341. /// Used to control main scene thread looping time when not updating via timer.
  342. /// </summary>
  343. private ManualResetEvent m_updateWaitEvent = new ManualResetEvent(false);
  344. // TODO: Possibly stop other classes being able to manipulate this directly.
  345. private SceneGraph m_sceneGraph;
  346. private readonly Timer m_restartTimer = new Timer(15000); // Wait before firing
  347. private volatile bool m_backingup;
  348. private Dictionary<UUID, ReturnInfo> m_returns = new Dictionary<UUID, ReturnInfo>();
  349. private Dictionary<UUID, int> m_groupsWithTargets = new Dictionary<UUID, int>();
  350. private string m_defaultScriptEngine;
  351. private int m_unixStartTime;
  352. public int UnixStartTime
  353. {
  354. get { return m_unixStartTime; }
  355. }
  356. /// <summary>
  357. /// Tick at which the last login occurred.
  358. /// </summary>
  359. private int m_LastLogin;
  360. private int m_lastIncoming;
  361. private int m_lastOutgoing;
  362. private int m_hbRestarts = 0;
  363. /// <summary>
  364. /// Thread that runs the scene loop.
  365. /// </summary>
  366. private Thread m_heartbeatThread;
  367. /// <summary>
  368. /// True if these scene is in the process of shutting down or is shutdown.
  369. /// </summary>
  370. public bool ShuttingDown
  371. {
  372. get { return m_shuttingDown; }
  373. }
  374. private volatile bool m_shuttingDown;
  375. /// <summary>
  376. /// Is the scene active?
  377. /// </summary>
  378. /// <remarks>
  379. /// If false, update loop is not being run, though after setting to false update may still
  380. /// be active for a period (and IsRunning will still be true). Updates can still be triggered manually if
  381. /// the scene is not active.
  382. /// </remarks>
  383. public bool Active
  384. {
  385. get { return m_active; }
  386. set
  387. {
  388. if (value)
  389. {
  390. if (!m_active)
  391. Start(false);
  392. }
  393. else
  394. {
  395. // This appears assymetric with Start() above but is not - setting m_active = false stops the loops
  396. // XXX: Possibly this should be in an explicit Stop() method for symmetry.
  397. m_active = false;
  398. }
  399. }
  400. }
  401. private volatile bool m_active;
  402. /// <summary>
  403. /// If true then updates are running. This may be true for a short period after a scene is de-activated.
  404. /// </summary>
  405. public bool IsRunning { get { return m_isRunning; } }
  406. private volatile bool m_isRunning;
  407. private bool m_firstHeartbeat = true;
  408. // private UpdatePrioritizationSchemes m_priorityScheme = UpdatePrioritizationSchemes.Time;
  409. // private bool m_reprioritizationEnabled = true;
  410. // private double m_reprioritizationInterval = 5000.0;
  411. // private double m_rootReprioritizationDistance = 10.0;
  412. // private double m_childReprioritizationDistance = 20.0;
  413. private Timer m_mapGenerationTimer = new Timer();
  414. private bool m_generateMaptiles;
  415. protected int m_lastHealth = -1;
  416. protected int m_lastUsers = -1;
  417. #endregion Fields
  418. #region Properties
  419. /* Used by the loadbalancer plugin on GForge */
  420. public int SplitRegionID
  421. {
  422. get { return m_splitRegionID; }
  423. set { m_splitRegionID = value; }
  424. }
  425. public new float TimeDilation
  426. {
  427. get { return m_sceneGraph.PhysicsScene.TimeDilation; }
  428. }
  429. public void setThreadCount(int inUseThreads)
  430. {
  431. // Just pass the thread count information on its way as the Scene
  432. // does not require the value for anything at this time
  433. StatsReporter.SetThreadCount(inUseThreads);
  434. }
  435. public SceneCommunicationService SceneGridService
  436. {
  437. get { return m_sceneGridService; }
  438. }
  439. public ISnmpModule SnmpService
  440. {
  441. get
  442. {
  443. if (m_snmpService == null)
  444. {
  445. m_snmpService = RequestModuleInterface<ISnmpModule>();
  446. }
  447. return m_snmpService;
  448. }
  449. }
  450. public ISimulationDataService SimulationDataService
  451. {
  452. get
  453. {
  454. if (m_SimulationDataService == null)
  455. {
  456. m_SimulationDataService = RequestModuleInterface<ISimulationDataService>();
  457. if (m_SimulationDataService == null)
  458. {
  459. throw new Exception("No ISimulationDataService available.");
  460. }
  461. }
  462. return m_SimulationDataService;
  463. }
  464. }
  465. public IEstateDataService EstateDataService
  466. {
  467. get
  468. {
  469. if (m_EstateDataService == null)
  470. {
  471. m_EstateDataService = RequestModuleInterface<IEstateDataService>();
  472. if (m_EstateDataService == null)
  473. {
  474. throw new Exception("No IEstateDataService available.");
  475. }
  476. }
  477. return m_EstateDataService;
  478. }
  479. }
  480. public IAssetService AssetService
  481. {
  482. get
  483. {
  484. if (m_AssetService == null)
  485. {
  486. m_AssetService = RequestModuleInterface<IAssetService>();
  487. if (m_AssetService == null)
  488. {
  489. throw new Exception("No IAssetService available.");
  490. }
  491. }
  492. return m_AssetService;
  493. }
  494. }
  495. public IAuthorizationService AuthorizationService
  496. {
  497. get
  498. {
  499. if (m_AuthorizationService == null)
  500. {
  501. m_AuthorizationService = RequestModuleInterface<IAuthorizationService>();
  502. //if (m_AuthorizationService == null)
  503. //{
  504. // // don't throw an exception if no authorization service is set for the time being
  505. // m_log.InfoFormat("[SCENE]: No Authorization service is configured");
  506. //}
  507. }
  508. return m_AuthorizationService;
  509. }
  510. }
  511. public IInventoryService InventoryService
  512. {
  513. get
  514. {
  515. if (m_InventoryService == null)
  516. {
  517. m_InventoryService = RequestModuleInterface<IInventoryService>();
  518. if (m_InventoryService == null)
  519. {
  520. throw new Exception("No IInventoryService available. This could happen if the config_include folder doesn't exist or if the OpenSim.ini [Architecture] section isn't set. Please also check that you have the correct version of your inventory service dll. Sometimes old versions of this dll will still exist. Do a clean checkout and re-create the opensim.ini from the opensim.ini.example.");
  521. }
  522. }
  523. return m_InventoryService;
  524. }
  525. }
  526. public IGridService GridService
  527. {
  528. get
  529. {
  530. if (m_GridService == null)
  531. {
  532. m_GridService = RequestModuleInterface<IGridService>();
  533. if (m_GridService == null)
  534. {
  535. throw new Exception("No IGridService available. This could happen if the config_include folder doesn't exist or if the OpenSim.ini [Architecture] section isn't set. Please also check that you have the correct version of your inventory service dll. Sometimes old versions of this dll will still exist. Do a clean checkout and re-create the opensim.ini from the opensim.ini.example.");
  536. }
  537. }
  538. return m_GridService;
  539. }
  540. }
  541. public ILibraryService LibraryService
  542. {
  543. get
  544. {
  545. if (m_LibraryService == null)
  546. m_LibraryService = RequestModuleInterface<ILibraryService>();
  547. return m_LibraryService;
  548. }
  549. }
  550. public ISimulationService SimulationService
  551. {
  552. get
  553. {
  554. if (m_simulationService == null)
  555. m_simulationService = RequestModuleInterface<ISimulationService>();
  556. return m_simulationService;
  557. }
  558. }
  559. public IAuthenticationService AuthenticationService
  560. {
  561. get
  562. {
  563. if (m_AuthenticationService == null)
  564. m_AuthenticationService = RequestModuleInterface<IAuthenticationService>();
  565. return m_AuthenticationService;
  566. }
  567. }
  568. public IPresenceService PresenceService
  569. {
  570. get
  571. {
  572. if (m_PresenceService == null)
  573. m_PresenceService = RequestModuleInterface<IPresenceService>();
  574. return m_PresenceService;
  575. }
  576. }
  577. public IUserAccountService UserAccountService
  578. {
  579. get
  580. {
  581. if (m_UserAccountService == null)
  582. m_UserAccountService = RequestModuleInterface<IUserAccountService>();
  583. return m_UserAccountService;
  584. }
  585. }
  586. public IAvatarService AvatarService
  587. {
  588. get
  589. {
  590. if (m_AvatarService == null)
  591. m_AvatarService = RequestModuleInterface<IAvatarService>();
  592. return m_AvatarService;
  593. }
  594. }
  595. public IGridUserService GridUserService
  596. {
  597. get
  598. {
  599. if (m_GridUserService == null)
  600. m_GridUserService = RequestModuleInterface<IGridUserService>();
  601. return m_GridUserService;
  602. }
  603. }
  604. public IAgentPreferencesService AgentPreferencesService
  605. {
  606. get
  607. {
  608. if (m_AgentPreferencesService == null)
  609. m_AgentPreferencesService = RequestModuleInterface<IAgentPreferencesService>();
  610. return m_AgentPreferencesService;
  611. }
  612. }
  613. public IAttachmentsModule AttachmentsModule { get; set; }
  614. public IEntityTransferModule EntityTransferModule { get; private set; }
  615. public IAgentAssetTransactions AgentTransactionsModule { get; private set; }
  616. public IUserManagement UserManagementModule { get; private set; }
  617. public IAvatarFactoryModule AvatarFactory
  618. {
  619. get { return m_AvatarFactory; }
  620. }
  621. public ICapabilitiesModule CapsModule
  622. {
  623. get { return m_capsModule; }
  624. }
  625. public int MonitorFrameTime { get { return (int)frameMS; } }
  626. public int MonitorPhysicsUpdateTime { get { return (int)physicsMS; } }
  627. public int MonitorPhysicsSyncTime { get { return (int)physicsMS2; } }
  628. public int MonitorOtherTime { get { return (int)otherMS; } }
  629. public int MonitorTempOnRezTime { get { return (int)tempOnRezMS; } }
  630. public int MonitorEventTime { get { return (int)eventMS; } } // This may need to be divided into each event?
  631. public int MonitorBackupTime { get { return (int)backupMS; } }
  632. public int MonitorTerrainTime { get { return (int)terrainMS; } }
  633. public int MonitorLandTime { get { return (int)landMS; } }
  634. public int MonitorLastFrameTick { get { return m_lastFrameTick; } }
  635. public UpdatePrioritizationSchemes UpdatePrioritizationScheme { get; set; }
  636. public bool IsReprioritizationEnabled { get; set; }
  637. public float ReprioritizationInterval { get; set; }
  638. public float ReprioritizationDistance { get; set; }
  639. private float m_minReprioritizationDistance = 32f;
  640. public bool ObjectsCullingByDistance = false;
  641. private ExpiringCache<UUID, UUID> TeleportTargetsCoolDown = new ExpiringCache<UUID, UUID>();
  642. public AgentCircuitManager AuthenticateHandler
  643. {
  644. get { return m_authenticateHandler; }
  645. }
  646. // an instance to the physics plugin's Scene object.
  647. public PhysicsScene PhysicsScene
  648. {
  649. get { return m_sceneGraph.PhysicsScene; }
  650. set
  651. {
  652. // If we're not doing the initial set
  653. // Then we've got to remove the previous
  654. // event handler
  655. if (PhysicsScene != null && PhysicsScene.SupportsNINJAJoints)
  656. {
  657. PhysicsScene.OnJointMoved -= jointMoved;
  658. PhysicsScene.OnJointDeactivated -= jointDeactivated;
  659. PhysicsScene.OnJointErrorMessage -= jointErrorMessage;
  660. }
  661. m_sceneGraph.PhysicsScene = value;
  662. if (PhysicsScene != null && m_sceneGraph.PhysicsScene.SupportsNINJAJoints)
  663. {
  664. // register event handlers to respond to joint movement/deactivation
  665. PhysicsScene.OnJointMoved += jointMoved;
  666. PhysicsScene.OnJointDeactivated += jointDeactivated;
  667. PhysicsScene.OnJointErrorMessage += jointErrorMessage;
  668. }
  669. }
  670. }
  671. public string DefaultScriptEngine
  672. {
  673. get { return m_defaultScriptEngine; }
  674. }
  675. public EntityManager Entities
  676. {
  677. get { return m_sceneGraph.Entities; }
  678. }
  679. // used in sequence see: SpawnPoint()
  680. private int m_SpawnPoint;
  681. // can be closest/random/sequence
  682. public string SpawnPointRouting
  683. {
  684. get;
  685. private set;
  686. }
  687. // allow landmarks to pass
  688. public bool TelehubAllowLandmarks
  689. {
  690. get;
  691. private set;
  692. }
  693. #endregion Properties
  694. #region Constructors
  695. public Scene(RegionInfo regInfo, AgentCircuitManager authen,
  696. ISimulationDataService simDataService, IEstateDataService estateDataService,
  697. IConfigSource config, string simulatorVersion)
  698. : this(regInfo)
  699. {
  700. m_config = config;
  701. FrameTime = 0.0908f;
  702. FrameTimeWarnPercent = 60;
  703. FrameTimeCritPercent = 40;
  704. Normalized55FPS = true;
  705. SeeIntoRegion = true;
  706. Random random = new Random();
  707. m_lastAllocatedLocalId = (uint)(random.NextDouble() * (double)(uint.MaxValue / 2)) + (uint)(uint.MaxValue / 4);
  708. m_authenticateHandler = authen;
  709. m_sceneGridService = new SceneCommunicationService();
  710. m_SimulationDataService = simDataService;
  711. m_EstateDataService = estateDataService;
  712. m_lastIncoming = 0;
  713. m_lastOutgoing = 0;
  714. m_asyncSceneObjectDeleter = new AsyncSceneObjectGroupDeleter(this);
  715. m_asyncSceneObjectDeleter.Enabled = true;
  716. m_asyncInventorySender = new AsyncInventorySender(this);
  717. #region Region Settings
  718. // Load region settings
  719. // LoadRegionSettings creates new region settings in persistence if they don't already exist for this region.
  720. // However, in this case, the default textures are not set in memory properly, so we need to do it here and
  721. // resave.
  722. // FIXME: It shouldn't be up to the database plugins to create this data - we should do it when a new
  723. // region is set up and avoid these gyrations.
  724. RegionSettings rs = simDataService.LoadRegionSettings(RegionInfo.RegionID);
  725. m_extraSettings = simDataService.GetExtra(RegionInfo.RegionID);
  726. bool updatedTerrainTextures = false;
  727. if (rs.TerrainTexture1 == UUID.Zero)
  728. {
  729. rs.TerrainTexture1 = RegionSettings.DEFAULT_TERRAIN_TEXTURE_1;
  730. updatedTerrainTextures = true;
  731. }
  732. if (rs.TerrainTexture2 == UUID.Zero)
  733. {
  734. rs.TerrainTexture2 = RegionSettings.DEFAULT_TERRAIN_TEXTURE_2;
  735. updatedTerrainTextures = true;
  736. }
  737. if (rs.TerrainTexture3 == UUID.Zero)
  738. {
  739. rs.TerrainTexture3 = RegionSettings.DEFAULT_TERRAIN_TEXTURE_3;
  740. updatedTerrainTextures = true;
  741. }
  742. if (rs.TerrainTexture4 == UUID.Zero)
  743. {
  744. rs.TerrainTexture4 = RegionSettings.DEFAULT_TERRAIN_TEXTURE_4;
  745. updatedTerrainTextures = true;
  746. }
  747. if (updatedTerrainTextures)
  748. rs.Save();
  749. RegionInfo.RegionSettings = rs;
  750. if (estateDataService != null)
  751. RegionInfo.EstateSettings = estateDataService.LoadEstateSettings(RegionInfo.RegionID, false);
  752. #endregion Region Settings
  753. //Bind Storage Manager functions to some land manager functions for this scene
  754. EventManager.OnLandObjectAdded +=
  755. new EventManager.LandObjectAdded(simDataService.StoreLandObject);
  756. EventManager.OnLandObjectRemoved +=
  757. new EventManager.LandObjectRemoved(simDataService.RemoveLandObject);
  758. RegisterDefaultSceneEvents();
  759. // XXX: Don't set the public property since we don't want to activate here. This needs to be handled
  760. // better in the future.
  761. m_scripts_enabled = !RegionInfo.RegionSettings.DisableScripts;
  762. PhysicsEnabled = !RegionInfo.RegionSettings.DisablePhysics;
  763. m_simulatorVersion = simulatorVersion + " (" + Util.GetRuntimeInformation() + ")";
  764. #region Region Config
  765. // Region config overrides global config
  766. //
  767. if (m_config.Configs["Startup"] != null)
  768. {
  769. IConfig startupConfig = m_config.Configs["Startup"];
  770. StartDisabled = startupConfig.GetBoolean("StartDisabled", false);
  771. m_defaultDrawDistance = startupConfig.GetFloat("DefaultDrawDistance", m_defaultDrawDistance);
  772. m_maxDrawDistance = startupConfig.GetFloat("MaxDrawDistance", m_maxDrawDistance);
  773. m_maxRegionViewDistance = startupConfig.GetFloat("MaxRegionsViewDistance", m_maxRegionViewDistance);
  774. m_minRegionViewDistance = startupConfig.GetFloat("MinRegionsViewDistance", m_minRegionViewDistance);
  775. // old versions compatibility
  776. LegacySitOffsets = startupConfig.GetBoolean("LegacySitOffsets", LegacySitOffsets);
  777. if (m_defaultDrawDistance > m_maxDrawDistance)
  778. m_defaultDrawDistance = m_maxDrawDistance;
  779. if (m_maxRegionViewDistance > m_maxDrawDistance)
  780. m_maxRegionViewDistance = m_maxDrawDistance;
  781. if(m_minRegionViewDistance < 96f)
  782. m_minRegionViewDistance = 96f;
  783. if(m_minRegionViewDistance > m_maxRegionViewDistance)
  784. m_minRegionViewDistance = m_maxRegionViewDistance;
  785. UseBackup = startupConfig.GetBoolean("UseSceneBackup", UseBackup);
  786. if (!UseBackup)
  787. m_log.InfoFormat("[SCENE]: Backup has been disabled for {0}", RegionInfo.RegionName);
  788. //Animation states
  789. m_useFlySlow = startupConfig.GetBoolean("enableflyslow", false);
  790. SeeIntoRegion = startupConfig.GetBoolean("see_into_region", SeeIntoRegion);
  791. MaxUndoCount = startupConfig.GetInt("MaxPrimUndos", 20);
  792. PhysicalPrims = startupConfig.GetBoolean("physical_prim", true);
  793. CollidablePrims = startupConfig.GetBoolean("collidable_prim", true);
  794. m_minNonphys = startupConfig.GetFloat("NonPhysicalPrimMin", m_minNonphys);
  795. if (RegionInfo.NonphysPrimMin > 0)
  796. {
  797. m_minNonphys = RegionInfo.NonphysPrimMin;
  798. }
  799. // don't allow nonsense values
  800. if(m_minNonphys < 0.001f)
  801. m_minNonphys = 0.001f;
  802. m_maxNonphys = startupConfig.GetFloat("NonPhysicalPrimMax", m_maxNonphys);
  803. if (RegionInfo.NonphysPrimMax > 0)
  804. {
  805. m_maxNonphys = RegionInfo.NonphysPrimMax;
  806. }
  807. if (m_maxNonphys > 65536)
  808. m_maxNonphys = 65536;
  809. m_minPhys = startupConfig.GetFloat("PhysicalPrimMin", m_minPhys);
  810. if (RegionInfo.PhysPrimMin > 0)
  811. {
  812. m_minPhys = RegionInfo.PhysPrimMin;
  813. }
  814. if(m_minPhys < 0.01f)
  815. m_minPhys = 0.01f;
  816. m_maxPhys = startupConfig.GetFloat("PhysicalPrimMax", m_maxPhys);
  817. if (RegionInfo.PhysPrimMax > 0)
  818. {
  819. m_maxPhys = RegionInfo.PhysPrimMax;
  820. }
  821. if (m_maxPhys > 2048)
  822. m_maxPhys = 2048;
  823. m_linksetCapacity = startupConfig.GetInt("LinksetPrims", m_linksetCapacity);
  824. if (RegionInfo.LinksetCapacity > 0)
  825. {
  826. m_linksetCapacity = RegionInfo.LinksetCapacity;
  827. }
  828. m_linksetPhysCapacity = startupConfig.GetInt("LinksetPhysPrims", m_linksetPhysCapacity);
  829. SpawnPointRouting = startupConfig.GetString("SpawnPointRouting", "closest");
  830. TelehubAllowLandmarks = startupConfig.GetBoolean("TelehubAllowLandmark", false);
  831. // Here, if clamping is requested in either global or
  832. // local config, it will be used
  833. //
  834. m_clampPrimSize = startupConfig.GetBoolean("ClampPrimSize", m_clampPrimSize);
  835. if (RegionInfo.ClampPrimSize)
  836. {
  837. m_clampPrimSize = true;
  838. }
  839. m_clampNegativeZ = startupConfig.GetBoolean("ClampNegativeZ", m_clampNegativeZ);
  840. m_useTrashOnDelete = startupConfig.GetBoolean("UseTrashOnDelete",m_useTrashOnDelete);
  841. m_trustBinaries = startupConfig.GetBoolean("TrustBinaries", m_trustBinaries);
  842. m_allowScriptCrossings = startupConfig.GetBoolean("AllowScriptCrossing", m_allowScriptCrossings);
  843. m_dontPersistBefore = startupConfig.GetLong("MinimumTimeBeforePersistenceConsidered", DEFAULT_MIN_TIME_FOR_PERSISTENCE);
  844. m_dontPersistBefore *= 10000000;
  845. m_persistAfter = startupConfig.GetLong("MaximumTimeBeforePersistenceConsidered", DEFAULT_MAX_TIME_FOR_PERSISTENCE);
  846. m_persistAfter *= 10000000;
  847. m_defaultScriptEngine = startupConfig.GetString("DefaultScriptEngine", "XEngine");
  848. m_log.InfoFormat("[SCENE]: Default script engine {0}", m_defaultScriptEngine);
  849. m_strictAccessControl = startupConfig.GetBoolean("StrictAccessControl", m_strictAccessControl);
  850. m_seeIntoBannedRegion = startupConfig.GetBoolean("SeeIntoBannedRegion", m_seeIntoBannedRegion);
  851. string[] possibleMapConfigSections = new string[] { "Map", "Startup" };
  852. m_generateMaptiles
  853. = Util.GetConfigVarFromSections<bool>(config, "GenerateMaptiles", possibleMapConfigSections, true);
  854. if (m_generateMaptiles)
  855. {
  856. int maptileRefresh = Util.GetConfigVarFromSections<int>(config, "MaptileRefresh", possibleMapConfigSections, 0);
  857. m_log.InfoFormat("[SCENE]: Region {0}, WORLD MAP refresh time set to {1} seconds", RegionInfo.RegionName, maptileRefresh);
  858. if (maptileRefresh != 0)
  859. {
  860. m_mapGenerationTimer.Interval = maptileRefresh * 1000;
  861. m_mapGenerationTimer.Elapsed += RegenerateMaptileAndReregister;
  862. m_mapGenerationTimer.AutoReset = false;
  863. m_mapGenerationTimer.Start();
  864. }
  865. }
  866. else
  867. {
  868. string tile
  869. = Util.GetConfigVarFromSections<string>(
  870. config, "MaptileStaticUUID", possibleMapConfigSections, UUID.Zero.ToString());
  871. UUID tileID;
  872. if (tile != UUID.Zero.ToString() && UUID.TryParse(tile, out tileID))
  873. {
  874. RegionInfo.RegionSettings.TerrainImageID = tileID;
  875. }
  876. else
  877. {
  878. RegionInfo.RegionSettings.TerrainImageID = RegionInfo.MaptileStaticUUID;
  879. m_log.InfoFormat("[SCENE]: Region {0}, maptile set to {1}", RegionInfo.RegionName, RegionInfo.MaptileStaticUUID.ToString());
  880. }
  881. }
  882. string[] possibleAccessControlConfigSections = new string[] { "Startup", "AccessControl"};
  883. string grant
  884. = Util.GetConfigVarFromSections<string>(
  885. config, "AllowedClients", possibleAccessControlConfigSections, string.Empty);
  886. if (grant.Length > 0)
  887. {
  888. foreach (string viewer in grant.Split(','))
  889. {
  890. m_AllowedViewers.Add(viewer.Trim().ToLower());
  891. }
  892. }
  893. grant
  894. = Util.GetConfigVarFromSections<string>(
  895. config, "DeniedClients", possibleAccessControlConfigSections, String.Empty);
  896. // Deal with the mess of someone having used a different word at some point
  897. if (grant == String.Empty)
  898. grant = Util.GetConfigVarFromSections<string>(
  899. config, "BannedClients", possibleAccessControlConfigSections, String.Empty);
  900. if (grant.Length > 0)
  901. {
  902. foreach (string viewer in grant.Split(','))
  903. {
  904. m_BannedViewers.Add(viewer.Trim().ToLower());
  905. }
  906. }
  907. FrameTime = startupConfig.GetFloat( "FrameTime", FrameTime);
  908. FrameTimeWarnPercent = startupConfig.GetInt( "FrameTimeWarnPercent", FrameTimeWarnPercent);
  909. FrameTimeCritPercent = startupConfig.GetInt( "FrameTimeCritPercent", FrameTimeCritPercent);
  910. Normalized55FPS = startupConfig.GetBoolean( "Normalized55FPS", Normalized55FPS);
  911. m_update_backup = startupConfig.GetInt("UpdateStorageEveryNFrames", m_update_backup);
  912. m_update_coarse_locations = startupConfig.GetInt("UpdateCoarseLocationsEveryNFrames", m_update_coarse_locations);
  913. m_update_entitymovement = startupConfig.GetInt("UpdateEntityMovementEveryNFrames", m_update_entitymovement);
  914. m_update_events = startupConfig.GetInt("UpdateEventsEveryNFrames", m_update_events);
  915. m_update_objects = startupConfig.GetInt("UpdateObjectsEveryNFrames", m_update_objects);
  916. m_update_physics = startupConfig.GetInt("UpdatePhysicsEveryNFrames", m_update_physics);
  917. m_update_presences = startupConfig.GetInt("UpdateAgentsEveryNFrames", m_update_presences);
  918. m_update_terrain = startupConfig.GetInt("UpdateTerrainEveryNFrames", m_update_terrain);
  919. m_update_temp_cleaning = startupConfig.GetInt("UpdateTempCleaningEveryNSeconds", m_update_temp_cleaning);
  920. }
  921. #endregion Region Config
  922. IConfig entityTransferConfig = m_config.Configs["EntityTransfer"];
  923. if (entityTransferConfig != null)
  924. {
  925. AllowAvatarCrossing = entityTransferConfig.GetBoolean("AllowAvatarCrossing", AllowAvatarCrossing);
  926. DisableObjectTransfer = entityTransferConfig.GetBoolean("DisableObjectTransfer", false);
  927. }
  928. #region Interest Management
  929. IConfig interestConfig = m_config.Configs["InterestManagement"];
  930. if (interestConfig != null)
  931. {
  932. string update_prioritization_scheme = interestConfig.GetString("UpdatePrioritizationScheme", "Time").Trim().ToLower();
  933. try
  934. {
  935. UpdatePrioritizationScheme = (UpdatePrioritizationSchemes)Enum.Parse(typeof(UpdatePrioritizationSchemes), update_prioritization_scheme, true);
  936. }
  937. catch (Exception)
  938. {
  939. m_log.Warn("[PRIORITIZER]: UpdatePrioritizationScheme was not recognized, setting to default BestAvatarResponsiveness");
  940. UpdatePrioritizationScheme = UpdatePrioritizationSchemes.BestAvatarResponsiveness;
  941. }
  942. IsReprioritizationEnabled
  943. = interestConfig.GetBoolean("ReprioritizationEnabled", IsReprioritizationEnabled);
  944. ReprioritizationInterval
  945. = interestConfig.GetFloat("ReprioritizationInterval", ReprioritizationInterval);
  946. ReprioritizationDistance
  947. = interestConfig.GetFloat("RootReprioritizationDistance", ReprioritizationDistance);
  948. if(ReprioritizationDistance < m_minReprioritizationDistance)
  949. ReprioritizationDistance = m_minReprioritizationDistance;
  950. ObjectsCullingByDistance
  951. = interestConfig.GetBoolean("ObjectsCullingByDistance", ObjectsCullingByDistance);
  952. }
  953. m_log.DebugFormat("[SCENE]: Using the {0} prioritization scheme", UpdatePrioritizationScheme);
  954. #endregion Interest Management
  955. StatsReporter = new SimStatsReporter(this);
  956. StatsReporter.OnSendStatsResult += SendSimStatsPackets;
  957. StatsReporter.OnStatsIncorrect += m_sceneGraph.RecalculateStats;
  958. IConfig restartConfig = config.Configs["RestartModule"];
  959. if (restartConfig != null)
  960. {
  961. string markerPath = restartConfig.GetString("MarkerPath", String.Empty);
  962. if (markerPath != String.Empty)
  963. {
  964. string path = Path.Combine(markerPath, RegionInfo.RegionID.ToString() + ".started");
  965. try
  966. {
  967. string pidstring = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
  968. FileStream fs = File.Create(path);
  969. System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
  970. Byte[] buf = enc.GetBytes(pidstring);
  971. fs.Write(buf, 0, buf.Length);
  972. fs.Close();
  973. }
  974. catch (Exception)
  975. {
  976. }
  977. }
  978. }
  979. StartTimerWatchdog();
  980. }
  981. public Scene(RegionInfo regInfo)
  982. : base(regInfo)
  983. {
  984. m_sceneGraph = new SceneGraph(this);
  985. // If the scene graph has an Unrecoverable error, restart this sim.
  986. // Currently the only thing that causes it to happen is two kinds of specific
  987. // Physics based crashes.
  988. //
  989. // Out of memory
  990. // Operating system has killed the plugin
  991. m_sceneGraph.UnRecoverableError
  992. += () =>
  993. {
  994. m_log.ErrorFormat("[SCENE]: Restarting region {0} due to unrecoverable physics crash", Name);
  995. RestartNow();
  996. };
  997. PhysicalPrims = true;
  998. CollidablePrims = true;
  999. PhysicsEnabled = true;
  1000. AllowAvatarCrossing = true;
  1001. PeriodicBackup = true;
  1002. UseBackup = true;
  1003. IsReprioritizationEnabled = true;
  1004. UpdatePrioritizationScheme = UpdatePrioritizationSchemes.BestAvatarResponsiveness;
  1005. ReprioritizationInterval = 5000;
  1006. ReprioritizationDistance = m_minReprioritizationDistance;
  1007. m_eventManager = new EventManager();
  1008. m_permissions = new ScenePermissions(this);
  1009. }
  1010. #endregion
  1011. #region Startup / Close Methods
  1012. /// <value>
  1013. /// The scene graph for this scene
  1014. /// </value>
  1015. /// TODO: Possibly stop other classes being able to manipulate this directly.
  1016. public SceneGraph SceneGraph
  1017. {
  1018. get { return m_sceneGraph; }
  1019. }
  1020. /// <summary>
  1021. /// Called by the module loader when all modules are loaded, after each module's
  1022. /// RegionLoaded hook is called. This is the earliest time where RequestModuleInterface
  1023. /// may be used.
  1024. /// </summary>
  1025. public void AllModulesLoaded()
  1026. {
  1027. IDialogModule dm = RequestModuleInterface<IDialogModule>();
  1028. if (dm != null)
  1029. m_eventManager.OnPermissionError += dm.SendAlertToUser;
  1030. ISimulatorFeaturesModule fm = RequestModuleInterface<ISimulatorFeaturesModule>();
  1031. if (fm != null)
  1032. {
  1033. OSD openSimExtras;
  1034. OSDMap openSimExtrasMap;
  1035. if (!fm.TryGetFeature("OpenSimExtras", out openSimExtras))
  1036. openSimExtras = new OSDMap();
  1037. float statisticsFPSfactor = 1.0f;
  1038. if(Normalized55FPS)
  1039. statisticsFPSfactor = 55.0f * FrameTime;
  1040. openSimExtrasMap = (OSDMap)openSimExtras;
  1041. openSimExtrasMap["SimulatorFPS"] = OSD.FromReal(1.0f / FrameTime);
  1042. openSimExtrasMap["SimulatorFPSFactor"] = OSD.FromReal(statisticsFPSfactor);
  1043. openSimExtrasMap["SimulatorFPSWarnPercent"] = OSD.FromInteger(FrameTimeWarnPercent);
  1044. openSimExtrasMap["SimulatorFPSCritPercent"] = OSD.FromInteger(FrameTimeCritPercent);
  1045. fm.AddFeature("OpenSimExtras", openSimExtrasMap);
  1046. }
  1047. }
  1048. protected virtual void RegisterDefaultSceneEvents()
  1049. {
  1050. // m_eventManager.OnSignificantClientMovement += HandleOnSignificantClientMovement;
  1051. }
  1052. public override string GetSimulatorVersion()
  1053. {
  1054. return m_simulatorVersion;
  1055. }
  1056. /// <summary>
  1057. /// Process the fact that a neighbouring region has come up.
  1058. /// </summary>
  1059. /// <remarks>
  1060. /// We only add it to the neighbor list if it's within 1 region from here.
  1061. /// Agents may have draw distance values that cross two regions though, so
  1062. /// we add it to the notify list regardless of distance. We'll check
  1063. /// the agent's draw distance before notifying them though.
  1064. /// </remarks>
  1065. /// <param name="otherRegion">RegionInfo handle for the new region.</param>
  1066. /// <returns>True after all operations complete, throws exceptions otherwise.</returns>
  1067. public override void OtherRegionUp(GridRegion otherRegion)
  1068. {
  1069. if (RegionInfo.RegionHandle != otherRegion.RegionHandle)
  1070. {
  1071. if (isNeighborRegion(otherRegion))
  1072. {
  1073. // Let the grid service module know, so this can be cached
  1074. m_eventManager.TriggerOnRegionUp(otherRegion);
  1075. try
  1076. {
  1077. ForEachRootScenePresence(delegate(ScenePresence agent)
  1078. {
  1079. List<ulong> old = new List<ulong>();
  1080. old.Add(otherRegion.RegionHandle);
  1081. agent.DropOldNeighbours(old);
  1082. if (EntityTransferModule != null && agent.PresenceType != PresenceType.Npc)
  1083. EntityTransferModule.EnableChildAgent(agent, otherRegion);
  1084. });
  1085. }
  1086. catch (NullReferenceException)
  1087. {
  1088. // This means that we're not booted up completely yet.
  1089. // This shouldn't happen too often anymore.
  1090. m_log.Error("[SCENE]: Couldn't inform client of regionup because we got a null reference exception");
  1091. }
  1092. }
  1093. else
  1094. {
  1095. m_log.InfoFormat(
  1096. "[SCENE]: Got notice about far away Region: {0} at ({1}, {2})",
  1097. otherRegion.RegionName, otherRegion.RegionLocX, otherRegion.RegionLocY);
  1098. }
  1099. }
  1100. }
  1101. public bool isNeighborRegion(GridRegion otherRegion)
  1102. {
  1103. int tmp = otherRegion.RegionLocX - (int)RegionInfo.WorldLocX;
  1104. if (tmp < -otherRegion.RegionSizeX && tmp > RegionInfo.RegionSizeX)
  1105. return false;
  1106. tmp = otherRegion.RegionLocY - (int)RegionInfo.WorldLocY;
  1107. if (tmp < -otherRegion.RegionSizeY && tmp > RegionInfo.RegionSizeY)
  1108. return false;
  1109. return true;
  1110. }
  1111. public void AddNeighborRegion(RegionInfo region)
  1112. {
  1113. lock (m_neighbours)
  1114. {
  1115. if (!CheckNeighborRegion(region))
  1116. {
  1117. m_neighbours.Add(region);
  1118. }
  1119. }
  1120. }
  1121. public bool CheckNeighborRegion(RegionInfo region)
  1122. {
  1123. bool found = false;
  1124. lock (m_neighbours)
  1125. {
  1126. foreach (RegionInfo reg in m_neighbours)
  1127. {
  1128. if (reg.RegionHandle == region.RegionHandle)
  1129. {
  1130. found = true;
  1131. break;
  1132. }
  1133. }
  1134. }
  1135. return found;
  1136. }
  1137. // Alias IncomingHelloNeighbour OtherRegionUp, for now
  1138. public GridRegion IncomingHelloNeighbour(RegionInfo neighbour)
  1139. {
  1140. OtherRegionUp(new GridRegion(neighbour));
  1141. return new GridRegion(RegionInfo);
  1142. }
  1143. // This causes the region to restart immediatley.
  1144. public void RestartNow()
  1145. {
  1146. IConfig startupConfig = m_config.Configs["Startup"];
  1147. if (startupConfig != null)
  1148. {
  1149. if (startupConfig.GetBoolean("InworldRestartShutsDown", false))
  1150. {
  1151. MainConsole.Instance.RunCommand("shutdown");
  1152. return;
  1153. }
  1154. }
  1155. m_log.InfoFormat("[REGION]: Restarting region {0}", Name);
  1156. Close();
  1157. base.Restart();
  1158. }
  1159. // This is a helper function that notifies root agents in this region that a new sim near them has come up
  1160. // This is in the form of a timer because when an instance of OpenSim.exe is started,
  1161. // Even though the sims initialize, they don't listen until 'all of the sims are initialized'
  1162. // If we tell an agent about a sim that's not listening yet, the agent will not be able to connect to it.
  1163. // subsequently the agent will never see the region come back online.
  1164. public void RestartNotifyWaitElapsed(object sender, ElapsedEventArgs e)
  1165. {
  1166. m_restartWaitTimer.Stop();
  1167. lock (m_regionRestartNotifyList)
  1168. {
  1169. foreach (RegionInfo region in m_regionRestartNotifyList)
  1170. {
  1171. GridRegion r = new GridRegion(region);
  1172. try
  1173. {
  1174. ForEachRootScenePresence(delegate(ScenePresence agent)
  1175. {
  1176. if (EntityTransferModule != null && agent.PresenceType != PresenceType.Npc)
  1177. EntityTransferModule.EnableChildAgent(agent, r);
  1178. });
  1179. }
  1180. catch (NullReferenceException)
  1181. {
  1182. // This means that we're not booted up completely yet.
  1183. // This shouldn't happen too often anymore.
  1184. }
  1185. }
  1186. // Reset list to nothing.
  1187. m_regionRestartNotifyList.Clear();
  1188. }
  1189. }
  1190. public int GetInaccurateNeighborCount()
  1191. {
  1192. return m_neighbours.Count;
  1193. }
  1194. // This is the method that shuts down the scene.
  1195. public override void Close()
  1196. {
  1197. if (m_shuttingDown)
  1198. {
  1199. m_log.WarnFormat("[SCENE]: Ignoring close request because already closing {0}", Name);
  1200. return;
  1201. }
  1202. IEtcdModule etcd = RequestModuleInterface<IEtcdModule>();
  1203. if (etcd != null)
  1204. {
  1205. etcd.Delete("Health");
  1206. etcd.Delete("HealthFlags");
  1207. etcd.Delete("RootAgents");
  1208. }
  1209. m_log.InfoFormat("[SCENE]: Closing down the single simulator: {0}", RegionInfo.RegionName);
  1210. StatsReporter.Close();
  1211. m_restartTimer.Stop();
  1212. m_restartTimer.Close();
  1213. if (!GridService.DeregisterRegion(RegionInfo.RegionID))
  1214. m_log.WarnFormat("[SCENE]: Deregister from grid failed for region {0}", Name);
  1215. // Kick all ROOT agents with the message, 'The simulator is going down'
  1216. ForEachScenePresence(delegate(ScenePresence avatar)
  1217. {
  1218. avatar.RemoveNeighbourRegion(RegionInfo.RegionHandle);
  1219. if (!avatar.IsChildAgent)
  1220. avatar.ControllingClient.Kick("The simulator is going down.");
  1221. avatar.ControllingClient.SendShutdownConnectionNotice();
  1222. });
  1223. // Stop updating the scene objects and agents.
  1224. m_shuttingDown = true;
  1225. // Wait here, or the kick messages won't actually get to the agents before the scene terminates.
  1226. // We also need to wait to avoid a race condition with the scene update loop which might not yet
  1227. // have checked ShuttingDown.
  1228. Thread.Sleep(500);
  1229. // Stop all client threads.
  1230. ForEachScenePresence(delegate(ScenePresence avatar) { CloseAgent(avatar.UUID, false); });
  1231. m_log.Debug("[SCENE]: TriggerSceneShuttingDown");
  1232. EventManager.TriggerSceneShuttingDown(this);
  1233. m_log.Debug("[SCENE]: Persisting changed objects");
  1234. Backup(true);
  1235. m_log.Debug("[SCENE]: Closing scene");
  1236. m_sceneGraph.Close();
  1237. base.Close();
  1238. // XEngine currently listens to the EventManager.OnShutdown event to trigger script stop and persistence.
  1239. // Therefore. we must dispose of the PhysicsScene after this to prevent a window where script code can
  1240. // attempt to reference a null or disposed physics scene.
  1241. if (PhysicsScene != null)
  1242. {
  1243. m_log.Debug("[SCENE]: Dispose Physics");
  1244. PhysicsScene phys = PhysicsScene;
  1245. // remove the physics engine from both Scene and SceneGraph
  1246. PhysicsScene = null;
  1247. phys.Dispose();
  1248. phys = null;
  1249. }
  1250. }
  1251. public override void Start()
  1252. {
  1253. Start(true);
  1254. }
  1255. /// <summary>
  1256. /// Start the scene
  1257. /// </summary>
  1258. /// <param name='startScripts'>
  1259. /// Start the scripts within the scene.
  1260. /// </param>
  1261. public void Start(bool startScripts)
  1262. {
  1263. if (IsRunning)
  1264. return;
  1265. m_isRunning = true;
  1266. m_active = true;
  1267. m_unixStartTime = Util.UnixTimeSinceEpoch();
  1268. // m_log.DebugFormat("[SCENE]: Starting Heartbeat timer for {0}", RegionInfo.RegionName);
  1269. if (m_heartbeatThread != null)
  1270. {
  1271. m_hbRestarts++;
  1272. if(m_hbRestarts > 10)
  1273. Environment.Exit(1);
  1274. m_log.ErrorFormat("[SCENE]: Restarting heartbeat thread because it hasn't reported in in region {0}", RegionInfo.RegionName);
  1275. //int pid = System.Diagnostics.Process.GetCurrentProcess().Id;
  1276. //System.Diagnostics.Process proc = new System.Diagnostics.Process();
  1277. //proc.EnableRaisingEvents=false;
  1278. //proc.StartInfo.FileName = "/bin/kill";
  1279. //proc.StartInfo.Arguments = "-QUIT " + pid.ToString();
  1280. //proc.Start();
  1281. //proc.WaitForExit();
  1282. //Thread.Sleep(1000);
  1283. //Environment.Exit(1);
  1284. m_heartbeatThread.Abort();
  1285. Watchdog.AbortThread(m_heartbeatThread.ManagedThreadId);
  1286. m_heartbeatThread = null;
  1287. }
  1288. GC.Collect();
  1289. GC.WaitForPendingFinalizers();
  1290. GC.Collect();
  1291. // tell physics to finish building actor
  1292. m_sceneGraph.ProcessPhysicsPreSimulation();
  1293. m_heartbeatThread = WorkManager.StartThread(
  1294. Heartbeat, string.Format("Heartbeat-({0})", RegionInfo.RegionName.Replace(" ", "_")), ThreadPriority.Normal, false,
  1295. false, null, 20000, false);
  1296. StartScripts();
  1297. }
  1298. /// <summary>
  1299. /// Sets up references to modules required by the scene
  1300. /// </summary>
  1301. public void SetModuleInterfaces()
  1302. {
  1303. m_xmlrpcModule = RequestModuleInterface<IXMLRPC>();
  1304. m_worldCommModule = RequestModuleInterface<IWorldComm>();
  1305. XferManager = RequestModuleInterface<IXfer>();
  1306. m_AvatarFactory = RequestModuleInterface<IAvatarFactoryModule>();
  1307. AttachmentsModule = RequestModuleInterface<IAttachmentsModule>();
  1308. m_serialiser = RequestModuleInterface<IRegionSerialiserModule>();
  1309. m_dialogModule = RequestModuleInterface<IDialogModule>();
  1310. m_capsModule = RequestModuleInterface<ICapabilitiesModule>();
  1311. EntityTransferModule = RequestModuleInterface<IEntityTransferModule>();
  1312. m_groupsModule = RequestModuleInterface<IGroupsModule>();
  1313. AgentTransactionsModule = RequestModuleInterface<IAgentAssetTransactions>();
  1314. UserManagementModule = RequestModuleInterface<IUserManagement>();
  1315. }
  1316. #endregion
  1317. #region Update Methods
  1318. /// <summary>
  1319. /// Activate the various loops necessary to continually update the scene.
  1320. /// </summary>
  1321. private void Heartbeat()
  1322. {
  1323. m_eventManager.TriggerOnRegionStarted(this);
  1324. // The first frame can take a very long time due to physics actors being added on startup. Therefore,
  1325. // don't turn on the watchdog alarm for this thread until the second frame, in order to prevent false
  1326. // alarms for scenes with many objects.
  1327. Update(1);
  1328. Watchdog.GetCurrentThreadInfo().AlarmIfTimeout = true;
  1329. m_lastFrameTick = Util.EnvironmentTickCount();
  1330. Update(-1);
  1331. Watchdog.RemoveThread();
  1332. }
  1333. public override void Update(int frames)
  1334. {
  1335. long? endFrame = null;
  1336. if (frames >= 0)
  1337. endFrame = Frame + frames;
  1338. float physicsFPS = 0f;
  1339. float frameTimeMS = FrameTime * 1000.0f;
  1340. int previousFrameTick;
  1341. double tmpMS;
  1342. double tmpMS2;
  1343. double framestart;
  1344. float sleepMS;
  1345. float sleepError = 0;
  1346. while (!m_shuttingDown && ((endFrame == null && Active) || Frame < endFrame))
  1347. {
  1348. framestart = Util.GetTimeStampMS();
  1349. ++Frame;
  1350. // m_log.DebugFormat("[SCENE]: Processing frame {0} in {1}", Frame, RegionInfo.RegionName);
  1351. agentMS = tempOnRezMS = eventMS = backupMS = terrainMS = landMS = 0f;
  1352. try
  1353. {
  1354. EventManager.TriggerRegionHeartbeatStart(this);
  1355. // Apply taints in terrain module to terrain in physics scene
  1356. tmpMS = Util.GetTimeStampMS();
  1357. if (Frame % 4 == 0)
  1358. {
  1359. CheckTerrainUpdates();
  1360. }
  1361. if (Frame % m_update_terrain == 0)
  1362. {
  1363. UpdateTerrain();
  1364. }
  1365. tmpMS2 = Util.GetTimeStampMS();
  1366. terrainMS = (float)(tmpMS2 - tmpMS);
  1367. tmpMS = tmpMS2;
  1368. if (PhysicsEnabled && Frame % m_update_physics == 0)
  1369. m_sceneGraph.UpdatePreparePhysics();
  1370. tmpMS2 = Util.GetTimeStampMS();
  1371. physicsMS2 = (float)(tmpMS2 - tmpMS);
  1372. tmpMS = tmpMS2;
  1373. /*
  1374. // Apply any pending avatar force input to the avatar's velocity
  1375. if (Frame % m_update_entitymovement == 0)
  1376. m_sceneGraph.UpdateScenePresenceMovement();
  1377. */
  1378. if (Frame % (m_update_coarse_locations) == 0 && !m_sendingCoarseLocations)
  1379. {
  1380. m_sendingCoarseLocations = true;
  1381. WorkManager.RunInThreadPool(
  1382. delegate
  1383. {
  1384. List<Vector3> coarseLocations;
  1385. List<UUID> avatarUUIDs;
  1386. SceneGraph.GetCoarseLocations(out coarseLocations, out avatarUUIDs, 60);
  1387. // Send coarse locations to clients
  1388. ForEachScenePresence(delegate(ScenePresence presence)
  1389. {
  1390. presence.SendCoarseLocations(coarseLocations, avatarUUIDs);
  1391. });
  1392. m_sendingCoarseLocations = false;
  1393. }, null, string.Format("SendCoarseLocations ({0})", Name));
  1394. }
  1395. // Get the simulation frame time that the avatar force input
  1396. // took
  1397. tmpMS2 = Util.GetTimeStampMS();
  1398. agentMS = (float)(tmpMS2 - tmpMS);
  1399. tmpMS = tmpMS2;
  1400. // Perform the main physics update. This will do the actual work of moving objects and avatars according to their
  1401. // velocity
  1402. if (Frame % m_update_physics == 0)
  1403. {
  1404. if (PhysicsEnabled)
  1405. physicsFPS = m_sceneGraph.UpdatePhysics(FrameTime);
  1406. }
  1407. tmpMS2 = Util.GetTimeStampMS();
  1408. physicsMS = (float)(tmpMS2 - tmpMS);
  1409. tmpMS = tmpMS2;
  1410. // Check if any objects have reached their targets
  1411. CheckAtTargets();
  1412. // Update SceneObjectGroups that have scheduled themselves for updates
  1413. // Objects queue their updates onto all scene presences
  1414. if (Frame % m_update_objects == 0)
  1415. m_sceneGraph.UpdateObjectGroups();
  1416. // Run through all ScenePresences looking for updates
  1417. // Presence updates and queued object updates for each presence are sent to clients
  1418. if (Frame % m_update_presences == 0)
  1419. m_sceneGraph.UpdatePresences();
  1420. tmpMS2 = Util.GetTimeStampMS();
  1421. agentMS += (float)(tmpMS2 - tmpMS);
  1422. tmpMS = tmpMS2;
  1423. // Delete temp-on-rez stuff
  1424. if (Frame % m_update_temp_cleaning == 0 && !m_cleaningTemps)
  1425. {
  1426. m_cleaningTemps = true;
  1427. WorkManager.RunInThreadPool(
  1428. delegate { CleanTempObjects(); m_cleaningTemps = false; }, null, string.Format("CleanTempObjects ({0})", Name));
  1429. tmpMS2 = Util.GetTimeStampMS();
  1430. tempOnRezMS = (float)(tmpMS2 - tmpMS); // bad.. counts the FireAndForget, not CleanTempObjects
  1431. tmpMS = tmpMS2;
  1432. }
  1433. if (Frame % m_update_events == 0)
  1434. {
  1435. UpdateEvents();
  1436. tmpMS2 = Util.GetTimeStampMS();
  1437. eventMS = (float)(tmpMS2 - tmpMS);
  1438. tmpMS = tmpMS2;
  1439. }
  1440. if (PeriodicBackup && Frame % m_update_backup == 0)
  1441. {
  1442. UpdateStorageBackup();
  1443. tmpMS2 = Util.GetTimeStampMS();
  1444. backupMS = (float)(tmpMS2 - tmpMS);
  1445. tmpMS = tmpMS2;
  1446. }
  1447. //if (Frame % m_update_land == 0)
  1448. //{
  1449. // int ldMS = Util.EnvironmentTickCount();
  1450. // UpdateLand();
  1451. // landMS = Util.EnvironmentTickCountSubtract(ldMS);
  1452. //}
  1453. if (!LoginsEnabled && Frame == 20)
  1454. {
  1455. GC.Collect();
  1456. GC.WaitForPendingFinalizers();
  1457. GC.Collect();
  1458. if (!LoginLock)
  1459. {
  1460. if (!StartDisabled)
  1461. {
  1462. m_log.InfoFormat("[REGION]: Enabling logins for {0}", RegionInfo.RegionName);
  1463. LoginsEnabled = true;
  1464. }
  1465. m_sceneGridService.InformNeighborsThatRegionisUp(
  1466. RequestModuleInterface<INeighbourService>(), RegionInfo);
  1467. // Region ready should always be set
  1468. Ready = true;
  1469. IConfig restartConfig = m_config.Configs["RestartModule"];
  1470. if (restartConfig != null)
  1471. {
  1472. string markerPath = restartConfig.GetString("MarkerPath", String.Empty);
  1473. if (markerPath != String.Empty)
  1474. {
  1475. string path = Path.Combine(markerPath, RegionInfo.RegionID.ToString() + ".ready");
  1476. try
  1477. {
  1478. string pidstring = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
  1479. FileStream fs = File.Create(path);
  1480. System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
  1481. Byte[] buf = enc.GetBytes(pidstring);
  1482. fs.Write(buf, 0, buf.Length);
  1483. fs.Close();
  1484. }
  1485. catch (Exception)
  1486. {
  1487. }
  1488. }
  1489. }
  1490. }
  1491. else
  1492. {
  1493. // This handles a case of a region having no scripts for the RegionReady module
  1494. if (m_sceneGraph.GetActiveScriptsCount() == 0)
  1495. {
  1496. // In this case, we leave it to the IRegionReadyModule to enable logins
  1497. // LoginLock can currently only be set by a region module implementation.
  1498. // If somehow this hasn't been done then the quickest way to bugfix is to see the
  1499. // NullReferenceException
  1500. IRegionReadyModule rrm = RequestModuleInterface<IRegionReadyModule>();
  1501. rrm.TriggerRegionReady(this);
  1502. }
  1503. }
  1504. }
  1505. }
  1506. catch (Exception e)
  1507. {
  1508. m_log.ErrorFormat(
  1509. "[SCENE]: Failed on region {0} with exception {1}{2}",
  1510. RegionInfo.RegionName, e.Message, e.StackTrace);
  1511. }
  1512. EventManager.TriggerRegionHeartbeatEnd(this);
  1513. m_firstHeartbeat = false;
  1514. Watchdog.UpdateThread();
  1515. otherMS = tempOnRezMS + eventMS + backupMS + terrainMS + landMS;
  1516. tmpMS = Util.GetTimeStampMS();
  1517. previousFrameTick = m_lastFrameTick;
  1518. m_lastFrameTick = (int)(tmpMS + 0.5);
  1519. // estimate sleep time
  1520. tmpMS2 = tmpMS - framestart;
  1521. tmpMS2 = (double)frameTimeMS - tmpMS2 - sleepError;
  1522. // reuse frameMS as temporary
  1523. frameMS = (float)tmpMS2;
  1524. // sleep if we can
  1525. if (tmpMS2 > 0)
  1526. {
  1527. Thread.Sleep((int)(tmpMS2 + 0.5));
  1528. tmpMS2 = Util.GetTimeStampMS();
  1529. sleepMS = (float)(tmpMS2 - tmpMS);
  1530. sleepError = sleepMS - frameMS;
  1531. Util.Clamp(sleepError, 0.0f, 20f);
  1532. frameMS = (float)(tmpMS2 - framestart);
  1533. }
  1534. else
  1535. {
  1536. tmpMS2 = Util.GetTimeStampMS();
  1537. frameMS = (float)(tmpMS2 - framestart);
  1538. sleepMS = 0.0f;
  1539. sleepError = 0.0f;
  1540. }
  1541. // script time is not scene frame time, but is displayed per frame
  1542. float scriptTimeMS = GetAndResetScriptExecutionTime();
  1543. StatsReporter.AddFrameStats(TimeDilation, physicsFPS, agentMS,
  1544. physicsMS + physicsMS2, otherMS , sleepMS, frameMS, scriptTimeMS);
  1545. // if (Frame%m_update_avatars == 0)
  1546. // UpdateInWorldTime();
  1547. // Optionally warn if a frame takes double the amount of time that it should.
  1548. if (DebugUpdates
  1549. && Util.EnvironmentTickCountSubtract(
  1550. m_lastFrameTick, previousFrameTick) > (int)(FrameTime * 1000 * 2))
  1551. m_log.WarnFormat(
  1552. "[SCENE]: Frame took {0} ms (desired max {1} ms) in {2}",
  1553. Util.EnvironmentTickCountSubtract(m_lastFrameTick, previousFrameTick),
  1554. FrameTime * 1000,
  1555. RegionInfo.RegionName);
  1556. }
  1557. }
  1558. /// <summary>
  1559. /// Adds the execution time of one script to the total scripts execution time for this region.
  1560. /// </summary>
  1561. /// <param name="ticks">Elapsed Stopwatch ticks</param>
  1562. public void AddScriptExecutionTime(long ticks)
  1563. {
  1564. StatsReporter.addScriptEvents(1);
  1565. Interlocked.Add(ref m_scriptExecutionTime, ticks);
  1566. }
  1567. /// <summary>
  1568. /// Returns the total execution time of all the scripts in the region since the last call
  1569. /// (in milliseconds), and clears the value in preparation for the next call.
  1570. /// </summary>
  1571. /// <returns>Time in milliseconds</returns>
  1572. // Warning: this is now called from StatsReporter, and can't be shared
  1573. public long GetAndResetScriptExecutionTime()
  1574. {
  1575. long ticks = Interlocked.Exchange(ref m_scriptExecutionTime, 0);
  1576. return (ticks * 1000L) / Stopwatch.Frequency;
  1577. }
  1578. public void AddGroupTarget(SceneObjectGroup grp)
  1579. {
  1580. lock (m_groupsWithTargets)
  1581. m_groupsWithTargets[grp.UUID] = 0;
  1582. }
  1583. public void RemoveGroupTarget(SceneObjectGroup grp)
  1584. {
  1585. lock (m_groupsWithTargets)
  1586. m_groupsWithTargets.Remove(grp.UUID);
  1587. }
  1588. private void CheckAtTargets()
  1589. {
  1590. List<UUID> objs = null;
  1591. lock (m_groupsWithTargets)
  1592. {
  1593. if (m_groupsWithTargets.Count != 0)
  1594. objs = new List<UUID>(m_groupsWithTargets.Keys);
  1595. }
  1596. if (objs != null)
  1597. {
  1598. foreach (UUID entry in objs)
  1599. {
  1600. SceneObjectGroup grp = GetSceneObjectGroup(entry);
  1601. if (grp == null)
  1602. m_groupsWithTargets.Remove(entry);
  1603. else
  1604. grp.checkAtTargets();
  1605. }
  1606. }
  1607. }
  1608. /// <summary>
  1609. /// Send out simstats data to all clients
  1610. /// </summary>
  1611. /// <param name="stats">Stats on the Simulator's performance</param>
  1612. private void SendSimStatsPackets(SimStats stats)
  1613. {
  1614. ForEachRootClient(delegate(IClientAPI client)
  1615. {
  1616. client.SendSimStats(stats);
  1617. });
  1618. }
  1619. /// <summary>
  1620. /// Update the terrain if it needs to be updated.
  1621. /// </summary>
  1622. private void UpdateTerrain()
  1623. {
  1624. EventManager.TriggerTerrainTick();
  1625. }
  1626. private void CheckTerrainUpdates()
  1627. {
  1628. EventManager.TriggerTerrainCheckUpdates();
  1629. }
  1630. /// <summary>
  1631. /// Back up queued up changes
  1632. /// </summary>
  1633. private void UpdateStorageBackup()
  1634. {
  1635. if (!m_backingup)
  1636. {
  1637. WorkManager.RunInThreadPool(o => Backup(false), null, string.Format("BackupWorker ({0})", Name), false);
  1638. }
  1639. }
  1640. /// <summary>
  1641. /// Sends out the OnFrame event to the modules
  1642. /// </summary>
  1643. private void UpdateEvents()
  1644. {
  1645. m_eventManager.TriggerOnFrame();
  1646. }
  1647. /// <summary>
  1648. /// Backup the scene.
  1649. /// </summary>
  1650. /// <remarks>
  1651. /// This acts as the main method of the backup thread. In a regression test whether the backup thread is not
  1652. /// running independently this can be invoked directly.
  1653. /// </remarks>
  1654. /// <param name="forced">
  1655. /// If true, then any changes that have not yet been persisted are persisted. If false,
  1656. /// then the persistence decision is left to the backup code (in some situations, such as object persistence,
  1657. /// it's much more efficient to backup multiple changes at once rather than every single one).
  1658. /// <returns></returns>
  1659. public void Backup(bool forced)
  1660. {
  1661. lock (m_returns)
  1662. {
  1663. if(m_backingup)
  1664. {
  1665. m_log.WarnFormat("[Scene] Backup of {0} already running. New call skipped", RegionInfo.RegionName);
  1666. return;
  1667. }
  1668. m_backingup = true;
  1669. try
  1670. {
  1671. EventManager.TriggerOnBackup(SimulationDataService, forced);
  1672. if(m_returns.Count == 0)
  1673. return;
  1674. IMessageTransferModule tr = RequestModuleInterface<IMessageTransferModule>();
  1675. if (tr == null)
  1676. return;
  1677. uint unixtime = (uint)Util.UnixTimeSinceEpoch();
  1678. uint estateid = RegionInfo.EstateSettings.ParentEstateID;
  1679. Guid regionguid = RegionInfo.RegionID.Guid;
  1680. foreach (KeyValuePair<UUID, ReturnInfo> ret in m_returns)
  1681. {
  1682. GridInstantMessage msg = new GridInstantMessage();
  1683. msg.fromAgentID = Guid.Empty; // From server
  1684. msg.toAgentID = ret.Key.Guid;
  1685. msg.imSessionID = Guid.NewGuid();
  1686. msg.timestamp = unixtime;
  1687. msg.fromAgentName = "Server";
  1688. msg.dialog = 19; // Object msg
  1689. msg.fromGroup = false;
  1690. msg.offline = 1;
  1691. msg.ParentEstateID = estateid;
  1692. msg.Position = Vector3.Zero;
  1693. msg.RegionID = regionguid;
  1694. // We must fill in a null-terminated 'empty' string here since bytes[0] will crash viewer 3.
  1695. msg.binaryBucket = new Byte[1] {0};
  1696. if (ret.Value.count > 1)
  1697. msg.message = string.Format("Your {0} objects were returned from {1} in region {2} due to {3}", ret.Value.count, ret.Value.location.ToString(), RegionInfo.RegionName, ret.Value.reason);
  1698. else
  1699. msg.message = string.Format("Your object {0} was returned from {1} in region {2} due to {3}", ret.Value.objectName, ret.Value.location.ToString(), RegionInfo.RegionName, ret.Value.reason);
  1700. tr.SendInstantMessage(msg, delegate(bool success) { });
  1701. }
  1702. m_returns.Clear();
  1703. }
  1704. finally
  1705. {
  1706. m_backingup = false;
  1707. }
  1708. }
  1709. }
  1710. /// <summary>
  1711. /// Synchronous force backup. For deletes and links/unlinks
  1712. /// </summary>
  1713. /// <param name="group">Object to be backed up</param>
  1714. public void ForceSceneObjectBackup(SceneObjectGroup group)
  1715. {
  1716. if (group != null)
  1717. {
  1718. group.HasGroupChanged = true;
  1719. group.ProcessBackup(SimulationDataService, true);
  1720. }
  1721. }
  1722. /// <summary>
  1723. /// Tell an agent that their object has been returned.
  1724. /// </summary>
  1725. /// <remarks>
  1726. /// The actual return is handled by the caller.
  1727. /// </remarks>
  1728. /// <param name="agentID">Avatar Unique Id</param>
  1729. /// <param name="objectName">Name of object returned</param>
  1730. /// <param name="location">Location of object returned</param>
  1731. /// <param name="reason">Reasion for object return</param>
  1732. public void AddReturn(UUID agentID, string objectName, Vector3 location, string reason)
  1733. {
  1734. lock (m_returns)
  1735. {
  1736. if (m_returns.ContainsKey(agentID))
  1737. {
  1738. ReturnInfo info = m_returns[agentID];
  1739. info.count++;
  1740. m_returns[agentID] = info;
  1741. }
  1742. else
  1743. {
  1744. ReturnInfo info = new ReturnInfo();
  1745. info.count = 1;
  1746. info.objectName = objectName;
  1747. info.location = location;
  1748. info.reason = reason;
  1749. m_returns[agentID] = info;
  1750. }
  1751. }
  1752. }
  1753. #endregion
  1754. #region Load Terrain
  1755. /// <summary>
  1756. /// Store the terrain in the persistant data store
  1757. /// </summary>
  1758. public void SaveTerrain()
  1759. {
  1760. SimulationDataService.StoreTerrain(Heightmap.GetTerrainData(), RegionInfo.RegionID);
  1761. }
  1762. /// <summary>
  1763. /// Store the terrain in the persistant data store
  1764. /// </summary>
  1765. public void SaveBakedTerrain()
  1766. {
  1767. if(Bakedmap != null)
  1768. SimulationDataService.StoreBakedTerrain(Bakedmap.GetTerrainData(), RegionInfo.RegionID);
  1769. }
  1770. public void StoreWindlightProfile(RegionLightShareData wl)
  1771. {
  1772. RegionInfo.WindlightSettings = wl;
  1773. SimulationDataService.StoreRegionWindlightSettings(wl);
  1774. m_eventManager.TriggerOnSaveNewWindlightProfile();
  1775. }
  1776. public void LoadWindlightProfile()
  1777. {
  1778. RegionInfo.WindlightSettings = SimulationDataService.LoadRegionWindlightSettings(RegionInfo.RegionID);
  1779. m_eventManager.TriggerOnSaveNewWindlightProfile();
  1780. }
  1781. /// <summary>
  1782. /// Loads the World heightmap
  1783. /// </summary>
  1784. public override void LoadWorldMap()
  1785. {
  1786. try
  1787. {
  1788. Bakedmap = null;
  1789. TerrainData map = SimulationDataService.LoadBakedTerrain(RegionInfo.RegionID, (int)RegionInfo.RegionSizeX, (int)RegionInfo.RegionSizeY, (int)RegionInfo.RegionSizeZ);
  1790. if (map != null)
  1791. {
  1792. Bakedmap = new TerrainChannel(map);
  1793. }
  1794. }
  1795. catch (Exception e)
  1796. {
  1797. m_log.WarnFormat(
  1798. "[TERRAIN]: Scene.cs: LoadWorldMap() baked terrain - Failed with exception {0}{1}", e.Message, e.StackTrace);
  1799. }
  1800. try
  1801. {
  1802. TerrainData map = SimulationDataService.LoadTerrain(RegionInfo.RegionID, (int)RegionInfo.RegionSizeX, (int)RegionInfo.RegionSizeY, (int)RegionInfo.RegionSizeZ);
  1803. if (map == null)
  1804. {
  1805. if(Bakedmap != null)
  1806. {
  1807. m_log.Warn("[TERRAIN]: terrain not found. Used stored baked terrain.");
  1808. Heightmap = Bakedmap.MakeCopy();
  1809. SimulationDataService.StoreTerrain(Heightmap.GetTerrainData(), RegionInfo.RegionID);
  1810. }
  1811. else
  1812. {
  1813. // This should be in the Terrain module, but it isn't because
  1814. // the heightmap is needed _way_ before the modules are initialized...
  1815. IConfig terrainConfig = m_config.Configs["Terrain"];
  1816. String m_InitialTerrain = "pinhead-island";
  1817. if (terrainConfig != null)
  1818. m_InitialTerrain = terrainConfig.GetString("InitialTerrain", m_InitialTerrain);
  1819. m_log.InfoFormat("[TERRAIN]: No default terrain. Generating a new terrain {0}.", m_InitialTerrain);
  1820. Heightmap = new TerrainChannel(m_InitialTerrain, (int)RegionInfo.RegionSizeX, (int)RegionInfo.RegionSizeY, (int)RegionInfo.RegionSizeZ);
  1821. SimulationDataService.StoreTerrain(Heightmap.GetTerrainData(), RegionInfo.RegionID);
  1822. }
  1823. }
  1824. else
  1825. {
  1826. Heightmap = new TerrainChannel(map);
  1827. }
  1828. }
  1829. catch (IOException e)
  1830. {
  1831. m_log.WarnFormat(
  1832. "[TERRAIN]: Scene.cs: LoadWorldMap() - Regenerating as failed with exception {0}{1}",
  1833. e.Message, e.StackTrace);
  1834. #pragma warning disable 0162
  1835. if ((int)Constants.RegionSize != 256)
  1836. {
  1837. Heightmap = new TerrainChannel();
  1838. SimulationDataService.StoreTerrain(Heightmap.GetTerrainData(), RegionInfo.RegionID);
  1839. }
  1840. }
  1841. catch (Exception e)
  1842. {
  1843. m_log.WarnFormat(
  1844. "[TERRAIN]: Scene.cs: LoadWorldMap() - Failed with exception {0}{1}", e.Message, e.StackTrace);
  1845. }
  1846. if(Bakedmap == null && Heightmap != null)
  1847. {
  1848. Bakedmap = Heightmap.MakeCopy();
  1849. SimulationDataService.StoreBakedTerrain(Bakedmap.GetTerrainData(), RegionInfo.RegionID);
  1850. }
  1851. }
  1852. /// <summary>
  1853. /// Register this region with a grid service
  1854. /// </summary>
  1855. /// <exception cref="System.Exception">Thrown if registration of the region itself fails.</exception>
  1856. public void RegisterRegionWithGrid()
  1857. {
  1858. m_sceneGridService.SetScene(this);
  1859. //// Unfortunately this needs to be here and it can't be async.
  1860. //// The map tile image is stored in RegionSettings, but it also needs to be
  1861. //// stored in the GridService, because that's what the world map module uses
  1862. //// to send the map image UUIDs (of other regions) to the viewer...
  1863. if (m_generateMaptiles)
  1864. RegenerateMaptile();
  1865. GridRegion region = new GridRegion(RegionInfo);
  1866. string error = GridService.RegisterRegion(RegionInfo.ScopeID, region);
  1867. // m_log.DebugFormat("[SCENE]: RegisterRegionWithGrid. name={0},id={1},loc=<{2},{3}>,size=<{4},{5}>",
  1868. // m_regionName,
  1869. // RegionInfo.RegionID,
  1870. // RegionInfo.RegionLocX, RegionInfo.RegionLocY,
  1871. // RegionInfo.RegionSizeX, RegionInfo.RegionSizeY);
  1872. if (error != String.Empty)
  1873. throw new Exception(error);
  1874. }
  1875. #endregion
  1876. #region Load Land
  1877. /// <summary>
  1878. /// Loads all Parcel data from the datastore for region identified by regionID
  1879. /// </summary>
  1880. /// <param name="regionID">Unique Identifier of the Region to load parcel data for</param>
  1881. public void loadAllLandObjectsFromStorage(UUID regionID)
  1882. {
  1883. m_log.Info("[SCENE]: Loading land objects from storage");
  1884. List<LandData> landData = SimulationDataService.LoadLandObjects(regionID);
  1885. if (LandChannel != null)
  1886. {
  1887. if (landData.Count == 0)
  1888. {
  1889. EventManager.TriggerNoticeNoLandDataFromStorage();
  1890. }
  1891. else
  1892. {
  1893. EventManager.TriggerIncomingLandDataFromStorage(landData);
  1894. }
  1895. }
  1896. else
  1897. {
  1898. m_log.Error("[SCENE]: Land Channel is not defined. Cannot load from storage!");
  1899. }
  1900. }
  1901. #endregion
  1902. #region Primitives Methods
  1903. /// <summary>
  1904. /// Loads the World's objects
  1905. /// </summary>
  1906. /// <param name="regionID"></param>
  1907. public virtual void LoadPrimsFromStorage(UUID regionID)
  1908. {
  1909. LoadingPrims = true;
  1910. m_log.Info("[SCENE]: Loading objects from datastore");
  1911. List<SceneObjectGroup> PrimsFromDB = SimulationDataService.LoadObjects(regionID);
  1912. m_log.InfoFormat("[SCENE]: Loaded {0} objects from the datastore", PrimsFromDB.Count);
  1913. foreach (SceneObjectGroup group in PrimsFromDB)
  1914. {
  1915. AddRestoredSceneObject(group, true, true);
  1916. EventManager.TriggerOnSceneObjectLoaded(group);
  1917. SceneObjectPart rootPart = group.GetPart(group.UUID);
  1918. rootPart.Flags &= ~PrimFlags.Scripted;
  1919. rootPart.TrimPermissions();
  1920. group.InvalidateDeepEffectivePerms();
  1921. // Don't do this here - it will get done later on when sculpt data is loaded.
  1922. // group.CheckSculptAndLoad();
  1923. }
  1924. LoadingPrims = false;
  1925. EventManager.TriggerPrimsLoaded(this);
  1926. }
  1927. public bool SupportsRayCastFiltered()
  1928. {
  1929. if (PhysicsScene == null)
  1930. return false;
  1931. return PhysicsScene.SupportsRaycastWorldFiltered();
  1932. }
  1933. public object RayCastFiltered(Vector3 position, Vector3 direction, float length, int Count, RayFilterFlags filter)
  1934. {
  1935. if (PhysicsScene == null)
  1936. return null;
  1937. return PhysicsScene.RaycastWorld(position, direction, length, Count, filter);
  1938. }
  1939. /// <summary>
  1940. /// Gets a new rez location based on the raycast and the size of the object that is being rezzed.
  1941. /// </summary>
  1942. /// <param name="RayStart"></param>
  1943. /// <param name="RayEnd"></param>
  1944. /// <param name="RayTargetID"></param>
  1945. /// <param name="rot"></param>
  1946. /// <param name="bypassRayCast"></param>
  1947. /// <param name="RayEndIsIntersection"></param>
  1948. /// <param name="frontFacesOnly"></param>
  1949. /// <param name="scale"></param>
  1950. /// <param name="FaceCenter"></param>
  1951. /// <returns></returns>
  1952. public Vector3 GetNewRezLocation(Vector3 RayStart, Vector3 RayEnd, UUID RayTargetID, Quaternion rot, byte bypassRayCast, byte RayEndIsIntersection, bool frontFacesOnly, Vector3 scale, bool FaceCenter)
  1953. {
  1954. Vector3 dir = RayEnd - RayStart;
  1955. float wheight = (float)RegionInfo.RegionSettings.WaterHeight;
  1956. Vector3 wpos = Vector3.Zero;
  1957. // Check for water surface intersection from above
  1958. if ((RayStart.Z > wheight) && (RayEnd.Z < wheight))
  1959. {
  1960. float ratio = (wheight - RayStart.Z) / dir.Z;
  1961. wpos.X = RayStart.X + (ratio * dir.X);
  1962. wpos.Y = RayStart.Y + (ratio * dir.Y);
  1963. wpos.Z = wheight;
  1964. }
  1965. Vector3 pos = Vector3.Zero;
  1966. if (RayEndIsIntersection != (byte)1)
  1967. {
  1968. float dist = dir.Length();
  1969. if (dist != 0)
  1970. {
  1971. Vector3 direction = dir * (1 / dist);
  1972. dist += 1.0f;
  1973. if (SupportsRayCastFiltered())
  1974. {
  1975. RayFilterFlags rayfilter = RayFilterFlags.BackFaceCull;
  1976. rayfilter |= RayFilterFlags.land;
  1977. rayfilter |= RayFilterFlags.physical;
  1978. rayfilter |= RayFilterFlags.nonphysical;
  1979. rayfilter |= RayFilterFlags.LSLPhantom; // ubODE will only see volume detectors
  1980. // get some more contacts ???
  1981. int physcount = 4;
  1982. List<ContactResult> physresults =
  1983. (List<ContactResult>)RayCastFiltered(RayStart, direction, dist, physcount, rayfilter);
  1984. if (physresults != null && physresults.Count > 0)
  1985. {
  1986. // look for terrain ?
  1987. if(RayTargetID == UUID.Zero)
  1988. {
  1989. foreach (ContactResult r in physresults)
  1990. {
  1991. if (r.ConsumerID == 0)
  1992. {
  1993. pos = r.Normal * scale;
  1994. pos *= 0.5f;
  1995. pos = r.Pos + pos;
  1996. if (wpos.Z > pos.Z) pos = wpos;
  1997. return pos;
  1998. }
  1999. }
  2000. }
  2001. else
  2002. {
  2003. foreach (ContactResult r in physresults)
  2004. {
  2005. SceneObjectPart part = GetSceneObjectPart(r.ConsumerID);
  2006. if (part == null)
  2007. continue;
  2008. if (part.UUID == RayTargetID)
  2009. {
  2010. pos = r.Normal * scale;
  2011. pos *= 0.5f;
  2012. pos = r.Pos + pos;
  2013. if (wpos.Z > pos.Z) pos = wpos;
  2014. return pos;
  2015. }
  2016. }
  2017. }
  2018. // else the first we got
  2019. pos = physresults[0].Normal * scale;
  2020. pos *= 0.5f;
  2021. pos = physresults[0].Pos + pos;
  2022. if (wpos.Z > pos.Z)
  2023. pos = wpos;
  2024. return pos;
  2025. }
  2026. }
  2027. if (RayTargetID != UUID.Zero)
  2028. {
  2029. SceneObjectPart target = GetSceneObjectPart(RayTargetID);
  2030. Ray NewRay = new Ray(RayStart, direction);
  2031. if (target != null)
  2032. {
  2033. pos = target.AbsolutePosition;
  2034. // Ray Trace against target here
  2035. EntityIntersection ei = target.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, FaceCenter);
  2036. // Un-comment out the following line to Get Raytrace results printed to the console.
  2037. // m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  2038. float ScaleOffset = 0.5f;
  2039. // If we hit something
  2040. if (ei.HitTF)
  2041. {
  2042. Vector3 scaleComponent = ei.AAfaceNormal;
  2043. if (scaleComponent.X != 0) ScaleOffset = scale.X;
  2044. if (scaleComponent.Y != 0) ScaleOffset = scale.Y;
  2045. if (scaleComponent.Z != 0) ScaleOffset = scale.Z;
  2046. ScaleOffset = Math.Abs(ScaleOffset);
  2047. Vector3 intersectionpoint = ei.ipoint;
  2048. Vector3 normal = ei.normal;
  2049. // Set the position to the intersection point
  2050. Vector3 offset = (normal * (ScaleOffset / 2f));
  2051. pos = (intersectionpoint + offset);
  2052. //Seems to make no sense to do this as this call is used for rezzing from inventory as well, and with inventory items their size is not always 0.5f
  2053. //And in cases when we weren't rezzing from inventory we were re-adding the 0.25 straight after calling this method
  2054. // Un-offset the prim (it gets offset later by the consumer method)
  2055. //pos.Z -= 0.25F;
  2056. if (wpos.Z > pos.Z) pos = wpos;
  2057. return pos;
  2058. }
  2059. }
  2060. else
  2061. {
  2062. // We don't have a target here, so we're going to raytrace all the objects in the scene.
  2063. EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(NewRay, true, false);
  2064. // Un-comment the following line to print the raytrace results to the console.
  2065. //m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  2066. if (ei.HitTF)
  2067. {
  2068. pos = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
  2069. }
  2070. else
  2071. {
  2072. // fall back to our stupid functionality
  2073. pos = RayEnd;
  2074. }
  2075. if (wpos.Z > pos.Z) pos = wpos;
  2076. return pos;
  2077. }
  2078. }
  2079. }
  2080. }
  2081. // fall back to our stupid functionality
  2082. pos = RayEnd;
  2083. //increase height so its above the ground.
  2084. //should be getting the normal of the ground at the rez point and using that?
  2085. pos.Z += scale.Z / 2f;
  2086. // return pos;
  2087. // check against posible water intercept
  2088. if (wpos.Z > pos.Z) pos = wpos;
  2089. return pos;
  2090. }
  2091. /// <summary>
  2092. /// Create a New SceneObjectGroup/Part by raycasting
  2093. /// </summary>
  2094. /// <param name="ownerID"></param>
  2095. /// <param name="groupID"></param>
  2096. /// <param name="RayEnd"></param>
  2097. /// <param name="rot"></param>
  2098. /// <param name="shape"></param>
  2099. /// <param name="bypassRaycast"></param>
  2100. /// <param name="RayStart"></param>
  2101. /// <param name="RayTargetID"></param>
  2102. /// <param name="RayEndIsIntersection"></param>
  2103. public virtual void AddNewPrim(UUID ownerID, UUID groupID, Vector3 RayEnd, Quaternion rot, PrimitiveBaseShape shape,
  2104. byte bypassRaycast, Vector3 RayStart, UUID RayTargetID,
  2105. byte RayEndIsIntersection)
  2106. {
  2107. Vector3 pos = GetNewRezLocation(RayStart, RayEnd, RayTargetID, rot, bypassRaycast, RayEndIsIntersection, true, new Vector3(0.5f, 0.5f, 0.5f), false);
  2108. if (Permissions.CanRezObject(1, ownerID, pos))
  2109. {
  2110. // rez ON the ground, not IN the ground
  2111. // pos.Z += 0.25F; The rez point should now be correct so that its not in the ground
  2112. AddNewPrim(ownerID, groupID, pos, rot, shape);
  2113. }
  2114. else
  2115. {
  2116. IClientAPI client = null;
  2117. if (TryGetClient(ownerID, out client))
  2118. client.SendAlertMessage("You cannot create objects here.");
  2119. }
  2120. }
  2121. public virtual SceneObjectGroup AddNewPrim(
  2122. UUID ownerID, UUID groupID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape)
  2123. {
  2124. //m_log.DebugFormat(
  2125. // "[SCENE]: Scene.AddNewPrim() pcode {0} called for {1} in {2}", shape.PCode, ownerID, RegionInfo.RegionName);
  2126. SceneObjectGroup sceneObject = null;
  2127. // If an entity creator has been registered for this prim type then use that
  2128. if (m_entityCreators.ContainsKey((PCode)shape.PCode))
  2129. {
  2130. sceneObject = m_entityCreators[(PCode)shape.PCode].CreateEntity(ownerID, groupID, pos, rot, shape);
  2131. }
  2132. else
  2133. {
  2134. // Otherwise, use this default creation code;
  2135. sceneObject = new SceneObjectGroup(ownerID, pos, rot, shape);
  2136. sceneObject.SetGroup(groupID, null);
  2137. AddNewSceneObject(sceneObject, true);
  2138. if (AgentPreferencesService != null) // This will override the brave new full perm world!
  2139. {
  2140. AgentPrefs prefs = AgentPreferencesService.GetAgentPreferences(ownerID);
  2141. // Only apply user selected prefs if the user set them
  2142. if (prefs != null && prefs.PermNextOwner != 0)
  2143. {
  2144. sceneObject.RootPart.GroupMask = (uint)prefs.PermGroup;
  2145. sceneObject.RootPart.EveryoneMask = (uint)prefs.PermEveryone;
  2146. sceneObject.RootPart.NextOwnerMask = (uint)prefs.PermNextOwner;
  2147. }
  2148. }
  2149. }
  2150. if (UserManagementModule != null)
  2151. sceneObject.RootPart.CreatorIdentification = UserManagementModule.GetUserUUI(ownerID);
  2152. sceneObject.InvalidateDeepEffectivePerms();;
  2153. sceneObject.ScheduleGroupForFullAnimUpdate();
  2154. return sceneObject;
  2155. }
  2156. /// <summary>
  2157. /// Add an object into the scene that has come from storage
  2158. /// </summary>
  2159. ///
  2160. /// <param name="sceneObject"></param>
  2161. /// <param name="attachToBackup">
  2162. /// If true, changes to the object will be reflected in its persisted data
  2163. /// If false, the persisted data will not be changed even if the object in the scene is changed
  2164. /// </param>
  2165. /// <param name="alreadyPersisted">
  2166. /// If true, we won't persist this object until it changes
  2167. /// If false, we'll persist this object immediately
  2168. /// </param>
  2169. /// <param name="sendClientUpdates">
  2170. /// If true, we send updates to the client to tell it about this object
  2171. /// If false, we leave it up to the caller to do this
  2172. /// </param>
  2173. /// <returns>
  2174. /// true if the object was added, false if an object with the same uuid was already in the scene
  2175. /// </returns>
  2176. public bool AddRestoredSceneObject(
  2177. SceneObjectGroup sceneObject, bool attachToBackup, bool alreadyPersisted, bool sendClientUpdates)
  2178. {
  2179. if (m_sceneGraph.AddRestoredSceneObject(sceneObject, attachToBackup, alreadyPersisted, sendClientUpdates))
  2180. {
  2181. sceneObject.IsDeleted = false;
  2182. EventManager.TriggerObjectAddedToScene(sceneObject);
  2183. return true;
  2184. }
  2185. return false;
  2186. }
  2187. /// <summary>
  2188. /// Add an object into the scene that has come from storage
  2189. /// </summary>
  2190. ///
  2191. /// <param name="sceneObject"></param>
  2192. /// <param name="attachToBackup">
  2193. /// If true, changes to the object will be reflected in its persisted data
  2194. /// If false, the persisted data will not be changed even if the object in the scene is changed
  2195. /// </param>
  2196. /// <param name="alreadyPersisted">
  2197. /// If true, we won't persist this object until it changes
  2198. /// If false, we'll persist this object immediately
  2199. /// </param>
  2200. /// <returns>
  2201. /// true if the object was added, false if an object with the same uuid was already in the scene
  2202. /// </returns>
  2203. public bool AddRestoredSceneObject(
  2204. SceneObjectGroup sceneObject, bool attachToBackup, bool alreadyPersisted)
  2205. {
  2206. return AddRestoredSceneObject(sceneObject, attachToBackup, alreadyPersisted, true);
  2207. }
  2208. /// <summary>
  2209. /// Add a newly created object to the scene. Updates are also sent to viewers.
  2210. /// </summary>
  2211. /// <param name="sceneObject"></param>
  2212. /// <param name="attachToBackup">
  2213. /// If true, the object is made persistent into the scene.
  2214. /// If false, the object will not persist over server restarts
  2215. /// </param>
  2216. /// <returns>true if the object was added. false if not</returns>
  2217. public bool AddNewSceneObject(SceneObjectGroup sceneObject, bool attachToBackup)
  2218. {
  2219. return AddNewSceneObject(sceneObject, attachToBackup, true);
  2220. }
  2221. /// <summary>
  2222. /// Add a newly created object to the scene
  2223. /// </summary>
  2224. /// <param name="sceneObject"></param>
  2225. /// <param name="attachToBackup">
  2226. /// If true, the object is made persistent into the scene.
  2227. /// If false, the object will not persist over server restarts
  2228. /// </param>
  2229. /// <param name="sendClientUpdates">
  2230. /// If true, updates for the new scene object are sent to all viewers in range.
  2231. /// If false, it is left to the caller to schedule the update
  2232. /// </param>
  2233. /// <returns>true if the object was added. false if not</returns>
  2234. public bool AddNewSceneObject(SceneObjectGroup sceneObject, bool attachToBackup, bool sendClientUpdates)
  2235. {
  2236. if (m_sceneGraph.AddNewSceneObject(sceneObject, attachToBackup, sendClientUpdates))
  2237. {
  2238. EventManager.TriggerObjectAddedToScene(sceneObject);
  2239. return true;
  2240. }
  2241. return false;
  2242. }
  2243. /// <summary>
  2244. /// Add a newly created object to the scene.
  2245. /// </summary>
  2246. /// <remarks>
  2247. /// This method does not send updates to the client - callers need to handle this themselves.
  2248. /// </remarks>
  2249. /// <param name="sceneObject"></param>
  2250. /// <param name="attachToBackup"></param>
  2251. /// <param name="pos">Position of the object. If null then the position stored in the object is used.</param>
  2252. /// <param name="rot">Rotation of the object. If null then the rotation stored in the object is used.</param>
  2253. /// <param name="vel">Velocity of the object. This parameter only has an effect if the object is physical</param>
  2254. /// <returns></returns>
  2255. public bool AddNewSceneObject(
  2256. SceneObjectGroup sceneObject, bool attachToBackup, Vector3? pos, Quaternion? rot, Vector3 vel)
  2257. {
  2258. if (m_sceneGraph.AddNewSceneObject(sceneObject, attachToBackup, pos, rot, vel))
  2259. {
  2260. EventManager.TriggerObjectAddedToScene(sceneObject);
  2261. return true;
  2262. }
  2263. return false;
  2264. }
  2265. /// <summary>
  2266. /// Delete every object from the scene. This does not include attachments worn by avatars.
  2267. /// </summary>
  2268. public void DeleteAllSceneObjects()
  2269. {
  2270. DeleteAllSceneObjects(false);
  2271. }
  2272. /// <summary>
  2273. /// Delete every object from the scene. This does not include attachments worn by avatars.
  2274. /// </summary>
  2275. public void DeleteAllSceneObjects(bool exceptNoCopy)
  2276. {
  2277. List<SceneObjectGroup> toReturn = new List<SceneObjectGroup>();
  2278. lock (Entities)
  2279. {
  2280. EntityBase[] entities = Entities.GetEntities();
  2281. foreach (EntityBase e in entities)
  2282. {
  2283. if (e is SceneObjectGroup)
  2284. {
  2285. SceneObjectGroup sog = (SceneObjectGroup)e;
  2286. if (sog != null && !sog.IsAttachment)
  2287. {
  2288. if (!exceptNoCopy || ((sog.EffectiveOwnerPerms & (uint)PermissionMask.Copy) != 0))
  2289. {
  2290. DeleteSceneObject((SceneObjectGroup)e, false);
  2291. }
  2292. else
  2293. {
  2294. toReturn.Add((SceneObjectGroup)e);
  2295. }
  2296. }
  2297. }
  2298. }
  2299. }
  2300. if (toReturn.Count > 0)
  2301. {
  2302. returnObjects(toReturn.ToArray(), null);
  2303. }
  2304. }
  2305. /// <summary>
  2306. /// Synchronously delete the given object from the scene.
  2307. /// </summary>
  2308. /// <remarks>
  2309. /// Scripts are also removed.
  2310. /// </remarks>
  2311. /// <param name="group">Object Id</param>
  2312. /// <param name="silent">Suppress broadcasting changes to other clients.</param>
  2313. public void DeleteSceneObject(SceneObjectGroup group, bool silent)
  2314. {
  2315. DeleteSceneObject(group, silent, true);
  2316. }
  2317. /// <summary>
  2318. /// Synchronously delete the given object from the scene.
  2319. /// </summary>
  2320. /// <param name="group">Object Id</param>
  2321. /// <param name="silent">Suppress broadcasting changes to other clients.</param>
  2322. /// <param name="removeScripts">If true, then scripts are removed. If false, then they are only stopped.</para>
  2323. public void DeleteSceneObject(SceneObjectGroup group, bool silent, bool removeScripts)
  2324. {
  2325. // m_log.DebugFormat("[SCENE]: Deleting scene object {0} {1}", group.Name, group.UUID);
  2326. if (removeScripts)
  2327. group.RemoveScriptInstances(true);
  2328. else
  2329. group.StopScriptInstances();
  2330. SceneObjectPart[] partList = group.Parts;
  2331. foreach (SceneObjectPart part in partList)
  2332. {
  2333. if (part.KeyframeMotion != null)
  2334. {
  2335. part.KeyframeMotion.Delete();
  2336. part.KeyframeMotion = null;
  2337. }
  2338. if (part.IsJoint() && ((part.Flags & PrimFlags.Physics) != 0))
  2339. {
  2340. PhysicsScene.RequestJointDeletion(part.Name); // FIXME: what if the name changed?
  2341. }
  2342. else if (part.PhysActor != null)
  2343. {
  2344. part.RemoveFromPhysics();
  2345. }
  2346. }
  2347. if (UnlinkSceneObject(group, false))
  2348. {
  2349. EventManager.TriggerObjectBeingRemovedFromScene(group);
  2350. EventManager.TriggerParcelPrimCountTainted();
  2351. }
  2352. group.DeleteGroupFromScene(silent);
  2353. // use this to mean also full delete
  2354. if (removeScripts)
  2355. group.Clear();
  2356. partList = null;
  2357. // m_log.DebugFormat("[SCENE]: Exit DeleteSceneObject() for {0} {1}", group.Name, group.UUID);
  2358. }
  2359. /// <summary>
  2360. /// Unlink the given object from the scene. Unlike delete, this just removes the record of the object - the
  2361. /// object itself is not destroyed.
  2362. /// </summary>
  2363. /// <param name="so">The scene object.</param>
  2364. /// <param name="softDelete">If true, only deletes from scene, but keeps the object in the database.</param>
  2365. /// <returns>true if the object was in the scene, false if it was not</returns>
  2366. public bool UnlinkSceneObject(SceneObjectGroup so, bool softDelete)
  2367. {
  2368. if (m_sceneGraph.DeleteSceneObject(so.UUID, softDelete))
  2369. {
  2370. if (!softDelete)
  2371. {
  2372. // If the group contains prims whose SceneGroupID is incorrect then force a
  2373. // database update, because RemoveObject() works by searching on the SceneGroupID.
  2374. // This is an expensive thing to do so only do it if absolutely necessary.
  2375. if (so.GroupContainsForeignPrims)
  2376. ForceSceneObjectBackup(so);
  2377. so.DetachFromBackup();
  2378. SimulationDataService.RemoveObject(so.UUID, RegionInfo.RegionID);
  2379. }
  2380. // We need to keep track of this state in case this group is still queued for further backup.
  2381. so.IsDeleted = true;
  2382. return true;
  2383. }
  2384. return false;
  2385. }
  2386. /* not in use, outdate by async method
  2387. /// <summary>
  2388. /// Move the given scene object into a new region depending on which region its absolute position has moved
  2389. /// into.
  2390. ///
  2391. /// </summary>
  2392. /// <param name="attemptedPosition">the attempted out of region position of the scene object</param>
  2393. /// <param name="grp">the scene object that we're crossing</param>
  2394. public void CrossPrimGroupIntoNewRegion(Vector3 attemptedPosition, SceneObjectGroup grp, bool silent)
  2395. {
  2396. if (grp == null)
  2397. return;
  2398. if (grp.IsDeleted)
  2399. return;
  2400. if (grp.RootPart.DIE_AT_EDGE)
  2401. {
  2402. // We remove the object here
  2403. try
  2404. {
  2405. DeleteSceneObject(grp, false);
  2406. }
  2407. catch (Exception)
  2408. {
  2409. m_log.Warn("[SCENE]: exception when trying to remove the prim that crossed the border.");
  2410. }
  2411. return;
  2412. }
  2413. if (grp.RootPart.RETURN_AT_EDGE)
  2414. {
  2415. // We remove the object here
  2416. try
  2417. {
  2418. List<SceneObjectGroup> objects = new List<SceneObjectGroup>();
  2419. objects.Add(grp);
  2420. SceneObjectGroup[] objectsArray = objects.ToArray();
  2421. returnObjects(objectsArray, UUID.Zero);
  2422. }
  2423. catch (Exception)
  2424. {
  2425. m_log.Warn("[SCENE]: exception when trying to return the prim that crossed the border.");
  2426. }
  2427. return;
  2428. }
  2429. if (EntityTransferModule != null)
  2430. EntityTransferModule.Cross(grp, attemptedPosition, silent);
  2431. }
  2432. */
  2433. // Simple test to see if a position is in the current region.
  2434. // This test is mostly used to see if a region crossing is necessary.
  2435. // Assuming the position is relative to the region so anything outside its bounds.
  2436. // Return 'true' if position inside region.
  2437. public bool PositionIsInCurrentRegion(Vector3 pos)
  2438. {
  2439. float t = pos.X;
  2440. if (t < 0 || t >= RegionInfo.RegionSizeX)
  2441. return false;
  2442. t = pos.Y;
  2443. if (t < 0 || t >= RegionInfo.RegionSizeY)
  2444. return false;
  2445. return true;
  2446. }
  2447. /// <summary>
  2448. /// Called when objects or attachments cross the border, or teleport, between regions.
  2449. /// </summary>
  2450. /// <param name="sog"></param>
  2451. /// <returns></returns>
  2452. public bool IncomingCreateObject(Vector3 newPosition, ISceneObject sog)
  2453. {
  2454. //m_log.DebugFormat(" >>> IncomingCreateObject(sog) <<< {0} deleted? {1} isAttach? {2}", ((SceneObjectGroup)sog).AbsolutePosition,
  2455. // ((SceneObjectGroup)sog).IsDeleted, ((SceneObjectGroup)sog).RootPart.IsAttachment);
  2456. SceneObjectGroup newObject;
  2457. try
  2458. {
  2459. newObject = (SceneObjectGroup)sog;
  2460. }
  2461. catch (Exception e)
  2462. {
  2463. m_log.WarnFormat("[INTERREGION]: Problem casting object, exception {0}{1}", e.Message, e.StackTrace);
  2464. return false;
  2465. }
  2466. if (!EntityTransferModule.HandleIncomingSceneObject(newObject, newPosition))
  2467. return false;
  2468. // Do this as late as possible so that listeners have full access to the incoming object
  2469. EventManager.TriggerOnIncomingSceneObject(newObject);
  2470. return true;
  2471. }
  2472. /// <summary>
  2473. /// Adds a Scene Object group to the Scene.
  2474. /// Verifies that the creator of the object is not banned from the simulator.
  2475. /// Checks if the item is an Attachment
  2476. /// </summary>
  2477. /// <param name="sceneObject"></param>
  2478. /// <returns>True if the SceneObjectGroup was added, False if it was not</returns>
  2479. public bool AddSceneObject(SceneObjectGroup sceneObject)
  2480. {
  2481. if (sceneObject.OwnerID == UUID.Zero)
  2482. {
  2483. m_log.ErrorFormat("[SCENE]: Owner ID for {0} was zero", sceneObject.UUID);
  2484. return false;
  2485. }
  2486. // If the user is banned, we won't let any of their objects
  2487. // enter. Period.
  2488. //
  2489. int flags = GetUserFlags(sceneObject.OwnerID);
  2490. if (RegionInfo.EstateSettings.IsBanned(sceneObject.OwnerID, flags))
  2491. {
  2492. m_log.InfoFormat("[INTERREGION]: Denied prim crossing for banned avatar {0}", sceneObject.OwnerID);
  2493. return false;
  2494. }
  2495. // Force allocation of new LocalId
  2496. //
  2497. SceneObjectPart[] parts = sceneObject.Parts;
  2498. for (int i = 0; i < parts.Length; i++)
  2499. parts[i].LocalId = 0;
  2500. if (sceneObject.IsAttachmentCheckFull()) // Attachment
  2501. {
  2502. sceneObject.RootPart.AddFlag(PrimFlags.TemporaryOnRez);
  2503. // Don't sent a full update here because this will cause full updates to be sent twice for
  2504. // attachments on region crossings, resulting in viewer glitches.
  2505. AddRestoredSceneObject(sceneObject, false, false, false);
  2506. // Handle attachment special case
  2507. SceneObjectPart RootPrim = sceneObject.RootPart;
  2508. // Fix up attachment Parent Local ID
  2509. ScenePresence sp = GetScenePresence(sceneObject.OwnerID);
  2510. if (sp != null)
  2511. {
  2512. SceneObjectGroup grp = sceneObject;
  2513. // m_log.DebugFormat(
  2514. // "[ATTACHMENT]: Received attachment {0}, inworld asset id {1}", grp.FromItemID, grp.UUID);
  2515. // m_log.DebugFormat(
  2516. // "[ATTACHMENT]: Attach to avatar {0} at position {1}", sp.UUID, grp.AbsolutePosition);
  2517. // We must currently not resume scripts at this stage since AttachmentsModule does not have the
  2518. // information that this is due to a teleport/border cross rather than an ordinary attachment.
  2519. // We currently do this in Scene.MakeRootAgent() instead.
  2520. bool attached = false;
  2521. if (AttachmentsModule != null)
  2522. attached = AttachmentsModule.AttachObject(sp, grp, 0, false, false, true);
  2523. if (attached)
  2524. RootPrim.RemFlag(PrimFlags.TemporaryOnRez);
  2525. else
  2526. m_log.DebugFormat("[SCENE]: Attachment {0} arrived but failed to attach, setting to temp", sceneObject.UUID);
  2527. }
  2528. else
  2529. {
  2530. m_log.DebugFormat("[SCENE]: Attachment {0} arrived and scene presence was not found, setting to temp", sceneObject.UUID);
  2531. // RootPrim.RemFlag(PrimFlags.TemporaryOnRez);
  2532. // RootPrim.AddFlag(PrimFlags.TemporaryOnRez);
  2533. }
  2534. if (sceneObject.OwnerID == UUID.Zero)
  2535. {
  2536. m_log.ErrorFormat("[SCENE]: Owner ID for {0} was zero after attachment processing. BUG!", sceneObject.UUID);
  2537. return false;
  2538. }
  2539. }
  2540. else
  2541. {
  2542. if (sceneObject.OwnerID == UUID.Zero)
  2543. {
  2544. m_log.ErrorFormat("[SCENE]: Owner ID for non-attachment {0} was zero", sceneObject.UUID);
  2545. return false;
  2546. }
  2547. AddRestoredSceneObject(sceneObject, true, false);
  2548. }
  2549. return true;
  2550. }
  2551. private int GetStateSource(SceneObjectGroup sog)
  2552. {
  2553. if(!sog.IsAttachmentCheckFull())
  2554. return 2; // StateSource.PrimCrossing
  2555. ScenePresence sp = GetScenePresence(sog.OwnerID);
  2556. if (sp != null)
  2557. return sp.GetStateSource();
  2558. return 2; // StateSource.PrimCrossing
  2559. }
  2560. public int GetUserFlags(UUID user)
  2561. {
  2562. //Unfortunately the SP approach means that the value is cached until region is restarted
  2563. /*
  2564. ScenePresence sp;
  2565. if (TryGetScenePresence(user, out sp))
  2566. {
  2567. return sp.UserFlags;
  2568. }
  2569. else
  2570. {
  2571. */
  2572. UserAccount uac = UserAccountService.GetUserAccount(RegionInfo.ScopeID, user);
  2573. if (uac == null)
  2574. return 0;
  2575. return uac.UserFlags;
  2576. //}
  2577. }
  2578. #endregion
  2579. #region Add/Remove Avatar Methods
  2580. public override ISceneAgent AddNewAgent(IClientAPI client, PresenceType type)
  2581. {
  2582. ScenePresence sp;
  2583. bool vialogin;
  2584. bool reallyNew = true;
  2585. // Update the number of users attempting to login
  2586. StatsReporter.UpdateUsersLoggingIn(true);
  2587. // Validation occurs in LLUDPServer
  2588. //
  2589. // XXX: A race condition exists here where two simultaneous calls to AddNewAgent can interfere with
  2590. // each other. In practice, this does not currently occur in the code.
  2591. AgentCircuitData aCircuit = m_authenticateHandler.GetAgentCircuitData(client.CircuitCode);
  2592. // We lock here on AgentCircuitData to prevent a race condition between the thread adding a new connection
  2593. // and a simultaneous one that removes it (as can happen if the client is closed at a particular point
  2594. // whilst connecting).
  2595. //
  2596. // It would be easier to lock across all NewUserConnection(), AddNewAgent() and
  2597. // RemoveClient() calls for all agents, but this would allow a slow call (e.g. because of slow service
  2598. // response in some module listening to AddNewAgent()) from holding up unrelated agent calls.
  2599. //
  2600. // In practice, the lock (this) in LLUDPServer.AddNewClient() currently lock across all
  2601. // AddNewClient() operations (though not other ops).
  2602. // In the future this can be relieved once locking per agent (not necessarily on AgentCircuitData) is improved.
  2603. lock (aCircuit)
  2604. {
  2605. vialogin
  2606. = (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin) != 0
  2607. || (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaLogin) != 0;
  2608. CheckHeartbeat();
  2609. sp = GetScenePresence(client.AgentId);
  2610. if (sp == null)
  2611. {
  2612. m_log.DebugFormat(
  2613. "[SCENE]: Adding new child scene presence {0} {1} to scene {2} at pos {3}, tpflags: {4}",
  2614. client.Name, client.AgentId, RegionInfo.RegionName, client.StartPos,
  2615. ((TPFlags)aCircuit.teleportFlags).ToString());
  2616. m_clientManager.Add(client);
  2617. SubscribeToClientEvents(client);
  2618. sp = m_sceneGraph.CreateAndAddChildScenePresence(client, aCircuit.Appearance, type);
  2619. sp.TeleportFlags = (TPFlags)aCircuit.teleportFlags;
  2620. m_eventManager.TriggerOnNewPresence(sp);
  2621. }
  2622. else
  2623. {
  2624. // We must set this here so that TriggerOnNewClient and TriggerOnClientLogin can determine whether the
  2625. // client is for a root or child agent.
  2626. // XXX: This may be better set for a new client before that client is added to the client manager.
  2627. // But need to know what happens in the case where a ScenePresence is already present (and if this
  2628. // actually occurs).
  2629. m_log.WarnFormat(
  2630. "[SCENE]: Already found {0} scene presence for {1} in {2} when asked to add new scene presence",
  2631. sp.IsChildAgent ? "child" : "root", sp.Name, RegionInfo.RegionName);
  2632. reallyNew = false;
  2633. }
  2634. client.SceneAgent = sp;
  2635. // This is currently also being done earlier in NewUserConnection for real users to see if this
  2636. // resolves problems where HG agents are occasionally seen by others as "Unknown user" in chat and other
  2637. // places. However, we still need to do it here for NPCs.
  2638. CacheUserName(sp, aCircuit);
  2639. if (reallyNew)
  2640. EventManager.TriggerOnNewClient(client);
  2641. if (vialogin)
  2642. EventManager.TriggerOnClientLogin(client);
  2643. }
  2644. // User has logged into the scene so update the list of users logging
  2645. // in
  2646. StatsReporter.UpdateUsersLoggingIn(false);
  2647. m_LastLogin = Util.EnvironmentTickCount();
  2648. return sp;
  2649. }
  2650. /// <summary>
  2651. /// Returns the Home URI of the agent, or null if unknown.
  2652. /// </summary>
  2653. public string GetAgentHomeURI(UUID agentID)
  2654. {
  2655. AgentCircuitData circuit = AuthenticateHandler.GetAgentCircuitData(agentID);
  2656. if (circuit != null && circuit.ServiceURLs != null && circuit.ServiceURLs.ContainsKey("HomeURI"))
  2657. return circuit.ServiceURLs["HomeURI"].ToString();
  2658. else
  2659. return null;
  2660. }
  2661. /// <summary>
  2662. /// Cache the user name for later use.
  2663. /// </summary>
  2664. /// <param name="sp"></param>
  2665. /// <param name="aCircuit"></param>
  2666. private void CacheUserName(ScenePresence sp, AgentCircuitData aCircuit)
  2667. {
  2668. if (UserManagementModule != null)
  2669. {
  2670. string first = aCircuit.firstname, last = aCircuit.lastname;
  2671. if (sp != null && sp.PresenceType == PresenceType.Npc)
  2672. {
  2673. UserManagementModule.AddUser(aCircuit.AgentID, first, last, true);
  2674. }
  2675. else
  2676. {
  2677. string homeURL = string.Empty;
  2678. if (aCircuit.ServiceURLs.ContainsKey("HomeURI"))
  2679. homeURL = aCircuit.ServiceURLs["HomeURI"].ToString();
  2680. if (aCircuit.lastname.StartsWith("@"))
  2681. {
  2682. string[] parts = aCircuit.firstname.Split('.');
  2683. if (parts.Length >= 2)
  2684. {
  2685. first = parts[0];
  2686. last = parts[1];
  2687. }
  2688. }
  2689. UserManagementModule.AddUser(aCircuit.AgentID, first, last, homeURL);
  2690. }
  2691. }
  2692. }
  2693. private bool VerifyClient(AgentCircuitData aCircuit, System.Net.IPEndPoint ep, out bool vialogin)
  2694. {
  2695. vialogin = false;
  2696. // Do the verification here
  2697. if ((aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin) != 0)
  2698. {
  2699. m_log.DebugFormat("[SCENE]: Incoming client {0} {1} in region {2} via HG login", aCircuit.firstname, aCircuit.lastname, RegionInfo.RegionName);
  2700. vialogin = true;
  2701. IUserAgentVerificationModule userVerification = RequestModuleInterface<IUserAgentVerificationModule>();
  2702. if (userVerification != null && ep != null)
  2703. {
  2704. if (!userVerification.VerifyClient(aCircuit, ep.Address.ToString()))
  2705. {
  2706. // uh-oh, this is fishy
  2707. m_log.DebugFormat("[SCENE]: User Client Verification for {0} {1} in {2} returned false", aCircuit.firstname, aCircuit.lastname, RegionInfo.RegionName);
  2708. return false;
  2709. }
  2710. else
  2711. m_log.DebugFormat("[SCENE]: User Client Verification for {0} {1} in {2} returned true", aCircuit.firstname, aCircuit.lastname, RegionInfo.RegionName);
  2712. }
  2713. }
  2714. else if ((aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaLogin) != 0)
  2715. {
  2716. m_log.DebugFormat("[SCENE]: Incoming client {0} {1} in region {2} via regular login. Client IP verification not performed.",
  2717. aCircuit.firstname, aCircuit.lastname, RegionInfo.RegionName);
  2718. vialogin = true;
  2719. }
  2720. return true;
  2721. }
  2722. // Called by Caps, on the first HTTP contact from the client
  2723. public override bool CheckClient(UUID agentID, System.Net.IPEndPoint ep)
  2724. {
  2725. AgentCircuitData aCircuit = m_authenticateHandler.GetAgentCircuitData(agentID);
  2726. if (aCircuit == null)
  2727. return false;
  2728. bool vialogin = false;
  2729. if (VerifyClient(aCircuit, ep, out vialogin))
  2730. return true;
  2731. // if it doesn't pass, we remove the agentcircuitdata altogether
  2732. // and the scene presence and the client, if they exist
  2733. try
  2734. {
  2735. ScenePresence sp = WaitGetScenePresence(agentID);
  2736. if (sp != null)
  2737. {
  2738. PresenceService.LogoutAgent(sp.ControllingClient.SessionId);
  2739. CloseAgent(sp.UUID, false);
  2740. }
  2741. // BANG! SLASH!
  2742. m_authenticateHandler.RemoveCircuit(agentID);
  2743. }
  2744. catch (Exception e)
  2745. {
  2746. m_log.DebugFormat("[SCENE]: Exception while closing aborted client: {0}", e.StackTrace);
  2747. }
  2748. return false;
  2749. }
  2750. /// <summary>
  2751. /// Register for events from the client
  2752. /// </summary>
  2753. /// <param name="client">The IClientAPI of the connected client</param>
  2754. public virtual void SubscribeToClientEvents(IClientAPI client)
  2755. {
  2756. SubscribeToClientTerrainEvents(client);
  2757. SubscribeToClientPrimEvents(client);
  2758. SubscribeToClientPrimRezEvents(client);
  2759. SubscribeToClientInventoryEvents(client);
  2760. SubscribeToClientTeleportEvents(client);
  2761. SubscribeToClientScriptEvents(client);
  2762. SubscribeToClientParcelEvents(client);
  2763. SubscribeToClientGridEvents(client);
  2764. SubscribeToClientNetworkEvents(client);
  2765. }
  2766. public virtual void SubscribeToClientTerrainEvents(IClientAPI client)
  2767. {
  2768. // client.OnRegionHandShakeReply += SendLayerData;
  2769. }
  2770. public virtual void SubscribeToClientPrimEvents(IClientAPI client)
  2771. {
  2772. client.OnUpdatePrimGroupPosition += m_sceneGraph.UpdatePrimGroupPosition;
  2773. client.OnUpdatePrimSinglePosition += m_sceneGraph.UpdatePrimSinglePosition;
  2774. client.onClientChangeObject += m_sceneGraph.ClientChangeObject;
  2775. client.OnUpdatePrimGroupRotation += m_sceneGraph.UpdatePrimGroupRotation;
  2776. client.OnUpdatePrimGroupMouseRotation += m_sceneGraph.UpdatePrimGroupRotation;
  2777. client.OnUpdatePrimSingleRotation += m_sceneGraph.UpdatePrimSingleRotation;
  2778. client.OnUpdatePrimSingleRotationPosition += m_sceneGraph.UpdatePrimSingleRotationPosition;
  2779. client.OnUpdatePrimScale += m_sceneGraph.UpdatePrimScale;
  2780. client.OnUpdatePrimGroupScale += m_sceneGraph.UpdatePrimGroupScale;
  2781. client.OnUpdateExtraParams += m_sceneGraph.UpdateExtraParam;
  2782. client.OnUpdatePrimShape += m_sceneGraph.UpdatePrimShape;
  2783. client.OnUpdatePrimTexture += m_sceneGraph.UpdatePrimTexture;
  2784. client.OnObjectRequest += RequestPrim;
  2785. client.OnObjectSelect += SelectPrim;
  2786. client.OnObjectDeselect += DeselectPrim;
  2787. client.OnDeRezObject += DeRezObjects;
  2788. client.OnObjectName += m_sceneGraph.PrimName;
  2789. client.OnObjectClickAction += m_sceneGraph.PrimClickAction;
  2790. client.OnObjectMaterial += m_sceneGraph.PrimMaterial;
  2791. client.OnLinkObjects += LinkObjects;
  2792. client.OnDelinkObjects += DelinkObjects;
  2793. client.OnObjectDuplicate += DuplicateObject;
  2794. client.OnObjectDuplicateOnRay += doObjectDuplicateOnRay;
  2795. client.OnUpdatePrimFlags += m_sceneGraph.UpdatePrimFlags;
  2796. client.OnRequestObjectPropertiesFamily += m_sceneGraph.RequestObjectPropertiesFamily;
  2797. client.OnObjectPermissions += HandleObjectPermissionsUpdate;
  2798. client.OnGrabObject += ProcessObjectGrab;
  2799. client.OnGrabUpdate += ProcessObjectGrabUpdate;
  2800. client.OnDeGrabObject += ProcessObjectDeGrab;
  2801. client.OnSpinStart += ProcessSpinStart;
  2802. client.OnSpinUpdate += ProcessSpinObject;
  2803. client.OnSpinStop += ProcessSpinObjectStop;
  2804. client.OnUndo += m_sceneGraph.HandleUndo;
  2805. client.OnRedo += m_sceneGraph.HandleRedo;
  2806. client.OnObjectDescription += m_sceneGraph.PrimDescription;
  2807. client.OnObjectIncludeInSearch += m_sceneGraph.MakeObjectSearchable;
  2808. client.OnObjectOwner += ObjectOwner;
  2809. client.OnObjectGroupRequest += HandleObjectGroupUpdate;
  2810. }
  2811. public virtual void SubscribeToClientPrimRezEvents(IClientAPI client)
  2812. {
  2813. client.OnAddPrim += AddNewPrim;
  2814. client.OnRezObject += RezObject;
  2815. }
  2816. public virtual void SubscribeToClientInventoryEvents(IClientAPI client)
  2817. {
  2818. client.OnLinkInventoryItem += HandleLinkInventoryItem;
  2819. client.OnCreateNewInventoryFolder += HandleCreateInventoryFolder;
  2820. client.OnUpdateInventoryFolder += HandleUpdateInventoryFolder;
  2821. client.OnMoveInventoryFolder += HandleMoveInventoryFolder; // 2; //!!
  2822. client.OnFetchInventoryDescendents += HandleFetchInventoryDescendents;
  2823. client.OnPurgeInventoryDescendents += HandlePurgeInventoryDescendents; // 2; //!!
  2824. client.OnFetchInventory += m_asyncInventorySender.HandleFetchInventory;
  2825. client.OnUpdateInventoryItem += UpdateInventoryItemAsset;
  2826. client.OnCopyInventoryItem += CopyInventoryItem;
  2827. client.OnMoveItemsAndLeaveCopy += MoveInventoryItemsLeaveCopy;
  2828. client.OnMoveInventoryItem += MoveInventoryItem;
  2829. client.OnRemoveInventoryItem += RemoveInventoryItem;
  2830. client.OnRemoveInventoryFolder += RemoveInventoryFolder;
  2831. client.OnRezScript += RezScript;
  2832. client.OnRequestTaskInventory += RequestTaskInventory;
  2833. client.OnRemoveTaskItem += RemoveTaskInventory;
  2834. client.OnUpdateTaskInventory += UpdateTaskInventory;
  2835. client.OnMoveTaskItem += ClientMoveTaskInventoryItem;
  2836. }
  2837. public virtual void SubscribeToClientTeleportEvents(IClientAPI client)
  2838. {
  2839. client.OnTeleportLocationRequest += RequestTeleportLocation;
  2840. }
  2841. public virtual void SubscribeToClientScriptEvents(IClientAPI client)
  2842. {
  2843. client.OnScriptReset += ProcessScriptReset;
  2844. client.OnGetScriptRunning += GetScriptRunning;
  2845. client.OnSetScriptRunning += SetScriptRunning;
  2846. }
  2847. public virtual void SubscribeToClientParcelEvents(IClientAPI client)
  2848. {
  2849. client.OnParcelReturnObjectsRequest += LandChannel.ReturnObjectsInParcel;
  2850. client.OnParcelSetOtherCleanTime += LandChannel.SetParcelOtherCleanTime;
  2851. client.OnParcelBuy += ProcessParcelBuy;
  2852. }
  2853. public virtual void SubscribeToClientGridEvents(IClientAPI client)
  2854. {
  2855. //client.OnNameFromUUIDRequest += HandleUUIDNameRequest;
  2856. client.OnMoneyTransferRequest += ProcessMoneyTransferRequest;
  2857. }
  2858. public virtual void SubscribeToClientNetworkEvents(IClientAPI client)
  2859. {
  2860. client.OnNetworkStatsUpdate += StatsReporter.AddPacketsStats;
  2861. client.OnViewerEffect += ProcessViewerEffect;
  2862. }
  2863. /// <summary>
  2864. /// Unsubscribe the client from events.
  2865. /// </summary>
  2866. /// FIXME: Not called anywhere!
  2867. /// <param name="client">The IClientAPI of the client</param>
  2868. public virtual void UnSubscribeToClientEvents(IClientAPI client)
  2869. {
  2870. UnSubscribeToClientTerrainEvents(client);
  2871. UnSubscribeToClientPrimEvents(client);
  2872. UnSubscribeToClientPrimRezEvents(client);
  2873. UnSubscribeToClientInventoryEvents(client);
  2874. UnSubscribeToClientTeleportEvents(client);
  2875. UnSubscribeToClientScriptEvents(client);
  2876. UnSubscribeToClientParcelEvents(client);
  2877. UnSubscribeToClientGridEvents(client);
  2878. UnSubscribeToClientNetworkEvents(client);
  2879. }
  2880. public virtual void UnSubscribeToClientTerrainEvents(IClientAPI client)
  2881. {
  2882. // client.OnRegionHandShakeReply -= SendLayerData;
  2883. }
  2884. public virtual void UnSubscribeToClientPrimEvents(IClientAPI client)
  2885. {
  2886. client.OnUpdatePrimGroupPosition -= m_sceneGraph.UpdatePrimGroupPosition;
  2887. client.OnUpdatePrimSinglePosition -= m_sceneGraph.UpdatePrimSinglePosition;
  2888. client.onClientChangeObject -= m_sceneGraph.ClientChangeObject;
  2889. client.OnUpdatePrimGroupRotation -= m_sceneGraph.UpdatePrimGroupRotation;
  2890. client.OnUpdatePrimGroupMouseRotation -= m_sceneGraph.UpdatePrimGroupRotation;
  2891. client.OnUpdatePrimSingleRotation -= m_sceneGraph.UpdatePrimSingleRotation;
  2892. client.OnUpdatePrimSingleRotationPosition -= m_sceneGraph.UpdatePrimSingleRotationPosition;
  2893. client.OnUpdatePrimScale -= m_sceneGraph.UpdatePrimScale;
  2894. client.OnUpdatePrimGroupScale -= m_sceneGraph.UpdatePrimGroupScale;
  2895. client.OnUpdateExtraParams -= m_sceneGraph.UpdateExtraParam;
  2896. client.OnUpdatePrimShape -= m_sceneGraph.UpdatePrimShape;
  2897. client.OnUpdatePrimTexture -= m_sceneGraph.UpdatePrimTexture;
  2898. client.OnObjectRequest -= RequestPrim;
  2899. client.OnObjectSelect -= SelectPrim;
  2900. client.OnObjectDeselect -= DeselectPrim;
  2901. client.OnDeRezObject -= DeRezObjects;
  2902. client.OnObjectName -= m_sceneGraph.PrimName;
  2903. client.OnObjectClickAction -= m_sceneGraph.PrimClickAction;
  2904. client.OnObjectMaterial -= m_sceneGraph.PrimMaterial;
  2905. client.OnLinkObjects -= LinkObjects;
  2906. client.OnDelinkObjects -= DelinkObjects;
  2907. client.OnObjectDuplicate -= DuplicateObject;
  2908. client.OnObjectDuplicateOnRay -= doObjectDuplicateOnRay;
  2909. client.OnUpdatePrimFlags -= m_sceneGraph.UpdatePrimFlags;
  2910. client.OnRequestObjectPropertiesFamily -= m_sceneGraph.RequestObjectPropertiesFamily;
  2911. client.OnObjectPermissions -= HandleObjectPermissionsUpdate;
  2912. client.OnGrabObject -= ProcessObjectGrab;
  2913. client.OnGrabUpdate -= ProcessObjectGrabUpdate;
  2914. client.OnDeGrabObject -= ProcessObjectDeGrab;
  2915. client.OnSpinStart -= ProcessSpinStart;
  2916. client.OnSpinUpdate -= ProcessSpinObject;
  2917. client.OnSpinStop -= ProcessSpinObjectStop;
  2918. client.OnUndo -= m_sceneGraph.HandleUndo;
  2919. client.OnRedo -= m_sceneGraph.HandleRedo;
  2920. client.OnObjectDescription -= m_sceneGraph.PrimDescription;
  2921. client.OnObjectIncludeInSearch -= m_sceneGraph.MakeObjectSearchable;
  2922. client.OnObjectOwner -= ObjectOwner;
  2923. }
  2924. public virtual void UnSubscribeToClientPrimRezEvents(IClientAPI client)
  2925. {
  2926. client.OnAddPrim -= AddNewPrim;
  2927. client.OnRezObject -= RezObject;
  2928. }
  2929. public virtual void UnSubscribeToClientInventoryEvents(IClientAPI client)
  2930. {
  2931. client.OnCreateNewInventoryFolder -= HandleCreateInventoryFolder;
  2932. client.OnUpdateInventoryFolder -= HandleUpdateInventoryFolder;
  2933. client.OnMoveInventoryFolder -= HandleMoveInventoryFolder; // 2; //!!
  2934. client.OnFetchInventoryDescendents -= HandleFetchInventoryDescendents;
  2935. client.OnPurgeInventoryDescendents -= HandlePurgeInventoryDescendents; // 2; //!!
  2936. client.OnFetchInventory -= m_asyncInventorySender.HandleFetchInventory;
  2937. client.OnUpdateInventoryItem -= UpdateInventoryItemAsset;
  2938. client.OnCopyInventoryItem -= CopyInventoryItem;
  2939. client.OnMoveInventoryItem -= MoveInventoryItem;
  2940. client.OnRemoveInventoryItem -= RemoveInventoryItem;
  2941. client.OnRemoveInventoryFolder -= RemoveInventoryFolder;
  2942. client.OnRezScript -= RezScript;
  2943. client.OnRequestTaskInventory -= RequestTaskInventory;
  2944. client.OnRemoveTaskItem -= RemoveTaskInventory;
  2945. client.OnUpdateTaskInventory -= UpdateTaskInventory;
  2946. client.OnMoveTaskItem -= ClientMoveTaskInventoryItem;
  2947. }
  2948. public virtual void UnSubscribeToClientTeleportEvents(IClientAPI client)
  2949. {
  2950. client.OnTeleportLocationRequest -= RequestTeleportLocation;
  2951. //client.OnTeleportLandmarkRequest -= RequestTeleportLandmark;
  2952. //client.OnTeleportHomeRequest -= TeleportClientHome;
  2953. }
  2954. public virtual void UnSubscribeToClientScriptEvents(IClientAPI client)
  2955. {
  2956. client.OnScriptReset -= ProcessScriptReset;
  2957. client.OnGetScriptRunning -= GetScriptRunning;
  2958. client.OnSetScriptRunning -= SetScriptRunning;
  2959. }
  2960. public virtual void UnSubscribeToClientParcelEvents(IClientAPI client)
  2961. {
  2962. client.OnParcelReturnObjectsRequest -= LandChannel.ReturnObjectsInParcel;
  2963. client.OnParcelSetOtherCleanTime -= LandChannel.SetParcelOtherCleanTime;
  2964. client.OnParcelBuy -= ProcessParcelBuy;
  2965. }
  2966. public virtual void UnSubscribeToClientGridEvents(IClientAPI client)
  2967. {
  2968. //client.OnNameFromUUIDRequest -= HandleUUIDNameRequest;
  2969. client.OnMoneyTransferRequest -= ProcessMoneyTransferRequest;
  2970. }
  2971. public virtual void UnSubscribeToClientNetworkEvents(IClientAPI client)
  2972. {
  2973. client.OnNetworkStatsUpdate -= StatsReporter.AddPacketsStats;
  2974. client.OnViewerEffect -= ProcessViewerEffect;
  2975. }
  2976. /// <summary>
  2977. /// Teleport an avatar to their home region
  2978. /// </summary>
  2979. /// <param name="agentId">The avatar's Unique ID</param>
  2980. /// <param name="client">The IClientAPI for the client</param>
  2981. public virtual bool TeleportClientHome(UUID agentId, IClientAPI client)
  2982. {
  2983. if (EntityTransferModule != null)
  2984. {
  2985. return EntityTransferModule.TeleportHome(agentId, client);
  2986. }
  2987. else
  2988. {
  2989. m_log.DebugFormat("[SCENE]: Unable to teleport user home: no AgentTransferModule is active");
  2990. client.SendTeleportFailed("Unable to perform teleports on this simulator.");
  2991. }
  2992. return false;
  2993. }
  2994. /// <summary>
  2995. /// Duplicates object specified by localID. This is the event handler for IClientAPI.
  2996. /// </summary>
  2997. /// <param name="originalPrim">ID of object to duplicate</param>
  2998. /// <param name="offset"></param>
  2999. /// <param name="flags"></param>
  3000. /// <param name="AgentID">Agent doing the duplication</param>
  3001. /// <param name="GroupID">Group of new object</param>
  3002. public void DuplicateObject(uint originalPrim, Vector3 offset, uint flags, UUID AgentID, UUID GroupID)
  3003. {
  3004. bool createSelected = (flags & (uint)PrimFlags.CreateSelected) != 0;
  3005. SceneObjectGroup copy = SceneGraph.DuplicateObject(originalPrim, offset, AgentID,
  3006. GroupID, Quaternion.Identity, createSelected);
  3007. if (copy != null)
  3008. EventManager.TriggerObjectAddedToScene(copy);
  3009. }
  3010. /// <summary>
  3011. /// Duplicates object specified by localID at position raycasted against RayTargetObject using
  3012. /// RayEnd and RayStart to determine what the angle of the ray is
  3013. /// </summary>
  3014. /// <param name="localID">ID of object to duplicate</param>
  3015. /// <param name="dupeFlags"></param>
  3016. /// <param name="AgentID">Agent doing the duplication</param>
  3017. /// <param name="GroupID">Group of new object</param>
  3018. /// <param name="RayTargetObj">The target of the Ray</param>
  3019. /// <param name="RayEnd">The ending of the ray (farthest away point)</param>
  3020. /// <param name="RayStart">The Beginning of the ray (closest point)</param>
  3021. /// <param name="BypassRaycast">Bool to bypass raycasting</param>
  3022. /// <param name="RayEndIsIntersection">The End specified is the place to add the object</param>
  3023. /// <param name="CopyCenters">Position the object at the center of the face that it's colliding with</param>
  3024. /// <param name="CopyRotates">Rotate the object the same as the localID object</param>
  3025. public void doObjectDuplicateOnRay(uint localID, uint dupeFlags, UUID AgentID, UUID GroupID,
  3026. UUID RayTargetObj, Vector3 RayEnd, Vector3 RayStart,
  3027. bool BypassRaycast, bool RayEndIsIntersection, bool CopyCenters, bool CopyRotates)
  3028. {
  3029. Vector3 pos;
  3030. const bool frontFacesOnly = true;
  3031. //m_log.Info("HITTARGET: " + RayTargetObj.ToString() + ", COPYTARGET: " + localID.ToString());
  3032. SceneObjectPart target = GetSceneObjectPart(localID);
  3033. SceneObjectPart target2 = GetSceneObjectPart(RayTargetObj);
  3034. bool createSelected = (dupeFlags & (uint)PrimFlags.CreateSelected) != 0;
  3035. if (target != null && target2 != null)
  3036. {
  3037. Vector3 direction = Vector3.Normalize(RayEnd - RayStart);
  3038. pos = target2.AbsolutePosition;
  3039. //m_log.Info("[OBJECT_REZ]: TargetPos: " + pos.ToString() + ", RayStart: " + RayStart.ToString() + ", RayEnd: " + RayEnd.ToString() + ", Volume: " + Util.GetDistanceTo(RayStart,RayEnd).ToString() + ", mag1: " + Util.GetMagnitude(RayStart).ToString() + ", mag2: " + Util.GetMagnitude(RayEnd).ToString());
  3040. // TODO: Raytrace better here
  3041. //EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection));
  3042. Ray NewRay = new Ray(RayStart,direction);
  3043. // Ray Trace against target here
  3044. EntityIntersection ei = target2.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, CopyCenters);
  3045. // Un-comment out the following line to Get Raytrace results printed to the console.
  3046. //m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  3047. float ScaleOffset = 0.5f;
  3048. // If we hit something
  3049. if (ei.HitTF)
  3050. {
  3051. Vector3 scale = target.Scale;
  3052. Vector3 scaleComponent = ei.AAfaceNormal;
  3053. if (scaleComponent.X != 0) ScaleOffset = scale.X;
  3054. if (scaleComponent.Y != 0) ScaleOffset = scale.Y;
  3055. if (scaleComponent.Z != 0) ScaleOffset = scale.Z;
  3056. ScaleOffset = Math.Abs(ScaleOffset);
  3057. Vector3 intersectionpoint = ei.ipoint;
  3058. Vector3 normal = ei.normal;
  3059. Vector3 offset = normal * (ScaleOffset / 2f);
  3060. pos = intersectionpoint + offset;
  3061. // stick in offset format from the original prim
  3062. pos = pos - target.ParentGroup.AbsolutePosition;
  3063. SceneObjectGroup copy;
  3064. if (CopyRotates)
  3065. {
  3066. Quaternion worldRot = target2.GetWorldRotation();
  3067. // SceneObjectGroup obj = m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID, worldRot);
  3068. copy = m_sceneGraph.DuplicateObject(localID, pos, AgentID, GroupID, worldRot, createSelected);
  3069. //obj.Rotation = worldRot;
  3070. //obj.UpdateGroupRotationR(worldRot);
  3071. }
  3072. else
  3073. {
  3074. copy = m_sceneGraph.DuplicateObject(localID, pos, AgentID, GroupID, Quaternion.Identity, createSelected);
  3075. }
  3076. if (copy != null)
  3077. EventManager.TriggerObjectAddedToScene(copy);
  3078. }
  3079. }
  3080. }
  3081. /// <summary>
  3082. /// Get the avatar appearance for the given client.
  3083. /// </summary>
  3084. /// <param name="client"></param>
  3085. /// <param name="appearance"></param>
  3086. public void GetAvatarAppearance(IClientAPI client, out AvatarAppearance appearance)
  3087. {
  3088. AgentCircuitData aCircuit = m_authenticateHandler.GetAgentCircuitData(client.CircuitCode);
  3089. if (aCircuit == null)
  3090. {
  3091. m_log.DebugFormat("[APPEARANCE] Client did not supply a circuit. Non-Linden? Creating default appearance.");
  3092. appearance = new AvatarAppearance();
  3093. return;
  3094. }
  3095. appearance = aCircuit.Appearance;
  3096. if (appearance == null)
  3097. {
  3098. m_log.DebugFormat("[APPEARANCE]: Appearance not found in {0}, returning default", RegionInfo.RegionName);
  3099. appearance = new AvatarAppearance();
  3100. }
  3101. }
  3102. /// <summary>
  3103. /// Remove the given client from the scene.
  3104. /// </summary>
  3105. /// <remarks>
  3106. /// Only clientstack code should call this directly. All other code should call IncomingCloseAgent() instead
  3107. /// to properly operate the state machine and avoid race conditions with other close requests (such as directly
  3108. /// from viewers).
  3109. /// </remarks>
  3110. /// <param name='agentID'>ID of agent to close</param>
  3111. /// <param name='closeChildAgents'>
  3112. /// Close the neighbour child agents associated with this client.
  3113. /// </param>
  3114. ///
  3115. private object m_removeClientPrivLock = new Object();
  3116. public void RemoveClient(UUID agentID, bool closeChildAgents)
  3117. {
  3118. AgentCircuitData acd = m_authenticateHandler.GetAgentCircuitData(agentID);
  3119. // Shouldn't be necessary since RemoveClient() is currently only called by IClientAPI.Close() which
  3120. // in turn is only called by Scene.IncomingCloseAgent() which checks whether the presence exists or not
  3121. // However, will keep for now just in case.
  3122. if (acd == null)
  3123. {
  3124. m_log.ErrorFormat(
  3125. "[SCENE]: No agent circuit found for {0} in {1}, aborting Scene.RemoveClient", agentID, Name);
  3126. return;
  3127. }
  3128. // TODO: Can we now remove this lock?
  3129. lock (m_removeClientPrivLock)
  3130. {
  3131. bool isChildAgent = false;
  3132. ScenePresence avatar = GetScenePresence(agentID);
  3133. // Shouldn't be necessary since RemoveClient() is currently only called by IClientAPI.Close() which
  3134. // in turn is only called by Scene.IncomingCloseAgent() which checks whether the presence exists or not
  3135. // However, will keep for now just in case.
  3136. if (avatar == null)
  3137. {
  3138. m_log.ErrorFormat(
  3139. "[SCENE]: Called RemoveClient() with agent ID {0} but no such presence is in the scene.", agentID);
  3140. m_authenticateHandler.RemoveCircuit(agentID);
  3141. return;
  3142. }
  3143. try
  3144. {
  3145. isChildAgent = avatar.IsChildAgent;
  3146. m_log.DebugFormat(
  3147. "[SCENE]: Removing {0} agent {1} {2} from {3}",
  3148. isChildAgent ? "child" : "root", avatar.Name, agentID, Name);
  3149. // Don't do this to root agents, it's not nice for the viewer
  3150. if (closeChildAgents && isChildAgent)
  3151. {
  3152. // Tell a single agent to disconnect from the region.
  3153. // Let's do this via UDP
  3154. avatar.ControllingClient.SendShutdownConnectionNotice();
  3155. }
  3156. // Only applies to root agents.
  3157. if (avatar.ParentID != 0)
  3158. {
  3159. avatar.StandUp();
  3160. }
  3161. m_sceneGraph.removeUserCount(!isChildAgent);
  3162. // TODO: We shouldn't use closeChildAgents here - it's being used by the NPC module to stop
  3163. // unnecessary operations. This should go away once NPCs have no accompanying IClientAPI
  3164. if (closeChildAgents && CapsModule != null)
  3165. CapsModule.RemoveCaps(agentID, avatar.ControllingClient.CircuitCode);
  3166. if (closeChildAgents && !isChildAgent)
  3167. {
  3168. List<ulong> regions = avatar.KnownRegionHandles;
  3169. regions.Remove(RegionInfo.RegionHandle);
  3170. // This ends up being done asynchronously so that a logout isn't held up where there are many present but unresponsive neighbours.
  3171. m_sceneGridService.SendCloseChildAgentConnections(agentID, acd.SessionID.ToString(), regions);
  3172. }
  3173. m_eventManager.TriggerClientClosed(agentID, this);
  3174. // m_log.Debug("[Scene]TriggerClientClosed done");
  3175. m_eventManager.TriggerOnRemovePresence(agentID);
  3176. // m_log.Debug("[Scene]TriggerOnRemovePresence done");
  3177. if (!isChildAgent)
  3178. {
  3179. if (AttachmentsModule != null)
  3180. {
  3181. // m_log.Debug("[Scene]DeRezAttachments");
  3182. AttachmentsModule.DeRezAttachments(avatar);
  3183. // m_log.Debug("[Scene]DeRezAttachments done");
  3184. }
  3185. ForEachClient(
  3186. delegate(IClientAPI client)
  3187. {
  3188. //We can safely ignore null reference exceptions. It means the avatar is dead and cleaned up anyway
  3189. try { client.SendKillObject(new List<uint> { avatar.LocalId }); }
  3190. catch (NullReferenceException) { }
  3191. });
  3192. }
  3193. // It's possible for child agents to have transactions if changes are being made cross-border.
  3194. if (AgentTransactionsModule != null)
  3195. {
  3196. // m_log.Debug("[Scene]RemoveAgentAssetTransactions");
  3197. AgentTransactionsModule.RemoveAgentAssetTransactions(agentID);
  3198. }
  3199. m_log.Debug("[Scene] The avatar has left the building");
  3200. }
  3201. catch (Exception e)
  3202. {
  3203. m_log.Error(
  3204. string.Format("[SCENE]: Exception removing {0} from {1}. Cleaning up. Exception ", avatar.Name, Name), e);
  3205. }
  3206. finally
  3207. {
  3208. try
  3209. {
  3210. // Always clean these structures up so that any failure above doesn't cause them to remain in the
  3211. // scene with possibly bad effects (e.g. continually timing out on unacked packets and triggering
  3212. // the same cleanup exception continually.
  3213. m_authenticateHandler.RemoveCircuit(agentID);
  3214. m_sceneGraph.RemoveScenePresence(agentID);
  3215. m_clientManager.Remove(agentID);
  3216. avatar.Close();
  3217. }
  3218. catch (Exception e)
  3219. {
  3220. m_log.Error(
  3221. string.Format("[SCENE]: Exception in final clean up of {0} in {1}. Exception ", avatar.Name, Name), e);
  3222. }
  3223. }
  3224. }
  3225. //m_log.InfoFormat("[SCENE] Memory pre GC {0}", System.GC.GetTotalMemory(false));
  3226. //m_log.InfoFormat("[SCENE] Memory post GC {0}", System.GC.GetTotalMemory(true));
  3227. }
  3228. /// <summary>
  3229. /// Removes region from an avatar's known region list. This coincides with child agents. For each child agent, there will be a known region entry.
  3230. ///
  3231. /// </summary>
  3232. /// <param name="avatarID"></param>
  3233. /// <param name="regionslst"></param>
  3234. public void HandleRemoveKnownRegionsFromAvatar(UUID avatarID, List<ulong> regionslst)
  3235. {
  3236. ScenePresence av = GetScenePresence(avatarID);
  3237. if (av != null)
  3238. {
  3239. lock (av)
  3240. {
  3241. for (int i = 0; i < regionslst.Count; i++)
  3242. {
  3243. av.RemoveNeighbourRegion(regionslst[i]);
  3244. }
  3245. }
  3246. }
  3247. }
  3248. #endregion
  3249. #region Entities
  3250. public void SendKillObject(List<uint> localIDs)
  3251. {
  3252. List<uint> deleteIDs = new List<uint>();
  3253. foreach (uint localID in localIDs)
  3254. {
  3255. SceneObjectPart part = GetSceneObjectPart(localID);
  3256. if (part != null && part.ParentGroup != null &&
  3257. part.ParentGroup.RootPart == part)
  3258. deleteIDs.Add(localID);
  3259. }
  3260. ForEachClient(c => c.SendKillObject(deleteIDs));
  3261. }
  3262. #endregion
  3263. #region RegionComms
  3264. /// <summary>
  3265. /// Do the work necessary to initiate a new user connection for a particular scene.
  3266. /// </summary>
  3267. /// <param name="agent">CircuitData of the agent who is connecting</param>
  3268. /// <param name="teleportFlags"></param>
  3269. /// <param name="source">Source region (may be null)</param>
  3270. /// <param name="reason">Outputs the reason for the false response on this string</param>
  3271. /// <returns>True if the region accepts this agent. False if it does not. False will
  3272. /// also return a reason.</returns>
  3273. public bool NewUserConnection(AgentCircuitData agent, uint teleportFlags, GridRegion source, out string reason)
  3274. {
  3275. return NewUserConnection(agent, teleportFlags, source, out reason, true);
  3276. }
  3277. /// <summary>
  3278. /// Do the work necessary to initiate a new user connection for a particular scene.
  3279. /// </summary>
  3280. /// <remarks>
  3281. /// The return bool should allow for connections to be refused, but as not all calling paths
  3282. /// take proper notice of it yet, we still allowed banned users in.
  3283. ///
  3284. /// At the moment this method consists of setting up the caps infrastructure
  3285. /// The return bool should allow for connections to be refused, but as not all calling paths
  3286. /// take proper notice of it let, we allowed banned users in still.
  3287. ///
  3288. /// This method is called by the login service (in the case of login) or another simulator (in the case of region
  3289. /// cross or teleport) to initiate the connection. It is not triggered by the viewer itself - the connection
  3290. /// is activated later when the viewer sends the initial UseCircuitCodePacket UDP packet (in the case of
  3291. /// the LLUDP stack).
  3292. /// </remarks>
  3293. /// <param name="acd">CircuitData of the agent who is connecting</param>
  3294. /// <param name="source">Source region (may be null)</param>
  3295. /// <param name="reason">Outputs the reason for the false response on this string</param>
  3296. /// <param name="requirePresenceLookup">True for normal presence. False for NPC
  3297. /// or other applications where a full grid/Hypergrid presence may not be required.</param>
  3298. /// <returns>True if the region accepts this agent. False if it does not. False will
  3299. /// also return a reason.</returns>
  3300. ///
  3301. private object m_newUserConnLock = new object();
  3302. public bool NewUserConnection(AgentCircuitData acd, uint teleportFlags, GridRegion source, out string reason, bool requirePresenceLookup)
  3303. {
  3304. bool vialogin = ((teleportFlags & (uint)TPFlags.ViaLogin) != 0 ||
  3305. (teleportFlags & (uint)TPFlags.ViaHGLogin) != 0);
  3306. bool viahome = ((teleportFlags & (uint)TPFlags.ViaHome) != 0);
  3307. // bool godlike = ((teleportFlags & (uint)TPFlags.Godlike) != 0);
  3308. reason = String.Empty;
  3309. //Teleport flags:
  3310. //
  3311. // TeleportFlags.ViaGodlikeLure - Border Crossing
  3312. // TeleportFlags.ViaLogin - Login
  3313. // TeleportFlags.TeleportFlags.ViaLure - Teleport request sent by another user
  3314. // TeleportFlags.ViaLandmark | TeleportFlags.ViaLocation | TeleportFlags.ViaLandmark | TeleportFlags.Default - Regular Teleport
  3315. // Don't disable this log message - it's too helpful
  3316. string curViewer = Util.GetViewerName(acd);
  3317. m_log.DebugFormat(
  3318. "[SCENE]: Region {0} told of incoming {1} agent {2} {3} {4} (circuit code {5}, IP {6}, viewer {7}, teleportflags ({8}), position {9}. {10}",
  3319. RegionInfo.RegionName,
  3320. (acd.child ? "child" : "root"),
  3321. acd.firstname,
  3322. acd.lastname,
  3323. acd.AgentID,
  3324. acd.circuitcode,
  3325. acd.IPAddress,
  3326. curViewer,
  3327. ((TPFlags)teleportFlags).ToString(),
  3328. acd.startpos,
  3329. (source == null) ? "" : string.Format("From region {0} ({1}){2}", source.RegionName, source.RegionID, (source.RawServerURI == null) ? "" : " @ " + source.ServerURI)
  3330. );
  3331. // m_log.DebugFormat("NewUserConnection stack {0}", Environment.StackTrace);
  3332. if (!LoginsEnabled)
  3333. {
  3334. reason = "Logins to this region are disabled";
  3335. return false;
  3336. }
  3337. //Check if the viewer is banned or in the viewer access list
  3338. //We check if the substring is listed for higher flexebility
  3339. bool ViewerDenied = true;
  3340. //Check if the specific viewer is listed in the allowed viewer list
  3341. if (m_AllowedViewers.Count > 0)
  3342. {
  3343. foreach (string viewer in m_AllowedViewers)
  3344. {
  3345. if (viewer == curViewer.Substring(0, Math.Min(viewer.Length, curViewer.Length)).Trim().ToLower())
  3346. {
  3347. ViewerDenied = false;
  3348. break;
  3349. }
  3350. }
  3351. }
  3352. else
  3353. {
  3354. ViewerDenied = false;
  3355. }
  3356. //Check if the viewer is in the banned list
  3357. if (m_BannedViewers.Count > 0)
  3358. {
  3359. foreach (string viewer in m_BannedViewers)
  3360. {
  3361. if (viewer == curViewer.Substring(0, Math.Min(viewer.Length, curViewer.Length)).Trim().ToLower())
  3362. {
  3363. ViewerDenied = true;
  3364. break;
  3365. }
  3366. }
  3367. }
  3368. if (ViewerDenied)
  3369. {
  3370. m_log.DebugFormat(
  3371. "[SCENE]: Access denied for {0} {1} using {2}",
  3372. acd.firstname, acd.lastname, curViewer);
  3373. reason = "Access denied, your viewer is banned by the region owner";
  3374. return false;
  3375. }
  3376. ScenePresence sp;
  3377. lock (m_removeClientLock)
  3378. {
  3379. sp = GetScenePresence(acd.AgentID);
  3380. // We need to ensure that we are not already removing the scene presence before we ask it not to be
  3381. // closed.
  3382. if (sp != null && sp.IsChildAgent
  3383. && (sp.LifecycleState == ScenePresenceState.Running
  3384. || sp.LifecycleState == ScenePresenceState.PreRemove))
  3385. {
  3386. m_log.DebugFormat(
  3387. "[SCENE]: Reusing existing child scene presence for {0}, state {1} in {2}",
  3388. sp.Name, sp.LifecycleState, Name);
  3389. // In the case where, for example, an A B C D region layout, an avatar may
  3390. // teleport from A -> D, but then -> C before A has asked B to close its old child agent. When C
  3391. // renews the lease on the child agent at B, we must make sure that the close from A does not succeed.
  3392. //
  3393. // XXX: In the end, this should not be necessary if child agents are closed without delay on
  3394. // teleport, since realistically, the close request should always be processed before any other
  3395. // region tried to re-establish a child agent. This is much simpler since the logic below is
  3396. // vulnerable to an issue when a viewer quits a region without sending a proper logout but then
  3397. // re-establishes the connection on a relogin. This could wrongly set the DoNotCloseAfterTeleport
  3398. // flag when no teleport had taken place (and hence no close was going to come).
  3399. // if (!acd.ChildrenCapSeeds.ContainsKey(RegionInfo.RegionHandle))
  3400. // {
  3401. // m_log.DebugFormat(
  3402. // "[SCENE]: Setting DoNotCloseAfterTeleport for child scene presence {0} in {1} because source will attempt close.",
  3403. // sp.Name, Name);
  3404. //
  3405. // sp.DoNotCloseAfterTeleport = true;
  3406. // }
  3407. // else if (EntityTransferModule.IsInTransit(sp.UUID))
  3408. sp.LifecycleState = ScenePresenceState.Running;
  3409. if (EntityTransferModule.IsInTransit(sp.UUID))
  3410. {
  3411. sp.DoNotCloseAfterTeleport = true;
  3412. m_log.DebugFormat(
  3413. "[SCENE]: Set DoNotCloseAfterTeleport for child scene presence {0} in {1} because this region will attempt end-of-teleport close from a previous close.",
  3414. sp.Name, Name);
  3415. }
  3416. }
  3417. }
  3418. // Need to poll here in case we are currently deleting an sp. Letting threads run over each other will
  3419. // allow unpredictable things to happen.
  3420. if (sp != null)
  3421. {
  3422. const int polls = 10;
  3423. const int pollInterval = 1000;
  3424. int pollsLeft = polls;
  3425. while (sp.LifecycleState == ScenePresenceState.Removing && pollsLeft-- > 0)
  3426. Thread.Sleep(pollInterval);
  3427. if (sp.LifecycleState == ScenePresenceState.Removing)
  3428. {
  3429. m_log.WarnFormat(
  3430. "[SCENE]: Agent {0} in {1} was still being removed after {2}s. Aborting NewUserConnection.",
  3431. sp.Name, Name, polls * pollInterval / 1000);
  3432. return false;
  3433. }
  3434. else if (polls != pollsLeft)
  3435. {
  3436. m_log.DebugFormat(
  3437. "[SCENE]: NewUserConnection for agent {0} in {1} had to wait {2}s for in-progress removal to complete on an old presence.",
  3438. sp.Name, Name, polls * pollInterval / 1000);
  3439. }
  3440. }
  3441. // TODO: can we remove this lock?
  3442. lock (m_newUserConnLock)
  3443. {
  3444. if (sp != null && !sp.IsChildAgent)
  3445. {
  3446. // We have a root agent. Is it in transit?
  3447. if (!EntityTransferModule.IsInTransit(sp.UUID))
  3448. {
  3449. // We have a zombie from a crashed session.
  3450. // Or the same user is trying to be root twice here, won't work.
  3451. // Kill it.
  3452. m_log.WarnFormat(
  3453. "[SCENE]: Existing root scene presence detected for {0} {1} in {2} when connecting. Removing existing presence.",
  3454. sp.Name, sp.UUID, RegionInfo.RegionName);
  3455. if (sp.ControllingClient != null)
  3456. CloseAgent(sp.UUID, true);
  3457. sp = null;
  3458. }
  3459. //else
  3460. // m_log.WarnFormat("[SCENE]: Existing root scene presence for {0} {1} in {2}, but agent is in trasit", sp.Name, sp.UUID, RegionInfo.RegionName);
  3461. }
  3462. // Optimistic: add or update the circuit data with the new agent circuit data and teleport flags.
  3463. // We need the circuit data here for some of the subsequent checks. (groups, for example)
  3464. // If the checks fail, we remove the circuit.
  3465. acd.teleportFlags = teleportFlags;
  3466. if (vialogin)
  3467. {
  3468. IUserAccountCacheModule cache = RequestModuleInterface<IUserAccountCacheModule>();
  3469. if (cache != null)
  3470. // cache.Remove(acd.firstname + " " + acd.lastname);
  3471. cache.Remove(acd.AgentID);
  3472. // Remove any preexisting circuit - we don't want duplicates
  3473. // This is a stab at preventing avatar "ghosting"
  3474. m_authenticateHandler.RemoveCircuit(acd.AgentID);
  3475. }
  3476. m_authenticateHandler.AddNewCircuit(acd.circuitcode, acd);
  3477. if (sp == null) // We don't have an [child] agent here already
  3478. {
  3479. if (requirePresenceLookup)
  3480. {
  3481. try
  3482. {
  3483. if (!VerifyUserPresence(acd, out reason))
  3484. {
  3485. m_authenticateHandler.RemoveCircuit(acd.circuitcode);
  3486. return false;
  3487. }
  3488. }
  3489. catch (Exception e)
  3490. {
  3491. m_log.ErrorFormat(
  3492. "[SCENE]: Exception verifying presence {0}{1}", e.Message, e.StackTrace);
  3493. m_authenticateHandler.RemoveCircuit(acd.circuitcode);
  3494. return false;
  3495. }
  3496. }
  3497. try
  3498. {
  3499. if (!AuthorizeUser(acd, (vialogin ? false : SeeIntoRegion), out reason))
  3500. {
  3501. m_authenticateHandler.RemoveCircuit(acd.circuitcode);
  3502. return false;
  3503. }
  3504. }
  3505. catch (Exception e)
  3506. {
  3507. m_log.ErrorFormat(
  3508. "[SCENE]: Exception authorizing user {0}{1}", e.Message, e.StackTrace);
  3509. m_authenticateHandler.RemoveCircuit(acd.circuitcode);
  3510. return false;
  3511. }
  3512. m_log.InfoFormat(
  3513. "[SCENE]: Region {0} authenticated and authorized incoming {1} agent {2} {3} {4} (circuit code {5})",
  3514. Name, (acd.child ? "child" : "root"), acd.firstname, acd.lastname,
  3515. acd.AgentID, acd.circuitcode);
  3516. if (CapsModule != null)
  3517. {
  3518. CapsModule.SetAgentCapsSeeds(acd);
  3519. CapsModule.CreateCaps(acd.AgentID, acd.circuitcode);
  3520. }
  3521. }
  3522. else
  3523. {
  3524. // Let the SP know how we got here. This has a lot of interesting
  3525. // uses down the line.
  3526. sp.TeleportFlags = (TPFlags)teleportFlags;
  3527. if (sp.IsChildAgent)
  3528. {
  3529. m_log.DebugFormat(
  3530. "[SCENE]: Adjusting known seeds for existing agent {0} in {1}",
  3531. acd.AgentID, RegionInfo.RegionName);
  3532. if (CapsModule != null)
  3533. {
  3534. CapsModule.SetAgentCapsSeeds(acd);
  3535. CapsModule.CreateCaps(acd.AgentID, acd.circuitcode);
  3536. }
  3537. sp.AdjustKnownSeeds();
  3538. }
  3539. }
  3540. // Try caching an incoming user name much earlier on to see if this helps with an issue
  3541. // where HG users are occasionally seen by others as "Unknown User" because their UUIDName
  3542. // request for the HG avatar appears to trigger before the user name is cached.
  3543. CacheUserName(null, acd);
  3544. }
  3545. if (CapsModule != null)
  3546. {
  3547. CapsModule.ActivateCaps(acd.circuitcode);
  3548. }
  3549. // if (vialogin)
  3550. // {
  3551. // CleanDroppedAttachments();
  3552. // }
  3553. if(teleportFlags != (uint) TPFlags.Default)
  3554. {
  3555. // Make sure root avatar position is in the region
  3556. if (acd.startpos.X < 0)
  3557. acd.startpos.X = 1f;
  3558. else if (acd.startpos.X >= RegionInfo.RegionSizeX)
  3559. acd.startpos.X = RegionInfo.RegionSizeX - 1f;
  3560. if (acd.startpos.Y < 0)
  3561. acd.startpos.Y = 1f;
  3562. else if (acd.startpos.Y >= RegionInfo.RegionSizeY)
  3563. acd.startpos.Y = RegionInfo.RegionSizeY - 1f;
  3564. }
  3565. // only check access, actual relocations will happen later on ScenePresence MakeRoot
  3566. // allow child agents creation
  3567. // if(!godlike && teleportFlags != (uint) TPFlags.Default)
  3568. if(teleportFlags != (uint) TPFlags.Default)
  3569. {
  3570. bool checkTeleHub;
  3571. // don't check hubs if via home or via lure
  3572. if((teleportFlags & (uint) TPFlags.ViaHome) != 0
  3573. || (teleportFlags & (uint) TPFlags.ViaLure) != 0)
  3574. checkTeleHub = false;
  3575. else
  3576. checkTeleHub = vialogin
  3577. || (TelehubAllowLandmarks == true ? false : ((teleportFlags & (uint)TPFlags.ViaLandmark) != 0 ))
  3578. || (teleportFlags & (uint) TPFlags.ViaLocation) != 0;
  3579. if(!CheckLandPositionAccess(acd.AgentID, true, checkTeleHub, acd.startpos, out reason))
  3580. {
  3581. m_authenticateHandler.RemoveCircuit(acd.circuitcode);
  3582. return false;
  3583. }
  3584. }
  3585. return true;
  3586. }
  3587. private bool IsPositionAllowed(UUID agentID, Vector3 pos, ref string reason)
  3588. {
  3589. ILandObject land = LandChannel.GetLandObject(pos);
  3590. if (land == null)
  3591. return true;
  3592. if (land.IsBannedFromLand(agentID) || land.IsRestrictedFromLand(agentID))
  3593. {
  3594. reason = "You are banned from the region.";
  3595. return false;
  3596. }
  3597. return true;
  3598. }
  3599. public bool TestLandRestrictions(UUID agentID, out string reason, ref float posX, ref float posY)
  3600. {
  3601. if (posX < 0)
  3602. posX = 0;
  3603. else if (posX >= RegionInfo.RegionSizeX)
  3604. posX = RegionInfo.RegionSizeX - 0.5f;
  3605. if (posY < 0)
  3606. posY = 0;
  3607. else if (posY >= RegionInfo.RegionSizeY)
  3608. posY = RegionInfo.RegionSizeY - 0.5f;
  3609. reason = String.Empty;
  3610. if (Permissions.IsGod(agentID))
  3611. return true;
  3612. ILandObject land = LandChannel.GetLandObject(posX, posY);
  3613. if (land == null)
  3614. return false;
  3615. bool banned = land.IsBannedFromLand(agentID);
  3616. bool restricted = land.IsRestrictedFromLand(agentID);
  3617. if (banned || restricted)
  3618. {
  3619. ILandObject nearestParcel = GetNearestAllowedParcel(agentID, posX, posY);
  3620. Vector2? newPosition = null;
  3621. if (nearestParcel != null)
  3622. {
  3623. //Move agent to nearest allowed
  3624. // Vector2 newPosition = GetParcelSafeCorner(nearestParcel);
  3625. newPosition = nearestParcel.GetNearestPoint(new Vector3(posX, posY,0));
  3626. }
  3627. if(newPosition == null)
  3628. {
  3629. if (banned)
  3630. {
  3631. reason = "Cannot regioncross into banned parcel.";
  3632. }
  3633. else
  3634. {
  3635. reason = String.Format("Denied access to private region {0}: You are not on the access list for that region.",
  3636. RegionInfo.RegionName);
  3637. }
  3638. return false;
  3639. }
  3640. else
  3641. {
  3642. posX = newPosition.Value.X;
  3643. posY = newPosition.Value.Y;
  3644. }
  3645. }
  3646. reason = "";
  3647. return true;
  3648. }
  3649. /// <summary>
  3650. /// Verifies that the user has a presence on the Grid
  3651. /// </summary>
  3652. /// <param name="agent">Circuit Data of the Agent we're verifying</param>
  3653. /// <param name="reason">Outputs the reason for the false response on this string</param>
  3654. /// <returns>True if the user has a session on the grid. False if it does not. False will
  3655. /// also return a reason.</returns>
  3656. public virtual bool VerifyUserPresence(AgentCircuitData agent, out string reason)
  3657. {
  3658. reason = String.Empty;
  3659. IPresenceService presence = RequestModuleInterface<IPresenceService>();
  3660. if (presence == null)
  3661. {
  3662. reason = String.Format("Failed to verify user presence in the grid for {0} {1} in region {2}. Presence service does not exist.", agent.firstname, agent.lastname, RegionInfo.RegionName);
  3663. return false;
  3664. }
  3665. OpenSim.Services.Interfaces.PresenceInfo pinfo = presence.GetAgent(agent.SessionID);
  3666. if (pinfo == null)
  3667. {
  3668. reason = String.Format("Failed to verify user presence in the grid for {0} {1}, access denied to region {2}.", agent.firstname, agent.lastname, RegionInfo.RegionName);
  3669. return false;
  3670. }
  3671. return true;
  3672. }
  3673. /// <summary>
  3674. /// Verify if the user can connect to this region. Checks the banlist and ensures that the region is set for public access
  3675. /// </summary>
  3676. /// <param name="agent">The circuit data for the agent</param>
  3677. /// <param name="reason">outputs the reason to this string</param>
  3678. /// <returns>True if the region accepts this agent. False if it does not. False will
  3679. /// also return a reason.</returns>
  3680. protected virtual bool AuthorizeUser(AgentCircuitData agent, bool bypassAccessControl, out string reason)
  3681. {
  3682. reason = String.Empty;
  3683. if (!m_strictAccessControl)
  3684. return true;
  3685. if (Permissions.IsGod(agent.AgentID))
  3686. return true;
  3687. if (AuthorizationService != null)
  3688. {
  3689. if (!AuthorizationService.IsAuthorizedForRegion(
  3690. agent.AgentID.ToString(), agent.firstname, agent.lastname, RegionInfo.RegionID.ToString(), out reason))
  3691. {
  3692. m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because: {4}",
  3693. agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName, reason);
  3694. return false;
  3695. }
  3696. }
  3697. // We only test the things below when we want to cut off
  3698. // child agents from being present in the scene for which their root
  3699. // agent isn't allowed. Otherwise, we allow child agents. The test for
  3700. // the root is done elsewhere (QueryAccess)
  3701. if (!bypassAccessControl)
  3702. {
  3703. if(RegionInfo.EstateSettings == null)
  3704. {
  3705. // something is broken? let it get in
  3706. m_log.ErrorFormat("[CONNECTION BEGIN]: Estate Settings is null!");
  3707. return true;
  3708. }
  3709. // check estate ban
  3710. int flags = GetUserFlags(agent.AgentID);
  3711. if (RegionInfo.EstateSettings.IsBanned(agent.AgentID, flags))
  3712. {
  3713. m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user is on the banlist",
  3714. agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
  3715. reason = String.Format("Denied access to region {0}: You have been banned from that region.",
  3716. RegionInfo.RegionName);
  3717. return false;
  3718. }
  3719. // public access
  3720. if (RegionInfo.EstateSettings.PublicAccess)
  3721. return true;
  3722. // in access list / owner / manager
  3723. if (RegionInfo.EstateSettings.HasAccess(agent.AgentID))
  3724. return true;
  3725. // finally test groups
  3726. bool groupAccess = false;
  3727. // some say GOTO is ugly
  3728. if(m_groupsModule == null) // if no groups refuse
  3729. goto Label_GroupsDone;
  3730. UUID[] estateGroups = RegionInfo.EstateSettings.EstateGroups;
  3731. if(estateGroups == null)
  3732. {
  3733. m_log.ErrorFormat("[CONNECTION BEGIN]: Estate GroupMembership is null!");
  3734. goto Label_GroupsDone;
  3735. }
  3736. if(estateGroups.Length == 0)
  3737. goto Label_GroupsDone;
  3738. List<UUID> agentGroups = new List<UUID>();
  3739. GroupMembershipData[] GroupMembership = m_groupsModule.GetMembershipData(agent.AgentID);
  3740. if(GroupMembership == null)
  3741. {
  3742. m_log.ErrorFormat("[CONNECTION BEGIN]: GroupMembership is null!");
  3743. goto Label_GroupsDone;
  3744. }
  3745. if(GroupMembership.Length == 0)
  3746. goto Label_GroupsDone;
  3747. for(int i = 0;i < GroupMembership.Length;i++)
  3748. agentGroups.Add(GroupMembership[i].GroupID);
  3749. foreach(UUID group in estateGroups)
  3750. {
  3751. if(agentGroups.Contains(group))
  3752. {
  3753. groupAccess = true;
  3754. break;
  3755. }
  3756. }
  3757. Label_GroupsDone:
  3758. if (!groupAccess)
  3759. {
  3760. m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user does not have access to the estate",
  3761. agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
  3762. reason = String.Format("Denied access to private region {0}: You do not have access to that region.",
  3763. RegionInfo.RegionName);
  3764. return false;
  3765. }
  3766. }
  3767. return true;
  3768. }
  3769. /// <summary>
  3770. /// Update an AgentCircuitData object with new information
  3771. /// </summary>
  3772. /// <param name="data">Information to update the AgentCircuitData with</param>
  3773. public void UpdateCircuitData(AgentCircuitData data)
  3774. {
  3775. m_authenticateHandler.UpdateAgentData(data);
  3776. }
  3777. /// <summary>
  3778. /// Change the Circuit Code for the user's Circuit Data
  3779. /// </summary>
  3780. /// <param name="oldcc">The old Circuit Code. Must match a previous circuit code</param>
  3781. /// <param name="newcc">The new Circuit Code. Must not be an already existing circuit code</param>
  3782. /// <returns>True if we successfully changed it. False if we did not</returns>
  3783. public bool ChangeCircuitCode(uint oldcc, uint newcc)
  3784. {
  3785. return m_authenticateHandler.TryChangeCiruitCode(oldcc, newcc);
  3786. }
  3787. // /// <summary>
  3788. // /// The Grid has requested that we log-off a user. Log them off.
  3789. // /// </summary>
  3790. // /// <param name="AvatarID">Unique ID of the avatar to log-off</param>
  3791. // /// <param name="RegionSecret">SecureSessionID of the user, or the RegionSecret text when logging on to the grid</param>
  3792. // /// <param name="message">message to display to the user. Reason for being logged off</param>
  3793. // public void HandleLogOffUserFromGrid(UUID AvatarID, UUID RegionSecret, string message)
  3794. // {
  3795. // ScenePresence loggingOffUser = GetScenePresence(AvatarID);
  3796. // if (loggingOffUser != null)
  3797. // {
  3798. // UUID localRegionSecret = UUID.Zero;
  3799. // bool parsedsecret = UUID.TryParse(RegionInfo.regionSecret, out localRegionSecret);
  3800. //
  3801. // // Region Secret is used here in case a new sessionid overwrites an old one on the user server.
  3802. // // Will update the user server in a few revisions to use it.
  3803. //
  3804. // if (RegionSecret == loggingOffUser.ControllingClient.SecureSessionId || (parsedsecret && RegionSecret == localRegionSecret))
  3805. // {
  3806. // m_sceneGridService.SendCloseChildAgentConnections(loggingOffUser.UUID, loggingOffUser.KnownRegionHandles);
  3807. // loggingOffUser.ControllingClient.Kick(message);
  3808. // // Give them a second to receive the message!
  3809. // Thread.Sleep(1000);
  3810. // loggingOffUser.ControllingClient.Close();
  3811. // }
  3812. // else
  3813. // {
  3814. // m_log.Info("[USERLOGOFF]: System sending the LogOff user message failed to sucessfully authenticate");
  3815. // }
  3816. // }
  3817. // else
  3818. // {
  3819. // m_log.InfoFormat("[USERLOGOFF]: Got a logoff request for {0} but the user isn't here. The user might already have been logged out", AvatarID.ToString());
  3820. // }
  3821. // }
  3822. // /// <summary>
  3823. // /// Triggered when an agent crosses into this sim. Also happens on initial login.
  3824. // /// </summary>
  3825. // /// <param name="agentID"></param>
  3826. // /// <param name="position"></param>
  3827. // /// <param name="isFlying"></param>
  3828. // public virtual void AgentCrossing(UUID agentID, Vector3 position, bool isFlying)
  3829. // {
  3830. // ScenePresence presence = GetScenePresence(agentID);
  3831. // if (presence != null)
  3832. // {
  3833. // try
  3834. // {
  3835. // presence.MakeRootAgent(position, isFlying);
  3836. // }
  3837. // catch (Exception e)
  3838. // {
  3839. // m_log.ErrorFormat("[SCENE]: Unable to do agent crossing, exception {0}{1}", e.Message, e.StackTrace);
  3840. // }
  3841. // }
  3842. // else
  3843. // {
  3844. // m_log.ErrorFormat(
  3845. // "[SCENE]: Could not find presence for agent {0} crossing into scene {1}",
  3846. // agentID, RegionInfo.RegionName);
  3847. // }
  3848. // }
  3849. /// <summary>
  3850. /// We've got an update about an agent that sees into this region,
  3851. /// send it to ScenePresence for processing It's the full data.
  3852. /// </summary>
  3853. /// <param name="cAgentData">Agent that contains all of the relevant things about an agent.
  3854. /// Appearance, animations, position, etc.</param>
  3855. /// <returns>true if we handled it.</returns>
  3856. public virtual bool IncomingUpdateChildAgent(AgentData cAgentData)
  3857. {
  3858. m_log.DebugFormat(
  3859. "[SCENE]: Incoming child agent update for {0} in {1}", cAgentData.AgentID, RegionInfo.RegionName);
  3860. if (!LoginsEnabled)
  3861. {
  3862. // reason = "Logins Disabled";
  3863. m_log.DebugFormat(
  3864. "[SCENE]: update for {0} in {1} refused: Logins Disabled", cAgentData.AgentID, RegionInfo.RegionName);
  3865. return false;
  3866. }
  3867. int flags = GetUserFlags(cAgentData.AgentID);
  3868. if (RegionInfo.EstateSettings.IsBanned(cAgentData.AgentID, flags))
  3869. {
  3870. m_log.DebugFormat("[SCENE]: Denying root agent entry to {0}: banned", cAgentData.AgentID);
  3871. return false;
  3872. }
  3873. // TODO: This check should probably be in QueryAccess().
  3874. ILandObject nearestParcel = GetNearestAllowedParcel(cAgentData.AgentID,
  3875. (float)RegionInfo.RegionSizeX * 0.5f, (float)RegionInfo.RegionSizeY * 0.5f);
  3876. if (nearestParcel == null)
  3877. {
  3878. m_log.InfoFormat(
  3879. "[SCENE]: Denying root agent entry to {0} in {1}: no allowed parcel",
  3880. cAgentData.AgentID, RegionInfo.RegionName);
  3881. return false;
  3882. }
  3883. // We have to wait until the viewer contacts this region
  3884. // after receiving the EnableSimulator HTTP Event Queue message (for the v1 teleport protocol)
  3885. // or TeleportFinish (for the v2 teleport protocol). This triggers the viewer to send
  3886. // a UseCircuitCode packet which in turn calls AddNewAgent which finally creates the ScenePresence.
  3887. ScenePresence sp = WaitGetScenePresence(cAgentData.AgentID);
  3888. if (sp != null)
  3889. {
  3890. if (!sp.IsChildAgent)
  3891. {
  3892. m_log.WarnFormat("[SCENE]: Ignoring a child update on a root agent {0} {1} in {2}",
  3893. sp.Name, sp.UUID, Name);
  3894. return false;
  3895. }
  3896. if (cAgentData.SessionID != sp.ControllingClient.SessionId)
  3897. {
  3898. m_log.WarnFormat(
  3899. "[SCENE]: Attempt to update agent {0} with diferent session id {1} != {2}",
  3900. sp.UUID, sp.ControllingClient.SessionId, cAgentData.SessionID);
  3901. return false;
  3902. }
  3903. sp.UpdateChildAgent(cAgentData);
  3904. int ntimes = 100;
  3905. if (cAgentData.SenderWantsToWaitForRoot)
  3906. {
  3907. while (sp.IsChildAgent && ntimes-- > 0)
  3908. Thread.Sleep(250);
  3909. if (sp.IsChildAgent)
  3910. {
  3911. m_log.WarnFormat(
  3912. "[SCENE]: Found presence {0} {1} unexpectedly still child in {2}",
  3913. sp.Name, sp.UUID, Name);
  3914. return false;
  3915. }
  3916. }
  3917. return true;
  3918. }
  3919. return false;
  3920. }
  3921. /// <summary>
  3922. /// We've got an update about an agent that sees into this region,
  3923. /// send it to ScenePresence for processing It's only positional data
  3924. /// </summary>
  3925. /// <param name="cAgentData">AgentPosition that contains agent positional data so we can know what to send</param>
  3926. /// <returns>true if we handled it.</returns>
  3927. public virtual bool IncomingUpdateChildAgent(AgentPosition cAgentData)
  3928. {
  3929. // m_log.DebugFormat(
  3930. // "[SCENE PRESENCE]: IncomingChildAgentDataUpdate POSITION for {0} in {1}, position {2}",
  3931. // cAgentData.AgentID, Name, cAgentData.Position);
  3932. ScenePresence childAgentUpdate = GetScenePresence(cAgentData.AgentID);
  3933. if (childAgentUpdate != null)
  3934. {
  3935. // if (childAgentUpdate.ControllingClient.SessionId != cAgentData.SessionID)
  3936. // // Only warn for now
  3937. // m_log.WarnFormat("[SCENE]: Attempt at updating position of agent {0} with invalid session id {1}. Neighbor running older version?",
  3938. // childAgentUpdate.UUID, cAgentData.SessionID);
  3939. // I can't imagine *yet* why we would get an update if the agent is a root agent..
  3940. // however to avoid a race condition crossing borders..
  3941. if (childAgentUpdate.IsChildAgent)
  3942. {
  3943. uint rRegionX = (uint)(cAgentData.RegionHandle >> 40);
  3944. uint rRegionY = (((uint)(cAgentData.RegionHandle)) >> 8);
  3945. uint tRegionX = RegionInfo.RegionLocX;
  3946. uint tRegionY = RegionInfo.RegionLocY;
  3947. //Send Data to ScenePresence
  3948. childAgentUpdate.UpdateChildAgent(cAgentData, tRegionX, tRegionY, rRegionX, rRegionY);
  3949. // Not Implemented:
  3950. //TODO: Do we need to pass the message on to one of our neighbors?
  3951. }
  3952. return true;
  3953. }
  3954. return false;
  3955. }
  3956. /// <summary>
  3957. /// Poll until the requested ScenePresence appears or we timeout.
  3958. /// </summary>
  3959. /// <returns>The scene presence is found, else null.</returns>
  3960. /// <param name='agentID'></param>
  3961. protected virtual ScenePresence WaitGetScenePresence(UUID agentID)
  3962. {
  3963. int ntimes = 120; // 30s
  3964. ScenePresence sp = null;
  3965. while ((sp = GetScenePresence(agentID)) == null && (ntimes-- > 0))
  3966. Thread.Sleep(250);
  3967. if (sp == null)
  3968. m_log.WarnFormat(
  3969. "[SCENE PRESENCE]: Did not find presence with id {0} in {1} before timeout",
  3970. agentID, RegionInfo.RegionName);
  3971. return sp;
  3972. }
  3973. /// <summary>
  3974. /// Authenticated close (via network)
  3975. /// </summary>
  3976. /// <param name="agentID"></param>
  3977. /// <param name="force"></param>
  3978. /// <param name="auth_token"></param>
  3979. /// <returns></returns>
  3980. public bool CloseAgent(UUID agentID, bool force, string auth_token)
  3981. {
  3982. //m_log.DebugFormat("[SCENE]: Processing incoming close agent {0} in region {1} with auth_token {2}", agentID, RegionInfo.RegionName, auth_token);
  3983. // Check that the auth_token is valid
  3984. AgentCircuitData acd = AuthenticateHandler.GetAgentCircuitData(agentID);
  3985. if (acd == null)
  3986. {
  3987. m_log.DebugFormat(
  3988. "[SCENE]: Request to close agent {0} but no such agent in scene {1}. May have been closed previously.",
  3989. agentID, Name);
  3990. return false;
  3991. }
  3992. if (acd.SessionID.ToString() == auth_token)
  3993. {
  3994. return CloseAgent(agentID, force);
  3995. }
  3996. else
  3997. {
  3998. m_log.WarnFormat(
  3999. "[SCENE]: Request to close agent {0} with invalid authorization token {1} in {2}",
  4000. agentID, auth_token, Name);
  4001. }
  4002. return false;
  4003. }
  4004. /// <summary>
  4005. /// Tell a single client to prepare to close.
  4006. /// </summary>
  4007. /// <remarks>
  4008. /// This should only be called if we may close the client but there will be some delay in so doing. Meant for
  4009. /// internal use - other callers should almost certainly called CloseClient().
  4010. /// </remarks>
  4011. /// <param name="sp"></param>
  4012. /// <returns>true if pre-close state notification was successful. false if the agent
  4013. /// was not in a state where it could transition to pre-close.</returns>
  4014. public bool IncomingPreCloseClient(ScenePresence sp)
  4015. {
  4016. lock (m_removeClientLock)
  4017. {
  4018. // We need to avoid a race condition where in, for example, an A B C D region layout, an avatar may
  4019. // teleport from A -> D, but then -> C before A has asked B to close its old child agent. We do not
  4020. // want to obey this close since C may have renewed the child agent lease on B.
  4021. if (sp.DoNotCloseAfterTeleport)
  4022. {
  4023. m_log.DebugFormat(
  4024. "[SCENE]: Not pre-closing {0} agent {1} in {2} since another simulator has re-established the child connection",
  4025. sp.IsChildAgent ? "child" : "root", sp.Name, Name);
  4026. // Need to reset the flag so that a subsequent close after another teleport can succeed.
  4027. sp.DoNotCloseAfterTeleport = false;
  4028. return false;
  4029. }
  4030. if (sp.LifecycleState != ScenePresenceState.Running)
  4031. {
  4032. m_log.DebugFormat(
  4033. "[SCENE]: Called IncomingPreCloseAgent() for {0} in {1} but presence is already in state {2}",
  4034. sp.Name, Name, sp.LifecycleState);
  4035. return false;
  4036. }
  4037. sp.LifecycleState = ScenePresenceState.PreRemove;
  4038. return true;
  4039. }
  4040. }
  4041. /// <summary>
  4042. /// Tell a single agent to disconnect from the region.
  4043. /// </summary>
  4044. /// <param name="agentID"></param>
  4045. /// <param name="force">
  4046. /// Force the agent to close even if it might be in the middle of some other operation. You do not want to
  4047. /// force unless you are absolutely sure that the agent is dead and a normal close is not working.
  4048. /// </param>
  4049. public override bool CloseAgent(UUID agentID, bool force)
  4050. {
  4051. ScenePresence sp;
  4052. lock (m_removeClientLock)
  4053. {
  4054. sp = GetScenePresence(agentID);
  4055. if (sp == null)
  4056. {
  4057. // If there is no scene presence, we may be handling a dead
  4058. // client. These can keep an avatar from reentering a region
  4059. // and since they don't get cleaned up they will stick
  4060. // around until region restart. So, if there is no SP,
  4061. // remove the client as well.
  4062. IClientAPI client = null;
  4063. if (m_clientManager.TryGetValue(agentID, out client))
  4064. {
  4065. m_clientManager.Remove(agentID);
  4066. if (CapsModule != null)
  4067. CapsModule.RemoveCaps(agentID, 0);
  4068. m_log.DebugFormat( "[SCENE]: Dead client for agent ID {0} was cleaned up in {1}", agentID, Name);
  4069. return true;
  4070. }
  4071. m_log.DebugFormat(
  4072. "[SCENE]: Called CloseClient() with agent ID {0} but no such presence is in {1}",
  4073. agentID, Name);
  4074. return false;
  4075. }
  4076. if (sp.LifecycleState != ScenePresenceState.Running && sp.LifecycleState != ScenePresenceState.PreRemove)
  4077. {
  4078. m_log.DebugFormat(
  4079. "[SCENE]: Called CloseClient() for {0} in {1} but presence is already in state {2}",
  4080. sp.Name, Name, sp.LifecycleState);
  4081. return false;
  4082. }
  4083. // We need to avoid a race condition where in, for example, an A B C D region layout, an avatar may
  4084. // teleport from A -> D, but then -> C before A has asked B to close its old child agent. We do not
  4085. // want to obey this close since C may have renewed the child agent lease on B.
  4086. if (sp.DoNotCloseAfterTeleport)
  4087. {
  4088. m_log.DebugFormat(
  4089. "[SCENE]: Not closing {0} agent {1} in {2} since another simulator has re-established the child connection",
  4090. sp.IsChildAgent ? "child" : "root", sp.Name, Name);
  4091. // Need to reset the flag so that a subsequent close after another teleport can succeed.
  4092. sp.DoNotCloseAfterTeleport = false;
  4093. return false;
  4094. }
  4095. sp.LifecycleState = ScenePresenceState.Removing;
  4096. }
  4097. if (sp != null)
  4098. {
  4099. sp.ControllingClient.Close(force, force);
  4100. if(sp.IsNPC && UserManagementModule != null)
  4101. UserManagementModule.RemoveUser(sp.UUID);
  4102. return true;
  4103. }
  4104. return true;
  4105. }
  4106. /// <summary>
  4107. /// Tries to teleport agent within region.
  4108. /// </summary>
  4109. /// <param name="remoteClient"></param>
  4110. /// <param name="position"></param>
  4111. /// <param name="lookAt"></param>
  4112. /// <param name="teleportFlags"></param>
  4113. public void RequestLocalTeleport(ScenePresence sp, Vector3 position, Vector3 vel,
  4114. Vector3 lookat, int flags)
  4115. {
  4116. sp.LocalTeleport(position, vel, lookat, flags);
  4117. }
  4118. /// <summary>
  4119. /// Tries to teleport agent to another region.
  4120. /// </summary>
  4121. /// <remarks>
  4122. /// The region name must exactly match that given.
  4123. /// </remarks>
  4124. /// <param name="remoteClient"></param>
  4125. /// <param name="regionName"></param>
  4126. /// <param name="position"></param>
  4127. /// <param name="lookAt"></param>
  4128. /// <param name="teleportFlags"></param>
  4129. public void RequestTeleportLocation(IClientAPI remoteClient, string regionName, Vector3 position,
  4130. Vector3 lookat, uint teleportFlags)
  4131. {
  4132. if (EntityTransferModule == null)
  4133. {
  4134. m_log.DebugFormat("[SCENE]: Unable to perform teleports: no AgentTransferModule is active");
  4135. return;
  4136. }
  4137. ScenePresence sp = GetScenePresence(remoteClient.AgentId);
  4138. if (sp == null || sp.IsDeleted || sp.IsInTransit)
  4139. return;
  4140. ulong regionHandle = 0;
  4141. if(regionName == RegionInfo.RegionName)
  4142. regionHandle = RegionInfo.RegionHandle;
  4143. else
  4144. {
  4145. GridRegion region = GridService.GetRegionByName(RegionInfo.ScopeID, regionName);
  4146. if (region != null)
  4147. regionHandle = region.RegionHandle;
  4148. }
  4149. if(regionHandle == 0)
  4150. {
  4151. // can't find the region: Tell viewer and abort
  4152. remoteClient.SendTeleportFailed("The region '" + regionName + "' could not be found.");
  4153. return;
  4154. }
  4155. EntityTransferModule.Teleport(sp, regionHandle, position, lookat, teleportFlags);
  4156. }
  4157. /// <summary>
  4158. /// Tries to teleport agent to other region.
  4159. /// </summary>
  4160. /// <param name="remoteClient"></param>
  4161. /// <param name="regionHandle"></param>
  4162. /// <param name="position"></param>
  4163. /// <param name="lookAt"></param>
  4164. /// <param name="teleportFlags"></param>
  4165. public void RequestTeleportLocation(IClientAPI remoteClient, ulong regionHandle, Vector3 position,
  4166. Vector3 lookAt, uint teleportFlags)
  4167. {
  4168. if (EntityTransferModule == null)
  4169. {
  4170. m_log.DebugFormat("[SCENE]: Unable to perform teleports: no AgentTransferModule is active");
  4171. return;
  4172. }
  4173. ScenePresence sp = GetScenePresence(remoteClient.AgentId);
  4174. if (sp == null || sp.IsDeleted || sp.IsInTransit)
  4175. return;
  4176. EntityTransferModule.Teleport(sp, regionHandle, position, lookAt, teleportFlags);
  4177. }
  4178. public bool CrossAgentToNewRegion(ScenePresence agent, bool isFlying)
  4179. {
  4180. if (EntityTransferModule != null)
  4181. {
  4182. return EntityTransferModule.Cross(agent, isFlying);
  4183. }
  4184. else
  4185. {
  4186. m_log.DebugFormat("[SCENE]: Unable to cross agent to neighbouring region, because there is no AgentTransferModule");
  4187. }
  4188. return false;
  4189. }
  4190. public void SendOutChildAgentUpdates(AgentPosition cadu, ScenePresence presence)
  4191. {
  4192. m_sceneGridService.SendChildAgentDataUpdate(cadu, presence);
  4193. }
  4194. #endregion
  4195. #region Other Methods
  4196. protected override IConfigSource GetConfig()
  4197. {
  4198. return m_config;
  4199. }
  4200. #endregion
  4201. public void HandleObjectPermissionsUpdate(IClientAPI controller, UUID agentID, UUID sessionID, byte field, uint localId, uint mask, byte set)
  4202. {
  4203. // Check for spoofing.. since this is permissions we're talking about here!
  4204. if ((controller.SessionId == sessionID) && (controller.AgentId == agentID))
  4205. {
  4206. // Tell the object to do permission update
  4207. if (localId != 0)
  4208. {
  4209. SceneObjectGroup chObjectGroup = GetGroupByPrim(localId);
  4210. if (chObjectGroup != null)
  4211. {
  4212. chObjectGroup.UpdatePermissions(agentID, field, localId, mask, set);
  4213. }
  4214. }
  4215. }
  4216. }
  4217. /// <summary>
  4218. /// Causes all clients to get a full object update on all of the objects in the scene.
  4219. /// </summary>
  4220. public void ForceClientUpdate()
  4221. {
  4222. EntityBase[] entityList = GetEntities();
  4223. foreach (EntityBase ent in entityList)
  4224. {
  4225. if (ent is SceneObjectGroup)
  4226. {
  4227. ((SceneObjectGroup)ent).ScheduleGroupForFullUpdate();
  4228. }
  4229. }
  4230. }
  4231. /// <summary>
  4232. /// This is currently only used for scale (to scale to MegaPrim size)
  4233. /// There is a console command that calls this in OpenSimMain
  4234. /// </summary>
  4235. /// <param name="cmdparams"></param>
  4236. public void HandleEditCommand(string[] cmdparams)
  4237. {
  4238. m_log.DebugFormat("Searching for Primitive: '{0}'", cmdparams[2]);
  4239. EntityBase[] entityList = GetEntities();
  4240. foreach (EntityBase ent in entityList)
  4241. {
  4242. if (ent is SceneObjectGroup)
  4243. {
  4244. SceneObjectPart part = ((SceneObjectGroup)ent).GetPart(((SceneObjectGroup)ent).UUID);
  4245. if (part != null)
  4246. {
  4247. if (part.Name == cmdparams[2])
  4248. {
  4249. part.Resize(
  4250. new Vector3(Convert.ToSingle(cmdparams[3]), Convert.ToSingle(cmdparams[4]),
  4251. Convert.ToSingle(cmdparams[5])));
  4252. m_log.DebugFormat("Edited scale of Primitive: {0}", part.Name);
  4253. }
  4254. }
  4255. }
  4256. }
  4257. }
  4258. #region Script Handling Methods
  4259. /// <summary>
  4260. /// Console command handler to send script command to script engine.
  4261. /// </summary>
  4262. /// <param name="args"></param>
  4263. public void SendCommandToPlugins(string[] args)
  4264. {
  4265. m_eventManager.TriggerOnPluginConsole(args);
  4266. }
  4267. public LandData GetLandData(float x, float y)
  4268. {
  4269. ILandObject parcel = LandChannel.GetLandObject(x, y);
  4270. if (parcel == null)
  4271. return null;
  4272. return parcel.LandData;
  4273. }
  4274. /// <summary>
  4275. /// Get LandData by position.
  4276. /// </summary>
  4277. /// <param name="pos"></param>
  4278. /// <returns></returns>
  4279. public LandData GetLandData(Vector3 pos)
  4280. {
  4281. return GetLandData(pos.X, pos.Y);
  4282. }
  4283. public LandData GetLandData(uint x, uint y)
  4284. {
  4285. // m_log.DebugFormat("[SCENE]: returning land for {0},{1}", x, y);
  4286. ILandObject parcel = LandChannel.GetLandObject((int)x, (int)y);
  4287. if (parcel == null)
  4288. return null;
  4289. return parcel.LandData;
  4290. }
  4291. #endregion
  4292. #region Script Engine
  4293. public bool LSLScriptDanger(SceneObjectPart part, Vector3 pos)
  4294. {
  4295. ILandObject parcel = LandChannel.GetLandObject(pos.X, pos.Y);
  4296. if (parcel == null)
  4297. return true;
  4298. LandData ldata = parcel.LandData;
  4299. if (ldata == null)
  4300. return true;
  4301. uint landflags = ldata.Flags;
  4302. uint mask = (uint)(ParcelFlags.CreateObjects | ParcelFlags.AllowAPrimitiveEntry);
  4303. if((landflags & mask) != mask)
  4304. return true;
  4305. if((landflags & (uint)ParcelFlags.AllowOtherScripts) != 0)
  4306. return false;
  4307. if(part == null)
  4308. return true;
  4309. if(part.GroupID == ldata.GroupID && (landflags & (uint)ParcelFlags.AllowGroupScripts) != 0)
  4310. return false;
  4311. return true;
  4312. }
  4313. private bool ScriptDanger(SceneObjectPart part, Vector3 pos)
  4314. {
  4315. if (part == null)
  4316. return false;
  4317. ILandObject parcel = LandChannel.GetLandObject(pos.X, pos.Y);
  4318. if (parcel != null)
  4319. {
  4320. if ((parcel.LandData.Flags & (uint)ParcelFlags.AllowOtherScripts) != 0)
  4321. return true;
  4322. if ((part.OwnerID == parcel.LandData.OwnerID) || Permissions.IsGod(part.OwnerID))
  4323. return true;
  4324. if (((parcel.LandData.Flags & (uint)ParcelFlags.AllowGroupScripts) != 0)
  4325. && (parcel.LandData.GroupID != UUID.Zero) && (parcel.LandData.GroupID == part.GroupID))
  4326. return true;
  4327. }
  4328. else
  4329. {
  4330. if (pos.X > 0f && pos.X < RegionInfo.RegionSizeX && pos.Y > 0f && pos.Y < RegionInfo.RegionSizeY)
  4331. return true;
  4332. }
  4333. return false;
  4334. }
  4335. public bool PipeEventsForScript(uint localID)
  4336. {
  4337. SceneObjectPart part = GetSceneObjectPart(localID);
  4338. if (part != null)
  4339. {
  4340. SceneObjectPart parent = part.ParentGroup.RootPart;
  4341. return ScriptDanger(parent, parent.GetWorldPosition());
  4342. }
  4343. else
  4344. {
  4345. return false;
  4346. }
  4347. }
  4348. #endregion
  4349. #region SceneGraph wrapper methods
  4350. public void SwapRootAgentCount(bool rootChildChildRootTF)
  4351. {
  4352. m_sceneGraph.SwapRootChildAgent(rootChildChildRootTF);
  4353. }
  4354. public void AddPhysicalPrim(int num)
  4355. {
  4356. m_sceneGraph.AddPhysicalPrim(num);
  4357. }
  4358. public void RemovePhysicalPrim(int num)
  4359. {
  4360. m_sceneGraph.RemovePhysicalPrim(num);
  4361. }
  4362. public int GetRootAgentCount()
  4363. {
  4364. return m_sceneGraph.GetRootAgentCount();
  4365. }
  4366. public int GetChildAgentCount()
  4367. {
  4368. return m_sceneGraph.GetChildAgentCount();
  4369. }
  4370. /// <summary>
  4371. /// Request a scene presence by UUID. Fast, indexed lookup.
  4372. /// </summary>
  4373. /// <param name="agentID"></param>
  4374. /// <returns>null if the presence was not found</returns>
  4375. public ScenePresence GetScenePresence(UUID agentID)
  4376. {
  4377. return m_sceneGraph.GetScenePresence(agentID);
  4378. }
  4379. /// <summary>
  4380. /// Request the scene presence by name.
  4381. /// </summary>
  4382. /// <param name="firstName"></param>
  4383. /// <param name="lastName"></param>
  4384. /// <returns>null if the presence was not found</returns>
  4385. public ScenePresence GetScenePresence(string firstName, string lastName)
  4386. {
  4387. return m_sceneGraph.GetScenePresence(firstName, lastName);
  4388. }
  4389. /// <summary>
  4390. /// Request the scene presence by localID.
  4391. /// </summary>
  4392. /// <param name="localID"></param>
  4393. /// <returns>null if the presence was not found</returns>
  4394. public ScenePresence GetScenePresence(uint localID)
  4395. {
  4396. return m_sceneGraph.GetScenePresence(localID);
  4397. }
  4398. /// <summary>
  4399. /// Gets all the scene presences in this scene.
  4400. /// </summary>
  4401. /// <remarks>
  4402. /// This method will return both root and child scene presences.
  4403. ///
  4404. /// Consider using ForEachScenePresence() or ForEachRootScenePresence() if possible since these will not
  4405. /// involving creating a new List object.
  4406. /// </remarks>
  4407. /// <returns>
  4408. /// A list of the scene presences. Adding or removing from the list will not affect the presences in the scene.
  4409. /// </returns>
  4410. public List<ScenePresence> GetScenePresences()
  4411. {
  4412. return new List<ScenePresence>(m_sceneGraph.GetScenePresences());
  4413. }
  4414. /// <summary>
  4415. /// Performs action on all avatars in the scene (root scene presences)
  4416. /// Avatars may be an NPC or a 'real' client.
  4417. /// </summary>
  4418. /// <param name="action"></param>
  4419. public void ForEachRootScenePresence(Action<ScenePresence> action)
  4420. {
  4421. m_sceneGraph.ForEachAvatar(action);
  4422. }
  4423. /// <summary>
  4424. /// Performs action on all scene presences (root and child)
  4425. /// </summary>
  4426. /// <param name="action"></param>
  4427. public void ForEachScenePresence(Action<ScenePresence> action)
  4428. {
  4429. m_sceneGraph.ForEachScenePresence(action);
  4430. }
  4431. /// <summary>
  4432. /// Get all the scene object groups.
  4433. /// </summary>
  4434. /// <returns>
  4435. /// The scene object groups. If the scene is empty then an empty list is returned.
  4436. /// </returns>
  4437. public List<SceneObjectGroup> GetSceneObjectGroups()
  4438. {
  4439. return m_sceneGraph.GetSceneObjectGroups();
  4440. }
  4441. /// <summary>
  4442. /// Get a group via its UUID
  4443. /// </summary>
  4444. /// <param name="fullID"></param>
  4445. /// <returns>null if no group with that id exists</returns>
  4446. public SceneObjectGroup GetSceneObjectGroup(UUID fullID)
  4447. {
  4448. return m_sceneGraph.GetSceneObjectGroup(fullID);
  4449. }
  4450. /// <summary>
  4451. /// Get a group via its local ID
  4452. /// </summary>
  4453. /// <remarks>This will only return a group if the local ID matches a root part</remarks>
  4454. /// <param name="localID"></param>
  4455. /// <returns>null if no group with that id exists</returns>
  4456. public SceneObjectGroup GetSceneObjectGroup(uint localID)
  4457. {
  4458. return m_sceneGraph.GetSceneObjectGroup(localID);
  4459. }
  4460. /// <summary>
  4461. /// Get a group by name from the scene (will return the first
  4462. /// found, if there are more than one prim with the same name)
  4463. /// </summary>
  4464. /// <param name="name"></param>
  4465. /// <returns>null if no group with that name exists</returns>
  4466. public SceneObjectGroup GetSceneObjectGroup(string name)
  4467. {
  4468. return m_sceneGraph.GetSceneObjectGroup(name);
  4469. }
  4470. /// <summary>
  4471. /// Attempt to get the SOG via its UUID
  4472. /// </summary>
  4473. /// <param name="fullID"></param>
  4474. /// <param name="sog"></param>
  4475. /// <returns></returns>
  4476. public bool TryGetSceneObjectGroup(UUID fullID, out SceneObjectGroup sog)
  4477. {
  4478. sog = GetSceneObjectGroup(fullID);
  4479. return sog != null;
  4480. }
  4481. /// <summary>
  4482. /// Get a prim by name from the scene (will return the first
  4483. /// found, if there are more than one prim with the same name)
  4484. /// </summary>
  4485. /// <param name="name"></param>
  4486. /// <returns></returns>
  4487. public SceneObjectPart GetSceneObjectPart(string name)
  4488. {
  4489. return m_sceneGraph.GetSceneObjectPart(name);
  4490. }
  4491. /// <summary>
  4492. /// Get a prim via its local id
  4493. /// </summary>
  4494. /// <param name="localID"></param>
  4495. /// <returns></returns>
  4496. public SceneObjectPart GetSceneObjectPart(uint localID)
  4497. {
  4498. return m_sceneGraph.GetSceneObjectPart(localID);
  4499. }
  4500. /// <summary>
  4501. /// Get a prim via its UUID
  4502. /// </summary>
  4503. /// <param name="fullID"></param>
  4504. /// <returns></returns>
  4505. public SceneObjectPart GetSceneObjectPart(UUID fullID)
  4506. {
  4507. return m_sceneGraph.GetSceneObjectPart(fullID);
  4508. }
  4509. /// <summary>
  4510. /// Attempt to get a prim via its UUID
  4511. /// </summary>
  4512. /// <param name="fullID"></param>
  4513. /// <param name="sop"></param>
  4514. /// <returns></returns>
  4515. public bool TryGetSceneObjectPart(UUID fullID, out SceneObjectPart sop)
  4516. {
  4517. sop = GetSceneObjectPart(fullID);
  4518. return sop != null;
  4519. }
  4520. /// <summary>
  4521. /// Get a scene object group that contains the prim with the given local id
  4522. /// </summary>
  4523. /// <param name="localID"></param>
  4524. /// <returns>null if no scene object group containing that prim is found</returns>
  4525. public SceneObjectGroup GetGroupByPrim(uint localID)
  4526. {
  4527. return m_sceneGraph.GetGroupByPrim(localID);
  4528. }
  4529. /// <summary>
  4530. /// Get a scene object group that contains the prim with the given uuid
  4531. /// </summary>
  4532. /// <param name="fullID"></param>
  4533. /// <returns>null if no scene object group containing that prim is found</returns>
  4534. public SceneObjectGroup GetGroupByPrim(UUID fullID)
  4535. {
  4536. return m_sceneGraph.GetGroupByPrim(fullID);
  4537. }
  4538. public override bool TryGetScenePresence(UUID agentID, out ScenePresence sp)
  4539. {
  4540. return m_sceneGraph.TryGetScenePresence(agentID, out sp);
  4541. }
  4542. public bool TryGetAvatarByName(string avatarName, out ScenePresence avatar)
  4543. {
  4544. return m_sceneGraph.TryGetAvatarByName(avatarName, out avatar);
  4545. }
  4546. /// <summary>
  4547. /// Perform an action on all clients with an avatar in this scene (root only)
  4548. /// </summary>
  4549. /// <param name="action"></param>
  4550. public void ForEachRootClient(Action<IClientAPI> action)
  4551. {
  4552. ForEachRootScenePresence(delegate(ScenePresence presence)
  4553. {
  4554. action(presence.ControllingClient);
  4555. });
  4556. }
  4557. /// <summary>
  4558. /// Perform an action on all clients connected to the region (root and child)
  4559. /// </summary>
  4560. /// <param name="action"></param>
  4561. public void ForEachClient(Action<IClientAPI> action)
  4562. {
  4563. m_clientManager.ForEach(action);
  4564. }
  4565. public int GetNumberOfClients()
  4566. {
  4567. return m_clientManager.Count;
  4568. }
  4569. public bool TryGetClient(UUID avatarID, out IClientAPI client)
  4570. {
  4571. return m_clientManager.TryGetValue(avatarID, out client);
  4572. }
  4573. public bool TryGetClient(System.Net.IPEndPoint remoteEndPoint, out IClientAPI client)
  4574. {
  4575. return m_clientManager.TryGetValue(remoteEndPoint, out client);
  4576. }
  4577. public void ForEachSOG(Action<SceneObjectGroup> action)
  4578. {
  4579. m_sceneGraph.ForEachSOG(action);
  4580. }
  4581. /// <summary>
  4582. /// Returns a list of the entities in the scene. This is a new list so operations perform on the list itself
  4583. /// will not affect the original list of objects in the scene.
  4584. /// </summary>
  4585. /// <returns></returns>
  4586. public EntityBase[] GetEntities()
  4587. {
  4588. return m_sceneGraph.GetEntities();
  4589. }
  4590. #endregion
  4591. // Commented pending deletion since this method no longer appears to do anything at all
  4592. // public bool NeedSceneCacheClear(UUID agentID)
  4593. // {
  4594. // IInventoryTransferModule inv = RequestModuleInterface<IInventoryTransferModule>();
  4595. // if (inv == null)
  4596. // return true;
  4597. //
  4598. // return inv.NeedSceneCacheClear(agentID, this);
  4599. // }
  4600. public void CleanTempObjects()
  4601. {
  4602. DateTime now = DateTime.UtcNow;
  4603. EntityBase[] entities = GetEntities();
  4604. foreach (EntityBase obj in entities)
  4605. {
  4606. if (obj is SceneObjectGroup)
  4607. {
  4608. SceneObjectGroup grp = (SceneObjectGroup)obj;
  4609. if (!grp.IsDeleted)
  4610. {
  4611. if ((grp.RootPart.Flags & PrimFlags.TemporaryOnRez) != 0)
  4612. {
  4613. if (grp.GetSittingAvatarsCount() == 0 && grp.RootPart.Expires <= now)
  4614. DeleteSceneObject(grp, false);
  4615. }
  4616. }
  4617. }
  4618. }
  4619. }
  4620. public void DeleteFromStorage(UUID uuid)
  4621. {
  4622. SimulationDataService.RemoveObject(uuid, RegionInfo.RegionID);
  4623. }
  4624. public int GetHealth(out int flags, out string message)
  4625. {
  4626. // Returns:
  4627. // 1 = sim is up and accepting http requests. The heartbeat has
  4628. // stopped and the sim is probably locked up, but a remote
  4629. // admin restart may succeed
  4630. //
  4631. // 2 = Sim is up and the heartbeat is running. The sim is likely
  4632. // usable for people within
  4633. //
  4634. // 3 = Sim is up and one packet thread is running. Sim is
  4635. // unstable and will not accept new logins
  4636. //
  4637. // 4 = Sim is up and both packet threads are running. Sim is
  4638. // likely usable
  4639. //
  4640. // 5 = We have seen a new user enter within the past 4 minutes
  4641. // which can be seen as positive confirmation of sim health
  4642. //
  4643. int health = 1; // Start at 1, means we're up
  4644. flags = 0;
  4645. message = String.Empty;
  4646. CheckHeartbeat();
  4647. if (m_firstHeartbeat || (m_lastIncoming == 0 && m_lastOutgoing == 0))
  4648. {
  4649. // We're still starting
  4650. // 0 means "in startup", it can't happen another way, since
  4651. // to get here, we must be able to accept http connections
  4652. return 0;
  4653. }
  4654. if ((Util.EnvironmentTickCountSubtract(m_lastFrameTick)) < 2000)
  4655. {
  4656. health+=1;
  4657. flags |= 1;
  4658. }
  4659. if (Util.EnvironmentTickCountSubtract(m_lastIncoming) < 2000)
  4660. {
  4661. health+=1;
  4662. flags |= 2;
  4663. }
  4664. if (Util.EnvironmentTickCountSubtract(m_lastOutgoing) < 2000)
  4665. {
  4666. health+=1;
  4667. flags |= 4;
  4668. }
  4669. /*
  4670. else
  4671. {
  4672. int pid = System.Diagnostics.Process.GetCurrentProcess().Id;
  4673. System.Diagnostics.Process proc = new System.Diagnostics.Process();
  4674. proc.EnableRaisingEvents=false;
  4675. proc.StartInfo.FileName = "/bin/kill";
  4676. proc.StartInfo.Arguments = "-QUIT " + pid.ToString();
  4677. proc.Start();
  4678. proc.WaitForExit();
  4679. Thread.Sleep(1000);
  4680. Environment.Exit(1);
  4681. }
  4682. */
  4683. if (flags != 7)
  4684. return health;
  4685. // A login in the last 4 mins? We can't be doing too badly
  4686. //
  4687. if (Util.EnvironmentTickCountSubtract(m_LastLogin) < 240000)
  4688. health++;
  4689. else
  4690. return health;
  4691. return health;
  4692. }
  4693. // This callback allows the PhysicsScene to call back to its caller (the SceneGraph) and
  4694. // update non-physical objects like the joint proxy objects that represent the position
  4695. // of the joints in the scene.
  4696. // This routine is normally called from within a lock (OdeLock) from within the OdePhysicsScene
  4697. // WARNING: be careful of deadlocks here if you manipulate the scene. Remember you are being called
  4698. // from within the OdePhysicsScene.
  4699. protected internal void jointMoved(PhysicsJoint joint)
  4700. {
  4701. // m_parentScene.PhysicsScene.DumpJointInfo(); // non-thread-locked version; we should already be in a lock (OdeLock) when this callback is invoked
  4702. SceneObjectPart jointProxyObject = GetSceneObjectPart(joint.ObjectNameInScene);
  4703. if (jointProxyObject == null)
  4704. {
  4705. jointErrorMessage(joint, "WARNING, joint proxy not found, name " + joint.ObjectNameInScene);
  4706. return;
  4707. }
  4708. // now update the joint proxy object in the scene to have the position of the joint as returned by the physics engine
  4709. SceneObjectPart trackedBody = GetSceneObjectPart(joint.TrackedBodyName); // FIXME: causes a sequential lookup
  4710. if (trackedBody == null) return; // the actor may have been deleted but the joint still lingers around a few frames waiting for deletion. during this time, trackedBody is NULL to prevent further motion of the joint proxy.
  4711. jointProxyObject.Velocity = trackedBody.Velocity;
  4712. jointProxyObject.AngularVelocity = trackedBody.AngularVelocity;
  4713. switch (joint.Type)
  4714. {
  4715. case PhysicsJointType.Ball:
  4716. {
  4717. Vector3 jointAnchor = PhysicsScene.GetJointAnchor(joint);
  4718. Vector3 proxyPos = jointAnchor;
  4719. jointProxyObject.ParentGroup.UpdateGroupPosition(proxyPos); // schedules the entire group for a terse update
  4720. }
  4721. break;
  4722. case PhysicsJointType.Hinge:
  4723. {
  4724. Vector3 jointAnchor = PhysicsScene.GetJointAnchor(joint);
  4725. // Normally, we would just ask the physics scene to return the axis for the joint.
  4726. // Unfortunately, ODE sometimes returns <0,0,0> for the joint axis, which should
  4727. // never occur. Therefore we cannot rely on ODE to always return a correct joint axis.
  4728. // Therefore the following call does not always work:
  4729. //PhysicsVector phyJointAxis = _PhyScene.GetJointAxis(joint);
  4730. // instead we compute the joint orientation by saving the original joint orientation
  4731. // relative to one of the jointed bodies, and applying this transformation
  4732. // to the current position of the jointed bodies (the tracked body) to compute the
  4733. // current joint orientation.
  4734. if (joint.TrackedBodyName == null)
  4735. {
  4736. jointErrorMessage(joint, "joint.TrackedBodyName is null, joint " + joint.ObjectNameInScene);
  4737. }
  4738. Vector3 proxyPos = jointAnchor;
  4739. Quaternion q = trackedBody.RotationOffset * joint.LocalRotation;
  4740. jointProxyObject.ParentGroup.UpdateGroupPosition(proxyPos); // schedules the entire group for a terse update
  4741. jointProxyObject.ParentGroup.UpdateGroupRotationR(q); // schedules the entire group for a terse update
  4742. }
  4743. break;
  4744. }
  4745. }
  4746. // This callback allows the PhysicsScene to call back to its caller (the SceneGraph) and
  4747. // update non-physical objects like the joint proxy objects that represent the position
  4748. // of the joints in the scene.
  4749. // This routine is normally called from within a lock (OdeLock) from within the OdePhysicsScene
  4750. // WARNING: be careful of deadlocks here if you manipulate the scene. Remember you are being called
  4751. // from within the OdePhysicsScene.
  4752. protected internal void jointDeactivated(PhysicsJoint joint)
  4753. {
  4754. //m_log.Debug("[NINJA] SceneGraph.jointDeactivated, joint:" + joint.ObjectNameInScene);
  4755. SceneObjectPart jointProxyObject = GetSceneObjectPart(joint.ObjectNameInScene);
  4756. if (jointProxyObject == null)
  4757. {
  4758. jointErrorMessage(joint, "WARNING, trying to deactivate (stop interpolation of) joint proxy, but not found, name " + joint.ObjectNameInScene);
  4759. return;
  4760. }
  4761. // turn the proxy non-physical, which also stops its client-side interpolation
  4762. bool wasUsingPhysics = ((jointProxyObject.Flags & PrimFlags.Physics) != 0);
  4763. if (wasUsingPhysics)
  4764. {
  4765. jointProxyObject.UpdatePrimFlags(false, false, true, false,false); // FIXME: possible deadlock here; check to make sure all the scene alterations set into motion here won't deadlock
  4766. }
  4767. }
  4768. // This callback allows the PhysicsScene to call back to its caller (the SceneGraph) and
  4769. // alert the user of errors by using the debug channel in the same way that scripts alert
  4770. // the user of compile errors.
  4771. // This routine is normally called from within a lock (OdeLock) from within the OdePhysicsScene
  4772. // WARNING: be careful of deadlocks here if you manipulate the scene. Remember you are being called
  4773. // from within the OdePhysicsScene.
  4774. public void jointErrorMessage(PhysicsJoint joint, string message)
  4775. {
  4776. if (joint != null)
  4777. {
  4778. if (joint.ErrorMessageCount > PhysicsJoint.maxErrorMessages)
  4779. return;
  4780. SceneObjectPart jointProxyObject = GetSceneObjectPart(joint.ObjectNameInScene);
  4781. if (jointProxyObject != null)
  4782. {
  4783. SimChat(Utils.StringToBytes("[NINJA]: " + message),
  4784. ChatTypeEnum.DebugChannel,
  4785. 2147483647,
  4786. jointProxyObject.AbsolutePosition,
  4787. jointProxyObject.Name,
  4788. jointProxyObject.UUID,
  4789. false);
  4790. joint.ErrorMessageCount++;
  4791. if (joint.ErrorMessageCount > PhysicsJoint.maxErrorMessages)
  4792. {
  4793. SimChat(Utils.StringToBytes("[NINJA]: Too many messages for this joint, suppressing further messages."),
  4794. ChatTypeEnum.DebugChannel,
  4795. 2147483647,
  4796. jointProxyObject.AbsolutePosition,
  4797. jointProxyObject.Name,
  4798. jointProxyObject.UUID,
  4799. false);
  4800. }
  4801. }
  4802. else
  4803. {
  4804. // couldn't find the joint proxy object; the error message is silently suppressed
  4805. }
  4806. }
  4807. }
  4808. public Scene ConsoleScene()
  4809. {
  4810. if (MainConsole.Instance == null)
  4811. return null;
  4812. if (MainConsole.Instance.ConsoleScene is Scene)
  4813. return (Scene)MainConsole.Instance.ConsoleScene;
  4814. return null;
  4815. }
  4816. // Get terrain height at the specified <x,y> location.
  4817. // Presumes the underlying implementation is a heightmap which is a 1m grid.
  4818. // Finds heightmap grid points before and after the point and
  4819. // does a linear approximation of the height at this intermediate point.
  4820. public float GetGroundHeight(float x, float y)
  4821. {
  4822. if (x < 0)
  4823. x = 0;
  4824. if (x >= Heightmap.Width)
  4825. x = Heightmap.Width - 1;
  4826. if (y < 0)
  4827. y = 0;
  4828. if (y >= Heightmap.Height)
  4829. y = Heightmap.Height - 1;
  4830. Vector3 p0 = new Vector3(x, y, (float)Heightmap[(int)x, (int)y]);
  4831. Vector3 p1 = p0;
  4832. Vector3 p2 = p0;
  4833. p1.X += 1.0f;
  4834. if (p1.X < Heightmap.Width)
  4835. p1.Z = (float)Heightmap[(int)p1.X, (int)p1.Y];
  4836. p2.Y += 1.0f;
  4837. if (p2.Y < Heightmap.Height)
  4838. p2.Z = (float)Heightmap[(int)p2.X, (int)p2.Y];
  4839. Vector3 v0 = new Vector3(p1.X - p0.X, p1.Y - p0.Y, p1.Z - p0.Z);
  4840. Vector3 v1 = new Vector3(p2.X - p0.X, p2.Y - p0.Y, p2.Z - p0.Z);
  4841. v0.Normalize();
  4842. v1.Normalize();
  4843. Vector3 vsn = new Vector3();
  4844. vsn.X = (v0.Y * v1.Z) - (v0.Z * v1.Y);
  4845. vsn.Y = (v0.Z * v1.X) - (v0.X * v1.Z);
  4846. vsn.Z = (v0.X * v1.Y) - (v0.Y * v1.X);
  4847. vsn.Normalize();
  4848. float xdiff = x - (float)((int)x);
  4849. float ydiff = y - (float)((int)y);
  4850. return (((vsn.X * xdiff) + (vsn.Y * ydiff)) / (-1 * vsn.Z)) + p0.Z;
  4851. }
  4852. private void CheckHeartbeat()
  4853. {
  4854. if (m_firstHeartbeat)
  4855. return;
  4856. if ((Util.EnvironmentTickCountSubtract(m_lastFrameTick)) > 5000)
  4857. Start();
  4858. }
  4859. public override ISceneObject DeserializeObject(string representation)
  4860. {
  4861. return SceneObjectSerializer.FromXml2Format(representation);
  4862. }
  4863. public override bool AllowScriptCrossings
  4864. {
  4865. get { return m_allowScriptCrossings; }
  4866. }
  4867. public Vector3 GetNearestAllowedPosition(ScenePresence avatar)
  4868. {
  4869. return GetNearestAllowedPosition(avatar, null);
  4870. }
  4871. public Vector3 GetNearestAllowedPosition(ScenePresence avatar, ILandObject excludeParcel)
  4872. {
  4873. Vector3 pos = avatar.AbsolutePosition;
  4874. ILandObject nearestParcel = GetNearestAllowedParcel(avatar.UUID, pos.X, pos.Y, excludeParcel);
  4875. if (nearestParcel != null)
  4876. {
  4877. Vector2? nearestPoint = null;
  4878. Vector3 dir = -avatar.Velocity;
  4879. float dirlen = dir.Length();
  4880. if(dirlen > 1.0f)
  4881. //Try to get a location that feels like where they came from
  4882. nearestPoint = nearestParcel.GetNearestPointAlongDirection(pos, dir);
  4883. if (nearestPoint == null)
  4884. nearestPoint = nearestParcel.GetNearestPoint(pos);
  4885. if (nearestPoint != null)
  4886. {
  4887. return GetPositionAtAvatarHeightOrGroundHeight(avatar,
  4888. nearestPoint.Value.X, nearestPoint.Value.Y);
  4889. }
  4890. ILandObject dest = LandChannel.GetLandObject(avatar.lastKnownAllowedPosition.X, avatar.lastKnownAllowedPosition.Y);
  4891. if (dest != excludeParcel)
  4892. {
  4893. // Ultimate backup if we have no idea where they are and
  4894. // the last allowed position was in another parcel
  4895. m_log.Debug("Have no idea where they are, sending them to: " + avatar.lastKnownAllowedPosition.ToString());
  4896. return avatar.lastKnownAllowedPosition;
  4897. }
  4898. // else fall through to region edge
  4899. }
  4900. //Go to the edge, this happens in teleporting to a region with no available parcels
  4901. Vector3 nearestRegionEdgePoint = GetNearestRegionEdgePosition(avatar);
  4902. //Debug.WriteLine("They are really in a place they don't belong, sending them to: " + nearestRegionEdgePoint.ToString());
  4903. return nearestRegionEdgePoint;
  4904. }
  4905. private Vector3 GetParcelCenterAtGround(ILandObject parcel)
  4906. {
  4907. Vector2 center = parcel.CenterPoint;
  4908. return GetPositionAtGround(center.X, center.Y);
  4909. }
  4910. public ILandObject GetNearestAllowedParcel(UUID avatarId, float x, float y)
  4911. {
  4912. return GetNearestAllowedParcel(avatarId, x, y, null);
  4913. }
  4914. public ILandObject GetNearestAllowedParcel(UUID avatarId, float x, float y, ILandObject excludeParcel)
  4915. {
  4916. if(LandChannel == null)
  4917. return null;
  4918. List<ILandObject> all = LandChannel.AllParcels();
  4919. if(all == null || all.Count == 0)
  4920. return null;
  4921. float minParcelDistanceSQ = float.MaxValue;
  4922. ILandObject nearestParcel = null;
  4923. Vector2 curCenter;
  4924. float parcelDistanceSQ;
  4925. foreach (var parcel in all)
  4926. {
  4927. if (parcel != excludeParcel && !parcel.IsEitherBannedOrRestricted(avatarId))
  4928. {
  4929. curCenter = parcel.CenterPoint;
  4930. curCenter.X -= x;
  4931. curCenter.Y -= y;
  4932. parcelDistanceSQ = curCenter.LengthSquared();
  4933. if (parcelDistanceSQ < minParcelDistanceSQ)
  4934. {
  4935. minParcelDistanceSQ = parcelDistanceSQ;
  4936. nearestParcel = parcel;
  4937. }
  4938. }
  4939. }
  4940. return nearestParcel;
  4941. }
  4942. private Vector2 GetParcelSafeCorner(ILandObject parcel)
  4943. {
  4944. Vector2 place = parcel.StartPoint;
  4945. place.X += 2f;
  4946. place.Y += 2f;
  4947. return place;
  4948. }
  4949. private Vector3 GetNearestRegionEdgePosition(ScenePresence avatar)
  4950. {
  4951. float posX = avatar.AbsolutePosition.X;
  4952. float posY = avatar.AbsolutePosition.Y;
  4953. float regionSizeX = RegionInfo.RegionSizeX;
  4954. float halfRegionSizeX = regionSizeX * 0.5f;
  4955. float regionSizeY = RegionInfo.RegionSizeY;
  4956. float halfRegionSizeY = regionSizeY * 0.5f;
  4957. float xdistance = posX < halfRegionSizeX ? posX : regionSizeX - posX;
  4958. float ydistance = posY < halfRegionSizeY ? posY : regionSizeY - posY;
  4959. //find out what vertical edge to go to
  4960. if (xdistance < ydistance)
  4961. {
  4962. if (posX < halfRegionSizeX)
  4963. return GetPositionAtAvatarHeightOrGroundHeight(avatar, 0.5f, posY);
  4964. else
  4965. return GetPositionAtAvatarHeightOrGroundHeight(avatar, regionSizeX - 0.5f, posY);
  4966. }
  4967. //find out what horizontal edge to go to
  4968. else
  4969. {
  4970. if (posY < halfRegionSizeY)
  4971. return GetPositionAtAvatarHeightOrGroundHeight(avatar, posX, 0.5f);
  4972. else
  4973. return GetPositionAtAvatarHeightOrGroundHeight(avatar, posX, regionSizeY - 0.5f);
  4974. }
  4975. }
  4976. private Vector3 GetPositionAtAvatarHeightOrGroundHeight(ScenePresence avatar, float x, float y)
  4977. {
  4978. Vector3 ground = GetPositionAtGround(x, y);
  4979. if(avatar.Appearance != null)
  4980. ground.Z += avatar.Appearance.AvatarHeight * 0.5f;
  4981. else
  4982. ground.Z += 0.8f;
  4983. if (avatar.AbsolutePosition.Z > ground.Z)
  4984. {
  4985. ground.Z = avatar.AbsolutePosition.Z;
  4986. }
  4987. return ground;
  4988. }
  4989. private Vector3 GetPositionAtGround(float x, float y)
  4990. {
  4991. return new Vector3(x, y, GetGroundHeight(x, y));
  4992. }
  4993. public List<UUID> GetEstateRegions(int estateID)
  4994. {
  4995. IEstateDataService estateDataService = EstateDataService;
  4996. if (estateDataService == null)
  4997. return new List<UUID>(0);
  4998. return estateDataService.GetRegions(estateID);
  4999. }
  5000. public void ReloadEstateData()
  5001. {
  5002. IEstateDataService estateDataService = EstateDataService;
  5003. if (estateDataService != null)
  5004. {
  5005. RegionInfo.EstateSettings = estateDataService.LoadEstateSettings(RegionInfo.RegionID, false);
  5006. TriggerEstateSunUpdate();
  5007. }
  5008. }
  5009. public void TriggerEstateSunUpdate()
  5010. {
  5011. EventManager.TriggerEstateToolsSunUpdate(RegionInfo.RegionHandle);
  5012. }
  5013. private void HandleReloadEstate(string module, string[] cmd)
  5014. {
  5015. if (MainConsole.Instance.ConsoleScene == null ||
  5016. (MainConsole.Instance.ConsoleScene is Scene &&
  5017. (Scene)MainConsole.Instance.ConsoleScene == this))
  5018. {
  5019. ReloadEstateData();
  5020. }
  5021. }
  5022. /// <summary>
  5023. /// Get the volume of space that will encompass all the given objects.
  5024. /// </summary>
  5025. /// <param name="objects"></param>
  5026. /// <param name="minX"></param>
  5027. /// <param name="maxX"></param>
  5028. /// <param name="minY"></param>
  5029. /// <param name="maxY"></param>
  5030. /// <param name="minZ"></param>
  5031. /// <param name="maxZ"></param>
  5032. /// <returns></returns>
  5033. public static Vector3[] GetCombinedBoundingBox(
  5034. List<SceneObjectGroup> objects,
  5035. out float minX, out float maxX, out float minY, out float maxY, out float minZ, out float maxZ)
  5036. {
  5037. minX = float.MaxValue;
  5038. maxX = float.MinValue;
  5039. minY = float.MaxValue;
  5040. maxY = float.MinValue;
  5041. minZ = float.MaxValue;
  5042. maxZ = float.MinValue;
  5043. List<Vector3> offsets = new List<Vector3>();
  5044. foreach (SceneObjectGroup g in objects)
  5045. {
  5046. float ominX, ominY, ominZ, omaxX, omaxY, omaxZ;
  5047. Vector3 vec = g.AbsolutePosition;
  5048. g.GetAxisAlignedBoundingBoxRaw(out ominX, out omaxX, out ominY, out omaxY, out ominZ, out omaxZ);
  5049. // m_log.DebugFormat(
  5050. // "[SCENE]: For {0} found AxisAlignedBoundingBoxRaw {1}, {2}",
  5051. // g.Name, new Vector3(ominX, ominY, ominZ), new Vector3(omaxX, omaxY, omaxZ));
  5052. ominX += vec.X;
  5053. omaxX += vec.X;
  5054. ominY += vec.Y;
  5055. omaxY += vec.Y;
  5056. ominZ += vec.Z;
  5057. omaxZ += vec.Z;
  5058. if (minX > ominX)
  5059. minX = ominX;
  5060. if (minY > ominY)
  5061. minY = ominY;
  5062. if (minZ > ominZ)
  5063. minZ = ominZ;
  5064. if (maxX < omaxX)
  5065. maxX = omaxX;
  5066. if (maxY < omaxY)
  5067. maxY = omaxY;
  5068. if (maxZ < omaxZ)
  5069. maxZ = omaxZ;
  5070. }
  5071. foreach (SceneObjectGroup g in objects)
  5072. {
  5073. Vector3 vec = g.AbsolutePosition;
  5074. vec.X -= minX;
  5075. vec.Y -= minY;
  5076. vec.Z -= minZ;
  5077. offsets.Add(vec);
  5078. }
  5079. return offsets.ToArray();
  5080. }
  5081. /// <summary>
  5082. /// Regenerate the maptile for this scene.
  5083. /// </summary>
  5084. /// <param name="sender"></param>
  5085. /// <param name="e"></param>
  5086. private void RegenerateMaptile()
  5087. {
  5088. IWorldMapModule mapModule = RequestModuleInterface<IWorldMapModule>();
  5089. if (mapModule != null)
  5090. mapModule.GenerateMaptile();
  5091. }
  5092. // public void CleanDroppedAttachments()
  5093. // {
  5094. // List<SceneObjectGroup> objectsToDelete =
  5095. // new List<SceneObjectGroup>();
  5096. //
  5097. // lock (m_cleaningAttachments)
  5098. // {
  5099. // ForEachSOG(delegate (SceneObjectGroup grp)
  5100. // {
  5101. // if (grp.RootPart.Shape.PCode == 0 && grp.RootPart.Shape.State != 0 && (!objectsToDelete.Contains(grp)))
  5102. // {
  5103. // UUID agentID = grp.OwnerID;
  5104. // if (agentID == UUID.Zero)
  5105. // {
  5106. // objectsToDelete.Add(grp);
  5107. // return;
  5108. // }
  5109. //
  5110. // ScenePresence sp = GetScenePresence(agentID);
  5111. // if (sp == null)
  5112. // {
  5113. // objectsToDelete.Add(grp);
  5114. // return;
  5115. // }
  5116. // }
  5117. // });
  5118. // }
  5119. //
  5120. // foreach (SceneObjectGroup grp in objectsToDelete)
  5121. // {
  5122. // m_log.InfoFormat("[SCENE]: Deleting dropped attachment {0} of user {1}", grp.UUID, grp.OwnerID);
  5123. // DeleteSceneObject(grp, true);
  5124. // }
  5125. // }
  5126. public void ThreadAlive(int threadCode)
  5127. {
  5128. switch(threadCode)
  5129. {
  5130. case 1: // Incoming
  5131. m_lastIncoming = Util.EnvironmentTickCount();
  5132. break;
  5133. case 2: // Incoming
  5134. m_lastOutgoing = Util.EnvironmentTickCount();
  5135. break;
  5136. }
  5137. }
  5138. public void RegenerateMaptileAndReregister(object sender, ElapsedEventArgs e)
  5139. {
  5140. RegenerateMaptile();
  5141. // We need to propagate the new image UUID to the grid service
  5142. // so that all simulators can retrieve it
  5143. string error = GridService.RegisterRegion(RegionInfo.ScopeID, new GridRegion(RegionInfo));
  5144. if (error != string.Empty)
  5145. throw new Exception(error);
  5146. if(m_generateMaptiles)
  5147. m_mapGenerationTimer.Start();
  5148. }
  5149. /// <summary>
  5150. /// This method is called across the simulation connector to
  5151. /// determine if a given agent is allowed in this region
  5152. /// AS A ROOT AGENT
  5153. /// </summary>
  5154. /// <remarks>
  5155. /// Returning false here will prevent them
  5156. /// from logging into the region, teleporting into the region
  5157. /// or corssing the broder walking, but will NOT prevent
  5158. /// child agent creation, thereby emulating the SL behavior.
  5159. /// </remarks>
  5160. /// <param name='agentID'>The visitor's User ID</param>
  5161. /// <param name="agentHomeURI">The visitor's Home URI (may be null)</param>
  5162. /// <param name='position'></param>
  5163. /// <param name='reason'></param>
  5164. /// <returns></returns>
  5165. public bool QueryAccess(UUID agentID, string agentHomeURI, bool viaTeleport, Vector3 position, List<UUID> features, out string reason)
  5166. {
  5167. reason = string.Empty;
  5168. if (Permissions.IsGod(agentID))
  5169. return true;
  5170. if (!AllowAvatarCrossing && !viaTeleport)
  5171. {
  5172. reason = "Region Crossing not allowed";
  5173. return false;
  5174. }
  5175. bool isAdmin = Permissions.IsAdministrator(agentID);
  5176. bool isManager = Permissions.IsEstateManager(agentID);
  5177. // FIXME: Root agent count is currently known to be inaccurate. This forces a recount before we check.
  5178. // However, the long term fix is to make sure root agent count is always accurate.
  5179. m_sceneGraph.RecalculateStats();
  5180. int num = m_sceneGraph.GetRootAgentCount();
  5181. if (num >= RegionInfo.RegionSettings.AgentLimit)
  5182. {
  5183. if (!(isAdmin || isManager))
  5184. {
  5185. reason = "The region is full";
  5186. m_log.DebugFormat(
  5187. "[SCENE]: Denying presence with id {0} entry into {1} since region is at agent limit of {2}",
  5188. agentID, RegionInfo.RegionName, RegionInfo.RegionSettings.AgentLimit);
  5189. return false;
  5190. }
  5191. }
  5192. ScenePresence presence = GetScenePresence(agentID);
  5193. IClientAPI client = null;
  5194. AgentCircuitData aCircuit = null;
  5195. if (presence != null)
  5196. {
  5197. client = presence.ControllingClient;
  5198. if (client != null)
  5199. aCircuit = client.RequestClientInfo();
  5200. }
  5201. // We may be called before there is a presence or a client.
  5202. // Fake AgentCircuitData to keep IAuthorizationModule smiling
  5203. if (client == null)
  5204. {
  5205. aCircuit = new AgentCircuitData();
  5206. aCircuit.AgentID = agentID;
  5207. aCircuit.firstname = String.Empty;
  5208. aCircuit.lastname = String.Empty;
  5209. }
  5210. try
  5211. {
  5212. if (!AuthorizeUser(aCircuit, false, out reason))
  5213. {
  5214. //m_log.DebugFormat("[SCENE]: Denying access for {0}", agentID);
  5215. // reason = "Region authorization fail";
  5216. return false;
  5217. }
  5218. }
  5219. catch (Exception e)
  5220. {
  5221. m_log.DebugFormat("[SCENE]: Exception authorizing agent: {0} " + e.StackTrace, e.Message);
  5222. reason = "Error authorizing agent: " + e.Message;
  5223. return false;
  5224. }
  5225. // last check aditional land access restrictions and relocations
  5226. // if crossing (viaTeleport false) check only the specified parcel
  5227. return CheckLandPositionAccess(agentID, viaTeleport, true, position, out reason);
  5228. }
  5229. // check access to land.
  5230. public bool CheckLandPositionAccess(UUID agentID, bool NotCrossing, bool checkTeleHub, Vector3 position, out string reason)
  5231. {
  5232. reason = string.Empty;
  5233. if (Permissions.IsGod(agentID))
  5234. return true;
  5235. // Permissions.IsAdministrator is the same as IsGod for now
  5236. // bool isAdmin = Permissions.IsAdministrator(agentID);
  5237. // if(isAdmin)
  5238. // return true;
  5239. // also honor estate managers access rights
  5240. bool isManager = Permissions.IsEstateManager(agentID);
  5241. if(isManager)
  5242. return true;
  5243. if (NotCrossing)
  5244. {
  5245. if (!RegionInfo.EstateSettings.AllowDirectTeleport)
  5246. {
  5247. SceneObjectGroup telehub;
  5248. if (RegionInfo.RegionSettings.TelehubObject != UUID.Zero && (telehub = GetSceneObjectGroup (RegionInfo.RegionSettings.TelehubObject)) != null && checkTeleHub)
  5249. {
  5250. bool banned = true;
  5251. bool validTelehub = false;
  5252. List<SpawnPoint> spawnPoints = RegionInfo.RegionSettings.SpawnPoints();
  5253. Vector3 spawnPoint;
  5254. ILandObject land = null;
  5255. Vector3 telehubPosition = telehub.AbsolutePosition;
  5256. if(spawnPoints.Count == 0)
  5257. {
  5258. // will this ever happen?
  5259. // if so use the telehub object position
  5260. spawnPoint = telehubPosition;
  5261. land = LandChannel.GetLandObject(spawnPoint.X, spawnPoint.Y);
  5262. if(land != null && !land.IsEitherBannedOrRestricted(agentID))
  5263. {
  5264. banned = false;
  5265. validTelehub = true;
  5266. }
  5267. }
  5268. else
  5269. {
  5270. Quaternion telehubRotation = telehub.GroupRotation;
  5271. foreach (SpawnPoint spawn in spawnPoints)
  5272. {
  5273. spawnPoint = spawn.GetLocation(telehubPosition, telehubRotation);
  5274. land = LandChannel.GetLandObject(spawnPoint.X, spawnPoint.Y);
  5275. if (land == null)
  5276. continue;
  5277. validTelehub = true;
  5278. if (!land.IsEitherBannedOrRestricted(agentID))
  5279. {
  5280. banned = false;
  5281. break;
  5282. }
  5283. }
  5284. }
  5285. if(validTelehub)
  5286. {
  5287. if (banned)
  5288. {
  5289. reason = "No suitable landing point found";
  5290. return false;
  5291. }
  5292. else
  5293. return true;
  5294. }
  5295. // possible broken telehub, fall into normal check
  5296. }
  5297. }
  5298. float posX = position.X;
  5299. float posY = position.Y;
  5300. // allow position relocation
  5301. if (!TestLandRestrictions(agentID, out reason, ref posX, ref posY))
  5302. {
  5303. // m_log.DebugFormat("[SCENE]: Denying {0} because they are banned on all parcels", agentID);
  5304. reason = "You dont have access to the region parcels";
  5305. return false;
  5306. }
  5307. }
  5308. else // check for query region crossing only
  5309. {
  5310. // no relocation allowed on crossings
  5311. ILandObject land = LandChannel.GetLandObject(position.X, position.Y);
  5312. if (land == null)
  5313. {
  5314. reason = "No parcel found";
  5315. return false;
  5316. }
  5317. bool banned = land.IsBannedFromLand(agentID);
  5318. bool restricted = land.IsRestrictedFromLand(agentID);
  5319. if (banned || restricted)
  5320. {
  5321. if (banned)
  5322. reason = "You are banned from the parcel";
  5323. else
  5324. reason = "The parcel is restricted";
  5325. return false;
  5326. }
  5327. }
  5328. return true;
  5329. }
  5330. public void StartTimerWatchdog()
  5331. {
  5332. m_timerWatchdog.Interval = 1000;
  5333. m_timerWatchdog.Elapsed += TimerWatchdog;
  5334. m_timerWatchdog.AutoReset = true;
  5335. m_timerWatchdog.Start();
  5336. }
  5337. public void TimerWatchdog(object sender, ElapsedEventArgs e)
  5338. {
  5339. CheckHeartbeat();
  5340. IEtcdModule etcd = RequestModuleInterface<IEtcdModule>();
  5341. int flags;
  5342. string message;
  5343. if (etcd != null)
  5344. {
  5345. int health = GetHealth(out flags, out message);
  5346. if (health != m_lastHealth)
  5347. {
  5348. m_lastHealth = health;
  5349. etcd.Store("Health", health.ToString(), 300000);
  5350. etcd.Store("HealthFlags", flags.ToString(), 300000);
  5351. }
  5352. int roots = 0;
  5353. foreach (ScenePresence sp in GetScenePresences())
  5354. if (!sp.IsChildAgent && !sp.IsNPC)
  5355. roots++;
  5356. if (m_lastUsers != roots)
  5357. {
  5358. m_lastUsers = roots;
  5359. etcd.Store("RootAgents", roots.ToString(), 300000);
  5360. }
  5361. }
  5362. }
  5363. /// This method deals with movement when an avatar is automatically moving (but this is distinct from the
  5364. /// autopilot that moves an avatar to a sit target!.
  5365. /// </summary>
  5366. /// <remarks>
  5367. /// This is not intended as a permament location for this method.
  5368. /// </remarks>
  5369. /// <param name="presence"></param>
  5370. /* move to target is now done on presence update
  5371. private void HandleOnSignificantClientMovement(ScenePresence presence)
  5372. {
  5373. if (presence.MovingToTarget)
  5374. {
  5375. double distanceToTarget = Util.GetDistanceTo(presence.AbsolutePosition, presence.MoveToPositionTarget);
  5376. // m_log.DebugFormat(
  5377. // "[SCENE]: Abs pos of {0} is {1}, target {2}, distance {3}",
  5378. // presence.Name, presence.AbsolutePosition, presence.MoveToPositionTarget, distanceToTarget);
  5379. // Check the error term of the current position in relation to the target position
  5380. if (distanceToTarget <= ScenePresence.SIGNIFICANT_MOVEMENT)
  5381. {
  5382. // We are close enough to the target
  5383. // m_log.DebugFormat("[SCENEE]: Stopping autopilot of {0}", presence.Name);
  5384. presence.Velocity = Vector3.Zero;
  5385. presence.AbsolutePosition = presence.MoveToPositionTarget;
  5386. presence.ResetMoveToTarget();
  5387. if (presence.Flying)
  5388. {
  5389. // A horrible hack to stop the avatar dead in its tracks rather than having them overshoot
  5390. // the target if flying.
  5391. // We really need to be more subtle (slow the avatar as it approaches the target) or at
  5392. // least be able to set collision status once, rather than 5 times to give it enough
  5393. // weighting so that that PhysicsActor thinks it really is colliding.
  5394. for (int i = 0; i < 5; i++)
  5395. presence.IsColliding = true;
  5396. if (presence.LandAtTarget)
  5397. presence.Flying = false;
  5398. // Vector3 targetPos = presence.MoveToPositionTarget;
  5399. // float terrainHeight = (float)presence.Scene.Heightmap[(int)targetPos.X, (int)targetPos.Y];
  5400. // if (targetPos.Z - terrainHeight < 0.2)
  5401. // {
  5402. // presence.Flying = false;
  5403. // }
  5404. }
  5405. // m_log.DebugFormat(
  5406. // "[SCENE]: AgentControlFlags {0}, MovementFlag {1} for {2}",
  5407. // presence.AgentControlFlags, presence.MovementFlag, presence.Name);
  5408. }
  5409. else
  5410. {
  5411. // m_log.DebugFormat(
  5412. // "[SCENE]: Updating npc {0} at {1} for next movement to {2}",
  5413. // presence.Name, presence.AbsolutePosition, presence.MoveToPositionTarget);
  5414. Vector3 agent_control_v3 = new Vector3();
  5415. presence.HandleMoveToTargetUpdate(1, ref agent_control_v3);
  5416. presence.AddNewMovement(agent_control_v3);
  5417. }
  5418. }
  5419. }
  5420. */
  5421. // manage and select spawn points in sequence
  5422. public int SpawnPoint()
  5423. {
  5424. int spawnpoints = RegionInfo.RegionSettings.SpawnPoints().Count;
  5425. if (spawnpoints == 0)
  5426. return 0;
  5427. m_SpawnPoint++;
  5428. if (m_SpawnPoint > spawnpoints)
  5429. m_SpawnPoint = 1;
  5430. return m_SpawnPoint - 1;
  5431. }
  5432. private void HandleGcCollect(string module, string[] args)
  5433. {
  5434. GC.Collect();
  5435. }
  5436. /// <summary>
  5437. /// Wrappers to get physics modules retrieve assets.
  5438. /// </summary>
  5439. /// <remarks>
  5440. /// Has to be done this way
  5441. /// because we can't assign the asset service to physics directly - at the
  5442. /// time physics are instantiated it's not registered but it will be by
  5443. /// the time the first prim exists.
  5444. /// </remarks>
  5445. /// <param name="assetID"></param>
  5446. /// <param name="callback"></param>
  5447. public void PhysicsRequestAsset(UUID assetID, AssetReceivedDelegate callback)
  5448. {
  5449. AssetService.Get(assetID.ToString(), callback, PhysicsAssetReceived);
  5450. }
  5451. private void PhysicsAssetReceived(string id, Object sender, AssetBase asset)
  5452. {
  5453. AssetReceivedDelegate callback = (AssetReceivedDelegate)sender;
  5454. callback(asset);
  5455. }
  5456. public string GetExtraSetting(string name)
  5457. {
  5458. if (m_extraSettings == null)
  5459. return String.Empty;
  5460. string val;
  5461. if (!m_extraSettings.TryGetValue(name, out val))
  5462. return String.Empty;
  5463. return val;
  5464. }
  5465. public void StoreExtraSetting(string name, string val)
  5466. {
  5467. if (m_extraSettings == null)
  5468. return;
  5469. string oldVal;
  5470. if (m_extraSettings.TryGetValue(name, out oldVal))
  5471. {
  5472. if (oldVal == val)
  5473. return;
  5474. }
  5475. m_extraSettings[name] = val;
  5476. m_SimulationDataService.SaveExtra(RegionInfo.RegionID, name, val);
  5477. m_eventManager.TriggerExtraSettingChanged(this, name, val);
  5478. }
  5479. public void RemoveExtraSetting(string name)
  5480. {
  5481. if (m_extraSettings == null)
  5482. return;
  5483. if (!m_extraSettings.ContainsKey(name))
  5484. return;
  5485. m_extraSettings.Remove(name);
  5486. m_SimulationDataService.RemoveExtra(RegionInfo.RegionID, name);
  5487. m_eventManager.TriggerExtraSettingChanged(this, name, String.Empty);
  5488. }
  5489. public bool InTeleportTargetsCoolDown(UUID sourceID, UUID targetID, double timeout)
  5490. {
  5491. lock(TeleportTargetsCoolDown)
  5492. {
  5493. UUID lastSource = UUID.Zero;
  5494. TeleportTargetsCoolDown.TryGetValue(targetID, out lastSource);
  5495. if(lastSource == UUID.Zero)
  5496. {
  5497. TeleportTargetsCoolDown.Add(targetID, sourceID, timeout);
  5498. return false;
  5499. }
  5500. TeleportTargetsCoolDown.AddOrUpdate(targetID, sourceID, timeout);
  5501. return lastSource == sourceID;
  5502. }
  5503. }
  5504. }
  5505. }