ScenePresence.cs 185 KB

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