ScenePresence.cs 151 KB

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