1
0

ScenePresence.cs 151 KB

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