1
0

ScenePresence.cs 152 KB

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