ScenePresence.cs 146 KB

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