1
0

Scene.cs 100 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the 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. */
  28. using System;
  29. using System.Collections.Generic;
  30. using System.Drawing;
  31. using System.Drawing.Imaging;
  32. using System.Threading;
  33. using System.Timers;
  34. using Axiom.Math;
  35. using libsecondlife;
  36. using libsecondlife.Packets;
  37. using OpenJPEGNet;
  38. using OpenSim.Framework;
  39. using OpenSim.Framework.Communications;
  40. using OpenSim.Framework.Communications.Cache;
  41. using OpenSim.Framework.Console;
  42. using OpenSim.Framework.Servers;
  43. using OpenSim.Region.Environment.Interfaces;
  44. using OpenSim.Region.Environment.LandManagement;
  45. using OpenSim.Region.Environment.Modules;
  46. using OpenSim.Region.Environment.Scenes.Scripting;
  47. using OpenSim.Region.Physics.Manager;
  48. using OpenSim.Region.Terrain;
  49. using Caps = OpenSim.Region.Capabilities.Caps;
  50. using Image = System.Drawing.Image;
  51. using Timer = System.Timers.Timer;
  52. namespace OpenSim.Region.Environment.Scenes
  53. {
  54. public delegate bool FilterAvatarList(ScenePresence avatar);
  55. public partial class Scene : SceneBase
  56. {
  57. #region Fields
  58. protected Timer m_heartbeatTimer = new Timer();
  59. protected Timer m_restartWaitTimer = new Timer();
  60. protected SimStatsReporter m_statsReporter;
  61. protected List<RegionInfo> m_regionRestartNotifyList = new List<RegionInfo>();
  62. protected List<RegionInfo> m_neighbours = new List<RegionInfo>();
  63. public InnerScene m_innerScene;
  64. private Random Rand = new Random();
  65. private uint _primCount = 720000;
  66. private readonly Mutex _primAllocateMutex = new Mutex(false);
  67. private int m_timePhase = 24;
  68. private int m_timeUpdateCount;
  69. private readonly Mutex updateLock;
  70. public bool m_physicalPrim;
  71. public bool m_seeIntoRegionFromNeighbor;
  72. private int m_RestartTimerCounter;
  73. private readonly Timer m_restartTimer = new Timer(15000); // Wait before firing
  74. private int m_incrementsof15seconds = 0;
  75. public string m_simulatorVersion = "OpenSimulator 0.5";
  76. protected ModuleLoader m_moduleLoader;
  77. protected StorageManager m_storageManager;
  78. protected AgentCircuitManager m_authenticateHandler;
  79. public CommunicationsManager CommsManager;
  80. // protected XferManager xferManager;
  81. protected SceneCommunicationService m_sceneGridService;
  82. protected SceneXmlLoader m_sceneXmlLoader;
  83. protected Dictionary<LLUUID, Caps> m_capsHandlers = new Dictionary<LLUUID, Caps>();
  84. protected BaseHttpServer m_httpListener;
  85. protected Dictionary<string, IRegionModule> Modules = new Dictionary<string, IRegionModule>();
  86. public Dictionary<Type, object> ModuleInterfaces = new Dictionary<Type, object>();
  87. protected Dictionary<string, object> ModuleAPIMethods = new Dictionary<string, object>();
  88. //API module interfaces
  89. public IXfer XferManager;
  90. protected IHttpRequests m_httpRequestModule;
  91. protected ISimChat m_simChatModule;
  92. protected IXMLRPC m_xmlrpcModule;
  93. protected IWorldComm m_worldCommModule;
  94. protected IAvatarFactory m_AvatarFactory;
  95. // Central Update Loop
  96. protected int m_fps = 10;
  97. protected int m_frame = 0;
  98. protected float m_timespan = 0.089f;
  99. protected DateTime m_lastupdate = DateTime.Now;
  100. protected float m_timedilation = 1.0f;
  101. private int m_update_physics = 1;
  102. private int m_update_entitymovement = 1;
  103. private int m_update_entities = 1;
  104. private int m_update_events = 1;
  105. private int m_update_backup = 200;
  106. private int m_update_terrain = 50;
  107. private int m_update_land = 1;
  108. private int m_update_avatars = 1;
  109. private int frameMS = 0;
  110. private int physicsMS2 = 0;
  111. private int physicsMS = 0;
  112. private int otherMS = 0;
  113. private bool m_physics_enabled = true;
  114. private bool m_physics_collisions_enabled = true;
  115. private bool m_scripts_enabled = true;
  116. #endregion
  117. #region Properties
  118. public AgentCircuitManager AuthenticateHandler
  119. {
  120. get { return m_authenticateHandler; }
  121. }
  122. protected readonly LandManager m_LandManager;
  123. // LandManager object instance that manages land related things. Parcel, primcounts etc..
  124. public LandManager LandManager
  125. {
  126. get { return m_LandManager; }
  127. }
  128. protected readonly EstateManager m_estateManager;
  129. // an instance to the physics plugin's Scene object.
  130. public PhysicsScene PhysicsScene
  131. {
  132. set { m_innerScene.PhysicsScene = value; }
  133. get { return (m_innerScene.PhysicsScene); }
  134. }
  135. // This gets locked so things stay thread safe.
  136. public object SyncRoot
  137. {
  138. get { return m_innerScene.m_syncRoot; }
  139. }
  140. public EstateManager EstateManager
  141. {
  142. get { return m_estateManager; }
  143. }
  144. public float TimeDilation
  145. {
  146. get { return m_timedilation; }
  147. }
  148. protected readonly PermissionManager m_permissionManager;
  149. // This is the instance to the permissions manager.
  150. // This manages permissions to clients on in world objects
  151. public PermissionManager PermissionsMngr
  152. {
  153. get { return m_permissionManager; }
  154. }
  155. public int TimePhase
  156. {
  157. get { return m_timePhase; }
  158. }
  159. // Local reference to the objects in the scene (which are held in innerScene)
  160. // public Dictionary<LLUUID, SceneObjectGroup> Objects
  161. // {
  162. // get { return m_innerScene.SceneObjects; }
  163. // }
  164. // Reference to all of the agents in the scene (root and child)
  165. protected Dictionary<LLUUID, ScenePresence> m_scenePresences
  166. {
  167. get { return m_innerScene.ScenePresences; }
  168. set { m_innerScene.ScenePresences = value; }
  169. }
  170. // protected Dictionary<LLUUID, SceneObjectGroup> m_sceneObjects
  171. // {
  172. // get { return m_innerScene.SceneObjects; }
  173. // set { m_innerScene.SceneObjects = value; }
  174. // }
  175. public Dictionary<LLUUID, EntityBase> Entities
  176. {
  177. get { return m_innerScene.Entities; }
  178. set { m_innerScene.Entities = value; }
  179. }
  180. #endregion
  181. #region Constructors
  182. public Scene(RegionInfo regInfo, AgentCircuitManager authen, PermissionManager permissionManager,
  183. CommunicationsManager commsMan, SceneCommunicationService sceneGridService,
  184. AssetCache assetCach, StorageManager storeManager, BaseHttpServer httpServer,
  185. ModuleLoader moduleLoader, bool dumpAssetsToFile, bool physicalPrim, bool SeeIntoRegionFromNeighbor)
  186. {
  187. updateLock = new Mutex(false);
  188. m_moduleLoader = moduleLoader;
  189. m_authenticateHandler = authen;
  190. CommsManager = commsMan;
  191. m_sceneGridService = sceneGridService;
  192. m_sceneGridService.debugRegionName = regInfo.RegionName;
  193. m_storageManager = storeManager;
  194. AssetCache = assetCach;
  195. m_regInfo = regInfo;
  196. m_regionHandle = m_regInfo.RegionHandle;
  197. m_regionName = m_regInfo.RegionName;
  198. m_datastore = m_regInfo.DataStore;
  199. m_physicalPrim = physicalPrim;
  200. m_seeIntoRegionFromNeighbor = SeeIntoRegionFromNeighbor;
  201. m_eventManager = new EventManager();
  202. m_LandManager = new LandManager(this, m_regInfo);
  203. //Bind Storage Manager functions to some land manager functions for this scene
  204. EventManager.OnLandObjectAdded +=
  205. new EventManager.LandObjectAdded(m_storageManager.DataStore.StoreLandObject);
  206. EventManager.OnLandObjectRemoved +=
  207. new EventManager.LandObjectRemoved(m_storageManager.DataStore.RemoveLandObject);
  208. m_estateManager = new EstateManager(this, m_regInfo);
  209. m_permissionManager = permissionManager;
  210. m_permissionManager.Initialise(this);
  211. m_innerScene = new InnerScene(this, m_regInfo, m_permissionManager);
  212. // If the Inner scene has an Unrecoverable error, restart this sim.
  213. // Currently the only thing that causes it to happen is two kinds of specific
  214. // Physics based crashes.
  215. //
  216. // Out of memory
  217. // Operating system has killed the plugin
  218. m_innerScene.UnRecoverableError += RestartNow;
  219. m_sceneXmlLoader = new SceneXmlLoader(this, m_innerScene, m_regInfo);
  220. RegisterDefaultSceneEvents();
  221. m_log.Info("[SCENE]: Creating new entitities instance");
  222. Entities = new Dictionary<LLUUID, EntityBase>();
  223. m_scenePresences = new Dictionary<LLUUID, ScenePresence>();
  224. //m_sceneObjects = new Dictionary<LLUUID, SceneObjectGroup>();
  225. m_log.Info("[SCENE]: Creating LandMap");
  226. Terrain = new TerrainEngine((int)RegionInfo.RegionLocX, (int)RegionInfo.RegionLocY);
  227. m_httpListener = httpServer;
  228. m_dumpAssetsToFile = dumpAssetsToFile;
  229. if ((RegionInfo.EstateSettings.regionFlags & Simulator.RegionFlags.SkipScripts) == Simulator.RegionFlags.SkipScripts)
  230. {
  231. m_scripts_enabled = false;
  232. }
  233. else
  234. {
  235. m_scripts_enabled = true;
  236. }
  237. if ((RegionInfo.EstateSettings.regionFlags & Simulator.RegionFlags.SkipPhysics) == Simulator.RegionFlags.SkipPhysics)
  238. {
  239. m_physics_enabled = false;
  240. }
  241. else
  242. {
  243. m_physics_enabled = true;
  244. }
  245. m_statsReporter = new SimStatsReporter(regInfo);
  246. m_statsReporter.OnSendStatsResult += SendSimStatsPackets;
  247. string OSString = "";
  248. if (System.Environment.OSVersion.Platform != PlatformID.Unix)
  249. {
  250. OSString = System.Environment.OSVersion.ToString();
  251. }
  252. else
  253. {
  254. OSString = Util.ReadEtcIssue();
  255. }
  256. if (OSString.Length > 45)
  257. {
  258. OSString = OSString.Substring(0, 45);
  259. }
  260. m_simulatorVersion = "OpenSimulator v0.5-SVN on " + OSString + " ChilTasks:" + m_seeIntoRegionFromNeighbor.ToString() + " PhysPrim:" + m_physicalPrim.ToString();
  261. }
  262. #endregion
  263. #region Startup / Close Methods
  264. protected virtual void RegisterDefaultSceneEvents()
  265. {
  266. m_eventManager.OnParcelPrimCountAdd += m_LandManager.addPrimToLandPrimCounts;
  267. m_eventManager.OnParcelPrimCountUpdate += addPrimsToParcelCounts;
  268. m_eventManager.OnPermissionError += SendPermissionAlert;
  269. }
  270. public override string GetSimulatorVersion()
  271. {
  272. return m_simulatorVersion;
  273. }
  274. public override bool OtherRegionUp(RegionInfo otherRegion)
  275. {
  276. // Another region is up.
  277. // Gets called from Grid Comms (SceneCommunicationService<---RegionListener<----LocalBackEnd<----OGS1)
  278. // We have to tell all our ScenePresences about it..
  279. // and add it to the neighbor list.
  280. // We only add it to the neighbor list if it's within 1 region from here.
  281. // Agents may have draw distance values that cross two regions though, so
  282. // we add it to the notify list regardless of distance.
  283. // We'll check the agent's draw distance before notifying them though.
  284. if (RegionInfo.RegionHandle != otherRegion.RegionHandle)
  285. {
  286. for (int i = 0; i < m_neighbours.Count; i++)
  287. {
  288. // The purpose of this loop is to re-update the known neighbors
  289. // when another region comes up on top of another one.
  290. // The latest region in that location ends up in the
  291. // 'known neighbors list'
  292. // Additionally, the commFailTF property gets reset to false.
  293. if (m_neighbours[i].RegionHandle == otherRegion.RegionHandle)
  294. {
  295. lock (m_neighbours)
  296. {
  297. m_neighbours[i] = otherRegion;
  298. }
  299. }
  300. }
  301. // If the value isn't in the neighbours, add it.
  302. // If the RegionInfo isn't exact but is for the same XY World location,
  303. // then the above loop will fix that.
  304. if (!(m_neighbours.Contains(otherRegion)))
  305. {
  306. lock (m_neighbours)
  307. {
  308. m_neighbours.Add(otherRegion);
  309. }
  310. }
  311. // If these are cast to INT because long + negative values + abs returns invalid data
  312. int resultX = Math.Abs((int)otherRegion.RegionLocX - (int)RegionInfo.RegionLocX);
  313. int resultY = Math.Abs((int)otherRegion.RegionLocY - (int)RegionInfo.RegionLocY);
  314. if ((resultX <= 1) &&
  315. (resultY <= 1))
  316. {
  317. try
  318. {
  319. ForEachScenePresence(delegate(ScenePresence agent)
  320. {
  321. // If agent is a root agent.
  322. if (!agent.IsChildAgent)
  323. {
  324. //agent.ControllingClient.new
  325. //this.CommsManager.InterRegion.InformRegionOfChildAgent(otherRegion.RegionHandle, agent.ControllingClient.RequestClientInfo());
  326. InformClientOfNeighbor(agent, otherRegion);
  327. }
  328. }
  329. );
  330. }
  331. catch (NullReferenceException)
  332. {
  333. // This means that we're not booted up completely yet.
  334. // This shouldn't happen too often anymore.
  335. m_log.Error("[SCENE]: Couldn't inform client of regionup because we got a null reference exception");
  336. }
  337. }
  338. else
  339. {
  340. m_log.Info("[INTERGRID]: Got notice about far away Region: " + otherRegion.RegionName.ToString() +
  341. " at (" + otherRegion.RegionLocX.ToString() + ", " +
  342. otherRegion.RegionLocY.ToString() + ")");
  343. }
  344. }
  345. return true;
  346. }
  347. // Given float seconds, this will restart the region.
  348. public virtual void Restart(float seconds)
  349. {
  350. // notifications are done in 15 second increments
  351. // so .. if the number of seconds is less then 15 seconds, it's not really a restart request
  352. // It's a 'Cancel restart' request.
  353. // RestartNow() does immediate restarting.
  354. if (seconds < 15)
  355. {
  356. m_restartTimer.Stop();
  357. SendGeneralAlert("Restart Aborted");
  358. }
  359. else
  360. {
  361. // Now we figure out what to set the timer to that does the notifications and calls, RestartNow()
  362. m_restartTimer.Interval = 15000;
  363. m_incrementsof15seconds = (int)seconds / 15;
  364. m_RestartTimerCounter = 0;
  365. m_restartTimer.AutoReset = true;
  366. m_restartTimer.Elapsed += new ElapsedEventHandler(RestartTimer_Elapsed);
  367. m_log.Error("[REGION]: Restarting Region in " + (seconds / 60) + " minutes");
  368. m_restartTimer.Start();
  369. SendRegionMessageFromEstateTools(LLUUID.Random(), LLUUID.Random(), String.Empty, RegionInfo.RegionName + ": Restarting in 2 Minutes");
  370. //SendGeneralAlert(RegionInfo.RegionName + ": Restarting in 2 Minutes");
  371. }
  372. }
  373. // The Restart timer has occured.
  374. // We have to figure out if this is a notification or if the number of seconds specified in Restart
  375. // have elapsed.
  376. // If they have elapsed, call RestartNow()
  377. public void RestartTimer_Elapsed(object sender, ElapsedEventArgs e)
  378. {
  379. m_RestartTimerCounter++;
  380. if (m_RestartTimerCounter <= m_incrementsof15seconds)
  381. {
  382. if (m_RestartTimerCounter == 4 || m_RestartTimerCounter == 6 || m_RestartTimerCounter == 7)
  383. SendRegionMessageFromEstateTools(LLUUID.Random(), LLUUID.Random(), String.Empty, RegionInfo.RegionName + ": Restarting in " +
  384. ((8 - m_RestartTimerCounter) * 15) + " seconds");
  385. // SendGeneralAlert(RegionInfo.RegionName + ": Restarting in " + ((8 - m_RestartTimerCounter)*15) +
  386. //" seconds");
  387. }
  388. else
  389. {
  390. m_restartTimer.Stop();
  391. m_restartTimer.AutoReset = false;
  392. RestartNow();
  393. }
  394. }
  395. // This causes the region to restart immediatley.
  396. public void RestartNow()
  397. {
  398. if (PhysicsScene != null)
  399. {
  400. PhysicsScene.Dispose();
  401. }
  402. m_log.Error("[REGION]: Closing");
  403. Close();
  404. m_log.Error("[REGION]: Firing Region Restart Message");
  405. base.Restart(0);
  406. }
  407. // This is a helper function that notifies root agents in this region that a new sim near them has come up
  408. // This is in the form of a timer because when an instance of OpenSim.exe is started,
  409. // Even though the sims initialize, they don't listen until 'all of the sims are initialized'
  410. // If we tell an agent about a sim that's not listening yet, the agent will not be able to connect to it.
  411. // subsequently the agent will never see the region come back online.
  412. public void RestartNotifyWaitElapsed(object sender, ElapsedEventArgs e)
  413. {
  414. m_restartWaitTimer.Stop();
  415. lock (m_regionRestartNotifyList)
  416. {
  417. foreach (RegionInfo region in m_regionRestartNotifyList)
  418. {
  419. try
  420. {
  421. ForEachScenePresence(delegate(ScenePresence agent)
  422. {
  423. // If agent is a root agent.
  424. if (!agent.IsChildAgent)
  425. {
  426. //agent.ControllingClient.new
  427. //this.CommsManager.InterRegion.InformRegionOfChildAgent(otherRegion.RegionHandle, agent.ControllingClient.RequestClientInfo());
  428. InformClientOfNeighbor(agent, region);
  429. }
  430. }
  431. );
  432. }
  433. catch (NullReferenceException)
  434. {
  435. // This means that we're not booted up completely yet.
  436. // This shouldn't happen too often anymore.
  437. }
  438. }
  439. // Reset list to nothing.
  440. m_regionRestartNotifyList.Clear();
  441. }
  442. }
  443. public void SetSceneCoreDebug(bool ScriptEngine, bool CollisionEvents, bool PhysicsEngine)
  444. {
  445. if (m_scripts_enabled != !ScriptEngine)
  446. {
  447. // Tedd! Here's the method to disable the scripting engine!
  448. if (ScriptEngine)
  449. {
  450. m_log.Info("Stopping all Scripts in Scene");
  451. lock (Entities)
  452. {
  453. foreach (EntityBase ent in Entities.Values)
  454. {
  455. if (ent is SceneObjectGroup)
  456. {
  457. ((SceneObjectGroup)ent).StopScripts();
  458. }
  459. }
  460. }
  461. }
  462. else
  463. {
  464. m_log.Info("Starting all Scripts in Scene");
  465. lock (Entities)
  466. {
  467. foreach (EntityBase ent in Entities.Values)
  468. {
  469. if (ent is SceneObjectGroup)
  470. {
  471. ((SceneObjectGroup)ent).StartScripts();
  472. }
  473. }
  474. }
  475. }
  476. m_scripts_enabled = !ScriptEngine;
  477. m_log.Info("[TOTEDD]: Here is the method to trigger disabling of the scripting engine");
  478. }
  479. if (m_physics_enabled != !PhysicsEngine)
  480. {
  481. m_physics_enabled = !PhysicsEngine;
  482. }
  483. }
  484. // This is the method that shuts down the scene.
  485. public override void Close()
  486. {
  487. m_log.Warn("[SCENE]: Closing down the single simulator: " + RegionInfo.RegionName);
  488. // Kick all ROOT agents with the message, 'The simulator is going down'
  489. ForEachScenePresence(delegate(ScenePresence avatar)
  490. {
  491. if (avatar.KnownChildRegions.Contains(RegionInfo.RegionHandle))
  492. avatar.KnownChildRegions.Remove(RegionInfo.RegionHandle);
  493. if (!avatar.IsChildAgent)
  494. avatar.ControllingClient.Kick("The simulator is going down.");
  495. avatar.ControllingClient.OutPacket(PacketPool.Instance.GetPacket(libsecondlife.Packets.PacketType.DisableSimulator),
  496. ThrottleOutPacketType.Task);
  497. });
  498. // Wait here, or the kick messages won't actually get to the agents before the scene terminates.
  499. Thread.Sleep(500);
  500. // Stop all client threads.
  501. ForEachScenePresence(delegate(ScenePresence avatar) { avatar.ControllingClient.Close(true); });
  502. // Stop updating the scene objects and agents.
  503. m_heartbeatTimer.Close();
  504. // close the inner scene
  505. m_innerScene.Close();
  506. // De-register with region communications (events cleanup)
  507. UnRegisterReginWithComms();
  508. // Shut down all non shared modules.
  509. foreach (IRegionModule module in Modules.Values)
  510. {
  511. if (!module.IsSharedModule)
  512. {
  513. module.Close();
  514. }
  515. }
  516. Modules.Clear();
  517. // call the base class Close method.
  518. base.Close();
  519. }
  520. /// <summary>
  521. ///
  522. /// </summary>
  523. public void StartTimer()
  524. {
  525. m_log.Debug("[SCENE]: Starting timer");
  526. m_heartbeatTimer.Enabled = true;
  527. m_heartbeatTimer.Interval = (int)(m_timespan * 1000);
  528. m_heartbeatTimer.Elapsed += new ElapsedEventHandler(Heartbeat);
  529. }
  530. public void SetModuleInterfaces()
  531. {
  532. m_simChatModule = RequestModuleInterface<ISimChat>();
  533. m_httpRequestModule = RequestModuleInterface<IHttpRequests>();
  534. m_xmlrpcModule = RequestModuleInterface<IXMLRPC>();
  535. m_worldCommModule = RequestModuleInterface<IWorldComm>();
  536. XferManager = RequestModuleInterface<IXfer>();
  537. m_AvatarFactory = RequestModuleInterface<IAvatarFactory>();
  538. }
  539. #endregion
  540. #region Update Methods
  541. /// <summary>
  542. /// Performs per-frame updates regularly
  543. /// </summary>
  544. /// <param name="sender"></param>
  545. /// <param name="e"></param>
  546. private void Heartbeat(object sender, EventArgs e)
  547. {
  548. Update();
  549. }
  550. /// <summary>
  551. /// Performs per-frame updates on the scene, this should be the central scene loop
  552. /// </summary>
  553. public override void Update()
  554. {
  555. TimeSpan SinceLastFrame = DateTime.Now - m_lastupdate;
  556. // Aquire a lock so only one update call happens at once
  557. updateLock.WaitOne();
  558. float physicsFPS = 0;
  559. int agentsInScene = m_innerScene.GetRootAgentCount() + m_innerScene.GetChildAgentCount();
  560. if (agentsInScene > 21)
  561. {
  562. if (m_update_entities == 1)
  563. {
  564. m_update_avatars = 5;
  565. m_update_entities = 5;
  566. m_statsReporter.SetUpdateMS(6000);
  567. }
  568. }
  569. else
  570. {
  571. if (m_update_entities == 5)
  572. {
  573. m_update_avatars = 1;
  574. m_update_entities = 1;
  575. m_statsReporter.SetUpdateMS(3000);
  576. }
  577. }
  578. frameMS = System.Environment.TickCount;
  579. try
  580. {
  581. // Increment the frame counter
  582. m_frame++;
  583. // Loop it
  584. if (m_frame == Int32.MaxValue)
  585. m_frame = 0;
  586. physicsMS2 = System.Environment.TickCount;
  587. if ((m_frame % m_update_physics == 0) && m_physics_enabled)
  588. m_innerScene.UpdatePreparePhysics();
  589. physicsMS2 = System.Environment.TickCount - physicsMS2;
  590. if (m_frame % m_update_entitymovement == 0)
  591. m_innerScene.UpdateEntityMovement();
  592. physicsMS = System.Environment.TickCount;
  593. if ((m_frame % m_update_physics == 0) && m_physics_enabled)
  594. physicsFPS = m_innerScene.UpdatePhysics(
  595. Math.Max(SinceLastFrame.TotalSeconds, m_timespan)
  596. );
  597. physicsMS = System.Environment.TickCount - physicsMS;
  598. physicsMS += physicsMS2;
  599. otherMS = System.Environment.TickCount;
  600. if (m_frame % m_update_entities == 0)
  601. m_innerScene.UpdateEntities();
  602. if (m_frame % m_update_events == 0)
  603. UpdateEvents();
  604. if (m_frame % m_update_backup == 0)
  605. UpdateStorageBackup();
  606. if (m_frame % m_update_terrain == 0)
  607. UpdateTerrain();
  608. if (m_frame % m_update_land == 0)
  609. UpdateLand();
  610. otherMS = System.Environment.TickCount - otherMS;
  611. // if (m_frame%m_update_avatars == 0)
  612. // UpdateInWorldTime();
  613. m_statsReporter.AddPhysicsFPS(physicsFPS);
  614. m_statsReporter.AddTimeDilation(m_timedilation);
  615. m_statsReporter.AddFPS(1);
  616. m_statsReporter.AddInPackets(0);
  617. m_statsReporter.SetRootAgents(m_innerScene.GetRootAgentCount());
  618. m_statsReporter.SetChildAgents(m_innerScene.GetChildAgentCount());
  619. m_statsReporter.SetObjects(m_innerScene.GetTotalObjects());
  620. m_statsReporter.SetActiveObjects(m_innerScene.GetActiveObjects());
  621. frameMS = System.Environment.TickCount - frameMS;
  622. m_statsReporter.addFrameMS(frameMS);
  623. m_statsReporter.addPhysicsMS(physicsMS);
  624. m_statsReporter.addOtherMS(otherMS);
  625. m_statsReporter.SetActiveScripts(m_innerScene.GetActiveScripts());
  626. m_statsReporter.addScriptLines(m_innerScene.GetScriptLPS());
  627. }
  628. catch (NotImplementedException)
  629. {
  630. throw;
  631. }
  632. catch (System.AccessViolationException e)
  633. {
  634. m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  635. }
  636. catch (System.NullReferenceException e)
  637. {
  638. m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  639. }
  640. catch (System.InvalidOperationException e)
  641. {
  642. m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  643. }
  644. catch (Exception e)
  645. {
  646. m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  647. }
  648. finally
  649. {
  650. updateLock.ReleaseMutex();
  651. // Get actual time dilation
  652. float tmpval = (m_timespan / (float)SinceLastFrame.TotalSeconds);
  653. // If actual time dilation is greater then one, we're catching up, so subtract
  654. // the amount that's greater then 1 from the time dilation
  655. if (tmpval > 1.0)
  656. {
  657. tmpval = tmpval - (tmpval - 1.0f);
  658. }
  659. m_timedilation = tmpval;
  660. m_lastupdate = DateTime.Now;
  661. }
  662. }
  663. //Updates the time in the viewer.
  664. private void UpdateInWorldTime()
  665. {
  666. m_timeUpdateCount++;
  667. if (m_timeUpdateCount > 600)
  668. {
  669. List<ScenePresence> avatars = GetAvatars();
  670. foreach (ScenePresence avatar in avatars)
  671. {
  672. avatar.ControllingClient.SendViewerTime(m_timePhase);
  673. }
  674. m_timeUpdateCount = 0;
  675. m_timePhase++;
  676. if (m_timePhase > 94)
  677. {
  678. m_timePhase = 0;
  679. }
  680. }
  681. }
  682. private void SendSimStatsPackets(SimStatsPacket pack)
  683. {
  684. List<ScenePresence> StatSendAgents = GetScenePresences();
  685. foreach (ScenePresence agent in StatSendAgents)
  686. {
  687. if (!agent.IsChildAgent)
  688. {
  689. pack.Header.Reliable = false;
  690. agent.ControllingClient.OutPacket(pack, ThrottleOutPacketType.Task);
  691. }
  692. }
  693. }
  694. private void UpdateLand()
  695. {
  696. if (m_LandManager.landPrimCountTainted)
  697. {
  698. //Perform land update of prim count
  699. performParcelPrimCountUpdate();
  700. }
  701. }
  702. private void UpdateTerrain()
  703. {
  704. if (Terrain.IsTainted() && !Terrain.IsUserStillEditing())
  705. {
  706. CreateTerrainTexture(true);
  707. lock (Terrain.heightmap)
  708. {
  709. lock (SyncRoot)
  710. {
  711. PhysicsScene.SetTerrain(Terrain.GetHeights1D());
  712. }
  713. m_storageManager.DataStore.StoreTerrain(Terrain.GetHeights2DD(), RegionInfo.RegionID);
  714. SendTerrainUpdate(true);
  715. Terrain.ResetTaint();
  716. }
  717. }
  718. }
  719. public void SendTerrainUpdate(bool checkForTainted)
  720. {
  721. float[] terData = Terrain.GetHeights1D();
  722. Broadcast(delegate(IClientAPI client)
  723. {
  724. for (int x = 0; x < 16; x++)
  725. {
  726. for (int y = 0; y < 16; y++)
  727. {
  728. if ((!checkForTainted) || (Terrain.IsTainted(x * 16, y * 16)))
  729. {
  730. client.SendLayerData(x, y, terData);
  731. }
  732. }
  733. }
  734. });
  735. }
  736. private void UpdateStorageBackup()
  737. {
  738. Backup();
  739. }
  740. private void UpdateEvents()
  741. {
  742. m_eventManager.TriggerOnFrame();
  743. }
  744. /// <summary>
  745. /// Perform delegate action on all clients subscribing to updates from this region.
  746. /// </summary>
  747. /// <returns></returns>
  748. internal void Broadcast(Action<IClientAPI> whatToDo)
  749. {
  750. ForEachScenePresence(delegate(ScenePresence presence) { whatToDo(presence.ControllingClient); });
  751. }
  752. /// <summary>
  753. ///
  754. /// </summary>
  755. /// <returns></returns>
  756. public bool Backup()
  757. {
  758. EventManager.TriggerOnBackup(m_storageManager.DataStore);
  759. return true;
  760. }
  761. #endregion
  762. #region Load Terrain
  763. public void ExportWorldMap(string fileName)
  764. {
  765. List<MapBlockData> mapBlocks =
  766. m_sceneGridService.RequestNeighbourMapBlocks((int)(RegionInfo.RegionLocX - 9),
  767. (int)(RegionInfo.RegionLocY - 9),
  768. (int)(RegionInfo.RegionLocX + 9),
  769. (int)(RegionInfo.RegionLocY + 9));
  770. List<AssetBase> textures = new List<AssetBase>();
  771. List<Image> bitImages = new List<Image>();
  772. foreach (MapBlockData mapBlock in mapBlocks)
  773. {
  774. AssetBase texAsset = AssetCache.GetAsset(mapBlock.MapImageId, true);
  775. if (texAsset != null)
  776. {
  777. textures.Add(texAsset);
  778. }
  779. else
  780. {
  781. texAsset = AssetCache.GetAsset(mapBlock.MapImageId, true);
  782. if (texAsset != null)
  783. {
  784. textures.Add(texAsset);
  785. }
  786. }
  787. }
  788. foreach (AssetBase asset in textures)
  789. {
  790. Image image = OpenJPEG.DecodeToImage(asset.Data);
  791. bitImages.Add(image);
  792. }
  793. Bitmap mapTexture = new Bitmap(2560, 2560);
  794. Graphics g = Graphics.FromImage(mapTexture);
  795. SolidBrush sea = new SolidBrush(Color.DarkBlue);
  796. g.FillRectangle(sea, 0, 0, 2560, 2560);
  797. for (int i = 0; i < mapBlocks.Count; i++)
  798. {
  799. ushort x = (ushort)((mapBlocks[i].X - RegionInfo.RegionLocX) + 10);
  800. ushort y = (ushort)((mapBlocks[i].Y - RegionInfo.RegionLocY) + 10);
  801. g.DrawImage(bitImages[i], (x * 128), (y * 128), 128, 128);
  802. }
  803. mapTexture.Save(fileName, ImageFormat.Jpeg);
  804. }
  805. /// <summary>
  806. /// Loads a world map from a specified R32 file
  807. /// </summary>
  808. /// <param name="filename">A working R32 file</param>
  809. public void LoadWorldMap(string filename)
  810. {
  811. Terrain.LoadFromFileF32(filename);
  812. Terrain.SaveRevertMap();
  813. }
  814. /// <summary>
  815. /// Loads the World heightmap
  816. /// </summary>
  817. ///
  818. public override void LoadWorldMap()
  819. {
  820. try
  821. {
  822. double[,] map = m_storageManager.DataStore.LoadTerrain(RegionInfo.RegionID);
  823. if (map == null)
  824. {
  825. if (string.IsNullOrEmpty(m_regInfo.EstateSettings.terrainFile))
  826. {
  827. m_log.Info("[TERRAIN]: No default terrain. Generating a new terrain.");
  828. Terrain.SetDefaultTerrain();
  829. m_storageManager.DataStore.StoreTerrain(Terrain.GetHeights2DD(), RegionInfo.RegionID);
  830. }
  831. else
  832. {
  833. try
  834. {
  835. Terrain.LoadFromFileF32(m_regInfo.EstateSettings.terrainFile);
  836. Terrain *= m_regInfo.EstateSettings.terrainMultiplier;
  837. }
  838. catch
  839. {
  840. m_log.Info("[TERRAIN]: No terrain found in database or default. Generating a new terrain.");
  841. Terrain.SetDefaultTerrain();
  842. }
  843. m_storageManager.DataStore.StoreTerrain(Terrain.GetHeights2DD(), RegionInfo.RegionID);
  844. }
  845. }
  846. else
  847. {
  848. Terrain.SetHeights2D(map);
  849. }
  850. CreateTerrainTexture(true);
  851. //CommsManager.GridService.RegisterRegion(RegionInfo); //hack to update the terrain texture in grid mode so it shows on world map
  852. }
  853. catch (Exception e)
  854. {
  855. m_log.Warn("[terrain]: Scene.cs: LoadWorldMap() - Failed with exception " + e.ToString());
  856. }
  857. }
  858. public void RegisterRegionWithGrid()
  859. {
  860. RegisterCommsEvents();
  861. // These two 'commands' *must be* next to each other or sim rebooting fails.
  862. m_sceneGridService.RegisterRegion(RegionInfo);
  863. m_sceneGridService.InformNeighborsThatRegionisUp(RegionInfo);
  864. Dictionary<string, string> dGridSettings = m_sceneGridService.GetGridSettings();
  865. if (dGridSettings.ContainsKey("allow_forceful_banlines"))
  866. {
  867. if (dGridSettings["allow_forceful_banlines"] != "TRUE")
  868. {
  869. m_log.Info("[GRID]: Grid is disabling forceful parcel banlists");
  870. m_LandManager.allowedForcefulBans = false;
  871. }
  872. else
  873. {
  874. m_log.Info("[GRID]: Grid is allowing forceful parcel banlists");
  875. m_LandManager.allowedForcefulBans = true;
  876. }
  877. }
  878. }
  879. /// <summary>
  880. ///
  881. /// </summary>
  882. public void CreateTerrainTexture(bool temporary)
  883. {
  884. //create a texture asset of the terrain
  885. byte[] data = Terrain.WriteJpegImage("defaultstripe.png");
  886. m_regInfo.EstateSettings.terrainImageID = LLUUID.Random();
  887. AssetBase asset = new AssetBase();
  888. asset.FullID = m_regInfo.EstateSettings.terrainImageID;
  889. asset.Data = data;
  890. asset.Name = "terrainImage";
  891. asset.Description = RegionInfo.RegionName;
  892. asset.Type = 0;
  893. asset.Temporary = temporary;
  894. AssetCache.AddAsset(asset);
  895. }
  896. #endregion
  897. #region Load Land
  898. public void loadAllLandObjectsFromStorage()
  899. {
  900. m_log.Info("[SCENE]: Loading land objects from storage");
  901. List<LandData> landData = m_storageManager.DataStore.LoadLandObjects(RegionInfo.RegionID);
  902. if (landData.Count == 0)
  903. {
  904. m_LandManager.NoLandDataFromStorage();
  905. }
  906. else
  907. {
  908. m_LandManager.IncomingLandObjectsFromStorage(landData);
  909. }
  910. }
  911. #endregion
  912. #region Primitives Methods
  913. /// <summary>
  914. /// Loads the World's objects
  915. /// </summary>
  916. public virtual void LoadPrimsFromStorage(bool m_permissions)
  917. {
  918. m_log.Info("[SCENE]: Loading objects from datastore");
  919. List<SceneObjectGroup> PrimsFromDB = m_storageManager.DataStore.LoadObjects(m_regInfo.RegionID);
  920. foreach (SceneObjectGroup group in PrimsFromDB)
  921. {
  922. AddEntityFromStorage(group);
  923. SceneObjectPart rootPart = group.GetChildPart(group.UUID);
  924. rootPart.ObjectFlags &= ~(uint)LLObject.ObjectFlags.Scripted;
  925. rootPart.TrimPermissions();
  926. group.ApplyPhysics(m_physicalPrim);
  927. //rootPart.DoPhysicsPropertyUpdate(UsePhysics, true);
  928. }
  929. m_log.Info("[SCENE]: Loaded " + PrimsFromDB.Count.ToString() + " SceneObject(s)");
  930. }
  931. /// <summary>
  932. /// Returns a new unallocated primitive ID
  933. /// </summary>
  934. /// <returns>A brand new primitive ID</returns>
  935. public uint PrimIDAllocate()
  936. {
  937. uint myID;
  938. _primAllocateMutex.WaitOne();
  939. ++_primCount;
  940. myID = _primCount;
  941. _primAllocateMutex.ReleaseMutex();
  942. return myID;
  943. }
  944. public LLVector3 GetNewRezLocation(LLVector3 RayStart, LLVector3 RayEnd, LLUUID RayTargetID, LLQuaternion rot, byte bypassRayCast, byte RayEndIsIntersection)
  945. {
  946. LLVector3 pos = LLVector3.Zero;
  947. if (RayEndIsIntersection == (byte)1)
  948. {
  949. pos = RayEnd;
  950. return pos;
  951. }
  952. if (RayTargetID != LLUUID.Zero)
  953. {
  954. SceneObjectPart target = GetSceneObjectPart(RayTargetID);
  955. if (target != null)
  956. {
  957. pos = target.AbsolutePosition;
  958. // TODO: Raytrace here
  959. return pos;
  960. }
  961. else
  962. {
  963. // fall back to our stupid functionality
  964. pos = RayEnd;
  965. return pos;
  966. }
  967. }
  968. else
  969. {
  970. // fall back to our stupid functionality
  971. pos = RayEnd;
  972. return pos;
  973. }
  974. }
  975. public virtual void AddNewPrim(LLUUID ownerID, LLVector3 RayEnd, LLQuaternion rot, PrimitiveBaseShape shape,
  976. byte bypassRaycast, LLVector3 RayStart, LLUUID RayTargetID,
  977. byte RayEndIsIntersection)
  978. {
  979. LLVector3 pos = GetNewRezLocation(RayStart, RayEnd, RayTargetID, rot, bypassRaycast, RayEndIsIntersection);
  980. if (PermissionsMngr.CanRezObject(ownerID, pos))
  981. {
  982. // rez ON the ground, not IN the ground
  983. pos.Z += 0.25F;
  984. AddNewPrim(ownerID, pos, rot, shape);
  985. }
  986. }
  987. public virtual SceneObjectGroup AddNewPrim(LLUUID ownerID, LLVector3 pos, LLQuaternion rot, PrimitiveBaseShape shape)
  988. {
  989. SceneObjectGroup sceneOb =
  990. new SceneObjectGroup(this, m_regionHandle, ownerID, PrimIDAllocate(), pos, rot, shape);
  991. AddEntity(sceneOb);
  992. SceneObjectPart rootPart = sceneOb.GetChildPart(sceneOb.UUID);
  993. // if grass or tree, make phantom
  994. //rootPart.TrimPermissions();
  995. if ((rootPart.Shape.PCode == 95) || (rootPart.Shape.PCode == 255) || (rootPart.Shape.PCode == 111))
  996. {
  997. rootPart.AddFlag(LLObject.ObjectFlags.Phantom);
  998. //rootPart.ObjectFlags += (uint)LLObject.ObjectFlags.Phantom;
  999. }
  1000. // if not phantom, add to physics
  1001. sceneOb.ApplyPhysics(m_physicalPrim);
  1002. return sceneOb;
  1003. }
  1004. public SceneObjectGroup AddTree(LLVector3 scale, LLQuaternion rotation, LLVector3 position,
  1005. Tree treeType, bool newTree)
  1006. {
  1007. LLUUID uuid = this.RegionInfo.MasterAvatarAssignedUUID;
  1008. PrimitiveBaseShape treeShape = new PrimitiveBaseShape();
  1009. treeShape.PathCurve = 16;
  1010. treeShape.PathEnd = 49900;
  1011. treeShape.PCode = newTree ? (byte)PCode.NewTree : (byte)PCode.Tree;
  1012. treeShape.Scale = scale;
  1013. treeShape.State = (byte)treeType;
  1014. return AddNewPrim(uuid, position, rotation, treeShape);
  1015. }
  1016. public void RemovePrim(uint localID, LLUUID avatar_deleter)
  1017. {
  1018. m_innerScene.RemovePrim(localID, avatar_deleter);
  1019. }
  1020. public void AddEntityFromStorage(SceneObjectGroup sceneObject)
  1021. {
  1022. m_innerScene.AddEntityFromStorage(sceneObject);
  1023. }
  1024. public void AddEntity(SceneObjectGroup sceneObject)
  1025. {
  1026. m_innerScene.AddEntity(sceneObject);
  1027. }
  1028. public void RemoveEntity(SceneObjectGroup sceneObject)
  1029. {
  1030. if (Entities.ContainsKey(sceneObject.UUID))
  1031. {
  1032. m_LandManager.removePrimFromLandPrimCounts(sceneObject);
  1033. Entities.Remove(sceneObject.UUID);
  1034. m_LandManager.setPrimsTainted();
  1035. m_innerScene.RemoveAPrimCount();
  1036. }
  1037. }
  1038. /// <summary>
  1039. /// Called by a prim when it has been created/cloned, so that its events can be subscribed to
  1040. /// </summary>
  1041. /// <param name="prim"></param>
  1042. public void AcknowledgeNewPrim(SceneObjectGroup prim)
  1043. {
  1044. prim.OnPrimCountTainted += m_LandManager.setPrimsTainted;
  1045. }
  1046. public void LoadPrimsFromXml(string fileName, bool newIdsFlag, LLVector3 loadOffset)
  1047. {
  1048. m_sceneXmlLoader.LoadPrimsFromXml(fileName, newIdsFlag, loadOffset);
  1049. }
  1050. public void SavePrimsToXml(string fileName)
  1051. {
  1052. m_sceneXmlLoader.SavePrimsToXml(fileName);
  1053. }
  1054. public void LoadPrimsFromXml2(string fileName)
  1055. {
  1056. m_sceneXmlLoader.LoadPrimsFromXml2(fileName);
  1057. }
  1058. public void SavePrimsToXml2(string fileName)
  1059. {
  1060. m_sceneXmlLoader.SavePrimsToXml2(fileName);
  1061. }
  1062. public void CrossPrimGroupIntoNewRegion(LLVector3 position, SceneObjectGroup grp)
  1063. {
  1064. m_log.Warn("Prim crossing: " + grp.UUID.ToString());
  1065. int thisx = (int)RegionInfo.RegionLocX;
  1066. int thisy = (int)RegionInfo.RegionLocY;
  1067. ulong newRegionHandle = 0;
  1068. LLVector3 pos = position;
  1069. if (position.X > Constants.RegionSize + 0.1f)
  1070. {
  1071. pos.X = ((pos.X - Constants.RegionSize));
  1072. newRegionHandle = Util.UIntsToLong((uint)((thisx + 1) * Constants.RegionSize), (uint)(thisy * Constants.RegionSize));
  1073. // x + 1
  1074. }
  1075. else if (position.X < -0.1f)
  1076. {
  1077. pos.X = ((pos.X + Constants.RegionSize));
  1078. newRegionHandle = Util.UIntsToLong((uint)((thisx - 1) * Constants.RegionSize), (uint)(thisy * Constants.RegionSize));
  1079. // x - 1
  1080. }
  1081. if (position.Y > Constants.RegionSize + 0.1f)
  1082. {
  1083. pos.Y = ((pos.Y - Constants.RegionSize));
  1084. newRegionHandle = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy + 1) * Constants.RegionSize));
  1085. // y + 1
  1086. }
  1087. else if (position.Y < -1f)
  1088. {
  1089. pos.Y = ((pos.Y + Constants.RegionSize));
  1090. newRegionHandle = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy - 1) * Constants.RegionSize));
  1091. // y - 1
  1092. }
  1093. // Offset the positions for the new region across the border
  1094. grp.OffsetForNewRegion(pos);
  1095. if (newRegionHandle != 0)
  1096. {
  1097. bool successYN = false;
  1098. successYN = m_sceneGridService.PrimCrossToNeighboringRegion(newRegionHandle, grp.UUID, m_sceneXmlLoader.SavePrimGroupToXML2String(grp));
  1099. if (successYN)
  1100. {
  1101. // We remove the object here
  1102. try
  1103. {
  1104. DeleteSceneObjectGroup(grp);
  1105. }
  1106. catch (System.Exception)
  1107. {
  1108. m_log.Warn("[DATABASE]: exception when trying to remove the prim that crossed the border.");
  1109. }
  1110. }
  1111. else
  1112. {
  1113. m_log.Warn("[INTERREGION]: Prim Crossing Failed!");
  1114. if (grp.RootPart != null)
  1115. {
  1116. if (grp.RootPart.PhysActor != null)
  1117. {
  1118. grp.RootPart.PhysActor.CrossingFailure();
  1119. }
  1120. }
  1121. }
  1122. }
  1123. }
  1124. public void IncomingInterRegionPrimGroup(ulong regionHandle, LLUUID primID, string objXMLData)
  1125. {
  1126. m_log.Warn("{[INTERREGION]: A new prim arrived from a neighbor");
  1127. m_sceneXmlLoader.LoadGroupFromXml2String(objXMLData);
  1128. }
  1129. #endregion
  1130. #region Add/Remove Avatar Methods
  1131. /// <summary>
  1132. ///
  1133. /// </summary>
  1134. /// <param name="client"></param
  1135. /// <param name="child"></param>
  1136. public override void AddNewClient(IClientAPI client, bool child)
  1137. {
  1138. m_log.Warn("[CONNECTION DEBUGGING]: Creating new client for " + client.AgentId.ToString());
  1139. SubscribeToClientEvents(client);
  1140. m_estateManager.sendRegionHandshake(client);
  1141. CreateAndAddScenePresence(client, child);
  1142. m_LandManager.sendParcelOverlay(client);
  1143. CommsManager.UserProfileCacheService.AddNewUser(client.AgentId);
  1144. }
  1145. protected virtual void SubscribeToClientEvents(IClientAPI client)
  1146. {
  1147. client.OnRegionHandShakeReply += SendLayerData;
  1148. //remoteClient.OnRequestWearables += new GenericCall(this.GetInitialPrims);
  1149. client.OnModifyTerrain += ModifyTerrain;
  1150. // client.OnRequestWearables += InformClientOfNeighbours;
  1151. client.OnAddPrim += AddNewPrim;
  1152. client.OnUpdatePrimGroupPosition += m_innerScene.UpdatePrimPosition;
  1153. client.OnUpdatePrimSinglePosition += m_innerScene.UpdatePrimSinglePosition;
  1154. client.OnUpdatePrimGroupRotation += m_innerScene.UpdatePrimRotation;
  1155. client.OnUpdatePrimGroupMouseRotation += m_innerScene.UpdatePrimRotation;
  1156. client.OnUpdatePrimSingleRotation += m_innerScene.UpdatePrimSingleRotation;
  1157. client.OnUpdatePrimScale += m_innerScene.UpdatePrimScale;
  1158. client.OnUpdateExtraParams += m_innerScene.UpdateExtraParam;
  1159. client.OnUpdatePrimShape += m_innerScene.UpdatePrimShape;
  1160. client.OnRequestMapBlocks += RequestMapBlocks;
  1161. client.OnUpdatePrimTexture += m_innerScene.UpdatePrimTexture;
  1162. client.OnTeleportLocationRequest += RequestTeleportLocation;
  1163. client.OnObjectSelect += SelectPrim;
  1164. client.OnObjectDeselect += DeselectPrim;
  1165. client.OnGrabUpdate += m_innerScene.MoveObject;
  1166. client.OnDeRezObject += DeRezObject;
  1167. client.OnRezObject += RezObject;
  1168. client.OnNameFromUUIDRequest += CommsManager.HandleUUIDNameRequest;
  1169. client.OnObjectDescription += m_innerScene.PrimDescription;
  1170. client.OnObjectName += m_innerScene.PrimName;
  1171. client.OnLinkObjects += m_innerScene.LinkObjects;
  1172. client.OnDelinkObjects += m_innerScene.DelinkObjects;
  1173. client.OnObjectDuplicate += m_innerScene.DuplicateObject;
  1174. client.OnUpdatePrimFlags += m_innerScene.UpdatePrimFlags;
  1175. client.OnRequestObjectPropertiesFamily += m_innerScene.RequestObjectPropertiesFamily;
  1176. client.OnParcelPropertiesRequest += new ParcelPropertiesRequest(m_LandManager.handleParcelPropertiesRequest);
  1177. client.OnParcelDivideRequest += new ParcelDivideRequest(m_LandManager.handleParcelDivideRequest);
  1178. client.OnParcelJoinRequest += new ParcelJoinRequest(m_LandManager.handleParcelJoinRequest);
  1179. client.OnParcelPropertiesUpdateRequest +=
  1180. new ParcelPropertiesUpdateRequest(m_LandManager.handleParcelPropertiesUpdateRequest);
  1181. client.OnParcelSelectObjects += new ParcelSelectObjects(m_LandManager.handleParcelSelectObjectsRequest);
  1182. client.OnParcelObjectOwnerRequest +=
  1183. new ParcelObjectOwnerRequest(m_LandManager.handleParcelObjectOwnersRequest);
  1184. client.OnParcelAccessListRequest += new ParcelAccessListRequest(m_LandManager.handleParcelAccessRequest);
  1185. client.OnParcelAccessListUpdateRequest +=
  1186. new ParcelAccessListUpdateRequest(m_LandManager.handleParcelAccessUpdateRequest);
  1187. client.OnEstateOwnerMessage += new EstateOwnerMessageRequest(m_estateManager.handleEstateOwnerMessage);
  1188. client.OnRegionInfoRequest += m_estateManager.HandleRegionInfoRequest;
  1189. client.OnEstateCovenantRequest += m_estateManager.HandleEstateCovenantRequest;
  1190. client.OnRequestGodlikePowers += handleRequestGodlikePowers;
  1191. client.OnGodKickUser += handleGodlikeKickUser;
  1192. client.OnObjectPermissions += HandleObjectPermissionsUpdate;
  1193. client.OnCreateNewInventoryItem += CreateNewInventoryItem;
  1194. client.OnCreateNewInventoryFolder += CommsManager.UserProfileCacheService.HandleCreateInventoryFolder;
  1195. client.OnUpdateInventoryFolder += CommsManager.UserProfileCacheService.HandleUpdateInventoryFolder;
  1196. client.OnMoveInventoryFolder += CommsManager.UserProfileCacheService.HandleMoveInventoryFolder;
  1197. client.OnFetchInventoryDescendents += CommsManager.UserProfileCacheService.HandleFetchInventoryDescendents;
  1198. client.OnPurgeInventoryDescendents += CommsManager.UserProfileCacheService.HandlePurgeInventoryDescendents;
  1199. client.OnFetchInventory += CommsManager.UserProfileCacheService.HandleFetchInventory;
  1200. client.OnUpdateInventoryItem += UpdateInventoryItemAsset;
  1201. client.OnCopyInventoryItem += CopyInventoryItem;
  1202. client.OnMoveInventoryItem += MoveInventoryItem;
  1203. client.OnRemoveInventoryItem += RemoveInventoryItem;
  1204. client.OnRemoveInventoryFolder += RemoveInventoryFolder;
  1205. // client.OnAssetUploadRequest += CommsManager.TransactionsManager.HandleUDPUploadRequest;
  1206. // client.OnXferReceive += CommsManager.TransactionsManager.HandleXfer;
  1207. client.OnRezScript += RezScript;
  1208. client.OnRequestTaskInventory += RequestTaskInventory;
  1209. client.OnRemoveTaskItem += RemoveTaskInventory;
  1210. client.OnUpdateTaskInventory += UpdateTaskInventory;
  1211. client.OnGrabObject += ProcessObjectGrab;
  1212. client.OnMoneyTransferRequest += ProcessMoneyTransferRequest;
  1213. client.OnAvatarPickerRequest += ProcessAvatarPickerRequest;
  1214. client.OnPacketStats += AddPacketStats;
  1215. client.OnRezSingleAttachmentFromInv += SingleAttachmentFromInv;
  1216. client.OnObjectAttach += ObjectAttach;
  1217. client.OnObjectDetach += ObjectDetach;
  1218. EventManager.TriggerOnNewClient(client);
  1219. }
  1220. protected virtual ScenePresence CreateAndAddScenePresence(IClientAPI client, bool child)
  1221. {
  1222. ScenePresence avatar = null;
  1223. AvatarAppearance appearance;
  1224. GetAvatarAppearance(client, out appearance);
  1225. avatar = m_innerScene.CreateAndAddScenePresence(client, child, appearance);
  1226. if (avatar.IsChildAgent)
  1227. {
  1228. avatar.OnSignificantClientMovement += m_LandManager.handleSignificantClientMovement;
  1229. }
  1230. return avatar;
  1231. }
  1232. protected void GetAvatarAppearance(IClientAPI client, out AvatarAppearance appearance)
  1233. {
  1234. if (m_AvatarFactory == null ||
  1235. !m_AvatarFactory.TryGetAvatarAppearance(client.AgentId, out appearance))
  1236. {
  1237. //not found Appearance
  1238. m_log.Warn("[AVATAR DEBUGGING]: Couldn't fetch avatar appearance from factory, please report this to the opensim mantis");
  1239. byte[] visualParams;
  1240. AvatarWearable[] wearables;
  1241. AvatarFactoryModule.GetDefaultAvatarAppearance(out wearables, out visualParams);
  1242. appearance = new AvatarAppearance(client.AgentId, wearables, visualParams);
  1243. }
  1244. }
  1245. /// <summary>
  1246. ///
  1247. /// </summary>
  1248. /// <param name="agentID"></param>
  1249. public override void RemoveClient(LLUUID agentID)
  1250. {
  1251. ScenePresence avatar = GetScenePresence(agentID);
  1252. try
  1253. {
  1254. if (avatar.IsChildAgent)
  1255. {
  1256. m_innerScene.removeUserCount(false);
  1257. }
  1258. else
  1259. {
  1260. m_innerScene.removeUserCount(true);
  1261. m_sceneGridService.LogOffUser(agentID, RegionInfo.RegionID, RegionInfo.RegionHandle,
  1262. avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y,
  1263. avatar.AbsolutePosition.Z);
  1264. m_sceneGridService.SendCloseChildAgentConnections(avatar);
  1265. }
  1266. m_eventManager.TriggerClientClosed(agentID);
  1267. }
  1268. catch (NullReferenceException)
  1269. {
  1270. // We don't know which count to remove it from
  1271. // Avatar is already disposed :/
  1272. }
  1273. m_eventManager.TriggerOnRemovePresence(agentID);
  1274. Broadcast(delegate(IClientAPI client)
  1275. {
  1276. try
  1277. {
  1278. client.SendKillObject(avatar.RegionHandle, avatar.LocalId);
  1279. }
  1280. catch (System.NullReferenceException)
  1281. {
  1282. //We can safely ignore null reference exceptions. It means the avatar are dead and cleaned up anyway.
  1283. }
  1284. });
  1285. ForEachScenePresence(
  1286. delegate(ScenePresence presence) { presence.CoarseLocationChange(); });
  1287. IAgentAssetTransactions agentTransactions = this.RequestModuleInterface<IAgentAssetTransactions>();
  1288. if (agentTransactions != null)
  1289. {
  1290. agentTransactions.RemoveAgentAssetTransactions(agentID);
  1291. }
  1292. lock (m_scenePresences)
  1293. {
  1294. if (m_scenePresences.Remove(agentID))
  1295. {
  1296. //m_log.InfoFormat("[SCENE] Removed scene presence {0}", agentID);
  1297. }
  1298. else
  1299. {
  1300. m_log.WarnFormat("[SCENE] Tried to remove non-existent scene prescence with agent ID {0} from scene ScenePresences list", agentID);
  1301. }
  1302. }
  1303. lock (Entities)
  1304. {
  1305. if (Entities.Remove(agentID))
  1306. {
  1307. //m_log.InfoFormat("[SCENE] Removed scene presence {0} from entities list", agentID);
  1308. }
  1309. else
  1310. {
  1311. m_log.WarnFormat("[SCENE] Tried to remove non-existent scene prescence with agent ID {0} from scene Entities list", agentID);
  1312. }
  1313. }
  1314. try
  1315. {
  1316. avatar.Close();
  1317. }
  1318. catch (NullReferenceException)
  1319. {
  1320. //We can safely ignore null reference exceptions. It means the avatar are dead and cleaned up anyway.
  1321. }
  1322. catch (Exception e)
  1323. {
  1324. m_log.Error("[SCENE] Scene.cs:RemoveClient exception: " + e.ToString());
  1325. }
  1326. // Remove client agent from profile, so new logins will work
  1327. m_sceneGridService.ClearUserAgent(agentID);
  1328. //m_log.InfoFormat("[SCENE] Memory pre GC {0}", System.GC.GetTotalMemory(false));
  1329. //m_log.InfoFormat("[SCENE] Memory post GC {0}", System.GC.GetTotalMemory(true));
  1330. }
  1331. public override void CloseAllAgents(uint circuitcode)
  1332. {
  1333. // Called by ClientView to kill all circuit codes
  1334. ClientManager.CloseAllAgents(circuitcode);
  1335. }
  1336. public void NotifyMyCoarseLocationChange()
  1337. {
  1338. ForEachScenePresence(delegate(ScenePresence presence) { presence.CoarseLocationChange(); });
  1339. }
  1340. #endregion
  1341. #region Entities
  1342. /// <summary>
  1343. ///
  1344. /// </summary>
  1345. /// <param name="entID"></param>
  1346. /// <returns></returns>
  1347. public bool DeleteEntity(LLUUID entID)
  1348. {
  1349. if (Entities.ContainsKey(entID))
  1350. {
  1351. Entities.Remove(entID);
  1352. m_storageManager.DataStore.RemoveObject(entID, m_regInfo.RegionID);
  1353. m_innerScene.RemoveAPrimCount();
  1354. return true;
  1355. }
  1356. return false;
  1357. }
  1358. public void SendKillObject(uint localID)
  1359. {
  1360. Broadcast(delegate(IClientAPI client) { client.SendKillObject(m_regionHandle, localID); });
  1361. }
  1362. #endregion
  1363. #region RegionComms
  1364. /// <summary>
  1365. ///
  1366. /// </summary>
  1367. public void RegisterCommsEvents()
  1368. {
  1369. m_sceneGridService.OnExpectUser += NewUserConnection;
  1370. m_sceneGridService.OnAvatarCrossingIntoRegion += AgentCrossing;
  1371. m_sceneGridService.OnCloseAgentConnection += CloseConnection;
  1372. m_sceneGridService.OnRegionUp += OtherRegionUp;
  1373. m_sceneGridService.OnChildAgentUpdate += IncomingChildAgentDataUpdate;
  1374. m_sceneGridService.OnExpectPrim += IncomingInterRegionPrimGroup;
  1375. m_sceneGridService.KillObject = SendKillObject;
  1376. }
  1377. /// <summary>
  1378. ///
  1379. /// </summary>
  1380. public void UnRegisterReginWithComms()
  1381. {
  1382. m_sceneGridService.OnExpectPrim -= IncomingInterRegionPrimGroup;
  1383. m_sceneGridService.OnChildAgentUpdate -= IncomingChildAgentDataUpdate;
  1384. m_sceneGridService.OnRegionUp -= OtherRegionUp;
  1385. m_sceneGridService.OnExpectUser -= NewUserConnection;
  1386. m_sceneGridService.OnAvatarCrossingIntoRegion -= AgentCrossing;
  1387. m_sceneGridService.OnCloseAgentConnection -= CloseConnection;
  1388. m_sceneGridService.Close();
  1389. }
  1390. /// <summary>
  1391. ///
  1392. /// </summary>
  1393. /// <param name="regionHandle"></param>
  1394. /// <param name="agent"></param>
  1395. public void NewUserConnection(ulong regionHandle, AgentCircuitData agent)
  1396. {
  1397. if (regionHandle == m_regInfo.RegionHandle)
  1398. {
  1399. if (agent.CapsPath != String.Empty)
  1400. {
  1401. m_log.Debug("[CONNECTION DEBUGGING]: Setting up CAPS handler for " + agent.AgentID.ToString() + " at " + agent.CapsPath.ToString());
  1402. Caps cap =
  1403. new Caps(AssetCache, m_httpListener, m_regInfo.ExternalHostName, m_httpListener.Port,
  1404. agent.CapsPath, agent.AgentID, m_dumpAssetsToFile);
  1405. Util.SetCapsURL(agent.AgentID,
  1406. "http://" + m_regInfo.ExternalHostName + ":" + m_httpListener.Port.ToString() +
  1407. "/CAPS/" + agent.CapsPath + "0000/");
  1408. cap.RegisterHandlers();
  1409. if (agent.child)
  1410. {
  1411. }
  1412. cap.AddNewInventoryItem = AddInventoryItem;
  1413. cap.ItemUpdatedCall = CapsUpdateInventoryItemAsset;
  1414. cap.TaskScriptUpdatedCall = CapsUpdateTaskInventoryScriptAsset;
  1415. if (m_capsHandlers.ContainsKey(agent.AgentID))
  1416. {
  1417. m_log.Debug("[CONNECTION DEBUGGING]: Caps path already in use for " + agent.AgentID.ToString());
  1418. try
  1419. {
  1420. m_capsHandlers[agent.AgentID] = cap;
  1421. }
  1422. catch (KeyNotFoundException)
  1423. {
  1424. m_log.Debug("[CONNECTION DEBUGGING]: Caught exception adding handler for " + agent.AgentID.ToString());
  1425. // Fix for a potential race condition.
  1426. m_capsHandlers.Add(agent.AgentID, cap);
  1427. }
  1428. }
  1429. else
  1430. {
  1431. m_capsHandlers.Add(agent.AgentID, cap);
  1432. }
  1433. }
  1434. else
  1435. {
  1436. m_log.Warn("[CONNECTION DEBUGGING]: Skipped setting up CAPS handler for " + agent.AgentID.ToString());
  1437. }
  1438. m_log.Debug("[CONNECTION DEBUGGING]: Creating new circuit code (" + agent.circuitcode.ToString() + ") for " + agent.AgentID.ToString());
  1439. m_authenticateHandler.AddNewCircuit(agent.circuitcode, agent);
  1440. }
  1441. else
  1442. {
  1443. m_log.Warn("[CONNECTION DEBUGGING]: Skipping this region for welcoming " + agent.AgentID.ToString() + " [" + regionHandle.ToString() + "]");
  1444. }
  1445. }
  1446. /// <summary>
  1447. ///
  1448. /// </summary>
  1449. /// <param name="regionHandle"></param>
  1450. /// <param name="agentID"></param>
  1451. /// <param name="position"></param>
  1452. /// <param name="isFlying"></param>
  1453. public virtual void AgentCrossing(ulong regionHandle, LLUUID agentID, LLVector3 position, bool isFlying)
  1454. {
  1455. if (regionHandle == m_regInfo.RegionHandle)
  1456. {
  1457. if (m_scenePresences.ContainsKey(agentID))
  1458. {
  1459. try
  1460. {
  1461. m_scenePresences[agentID].MakeRootAgent(position, isFlying);
  1462. }
  1463. catch (Exception e)
  1464. {
  1465. m_log.Info("[SCENE]: Unable to do Agent Crossing.");
  1466. m_log.Debug("[SCENE]: " + e.ToString());
  1467. }
  1468. //m_innerScene.SwapRootChildAgent(false);
  1469. }
  1470. }
  1471. }
  1472. public virtual bool IncomingChildAgentDataUpdate(ulong regionHandle, ChildAgentDataUpdate cAgentData)
  1473. {
  1474. ScenePresence childAgentUpdate = GetScenePresence(new LLUUID(cAgentData.AgentID));
  1475. if (childAgentUpdate != null)
  1476. {
  1477. // I can't imagine *yet* why we would get an update if the agent is a root agent..
  1478. // however to avoid a race condition crossing borders..
  1479. if (childAgentUpdate.IsChildAgent)
  1480. {
  1481. uint rRegionX = (uint)(cAgentData.regionHandle >> 40);
  1482. uint rRegionY = (((uint)(cAgentData.regionHandle)) >> 8);
  1483. uint tRegionX = RegionInfo.RegionLocX;
  1484. uint tRegionY = RegionInfo.RegionLocY;
  1485. //Send Data to ScenePresence
  1486. childAgentUpdate.ChildAgentDataUpdate(cAgentData, tRegionX, tRegionY, rRegionX, rRegionY);
  1487. // Not Implemented:
  1488. //TODO: Do we need to pass the message on to one of our neighbors?
  1489. }
  1490. return true;
  1491. }
  1492. return false;
  1493. }
  1494. /// <summary>
  1495. /// Tell a single agent to disconnect from the region.
  1496. /// </summary>
  1497. /// <param name="regionHandle"></param>
  1498. /// <param name="agentID"></param>
  1499. public bool CloseConnection(ulong regionHandle, LLUUID agentID)
  1500. {
  1501. if (regionHandle == m_regionHandle)
  1502. {
  1503. ScenePresence presence = m_innerScene.GetScenePresence(agentID);
  1504. if (presence != null)
  1505. {
  1506. if (presence.IsChildAgent)
  1507. {
  1508. m_innerScene.removeUserCount(false);
  1509. }
  1510. else
  1511. {
  1512. m_innerScene.removeUserCount(true);
  1513. }
  1514. // Tell a single agent to disconnect from the region.
  1515. libsecondlife.Packets.DisableSimulatorPacket disable = (libsecondlife.Packets.DisableSimulatorPacket)PacketPool.Instance.GetPacket(libsecondlife.Packets.PacketType.DisableSimulator);
  1516. presence.ControllingClient.OutPacket(disable, ThrottleOutPacketType.Task);
  1517. presence.ControllingClient.Close(true);
  1518. }
  1519. }
  1520. return true;
  1521. }
  1522. /// <summary>
  1523. /// Tell neighboring regions about this agent
  1524. /// When the regions respond with a true value,
  1525. /// tell the agents about the region.
  1526. ///
  1527. /// We have to tell the regions about the agents first otherwise it'll deny them access
  1528. ///
  1529. /// </summary>
  1530. /// <param name="presence"></param>
  1531. public void InformClientOfNeighbours(ScenePresence presence)
  1532. {
  1533. m_sceneGridService.EnableNeighbourChildAgents(presence, m_neighbours);
  1534. }
  1535. /// <summary>
  1536. /// Tell a neighboring region about this agent
  1537. /// </summary>
  1538. /// <param name="presence"></param>
  1539. /// <param name="region"></param>
  1540. public void InformClientOfNeighbor(ScenePresence presence, RegionInfo region)
  1541. {
  1542. m_sceneGridService.InformNeighborChildAgent(presence, region, m_neighbours);
  1543. }
  1544. /// <summary>
  1545. /// Requests information about this region from gridcomms
  1546. /// </summary>
  1547. /// <param name="regionHandle"></param>
  1548. /// <returns></returns>
  1549. public RegionInfo RequestNeighbouringRegionInfo(ulong regionHandle)
  1550. {
  1551. return m_sceneGridService.RequestNeighbouringRegionInfo(regionHandle);
  1552. }
  1553. /// <summary>
  1554. /// Requests textures for map from minimum region to maximum region in world cordinates
  1555. /// </summary>
  1556. /// <param name="remoteClient"></param>
  1557. /// <param name="minX"></param>
  1558. /// <param name="minY"></param>
  1559. /// <param name="maxX"></param>
  1560. /// <param name="maxY"></param>
  1561. public void RequestMapBlocks(IClientAPI remoteClient, int minX, int minY, int maxX, int maxY)
  1562. {
  1563. m_sceneGridService.RequestMapBlocks(remoteClient, minX, minY, maxX, maxX);
  1564. }
  1565. /// <summary>
  1566. /// Tries to teleport agent to other region.
  1567. /// </summary>
  1568. /// <param name="remoteClient"></param>
  1569. /// <param name="regionHandle"></param>
  1570. /// <param name="position"></param>
  1571. /// <param name="lookAt"></param>
  1572. /// <param name="flags"></param>
  1573. public void RequestTeleportLocation(IClientAPI remoteClient, ulong regionHandle, LLVector3 position,
  1574. LLVector3 lookAt, uint flags)
  1575. {
  1576. if (m_scenePresences.ContainsKey(remoteClient.AgentId))
  1577. {
  1578. m_sceneGridService.RequestTeleportToLocation(m_scenePresences[remoteClient.AgentId], regionHandle,
  1579. position, lookAt, flags);
  1580. }
  1581. }
  1582. /// <summary>
  1583. /// Agent is crossing the border into a neighbouring region. Tell the neighbour about it!
  1584. /// </summary>
  1585. /// <param name="regionHandle"></param>
  1586. /// <param name="agentID"></param>
  1587. /// <param name="position"></param>
  1588. /// <param name="isFlying"></param>
  1589. /// <returns></returns>
  1590. public bool InformNeighbourOfCrossing(ulong regionHandle, LLUUID agentID, LLVector3 position, bool isFlying)
  1591. {
  1592. return m_sceneGridService.CrossToNeighbouringRegion(regionHandle, agentID, position, isFlying);
  1593. }
  1594. public void SendOutChildAgentUpdates(ChildAgentDataUpdate cadu, ScenePresence presence)
  1595. {
  1596. m_sceneGridService.SendChildAgentDataUpdate(cadu, presence);
  1597. }
  1598. #endregion
  1599. #region Module Methods
  1600. /// <summary>
  1601. ///
  1602. /// </summary>
  1603. /// <param name="name"></param>
  1604. /// <param name="module"></param>
  1605. public void AddModule(string name, IRegionModule module)
  1606. {
  1607. if (!Modules.ContainsKey(name))
  1608. {
  1609. Modules.Add(name, module);
  1610. }
  1611. }
  1612. /// <summary>
  1613. ///
  1614. /// </summary>
  1615. /// <param name="mod"></param>
  1616. public void RegisterModuleInterface<M>(M mod)
  1617. {
  1618. if (!ModuleInterfaces.ContainsKey(typeof(M)))
  1619. {
  1620. ModuleInterfaces.Add(typeof(M), mod);
  1621. }
  1622. }
  1623. /// <summary>
  1624. ///
  1625. /// </summary>
  1626. /// <returns></returns>
  1627. public T RequestModuleInterface<T>()
  1628. {
  1629. if (ModuleInterfaces.ContainsKey(typeof(T)))
  1630. {
  1631. return (T)ModuleInterfaces[typeof(T)];
  1632. }
  1633. else
  1634. {
  1635. return default(T);
  1636. }
  1637. }
  1638. #endregion
  1639. #region Other Methods
  1640. /// <summary>
  1641. ///
  1642. /// </summary>
  1643. /// <param name="phase"></param>
  1644. public void SetTimePhase(int phase)
  1645. {
  1646. m_timePhase = phase;
  1647. }
  1648. /// <summary>
  1649. ///
  1650. /// </summary>
  1651. /// <param name="avatarID"></param>
  1652. /// <param name="objectName"></param>
  1653. /// <param name="objectID"></param>
  1654. /// <param name="ownerID"></param>
  1655. /// <param name="groupOwned"></param>
  1656. /// <param name="message"></param>
  1657. /// <param name="url"></param>
  1658. public void SendUrlToUser(LLUUID avatarID, string objectName, LLUUID objectID, LLUUID ownerID, bool groupOwned,
  1659. string message, string url)
  1660. {
  1661. if (m_scenePresences.ContainsKey(avatarID))
  1662. {
  1663. m_scenePresences[avatarID].ControllingClient.SendLoadURL(objectName, objectID, ownerID, groupOwned,
  1664. message, url);
  1665. }
  1666. }
  1667. public void SendDialogToUser(LLUUID avatarID, string objectName, LLUUID objectID, LLUUID ownerID, string message, LLUUID TextureID, int ch, string[] buttonlabels)
  1668. {
  1669. if (m_scenePresences.ContainsKey(avatarID))
  1670. {
  1671. m_scenePresences[avatarID].ControllingClient.SendDialog(objectName, objectID, ownerID, message, TextureID, ch, buttonlabels);
  1672. }
  1673. }
  1674. /// <summary>
  1675. ///
  1676. /// </summary>
  1677. /// <param name="url"></param>
  1678. /// <param name="type"></param>
  1679. /// <param name="body"></param>
  1680. /// <returns></returns>
  1681. public LLUUID MakeHttpRequest(string url, string type, string body)
  1682. {
  1683. if (m_httpRequestModule != null)
  1684. {
  1685. return m_httpRequestModule.MakeHttpRequest(url, type, body);
  1686. }
  1687. return LLUUID.Zero;
  1688. }
  1689. /// <summary>
  1690. ///
  1691. /// </summary>
  1692. public void performParcelPrimCountUpdate()
  1693. {
  1694. m_LandManager.resetAllLandPrimCounts();
  1695. m_eventManager.TriggerParcelPrimCountUpdate();
  1696. m_LandManager.finalizeLandPrimCountUpdate();
  1697. m_LandManager.landPrimCountTainted = false;
  1698. }
  1699. /// <summary>
  1700. ///
  1701. /// </summary>
  1702. public void addPrimsToParcelCounts()
  1703. {
  1704. foreach (EntityBase obj in Entities.Values)
  1705. {
  1706. if (obj is SceneObjectGroup)
  1707. {
  1708. m_eventManager.TriggerParcelPrimCountAdd((SceneObjectGroup)obj);
  1709. }
  1710. }
  1711. }
  1712. /// <summary>
  1713. /// This method is a way for the Friends Module to create an instant
  1714. /// message to the avatar and for Instant Messages that travel across
  1715. /// gridcomms to make it to the Instant Message Module.
  1716. ///
  1717. /// Friendship establishment and groups are unfortunately tied with instant messaging and
  1718. /// there's no way to separate them completely.
  1719. /// </summary>
  1720. /// <param name="message">object containing the instant message data</param>
  1721. /// <returns>void</returns>
  1722. public void TriggerGridInstantMessage(GridInstantMessage message, InstantMessageReceiver options)
  1723. {
  1724. m_eventManager.TriggerGridInstantMessage(message, options);
  1725. }
  1726. public virtual void StoreAddFriendship(LLUUID ownerID, LLUUID friendID, uint perms)
  1727. {
  1728. // TODO: m_sceneGridService.DoStuff;
  1729. m_sceneGridService.AddNewUserFriend(ownerID, friendID, perms);
  1730. }
  1731. public virtual void StoreUpdateFriendship(LLUUID ownerID, LLUUID friendID, uint perms)
  1732. {
  1733. // TODO: m_sceneGridService.DoStuff;
  1734. m_sceneGridService.UpdateUserFriendPerms(ownerID, friendID, perms);
  1735. }
  1736. public virtual void StoreRemoveFriendship(LLUUID ownerID, LLUUID ExfriendID)
  1737. {
  1738. // TODO: m_sceneGridService.DoStuff;
  1739. m_sceneGridService.RemoveUserFriend(ownerID, ExfriendID);
  1740. }
  1741. public virtual List<FriendListItem> StoreGetFriendsForUser(LLUUID ownerID)
  1742. {
  1743. // TODO: m_sceneGridService.DoStuff;
  1744. return m_sceneGridService.GetUserFriendList(ownerID);
  1745. }
  1746. public void AddPacketStats(int inPackets, int outPackets, int unAckedBytes)
  1747. {
  1748. m_statsReporter.AddInPackets(inPackets);
  1749. m_statsReporter.AddOutPackets(outPackets);
  1750. m_statsReporter.AddunAckedBytes(unAckedBytes);
  1751. }
  1752. public void AddAgentTime(int ms)
  1753. {
  1754. m_statsReporter.addFrameMS(ms);
  1755. m_statsReporter.addAgentMS(ms);
  1756. }
  1757. public void AddAgentUpdates(int count)
  1758. {
  1759. m_statsReporter.AddAgentUpdates(count);
  1760. }
  1761. public void AddPendingDownloads(int count)
  1762. {
  1763. m_statsReporter.addPendingDownload(count);
  1764. }
  1765. #endregion
  1766. #region Console Commands
  1767. #region Alert Methods
  1768. private void SendPermissionAlert(LLUUID user, string reason)
  1769. {
  1770. SendAlertToUser(user, reason, false);
  1771. }
  1772. /// <summary>
  1773. ///
  1774. /// </summary>
  1775. /// <param name="message"></param>
  1776. public void SendGeneralAlert(string message)
  1777. {
  1778. List<ScenePresence> presenceList = GetScenePresences();
  1779. foreach (ScenePresence presence in presenceList)
  1780. {
  1781. presence.ControllingClient.SendAlertMessage(message);
  1782. }
  1783. }
  1784. /// <summary>
  1785. ///
  1786. /// </summary>
  1787. /// <param name="agentID"></param>
  1788. /// <param name="message"></param>
  1789. /// <param name="modal"></param>
  1790. public void SendAlertToUser(LLUUID agentID, string message, bool modal)
  1791. {
  1792. if (m_scenePresences.ContainsKey(agentID))
  1793. {
  1794. m_scenePresences[agentID].ControllingClient.SendAgentAlertMessage(message, modal);
  1795. }
  1796. }
  1797. /// <summary>
  1798. ///
  1799. /// </summary>
  1800. /// <param name="agentID"></param>
  1801. /// <param name="sessionID"></param>
  1802. /// <param name="token"></param>
  1803. /// <param name="controllingClient"></param>
  1804. public void handleRequestGodlikePowers(LLUUID agentID, LLUUID sessionID, LLUUID token,
  1805. IClientAPI controllingClient)
  1806. {
  1807. // First check that this is the sim owner
  1808. if (m_permissionManager.GenericEstatePermission(agentID))
  1809. {
  1810. // User needs to be logged into this sim
  1811. if (m_scenePresences.ContainsKey(agentID))
  1812. {
  1813. // Next we check for spoofing.....
  1814. LLUUID testSessionID = m_scenePresences[agentID].ControllingClient.SessionId;
  1815. if (sessionID == testSessionID)
  1816. {
  1817. if (sessionID == controllingClient.SessionId)
  1818. {
  1819. m_scenePresences[agentID].GrantGodlikePowers(agentID, testSessionID, token);
  1820. }
  1821. }
  1822. }
  1823. }
  1824. else
  1825. {
  1826. m_scenePresences[agentID].ControllingClient.SendAgentAlertMessage("Request for god powers denied", false);
  1827. }
  1828. }
  1829. /// <summary>
  1830. /// Sends a Big Blue Box message on the upper right of the screen to the client
  1831. /// for all agents in the region
  1832. /// </summary>
  1833. /// <param name="FromAvatarID">The person sending the message</param>
  1834. /// <param name="fromSessionID">The session of the person sending the message</param>
  1835. /// <param name="FromAvatarName">The name of the person doing the sending</param>
  1836. /// <param name="Message">The Message being sent to the user</param>
  1837. public void SendRegionMessageFromEstateTools(LLUUID FromAvatarID, LLUUID fromSessionID, String FromAvatarName, String Message)
  1838. {
  1839. List<ScenePresence> presenceList = GetScenePresences();
  1840. foreach (ScenePresence presence in presenceList)
  1841. {
  1842. if (!presence.IsChildAgent)
  1843. presence.ControllingClient.SendBlueBoxMessage(FromAvatarID, fromSessionID, FromAvatarName, Message);
  1844. }
  1845. }
  1846. /// <summary>
  1847. /// Sends a Big Blue Box message on the upper right of the screen to the client
  1848. /// for all agents in the estate
  1849. /// </summary>
  1850. /// <param name="FromAvatarID">The person sending the message</param>
  1851. /// <param name="fromSessionID">The session of the person sending the message</param>
  1852. /// <param name="FromAvatarName">The name of the person doing the sending</param>
  1853. /// <param name="Message">The Message being sent to the user</param>
  1854. public void SendEstateMessageFromEstateTools(LLUUID FromAvatarID, LLUUID fromSessionID, String FromAvatarName, String Message)
  1855. {
  1856. ClientManager.ForEachClient(delegate(IClientAPI controller)
  1857. {
  1858. controller.SendBlueBoxMessage(FromAvatarID, fromSessionID, FromAvatarName, Message);
  1859. }
  1860. );
  1861. }
  1862. /// <summary>
  1863. /// Kicks User specified from the simulator. This logs them off of the grid
  1864. /// If the client gets the UUID: 44e87126e7944ded05b37c42da3d5cdb it assumes
  1865. /// that you're kicking it even if the avatar's UUID isn't the UUID that the
  1866. /// agent is assigned
  1867. /// </summary>
  1868. /// <param name="godID">The person doing the kicking</param>
  1869. /// <param name="sessionID">The session of the person doing the kicking</param>
  1870. /// <param name="agentID">the person that is being kicked</param>
  1871. /// <param name="kickflags">This isn't used apparently</param>
  1872. /// <param name="reason">The message to send to the user after it's been turned into a field</param>
  1873. public void handleGodlikeKickUser(LLUUID godID, LLUUID sessionID, LLUUID agentID, uint kickflags, byte[] reason)
  1874. {
  1875. // For some reason the client sends this seemingly hard coded UUID for kicking everyone. Dun-know.
  1876. LLUUID kickUserID = new LLUUID("44e87126e7944ded05b37c42da3d5cdb");
  1877. if (m_scenePresences.ContainsKey(agentID) || agentID == kickUserID)
  1878. {
  1879. if (m_permissionManager.GenericEstatePermission(godID))
  1880. {
  1881. if (agentID == kickUserID)
  1882. {
  1883. ClientManager.ForEachClient(delegate(IClientAPI controller)
  1884. {
  1885. if (controller.AgentId != godID)
  1886. controller.Kick(Helpers.FieldToUTF8String(reason));
  1887. }
  1888. );
  1889. // This is a bit crude. It seems the client will be null before it actually stops the thread
  1890. // The thread will kill itself eventually :/
  1891. // Is there another way to make sure *all* clients get this 'inter region' message?
  1892. ClientManager.ForEachClient(delegate(IClientAPI controller)
  1893. {
  1894. ScenePresence p = GetScenePresence(controller.AgentId);
  1895. bool childagent = !p.Equals(null) && p.IsChildAgent;
  1896. if (controller.AgentId != godID && !childagent)
  1897. // Do we really want to kick the initiator of this madness?
  1898. {
  1899. controller.Close(true);
  1900. }
  1901. }
  1902. );
  1903. }
  1904. else
  1905. {
  1906. if (m_scenePresences[agentID].IsChildAgent)
  1907. {
  1908. m_innerScene.removeUserCount(false);
  1909. }
  1910. else
  1911. {
  1912. m_innerScene.removeUserCount(true);
  1913. }
  1914. m_scenePresences[agentID].ControllingClient.Kick(Helpers.FieldToUTF8String(reason));
  1915. m_scenePresences[agentID].ControllingClient.Close(true);
  1916. }
  1917. }
  1918. else
  1919. {
  1920. if (m_scenePresences.ContainsKey(godID))
  1921. m_scenePresences[godID].ControllingClient.SendAgentAlertMessage("Kick request denied", false);
  1922. }
  1923. }
  1924. }
  1925. public void HandleObjectPermissionsUpdate(IClientAPI controller, LLUUID agentID, LLUUID sessionID, byte field, uint localId, uint mask, byte set)
  1926. {
  1927. // Check for spoofing.. since this is permissions we're talking about here!
  1928. if ((controller.SessionId == sessionID) && (controller.AgentId == agentID))
  1929. {
  1930. // Tell the object to do permission update
  1931. SceneObjectGroup chObjectGroup = GetGroupByPrim(localId);
  1932. chObjectGroup.UpdatePermissions(agentID, field, localId, mask, set);
  1933. }
  1934. }
  1935. /// <summary>
  1936. ///
  1937. /// </summary>
  1938. /// <param name="firstName"></param>
  1939. /// <param name="lastName"></param>
  1940. /// <param name="message"></param>
  1941. /// <param name="modal"></param>
  1942. public void SendAlertToUser(string firstName, string lastName, string message, bool modal)
  1943. {
  1944. List<ScenePresence> presenceList = GetScenePresences();
  1945. foreach (ScenePresence presence in presenceList)
  1946. {
  1947. if ((presence.Firstname == firstName) && (presence.Lastname == lastName))
  1948. {
  1949. presence.ControllingClient.SendAgentAlertMessage(message, modal);
  1950. break;
  1951. }
  1952. }
  1953. }
  1954. /// <summary>
  1955. ///
  1956. /// </summary>
  1957. /// <param name="commandParams"></param>
  1958. public void HandleAlertCommand(string[] commandParams)
  1959. {
  1960. if (commandParams[0] == "general")
  1961. {
  1962. string message = CombineParams(commandParams, 1);
  1963. SendGeneralAlert(message);
  1964. }
  1965. else
  1966. {
  1967. string message = CombineParams(commandParams, 2);
  1968. SendAlertToUser(commandParams[0], commandParams[1], message, false);
  1969. }
  1970. }
  1971. private string CombineParams(string[] commandParams, int pos)
  1972. {
  1973. string result = String.Empty;
  1974. for (int i = pos; i < commandParams.Length; i++)
  1975. {
  1976. result += commandParams[i] + " ";
  1977. }
  1978. return result;
  1979. }
  1980. #endregion
  1981. /// <summary>
  1982. /// Causes all clients to get a full object update on all of the objects in the scene.
  1983. /// </summary>
  1984. public void ForceClientUpdate()
  1985. {
  1986. List<EntityBase> EntitieList = GetEntities();
  1987. foreach (EntityBase ent in EntitieList)
  1988. {
  1989. if (ent is SceneObjectGroup)
  1990. {
  1991. ((SceneObjectGroup)ent).ScheduleGroupForFullUpdate();
  1992. }
  1993. }
  1994. }
  1995. /// <summary>
  1996. /// This is currently only used for scale (to scale to MegaPrim size)
  1997. /// There is a console command that calls this in OpenSimMain
  1998. /// </summary>
  1999. /// <param name="cmdparams"></param>
  2000. public void HandleEditCommand(string[] cmdparams)
  2001. {
  2002. Console.WriteLine("Searching for Primitive: '" + cmdparams[0] + "'");
  2003. List<EntityBase> EntitieList = GetEntities();
  2004. foreach (EntityBase ent in EntitieList)
  2005. {
  2006. if (ent is SceneObjectGroup)
  2007. {
  2008. SceneObjectPart part = ((SceneObjectGroup)ent).GetChildPart(((SceneObjectGroup)ent).UUID);
  2009. if (part != null)
  2010. {
  2011. if (part.Name == cmdparams[0])
  2012. {
  2013. part.Resize(
  2014. new LLVector3(Convert.ToSingle(cmdparams[1]), Convert.ToSingle(cmdparams[2]),
  2015. Convert.ToSingle(cmdparams[3])));
  2016. Console.WriteLine("Edited scale of Primitive: " + part.Name);
  2017. }
  2018. }
  2019. }
  2020. }
  2021. }
  2022. /// <summary>
  2023. /// Shows various details about the sim based on the parameters supplied by the console command in openSimMain.
  2024. /// </summary>
  2025. /// <param name="showWhat"></param>
  2026. public void Show(string showWhat)
  2027. {
  2028. switch (showWhat)
  2029. {
  2030. case "users":
  2031. m_log.Error("Current Region: " + RegionInfo.RegionName);
  2032. m_log.ErrorFormat("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16}{5,-16}{6,-16}", "Firstname", "Lastname",
  2033. "Agent ID", "Session ID", "Circuit", "IP", "World");
  2034. foreach (ScenePresence scenePrescence in GetAvatars())
  2035. {
  2036. m_log.ErrorFormat("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16},{5,-16}{6,-16}",
  2037. scenePrescence.Firstname,
  2038. scenePrescence.Lastname,
  2039. scenePrescence.UUID,
  2040. scenePrescence.ControllingClient.AgentId,
  2041. "Unknown",
  2042. "Unknown",
  2043. RegionInfo.RegionName);
  2044. }
  2045. break;
  2046. case "modules":
  2047. m_log.Error("The currently loaded modules in " + RegionInfo.RegionName + " are:");
  2048. foreach (IRegionModule module in Modules.Values)
  2049. {
  2050. if (!module.IsSharedModule)
  2051. {
  2052. m_log.Error("Region Module: " + module.Name);
  2053. }
  2054. }
  2055. break;
  2056. }
  2057. }
  2058. #endregion
  2059. #region Script Handling Methods
  2060. /// <summary>
  2061. /// Console command handler to send script command to script engine.
  2062. /// </summary>
  2063. /// <param name="args"></param>
  2064. public void SendCommandToPlugins(string[] args)
  2065. {
  2066. m_eventManager.TriggerOnPluginConsole(args);
  2067. }
  2068. public double GetLandHeight(int x, int y)
  2069. {
  2070. return Terrain.GetHeight(x, y);
  2071. }
  2072. public LLUUID GetLandOwner(float x, float y)
  2073. {
  2074. Land land = LandManager.getLandObject(x, y);
  2075. if (land == null)
  2076. {
  2077. return LLUUID.Zero;
  2078. }
  2079. else
  2080. {
  2081. return land.landData.ownerID;
  2082. }
  2083. }
  2084. public LandData GetLandData(float x, float y)
  2085. {
  2086. return LandManager.getLandObject(x, y).landData;
  2087. }
  2088. public void SetLandMusicURL(float x, float y, string url)
  2089. {
  2090. Land land = LandManager.getLandObject(x, y);
  2091. if (land == null)
  2092. {
  2093. return;
  2094. }
  2095. else
  2096. {
  2097. land.landData.musicURL = url;
  2098. return;
  2099. }
  2100. }
  2101. #endregion
  2102. #region Script Engine
  2103. private List<ScriptEngineInterface> ScriptEngines = new List<ScriptEngineInterface>();
  2104. private bool m_dumpAssetsToFile;
  2105. /// <summary>
  2106. ///
  2107. /// </summary>
  2108. /// <param name="scriptEngine"></param>
  2109. public void AddScriptEngine(ScriptEngineInterface scriptEngine)
  2110. {
  2111. ScriptEngines.Add(scriptEngine);
  2112. scriptEngine.InitializeEngine(this);
  2113. }
  2114. public void TriggerObjectChanged(uint localID, uint change)
  2115. {
  2116. m_eventManager.TriggerOnScriptChangedEvent(localID, change);
  2117. }
  2118. #endregion
  2119. #region InnerScene wrapper methods
  2120. /// <summary>
  2121. ///
  2122. /// </summary>
  2123. /// <param name="localID"></param>
  2124. /// <returns></returns>
  2125. public LLUUID ConvertLocalIDToFullID(uint localID)
  2126. {
  2127. return m_innerScene.ConvertLocalIDToFullID(localID);
  2128. }
  2129. public void SwapRootAgentCount(bool rootChildChildRootTF)
  2130. {
  2131. m_innerScene.SwapRootChildAgent(rootChildChildRootTF);
  2132. }
  2133. public void AddPhysicalPrim(int num)
  2134. {
  2135. m_innerScene.AddPhysicalPrim(num);
  2136. }
  2137. public void RemovePhysicalPrim(int num)
  2138. {
  2139. m_innerScene.RemovePhysicalPrim(num);
  2140. }
  2141. /// <summary>
  2142. ///
  2143. /// </summary>
  2144. /// <param name="presence"></param>
  2145. public void SendAllSceneObjectsToClient(ScenePresence presence)
  2146. {
  2147. m_innerScene.SendAllSceneObjectsToClient(presence);
  2148. }
  2149. //The idea is to have a group of method that return a list of avatars meeting some requirement
  2150. // ie it could be all m_scenePresences within a certain range of the calling prim/avatar.
  2151. /// <summary>
  2152. ///
  2153. /// </summary>
  2154. /// <returns></returns>
  2155. public List<ScenePresence> GetAvatars()
  2156. {
  2157. return m_innerScene.GetAvatars();
  2158. }
  2159. /// <summary>
  2160. /// Request a List of all m_scenePresences in this World
  2161. /// </summary>
  2162. /// <returns></returns>
  2163. public List<ScenePresence> GetScenePresences()
  2164. {
  2165. return m_innerScene.GetScenePresences();
  2166. }
  2167. /// <summary>
  2168. /// Request a filtered list of m_scenePresences in this World
  2169. /// </summary>
  2170. /// <param name="filter"></param>
  2171. /// <returns></returns>
  2172. public List<ScenePresence> GetScenePresences(FilterAvatarList filter)
  2173. {
  2174. return m_innerScene.GetScenePresences(filter);
  2175. }
  2176. /// <summary>
  2177. /// Request a Avatar by UUID
  2178. /// </summary>
  2179. /// <param name="avatarID"></param>
  2180. /// <returns></returns>
  2181. public ScenePresence GetScenePresence(LLUUID avatarID)
  2182. {
  2183. return m_innerScene.GetScenePresence(avatarID);
  2184. }
  2185. /// <summary>
  2186. /// Request an Avatar's Child Status - used by ClientView when a 'kick everyone' or 'estate message' occurs
  2187. /// </summary>
  2188. /// <param name="avatarID">AvatarID to lookup</param>
  2189. /// <returns></returns>
  2190. public override bool PresenceChildStatus(LLUUID avatarID)
  2191. {
  2192. ScenePresence cp = GetScenePresence(avatarID);
  2193. return cp.IsChildAgent;
  2194. }
  2195. /// <summary>
  2196. ///
  2197. /// </summary>
  2198. /// <param name="action"></param>
  2199. public void ForEachScenePresence(Action<ScenePresence> action)
  2200. {
  2201. // We don't want to try to send messages if there are no avatar.
  2202. if (!(m_scenePresences.Equals(null)))
  2203. {
  2204. try
  2205. {
  2206. List<ScenePresence> presenceList = GetScenePresences();
  2207. foreach (ScenePresence presence in presenceList)
  2208. {
  2209. action(presence);
  2210. }
  2211. }
  2212. catch (Exception e)
  2213. {
  2214. m_log.Info("[BUG]: " + e.ToString());
  2215. }
  2216. }
  2217. }
  2218. /// <summary>
  2219. ///
  2220. /// </summary>
  2221. /// <param name="action"></param>
  2222. // public void ForEachObject(Action<SceneObjectGroup> action)
  2223. // {
  2224. // List<SceneObjectGroup> presenceList;
  2225. //
  2226. // lock (m_sceneObjects)
  2227. // {
  2228. // presenceList = new List<SceneObjectGroup>(m_sceneObjects.Values);
  2229. // }
  2230. //
  2231. // foreach (SceneObjectGroup presence in presenceList)
  2232. // {
  2233. // action(presence);
  2234. // }
  2235. // }
  2236. /// <summary>
  2237. ///
  2238. /// </summary>
  2239. /// <param name="localID"></param>
  2240. /// <returns></returns>
  2241. public SceneObjectPart GetSceneObjectPart(uint localID)
  2242. {
  2243. return m_innerScene.GetSceneObjectPart(localID);
  2244. }
  2245. /// <summary>
  2246. ///
  2247. /// </summary>
  2248. /// <param name="fullID"></param>
  2249. /// <returns></returns>
  2250. public SceneObjectPart GetSceneObjectPart(LLUUID fullID)
  2251. {
  2252. return m_innerScene.GetSceneObjectPart(fullID);
  2253. }
  2254. internal bool TryGetAvatar(LLUUID avatarId, out ScenePresence avatar)
  2255. {
  2256. return m_innerScene.TryGetAvatar(avatarId, out avatar);
  2257. }
  2258. internal bool TryGetAvatarByName(string avatarName, out ScenePresence avatar)
  2259. {
  2260. return m_innerScene.TryGetAvatarByName(avatarName, out avatar);
  2261. }
  2262. internal void ForEachClient(Action<IClientAPI> action)
  2263. {
  2264. m_innerScene.ForEachClient(action);
  2265. }
  2266. public List<EntityBase> GetEntities()
  2267. {
  2268. return m_innerScene.GetEntities();
  2269. }
  2270. #endregion
  2271. #region BaseHTTPServer wrapper methods
  2272. public bool AddHTTPHandler(string method, GenericHTTPMethod handler)
  2273. {
  2274. return m_httpListener.AddHTTPHandler(method, handler);
  2275. }
  2276. public bool AddXmlRPCHandler(string method, XmlRpcMethod handler)
  2277. {
  2278. return m_httpListener.AddXmlRPCHandler(method, handler);
  2279. }
  2280. public void AddStreamHandler(IRequestHandler handler)
  2281. {
  2282. m_httpListener.AddStreamHandler(handler);
  2283. }
  2284. public void RemoveStreamHandler(string httpMethod, string path)
  2285. {
  2286. m_httpListener.RemoveStreamHandler(httpMethod, path);
  2287. }
  2288. public void RemoveHTTPHandler(string httpMethod, string path)
  2289. {
  2290. m_httpListener.RemoveHTTPHandler(httpMethod, path);
  2291. }
  2292. #endregion
  2293. }
  2294. }