Scene.cs 179 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380
  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 OpenSim 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.Drawing;
  30. using System.Drawing.Imaging;
  31. using System.IO;
  32. using System.Xml;
  33. using System.Threading;
  34. using System.Timers;
  35. using OpenMetaverse;
  36. using OpenMetaverse.Imaging;
  37. using OpenMetaverse.Packets;
  38. using OpenSim.Framework;
  39. using OpenSim.Framework.Communications;
  40. using OpenSim.Framework.Communications.Cache;
  41. using OpenSim.Framework.Servers;
  42. using OpenSim.Region.Environment.Interfaces;
  43. using OpenSim.Region.Interfaces;
  44. using OpenSim.Region.Environment.Modules.World.Terrain;
  45. using OpenSim.Region.Environment.Scenes.Scripting;
  46. using OpenSim.Region.Physics.Manager;
  47. using Nini.Config;
  48. using Caps = OpenSim.Framework.Communications.Capabilities.Caps;
  49. using Image = System.Drawing.Image;
  50. using TPFlags = OpenSim.Framework.Constants.TeleportFlags;
  51. using Timer = System.Timers.Timer;
  52. using OSD = OpenMetaverse.StructuredData.OSD;
  53. namespace OpenSim.Region.Environment.Scenes
  54. {
  55. public delegate bool FilterAvatarList(ScenePresence avatar);
  56. public partial class Scene : SceneBase
  57. {
  58. public delegate void SynchronizeSceneHandler(Scene scene);
  59. public SynchronizeSceneHandler SynchronizeScene = null;
  60. public int splitID = 0;
  61. private const long DEFAULT_MIN_TIME_FOR_PERSISTENCE = 60L;
  62. private const long DEFAULT_MAX_TIME_FOR_PERSISTENCE = 600L;
  63. #region Fields
  64. protected Timer m_restartWaitTimer = new Timer();
  65. public SimStatsReporter StatsReporter;
  66. protected List<RegionInfo> m_regionRestartNotifyList = new List<RegionInfo>();
  67. protected List<RegionInfo> m_neighbours = new List<RegionInfo>();
  68. /// <value>
  69. /// The scene graph for this scene
  70. /// </value>
  71. /// TODO: Possibly stop other classes being able to manipulate this directly.
  72. public SceneGraph m_sceneGraph;
  73. /// <summary>
  74. /// Are we applying physics to any of the prims in this scene?
  75. /// </summary>
  76. public bool m_physicalPrim;
  77. public float m_maxNonphys = 65536;
  78. public float m_maxPhys = 10;
  79. public bool m_clampPrimSize = false;
  80. public bool m_trustBinaries = false;
  81. public bool m_allowScriptCrossings = false;
  82. public bool m_seeIntoRegionFromNeighbor;
  83. public int MaxUndoCount = 5;
  84. private int m_RestartTimerCounter;
  85. private readonly Timer m_restartTimer = new Timer(15000); // Wait before firing
  86. private int m_incrementsof15seconds = 0;
  87. private volatile bool m_backingup = false;
  88. private Dictionary<UUID, ReturnInfo> m_returns = new Dictionary<UUID, ReturnInfo>();
  89. protected string m_simulatorVersion = "OpenSimulator Server";
  90. protected ModuleLoader m_moduleLoader;
  91. protected StorageManager m_storageManager;
  92. protected AgentCircuitManager m_authenticateHandler;
  93. public CommunicationsManager CommsManager;
  94. protected SceneCommunicationService m_sceneGridService;
  95. public SceneCommunicationService SceneGridService
  96. {
  97. get { return m_sceneGridService; }
  98. }
  99. /// <value>
  100. /// All the region modules attached to this scene.
  101. /// </value>
  102. public Dictionary<string, IRegionModule> Modules
  103. {
  104. get { return m_modules; }
  105. }
  106. protected Dictionary<string, IRegionModule> m_modules = new Dictionary<string, IRegionModule>();
  107. /// <value>
  108. /// The module interfaces available from this scene.
  109. /// </value>
  110. protected Dictionary<Type, List<object> > ModuleInterfaces = new Dictionary<Type, List<object> >();
  111. protected Dictionary<string, object> ModuleAPIMethods = new Dictionary<string, object>();
  112. protected Dictionary<string, ICommander> m_moduleCommanders = new Dictionary<string, ICommander>();
  113. //API module interfaces
  114. public IXfer XferManager;
  115. protected IXMLRPC m_xmlrpcModule;
  116. protected IWorldComm m_worldCommModule;
  117. protected IAvatarFactory m_AvatarFactory;
  118. protected IConfigSource m_config;
  119. protected IRegionSerialiserModule m_serialiser;
  120. protected IInterregionCommsOut m_interregionCommsOut;
  121. protected IInterregionCommsIn m_interregionCommsIn;
  122. protected IDialogModule m_dialogModule;
  123. protected internal ICapabilitiesModule CapsModule;
  124. // Central Update Loop
  125. protected int m_fps = 10;
  126. protected int m_frame = 0;
  127. protected float m_timespan = 0.089f;
  128. protected DateTime m_lastupdate = DateTime.Now;
  129. protected float m_timedilation = 1.0f;
  130. private int m_update_physics = 1;
  131. private int m_update_entitymovement = 1;
  132. private int m_update_entities = 1; // Run through all objects checking for updates
  133. private int m_update_entitiesquick = 200; // Run through objects that have scheduled updates checking for updates
  134. private int m_update_presences = 1; // Update scene presence movements
  135. private int m_update_events = 1;
  136. private int m_update_backup = 200;
  137. private int m_update_terrain = 50;
  138. private int m_update_land = 1;
  139. private int frameMS = 0;
  140. private int physicsMS2 = 0;
  141. private int physicsMS = 0;
  142. private int otherMS = 0;
  143. private bool m_physics_enabled = true;
  144. private bool m_scripts_enabled = true;
  145. private string m_defaultScriptEngine;
  146. private int m_LastLogin = 0;
  147. private Thread HeartbeatThread;
  148. private volatile bool shuttingdown = false;
  149. private object m_deleting_scene_object = new object();
  150. // the minimum time that must elapse before a changed object will be considered for persisted
  151. public long m_dontPersistBefore = DEFAULT_MIN_TIME_FOR_PERSISTENCE * 10000000L;
  152. // the maximum time that must elapse before a changed object will be considered for persisted
  153. public long m_persistAfter = DEFAULT_MAX_TIME_FOR_PERSISTENCE * 10000000L;
  154. #endregion
  155. #region Properties
  156. public AgentCircuitManager AuthenticateHandler
  157. {
  158. get { return m_authenticateHandler; }
  159. }
  160. public SceneGraph SceneContents
  161. {
  162. get { return m_sceneGraph; }
  163. }
  164. // an instance to the physics plugin's Scene object.
  165. public PhysicsScene PhysicsScene
  166. {
  167. get { return m_sceneGraph.PhysicsScene; }
  168. set
  169. {
  170. // If we're not doing the initial set
  171. // Then we've got to remove the previous
  172. // event handler
  173. if (PhysicsScene != null && PhysicsScene.SupportsNINJAJoints)
  174. {
  175. PhysicsScene.OnJointMoved -= jointMoved;
  176. PhysicsScene.OnJointDeactivated -= jointDeactivated;
  177. PhysicsScene.OnJointErrorMessage -= jointErrorMessage;
  178. }
  179. m_sceneGraph.PhysicsScene = value;
  180. if (PhysicsScene != null && m_sceneGraph.PhysicsScene.SupportsNINJAJoints)
  181. {
  182. // register event handlers to respond to joint movement/deactivation
  183. PhysicsScene.OnJointMoved += jointMoved;
  184. PhysicsScene.OnJointDeactivated += jointDeactivated;
  185. PhysicsScene.OnJointErrorMessage += jointErrorMessage;
  186. }
  187. }
  188. }
  189. // This gets locked so things stay thread safe.
  190. public object SyncRoot
  191. {
  192. get { return m_sceneGraph.m_syncRoot; }
  193. }
  194. public float TimeDilation
  195. {
  196. get { return m_timedilation; }
  197. }
  198. /// <summary>
  199. /// This is for llGetRegionFPS
  200. /// </summary>
  201. public float SimulatorFPS
  202. {
  203. get { return StatsReporter.getLastReportedSimFPS(); }
  204. }
  205. public string DefaultScriptEngine
  206. {
  207. get { return m_defaultScriptEngine; }
  208. }
  209. // Local reference to the objects in the scene (which are held in the scenegraph)
  210. // public Dictionary<UUID, SceneObjectGroup> Objects
  211. // {
  212. // get { return m_sceneGraph.SceneObjects; }
  213. // }
  214. // Reference to all of the agents in the scene (root and child)
  215. protected Dictionary<UUID, ScenePresence> m_scenePresences
  216. {
  217. get { return m_sceneGraph.ScenePresences; }
  218. set { m_sceneGraph.ScenePresences = value; }
  219. }
  220. // protected Dictionary<UUID, SceneObjectGroup> m_sceneObjects
  221. // {
  222. // get { return m_sceneGraph.SceneObjects; }
  223. // set { m_sceneGraph.SceneObjects = value; }
  224. // }
  225. public EntityManager Entities
  226. {
  227. get { return m_sceneGraph.Entities; }
  228. }
  229. public Dictionary<UUID, ScenePresence> m_restorePresences
  230. {
  231. get { return m_sceneGraph.RestorePresences; }
  232. set { m_sceneGraph.RestorePresences = value; }
  233. }
  234. public int objectCapacity = 45000;
  235. /// <value>
  236. /// Registered classes that are capable of creating entities.
  237. /// </value>
  238. protected Dictionary<PCode, IEntityCreator> m_entityCreators = new Dictionary<PCode, IEntityCreator>();
  239. #endregion
  240. #region Constructors
  241. public Scene(RegionInfo regInfo, AgentCircuitManager authen,
  242. CommunicationsManager commsMan, SceneCommunicationService sceneGridService,
  243. AssetCache assetCach, StorageManager storeManager,
  244. ModuleLoader moduleLoader, bool dumpAssetsToFile, bool physicalPrim,
  245. bool SeeIntoRegionFromNeighbor, IConfigSource config, string simulatorVersion)
  246. {
  247. m_config = config;
  248. Random random = new Random();
  249. m_lastAllocatedLocalId = (uint)(random.NextDouble() * (double)(uint.MaxValue/2))+(uint)(uint.MaxValue/4);
  250. m_moduleLoader = moduleLoader;
  251. m_authenticateHandler = authen;
  252. CommsManager = commsMan;
  253. m_sceneGridService = sceneGridService;
  254. m_storageManager = storeManager;
  255. AssetCache = assetCach;
  256. m_regInfo = regInfo;
  257. m_regionHandle = m_regInfo.RegionHandle;
  258. m_regionName = m_regInfo.RegionName;
  259. m_datastore = m_regInfo.DataStore;
  260. m_physicalPrim = physicalPrim;
  261. m_seeIntoRegionFromNeighbor = SeeIntoRegionFromNeighbor;
  262. m_eventManager = new EventManager();
  263. m_permissions = new ScenePermissions(this);
  264. m_asyncSceneObjectDeleter = new AsyncSceneObjectGroupDeleter(this);
  265. m_asyncSceneObjectDeleter.Enabled = true;
  266. // Load region settings
  267. m_regInfo.RegionSettings = m_storageManager.DataStore.LoadRegionSettings(m_regInfo.RegionID);
  268. if (m_storageManager.EstateDataStore != null)
  269. m_regInfo.EstateSettings = m_storageManager.EstateDataStore.LoadEstateSettings(m_regInfo.RegionID);
  270. //Bind Storage Manager functions to some land manager functions for this scene
  271. EventManager.OnLandObjectAdded +=
  272. new EventManager.LandObjectAdded(m_storageManager.DataStore.StoreLandObject);
  273. EventManager.OnLandObjectRemoved +=
  274. new EventManager.LandObjectRemoved(m_storageManager.DataStore.RemoveLandObject);
  275. m_sceneGraph = new SceneGraph(this, m_regInfo);
  276. // If the scene graph has an Unrecoverable error, restart this sim.
  277. // Currently the only thing that causes it to happen is two kinds of specific
  278. // Physics based crashes.
  279. //
  280. // Out of memory
  281. // Operating system has killed the plugin
  282. m_sceneGraph.UnRecoverableError += RestartNow;
  283. RegisterDefaultSceneEvents();
  284. DumpAssetsToFile = dumpAssetsToFile;
  285. m_scripts_enabled = !RegionInfo.RegionSettings.DisableScripts;
  286. m_physics_enabled = !RegionInfo.RegionSettings.DisablePhysics;
  287. StatsReporter = new SimStatsReporter(this);
  288. StatsReporter.OnSendStatsResult += SendSimStatsPackets;
  289. StatsReporter.OnStatsIncorrect += m_sceneGraph.RecalculateStats;
  290. StatsReporter.SetObjectCapacity(objectCapacity);
  291. m_simulatorVersion = simulatorVersion
  292. + " (OS " + Util.GetOperatingSystemInformation() + ")"
  293. + " ChilTasks:" + m_seeIntoRegionFromNeighbor.ToString()
  294. + " PhysPrim:" + m_physicalPrim.ToString();
  295. try
  296. {
  297. // Region config overrides global config
  298. //
  299. IConfig startupConfig = m_config.Configs["Startup"];
  300. m_maxNonphys = startupConfig.GetFloat("NonPhysicalPrimMax", 65536.0f);
  301. if (RegionInfo.NonphysPrimMax > 0)
  302. m_maxNonphys = RegionInfo.NonphysPrimMax;
  303. m_maxPhys = startupConfig.GetFloat("PhysicalPrimMax", 10.0f);
  304. if (RegionInfo.PhysPrimMax > 0)
  305. m_maxPhys = RegionInfo.PhysPrimMax;
  306. // Here, if clamping is requested in either global or
  307. // local config, it will be used
  308. //
  309. m_clampPrimSize = startupConfig.GetBoolean("ClampPrimSize", false);
  310. if (RegionInfo.ClampPrimSize)
  311. m_clampPrimSize = true;
  312. m_trustBinaries = startupConfig.GetBoolean("TrustBinaries", false);
  313. m_allowScriptCrossings = startupConfig.GetBoolean("AllowScriptCrossing", false);
  314. m_dontPersistBefore =
  315. startupConfig.GetLong("MinimumTimeBeforePersistenceConsidered", DEFAULT_MIN_TIME_FOR_PERSISTENCE);
  316. m_dontPersistBefore *= 10000000;
  317. m_persistAfter =
  318. startupConfig.GetLong("MaximumTimeBeforePersistenceConsidered", DEFAULT_MAX_TIME_FOR_PERSISTENCE);
  319. m_persistAfter *= 10000000;
  320. m_defaultScriptEngine = startupConfig.GetString("DefaultScriptEngine", "DotNetEngine");
  321. }
  322. catch
  323. {
  324. m_log.Warn("[SCENE]: Failed to load StartupConfig");
  325. }
  326. }
  327. /// <summary>
  328. /// Mock constructor for scene group persistency unit tests.
  329. /// SceneObjectGroup RegionId property is delegated to Scene.
  330. /// </summary>
  331. /// <param name="regInfo"></param>
  332. public Scene(RegionInfo regInfo)
  333. {
  334. m_regInfo = regInfo;
  335. m_eventManager = new EventManager();
  336. }
  337. #endregion
  338. #region Startup / Close Methods
  339. public bool ShuttingDown
  340. {
  341. get { return shuttingdown; }
  342. }
  343. protected virtual void RegisterDefaultSceneEvents()
  344. {
  345. IDialogModule dm = RequestModuleInterface<IDialogModule>();
  346. if (dm != null)
  347. m_eventManager.OnPermissionError += dm.SendAlertToUser;
  348. }
  349. public override string GetSimulatorVersion()
  350. {
  351. return m_simulatorVersion;
  352. }
  353. /// <summary>
  354. /// Another region is up. Gets called from Grid Comms:
  355. /// (OGS1 -> LocalBackEnd -> RegionListened -> SceneCommunicationService)
  356. /// We have to tell all our ScenePresences about it, and add it to the
  357. /// neighbor list.
  358. ///
  359. /// We only add it to the neighbor list if it's within 1 region from here.
  360. /// Agents may have draw distance values that cross two regions though, so
  361. /// we add it to the notify list regardless of distance. We'll check
  362. /// the agent's draw distance before notifying them though.
  363. /// </summary>
  364. /// <param name="otherRegion">RegionInfo handle for the new region.</param>
  365. /// <returns>True after all operations complete, throws exceptions otherwise.</returns>
  366. public override bool OtherRegionUp(RegionInfo otherRegion)
  367. {
  368. if (RegionInfo.RegionHandle != otherRegion.RegionHandle)
  369. {
  370. for (int i = 0; i < m_neighbours.Count; i++)
  371. {
  372. // The purpose of this loop is to re-update the known neighbors
  373. // when another region comes up on top of another one.
  374. // The latest region in that location ends up in the
  375. // 'known neighbors list'
  376. // Additionally, the commFailTF property gets reset to false.
  377. if (m_neighbours[i].RegionHandle == otherRegion.RegionHandle)
  378. {
  379. lock (m_neighbours)
  380. {
  381. m_neighbours[i] = otherRegion;
  382. }
  383. }
  384. }
  385. // If the value isn't in the neighbours, add it.
  386. // If the RegionInfo isn't exact but is for the same XY World location,
  387. // then the above loop will fix that.
  388. if (!(CheckNeighborRegion(otherRegion)))
  389. {
  390. lock (m_neighbours)
  391. {
  392. m_neighbours.Add(otherRegion);
  393. //m_log.Info("[UP]: " + otherRegion.RegionHandle.ToString());
  394. }
  395. }
  396. // If these are cast to INT because long + negative values + abs returns invalid data
  397. int resultX = Math.Abs((int)otherRegion.RegionLocX - (int)RegionInfo.RegionLocX);
  398. int resultY = Math.Abs((int)otherRegion.RegionLocY - (int)RegionInfo.RegionLocY);
  399. if (resultX <= 1 && resultY <= 1)
  400. {
  401. try
  402. {
  403. ForEachScenePresence(delegate(ScenePresence agent)
  404. {
  405. // If agent is a root agent.
  406. if (!agent.IsChildAgent)
  407. {
  408. //agent.ControllingClient.new
  409. //this.CommsManager.InterRegion.InformRegionOfChildAgent(otherRegion.RegionHandle, agent.ControllingClient.RequestClientInfo());
  410. InformClientOfNeighbor(agent, otherRegion);
  411. }
  412. }
  413. );
  414. }
  415. catch (NullReferenceException)
  416. {
  417. // This means that we're not booted up completely yet.
  418. // This shouldn't happen too often anymore.
  419. m_log.Error("[SCENE]: Couldn't inform client of regionup because we got a null reference exception");
  420. }
  421. }
  422. else
  423. {
  424. m_log.Info("[INTERGRID]: Got notice about far away Region: " + otherRegion.RegionName.ToString() +
  425. " at (" + otherRegion.RegionLocX.ToString() + ", " +
  426. otherRegion.RegionLocY.ToString() + ")");
  427. }
  428. }
  429. return true;
  430. }
  431. public void AddNeighborRegion(RegionInfo region)
  432. {
  433. lock (m_neighbours)
  434. {
  435. if (!CheckNeighborRegion(region))
  436. {
  437. m_neighbours.Add(region);
  438. }
  439. }
  440. }
  441. public bool CheckNeighborRegion(RegionInfo region)
  442. {
  443. bool found = false;
  444. lock (m_neighbours)
  445. {
  446. foreach (RegionInfo reg in m_neighbours)
  447. {
  448. if (reg.RegionHandle == region.RegionHandle)
  449. {
  450. found = true;
  451. break;
  452. }
  453. }
  454. }
  455. return found;
  456. }
  457. /// <summary>
  458. /// Given float seconds, this will restart the region.
  459. /// </summary>
  460. /// <param name="seconds">float indicating duration before restart.</param>
  461. public virtual void Restart(float seconds)
  462. {
  463. // notifications are done in 15 second increments
  464. // so .. if the number of seconds is less then 15 seconds, it's not really a restart request
  465. // It's a 'Cancel restart' request.
  466. // RestartNow() does immediate restarting.
  467. if (seconds < 15)
  468. {
  469. m_restartTimer.Stop();
  470. m_dialogModule.SendGeneralAlert("Restart Aborted");
  471. }
  472. else
  473. {
  474. // Now we figure out what to set the timer to that does the notifications and calls, RestartNow()
  475. m_restartTimer.Interval = 15000;
  476. m_incrementsof15seconds = (int)seconds / 15;
  477. m_RestartTimerCounter = 0;
  478. m_restartTimer.AutoReset = true;
  479. m_restartTimer.Elapsed += new ElapsedEventHandler(RestartTimer_Elapsed);
  480. m_log.Info("[REGION]: Restarting Region in " + (seconds / 60) + " minutes");
  481. m_restartTimer.Start();
  482. m_dialogModule.SendNotificationToUsersInRegion(
  483. UUID.Random(), String.Empty, RegionInfo.RegionName + ": Restarting in 2 Minutes");
  484. }
  485. }
  486. // The Restart timer has occured.
  487. // We have to figure out if this is a notification or if the number of seconds specified in Restart
  488. // have elapsed.
  489. // If they have elapsed, call RestartNow()
  490. public void RestartTimer_Elapsed(object sender, ElapsedEventArgs e)
  491. {
  492. m_RestartTimerCounter++;
  493. if (m_RestartTimerCounter <= m_incrementsof15seconds)
  494. {
  495. if (m_RestartTimerCounter == 4 || m_RestartTimerCounter == 6 || m_RestartTimerCounter == 7)
  496. m_dialogModule.SendNotificationToUsersInRegion(
  497. UUID.Random(),
  498. String.Empty,
  499. RegionInfo.RegionName + ": Restarting in " + ((8 - m_RestartTimerCounter) * 15) + " seconds");
  500. }
  501. else
  502. {
  503. m_restartTimer.Stop();
  504. m_restartTimer.AutoReset = false;
  505. RestartNow();
  506. }
  507. }
  508. // This causes the region to restart immediatley.
  509. public void RestartNow()
  510. {
  511. if (PhysicsScene != null)
  512. {
  513. PhysicsScene.Dispose();
  514. }
  515. m_log.Error("[REGION]: Closing");
  516. Close();
  517. m_log.Error("[REGION]: Firing Region Restart Message");
  518. base.Restart(0);
  519. }
  520. // This is a helper function that notifies root agents in this region that a new sim near them has come up
  521. // This is in the form of a timer because when an instance of OpenSim.exe is started,
  522. // Even though the sims initialize, they don't listen until 'all of the sims are initialized'
  523. // If we tell an agent about a sim that's not listening yet, the agent will not be able to connect to it.
  524. // subsequently the agent will never see the region come back online.
  525. public void RestartNotifyWaitElapsed(object sender, ElapsedEventArgs e)
  526. {
  527. m_restartWaitTimer.Stop();
  528. lock (m_regionRestartNotifyList)
  529. {
  530. foreach (RegionInfo region in m_regionRestartNotifyList)
  531. {
  532. try
  533. {
  534. ForEachScenePresence(delegate(ScenePresence agent)
  535. {
  536. // If agent is a root agent.
  537. if (!agent.IsChildAgent)
  538. {
  539. //agent.ControllingClient.new
  540. //this.CommsManager.InterRegion.InformRegionOfChildAgent(otherRegion.RegionHandle, agent.ControllingClient.RequestClientInfo());
  541. InformClientOfNeighbor(agent, region);
  542. }
  543. }
  544. );
  545. }
  546. catch (NullReferenceException)
  547. {
  548. // This means that we're not booted up completely yet.
  549. // This shouldn't happen too often anymore.
  550. }
  551. }
  552. // Reset list to nothing.
  553. m_regionRestartNotifyList.Clear();
  554. }
  555. }
  556. public void SetSceneCoreDebug(bool ScriptEngine, bool CollisionEvents, bool PhysicsEngine)
  557. {
  558. if (m_scripts_enabled != !ScriptEngine)
  559. {
  560. // Tedd! Here's the method to disable the scripting engine!
  561. if (ScriptEngine)
  562. {
  563. m_log.Info("Stopping all Scripts in Scene");
  564. foreach (EntityBase ent in Entities)
  565. {
  566. if (ent is SceneObjectGroup)
  567. {
  568. ((SceneObjectGroup) ent).RemoveScriptInstances();
  569. }
  570. }
  571. }
  572. else
  573. {
  574. m_log.Info("Starting all Scripts in Scene");
  575. lock (Entities)
  576. {
  577. foreach (EntityBase ent in Entities)
  578. {
  579. if (ent is SceneObjectGroup)
  580. {
  581. ((SceneObjectGroup)ent).CreateScriptInstances(0, false, DefaultScriptEngine, 0);
  582. }
  583. }
  584. }
  585. }
  586. m_scripts_enabled = !ScriptEngine;
  587. m_log.Info("[TOTEDD]: Here is the method to trigger disabling of the scripting engine");
  588. }
  589. if (m_physics_enabled != !PhysicsEngine)
  590. {
  591. m_physics_enabled = !PhysicsEngine;
  592. }
  593. }
  594. public int GetInaccurateNeighborCount()
  595. {
  596. lock (m_neighbours)
  597. {
  598. return m_neighbours.Count;
  599. }
  600. }
  601. // This is the method that shuts down the scene.
  602. public override void Close()
  603. {
  604. m_log.InfoFormat("[SCENE]: Closing down the single simulator: {0}", RegionInfo.RegionName);
  605. // Kick all ROOT agents with the message, 'The simulator is going down'
  606. ForEachScenePresence(delegate(ScenePresence avatar)
  607. {
  608. if (avatar.KnownChildRegionHandles.Contains(RegionInfo.RegionHandle))
  609. avatar.KnownChildRegionHandles.Remove(RegionInfo.RegionHandle);
  610. if (!avatar.IsChildAgent)
  611. avatar.ControllingClient.Kick("The simulator is going down.");
  612. avatar.ControllingClient.SendShutdownConnectionNotice();
  613. });
  614. // Wait here, or the kick messages won't actually get to the agents before the scene terminates.
  615. Thread.Sleep(500);
  616. // Stop all client threads.
  617. ForEachScenePresence(delegate(ScenePresence avatar) { avatar.ControllingClient.Close(true); });
  618. // Stop updating the scene objects and agents.
  619. //m_heartbeatTimer.Close();
  620. shuttingdown = true;
  621. m_log.Debug("[SCENE]: Persisting changed objects");
  622. List<EntityBase> entities = GetEntities();
  623. foreach (EntityBase entity in entities)
  624. {
  625. if (!entity.IsDeleted && entity is SceneObjectGroup && ((SceneObjectGroup)entity).HasGroupChanged)
  626. {
  627. ((SceneObjectGroup)entity).ProcessBackup(m_storageManager.DataStore);
  628. }
  629. }
  630. m_sceneGraph.Close();
  631. // De-register with region communications (events cleanup)
  632. UnRegisterRegionWithComms();
  633. // Shut down all non shared modules.
  634. foreach (IRegionModule module in Modules.Values)
  635. {
  636. if (!module.IsSharedModule)
  637. {
  638. module.Close();
  639. }
  640. }
  641. Modules.Clear();
  642. // call the base class Close method.
  643. base.Close();
  644. }
  645. /// <summary>
  646. /// Start the timer which triggers regular scene updates
  647. /// </summary>
  648. public void StartTimer()
  649. {
  650. //m_log.Debug("[SCENE]: Starting timer");
  651. //m_heartbeatTimer.Enabled = true;
  652. //m_heartbeatTimer.Interval = (int)(m_timespan * 1000);
  653. //m_heartbeatTimer.Elapsed += new ElapsedEventHandler(Heartbeat);
  654. HeartbeatThread = new Thread(new ParameterizedThreadStart(Heartbeat));
  655. HeartbeatThread.SetApartmentState(ApartmentState.MTA);
  656. HeartbeatThread.Name = "Heartbeat";
  657. HeartbeatThread.Priority = ThreadPriority.AboveNormal;
  658. ThreadTracker.Add(HeartbeatThread);
  659. HeartbeatThread.Start();
  660. }
  661. /// <summary>
  662. /// Sets up references to modules required by the scene
  663. /// </summary>
  664. public void SetModuleInterfaces()
  665. {
  666. m_xmlrpcModule = RequestModuleInterface<IXMLRPC>();
  667. m_worldCommModule = RequestModuleInterface<IWorldComm>();
  668. XferManager = RequestModuleInterface<IXfer>();
  669. m_AvatarFactory = RequestModuleInterface<IAvatarFactory>();
  670. m_serialiser = RequestModuleInterface<IRegionSerialiserModule>();
  671. m_interregionCommsOut = RequestModuleInterface<IInterregionCommsOut>();
  672. m_interregionCommsIn = RequestModuleInterface<IInterregionCommsIn>();
  673. m_dialogModule = RequestModuleInterface<IDialogModule>();
  674. CapsModule = RequestModuleInterface<ICapabilitiesModule>();
  675. }
  676. #endregion
  677. #region Update Methods
  678. /// <summary>
  679. /// Performs per-frame updates regularly
  680. /// </summary>
  681. /// <param name="sender"></param>
  682. /// <param name="e"></param>
  683. private void Heartbeat(object sender)
  684. {
  685. Update();
  686. }
  687. /// <summary>
  688. /// Performs per-frame updates on the scene, this should be the central scene loop
  689. /// </summary>
  690. public override void Update()
  691. {
  692. int maintc = 0;
  693. while (!shuttingdown)
  694. {
  695. maintc = System.Environment.TickCount;
  696. TimeSpan SinceLastFrame = DateTime.Now - m_lastupdate;
  697. // Aquire a lock so only one update call happens at once
  698. //updateLock.WaitOne();
  699. float physicsFPS = 0;
  700. //m_log.Info("sadfadf" + m_neighbours.Count.ToString());
  701. int agentsInScene = m_sceneGraph.GetRootAgentCount() + m_sceneGraph.GetChildAgentCount();
  702. if (agentsInScene > 21)
  703. {
  704. if (m_update_entities == 1)
  705. {
  706. m_update_entities = 5;
  707. StatsReporter.SetUpdateMS(6000);
  708. }
  709. }
  710. else
  711. {
  712. if (m_update_entities == 5)
  713. {
  714. m_update_entities = 1;
  715. StatsReporter.SetUpdateMS(3000);
  716. }
  717. }
  718. frameMS = System.Environment.TickCount;
  719. try
  720. {
  721. // Increment the frame counter
  722. m_frame++;
  723. // Loop it
  724. if (m_frame == Int32.MaxValue)
  725. m_frame = 0;
  726. physicsMS2 = System.Environment.TickCount;
  727. if ((m_frame % m_update_physics == 0) && m_physics_enabled)
  728. m_sceneGraph.UpdatePreparePhysics();
  729. physicsMS2 = System.Environment.TickCount - physicsMS2;
  730. if (m_frame % m_update_entitymovement == 0)
  731. m_sceneGraph.UpdateEntityMovement();
  732. physicsMS = System.Environment.TickCount;
  733. if ((m_frame % m_update_physics == 0) && m_physics_enabled)
  734. physicsFPS = m_sceneGraph.UpdatePhysics(
  735. Math.Max(SinceLastFrame.TotalSeconds, m_timespan)
  736. );
  737. if (m_frame % m_update_physics == 0 && SynchronizeScene != null)
  738. SynchronizeScene(this);
  739. physicsMS = System.Environment.TickCount - physicsMS;
  740. physicsMS += physicsMS2;
  741. otherMS = System.Environment.TickCount;
  742. // run through all entities looking for updates (slow)
  743. if (m_frame % m_update_entities == 0)
  744. m_sceneGraph.UpdateEntities();
  745. // run through entities that have scheduled themselves for
  746. // updates looking for updates(faster)
  747. if (m_frame % m_update_entitiesquick == 0)
  748. m_sceneGraph.ProcessUpdates();
  749. // Run through scenepresences looking for updates
  750. if (m_frame % m_update_presences == 0)
  751. m_sceneGraph.UpdatePresences();
  752. // Delete temp-on-rez stuff
  753. if (m_frame % m_update_backup == 0)
  754. CleanTempObjects();
  755. if (Region_Status != RegionStatus.SlaveScene)
  756. {
  757. if (m_frame % m_update_events == 0)
  758. UpdateEvents();
  759. if (m_frame % m_update_backup == 0)
  760. {
  761. UpdateStorageBackup();
  762. }
  763. if (m_frame % m_update_terrain == 0)
  764. UpdateTerrain();
  765. if (m_frame % m_update_land == 0)
  766. UpdateLand();
  767. otherMS = System.Environment.TickCount - otherMS;
  768. // if (m_frame%m_update_avatars == 0)
  769. // UpdateInWorldTime();
  770. StatsReporter.AddPhysicsFPS(physicsFPS);
  771. StatsReporter.AddTimeDilation(m_timedilation);
  772. StatsReporter.AddFPS(1);
  773. StatsReporter.AddInPackets(0);
  774. StatsReporter.SetRootAgents(m_sceneGraph.GetRootAgentCount());
  775. StatsReporter.SetChildAgents(m_sceneGraph.GetChildAgentCount());
  776. StatsReporter.SetObjects(m_sceneGraph.GetTotalObjectsCount());
  777. StatsReporter.SetActiveObjects(m_sceneGraph.GetActiveObjectsCount());
  778. frameMS = System.Environment.TickCount - frameMS;
  779. StatsReporter.addFrameMS(frameMS);
  780. StatsReporter.addPhysicsMS(physicsMS);
  781. StatsReporter.addOtherMS(otherMS);
  782. StatsReporter.SetActiveScripts(m_sceneGraph.GetActiveScriptsCount());
  783. StatsReporter.addScriptLines(m_sceneGraph.GetScriptLPS());
  784. }
  785. }
  786. catch (NotImplementedException)
  787. {
  788. throw;
  789. }
  790. catch (AccessViolationException e)
  791. {
  792. m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  793. }
  794. //catch (NullReferenceException e)
  795. //{
  796. // m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  797. //}
  798. catch (InvalidOperationException e)
  799. {
  800. m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  801. }
  802. catch (Exception e)
  803. {
  804. m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  805. }
  806. finally
  807. {
  808. //updateLock.ReleaseMutex();
  809. // Get actual time dilation
  810. float tmpval = (m_timespan / (float)SinceLastFrame.TotalSeconds);
  811. // If actual time dilation is greater then one, we're catching up, so subtract
  812. // the amount that's greater then 1 from the time dilation
  813. if (tmpval > 1.0)
  814. {
  815. tmpval = tmpval - (tmpval - 1.0f);
  816. }
  817. m_timedilation = tmpval;
  818. m_lastupdate = DateTime.Now;
  819. }
  820. maintc = System.Environment.TickCount - maintc;
  821. maintc = (int)(m_timespan * 1000) - maintc;
  822. if ((maintc < (m_timespan * 1000)) && maintc > 0)
  823. Thread.Sleep(maintc);
  824. }
  825. }
  826. private void SendSimStatsPackets(SimStats stats)
  827. {
  828. List<ScenePresence> StatSendAgents = GetScenePresences();
  829. foreach (ScenePresence agent in StatSendAgents)
  830. {
  831. if (!agent.IsChildAgent)
  832. {
  833. agent.ControllingClient.SendSimStats(stats);
  834. }
  835. }
  836. }
  837. private void UpdateLand()
  838. {
  839. if (LandChannel != null)
  840. {
  841. if (LandChannel.IsLandPrimCountTainted())
  842. {
  843. EventManager.TriggerParcelPrimCountUpdate();
  844. }
  845. }
  846. }
  847. private void UpdateTerrain()
  848. {
  849. EventManager.TriggerTerrainTick();
  850. }
  851. private void UpdateStorageBackup()
  852. {
  853. if (!m_backingup)
  854. {
  855. m_backingup = true;
  856. Thread backupthread = new Thread(Backup);
  857. backupthread.Name = "BackupWriter";
  858. backupthread.IsBackground = true;
  859. backupthread.Start();
  860. }
  861. }
  862. private void UpdateEvents()
  863. {
  864. m_eventManager.TriggerOnFrame();
  865. }
  866. /// <summary>
  867. /// Perform delegate action on all clients subscribing to updates from this region.
  868. /// </summary>
  869. /// <returns></returns>
  870. internal void Broadcast(Action<IClientAPI> whatToDo)
  871. {
  872. ForEachScenePresence(delegate(ScenePresence presence) { whatToDo(presence.ControllingClient); });
  873. }
  874. /// <summary>
  875. /// Backup the scene. This acts as the main method of the backup thread.
  876. /// </summary>
  877. /// <returns></returns>
  878. public void Backup()
  879. {
  880. lock (m_returns)
  881. {
  882. EventManager.TriggerOnBackup(m_storageManager.DataStore);
  883. m_backingup = false;
  884. foreach (KeyValuePair<UUID, ReturnInfo> ret in m_returns)
  885. {
  886. UUID transaction = UUID.Random();
  887. GridInstantMessage msg = new GridInstantMessage();
  888. msg.fromAgentID = new Guid(UUID.Zero.ToString()); // From server
  889. msg.toAgentID = new Guid(ret.Key.ToString());
  890. msg.imSessionID = new Guid(transaction.ToString());
  891. msg.timestamp = (uint)Util.UnixTimeSinceEpoch();
  892. msg.fromAgentName = "Server";
  893. msg.dialog = (byte)19; // Object msg
  894. msg.fromGroup = false;
  895. msg.offline = (byte)1;
  896. msg.ParentEstateID = RegionInfo.EstateSettings.ParentEstateID;
  897. msg.Position = Vector3.Zero;
  898. msg.RegionID = RegionInfo.RegionID.Guid;
  899. msg.binaryBucket = new byte[0];
  900. if (ret.Value.count > 1)
  901. 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);
  902. else
  903. 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);
  904. IMessageTransferModule tr = RequestModuleInterface<IMessageTransferModule>();
  905. if (tr != null)
  906. tr.SendInstantMessage(msg, delegate(bool success) {} );
  907. }
  908. m_returns.Clear();
  909. }
  910. }
  911. public void AddReturn(UUID agentID, string objectName, Vector3 location, string reason)
  912. {
  913. lock (m_returns)
  914. {
  915. if (m_returns.ContainsKey(agentID))
  916. {
  917. ReturnInfo info = m_returns[agentID];
  918. info.count++;
  919. m_returns[agentID] = info;
  920. }
  921. else
  922. {
  923. ReturnInfo info = new ReturnInfo();
  924. info.count = 1;
  925. info.objectName = objectName;
  926. info.location = location;
  927. info.reason = reason;
  928. m_returns[agentID] = info;
  929. }
  930. }
  931. }
  932. #endregion
  933. #region Load Terrain
  934. public void ExportWorldMap(string fileName)
  935. {
  936. List<MapBlockData> mapBlocks =
  937. m_sceneGridService.RequestNeighbourMapBlocks((int)(RegionInfo.RegionLocX - 9),
  938. (int)(RegionInfo.RegionLocY - 9),
  939. (int)(RegionInfo.RegionLocX + 9),
  940. (int)(RegionInfo.RegionLocY + 9));
  941. List<AssetBase> textures = new List<AssetBase>();
  942. List<Image> bitImages = new List<Image>();
  943. foreach (MapBlockData mapBlock in mapBlocks)
  944. {
  945. AssetBase texAsset = AssetCache.GetAsset(mapBlock.MapImageId, true);
  946. if (texAsset != null)
  947. {
  948. textures.Add(texAsset);
  949. }
  950. else
  951. {
  952. texAsset = AssetCache.GetAsset(mapBlock.MapImageId, true);
  953. if (texAsset != null)
  954. {
  955. textures.Add(texAsset);
  956. }
  957. }
  958. }
  959. foreach (AssetBase asset in textures)
  960. {
  961. ManagedImage managedImage;
  962. Image image;
  963. if (OpenJPEG.DecodeToImage(asset.Data, out managedImage, out image))
  964. bitImages.Add(image);
  965. }
  966. Bitmap mapTexture = new Bitmap(2560, 2560);
  967. Graphics g = Graphics.FromImage(mapTexture);
  968. SolidBrush sea = new SolidBrush(Color.DarkBlue);
  969. g.FillRectangle(sea, 0, 0, 2560, 2560);
  970. for (int i = 0; i < mapBlocks.Count; i++)
  971. {
  972. ushort x = (ushort)((mapBlocks[i].X - RegionInfo.RegionLocX) + 10);
  973. ushort y = (ushort)((mapBlocks[i].Y - RegionInfo.RegionLocY) + 10);
  974. g.DrawImage(bitImages[i], (x * 128), (y * 128), 128, 128);
  975. }
  976. mapTexture.Save(fileName, ImageFormat.Jpeg);
  977. }
  978. public void SaveTerrain()
  979. {
  980. m_storageManager.DataStore.StoreTerrain(Heightmap.GetDoubles(), RegionInfo.RegionID);
  981. }
  982. /// <summary>
  983. /// Loads the World heightmap
  984. /// </summary>
  985. public override void LoadWorldMap()
  986. {
  987. try
  988. {
  989. double[,] map = m_storageManager.DataStore.LoadTerrain(RegionInfo.RegionID);
  990. if (map == null)
  991. {
  992. m_log.Info("[TERRAIN]: No default terrain. Generating a new terrain.");
  993. Heightmap = new TerrainChannel();
  994. m_storageManager.DataStore.StoreTerrain(Heightmap.GetDoubles(), RegionInfo.RegionID);
  995. }
  996. else
  997. {
  998. Heightmap = new TerrainChannel(map);
  999. }
  1000. }
  1001. catch (Exception e)
  1002. {
  1003. m_log.Warn("[TERRAIN]: Scene.cs: LoadWorldMap() - Failed with exception " + e.ToString());
  1004. }
  1005. }
  1006. /// <summary>
  1007. /// Register this region with a grid service
  1008. /// </summary>
  1009. /// <exception cref="System.Exception">Thrown if registration of the region itself fails.</exception>
  1010. public void RegisterRegionWithGrid()
  1011. {
  1012. RegisterCommsEvents();
  1013. // These two 'commands' *must be* next to each other or sim rebooting fails.
  1014. m_sceneGridService.RegisterRegion(m_interregionCommsOut, RegionInfo);
  1015. m_sceneGridService.InformNeighborsThatRegionisUp(RegionInfo);
  1016. Dictionary<string, string> dGridSettings = m_sceneGridService.GetGridSettings();
  1017. if (dGridSettings.ContainsKey("allow_forceful_banlines"))
  1018. {
  1019. if (dGridSettings["allow_forceful_banlines"] != "TRUE")
  1020. {
  1021. m_log.Info("[GRID]: Grid is disabling forceful parcel banlists");
  1022. EventManager.TriggerSetAllowForcefulBan(false);
  1023. }
  1024. else
  1025. {
  1026. m_log.Info("[GRID]: Grid is allowing forceful parcel banlists");
  1027. EventManager.TriggerSetAllowForcefulBan(true);
  1028. }
  1029. }
  1030. }
  1031. /// <summary>
  1032. ///
  1033. /// </summary>
  1034. public void CreateTerrainTexture(bool temporary)
  1035. {
  1036. //create a texture asset of the terrain
  1037. IMapImageGenerator terrain = RequestModuleInterface<IMapImageGenerator>();
  1038. // Cannot create a map for a nonexistant heightmap yet.
  1039. if (Heightmap == null)
  1040. return;
  1041. if (terrain == null)
  1042. {
  1043. #region Fallback default maptile generation
  1044. int tc = System.Environment.TickCount;
  1045. m_log.Info("[MAPTILE]: Generating Maptile Step 1: Terrain");
  1046. Bitmap mapbmp = new Bitmap(256, 256);
  1047. double[,] hm = Heightmap.GetDoubles();
  1048. bool ShadowDebugContinue = true;
  1049. //Color prim = Color.FromArgb(120, 120, 120);
  1050. //Vector3 RayEnd = new Vector3(0, 0, 0);
  1051. //Vector3 RayStart = new Vector3(0, 0, 0);
  1052. //Vector3 direction = new Vector3(0, 0, -1);
  1053. //Vector3 AXOrigin = new Vector3();
  1054. //Vector3 AXdirection = new Vector3();
  1055. //Ray testRay = new Ray();
  1056. //EntityIntersection rt = new EntityIntersection();
  1057. bool terraincorruptedwarningsaid = false;
  1058. float low = 255;
  1059. float high = 0;
  1060. for (int x = 0; x < 256; x++)
  1061. {
  1062. for (int y = 0; y < 256; y++)
  1063. {
  1064. float hmval = (float)hm[x, y];
  1065. if (hmval < low)
  1066. low = hmval;
  1067. if (hmval > high)
  1068. high = hmval;
  1069. }
  1070. }
  1071. float mid = (high + low) * 0.5f;
  1072. // temporary initializer
  1073. float hfvalue = (float)m_regInfo.RegionSettings.WaterHeight;
  1074. float hfvaluecompare = hfvalue;
  1075. float hfdiff = hfvalue;
  1076. int hfdiffi = 0;
  1077. for (int x = 0; x < 256; x++)
  1078. {
  1079. //int tc = System.Environment.TickCount;
  1080. for (int y = 0; y < 256; y++)
  1081. {
  1082. //RayEnd = new Vector3(x, y, 0);
  1083. //RayStart = new Vector3(x, y, 255);
  1084. //direction = Vector3.Norm(RayEnd - RayStart);
  1085. //AXOrigin = new Vector3(RayStart.X, RayStart.Y, RayStart.Z);
  1086. //AXdirection = new Vector3(direction.X, direction.Y, direction.Z);
  1087. //testRay = new Ray(AXOrigin, AXdirection);
  1088. //rt = m_sceneGraph.GetClosestIntersectingPrim(testRay);
  1089. //if (rt.HitTF)
  1090. //{
  1091. //mapbmp.SetPixel(x, y, prim);
  1092. //}
  1093. //else
  1094. //{
  1095. //float tmpval = (float)hm[x, y];
  1096. float heightvalue = (float)hm[x, y];
  1097. if (heightvalue > (float)m_regInfo.RegionSettings.WaterHeight)
  1098. {
  1099. // scale height value
  1100. heightvalue = low + mid * (heightvalue - low) / mid;
  1101. if (heightvalue > 255)
  1102. heightvalue = 255;
  1103. if (heightvalue < 0)
  1104. heightvalue = 0;
  1105. if (Single.IsInfinity(heightvalue) || Single.IsNaN(heightvalue))
  1106. heightvalue = 0;
  1107. try
  1108. {
  1109. Color green = Color.FromArgb((int)heightvalue, 100, (int)heightvalue);
  1110. // Y flip the cordinates
  1111. mapbmp.SetPixel(x, (256 - y) - 1, green);
  1112. //X
  1113. // .
  1114. //
  1115. // Shade the terrain for shadows
  1116. if ((x - 1 > 0) && (y - 1 > 0))
  1117. {
  1118. hfvalue = (float)hm[x, y];
  1119. hfvaluecompare = (float)hm[x - 1, y - 1];
  1120. if (Single.IsInfinity(hfvalue) || Single.IsNaN(hfvalue))
  1121. hfvalue = 0;
  1122. if (Single.IsInfinity(hfvaluecompare) || Single.IsNaN(hfvaluecompare))
  1123. hfvaluecompare = 0;
  1124. hfdiff = hfvaluecompare - hfvalue;
  1125. if (hfdiff > 0.3f)
  1126. {
  1127. }
  1128. else if (hfdiff < -0.3f)
  1129. {
  1130. // We have to desaturate and blacken the land at the same time
  1131. // we use floats, colors use bytes, so shrink are space down to
  1132. // 0-255
  1133. try
  1134. {
  1135. hfdiffi = Math.Abs((int)((hfdiff * 4) + (hfdiff * 0.5))) + 1;
  1136. if (hfdiff % 1 != 0)
  1137. {
  1138. hfdiffi = hfdiffi + Math.Abs((int)(((hfdiff % 1) * 0.5f) * 10f) - 1);
  1139. }
  1140. }
  1141. catch (System.OverflowException)
  1142. {
  1143. m_log.Debug("[MAPTILE]: Shadow failed at value: " + hfdiff.ToString());
  1144. ShadowDebugContinue = false;
  1145. }
  1146. if (ShadowDebugContinue)
  1147. {
  1148. if ((256 - y) - 1 > 0)
  1149. {
  1150. Color Shade = mapbmp.GetPixel(x - 1, (256 - y) - 1);
  1151. int r = Shade.R;
  1152. int g = Shade.G;
  1153. int b = Shade.B;
  1154. Shade = Color.FromArgb((r - hfdiffi > 0) ? r - hfdiffi : 0, (g - hfdiffi > 0) ? g - hfdiffi : 0, (b - hfdiffi > 0) ? b - hfdiffi : 0);
  1155. //Console.WriteLine("d:" + hfdiff.ToString() + ", i:" + hfdiffi + ", pos: " + x + "," + y + " - R:" + Shade.R.ToString() + ", G:" + Shade.G.ToString() + ", B:" + Shade.G.ToString());
  1156. mapbmp.SetPixel(x - 1, (256 - y) - 1, Shade);
  1157. }
  1158. }
  1159. }
  1160. }
  1161. }
  1162. catch (System.ArgumentException)
  1163. {
  1164. if (!terraincorruptedwarningsaid)
  1165. {
  1166. m_log.WarnFormat("[MAPIMAGE]: Your terrain is corrupted in region {0}, it might take a few minutes to generate the map image depending on the corruption level", RegionInfo.RegionName);
  1167. terraincorruptedwarningsaid = true;
  1168. }
  1169. Color black = Color.Black;
  1170. mapbmp.SetPixel(x, (256 - y) - 1, black);
  1171. }
  1172. }
  1173. else
  1174. {
  1175. // Y flip the cordinates
  1176. heightvalue = (float)m_regInfo.RegionSettings.WaterHeight - heightvalue;
  1177. if (heightvalue > 19)
  1178. heightvalue = 19;
  1179. if (heightvalue < 0)
  1180. heightvalue = 0;
  1181. heightvalue = 100 - (heightvalue * 100) / 19;
  1182. if (heightvalue > 255)
  1183. heightvalue = 255;
  1184. if (heightvalue < 0)
  1185. heightvalue = 0;
  1186. if (Single.IsInfinity(heightvalue) || Single.IsNaN(heightvalue))
  1187. heightvalue = 0;
  1188. try
  1189. {
  1190. Color water = Color.FromArgb((int)heightvalue, (int)heightvalue, 255);
  1191. mapbmp.SetPixel(x, (256 - y) - 1, water);
  1192. }
  1193. catch (System.ArgumentException)
  1194. {
  1195. if (!terraincorruptedwarningsaid)
  1196. {
  1197. m_log.WarnFormat("[MAPIMAGE]: Your terrain is corrupted in region {0}, it might take a few minutes to generate the map image depending on the corruption level", RegionInfo.RegionName);
  1198. terraincorruptedwarningsaid = true;
  1199. }
  1200. Color black = Color.Black;
  1201. mapbmp.SetPixel(x, (256 - y) - 1, black);
  1202. }
  1203. }
  1204. }
  1205. //}
  1206. //tc = System.Environment.TickCount - tc;
  1207. //m_log.Info("[MAPTILE]: Completed One row in " + tc + " ms");
  1208. }
  1209. m_log.Info("[MAPTILE]: Generating Maptile Step 1: Done in " + (System.Environment.TickCount - tc) + " ms");
  1210. bool drawPrimVolume = true;
  1211. try
  1212. {
  1213. IConfig startupConfig = m_config.Configs["Startup"];
  1214. drawPrimVolume = startupConfig.GetBoolean("DrawPrimOnMapTile", true);
  1215. }
  1216. catch
  1217. {
  1218. m_log.Warn("[MAPTILE]: Failed to load StartupConfig");
  1219. }
  1220. if (drawPrimVolume)
  1221. {
  1222. tc = System.Environment.TickCount;
  1223. m_log.Info("[MAPTILE]: Generating Maptile Step 2: Object Volume Profile");
  1224. List<EntityBase> objs = GetEntities();
  1225. lock (objs)
  1226. {
  1227. foreach (EntityBase obj in objs)
  1228. {
  1229. // Only draw the contents of SceneObjectGroup
  1230. if (obj is SceneObjectGroup)
  1231. {
  1232. SceneObjectGroup mapdot = (SceneObjectGroup)obj;
  1233. Color mapdotspot = Color.Gray; // Default color when prim color is white
  1234. // Loop over prim in group
  1235. foreach (SceneObjectPart part in mapdot.Children.Values)
  1236. {
  1237. if (part == null)
  1238. continue;
  1239. // Draw if the object is at least 1 meter wide in any direction
  1240. if (part.Scale.X > 1f || part.Scale.Y > 1f || part.Scale.Z > 1f)
  1241. {
  1242. // Try to get the RGBA of the default texture entry..
  1243. //
  1244. try
  1245. {
  1246. if (part == null)
  1247. continue;
  1248. if (part.Shape == null)
  1249. continue;
  1250. if (part.Shape.PCode == (byte)PCode.Tree || part.Shape.PCode == (byte)PCode.NewTree)
  1251. continue; // eliminates trees from this since we don't really have a good tree representation
  1252. // if you want tree blocks on the map comment the above line and uncomment the below line
  1253. //mapdotspot = Color.PaleGreen;
  1254. if (part.Shape.Textures == null)
  1255. continue;
  1256. if (part.Shape.Textures.DefaultTexture == null)
  1257. continue;
  1258. Color4 texcolor = part.Shape.Textures.DefaultTexture.RGBA;
  1259. // Not sure why some of these are null, oh well.
  1260. int colorr = 255 - (int)(texcolor.R * 255f);
  1261. int colorg = 255 - (int)(texcolor.G * 255f);
  1262. int colorb = 255 - (int)(texcolor.B * 255f);
  1263. if (!(colorr == 255 && colorg == 255 && colorb == 255))
  1264. {
  1265. //Try to set the map spot color
  1266. try
  1267. {
  1268. // If the color gets goofy somehow, skip it *shakes fist at Color4
  1269. mapdotspot = Color.FromArgb(colorr, colorg, colorb);
  1270. }
  1271. catch (ArgumentException)
  1272. {
  1273. }
  1274. }
  1275. }
  1276. catch (IndexOutOfRangeException)
  1277. {
  1278. // Windows Array
  1279. }
  1280. catch (ArgumentOutOfRangeException)
  1281. {
  1282. // Mono Array
  1283. }
  1284. Vector3 pos = part.GetWorldPosition();
  1285. // skip prim outside of retion
  1286. if (pos.X < 0f || pos.X > 256f || pos.Y < 0f || pos.Y > 256f)
  1287. continue;
  1288. // skip prim in non-finite position
  1289. if (Single.IsNaN(pos.X) || Single.IsNaN(pos.Y) || Single.IsInfinity(pos.X)
  1290. || Single.IsInfinity(pos.Y))
  1291. continue;
  1292. // Figure out if object is under 256m above the height of the terrain
  1293. bool isBelow256AboveTerrain = false;
  1294. try
  1295. {
  1296. isBelow256AboveTerrain = (pos.Z < ((float)hm[(int)pos.X, (int)pos.Y] + 256f));
  1297. }
  1298. catch (Exception)
  1299. {
  1300. }
  1301. if (isBelow256AboveTerrain)
  1302. {
  1303. // Translate scale by rotation so scale is represented properly when object is rotated
  1304. Vector3 scale = part.Shape.Scale;
  1305. Quaternion rot = part.GetWorldRotation();
  1306. scale *= rot;
  1307. // negative scales don't work in this situation
  1308. scale.X = Math.Abs(scale.X);
  1309. scale.Y = Math.Abs(scale.Y);
  1310. scale.Z = Math.Abs(scale.Z);
  1311. // This scaling isn't very accurate and doesn't take into account the face rotation :P
  1312. int mapdrawstartX = (int)(pos.X - scale.X);
  1313. int mapdrawstartY = (int)(pos.Y - scale.Y);
  1314. int mapdrawendX = (int)(pos.X + scale.X);
  1315. int mapdrawendY = (int)(pos.Y + scale.Y);
  1316. // If object is beyond the edge of the map, don't draw it to avoid errors
  1317. if (mapdrawstartX < 0 || mapdrawstartX > 255 || mapdrawendX < 0 || mapdrawendX > 255
  1318. || mapdrawstartY < 0 || mapdrawstartY > 255 || mapdrawendY < 0
  1319. || mapdrawendY > 255)
  1320. continue;
  1321. int wy = 0;
  1322. bool breakYN = false; // If we run into an error drawing, break out of the
  1323. // loop so we don't lag to death on error handling
  1324. for (int wx = mapdrawstartX; wx < mapdrawendX; wx++)
  1325. {
  1326. for (wy = mapdrawstartY; wy < mapdrawendY; wy++)
  1327. {
  1328. //m_log.InfoFormat("[MAPDEBUG]: {0},{1}({2})", wx, (255 - wy),wy);
  1329. try
  1330. {
  1331. // Remember, flip the y!
  1332. mapbmp.SetPixel(wx, (255 - wy), mapdotspot);
  1333. }
  1334. catch (ArgumentException)
  1335. {
  1336. breakYN = true;
  1337. }
  1338. if (breakYN)
  1339. break;
  1340. }
  1341. if (breakYN)
  1342. break;
  1343. }
  1344. } // Object is within 256m Z of terrain
  1345. } // object is at least a meter wide
  1346. } // loop over group children
  1347. } // entitybase is sceneobject group
  1348. } // foreach loop over entities
  1349. } // lock entities objs
  1350. m_log.Info("[MAPTILE]: Generating Maptile Step 2: Done in " + (System.Environment.TickCount - tc) + " ms");
  1351. } // end if drawPrimOnMaptle
  1352. byte[] data;
  1353. try
  1354. {
  1355. data = OpenJPEG.EncodeFromImage(mapbmp, false);
  1356. }
  1357. catch (Exception)
  1358. {
  1359. return;
  1360. }
  1361. LazySaveGeneratedMaptile(data,temporary);
  1362. #endregion
  1363. }
  1364. else
  1365. {
  1366. // Use the module to generate the maptile.
  1367. byte[] data = terrain.WriteJpeg2000Image("defaultstripe.png");
  1368. if (data != null)
  1369. {
  1370. LazySaveGeneratedMaptile(data,temporary);
  1371. }
  1372. }
  1373. }
  1374. public void LazySaveGeneratedMaptile(byte[] data, bool temporary)
  1375. {
  1376. // Overwrites the local Asset cache with new maptile data
  1377. // Assets are single write, this causes the asset server to ignore this update,
  1378. // but the local asset cache does not
  1379. // this is on purpose! The net result of this is the region always has the most up to date
  1380. // map tile while protecting the (grid) asset database from bloat caused by a new asset each
  1381. // time a mapimage is generated!
  1382. UUID lastMapRegionUUID = m_regInfo.lastMapUUID;
  1383. int lastMapRefresh = 0;
  1384. int twoDays = 172800;
  1385. int RefreshSeconds = twoDays;
  1386. try
  1387. {
  1388. lastMapRefresh = Convert.ToInt32(m_regInfo.lastMapRefresh);
  1389. }
  1390. catch (ArgumentException)
  1391. {
  1392. }
  1393. catch (FormatException)
  1394. {
  1395. }
  1396. catch (OverflowException)
  1397. {
  1398. }
  1399. UUID TerrainImageUUID = UUID.Random();
  1400. if (lastMapRegionUUID == UUID.Zero || (lastMapRefresh + RefreshSeconds) < Util.UnixTimeSinceEpoch())
  1401. {
  1402. m_regInfo.SaveLastMapUUID(TerrainImageUUID);
  1403. m_log.Warn("[MAPTILE]: STORING MAPTILE IMAGE");
  1404. }
  1405. else
  1406. {
  1407. TerrainImageUUID = lastMapRegionUUID;
  1408. m_log.Warn("[MAPTILE]: REUSING OLD MAPTILE IMAGE ID");
  1409. }
  1410. m_regInfo.RegionSettings.TerrainImageID = TerrainImageUUID;
  1411. AssetBase asset = new AssetBase();
  1412. asset.FullID = m_regInfo.RegionSettings.TerrainImageID;
  1413. asset.Data = data;
  1414. asset.Name = "terrainImage_" + m_regInfo.RegionID.ToString() + "_" + lastMapRefresh.ToString();
  1415. asset.Description = RegionInfo.RegionName;
  1416. asset.Type = 0;
  1417. asset.Temporary = temporary;
  1418. AssetCache.AddAsset(asset);
  1419. }
  1420. #endregion
  1421. #region Load Land
  1422. public void loadAllLandObjectsFromStorage(UUID regionID)
  1423. {
  1424. m_log.Info("[SCENE]: Loading land objects from storage");
  1425. List<LandData> landData = m_storageManager.DataStore.LoadLandObjects(regionID);
  1426. if (LandChannel != null)
  1427. {
  1428. if (landData.Count == 0)
  1429. {
  1430. EventManager.TriggerNoticeNoLandDataFromStorage();
  1431. }
  1432. else
  1433. {
  1434. EventManager.TriggerIncomingLandDataFromStorage(landData);
  1435. }
  1436. }
  1437. else
  1438. {
  1439. m_log.Error("[SCENE]: Land Channel is not defined. Cannot load from storage!");
  1440. }
  1441. }
  1442. #endregion
  1443. #region Primitives Methods
  1444. /// <summary>
  1445. /// Loads the World's objects
  1446. /// </summary>
  1447. public virtual void LoadPrimsFromStorage(UUID regionID)
  1448. {
  1449. m_log.Info("[SCENE]: Loading objects from datastore");
  1450. List<SceneObjectGroup> PrimsFromDB = m_storageManager.DataStore.LoadObjects(regionID);
  1451. foreach (SceneObjectGroup group in PrimsFromDB)
  1452. {
  1453. if (group.RootPart == null)
  1454. {
  1455. m_log.ErrorFormat("[SCENE] Found a SceneObjectGroup with m_rootPart == null and {0} children",
  1456. group.Children == null ? 0 : group.Children.Count);
  1457. }
  1458. AddRestoredSceneObject(group, true, true);
  1459. SceneObjectPart rootPart = group.GetChildPart(group.UUID);
  1460. rootPart.ObjectFlags &= ~(uint)PrimFlags.Scripted;
  1461. rootPart.TrimPermissions();
  1462. group.CheckSculptAndLoad();
  1463. //rootPart.DoPhysicsPropertyUpdate(UsePhysics, true);
  1464. }
  1465. m_log.Info("[SCENE]: Loaded " + PrimsFromDB.Count.ToString() + " SceneObject(s)");
  1466. }
  1467. public Vector3 GetNewRezLocation(Vector3 RayStart, Vector3 RayEnd, UUID RayTargetID, Quaternion rot, byte bypassRayCast, byte RayEndIsIntersection, bool frontFacesOnly, Vector3 scale, bool FaceCenter)
  1468. {
  1469. Vector3 pos = Vector3.Zero;
  1470. if (RayEndIsIntersection == (byte)1)
  1471. {
  1472. pos = RayEnd;
  1473. return pos;
  1474. }
  1475. if (RayTargetID != UUID.Zero)
  1476. {
  1477. SceneObjectPart target = GetSceneObjectPart(RayTargetID);
  1478. Vector3 direction = Vector3.Normalize(RayEnd - RayStart);
  1479. Vector3 AXOrigin = new Vector3(RayStart.X, RayStart.Y, RayStart.Z);
  1480. Vector3 AXdirection = new Vector3(direction.X, direction.Y, direction.Z);
  1481. if (target != null)
  1482. {
  1483. pos = target.AbsolutePosition;
  1484. //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());
  1485. // TODO: Raytrace better here
  1486. //EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection));
  1487. Ray NewRay = new Ray(AXOrigin, AXdirection);
  1488. // Ray Trace against target here
  1489. EntityIntersection ei = target.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, FaceCenter);
  1490. // Un-comment out the following line to Get Raytrace results printed to the console.
  1491. // m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  1492. float ScaleOffset = 0.5f;
  1493. // If we hit something
  1494. if (ei.HitTF)
  1495. {
  1496. Vector3 scaleComponent = new Vector3(ei.AAfaceNormal.X, ei.AAfaceNormal.Y, ei.AAfaceNormal.Z);
  1497. if (scaleComponent.X != 0) ScaleOffset = scale.X;
  1498. if (scaleComponent.Y != 0) ScaleOffset = scale.Y;
  1499. if (scaleComponent.Z != 0) ScaleOffset = scale.Z;
  1500. ScaleOffset = Math.Abs(ScaleOffset);
  1501. Vector3 intersectionpoint = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
  1502. Vector3 normal = new Vector3(ei.normal.X, ei.normal.Y, ei.normal.Z);
  1503. // Set the position to the intersection point
  1504. Vector3 offset = (normal * (ScaleOffset / 2f));
  1505. pos = (intersectionpoint + offset);
  1506. // Un-offset the prim (it gets offset later by the consumer method)
  1507. pos.Z -= 0.25F;
  1508. }
  1509. return pos;
  1510. }
  1511. else
  1512. {
  1513. // We don't have a target here, so we're going to raytrace all the objects in the scene.
  1514. EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection), true, false);
  1515. // Un-comment the following line to print the raytrace results to the console.
  1516. //m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  1517. if (ei.HitTF)
  1518. {
  1519. pos = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
  1520. } else
  1521. {
  1522. // fall back to our stupid functionality
  1523. pos = RayEnd;
  1524. }
  1525. return pos;
  1526. }
  1527. }
  1528. else
  1529. {
  1530. // fall back to our stupid functionality
  1531. pos = RayEnd;
  1532. return pos;
  1533. }
  1534. }
  1535. public virtual void AddNewPrim(UUID ownerID, UUID groupID, Vector3 RayEnd, Quaternion rot, PrimitiveBaseShape shape,
  1536. byte bypassRaycast, Vector3 RayStart, UUID RayTargetID,
  1537. byte RayEndIsIntersection)
  1538. {
  1539. Vector3 pos = GetNewRezLocation(RayStart, RayEnd, RayTargetID, rot, bypassRaycast, RayEndIsIntersection, true, new Vector3(0.5f, 0.5f, 0.5f), false);
  1540. if (Permissions.CanRezObject(1, ownerID, pos))
  1541. {
  1542. // rez ON the ground, not IN the ground
  1543. pos.Z += 0.25F;
  1544. AddNewPrim(ownerID, groupID, pos, rot, shape);
  1545. }
  1546. }
  1547. public virtual SceneObjectGroup AddNewPrim(
  1548. UUID ownerID, UUID groupID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape)
  1549. {
  1550. //m_log.DebugFormat(
  1551. // "[SCENE]: Scene.AddNewPrim() pcode {0} called for {1} in {2}", shape.PCode, ownerID, RegionInfo.RegionName);
  1552. // If an entity creator has been registered for this prim type then use that
  1553. if (m_entityCreators.ContainsKey((PCode)shape.PCode))
  1554. return m_entityCreators[(PCode)shape.PCode].CreateEntity(ownerID, groupID, pos, rot, shape);
  1555. // Otherwise, use this default creation code;
  1556. SceneObjectGroup sceneObject = new SceneObjectGroup(ownerID, pos, rot, shape);
  1557. AddNewSceneObject(sceneObject, true);
  1558. sceneObject.SetGroup(groupID, null);
  1559. return sceneObject;
  1560. }
  1561. /// <summary>
  1562. /// Add an object into the scene that has come from storage
  1563. /// </summary>
  1564. /// <param name="sceneObject"></param>
  1565. /// <param name="attachToBackup">
  1566. /// If true, changes to the object will be reflected in its persisted data
  1567. /// If false, the persisted data will not be changed even if the object in the scene is changed
  1568. /// </param>
  1569. /// <param name="alreadyPersisted">
  1570. /// If true, we won't persist this object until it changes
  1571. /// If false, we'll persist this object immediately
  1572. /// </param>
  1573. /// <returns>
  1574. /// true if the object was added, false if an object with the same uuid was already in the scene
  1575. /// </returns>
  1576. public bool AddRestoredSceneObject(
  1577. SceneObjectGroup sceneObject, bool attachToBackup, bool alreadyPersisted)
  1578. {
  1579. return m_sceneGraph.AddRestoredSceneObject(sceneObject, attachToBackup, alreadyPersisted);
  1580. }
  1581. /// <summary>
  1582. /// Add a newly created object to the scene
  1583. /// </summary>
  1584. /// <param name="sceneObject"></param>
  1585. /// <param name="attachToBackup">
  1586. /// If true, the object is made persistent into the scene.
  1587. /// If false, the object will not persist over server restarts
  1588. /// </param>
  1589. public bool AddNewSceneObject(SceneObjectGroup sceneObject, bool attachToBackup)
  1590. {
  1591. return m_sceneGraph.AddNewSceneObject(sceneObject, attachToBackup);
  1592. }
  1593. /// <summary>
  1594. /// Delete every object from the scene
  1595. /// </summary>
  1596. public void DeleteAllSceneObjects()
  1597. {
  1598. lock (Entities)
  1599. {
  1600. ICollection<EntityBase> entities = new List<EntityBase>(Entities);
  1601. foreach (EntityBase e in entities)
  1602. {
  1603. if (e is SceneObjectGroup)
  1604. DeleteSceneObject((SceneObjectGroup)e, false);
  1605. }
  1606. }
  1607. }
  1608. /// <summary>
  1609. /// Synchronously delete the given object from the scene.
  1610. /// </summary>
  1611. /// <param name="group"></param>
  1612. public void DeleteSceneObject(SceneObjectGroup group, bool silent)
  1613. {
  1614. //SceneObjectPart rootPart = group.GetChildPart(group.UUID);
  1615. // Serialise calls to RemoveScriptInstances to avoid
  1616. // deadlocking on m_parts inside SceneObjectGroup
  1617. lock (m_deleting_scene_object)
  1618. {
  1619. group.RemoveScriptInstances();
  1620. }
  1621. foreach (SceneObjectPart part in group.Children.Values)
  1622. {
  1623. if (part.IsJoint() && ((part.ObjectFlags&(uint)PrimFlags.Physics) != 0) )
  1624. {
  1625. PhysicsScene.RequestJointDeletion(part.Name); // FIXME: what if the name changed?
  1626. }
  1627. else if (part.PhysActor != null)
  1628. {
  1629. PhysicsScene.RemovePrim(part.PhysActor);
  1630. part.PhysActor = null;
  1631. }
  1632. }
  1633. // if (rootPart.PhysActor != null)
  1634. // {
  1635. // PhysicsScene.RemovePrim(rootPart.PhysActor);
  1636. // rootPart.PhysActor = null;
  1637. // }
  1638. if (UnlinkSceneObject(group.UUID, false))
  1639. {
  1640. EventManager.TriggerObjectBeingRemovedFromScene(group);
  1641. EventManager.TriggerParcelPrimCountTainted();
  1642. }
  1643. group.DeleteGroup(silent);
  1644. }
  1645. /// <summary>
  1646. /// Unlink the given object from the scene. Unlike delete, this just removes the record of the object - the
  1647. /// object itself is not destroyed.
  1648. /// </summary>
  1649. /// <param name="uuid"></param>
  1650. /// <returns>true if the object was in the scene, false if it was not</returns>
  1651. public bool UnlinkSceneObject(UUID uuid, bool resultOfLinkingObjects)
  1652. {
  1653. if (m_sceneGraph.DeleteSceneObject(uuid, resultOfLinkingObjects))
  1654. {
  1655. if (!resultOfLinkingObjects)
  1656. m_storageManager.DataStore.RemoveObject(uuid,
  1657. m_regInfo.RegionID);
  1658. return true;
  1659. }
  1660. return false;
  1661. }
  1662. /// <summary>
  1663. /// Move the given scene object into a new region depending on which region its absolute position has moved
  1664. /// into.
  1665. ///
  1666. /// This method locates the new region handle and offsets the prim position for the new region
  1667. /// </summary>
  1668. /// <param name="attemptedPosition">the attempted out of region position of the scene object</param>
  1669. /// <param name="grp">the scene object that we're crossing</param>
  1670. public void CrossPrimGroupIntoNewRegion(Vector3 attemptedPosition, SceneObjectGroup grp, bool silent)
  1671. {
  1672. if (grp == null)
  1673. return;
  1674. if (grp.IsDeleted)
  1675. return;
  1676. if (grp.RootPart.DIE_AT_EDGE)
  1677. {
  1678. // We remove the object here
  1679. try
  1680. {
  1681. DeleteSceneObject(grp, false);
  1682. }
  1683. catch (Exception)
  1684. {
  1685. m_log.Warn("[DATABASE]: exception when trying to remove the prim that crossed the border.");
  1686. }
  1687. return;
  1688. }
  1689. int thisx = (int)RegionInfo.RegionLocX;
  1690. int thisy = (int)RegionInfo.RegionLocY;
  1691. ulong newRegionHandle = 0;
  1692. Vector3 pos = attemptedPosition;
  1693. if (attemptedPosition.X > Constants.RegionSize + 0.1f)
  1694. {
  1695. pos.X = ((pos.X - Constants.RegionSize));
  1696. newRegionHandle
  1697. = Util.UIntsToLong((uint)((thisx + 1) * Constants.RegionSize), (uint)(thisy * Constants.RegionSize));
  1698. // x + 1
  1699. }
  1700. else if (attemptedPosition.X < -0.1f)
  1701. {
  1702. pos.X = ((pos.X + Constants.RegionSize));
  1703. newRegionHandle
  1704. = Util.UIntsToLong((uint)((thisx - 1) * Constants.RegionSize), (uint)(thisy * Constants.RegionSize));
  1705. // x - 1
  1706. }
  1707. if (attemptedPosition.Y > Constants.RegionSize + 0.1f)
  1708. {
  1709. pos.Y = ((pos.Y - Constants.RegionSize));
  1710. newRegionHandle
  1711. = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy + 1) * Constants.RegionSize));
  1712. // y + 1
  1713. }
  1714. else if (attemptedPosition.Y < -0.1f)
  1715. {
  1716. pos.Y = ((pos.Y + Constants.RegionSize));
  1717. newRegionHandle
  1718. = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy - 1) * Constants.RegionSize));
  1719. // y - 1
  1720. }
  1721. // Offset the positions for the new region across the border
  1722. Vector3 oldGroupPosition = grp.RootPart.GroupPosition;
  1723. grp.OffsetForNewRegion(pos);
  1724. // If we fail to cross the border, then reset the position of the scene object on that border.
  1725. if (!CrossPrimGroupIntoNewRegion(newRegionHandle, grp, silent))
  1726. {
  1727. grp.OffsetForNewRegion(oldGroupPosition);
  1728. grp.ScheduleGroupForFullUpdate();
  1729. }
  1730. }
  1731. /// <summary>
  1732. /// Move the given scene object into a new region
  1733. /// </summary>
  1734. /// <param name="newRegionHandle"></param>
  1735. /// <param name="grp">Scene Object Group that we're crossing</param>
  1736. /// <returns>
  1737. /// true if the crossing itself was successful, false on failure
  1738. /// FIMXE: we still return true if the crossing object was not successfully deleted from the originating region
  1739. /// </returns>
  1740. public bool CrossPrimGroupIntoNewRegion(ulong newRegionHandle, SceneObjectGroup grp, bool silent)
  1741. {
  1742. bool successYN = false;
  1743. grp.RootPart.UpdateFlag = 0;
  1744. int primcrossingXMLmethod = 0;
  1745. if (newRegionHandle != 0)
  1746. {
  1747. string objectState = grp.GetStateSnapshot();
  1748. successYN
  1749. = m_sceneGridService.PrimCrossToNeighboringRegion(
  1750. newRegionHandle, grp.UUID, m_serialiser.SaveGroupToXml2(grp), primcrossingXMLmethod);
  1751. if (successYN && (objectState != "") && m_allowScriptCrossings)
  1752. {
  1753. successYN = m_sceneGridService.PrimCrossToNeighboringRegion(
  1754. newRegionHandle, grp.UUID, objectState, 100);
  1755. }
  1756. if (successYN)
  1757. {
  1758. // We remove the object here
  1759. try
  1760. {
  1761. DeleteSceneObject(grp, silent);
  1762. }
  1763. catch (Exception e)
  1764. {
  1765. m_log.ErrorFormat(
  1766. "[INTERREGION]: Exception deleting the old object left behind on a border crossing for {0}, {1}",
  1767. grp, e);
  1768. }
  1769. }
  1770. else
  1771. {
  1772. if (!grp.IsDeleted)
  1773. {
  1774. if (grp.RootPart.PhysActor != null)
  1775. {
  1776. grp.RootPart.PhysActor.CrossingFailure();
  1777. }
  1778. }
  1779. m_log.ErrorFormat("[INTERREGION]: Prim crossing failed for {0}", grp);
  1780. }
  1781. }
  1782. else
  1783. {
  1784. m_log.Error("[INTERREGION]: region handle was unexpectedly 0 in Scene.CrossPrimGroupIntoNewRegion()");
  1785. }
  1786. return successYN;
  1787. }
  1788. /// <summary>
  1789. /// Handle a scene object that is crossing into this region from another.
  1790. /// </summary>
  1791. /// <param name="regionHandle"></param>
  1792. /// <param name="primID"></param>
  1793. /// <param name="objXMLData"></param>
  1794. /// <param name="XMLMethod"></param>
  1795. /// <returns></returns>
  1796. public bool IncomingInterRegionPrimGroup(UUID primID, string objXMLData, int XMLMethod)
  1797. {
  1798. if (XMLMethod == 0)
  1799. {
  1800. m_log.DebugFormat("[INTERREGION]: A new prim {0} arrived from a neighbor", primID);
  1801. SceneObjectGroup sceneObject = m_serialiser.DeserializeGroupFromXml2(objXMLData);
  1802. // If the user is banned, we won't let any of their objects
  1803. // enter. Period.
  1804. //
  1805. if (m_regInfo.EstateSettings.IsBanned(sceneObject.OwnerID))
  1806. {
  1807. m_log.Info("[INTERREGION]: Denied prim crossing for "+
  1808. "banned avatar");
  1809. return false;
  1810. }
  1811. // Force allocation of new LocalId
  1812. //
  1813. foreach (SceneObjectPart p in sceneObject.Children.Values)
  1814. p.LocalId = 0;
  1815. if (sceneObject.RootPart.Shape.PCode == (byte)PCode.Prim)
  1816. {
  1817. if (sceneObject.RootPart.Shape.State != 0)
  1818. {
  1819. // Fix up attachment Parent Local ID
  1820. //
  1821. ScenePresence sp = GetScenePresence(sceneObject.OwnerID);
  1822. uint parentLocalID = 0;
  1823. if (sp != null)
  1824. parentLocalID = sp.LocalId;
  1825. sceneObject.RootPart.IsAttachment = true;
  1826. sceneObject.RootPart.SetParentLocalId(parentLocalID);
  1827. AddRestoredSceneObject(sceneObject, false, false);
  1828. // Handle attachment special case
  1829. //
  1830. SceneObjectPart RootPrim = GetSceneObjectPart(primID);
  1831. if (RootPrim != null)
  1832. {
  1833. SceneObjectGroup grp = RootPrim.ParentGroup;
  1834. RootPrim.SetParentLocalId(parentLocalID);
  1835. if (grp != null)
  1836. {
  1837. m_log.DebugFormat("[ATTACHMENT]: Received "+
  1838. "attachment {0}, inworld asset id {1}",
  1839. grp.RootPart.LastOwnerID.ToString(),
  1840. grp.UUID.ToString());
  1841. if (sp != null)
  1842. {
  1843. grp.SetFromAssetID(grp.RootPart.LastOwnerID);
  1844. m_log.DebugFormat("[ATTACHMENT]: Attach "+
  1845. "to avatar {0}",
  1846. sp.UUID.ToString());
  1847. AttachObject(sp.ControllingClient,
  1848. grp.LocalId, (uint)0,
  1849. grp.GroupRotation,
  1850. grp.AbsolutePosition, false);
  1851. grp.SendGroupFullUpdate();
  1852. }
  1853. else
  1854. {
  1855. RootPrim.RemFlag(PrimFlags.TemporaryOnRez);
  1856. RootPrim.AddFlag(PrimFlags.TemporaryOnRez);
  1857. }
  1858. }
  1859. }
  1860. }
  1861. else
  1862. {
  1863. AddRestoredSceneObject(sceneObject, true, false);
  1864. if (!Permissions.CanObjectEntry(sceneObject.UUID,
  1865. true, sceneObject.AbsolutePosition))
  1866. {
  1867. // Deny non attachments based on parcel settings
  1868. //
  1869. m_log.Info("[INTERREGION]: Denied prim crossing "+
  1870. "because of parcel settings");
  1871. DeleteSceneObject(sceneObject, false);
  1872. return false;
  1873. }
  1874. }
  1875. }
  1876. }
  1877. else if ((XMLMethod == 100) && m_allowScriptCrossings)
  1878. {
  1879. m_log.Warn("[INTERREGION]: Prim state data arrived from a neighbor");
  1880. XmlDocument doc = new XmlDocument();
  1881. doc.LoadXml(objXMLData);
  1882. XmlNodeList rootL = doc.GetElementsByTagName("ScriptData");
  1883. if (rootL.Count == 1)
  1884. {
  1885. XmlNode rootNode = rootL[0];
  1886. if (rootNode != null)
  1887. {
  1888. XmlNodeList partL = rootNode.ChildNodes;
  1889. foreach (XmlNode part in partL)
  1890. {
  1891. XmlNodeList nodeL = part.ChildNodes;
  1892. switch (part.Name)
  1893. {
  1894. case "Assemblies":
  1895. foreach (XmlNode asm in nodeL)
  1896. {
  1897. string fn = asm.Attributes.GetNamedItem("Filename").Value;
  1898. Byte[] filedata = Convert.FromBase64String(asm.InnerText);
  1899. string path = Path.Combine("ScriptEngines", RegionInfo.RegionID.ToString());
  1900. path = Path.Combine(path, fn);
  1901. if (!File.Exists(path))
  1902. {
  1903. FileStream fs = File.Create(path);
  1904. fs.Write(filedata, 0, filedata.Length);
  1905. fs.Close();
  1906. }
  1907. }
  1908. break;
  1909. case "ScriptStates":
  1910. foreach (XmlNode st in nodeL)
  1911. {
  1912. string id = st.Attributes.GetNamedItem("UUID").Value;
  1913. UUID uuid = new UUID(id);
  1914. XmlNode state = st.ChildNodes[0];
  1915. XmlDocument sdoc = new XmlDocument();
  1916. XmlNode sxmlnode = sdoc.CreateNode(
  1917. XmlNodeType.XmlDeclaration,
  1918. "", "");
  1919. sdoc.AppendChild(sxmlnode);
  1920. XmlNode newnode = sdoc.ImportNode(state, true);
  1921. sdoc.AppendChild(newnode);
  1922. string spath = Path.Combine("ScriptEngines", RegionInfo.RegionID.ToString());
  1923. spath = Path.Combine(spath, uuid.ToString());
  1924. FileStream sfs = File.Create(spath + ".state");
  1925. System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
  1926. Byte[] buf = enc.GetBytes(sdoc.InnerXml);
  1927. sfs.Write(buf, 0, buf.Length);
  1928. sfs.Close();
  1929. }
  1930. break;
  1931. }
  1932. }
  1933. }
  1934. }
  1935. SceneObjectPart RootPrim = GetSceneObjectPart(primID);
  1936. RootPrim.ParentGroup.CreateScriptInstances(0, false, DefaultScriptEngine, 1);
  1937. return true;
  1938. }
  1939. return true;
  1940. }
  1941. #endregion
  1942. #region Add/Remove Avatar Methods
  1943. public override void AddNewClient(IClientAPI client)
  1944. {
  1945. SubscribeToClientEvents(client);
  1946. ScenePresence presence;
  1947. if (m_restorePresences.ContainsKey(client.AgentId))
  1948. {
  1949. m_log.DebugFormat("[SCENE]: Restoring agent {0} {1} in {2}", client.Name, client.AgentId, RegionInfo.RegionName);
  1950. presence = m_restorePresences[client.AgentId];
  1951. m_restorePresences.Remove(client.AgentId);
  1952. // This is one of two paths to create avatars that are
  1953. // used. This tends to get called more in standalone
  1954. // than grid, not really sure why, but as such needs
  1955. // an explicity appearance lookup here.
  1956. AvatarAppearance appearance = null;
  1957. GetAvatarAppearance(client, out appearance);
  1958. presence.Appearance = appearance;
  1959. presence.initializeScenePresence(client, RegionInfo, this);
  1960. m_sceneGraph.AddScenePresence(presence);
  1961. lock (m_restorePresences)
  1962. {
  1963. Monitor.PulseAll(m_restorePresences);
  1964. }
  1965. }
  1966. else
  1967. {
  1968. m_log.DebugFormat(
  1969. "[SCENE]: Adding new child agent for {0} in {1}",
  1970. client.Name, RegionInfo.RegionName);
  1971. CommsManager.UserProfileCacheService.AddNewUser(client.AgentId);
  1972. CreateAndAddScenePresence(client);
  1973. }
  1974. m_LastLogin = System.Environment.TickCount;
  1975. EventManager.TriggerOnNewClient(client);
  1976. }
  1977. protected virtual void SubscribeToClientEvents(IClientAPI client)
  1978. {
  1979. client.OnRegionHandShakeReply += SendLayerData;
  1980. client.OnAddPrim += AddNewPrim;
  1981. client.OnUpdatePrimGroupPosition += m_sceneGraph.UpdatePrimPosition;
  1982. client.OnUpdatePrimSinglePosition += m_sceneGraph.UpdatePrimSinglePosition;
  1983. client.OnUpdatePrimGroupRotation += m_sceneGraph.UpdatePrimRotation;
  1984. client.OnUpdatePrimGroupMouseRotation += m_sceneGraph.UpdatePrimRotation;
  1985. client.OnUpdatePrimSingleRotation += m_sceneGraph.UpdatePrimSingleRotation;
  1986. client.OnUpdatePrimScale += m_sceneGraph.UpdatePrimScale;
  1987. client.OnUpdatePrimGroupScale += m_sceneGraph.UpdatePrimGroupScale;
  1988. client.OnUpdateExtraParams += m_sceneGraph.UpdateExtraParam;
  1989. client.OnUpdatePrimShape += m_sceneGraph.UpdatePrimShape;
  1990. client.OnUpdatePrimTexture += m_sceneGraph.UpdatePrimTexture;
  1991. client.OnTeleportLocationRequest += RequestTeleportLocation;
  1992. client.OnTeleportLandmarkRequest += RequestTeleportLandmark;
  1993. client.OnObjectSelect += SelectPrim;
  1994. client.OnObjectDeselect += DeselectPrim;
  1995. client.OnGrabUpdate += m_sceneGraph.MoveObject;
  1996. client.OnDeRezObject += DeRezObject;
  1997. client.OnRezObject += RezObject;
  1998. client.OnRezSingleAttachmentFromInv += RezSingleAttachment;
  1999. client.OnDetachAttachmentIntoInv += DetachSingleAttachmentToInv;
  2000. client.OnObjectAttach += m_sceneGraph.AttachObject;
  2001. client.OnObjectDetach += m_sceneGraph.DetachObject;
  2002. client.OnObjectDrop += m_sceneGraph.DropObject;
  2003. client.OnNameFromUUIDRequest += CommsManager.HandleUUIDNameRequest;
  2004. client.OnObjectDescription += m_sceneGraph.PrimDescription;
  2005. client.OnObjectName += m_sceneGraph.PrimName;
  2006. client.OnObjectClickAction += m_sceneGraph.PrimClickAction;
  2007. client.OnObjectMaterial += m_sceneGraph.PrimMaterial;
  2008. client.OnLinkObjects += m_sceneGraph.LinkObjects;
  2009. client.OnDelinkObjects += m_sceneGraph.DelinkObjects;
  2010. client.OnObjectDuplicate += m_sceneGraph.DuplicateObject;
  2011. client.OnObjectDuplicateOnRay += doObjectDuplicateOnRay;
  2012. client.OnUpdatePrimFlags += m_sceneGraph.UpdatePrimFlags;
  2013. client.OnRequestObjectPropertiesFamily += m_sceneGraph.RequestObjectPropertiesFamily;
  2014. client.OnRequestGodlikePowers += handleRequestGodlikePowers;
  2015. client.OnGodKickUser += HandleGodlikeKickUser;
  2016. client.OnObjectPermissions += HandleObjectPermissionsUpdate;
  2017. client.OnCreateNewInventoryItem += CreateNewInventoryItem;
  2018. client.OnCreateNewInventoryFolder += HandleCreateInventoryFolder;
  2019. client.OnUpdateInventoryFolder += HandleUpdateInventoryFolder;
  2020. client.OnMoveInventoryFolder += HandleMoveInventoryFolder;
  2021. client.OnFetchInventoryDescendents += HandleFetchInventoryDescendents;
  2022. client.OnPurgeInventoryDescendents += HandlePurgeInventoryDescendents;
  2023. client.OnFetchInventory += HandleFetchInventory;
  2024. client.OnUpdateInventoryItem += UpdateInventoryItemAsset;
  2025. client.OnCopyInventoryItem += CopyInventoryItem;
  2026. client.OnMoveInventoryItem += MoveInventoryItem;
  2027. client.OnRemoveInventoryItem += RemoveInventoryItem;
  2028. client.OnRemoveInventoryFolder += RemoveInventoryFolder;
  2029. client.OnRezScript += RezScript;
  2030. client.OnRequestTaskInventory += RequestTaskInventory;
  2031. client.OnRemoveTaskItem += RemoveTaskInventory;
  2032. client.OnUpdateTaskInventory += UpdateTaskInventory;
  2033. client.OnMoveTaskItem += ClientMoveTaskInventoryItem;
  2034. client.OnGrabObject += ProcessObjectGrab;
  2035. client.OnDeGrabObject += ProcessObjectDeGrab;
  2036. client.OnMoneyTransferRequest += ProcessMoneyTransferRequest;
  2037. client.OnParcelBuy += ProcessParcelBuy;
  2038. client.OnAvatarPickerRequest += ProcessAvatarPickerRequest;
  2039. client.OnObjectIncludeInSearch += m_sceneGraph.MakeObjectSearchable;
  2040. client.OnTeleportHomeRequest += TeleportClientHome;
  2041. client.OnSetStartLocationRequest += SetHomeRezPoint;
  2042. client.OnUndo += m_sceneGraph.HandleUndo;
  2043. client.OnObjectGroupRequest += m_sceneGraph.HandleObjectGroupUpdate;
  2044. client.OnParcelReturnObjectsRequest += LandChannel.ReturnObjectsInParcel;
  2045. client.OnParcelSetOtherCleanTime += LandChannel.SetParcelOtherCleanTime;
  2046. client.OnObjectSaleInfo += ObjectSaleInfo;
  2047. client.OnScriptReset += ProcessScriptReset;
  2048. client.OnGetScriptRunning += GetScriptRunning;
  2049. client.OnSetScriptRunning += SetScriptRunning;
  2050. client.OnRegionHandleRequest += RegionHandleRequest;
  2051. client.OnUnackedTerrain += TerrainUnAcked;
  2052. client.OnObjectOwner += ObjectOwner;
  2053. if (StatsReporter != null)
  2054. client.OnNetworkStatsUpdate += StatsReporter.AddPacketsFromClientStats;
  2055. // EventManager.TriggerOnNewClient(client);
  2056. }
  2057. /// <summary>
  2058. /// Teleport an avatar to their home region
  2059. /// </summary>
  2060. /// <param name="agentId"></param>
  2061. /// <param name="client"></param>
  2062. public virtual void TeleportClientHome(UUID agentId, IClientAPI client)
  2063. {
  2064. UserProfileData UserProfile = CommsManager.UserService.GetUserProfile(agentId);
  2065. if (UserProfile != null)
  2066. {
  2067. RegionInfo regionInfo = CommsManager.GridService.RequestNeighbourInfo(UserProfile.HomeRegionID);
  2068. if (regionInfo == null)
  2069. {
  2070. regionInfo = CommsManager.GridService.RequestNeighbourInfo(UserProfile.HomeRegion);
  2071. if (regionInfo != null) // home region can be away temporarily, too
  2072. {
  2073. UserProfile.HomeRegionID = regionInfo.RegionID;
  2074. CommsManager.UserService.UpdateUserProfile(UserProfile);
  2075. }
  2076. }
  2077. if (regionInfo == null)
  2078. {
  2079. // can't find the Home region: Tell viewer and abort
  2080. client.SendTeleportFailed("Your home-region could not be found.");
  2081. return;
  2082. }
  2083. RequestTeleportLocation(
  2084. client, regionInfo.RegionHandle, UserProfile.HomeLocation, UserProfile.HomeLookAt,
  2085. (uint)(TPFlags.SetLastToTarget | TPFlags.ViaHome));
  2086. }
  2087. }
  2088. public void doObjectDuplicateOnRay(uint localID, uint dupeFlags, UUID AgentID, UUID GroupID,
  2089. UUID RayTargetObj, Vector3 RayEnd, Vector3 RayStart,
  2090. bool BypassRaycast, bool RayEndIsIntersection, bool CopyCenters, bool CopyRotates)
  2091. {
  2092. Vector3 pos;
  2093. const bool frontFacesOnly = true;
  2094. //m_log.Info("HITTARGET: " + RayTargetObj.ToString() + ", COPYTARGET: " + localID.ToString());
  2095. SceneObjectPart target = GetSceneObjectPart(localID);
  2096. SceneObjectPart target2 = GetSceneObjectPart(RayTargetObj);
  2097. if (target != null && target2 != null)
  2098. {
  2099. Vector3 direction = Vector3.Normalize(RayEnd - RayStart);
  2100. Vector3 AXOrigin = new Vector3(RayStart.X, RayStart.Y, RayStart.Z);
  2101. Vector3 AXdirection = new Vector3(direction.X, direction.Y, direction.Z);
  2102. if (target2.ParentGroup != null)
  2103. {
  2104. pos = target2.AbsolutePosition;
  2105. //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());
  2106. // TODO: Raytrace better here
  2107. //EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection));
  2108. Ray NewRay = new Ray(AXOrigin, AXdirection);
  2109. // Ray Trace against target here
  2110. EntityIntersection ei = target2.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, CopyCenters);
  2111. // Un-comment out the following line to Get Raytrace results printed to the console.
  2112. //m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  2113. float ScaleOffset = 0.5f;
  2114. // If we hit something
  2115. if (ei.HitTF)
  2116. {
  2117. Vector3 scale = target.Scale;
  2118. Vector3 scaleComponent = new Vector3(ei.AAfaceNormal.X, ei.AAfaceNormal.Y, ei.AAfaceNormal.Z);
  2119. if (scaleComponent.X != 0) ScaleOffset = scale.X;
  2120. if (scaleComponent.Y != 0) ScaleOffset = scale.Y;
  2121. if (scaleComponent.Z != 0) ScaleOffset = scale.Z;
  2122. ScaleOffset = Math.Abs(ScaleOffset);
  2123. Vector3 intersectionpoint = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
  2124. Vector3 normal = new Vector3(ei.normal.X, ei.normal.Y, ei.normal.Z);
  2125. Vector3 offset = normal * (ScaleOffset / 2f);
  2126. pos = intersectionpoint + offset;
  2127. // stick in offset format from the original prim
  2128. pos = pos - target.ParentGroup.AbsolutePosition;
  2129. if (CopyRotates)
  2130. {
  2131. Quaternion worldRot = target2.GetWorldRotation();
  2132. // SceneObjectGroup obj = m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID, worldRot);
  2133. m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID, worldRot);
  2134. //obj.Rotation = worldRot;
  2135. //obj.UpdateGroupRotation(worldRot);
  2136. }
  2137. else
  2138. {
  2139. m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID);
  2140. }
  2141. }
  2142. return;
  2143. }
  2144. return;
  2145. }
  2146. }
  2147. public virtual void SetHomeRezPoint(IClientAPI remoteClient, ulong regionHandle, Vector3 position, Vector3 lookAt, uint flags)
  2148. {
  2149. UserProfileData UserProfile = CommsManager.UserService.GetUserProfile(remoteClient.AgentId);
  2150. if (UserProfile != null)
  2151. {
  2152. // I know I'm ignoring the regionHandle provided by the teleport location request.
  2153. // reusing the TeleportLocationRequest delegate, so regionHandle isn't valid
  2154. UserProfile.HomeRegionID = RegionInfo.RegionID;
  2155. // TODO: The next line can be removed, as soon as only homeRegionID based UserServers are around.
  2156. // TODO: The HomeRegion property can be removed then, too
  2157. UserProfile.HomeRegion = RegionInfo.RegionHandle;
  2158. UserProfile.HomeLocation = position;
  2159. UserProfile.HomeLookAt = lookAt;
  2160. CommsManager.UserService.UpdateUserProfile(UserProfile);
  2161. // FUBAR ALERT: this needs to be "Home position set." so the viewer saves a home-screenshot.
  2162. m_dialogModule.SendAlertToUser(remoteClient, "Home position set.");
  2163. }
  2164. else
  2165. {
  2166. m_dialogModule.SendAlertToUser(remoteClient, "Set Home request Failed.");
  2167. }
  2168. }
  2169. /// <summary>
  2170. /// Create a child agent scene presence and add it to this scene.
  2171. /// </summary>
  2172. /// <param name="client"></param>
  2173. /// <returns></returns>
  2174. protected virtual ScenePresence CreateAndAddScenePresence(IClientAPI client)
  2175. {
  2176. AvatarAppearance appearance = null;
  2177. GetAvatarAppearance(client, out appearance);
  2178. ScenePresence avatar = m_sceneGraph.CreateAndAddChildScenePresence(client, appearance);
  2179. //avatar.KnownRegions = GetChildrenSeeds(avatar.UUID);
  2180. return avatar;
  2181. }
  2182. /// <summary>
  2183. /// Get the avatar apperance for the given client.
  2184. /// </summary>
  2185. /// <param name="client"></param>
  2186. /// <param name="appearance"></param>
  2187. public void GetAvatarAppearance(IClientAPI client, out AvatarAppearance appearance)
  2188. {
  2189. appearance = new AvatarAppearance();
  2190. try
  2191. {
  2192. if (m_AvatarFactory != null)
  2193. {
  2194. if (m_AvatarFactory.TryGetAvatarAppearance(client.AgentId, out appearance))
  2195. return;
  2196. }
  2197. }
  2198. catch (Exception e)
  2199. {
  2200. m_log.ErrorFormat("[APPEARANCE]: Problem fetching appearance for avatar {0}, {1}",
  2201. client.Name, e);
  2202. }
  2203. m_log.Warn("[APPEARANCE]: Appearance not found, returning default");
  2204. }
  2205. /// <summary>
  2206. /// Remove the given client from the scene.
  2207. /// </summary>
  2208. /// <param name="agentID"></param>
  2209. public override void RemoveClient(UUID agentID)
  2210. {
  2211. bool childagentYN = false;
  2212. ScenePresence avatar = GetScenePresence(agentID);
  2213. if (avatar != null)
  2214. {
  2215. childagentYN = avatar.IsChildAgent;
  2216. }
  2217. try
  2218. {
  2219. m_log.DebugFormat(
  2220. "[SCENE]: Removing {0} agent {1} from region {2}",
  2221. (childagentYN ? "child" : "root"), agentID, RegionInfo.RegionName);
  2222. m_sceneGraph.removeUserCount(!childagentYN);
  2223. CapsModule.RemoveCapsHandler(agentID);
  2224. if (avatar.Scene.NeedSceneCacheClear(avatar.UUID))
  2225. {
  2226. CommsManager.UserProfileCacheService.RemoveUser(agentID);
  2227. }
  2228. if (!avatar.IsChildAgent)
  2229. {
  2230. m_sceneGridService.LogOffUser(agentID, RegionInfo.RegionID, RegionInfo.RegionHandle, avatar.AbsolutePosition, avatar.Lookat);
  2231. //List<ulong> childknownRegions = new List<ulong>();
  2232. //List<ulong> ckn = avatar.KnownChildRegionHandles;
  2233. //for (int i = 0; i < ckn.Count; i++)
  2234. //{
  2235. // childknownRegions.Add(ckn[i]);
  2236. //}
  2237. List<ulong> regions = new List<ulong>(avatar.KnownChildRegionHandles);
  2238. regions.Remove(RegionInfo.RegionHandle);
  2239. m_sceneGridService.SendCloseChildAgentConnections(agentID, regions);
  2240. }
  2241. m_eventManager.TriggerClientClosed(agentID);
  2242. }
  2243. catch (NullReferenceException)
  2244. {
  2245. // We don't know which count to remove it from
  2246. // Avatar is already disposed :/
  2247. }
  2248. m_eventManager.TriggerOnRemovePresence(agentID);
  2249. Broadcast(delegate(IClientAPI client)
  2250. {
  2251. try
  2252. {
  2253. client.SendKillObject(avatar.RegionHandle, avatar.LocalId);
  2254. }
  2255. catch (NullReferenceException)
  2256. {
  2257. //We can safely ignore null reference exceptions. It means the avatar are dead and cleaned up anyway.
  2258. }
  2259. });
  2260. ForEachScenePresence(
  2261. delegate(ScenePresence presence) { presence.CoarseLocationChange(); });
  2262. IAgentAssetTransactions agentTransactions = this.RequestModuleInterface<IAgentAssetTransactions>();
  2263. if (agentTransactions != null)
  2264. {
  2265. agentTransactions.RemoveAgentAssetTransactions(agentID);
  2266. }
  2267. m_sceneGraph.RemoveScenePresence(agentID);
  2268. try
  2269. {
  2270. avatar.Close();
  2271. }
  2272. catch (NullReferenceException)
  2273. {
  2274. //We can safely ignore null reference exceptions. It means the avatar are dead and cleaned up anyway.
  2275. }
  2276. catch (Exception e)
  2277. {
  2278. m_log.Error("[SCENE] Scene.cs:RemoveClient exception: " + e.ToString());
  2279. }
  2280. // Remove client agent from profile, so new logins will work
  2281. if (!childagentYN)
  2282. {
  2283. m_sceneGridService.ClearUserAgent(agentID);
  2284. }
  2285. //m_log.InfoFormat("[SCENE] Memory pre GC {0}", System.GC.GetTotalMemory(false));
  2286. //m_log.InfoFormat("[SCENE] Memory post GC {0}", System.GC.GetTotalMemory(true));
  2287. }
  2288. public void HandleRemoveKnownRegionsFromAvatar(UUID avatarID, List<ulong> regionslst)
  2289. {
  2290. ScenePresence av = GetScenePresence(avatarID);
  2291. if (av != null)
  2292. {
  2293. lock (av)
  2294. {
  2295. for (int i = 0; i < regionslst.Count; i++)
  2296. {
  2297. av.KnownChildRegionHandles.Remove(regionslst[i]);
  2298. }
  2299. }
  2300. }
  2301. }
  2302. public override void CloseAllAgents(uint circuitcode)
  2303. {
  2304. // Called by ClientView to kill all circuit codes
  2305. ClientManager.CloseAllAgents(circuitcode);
  2306. }
  2307. public void NotifyMyCoarseLocationChange()
  2308. {
  2309. ForEachScenePresence(delegate(ScenePresence presence) { presence.CoarseLocationChange(); });
  2310. }
  2311. #endregion
  2312. #region Entities
  2313. public void SendKillObject(uint localID)
  2314. {
  2315. SceneObjectPart part = GetSceneObjectPart(localID);
  2316. if (part != null) // It is a prim
  2317. {
  2318. if (part.ParentGroup != null && !part.ParentGroup.IsDeleted) // Valid
  2319. {
  2320. if (part.ParentGroup.RootPart != part) // Child part
  2321. return;
  2322. }
  2323. }
  2324. Broadcast(delegate(IClientAPI client) { client.SendKillObject(m_regionHandle, localID); });
  2325. }
  2326. #endregion
  2327. #region RegionComms
  2328. /// <summary>
  2329. /// Register the methods that should be invoked when this scene receives various incoming events
  2330. /// </summary>
  2331. public void RegisterCommsEvents()
  2332. {
  2333. m_sceneGridService.OnExpectUser += NewUserConnection;
  2334. m_sceneGridService.OnAvatarCrossingIntoRegion += AgentCrossing;
  2335. m_sceneGridService.OnCloseAgentConnection += IncomingCloseAgent;
  2336. m_sceneGridService.OnRegionUp += OtherRegionUp;
  2337. //m_sceneGridService.OnChildAgentUpdate += IncomingChildAgentDataUpdate;
  2338. m_sceneGridService.OnExpectPrim += IncomingInterRegionPrimGroup;
  2339. //m_sceneGridService.OnRemoveKnownRegionFromAvatar += HandleRemoveKnownRegionsFromAvatar;
  2340. m_sceneGridService.OnLogOffUser += HandleLogOffUserFromGrid;
  2341. m_sceneGridService.KiPrimitive += SendKillObject;
  2342. m_sceneGridService.OnGetLandData += GetLandData;
  2343. if (m_interregionCommsIn != null)
  2344. {
  2345. m_log.Debug("[SCENE]: Registering with InterregionCommsIn");
  2346. m_interregionCommsIn.OnChildAgentUpdate += IncomingChildAgentDataUpdate;
  2347. }
  2348. else
  2349. m_log.Debug("[SCENE]: Unable to register with InterregionCommsIn");
  2350. }
  2351. /// <summary>
  2352. /// Deregister this scene from receiving incoming region events
  2353. /// </summary>
  2354. public void UnRegisterRegionWithComms()
  2355. {
  2356. m_sceneGridService.KiPrimitive -= SendKillObject;
  2357. m_sceneGridService.OnLogOffUser -= HandleLogOffUserFromGrid;
  2358. //m_sceneGridService.OnRemoveKnownRegionFromAvatar -= HandleRemoveKnownRegionsFromAvatar;
  2359. m_sceneGridService.OnExpectPrim -= IncomingInterRegionPrimGroup;
  2360. //m_sceneGridService.OnChildAgentUpdate -= IncomingChildAgentDataUpdate;
  2361. m_sceneGridService.OnRegionUp -= OtherRegionUp;
  2362. m_sceneGridService.OnExpectUser -= NewUserConnection;
  2363. m_sceneGridService.OnAvatarCrossingIntoRegion -= AgentCrossing;
  2364. m_sceneGridService.OnCloseAgentConnection -= IncomingCloseAgent;
  2365. m_sceneGridService.OnGetLandData -= GetLandData;
  2366. if (m_interregionCommsIn != null)
  2367. m_interregionCommsIn.OnChildAgentUpdate -= IncomingChildAgentDataUpdate;
  2368. m_sceneGridService.Close();
  2369. }
  2370. /// <summary>
  2371. /// Do the work necessary to initiate a new user connection for a particular scene.
  2372. /// At the moment, this consists of setting up the caps infrastructure
  2373. /// </summary>
  2374. /// <param name="regionHandle"></param>
  2375. /// <param name="agent"></param>
  2376. public void NewUserConnection(AgentCircuitData agent)
  2377. {
  2378. CapsModule.NewUserConnection(agent);
  2379. ScenePresence sp = m_sceneGraph.GetScenePresence(agent.AgentID);
  2380. if (sp != null)
  2381. {
  2382. m_log.DebugFormat(
  2383. "[SCENE]: Adjusting known seeds for existing agent {0} in {1}",
  2384. agent.AgentID, RegionInfo.RegionName);
  2385. sp.AdjustKnownSeeds();
  2386. return;
  2387. }
  2388. // Don't disable this log message - it's too helpful
  2389. m_log.DebugFormat(
  2390. "[CONNECTION BEGIN]: Region {0} told of incoming client {1} {2} {3} (circuit code {4})",
  2391. RegionInfo.RegionName, agent.firstname, agent.lastname, agent.AgentID, agent.circuitcode);
  2392. if (m_regInfo.EstateSettings.IsBanned(agent.AgentID))
  2393. {
  2394. m_log.WarnFormat(
  2395. "[CONNECTION BEGIN]: Denied access to: {0} at {1} because the user is on the region banlist",
  2396. agent.AgentID, RegionInfo.RegionName);
  2397. }
  2398. CapsModule.AddCapsHandler(agent.AgentID);
  2399. if (!agent.child)
  2400. {
  2401. // Honor parcel landing type and position.
  2402. ILandObject land = LandChannel.GetLandObject(agent.startpos.X, agent.startpos.Y);
  2403. if (land != null)
  2404. {
  2405. if (land.landData.LandingType == (byte)1 && land.landData.UserLocation != Vector3.Zero)
  2406. {
  2407. agent.startpos = land.landData.UserLocation;
  2408. }
  2409. }
  2410. }
  2411. m_authenticateHandler.AddNewCircuit(agent.circuitcode, agent);
  2412. // rewrite session_id
  2413. CachedUserInfo userinfo = CommsManager.UserProfileCacheService.GetUserDetails(agent.AgentID);
  2414. if (userinfo != null)
  2415. {
  2416. userinfo.SessionID = agent.SessionID;
  2417. }
  2418. else
  2419. {
  2420. m_log.WarnFormat(
  2421. "[CONNECTION BEGIN]: We couldn't find a User Info record for {0}. This is usually an indication that the UUID we're looking up is invalid", agent.AgentID);
  2422. }
  2423. }
  2424. public void UpdateCircuitData(AgentCircuitData data)
  2425. {
  2426. m_authenticateHandler.UpdateAgentData(data);
  2427. }
  2428. public bool ChangeCircuitCode(uint oldcc, uint newcc)
  2429. {
  2430. return m_authenticateHandler.TryChangeCiruitCode(oldcc, newcc);
  2431. }
  2432. protected void HandleLogOffUserFromGrid(UUID AvatarID, UUID RegionSecret, string message)
  2433. {
  2434. ScenePresence loggingOffUser = null;
  2435. loggingOffUser = GetScenePresence(AvatarID);
  2436. if (loggingOffUser != null)
  2437. {
  2438. UUID localRegionSecret = UUID.Zero;
  2439. bool parsedsecret = UUID.TryParse(m_regInfo.regionSecret, out localRegionSecret);
  2440. // Region Secret is used here in case a new sessionid overwrites an old one on the user server.
  2441. // Will update the user server in a few revisions to use it.
  2442. if (RegionSecret == loggingOffUser.ControllingClient.SecureSessionId || (parsedsecret && RegionSecret == localRegionSecret))
  2443. {
  2444. m_sceneGridService.SendCloseChildAgentConnections(loggingOffUser.UUID, new List<ulong>(loggingOffUser.KnownRegions.Keys));
  2445. loggingOffUser.ControllingClient.Kick(message);
  2446. // Give them a second to receive the message!
  2447. System.Threading.Thread.Sleep(1000);
  2448. loggingOffUser.ControllingClient.Close(true);
  2449. }
  2450. else
  2451. {
  2452. m_log.Info("[USERLOGOFF]: System sending the LogOff user message failed to sucessfully authenticate");
  2453. }
  2454. }
  2455. else
  2456. {
  2457. 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());
  2458. }
  2459. }
  2460. /// <summary>
  2461. /// Triggered when an agent crosses into this sim. Also happens on initial login.
  2462. /// </summary>
  2463. /// <param name="agentID"></param>
  2464. /// <param name="position"></param>
  2465. /// <param name="isFlying"></param>
  2466. public virtual void AgentCrossing(UUID agentID, Vector3 position, bool isFlying)
  2467. {
  2468. ScenePresence presence;
  2469. lock (m_scenePresences)
  2470. {
  2471. m_scenePresences.TryGetValue(agentID, out presence);
  2472. }
  2473. if (presence != null)
  2474. {
  2475. try
  2476. {
  2477. presence.MakeRootAgent(position, isFlying);
  2478. }
  2479. catch (Exception e)
  2480. {
  2481. m_log.ErrorFormat("[SCENE]: Unable to do agent crossing, exception {0}", e);
  2482. }
  2483. }
  2484. else
  2485. {
  2486. m_log.ErrorFormat(
  2487. "[SCENE]: Could not find presence for agent {0} crossing into scene {1}",
  2488. agentID, RegionInfo.RegionName);
  2489. }
  2490. }
  2491. public virtual bool IncomingChildAgentDataUpdate(AgentData cAgentData)
  2492. {
  2493. // m_log.DebugFormat(
  2494. // "[SCENE]: Incoming child agent update for {0} in {1}", cAgentData.AgentID, RegionInfo.RegionName);
  2495. ScenePresence childAgentUpdate = GetScenePresence(cAgentData.AgentID);
  2496. if (childAgentUpdate != null)
  2497. {
  2498. childAgentUpdate.ChildAgentDataUpdate(cAgentData);
  2499. return true;
  2500. }
  2501. return false;
  2502. }
  2503. public virtual bool IncomingChildAgentDataUpdate(AgentPosition cAgentData)
  2504. {
  2505. //Console.WriteLine(" XXX Scene IncomingChildAgentDataUpdate POSITION in " + RegionInfo.RegionName);
  2506. ScenePresence childAgentUpdate = GetScenePresence(cAgentData.AgentID);
  2507. if (childAgentUpdate != null)
  2508. {
  2509. // I can't imagine *yet* why we would get an update if the agent is a root agent..
  2510. // however to avoid a race condition crossing borders..
  2511. if (childAgentUpdate.IsChildAgent)
  2512. {
  2513. uint rRegionX = (uint)(cAgentData.RegionHandle >> 40);
  2514. uint rRegionY = (((uint)(cAgentData.RegionHandle)) >> 8);
  2515. uint tRegionX = RegionInfo.RegionLocX;
  2516. uint tRegionY = RegionInfo.RegionLocY;
  2517. //Send Data to ScenePresence
  2518. childAgentUpdate.ChildAgentDataUpdate(cAgentData, tRegionX, tRegionY, rRegionX, rRegionY);
  2519. // Not Implemented:
  2520. //TODO: Do we need to pass the message on to one of our neighbors?
  2521. }
  2522. return true;
  2523. }
  2524. return false;
  2525. }
  2526. public virtual bool IncomingReleaseAgent(UUID id)
  2527. {
  2528. return m_sceneGridService.ReleaseAgent(id);
  2529. }
  2530. public void SendReleaseAgent(ulong regionHandle, UUID id, string uri)
  2531. {
  2532. m_interregionCommsOut.SendReleaseAgent(regionHandle, id, uri);
  2533. }
  2534. /// <summary>
  2535. /// Tell a single agent to disconnect from the region.
  2536. /// </summary>
  2537. /// <param name="regionHandle"></param>
  2538. /// <param name="agentID"></param>
  2539. public bool IncomingCloseAgent(UUID agentID)
  2540. {
  2541. //m_log.DebugFormat("[SCENE]: Processing incoming close agent for {0}", agentID);
  2542. ScenePresence presence = m_sceneGraph.GetScenePresence(agentID);
  2543. if (presence != null)
  2544. {
  2545. // Nothing is removed here, so down count it as such
  2546. if (presence.IsChildAgent)
  2547. {
  2548. m_sceneGraph.removeUserCount(false);
  2549. }
  2550. else
  2551. {
  2552. m_sceneGraph.removeUserCount(true);
  2553. }
  2554. // Don't do this to root agents on logout, it's not nice for the viewer
  2555. if (presence.IsChildAgent)
  2556. {
  2557. // Tell a single agent to disconnect from the region.
  2558. IEventQueue eq = RequestModuleInterface<IEventQueue>();
  2559. if (eq != null)
  2560. {
  2561. OSD Item = EventQueueHelper.DisableSimulator(RegionInfo.RegionHandle);
  2562. eq.Enqueue(Item, agentID);
  2563. }
  2564. else
  2565. presence.ControllingClient.SendShutdownConnectionNotice();
  2566. }
  2567. presence.ControllingClient.Close(true);
  2568. return true;
  2569. }
  2570. // Agent not here
  2571. return false;
  2572. }
  2573. /// <summary>
  2574. /// Tell neighboring regions about this agent
  2575. /// When the regions respond with a true value,
  2576. /// tell the agents about the region.
  2577. ///
  2578. /// We have to tell the regions about the agents first otherwise it'll deny them access
  2579. ///
  2580. /// </summary>
  2581. /// <param name="presence"></param>
  2582. public void InformClientOfNeighbours(ScenePresence presence)
  2583. {
  2584. m_sceneGridService.EnableNeighbourChildAgents(presence, m_neighbours);
  2585. }
  2586. /// <summary>
  2587. /// Tell a neighboring region about this agent
  2588. /// </summary>
  2589. /// <param name="presence"></param>
  2590. /// <param name="region"></param>
  2591. public void InformClientOfNeighbor(ScenePresence presence, RegionInfo region)
  2592. {
  2593. m_sceneGridService.InformNeighborChildAgent(presence, region, m_neighbours);
  2594. }
  2595. /// <summary>
  2596. /// Requests information about this region from gridcomms
  2597. /// </summary>
  2598. /// <param name="regionHandle"></param>
  2599. /// <returns></returns>
  2600. public RegionInfo RequestNeighbouringRegionInfo(ulong regionHandle)
  2601. {
  2602. return m_sceneGridService.RequestNeighbouringRegionInfo(regionHandle);
  2603. }
  2604. /// <summary>
  2605. /// Requests textures for map from minimum region to maximum region in world cordinates
  2606. /// </summary>
  2607. /// <param name="remoteClient"></param>
  2608. /// <param name="minX"></param>
  2609. /// <param name="minY"></param>
  2610. /// <param name="maxX"></param>
  2611. /// <param name="maxY"></param>
  2612. public void RequestMapBlocks(IClientAPI remoteClient, int minX, int minY, int maxX, int maxY)
  2613. {
  2614. m_log.InfoFormat("[MAPBLOCK]: {0}-{1}, {2}-{3}", minX, minY, maxX, maxY);
  2615. m_sceneGridService.RequestMapBlocks(remoteClient, minX, minY, maxX, maxY);
  2616. }
  2617. /// <summary>
  2618. /// Tries to teleport agent to other region.
  2619. /// </summary>
  2620. /// <param name="remoteClient"></param>
  2621. /// <param name="regionName"></param>
  2622. /// <param name="position"></param>
  2623. /// <param name="lookAt"></param>
  2624. /// <param name="teleportFlags"></param>
  2625. public void RequestTeleportLocation(IClientAPI remoteClient, string regionName, Vector3 position,
  2626. Vector3 lookat, uint teleportFlags)
  2627. {
  2628. RegionInfo regionInfo = m_sceneGridService.RequestClosestRegion(regionName);
  2629. if (regionInfo == null)
  2630. {
  2631. // can't find the region: Tell viewer and abort
  2632. remoteClient.SendTeleportFailed("The region '" + regionName + "' could not be found.");
  2633. return;
  2634. }
  2635. RequestTeleportLocation(remoteClient, regionInfo.RegionHandle, position, lookat, teleportFlags);
  2636. }
  2637. /// <summary>
  2638. /// Tries to teleport agent to other region.
  2639. /// </summary>
  2640. /// <param name="remoteClient"></param>
  2641. /// <param name="regionHandle"></param>
  2642. /// <param name="position"></param>
  2643. /// <param name="lookAt"></param>
  2644. /// <param name="teleportFlags"></param>
  2645. public void RequestTeleportLocation(IClientAPI remoteClient, ulong regionHandle, Vector3 position,
  2646. Vector3 lookAt, uint teleportFlags)
  2647. {
  2648. ScenePresence sp = null;
  2649. lock (m_scenePresences)
  2650. {
  2651. if (m_scenePresences.ContainsKey(remoteClient.AgentId))
  2652. sp = m_scenePresences[remoteClient.AgentId];
  2653. }
  2654. if (sp != null)
  2655. {
  2656. m_sceneGridService.RequestTeleportToLocation(sp, regionHandle,
  2657. position, lookAt, teleportFlags);
  2658. }
  2659. }
  2660. /// <summary>
  2661. /// Tries to teleport agent to landmark.
  2662. /// </summary>
  2663. /// <param name="remoteClient"></param>
  2664. /// <param name="regionHandle"></param>
  2665. /// <param name="position"></param>
  2666. public void RequestTeleportLandmark(IClientAPI remoteClient, UUID regionID, Vector3 position)
  2667. {
  2668. RegionInfo info = CommsManager.GridService.RequestNeighbourInfo(regionID);
  2669. if (info == null)
  2670. {
  2671. // can't find the region: Tell viewer and abort
  2672. remoteClient.SendTeleportFailed("The teleport destination could not be found.");
  2673. return;
  2674. }
  2675. ScenePresence sp = null;
  2676. lock (m_scenePresences)
  2677. {
  2678. if (m_scenePresences.ContainsKey(remoteClient.AgentId))
  2679. sp = m_scenePresences[remoteClient.AgentId];
  2680. }
  2681. if (sp != null)
  2682. {
  2683. m_sceneGridService.RequestTeleportToLocation(sp, info.RegionHandle,
  2684. position, Vector3.Zero, (uint)(TPFlags.SetLastToTarget | TPFlags.ViaLandmark));
  2685. }
  2686. }
  2687. /// <summary>
  2688. /// Agent is crossing the border into a neighbouring region. Tell the neighbour about it!
  2689. /// </summary>
  2690. /// <param name="regionHandle"></param>
  2691. /// <param name="agentID"></param>
  2692. /// <param name="position"></param>
  2693. /// <param name="isFlying"></param>
  2694. /// <returns></returns>
  2695. public bool InformNeighbourOfCrossing(ulong regionHandle, UUID agentID, Vector3 position, bool isFlying)
  2696. {
  2697. return m_sceneGridService.CrossToNeighbouringRegion(regionHandle, agentID, position, isFlying);
  2698. }
  2699. public void SendOutChildAgentUpdates(AgentPosition cadu, ScenePresence presence)
  2700. {
  2701. m_sceneGridService.SendChildAgentDataUpdate(cadu, presence);
  2702. }
  2703. #endregion
  2704. #region Module Methods
  2705. /// <summary>
  2706. /// Add a module to this scene.
  2707. /// </summary>
  2708. /// <param name="name"></param>
  2709. /// <param name="module"></param>
  2710. public void AddModule(string name, IRegionModule module)
  2711. {
  2712. if (!Modules.ContainsKey(name))
  2713. {
  2714. Modules.Add(name, module);
  2715. }
  2716. }
  2717. public void RegisterModuleCommander(string name, ICommander commander)
  2718. {
  2719. lock (m_moduleCommanders)
  2720. {
  2721. m_moduleCommanders.Add(name, commander);
  2722. }
  2723. }
  2724. public ICommander GetCommander(string name)
  2725. {
  2726. lock (m_moduleCommanders)
  2727. {
  2728. return m_moduleCommanders[name];
  2729. }
  2730. }
  2731. public Dictionary<string, ICommander> GetCommanders()
  2732. {
  2733. return m_moduleCommanders;
  2734. }
  2735. /// <summary>
  2736. /// Register an interface to a region module. This allows module methods to be called directly as
  2737. /// well as via events. If there is already a module registered for this interface, it is not replaced
  2738. /// (is this the best behaviour?)
  2739. /// </summary>
  2740. /// <param name="mod"></param>
  2741. public void RegisterModuleInterface<M>(M mod)
  2742. {
  2743. if (!ModuleInterfaces.ContainsKey(typeof(M)))
  2744. {
  2745. List<Object> l = new List<Object>();
  2746. l.Add(mod);
  2747. ModuleInterfaces.Add(typeof(M), l);
  2748. if (mod is IEntityCreator)
  2749. {
  2750. IEntityCreator entityCreator = (IEntityCreator)mod;
  2751. foreach (PCode pcode in entityCreator.CreationCapabilities)
  2752. {
  2753. m_entityCreators[pcode] = entityCreator;
  2754. }
  2755. }
  2756. }
  2757. }
  2758. public void StackModuleInterface<M>(M mod)
  2759. {
  2760. List<Object> l;
  2761. if (ModuleInterfaces.ContainsKey(typeof(M)))
  2762. l = ModuleInterfaces[typeof(M)];
  2763. else
  2764. l = new List<Object>();
  2765. if (l.Contains(mod))
  2766. return;
  2767. l.Add(mod);
  2768. if (mod is IEntityCreator)
  2769. {
  2770. IEntityCreator entityCreator = (IEntityCreator)mod;
  2771. foreach (PCode pcode in entityCreator.CreationCapabilities)
  2772. {
  2773. m_entityCreators[pcode] = entityCreator;
  2774. }
  2775. }
  2776. ModuleInterfaces[typeof(M)] = l;
  2777. }
  2778. /// <summary>
  2779. /// For the given interface, retrieve the region module which implements it.
  2780. /// </summary>
  2781. /// <returns>null if there is no registered module implementing that interface</returns>
  2782. public override T RequestModuleInterface<T>()
  2783. {
  2784. if (ModuleInterfaces.ContainsKey(typeof(T)))
  2785. {
  2786. return (T)ModuleInterfaces[typeof(T)][0];
  2787. }
  2788. else
  2789. {
  2790. return default(T);
  2791. }
  2792. }
  2793. /// <summary>
  2794. /// For the given interface, retrieve an array of region modules that implement it.
  2795. /// </summary>
  2796. /// <returns>an empty array if there are no registered modules implementing that interface</returns>
  2797. public override T[] RequestModuleInterfaces<T>()
  2798. {
  2799. if (ModuleInterfaces.ContainsKey(typeof(T)))
  2800. {
  2801. List<T> ret = new List<T>();
  2802. foreach (Object o in ModuleInterfaces[typeof(T)])
  2803. ret.Add((T)o);
  2804. return ret.ToArray();
  2805. }
  2806. else
  2807. {
  2808. return new T[] { default(T) };
  2809. }
  2810. }
  2811. public void SetObjectCapacity(int objects)
  2812. {
  2813. // Region specific config overrides global
  2814. //
  2815. if (RegionInfo.ObjectCapacity != 0)
  2816. objects = RegionInfo.ObjectCapacity;
  2817. if (StatsReporter != null)
  2818. {
  2819. StatsReporter.SetObjectCapacity(objects);
  2820. }
  2821. objectCapacity = objects;
  2822. }
  2823. public List<FriendListItem> GetFriendList(UUID avatarID)
  2824. {
  2825. return CommsManager.GetUserFriendList(avatarID);
  2826. }
  2827. public Dictionary<UUID, FriendRegionInfo> GetFriendRegionInfos(List<UUID> uuids)
  2828. {
  2829. return CommsManager.GetFriendRegionInfos(uuids);
  2830. }
  2831. public List<UUID> InformFriendsInOtherRegion(UUID agentId, ulong destRegionHandle, List<UUID> friends, bool online)
  2832. {
  2833. return CommsManager.InformFriendsInOtherRegion(agentId, destRegionHandle, friends, online);
  2834. }
  2835. public bool TriggerTerminateFriend(ulong regionHandle, UUID agentID, UUID exFriendID)
  2836. {
  2837. return CommsManager.TriggerTerminateFriend(regionHandle, agentID, exFriendID);
  2838. }
  2839. #endregion
  2840. #region Other Methods
  2841. public virtual void StoreAddFriendship(UUID ownerID, UUID friendID, uint perms)
  2842. {
  2843. m_sceneGridService.AddNewUserFriend(ownerID, friendID, perms);
  2844. }
  2845. public virtual void StoreUpdateFriendship(UUID ownerID, UUID friendID, uint perms)
  2846. {
  2847. m_sceneGridService.UpdateUserFriendPerms(ownerID, friendID, perms);
  2848. }
  2849. public virtual void StoreRemoveFriendship(UUID ownerID, UUID ExfriendID)
  2850. {
  2851. m_sceneGridService.RemoveUserFriend(ownerID, ExfriendID);
  2852. }
  2853. public void AddPacketStats(int inPackets, int outPackets, int unAckedBytes)
  2854. {
  2855. StatsReporter.AddInPackets(inPackets);
  2856. StatsReporter.AddOutPackets(outPackets);
  2857. StatsReporter.AddunAckedBytes(unAckedBytes);
  2858. }
  2859. public void AddAgentTime(int ms)
  2860. {
  2861. StatsReporter.addFrameMS(ms);
  2862. StatsReporter.addAgentMS(ms);
  2863. }
  2864. public void AddAgentUpdates(int count)
  2865. {
  2866. StatsReporter.AddAgentUpdates(count);
  2867. }
  2868. public void AddPendingDownloads(int count)
  2869. {
  2870. StatsReporter.addPendingDownload(count);
  2871. }
  2872. #endregion
  2873. #region Alert Methods
  2874. /// <summary>
  2875. /// Handle a request for admin rights
  2876. /// </summary>
  2877. /// <param name="agentID"></param>
  2878. /// <param name="sessionID"></param>
  2879. /// <param name="token"></param>
  2880. /// <param name="controllingClient"></param>
  2881. public void handleRequestGodlikePowers(UUID agentID, UUID sessionID, UUID token, bool godLike,
  2882. IClientAPI controllingClient)
  2883. {
  2884. ScenePresence sp = null;
  2885. lock (m_scenePresences)
  2886. {
  2887. // User needs to be logged into this sim
  2888. m_scenePresences.TryGetValue(agentID, out sp);
  2889. }
  2890. if (sp != null)
  2891. {
  2892. if (godLike == false)
  2893. {
  2894. sp.GrantGodlikePowers(agentID, sessionID, token, godLike);
  2895. return;
  2896. }
  2897. // First check that this is the sim owner
  2898. if (Permissions.IsGod(agentID))
  2899. {
  2900. // Next we check for spoofing.....
  2901. UUID testSessionID = sp.ControllingClient.SessionId;
  2902. if (sessionID == testSessionID)
  2903. {
  2904. if (sessionID == controllingClient.SessionId)
  2905. {
  2906. //m_log.Info("godlike: " + godLike.ToString());
  2907. sp.GrantGodlikePowers(agentID, testSessionID, token, godLike);
  2908. }
  2909. }
  2910. }
  2911. else
  2912. {
  2913. m_dialogModule.SendAlertToUser(agentID, "Request for god powers denied");
  2914. }
  2915. }
  2916. }
  2917. /// <summary>
  2918. /// Kicks User specified from the simulator. This logs them off of the grid
  2919. /// If the client gets the UUID: 44e87126e7944ded05b37c42da3d5cdb it assumes
  2920. /// that you're kicking it even if the avatar's UUID isn't the UUID that the
  2921. /// agent is assigned
  2922. /// </summary>
  2923. /// <param name="godID">The person doing the kicking</param>
  2924. /// <param name="sessionID">The session of the person doing the kicking</param>
  2925. /// <param name="agentID">the person that is being kicked</param>
  2926. /// <param name="kickflags">This isn't used apparently</param>
  2927. /// <param name="reason">The message to send to the user after it's been turned into a field</param>
  2928. public void HandleGodlikeKickUser(UUID godID, UUID sessionID, UUID agentID, uint kickflags, byte[] reason)
  2929. {
  2930. // For some reason the client sends this seemingly hard coded UUID for kicking everyone. Dun-know.
  2931. UUID kickUserID = new UUID("44e87126e7944ded05b37c42da3d5cdb");
  2932. lock (m_scenePresences)
  2933. {
  2934. if (m_scenePresences.ContainsKey(agentID) || agentID == kickUserID)
  2935. {
  2936. if (Permissions.IsGod(godID))
  2937. {
  2938. if (agentID == kickUserID)
  2939. {
  2940. ClientManager.ForEachClient(delegate(IClientAPI controller)
  2941. {
  2942. if (controller.AgentId != godID)
  2943. controller.Kick(Utils.BytesToString(reason));
  2944. }
  2945. );
  2946. // This is a bit crude. It seems the client will be null before it actually stops the thread
  2947. // The thread will kill itself eventually :/
  2948. // Is there another way to make sure *all* clients get this 'inter region' message?
  2949. ClientManager.ForEachClient(delegate(IClientAPI controller)
  2950. {
  2951. ScenePresence p = GetScenePresence(controller.AgentId);
  2952. bool childagent = p != null && p.IsChildAgent;
  2953. if (controller.AgentId != godID && !childagent)
  2954. // Do we really want to kick the initiator of this madness?
  2955. {
  2956. controller.Close(true);
  2957. }
  2958. }
  2959. );
  2960. }
  2961. else
  2962. {
  2963. m_sceneGraph.removeUserCount(!m_scenePresences[agentID].IsChildAgent);
  2964. m_scenePresences[agentID].ControllingClient.Kick(Utils.BytesToString(reason));
  2965. m_scenePresences[agentID].ControllingClient.Close(true);
  2966. }
  2967. }
  2968. else
  2969. {
  2970. m_dialogModule.SendAlertToUser(godID, "Kick request denied");
  2971. }
  2972. }
  2973. }
  2974. }
  2975. public void HandleObjectPermissionsUpdate(IClientAPI controller, UUID agentID, UUID sessionID, byte field, uint localId, uint mask, byte set)
  2976. {
  2977. // Check for spoofing.. since this is permissions we're talking about here!
  2978. if ((controller.SessionId == sessionID) && (controller.AgentId == agentID))
  2979. {
  2980. // Tell the object to do permission update
  2981. if (localId != 0)
  2982. {
  2983. SceneObjectGroup chObjectGroup = GetGroupByPrim(localId);
  2984. if (chObjectGroup != null)
  2985. {
  2986. chObjectGroup.UpdatePermissions(agentID, field, localId, mask, set);
  2987. }
  2988. }
  2989. }
  2990. }
  2991. /// <summary>
  2992. /// Handle an alert command from the console.
  2993. /// FIXME: Command parsing code really shouldn't be in this core Scene class.
  2994. /// </summary>
  2995. /// <param name="commandParams"></param>
  2996. public void HandleAlertCommand(string[] commandParams)
  2997. {
  2998. if (commandParams[0] == "general")
  2999. {
  3000. string message = CombineParams(commandParams, 1);
  3001. m_dialogModule.SendGeneralAlert(message);
  3002. }
  3003. else
  3004. {
  3005. string message = CombineParams(commandParams, 2);
  3006. m_dialogModule.SendAlertToUser(commandParams[0], commandParams[1], message, false);
  3007. }
  3008. }
  3009. private string CombineParams(string[] commandParams, int pos)
  3010. {
  3011. string result = String.Empty;
  3012. for (int i = pos; i < commandParams.Length; i++)
  3013. {
  3014. result += commandParams[i] + " ";
  3015. }
  3016. return result;
  3017. }
  3018. #endregion
  3019. /// <summary>
  3020. /// Causes all clients to get a full object update on all of the objects in the scene.
  3021. /// </summary>
  3022. public void ForceClientUpdate()
  3023. {
  3024. List<EntityBase> EntityList = GetEntities();
  3025. foreach (EntityBase ent in EntityList)
  3026. {
  3027. if (ent is SceneObjectGroup)
  3028. {
  3029. ((SceneObjectGroup)ent).ScheduleGroupForFullUpdate();
  3030. }
  3031. }
  3032. }
  3033. /// <summary>
  3034. /// This is currently only used for scale (to scale to MegaPrim size)
  3035. /// There is a console command that calls this in OpenSimMain
  3036. /// </summary>
  3037. /// <param name="cmdparams"></param>
  3038. public void HandleEditCommand(string[] cmdparams)
  3039. {
  3040. Console.WriteLine("Searching for Primitive: '" + cmdparams[0] + "'");
  3041. List<EntityBase> EntityList = GetEntities();
  3042. foreach (EntityBase ent in EntityList)
  3043. {
  3044. if (ent is SceneObjectGroup)
  3045. {
  3046. SceneObjectPart part = ((SceneObjectGroup)ent).GetChildPart(((SceneObjectGroup)ent).UUID);
  3047. if (part != null)
  3048. {
  3049. if (part.Name == cmdparams[0])
  3050. {
  3051. part.Resize(
  3052. new Vector3(Convert.ToSingle(cmdparams[1]), Convert.ToSingle(cmdparams[2]),
  3053. Convert.ToSingle(cmdparams[3])));
  3054. Console.WriteLine("Edited scale of Primitive: " + part.Name);
  3055. }
  3056. }
  3057. }
  3058. }
  3059. }
  3060. /// <summary>
  3061. /// Shows various details about the sim based on the parameters supplied by the console command in openSimMain.
  3062. /// </summary>
  3063. /// <param name="showParams">What to show</param>
  3064. public void Show(string[] showParams)
  3065. {
  3066. switch (showParams[0])
  3067. {
  3068. case "users":
  3069. m_log.Error("Current Region: " + RegionInfo.RegionName);
  3070. m_log.ErrorFormat("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16}{5,-16}{6,-16}", "Firstname", "Lastname",
  3071. "Agent ID", "Session ID", "Circuit", "IP", "World");
  3072. foreach (ScenePresence scenePresence in GetAvatars())
  3073. {
  3074. m_log.ErrorFormat("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16},{5,-16}{6,-16}",
  3075. scenePresence.Firstname,
  3076. scenePresence.Lastname,
  3077. scenePresence.UUID,
  3078. scenePresence.ControllingClient.AgentId,
  3079. "Unknown",
  3080. "Unknown",
  3081. RegionInfo.RegionName);
  3082. }
  3083. break;
  3084. case "modules":
  3085. m_log.Error("The currently loaded modules in " + RegionInfo.RegionName + " are:");
  3086. foreach (IRegionModule module in Modules.Values)
  3087. {
  3088. if (!module.IsSharedModule)
  3089. {
  3090. m_log.Error("Region Module: " + module.Name);
  3091. }
  3092. }
  3093. break;
  3094. }
  3095. }
  3096. #region Script Handling Methods
  3097. /// <summary>
  3098. /// Console command handler to send script command to script engine.
  3099. /// </summary>
  3100. /// <param name="args"></param>
  3101. public void SendCommandToPlugins(string[] args)
  3102. {
  3103. m_eventManager.TriggerOnPluginConsole(args);
  3104. }
  3105. public double GetLandHeight(int x, int y)
  3106. {
  3107. return Heightmap[x, y];
  3108. }
  3109. public UUID GetLandOwner(float x, float y)
  3110. {
  3111. ILandObject land = LandChannel.GetLandObject(x, y);
  3112. if (land == null)
  3113. {
  3114. return UUID.Zero;
  3115. }
  3116. else
  3117. {
  3118. return land.landData.OwnerID;
  3119. }
  3120. }
  3121. public LandData GetLandData(float x, float y)
  3122. {
  3123. return LandChannel.GetLandObject(x, y).landData;
  3124. }
  3125. public LandData GetLandData(uint x, uint y)
  3126. {
  3127. m_log.DebugFormat("[SCENE] returning land for {0},{1}", x, y);
  3128. return LandChannel.GetLandObject((int)x, (int)y).landData;
  3129. }
  3130. public void SetLandMusicURL(float x, float y, string url)
  3131. {
  3132. ILandObject land = LandChannel.GetLandObject(x, y);
  3133. if (land == null)
  3134. {
  3135. return;
  3136. }
  3137. else
  3138. {
  3139. land.landData.MusicURL = url;
  3140. land.sendLandUpdateToAvatarsOverMe();
  3141. return;
  3142. }
  3143. }
  3144. public void SetLandMediaURL(float x, float y, string url)
  3145. {
  3146. ILandObject land = LandChannel.GetLandObject(x, y);
  3147. if (land == null)
  3148. {
  3149. return;
  3150. }
  3151. else
  3152. {
  3153. land.landData.MediaURL = url;
  3154. land.sendLandUpdateToAvatarsOverMe();
  3155. return;
  3156. }
  3157. }
  3158. public RegionInfo RequestClosestRegion(string name)
  3159. {
  3160. return m_sceneGridService.RequestClosestRegion(name);
  3161. }
  3162. #endregion
  3163. #region Script Engine
  3164. private List<ScriptEngineInterface> ScriptEngines = new List<ScriptEngineInterface>();
  3165. public bool DumpAssetsToFile;
  3166. /// <summary>
  3167. ///
  3168. /// </summary>
  3169. /// <param name="scriptEngine"></param>
  3170. public void AddScriptEngine(ScriptEngineInterface scriptEngine)
  3171. {
  3172. ScriptEngines.Add(scriptEngine);
  3173. scriptEngine.InitializeEngine(this);
  3174. }
  3175. public void TriggerObjectChanged(uint localID, uint change)
  3176. {
  3177. m_eventManager.TriggerOnScriptChangedEvent(localID, change);
  3178. }
  3179. public void TriggerAtTargetEvent(uint localID, uint handle, Vector3 targetpos, Vector3 currentpos)
  3180. {
  3181. m_eventManager.TriggerAtTargetEvent(localID, handle, targetpos, currentpos);
  3182. }
  3183. public void TriggerNotAtTargetEvent(uint localID)
  3184. {
  3185. m_eventManager.TriggerNotAtTargetEvent(localID);
  3186. }
  3187. private bool ScriptDanger(SceneObjectPart part,Vector3 pos)
  3188. {
  3189. ILandObject parcel = LandChannel.GetLandObject(pos.X, pos.Y);
  3190. if (part != null)
  3191. {
  3192. if (parcel != null)
  3193. {
  3194. if ((parcel.landData.Flags & (uint)Parcel.ParcelFlags.AllowOtherScripts) != 0)
  3195. {
  3196. return true;
  3197. }
  3198. else if ((parcel.landData.Flags & (uint)Parcel.ParcelFlags.AllowGroupScripts) != 0)
  3199. {
  3200. if (part.OwnerID == parcel.landData.OwnerID || (parcel.landData.IsGroupOwned && part.GroupID == parcel.landData.GroupID) || Permissions.IsGod(part.OwnerID))
  3201. {
  3202. return true;
  3203. }
  3204. else
  3205. {
  3206. return false;
  3207. }
  3208. }
  3209. else
  3210. {
  3211. if (part.OwnerID == parcel.landData.OwnerID)
  3212. {
  3213. return true;
  3214. }
  3215. else
  3216. {
  3217. return false;
  3218. }
  3219. }
  3220. }
  3221. else
  3222. {
  3223. if (pos.X > 0f && pos.X < Constants.RegionSize && pos.Y > 0f && pos.Y < Constants.RegionSize)
  3224. {
  3225. // The only time parcel != null when an object is inside a region is when
  3226. // there is nothing behind the landchannel. IE, no land plugin loaded.
  3227. return true;
  3228. }
  3229. else
  3230. {
  3231. // The object is outside of this region. Stop piping events to it.
  3232. return false;
  3233. }
  3234. }
  3235. }
  3236. else
  3237. {
  3238. return false;
  3239. }
  3240. }
  3241. public bool ScriptDanger(uint localID, Vector3 pos)
  3242. {
  3243. SceneObjectPart part = GetSceneObjectPart(localID);
  3244. if (part != null)
  3245. {
  3246. return ScriptDanger(part, pos);
  3247. }
  3248. else
  3249. {
  3250. return false;
  3251. }
  3252. }
  3253. public bool PipeEventsForScript(uint localID)
  3254. {
  3255. SceneObjectPart part = GetSceneObjectPart(localID);
  3256. if (part != null)
  3257. {
  3258. // Changed so that child prims of attachments return ScriptDanger for their parent, so that
  3259. // their scripts will actually run.
  3260. // -- Leaf, Tue Aug 12 14:17:05 EDT 2008
  3261. SceneObjectPart parent = part.ParentGroup.RootPart;
  3262. if (parent != null && parent.IsAttachment)
  3263. return ScriptDanger(parent, parent.GetWorldPosition());
  3264. else
  3265. return ScriptDanger(part, part.GetWorldPosition());
  3266. }
  3267. else
  3268. {
  3269. return false;
  3270. }
  3271. }
  3272. #endregion
  3273. #region SceneGraph wrapper methods
  3274. /// <summary>
  3275. ///
  3276. /// </summary>
  3277. /// <param name="localID"></param>
  3278. /// <returns></returns>
  3279. public UUID ConvertLocalIDToFullID(uint localID)
  3280. {
  3281. return m_sceneGraph.ConvertLocalIDToFullID(localID);
  3282. }
  3283. public void SwapRootAgentCount(bool rootChildChildRootTF)
  3284. {
  3285. m_sceneGraph.SwapRootChildAgent(rootChildChildRootTF);
  3286. }
  3287. public void AddPhysicalPrim(int num)
  3288. {
  3289. m_sceneGraph.AddPhysicalPrim(num);
  3290. }
  3291. public void RemovePhysicalPrim(int num)
  3292. {
  3293. m_sceneGraph.RemovePhysicalPrim(num);
  3294. }
  3295. //The idea is to have a group of method that return a list of avatars meeting some requirement
  3296. // ie it could be all m_scenePresences within a certain range of the calling prim/avatar.
  3297. /// <summary>
  3298. /// Return a list of all avatars in this region.
  3299. /// This list is a new object, so it can be iterated over without locking.
  3300. /// </summary>
  3301. /// <returns></returns>
  3302. public List<ScenePresence> GetAvatars()
  3303. {
  3304. return m_sceneGraph.GetAvatars();
  3305. }
  3306. /// <summary>
  3307. /// Return a list of all ScenePresences in this region. This returns child agents as well as root agents.
  3308. /// This list is a new object, so it can be iterated over without locking.
  3309. /// </summary>
  3310. /// <returns></returns>
  3311. public List<ScenePresence> GetScenePresences()
  3312. {
  3313. return m_sceneGraph.GetScenePresences();
  3314. }
  3315. /// <summary>
  3316. /// Request a filtered list of ScenePresences in this region.
  3317. /// This list is a new object, so it can be iterated over without locking.
  3318. /// </summary>
  3319. /// <param name="filter"></param>
  3320. /// <returns></returns>
  3321. public List<ScenePresence> GetScenePresences(FilterAvatarList filter)
  3322. {
  3323. return m_sceneGraph.GetScenePresences(filter);
  3324. }
  3325. /// <summary>
  3326. /// Request a scene presence by UUID
  3327. /// </summary>
  3328. /// <param name="avatarID"></param>
  3329. /// <returns></returns>
  3330. public ScenePresence GetScenePresence(UUID avatarID)
  3331. {
  3332. return m_sceneGraph.GetScenePresence(avatarID);
  3333. }
  3334. public override bool PresenceChildStatus(UUID avatarID)
  3335. {
  3336. ScenePresence cp = GetScenePresence(avatarID);
  3337. // FIXME: This is really crap - some logout code is relying on a NullReferenceException to halt its processing
  3338. // This needs to be fixed properly by cleaning up the logout code.
  3339. //if (cp != null)
  3340. // return cp.IsChildAgent;
  3341. //return false;
  3342. return cp.IsChildAgent;
  3343. }
  3344. /// <summary>
  3345. ///
  3346. /// </summary>
  3347. /// <param name="action"></param>
  3348. public void ForEachScenePresence(Action<ScenePresence> action)
  3349. {
  3350. // We don't want to try to send messages if there are no avatars.
  3351. if (m_scenePresences != null)
  3352. {
  3353. try
  3354. {
  3355. List<ScenePresence> presenceList = GetScenePresences();
  3356. foreach (ScenePresence presence in presenceList)
  3357. {
  3358. action(presence);
  3359. }
  3360. }
  3361. catch (Exception e)
  3362. {
  3363. m_log.Info("[BUG]: " + e.ToString());
  3364. }
  3365. }
  3366. }
  3367. /// <summary>
  3368. ///
  3369. /// </summary>
  3370. /// <param name="action"></param>
  3371. // public void ForEachObject(Action<SceneObjectGroup> action)
  3372. // {
  3373. // List<SceneObjectGroup> presenceList;
  3374. //
  3375. // lock (m_sceneObjects)
  3376. // {
  3377. // presenceList = new List<SceneObjectGroup>(m_sceneObjects.Values);
  3378. // }
  3379. //
  3380. // foreach (SceneObjectGroup presence in presenceList)
  3381. // {
  3382. // action(presence);
  3383. // }
  3384. // }
  3385. /// <summary>
  3386. /// Get a named prim contained in this scene (will return the first
  3387. /// found, if there are more than one prim with the same name)
  3388. /// </summary>
  3389. /// <param name="name"></param>
  3390. /// <returns></returns>
  3391. public SceneObjectPart GetSceneObjectPart(string name)
  3392. {
  3393. return m_sceneGraph.GetSceneObjectPart(name);
  3394. }
  3395. /// <summary>
  3396. /// Get a prim via its local id
  3397. /// </summary>
  3398. /// <param name="localID"></param>
  3399. /// <returns></returns>
  3400. public SceneObjectPart GetSceneObjectPart(uint localID)
  3401. {
  3402. return m_sceneGraph.GetSceneObjectPart(localID);
  3403. }
  3404. /// <summary>
  3405. /// Get a prim via its UUID
  3406. /// </summary>
  3407. /// <param name="fullID"></param>
  3408. /// <returns></returns>
  3409. public SceneObjectPart GetSceneObjectPart(UUID fullID)
  3410. {
  3411. return m_sceneGraph.GetSceneObjectPart(fullID);
  3412. }
  3413. internal bool TryGetAvatar(UUID avatarId, out ScenePresence avatar)
  3414. {
  3415. return m_sceneGraph.TryGetAvatar(avatarId, out avatar);
  3416. }
  3417. internal bool TryGetAvatarByName(string avatarName, out ScenePresence avatar)
  3418. {
  3419. return m_sceneGraph.TryGetAvatarByName(avatarName, out avatar);
  3420. }
  3421. public void ForEachClient(Action<IClientAPI> action)
  3422. {
  3423. m_sceneGraph.ForEachClient(action);
  3424. }
  3425. /// <summary>
  3426. /// Returns a list of the entities in the scene. This is a new list so operations perform on the list itself
  3427. /// will not affect the original list of objects in the scene.
  3428. /// </summary>
  3429. /// <returns></returns>
  3430. public List<EntityBase> GetEntities()
  3431. {
  3432. return m_sceneGraph.GetEntities();
  3433. }
  3434. #endregion
  3435. #region Avatar Appearance Default
  3436. public static void GetDefaultAvatarAppearance(out AvatarWearable[] wearables, out byte[] visualParams)
  3437. {
  3438. visualParams = GetDefaultVisualParams();
  3439. wearables = AvatarWearable.DefaultWearables;
  3440. }
  3441. private static byte[] GetDefaultVisualParams()
  3442. {
  3443. byte[] visualParams;
  3444. visualParams = new byte[218];
  3445. for (int i = 0; i < 218; i++)
  3446. {
  3447. visualParams[i] = 100;
  3448. }
  3449. return visualParams;
  3450. }
  3451. #endregion
  3452. public void ParcelMediaSetTime(float time)
  3453. {
  3454. //should be doing this by parcel, but as its only for testing
  3455. // The use of Thread.Sleep here causes the following compiler error under mono 1.2.4
  3456. // OpenSim/Region/Environment/Scenes/Scene.cs(3675,17): error CS0103: The name `Thread' does not exist
  3457. // in the context of `<>c__CompilerGenerated17'
  3458. // MW said it was okay to comment the body of this method out for now since the code is experimental
  3459. // and will be replaced anyway
  3460. // ForEachClient(delegate(IClientAPI client)
  3461. // {
  3462. // client.SendParcelMediaCommand((uint)(2), ParcelMediaCommandEnum.Pause, 0);
  3463. // Thread.Sleep(10);
  3464. // client.SendParcelMediaCommand((uint)(64), ParcelMediaCommandEnum.Time, time);
  3465. // Thread.Sleep(200);
  3466. // client.SendParcelMediaCommand((uint)(4), ParcelMediaCommandEnum.Play, 0);
  3467. // });
  3468. }
  3469. public void RegionHandleRequest(IClientAPI client, UUID regionID)
  3470. {
  3471. RegionInfo info;
  3472. if (regionID == RegionInfo.RegionID)
  3473. info = RegionInfo;
  3474. else
  3475. info = CommsManager.GridService.RequestNeighbourInfo(regionID);
  3476. if (info != null)
  3477. client.SendRegionHandle(regionID, info.RegionHandle);
  3478. }
  3479. public void TerrainUnAcked(IClientAPI client, int patchX, int patchY)
  3480. {
  3481. //Console.WriteLine("Terrain packet unacked, resending patch: " + patchX + " , " + patchY);
  3482. client.SendLayerData(patchX, patchY, Heightmap.GetFloatsSerialised());
  3483. }
  3484. public void SetRootAgentScene(UUID agentID)
  3485. {
  3486. IInventoryTransferModule inv = RequestModuleInterface<IInventoryTransferModule>();
  3487. if (inv == null)
  3488. return;
  3489. inv.SetRootAgentScene(agentID, this);
  3490. EventManager.TriggerSetRootAgentScene(agentID, this);
  3491. }
  3492. public bool NeedSceneCacheClear(UUID agentID)
  3493. {
  3494. IInventoryTransferModule inv = RequestModuleInterface<IInventoryTransferModule>();
  3495. if (inv == null)
  3496. return true;
  3497. return inv.NeedSceneCacheClear(agentID, this);
  3498. }
  3499. public void ObjectSaleInfo(IClientAPI client, UUID agentID, UUID sessionID, uint localID, byte saleType, int salePrice)
  3500. {
  3501. SceneObjectPart part = GetSceneObjectPart(localID);
  3502. if (part == null || part.ParentGroup == null)
  3503. return;
  3504. if (part.ParentGroup.IsDeleted)
  3505. return;
  3506. part = part.ParentGroup.RootPart;
  3507. part.ObjectSaleType = saleType;
  3508. part.SalePrice = salePrice;
  3509. part.ParentGroup.HasGroupChanged = true;
  3510. part.GetProperties(client);
  3511. }
  3512. public bool PerformObjectBuy(IClientAPI remoteClient, UUID categoryID,
  3513. uint localID, byte saleType)
  3514. {
  3515. SceneObjectPart part = GetSceneObjectPart(localID);
  3516. if (part == null)
  3517. return false;
  3518. if (part.ParentGroup == null)
  3519. return false;
  3520. SceneObjectGroup group = part.ParentGroup;
  3521. switch (saleType)
  3522. {
  3523. case 1: // Sell as original (in-place sale)
  3524. uint effectivePerms=group.GetEffectivePermissions();
  3525. if ((effectivePerms & (uint)PermissionMask.Transfer) == 0)
  3526. {
  3527. m_dialogModule.SendAlertToUser(remoteClient, "This item doesn't appear to be for sale");
  3528. return false;
  3529. }
  3530. group.SetOwnerId(remoteClient.AgentId);
  3531. group.SetRootPartOwner(part, remoteClient.AgentId,
  3532. remoteClient.ActiveGroupId);
  3533. List<SceneObjectPart> partList =
  3534. new List<SceneObjectPart>(group.Children.Values);
  3535. if (Permissions.PropagatePermissions())
  3536. {
  3537. foreach (SceneObjectPart child in partList)
  3538. {
  3539. child.Inventory.ChangeInventoryOwner(remoteClient.AgentId);
  3540. child.ApplyNextOwnerPermissions();
  3541. }
  3542. }
  3543. part.ObjectSaleType = 0;
  3544. part.SalePrice = 10;
  3545. group.HasGroupChanged = true;
  3546. part.GetProperties(remoteClient);
  3547. part.ScheduleFullUpdate();
  3548. break;
  3549. case 2: // Sell a copy
  3550. string sceneObjectXml = group.ToXmlString();
  3551. CachedUserInfo userInfo =
  3552. CommsManager.UserProfileCacheService.GetUserDetails(remoteClient.AgentId);
  3553. if (userInfo != null)
  3554. {
  3555. uint perms=group.GetEffectivePermissions();
  3556. if ((perms & (uint)PermissionMask.Transfer) == 0)
  3557. {
  3558. m_dialogModule.SendAlertToUser(remoteClient, "This item doesn't appear to be for sale");
  3559. return false;
  3560. }
  3561. AssetBase asset = CreateAsset(
  3562. group.GetPartName(localID),
  3563. group.GetPartDescription(localID),
  3564. (sbyte)AssetType.Object,
  3565. Utils.StringToBytes(sceneObjectXml));
  3566. AssetCache.AddAsset(asset);
  3567. InventoryItemBase item = new InventoryItemBase();
  3568. item.Creator = part.CreatorID;
  3569. item.ID = UUID.Random();
  3570. item.Owner = remoteClient.AgentId;
  3571. item.AssetID = asset.FullID;
  3572. item.Description = asset.Description;
  3573. item.Name = asset.Name;
  3574. item.AssetType = asset.Type;
  3575. item.InvType = (int)InventoryType.Object;
  3576. item.Folder = categoryID;
  3577. uint nextPerms=(perms & 7) << 13;
  3578. if ((nextPerms & (uint)PermissionMask.Copy) == 0)
  3579. perms &= ~(uint)PermissionMask.Copy;
  3580. if ((nextPerms & (uint)PermissionMask.Transfer) == 0)
  3581. perms &= ~(uint)PermissionMask.Transfer;
  3582. if ((nextPerms & (uint)PermissionMask.Modify) == 0)
  3583. perms &= ~(uint)PermissionMask.Modify;
  3584. item.BasePermissions = perms & part.NextOwnerMask;
  3585. item.CurrentPermissions = perms & part.NextOwnerMask;
  3586. item.NextPermissions = part.NextOwnerMask;
  3587. item.EveryOnePermissions = part.EveryoneMask &
  3588. part.NextOwnerMask;
  3589. item.GroupPermissions = part.GroupMask &
  3590. part.NextOwnerMask;
  3591. item.CurrentPermissions |= 8; // Slam!
  3592. item.CreationDate = Util.UnixTimeSinceEpoch();
  3593. userInfo.AddItem(item);
  3594. remoteClient.SendInventoryItemCreateUpdate(item);
  3595. }
  3596. else
  3597. {
  3598. m_dialogModule.SendAlertToUser(remoteClient, "Cannot buy now. Your inventory is unavailable");
  3599. return false;
  3600. }
  3601. break;
  3602. case 3: // Sell contents
  3603. List<UUID> invList = part.Inventory.GetInventoryList();
  3604. bool okToSell = true;
  3605. foreach (UUID invID in invList)
  3606. {
  3607. TaskInventoryItem item = part.Inventory.GetInventoryItem(invID);
  3608. if ((item.CurrentPermissions &
  3609. (uint)PermissionMask.Transfer) == 0)
  3610. {
  3611. okToSell = false;
  3612. break;
  3613. }
  3614. }
  3615. if (!okToSell)
  3616. {
  3617. m_dialogModule.SendAlertToUser(
  3618. remoteClient, "This item's inventory doesn't appear to be for sale");
  3619. return false;
  3620. }
  3621. if (invList.Count > 0)
  3622. MoveTaskInventoryItems(remoteClient.AgentId, part.Name,
  3623. part, invList);
  3624. break;
  3625. }
  3626. return true;
  3627. }
  3628. public void CleanTempObjects()
  3629. {
  3630. List<EntityBase> objs = GetEntities();
  3631. foreach (EntityBase obj in objs)
  3632. {
  3633. if (obj is SceneObjectGroup)
  3634. {
  3635. SceneObjectGroup grp = (SceneObjectGroup)obj;
  3636. if (!grp.IsDeleted)
  3637. {
  3638. if ((grp.RootPart.Flags & PrimFlags.TemporaryOnRez) != 0)
  3639. {
  3640. if (grp.RootPart.Expires <= DateTime.Now)
  3641. DeleteSceneObject(grp, false);
  3642. }
  3643. }
  3644. }
  3645. }
  3646. }
  3647. public void DeleteFromStorage(UUID uuid)
  3648. {
  3649. m_storageManager.DataStore.RemoveObject(uuid, m_regInfo.RegionID);
  3650. }
  3651. public int GetHealth()
  3652. {
  3653. int health=1; // Start at 1, means we're up
  3654. // A login in the last 4 mins? We can't be doing too badly
  3655. //
  3656. if ((System.Environment.TickCount - m_LastLogin) < 240000)
  3657. health++;
  3658. return 0;
  3659. }
  3660. // This callback allows the PhysicsScene to call back to its caller (the SceneGraph) and
  3661. // update non-physical objects like the joint proxy objects that represent the position
  3662. // of the joints in the scene.
  3663. // This routine is normally called from within a lock (OdeLock) from within the OdePhysicsScene
  3664. // WARNING: be careful of deadlocks here if you manipulate the scene. Remember you are being called
  3665. // from within the OdePhysicsScene.
  3666. protected internal void jointMoved(PhysicsJoint joint)
  3667. {
  3668. // m_parentScene.PhysicsScene.DumpJointInfo(); // non-thread-locked version; we should already be in a lock (OdeLock) when this callback is invoked
  3669. // FIXME: this causes a sequential lookup of all objects in the scene; use a dictionary
  3670. SceneObjectPart jointProxyObject = GetSceneObjectPart(joint.ObjectNameInScene);
  3671. if (jointProxyObject == null)
  3672. {
  3673. jointErrorMessage(joint, "WARNING, joint proxy not found, name " + joint.ObjectNameInScene);
  3674. return;
  3675. }
  3676. // now update the joint proxy object in the scene to have the position of the joint as returned by the physics engine
  3677. SceneObjectPart trackedBody = GetSceneObjectPart(joint.TrackedBodyName); // FIXME: causes a sequential lookup
  3678. 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.
  3679. jointProxyObject.Velocity = trackedBody.Velocity;
  3680. jointProxyObject.RotationalVelocity = trackedBody.RotationalVelocity;
  3681. switch (joint.Type)
  3682. {
  3683. case PhysicsJointType.Ball:
  3684. {
  3685. PhysicsVector jointAnchor = PhysicsScene.GetJointAnchor(joint);
  3686. Vector3 proxyPos = new Vector3(jointAnchor.X, jointAnchor.Y, jointAnchor.Z);
  3687. jointProxyObject.ParentGroup.UpdateGroupPosition(proxyPos); // schedules the entire group for a terse update
  3688. }
  3689. break;
  3690. case PhysicsJointType.Hinge:
  3691. {
  3692. PhysicsVector jointAnchor = PhysicsScene.GetJointAnchor(joint);
  3693. // Normally, we would just ask the physics scene to return the axis for the joint.
  3694. // Unfortunately, ODE sometimes returns <0,0,0> for the joint axis, which should
  3695. // never occur. Therefore we cannot rely on ODE to always return a correct joint axis.
  3696. // Therefore the following call does not always work:
  3697. //PhysicsVector phyJointAxis = _PhyScene.GetJointAxis(joint);
  3698. // instead we compute the joint orientation by saving the original joint orientation
  3699. // relative to one of the jointed bodies, and applying this transformation
  3700. // to the current position of the jointed bodies (the tracked body) to compute the
  3701. // current joint orientation.
  3702. if (joint.TrackedBodyName == null)
  3703. {
  3704. jointErrorMessage(joint, "joint.TrackedBodyName is null, joint " + joint.ObjectNameInScene);
  3705. }
  3706. Vector3 proxyPos = new Vector3(jointAnchor.X, jointAnchor.Y, jointAnchor.Z);
  3707. Quaternion q = trackedBody.RotationOffset * joint.LocalRotation;
  3708. jointProxyObject.ParentGroup.UpdateGroupPosition(proxyPos); // schedules the entire group for a terse update
  3709. jointProxyObject.ParentGroup.UpdateGroupRotation(q); // schedules the entire group for a terse update
  3710. }
  3711. break;
  3712. }
  3713. }
  3714. // This callback allows the PhysicsScene to call back to its caller (the SceneGraph) and
  3715. // update non-physical objects like the joint proxy objects that represent the position
  3716. // of the joints in the scene.
  3717. // This routine is normally called from within a lock (OdeLock) from within the OdePhysicsScene
  3718. // WARNING: be careful of deadlocks here if you manipulate the scene. Remember you are being called
  3719. // from within the OdePhysicsScene.
  3720. protected internal void jointDeactivated(PhysicsJoint joint)
  3721. {
  3722. //m_log.Debug("[NINJA] SceneGraph.jointDeactivated, joint:" + joint.ObjectNameInScene);
  3723. // FIXME: this causes a sequential lookup of all objects in the scene; use a dictionary
  3724. SceneObjectPart jointProxyObject = GetSceneObjectPart(joint.ObjectNameInScene);
  3725. if (jointProxyObject == null)
  3726. {
  3727. jointErrorMessage(joint, "WARNING, trying to deactivate (stop interpolation of) joint proxy, but not found, name " + joint.ObjectNameInScene);
  3728. return;
  3729. }
  3730. // turn the proxy non-physical, which also stops its client-side interpolation
  3731. bool wasUsingPhysics = ((jointProxyObject.ObjectFlags & (uint)PrimFlags.Physics) != 0);
  3732. if (wasUsingPhysics)
  3733. {
  3734. 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
  3735. }
  3736. }
  3737. // This callback allows the PhysicsScene to call back to its caller (the SceneGraph) and
  3738. // alert the user of errors by using the debug channel in the same way that scripts alert
  3739. // the user of compile errors.
  3740. // This routine is normally called from within a lock (OdeLock) from within the OdePhysicsScene
  3741. // WARNING: be careful of deadlocks here if you manipulate the scene. Remember you are being called
  3742. // from within the OdePhysicsScene.
  3743. public void jointErrorMessage(PhysicsJoint joint, string message)
  3744. {
  3745. // FIXME: this causes a sequential lookup of all objects in the scene; use a dictionary
  3746. if (joint != null)
  3747. {
  3748. if (joint.ErrorMessageCount > PhysicsJoint.maxErrorMessages)
  3749. return;
  3750. SceneObjectPart jointProxyObject = GetSceneObjectPart(joint.ObjectNameInScene);
  3751. if (jointProxyObject != null)
  3752. {
  3753. SimChat(Utils.StringToBytes("[NINJA] " + message),
  3754. ChatTypeEnum.DebugChannel,
  3755. 2147483647,
  3756. jointProxyObject.AbsolutePosition,
  3757. jointProxyObject.Name,
  3758. jointProxyObject.UUID,
  3759. false);
  3760. joint.ErrorMessageCount++;
  3761. if (joint.ErrorMessageCount > PhysicsJoint.maxErrorMessages)
  3762. {
  3763. SimChat(Utils.StringToBytes("[NINJA] Too many messages for this joint, suppressing further messages."),
  3764. ChatTypeEnum.DebugChannel,
  3765. 2147483647,
  3766. jointProxyObject.AbsolutePosition,
  3767. jointProxyObject.Name,
  3768. jointProxyObject.UUID,
  3769. false);
  3770. }
  3771. }
  3772. else
  3773. {
  3774. // couldn't find the joint proxy object; the error message is silently suppressed
  3775. }
  3776. }
  3777. }
  3778. }
  3779. }