1
0

ScenePresence.cs 145 KB

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