PageRenderTime 52ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/OpenSim/Region/Framework/Scenes/SceneGraph.cs

https://bitbucket.org/VirtualReality/taiga
C# | 1952 lines | 1260 code | 236 blank | 456 comment | 228 complexity | 3a5d82e7eb645804ec9b97ce391ee359 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the 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.Threading;
  29. using System.Collections.Generic;
  30. using System.Reflection;
  31. using OpenMetaverse;
  32. using OpenMetaverse.Packets;
  33. using log4net;
  34. using OpenSim.Framework;
  35. using OpenSim.Region.Framework.Scenes.Types;
  36. using OpenSim.Region.Physics.Manager;
  37. namespace OpenSim.Region.Framework.Scenes
  38. {
  39. public delegate void PhysicsCrash();
  40. public delegate void ObjectDuplicateDelegate(EntityBase original, EntityBase clone);
  41. public delegate void ObjectCreateDelegate(EntityBase obj);
  42. public delegate void ObjectDeleteDelegate(EntityBase obj);
  43. /// <summary>
  44. /// This class used to be called InnerScene and may not yet truly be a SceneGraph. The non scene graph components
  45. /// should be migrated out over time.
  46. /// </summary>
  47. public class SceneGraph
  48. {
  49. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  50. #region Events
  51. protected internal event PhysicsCrash UnRecoverableError;
  52. private PhysicsCrash handlerPhysicsCrash = null;
  53. public event ObjectDuplicateDelegate OnObjectDuplicate;
  54. public event ObjectCreateDelegate OnObjectCreate;
  55. public event ObjectDeleteDelegate OnObjectRemove;
  56. #endregion
  57. #region Fields
  58. protected Dictionary<UUID, ScenePresence> m_scenePresences = new Dictionary<UUID, ScenePresence>();
  59. protected ScenePresence[] m_scenePresenceArray = new ScenePresence[0];
  60. // SceneObjects is not currently populated or used.
  61. //public Dictionary<UUID, SceneObjectGroup> SceneObjects;
  62. protected internal EntityManager Entities = new EntityManager();
  63. // protected internal Dictionary<UUID, EntityBase> Entities = new Dictionary<UUID, EntityBase>();
  64. protected internal Dictionary<UUID, ScenePresence> RestorePresences = new Dictionary<UUID, ScenePresence>();
  65. protected internal BasicQuadTreeNode QuadTree;
  66. protected RegionInfo m_regInfo;
  67. protected Scene m_parentScene;
  68. protected Dictionary<UUID, SceneObjectGroup> m_updateList = new Dictionary<UUID, SceneObjectGroup>();
  69. protected int m_numRootAgents = 0;
  70. protected int m_numPrim = 0;
  71. protected int m_numChildAgents = 0;
  72. protected int m_physicalPrim = 0;
  73. protected int m_activeScripts = 0;
  74. protected int m_scriptLPS = 0;
  75. protected internal object m_syncRoot = new object();
  76. protected internal PhysicsScene _PhyScene;
  77. protected internal Dictionary<uint, SceneObjectGroup> SceneObjectGroupsByLocalID = new Dictionary<uint, SceneObjectGroup>();
  78. protected internal Dictionary<UUID, SceneObjectGroup> SceneObjectGroupsByFullID = new Dictionary<UUID, SceneObjectGroup>();
  79. private readonly Object m_dictionary_lock = new Object();
  80. private Object m_updateLock = new Object();
  81. #endregion
  82. protected internal SceneGraph(Scene parent, RegionInfo regInfo)
  83. {
  84. m_parentScene = parent;
  85. m_regInfo = regInfo;
  86. QuadTree = new BasicQuadTreeNode(null, "/0/", 0, 0, (short)Constants.RegionSize, (short)Constants.RegionSize);
  87. QuadTree.Subdivide();
  88. QuadTree.Subdivide();
  89. }
  90. public PhysicsScene PhysicsScene
  91. {
  92. get { return _PhyScene; }
  93. set
  94. {
  95. // If we're not doing the initial set
  96. // Then we've got to remove the previous
  97. // event handler
  98. if (_PhyScene != null)
  99. _PhyScene.OnPhysicsCrash -= physicsBasedCrash;
  100. _PhyScene = value;
  101. if (_PhyScene != null)
  102. _PhyScene.OnPhysicsCrash += physicsBasedCrash;
  103. }
  104. }
  105. protected internal void Close()
  106. {
  107. lock (m_scenePresences)
  108. {
  109. m_scenePresences.Clear();
  110. m_scenePresenceArray = new ScenePresence[0];
  111. }
  112. lock (m_dictionary_lock)
  113. {
  114. SceneObjectGroupsByFullID.Clear();
  115. SceneObjectGroupsByLocalID.Clear();
  116. }
  117. Entities.Clear();
  118. }
  119. #region Update Methods
  120. protected internal void UpdatePreparePhysics()
  121. {
  122. // If we are using a threaded physics engine
  123. // grab the latest scene from the engine before
  124. // trying to process it.
  125. // PhysX does this (runs in the background).
  126. if (_PhyScene.IsThreaded)
  127. {
  128. _PhyScene.GetResults();
  129. }
  130. }
  131. protected internal void UpdatePresences()
  132. {
  133. ScenePresence[] updateScenePresences = GetScenePresences();
  134. for (int i = 0; i < updateScenePresences.Length; i++)
  135. updateScenePresences[i].Update();
  136. }
  137. protected internal float UpdatePhysics(double elapsed)
  138. {
  139. lock (m_syncRoot)
  140. {
  141. // Here is where the Scene calls the PhysicsScene. This is a one-way
  142. // interaction; the PhysicsScene cannot access the calling Scene directly.
  143. // But with joints, we want a PhysicsActor to be able to influence a
  144. // non-physics SceneObjectPart. In particular, a PhysicsActor that is connected
  145. // with a joint should be able to move the SceneObjectPart which is the visual
  146. // representation of that joint (for editing and serialization purposes).
  147. // However the PhysicsActor normally cannot directly influence anything outside
  148. // of the PhysicsScene, and the non-physical SceneObjectPart which represents
  149. // the joint in the Scene does not exist in the PhysicsScene.
  150. //
  151. // To solve this, we have an event in the PhysicsScene that is fired when a joint
  152. // has changed position (because one of its associated PhysicsActors has changed
  153. // position).
  154. //
  155. // Therefore, JointMoved and JointDeactivated events will be fired as a result of the following Simulate().
  156. return _PhyScene.Simulate((float)elapsed);
  157. }
  158. }
  159. protected internal void UpdateScenePresenceMovement()
  160. {
  161. ScenePresence[] moveEntities = GetScenePresences();
  162. for (int i = 0; i < moveEntities.Length; i++)
  163. moveEntities[i].UpdateMovement();
  164. }
  165. #endregion
  166. #region Entity Methods
  167. /// <summary>
  168. /// Add an object into the scene that has come from storage
  169. /// </summary>
  170. /// <param name="sceneObject"></param>
  171. /// <param name="attachToBackup">
  172. /// If true, changes to the object will be reflected in its persisted data
  173. /// If false, the persisted data will not be changed even if the object in the scene is changed
  174. /// </param>
  175. /// <param name="alreadyPersisted">
  176. /// If true, we won't persist this object until it changes
  177. /// If false, we'll persist this object immediately
  178. /// </param>
  179. /// <returns>
  180. /// true if the object was added, false if an object with the same uuid was already in the scene
  181. /// </returns>
  182. protected internal bool AddRestoredSceneObject(
  183. SceneObjectGroup sceneObject, bool attachToBackup, bool alreadyPersisted)
  184. {
  185. if (!alreadyPersisted)
  186. {
  187. sceneObject.ForceInventoryPersistence();
  188. sceneObject.HasGroupChanged = true;
  189. }
  190. return AddSceneObject(sceneObject, attachToBackup, true);
  191. }
  192. /// <summary>
  193. /// Add a newly created object to the scene. This will both update the scene, and send information about the
  194. /// new object to all clients interested in the scene.
  195. /// </summary>
  196. /// <param name="sceneObject"></param>
  197. /// <param name="attachToBackup">
  198. /// If true, the object is made persistent into the scene.
  199. /// If false, the object will not persist over server restarts
  200. /// </param>
  201. /// <returns>
  202. /// true if the object was added, false if an object with the same uuid was already in the scene
  203. /// </returns>
  204. protected internal bool AddNewSceneObject(SceneObjectGroup sceneObject, bool attachToBackup, bool sendClientUpdates)
  205. {
  206. // Ensure that we persist this new scene object
  207. sceneObject.HasGroupChanged = true;
  208. return AddSceneObject(sceneObject, attachToBackup, sendClientUpdates);
  209. }
  210. /// <summary>
  211. /// Add an object to the scene. This will both update the scene, and send information about the
  212. /// new object to all clients interested in the scene.
  213. /// </summary>
  214. /// <param name="sceneObject"></param>
  215. /// <param name="attachToBackup">
  216. /// If true, the object is made persistent into the scene.
  217. /// If false, the object will not persist over server restarts
  218. /// </param>
  219. /// <param name="sendClientUpdates">
  220. /// If true, updates for the new scene object are sent to all viewers in range.
  221. /// If false, it is left to the caller to schedule the update
  222. /// </param>
  223. /// <returns>
  224. /// true if the object was added, false if an object with the same uuid was already in the scene
  225. /// </returns>
  226. protected bool AddSceneObject(SceneObjectGroup sceneObject, bool attachToBackup, bool sendClientUpdates)
  227. {
  228. if (sceneObject == null || sceneObject.RootPart == null || sceneObject.RootPart.UUID == UUID.Zero)
  229. return false;
  230. bool alreadyExisted = false;
  231. if (m_parentScene.m_clampPrimSize)
  232. {
  233. foreach (SceneObjectPart part in sceneObject.Children.Values)
  234. {
  235. Vector3 scale = part.Shape.Scale;
  236. if (scale.X > m_parentScene.m_maxNonphys)
  237. scale.X = m_parentScene.m_maxNonphys;
  238. if (scale.Y > m_parentScene.m_maxNonphys)
  239. scale.Y = m_parentScene.m_maxNonphys;
  240. if (scale.Z > m_parentScene.m_maxNonphys)
  241. scale.Z = m_parentScene.m_maxNonphys;
  242. part.Shape.Scale = scale;
  243. }
  244. }
  245. sceneObject.AttachToScene(m_parentScene);
  246. if (sendClientUpdates)
  247. sceneObject.ScheduleGroupForFullUpdate();
  248. lock (sceneObject)
  249. {
  250. if (!Entities.ContainsKey(sceneObject.UUID))
  251. {
  252. Entities.Add(sceneObject);
  253. m_numPrim += sceneObject.Children.Count;
  254. if (attachToBackup)
  255. sceneObject.AttachToBackup();
  256. if (OnObjectCreate != null)
  257. OnObjectCreate(sceneObject);
  258. lock (m_dictionary_lock)
  259. {
  260. SceneObjectGroupsByFullID[sceneObject.UUID] = sceneObject;
  261. SceneObjectGroupsByLocalID[sceneObject.LocalId] = sceneObject;
  262. foreach (SceneObjectPart part in sceneObject.Children.Values)
  263. {
  264. SceneObjectGroupsByFullID[part.UUID] = sceneObject;
  265. SceneObjectGroupsByLocalID[part.LocalId] = sceneObject;
  266. }
  267. }
  268. }
  269. else
  270. {
  271. alreadyExisted = true;
  272. }
  273. }
  274. return alreadyExisted;
  275. }
  276. /// <summary>
  277. /// Delete an object from the scene
  278. /// </summary>
  279. /// <returns>true if the object was deleted, false if there was no object to delete</returns>
  280. public bool DeleteSceneObject(UUID uuid, bool resultOfObjectLinked)
  281. {
  282. if (Entities.ContainsKey(uuid))
  283. {
  284. if (!resultOfObjectLinked)
  285. {
  286. m_numPrim -= ((SceneObjectGroup) Entities[uuid]).Children.Count;
  287. if ((((SceneObjectGroup)Entities[uuid]).RootPart.Flags & PrimFlags.Physics) == PrimFlags.Physics)
  288. {
  289. RemovePhysicalPrim(((SceneObjectGroup)Entities[uuid]).Children.Count);
  290. }
  291. }
  292. if (OnObjectRemove != null)
  293. OnObjectRemove(Entities[uuid]);
  294. lock (m_dictionary_lock)
  295. {
  296. SceneObjectGroupsByFullID.Remove(uuid);
  297. SceneObjectGroupsByLocalID.Remove(((SceneObjectGroup)Entities[uuid]).LocalId);
  298. }
  299. Entities.Remove(uuid);
  300. //SceneObjectGroup part;
  301. //((part.RootPart.Flags & PrimFlags.Physics) == PrimFlags.Physics)
  302. return true;
  303. }
  304. return false;
  305. }
  306. /// <summary>
  307. /// Add an object to the list of prims to process on the next update
  308. /// </summary>
  309. /// <param name="obj">
  310. /// A <see cref="SceneObjectGroup"/>
  311. /// </param>
  312. protected internal void AddToUpdateList(SceneObjectGroup obj)
  313. {
  314. lock (m_updateList)
  315. {
  316. m_updateList[obj.UUID] = obj;
  317. }
  318. }
  319. /// <summary>
  320. /// Process all pending updates
  321. /// </summary>
  322. protected internal void UpdateObjectGroups()
  323. {
  324. if (!Monitor.TryEnter(m_updateLock))
  325. return;
  326. List<SceneObjectGroup> updates;
  327. // Some updates add more updates to the updateList.
  328. // Get the current list of updates and clear the list before iterating
  329. lock (m_updateList)
  330. {
  331. updates = new List<SceneObjectGroup>(m_updateList.Values);
  332. m_updateList.Clear();
  333. }
  334. // Go through all updates
  335. for (int i = 0; i < updates.Count; i++)
  336. {
  337. SceneObjectGroup sog = updates[i];
  338. // Don't abort the whole update if one entity happens to give us an exception.
  339. try
  340. {
  341. sog.Update();
  342. }
  343. catch (Exception e)
  344. {
  345. m_log.ErrorFormat(
  346. "[INNER SCENE]: Failed to update {0}, {1} - {2}", sog.Name, sog.UUID, e);
  347. }
  348. }
  349. Monitor.Exit(m_updateLock);
  350. }
  351. protected internal void AddPhysicalPrim(int number)
  352. {
  353. m_physicalPrim++;
  354. }
  355. protected internal void RemovePhysicalPrim(int number)
  356. {
  357. m_physicalPrim--;
  358. }
  359. protected internal void AddToScriptLPS(int number)
  360. {
  361. m_scriptLPS += number;
  362. }
  363. protected internal void AddActiveScripts(int number)
  364. {
  365. m_activeScripts += number;
  366. }
  367. public void DropObject(uint objectLocalID, IClientAPI remoteClient)
  368. {
  369. SceneObjectGroup group = GetGroupByPrim(objectLocalID);
  370. if (group != null)
  371. {
  372. m_parentScene.DetachSingleAttachmentToGround(group.UUID, remoteClient);
  373. }
  374. }
  375. protected internal void DetachObject(uint objectLocalID, IClientAPI remoteClient)
  376. {
  377. SceneObjectGroup group = GetGroupByPrim(objectLocalID);
  378. if (group != null)
  379. {
  380. //group.DetachToGround();
  381. m_parentScene.DetachSingleAttachmentToInv(group.GetFromItemID(), remoteClient);
  382. }
  383. }
  384. protected internal void HandleUndo(IClientAPI remoteClient, UUID primId)
  385. {
  386. if (primId != UUID.Zero)
  387. {
  388. SceneObjectPart part = m_parentScene.GetSceneObjectPart(primId);
  389. if (part != null)
  390. part.Undo();
  391. }
  392. }
  393. protected internal void HandleRedo(IClientAPI remoteClient, UUID primId)
  394. {
  395. if (primId != UUID.Zero)
  396. {
  397. SceneObjectPart part = m_parentScene.GetSceneObjectPart(primId);
  398. if (part != null)
  399. part.Redo();
  400. }
  401. }
  402. protected internal void HandleObjectGroupUpdate(
  403. IClientAPI remoteClient, UUID GroupID, uint objectLocalID, UUID Garbage)
  404. {
  405. SceneObjectGroup group = GetGroupByPrim(objectLocalID);
  406. if (group != null)
  407. {
  408. if (group.OwnerID == remoteClient.AgentId)
  409. group.SetGroup(GroupID, remoteClient);
  410. }
  411. }
  412. /// <summary>
  413. /// Event Handling routine for Attach Object
  414. /// </summary>
  415. /// <param name="remoteClient"></param>
  416. /// <param name="objectLocalID"></param>
  417. /// <param name="AttachmentPt"></param>
  418. /// <param name="rot"></param>
  419. protected internal void AttachObject(IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, Quaternion rot, bool silent)
  420. {
  421. // If we can't take it, we can't attach it!
  422. SceneObjectPart part = m_parentScene.GetSceneObjectPart(objectLocalID);
  423. if (part == null)
  424. return;
  425. if (!m_parentScene.Permissions.CanTakeObject(part.UUID, remoteClient.AgentId))
  426. return;
  427. // Calls attach with a Zero position
  428. if (AttachObject(remoteClient, objectLocalID, AttachmentPt, rot, Vector3.Zero, false))
  429. {
  430. m_parentScene.SendAttachEvent(objectLocalID, part.ParentGroup.GetFromItemID(), remoteClient.AgentId);
  431. // Save avatar attachment information
  432. ScenePresence presence;
  433. if (m_parentScene.AvatarFactory != null && m_parentScene.TryGetAvatar(remoteClient.AgentId, out presence))
  434. {
  435. m_log.Info(
  436. "[SCENE]: Saving avatar attachment. AgentID: " + remoteClient.AgentId
  437. + ", AttachmentPoint: " + AttachmentPt);
  438. m_parentScene.AvatarFactory.UpdateDatabase(remoteClient.AgentId, presence.Appearance);
  439. }
  440. }
  441. }
  442. /// <summary>
  443. /// Rez an attachment
  444. /// </summary>
  445. /// <param name="remoteClient"></param>
  446. /// <param name="itemID"></param>
  447. /// <param name="AttachmentPt"></param>
  448. /// <returns>The scene object that was attached. Null if the scene object could not be found</returns>
  449. public SceneObjectGroup RezSingleAttachment(IClientAPI remoteClient, UUID itemID, uint AttachmentPt)
  450. {
  451. SceneObjectGroup objatt = m_parentScene.RezObject(remoteClient,
  452. itemID, Vector3.Zero, Vector3.Zero, UUID.Zero, (byte)1, true,
  453. false, false, remoteClient.AgentId, true);
  454. // m_log.DebugFormat(
  455. // "[SCENE GRAPH]: Retrieved single object {0} for attachment to {1} on point {2}",
  456. // objatt.Name, remoteClient.Name, AttachmentPt);
  457. if (objatt != null)
  458. {
  459. bool tainted = false;
  460. if (AttachmentPt != 0 && AttachmentPt != objatt.GetAttachmentPoint())
  461. tainted = true;
  462. AttachObject(remoteClient, objatt.LocalId, AttachmentPt, Quaternion.Identity, objatt.AbsolutePosition, false);
  463. //objatt.ScheduleGroupForFullUpdate();
  464. if (tainted)
  465. objatt.HasGroupChanged = true;
  466. // Fire after attach, so we don't get messy perms dialogs
  467. // 3 == AttachedRez
  468. objatt.CreateScriptInstances(0, true, m_parentScene.DefaultScriptEngine, 3);
  469. // Do this last so that event listeners have access to all the effects of the attachment
  470. m_parentScene.EventManager.TriggerOnAttach(objatt.LocalId, itemID, remoteClient.AgentId);
  471. }
  472. else
  473. {
  474. m_log.WarnFormat(
  475. "[SCENE GRAPH]: Could not retrieve item {0} for attaching to avatar {1} at point {2}",
  476. itemID, remoteClient.Name, AttachmentPt);
  477. }
  478. return objatt;
  479. }
  480. // What makes this method odd and unique is it tries to detach using an UUID.... Yay for standards.
  481. // To LocalId or UUID, *THAT* is the question. How now Brown UUID??
  482. public void DetachSingleAttachmentToInv(UUID itemID, IClientAPI remoteClient)
  483. {
  484. if (itemID == UUID.Zero) // If this happened, someone made a mistake....
  485. return;
  486. // We can NOT use the dictionries here, as we are looking
  487. // for an entity by the fromAssetID, which is NOT the prim UUID
  488. //
  489. List<EntityBase> detachEntities = GetEntities();
  490. SceneObjectGroup group;
  491. foreach (EntityBase entity in detachEntities)
  492. {
  493. if (entity is SceneObjectGroup)
  494. {
  495. group = (SceneObjectGroup)entity;
  496. if (group.GetFromItemID() == itemID)
  497. {
  498. m_parentScene.SendAttachEvent(group.LocalId, itemID, UUID.Zero);
  499. group.DetachToInventoryPrep();
  500. m_log.Debug("[DETACH]: Saving attachpoint: " +
  501. ((uint)group.GetAttachmentPoint()).ToString());
  502. m_parentScene.UpdateKnownItem(remoteClient, group,
  503. group.GetFromItemID(), group.OwnerID);
  504. m_parentScene.DeleteSceneObject(group, false);
  505. return;
  506. }
  507. }
  508. }
  509. }
  510. /// <summary>
  511. /// Attach a scene object to an avatar.
  512. /// </summary>
  513. /// <param name="remoteClient"></param>
  514. /// <param name="objectLocalID"></param>
  515. /// <param name="AttachmentPt"></param>
  516. /// <param name="rot"></param>
  517. /// <param name="attachPos"></param>
  518. /// <param name="silent"></param>
  519. /// <returns>true if the attachment was successful, false otherwise</returns>
  520. protected internal bool AttachObject(
  521. IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, Quaternion rot, Vector3 attachPos, bool silent)
  522. {
  523. SceneObjectGroup group = GetGroupByPrim(objectLocalID);
  524. if (group != null)
  525. {
  526. if (m_parentScene.Permissions.CanTakeObject(group.UUID, remoteClient.AgentId))
  527. {
  528. // If the attachment point isn't the same as the one previously used
  529. // set it's offset position = 0 so that it appears on the attachment point
  530. // and not in a weird location somewhere unknown.
  531. if (AttachmentPt != 0 && AttachmentPt != (uint)group.GetAttachmentPoint())
  532. {
  533. attachPos = Vector3.Zero;
  534. }
  535. // AttachmentPt 0 means the client chose to 'wear' the attachment.
  536. if (AttachmentPt == 0)
  537. {
  538. // Check object for stored attachment point
  539. AttachmentPt = (uint)group.GetAttachmentPoint();
  540. }
  541. // if we still didn't find a suitable attachment point.......
  542. if (AttachmentPt == 0)
  543. {
  544. // Stick it on left hand with Zero Offset from the attachment point.
  545. AttachmentPt = (uint)AttachmentPoint.LeftHand;
  546. attachPos = Vector3.Zero;
  547. }
  548. group.SetAttachmentPoint((byte)AttachmentPt);
  549. group.AbsolutePosition = attachPos;
  550. // Saves and gets itemID
  551. UUID itemId;
  552. if (group.GetFromItemID() == UUID.Zero)
  553. {
  554. m_parentScene.attachObjectAssetStore(remoteClient, group, remoteClient.AgentId, out itemId);
  555. }
  556. else
  557. {
  558. itemId = group.GetFromItemID();
  559. }
  560. m_parentScene.AttachObject(remoteClient, AttachmentPt, itemId, group);
  561. group.AttachToAgent(remoteClient.AgentId, AttachmentPt, attachPos, silent);
  562. // In case it is later dropped again, don't let
  563. // it get cleaned up
  564. //
  565. group.RootPart.RemFlag(PrimFlags.TemporaryOnRez);
  566. group.HasGroupChanged = false;
  567. }
  568. else
  569. {
  570. remoteClient.SendAgentAlertMessage("You don't have sufficient permissions to attach this object", false);
  571. return false;
  572. }
  573. }
  574. else
  575. {
  576. m_log.DebugFormat("[SCENE GRAPH]: AttachObject found no such scene object {0}", objectLocalID);
  577. return false;
  578. }
  579. return true;
  580. }
  581. protected internal ScenePresence CreateAndAddChildScenePresence(IClientAPI client, AvatarAppearance appearance)
  582. {
  583. ScenePresence newAvatar = null;
  584. newAvatar = new ScenePresence(client, m_parentScene, m_regInfo, appearance);
  585. newAvatar.IsChildAgent = true;
  586. AddScenePresence(newAvatar);
  587. return newAvatar;
  588. }
  589. /// <summary>
  590. /// Add a presence to the scene
  591. /// </summary>
  592. /// <param name="presence"></param>
  593. protected internal void AddScenePresence(ScenePresence presence)
  594. {
  595. bool child = presence.IsChildAgent;
  596. if (child)
  597. {
  598. m_numChildAgents++;
  599. }
  600. else
  601. {
  602. m_numRootAgents++;
  603. presence.AddToPhysicalScene(false);
  604. }
  605. Entities[presence.UUID] = presence;
  606. lock (m_scenePresences)
  607. {
  608. if (!m_scenePresences.ContainsKey(presence.UUID))
  609. {
  610. m_scenePresences.Add(presence.UUID, presence);
  611. // Create a new array of ScenePresence references
  612. int oldLength = m_scenePresenceArray.Length;
  613. ScenePresence[] newArray = new ScenePresence[oldLength + 1];
  614. Array.Copy(m_scenePresenceArray, newArray, oldLength);
  615. newArray[oldLength] = presence;
  616. m_scenePresenceArray = newArray;
  617. }
  618. else
  619. {
  620. m_scenePresences[presence.UUID] = presence;
  621. // Do a linear search through the array of ScenePresence references
  622. // and update the modified entry
  623. for (int i = 0; i < m_scenePresenceArray.Length; i++)
  624. {
  625. if (m_scenePresenceArray[i].UUID == presence.UUID)
  626. {
  627. m_scenePresenceArray[i] = presence;
  628. break;
  629. }
  630. }
  631. }
  632. }
  633. }
  634. /// <summary>
  635. /// Remove a presence from the scene
  636. /// </summary>
  637. protected internal void RemoveScenePresence(UUID agentID)
  638. {
  639. if (!Entities.Remove(agentID))
  640. {
  641. m_log.WarnFormat(
  642. "[SCENE] Tried to remove non-existent scene presence with agent ID {0} from scene Entities list",
  643. agentID);
  644. }
  645. lock (m_scenePresences)
  646. {
  647. if (m_scenePresences.Remove(agentID))
  648. {
  649. // Copy all of the elements from the previous array
  650. // into the new array except the removed element
  651. int oldLength = m_scenePresenceArray.Length;
  652. ScenePresence[] newArray = new ScenePresence[oldLength - 1];
  653. int j = 0;
  654. for (int i = 0; i < m_scenePresenceArray.Length; i++)
  655. {
  656. ScenePresence presence = m_scenePresenceArray[i];
  657. if (presence.UUID != agentID)
  658. {
  659. newArray[j] = presence;
  660. ++j;
  661. }
  662. }
  663. m_scenePresenceArray = newArray;
  664. }
  665. else
  666. {
  667. m_log.WarnFormat("[SCENE] Tried to remove non-existent scene presence with agent ID {0} from scene ScenePresences list", agentID);
  668. }
  669. }
  670. }
  671. protected internal void SwapRootChildAgent(bool direction_RC_CR_T_F)
  672. {
  673. if (direction_RC_CR_T_F)
  674. {
  675. m_numRootAgents--;
  676. m_numChildAgents++;
  677. }
  678. else
  679. {
  680. m_numChildAgents--;
  681. m_numRootAgents++;
  682. }
  683. }
  684. public void removeUserCount(bool TypeRCTF)
  685. {
  686. if (TypeRCTF)
  687. {
  688. m_numRootAgents--;
  689. }
  690. else
  691. {
  692. m_numChildAgents--;
  693. }
  694. }
  695. public void RecalculateStats()
  696. {
  697. ScenePresence[] presences = GetScenePresences();
  698. int rootcount = 0;
  699. int childcount = 0;
  700. for (int i = 0; i < presences.Length; i++)
  701. {
  702. ScenePresence user = presences[i];
  703. if (user.IsChildAgent)
  704. ++childcount;
  705. else
  706. ++rootcount;
  707. }
  708. m_numRootAgents = rootcount;
  709. m_numChildAgents = childcount;
  710. }
  711. public int GetChildAgentCount()
  712. {
  713. // some network situations come in where child agents get closed twice.
  714. if (m_numChildAgents < 0)
  715. {
  716. m_numChildAgents = 0;
  717. }
  718. return m_numChildAgents;
  719. }
  720. public int GetRootAgentCount()
  721. {
  722. return m_numRootAgents;
  723. }
  724. public int GetTotalObjectsCount()
  725. {
  726. return m_numPrim;
  727. }
  728. public int GetActiveObjectsCount()
  729. {
  730. return m_physicalPrim;
  731. }
  732. public int GetActiveScriptsCount()
  733. {
  734. return m_activeScripts;
  735. }
  736. public int GetScriptLPS()
  737. {
  738. int returnval = m_scriptLPS;
  739. m_scriptLPS = 0;
  740. return returnval;
  741. }
  742. #endregion
  743. #region Get Methods
  744. /// <summary>
  745. /// Request a List of all scene presences in this scene. This is a new list, so no
  746. /// locking is required to iterate over it.
  747. /// </summary>
  748. /// <returns></returns>
  749. protected internal ScenePresence[] GetScenePresences()
  750. {
  751. return m_scenePresenceArray;
  752. }
  753. protected internal List<ScenePresence> GetAvatars()
  754. {
  755. List<ScenePresence> result =
  756. GetScenePresences(delegate(ScenePresence scenePresence) { return !scenePresence.IsChildAgent; });
  757. return result;
  758. }
  759. /// <summary>
  760. /// Get the controlling client for the given avatar, if there is one.
  761. ///
  762. /// FIXME: The only user of the method right now is Caps.cs, in order to resolve a client API since it can't
  763. /// use the ScenePresence. This could be better solved in a number of ways - we could establish an
  764. /// OpenSim.Framework.IScenePresence, or move the caps code into a region package (which might be the more
  765. /// suitable solution).
  766. /// </summary>
  767. /// <param name="agentId"></param>
  768. /// <returns>null if either the avatar wasn't in the scene, or
  769. /// they do not have a controlling client</returns>
  770. /// <remarks>this used to be protected internal, but that
  771. /// prevents CapabilitiesModule from accessing it</remarks>
  772. public IClientAPI GetControllingClient(UUID agentId)
  773. {
  774. ScenePresence presence = GetScenePresence(agentId);
  775. if (presence != null)
  776. {
  777. return presence.ControllingClient;
  778. }
  779. return null;
  780. }
  781. /// <summary>
  782. /// Request a filtered list of m_scenePresences in this World
  783. /// </summary>
  784. /// <returns></returns>
  785. protected internal List<ScenePresence> GetScenePresences(FilterAvatarList filter)
  786. {
  787. // No locking of scene presences here since we're passing back a list...
  788. List<ScenePresence> result = new List<ScenePresence>();
  789. ScenePresence[] scenePresences = GetScenePresences();
  790. for (int i = 0; i < scenePresences.Length; i++)
  791. {
  792. ScenePresence avatar = scenePresences[i];
  793. if (filter(avatar))
  794. result.Add(avatar);
  795. }
  796. return result;
  797. }
  798. /// <summary>
  799. /// Request a scene presence by UUID
  800. /// </summary>
  801. /// <param name="avatarID"></param>
  802. /// <returns>null if the agent was not found</returns>
  803. protected internal ScenePresence GetScenePresence(UUID agentID)
  804. {
  805. ScenePresence sp;
  806. lock (m_scenePresences)
  807. {
  808. m_scenePresences.TryGetValue(agentID, out sp);
  809. }
  810. return sp;
  811. }
  812. /// <summary>
  813. /// Get a scene object group that contains the prim with the given local id
  814. /// </summary>
  815. /// <param name="localID"></param>
  816. /// <returns>null if no scene object group containing that prim is found</returns>
  817. public SceneObjectGroup GetGroupByPrim(uint localID)
  818. {
  819. if (Entities.ContainsKey(localID))
  820. return Entities[localID] as SceneObjectGroup;
  821. //m_log.DebugFormat("Entered GetGroupByPrim with localID {0}", localID);
  822. SceneObjectGroup sog;
  823. lock (SceneObjectGroupsByLocalID)
  824. {
  825. if (SceneObjectGroupsByLocalID.TryGetValue(localID, out sog))
  826. {
  827. return sog;
  828. }
  829. }
  830. List<EntityBase> EntityList = GetEntities();
  831. foreach (EntityBase ent in EntityList)
  832. {
  833. //m_log.DebugFormat("Looking at entity {0}", ent.UUID);
  834. if (ent is SceneObjectGroup)
  835. {
  836. if (((SceneObjectGroup)ent).HasChildPrim(localID))
  837. {
  838. sog = (SceneObjectGroup)ent;
  839. lock (SceneObjectGroupsByLocalID)
  840. {
  841. SceneObjectGroupsByLocalID[localID] = sog;
  842. }
  843. return sog;
  844. }
  845. }
  846. }
  847. return null;
  848. }
  849. /// <summary>
  850. /// Get a scene object group that contains the prim with the given uuid
  851. /// </summary>
  852. /// <param name="fullID"></param>
  853. /// <returns>null if no scene object group containing that prim is found</returns>
  854. private SceneObjectGroup GetGroupByPrim(UUID fullID)
  855. {
  856. SceneObjectGroup sog;
  857. lock (SceneObjectGroupsByFullID)
  858. {
  859. if (SceneObjectGroupsByFullID.TryGetValue(fullID, out sog))
  860. {
  861. return sog;
  862. }
  863. }
  864. List<EntityBase> EntityList = GetEntities();
  865. foreach (EntityBase ent in EntityList)
  866. {
  867. if (ent is SceneObjectGroup)
  868. {
  869. if (((SceneObjectGroup)ent).HasChildPrim(fullID))
  870. {
  871. sog = (SceneObjectGroup)ent;
  872. lock (SceneObjectGroupsByFullID)
  873. {
  874. SceneObjectGroupsByFullID[fullID] = sog;
  875. }
  876. return sog;
  877. }
  878. }
  879. }
  880. return null;
  881. }
  882. protected internal EntityIntersection GetClosestIntersectingPrim(Ray hray, bool frontFacesOnly, bool faceCenters)
  883. {
  884. // Primitive Ray Tracing
  885. float closestDistance = 280f;
  886. EntityIntersection result = new EntityIntersection();
  887. List<EntityBase> EntityList = GetEntities();
  888. foreach (EntityBase ent in EntityList)
  889. {
  890. if (ent is SceneObjectGroup)
  891. {
  892. SceneObjectGroup reportingG = (SceneObjectGroup)ent;
  893. EntityIntersection inter = reportingG.TestIntersection(hray, frontFacesOnly, faceCenters);
  894. if (inter.HitTF && inter.distance < closestDistance)
  895. {
  896. closestDistance = inter.distance;
  897. result = inter;
  898. }
  899. }
  900. }
  901. return result;
  902. }
  903. /// <summary>
  904. /// Get a part contained in this scene.
  905. /// </summary>
  906. /// <param name="localID"></param>
  907. /// <returns>null if the part was not found</returns>
  908. protected internal SceneObjectPart GetSceneObjectPart(uint localID)
  909. {
  910. SceneObjectGroup group = GetGroupByPrim(localID);
  911. if (group == null)
  912. return null;
  913. return group.GetChildPart(localID);
  914. }
  915. /// <summary>
  916. /// Get a named prim contained in this scene (will return the first
  917. /// found, if there are more than one prim with the same name)
  918. /// </summary>
  919. /// <param name="name"></param>
  920. /// <returns>null if the part was not found</returns>
  921. protected internal SceneObjectPart GetSceneObjectPart(string name)
  922. {
  923. List<EntityBase> EntityList = GetEntities();
  924. // FIXME: use a dictionary here
  925. foreach (EntityBase ent in EntityList)
  926. {
  927. if (ent is SceneObjectGroup)
  928. {
  929. foreach (SceneObjectPart p in ((SceneObjectGroup) ent).GetParts())
  930. {
  931. if (p.Name == name)
  932. {
  933. return p;
  934. }
  935. }
  936. }
  937. }
  938. return null;
  939. }
  940. /// <summary>
  941. /// Get a part contained in this scene.
  942. /// </summary>
  943. /// <param name="fullID"></param>
  944. /// <returns>null if the part was not found</returns>
  945. protected internal SceneObjectPart GetSceneObjectPart(UUID fullID)
  946. {
  947. SceneObjectGroup group = GetGroupByPrim(fullID);
  948. if (group == null)
  949. return null;
  950. return group.GetChildPart(fullID);
  951. }
  952. protected internal bool TryGetAvatar(UUID avatarId, out ScenePresence avatar)
  953. {
  954. lock (m_scenePresences)
  955. return m_scenePresences.TryGetValue(avatarId, out avatar);
  956. }
  957. protected internal bool TryGetAvatarByName(string avatarName, out ScenePresence avatar)
  958. {
  959. ScenePresence[] presences = GetScenePresences();
  960. for (int i = 0; i < presences.Length; i++)
  961. {
  962. ScenePresence presence = presences[i];
  963. if (!presence.IsChildAgent)
  964. {
  965. if (String.Compare(avatarName, presence.ControllingClient.Name, true) == 0)
  966. {
  967. avatar = presence;
  968. return true;
  969. }
  970. }
  971. }
  972. avatar = null;
  973. return false;
  974. }
  975. /// <summary>
  976. /// Returns a list of the entities in the scene. This is a new list so no locking is required to iterate over
  977. /// it
  978. /// </summary>
  979. /// <returns></returns>
  980. protected internal List<EntityBase> GetEntities()
  981. {
  982. return Entities.GetEntities();
  983. }
  984. public Dictionary<uint, float> GetTopScripts()
  985. {
  986. Dictionary<uint, float> topScripts = new Dictionary<uint, float>();
  987. List<EntityBase> EntityList = GetEntities();
  988. int limit = 0;
  989. foreach (EntityBase ent in EntityList)
  990. {
  991. if (ent is SceneObjectGroup)
  992. {
  993. SceneObjectGroup grp = (SceneObjectGroup)ent;
  994. if ((grp.RootPart.GetEffectiveObjectFlags() & (uint)PrimFlags.Scripted) != 0)
  995. {
  996. if (grp.scriptScore >= 0.01)
  997. {
  998. topScripts.Add(grp.LocalId, grp.scriptScore);
  999. limit++;
  1000. if (limit >= 100)
  1001. {
  1002. break;
  1003. }
  1004. }
  1005. grp.scriptScore = 0;
  1006. }
  1007. }
  1008. }
  1009. return topScripts;
  1010. }
  1011. #endregion
  1012. #region Other Methods
  1013. protected internal void physicsBasedCrash()
  1014. {
  1015. handlerPhysicsCrash = UnRecoverableError;
  1016. if (handlerPhysicsCrash != null)
  1017. {
  1018. handlerPhysicsCrash();
  1019. }
  1020. }
  1021. protected internal UUID ConvertLocalIDToFullID(uint localID)
  1022. {
  1023. SceneObjectGroup group = GetGroupByPrim(localID);
  1024. if (group != null)
  1025. return group.GetPartsFullID(localID);
  1026. else
  1027. return UUID.Zero;
  1028. }
  1029. protected internal void ForEachSOG(Action<SceneObjectGroup> action)
  1030. {
  1031. List<SceneObjectGroup> objlist = new List<SceneObjectGroup>(SceneObjectGroupsByFullID.Values);
  1032. foreach (SceneObjectGroup obj in objlist)
  1033. {
  1034. try
  1035. {
  1036. action(obj);
  1037. }
  1038. catch (Exception e)
  1039. {
  1040. // Catch it and move on. This includes situations where splist has inconsistent info
  1041. m_log.WarnFormat("[SCENE]: Problem processing action in ForEachSOG: ", e.Message);
  1042. }
  1043. }
  1044. }
  1045. #endregion
  1046. #region Client Event handlers
  1047. /// <summary>
  1048. ///
  1049. /// </summary>
  1050. /// <param name="localID"></param>
  1051. /// <param name="scale"></param>
  1052. /// <param name="remoteClient"></param>
  1053. protected internal void UpdatePrimScale(uint localID, Vector3 scale, IClientAPI remoteClient)
  1054. {
  1055. SceneObjectGroup group = GetGroupByPrim(localID);
  1056. if (group != null)
  1057. {
  1058. if (m_parentScene.Permissions.CanEditObject(group.UUID, remoteClient.AgentId))
  1059. {
  1060. group.Resize(scale, localID);
  1061. }
  1062. }
  1063. }
  1064. protected internal void UpdatePrimGroupScale(uint localID, Vector3 scale, IClientAPI remoteClient)
  1065. {
  1066. SceneObjectGroup group = GetGroupByPrim(localID);
  1067. if (group != null)
  1068. {
  1069. if (m_parentScene.Permissions.CanEditObject(group.UUID, remoteClient.AgentId))
  1070. {
  1071. group.GroupResize(scale, localID);
  1072. }
  1073. }
  1074. }
  1075. /// <summary>
  1076. /// This handles the nifty little tool tip that you get when you drag your mouse over an object
  1077. /// Send to the Object Group to process. We don't know enough to service the request
  1078. /// </summary>
  1079. /// <param name="remoteClient"></param>
  1080. /// <param name="AgentID"></param>
  1081. /// <param name="RequestFlags"></param>
  1082. /// <param name="ObjectID"></param>
  1083. protected internal void RequestObjectPropertiesFamily(
  1084. IClientAPI remoteClient, UUID AgentID, uint RequestFlags, UUID ObjectID)
  1085. {
  1086. SceneObjectGroup group = GetGroupByPrim(ObjectID);
  1087. if (group != null)
  1088. {
  1089. group.ServiceObjectPropertiesFamilyRequest(remoteClient, AgentID, RequestFlags);
  1090. }
  1091. }
  1092. /// <summary>
  1093. ///
  1094. /// </summary>
  1095. /// <param name="localID"></param>
  1096. /// <param name="rot"></param>
  1097. /// <param name="remoteClient"></param>
  1098. protected internal void UpdatePrimSingleRotation(uint localID, Quaternion rot, IClientAPI remoteClient)
  1099. {
  1100. SceneObjectGroup group = GetGroupByPrim(localID);
  1101. if (group != null)
  1102. {
  1103. if (m_parentScene.Permissions.CanMoveObject(group.UUID, remoteClient.AgentId))
  1104. {
  1105. group.UpdateSingleRotation(rot, localID);
  1106. }
  1107. }
  1108. }
  1109. /// <summary>
  1110. ///
  1111. /// </summary>
  1112. /// <param name="localID"></param>
  1113. /// <param name="rot"></param>
  1114. /// <param name="remoteClient"></param>
  1115. protected internal void UpdatePrimSingleRotationPosition(uint localID, Quaternion rot, Vector3 pos, IClientAPI remoteClient)
  1116. {
  1117. SceneObjectGroup group = GetGroupByPrim(localID);
  1118. if (group != null)
  1119. {
  1120. if (m_parentScene.Permissions.CanMoveObject(group.UUID, remoteClient.AgentId))
  1121. {
  1122. group.UpdateSingleRotation(rot,pos, localID);
  1123. }
  1124. }
  1125. }
  1126. /// <summary>
  1127. ///
  1128. /// </summary>
  1129. /// <param name="localID"></param>
  1130. /// <param name="rot"></param>
  1131. /// <param name="remoteClient"></param>
  1132. protected internal void UpdatePrimRotation(uint localID, Quaternion rot, IClientAPI remoteClient)
  1133. {
  1134. SceneObjectGroup group = GetGroupByPrim(localID);
  1135. if (group != null)
  1136. {
  1137. if (m_parentScene.Permissions.CanMoveObject(group.UUID, remoteClient.AgentId))
  1138. {
  1139. group.UpdateGroupRotationR(rot);
  1140. }
  1141. }
  1142. }
  1143. /// <summary>
  1144. ///
  1145. /// </summary>
  1146. /// <param name="localID"></param>
  1147. /// <param name="pos"></param>
  1148. /// <param name="rot"></param>
  1149. /// <param name="remoteClient"></param>
  1150. protected internal void UpdatePrimRotation(uint localID, Vector3 pos, Quaternion rot, IClientAPI remoteClient)
  1151. {
  1152. SceneObjectGroup group = GetGroupByPrim(localID);
  1153. if (group != null)
  1154. {
  1155. if (m_parentScene.Permissions.CanMoveObject(group.UUID, remoteClient.AgentId))
  1156. {
  1157. group.UpdateGroupRotationPR(pos, rot);
  1158. }
  1159. }
  1160. }
  1161. /// <summary>
  1162. /// Update the position of the given part
  1163. /// </summary>
  1164. /// <param name="localID"></param>
  1165. /// <param name="pos"></param>
  1166. /// <param name="remoteClient"></param>
  1167. protected internal void UpdatePrimSinglePosition(uint localID, Vector3 pos, IClientAPI remoteClient)
  1168. {
  1169. SceneObjectGroup group = GetGroupByPrim(localID);
  1170. if (g

Large files files are truncated, but you can click here to view the full file