ScenePresence.cs 146 KB

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