Scene.cs 252 KB

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