PageRenderTime 66ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/Aurora/Region/SceneGraph.cs

https://bitbucket.org/VirtualReality/software-testing
C# | 2314 lines | 1537 code | 221 blank | 556 comment | 276 complexity | 9b54046049b2fed1c55899ebd36e7387 MD5 | raw file

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

  1. /*
  2. * Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim 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 Aurora.Framework;
  28. using Aurora.Framework.ClientInterfaces;
  29. using Aurora.Framework.ConsoleFramework;
  30. using Aurora.Framework.Modules;
  31. using Aurora.Framework.Physics;
  32. using Aurora.Framework.PresenceInfo;
  33. using Aurora.Framework.SceneInfo;
  34. using Aurora.Framework.SceneInfo.Entities;
  35. using Aurora.Framework.Services;
  36. using Aurora.Framework.Utilities;
  37. using Nini.Config;
  38. using OpenMetaverse;
  39. using OpenMetaverse.Packets;
  40. using System;
  41. using System.Collections.Generic;
  42. using System.Linq;
  43. using System.Threading;
  44. namespace Aurora.Region
  45. {
  46. /// <summary>
  47. /// This class used to be called InnerScene and may not yet truly be a SceneGraph. The non scene graph components
  48. /// should be migrated out over time.
  49. /// </summary>
  50. public class SceneGraph : ISceneGraph
  51. {
  52. #region Declares
  53. protected internal EntityManager Entities = new EntityManager();
  54. protected RegionInfo m_regInfo;
  55. protected IScene m_parentScene;
  56. protected bool EnableFakeRaycasting = false;
  57. protected string m_DefaultObjectName = "Primitive";
  58. /// <summary>
  59. /// The last allocated local prim id. When a new local id is requested, the next number in the sequence is
  60. /// dispensed.
  61. /// </summary>
  62. protected uint m_lastAllocatedLocalId = 720000;
  63. private readonly object _primAllocateLock = new object();
  64. protected internal object m_syncRoot = new object();
  65. protected internal PhysicsScene _PhyScene;
  66. private readonly Object m_updateLock = new Object();
  67. public PhysicsScene PhysicsScene
  68. {
  69. get { return _PhyScene; }
  70. set { _PhyScene = value; }
  71. }
  72. #endregion
  73. #region Constructor and close
  74. protected internal SceneGraph(IScene parent, RegionInfo regInfo)
  75. {
  76. Random random = new Random();
  77. m_lastAllocatedLocalId = (uint) (random.NextDouble()*(uint.MaxValue/2)) + uint.MaxValue/4;
  78. m_parentScene = parent;
  79. m_regInfo = regInfo;
  80. //Subscript to the scene events
  81. m_parentScene.EventManager.OnNewClient += SubscribeToClientEvents;
  82. m_parentScene.EventManager.OnClosingClient += UnSubscribeToClientEvents;
  83. IConfig aurorastartupConfig = parent.Config.Configs["AuroraStartup"];
  84. if (aurorastartupConfig != null)
  85. {
  86. m_DefaultObjectName = aurorastartupConfig.GetString("DefaultObjectName", m_DefaultObjectName);
  87. EnableFakeRaycasting = aurorastartupConfig.GetBoolean("EnableFakeRaycasting", false);
  88. }
  89. }
  90. protected internal void Close()
  91. {
  92. Entities.Clear();
  93. //Remove the events
  94. m_parentScene.EventManager.OnNewClient -= SubscribeToClientEvents;
  95. m_parentScene.EventManager.OnClosingClient -= UnSubscribeToClientEvents;
  96. }
  97. #endregion
  98. #region Update Methods
  99. protected internal void UpdatePreparePhysics()
  100. {
  101. // If we are using a threaded physics engine
  102. // grab the latest scene from the engine before
  103. // trying to process it.
  104. // PhysX does this (runs in the background).
  105. if (_PhyScene != null && _PhyScene.IsThreaded)
  106. {
  107. _PhyScene.GetResults();
  108. }
  109. }
  110. private readonly object m_taintedPresencesLock = new object();
  111. private readonly List<IScenePresence> m_taintedPresences = new List<IScenePresence>();
  112. public void TaintPresenceForUpdate(IScenePresence presence, PresenceTaint taint)
  113. {
  114. lock (m_taintedPresencesLock)
  115. {
  116. if (!presence.IsTainted) //We ONLY set the IsTainted under this lock, so we can trust it
  117. m_taintedPresences.Add(presence);
  118. presence.Taints |= taint;
  119. }
  120. }
  121. protected internal void UpdateEntities()
  122. {
  123. IScenePresence[] presences;
  124. lock (m_taintedPresencesLock)
  125. {
  126. presences = new IScenePresence[m_taintedPresences.Count];
  127. m_taintedPresences.CopyTo(presences);
  128. m_taintedPresences.Clear();
  129. }
  130. foreach (IScenePresence presence in presences)
  131. {
  132. presence.IsTainted = false;
  133. //We set this first so that it is cleared out, but also so that the method can re-taint us
  134. presence.Update();
  135. }
  136. }
  137. protected internal void UpdatePhysics(double elapsed)
  138. {
  139. if (_PhyScene == null)
  140. return;
  141. lock (m_syncRoot)
  142. {
  143. // Update DisableCollisions
  144. _PhyScene.DisableCollisions = m_regInfo.RegionSettings.DisableCollisions;
  145. // Here is where the Scene calls the PhysicsScene. This is a one-way
  146. // interaction; the PhysicsScene cannot access the calling Scene directly.
  147. // But with joints, we want a PhysicsActor to be able to influence a
  148. // non-physics SceneObjectPart. In particular, a PhysicsActor that is connected
  149. // with a joint should be able to move the SceneObjectPart which is the visual
  150. // representation of that joint (for editing and serialization purposes).
  151. // However the PhysicsActor normally cannot directly influence anything outside
  152. // of the PhysicsScene, and the non-physical SceneObjectPart which represents
  153. // the joint in the Scene does not exist in the PhysicsScene.
  154. //
  155. // To solve this, we have an event in the PhysicsScene that is fired when a joint
  156. // has changed position (because one of its associated PhysicsActors has changed
  157. // position).
  158. //
  159. // Therefore, JointMoved and JointDeactivated events will be fired as a result of the following Simulate().
  160. _PhyScene.Simulate((float) elapsed);
  161. }
  162. }
  163. private List<Vector3> m_oldCoarseLocations = new List<Vector3>();
  164. private List<UUID> m_oldAvatarUUIDs = new List<UUID>();
  165. public bool GetCoarseLocations(out List<Vector3> coarseLocations, out List<UUID> avatarUUIDs, uint maxLocations)
  166. {
  167. coarseLocations = new List<Vector3>();
  168. avatarUUIDs = new List<UUID>();
  169. List<IScenePresence> presences = GetScenePresences();
  170. for (int i = 0; i < Math.Min(presences.Count, maxLocations); i++)
  171. {
  172. IScenePresence sp = presences[i];
  173. // If this presence is a child agent, we don't want its coarse locations
  174. if (sp.IsChildAgent)
  175. continue;
  176. if (sp.ParentID != UUID.Zero)
  177. {
  178. // sitting avatar
  179. ISceneChildEntity sop = m_parentScene.GetSceneObjectPart(sp.ParentID);
  180. if (sop != null)
  181. {
  182. coarseLocations.Add(sop.AbsolutePosition + sp.OffsetPosition);
  183. avatarUUIDs.Add(sp.UUID);
  184. }
  185. else
  186. {
  187. // we can't find the parent.. ! arg!
  188. MainConsole.Instance.Warn("Could not find parent prim for avatar " + sp.Name);
  189. coarseLocations.Add(sp.AbsolutePosition);
  190. avatarUUIDs.Add(sp.UUID);
  191. }
  192. }
  193. else
  194. {
  195. coarseLocations.Add(sp.AbsolutePosition);
  196. avatarUUIDs.Add(sp.UUID);
  197. }
  198. }
  199. if (m_oldCoarseLocations.Count == coarseLocations.Count)
  200. {
  201. List<UUID> foundAvies = new List<UUID>(m_oldAvatarUUIDs);
  202. foreach (UUID t in avatarUUIDs)
  203. {
  204. foundAvies.Remove(t);
  205. }
  206. if (foundAvies.Count == 0)
  207. {
  208. //All avies are still the same, check their locations now
  209. for (int i = 0; i < avatarUUIDs.Count; i++)
  210. {
  211. if (m_oldCoarseLocations[i].ApproxEquals(coarseLocations[i], 5))
  212. continue;
  213. m_oldCoarseLocations = coarseLocations;
  214. m_oldAvatarUUIDs = avatarUUIDs;
  215. return true;
  216. }
  217. //Things are still close enough to the same
  218. return false;
  219. }
  220. }
  221. m_oldCoarseLocations = coarseLocations;
  222. m_oldAvatarUUIDs = avatarUUIDs;
  223. //Its changed, tell it to send new
  224. return true;
  225. }
  226. #endregion
  227. #region Entity Methods
  228. protected internal void HandleUndo(IClientAPI remoteClient, UUID primId)
  229. {
  230. if (primId != UUID.Zero)
  231. {
  232. ISceneChildEntity part = m_parentScene.GetSceneObjectPart(primId);
  233. if (part != null)
  234. if (m_parentScene.Permissions.CanEditObject(part.UUID, remoteClient.AgentId))
  235. part.Undo();
  236. }
  237. }
  238. protected internal void HandleRedo(IClientAPI remoteClient, UUID primId)
  239. {
  240. if (primId != UUID.Zero)
  241. {
  242. ISceneChildEntity part = m_parentScene.GetSceneObjectPart(primId);
  243. if (part != null)
  244. if (m_parentScene.Permissions.CanEditObject(part.UUID, remoteClient.AgentId))
  245. part.Redo();
  246. }
  247. }
  248. protected internal void HandleObjectGroupUpdate(
  249. IClientAPI remoteClient, UUID GroupID, uint LocalID, UUID Garbage)
  250. {
  251. IEntity entity;
  252. if (TryGetEntity(LocalID, out entity))
  253. {
  254. if (m_parentScene.Permissions.CanEditObject(entity.UUID, remoteClient.AgentId))
  255. if (((ISceneEntity) entity).OwnerID == remoteClient.AgentId)
  256. ((ISceneEntity) entity).SetGroup(GroupID, remoteClient.AgentId, true);
  257. }
  258. }
  259. /// <summary>
  260. /// Add a presence to the scene
  261. /// </summary>
  262. /// <param name="presence"></param>
  263. protected internal void AddScenePresence(IScenePresence presence)
  264. {
  265. AddEntity(presence, true);
  266. }
  267. /// <summary>
  268. /// Remove a presence from the scene
  269. /// </summary>
  270. protected internal void RemoveScenePresence(IEntity agent)
  271. {
  272. if (!Entities.Remove(agent))
  273. {
  274. MainConsole.Instance.WarnFormat(
  275. "[SCENE]: Tried to remove non-existent scene presence with agent ID {0} from scene Entities list",
  276. agent.UUID);
  277. return;
  278. }
  279. }
  280. #endregion
  281. #region Get Methods
  282. /// <summary>
  283. /// Get a reference to the scene presence list. Changes to the list will be done in a copy
  284. /// There is no guarantee that presences will remain in the scene after the list is returned.
  285. /// This list should remain private to SceneGraph. Callers wishing to iterate should instead
  286. /// pass a delegate to ForEachScenePresence.
  287. /// </summary>
  288. /// <returns></returns>
  289. public List<IScenePresence> GetScenePresences()
  290. {
  291. return Entities.GetPresences();
  292. }
  293. /// <summary>
  294. /// Request a scene presence by UUID. Fast, indexed lookup.
  295. /// </summary>
  296. /// <param name="agentID"></param>
  297. /// <returns>null if the presence was not found</returns>
  298. protected internal IScenePresence GetScenePresence(UUID agentID)
  299. {
  300. IScenePresence sp;
  301. Entities.TryGetPresenceValue(agentID, out sp);
  302. return sp;
  303. }
  304. /// <summary>
  305. /// Request the scene presence by name.
  306. /// NOTE: Depricated, use the ScenePresence GetScenePresence (string Name) instead!
  307. /// </summary>
  308. /// <param name="firstName"></param>
  309. /// <param name="lastName"></param>
  310. /// <returns>null if the presence was not found</returns>
  311. public IScenePresence GetScenePresence(string firstName, string lastName)
  312. {
  313. List<IScenePresence> presences = GetScenePresences();
  314. #if (!ISWIN)
  315. foreach (IScenePresence presence in presences)
  316. {
  317. if (presence.Firstname == firstName && presence.Lastname == lastName) return presence;
  318. }
  319. return null;
  320. #else
  321. return presences.FirstOrDefault(presence => presence.Firstname == firstName && presence.Lastname == lastName);
  322. #endif
  323. }
  324. /// <summary>
  325. /// Request the scene presence by localID.
  326. /// </summary>
  327. /// <param name="localID"></param>
  328. /// <returns>null if the presence was not found</returns>
  329. public IScenePresence GetScenePresence(uint localID)
  330. {
  331. List<IScenePresence> presences = GetScenePresences();
  332. #if (!ISWIN)
  333. foreach (IScenePresence presence in presences)
  334. {
  335. if (presence.LocalId == localID) return presence;
  336. }
  337. return null;
  338. #else
  339. return presences.FirstOrDefault(presence => presence.LocalId == localID);
  340. #endif
  341. }
  342. protected internal bool TryGetScenePresence(UUID agentID, out IScenePresence avatar)
  343. {
  344. return Entities.TryGetPresenceValue(agentID, out avatar);
  345. }
  346. protected internal bool TryGetAvatarByName(string name, out IScenePresence avatar)
  347. {
  348. #if (!ISWIN)
  349. avatar = null;
  350. foreach (IScenePresence presence in GetScenePresences())
  351. {
  352. if (String.Compare(name, presence.ControllingClient.Name, true) == 0)
  353. {
  354. avatar = presence;
  355. break;
  356. }
  357. }
  358. #else
  359. avatar =
  360. GetScenePresences()
  361. .FirstOrDefault(presence => String.Compare(name, presence.ControllingClient.Name, true) == 0);
  362. #endif
  363. return (avatar != null);
  364. }
  365. /// <summary>
  366. /// Get a scene object group that contains the prim with the given uuid
  367. /// </summary>
  368. /// <param name="hray"></param>
  369. /// <param name="frontFacesOnly"></param>
  370. /// <param name="faceCenters"></param>
  371. /// <returns>null if no scene object group containing that prim is found</returns>
  372. protected internal EntityIntersection GetClosestIntersectingPrim(Ray hray, bool frontFacesOnly, bool faceCenters)
  373. {
  374. // Primitive Ray Tracing
  375. float closestDistance = 280f;
  376. EntityIntersection result = new EntityIntersection();
  377. ISceneEntity[] EntityList = Entities.GetEntities(hray.Origin, closestDistance);
  378. foreach (ISceneEntity ent in EntityList)
  379. {
  380. if (ent is SceneObjectGroup)
  381. {
  382. SceneObjectGroup reportingG = (SceneObjectGroup) ent;
  383. EntityIntersection inter = reportingG.TestIntersection(hray, frontFacesOnly, faceCenters);
  384. if (inter.HitTF && inter.distance < closestDistance)
  385. {
  386. closestDistance = inter.distance;
  387. result = inter;
  388. }
  389. }
  390. }
  391. return result;
  392. }
  393. /// <summary>
  394. /// Gets a list of scene object group that intersect with the given ray
  395. /// </summary>
  396. public List<EntityIntersection> GetIntersectingPrims(Ray hray, float length, int count,
  397. bool frontFacesOnly, bool faceCenters, bool getAvatars,
  398. bool getLand, bool getPrims)
  399. {
  400. // Primitive Ray Tracing
  401. List<EntityIntersection> result = new List<EntityIntersection>(count);
  402. if (getPrims)
  403. {
  404. ISceneEntity[] EntityList = Entities.GetEntities(hray.Origin, length);
  405. #if (!ISWIN)
  406. foreach (ISceneEntity ent in EntityList)
  407. {
  408. if (ent is SceneObjectGroup)
  409. {
  410. SceneObjectGroup reportingG = (SceneObjectGroup)ent;
  411. EntityIntersection inter = reportingG.TestIntersection(hray, frontFacesOnly, faceCenters);
  412. if (inter.HitTF)
  413. result.Add(inter);
  414. }
  415. }
  416. #else
  417. result.AddRange(
  418. EntityList.OfType<SceneObjectGroup>()
  419. .Select(reportingG => reportingG.TestIntersection(hray, frontFacesOnly, faceCenters))
  420. .Where(inter => inter.HitTF));
  421. #endif
  422. }
  423. if (getAvatars)
  424. {
  425. List<IScenePresence> presenceList = Entities.GetPresences();
  426. foreach (IScenePresence ent in presenceList)
  427. {
  428. //Do rough approximation and keep the # of loops down
  429. Vector3 newPos = hray.Origin;
  430. for (int i = 0; i < 100; i++)
  431. {
  432. newPos += ((Vector3.One*(length*(i/100)))*hray.Direction);
  433. if (ent.AbsolutePosition.ApproxEquals(newPos, ent.PhysicsActor.Size.X*2))
  434. {
  435. EntityIntersection intersection = new EntityIntersection();
  436. intersection.distance = length*(i/100);
  437. intersection.face = 0;
  438. intersection.HitTF = true;
  439. intersection.obj = ent;
  440. intersection.ipoint = newPos;
  441. intersection.normal = newPos;
  442. result.Add(intersection);
  443. break;
  444. }
  445. }
  446. }
  447. }
  448. if (getLand)
  449. {
  450. //TODO
  451. }
  452. #if (!ISWIN)
  453. result.Sort(delegate(EntityIntersection a, EntityIntersection b)
  454. {
  455. return a.distance.CompareTo(b.distance);
  456. });
  457. #else
  458. result.Sort((a, b) => a.distance.CompareTo(b.distance));
  459. #endif
  460. if (result.Count > count)
  461. result.RemoveRange(count, result.Count - count);
  462. return result;
  463. }
  464. #endregion
  465. #region ForEach* Methods
  466. /// <summary>
  467. /// Performs action on all scene object groups.
  468. /// </summary>
  469. /// <param name="action"></param>
  470. protected internal void ForEachSceneEntity(Action<ISceneEntity> action)
  471. {
  472. ISceneEntity[] objlist = Entities.GetEntities();
  473. foreach (ISceneEntity obj in objlist)
  474. {
  475. try
  476. {
  477. action(obj);
  478. }
  479. catch (Exception e)
  480. {
  481. // Catch it and move on. This includes situations where splist has inconsistent info
  482. MainConsole.Instance.WarnFormat("[SCENE]: Problem processing action in ForEachSOG: {0}",
  483. e.ToString());
  484. }
  485. }
  486. }
  487. /// <summary>
  488. /// Performs action on all scene presences. This can ultimately run the actions in parallel but
  489. /// any delegates passed in will need to implement their own locking on data they reference and
  490. /// modify outside of the scope of the delegate.
  491. /// </summary>
  492. /// <param name="action"></param>
  493. public void ForEachScenePresence(Action<IScenePresence> action)
  494. {
  495. // Once all callers have their delegates configured for parallelism, we can unleash this
  496. /*
  497. Action<ScenePresence> protectedAction = new Action<ScenePresence>(delegate(ScenePresence sp)
  498. {
  499. try
  500. {
  501. action(sp);
  502. }
  503. catch (Exception e)
  504. {
  505. MainConsole.Instance.Info("[BUG] in " + m_parentScene.RegionInfo.RegionName + ": " + e.ToString());
  506. MainConsole.Instance.Info("[BUG] Stack Trace: " + e.StackTrace);
  507. }
  508. });
  509. Parallel.ForEach<ScenePresence>(GetScenePresences(), protectedAction);
  510. */
  511. // For now, perform actions serially
  512. List<IScenePresence> presences = new List<IScenePresence>(GetScenePresences());
  513. foreach (IScenePresence sp in presences)
  514. {
  515. try
  516. {
  517. action(sp);
  518. }
  519. catch (Exception e)
  520. {
  521. MainConsole.Instance.Info("[BUG] in " + m_parentScene.RegionInfo.RegionName + ": " + e.ToString());
  522. MainConsole.Instance.Info("[BUG] Stack Trace: " + e.StackTrace);
  523. }
  524. }
  525. }
  526. #endregion ForEach* Methods
  527. #region Client Event handlers
  528. public void SubscribeToClientEvents(IClientAPI client)
  529. {
  530. client.OnUpdatePrimGroupPosition += UpdatePrimPosition;
  531. client.OnUpdatePrimSinglePosition += UpdatePrimSinglePosition;
  532. client.OnUpdatePrimGroupRotation += UpdatePrimRotation;
  533. client.OnUpdatePrimGroupMouseRotation += UpdatePrimRotation;
  534. client.OnUpdatePrimSingleRotation += UpdatePrimSingleRotation;
  535. client.OnUpdatePrimSingleRotationPosition += UpdatePrimSingleRotationPosition;
  536. client.OnUpdatePrimScale += UpdatePrimScale;
  537. client.OnUpdatePrimGroupScale += UpdatePrimGroupScale;
  538. client.OnUpdateExtraParams += UpdateExtraParam;
  539. client.OnUpdatePrimShape += UpdatePrimShape;
  540. client.OnUpdatePrimTexture += UpdatePrimTexture;
  541. client.OnGrabUpdate += MoveObject;
  542. client.OnSpinStart += SpinStart;
  543. client.OnSpinUpdate += SpinObject;
  544. client.OnObjectName += PrimName;
  545. client.OnObjectClickAction += PrimClickAction;
  546. client.OnObjectMaterial += PrimMaterial;
  547. client.OnLinkObjects += LinkObjects;
  548. client.OnDelinkObjects += DelinkObjects;
  549. client.OnObjectDuplicate += DuplicateObject;
  550. client.OnUpdatePrimFlags += UpdatePrimFlags;
  551. client.OnRequestObjectPropertiesFamily += RequestObjectPropertiesFamily;
  552. client.OnObjectPermissions += HandleObjectPermissionsUpdate;
  553. client.OnGrabObject += ProcessObjectGrab;
  554. client.OnGrabUpdate += ProcessObjectGrabUpdate;
  555. client.OnDeGrabObject += ProcessObjectDeGrab;
  556. client.OnUndo += HandleUndo;
  557. client.OnRedo += HandleRedo;
  558. client.OnObjectDescription += PrimDescription;
  559. client.OnObjectIncludeInSearch += MakeObjectSearchable;
  560. client.OnObjectOwner += ObjectOwner;
  561. client.OnObjectGroupRequest += HandleObjectGroupUpdate;
  562. client.OnAddPrim += AddNewPrim;
  563. client.OnObjectDuplicateOnRay += doObjectDuplicateOnRay;
  564. }
  565. public void UnSubscribeToClientEvents(IClientAPI client)
  566. {
  567. client.OnUpdatePrimGroupPosition -= UpdatePrimPosition;
  568. client.OnUpdatePrimSinglePosition -= UpdatePrimSinglePosition;
  569. client.OnUpdatePrimGroupRotation -= UpdatePrimRotation;
  570. client.OnUpdatePrimGroupMouseRotation -= UpdatePrimRotation;
  571. client.OnUpdatePrimSingleRotation -= UpdatePrimSingleRotation;
  572. client.OnUpdatePrimSingleRotationPosition -= UpdatePrimSingleRotationPosition;
  573. client.OnUpdatePrimScale -= UpdatePrimScale;
  574. client.OnUpdatePrimGroupScale -= UpdatePrimGroupScale;
  575. client.OnUpdateExtraParams -= UpdateExtraParam;
  576. client.OnUpdatePrimShape -= UpdatePrimShape;
  577. client.OnUpdatePrimTexture -= UpdatePrimTexture;
  578. client.OnGrabUpdate -= MoveObject;
  579. client.OnSpinStart -= SpinStart;
  580. client.OnSpinUpdate -= SpinObject;
  581. client.OnObjectName -= PrimName;
  582. client.OnObjectClickAction -= PrimClickAction;
  583. client.OnObjectMaterial -= PrimMaterial;
  584. client.OnLinkObjects -= LinkObjects;
  585. client.OnDelinkObjects -= DelinkObjects;
  586. client.OnObjectDuplicate -= DuplicateObject;
  587. client.OnUpdatePrimFlags -= UpdatePrimFlags;
  588. client.OnRequestObjectPropertiesFamily -= RequestObjectPropertiesFamily;
  589. client.OnObjectPermissions -= HandleObjectPermissionsUpdate;
  590. client.OnGrabObject -= ProcessObjectGrab;
  591. client.OnGrabUpdate -= ProcessObjectGrabUpdate;
  592. client.OnDeGrabObject -= ProcessObjectDeGrab;
  593. client.OnUndo -= HandleUndo;
  594. client.OnRedo -= HandleRedo;
  595. client.OnObjectDescription -= PrimDescription;
  596. client.OnObjectIncludeInSearch -= MakeObjectSearchable;
  597. client.OnObjectOwner -= ObjectOwner;
  598. client.OnObjectGroupRequest -= HandleObjectGroupUpdate;
  599. client.OnAddPrim -= AddNewPrim;
  600. client.OnObjectDuplicateOnRay -= doObjectDuplicateOnRay;
  601. }
  602. public virtual void ProcessObjectGrab(uint localID, Vector3 offsetPos, IClientAPI remoteClient,
  603. List<SurfaceTouchEventArgs> surfaceArgs)
  604. {
  605. SurfaceTouchEventArgs surfaceArg = null;
  606. if (surfaceArgs != null && surfaceArgs.Count > 0)
  607. surfaceArg = surfaceArgs[0];
  608. ISceneChildEntity childPrim;
  609. if (TryGetPart(localID, out childPrim))
  610. {
  611. SceneObjectPart part = childPrim as SceneObjectPart;
  612. if (part != null)
  613. {
  614. SceneObjectGroup obj = part.ParentGroup;
  615. if (obj.RootPart.BlockGrab || obj.RootPart.BlockGrabObject)
  616. return;
  617. // Currently only grab/touch for the single prim
  618. // the client handles rez correctly
  619. obj.ObjectGrabHandler(localID, offsetPos, remoteClient);
  620. // If the touched prim handles touches, deliver it
  621. // If not, deliver to root prim
  622. m_parentScene.EventManager.TriggerObjectGrab(part, part, part.OffsetPosition, remoteClient,
  623. surfaceArg);
  624. // Deliver to the root prim if the touched prim doesn't handle touches
  625. // or if we're meant to pass on touches anyway. Don't send to root prim
  626. // if prim touched is the root prim as we just did it
  627. if ((part.LocalId != obj.RootPart.LocalId))
  628. {
  629. const int PASS_IF_NOT_HANDLED = 0;
  630. const int PASS_ALWAYS = 1;
  631. const int PASS_NEVER = 2;
  632. if (part.PassTouch == PASS_NEVER)
  633. {
  634. }
  635. if (part.PassTouch == PASS_ALWAYS)
  636. {
  637. m_parentScene.EventManager.TriggerObjectGrab(obj.RootPart, part, part.OffsetPosition,
  638. remoteClient, surfaceArg);
  639. }
  640. else if (((part.ScriptEvents & scriptEvents.touch_start) == 0) &&
  641. part.PassTouch == PASS_IF_NOT_HANDLED) //If no event in this prim, pass to parent
  642. {
  643. m_parentScene.EventManager.TriggerObjectGrab(obj.RootPart, part, part.OffsetPosition,
  644. remoteClient, surfaceArg);
  645. }
  646. }
  647. }
  648. }
  649. }
  650. public virtual void ProcessObjectGrabUpdate(UUID objectID, Vector3 offset, Vector3 pos, IClientAPI remoteClient,
  651. List<SurfaceTouchEventArgs> surfaceArgs)
  652. {
  653. SurfaceTouchEventArgs surfaceArg = null;
  654. if (surfaceArgs != null && surfaceArgs.Count > 0)
  655. surfaceArg = surfaceArgs[0];
  656. ISceneChildEntity childPrim;
  657. if (TryGetPart(objectID, out childPrim))
  658. {
  659. SceneObjectPart part = childPrim as SceneObjectPart;
  660. if (part != null)
  661. {
  662. SceneObjectGroup obj = part.ParentGroup;
  663. if (obj.RootPart.BlockGrab || obj.RootPart.BlockGrabObject)
  664. return;
  665. // If the touched prim handles touches, deliver it
  666. // If not, deliver to root prim
  667. m_parentScene.EventManager.TriggerObjectGrabbing(part, part, part.OffsetPosition, remoteClient,
  668. surfaceArg);
  669. // Deliver to the root prim if the touched prim doesn't handle touches
  670. // or if we're meant to pass on touches anyway. Don't send to root prim
  671. // if prim touched is the root prim as we just did it
  672. if ((part.LocalId != obj.RootPart.LocalId))
  673. {
  674. const int PASS_IF_NOT_HANDLED = 0;
  675. const int PASS_ALWAYS = 1;
  676. const int PASS_NEVER = 2;
  677. if (part.PassTouch == PASS_NEVER)
  678. {
  679. }
  680. if (part.PassTouch == PASS_ALWAYS)
  681. {
  682. m_parentScene.EventManager.TriggerObjectGrabbing(obj.RootPart, part, part.OffsetPosition,
  683. remoteClient, surfaceArg);
  684. }
  685. else if ((((part.ScriptEvents & scriptEvents.touch_start) == 0) ||
  686. ((part.ScriptEvents & scriptEvents.touch) == 0)) &&
  687. part.PassTouch == PASS_IF_NOT_HANDLED) //If no event in this prim, pass to parent
  688. {
  689. m_parentScene.EventManager.TriggerObjectGrabbing(obj.RootPart, part, part.OffsetPosition,
  690. remoteClient, surfaceArg);
  691. }
  692. }
  693. }
  694. }
  695. }
  696. public virtual void ProcessObjectDeGrab(uint localID, IClientAPI remoteClient,
  697. List<SurfaceTouchEventArgs> surfaceArgs)
  698. {
  699. SurfaceTouchEventArgs surfaceArg = null;
  700. if (surfaceArgs != null && surfaceArgs.Count > 0)
  701. surfaceArg = surfaceArgs[0];
  702. ISceneChildEntity childPrim;
  703. if (TryGetPart(localID, out childPrim))
  704. {
  705. SceneObjectPart part = childPrim as SceneObjectPart;
  706. if (part != null)
  707. {
  708. SceneObjectGroup obj = part.ParentGroup;
  709. // If the touched prim handles touches, deliver it
  710. // If not, deliver to root prim
  711. m_parentScene.EventManager.TriggerObjectDeGrab(part, part, remoteClient, surfaceArg);
  712. if ((part.LocalId != obj.RootPart.LocalId))
  713. {
  714. const int PASS_IF_NOT_HANDLED = 0;
  715. const int PASS_ALWAYS = 1;
  716. const int PASS_NEVER = 2;
  717. if (part.PassTouch == PASS_NEVER)
  718. {
  719. }
  720. if (part.PassTouch == PASS_ALWAYS)
  721. {
  722. m_parentScene.EventManager.TriggerObjectDeGrab(obj.RootPart, part, remoteClient, surfaceArg);
  723. }
  724. else if ((((part.ScriptEvents & scriptEvents.touch_start) == 0) ||
  725. ((part.ScriptEvents & scriptEvents.touch_end) == 0)) &&
  726. part.PassTouch == PASS_IF_NOT_HANDLED) //If no event in this prim, pass to parent
  727. {
  728. m_parentScene.EventManager.TriggerObjectDeGrab(obj.RootPart, part, remoteClient,
  729. surfaceArg);
  730. }
  731. }
  732. }
  733. }
  734. }
  735. /// <summary>
  736. /// Gets a new rez location based on the raycast and the size of the object that is being rezzed.
  737. /// </summary>
  738. /// <param name="RayStart"></param>
  739. /// <param name="RayEnd"></param>
  740. /// <param name="RayTargetID"></param>
  741. /// <param name="rot"></param>
  742. /// <param name="bypassRayCast"></param>
  743. /// <param name="RayEndIsIntersection"></param>
  744. /// <param name="frontFacesOnly"></param>
  745. /// <param name="scale"></param>
  746. /// <param name="FaceCenter"></param>
  747. /// <returns></returns>
  748. public Vector3 GetNewRezLocation(Vector3 RayStart, Vector3 RayEnd, UUID RayTargetID, Quaternion rot,
  749. byte bypassRayCast, byte RayEndIsIntersection, bool frontFacesOnly,
  750. Vector3 scale, bool FaceCenter)
  751. {
  752. Vector3 pos = Vector3.Zero;
  753. if (RayEndIsIntersection == 1)
  754. {
  755. pos = RayEnd;
  756. return pos;
  757. }
  758. if (RayTargetID != UUID.Zero)
  759. {
  760. ISceneChildEntity target = m_parentScene.GetSceneObjectPart(RayTargetID);
  761. Vector3 direction = Vector3.Normalize(RayEnd - RayStart);
  762. Vector3 AXOrigin = new Vector3(RayStart.X, RayStart.Y, RayStart.Z);
  763. Vector3 AXdirection = new Vector3(direction.X, direction.Y, direction.Z);
  764. if (target != null)
  765. {
  766. pos = target.AbsolutePosition;
  767. //MainConsole.Instance.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());
  768. // TODO: Raytrace better here
  769. //EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection));
  770. Ray NewRay = new Ray(AXOrigin, AXdirection);
  771. // Ray Trace against target here
  772. EntityIntersection ei = target.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly,
  773. FaceCenter);
  774. // Un-comment out the following line to Get Raytrace results printed to the console.
  775. //MainConsole.Instance.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  776. float ScaleOffset = 0.5f;
  777. // If we hit something
  778. if (ei.HitTF)
  779. {
  780. Vector3 scaleComponent = new Vector3(ei.AAfaceNormal.X, ei.AAfaceNormal.Y, ei.AAfaceNormal.Z);
  781. if (scaleComponent.X != 0) ScaleOffset = scale.X;
  782. if (scaleComponent.Y != 0) ScaleOffset = scale.Y;
  783. if (scaleComponent.Z != 0) ScaleOffset = scale.Z;
  784. ScaleOffset = Math.Abs(ScaleOffset);
  785. Vector3 intersectionpoint = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
  786. Vector3 normal = new Vector3(ei.normal.X, ei.normal.Y, ei.normal.Z);
  787. // Set the position to the intersection point
  788. Vector3 offset = (normal*(ScaleOffset/2f));
  789. pos = (intersectionpoint + offset);
  790. //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
  791. //And in cases when we weren't rezzing from inventory we were re-adding the 0.25 straight after calling this method
  792. // Un-offset the prim (it gets offset later by the consumer method)
  793. //pos.Z -= 0.25F;
  794. }
  795. return pos;
  796. }
  797. else
  798. {
  799. // We don't have a target here, so we're going to raytrace all the objects in the scene.
  800. EntityIntersection ei = GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection), true, false);
  801. // Un-comment the following line to print the raytrace results to the console.
  802. //MainConsole.Instance.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  803. pos = ei.HitTF ? new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z) : RayEnd;
  804. return pos;
  805. }
  806. }
  807. // fall back to our stupid functionality
  808. pos = RayEnd;
  809. //increase height so its above the ground.
  810. //should be getting the normal of the ground at the rez point and using that?
  811. pos.Z += scale.Z/2f;
  812. return pos;
  813. }
  814. public virtual void AddNewPrim(UUID ownerID, UUID groupID, Vector3 RayEnd, Quaternion rot,
  815. PrimitiveBaseShape shape,
  816. byte bypassRaycast, Vector3 RayStart, UUID RayTargetID,
  817. byte RayEndIsIntersection)
  818. {
  819. Vector3 pos = GetNewRezLocation(RayStart, RayEnd, RayTargetID, rot, bypassRaycast, RayEndIsIntersection,
  820. true, new Vector3(0.5f, 0.5f, 0.5f), false);
  821. string reason;
  822. if (m_parentScene.Permissions.CanRezObject(1, ownerID, pos, out reason))
  823. {
  824. AddNewPrim(ownerID, groupID, pos, rot, shape);
  825. }
  826. else
  827. {
  828. GetScenePresence(ownerID)
  829. .ControllingClient.SendAlertMessage("You do not have permission to rez objects here: " + reason);
  830. }
  831. }
  832. /// <summary>
  833. /// Create a New SceneObjectGroup/Part by raycasting
  834. /// </summary>
  835. /// <param name="ownerID"></param>
  836. /// <param name="groupID"></param>
  837. /// <param name="pos"></param>
  838. /// <param name="rot"></param>
  839. /// <param name="shape"></param>
  840. public virtual ISceneEntity AddNewPrim(
  841. UUID ownerID, UUID groupID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape)
  842. {
  843. SceneObjectGroup sceneObject = new SceneObjectGroup(ownerID, pos, rot, shape, m_DefaultObjectName,
  844. m_parentScene);
  845. // If an entity creator has been registered for this prim type then use that
  846. if (m_entityCreators.ContainsKey((PCode) shape.PCode))
  847. {
  848. sceneObject =
  849. (SceneObjectGroup)
  850. m_entityCreators[(PCode) shape.PCode].CreateEntity(sceneObject, ownerID, groupID, pos, rot, shape);
  851. }
  852. else
  853. {
  854. // Otherwise, use this default creation code;
  855. sceneObject.SetGroup(groupID, ownerID, false);
  856. AddPrimToScene(sceneObject);
  857. sceneObject.ScheduleGroupUpdate(PrimUpdateFlags.ForcedFullUpdate);
  858. }
  859. return sceneObject;
  860. }
  861. /// <summary>
  862. /// Duplicates object specified by localID at position raycasted against RayTargetObject using
  863. /// RayEnd and RayStart to determine what the angle of the ray is
  864. /// </summary>
  865. /// <param name="localID">ID of object to duplicate</param>
  866. /// <param name="dupeFlags"></param>
  867. /// <param name="AgentID">Agent doing the duplication</param>
  868. /// <param name="GroupID">Group of new object</param>
  869. /// <param name="RayTargetObj">The target of the Ray</param>
  870. /// <param name="RayEnd">The ending of the ray (farthest away point)</param>
  871. /// <param name="RayStart">The Beginning of the ray (closest point)</param>
  872. /// <param name="BypassRaycast">Bool to bypass raycasting</param>
  873. /// <param name="RayEndIsIntersection">The End specified is the place to add the object</param>
  874. /// <param name="CopyCenters">Position the object at the center of the face that it's colliding with</param>
  875. /// <param name="CopyRotates">Rotate the object the same as the localID object</param>
  876. public void doObjectDuplicateOnRay(uint localID, uint dupeFlags, UUID AgentID, UUID GroupID,
  877. UUID RayTargetObj, Vector3 RayEnd, Vector3 RayStart,
  878. bool BypassRaycast, bool RayEndIsIntersection, bool CopyCenters,
  879. bool CopyRotates)
  880. {
  881. const bool frontFacesOnly = true;
  882. //MainConsole.Instance.Info("HITTARGET: " + RayTargetObj.ToString() + ", COPYTARGET: " + localID.ToString());
  883. ISceneChildEntity target = m_parentScene.GetSceneObjectPart(localID);
  884. ISceneChildEntity target2 = m_parentScene.GetSceneObjectPart(RayTargetObj);
  885. IScenePresence Sp = GetScenePresence(AgentID);
  886. if (target != null && target2 != null)
  887. {
  888. Vector3 pos;
  889. if (EnableFakeRaycasting)
  890. {
  891. RayStart = Sp.CameraPosition;
  892. RayEnd = pos = target2.AbsolutePosition;
  893. }
  894. Vector3 direction = Vector3.Normalize(RayEnd - RayStart);
  895. Vector3 AXOrigin = new Vector3(RayStart.X, RayStart.Y, RayStart.Z);
  896. Vector3 AXdirection = new Vector3(direction.X, direction.Y, direction.Z);
  897. if (target2.ParentEntity != null)
  898. {
  899. pos = target2.AbsolutePosition;
  900. // TODO: Raytrace better here
  901. //EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection), false, false);
  902. Ray NewRay = new Ray(AXOrigin, AXdirection);
  903. // Ray Trace against target here
  904. EntityIntersection ei = target2.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly,
  905. CopyCenters);
  906. // Un-comment out the following line to Get Raytrace results printed to the console.
  907. //MainConsole.Instance.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  908. float ScaleOffset = 0.5f;
  909. // If we hit something
  910. if (ei.HitTF)
  911. {
  912. Vector3 scale = target.Scale;
  913. Vector3 scaleComponent = new Vector3(ei.AAfaceNormal.X, ei.AAfaceNormal.Y, ei.AAfaceNormal.Z);
  914. if (scaleComponent.X != 0) ScaleOffset = scale.X;
  915. if (scaleComponent.Y != 0) ScaleOffset = scale.Y;
  916. if (scaleComponent.Z != 0) ScaleOffset = scale.Z;
  917. ScaleOffset = Math.Abs(ScaleOffset);
  918. Vector3 intersectionpoint = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
  919. Vector3 normal = new Vector3(ei.normal.X, ei.normal.Y, ei.normal.Z);
  920. Vector3 offset = normal*(ScaleOffset/2f);
  921. pos = intersectionpoint + offset;
  922. // stick in offset format from the original prim
  923. pos = pos - target.ParentEntity.AbsolutePosition;
  924. if (CopyRotates)
  925. {
  926. Quaternion worldRot = target2.GetWorldRotation();
  927. // SceneObjectGroup obj = m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID, worldRot);
  928. DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID, worldRot);
  929. //obj.Rotation = worldRot;
  930. //obj.UpdateGroupRotationR(worldRot);
  931. }
  932. else
  933. {
  934. DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID,
  935. Quaternion.Identity);
  936. }
  937. }
  938. return;
  939. }
  940. return;
  941. }
  942. }
  943. /// <value>
  944. /// Registered classes that are capable of creating entities.
  945. /// </value>
  946. protected Dictionary<PCode, IEntityCreator> m_entityCreators = new Dictionary<PCode, IEntityCreator>();
  947. public void RegisterEntityCreatorModule(IEntityCreator entityCreator)
  948. {
  949. lock (m_entityCreators)
  950. {
  951. foreach (PCode pcode in entityCreator.CreationCapabilities)
  952. {
  953. m_entityCreators[pcode] = entityCreator;
  954. }
  955. }
  956. }
  957. /// <summary>
  958. /// Unregister a module commander and all its commands
  959. /// </summary>
  960. /// <param name="entityCreator"></param>
  961. public void UnregisterEntityCreatorCommander(IEntityCreator entityCreator)
  962. {
  963. lock (m_entityCreators)
  964. {
  965. foreach (PCode pcode in entityCreator.CreationC

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