PageRenderTime 78ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/OpenSim/Region/Framework/Scenes/Scene.cs

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