Scene.cs 245 KB

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