Scene.cs 212 KB

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