ScenePresence.cs 180 KB

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