PageRenderTime 83ms CodeModel.GetById 29ms RepoModel.GetById 4ms app.codeStats 1ms

/OpenSim/Region/Framework/Scenes/ScenePresence.cs

https://gitlab.com/N3X15/VoxelSim
C# | 3751 lines | 2378 code | 522 blank | 851 comment | 532 complexity | 7f20658cddec888950a40227101fff65 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 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.Collections.Generic;
  29. using System.Reflection;
  30. using System.Timers;
  31. using OpenMetaverse;
  32. using log4net;
  33. using OpenSim.Framework;
  34. using OpenSim.Framework.Client;
  35. using OpenSim.Region.Framework.Interfaces;
  36. using OpenSim.Region.Framework.Scenes.Animation;
  37. using OpenSim.Region.Framework.Scenes.Types;
  38. using OpenSim.Region.Physics.Manager;
  39. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  40. using OpenSim.Services.Interfaces;
  41. namespace OpenSim.Region.Framework.Scenes
  42. {
  43. enum ScriptControlled : uint
  44. {
  45. CONTROL_ZERO = 0,
  46. CONTROL_FWD = 1,
  47. CONTROL_BACK = 2,
  48. CONTROL_LEFT = 4,
  49. CONTROL_RIGHT = 8,
  50. CONTROL_UP = 16,
  51. CONTROL_DOWN = 32,
  52. CONTROL_ROT_LEFT = 256,
  53. CONTROL_ROT_RIGHT = 512,
  54. CONTROL_LBUTTON = 268435456,
  55. CONTROL_ML_LBUTTON = 1073741824
  56. }
  57. struct ScriptControllers
  58. {
  59. public UUID itemID;
  60. public ScriptControlled ignoreControls;
  61. public ScriptControlled eventControls;
  62. }
  63. public delegate void SendCourseLocationsMethod(UUID scene, ScenePresence presence, List<Vector3> coarseLocations, List<UUID> avatarUUIDs);
  64. public class ScenePresence : EntityBase, ISceneEntity
  65. {
  66. // ~ScenePresence()
  67. // {
  68. // m_log.Debug("[ScenePresence] Destructor called");
  69. // }
  70. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  71. // private static readonly byte[] DEFAULT_TEXTURE = AvatarAppearance.GetDefaultTexture().GetBytes();
  72. private static readonly Array DIR_CONTROL_FLAGS = Enum.GetValues(typeof(Dir_ControlFlags));
  73. private static readonly Vector3 HEAD_ADJUSTMENT = new Vector3(0f, 0f, 0.3f);
  74. /// <summary>
  75. /// Experimentally determined "fudge factor" to make sit-target positions
  76. /// the same as in SecondLife. Fudge factor was tested for 36 different
  77. /// test cases including prims of type box, sphere, cylinder, and torus,
  78. /// with varying parameters for sit target location, prim size, prim
  79. /// rotation, prim cut, prim twist, prim taper, and prim shear. See mantis
  80. /// issue #1716
  81. /// </summary>
  82. private static readonly Vector3 SIT_TARGET_ADJUSTMENT = new Vector3(0.1f, 0.0f, 0.3f);
  83. public UUID currentParcelUUID = UUID.Zero;
  84. private ISceneViewer m_sceneViewer;
  85. /// <value>
  86. /// The animator for this avatar
  87. /// </value>
  88. public ScenePresenceAnimator Animator
  89. {
  90. get { return m_animator; }
  91. }
  92. protected ScenePresenceAnimator m_animator;
  93. /// <value>
  94. /// The scene objects attached to this avatar. Do not change this list directly - use methods such as
  95. /// AddAttachment() and RemoveAttachment(). Lock this list when performing any read operations upon it.
  96. /// </value>
  97. public List<SceneObjectGroup> Attachments
  98. {
  99. get { return m_attachments; }
  100. }
  101. protected List<SceneObjectGroup> m_attachments = new List<SceneObjectGroup>();
  102. private Dictionary<UUID, ScriptControllers> scriptedcontrols = new Dictionary<UUID, ScriptControllers>();
  103. private ScriptControlled IgnoredControls = ScriptControlled.CONTROL_ZERO;
  104. private ScriptControlled LastCommands = ScriptControlled.CONTROL_ZERO;
  105. private bool MouseDown = false;
  106. private SceneObjectGroup proxyObjectGroup;
  107. //private SceneObjectPart proxyObjectPart = null;
  108. public Vector3 lastKnownAllowedPosition;
  109. public bool sentMessageAboutRestrictedParcelFlyingDown;
  110. public Vector4 CollisionPlane = Vector4.UnitW;
  111. private Vector3 m_lastPosition;
  112. private Quaternion m_lastRotation;
  113. private Vector3 m_lastVelocity;
  114. //private int m_lastTerseSent;
  115. private bool m_updateflag;
  116. private byte m_movementflag;
  117. private Vector3? m_forceToApply;
  118. private uint m_requestedSitTargetID;
  119. private UUID m_requestedSitTargetUUID;
  120. public bool SitGround = false;
  121. private SendCourseLocationsMethod m_sendCourseLocationsMethod;
  122. //private Vector3 m_requestedSitOffset = new Vector3();
  123. private Vector3 m_LastFinitePos;
  124. private float m_sitAvatarHeight = 2.0f;
  125. private int m_godLevel;
  126. private int m_userLevel;
  127. private bool m_invulnerable = true;
  128. private Vector3 m_lastChildAgentUpdatePosition;
  129. private Vector3 m_lastChildAgentUpdateCamPosition;
  130. private int m_perfMonMS;
  131. private bool m_setAlwaysRun;
  132. private bool m_forceFly;
  133. private bool m_flyDisabled;
  134. private float m_speedModifier = 1.0f;
  135. private Quaternion m_bodyRot= Quaternion.Identity;
  136. private Quaternion m_bodyRotPrevious = Quaternion.Identity;
  137. private const int LAND_VELOCITYMAG_MAX = 12;
  138. public bool IsRestrictedToRegion;
  139. public string JID = String.Empty;
  140. private float m_health = 100f;
  141. protected RegionInfo m_regionInfo;
  142. protected ulong crossingFromRegion;
  143. private readonly Vector3[] Dir_Vectors = new Vector3[9];
  144. // Position of agent's camera in world (region cordinates)
  145. protected Vector3 m_CameraCenter;
  146. protected Vector3 m_lastCameraCenter;
  147. protected Timer m_reprioritization_timer;
  148. protected bool m_reprioritizing;
  149. protected bool m_reprioritization_called;
  150. // Use these three vectors to figure out what the agent is looking at
  151. // Convert it to a Matrix and/or Quaternion
  152. protected Vector3 m_CameraAtAxis;
  153. protected Vector3 m_CameraLeftAxis;
  154. protected Vector3 m_CameraUpAxis;
  155. private AgentManager.ControlFlags m_AgentControlFlags;
  156. private Quaternion m_headrotation = Quaternion.Identity;
  157. private byte m_state;
  158. //Reuse the Vector3 instead of creating a new one on the UpdateMovement method
  159. // private Vector3 movementvector;
  160. private bool m_autopilotMoving;
  161. private Vector3 m_autoPilotTarget;
  162. private bool m_sitAtAutoTarget;
  163. private string m_nextSitAnimation = String.Empty;
  164. //PauPaw:Proper PID Controler for autopilot************
  165. private bool m_moveToPositionInProgress;
  166. private Vector3 m_moveToPositionTarget;
  167. private bool m_followCamAuto;
  168. private int m_movementUpdateCount;
  169. private const int NumMovementsBetweenRayCast = 5;
  170. private bool CameraConstraintActive;
  171. //private int m_moveToPositionStateStatus;
  172. //*****************************************************
  173. // Agent's Draw distance.
  174. protected float m_DrawDistance;
  175. protected AvatarAppearance m_appearance;
  176. // neighbouring regions we have enabled a child agent in
  177. // holds the seed cap for the child agent in that region
  178. private Dictionary<ulong, string> m_knownChildRegions = new Dictionary<ulong, string>();
  179. /// <summary>
  180. /// Implemented Control Flags
  181. /// </summary>
  182. private enum Dir_ControlFlags
  183. {
  184. DIR_CONTROL_FLAG_FORWARD = AgentManager.ControlFlags.AGENT_CONTROL_AT_POS,
  185. DIR_CONTROL_FLAG_BACK = AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG,
  186. DIR_CONTROL_FLAG_LEFT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS,
  187. DIR_CONTROL_FLAG_RIGHT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG,
  188. DIR_CONTROL_FLAG_UP = AgentManager.ControlFlags.AGENT_CONTROL_UP_POS,
  189. DIR_CONTROL_FLAG_DOWN = AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG,
  190. DIR_CONTROL_FLAG_FORWARD_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS,
  191. DIR_CONTROL_FLAG_BACKWARD_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_NEG,
  192. DIR_CONTROL_FLAG_DOWN_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG
  193. }
  194. /// <summary>
  195. /// Position at which a significant movement was made
  196. /// </summary>
  197. private Vector3 posLastSignificantMove;
  198. // For teleports and crossings callbacks
  199. string m_callbackURI;
  200. UUID m_originRegionID;
  201. ulong m_rootRegionHandle;
  202. /// <value>
  203. /// Script engines present in the scene
  204. /// </value>
  205. private IScriptModule[] m_scriptEngines;
  206. #region Properties
  207. /// <summary>
  208. /// Physical scene representation of this Avatar.
  209. /// </summary>
  210. public PhysicsActor PhysicsActor
  211. {
  212. set { m_physicsActor = value; }
  213. get { return m_physicsActor; }
  214. }
  215. public byte MovementFlag
  216. {
  217. set { m_movementflag = value; }
  218. get { return m_movementflag; }
  219. }
  220. public bool Updated
  221. {
  222. set { m_updateflag = value; }
  223. get { return m_updateflag; }
  224. }
  225. public bool Invulnerable
  226. {
  227. set { m_invulnerable = value; }
  228. get { return m_invulnerable; }
  229. }
  230. public int UserLevel
  231. {
  232. get { return m_userLevel; }
  233. }
  234. public int GodLevel
  235. {
  236. get { return m_godLevel; }
  237. }
  238. public ulong RegionHandle
  239. {
  240. get { return m_rootRegionHandle; }
  241. }
  242. public Vector3 CameraPosition
  243. {
  244. get { return m_CameraCenter; }
  245. }
  246. public Quaternion CameraRotation
  247. {
  248. get { return Util.Axes2Rot(m_CameraAtAxis, m_CameraLeftAxis, m_CameraUpAxis); }
  249. }
  250. public Vector3 CameraAtAxis
  251. {
  252. get { return m_CameraAtAxis; }
  253. }
  254. public Vector3 CameraLeftAxis
  255. {
  256. get { return m_CameraLeftAxis; }
  257. }
  258. public Vector3 CameraUpAxis
  259. {
  260. get { return m_CameraUpAxis; }
  261. }
  262. public Vector3 Lookat
  263. {
  264. get
  265. {
  266. Vector3 a = new Vector3(m_CameraAtAxis.X, m_CameraAtAxis.Y, 0);
  267. if (a == Vector3.Zero)
  268. return a;
  269. return Util.GetNormalizedVector(a);
  270. }
  271. }
  272. private readonly string m_firstname;
  273. public string Firstname
  274. {
  275. get { return m_firstname; }
  276. }
  277. private readonly string m_lastname;
  278. public string Lastname
  279. {
  280. get { return m_lastname; }
  281. }
  282. private string m_grouptitle;
  283. public string Grouptitle
  284. {
  285. get { return m_grouptitle; }
  286. set { m_grouptitle = value; }
  287. }
  288. public float DrawDistance
  289. {
  290. get { return m_DrawDistance; }
  291. }
  292. protected bool m_allowMovement = true;
  293. public bool AllowMovement
  294. {
  295. get { return m_allowMovement; }
  296. set { m_allowMovement = value; }
  297. }
  298. public bool SetAlwaysRun
  299. {
  300. get
  301. {
  302. if (PhysicsActor != null)
  303. {
  304. return PhysicsActor.SetAlwaysRun;
  305. }
  306. else
  307. {
  308. return m_setAlwaysRun;
  309. }
  310. }
  311. set
  312. {
  313. m_setAlwaysRun = value;
  314. if (PhysicsActor != null)
  315. {
  316. PhysicsActor.SetAlwaysRun = value;
  317. }
  318. }
  319. }
  320. public byte State
  321. {
  322. get { return m_state; }
  323. set { m_state = value; }
  324. }
  325. public uint AgentControlFlags
  326. {
  327. get { return (uint)m_AgentControlFlags; }
  328. set { m_AgentControlFlags = (AgentManager.ControlFlags)value; }
  329. }
  330. /// <summary>
  331. /// This works out to be the ClientView object associated with this avatar, or it's client connection manager
  332. /// </summary>
  333. private IClientAPI m_controllingClient;
  334. protected PhysicsActor m_physicsActor;
  335. /// <value>
  336. /// The client controlling this presence
  337. /// </value>
  338. public IClientAPI ControllingClient
  339. {
  340. get { return m_controllingClient; }
  341. }
  342. public IClientCore ClientView
  343. {
  344. get { return (IClientCore) m_controllingClient; }
  345. }
  346. protected Vector3 m_parentPosition;
  347. public Vector3 ParentPosition
  348. {
  349. get { return m_parentPosition; }
  350. set { m_parentPosition = value; }
  351. }
  352. /// <summary>
  353. /// Position of this avatar relative to the region the avatar is in
  354. /// </summary>
  355. public override Vector3 AbsolutePosition
  356. {
  357. get
  358. {
  359. PhysicsActor actor = m_physicsActor;
  360. if (actor != null)
  361. m_pos = actor.Position;
  362. return m_parentPosition + m_pos;
  363. }
  364. set
  365. {
  366. PhysicsActor actor = m_physicsActor;
  367. if (actor != null)
  368. {
  369. try
  370. {
  371. lock (m_scene.SyncRoot)
  372. m_physicsActor.Position = value;
  373. }
  374. catch (Exception e)
  375. {
  376. m_log.Error("[SCENEPRESENCE]: ABSOLUTE POSITION " + e.Message);
  377. }
  378. }
  379. m_pos = value;
  380. m_parentPosition = Vector3.Zero;
  381. }
  382. }
  383. public Vector3 OffsetPosition
  384. {
  385. get { return m_pos; }
  386. set { m_pos = value; }
  387. }
  388. /// <summary>
  389. /// Current velocity of the avatar.
  390. /// </summary>
  391. public override Vector3 Velocity
  392. {
  393. get
  394. {
  395. PhysicsActor actor = m_physicsActor;
  396. if (actor != null)
  397. m_velocity = actor.Velocity;
  398. return m_velocity;
  399. }
  400. set
  401. {
  402. PhysicsActor actor = m_physicsActor;
  403. if (actor != null)
  404. {
  405. try
  406. {
  407. lock (m_scene.SyncRoot)
  408. actor.Velocity = value;
  409. }
  410. catch (Exception e)
  411. {
  412. m_log.Error("[SCENEPRESENCE]: VELOCITY " + e.Message);
  413. }
  414. }
  415. m_velocity = value;
  416. }
  417. }
  418. public Quaternion Rotation
  419. {
  420. get { return m_bodyRot; }
  421. set { m_bodyRot = value; }
  422. }
  423. public Quaternion PreviousRotation
  424. {
  425. get { return m_bodyRotPrevious; }
  426. set { m_bodyRotPrevious = value; }
  427. }
  428. /// <summary>
  429. /// If this is true, agent doesn't have a representation in this scene.
  430. /// this is an agent 'looking into' this scene from a nearby scene(region)
  431. ///
  432. /// if False, this agent has a representation in this scene
  433. /// </summary>
  434. private bool m_isChildAgent = true;
  435. public bool IsChildAgent
  436. {
  437. get { return m_isChildAgent; }
  438. set { m_isChildAgent = value; }
  439. }
  440. private uint m_parentID;
  441. public uint ParentID
  442. {
  443. get { return m_parentID; }
  444. set { m_parentID = value; }
  445. }
  446. public float Health
  447. {
  448. get { return m_health; }
  449. set { m_health = value; }
  450. }
  451. /// <summary>
  452. /// These are the region handles known by the avatar.
  453. /// </summary>
  454. public List<ulong> KnownChildRegionHandles
  455. {
  456. get
  457. {
  458. if (m_knownChildRegions.Count == 0)
  459. return new List<ulong>();
  460. else
  461. return new List<ulong>(m_knownChildRegions.Keys);
  462. }
  463. }
  464. public Dictionary<ulong, string> KnownRegions
  465. {
  466. get { return m_knownChildRegions; }
  467. set
  468. {
  469. m_knownChildRegions = value;
  470. }
  471. }
  472. public ISceneViewer SceneViewer
  473. {
  474. get { return m_sceneViewer; }
  475. }
  476. public void AdjustKnownSeeds()
  477. {
  478. Dictionary<ulong, string> seeds;
  479. if (Scene.CapsModule != null)
  480. seeds = Scene.CapsModule.GetChildrenSeeds(UUID);
  481. else
  482. seeds = new Dictionary<ulong, string>();
  483. List<ulong> old = new List<ulong>();
  484. foreach (ulong handle in seeds.Keys)
  485. {
  486. uint x, y;
  487. Utils.LongToUInts(handle, out x, out y);
  488. x = x / Constants.RegionSize;
  489. y = y / Constants.RegionSize;
  490. if (Util.IsOutsideView(x, Scene.RegionInfo.RegionLocX, y, Scene.RegionInfo.RegionLocY))
  491. {
  492. old.Add(handle);
  493. }
  494. }
  495. DropOldNeighbours(old);
  496. if (Scene.CapsModule != null)
  497. Scene.CapsModule.SetChildrenSeed(UUID, seeds);
  498. KnownRegions = seeds;
  499. //m_log.Debug(" ++++++++++AFTER+++++++++++++ ");
  500. //DumpKnownRegions();
  501. }
  502. public void DumpKnownRegions()
  503. {
  504. m_log.Info("================ KnownRegions "+Scene.RegionInfo.RegionName+" ================");
  505. foreach (KeyValuePair<ulong, string> kvp in KnownRegions)
  506. {
  507. uint x, y;
  508. Utils.LongToUInts(kvp.Key, out x, out y);
  509. x = x / Constants.RegionSize;
  510. y = y / Constants.RegionSize;
  511. m_log.Info(" >> "+x+", "+y+": "+kvp.Value);
  512. }
  513. }
  514. private bool m_inTransit;
  515. private bool m_mouseLook;
  516. private bool m_leftButtonDown;
  517. public bool IsInTransit
  518. {
  519. get { return m_inTransit; }
  520. set { m_inTransit = value; }
  521. }
  522. public float SpeedModifier
  523. {
  524. get { return m_speedModifier; }
  525. set { m_speedModifier = value; }
  526. }
  527. public bool ForceFly
  528. {
  529. get { return m_forceFly; }
  530. set { m_forceFly = value; }
  531. }
  532. public bool FlyDisabled
  533. {
  534. get { return m_flyDisabled; }
  535. set { m_flyDisabled = value; }
  536. }
  537. public string Viewer
  538. {
  539. get { return m_scene.AuthenticateHandler.GetAgentCircuitData(ControllingClient.CircuitCode).Viewer; }
  540. }
  541. #endregion
  542. #region Constructor(s)
  543. public ScenePresence()
  544. {
  545. m_sendCourseLocationsMethod = SendCoarseLocationsDefault;
  546. CreateSceneViewer();
  547. m_animator = new ScenePresenceAnimator(this);
  548. }
  549. private ScenePresence(IClientAPI client, Scene world, RegionInfo reginfo) : this()
  550. {
  551. m_rootRegionHandle = reginfo.RegionHandle;
  552. m_controllingClient = client;
  553. m_firstname = m_controllingClient.FirstName;
  554. m_lastname = m_controllingClient.LastName;
  555. m_name = String.Format("{0} {1}", m_firstname, m_lastname);
  556. m_scene = world;
  557. m_uuid = client.AgentId;
  558. m_regionInfo = reginfo;
  559. m_localId = m_scene.AllocateLocalId();
  560. UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, m_uuid);
  561. if (account != null)
  562. m_userLevel = account.UserLevel;
  563. IGroupsModule gm = m_scene.RequestModuleInterface<IGroupsModule>();
  564. if (gm != null)
  565. m_grouptitle = gm.GetGroupTitle(m_uuid);
  566. m_scriptEngines = m_scene.RequestModuleInterfaces<IScriptModule>();
  567. AbsolutePosition = posLastSignificantMove = m_CameraCenter =
  568. m_lastCameraCenter = m_controllingClient.StartPos;
  569. m_reprioritization_timer = new Timer(world.ReprioritizationInterval);
  570. m_reprioritization_timer.Elapsed += new ElapsedEventHandler(Reprioritize);
  571. m_reprioritization_timer.AutoReset = false;
  572. AdjustKnownSeeds();
  573. // TODO: I think, this won't send anything, as we are still a child here...
  574. Animator.TrySetMovementAnimation("STAND");
  575. // we created a new ScenePresence (a new child agent) in a fresh region.
  576. // Request info about all the (root) agents in this region
  577. // Note: This won't send data *to* other clients in that region (children don't send)
  578. // MIC: This gets called again in CompleteMovement
  579. SendInitialFullUpdateToAllClients();
  580. RegisterToEvents();
  581. SetDirectionVectors();
  582. }
  583. public ScenePresence(IClientAPI client, Scene world, RegionInfo reginfo, AvatarAppearance appearance)
  584. : this(client, world, reginfo)
  585. {
  586. m_appearance = appearance;
  587. }
  588. private void CreateSceneViewer()
  589. {
  590. m_sceneViewer = new SceneViewer(this);
  591. }
  592. public void RegisterToEvents()
  593. {
  594. m_controllingClient.OnCompleteMovementToRegion += CompleteMovement;
  595. //m_controllingClient.OnCompleteMovementToRegion += SendInitialData;
  596. m_controllingClient.OnAgentUpdate += HandleAgentUpdate;
  597. m_controllingClient.OnAgentRequestSit += HandleAgentRequestSit;
  598. m_controllingClient.OnAgentSit += HandleAgentSit;
  599. m_controllingClient.OnSetAlwaysRun += HandleSetAlwaysRun;
  600. m_controllingClient.OnStartAnim += HandleStartAnim;
  601. m_controllingClient.OnStopAnim += HandleStopAnim;
  602. m_controllingClient.OnForceReleaseControls += HandleForceReleaseControls;
  603. m_controllingClient.OnAutoPilotGo += DoAutoPilot;
  604. m_controllingClient.AddGenericPacketHandler("autopilot", DoMoveToPosition);
  605. // ControllingClient.OnChildAgentStatus += new StatusChange(this.ChildStatusChange);
  606. // ControllingClient.OnStopMovement += new GenericCall2(this.StopMovement);
  607. }
  608. private void SetDirectionVectors()
  609. {
  610. Dir_Vectors[0] = Vector3.UnitX; //FORWARD
  611. Dir_Vectors[1] = -Vector3.UnitX; //BACK
  612. Dir_Vectors[2] = Vector3.UnitY; //LEFT
  613. Dir_Vectors[3] = -Vector3.UnitY; //RIGHT
  614. Dir_Vectors[4] = Vector3.UnitZ; //UP
  615. Dir_Vectors[5] = -Vector3.UnitZ; //DOWN
  616. Dir_Vectors[8] = new Vector3(0f, 0f, -0.5f); //DOWN_Nudge
  617. Dir_Vectors[6] = Vector3.UnitX*2; //FORWARD
  618. Dir_Vectors[7] = -Vector3.UnitX; //BACK
  619. }
  620. private Vector3[] GetWalkDirectionVectors()
  621. {
  622. Vector3[] vector = new Vector3[9];
  623. vector[0] = new Vector3(m_CameraUpAxis.Z, 0f, -m_CameraAtAxis.Z); //FORWARD
  624. vector[1] = new Vector3(-m_CameraUpAxis.Z, 0f, m_CameraAtAxis.Z); //BACK
  625. vector[2] = Vector3.UnitY; //LEFT
  626. vector[3] = -Vector3.UnitY; //RIGHT
  627. vector[4] = new Vector3(m_CameraAtAxis.Z, 0f, m_CameraUpAxis.Z); //UP
  628. vector[5] = new Vector3(-m_CameraAtAxis.Z, 0f, -m_CameraUpAxis.Z); //DOWN
  629. vector[8] = new Vector3(-m_CameraAtAxis.Z, 0f, -m_CameraUpAxis.Z); //DOWN_Nudge
  630. vector[6] = (new Vector3(m_CameraUpAxis.Z, 0f, -m_CameraAtAxis.Z) * 2); //FORWARD Nudge
  631. vector[7] = new Vector3(-m_CameraUpAxis.Z, 0f, m_CameraAtAxis.Z); //BACK Nudge
  632. return vector;
  633. }
  634. #endregion
  635. public uint GenerateClientFlags(UUID ObjectID)
  636. {
  637. return m_scene.Permissions.GenerateClientFlags(m_uuid, ObjectID);
  638. }
  639. /// <summary>
  640. /// Send updates to the client about prims which have been placed on the update queue. We don't
  641. /// necessarily send updates for all the parts on the queue, e.g. if an updates with a more recent
  642. /// timestamp has already been sent.
  643. /// </summary>
  644. public void SendPrimUpdates()
  645. {
  646. m_perfMonMS = Util.EnvironmentTickCount();
  647. m_sceneViewer.SendPrimUpdates();
  648. m_scene.StatsReporter.AddAgentTime(Util.EnvironmentTickCountSubtract(m_perfMonMS));
  649. }
  650. #region Status Methods
  651. /// <summary>
  652. /// This turns a child agent, into a root agent
  653. /// This is called when an agent teleports into a region, or if an
  654. /// agent crosses into this region from a neighbor over the border
  655. /// </summary>
  656. public void MakeRootAgent(Vector3 pos, bool isFlying)
  657. {
  658. m_log.DebugFormat(
  659. "[SCENE]: Upgrading child to root agent for {0} in {1}",
  660. Name, m_scene.RegionInfo.RegionName);
  661. //m_log.DebugFormat("[SCENE]: known regions in {0}: {1}", Scene.RegionInfo.RegionName, KnownChildRegionHandles.Count);
  662. IGroupsModule gm = m_scene.RequestModuleInterface<IGroupsModule>();
  663. if (gm != null)
  664. m_grouptitle = gm.GetGroupTitle(m_uuid);
  665. m_rootRegionHandle = m_scene.RegionInfo.RegionHandle;
  666. m_scene.EventManager.TriggerSetRootAgentScene(m_uuid, m_scene);
  667. // Moved this from SendInitialData to ensure that m_appearance is initialized
  668. // before the inventory is processed in MakeRootAgent. This fixes a race condition
  669. // related to the handling of attachments
  670. //m_scene.GetAvatarAppearance(m_controllingClient, out m_appearance);
  671. if (m_scene.TestBorderCross(pos, Cardinals.E))
  672. {
  673. Border crossedBorder = m_scene.GetCrossedBorder(pos, Cardinals.E);
  674. pos.X = crossedBorder.BorderLine.Z - 1;
  675. }
  676. if (m_scene.TestBorderCross(pos, Cardinals.N))
  677. {
  678. Border crossedBorder = m_scene.GetCrossedBorder(pos, Cardinals.N);
  679. pos.Y = crossedBorder.BorderLine.Z - 1;
  680. }
  681. if (pos.X < 0f || pos.Y < 0f || pos.Z < 0f)
  682. {
  683. m_log.WarnFormat(
  684. "[SCENE PRESENCE]: MakeRootAgent() was given an illegal position of {0} for avatar {1}, {2}. Clamping",
  685. pos, Name, UUID);
  686. if (pos.X < 0f) pos.X = 0f;
  687. if (pos.Y < 0f) pos.Y = 0f;
  688. if (pos.Z < 0f) pos.Z = 0f;
  689. }
  690. float localAVHeight = 1.56f;
  691. if (m_appearance != null)
  692. {
  693. if (m_appearance.AvatarHeight > 0)
  694. localAVHeight = m_appearance.AvatarHeight;
  695. }
  696. {
  697. if(m_scene.Voxels.IsInsideTerrain(pos))
  698. {
  699. Vector3 newPos=m_scene.Voxels.FindNearestAirVoxel(pos,true);
  700. newPos.Z+=localAVHeight / 2;
  701. pos=newPos;
  702. }
  703. }
  704. float posZLimit = 0;
  705. AbsolutePosition = pos;
  706. if (m_appearance != null)
  707. {
  708. if (m_appearance.AvatarHeight > 0)
  709. SetHeight(m_appearance.AvatarHeight);
  710. }
  711. else
  712. {
  713. m_log.ErrorFormat("[SCENE PRESENCE]: null appearance in MakeRoot in {0}", Scene.RegionInfo.RegionName);
  714. // emergency; this really shouldn't happen
  715. m_appearance = new AvatarAppearance(UUID);
  716. }
  717. AddToPhysicalScene(isFlying);
  718. if (m_appearance != null)
  719. {
  720. if (m_appearance.AvatarHeight > 0)
  721. SetHeight(m_appearance.AvatarHeight);
  722. }
  723. if (m_forceFly)
  724. {
  725. m_physicsActor.Flying = true;
  726. }
  727. else if (m_flyDisabled)
  728. {
  729. m_physicsActor.Flying = false;
  730. }
  731. // Don't send an animation pack here, since on a region crossing this will sometimes cause a flying
  732. // avatar to return to the standing position in mid-air. On login it looks like this is being sent
  733. // elsewhere anyway
  734. // Animator.SendAnimPack();
  735. m_scene.SwapRootAgentCount(false);
  736. //CachedUserInfo userInfo = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(m_uuid);
  737. //if (userInfo != null)
  738. // userInfo.FetchInventory();
  739. //else
  740. // m_log.ErrorFormat("[SCENE]: Could not find user info for {0} when making it a root agent", m_uuid);
  741. // On the next prim update, all objects will be sent
  742. //
  743. m_sceneViewer.Reset();
  744. m_isChildAgent = false;
  745. // send the animations of the other presences to me
  746. m_scene.ForEachScenePresence(delegate(ScenePresence presence)
  747. {
  748. if (presence != this)
  749. presence.Animator.SendAnimPackToClient(ControllingClient);
  750. });
  751. m_scene.EventManager.TriggerOnMakeRootAgent(this);
  752. }
  753. /// <summary>
  754. /// This turns a root agent into a child agent
  755. /// when an agent departs this region for a neighbor, this gets called.
  756. ///
  757. /// It doesn't get called for a teleport. Reason being, an agent that
  758. /// teleports out may not end up anywhere near this region
  759. /// </summary>
  760. public void MakeChildAgent()
  761. {
  762. // It looks like m_animator is set to null somewhere, and MakeChild
  763. // is called after that. Probably in aborted teleports.
  764. if (m_animator == null)
  765. m_animator = new ScenePresenceAnimator(this);
  766. else
  767. Animator.ResetAnimations();
  768. // m_log.DebugFormat(
  769. // "[SCENEPRESENCE]: Downgrading root agent {0}, {1} to a child agent in {2}",
  770. // Name, UUID, m_scene.RegionInfo.RegionName);
  771. // Don't zero out the velocity since this can cause problems when an avatar is making a region crossing,
  772. // depending on the exact timing. This shouldn't matter anyway since child agent positions are not updated.
  773. //Velocity = new Vector3(0, 0, 0);
  774. m_isChildAgent = true;
  775. m_scene.SwapRootAgentCount(true);
  776. RemoveFromPhysicalScene();
  777. // FIXME: Set m_rootRegionHandle to the region handle of the scene this agent is moving into
  778. m_scene.EventManager.TriggerOnMakeChildAgent(this);
  779. }
  780. /// <summary>
  781. /// Removes physics plugin scene representation of this agent if it exists.
  782. /// </summary>
  783. private void RemoveFromPhysicalScene()
  784. {
  785. if (PhysicsActor != null)
  786. {
  787. m_physicsActor.OnRequestTerseUpdate -= SendTerseUpdateToAllClients;
  788. m_physicsActor.OnOutOfBounds -= OutOfBoundsCall;
  789. m_scene.PhysicsScene.RemoveAvatar(PhysicsActor);
  790. m_physicsActor.UnSubscribeEvents();
  791. m_physicsActor.OnCollisionUpdate -= PhysicsCollisionUpdate;
  792. PhysicsActor = null;
  793. }
  794. }
  795. /// <summary>
  796. ///
  797. /// </summary>
  798. /// <param name="pos"></param>
  799. public void Teleport(Vector3 pos)
  800. {
  801. bool isFlying = false;
  802. if (m_physicsActor != null)
  803. isFlying = m_physicsActor.Flying;
  804. RemoveFromPhysicalScene();
  805. Velocity = Vector3.Zero;
  806. AbsolutePosition = pos;
  807. AddToPhysicalScene(isFlying);
  808. if (m_appearance != null)
  809. {
  810. if (m_appearance.AvatarHeight > 0)
  811. SetHeight(m_appearance.AvatarHeight);
  812. }
  813. SendTerseUpdateToAllClients();
  814. }
  815. public void TeleportWithMomentum(Vector3 pos)
  816. {
  817. bool isFlying = false;
  818. if (m_physicsActor != null)
  819. isFlying = m_physicsActor.Flying;
  820. RemoveFromPhysicalScene();
  821. AbsolutePosition = pos;
  822. AddToPhysicalScene(isFlying);
  823. if (m_appearance != null)
  824. {
  825. if (m_appearance.AvatarHeight > 0)
  826. SetHeight(m_appearance.AvatarHeight);
  827. }
  828. SendTerseUpdateToAllClients();
  829. }
  830. /// <summary>
  831. ///
  832. /// </summary>
  833. public void StopMovement()
  834. {
  835. }
  836. public void StopFlying()
  837. {
  838. ControllingClient.StopFlying(this);
  839. }
  840. public void AddNeighbourRegion(ulong regionHandle, string cap)
  841. {
  842. lock (m_knownChildRegions)
  843. {
  844. if (!m_knownChildRegions.ContainsKey(regionHandle))
  845. {
  846. uint x, y;
  847. Utils.LongToUInts(regionHandle, out x, out y);
  848. m_knownChildRegions.Add(regionHandle, cap);
  849. }
  850. }
  851. }
  852. public void RemoveNeighbourRegion(ulong regionHandle)
  853. {
  854. lock (m_knownChildRegions)
  855. {
  856. if (m_knownChildRegions.ContainsKey(regionHandle))
  857. {
  858. m_knownChildRegions.Remove(regionHandle);
  859. //m_log.Debug(" !!! removing known region {0} in {1}. Count = {2}", regionHandle, Scene.RegionInfo.RegionName, m_knownChildRegions.Count);
  860. }
  861. }
  862. }
  863. public void DropOldNeighbours(List<ulong> oldRegions)
  864. {
  865. foreach (ulong handle in oldRegions)
  866. {
  867. RemoveNeighbourRegion(handle);
  868. Scene.CapsModule.DropChildSeed(UUID, handle);
  869. }
  870. }
  871. public List<ulong> GetKnownRegionList()
  872. {
  873. return new List<ulong>(m_knownChildRegions.Keys);
  874. }
  875. #endregion
  876. #region Event Handlers
  877. /// <summary>
  878. /// Sets avatar height in the phyiscs plugin
  879. /// </summary>
  880. public void SetHeight(float height)
  881. {
  882. if (PhysicsActor != null && !IsChildAgent)
  883. {
  884. Vector3 SetSize = new Vector3(0.45f, 0.6f, height);
  885. PhysicsActor.Size = SetSize;
  886. }
  887. }
  888. /// <summary>
  889. /// Complete Avatar's movement into the region.
  890. /// This is called upon a very important packet sent from the client,
  891. /// so it's client-controlled. Never call this method directly.
  892. /// </summary>
  893. public void CompleteMovement(IClientAPI client)
  894. {
  895. DateTime startTime = DateTime.Now;
  896. m_log.DebugFormat(
  897. "[SCENE PRESENCE]: Completing movement of {0} into region {1}",
  898. client.Name, Scene.RegionInfo.RegionName);
  899. Vector3 look = Velocity;
  900. if ((look.X == 0) && (look.Y == 0) && (look.Z == 0))
  901. {
  902. look = new Vector3(0.99f, 0.042f, 0);
  903. }
  904. // Prevent teleporting to an underground location
  905. // (may crash client otherwise)
  906. //
  907. Vector3 pos = AbsolutePosition;
  908. float ground = m_scene.GetGroundHeight(pos.X, pos.Y);
  909. if (pos.Z < ground + 1.5f)
  910. {
  911. pos.Z = ground + 1.5f;
  912. AbsolutePosition = pos;
  913. }
  914. m_isChildAgent = false;
  915. bool m_flying = ((m_AgentControlFlags & AgentManager.ControlFlags.AGENT_CONTROL_FLY) != 0);
  916. MakeRootAgent(AbsolutePosition, m_flying);
  917. if ((m_callbackURI != null) && !m_callbackURI.Equals(""))
  918. {
  919. m_log.DebugFormat("[SCENE PRESENCE]: Releasing agent in URI {0}", m_callbackURI);
  920. Scene.SimulationService.ReleaseAgent(m_originRegionID, UUID, m_callbackURI);
  921. m_callbackURI = null;
  922. }
  923. //m_log.DebugFormat("Completed movement");
  924. m_controllingClient.MoveAgentIntoRegion(m_regionInfo, AbsolutePosition, look);
  925. SendInitialData();
  926. // Create child agents in neighbouring regions
  927. if (!m_isChildAgent)
  928. {
  929. IEntityTransferModule m_agentTransfer = m_scene.RequestModuleInterface<IEntityTransferModule>();
  930. if (m_agentTransfer != null)
  931. m_agentTransfer.EnableChildAgents(this);
  932. else
  933. m_log.DebugFormat("[SCENE PRESENCE]: Unable to create child agents in neighbours, because AgentTransferModule is not active");
  934. IFriendsModule friendsModule = m_scene.RequestModuleInterface<IFriendsModule>();
  935. if (friendsModule != null)
  936. friendsModule.SendFriendsOnlineIfNeeded(ControllingClient);
  937. }
  938. m_log.DebugFormat(
  939. "[SCENE PRESENCE]: Completing movement of {0} into region {1} took {2}ms",
  940. client.Name, Scene.RegionInfo.RegionName, (DateTime.Now - startTime).Milliseconds);
  941. }
  942. /// <summary>
  943. /// Callback for the Camera view block check. Gets called with the results of the camera view block test
  944. /// hitYN is true when there's something in the way.
  945. /// </summary>
  946. /// <param name="hitYN"></param>
  947. /// <param name="collisionPoint"></param>
  948. /// <param name="localid"></param>
  949. /// <param name="distance"></param>
  950. public void RayCastCameraCallback(bool hitYN, Vector3 collisionPoint, uint localid, float distance, Vector3 pNormal)
  951. {
  952. const float POSITION_TOLERANCE = 0.02f;
  953. const float VELOCITY_TOLERANCE = 0.02f;
  954. const float ROTATION_TOLERANCE = 0.02f;
  955. if (m_followCamAuto)
  956. {
  957. if (hitYN)
  958. {
  959. CameraConstraintActive = true;
  960. //m_log.DebugFormat("[RAYCASTRESULT]: {0}, {1}, {2}, {3}", hitYN, collisionPoint, localid, distance);
  961. Vector3 normal = Vector3.Normalize(new Vector3(0f, 0f, collisionPoint.Z) - collisionPoint);
  962. ControllingClient.SendCameraConstraint(new Vector4(normal.X, normal.Y, normal.Z, -1 * Vector3.Distance(new Vector3(0,0,collisionPoint.Z),collisionPoint)));
  963. }
  964. else
  965. {
  966. if (!m_pos.ApproxEquals(m_lastPosition, POSITION_TOLERANCE) ||
  967. !Velocity.ApproxEquals(m_lastVelocity, VELOCITY_TOLERANCE) ||
  968. !m_bodyRot.ApproxEquals(m_lastRotation, ROTATION_TOLERANCE))
  969. {
  970. if (CameraConstraintActive)
  971. {
  972. ControllingClient.SendCameraConstraint(new Vector4(0f, 0.5f, 0.9f, -3000f));
  973. CameraConstraintActive = false;
  974. }
  975. }
  976. }
  977. }
  978. }
  979. /// <summary>
  980. /// This is the event handler for client movement. If a client is moving, this event is triggering.
  981. /// </summary>
  982. public void HandleAgentUpdate(IClientAPI remoteClient, AgentUpdateArgs agentData)
  983. {
  984. //if (m_isChildAgent)
  985. //{
  986. // // m_log.Debug("DEBUG: HandleAgentUpdate: child agent");
  987. // return;
  988. //}
  989. m_perfMonMS = Util.EnvironmentTickCount();
  990. ++m_movementUpdateCount;
  991. if (m_movementUpdateCount < 1)
  992. m_movementUpdateCount = 1;
  993. #region Sanity Checking
  994. // This is irritating. Really.
  995. if (!AbsolutePosition.IsFinite())
  996. {
  997. RemoveFromPhysicalScene();
  998. m_log.Error("[AVATAR]: NonFinite Avatar position detected... Reset Position. Mantis this please. Error #9999902");
  999. m_pos = m_LastFinitePos;
  1000. if (!m_pos.IsFinite())
  1001. {
  1002. m_pos.X = 127f;
  1003. m_pos.Y = 127f;
  1004. m_pos.Z = 127f;
  1005. m_log.Error("[AVATAR]: NonFinite Avatar position detected... Reset Position. Mantis this please. Error #9999903");
  1006. }
  1007. AddToPhysicalScene(false);
  1008. }
  1009. else
  1010. {
  1011. m_LastFinitePos = m_pos;
  1012. }
  1013. #endregion Sanity Checking
  1014. #region Inputs
  1015. AgentManager.ControlFlags flags = (AgentManager.ControlFlags)agentData.ControlFlags;
  1016. Quaternion bodyRotation = agentData.BodyRotation;
  1017. // Camera location in world. We'll need to raytrace
  1018. // from this location from time to time.
  1019. m_CameraCenter = agentData.CameraCenter;
  1020. if (Vector3.Distance(m_lastCameraCenter, m_CameraCenter) >= Scene.RootReprioritizationDistance)
  1021. {
  1022. ReprioritizeUpdates();
  1023. m_lastCameraCenter = m_CameraCenter;
  1024. }
  1025. // Use these three vectors to figure out what the agent is looking at
  1026. // Convert it to a Matrix and/or Quaternion
  1027. m_CameraAtAxis = agentData.CameraAtAxis;
  1028. m_CameraLeftAxis = agentData.CameraLeftAxis;
  1029. m_CameraUpAxis = agentData.CameraUpAxis;
  1030. // The Agent's Draw distance setting
  1031. m_DrawDistance = agentData.Far;
  1032. // Check if Client has camera in 'follow cam' or 'build' mode.
  1033. Vector3 camdif = (Vector3.One * m_bodyRot - Vector3.One * CameraRotation);
  1034. m_followCamAuto = ((m_CameraUpAxis.Z > 0.959f && m_CameraUpAxis.Z < 0.98f)
  1035. && (Math.Abs(camdif.X) < 0.4f && Math.Abs(camdif.Y) < 0.4f)) ? true : false;
  1036. m_mouseLook = (flags & AgentManager.ControlFlags.AGENT_CONTROL_MOUSELOOK) != 0;
  1037. m_leftButtonDown = (flags & AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN) != 0;
  1038. #endregion Inputs
  1039. if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_STAND_UP) != 0)
  1040. {
  1041. StandUp();
  1042. }
  1043. //m_log.DebugFormat("[FollowCam]: {0}", m_followCamAuto);
  1044. // Raycast from the avatar's head to the camera to see if there's anything blocking the view
  1045. if ((m_movementUpdateCount % NumMovementsBetweenRayCast) == 0 && m_scene.PhysicsScene.SupportsRayCast())
  1046. {
  1047. if (m_followCamAuto)
  1048. {
  1049. Vector3 posAdjusted = m_pos + HEAD_ADJUSTMENT;
  1050. m_scene.PhysicsScene.RaycastWorld(m_pos, Vector3.Normalize(m_CameraCenter - posAdjusted), Vector3.Distance(m_CameraCenter, posAdjusted) + 0.3f, RayCastCameraCallback);
  1051. }
  1052. }
  1053. lock (scriptedcontrols)
  1054. {
  1055. if (scriptedcontrols.Count > 0)
  1056. {
  1057. SendControlToScripts((uint)flags);
  1058. flags = RemoveIgnoredControls(flags, IgnoredControls);
  1059. }
  1060. }
  1061. if (m_autopilotMoving)
  1062. CheckAtSitTarget();
  1063. if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_SIT_ON_GROUND) != 0)
  1064. {
  1065. // TODO: This doesn't prevent the user from walking yet.
  1066. // Setting parent ID would fix this, if we knew what value
  1067. // to use. Or we could add a m_isSitting variable.
  1068. //Animator.TrySetMovementAnimation("SIT_GROUND_CONSTRAINED");
  1069. SitGround = true;
  1070. }
  1071. // In the future, these values might need to go global.
  1072. // Here's where you get them.
  1073. m_AgentControlFlags = flags;
  1074. m_headrotation = agentData.HeadRotation;
  1075. m_state = agentData.State;
  1076. PhysicsActor actor = PhysicsActor;
  1077. if (actor == null)
  1078. {
  1079. return;
  1080. }
  1081. bool update_movementflag = false;
  1082. if (m_allowMovement && !SitGround)
  1083. {
  1084. if (agentData.UseClientAgentPosition)
  1085. {
  1086. m_moveToPositionInProgress = (agentData.ClientAgentPosition - AbsolutePosition).Length() > 0.2f;
  1087. m_moveToPositionTarget = agentData.ClientAgentPosition;
  1088. }
  1089. int i = 0;
  1090. bool update_rotation = false;
  1091. bool DCFlagKeyPressed = false;
  1092. Vector3 agent_control_v3 = Vector3.Zero;
  1093. Quaternion q = bodyRotation;
  1094. bool oldflying = PhysicsActor.Flying;
  1095. if (m_forceFly)
  1096. actor.Flying = true;
  1097. else if (m_flyDisabled)
  1098. actor.Flying = false;
  1099. else
  1100. actor.Flying = ((flags & AgentManager.ControlFlags.AGENT_CONTROL_FLY) != 0);
  1101. if (actor.Flying != oldflying)
  1102. update_movementflag = true;
  1103. if (q != m_bodyRot)
  1104. {
  1105. m_bodyRot = q;
  1106. update_rotation = true;
  1107. }
  1108. if (m_parentID == 0)
  1109. {
  1110. bool bAllowUpdateMoveToPosition = false;
  1111. bool bResetMoveToPosition = false;
  1112. Vector3[] dirVectors;
  1113. // use camera up angle when in mouselook and not flying or when holding the left mouse button down and not flying
  1114. // this prevents 'jumping' in inappropriate situations.
  1115. if ((m_mouseLook && !m_physicsActor.Flying) || (m_leftButtonDown && !m_physicsActor.Flying))
  1116. dirVectors = GetWalkDirectionVectors();
  1117. else
  1118. dirVectors = Dir_Vectors;
  1119. // The fact that m_movementflag is a byte needs to be fixed
  1120. // it really should be a uint
  1121. uint nudgehack = 250;
  1122. foreach (Dir_ControlFlags DCF in DIR_CONTROL_FLAGS)
  1123. {
  1124. if (((uint)flags & (uint)DCF) != 0)
  1125. {
  1126. bResetMoveToPosition = true;
  1127. DCFlagKeyPressed = true;
  1128. try
  1129. {
  1130. agent_control_v3 += dirVectors[i];
  1131. //m_log.DebugFormat("[Motion]: {0}, {1}",i, dirVectors[i]);
  1132. }
  1133. catch (IndexOutOfRangeException)
  1134. {
  1135. // Why did I get this?
  1136. }
  1137. if ((m_movementflag & (byte)(uint)DCF) == 0)
  1138. {
  1139. if (DCF == Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD_NUDGE || DCF == Dir_ControlFlags.DIR_CONTROL_FLAG_BACKWARD_NUDGE)
  1140. {
  1141. m_movementflag |= (byte)nudgehack;
  1142. }
  1143. m_movementflag += (byte)(uint)DCF;
  1144. update_movementflag = true;
  1145. }
  1146. }
  1147. else
  1148. {
  1149. if ((m_movementflag & (byte)(uint)DCF) != 0 ||
  1150. ((DCF == Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD_NUDGE || DCF == Dir_ControlFlags.DIR_CONTROL_FLAG_BACKWARD_NUDGE)
  1151. && ((m_movementflag & (byte)nudgehack) == nudgehack))
  1152. ) // This or is for Nudge forward
  1153. {
  1154. m_movementflag -= ((byte)(uint)DCF);
  1155. update_movementflag = true;
  1156. /*
  1157. if ((DCF == Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD_NUDGE || DCF == Dir_ControlFlags.DIR_CONTROL_FLAG_BACKWARD_NUDGE)
  1158. && ((m_movementflag & (byte)nudgehack) == nudgehack))
  1159. {
  1160. m_log.Debug("Removed Hack flag");
  1161. }
  1162. */
  1163. }
  1164. else
  1165. {
  1166. bAllowUpdateMoveToPosition = true;
  1167. }
  1168. }
  1169. i++;
  1170. }
  1171. //Paupaw:Do Proper PID for Autopilot here
  1172. if (bResetMoveToPosition)
  1173. {
  1174. m_moveToPositionTarget = Vector3.Zero;
  1175. m_moveToPositionInProgress = false;
  1176. update_movementflag = true;
  1177. bAllowUpdateMoveToPosition = false;
  1178. }
  1179. if (bAllowUpdateMoveToPosition && (m_moveToPositionInProgress && !m_autopilotMoving))
  1180. {
  1181. //Check the error term of the current position in relation to the target position
  1182. if (Util.GetDistanceTo(AbsolutePosition, m_moveToPositionTarget) <= 0.5f)
  1183. {
  1184. // we are close enough to the target
  1185. m_moveToPositionTarget = Vector3.Zero;
  1186. m_moveToPositionInProgress = false;
  1187. update_movementflag = true;
  1188. }
  1189. else
  1190. {
  1191. try
  1192. {
  1193. // move avatar in 2D at one meter/second towards target, in avatar coordinate frame.
  1194. // This movement vector gets added to the velocity through AddNewMovement().
  1195. // Theoretically we might need a more complex PID approach here if other
  1196. // unknown forces are acting on the avatar and we need to adaptively respond
  1197. // to such forces, but the following simple approach seems to works fine.
  1198. Vector3 LocalVectorToTarget3D =
  1199. (m_moveToPositionTarget - AbsolutePosition) // vector from cur. pos to target in global coords
  1200. * Matrix4.CreateFromQuaternion(Quaternion.Inverse(bodyRotation)); // change to avatar coords
  1201. // Ignore z component of vector
  1202. Vector3 LocalVectorToTarget2D = new Vector3((float)(LocalVectorToTarget3D.X), (float)(LocalVectorToTarget3D.Y), 0f);
  1203. LocalVectorToTarget2D.Normalize();
  1204. agent_control_v3 += LocalVectorToTarget2D;
  1205. // update avatar movement flags. the avatar coordinate system is as follows:
  1206. //
  1207. // +X (forward)
  1208. //
  1209. // ^
  1210. // |
  1211. // |
  1212. // |
  1213. // |
  1214. // (left) +Y <--------o--------> -Y
  1215. // avatar
  1216. // |
  1217. // |
  1218. // |
  1219. // |
  1220. // v
  1221. // -X
  1222. //
  1223. // based on the above avatar coordinate system, classify the movement into
  1224. // one of left/right/back/forward.
  1225. if (LocalVectorToTarget2D.Y > 0)//MoveLeft
  1226. {
  1227. m_movementflag += (byte)(uint)Dir_ControlFlags.DIR_CONTROL_FLAG_LEFT;
  1228. //AgentControlFlags
  1229. AgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_LEFT;
  1230. update_movementflag = true;
  1231. }
  1232. else if (LocalVectorToTarget2D.Y < 0) //MoveRight
  1233. {
  1234. m_movementflag += (byte)(uint)Dir_ControlFlags.DIR_CONTROL_FLAG_RIGHT;
  1235. AgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_RIGHT;
  1236. update_movementflag = true;
  1237. }
  1238. if (LocalVectorToTarget2D.X < 0) //MoveBack
  1239. {
  1240. m_movementflag += (byte)(uint)Dir_ControlFlags.DIR_CONTROL_FLAG_BACK;
  1241. AgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_BACK;
  1242. update_movementflag = true;
  1243. }
  1244. else if (LocalVectorToTarget2D.X > 0) //Move Forward
  1245. {
  1246. m_movementflag += (byte)(uint)Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD;
  1247. AgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD;
  1248. update_movementflag = true;
  1249. }
  1250. }
  1251. catch (Exception e)
  1252. {
  1253. //Avoid system crash, can be slower but...
  1254. m_log.DebugFormat("Crash! {0}", e.ToString());
  1255. }
  1256. }
  1257. }
  1258. }
  1259. // Cause the avatar to stop flying if it's colliding
  1260. // with something with the down arrow pressed.
  1261. // Only do this if we're flying
  1262. if (m_physicsActor != null && m_physicsActor.Flying && !m_forceFly)
  1263. {
  1264. // Landing detection code
  1265. // Are the landing controls requirements filled?
  1266. bool controlland = (((flags & AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0) ||
  1267. ((flags & AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG) != 0));
  1268. // Are the collision requirements fulfilled?
  1269. bool colliding = (m_physicsActor.IsColliding == true);
  1270. if (m_physicsActor.Flying && colliding && controlland)
  1271. {
  1272. // nesting this check because LengthSquared() is expensive and we don't
  1273. // want to do it every step when flying.
  1274. if ((Velocity.LengthSquared() <= LAND_VELOCITYMAG_MAX))
  1275. StopFlying();
  1276. }
  1277. }
  1278. // If the agent update does move the avatar, then calculate the force ready for the velocity update,
  1279. // which occurs later in the main scene loop
  1280. if (update_movementflag || (update_rotation && DCFlagKeyPressed))
  1281. {
  1282. // m_log.DebugFormat("{0} {1}", update_movementflag, (update_rotation && DCFlagKeyPressed));
  1283. // m_log.DebugFormat(
  1284. // "In {0} adding velocity to {1} of {2}", m_scene.RegionInfo.RegionName, Name, agent_control_v3);
  1285. AddNewMovement(agent_control_v3, q);
  1286. }
  1287. }
  1288. if (update_movementflag && ((flags & AgentManager.ControlFlags.AGENT_CONTROL_SIT_ON_GROUND) == 0) && (m_parentID == 0) && !SitGround)
  1289. Animator.UpdateMovementAnimations();
  1290. m_scene.EventManager.TriggerOnClientMovement(this);
  1291. m_scene.StatsReporter.AddAgentTime(Util.EnvironmentTickCountSubtract(m_perfMonMS));
  1292. }
  1293. public void DoAutoPilot(uint not_used, Vector3 Pos, IClientAPI remote_client)
  1294. {
  1295. m_autopilotMoving = true;
  1296. m_autoPilotTarget = Pos;
  1297. m_sitAtAutoTarget = false;
  1298. PrimitiveBaseShape proxy = PrimitiveBaseShape.Default;
  1299. //proxy.PCode = (byte)PCode.ParticleSystem;
  1300. proxyObjectGroup = new SceneObjectGroup(UUID, Pos, Rotation, proxy);
  1301. proxyObjectGroup.AttachToScene(m_scene);
  1302. // Commented out this code since it could never have executed, but might still be informative.
  1303. // if (proxyObjectGroup != null)
  1304. // {
  1305. proxyObjectGroup.SendGroupFullUpdate();
  1306. remote_client.SendSitResponse(proxyObjectGroup.UUID, Vector3.Zero, Quaternion.Identity, true, Vector3.Zero, Vector3.Zero, false);
  1307. m_scene.DeleteSceneObject(proxyObjectGroup, false);
  1308. // }
  1309. // else
  1310. // {
  1311. // m_autopilotMoving = false;
  1312. // m_autoPilotTarget = Vector3.Zero;
  1313. // ControllingClient.SendAlertMessage("Autopilot cancelled");
  1314. // }
  1315. }
  1316. public void DoMoveToPosition(Object sender, string method, List<String> args)
  1317. {
  1318. try
  1319. {
  1320. float locx = 0f;
  1321. float locy = 0f;
  1322. float locz = 0f;
  1323. uint regionX = 0;
  1324. uint regionY = 0;
  1325. try
  1326. {
  1327. Utils.LongToUInts(Scene.RegionInfo.RegionHandle, out regionX, out regionY);
  1328. locx = Convert.ToSingle(args[0]) - (float)regionX;
  1329. locy = Convert.ToSingle(args[1]) - (float)regionY;
  1330. locz = Convert.ToSingle(args[2]);
  1331. }
  1332. catch (InvalidCastException)
  1333. {
  1334. m_log.Error("[CLIENT]: Invalid autopilot request");
  1335. return;
  1336. }
  1337. m_moveToPositionInProgress = true;
  1338. m_moveToPositionTarget = new Vector3(locx, locy, locz);
  1339. }
  1340. catch (Exception ex)
  1341. {
  1342. //Why did I get this error?
  1343. m_log.Error("[SCENEPRESENCE]: DoMoveToPosition" + ex);
  1344. }
  1345. }
  1346. private void CheckAtSitTarget()
  1347. {
  1348. //m_log.Debug("[AUTOPILOT]: " + Util.GetDistanceTo(AbsolutePosition, m_autoPilotTarget).ToString());
  1349. if (Util.GetDistanceTo(AbsolutePosition, m_autoPilotTarget) <= 1.5)
  1350. {
  1351. if (m_sitAtAutoTarget)
  1352. {
  1353. SceneObjectPart part = m_scene.GetSceneObjectPart(m_requestedSitTargetUUID);
  1354. if (part != null)
  1355. {
  1356. AbsolutePosition = part.AbsolutePosition;
  1357. Velocity = Vector3.Zero;
  1358. SendFullUpdateToAllClients();
  1359. //HandleAgentSit(ControllingClient, m_requestedSitTargetUUID);
  1360. }
  1361. //ControllingClient.SendSitResponse(m_requestedSitTargetID, m_requestedSitOffset, Quaternion.Identity, false, Vector3.Zero, Vector3.Zero, false);
  1362. m_requestedSitTargetUUID = UUID.Zero;
  1363. }
  1364. /*
  1365. else
  1366. {
  1367. //ControllingClient.SendAlertMessage("Autopilot cancelled");
  1368. //SendTerseUpdateToAllClients();
  1369. //PrimitiveBaseShape proxy = PrimitiveBaseShape.Default;
  1370. //proxy.PCode = (byte)PCode.ParticleSystem;
  1371. ////uint nextUUID = m_scene.NextLocalId;
  1372. //proxyObjectGroup = new SceneObjectGroup(m_scene, m_scene.RegionInfo.RegionHandle, UUID, nextUUID, m_autoPilotTarget, Quaternion.Identity, proxy);
  1373. //if (proxyObjectGroup != null)
  1374. //{
  1375. //proxyObjectGroup.SendGroupFullUpdate();
  1376. //ControllingClient.SendSitResponse(UUID.Zero, m_autoPilotTarget, Quaternion.Identity, true, Vector3.Zero, Vector3.Zero, false);
  1377. //m_scene.DeleteSceneObject(proxyObjectGroup);
  1378. //}
  1379. }
  1380. */
  1381. m_autoPilotTarget = Vector3.Zero;
  1382. m_autopilotMoving = false;
  1383. }
  1384. }
  1385. /// <summary>
  1386. /// Perform the logic necessary to stand the avatar up. This method also executes
  1387. /// the stand animation.
  1388. /// </summary>
  1389. public void StandUp()
  1390. {
  1391. SitGround = false;
  1392. if (m_parentID != 0)
  1393. {
  1394. m_log.Debug("StandupCode Executed");
  1395. SceneObjectPart part = m_scene.GetSceneObjectPart(m_parentID);
  1396. if (part != null)
  1397. {
  1398. TaskInventoryDictionary taskIDict = part.TaskInventory;
  1399. if (taskIDict != null)
  1400. {
  1401. lock (taskIDict)
  1402. {
  1403. foreach (UUID taskID in taskIDict.Keys)
  1404. {
  1405. UnRegisterControlEventsToScript(LocalId, taskID);
  1406. taskIDict[taskID].PermsMask &= ~(
  1407. 2048 | //PERMISSION_CONTROL_CAMERA
  1408. 4); // PERMISSION_TAKE_CONTROLS
  1409. }
  1410. }
  1411. }
  1412. // Reset sit target.
  1413. if (part.GetAvatarOnSitTarget() == UUID)
  1414. part.SetAvatarOnSitTarget(UUID.Zero);
  1415. m_parentPosition = part.GetWorldPosition();
  1416. ControllingClient.SendClearFollowCamProperties(part.ParentUUID);
  1417. }
  1418. if (m_physicsActor == null)
  1419. {
  1420. AddToPhysicalScene(false);
  1421. }
  1422. m_pos += m_parentPosition + new Vector3(0.0f, 0.0f, 2.0f*m_sitAvatarHeight);
  1423. m_parentPosition = Vector3.Zero;
  1424. m_parentID = 0;
  1425. SendFullUpdateToAllClients();
  1426. m_requestedSitTargetID = 0;
  1427. if (m_physicsActor != null && m_appearance != null)
  1428. {
  1429. if (m_appearance.AvatarHeight > 0)
  1430. SetHeight(m_appearance.AvatarHeight);
  1431. }
  1432. }
  1433. Animator.TrySetMovementAnimation("STAND");
  1434. }
  1435. private SceneObjectPart FindNextAvailableSitTarget(UUID targetID)
  1436. {
  1437. SceneObjectPart targetPart = m_scene.GetSceneObjectPart(targetID);
  1438. if (targetPart == null)
  1439. return null;
  1440. // If the primitive the player clicked on has a sit target and that sit target is not full, that sit target is used.
  1441. // If the primitive the player clicked on has no sit target, and one or more other linked objects have sit targets that are not full, the sit target of the object with the lowest link number will be used.
  1442. // Get our own copy of the part array, and sort into the order we want to test
  1443. SceneObjectPart[] partArray = targetPart.ParentGroup.Parts;
  1444. Array.Sort(partArray, delegate(SceneObjectPart p1, SceneObjectPart p2)
  1445. {
  1446. // we want the originally selected part first, then the rest in link order -- so make the selected part link num (-1)
  1447. int linkNum1 = p1==targetPart ? -1 : p1.LinkNum;
  1448. int linkNum2 = p2==targetPart ? -1 : p2.LinkNum;
  1449. return linkNum1 - linkNum2;
  1450. }
  1451. );
  1452. //look for prims with explicit sit targets that are available
  1453. foreach (SceneObjectPart part in partArray)
  1454. {
  1455. // Is a sit target available?
  1456. Vector3 avSitOffSet = part.SitTargetPosition;
  1457. Quaternion avSitOrientation = part.SitTargetOrientation;
  1458. UUID avOnTargetAlready = part.GetAvatarOnSitTarget();
  1459. bool SitTargetUnOccupied = (!(avOnTargetAlready != UUID.Zero));
  1460. bool SitTargetisSet =
  1461. (!(avSitOffSet.X == 0f && avSitOffSet.Y == 0f && avSitOffSet.Z == 0f && avSitOrientation.W == 1f &&
  1462. avSitOrientation.X == 0f && avSitOrientation.Y == 0f && avSitOrientation.Z == 0f));
  1463. if (SitTargetisSet && SitTargetUnOccupied)
  1464. {
  1465. //switch the target to this prim
  1466. return part;
  1467. }
  1468. }
  1469. // no explicit sit target found - use original target
  1470. return targetPart;
  1471. }
  1472. private void SendSitResponse(IClientAPI remoteClient, UUID targetID, Vector3 offset, Quaternion pSitOrientation)
  1473. {
  1474. bool autopilot = true;
  1475. Vector3 pos = new Vector3();
  1476. Quaternion sitOrientation = pSitOrientation;
  1477. Vector3 cameraEyeOffset = Vector3.Zero;
  1478. Vector3 cameraAtOffset = Vector3.Zero;
  1479. bool forceMouselook = false;
  1480. //SceneObjectPart part = m_scene.GetSceneObjectPart(targetID);
  1481. SceneObjectPart part = FindNextAvailableSitTarget(targetID);
  1482. if (part != null)
  1483. {
  1484. // TODO: determine position to sit at based on scene geometry; don't trust offset from client
  1485. // see http://wiki.secondlife.com/wiki/User:Andrew_Linden/Office_Hours/2007_11_06 for details on how LL does it
  1486. // Is a sit target available?
  1487. Vector3 avSitOffSet = part.SitTargetPosition;
  1488. Quaternion avSitOrientation = part.SitTargetOrientation;
  1489. UUID avOnTargetAlready = part.GetAvatarOnSitTarget();
  1490. bool SitTargetUnOccupied = (!(avOnTargetAlready != UUID.Zero));
  1491. bool SitTargetisSet =
  1492. (!(avSitOffSet.X == 0f && avSitOffSet.Y == 0f && avSitOffSet.Z == 0f &&
  1493. (
  1494. avSitOrientation.X == 0f && avSitOrientation.Y == 0f && avSitOrientation.Z == 0f && avSitOrientation.W == 1f // Valid Zero Rotation quaternion
  1495. || avSitOrientation.X == 0f && avSitOrientation.Y == 0f && avSitOrientation.Z == 1f && avSitOrientation.W == 0f // W-Z Mapping was invalid at one point
  1496. || avSitOrientation.X == 0f && avSitOrientation.Y == 0f && avSitOrientation.Z == 0f && avSitOrientation.W == 0f // Invalid Quaternion
  1497. )
  1498. ));
  1499. if (SitTargetisSet && SitTargetUnOccupied)
  1500. {
  1501. part.SetAvatarOnSitTarget(UUID);
  1502. offset = new Vector3(avSitOffSet.X, avSitOffSet.Y, avSitOffSet.Z);
  1503. sitOrientation = avSitOrientation;
  1504. autopilot = false;
  1505. }
  1506. pos = part.AbsolutePosition + offset;
  1507. //if (Math.Abs(part.AbsolutePosition.Z - AbsolutePosition.Z) > 1)
  1508. //{
  1509. // offset = pos;
  1510. //autopilot = false;
  1511. //}
  1512. if (m_physicsActor != null)
  1513. {
  1514. // If we're not using the client autopilot, we're immediately warping the avatar to the location
  1515. // We can remove the physicsActor until they stand up.
  1516. m_sitAvatarHeight = m_physicsActor.Size.Z;
  1517. if (autopilot)
  1518. {
  1519. if (Util.GetDistanceTo(AbsolutePosition, pos) < 4.5)
  1520. {
  1521. autopilot = false;
  1522. RemoveFromPhysicalScene();
  1523. AbsolutePosition = pos + new Vector3(0.0f, 0.0f, m_sitAvatarHeight);
  1524. }
  1525. }
  1526. else
  1527. {
  1528. RemoveFromPhysicalScene();
  1529. }
  1530. }
  1531. cameraAtOffset = part.GetCameraAtOffset();
  1532. cameraEyeOffset = part.GetCameraEyeOffset();
  1533. forceMouselook = part.GetForceMouselook();
  1534. }
  1535. ControllingClient.SendSitResponse(targetID, offset, sitOrientation, autopilot, cameraAtOffset, cameraEyeOffset, forceMouselook);
  1536. m_requestedSitTargetUUID = targetID;
  1537. // This calls HandleAgentSit twice, once from here, and the client calls
  1538. // HandleAgentSit itself after it gets to the location
  1539. // It doesn't get to the location until we've moved them there though
  1540. // which happens in HandleAgentSit :P
  1541. m_autopilotMoving = autopilot;
  1542. m_autoPilotTarget = pos;
  1543. m_sitAtAutoTarget = autopilot;
  1544. if (!autopilot)
  1545. HandleAgentSit(remoteClient, UUID);
  1546. }
  1547. public void HandleAgentRequestSit(IClientAPI remoteClient, UUID agentID, UUID targetID, Vector3 offset)
  1548. {
  1549. if (m_parentID != 0)
  1550. {
  1551. StandUp();
  1552. }
  1553. m_nextSitAnimation = "SIT";
  1554. //SceneObjectPart part = m_scene.GetSceneObjectPart(targetID);
  1555. SceneObjectPart part = FindNextAvailableSitTarget(targetID);
  1556. if (part != null)
  1557. {
  1558. if (!String.IsNullOrEmpty(part.SitAnimation))
  1559. {
  1560. m_nextSitAnimation = part.SitAnimation;
  1561. }
  1562. m_requestedSitTargetID = part.LocalId;
  1563. //m_requestedSitOffset = offset;
  1564. m_requestedSitTargetUUID = targetID;
  1565. m_log.DebugFormat("[SIT]: Client requested Sit Position: {0}", offset);
  1566. if (m_scene.PhysicsScene.SupportsRayCast())
  1567. {
  1568. //m_scene.PhysicsScene.RaycastWorld(Vector3.Zero,Vector3.Zero, 0.01f,new RaycastCallback());
  1569. //SitRayCastAvatarPosition(part);
  1570. //return;
  1571. }
  1572. }
  1573. else
  1574. {
  1575. m_log.Warn("Sit requested on unknown object: " + targetID.ToString());
  1576. }
  1577. SendSitResponse(remoteClient, targetID, offset, Quaternion.Identity);
  1578. }
  1579. /*
  1580. public void SitRayCastAvatarPosition(SceneObjectPart part)
  1581. {
  1582. Vector3 EndRayCastPosition = part.AbsolutePosition + m_requestedSitOffset;
  1583. Vector3 StartRayCastPosition = AbsolutePosition;
  1584. Vector3 direction = Vector3.Normalize(EndRayCastPosition - StartRayCastPosition);
  1585. float distance = Vector3.Distance(EndRayCastPosition, StartRayCastPosition);
  1586. m_scene.PhysicsScene.RaycastWorld(StartRayCastPosition, direction, distance, SitRayCastAvatarPositionResponse);
  1587. }
  1588. public void SitRayCastAvatarPositionResponse(bool hitYN, Vector3 collisionPoint, uint localid, float pdistance, Vector3 normal)
  1589. {
  1590. SceneObjectPart part = FindNextAvailableSitTarget(m_requestedSitTargetUUID);
  1591. if (part != null)
  1592. {
  1593. if (hitYN)
  1594. {
  1595. if (collisionPoint.ApproxEquals(m_requestedSitOffset + part.AbsolutePosition, 0.2f))
  1596. {
  1597. SitRaycastFindEdge(collisionPoint, normal);
  1598. m_log.DebugFormat("[SIT]: Raycast Avatar Position succeeded at point: {0}, normal:{1}", collisionPoint, normal);
  1599. }
  1600. else
  1601. {
  1602. SitRayCastAvatarPositionCameraZ(part);
  1603. }
  1604. }
  1605. else
  1606. {
  1607. SitRayCastAvatarPositionCameraZ(part);
  1608. }
  1609. }
  1610. else
  1611. {
  1612. ControllingClient.SendAlertMessage("Sit position no longer exists");
  1613. m_requestedSitTargetUUID = UUID.Zero;
  1614. m_requestedSitTargetID = 0;
  1615. m_requestedSitOffset = Vector3.Zero;
  1616. }
  1617. }
  1618. public void SitRayCastAvatarPositionCameraZ(SceneObjectPart part)
  1619. {
  1620. // Next, try to raycast from the camera Z position
  1621. Vector3 EndRayCastPosition = part.AbsolutePosition + m_requestedSitOffset;
  1622. Vector3 StartRayCastPosition = AbsolutePosition; StartRayCastPosition.Z = CameraPosition.Z;
  1623. Vector3 direction = Vector3.Normalize(EndRayCastPosition - StartRayCastPosition);
  1624. float distance = Vector3.Distance(EndRayCastPosition, StartRayCastPosition);
  1625. m_scene.PhysicsScene.RaycastWorld(StartRayCastPosition, direction, distance, SitRayCastAvatarPositionCameraZResponse);
  1626. }
  1627. public void SitRayCastAvatarPositionCameraZResponse(bool hitYN, Vector3 collisionPoint, uint localid, float pdistance, Vector3 normal)
  1628. {
  1629. SceneObjectPart part = FindNextAvailableSitTarget(m_requestedSitTargetUUID);
  1630. if (part != null)
  1631. {
  1632. if (hitYN)
  1633. {
  1634. if (collisionPoint.ApproxEquals(m_requestedSitOffset + part.AbsolutePosition, 0.2f))
  1635. {
  1636. SitRaycastFindEdge(collisionPoint, normal);
  1637. m_log.DebugFormat("[SIT]: Raycast Avatar Position + CameraZ succeeded at point: {0}, normal:{1}", collisionPoint, normal);
  1638. }
  1639. else
  1640. {
  1641. SitRayCastCameraPosition(part);
  1642. }
  1643. }
  1644. else
  1645. {
  1646. SitRayCastCameraPosition(part);
  1647. }
  1648. }
  1649. else
  1650. {
  1651. ControllingClient.SendAlertMessage("Sit position no longer exists");
  1652. m_requestedSitTargetUUID = UUID.Zero;
  1653. m_requestedSitTargetID = 0;
  1654. m_requestedSitOffset = Vector3.Zero;
  1655. }
  1656. }
  1657. public void SitRayCastCameraPosition(SceneObjectPart part)
  1658. {
  1659. // Next, try to raycast from the camera position
  1660. Vector3 EndRayCastPosition = part.AbsolutePosition + m_requestedSitOffset;
  1661. Vector3 StartRayCastPosition = CameraPosition;
  1662. Vector3 direction = Vector3.Normalize(EndRayCastPosition - StartRayCastPosition);
  1663. float distance = Vector3.Distance(EndRayCastPosition, StartRayCastPosition);
  1664. m_scene.PhysicsScene.RaycastWorld(StartRayCastPosition, direction, distance, SitRayCastCameraPositionResponse);
  1665. }
  1666. public void SitRayCastCameraPositionResponse(bool hitYN, Vector3 collisionPoint, uint localid, float pdistance, Vector3 normal)
  1667. {
  1668. SceneObjectPart part = FindNextAvailableSitTarget(m_requestedSitTargetUUID);
  1669. if (part != null)
  1670. {
  1671. if (hitYN)
  1672. {
  1673. if (collisionPoint.ApproxEquals(m_requestedSitOffset + part.AbsolutePosition, 0.2f))
  1674. {
  1675. SitRaycastFindEdge(collisionPoint, normal);
  1676. m_log.DebugFormat("[SIT]: Raycast Camera Position succeeded at point: {0}, normal:{1}", collisionPoint, normal);
  1677. }
  1678. else
  1679. {
  1680. SitRayHorizontal(part);
  1681. }
  1682. }
  1683. else
  1684. {
  1685. SitRayHorizontal(part);
  1686. }
  1687. }
  1688. else
  1689. {
  1690. ControllingClient.SendAlertMessage("Sit position no longer exists");
  1691. m_requestedSitTargetUUID = UUID.Zero;
  1692. m_requestedSitTargetID = 0;
  1693. m_requestedSitOffset = Vector3.Zero;
  1694. }
  1695. }
  1696. public void SitRayHorizontal(SceneObjectPart part)
  1697. {
  1698. // Next, try to raycast from the avatar position to fwd
  1699. Vector3 EndRayCastPosition = part.AbsolutePosition + m_requestedSitOffset;
  1700. Vector3 StartRayCastPosition = CameraPosition;
  1701. Vector3 direction = Vector3.Normalize(EndRayCastPosition - StartRayCastPosition);
  1702. float distance = Vector3.Distance(EndRayCastPosition, StartRayCastPosition);
  1703. m_scene.PhysicsScene.RaycastWorld(StartRayCastPosition, direction, distance, SitRayCastHorizontalResponse);
  1704. }
  1705. public void SitRayCastHorizontalResponse(bool hitYN, Vector3 collisionPoint, uint localid, float pdistance, Vector3 normal)
  1706. {
  1707. SceneObjectPart part = FindNextAvailableSitTarget(m_requestedSitTargetUUID);
  1708. if (part != null)
  1709. {
  1710. if (hitYN)
  1711. {
  1712. if (collisionPoint.ApproxEquals(m_requestedSitOffset + part.AbsolutePosition, 0.2f))
  1713. {
  1714. SitRaycastFindEdge(collisionPoint, normal);
  1715. m_log.DebugFormat("[SIT]: Raycast Horizontal Position succeeded at point: {0}, normal:{1}", collisionPoint, normal);
  1716. // Next, try to raycast from the camera position
  1717. Vector3 EndRayCastPosition = part.AbsolutePosition + m_requestedSitOffset;
  1718. Vector3 StartRayCastPosition = CameraPosition;
  1719. Vector3 direction = Vector3.Normalize(EndRayCastPosition - StartRayCastPosition);
  1720. float distance = Vector3.Distance(EndRayCastPosition, StartRayCastPosition);
  1721. //m_scene.PhysicsScene.RaycastWorld(StartRayCastPosition, direction, distance, SitRayCastResponseAvatarPosition);
  1722. }
  1723. else
  1724. {
  1725. ControllingClient.SendAlertMessage("Sit position not accessable.");
  1726. m_requestedSitTargetUUID = UUID.Zero;
  1727. m_requestedSitTargetID = 0;
  1728. m_requestedSitOffset = Vector3.Zero;
  1729. }
  1730. }
  1731. else
  1732. {
  1733. ControllingClient.SendAlertMessage("Sit position not accessable.");
  1734. m_requestedSitTargetUUID = UUID.Zero;
  1735. m_requestedSitTargetID = 0;
  1736. m_requestedSitOffset = Vector3.Zero;
  1737. }
  1738. }
  1739. else
  1740. {
  1741. ControllingClient.SendAlertMessage("Sit position no longer exists");
  1742. m_requestedSitTargetUUID = UUID.Zero;
  1743. m_requestedSitTargetID = 0;
  1744. m_requestedSitOffset = Vector3.Zero;
  1745. }
  1746. }
  1747. private void SitRaycastFindEdge(Vector3 collisionPoint, Vector3 collisionNormal)
  1748. {
  1749. int i = 0;
  1750. //throw new NotImplementedException();
  1751. //m_requestedSitTargetUUID = UUID.Zero;
  1752. //m_requestedSitTargetID = 0;
  1753. //m_requestedSitOffset = Vector3.Zero;
  1754. SendSitResponse(ControllingClient, m_requestedSitTargetUUID, collisionPoint - m_requestedSitOffset, Quaternion.Identity);
  1755. }
  1756. */
  1757. public void HandleAgentRequestSit(IClientAPI remoteClient, UUID agentID, UUID targetID, Vector3 offset, string sitAnimation)
  1758. {
  1759. if (m_parentID != 0)
  1760. {
  1761. StandUp();
  1762. }
  1763. if (!String.IsNullOrEmpty(sitAnimation))
  1764. {
  1765. m_nextSitAnimation = sitAnimation;
  1766. }
  1767. else
  1768. {
  1769. m_nextSitAnimation = "SIT";
  1770. }
  1771. //SceneObjectPart part = m_scene.GetSceneObjectPart(targetID);
  1772. SceneObjectPart part = FindNextAvailableSitTarget(targetID);
  1773. if (part != null)
  1774. {
  1775. m_requestedSitTargetID = part.LocalId;
  1776. //m_requestedSitOffset = offset;
  1777. m_requestedSitTargetUUID = targetID;
  1778. m_log.DebugFormat("[SIT]: Client requested Sit Position: {0}", offset);
  1779. if (m_scene.PhysicsScene.SupportsRayCast())
  1780. {
  1781. //SitRayCastAvatarPosition(part);
  1782. //return;
  1783. }
  1784. }
  1785. else
  1786. {
  1787. m_log.Warn("Sit requested on unknown object: " + targetID);
  1788. }
  1789. SendSitResponse(remoteClient, targetID, offset, Quaternion.Identity);
  1790. }
  1791. public void HandleAgentSit(IClientAPI remoteClient, UUID agentID)
  1792. {
  1793. if (!String.IsNullOrEmpty(m_nextSitAnimation))
  1794. {
  1795. HandleAgentSit(remoteClient, agentID, m_nextSitAnimation);
  1796. }
  1797. else
  1798. {
  1799. HandleAgentSit(remoteClient, agentID, "SIT");
  1800. }
  1801. }
  1802. public void HandleAgentSit(IClientAPI remoteClient, UUID agentID, string sitAnimation)
  1803. {
  1804. SceneObjectPart part = m_scene.GetSceneObjectPart(m_requestedSitTargetID);
  1805. if (m_sitAtAutoTarget || !m_autopilotMoving)
  1806. {
  1807. if (part != null)
  1808. {
  1809. if (part.GetAvatarOnSitTarget() == UUID)
  1810. {
  1811. Vector3 sitTargetPos = part.SitTargetPosition;
  1812. Quaternion sitTargetOrient = part.SitTargetOrientation;
  1813. //Quaternion vq = new Quaternion(sitTargetPos.X, sitTargetPos.Y+0.2f, sitTargetPos.Z+0.2f, 0);
  1814. //Quaternion nq = new Quaternion(-sitTargetOrient.X, -sitTargetOrient.Y, -sitTargetOrient.Z, sitTargetOrient.w);
  1815. //Quaternion result = (sitTargetOrient * vq) * nq;
  1816. m_pos = new Vector3(sitTargetPos.X, sitTargetPos.Y, sitTargetPos.Z);
  1817. m_pos += SIT_TARGET_ADJUSTMENT;
  1818. m_bodyRot = sitTargetOrient;
  1819. //Rotation = sitTargetOrient;
  1820. m_parentPosition = part.AbsolutePosition;
  1821. //SendTerseUpdateToAllClients();
  1822. }
  1823. else
  1824. {
  1825. m_pos -= part.AbsolutePosition;
  1826. m_parentPosition = part.AbsolutePosition;
  1827. }
  1828. }
  1829. else
  1830. {
  1831. return;
  1832. }
  1833. }
  1834. m_parentID = m_requestedSitTargetID;
  1835. Velocity = Vector3.Zero;
  1836. RemoveFromPhysicalScene();
  1837. Animator.TrySetMovementAnimation(sitAnimation);
  1838. SendFullUpdateToAllClients();
  1839. // This may seem stupid, but Our Full updates don't send avatar rotation :P
  1840. // So we're also sending a terse update (which has avatar rotation)
  1841. // [Update] We do now.
  1842. //SendTerseUpdateToAllClients();
  1843. }
  1844. /// <summary>
  1845. /// Event handler for the 'Always run' setting on the client
  1846. /// Tells the physics plugin to increase speed of movement.
  1847. /// </summary>
  1848. public void HandleSetAlwaysRun(IClientAPI remoteClient, bool pSetAlwaysRun)
  1849. {
  1850. m_setAlwaysRun = pSetAlwaysRun;
  1851. if (PhysicsActor != null)
  1852. {
  1853. PhysicsActor.SetAlwaysRun = pSetAlwaysRun;
  1854. }
  1855. }
  1856. public void HandleStartAnim(IClientAPI remoteClient, UUID animID)
  1857. {
  1858. Animator.AddAnimation(animID, UUID.Zero);
  1859. }
  1860. public void HandleStopAnim(IClientAPI remoteClient, UUID animID)
  1861. {
  1862. Animator.RemoveAnimation(animID);
  1863. }
  1864. /// <summary>
  1865. /// Rotate the avatar to the given rotation and apply a movement in the given relative vector
  1866. /// </summary>
  1867. /// <param name="vec">The vector in which to move. This is relative to the rotation argument</param>
  1868. /// <param name="rotation">The direction in which this avatar should now face.
  1869. public void AddNewMovement(Vector3 vec, Quaternion rotation)
  1870. {
  1871. if (m_isChildAgent)
  1872. {
  1873. // WHAT???
  1874. m_log.Debug("[SCENEPRESENCE]: AddNewMovement() called on child agent, making root agent!");
  1875. // we have to reset the user's child agent connections.
  1876. // Likely, here they've lost the eventqueue for other regions so border
  1877. // crossings will fail at this point unless we reset them.
  1878. List<ulong> regions = new List<ulong>(KnownChildRegionHandles);
  1879. regions.Remove(m_scene.RegionInfo.RegionHandle);
  1880. MakeRootAgent(new Vector3(127f, 127f, 127f), true);
  1881. // Async command
  1882. if (m_scene.SceneGridService != null)
  1883. {
  1884. m_scene.SceneGridService.SendCloseChildAgentConnections(UUID, regions);
  1885. // Give the above command some time to try and close the connections.
  1886. // this is really an emergency.. so sleep, or we'll get all discombobulated.
  1887. System.Threading.Thread.Sleep(500);
  1888. }
  1889. if (m_scene.SceneGridService != null)
  1890. {
  1891. IEntityTransferModule m_agentTransfer = m_scene.RequestModuleInterface<IEntityTransferModule>();
  1892. if (m_agentTransfer != null)
  1893. m_agentTransfer.EnableChildAgents(this);
  1894. }
  1895. return;
  1896. }
  1897. m_perfMonMS = Util.EnvironmentTickCount();
  1898. Rotation = rotation;
  1899. Vector3 direc = vec * rotation;
  1900. direc.Normalize();
  1901. direc *= 0.03f * 128f * m_speedModifier;
  1902. PhysicsActor actor = m_physicsActor;
  1903. if (actor != null)
  1904. {
  1905. if (actor.Flying)
  1906. {
  1907. direc *= 4.0f;
  1908. //bool controlland = (((m_AgentControlFlags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0) || ((m_AgentControlFlags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG) != 0));
  1909. //bool colliding = (m_physicsActor.IsColliding==true);
  1910. //if (controlland)
  1911. // m_log.Info("[AGENT]: landCommand");
  1912. //if (colliding)
  1913. // m_log.Info("[AGENT]: colliding");
  1914. //if (m_physicsActor.Flying && colliding && controlland)
  1915. //{
  1916. // StopFlying();
  1917. // m_log.Info("[AGENT]: Stop FLying");
  1918. //}
  1919. }
  1920. else if (!actor.Flying && actor.IsColliding)
  1921. {
  1922. if (direc.Z > 2.0f)
  1923. {
  1924. direc.Z *= 3.0f;
  1925. // TODO: PreJump and jump happen too quickly. Many times prejump gets ignored.
  1926. Animator.TrySetMovementAnimation("PREJUMP");
  1927. Animator.TrySetMovementAnimation("JUMP");
  1928. }
  1929. }
  1930. }
  1931. // TODO: Add the force instead of only setting it to support multiple forces per frame?
  1932. m_forceToApply = direc;
  1933. m_scene.StatsReporter.AddAgentTime(Util.EnvironmentTickCountSubtract(m_perfMonMS));
  1934. }
  1935. #endregion
  1936. #region Overridden Methods
  1937. public override void Update()
  1938. {
  1939. const float ROTATION_TOLERANCE = 0.01f;
  1940. const float VELOCITY_TOLERANCE = 0.001f;
  1941. const float POSITION_TOLERANCE = 0.05f;
  1942. //const int TIME_MS_TOLERANCE = 3000;
  1943. SendPrimUpdates();
  1944. if (m_isChildAgent == false)
  1945. {
  1946. // PhysicsActor actor = m_physicsActor;
  1947. // NOTE: Velocity is not the same as m_velocity. Velocity will attempt to
  1948. // grab the latest PhysicsActor velocity, whereas m_velocity is often
  1949. // storing a requested force instead of an actual traveling velocity
  1950. // Throw away duplicate or insignificant updates
  1951. if (!m_bodyRot.ApproxEquals(m_lastRotation, ROTATION_TOLERANCE) ||
  1952. !Velocity.ApproxEquals(m_lastVelocity, VELOCITY_TOLERANCE) ||
  1953. !m_pos.ApproxEquals(m_lastPosition, POSITION_TOLERANCE))
  1954. //Environment.TickCount - m_lastTerseSent > TIME_MS_TOLERANCE)
  1955. {
  1956. SendTerseUpdateToAllClients();
  1957. // Update the "last" values
  1958. m_lastPosition = m_pos;
  1959. m_lastRotation = m_bodyRot;
  1960. m_lastVelocity = Velocity;
  1961. //m_lastTerseSent = Environment.TickCount;
  1962. }
  1963. // followed suggestion from mic bowman. reversed the two lines below.
  1964. if (m_parentID == 0 && m_physicsActor != null || m_parentID != 0) // Check that we have a physics actor or we're sitting on something
  1965. CheckForBorderCrossing();
  1966. CheckForSignificantMovement(); // sends update to the modules.
  1967. }
  1968. }
  1969. #endregion
  1970. #region Update Client(s)
  1971. /// <summary>
  1972. /// Sends a location update to the client connected to this scenePresence
  1973. /// </summary>
  1974. /// <param name="remoteClient"></param>
  1975. public void SendTerseUpdateToClient(IClientAPI remoteClient)
  1976. {
  1977. // If the client is inactive, it's getting its updates from another
  1978. // server.
  1979. if (remoteClient.IsActive)
  1980. {
  1981. m_perfMonMS = Util.EnvironmentTickCount();
  1982. Vector3 pos = m_pos;
  1983. pos.Z += m_appearance.HipOffset;
  1984. //m_log.DebugFormat("[SCENEPRESENCE]: TerseUpdate: Pos={0} Rot={1} Vel={2}", m_pos, m_bodyRot, m_velocity);
  1985. remoteClient.SendPrimUpdate(
  1986. this,
  1987. PrimUpdateFlags.Position | PrimUpdateFlags.Rotation | PrimUpdateFlags.Velocity
  1988. | PrimUpdateFlags.Acceleration | PrimUpdateFlags.AngularVelocity);
  1989. m_scene.StatsReporter.AddAgentTime(Util.EnvironmentTickCountSubtract(m_perfMonMS));
  1990. m_scene.StatsReporter.AddAgentUpdates(1);
  1991. }
  1992. }
  1993. /// <summary>
  1994. /// Send a location/velocity/accelleration update to all agents in scene
  1995. /// </summary>
  1996. public void SendTerseUpdateToAllClients()
  1997. {
  1998. m_perfMonMS = Util.EnvironmentTickCount();
  1999. m_scene.ForEachClient(SendTerseUpdateToClient);
  2000. m_scene.StatsReporter.AddAgentTime(Util.EnvironmentTickCountSubtract(m_perfMonMS));
  2001. }
  2002. public void SendCoarseLocations(List<Vector3> coarseLocations, List<UUID> avatarUUIDs)
  2003. {
  2004. SendCourseLocationsMethod d = m_sendCourseLocationsMethod;
  2005. if (d != null)
  2006. {
  2007. d.Invoke(m_scene.RegionInfo.originRegionID, this, coarseLocations, avatarUUIDs);
  2008. }
  2009. }
  2010. public void SetSendCourseLocationMethod(SendCourseLocationsMethod d)
  2011. {
  2012. if (d != null)
  2013. m_sendCourseLocationsMethod = d;
  2014. }
  2015. public void SendCoarseLocationsDefault(UUID sceneId, ScenePresence p, List<Vector3> coarseLocations, List<UUID> avatarUUIDs)
  2016. {
  2017. m_perfMonMS = Util.EnvironmentTickCount();
  2018. m_controllingClient.SendCoarseLocationUpdate(avatarUUIDs, coarseLocations);
  2019. m_scene.StatsReporter.AddAgentTime(Util.EnvironmentTickCountSubtract(m_perfMonMS));
  2020. }
  2021. /// <summary>
  2022. /// Tell other client about this avatar (The client previously didn't know or had outdated details about this avatar)
  2023. /// </summary>
  2024. /// <param name="remoteAvatar"></param>
  2025. public void SendFullUpdateToOtherClient(ScenePresence remoteAvatar)
  2026. {
  2027. // 2 stage check is needed.
  2028. if (remoteAvatar == null)
  2029. return;
  2030. IClientAPI cl = remoteAvatar.ControllingClient;
  2031. if (cl == null)
  2032. return;
  2033. if (m_appearance.Texture == null)
  2034. return;
  2035. // MT: This is needed for sit. It's legal to send it to oneself, and the name
  2036. // of the method is a misnomer
  2037. //
  2038. // if (LocalId == remoteAvatar.LocalId)
  2039. // {
  2040. // m_log.WarnFormat("[SCENEPRESENCE]: An agent is attempting to send avatar data to itself; {0}", UUID);
  2041. // return;
  2042. // }
  2043. if (IsChildAgent)
  2044. {
  2045. m_log.WarnFormat("[SCENEPRESENCE]: A child agent is attempting to send out avatar data; {0}", UUID);
  2046. return;
  2047. }
  2048. remoteAvatar.m_controllingClient.SendAvatarDataImmediate(this);
  2049. m_scene.StatsReporter.AddAgentUpdates(1);
  2050. }
  2051. /// <summary>
  2052. /// Tell *ALL* agents about this agent
  2053. /// </summary>
  2054. public void SendInitialFullUpdateToAllClients()
  2055. {
  2056. m_perfMonMS = Util.EnvironmentTickCount();
  2057. int avUpdates = 0;
  2058. m_scene.ForEachScenePresence(delegate(ScenePresence avatar)
  2059. {
  2060. ++avUpdates;
  2061. // Don't update ourselves
  2062. if (avatar.LocalId == LocalId)
  2063. return;
  2064. // If this is a root agent, then get info about the avatar
  2065. if (!IsChildAgent)
  2066. {
  2067. SendFullUpdateToOtherClient(avatar);
  2068. }
  2069. // If the other avatar is a root
  2070. if (!avatar.IsChildAgent)
  2071. {
  2072. avatar.SendFullUpdateToOtherClient(this);
  2073. avatar.SendAppearanceToOtherAgent(this);
  2074. avatar.Animator.SendAnimPackToClient(ControllingClient);
  2075. }
  2076. });
  2077. m_scene.StatsReporter.AddAgentUpdates(avUpdates);
  2078. m_scene.StatsReporter.AddAgentTime(Util.EnvironmentTickCountSubtract(m_perfMonMS));
  2079. //Animator.SendAnimPack();
  2080. }
  2081. public void SendFullUpdateToAllClients()
  2082. {
  2083. m_perfMonMS = Util.EnvironmentTickCount();
  2084. // only send update from root agents to other clients; children are only "listening posts"
  2085. if (IsChildAgent)
  2086. {
  2087. m_log.Warn("[SCENEPRESENCE] attempt to send update from a childagent");
  2088. return;
  2089. }
  2090. int count = 0;
  2091. m_scene.ForEachScenePresence(delegate(ScenePresence sp)
  2092. {
  2093. if (sp.IsChildAgent)
  2094. return;
  2095. SendFullUpdateToOtherClient(sp);
  2096. ++count;
  2097. });
  2098. m_scene.StatsReporter.AddAgentUpdates(count);
  2099. m_scene.StatsReporter.AddAgentTime(Util.EnvironmentTickCountSubtract(m_perfMonMS));
  2100. Animator.SendAnimPack();
  2101. }
  2102. /// <summary>
  2103. /// Do everything required once a client completes its movement into a region
  2104. /// </summary>
  2105. public void SendInitialData()
  2106. {
  2107. // Moved this into CompleteMovement to ensure that m_appearance is initialized before
  2108. // the inventory arrives
  2109. // m_scene.GetAvatarAppearance(m_controllingClient, out m_appearance);
  2110. m_controllingClient.SendAvatarDataImmediate(this);
  2111. if (m_scene.AvatarFactory != null)
  2112. {
  2113. if (m_scene.AvatarFactory.ValidateBakedTextureCache(m_controllingClient))
  2114. {
  2115. // m_log.WarnFormat("[SCENEPRESENCE]: baked textures are in the cache for {0}", Name);
  2116. m_controllingClient.SendAppearance(
  2117. m_appearance.Owner,m_appearance.VisualParams,m_appearance.Texture.GetBytes());
  2118. }
  2119. }
  2120. else
  2121. {
  2122. m_log.WarnFormat("[SCENEPRESENCE]: AvatarFactory not set for {0}", Name);
  2123. }
  2124. SendInitialFullUpdateToAllClients();
  2125. }
  2126. /// <summary>
  2127. ///
  2128. /// </summary>
  2129. public void SendAppearanceToAllOtherAgents()
  2130. {
  2131. // DEBUG ON
  2132. // m_log.WarnFormat("[SCENEPRESENCE]: Send appearance from {0} to all other agents", m_uuid);
  2133. // DEBUG OFF
  2134. m_perfMonMS = Util.EnvironmentTickCount();
  2135. m_scene.ForEachScenePresence(delegate(ScenePresence scenePresence)
  2136. {
  2137. if (scenePresence.UUID != UUID)
  2138. {
  2139. SendAppearanceToOtherAgent(scenePresence);
  2140. }
  2141. });
  2142. m_scene.StatsReporter.AddAgentTime(Util.EnvironmentTickCountSubtract(m_perfMonMS));
  2143. }
  2144. /// <summary>
  2145. /// Send appearance data to an agent that isn't this one.
  2146. /// </summary>
  2147. /// <param name="avatar"></param>
  2148. public void SendAppearanceToOtherAgent(ScenePresence avatar)
  2149. {
  2150. if (LocalId == avatar.LocalId)
  2151. {
  2152. m_log.WarnFormat("[SCENE PRESENCE]: An agent is attempting to send appearance data to itself; {0}", UUID);
  2153. return;
  2154. }
  2155. // DEBUG ON
  2156. // m_log.WarnFormat("[SP] Send appearance from {0} to {1}",m_uuid,avatar.ControllingClient.AgentId);
  2157. // DEBUG OFF
  2158. avatar.ControllingClient.SendAppearance(
  2159. m_appearance.Owner, m_appearance.VisualParams, m_appearance.Texture.GetBytes());
  2160. }
  2161. // Because appearance setting is in a module, we actually need
  2162. // to give it access to our appearance directly, otherwise we
  2163. // get a synchronization issue.
  2164. public AvatarAppearance Appearance
  2165. {
  2166. get { return m_appearance; }
  2167. set { m_appearance = value; }
  2168. }
  2169. #endregion
  2170. #region Significant Movement Method
  2171. /// <summary>
  2172. /// This checks for a significant movement and sends a courselocationchange update
  2173. /// </summary>
  2174. protected void CheckForSignificantMovement()
  2175. {
  2176. // Movement updates for agents in neighboring regions are sent directly to clients.
  2177. // This value only affects how often agent positions are sent to neighbor regions
  2178. // for things such as distance-based update prioritization
  2179. const float SIGNIFICANT_MOVEMENT = 2.0f;
  2180. if (Util.GetDistanceTo(AbsolutePosition, posLastSignificantMove) > SIGNIFICANT_MOVEMENT)
  2181. {
  2182. posLastSignificantMove = AbsolutePosition;
  2183. m_scene.EventManager.TriggerSignificantClientMovement(m_controllingClient);
  2184. }
  2185. // Minimum Draw distance is 64 meters, the Radius of the draw distance sphere is 32m
  2186. if (Util.GetDistanceTo(AbsolutePosition, m_lastChildAgentUpdatePosition) >= Scene.ChildReprioritizationDistance ||
  2187. Util.GetDistanceTo(CameraPosition, m_lastChildAgentUpdateCamPosition) >= Scene.ChildReprioritizationDistance)
  2188. {
  2189. m_lastChildAgentUpdatePosition = AbsolutePosition;
  2190. m_lastChildAgentUpdateCamPosition = CameraPosition;
  2191. ChildAgentDataUpdate cadu = new ChildAgentDataUpdate();
  2192. cadu.ActiveGroupID = UUID.Zero.Guid;
  2193. cadu.AgentID = UUID.Guid;
  2194. cadu.alwaysrun = m_setAlwaysRun;
  2195. cadu.AVHeight = m_appearance.AvatarHeight;
  2196. Vector3 tempCameraCenter = m_CameraCenter;
  2197. cadu.cameraPosition = tempCameraCenter;
  2198. cadu.drawdistance = m_DrawDistance;
  2199. cadu.GroupAccess = 0;
  2200. cadu.Position = AbsolutePosition;
  2201. cadu.regionHandle = m_rootRegionHandle;
  2202. float multiplier = 1;
  2203. int innacurateNeighbors = m_scene.GetInaccurateNeighborCount();
  2204. if (innacurateNeighbors != 0)
  2205. {
  2206. multiplier = 1f / (float)innacurateNeighbors;
  2207. }
  2208. if (multiplier <= 0f)
  2209. {
  2210. multiplier = 0.25f;
  2211. }
  2212. //m_log.Info("[NeighborThrottle]: " + m_scene.GetInaccurateNeighborCount().ToString() + " - m: " + multiplier.ToString());
  2213. cadu.throttles = ControllingClient.GetThrottlesPacked(multiplier);
  2214. cadu.Velocity = Velocity;
  2215. AgentPosition agentpos = new AgentPosition();
  2216. agentpos.CopyFrom(cadu);
  2217. m_scene.SendOutChildAgentUpdates(agentpos, this);
  2218. }
  2219. }
  2220. #endregion
  2221. #region Border Crossing Methods
  2222. /// <summary>
  2223. /// Checks to see if the avatar is in range of a border and calls CrossToNewRegion
  2224. /// </summary>
  2225. protected void CheckForBorderCrossing()
  2226. {
  2227. if (IsChildAgent)
  2228. return;
  2229. Vector3 pos2 = AbsolutePosition;
  2230. Vector3 vel = Velocity;
  2231. int neighbor = 0;
  2232. int[] fix = new int[2];
  2233. float timeStep = 0.1f;
  2234. pos2.X = pos2.X + (vel.X*timeStep);
  2235. pos2.Y = pos2.Y + (vel.Y*timeStep);
  2236. pos2.Z = pos2.Z + (vel.Z*timeStep);
  2237. if (!IsInTransit)
  2238. {
  2239. // Checks if where it's headed exists a region
  2240. bool needsTransit = false;
  2241. if (m_scene.TestBorderCross(pos2, Cardinals.W))
  2242. {
  2243. if (m_scene.TestBorderCross(pos2, Cardinals.S))
  2244. {
  2245. needsTransit = true;
  2246. neighbor = HaveNeighbor(Cardinals.SW, ref fix);
  2247. }
  2248. else if (m_scene.TestBorderCross(pos2, Cardinals.N))
  2249. {
  2250. needsTransit = true;
  2251. neighbor = HaveNeighbor(Cardinals.NW, ref fix);
  2252. }
  2253. else
  2254. {
  2255. needsTransit = true;
  2256. neighbor = HaveNeighbor(Cardinals.W, ref fix);
  2257. }
  2258. }
  2259. else if (m_scene.TestBorderCross(pos2, Cardinals.E))
  2260. {
  2261. if (m_scene.TestBorderCross(pos2, Cardinals.S))
  2262. {
  2263. needsTransit = true;
  2264. neighbor = HaveNeighbor(Cardinals.SE, ref fix);
  2265. }
  2266. else if (m_scene.TestBorderCross(pos2, Cardinals.N))
  2267. {
  2268. needsTransit = true;
  2269. neighbor = HaveNeighbor(Cardinals.NE, ref fix);
  2270. }
  2271. else
  2272. {
  2273. needsTransit = true;
  2274. neighbor = HaveNeighbor(Cardinals.E, ref fix);
  2275. }
  2276. }
  2277. else if (m_scene.TestBorderCross(pos2, Cardinals.S))
  2278. {
  2279. needsTransit = true;
  2280. neighbor = HaveNeighbor(Cardinals.S, ref fix);
  2281. }
  2282. else if (m_scene.TestBorderCross(pos2, Cardinals.N))
  2283. {
  2284. needsTransit = true;
  2285. neighbor = HaveNeighbor(Cardinals.N, ref fix);
  2286. }
  2287. // Makes sure avatar does not end up outside region
  2288. if (neighbor <= 0)
  2289. {
  2290. if (!needsTransit)
  2291. {
  2292. if (m_requestedSitTargetUUID == UUID.Zero)
  2293. {
  2294. Vector3 pos = AbsolutePosition;
  2295. if (AbsolutePosition.X < 0)
  2296. pos.X += Velocity.X;
  2297. else if (AbsolutePosition.X > Constants.RegionSize)
  2298. pos.X -= Velocity.X;
  2299. if (AbsolutePosition.Y < 0)
  2300. pos.Y += Velocity.Y;
  2301. else if (AbsolutePosition.Y > Constants.RegionSize)
  2302. pos.Y -= Velocity.Y;
  2303. AbsolutePosition = pos;
  2304. }
  2305. }
  2306. }
  2307. else if (neighbor > 0)
  2308. CrossToNewRegion();
  2309. }
  2310. else
  2311. {
  2312. RemoveFromPhysicalScene();
  2313. // This constant has been inferred from experimentation
  2314. // I'm not sure what this value should be, so I tried a few values.
  2315. timeStep = 0.04f;
  2316. pos2 = AbsolutePosition;
  2317. pos2.X = pos2.X + (vel.X * timeStep);
  2318. pos2.Y = pos2.Y + (vel.Y * timeStep);
  2319. pos2.Z = pos2.Z + (vel.Z * timeStep);
  2320. m_pos = pos2;
  2321. }
  2322. }
  2323. protected int HaveNeighbor(Cardinals car, ref int[] fix)
  2324. {
  2325. uint neighbourx = m_regionInfo.RegionLocX;
  2326. uint neighboury = m_regionInfo.RegionLocY;
  2327. int dir = (int)car;
  2328. if (dir > 1 && dir < 5) //Heading East
  2329. neighbourx++;
  2330. else if (dir > 5) // Heading West
  2331. neighbourx--;
  2332. if (dir < 3 || dir == 8) // Heading North
  2333. neighboury++;
  2334. else if (dir > 3 && dir < 7) // Heading Sout
  2335. neighboury--;
  2336. int x = (int)(neighbourx * Constants.RegionSize);
  2337. int y = (int)(neighboury * Constants.RegionSize);
  2338. GridRegion neighbourRegion = m_scene.GridService.GetRegionByPosition(m_scene.RegionInfo.ScopeID, x, y);
  2339. if (neighbourRegion == null)
  2340. {
  2341. fix[0] = (int)(m_regionInfo.RegionLocX - neighbourx);
  2342. fix[1] = (int)(m_regionInfo.RegionLocY - neighboury);
  2343. return dir * (-1);
  2344. }
  2345. else
  2346. return dir;
  2347. }
  2348. /// <summary>
  2349. /// Moves the agent outside the region bounds
  2350. /// Tells neighbor region that we're crossing to it
  2351. /// If the neighbor accepts, remove the agent's viewable avatar from this scene
  2352. /// set them to a child agent.
  2353. /// </summary>
  2354. protected void CrossToNewRegion()
  2355. {
  2356. InTransit();
  2357. try
  2358. {
  2359. m_scene.CrossAgentToNewRegion(this, m_physicsActor.Flying);
  2360. }
  2361. catch
  2362. {
  2363. m_scene.CrossAgentToNewRegion(this, false);
  2364. }
  2365. }
  2366. public void InTransit()
  2367. {
  2368. m_inTransit = true;
  2369. if ((m_physicsActor != null) && m_physicsActor.Flying)
  2370. m_AgentControlFlags |= AgentManager.ControlFlags.AGENT_CONTROL_FLY;
  2371. else if ((m_AgentControlFlags & AgentManager.ControlFlags.AGENT_CONTROL_FLY) != 0)
  2372. m_AgentControlFlags &= ~AgentManager.ControlFlags.AGENT_CONTROL_FLY;
  2373. }
  2374. public void NotInTransit()
  2375. {
  2376. m_inTransit = false;
  2377. }
  2378. public void RestoreInCurrentScene()
  2379. {
  2380. AddToPhysicalScene(false); // not exactly false
  2381. }
  2382. public void Reset()
  2383. {
  2384. // Put the child agent back at the center
  2385. AbsolutePosition
  2386. = new Vector3(((float)Constants.RegionSize * 0.5f), ((float)Constants.RegionSize * 0.5f), 70);
  2387. Animator.ResetAnimations();
  2388. }
  2389. /// <summary>
  2390. /// Computes which child agents to close when the scene presence moves to another region.
  2391. /// Removes those regions from m_knownRegions.
  2392. /// </summary>
  2393. /// <param name="newRegionX">The new region's x on the map</param>
  2394. /// <param name="newRegionY">The new region's y on the map</param>
  2395. /// <returns></returns>
  2396. public void CloseChildAgents(uint newRegionX, uint newRegionY)
  2397. {
  2398. List<ulong> byebyeRegions = new List<ulong>();
  2399. m_log.DebugFormat(
  2400. "[SCENE PRESENCE]: Closing child agents. Checking {0} regions in {1}",
  2401. m_knownChildRegions.Keys.Count, Scene.RegionInfo.RegionName);
  2402. //DumpKnownRegions();
  2403. lock (m_knownChildRegions)
  2404. {
  2405. foreach (ulong handle in m_knownChildRegions.Keys)
  2406. {
  2407. // Don't close the agent on this region yet
  2408. if (handle != Scene.RegionInfo.RegionHandle)
  2409. {
  2410. uint x, y;
  2411. Utils.LongToUInts(handle, out x, out y);
  2412. x = x / Constants.RegionSize;
  2413. y = y / Constants.RegionSize;
  2414. //m_log.Debug("---> x: " + x + "; newx:" + newRegionX + "; Abs:" + (int)Math.Abs((int)(x - newRegionX)));
  2415. //m_log.Debug("---> y: " + y + "; newy:" + newRegionY + "; Abs:" + (int)Math.Abs((int)(y - newRegionY)));
  2416. if (Util.IsOutsideView(x, newRegionX, y, newRegionY))
  2417. {
  2418. byebyeRegions.Add(handle);
  2419. }
  2420. }
  2421. }
  2422. }
  2423. if (byebyeRegions.Count > 0)
  2424. {
  2425. m_log.Debug("[SCENE PRESENCE]: Closing " + byebyeRegions.Count + " child agents");
  2426. m_scene.SceneGridService.SendCloseChildAgentConnections(m_controllingClient.AgentId, byebyeRegions);
  2427. }
  2428. foreach (ulong handle in byebyeRegions)
  2429. {
  2430. RemoveNeighbourRegion(handle);
  2431. }
  2432. }
  2433. #endregion
  2434. /// <summary>
  2435. /// This allows the Sim owner the abiility to kick users from their sim currently.
  2436. /// It tells the client that the agent has permission to do so.
  2437. /// </summary>
  2438. public void GrantGodlikePowers(UUID agentID, UUID sessionID, UUID token, bool godStatus)
  2439. {
  2440. if (godStatus)
  2441. {
  2442. // For now, assign god level 200 to anyone
  2443. // who is granted god powers, but has no god level set.
  2444. //
  2445. UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, agentID);
  2446. if (account != null)
  2447. {
  2448. if (account.UserLevel > 0)
  2449. m_godLevel = account.UserLevel;
  2450. else
  2451. m_godLevel = 200;
  2452. }
  2453. }
  2454. else
  2455. {
  2456. m_godLevel = 0;
  2457. }
  2458. ControllingClient.SendAdminResponse(token, (uint)m_godLevel);
  2459. }
  2460. #region Child Agent Updates
  2461. public void ChildAgentDataUpdate(AgentData cAgentData)
  2462. {
  2463. //m_log.Debug(" >>> ChildAgentDataUpdate <<< " + Scene.RegionInfo.RegionName);
  2464. if (!IsChildAgent)
  2465. return;
  2466. CopyFrom(cAgentData);
  2467. }
  2468. /// <summary>
  2469. /// This updates important decision making data about a child agent
  2470. /// The main purpose is to figure out what objects to send to a child agent that's in a neighboring region
  2471. /// </summary>
  2472. public void ChildAgentDataUpdate(AgentPosition cAgentData, uint tRegionX, uint tRegionY, uint rRegionX, uint rRegionY)
  2473. {
  2474. if (!IsChildAgent)
  2475. return;
  2476. //m_log.Debug(" >>> ChildAgentPositionUpdate <<< " + rRegionX + "-" + rRegionY);
  2477. int shiftx = ((int)rRegionX - (int)tRegionX) * (int)Constants.RegionSize;
  2478. int shifty = ((int)rRegionY - (int)tRegionY) * (int)Constants.RegionSize;
  2479. Vector3 offset = new Vector3(shiftx, shifty, 0f);
  2480. m_DrawDistance = cAgentData.Far;
  2481. if (cAgentData.Position != new Vector3(-1f, -1f, -1f)) // UGH!!
  2482. m_pos = cAgentData.Position + offset;
  2483. if (Vector3.Distance(AbsolutePosition, posLastSignificantMove) >= Scene.ChildReprioritizationDistance)
  2484. {
  2485. posLastSignificantMove = AbsolutePosition;
  2486. ReprioritizeUpdates();
  2487. }
  2488. m_CameraCenter = cAgentData.Center + offset;
  2489. //SetHeight(cAgentData.AVHeight);
  2490. if ((cAgentData.Throttles != null) && cAgentData.Throttles.Length > 0)
  2491. ControllingClient.SetChildAgentThrottle(cAgentData.Throttles);
  2492. // Sends out the objects in the user's draw distance if m_sendTasksToChild is true.
  2493. if (m_scene.m_seeIntoRegionFromNeighbor)
  2494. m_sceneViewer.Reset();
  2495. //cAgentData.AVHeight;
  2496. m_rootRegionHandle = cAgentData.RegionHandle;
  2497. //m_velocity = cAgentData.Velocity;
  2498. }
  2499. public void CopyTo(AgentData cAgent)
  2500. {
  2501. cAgent.CallbackURI = m_callbackURI;
  2502. cAgent.AgentID = UUID;
  2503. cAgent.RegionID = Scene.RegionInfo.RegionID;
  2504. cAgent.Position = AbsolutePosition;
  2505. cAgent.Velocity = m_velocity;
  2506. cAgent.Center = m_CameraCenter;
  2507. cAgent.AtAxis = m_CameraAtAxis;
  2508. cAgent.LeftAxis = m_CameraLeftAxis;
  2509. cAgent.UpAxis = m_CameraUpAxis;
  2510. cAgent.Far = m_DrawDistance;
  2511. // Throttles
  2512. float multiplier = 1;
  2513. int innacurateNeighbors = m_scene.GetInaccurateNeighborCount();
  2514. if (innacurateNeighbors != 0)
  2515. {
  2516. multiplier = 1f / innacurateNeighbors;
  2517. }
  2518. if (multiplier <= 0f)
  2519. {
  2520. multiplier = 0.25f;
  2521. }
  2522. //m_log.Info("[NeighborThrottle]: " + m_scene.GetInaccurateNeighborCount().ToString() + " - m: " + multiplier.ToString());
  2523. cAgent.Throttles = ControllingClient.GetThrottlesPacked(multiplier);
  2524. cAgent.HeadRotation = m_headrotation;
  2525. cAgent.BodyRotation = m_bodyRot;
  2526. cAgent.ControlFlags = (uint)m_AgentControlFlags;
  2527. if (m_scene.Permissions.IsGod(new UUID(cAgent.AgentID)))
  2528. cAgent.GodLevel = (byte)m_godLevel;
  2529. else
  2530. cAgent.GodLevel = (byte) 0;
  2531. cAgent.AlwaysRun = m_setAlwaysRun;
  2532. cAgent.Appearance = new AvatarAppearance(m_appearance);
  2533. /*
  2534. try
  2535. {
  2536. // We might not pass the Wearables in all cases...
  2537. // They're only needed so that persistent changes to the appearance
  2538. // are preserved in the new region where the user is moving to.
  2539. // But in Hypergrid we might not let this happen.
  2540. int i = 0;
  2541. UUID[] wears = new UUID[m_appearance.Wearables.Length * 2];
  2542. foreach (AvatarWearable aw in m_appearance.Wearables)
  2543. {
  2544. if (aw != null)
  2545. {
  2546. wears[i++] = aw.ItemID;
  2547. wears[i++] = aw.AssetID;
  2548. }
  2549. else
  2550. {
  2551. wears[i++] = UUID.Zero;
  2552. wears[i++] = UUID.Zero;
  2553. }
  2554. }
  2555. cAgent.Wearables = wears;
  2556. cAgent.VisualParams = m_appearance.VisualParams;
  2557. if (m_appearance.Texture != null)
  2558. cAgent.AgentTextures = m_appearance.Texture.GetBytes();
  2559. }
  2560. catch (Exception e)
  2561. {
  2562. m_log.Warn("[SCENE PRESENCE]: exception in CopyTo " + e.Message);
  2563. }
  2564. //Attachments
  2565. List<int> attPoints = m_appearance.GetAttachedPoints();
  2566. if (attPoints != null)
  2567. {
  2568. //m_log.DebugFormat("[SCENE PRESENCE]: attachments {0}", attPoints.Count);
  2569. int i = 0;
  2570. AvatarAttachment[] attachs = new AvatarAttachment[attPoints.Count];
  2571. foreach (int point in attPoints)
  2572. {
  2573. attachs[i++] = new AvatarAttachment(point, m_appearance.GetAttachedItem(point), m_appearance.GetAttachedAsset(point));
  2574. }
  2575. cAgent.Attachments = attachs;
  2576. }
  2577. */
  2578. lock (scriptedcontrols)
  2579. {
  2580. ControllerData[] controls = new ControllerData[scriptedcontrols.Count];
  2581. int i = 0;
  2582. foreach (ScriptControllers c in scriptedcontrols.Values)
  2583. {
  2584. controls[i++] = new ControllerData(c.itemID, (uint)c.ignoreControls, (uint)c.eventControls);
  2585. }
  2586. cAgent.Controllers = controls;
  2587. }
  2588. // Animations
  2589. try
  2590. {
  2591. cAgent.Anims = Animator.Animations.ToArray();
  2592. }
  2593. catch { }
  2594. // cAgent.GroupID = ??
  2595. // Groups???
  2596. }
  2597. public void CopyFrom(AgentData cAgent)
  2598. {
  2599. // DEBUG ON
  2600. m_log.ErrorFormat("[SCENEPRESENCE] CALLING COPYFROM");
  2601. // DEBUG OFF
  2602. m_originRegionID = cAgent.RegionID;
  2603. m_callbackURI = cAgent.CallbackURI;
  2604. m_pos = cAgent.Position;
  2605. m_velocity = cAgent.Velocity;
  2606. m_CameraCenter = cAgent.Center;
  2607. m_CameraAtAxis = cAgent.AtAxis;
  2608. m_CameraLeftAxis = cAgent.LeftAxis;
  2609. m_CameraUpAxis = cAgent.UpAxis;
  2610. m_DrawDistance = cAgent.Far;
  2611. if ((cAgent.Throttles != null) && cAgent.Throttles.Length > 0)
  2612. ControllingClient.SetChildAgentThrottle(cAgent.Throttles);
  2613. m_headrotation = cAgent.HeadRotation;
  2614. m_bodyRot = cAgent.BodyRotation;
  2615. m_AgentControlFlags = (AgentManager.ControlFlags)cAgent.ControlFlags;
  2616. if (m_scene.Permissions.IsGod(new UUID(cAgent.AgentID)))
  2617. m_godLevel = cAgent.GodLevel;
  2618. m_setAlwaysRun = cAgent.AlwaysRun;
  2619. m_appearance = new AvatarAppearance(cAgent.Appearance);
  2620. if (m_physicsActor != null)
  2621. {
  2622. bool isFlying = m_physicsActor.Flying;
  2623. RemoveFromPhysicalScene();
  2624. AddToPhysicalScene(isFlying);
  2625. }
  2626. /*
  2627. uint i = 0;
  2628. try
  2629. {
  2630. if (cAgent.Wearables == null)
  2631. cAgent.Wearables = new UUID[0];
  2632. AvatarWearable[] wears = new AvatarWearable[cAgent.Wearables.Length / 2];
  2633. for (uint n = 0; n < cAgent.Wearables.Length; n += 2)
  2634. {
  2635. UUID itemId = cAgent.Wearables[n];
  2636. UUID assetId = cAgent.Wearables[n + 1];
  2637. wears[i++] = new AvatarWearable(itemId, assetId);
  2638. }
  2639. // m_appearance.Wearables = wears;
  2640. Primitive.TextureEntry textures = null;
  2641. if (cAgent.AgentTextures != null && cAgent.AgentTextures.Length > 1)
  2642. textures = new Primitive.TextureEntry(cAgent.AgentTextures, 0, cAgent.AgentTextures.Length);
  2643. byte[] visuals = null;
  2644. if ((cAgent.VisualParams != null) && (cAgent.VisualParams.Length < AvatarAppearance.VISUALPARAM_COUNT))
  2645. visuals = (byte[])cAgent.VisualParams.Clone();
  2646. m_appearance = new AvatarAppearance(cAgent.AgentID,wears,textures,visuals);
  2647. }
  2648. catch (Exception e)
  2649. {
  2650. m_log.Warn("[SCENE PRESENCE]: exception in CopyFrom " + e.Message);
  2651. }
  2652. // Attachments
  2653. try
  2654. {
  2655. if (cAgent.Attachments != null)
  2656. {
  2657. m_appearance.ClearAttachments();
  2658. foreach (AvatarAttachment att in cAgent.Attachments)
  2659. {
  2660. m_appearance.SetAttachment(att.AttachPoint, att.ItemID, att.AssetID);
  2661. }
  2662. }
  2663. }
  2664. catch { }
  2665. */
  2666. try
  2667. {
  2668. lock (scriptedcontrols)
  2669. {
  2670. if (cAgent.Controllers != null)
  2671. {
  2672. scriptedcontrols.Clear();
  2673. foreach (ControllerData c in cAgent.Controllers)
  2674. {
  2675. ScriptControllers sc = new ScriptControllers();
  2676. sc.itemID = c.ItemID;
  2677. sc.ignoreControls = (ScriptControlled)c.IgnoreControls;
  2678. sc.eventControls = (ScriptControlled)c.EventControls;
  2679. scriptedcontrols[sc.itemID] = sc;
  2680. }
  2681. }
  2682. }
  2683. }
  2684. catch { }
  2685. // Animations
  2686. try
  2687. {
  2688. Animator.ResetAnimations();
  2689. Animator.Animations.FromArray(cAgent.Anims);
  2690. }
  2691. catch { }
  2692. //cAgent.GroupID = ??
  2693. //Groups???
  2694. }
  2695. public bool CopyAgent(out IAgentData agent)
  2696. {
  2697. agent = new CompleteAgentData();
  2698. CopyTo((AgentData)agent);
  2699. return true;
  2700. }
  2701. #endregion Child Agent Updates
  2702. /// <summary>
  2703. /// Handles part of the PID controller function for moving an avatar.
  2704. /// </summary>
  2705. public override void UpdateMovement()
  2706. {
  2707. if (m_forceToApply.HasValue)
  2708. {
  2709. Vector3 force = m_forceToApply.Value;
  2710. m_updateflag = true;
  2711. // movementvector = force;
  2712. Velocity = force;
  2713. m_forceToApply = null;
  2714. }
  2715. }
  2716. /// <summary>
  2717. /// Adds a physical representation of the avatar to the Physics plugin
  2718. /// </summary>
  2719. public void AddToPhysicalScene(bool isFlying)
  2720. {
  2721. if (m_appearance.AvatarHeight == 0)
  2722. m_appearance.SetHeight();
  2723. PhysicsScene scene = m_scene.PhysicsScene;
  2724. Vector3 pVec = AbsolutePosition;
  2725. // Old bug where the height was in centimeters instead of meters
  2726. m_physicsActor = scene.AddAvatar(Firstname + "." + Lastname, pVec,
  2727. new Vector3(0f, 0f, m_appearance.AvatarHeight), isFlying);
  2728. scene.AddPhysicsActorTaint(m_physicsActor);
  2729. //m_physicsActor.OnRequestTerseUpdate += SendTerseUpdateToAllClients;
  2730. m_physicsActor.OnCollisionUpdate += PhysicsCollisionUpdate;
  2731. m_physicsActor.OnOutOfBounds += OutOfBoundsCall; // Called for PhysicsActors when there's something wrong
  2732. m_physicsActor.SubscribeEvents(500);
  2733. m_physicsActor.LocalID = LocalId;
  2734. }
  2735. private void OutOfBoundsCall(Vector3 pos)
  2736. {
  2737. //bool flying = m_physicsActor.Flying;
  2738. //RemoveFromPhysicalScene();
  2739. //AddToPhysicalScene(flying);
  2740. if (ControllingClient != null)
  2741. ControllingClient.SendAgentAlertMessage("Physics is having a problem with your avatar. You may not be able to move until you relog.", true);
  2742. }
  2743. // Event called by the physics plugin to tell the avatar about a collision.
  2744. private void PhysicsCollisionUpdate(EventArgs e)
  2745. {
  2746. if (e == null)
  2747. return;
  2748. //if ((Math.Abs(Velocity.X) > 0.1e-9f) || (Math.Abs(Velocity.Y) > 0.1e-9f))
  2749. // The Physics Scene will send updates every 500 ms grep: m_physicsActor.SubscribeEvents(
  2750. // as of this comment the interval is set in AddToPhysicalScene
  2751. if (Animator!=null)
  2752. Animator.UpdateMovementAnimations();
  2753. CollisionEventUpdate collisionData = (CollisionEventUpdate)e;
  2754. Dictionary<uint, ContactPoint> coldata = collisionData.m_objCollisionList;
  2755. CollisionPlane = Vector4.UnitW;
  2756. if (coldata.Count != 0 && Animator != null)
  2757. {
  2758. switch (Animator.CurrentMovementAnimation)
  2759. {
  2760. case "STAND":
  2761. case "WALK":
  2762. case "RUN":
  2763. case "CROUCH":
  2764. case "CROUCHWALK":
  2765. {
  2766. ContactPoint lowest;
  2767. lowest.SurfaceNormal = Vector3.Zero;
  2768. lowest.Position = Vector3.Zero;
  2769. lowest.Position.Z = Single.NaN;
  2770. foreach (ContactPoint contact in coldata.Values)
  2771. {
  2772. if (Single.IsNaN(lowest.Position.Z) || contact.Position.Z < lowest.Position.Z)
  2773. {
  2774. lowest = contact;
  2775. }
  2776. }
  2777. CollisionPlane = new Vector4(-lowest.SurfaceNormal, -Vector3.Dot(lowest.Position, lowest.SurfaceNormal));
  2778. }
  2779. break;
  2780. }
  2781. }
  2782. if (m_invulnerable)
  2783. return;
  2784. float starthealth = Health;
  2785. uint killerObj = 0;
  2786. foreach (uint localid in coldata.Keys)
  2787. {
  2788. SceneObjectPart part = Scene.GetSceneObjectPart(localid);
  2789. if (part != null && part.ParentGroup.Damage != -1.0f)
  2790. Health -= part.ParentGroup.Damage;
  2791. else
  2792. {
  2793. if (coldata[localid].PenetrationDepth >= 0.10f)
  2794. Health -= coldata[localid].PenetrationDepth * 5.0f;
  2795. }
  2796. if (Health <= 0.0f)
  2797. {
  2798. if (localid != 0)
  2799. killerObj = localid;
  2800. }
  2801. //m_log.Debug("[AVATAR]: Collision with localid: " + localid.ToString() + " at depth: " + coldata[localid].ToString());
  2802. }
  2803. //Health = 100;
  2804. if (!m_invulnerable)
  2805. {
  2806. if (starthealth != Health)
  2807. {
  2808. ControllingClient.SendHealth(Health);
  2809. }
  2810. if (m_health <= 0)
  2811. m_scene.EventManager.TriggerAvatarKill(killerObj, this);
  2812. }
  2813. }
  2814. public void setHealthWithUpdate(float health)
  2815. {
  2816. Health = health;
  2817. ControllingClient.SendHealth(Health);
  2818. }
  2819. public void Close()
  2820. {
  2821. lock (m_attachments)
  2822. {
  2823. // Delete attachments from scene
  2824. // Don't try to save, as this thread won't live long
  2825. // enough to complete the save. This would cause no copy
  2826. // attachments to poof!
  2827. //
  2828. foreach (SceneObjectGroup grp in m_attachments)
  2829. {
  2830. m_scene.DeleteSceneObject(grp, false);
  2831. }
  2832. m_attachments.Clear();
  2833. }
  2834. lock (m_knownChildRegions)
  2835. {
  2836. m_knownChildRegions.Clear();
  2837. }
  2838. lock (m_reprioritization_timer)
  2839. {
  2840. m_reprioritization_timer.Enabled = false;
  2841. m_reprioritization_timer.Elapsed -= new ElapsedEventHandler(Reprioritize);
  2842. }
  2843. // I don't get it but mono crashes when you try to dispose of this timer,
  2844. // unsetting the elapsed callback should be enough to allow for cleanup however.
  2845. // m_reprioritizationTimer.Dispose();
  2846. m_sceneViewer.Close();
  2847. RemoveFromPhysicalScene();
  2848. m_animator.Close();
  2849. m_animator = null;
  2850. }
  2851. public void AddAttachment(SceneObjectGroup gobj)
  2852. {
  2853. lock (m_attachments)
  2854. {
  2855. m_attachments.Add(gobj);
  2856. }
  2857. }
  2858. /// <summary>
  2859. /// Get the scene object attached to the given point.
  2860. /// </summary>
  2861. /// <param name="attachmentPoint"></param>
  2862. /// <returns>Returns an empty list if there were no attachments at the point.</returns>
  2863. public List<SceneObjectGroup> GetAttachments(uint attachmentPoint)
  2864. {
  2865. List<SceneObjectGroup> attachments = new List<SceneObjectGroup>();
  2866. lock (m_attachments)
  2867. {
  2868. foreach (SceneObjectGroup so in m_attachments)
  2869. {
  2870. if (attachmentPoint == so.RootPart.AttachmentPoint)
  2871. attachments.Add(so);
  2872. }
  2873. }
  2874. return attachments;
  2875. }
  2876. public bool HasAttachments()
  2877. {
  2878. return m_attachments.Count > 0;
  2879. }
  2880. public bool HasScriptedAttachments()
  2881. {
  2882. lock (m_attachments)
  2883. {
  2884. foreach (SceneObjectGroup gobj in m_attachments)
  2885. {
  2886. if (gobj != null)
  2887. {
  2888. if (gobj.RootPart.Inventory.ContainsScripts())
  2889. return true;
  2890. }
  2891. }
  2892. }
  2893. return false;
  2894. }
  2895. public void RemoveAttachment(SceneObjectGroup gobj)
  2896. {
  2897. lock (m_attachments)
  2898. {
  2899. if (m_attachments.Contains(gobj))
  2900. {
  2901. m_attachments.Remove(gobj);
  2902. }
  2903. }
  2904. }
  2905. public bool ValidateAttachments()
  2906. {
  2907. lock (m_attachments)
  2908. {
  2909. // Validate
  2910. foreach (SceneObjectGroup gobj in m_attachments)
  2911. {
  2912. if (gobj == null)
  2913. return false;
  2914. if (gobj.IsDeleted)
  2915. return false;
  2916. }
  2917. }
  2918. return true;
  2919. }
  2920. /// <summary>
  2921. /// Send a script event to this scene presence's attachments
  2922. /// </summary>
  2923. /// <param name="eventName">The name of the event</param>
  2924. /// <param name="args">The arguments for the event</param>
  2925. public void SendScriptEventToAttachments(string eventName, Object[] args)
  2926. {
  2927. if (m_scriptEngines != null)
  2928. {
  2929. lock (m_attachments)
  2930. {
  2931. foreach (SceneObjectGroup grp in m_attachments)
  2932. {
  2933. // 16384 is CHANGED_ANIMATION
  2934. //
  2935. // Send this to all attachment root prims
  2936. //
  2937. foreach (IScriptModule m in m_scriptEngines)
  2938. {
  2939. if (m == null) // No script engine loaded
  2940. continue;
  2941. m.PostObjectEvent(grp.RootPart.UUID, "changed", new Object[] { (int)Changed.ANIMATION });
  2942. }
  2943. }
  2944. }
  2945. }
  2946. }
  2947. public void initializeScenePresence(IClientAPI client, RegionInfo region, Scene scene)
  2948. {
  2949. m_controllingClient = client;
  2950. m_regionInfo = region;
  2951. m_scene = scene;
  2952. RegisterToEvents();
  2953. /*
  2954. AbsolutePosition = client.StartPos;
  2955. Animations = new AvatarAnimations();
  2956. Animations.LoadAnims();
  2957. m_animations = new List<UUID>();
  2958. m_animations.Add(Animations.AnimsUUID["STAND"]);
  2959. m_animationSeqs.Add(m_controllingClient.NextAnimationSequenceNumber);
  2960. SetDirectionVectors();
  2961. */
  2962. }
  2963. internal void PushForce(Vector3 impulse)
  2964. {
  2965. if (PhysicsActor != null)
  2966. {
  2967. PhysicsActor.AddForce(impulse,true);
  2968. }
  2969. }
  2970. public void RegisterControlEventsToScript(int controls, int accept, int pass_on, uint Obj_localID, UUID Script_item_UUID)
  2971. {
  2972. ScriptControllers obj = new ScriptControllers();
  2973. obj.ignoreControls = ScriptControlled.CONTROL_ZERO;
  2974. obj.eventControls = ScriptControlled.CONTROL_ZERO;
  2975. obj.itemID = Script_item_UUID;
  2976. if (pass_on == 0 && accept == 0)
  2977. {
  2978. IgnoredControls |= (ScriptControlled)controls;
  2979. obj.ignoreControls = (ScriptControlled)controls;
  2980. }
  2981. if (pass_on == 0 && accept == 1)
  2982. {
  2983. IgnoredControls |= (ScriptControlled)controls;
  2984. obj.ignoreControls = (ScriptControlled)controls;
  2985. obj.eventControls = (ScriptControlled)controls;
  2986. }
  2987. if (pass_on == 1 && accept == 1)
  2988. {
  2989. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  2990. obj.eventControls = (ScriptControlled)controls;
  2991. obj.ignoreControls = ScriptControlled.CONTROL_ZERO;
  2992. }
  2993. lock (scriptedcontrols)
  2994. {
  2995. if (pass_on == 1 && accept == 0)
  2996. {
  2997. IgnoredControls &= ~(ScriptControlled)controls;
  2998. if (scriptedcontrols.ContainsKey(Script_item_UUID))
  2999. scriptedcontrols.Remove(Script_item_UUID);
  3000. }
  3001. else
  3002. {
  3003. scriptedcontrols[Script_item_UUID] = obj;
  3004. }
  3005. }
  3006. ControllingClient.SendTakeControls(controls, pass_on == 1 ? true : false, true);
  3007. }
  3008. public void HandleForceReleaseControls(IClientAPI remoteClient, UUID agentID)
  3009. {
  3010. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  3011. lock (scriptedcontrols)
  3012. {
  3013. scriptedcontrols.Clear();
  3014. }
  3015. ControllingClient.SendTakeControls(int.MaxValue, false, false);
  3016. }
  3017. public void UnRegisterControlEventsToScript(uint Obj_localID, UUID Script_item_UUID)
  3018. {
  3019. ScriptControllers takecontrols;
  3020. lock (scriptedcontrols)
  3021. {
  3022. if (scriptedcontrols.TryGetValue(Script_item_UUID, out takecontrols))
  3023. {
  3024. ScriptControlled sctc = takecontrols.eventControls;
  3025. ControllingClient.SendTakeControls((int)sctc, false, false);
  3026. ControllingClient.SendTakeControls((int)sctc, true, false);
  3027. scriptedcontrols.Remove(Script_item_UUID);
  3028. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  3029. foreach (ScriptControllers scData in scriptedcontrols.Values)
  3030. {
  3031. IgnoredControls |= scData.ignoreControls;
  3032. }
  3033. }
  3034. }
  3035. }
  3036. internal void SendControlToScripts(uint flags)
  3037. {
  3038. ScriptControlled allflags = ScriptControlled.CONTROL_ZERO;
  3039. if (MouseDown)
  3040. {
  3041. allflags = LastCommands & (ScriptControlled.CONTROL_ML_LBUTTON | ScriptControlled.CONTROL_LBUTTON);
  3042. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_UP) != 0 || (flags & unchecked((uint)AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_UP)) != 0)
  3043. {
  3044. allflags = ScriptControlled.CONTROL_ZERO;
  3045. MouseDown = true;
  3046. }
  3047. }
  3048. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_DOWN) != 0)
  3049. {
  3050. allflags |= ScriptControlled.CONTROL_ML_LBUTTON;
  3051. MouseDown = true;
  3052. }
  3053. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN) != 0)
  3054. {
  3055. allflags |= ScriptControlled.CONTROL_LBUTTON;
  3056. MouseDown = true;
  3057. }
  3058. // find all activated controls, whether the scripts are interested in them or not
  3059. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_AT_POS) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS) != 0)
  3060. {
  3061. allflags |= ScriptControlled.CONTROL_FWD;
  3062. }
  3063. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_NEG) != 0)
  3064. {
  3065. allflags |= ScriptControlled.CONTROL_BACK;
  3066. }
  3067. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_POS) != 0)
  3068. {
  3069. allflags |= ScriptControlled.CONTROL_UP;
  3070. }
  3071. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG) != 0)
  3072. {
  3073. allflags |= ScriptControlled.CONTROL_DOWN;
  3074. }
  3075. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_POS) != 0)
  3076. {
  3077. allflags |= ScriptControlled.CONTROL_LEFT;
  3078. }
  3079. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_NEG) != 0)
  3080. {
  3081. allflags |= ScriptControlled.CONTROL_RIGHT;
  3082. }
  3083. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG) != 0)
  3084. {
  3085. allflags |= ScriptControlled.CONTROL_ROT_RIGHT;
  3086. }
  3087. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS) != 0)
  3088. {
  3089. allflags |= ScriptControlled.CONTROL_ROT_LEFT;
  3090. }
  3091. // optimization; we have to check per script, but if nothing is pressed and nothing changed, we can skip that
  3092. if (allflags != ScriptControlled.CONTROL_ZERO || allflags != LastCommands)
  3093. {
  3094. lock (scriptedcontrols)
  3095. {
  3096. foreach (KeyValuePair<UUID, ScriptControllers> kvp in scriptedcontrols)
  3097. {
  3098. UUID scriptUUID = kvp.Key;
  3099. ScriptControllers scriptControlData = kvp.Value;
  3100. ScriptControlled localHeld = allflags & scriptControlData.eventControls; // the flags interesting for us
  3101. ScriptControlled localLast = LastCommands & scriptControlData.eventControls; // the activated controls in the last cycle
  3102. ScriptControlled localChange = localHeld ^ localLast; // the changed bits
  3103. if (localHeld != ScriptControlled.CONTROL_ZERO || localChange != ScriptControlled.CONTROL_ZERO)
  3104. {
  3105. // only send if still pressed or just changed
  3106. m_scene.EventManager.TriggerControlEvent(scriptUUID, UUID, (uint)localHeld, (uint)localChange);
  3107. }
  3108. }
  3109. }
  3110. }
  3111. LastCommands = allflags;
  3112. }
  3113. internal static AgentManager.ControlFlags RemoveIgnoredControls(AgentManager.ControlFlags flags, ScriptControlled ignored)
  3114. {
  3115. if (ignored == ScriptControlled.CONTROL_ZERO)
  3116. return flags;
  3117. if ((ignored & ScriptControlled.CONTROL_BACK) != 0)
  3118. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG | AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_NEG);
  3119. if ((ignored & ScriptControlled.CONTROL_FWD) != 0)
  3120. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS | AgentManager.ControlFlags.AGENT_CONTROL_AT_POS);
  3121. if ((ignored & ScriptControlled.CONTROL_DOWN) != 0)
  3122. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG | AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG);
  3123. if ((ignored & ScriptControlled.CONTROL_UP) != 0)
  3124. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_POS | AgentManager.ControlFlags.AGENT_CONTROL_UP_POS);
  3125. if ((ignored & ScriptControlled.CONTROL_LEFT) != 0)
  3126. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS | AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_POS);
  3127. if ((ignored & ScriptControlled.CONTROL_RIGHT) != 0)
  3128. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_NEG | AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG);
  3129. if ((ignored & ScriptControlled.CONTROL_ROT_LEFT) != 0)
  3130. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG);
  3131. if ((ignored & ScriptControlled.CONTROL_ROT_RIGHT) != 0)
  3132. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS);
  3133. if ((ignored & ScriptControlled.CONTROL_ML_LBUTTON) != 0)
  3134. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_DOWN);
  3135. if ((ignored & ScriptControlled.CONTROL_LBUTTON) != 0)
  3136. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_UP | AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN);
  3137. //DIR_CONTROL_FLAG_FORWARD = AgentManager.ControlFlags.AGENT_CONTROL_AT_POS,
  3138. //DIR_CONTROL_FLAG_BACK = AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG,
  3139. //DIR_CONTROL_FLAG_LEFT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS,
  3140. //DIR_CONTROL_FLAG_RIGHT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG,
  3141. //DIR_CONTROL_FLAG_UP = AgentManager.ControlFlags.AGENT_CONTROL_UP_POS,
  3142. //DIR_CONTROL_FLAG_DOWN = AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG,
  3143. //DIR_CONTROL_FLAG_DOWN_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG
  3144. return flags;
  3145. }
  3146. /// <summary>
  3147. /// RezAttachments. This should only be called upon login on the first region.
  3148. /// Attachment rezzings on crossings and TPs are done in a different way.
  3149. /// </summary>
  3150. public void RezAttachments()
  3151. {
  3152. if (null == m_appearance)
  3153. {
  3154. m_log.WarnFormat("[ATTACHMENT]: Appearance has not been initialized for agent {0}", UUID);
  3155. return;
  3156. }
  3157. List<AvatarAttachment> attachments = m_appearance.GetAttachments();
  3158. foreach (AvatarAttachment attach in attachments)
  3159. {
  3160. if (m_isDeleted)
  3161. return;
  3162. int p = attach.AttachPoint;
  3163. UUID itemID = attach.ItemID;
  3164. //UUID assetID = attach.AssetID;
  3165. // For some reason assetIDs are being written as Zero's in the DB -- need to track tat down
  3166. // But they're not used anyway, the item is being looked up for now, so let's proceed.
  3167. //if (UUID.Zero == assetID)
  3168. //{
  3169. // m_log.DebugFormat("[ATTACHMENT]: Cannot rez attachment in point {0} with itemID {1}", p, itemID);
  3170. // continue;
  3171. //}
  3172. try
  3173. {
  3174. m_scene.AttachmentsModule.RezSingleAttachmentFromInventory(ControllingClient, itemID, (uint)p);
  3175. }
  3176. catch (Exception e)
  3177. {
  3178. m_log.ErrorFormat("[ATTACHMENT]: Unable to rez attachment: {0}{1}", e.Message, e.StackTrace);
  3179. }
  3180. }
  3181. }
  3182. private void ReprioritizeUpdates()
  3183. {
  3184. if (Scene.IsReprioritizationEnabled && Scene.UpdatePrioritizationScheme != UpdatePrioritizationSchemes.Time)
  3185. {
  3186. lock (m_reprioritization_timer)
  3187. {
  3188. if (!m_reprioritizing)
  3189. m_reprioritization_timer.Enabled = m_reprioritizing = true;
  3190. else
  3191. m_reprioritization_called = true;
  3192. }
  3193. }
  3194. }
  3195. private void Reprioritize(object sender, ElapsedEventArgs e)
  3196. {
  3197. m_controllingClient.ReprioritizeUpdates();
  3198. lock (m_reprioritization_timer)
  3199. {
  3200. m_reprioritization_timer.Enabled = m_reprioritizing = m_reprioritization_called;
  3201. m_reprioritization_called = false;
  3202. }
  3203. }
  3204. }
  3205. }