ScenePresence.cs 144 KB

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