1
0

Scene.cs 215 KB

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