ScenePresence.cs 161 KB

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