1
0

ScenePresence.cs 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSim Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. *
  27. */
  28. using System;
  29. using System.Collections.Generic;
  30. using Axiom.Math;
  31. using libsecondlife;
  32. using libsecondlife.Packets;
  33. using OpenSim.Framework;
  34. using OpenSim.Framework.Console;
  35. using OpenSim.Region.Environment.Types;
  36. using OpenSim.Region.Physics.Manager;
  37. namespace OpenSim.Region.Environment.Scenes
  38. {
  39. public class ScenePresence : EntityBase
  40. {
  41. // ~ScenePresence()
  42. // {
  43. // System.Console.WriteLine("[ScenePresence] Destructor called");
  44. // }
  45. private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  46. public static AvatarAnimations Animations = new AvatarAnimations();
  47. public static byte[] DefaultTexture;
  48. public LLUUID currentParcelUUID = LLUUID.Zero;
  49. private List<LLUUID> m_animations = new List<LLUUID>();
  50. private List<int> m_animationSeqs = new List<int>();
  51. public Vector3 lastKnownAllowedPosition = new Vector3();
  52. public bool sentMessageAboutRestrictedParcelFlyingDown = false;
  53. private bool m_updateflag = false;
  54. private byte m_movementflag = 0;
  55. private readonly List<NewForce> m_forcesList = new List<NewForce>();
  56. private short m_updateCount = 0;
  57. private uint m_requestedSitTargetID = 0;
  58. private LLVector3 m_requestedSitOffset = new LLVector3();
  59. private float m_sitAvatarHeight = 2.0f;
  60. private float m_godlevel = 0;
  61. private LLVector3 m_LastChildAgentUpdatePosition = new LLVector3();
  62. private int m_perfMonMS = 0;
  63. private bool m_setAlwaysRun = false;
  64. private Quaternion m_bodyRot;
  65. public bool IsRestrictedToRegion = false;
  66. // Agent moves with a PID controller causing a force to be exerted.
  67. private bool m_newForce = false;
  68. private bool m_newCoarseLocations = true;
  69. private bool m_gotAllObjectsInScene = false;
  70. private bool m_lastPhysicsStoppedStatus = false;
  71. private LLVector3 m_lastVelocity = LLVector3.Zero;
  72. // Default AV Height
  73. private float m_avHeight = 127.0f;
  74. protected RegionInfo m_regionInfo;
  75. protected ulong crossingFromRegion = 0;
  76. private readonly Vector3[] Dir_Vectors = new Vector3[6];
  77. private LLVector3 lastPhysPos = new LLVector3();
  78. // Position of agent's camera in world (region cordinates)
  79. protected Vector3 m_CameraCenter = new Vector3(0, 0, 0);
  80. // Use these three vectors to figure out what the agent is looking at
  81. // Convert it to a Matrix and/or Quaternion
  82. protected Vector3 m_CameraAtAxis = new Vector3(0, 0, 0);
  83. protected Vector3 m_CameraLeftAxis = new Vector3(0, 0, 0);
  84. protected Vector3 m_CameraUpAxis = new Vector3(0, 0, 0);
  85. private uint m_AgentControlFlags = (uint) 0;
  86. private LLQuaternion m_headrotation = new LLQuaternion();
  87. private byte m_state = (byte) 0;
  88. //Reuse the LLVector3 instead of creating a new one on the UpdateMovement method
  89. private LLVector3 movementvector = new LLVector3();
  90. private List<LLUUID> m_knownPrimUUID = new List<LLUUID>();
  91. // Agent's Draw distance.
  92. protected float m_DrawDistance = 0f;
  93. protected AvatarAppearance m_appearance;
  94. private readonly List<ulong> m_knownChildRegions = new List<ulong>();
  95. //neighbouring regions we have enabled a child agent in
  96. /// <summary>
  97. /// Implemented Control Flags
  98. /// </summary>
  99. private enum Dir_ControlFlags
  100. {
  101. DIR_CONTROL_FLAG_FORWARD = AgentManager.ControlFlags.AGENT_CONTROL_AT_POS,
  102. DIR_CONTROL_FLAG_BACK = AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG,
  103. DIR_CONTROL_FLAG_LEFT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS,
  104. DIR_CONTROL_FLAG_RIGHT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG,
  105. DIR_CONTROL_FLAG_UP = AgentManager.ControlFlags.AGENT_CONTROL_UP_POS,
  106. DIR_CONTROL_FLAG_DOWN = AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG,
  107. DIR_CONTROL_FLAG_DOWN_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG
  108. }
  109. /// <summary>
  110. /// Position at which a significant movement was made
  111. /// </summary>
  112. private LLVector3 posLastSignificantMove = new LLVector3();
  113. public delegate void SignificantClientMovement(IClientAPI remote_client);
  114. public event SignificantClientMovement OnSignificantClientMovement;
  115. private UpdateQueue m_partsUpdateQueue = new UpdateQueue();
  116. private Dictionary<LLUUID, ScenePartUpdate> m_updateTimes = new Dictionary<LLUUID, ScenePartUpdate>();
  117. #region Properties
  118. /// <summary>
  119. /// Physical scene representation of this Avatar.
  120. /// </summary>
  121. public PhysicsActor PhysicsActor
  122. {
  123. set { m_physicsActor = value; }
  124. get { return m_physicsActor; }
  125. }
  126. public bool KnownPrim(LLUUID primID)
  127. {
  128. if (m_knownPrimUUID.Contains(primID))
  129. {
  130. return true;
  131. }
  132. m_knownPrimUUID.Add(primID);
  133. return false;
  134. }
  135. public bool Updated
  136. {
  137. set { m_updateflag = value; }
  138. get { return m_updateflag; }
  139. }
  140. private readonly ulong m_regionHandle;
  141. public ulong RegionHandle
  142. {
  143. get { return m_regionHandle; }
  144. }
  145. public Vector3 CameraPosition
  146. {
  147. get { return m_CameraCenter; }
  148. }
  149. private readonly string m_firstname;
  150. public string Firstname
  151. {
  152. get { return m_firstname; }
  153. }
  154. private readonly string m_lastname;
  155. public string Lastname
  156. {
  157. get { return m_lastname; }
  158. }
  159. public float DrawDistance
  160. {
  161. get { return m_DrawDistance; }
  162. }
  163. protected bool m_allowMovement = true;
  164. public bool AllowMovement
  165. {
  166. get { return m_allowMovement; }
  167. set { m_allowMovement = value; }
  168. }
  169. /// <summary>
  170. /// This works out to be the ClientView object associated with this avatar, or it's UDP connection manager
  171. /// </summary>
  172. private readonly IClientAPI m_controllingClient;
  173. protected PhysicsActor m_physicsActor;
  174. public IClientAPI ControllingClient
  175. {
  176. get { return m_controllingClient; }
  177. }
  178. protected LLVector3 m_parentPosition = new LLVector3();
  179. /// <summary>
  180. /// Absolute position of this avatar in 'region cordinates'
  181. /// </summary>
  182. public override LLVector3 AbsolutePosition
  183. {
  184. get
  185. {
  186. if (m_physicsActor != null)
  187. {
  188. m_pos.X = m_physicsActor.Position.X;
  189. m_pos.Y = m_physicsActor.Position.Y;
  190. m_pos.Z = m_physicsActor.Position.Z;
  191. }
  192. return m_parentPosition + m_pos;
  193. }
  194. set
  195. {
  196. if (m_physicsActor != null)
  197. {
  198. try
  199. {
  200. lock (m_scene.SyncRoot)
  201. {
  202. m_physicsActor.Position = new PhysicsVector(value.X, value.Y, value.Z);
  203. }
  204. }
  205. catch (Exception e)
  206. {
  207. Console.WriteLine(e.Message);
  208. }
  209. }
  210. m_pos = value;
  211. }
  212. }
  213. /// <summary>
  214. /// Current Velocity of the avatar.
  215. /// </summary>
  216. public override LLVector3 Velocity
  217. {
  218. get
  219. {
  220. if (m_physicsActor != null)
  221. {
  222. m_velocity.X = m_physicsActor.Velocity.X;
  223. m_velocity.Y = m_physicsActor.Velocity.Y;
  224. m_velocity.Z = m_physicsActor.Velocity.Z;
  225. }
  226. return m_velocity;
  227. }
  228. set
  229. {
  230. if (m_physicsActor != null)
  231. {
  232. try
  233. {
  234. lock (m_scene.SyncRoot)
  235. {
  236. m_physicsActor.Velocity = new PhysicsVector(value.X, value.Y, value.Z);
  237. }
  238. }
  239. catch (Exception e)
  240. {
  241. Console.WriteLine(e.Message);
  242. }
  243. }
  244. m_velocity = value;
  245. }
  246. }
  247. /// <summary>
  248. /// If this is true, agent doesn't have a representation in this scene.
  249. /// this is an agent 'looking into' this scene from a nearby scene(region)
  250. ///
  251. /// if False, this agent has a representation in this scene
  252. /// </summary>
  253. private bool m_isChildAgent = true;
  254. public bool IsChildAgent
  255. {
  256. get { return m_isChildAgent; }
  257. set { m_isChildAgent = value; }
  258. }
  259. private uint m_parentID = 0;
  260. public uint ParentID
  261. {
  262. get { return m_parentID; }
  263. set { m_parentID = value; }
  264. }
  265. /// <summary>
  266. /// These are the region handles known by the avatar.
  267. /// </summary>
  268. public List<ulong> KnownChildRegions
  269. {
  270. get { return m_knownChildRegions; }
  271. }
  272. #endregion
  273. #region Constructor(s)
  274. private ScenePresence(IClientAPI client, Scene world, RegionInfo reginfo)
  275. {
  276. m_regionHandle = reginfo.RegionHandle;
  277. m_controllingClient = client;
  278. m_firstname = m_controllingClient.FirstName;
  279. m_lastname = m_controllingClient.LastName;
  280. m_scene = world;
  281. m_uuid = client.AgentId;
  282. m_regionInfo = reginfo;
  283. m_localId = m_scene.NextLocalId;
  284. AbsolutePosition = m_controllingClient.StartPos;
  285. // TODO: m_animations and m_animationSeqs should always be of the same length.
  286. // Move them into an object to (hopefully) avoid threading issues.
  287. try
  288. {
  289. m_animations.Add(Animations.AnimsLLUUID["STAND"]);
  290. }
  291. catch (KeyNotFoundException)
  292. {
  293. m_log.Warn("[AVATAR]: KeyNotFound Exception playing avatar stand animation");
  294. }
  295. m_animationSeqs.Add(1);
  296. RegisterToEvents();
  297. SetDirectionVectors();
  298. m_scene.LandManager.sendLandUpdate(this, true);
  299. }
  300. public ScenePresence(IClientAPI client, Scene world, RegionInfo reginfo, byte[] visualParams,
  301. AvatarWearable[] wearables)
  302. : this(client, world, reginfo)
  303. {
  304. m_appearance = new AvatarAppearance(m_uuid, wearables, visualParams);
  305. }
  306. public ScenePresence(IClientAPI client, Scene world, RegionInfo reginfo, AvatarAppearance appearance)
  307. : this(client, world, reginfo)
  308. {
  309. m_appearance = appearance;
  310. }
  311. private void RegisterToEvents()
  312. {
  313. m_controllingClient.OnRequestWearables += SendOwnAppearance;
  314. m_controllingClient.OnSetAppearance += SetAppearance;
  315. m_controllingClient.OnCompleteMovementToRegion += CompleteMovement;
  316. m_controllingClient.OnCompleteMovementToRegion += SendInitialData;
  317. m_controllingClient.OnAgentUpdate += HandleAgentUpdate;
  318. m_controllingClient.OnAgentRequestSit += HandleAgentRequestSit;
  319. m_controllingClient.OnAgentSit += HandleAgentSit;
  320. m_controllingClient.OnSetAlwaysRun += HandleSetAlwaysRun;
  321. m_controllingClient.OnStartAnim += HandleStartAnim;
  322. m_controllingClient.OnStopAnim += HandleStopAnim;
  323. // ControllingClient.OnChildAgentStatus += new StatusChange(this.ChildStatusChange);
  324. // ControllingClient.OnStopMovement += new GenericCall2(this.StopMovement);
  325. }
  326. private void SetDirectionVectors()
  327. {
  328. Dir_Vectors[0] = new Vector3(1, 0, 0); //FORWARD
  329. Dir_Vectors[1] = new Vector3(-1, 0, 0); //BACK
  330. Dir_Vectors[2] = new Vector3(0, 1, 0); //LEFT
  331. Dir_Vectors[3] = new Vector3(0, -1, 0); //RIGHT
  332. Dir_Vectors[4] = new Vector3(0, 0, 1); //UP
  333. Dir_Vectors[5] = new Vector3(0, 0, -1); //DOWN
  334. Dir_Vectors[5] = new Vector3(0, 0, -0.5f); //DOWN_Nudge
  335. }
  336. #endregion
  337. public void QueuePartForUpdate(SceneObjectPart part)
  338. {
  339. //if (InterestList.Contains(part.ParentGroup))
  340. //{
  341. lock (m_partsUpdateQueue)
  342. {
  343. m_partsUpdateQueue.Enqueue(part);
  344. }
  345. // }
  346. }
  347. public uint GenerateClientFlags(LLUUID ObjectID)
  348. {
  349. return m_scene.PermissionsMngr.GenerateClientFlags(m_uuid, ObjectID);
  350. }
  351. public void SendPrimUpdates()
  352. {
  353. // if (m_scene.QuadTree.GetNodeID(this.AbsolutePosition.X, this.AbsolutePosition.Y) != m_currentQuadNode)
  354. //{
  355. // this.UpdateQuadTreeNode();
  356. //this.RefreshQuadObject();
  357. //}
  358. m_perfMonMS = System.Environment.TickCount;
  359. if (!m_gotAllObjectsInScene)
  360. {
  361. if (!m_isChildAgent || m_scene.m_seeIntoRegionFromNeighbor)
  362. {
  363. m_scene.SendAllSceneObjectsToClient(this);
  364. m_gotAllObjectsInScene = true;
  365. }
  366. }
  367. if (m_partsUpdateQueue.Count > 0)
  368. {
  369. bool runUpdate = true;
  370. int updateCount = 0;
  371. while (runUpdate)
  372. {
  373. SceneObjectPart part = m_partsUpdateQueue.Dequeue();
  374. if (m_updateTimes.ContainsKey(part.UUID))
  375. {
  376. ScenePartUpdate update = m_updateTimes[part.UUID];
  377. // Two updates can occur with the same timestamp (especially
  378. // since our timestamp resolution is to the nearest second). The first
  379. // could have been sent in the last update - we still need to send the
  380. // second here.
  381. if (update.LastFullUpdateTime < part.TimeStampFull)
  382. {
  383. //need to do a full update
  384. part.SendFullUpdate(ControllingClient, GenerateClientFlags(part.UUID));
  385. // We'll update to the part's timestamp rather than the current to
  386. // avoid the race condition whereby the next tick occurs while we are
  387. // doing this update. If this happened, then subsequent updates which occurred
  388. // on the same tick or the next tick of the last update would be ignored.
  389. update.LastFullUpdateTime = part.TimeStampFull;
  390. updateCount++;
  391. }
  392. else if (update.LastTerseUpdateTime <= part.TimeStampTerse)
  393. {
  394. part.SendTerseUpdate(ControllingClient);
  395. update.LastTerseUpdateTime = part.TimeStampTerse;
  396. updateCount++;
  397. }
  398. }
  399. else
  400. {
  401. //never been sent to client before so do full update
  402. part.SendFullUpdate(ControllingClient, GenerateClientFlags(part.UUID));
  403. ScenePartUpdate update = new ScenePartUpdate();
  404. update.FullID = part.UUID;
  405. update.LastFullUpdateTime = part.TimeStampFull;
  406. m_updateTimes.Add(part.UUID, update);
  407. updateCount++;
  408. }
  409. if (m_partsUpdateQueue.Count < 1 || updateCount > 60)
  410. {
  411. runUpdate = false;
  412. }
  413. }
  414. }
  415. m_scene.AddAgentTime(System.Environment.TickCount - m_perfMonMS);
  416. }
  417. public void forceAvatarMovement(Vector3 position, Quaternion rotation)
  418. {
  419. AddNewMovement(position, rotation);
  420. }
  421. #region Status Methods
  422. /// <summary>
  423. /// This turns a child agent, into a root agent
  424. /// This is called when an agent teleports into a region, or if an
  425. /// agent crosses into this region from a neighbor over the border
  426. /// </summary>
  427. public void MakeRootAgent(LLVector3 pos, bool isFlying)
  428. {
  429. m_isChildAgent = false;
  430. AbsolutePosition = pos;
  431. AddToPhysicalScene();
  432. m_physicsActor.Flying = isFlying;
  433. m_scene.SwapRootAgentCount(false);
  434. m_scene.CommsManager.UserProfileCacheService.UpdateUserInventory(m_uuid);
  435. //if (!m_gotAllObjectsInScene)
  436. //{
  437. m_scene.SendAllSceneObjectsToClient(this);
  438. m_scene.LandManager.sendLandUpdate(this, true);
  439. //m_gotAllObjectsInScene = true;
  440. //}
  441. }
  442. /// <summary>
  443. /// This turns a root agent into a child agent
  444. /// when an agent departs this region for a neighbor, this gets called.
  445. ///
  446. /// It doesn't get called for a teleport. Reason being, an agent that
  447. /// teleports out may not be anywhere near this region
  448. /// </summary>
  449. public void MakeChildAgent()
  450. {
  451. Velocity = new LLVector3(0, 0, 0);
  452. m_isChildAgent = true;
  453. m_scene.SwapRootAgentCount(true);
  454. RemoveFromPhysicalScene();
  455. //this.Pos = new LLVector3(128, 128, 70);
  456. }
  457. /// <summary>
  458. /// Removes physics plugin scene representation of this agent if it exists.
  459. /// </summary>
  460. private void RemoveFromPhysicalScene()
  461. {
  462. if (PhysicsActor != null)
  463. {
  464. m_scene.PhysicsScene.RemoveAvatar(PhysicsActor);
  465. m_physicsActor.OnRequestTerseUpdate -= SendTerseUpdateToAllClients;
  466. m_physicsActor.OnCollisionUpdate -= PhysicsCollisionUpdate;
  467. PhysicsActor = null;
  468. }
  469. }
  470. /// <summary>
  471. ///
  472. /// </summary>
  473. /// <param name="pos"></param>
  474. public void Teleport(LLVector3 pos)
  475. {
  476. AbsolutePosition = pos;
  477. SendTerseUpdateToAllClients();
  478. }
  479. /// <summary>
  480. ///
  481. /// </summary>
  482. public void StopMovement()
  483. {
  484. }
  485. public void StopFlying()
  486. {
  487. // It turns out to get the agent to stop flying, you have to feed it stop flying velocities
  488. // and send a full object update.
  489. // There's no message to send the client to tell it to stop flying
  490. // Add 1/6 the avatar's height to it's position so it doesn't shoot into the air
  491. // when the avatar stands up
  492. if (m_avHeight != 127.0f)
  493. {
  494. AbsolutePosition = AbsolutePosition + new LLVector3(0, 0, (m_avHeight / 6));
  495. }
  496. else
  497. {
  498. AbsolutePosition = AbsolutePosition + new LLVector3(0, 0, (1.56f / 6));
  499. }
  500. SetMovementAnimation(Animations.AnimsLLUUID["LAND"], 2);
  501. SendFullUpdateToAllClients();
  502. }
  503. public void AddNeighbourRegion(ulong regionHandle)
  504. {
  505. if (!m_knownChildRegions.Contains(regionHandle))
  506. {
  507. m_knownChildRegions.Add(regionHandle);
  508. }
  509. }
  510. public void RemoveNeighbourRegion(ulong regionHandle)
  511. {
  512. if (!m_knownChildRegions.Contains(regionHandle))
  513. {
  514. m_knownChildRegions.Remove(regionHandle);
  515. }
  516. }
  517. #endregion
  518. #region Event Handlers
  519. /// <summary>
  520. /// Sets avatar height in the phyiscs plugin
  521. /// </summary>
  522. internal void SetHeight(float height)
  523. {
  524. m_avHeight = height;
  525. if (PhysicsActor != null)
  526. {
  527. PhysicsVector SetSize = new PhysicsVector(0.45f, 0.6f, m_avHeight);
  528. PhysicsActor.Size = SetSize;
  529. }
  530. }
  531. /// <summary>
  532. /// Complete Avatar's movement into the region
  533. /// </summary>
  534. public void CompleteMovement()
  535. {
  536. LLVector3 look = Velocity;
  537. if ((look.X == 0) && (look.Y == 0) && (look.Z == 0))
  538. {
  539. look = new LLVector3(0.99f, 0.042f, 0);
  540. }
  541. m_controllingClient.MoveAgentIntoRegion(m_regionInfo, AbsolutePosition, look);
  542. if (m_isChildAgent)
  543. {
  544. m_isChildAgent = false;
  545. //this.m_scene.SendAllSceneObjectsToClient(this.ControllingClient);
  546. MakeRootAgent(AbsolutePosition, false);
  547. }
  548. }
  549. /// <summary>
  550. /// This is the event handler for client movement. If a client is moving, this event is triggering.
  551. /// </summary>
  552. public void HandleAgentUpdate(IClientAPI remoteClient, AgentUpdatePacket agentData)
  553. {
  554. //if (m_isChildAgent)
  555. //{
  556. // // Console.WriteLine("DEBUG: HandleAgentUpdate: child agent");
  557. // return;
  558. //}
  559. // Must check for standing up even when PhysicsActor is null,
  560. // since sitting currently removes avatar from physical scene
  561. m_perfMonMS = System.Environment.TickCount;
  562. uint flags = agentData.AgentData.ControlFlags;
  563. LLQuaternion bodyRotation = agentData.AgentData.BodyRotation;
  564. // Camera location in world. We'll need to raytrace
  565. // from this location from time to time.
  566. m_CameraCenter.x = agentData.AgentData.CameraCenter.X;
  567. m_CameraCenter.y = agentData.AgentData.CameraCenter.Y;
  568. m_CameraCenter.z = agentData.AgentData.CameraCenter.Z;
  569. // Use these three vectors to figure out what the agent is looking at
  570. // Convert it to a Matrix and/or Quaternion
  571. m_CameraAtAxis.x = agentData.AgentData.CameraAtAxis.X;
  572. m_CameraAtAxis.y = agentData.AgentData.CameraAtAxis.Y;
  573. m_CameraAtAxis.z = agentData.AgentData.CameraAtAxis.Z;
  574. m_CameraLeftAxis.x = agentData.AgentData.CameraLeftAxis.X;
  575. m_CameraLeftAxis.y = agentData.AgentData.CameraLeftAxis.Y;
  576. m_CameraLeftAxis.z = agentData.AgentData.CameraLeftAxis.Z;
  577. m_CameraUpAxis.x = agentData.AgentData.CameraUpAxis.X;
  578. m_CameraUpAxis.y = agentData.AgentData.CameraUpAxis.Y;
  579. m_CameraUpAxis.z = agentData.AgentData.CameraUpAxis.Z;
  580. // The Agent's Draw distance setting
  581. m_DrawDistance = agentData.AgentData.Far;
  582. if ((flags & (uint) AgentManager.ControlFlags.AGENT_CONTROL_STAND_UP) != 0)
  583. {
  584. StandUp();
  585. }
  586. if (PhysicsActor == null)
  587. {
  588. return;
  589. }
  590. if ((flags & (uint) AgentManager.ControlFlags.AGENT_CONTROL_SIT_ON_GROUND) != 0)
  591. {
  592. // TODO: This doesn't quite work yet -- probably a parent ID problem
  593. // m_parentID = (what should this be?)
  594. SetMovementAnimation(Animations.AnimsLLUUID["SIT_GROUND"], 1);
  595. }
  596. // In the future, these values might need to go global.
  597. // Here's where you get them.
  598. // m_AgentControlFlags = flags;
  599. // m_headrotation = agentData.AgentData.HeadRotation;
  600. // m_state = agentData.AgentData.State;
  601. if (m_allowMovement)
  602. {
  603. int i = 0;
  604. bool update_movementflag = false;
  605. bool update_rotation = false;
  606. bool DCFlagKeyPressed = false;
  607. Vector3 agent_control_v3 = new Vector3(0, 0, 0);
  608. Quaternion q = new Quaternion(bodyRotation.W, bodyRotation.X, bodyRotation.Y, bodyRotation.Z);
  609. bool oldflying = PhysicsActor.Flying;
  610. PhysicsActor.Flying = ((flags & (uint) AgentManager.ControlFlags.AGENT_CONTROL_FLY) != 0);
  611. if (PhysicsActor.Flying != oldflying)
  612. {
  613. update_movementflag = true;
  614. }
  615. if (q != m_bodyRot)
  616. {
  617. m_bodyRot = q;
  618. update_rotation = true;
  619. }
  620. if (m_parentID == 0)
  621. {
  622. foreach (Dir_ControlFlags DCF in Enum.GetValues(typeof (Dir_ControlFlags)))
  623. {
  624. if ((flags & (uint) DCF) != 0)
  625. {
  626. DCFlagKeyPressed = true;
  627. try
  628. {
  629. agent_control_v3 += Dir_Vectors[i];
  630. }
  631. catch (IndexOutOfRangeException)
  632. {
  633. // Why did I get this?
  634. }
  635. if ((m_movementflag & (uint) DCF) == 0)
  636. {
  637. m_movementflag += (byte) (uint) DCF;
  638. update_movementflag = true;
  639. }
  640. }
  641. else
  642. {
  643. if ((m_movementflag & (uint) DCF) != 0)
  644. {
  645. m_movementflag -= (byte) (uint) DCF;
  646. update_movementflag = true;
  647. }
  648. }
  649. i++;
  650. }
  651. }
  652. // Cause the avatar to stop flying if it's colliding
  653. // with something with the down arrow pressed.
  654. // Skip if there's no physicsactor
  655. if (m_physicsActor != null)
  656. {
  657. // Only do this if we're flying
  658. if (m_physicsActor.Flying)
  659. {
  660. // Are the landing controls requirements filled?
  661. bool controlland = (((flags & (uint) AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0) ||
  662. ((flags & (uint) AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG) != 0));
  663. // Are the collision requirements fulfilled?
  664. bool colliding = (m_physicsActor.IsColliding == true);
  665. if (m_physicsActor.Flying && colliding && controlland)
  666. {
  667. StopFlying();
  668. }
  669. }
  670. }
  671. if ((update_movementflag) || (update_rotation && DCFlagKeyPressed))
  672. {
  673. AddNewMovement(agent_control_v3, q);
  674. UpdateMovementAnimations(update_movementflag);
  675. }
  676. }
  677. m_scene.EventManager.TriggerOnClientMovement(this);
  678. m_scene.AddAgentTime(System.Environment.TickCount - m_perfMonMS);
  679. }
  680. /// <summary>
  681. /// Perform the logic necessary to stand the client up. This method also executes
  682. /// the stand animation.
  683. /// </summary>
  684. public void StandUp()
  685. {
  686. if (m_parentID != 0)
  687. {
  688. SceneObjectPart part = m_scene.GetSceneObjectPart(m_parentID);
  689. if (part != null)
  690. {
  691. // Reset sit target.
  692. if (part.GetAvatarOnSitTarget() == UUID)
  693. part.SetAvatarOnSitTarget(LLUUID.Zero);
  694. m_parentPosition = part.GetWorldPosition();
  695. }
  696. if (m_physicsActor == null)
  697. {
  698. AddToPhysicalScene();
  699. }
  700. m_pos += m_parentPosition + new LLVector3(0.0f, 0.0f, 2.0f*m_sitAvatarHeight);
  701. m_parentPosition = new LLVector3();
  702. m_parentID = 0;
  703. SendFullUpdateToAllClients();
  704. if (m_physicsActor != null)
  705. {
  706. SetHeight(m_avHeight);
  707. }
  708. }
  709. SetMovementAnimation(Animations.AnimsLLUUID["STAND"], 1);
  710. }
  711. private void SendSitResponse(IClientAPI remoteClient, LLUUID targetID, LLVector3 offset)
  712. {
  713. AvatarSitResponsePacket avatarSitResponse = new AvatarSitResponsePacket();
  714. avatarSitResponse.SitObject.ID = targetID;
  715. bool autopilot = true;
  716. LLVector3 pos = new LLVector3();
  717. LLQuaternion sitOrientation = new LLQuaternion(0, 0, 0, 1);
  718. SceneObjectPart part = m_scene.GetSceneObjectPart(targetID);
  719. if (part != null)
  720. {
  721. // TODO: determine position to sit at based on scene geometry; don't trust offset from client
  722. // see http://wiki.secondlife.com/wiki/User:Andrew_Linden/Office_Hours/2007_11_06 for details on how LL does it
  723. // Is a sit target available?
  724. Vector3 avSitOffSet = part.GetSitTargetPosition();
  725. Quaternion avSitOrientation = part.GetSitTargetOrientation();
  726. LLUUID avOnTargetAlready = part.GetAvatarOnSitTarget();
  727. bool SitTargetUnOccupied = (!(avOnTargetAlready != LLUUID.Zero));
  728. bool SitTargetisSet =
  729. (!(avSitOffSet.x == 0 && avSitOffSet.y == 0 && avSitOffSet.z == 0 && avSitOrientation.w == 0 &&
  730. avSitOrientation.x == 0 && avSitOrientation.y == 0 && avSitOrientation.z == 1));
  731. if (SitTargetisSet && SitTargetUnOccupied)
  732. {
  733. part.SetAvatarOnSitTarget(UUID);
  734. offset = new LLVector3(avSitOffSet.x, avSitOffSet.y, avSitOffSet.z);
  735. sitOrientation =
  736. new LLQuaternion(avSitOrientation.w, avSitOrientation.x, avSitOrientation.y, avSitOrientation.z);
  737. autopilot = false;
  738. }
  739. pos = part.AbsolutePosition + offset;
  740. if (m_physicsActor != null)
  741. {
  742. //
  743. // If we're not using the client autopilot, we're immediately warping the avatar to the location
  744. // We can remove the physicsActor until they stand up.
  745. //
  746. m_sitAvatarHeight = m_physicsActor.Size.Z;
  747. if (autopilot)
  748. {
  749. if (Util.GetDistanceTo(AbsolutePosition, pos) < 4.5)
  750. {
  751. autopilot = false;
  752. RemoveFromPhysicalScene();
  753. AbsolutePosition = pos + new LLVector3(0.0f, 0.0f, m_sitAvatarHeight);
  754. }
  755. else
  756. {
  757. }
  758. }
  759. else
  760. {
  761. RemoveFromPhysicalScene();
  762. }
  763. } // Physactor != null
  764. } // part != null
  765. avatarSitResponse.SitTransform.AutoPilot = autopilot;
  766. avatarSitResponse.SitTransform.SitPosition = offset;
  767. avatarSitResponse.SitTransform.SitRotation = sitOrientation;
  768. remoteClient.OutPacket(avatarSitResponse, ThrottleOutPacketType.Task);
  769. // This calls HandleAgentSit twice, once from here, and the client calls
  770. // HandleAgentSit itself after it gets to the location
  771. // It doesn't get to the location until we've moved them there though
  772. // which happens in HandleAgentSit :P
  773. if (!autopilot)
  774. HandleAgentSit(remoteClient, UUID);
  775. }
  776. public void HandleAgentRequestSit(IClientAPI remoteClient, LLUUID agentID, LLUUID targetID, LLVector3 offset)
  777. {
  778. if (m_parentID != 0)
  779. {
  780. StandUp();
  781. }
  782. SceneObjectPart part = m_scene.GetSceneObjectPart(targetID);
  783. if (part != null)
  784. {
  785. m_requestedSitTargetID = part.LocalID;
  786. m_requestedSitOffset = offset;
  787. }
  788. else
  789. {
  790. m_log.Warn("Sit requested on unknown object: " + targetID.ToString());
  791. }
  792. SendSitResponse(remoteClient, targetID, offset);
  793. }
  794. public void HandleAgentSit(IClientAPI remoteClient, LLUUID agentID)
  795. {
  796. SceneObjectPart part = m_scene.GetSceneObjectPart(m_requestedSitTargetID);
  797. if (part != null)
  798. {
  799. if (part.GetAvatarOnSitTarget() == UUID)
  800. {
  801. Vector3 sitTargetPos = part.GetSitTargetPosition();
  802. Quaternion sitTargetOrient = part.GetSitTargetOrientation();
  803. //Quaternion vq = new Quaternion(sitTargetPos.x, sitTargetPos.y+0.2f, sitTargetPos.z+0.2f, 0);
  804. //Quaternion nq = new Quaternion(sitTargetOrient.w, -sitTargetOrient.x, -sitTargetOrient.y, -sitTargetOrient.z);
  805. //Quaternion result = (sitTargetOrient * vq) * nq;
  806. m_pos = new LLVector3(sitTargetPos.x, sitTargetPos.y, sitTargetPos.z);
  807. m_bodyRot = sitTargetOrient;
  808. //Rotation = sitTargetOrient;
  809. m_parentPosition = part.AbsolutePosition;
  810. //SendTerseUpdateToAllClients();
  811. }
  812. else
  813. {
  814. m_pos -= part.AbsolutePosition;
  815. m_parentPosition = part.AbsolutePosition;
  816. }
  817. }
  818. m_parentID = m_requestedSitTargetID;
  819. Velocity = new LLVector3(0, 0, 0);
  820. RemoveFromPhysicalScene();
  821. SetMovementAnimation(Animations.AnimsLLUUID["SIT"], 1);
  822. SendFullUpdateToAllClients();
  823. // This may seem stupid, but Our Full updates don't send avatar rotation :P
  824. // So we're also sending a terse update (which has avatar rotation)
  825. SendTerseUpdateToAllClients();
  826. }
  827. /// <summary>
  828. /// Event handler for the 'Always run' setting on the client
  829. /// Tells the physics plugin to increase speed of movement.
  830. /// </summary>
  831. public void HandleSetAlwaysRun(IClientAPI remoteClient, bool SetAlwaysRun)
  832. {
  833. m_setAlwaysRun = SetAlwaysRun;
  834. if (PhysicsActor != null)
  835. {
  836. PhysicsActor.SetAlwaysRun = SetAlwaysRun;
  837. }
  838. }
  839. public void AddAnimation(LLUUID animID, int seq)
  840. {
  841. if (!m_animations.Contains(animID))
  842. {
  843. m_animations.Add(animID);
  844. m_animationSeqs.Add(seq);
  845. SendAnimPack();
  846. }
  847. }
  848. public void RemoveAnimation(LLUUID animID)
  849. {
  850. if (m_animations.Contains(animID))
  851. {
  852. if (m_animations[0] == animID)
  853. {
  854. SetMovementAnimation(Animations.AnimsLLUUID["STAND"], 1);
  855. }
  856. else
  857. {
  858. m_animations.Remove(animID);
  859. SendAnimPack();
  860. }
  861. }
  862. }
  863. public void HandleStartAnim(IClientAPI remoteClient, LLUUID animID, int seq)
  864. {
  865. AddAnimation(animID, seq);
  866. }
  867. public void HandleStopAnim(IClientAPI remoteClient, LLUUID animID)
  868. {
  869. RemoveAnimation(animID);
  870. }
  871. /// <summary>
  872. /// The movement animation is the first element of the animation list,
  873. /// reserved for "main" animations that are mutually exclusive,
  874. /// like flying and sitting, for example.
  875. /// </summary>
  876. protected void SetMovementAnimation(LLUUID anim, int seq)
  877. {
  878. try
  879. {
  880. if (m_animations[0] != anim)
  881. {
  882. m_animations[0] = anim;
  883. m_animationSeqs[0] = seq;
  884. SendAnimPack();
  885. }
  886. }
  887. catch
  888. {
  889. m_log.Warn("[AVATAR]: SetMovementAnimation for avatar failed. Attempting recovery...");
  890. m_animations[0] = anim;
  891. m_animationSeqs[0] = seq;
  892. SendAnimPack();
  893. }
  894. }
  895. /// <summary>
  896. /// This method handles agent movement related animations
  897. /// </summary>
  898. protected void UpdateMovementAnimations(bool update_movementflag)
  899. {
  900. if (update_movementflag)
  901. {
  902. // Are we moving?
  903. if (m_movementflag != 0)
  904. {
  905. // We are moving
  906. if (m_physicsActor.Flying)
  907. {
  908. // We are flying
  909. SetMovementAnimation(Animations.AnimsLLUUID["FLY"], 1);
  910. }
  911. else if (((m_movementflag & (uint) AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0) &&
  912. PhysicsActor.IsColliding)
  913. {
  914. // Client is pressing the page down button and moving and is colliding with something
  915. SetMovementAnimation(Animations.AnimsLLUUID["CROUCHWALK"], 1);
  916. }
  917. else if (!PhysicsActor.IsColliding && m_physicsActor.Velocity.Z < -6)
  918. {
  919. // Client is moving and falling at a velocity greater then 6 meters per unit
  920. SetMovementAnimation(Animations.AnimsLLUUID["FALLDOWN"], 1);
  921. }
  922. else if (!PhysicsActor.IsColliding && Velocity.Z > 0 &&
  923. (m_movementflag & (uint) AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) != 0)
  924. {
  925. // Client is moving, and colliding and pressing the page up button but isn't flying
  926. try
  927. {
  928. SetMovementAnimation(Animations.AnimsLLUUID["JUMP"], 1);
  929. }
  930. catch (KeyNotFoundException)
  931. { }
  932. }
  933. else if (m_setAlwaysRun)
  934. {
  935. // We are running
  936. try
  937. {
  938. SetMovementAnimation(Animations.AnimsLLUUID["RUN"], 1);
  939. }
  940. catch (KeyNotFoundException)
  941. { }
  942. }
  943. else
  944. {
  945. // We're moving, but we're not doing anything else.. so play the stand animation
  946. try
  947. {
  948. SetMovementAnimation(Animations.AnimsLLUUID["WALK"], 1);
  949. }
  950. catch (KeyNotFoundException)
  951. { }
  952. }
  953. }
  954. else
  955. {
  956. // Not moving
  957. if (((m_movementflag & (uint) AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0) &&
  958. PhysicsActor.IsColliding)
  959. {
  960. // Client pressing the page down button
  961. SetMovementAnimation(Animations.AnimsLLUUID["CROUCH"], 1);
  962. }
  963. else if (!PhysicsActor.IsColliding && m_physicsActor.Velocity.Z < -6 && !m_physicsActor.Flying)
  964. {
  965. // Not colliding and not flying, and we're falling at high speed
  966. SetMovementAnimation(Animations.AnimsLLUUID["FALLDOWN"], 1);
  967. }
  968. else if (!PhysicsActor.IsColliding && Velocity.Z > 0 && !m_physicsActor.Flying &&
  969. (m_movementflag & (uint) AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) != 0)
  970. {
  971. // This is the standing jump
  972. SetMovementAnimation(Animations.AnimsLLUUID["JUMP"], 1);
  973. }
  974. else if (m_physicsActor.Flying)
  975. {
  976. // We're flying but not moving
  977. SetMovementAnimation(Animations.AnimsLLUUID["HOVER"], 1);
  978. }
  979. else
  980. {
  981. // We're not moving.. and we're not doing anything.. so play the stand animation
  982. try
  983. {
  984. SetMovementAnimation(Animations.AnimsLLUUID["STAND"], 1);
  985. }
  986. catch (KeyNotFoundException)
  987. { }
  988. }
  989. }
  990. }
  991. }
  992. /// <summary>
  993. /// Adds a new movement
  994. /// </summary>
  995. protected void AddNewMovement(Vector3 vec, Quaternion rotation)
  996. {
  997. if (m_isChildAgent)
  998. {
  999. Console.WriteLine("DEBUG: AddNewMovement: child agent");
  1000. return;
  1001. }
  1002. m_perfMonMS = System.Environment.TickCount;
  1003. m_rotation = rotation;
  1004. NewForce newVelocity = new NewForce();
  1005. Vector3 direc = rotation*vec;
  1006. direc.Normalize();
  1007. direc *= 0.03f*128f;
  1008. if (m_physicsActor.Flying)
  1009. {
  1010. direc *= 4;
  1011. //bool controlland = (((m_AgentControlFlags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0) || ((m_AgentControlFlags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG) != 0));
  1012. //bool colliding = (m_physicsActor.IsColliding==true);
  1013. //if (controlland)
  1014. // m_log.Info("[AGENT]: landCommand");
  1015. //if (colliding )
  1016. // m_log.Info("[AGENT]: colliding");
  1017. //if (m_physicsActor.Flying && colliding && controlland)
  1018. //{
  1019. // StopFlying();
  1020. // m_log.Info("[AGENT]: Stop FLying");
  1021. //}
  1022. }
  1023. else
  1024. {
  1025. if (!m_physicsActor.Flying && m_physicsActor.IsColliding)
  1026. {
  1027. //direc.z *= 40;
  1028. if (direc.z > 2.0f)
  1029. {
  1030. direc.z *= 3;
  1031. //System.Console.WriteLine("Jump");
  1032. // PreJump and jump happen too quickly. Many times prejump gets ignored.
  1033. try
  1034. {
  1035. SetMovementAnimation(Animations.AnimsLLUUID["PREJUMP"], 1);
  1036. SetMovementAnimation(Animations.AnimsLLUUID["JUMP"], 1);
  1037. }
  1038. catch (KeyNotFoundException)
  1039. { }
  1040. }
  1041. }
  1042. }
  1043. newVelocity.X = direc.x;
  1044. newVelocity.Y = direc.y;
  1045. newVelocity.Z = direc.z;
  1046. m_forcesList.Add(newVelocity);
  1047. m_scene.AddAgentTime(System.Environment.TickCount - m_perfMonMS);
  1048. }
  1049. #endregion
  1050. #region Overridden Methods
  1051. /// <summary>
  1052. ///
  1053. /// </summary>
  1054. public override void Update()
  1055. {
  1056. SendPrimUpdates();
  1057. if (m_newCoarseLocations)
  1058. {
  1059. SendCoarseLocations();
  1060. m_newCoarseLocations = false;
  1061. }
  1062. if (m_isChildAgent == false)
  1063. {
  1064. if (m_newForce) // user movement 'forces' (ie commands to move)
  1065. {
  1066. SendTerseUpdateToAllClients();
  1067. m_updateCount = 0;
  1068. }
  1069. else if (m_movementflag != 0) // scripted movement (?)
  1070. {
  1071. m_updateCount++;
  1072. if (m_updateCount > 3)
  1073. {
  1074. SendTerseUpdateToAllClients();
  1075. m_updateCount = 0;
  1076. }
  1077. }
  1078. else if ((Util.GetDistanceTo(lastPhysPos, AbsolutePosition) > 0.02) || (Util.GetDistanceTo(m_lastVelocity, m_velocity) > 0.02)) // physics-related movement
  1079. {
  1080. // Send Terse Update to all clients updates lastPhysPos and m_lastVelocity
  1081. // doing the above assures us that we know what we sent the clients last
  1082. SendTerseUpdateToAllClients();
  1083. m_updateCount = 0;
  1084. }
  1085. // followed suggestion from mic bowman. reversed the two lines below.
  1086. CheckForBorderCrossing();
  1087. CheckForSignificantMovement(); // sends update to the modules.
  1088. }
  1089. }
  1090. #endregion
  1091. #region Update Client(s)
  1092. /// <summary>
  1093. /// Sends a location update to the client connected to this scenePresence
  1094. /// </summary>
  1095. /// <param name="remoteClient"></param>
  1096. public void SendTerseUpdateToClient(IClientAPI remoteClient)
  1097. {
  1098. m_perfMonMS = System.Environment.TickCount;
  1099. LLVector3 pos = m_pos;
  1100. LLVector3 vel = Velocity;
  1101. LLQuaternion rot = new LLQuaternion(m_bodyRot.x, m_bodyRot.y, m_bodyRot.z, m_bodyRot.w);
  1102. remoteClient.SendAvatarTerseUpdate(m_regionHandle, (ushort)(m_scene.TimeDilation * (float)ushort.MaxValue), LocalId, new LLVector3(pos.X, pos.Y, pos.Z),
  1103. new LLVector3(vel.X, vel.Y, vel.Z), rot);
  1104. m_scene.AddAgentTime(System.Environment.TickCount - m_perfMonMS);
  1105. m_scene.AddAgentUpdates(1);
  1106. }
  1107. /// <summary>
  1108. /// Send a location/velocity/accelleration update to all agents in scene
  1109. /// </summary>
  1110. public void SendTerseUpdateToAllClients()
  1111. {
  1112. m_perfMonMS = System.Environment.TickCount;
  1113. m_scene.Broadcast(SendTerseUpdateToClient);
  1114. m_lastVelocity = m_velocity;
  1115. lastPhysPos = AbsolutePosition;
  1116. m_scene.AddAgentTime(System.Environment.TickCount - m_perfMonMS);
  1117. }
  1118. public void SendCoarseLocations()
  1119. {
  1120. m_perfMonMS = System.Environment.TickCount;
  1121. List<LLVector3> CoarseLocations = new List<LLVector3>();
  1122. List<ScenePresence> avatars = m_scene.GetAvatars();
  1123. for (int i = 0; i < avatars.Count; i++)
  1124. {
  1125. if (avatars[i] != this)
  1126. {
  1127. CoarseLocations.Add(avatars[i].m_pos);
  1128. }
  1129. }
  1130. m_controllingClient.SendCoarseLocationUpdate(CoarseLocations);
  1131. m_scene.AddAgentTime(System.Environment.TickCount - m_perfMonMS);
  1132. }
  1133. public void CoarseLocationChange()
  1134. {
  1135. m_newCoarseLocations = true;
  1136. }
  1137. /// <summary>
  1138. /// Tell other client about this avatar (The client previously didn't know or had outdated details about this avatar)
  1139. /// </summary>
  1140. /// <param name="remoteAvatar"></param>
  1141. public void SendFullUpdateToOtherClient(ScenePresence remoteAvatar)
  1142. {
  1143. remoteAvatar.m_controllingClient.SendAvatarData(m_regionInfo.RegionHandle, m_firstname, m_lastname, m_uuid,
  1144. LocalId, m_pos, m_appearance.TextureEntry.ToBytes(),
  1145. m_parentID);
  1146. m_scene.AddAgentUpdates(1);
  1147. }
  1148. /// <summary>
  1149. /// Tell *ALL* agents about this agent
  1150. /// </summary>
  1151. public void SendFullUpdateToAllClients()
  1152. {
  1153. m_perfMonMS = System.Environment.TickCount;
  1154. List<ScenePresence> avatars = m_scene.GetScenePresences();
  1155. foreach (ScenePresence avatar in avatars)
  1156. {
  1157. SendFullUpdateToOtherClient(avatar);
  1158. if (avatar.LocalId != LocalId)
  1159. {
  1160. if (!avatar.m_isChildAgent || m_scene.m_seeIntoRegionFromNeighbor)
  1161. {
  1162. avatar.SendFullUpdateToOtherClient(this);
  1163. avatar.SendAppearanceToOtherAgent(this);
  1164. }
  1165. }
  1166. }
  1167. m_scene.AddAgentUpdates(avatars.Count);
  1168. m_scene.AddAgentTime(System.Environment.TickCount - m_perfMonMS);
  1169. }
  1170. /// <summary>
  1171. ///
  1172. /// </summary>
  1173. public void SendInitialData()
  1174. {
  1175. m_controllingClient.SendAvatarData(m_regionInfo.RegionHandle, m_firstname, m_lastname, m_uuid, LocalId,
  1176. m_pos, m_appearance.TextureEntry.ToBytes(), m_parentID);
  1177. if (!m_isChildAgent)
  1178. {
  1179. m_scene.InformClientOfNeighbours(this);
  1180. }
  1181. SendFullUpdateToAllClients();
  1182. SendAppearanceToAllOtherAgents();
  1183. }
  1184. /// <summary>
  1185. ///
  1186. /// </summary>
  1187. /// <param name="client"></param>
  1188. public void SendOwnAppearance()
  1189. {
  1190. m_appearance.SendOwnWearables(ControllingClient);
  1191. // TODO: remove this once the SunModule is slightly more tested
  1192. // m_controllingClient.SendViewerTime(m_scene.TimePhase);
  1193. }
  1194. /// <summary>
  1195. ///
  1196. /// </summary>
  1197. public void SendAppearanceToAllOtherAgents()
  1198. {
  1199. m_perfMonMS=System.Environment.TickCount;
  1200. m_scene.ForEachScenePresence(delegate(ScenePresence scenePresence)
  1201. {
  1202. if (scenePresence.UUID != UUID)
  1203. {
  1204. m_appearance.SendAppearanceToOtherAgent(scenePresence);
  1205. }
  1206. });
  1207. m_scene.AddAgentTime(System.Environment.TickCount - m_perfMonMS);
  1208. }
  1209. public void SendAppearanceToOtherAgent(ScenePresence avatar)
  1210. {
  1211. m_appearance.SendAppearanceToOtherAgent(avatar);
  1212. }
  1213. public void SetAppearance(byte[] texture, AgentSetAppearancePacket.VisualParamBlock[] visualParam)
  1214. {
  1215. m_appearance.SetAppearance(texture, visualParam);
  1216. SetHeight(m_appearance.AvatarHeight);
  1217. SendAppearanceToAllOtherAgents();
  1218. }
  1219. public void SetWearable(int wearableId, AvatarWearable wearable)
  1220. {
  1221. m_appearance.SetWearable(ControllingClient, wearableId, wearable);
  1222. }
  1223. /// <summary>
  1224. ///
  1225. /// </summary>
  1226. /// <param name="animations"></param>
  1227. /// <param name="seqs"></param>
  1228. public void SendAnimPack(LLUUID[] animations, int[] seqs)
  1229. {
  1230. m_scene.Broadcast(
  1231. delegate(IClientAPI client) { client.SendAnimations(animations, seqs, m_controllingClient.AgentId); });
  1232. }
  1233. /// <summary>
  1234. ///
  1235. /// </summary>
  1236. public void SendAnimPack()
  1237. {
  1238. SendAnimPack(m_animations.ToArray(), m_animationSeqs.ToArray());
  1239. }
  1240. #endregion
  1241. #region Significant Movement Method
  1242. /// <summary>
  1243. /// This checks for a significant movement and sends a courselocationchange update
  1244. /// </summary>
  1245. protected void CheckForSignificantMovement()
  1246. {
  1247. if (Util.GetDistanceTo(AbsolutePosition, posLastSignificantMove) > 0.5)
  1248. {
  1249. posLastSignificantMove = AbsolutePosition;
  1250. if (OnSignificantClientMovement != null)
  1251. {
  1252. OnSignificantClientMovement(m_controllingClient);
  1253. m_scene.NotifyMyCoarseLocationChange();
  1254. }
  1255. }
  1256. // Minimum Draw distance is 64 meters, the Radius of the draw distance sphere is 32m
  1257. if (Util.GetDistanceTo(AbsolutePosition,m_LastChildAgentUpdatePosition) > 32)
  1258. {
  1259. ChildAgentDataUpdate cadu = new ChildAgentDataUpdate();
  1260. cadu.ActiveGroupID=LLUUID.Zero.UUID;
  1261. cadu.AgentID = UUID.UUID;
  1262. cadu.alwaysrun = m_setAlwaysRun;
  1263. cadu.AVHeight = m_avHeight;
  1264. LLVector3 tempCameraCenter = new LLVector3(m_CameraCenter.x, m_CameraCenter.y, m_CameraCenter.z);
  1265. cadu.cameraPosition = new sLLVector3(tempCameraCenter);
  1266. cadu.drawdistance = m_DrawDistance;
  1267. cadu.godlevel = m_godlevel;
  1268. cadu.GroupAccess = 0;
  1269. cadu.Position = new sLLVector3(AbsolutePosition);
  1270. cadu.regionHandle = m_scene.RegionInfo.RegionHandle;
  1271. cadu.throttles = ControllingClient.GetThrottlesPacked(1f);
  1272. cadu.Velocity = new sLLVector3(Velocity);
  1273. m_scene.SendOutChildAgentUpdates(cadu,this);
  1274. m_LastChildAgentUpdatePosition.X = AbsolutePosition.X;
  1275. m_LastChildAgentUpdatePosition.Y = AbsolutePosition.Y;
  1276. m_LastChildAgentUpdatePosition.Z = AbsolutePosition.Z;
  1277. }
  1278. }
  1279. #endregion
  1280. #region Border Crossing Methods
  1281. /// <summary>
  1282. /// Checks to see if the avatar is in range of a border and calls CrossToNewRegion
  1283. /// </summary>
  1284. protected void CheckForBorderCrossing()
  1285. {
  1286. LLVector3 pos2 = AbsolutePosition;
  1287. LLVector3 vel = Velocity;
  1288. float timeStep = 0.1f;
  1289. pos2.X = pos2.X + (vel.X*timeStep);
  1290. pos2.Y = pos2.Y + (vel.Y*timeStep);
  1291. pos2.Z = pos2.Z + (vel.Z*timeStep);
  1292. if ((pos2.X < 0) || (pos2.X > Constants.RegionSize))
  1293. {
  1294. CrossToNewRegion();
  1295. }
  1296. if ((pos2.Y < 0) || (pos2.Y > Constants.RegionSize))
  1297. {
  1298. CrossToNewRegion();
  1299. }
  1300. }
  1301. /// <summary>
  1302. /// Moves the agent outside the region bounds
  1303. /// Tells neighbor region that we're crossing to it
  1304. /// If the neighbor accepts, remove the agent's viewable avatar from this scene
  1305. /// set them to a child agent.
  1306. /// </summary>
  1307. protected void CrossToNewRegion()
  1308. {
  1309. LLVector3 pos = AbsolutePosition;
  1310. LLVector3 newpos = new LLVector3(pos.X, pos.Y, pos.Z);
  1311. uint neighbourx = m_regionInfo.RegionLocX;
  1312. uint neighboury = m_regionInfo.RegionLocY;
  1313. // distance to edge that will trigger crossing
  1314. const float boundaryDistance = 1.7f;
  1315. // distance into new region to place avatar
  1316. const float enterDistance = 0.1f;
  1317. if (pos.X < boundaryDistance)
  1318. {
  1319. neighbourx--;
  1320. newpos.X = Constants.RegionSize - enterDistance;
  1321. }
  1322. else if (pos.X > Constants.RegionSize - boundaryDistance)
  1323. {
  1324. neighbourx++;
  1325. newpos.X = enterDistance;
  1326. }
  1327. if (pos.Y < boundaryDistance)
  1328. {
  1329. neighboury--;
  1330. newpos.Y = Constants.RegionSize - enterDistance;
  1331. }
  1332. else if (pos.Y > Constants.RegionSize - boundaryDistance)
  1333. {
  1334. neighboury++;
  1335. newpos.Y = enterDistance;
  1336. }
  1337. LLVector3 vel = m_velocity;
  1338. ulong neighbourHandle = Helpers.UIntsToLong((uint)(neighbourx * Constants.RegionSize), (uint)(neighboury * Constants.RegionSize));
  1339. SimpleRegionInfo neighbourRegion = m_scene.RequestNeighbouringRegionInfo(neighbourHandle);
  1340. if (neighbourRegion != null)
  1341. {
  1342. bool res =
  1343. m_scene.InformNeighbourOfCrossing(neighbourHandle, m_controllingClient.AgentId, newpos,
  1344. m_physicsActor.Flying);
  1345. if (res)
  1346. {
  1347. AgentCircuitData circuitdata = m_controllingClient.RequestClientInfo();
  1348. string capsPath = Util.GetCapsURL(m_controllingClient.AgentId);
  1349. m_controllingClient.CrossRegion(neighbourHandle, newpos, vel, neighbourRegion.ExternalEndPoint,
  1350. capsPath);
  1351. MakeChildAgent();
  1352. m_scene.SendKillObject(m_localId);
  1353. m_scene.NotifyMyCoarseLocationChange();
  1354. }
  1355. }
  1356. }
  1357. #endregion
  1358. /// <summary>
  1359. /// This allows the Sim owner the abiility to kick users from their sim currently.
  1360. /// It tells the client that the agent has permission to do so.
  1361. /// </summary>
  1362. public void GrantGodlikePowers(LLUUID agentID, LLUUID sessionID, LLUUID token)
  1363. {
  1364. GrantGodlikePowersPacket respondPacket = new GrantGodlikePowersPacket();
  1365. GrantGodlikePowersPacket.GrantDataBlock gdb = new GrantGodlikePowersPacket.GrantDataBlock();
  1366. GrantGodlikePowersPacket.AgentDataBlock adb = new GrantGodlikePowersPacket.AgentDataBlock();
  1367. adb.AgentID = agentID;
  1368. adb.SessionID = sessionID; // More security
  1369. gdb.GodLevel = (byte) 250;
  1370. gdb.Token = token;
  1371. //respondPacket.AgentData = (GrantGodlikePowersPacket.AgentDataBlock)ablock;
  1372. respondPacket.GrantData = gdb;
  1373. respondPacket.AgentData = adb;
  1374. ControllingClient.OutPacket(respondPacket, ThrottleOutPacketType.Task);
  1375. }
  1376. /// <summary>
  1377. /// This updates important decision making data about a child agent
  1378. /// The main purpose is to figure out what objects to send to a child agent that's in a neighboring region
  1379. /// </summary>
  1380. public void ChildAgentDataUpdate(ChildAgentDataUpdate cAgentData, uint tRegionX, uint tRegionY, uint rRegionX, uint rRegionY)
  1381. {
  1382. //
  1383. int shiftx = ((int)rRegionX - (int)tRegionX) * (int)Constants.RegionSize;
  1384. int shifty = ((int)rRegionY - (int)tRegionY) * (int)Constants.RegionSize;
  1385. m_DrawDistance = cAgentData.drawdistance;
  1386. m_pos = new LLVector3(cAgentData.Position.x + shiftx, cAgentData.Position.y + shifty, cAgentData.Position.z);
  1387. // It's hard to say here.. We can't really tell where the camera position is unless it's in world cordinates from the sending region
  1388. m_CameraCenter =
  1389. new Vector3(cAgentData.cameraPosition.x, cAgentData.cameraPosition.y, cAgentData.cameraPosition.z);
  1390. m_godlevel = cAgentData.godlevel;
  1391. SetHeight(cAgentData.AVHeight);
  1392. ControllingClient.SetChildAgentThrottle(cAgentData.throttles);
  1393. // Sends out the objects in the user's draw distance if m_sendTasksToChild is true.
  1394. if (m_scene.m_seeIntoRegionFromNeighbor)
  1395. m_scene.SendAllSceneObjectsToClient(this);
  1396. //cAgentData.AVHeight;
  1397. //cAgentData.regionHandle;
  1398. //m_velocity = cAgentData.Velocity;
  1399. }
  1400. /// <summary>
  1401. /// Handles part of the PID controller function for moving an avatar.
  1402. /// </summary>
  1403. public override void UpdateMovement()
  1404. {
  1405. m_newForce = false;
  1406. lock (m_forcesList)
  1407. {
  1408. if (m_forcesList.Count > 0)
  1409. {
  1410. for (int i = 0; i < m_forcesList.Count; i++)
  1411. {
  1412. NewForce force = m_forcesList[i];
  1413. m_updateflag = true;
  1414. try
  1415. {
  1416. movementvector.X = force.X;
  1417. movementvector.Y = force.Y;
  1418. movementvector.Z = force.Z;
  1419. Velocity = movementvector;
  1420. }
  1421. catch (System.NullReferenceException)
  1422. {
  1423. // Under extreme load, this returns a NullReference Exception that we can ignore.
  1424. // Ignoring this causes no movement to be sent to the physics engine...
  1425. // which when the scene is moving at 1 frame every 10 seconds, it doesn't really matter!
  1426. }
  1427. m_newForce = true;
  1428. }
  1429. for (int i = 0; i < m_forcesList.Count; i++)
  1430. {
  1431. m_forcesList.RemoveAt(0);
  1432. }
  1433. }
  1434. }
  1435. }
  1436. static ScenePresence()
  1437. {
  1438. LLObject.TextureEntry textu = AvatarAppearance.GetDefaultTextureEntry();
  1439. DefaultTexture = textu.ToBytes();
  1440. }
  1441. public class NewForce
  1442. {
  1443. public float X;
  1444. public float Y;
  1445. public float Z;
  1446. public NewForce()
  1447. {
  1448. }
  1449. }
  1450. public class ScenePartUpdate
  1451. {
  1452. public LLUUID FullID;
  1453. public uint LastFullUpdateTime;
  1454. public uint LastTerseUpdateTime;
  1455. public ScenePartUpdate()
  1456. {
  1457. FullID = LLUUID.Zero;
  1458. LastFullUpdateTime = 0;
  1459. LastTerseUpdateTime = 0;
  1460. }
  1461. }
  1462. public override void SetText(string text, Vector3 color, double alpha)
  1463. {
  1464. throw new Exception("Can't set Text on avatar.");
  1465. }
  1466. /// <summary>
  1467. /// Adds a physical representation of the avatar to the Physics plugin
  1468. /// </summary>
  1469. public void AddToPhysicalScene()
  1470. {
  1471. PhysicsScene scene = m_scene.PhysicsScene;
  1472. PhysicsVector pVec =
  1473. new PhysicsVector(AbsolutePosition.X, AbsolutePosition.Y,
  1474. AbsolutePosition.Z);
  1475. m_physicsActor = scene.AddAvatar(Firstname + "." + Lastname, pVec,new PhysicsVector(0,0,m_avHeight));
  1476. //m_physicsActor.OnRequestTerseUpdate += SendTerseUpdateToAllClients;
  1477. m_physicsActor.OnCollisionUpdate += PhysicsCollisionUpdate;
  1478. }
  1479. // Event called by the physics plugin to tell the avatar about a collision.
  1480. private void PhysicsCollisionUpdate(EventArgs e)
  1481. {
  1482. bool isUserMoving = Velocity.X > 0 || Velocity.Y > 0;
  1483. UpdateMovementAnimations(isUserMoving);
  1484. }
  1485. internal void Close()
  1486. {
  1487. RemoveFromPhysicalScene();
  1488. }
  1489. }
  1490. }