/* * Copyright (c) 2006-2007, Second Life Reverse Engineering Team * All rights reserved. * * - Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Neither the name of the Second Life Reverse Engineering Team nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Timers; using System.Net; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Text; using libsecondlife.Packets; namespace libsecondlife { #region Enums /// /// /// [Flags] public enum ScriptPermission : int { /// Placeholder for empty values, shouldn't ever see this None = 0, /// Script wants to take money from you Debit = 1 << 1, /// TakeControls = 1 << 2, /// RemapControls = 1 << 3, /// Script wants to trigger avatar animations TriggerAnimation = 1 << 4, /// Attach = 1 << 5, /// ReleaseOwnership = 1 << 6, /// ChangeLinks = 1 << 7, /// ChangeJoints = 1 << 8, /// ChangePermissions = 1 << 9, /// TrackCamera = 1 << 10, /// Script wants to control your camera ControlCamera = 1 << 11 } /// /// Special commands used in Instant Messages /// public enum InstantMessageDialog : byte { /// Indicates a regular IM from another agent MessageFromAgent = 0, /// Simple notification box with an OK button MessageBox = 1, /// Used to show a countdown notification with an OK /// button, deprecated now [Obsolete] MessageBoxCountdown = 2, /// You've been invited to join a group. GroupInvitation = 3, /// Inventory offer InventoryOffered = 4, /// Accepted inventory offer InventoryAccepted = 5, /// Declined inventory offer InventoryDeclined = 6, /// Group vote GroupVote = 7, /// A message to everyone in the agent's group, no longer /// used [Obsolete] DeprecatedGroupMessage = 8, /// An object is offering its inventory TaskInventoryOffered = 9, /// Accept an inventory offer from an object TaskInventoryAccepted = 10, /// Decline an inventory offer from an object TaskInventoryDeclined = 11, /// Unknown NewUserDefault = 12, /// Start a session, or add users to a session SessionAdd = 13, /// Start a session, but don't prune offline users SessionOfflineAdd = 14, /// Start a session with your group SessionGroupStart = 15, /// Start a session without a calling card (finder or objects) SessionCardlessStart = 16, /// Send a message to a session SessionSend = 17, /// Leave a session SessionDrop = 18, /// Indicates that the IM is from an object MessageFromObject = 19, /// sent an IM to a busy user, this is the auto response BusyAutoResponse = 20, /// Shows the message in the console and chat history ConsoleAndChatHistory = 21, /// IM Types used for luring your friends RequestTeleport = 22, /// Response sent to the agent which inititiated a teleport invitation AcceptTeleport = 23, /// Response sent to the agent which inititiated a teleport invitation DenyTeleport = 24, /// Only useful if you have Linden permissions GodLikeRequestTeleport = 25, /// A placeholder type for future expansion, currently not /// used CurrentlyUnused = 26, /// Notification of a new group election, this is /// deprecated [Obsolete] DeprecatedGroupElection = 27, /// IM to tell the user to go to an URL GotoUrl = 28, /// IM for help Session911Start = 29, /// IM sent automatically on call for help, sends a lure /// to each Helper reached Lure911 = 30, /// Like an IM but won't go to email FromTaskAsAlert = 31, /// IM from a group officer to all group members GroupNotice = 32, /// Unknown GroupNoticeInventoryAccepted = 33, /// Unknown GroupNoticeInventoryDeclined = 34, /// Accept a group invitation GroupInvitationAccept = 35, /// Decline a group invitation GroupInvitationDecline = 36, /// Unknown GroupNoticeRequested = 37, /// An avatar is offering you friendship FriendshipOffered = 38, /// An avatar has accepted your friendship offer FriendshipAccepted = 39, /// An avatar has declined your friendship offer FriendshipDeclined = 40, /// Indicates that a user has started typing StartTyping = 41, /// Indicates that a user has stopped typing StopTyping = 42 } /// /// Flag in Instant Messages, whether the IM should be delivered to /// offline avatars as well /// public enum InstantMessageOnline { /// Only deliver to online avatars Online = 0, /// If the avatar is offline the message will be held until /// they login next, and possibly forwarded to their e-mail account Offline = 1 } /// /// Conversion type to denote Chat Packet types in an easier-to-understand format /// public enum ChatType : byte { /// Whisper (5m radius) Whisper = 0, /// Normal chat (10/20m radius), what the official viewer typically sends Normal = 1, /// Shouting! (100m radius) Shout = 2, /// Say chat (10/20m radius) - The official viewer will /// print "[4:15] You say, hey" instead of "[4:15] You: hey" [Obsolete] Say = 3, /// Event message when an Avatar has begun to type StartTyping = 4, /// Event message when an Avatar has stopped typing StopTyping = 5, /// Unknown Debug = 6 } /// /// Identifies the source of a chat message /// public enum ChatSourceType : byte { /// Chat from the grid or simulator System = 0, /// Chat from another avatar Agent = 1, /// Chat from an object Object = 2 } /// /// /// public enum ChatAudibleLevel : sbyte { /// Not = -1, /// Barely = 0, /// Fully = 1 } /// /// Effect type used in ViewerEffect packets /// public enum EffectType : byte { /// Text = 0, /// Icon, /// Connector, /// FlexibleObject, /// AnimalControls, /// AnimationObject, /// Cloth, /// Project a beam from a source to a destination, such as /// the one used when editing an object Beam, /// Glow, /// Point, /// Trail, /// Create a swirl of particles around an object Sphere, /// Spiral, /// Edit, /// Cause an avatar to look at an object LookAt, /// Cause an avatar to point at an object PointAt } /// /// The action an avatar is doing when looking at something, used in /// ViewerEffect packets for the LookAt effect /// public enum LookAtType : byte { /// None, /// Idle, /// AutoListen, /// FreeLook, /// Respond, /// Hover, /// Deprecated [Obsolete] Conversation, /// Select, /// Focus, /// Mouselook, /// Clear } /// /// The action an avatar is doing when pointing at something, used in /// ViewerEffect packets for the PointAt effect /// public enum PointAtType : byte { /// None, /// Select, /// Grab, /// Clear } public enum MoneyTransactionType : int { None = 0, FailSimulatorTimeout = 1, FailDataserverTimeout = 2, ObjectClaim = 1000, LandClaim = 1001, GroupCreate = 1002, ObjectPublicClaim = 1003, GroupJoin = 1004, TeleportCharge = 1100, UploadCharge = 1101, LandAuction = 1102, ClassifiedCharge = 1103, ObjectTax = 2000, LandTax = 2001, LightTax = 2002, ParcelDirFee = 2003, GroupTax = 2004, ClassifiedRenew = 2005, GiveInventory = 3000, ObjectSale = 5000, Gift = 5001, LandSale = 5002, ReferBonus = 5003, InventorySale = 5004, RefundPurchase = 5005, LandPassSale = 5006, DwellBonus = 5007, PayObject = 5008, ObjectPays = 5009, GroupLandDeed = 6001, GroupObjectDeed = 6002, GroupLiability = 6003, GroupDividend = 6004, GroupMembershipDues = 6005, ObjectRelease = 8000, LandRelease = 8001, ObjectDelete = 8002, ObjectPublicDecay = 8003, ObjectPublicDelete = 8004, LindenAdjustment = 9000, LindenGrant = 9001, LindenPenalty = 9002, EventFee = 9003, EventPrize = 9004, StipendBasic = 10000, StipendDeveloper = 10001, StipendAlways = 10002, StipendDaily = 10003, StipendRating = 10004, StipendDelta = 10005 } [Flags] public enum TransactionFlags : byte { None = 0, SourceGroup = 1, DestGroup = 2, OwnerGroup = 4, SimultaneousContribution = 8, ContributionRemoval = 16 } #endregion Enums #region Structs /// /// Instant Message /// public struct InstantMessage { /// Key of sender public LLUUID FromAgentID; /// Name of sender public string FromAgentName; /// Key of destination avatar public LLUUID ToAgentID; /// ID of originating estate public uint ParentEstateID; /// Key of originating region public LLUUID RegionID; /// Coordinates in originating region public LLVector3 Position; /// Instant message type public InstantMessageDialog Dialog; /// Group IM session toggle public bool GroupIM; /// Key of IM session public LLUUID IMSessionID; /// Timestamp of the instant message public DateTime Timestamp; /// Instant message text public string Message; /// Whether this message is held for offline avatars public InstantMessageOnline Offline; /// Context specific packed data public byte[] BinaryBucket; } #endregion Structs /// /// Class to hold Client Avatar's data /// public partial class MainAvatar { #region Enums /// /// Currently only used to hide your group title /// [Flags] public enum AgentFlags : byte { /// No flags set None = 0, /// Hide your group title HideTitle = 0x01, } /// /// Action state of the avatar, which can currently be typing and /// editing /// [Flags] public enum AgentState : byte { /// None = 0x00, /// Typing = 0x04, /// Editing = 0x10 } /// /// Current teleport status /// public enum TeleportStatus { /// Unknown status None, /// Teleport initialized Start, /// Teleport in progress Progress, /// Teleport failed Failed, /// Teleport completed Finished, /// Teleport cancelled Cancelled } /// /// /// [Flags] public enum TeleportFlags : uint { /// Default = 0, /// SetHomeToTarget = 1 << 0, /// SetLastToTarget = 1 << 1, /// ViaLure = 1 << 2, /// ViaLandmark = 1 << 3, /// ViaLocation = 1 << 4, /// ViaHome = 1 << 5, /// ViaTelehub = 1 << 6, /// ViaLogin = 1 << 7, /// ViaGodlikeLure = 1 << 8, /// Godlike = 1 << 9, /// NineOneOne = 1 << 10, /// DisableCancel = 1 << 11, /// ViaRegionID = 1 << 12, /// IsFlying = 1 << 13 } /// /// /// [Flags] public enum TeleportLureFlags { /// NormalLure = 0, /// GodlikeLure = 1, /// GodlikePursuit = 2 } #endregion #region Callbacks & Events /// /// Triggered on incoming chat messages /// /// Text of chat message /// Audible level of this chat message /// Type of chat (whisper, shout, status, etc.) /// Source of the chat message /// Name of the sending object /// /// /// public delegate void ChatCallback(string message, ChatAudibleLevel audible, ChatType type, ChatSourceType sourceType, string fromName, LLUUID id, LLUUID ownerid, LLVector3 position); /// /// Triggered when a script pops up a dialog box /// /// The dialog box message /// Name of the object that sent the dialog /// Image to be displayed in the dialog /// ID of the object that sent the dialog /// First name of the object owner /// Last name of the object owner /// Chat channel that the object is communicating on /// List of button labels public delegate void ScriptDialogCallback(string message, string objectName, LLUUID imageID, LLUUID objectID, string firstName, string lastName, int chatChannel, List buttons); /// /// Triggered when a script asks for permissions /// /// Task ID of the script requesting permissions /// ID of the object containing the script /// Name of the object containing the script /// Name of the object's owner /// Bitwise value representing the requested permissions public delegate void ScriptQuestionCallback(LLUUID taskID, LLUUID itemID, string objectName, string objectOwner, ScriptPermission questions); /// /// Triggered when the L$ account balance for this avatar changes /// /// The new account balance public delegate void BalanceCallback(int balance); /// /// Triggered on Money Balance Reply /// /// ID provided in Request Money Balance, or auto-generated by system events /// Was the transaction successful /// Current balance /// /// /// public delegate void MoneyBalanceReplyCallback(LLUUID transactionID, bool transactionSuccess, int balance, int metersCredit, int metersCommitted, string description); /// /// Triggered on incoming instant messages /// /// Instant message data structure /// Simulator where this IM was received from public delegate void InstantMessageCallback(InstantMessage im, Simulator simulator); /// /// Triggered for any status updates of a teleport (progress, failed, succeeded) /// /// A message about the current teleport status /// The current status of the teleport /// Various flags describing the teleport public delegate void TeleportCallback(string message, TeleportStatus status, TeleportFlags flags); /// /// Reply to a request to join a group, informs whether it was successful or not /// /// The group we attempted to join /// Whether we joined the group or not public delegate void JoinGroupCallback(LLUUID groupID, bool success); /// /// Reply to a request to leave a group, informs whether it was successful or not /// /// The group we attempted to leave /// Whether we left the group or not public delegate void LeaveGroupCallback(LLUUID groupID, bool success); /// /// Informs the avatar that it is no longer a member of a group /// /// The group we are no longer a member of public delegate void GroupDroppedCallback(LLUUID groupID); /// /// /// /// /// /// /// /// /// public delegate void AgentDataCallback(string firstName, string lastName, LLUUID activeGroupID, string groupTitle, ulong groupPowers, string groupName); /// Callback for incoming chat packets public event ChatCallback OnChat; /// Callback for pop-up dialogs from scripts public event ScriptDialogCallback OnScriptDialog; /// Callback for pop-up dialogs regarding permissions public event ScriptQuestionCallback OnScriptQuestion; /// Callback for incoming IMs public event InstantMessageCallback OnInstantMessage; /// Callback for Teleport request update public event TeleportCallback OnTeleport; /// Callback for incoming change in L$ balance public event BalanceCallback OnBalanceUpdated; /// Callback for incoming Money Balance Replies public event MoneyBalanceReplyCallback OnMoneyBalanceReplyReceived; /// Callback reply for agent data updates, such as the active /// group changing public event AgentDataCallback OnAgentDataUpdated; #endregion #region Public Members /// Reference to the SecondLife client object public SecondLife Client; // FIXME: Most all of these should change from public variables to read-only public properties /// Your (client) avatar UUID public LLUUID ID; /// Your (client) avatar ID, local to the current region/sim public uint LocalID; /// Where the avatar started at login. Can be "last", "home" /// or a login URI public string StartLocation = String.Empty; /// The access level of this agent, usually M or PG public string AgentAccess = String.Empty; /// Positive and negative ratings /// This information is read-only and any changes will not be /// reflected on the server public Avatar.Statistics ProfileStatistics; /// Avatar properties including about text, profile URL, image IDs and /// publishing settings /// If you change fields in this struct, the changes will not /// be reflected on the server until you call SetAvatarInformation public Avatar.AvatarProperties ProfileProperties; /// Avatar interests including spoken languages, skills, and "want to" /// choices /// If you change fields in this struct, the changes will not /// be reflected on the server until you call SetAvatarInformation public Avatar.Interests ProfileInterests; /// Current position of avatar public LLVector3 Position; /// Current rotation of avatar public LLQuaternion Rotation = LLQuaternion.Identity; /// public LLVector4 CollisionPlane; /// public LLVector3 Velocity; /// public LLVector3 Acceleration; /// public LLVector3 AngularVelocity; /// The point the avatar is currently looking at /// (may not stay updated) public LLVector3 LookAt; /// Position avatar client will goto when login to 'home' or during /// teleport request to 'home' region. public LLVector3 HomePosition; /// LookAt point saved/restored with HomePosition public LLVector3 HomeLookAt; /// Used for camera and control key state tracking public MainAvatarStatus Status; /// The UUID of your root inventory folder public LLUUID InventoryRootFolderUUID; /// Avatar First Name (i.e. Philip) public string FirstName { get { return firstName; } } /// Avatar Last Name (i.e. Linden) public string LastName { get { return lastName; } } /// Avatar Full Name (i.e. Philip Linden) public string Name { get { // This is a fairly common request, so assume the name doesn't // change mid-session and cache the result if (fullName == null) fullName = String.Format("{0} {1}", firstName, lastName); return fullName; } } /// Gets the health of the agent public float Health { get { return health; } } /// Gets the current balance of the agent public int Balance { get { return balance; } } /// Gets the local ID of the prim the avatar is sitting on, /// zero if the avatar is not currently sitting public uint SittingOn { get { return sittingOn; } } /// Gets the UUID of the active group. public LLUUID ActiveGroup { get { return activeGroup; } } /// Current status message for teleporting public string TeleportMessage { get { return teleportMessage; } } /// Returns the global grid position of the avatar public LLVector3d GlobalPosition { get { if (Client.Network.CurrentSim != null) { uint globalX, globalY; Helpers.LongToUInts(Client.Network.CurrentSim.Handle, out globalX, out globalY); return new LLVector3d( (double)globalX + (double)Position.X, (double)globalY + (double)Position.Y, (double)Position.Z); } else return LLVector3d.Zero; } } #endregion Public Members internal string firstName = String.Empty; internal string lastName = String.Empty; internal string teleportMessage = String.Empty; internal uint sittingOn; internal DateTime lastInterpolation; private string fullName; private TeleportStatus TeleportStat = TeleportStatus.None; private ManualResetEvent TeleportEvent = new ManualResetEvent(false); private uint HeightWidthGenCounter; private float health; private int balance; private LLUUID activeGroup; #region AgentUpdate Constants private const int CONTROL_AT_POS_INDEX = 0; private const int CONTROL_AT_NEG_INDEX = 1; private const int CONTROL_LEFT_POS_INDEX = 2; private const int CONTROL_LEFT_NEG_INDEX = 3; private const int CONTROL_UP_POS_INDEX = 4; private const int CONTROL_UP_NEG_INDEX = 5; private const int CONTROL_PITCH_POS_INDEX = 6; private const int CONTROL_PITCH_NEG_INDEX = 7; private const int CONTROL_YAW_POS_INDEX = 8; private const int CONTROL_YAW_NEG_INDEX = 9; private const int CONTROL_FAST_AT_INDEX = 10; private const int CONTROL_FAST_LEFT_INDEX = 11; private const int CONTROL_FAST_UP_INDEX = 12; private const int CONTROL_FLY_INDEX = 13; private const int CONTROL_STOP_INDEX = 14; private const int CONTROL_FINISH_ANIM_INDEX = 15; private const int CONTROL_STAND_UP_INDEX = 16; private const int CONTROL_SIT_ON_GROUND_INDEX = 17; private const int CONTROL_MOUSELOOK_INDEX = 18; private const int CONTROL_NUDGE_AT_POS_INDEX = 19; private const int CONTROL_NUDGE_AT_NEG_INDEX = 20; private const int CONTROL_NUDGE_LEFT_POS_INDEX = 21; private const int CONTROL_NUDGE_LEFT_NEG_INDEX = 22; private const int CONTROL_NUDGE_UP_POS_INDEX = 23; private const int CONTROL_NUDGE_UP_NEG_INDEX = 24; private const int CONTROL_TURN_LEFT_INDEX = 25; private const int CONTROL_TURN_RIGHT_INDEX = 26; private const int CONTROL_AWAY_INDEX = 27; private const int CONTROL_LBUTTON_DOWN_INDEX = 28; private const int CONTROL_LBUTTON_UP_INDEX = 29; private const int CONTROL_ML_LBUTTON_DOWN_INDEX = 30; private const int CONTROL_ML_LBUTTON_UP_INDEX = 31; private const int TOTAL_CONTROLS = 32; #endregion AgentUpdate Constants /// /// Constructor, setup callbacks for packets related to our avatar /// /// public MainAvatar(SecondLife client) { Client = client; Status = new MainAvatarStatus(Client); NetworkManager.PacketCallback callback; Client.Network.OnDisconnected += new NetworkManager.DisconnectedCallback(Network_OnDisconnected); // Teleport callbacks callback = new NetworkManager.PacketCallback(TeleportHandler); Client.Network.RegisterCallback(PacketType.TeleportStart, callback); Client.Network.RegisterCallback(PacketType.TeleportProgress, callback); Client.Network.RegisterCallback(PacketType.TeleportFailed, callback); Client.Network.RegisterCallback(PacketType.TeleportFinish, callback); Client.Network.RegisterCallback(PacketType.TeleportCancel, callback); Client.Network.RegisterCallback(PacketType.TeleportLocal, callback); // Instant Message callback Client.Network.RegisterCallback(PacketType.ImprovedInstantMessage, new NetworkManager.PacketCallback(InstantMessageHandler)); // Chat callback Client.Network.RegisterCallback(PacketType.ChatFromSimulator, new NetworkManager.PacketCallback(ChatHandler)); // Script dialog callback Client.Network.RegisterCallback(PacketType.ScriptDialog, new NetworkManager.PacketCallback(ScriptDialogHandler)); // Script question callback Client.Network.RegisterCallback(PacketType.ScriptQuestion, new NetworkManager.PacketCallback(ScriptQuestionHandler)); // Movement complete callback Client.Network.RegisterCallback(PacketType.AgentMovementComplete, new NetworkManager.PacketCallback(MovementCompleteHandler)); // Health callback Client.Network.RegisterCallback(PacketType.HealthMessage, new NetworkManager.PacketCallback(HealthHandler)); // Money callbacks callback = new NetworkManager.PacketCallback(BalanceHandler); Client.Network.RegisterCallback(PacketType.MoneyBalanceReply, callback); //Agent Update Callback Client.Network.RegisterCallback(PacketType.AgentDataUpdate, new NetworkManager.PacketCallback(AgentDataUpdateHandler)); // CAPS callbacks Client.Network.RegisterEventCallback("TeleportFinish", new Capabilities.EventQueueCallback(TeleportFinishEventHandler)); Client.Network.RegisterEventCallback("EstablishAgentCommunication", new Capabilities.EventQueueCallback(EstablishAgentCommunicationEventHandler)); } /// /// Send an Instant Message /// /// Target of the Instant Message /// Text message being sent public void InstantMessage(LLUUID target, string message) { InstantMessage(Name, target, message, LLUUID.Random(), InstantMessageDialog.MessageFromAgent, InstantMessageOnline.Offline, this.Position, LLUUID.Zero, new byte[0]); } /// /// Send an Instant Message /// /// Target of the Instant Message /// Text message being sent /// IM session ID (to differentiate between IM windows) public void InstantMessage(LLUUID target, string message, LLUUID imSessionID) { InstantMessage(Name, target, message, imSessionID, InstantMessageDialog.MessageFromAgent, InstantMessageOnline.Offline, this.Position, LLUUID.Zero, new byte[0]); } /// /// Send an Instant Message /// /// The name this IM will show up as being from /// Key of Avatar /// Text message being sent /// IM session ID (to differentiate between IM windows) /// public void InstantMessage(string fromName, LLUUID target, string message, LLUUID imSessionID, LLUUID[] conferenceIDs) { byte[] binaryBucket; if (conferenceIDs != null && conferenceIDs.Length > 0) { binaryBucket = new byte[16 * conferenceIDs.Length]; for (int i = 0; i < conferenceIDs.Length; ++i) Buffer.BlockCopy(conferenceIDs[i].Data, 0, binaryBucket, i * 16, 16); } else { binaryBucket = new byte[0]; } InstantMessage(fromName, target, message, imSessionID, InstantMessageDialog.MessageFromAgent, InstantMessageOnline.Offline, LLVector3.Zero, LLUUID.Zero, binaryBucket); } /// /// Send an Instant Message /// /// The name this IM will show up as being from /// Key of Avatar /// Text message being sent /// IM session ID (to differentiate between IM windows) /// Type of instant message to send /// Whether to IM offline avatars as well /// /// /// Packed binary data that is specific to /// the dialog type public void InstantMessage(string fromName, LLUUID target, string message, LLUUID imSessionID, InstantMessageDialog dialog, InstantMessageOnline offline, LLVector3 position, LLUUID regionID, byte[] binaryBucket) { ImprovedInstantMessagePacket im = new ImprovedInstantMessagePacket(); im.AgentData.AgentID = Client.Network.AgentID; im.AgentData.SessionID = Client.Network.SessionID; im.MessageBlock.Dialog = (byte)dialog; im.MessageBlock.FromAgentName = Helpers.StringToField(fromName); im.MessageBlock.FromGroup = false; im.MessageBlock.ID = imSessionID; im.MessageBlock.Message = Helpers.StringToField(message); im.MessageBlock.Offline = (byte)offline; im.MessageBlock.ToAgentID = target; if (binaryBucket != null) im.MessageBlock.BinaryBucket = binaryBucket; else im.MessageBlock.BinaryBucket = new byte[0]; // These fields are mandatory, even if we don't have valid values for them im.MessageBlock.Position = LLVector3.Zero; //TODO: Allow region id to be correctly set by caller or fetched from Client.* im.MessageBlock.RegionID = regionID; // Send the message Client.Network.SendPacket(im); } /// /// Send an Instant Message to a group /// /// Key of Group /// Text Message being sent. public void InstantMessageGroup(LLUUID groupUUID, string message) { InstantMessageGroup(Name, groupUUID, message); } /// /// Send an Instant Message to a group /// /// The name this IM will show up as being from /// Key of the group /// Text message being sent /// This does not appear to function with groups the agent is not in public void InstantMessageGroup(string fromName, LLUUID groupUUID, string message) { ImprovedInstantMessagePacket im = new ImprovedInstantMessagePacket(); im.AgentData.AgentID = Client.Network.AgentID; im.AgentData.SessionID = Client.Network.SessionID; im.MessageBlock.Dialog = (byte)InstantMessageDialog.SessionSend; im.MessageBlock.FromAgentName = Helpers.StringToField(fromName); im.MessageBlock.FromGroup = false; im.MessageBlock.Message = Helpers.StringToField(message); im.MessageBlock.Offline = 0; im.MessageBlock.ID = groupUUID; im.MessageBlock.ToAgentID = groupUUID; im.MessageBlock.BinaryBucket = new byte[0]; im.MessageBlock.Position = LLVector3.Zero; im.MessageBlock.RegionID = LLUUID.Zero; // Send the message Client.Network.SendPacket(im); } /// /// /// /// /// /// /// /// public void PointAtEffect(LLUUID sourceAvatar, LLUUID targetObject, LLVector3d globalOffset, PointAtType type, LLUUID effectID) { ViewerEffectPacket effect = new ViewerEffectPacket(); effect.AgentData.AgentID = Client.Network.AgentID; effect.AgentData.SessionID = Client.Network.SessionID; effect.Effect = new ViewerEffectPacket.EffectBlock[1]; effect.Effect[0] = new ViewerEffectPacket.EffectBlock(); effect.Effect[0].AgentID = Client.Network.AgentID; effect.Effect[0].Color = LLColor.Black.GetBytes(); effect.Effect[0].Duration = (type == PointAtType.Clear) ? 0.0f : Single.MaxValue / 4.0f; effect.Effect[0].ID = effectID; effect.Effect[0].Type = (byte)EffectType.PointAt; byte[] typeData = new byte[57]; if (sourceAvatar != null) Buffer.BlockCopy(sourceAvatar.GetBytes(), 0, typeData, 0, 16); if (targetObject != null) Buffer.BlockCopy(targetObject.GetBytes(), 0, typeData, 16, 16); Buffer.BlockCopy(globalOffset.GetBytes(), 0, typeData, 32, 24); typeData[56] = (byte)type; effect.Effect[0].TypeData = typeData; Client.Network.SendPacket(effect); } /// /// /// /// /// /// /// /// public void LookAtEffect(LLUUID sourceAvatar, LLUUID targetObject, LLVector3d globalOffset, LookAtType type, LLUUID effectID) { ViewerEffectPacket effect = new ViewerEffectPacket(); effect.AgentData.AgentID = Client.Network.AgentID; effect.AgentData.SessionID = Client.Network.SessionID; float duration; switch (type) { case LookAtType.Clear: duration = 0.0f; break; case LookAtType.Hover: duration = 1.0f; break; case LookAtType.FreeLook: duration = 2.0f; break; case LookAtType.Idle: duration = 3.0f; break; case LookAtType.AutoListen: case LookAtType.Respond: duration = 4.0f; break; case LookAtType.None: case LookAtType.Select: case LookAtType.Focus: case LookAtType.Mouselook: duration = Single.MaxValue / 2.0f; break; default: duration = 0.0f; break; } effect.Effect = new ViewerEffectPacket.EffectBlock[1]; effect.Effect[0] = new ViewerEffectPacket.EffectBlock(); effect.Effect[0].AgentID = Client.Network.AgentID; effect.Effect[0].Color = LLColor.Black.GetBytes(); effect.Effect[0].Duration = duration; effect.Effect[0].ID = effectID; effect.Effect[0].Type = (byte)EffectType.LookAt; byte[] typeData = new byte[57]; if (sourceAvatar != null) Buffer.BlockCopy(sourceAvatar.GetBytes(), 0, typeData, 0, 16); if (targetObject != null) Buffer.BlockCopy(targetObject.GetBytes(), 0, typeData, 16, 16); typeData[56] = (byte)type; effect.Effect[0].TypeData = typeData; Client.Network.SendPacket(effect); } /// /// /// /// /// /// /// /// /// public void BeamEffect(LLUUID sourceAvatar, LLUUID targetObject, LLVector3d globalOffset, LLColor color, float duration, LLUUID effectID) { ViewerEffectPacket effect = new ViewerEffectPacket(); effect.AgentData.AgentID = Client.Network.AgentID; effect.AgentData.SessionID = Client.Network.SessionID; effect.Effect = new ViewerEffectPacket.EffectBlock[1]; effect.Effect[0] = new ViewerEffectPacket.EffectBlock(); effect.Effect[0].AgentID = Client.Network.AgentID; effect.Effect[0].Color = color.GetBytes(); effect.Effect[0].Duration = duration; effect.Effect[0].ID = effectID; effect.Effect[0].Type = (byte)EffectType.Beam; byte[] typeData = new byte[56]; if (sourceAvatar != null) Buffer.BlockCopy(sourceAvatar.GetBytes(), 0, typeData, 0, 16); if (targetObject != null) Buffer.BlockCopy(targetObject.GetBytes(), 0, typeData, 16, 16); Buffer.BlockCopy(globalOffset.GetBytes(), 0, typeData, 32, 24); effect.Effect[0].TypeData = typeData; Client.Network.SendPacket(effect); } /// /// Synchronize the local profile and interests information to the server /// public void SetAvatarInformation() { // Basic profile properties AvatarPropertiesUpdatePacket apup = new AvatarPropertiesUpdatePacket(); apup.AgentData.AgentID = this.ID; apup.AgentData.SessionID = Client.Network.SessionID; apup.PropertiesData.AboutText = Helpers.StringToField(this.ProfileProperties.AboutText); apup.PropertiesData.AllowPublish = this.ProfileProperties.AllowPublish; apup.PropertiesData.FLAboutText = Helpers.StringToField(this.ProfileProperties.FirstLifeText); apup.PropertiesData.FLImageID = this.ProfileProperties.FirstLifeImage; apup.PropertiesData.ImageID = this.ProfileProperties.ProfileImage; apup.PropertiesData.MaturePublish = this.ProfileProperties.MaturePublish; apup.PropertiesData.ProfileURL = Helpers.StringToField(this.ProfileProperties.ProfileURL); Client.Network.SendPacket(apup); // Interests AvatarInterestsUpdatePacket aiup = new AvatarInterestsUpdatePacket(); aiup.AgentData.AgentID = this.ID; aiup.AgentData.SessionID = Client.Network.SessionID; aiup.PropertiesData.LanguagesText = Helpers.StringToField(this.ProfileInterests.LanguagesText); aiup.PropertiesData.SkillsMask = this.ProfileInterests.SkillsMask; aiup.PropertiesData.SkillsText = Helpers.StringToField(this.ProfileInterests.SkillsText); aiup.PropertiesData.WantToMask = this.ProfileInterests.WantToMask; aiup.PropertiesData.WantToText = Helpers.StringToField(this.ProfileInterests.WantToText); Client.Network.SendPacket(aiup); } /// /// Send a chat message /// /// The Message you're sending out. /// Channel number (0 would be default 'Say' message, other numbers /// denote the equivalent of /# in normal client). /// Chat Type, see above. public void Chat(string message, int channel, ChatType type) { ChatFromViewerPacket chat = new ChatFromViewerPacket(); chat.AgentData.AgentID = this.ID; chat.AgentData.SessionID = Client.Network.SessionID; chat.ChatData.Channel = channel; chat.ChatData.Message = Helpers.StringToField(message); chat.ChatData.Type = (byte)type; Client.Network.SendPacket(chat); } /// /// Set the height and the width of the client window. This is used /// by the server to build a virtual camera frustum for our avatar /// /// New height of the viewer window /// New width of the viewer window public void SetHeightWidth(ushort height, ushort width) { AgentHeightWidthPacket heightwidth = new AgentHeightWidthPacket(); heightwidth.AgentData.AgentID = Client.Network.AgentID; heightwidth.AgentData.SessionID = Client.Network.SessionID; heightwidth.AgentData.CircuitCode = Client.Network.CircuitCode; heightwidth.HeightWidthBlock.Height = height; heightwidth.HeightWidthBlock.Width = width; heightwidth.HeightWidthBlock.GenCounter = HeightWidthGenCounter++; Client.Network.SendPacket(heightwidth); } /// /// Sends a request to sit on the specified object /// /// LLUUID of the object to sit on /// Sit at offset public void RequestSit(LLUUID targetID, LLVector3 offset) { AgentRequestSitPacket requestSit = new AgentRequestSitPacket(); requestSit.AgentData.AgentID = Client.Network.AgentID; requestSit.AgentData.SessionID = Client.Network.SessionID; requestSit.TargetObject.TargetID = targetID; requestSit.TargetObject.Offset = offset; Client.Network.SendPacket(requestSit); } /// /// Request the list of muted things for this avatar /// public void RequestMuteList() { MuteListRequestPacket mute = new MuteListRequestPacket(); mute.AgentData.AgentID = Client.Network.AgentID; mute.AgentData.SessionID = Client.Network.SessionID; mute.MuteData.MuteCRC = 0; Client.Network.SendPacket(mute); } /// /// Request the current L$ balance /// public void RequestBalance() { MoneyBalanceRequestPacket money = new MoneyBalanceRequestPacket(); money.AgentData.AgentID = Client.Network.AgentID; money.AgentData.SessionID = Client.Network.SessionID; money.MoneyData.TransactionID = LLUUID.Zero; Client.Network.SendPacket(money); } /// /// Sets home location /// public void SetHome() { SetStartLocationRequestPacket s = new SetStartLocationRequestPacket(); s.AgentData = new SetStartLocationRequestPacket.AgentDataBlock(); s.AgentData.AgentID = Client.Network.AgentID; s.AgentData.SessionID = Client.Network.SessionID; s.StartLocationData = new SetStartLocationRequestPacket.StartLocationDataBlock(); s.StartLocationData.LocationPos = Client.Self.Position; s.StartLocationData.LocationID = 1; s.StartLocationData.SimName = Helpers.StringToField(""); s.StartLocationData.LocationLookAt = Client.Self.LookAt; Client.Network.SendPacket(s); } /// /// Teleports the avatar home /// public bool GoHome() { return Teleport(new LLUUID()); } /// /// Follows a call to RequestSit() to actually sit on the object /// public void Sit() { AgentSitPacket sit = new AgentSitPacket(); sit.AgentData.AgentID = Client.Network.AgentID; sit.AgentData.SessionID = Client.Network.SessionID; Client.Network.SendPacket(sit); } /// /// Does a "ground sit" at the avatar's current position /// public bool SitOnGround() { if (Client.Settings.SEND_AGENT_UPDATES) { Client.Self.Status.SitOnGround = true; Client.Self.Status.SendUpdate(); Client.Self.Status.SitOnGround = false; Client.Self.Status.SendUpdate(); return true; } else { Client.Log("Attempted SitOnGround but agent updates are disabled", Helpers.LogLevel.Warning); return false; } } /// /// Starts crouching (begin holding the crouch key) /// public bool StartCrouch() { if (Client.Settings.SEND_AGENT_UPDATES) { Client.Self.Status.UpNeg = true; Client.Self.Status.SendUpdate(); return true; } else { Client.Log("Attempted StartCrouch but agent updates are disabled", Helpers.LogLevel.Warning); return false; } } /// /// Finishes crouching (releases the crouch key) /// public bool StopCrouch() { if (Client.Settings.SEND_AGENT_UPDATES) { Client.Self.Status.UpNeg = false; Client.Self.Status.SendUpdate(); return true; } else { Client.Log("Attempted StopCrouch but agent updates are disabled", Helpers.LogLevel.Warning); return false; } } /// /// Starts a jump (begin holding the jump key) /// public bool StartJump() { if (Client.Settings.SEND_AGENT_UPDATES) { Client.Self.Status.UpPos = true; Client.Self.Status.SendUpdate(); return true; } else { Client.Log("Attempted StartJump but agent updates are disabled", Helpers.LogLevel.Warning); return false; } } /// /// Finishes a jump (release the jump key) /// public bool StopJump() { if (Client.Settings.SEND_AGENT_UPDATES) { Client.Self.Status.UpPos = false; Client.Self.Status.FinishAnim = true; Client.Self.Status.SendUpdate(); Client.Self.Status.FinishAnim = false; Client.Self.Status.SendUpdate(); return true; } else { Client.Log("Attempted StopJump but agent updates are disabled", Helpers.LogLevel.Warning); return false; } } /// /// Give Money to destination Avatar /// /// UUID of the Target Avatar /// Amount in L$ public void GiveAvatarMoney(LLUUID target, int amount) { GiveMoney(target, amount, String.Empty, MoneyTransactionType.Gift, TransactionFlags.None); } /// /// Give Money to destination Avatar /// /// UUID of the Target Avatar /// Amount in L$ /// Description that will show up in the /// recipients transaction history public void GiveAvatarMoney(LLUUID target, int amount, string description) { GiveMoney(target, amount, description, MoneyTransactionType.Gift, TransactionFlags.None); } /// /// /// /// /// /// public void GiveObjectMoney(LLUUID target, int amount, string objectName) { GiveMoney(target, amount, objectName, MoneyTransactionType.PayObject, TransactionFlags.None); } /// /// /// /// /// public void GiveGroupMoney(LLUUID target, int amount) { GiveMoney(target, amount, String.Empty, MoneyTransactionType.Gift, TransactionFlags.DestGroup); } /// /// /// /// /// /// public void GiveGroupMoney(LLUUID target, int amount, string description) { GiveMoney(target, amount, description, MoneyTransactionType.Gift, TransactionFlags.DestGroup); } /// /// /// public void PayUploadFee() { GiveMoney(LLUUID.Zero, Client.Settings.UPLOAD_COST, String.Empty, MoneyTransactionType.UploadCharge, TransactionFlags.None); } /// /// /// /// public void PayUploadFee(string description) { GiveMoney(LLUUID.Zero, Client.Settings.UPLOAD_COST, description, MoneyTransactionType.UploadCharge, TransactionFlags.None); } /// /// Give Money to destionation Object or Avatar /// /// UUID of the Target Object/Avatar /// Amount in L$ /// Reason (Optional normally) /// The type of transaction /// Transaction flags, mostly for identifying group /// transactions public void GiveMoney(LLUUID target, int amount, string description, MoneyTransactionType type, TransactionFlags flags) { MoneyTransferRequestPacket money = new MoneyTransferRequestPacket(); money.AgentData.AgentID = this.ID; money.AgentData.SessionID = Client.Network.SessionID; money.MoneyData.Description = Helpers.StringToField(description); money.MoneyData.DestID = target; money.MoneyData.SourceID = this.ID; money.MoneyData.TransactionType = (int)type; money.MoneyData.AggregatePermInventory = 0; // This is weird, apparently always set to zero though money.MoneyData.AggregatePermNextOwner = 0; // This is weird, apparently always set to zero though money.MoneyData.Flags = (byte)flags; money.MoneyData.Amount = amount; Client.Network.SendPacket(money); } /// /// Send an AgentAnimation packet that toggles a single animation on /// /// The animation to start playing public void AnimationStart(LLUUID animation) { Dictionary animations = new Dictionary(); animations[animation] = true; Animate(animations); } /// /// Send an AgentAnimation packet that toggles a single animation off /// /// The animation to stop playing public void AnimationStop(LLUUID animation) { Dictionary animations = new Dictionary(); animations[animation] = false; Animate(animations); } /// /// Send an AgentAnimation packet that will toggle animations on or off /// /// A list of animation UUIDs, and whether to /// turn that animation on or off public void Animate(Dictionary animations) { AgentAnimationPacket animate = new AgentAnimationPacket(); animate.AgentData.AgentID = Client.Network.AgentID; animate.AgentData.SessionID = Client.Network.SessionID; animate.AnimationList = new AgentAnimationPacket.AnimationListBlock[animations.Count]; int i = 0; foreach (KeyValuePair animation in animations) { animate.AnimationList[i] = new AgentAnimationPacket.AnimationListBlock(); animate.AnimationList[i].AnimID = animation.Key; animate.AnimationList[i].StartAnim = animation.Value; i++; } Client.Network.SendPacket(animate); } public void AutoPilot(double globalX, double globalY, double z) { GenericMessagePacket autopilot = new GenericMessagePacket(); autopilot.AgentData.AgentID = Client.Network.AgentID; autopilot.AgentData.SessionID = Client.Network.SessionID; autopilot.AgentData.TransactionID = LLUUID.Zero; autopilot.MethodData.Invoice = LLUUID.Zero; autopilot.MethodData.Method = Helpers.StringToField("autopilot"); autopilot.ParamList = new GenericMessagePacket.ParamListBlock[3]; autopilot.ParamList[0] = new GenericMessagePacket.ParamListBlock(); autopilot.ParamList[0].Parameter = Helpers.StringToField(globalX.ToString()); autopilot.ParamList[1] = new GenericMessagePacket.ParamListBlock(); autopilot.ParamList[1].Parameter = Helpers.StringToField(globalY.ToString()); autopilot.ParamList[2] = new GenericMessagePacket.ParamListBlock(); autopilot.ParamList[2].Parameter = Helpers.StringToField(z.ToString()); Client.Network.SendPacket(autopilot); } /// /// Use the autopilot sim function to move the avatar to a new position /// /// The z value is currently not handled properly by the simulator /// Integer value for the global X coordinate to move to /// Integer value for the global Y coordinate to move to /// Floating-point value for the Z coordinate to move to public void AutoPilot(ulong globalX, ulong globalY, float z) { GenericMessagePacket autopilot = new GenericMessagePacket(); autopilot.AgentData.AgentID = Client.Network.AgentID; autopilot.AgentData.SessionID = Client.Network.SessionID; autopilot.AgentData.TransactionID = LLUUID.Zero; autopilot.MethodData.Invoice = LLUUID.Zero; autopilot.MethodData.Method = Helpers.StringToField("autopilot"); autopilot.ParamList = new GenericMessagePacket.ParamListBlock[3]; autopilot.ParamList[0] = new GenericMessagePacket.ParamListBlock(); autopilot.ParamList[0].Parameter = Helpers.StringToField(globalX.ToString()); autopilot.ParamList[1] = new GenericMessagePacket.ParamListBlock(); autopilot.ParamList[1].Parameter = Helpers.StringToField(globalY.ToString()); autopilot.ParamList[2] = new GenericMessagePacket.ParamListBlock(); autopilot.ParamList[2].Parameter = Helpers.StringToField(z.ToString()); Client.Network.SendPacket(autopilot); } /// /// Use the autopilot sim function to move the avatar to a new position /// /// The z value is currently not handled properly by the simulator /// Integer value for the local X coordinate to move to /// Integer value for the local Y coordinate to move to /// Floating-point value for the Z coordinate to move to public void AutoPilotLocal(int localX, int localY, float z) { uint x, y; Helpers.LongToUInts(Client.Network.CurrentSim.Handle, out x, out y); AutoPilot((ulong)(x + localX), (ulong)(y + localY), z); } /// Cancels autopilot sim function /// Not certain if this is how it is really done public bool AutoPilotCancel() { if (Client.Settings.SEND_AGENT_UPDATES) { Client.Self.Status.AtPos = true; Client.Self.Status.SendUpdate(); Client.Self.Status.AtPos = false; Client.Self.Status.SendUpdate(); return true; } else { Client.Log("Attempted AutoPilotCancel but agent updates are disabled", Helpers.LogLevel.Warning); return false; } } /// Requests missed/offline messages public void RetrieveInstantMessages() { RetrieveInstantMessagesPacket p = new RetrieveInstantMessagesPacket(); p.AgentData.AgentID = Client.Network.AgentID; p.AgentData.SessionID = Client.Network.SessionID; Client.Network.SendPacket(p); } /// Stands up from sitting on a prim or the ground public bool Stand() { if (Client.Settings.SEND_AGENT_UPDATES) { Client.Self.Status.StandUp = true; Client.Self.Status.SendUpdate(); Client.Self.Status.StandUp = false; Client.Self.Status.SendUpdate(); return true; } else { Client.Log("Attempted Stand but agent updates are disabled", Helpers.LogLevel.Warning); return false; } } /// Attempt teleport to specified LLUUID public bool Teleport(LLUUID landmark) { TeleportStat = TeleportStatus.None; TeleportEvent.Reset(); TeleportLandmarkRequestPacket p = new TeleportLandmarkRequestPacket(); p.Info = new TeleportLandmarkRequestPacket.InfoBlock(); p.Info.AgentID = Client.Network.AgentID; p.Info.SessionID = Client.Network.SessionID; p.Info.LandmarkID = landmark; Client.Network.SendPacket(p); TeleportEvent.WaitOne(Client.Settings.TELEPORT_TIMEOUT, false); if (TeleportStat == TeleportStatus.None || TeleportStat == TeleportStatus.Start || TeleportStat == TeleportStatus.Progress) { teleportMessage = "Teleport timed out."; TeleportStat = TeleportStatus.Failed; } return (TeleportStat == TeleportStatus.Finished); } /// /// Attempt to look up a simulator name and teleport to the discovered /// destination /// /// Region name to look up /// Position to teleport to /// True if the lookup and teleport were successful, otherwise /// false public bool Teleport(string simName, LLVector3 position) { return Teleport(simName, position, new LLVector3(0, 1.0f, 0)); } /// /// Attempt to look up a simulator name and teleport to the discovered /// destination /// /// Region name to look up /// Position to teleport to /// Target to look at /// True if the lookup and teleport were successful, otherwise /// false public bool Teleport(string simName, LLVector3 position, LLVector3 lookAt) { TeleportStat = TeleportStatus.None; simName = simName.ToLower(); if (simName != Client.Network.CurrentSim.Name.ToLower()) { // Teleporting to a foreign sim GridRegion region; if (Client.Grid.GetGridRegion(simName, out region)) { return Teleport(region.RegionHandle, position, lookAt); } else { teleportMessage = "Unable to resolve name: " + simName; TeleportStat = TeleportStatus.Failed; return false; } } else { // Teleporting to the sim we're already in return Teleport(Client.Network.CurrentSim.Handle, position, lookAt); } } /// /// Start a teleport process /// /// /// Position for Teleport /// public bool Teleport(ulong regionHandle, LLVector3 position) { return Teleport(regionHandle, position, new LLVector3(0.0f, 1.0f, 0.0f)); } /// /// Start a teleport process /// /// /// Position for Teleport /// Target to look at /// public bool Teleport(ulong regionHandle, LLVector3 position, LLVector3 lookAt) { TeleportStat = TeleportStatus.None; TeleportEvent.Reset(); RequestTeleport(regionHandle, position, lookAt); TeleportEvent.WaitOne(Client.Settings.TELEPORT_TIMEOUT, false); if (TeleportStat == TeleportStatus.None || TeleportStat == TeleportStatus.Start || TeleportStat == TeleportStatus.Progress) { teleportMessage = "Teleport timed out."; TeleportStat = TeleportStatus.Failed; } return (TeleportStat == TeleportStatus.Finished); } /// /// Start a teleport process /// /// /// Position for Teleport public void RequestTeleport(ulong regionHandle, LLVector3 position) { RequestTeleport(regionHandle, position, new LLVector3(0.0f, 1.0f, 0.0f)); } /// /// Start a teleport process /// /// /// Position for Teleport /// Target to look at public void RequestTeleport(ulong regionHandle, LLVector3 position, LLVector3 lookAt) { if (Client.Network.CurrentSim != null && Client.Network.CurrentSim.Caps != null && Client.Network.CurrentSim.Caps.IsEventQueueRunning) { TeleportLocationRequestPacket teleport = new TeleportLocationRequestPacket(); teleport.AgentData.AgentID = Client.Network.AgentID; teleport.AgentData.SessionID = Client.Network.SessionID; teleport.Info.LookAt = lookAt; teleport.Info.Position = position; teleport.Info.RegionHandle = regionHandle; Client.Log("Requesting teleport to region handle " + regionHandle.ToString(), Helpers.LogLevel.Info); Client.Network.SendPacket(teleport); } else { teleportMessage = "CAPS event queue is not running"; TeleportEvent.Set(); TeleportStat = TeleportStatus.Failed; } } public void SendTeleportLure(LLUUID targetID) { SendTeleportLure(targetID, "Join me in " + Client.Network.CurrentSim.Name + "!"); } public void SendTeleportLure(LLUUID targetID, string message) { StartLurePacket p = new StartLurePacket(); p.AgentData.AgentID = Client.Self.ID; p.AgentData.SessionID = Client.Network.SessionID; p.Info.LureType = 0; p.Info.Message = Helpers.StringToField(message); p.TargetData = new StartLurePacket.TargetDataBlock[] { new StartLurePacket.TargetDataBlock() }; p.TargetData[0].TargetID = targetID; Client.Network.SendPacket(p); } /// /// Respond to a teleport lure by either accepting it and initiating /// the teleport, or denying it /// /// UUID of the avatar requesting the teleport /// Accept the teleport request or deny it public void TeleportLureRespond(LLUUID requesterID, bool accept) { InstantMessage(Name, requesterID, String.Empty, LLUUID.Random(), accept ? InstantMessageDialog.AcceptTeleport : InstantMessageDialog.DenyTeleport, InstantMessageOnline.Offline, this.Position, LLUUID.Zero, new byte[0]); if (accept) { TeleportLureRequestPacket lure = new TeleportLureRequestPacket(); lure.Info.AgentID = Client.Network.AgentID; lure.Info.SessionID = Client.Network.SessionID; lure.Info.LureID = Client.Network.AgentID; lure.Info.TeleportFlags = (uint)TeleportFlags.ViaLure; Client.Network.SendPacket(lure); } } /// /// Grabs an object /// /// Local ID of Object to grab public void Grab(uint objectLocalID) { ObjectGrabPacket grab = new ObjectGrabPacket(); grab.AgentData.AgentID = Client.Network.AgentID; grab.AgentData.SessionID = Client.Network.SessionID; grab.ObjectData.LocalID = objectLocalID; grab.ObjectData.GrabOffset = new LLVector3(0, 0, 0); Client.Network.SendPacket(grab); } /// /// Drags on an object /// /// Strangely, LLUID instead of local ID /// Drag target in region coordinates public void GrabUpdate(LLUUID objectID, LLVector3 grabPosition) { ObjectGrabUpdatePacket grab = new ObjectGrabUpdatePacket(); grab.AgentData.AgentID = Client.Network.AgentID; grab.AgentData.SessionID = Client.Network.SessionID; grab.ObjectData.ObjectID = objectID; grab.ObjectData.GrabOffsetInitial = new LLVector3(0, 0, 0); grab.ObjectData.GrabPosition = grabPosition; grab.ObjectData.TimeSinceLast = 0; Client.Network.SendPacket(grab); } /// /// Releases a grabbed object /// public void DeGrab(uint objectLocalID) { ObjectDeGrabPacket degrab = new ObjectDeGrabPacket(); degrab.AgentData.AgentID = Client.Network.AgentID; degrab.AgentData.SessionID = Client.Network.SessionID; degrab.ObjectData.LocalID = objectLocalID; Client.Network.SendPacket(degrab); } /// /// Touches an object /// public void Touch(uint objectLocalID) { Client.Self.Grab(objectLocalID); Client.Self.DeGrab(objectLocalID); } /// /// Rotates body toward target position /// /// Region coordinates to turn toward public bool TurnToward(LLVector3 target) { if (Client.Settings.SEND_AGENT_UPDATES) { LLVector3 myPos = Client.Self.Position; LLVector3 forward = new LLVector3(1, 0, 0); LLVector3 offset = LLVector3.Norm(target - myPos); LLQuaternion newRot = LLVector3.RotBetween(forward, offset); Client.Self.Status.Camera.BodyRotation = newRot; Client.Self.Status.Camera.HeadRotation = newRot; //TODO - include CoordinateFrame for at/left/up camera axes Client.Self.Status.SendUpdate(); return true; } else { Client.Log("Attempted TurnToward but agent updates are disabled", Helpers.LogLevel.Warning); return false; } } /// /// Enters mouselook, presses and releases the left mouse button, and leaves mouselook /// /// public bool Shoot() { if (Client.Settings.SEND_AGENT_UPDATES) { Client.Self.Status.Mouselook = true; Client.Self.Status.MLButtonDown = true; Client.Self.Status.SendUpdate(); Client.Self.Status.MLButtonUp = true; Client.Self.Status.MLButtonDown = false; Client.Self.Status.FinishAnim = true; Client.Self.Status.SendUpdate(); Client.Self.Status.Mouselook = false; Client.Self.Status.MLButtonUp = false; Client.Self.Status.FinishAnim = false; Client.Self.Status.SendUpdate(); return true; } else { Client.Log("Attempted Shoot but agent updates are disabled", Helpers.LogLevel.Warning); return false; } } /// /// Aims at the specified position before shooting /// /// /// public bool Shoot(LLVector3 target) { if (TurnToward(target)) return Shoot(); else return false; } /// /// Request to join a group. If there is an enrollment fee it will /// automatically be deducted from your balance /// /// The group to attempt to join public void RequestJoinGroup(LLUUID groupID) { JoinGroupRequestPacket join = new JoinGroupRequestPacket(); join.AgentData.AgentID = Client.Network.AgentID; join.AgentData.SessionID = Client.Network.SessionID; join.GroupData.GroupID = groupID; Client.Network.SendPacket(join); } /// /// Request to leave a group /// /// The group to attempt to leave public void RequestLeaveGroup(LLUUID groupID) { LeaveGroupRequestPacket leave = new LeaveGroupRequestPacket(); leave.AgentData.AgentID = Client.Network.AgentID; leave.AgentData.SessionID = Client.Network.SessionID; leave.GroupData.GroupID = groupID; Client.Network.SendPacket(leave); } /// /// Set our current active group /// /// The group we are a member of that we want to /// activate public void ActivateGroup(LLUUID groupID) { ActivateGroupPacket activate = new ActivateGroupPacket(); activate.AgentData.AgentID = Client.Network.AgentID; activate.AgentData.SessionID = Client.Network.SessionID; activate.AgentData.GroupID = groupID; Client.Network.SendPacket(activate); } /// /// Move an agent in to a simulator. This packet is the last packet /// needed to complete the transition in to a new simulator /// /// public void CompleteAgentMovement(Simulator simulator) { CompleteAgentMovementPacket move = new CompleteAgentMovementPacket(); move.AgentData.AgentID = Client.Network.AgentID; move.AgentData.SessionID = Client.Network.SessionID; move.AgentData.CircuitCode = Client.Network.CircuitCode; Client.Network.SendPacket(move, simulator); } /// /// Sends camera and action updates to the server including the /// position and orientation of our camera, and a ControlFlags field /// specifying our current movement actions /// /// /// /// /// /// /// /// /// /// public void UpdateCamera(MainAvatar.ControlFlags controlFlags, LLVector3 position, LLVector3 forwardAxis, LLVector3 leftAxis, LLVector3 upAxis, LLQuaternion bodyRotation, LLQuaternion headRotation, float farClip, AgentFlags flags, AgentState state, bool reliable) { AgentUpdatePacket update = new AgentUpdatePacket(); update.AgentData.AgentID = Client.Network.AgentID; update.AgentData.SessionID = Client.Network.SessionID; update.AgentData.BodyRotation = bodyRotation; update.AgentData.HeadRotation = headRotation; update.AgentData.CameraCenter = position; update.AgentData.CameraAtAxis = forwardAxis; update.AgentData.CameraLeftAxis = leftAxis; update.AgentData.CameraUpAxis = upAxis; update.AgentData.Far = farClip; update.AgentData.ControlFlags = (uint)controlFlags; update.AgentData.Flags = (byte)flags; update.AgentData.State = (byte)state; update.Header.Reliable = reliable; Client.Network.SendPacket(update); } /// /// /// /// /// /// /// public void ScriptQuestionReply(Simulator simulator, LLUUID itemID, LLUUID taskID, ScriptPermission permissions) { ScriptAnswerYesPacket yes = new ScriptAnswerYesPacket(); yes.AgentData.AgentID = Client.Network.AgentID; yes.AgentData.SessionID = Client.Network.SessionID; yes.Data.ItemID = itemID; yes.Data.TaskID = taskID; yes.Data.Questions = (int)permissions; Client.Network.SendPacket(yes, simulator); } #region Packet Handlers /// /// Take an incoming ImprovedInstantMessage packet, auto-parse, and if /// OnInstantMessage is defined call that with the appropriate arguments /// /// Incoming ImprovedInstantMessagePacket /// Unused private void InstantMessageHandler(Packet packet, Simulator simulator) { if (packet.Type == PacketType.ImprovedInstantMessage) { ImprovedInstantMessagePacket im = (ImprovedInstantMessagePacket)packet; if (OnInstantMessage != null) { InstantMessage message; message.FromAgentID = im.AgentData.AgentID; message.FromAgentName = Helpers.FieldToUTF8String(im.MessageBlock.FromAgentName); message.ToAgentID = im.MessageBlock.ToAgentID; message.ParentEstateID = im.MessageBlock.ParentEstateID; message.RegionID = im.MessageBlock.RegionID; message.Position = im.MessageBlock.Position; message.Dialog = (InstantMessageDialog)im.MessageBlock.Dialog; message.GroupIM = im.MessageBlock.FromGroup; message.IMSessionID = im.MessageBlock.ID; message.Timestamp = new DateTime(im.MessageBlock.Timestamp); message.Message = Helpers.FieldToUTF8String(im.MessageBlock.Message); message.Offline = (InstantMessageOnline)im.MessageBlock.Offline; message.BinaryBucket = im.MessageBlock.BinaryBucket; try { OnInstantMessage(message, simulator); } catch (Exception e) { Client.Log(e.ToString(), Helpers.LogLevel.Error); } } } } /// /// Take an incoming Chat packet, auto-parse, and if OnChat is defined call /// that with the appropriate arguments. /// /// Incoming ChatFromSimulatorPacket /// Unused private void ChatHandler(Packet packet, Simulator simulator) { if (OnChat != null) { ChatFromSimulatorPacket chat = (ChatFromSimulatorPacket)packet; OnChat(Helpers.FieldToUTF8String(chat.ChatData.Message) , (ChatAudibleLevel)chat.ChatData.Audible , (ChatType)chat.ChatData.ChatType , (ChatSourceType)chat.ChatData.SourceType , Helpers.FieldToUTF8String(chat.ChatData.FromName) , chat.ChatData.SourceID , chat.ChatData.OwnerID , chat.ChatData.Position ); } } /// /// Used for parsing llDialogs /// /// Incoming ScriptDialog packet /// Unused private void ScriptDialogHandler(Packet packet, Simulator simulator) { if (OnScriptDialog != null) { ScriptDialogPacket dialog = (ScriptDialogPacket)packet; List buttons = new List(); foreach (ScriptDialogPacket.ButtonsBlock button in dialog.Buttons) { buttons.Add(Helpers.FieldToUTF8String(button.ButtonLabel)); } OnScriptDialog(Helpers.FieldToUTF8String(dialog.Data.Message), Helpers.FieldToUTF8String(dialog.Data.ObjectName), dialog.Data.ImageID, dialog.Data.ObjectID, Helpers.FieldToUTF8String(dialog.Data.FirstName), Helpers.FieldToUTF8String(dialog.Data.LastName), dialog.Data.ChatChannel, buttons); } } /// /// Used for parsing llRequestPermissions dialogs /// /// Incoming ScriptDialog packet /// Unused private void ScriptQuestionHandler(Packet packet, Simulator simulator) { if (OnScriptQuestion != null) { ScriptQuestionPacket question = (ScriptQuestionPacket)packet; try { OnScriptQuestion(question.Data.TaskID, question.Data.ItemID, Helpers.FieldToUTF8String(question.Data.ObjectName), Helpers.FieldToUTF8String(question.Data.ObjectOwner), (ScriptPermission)question.Data.Questions); } catch (Exception e) { Client.Log(e.ToString(), Helpers.LogLevel.Error); } } } /// /// Update client's Position, LookAt and region handle from incoming packet /// /// Incoming AgentMovementCompletePacket /// Unused private void MovementCompleteHandler(Packet packet, Simulator simulator) { AgentMovementCompletePacket movement = (AgentMovementCompletePacket)packet; this.Position = movement.Data.Position; this.LookAt = movement.Data.LookAt; simulator.Handle = movement.Data.RegionHandle; } /// /// Update Client Avatar's health via incoming packet /// /// Incoming HealthMessagePacket /// Unused private void HealthHandler(Packet packet, Simulator simulator) { health = ((HealthMessagePacket)packet).HealthData.Health; } private void AgentDataUpdateHandler(Packet packet, Simulator simulator) { AgentDataUpdatePacket p = (AgentDataUpdatePacket)packet; if (p.AgentData.AgentID == simulator.Client.Network.AgentID) { firstName = Helpers.FieldToUTF8String(p.AgentData.FirstName); lastName = Helpers.FieldToUTF8String(p.AgentData.LastName); activeGroup = p.AgentData.ActiveGroupID; if (OnAgentDataUpdated != null) { string groupTitle = Helpers.FieldToUTF8String(p.AgentData.GroupTitle); string groupName = Helpers.FieldToUTF8String(p.AgentData.GroupName); try { OnAgentDataUpdated(firstName, lastName, activeGroup, groupTitle, p.AgentData.GroupPowers, groupName); } catch (Exception e) { Client.Log(e.ToString(), Helpers.LogLevel.Error); } } } else { Client.Log("Got an AgentDataUpdate packet for avatar " + p.AgentData.AgentID.ToStringHyphenated() + " instead of " + Client.Network.AgentID.ToStringHyphenated() + ", this shouldn't happen", Helpers.LogLevel.Error); } } /// /// Update Client Avatar's L$ balance from incoming packet /// /// Incoming MoneyBalanceReplyPacket /// Unused private void BalanceHandler(Packet packet, Simulator simulator) { if (packet.Type == PacketType.MoneyBalanceReply) { MoneyBalanceReplyPacket mbrp = (MoneyBalanceReplyPacket)packet; balance = mbrp.MoneyData.MoneyBalance; if (OnMoneyBalanceReplyReceived != null) { try { OnMoneyBalanceReplyReceived(mbrp.MoneyData.TransactionID, mbrp.MoneyData.TransactionSuccess, mbrp.MoneyData.MoneyBalance, mbrp.MoneyData.SquareMetersCredit, mbrp.MoneyData.SquareMetersCommitted, Helpers.FieldToUTF8String(mbrp.MoneyData.Description)); } catch (Exception e) { Client.Log(e.ToString(), Helpers.LogLevel.Error); } } } if (OnBalanceUpdated != null) { try { OnBalanceUpdated(balance); } catch (Exception e) { Client.Log(e.ToString(), Helpers.LogLevel.Error); } } } private void TeleportFinishEventHandler(string message, Hashtable body, CapsEventQueue caps) { if (body.ContainsKey("Info")) { ArrayList infoList = (ArrayList)body["Info"]; Hashtable info = (Hashtable)infoList[0]; // Backwards compatibility hack TeleportFinishPacket packet = new TeleportFinishPacket(); packet.Info.SimIP = Helpers.BytesToUIntBig((byte[])info["SimIP"]); packet.Info.LocationID = Helpers.BytesToUInt((byte[])info["LocationID"]); packet.Info.TeleportFlags = Helpers.BytesToUInt((byte[])info["TeleportFlags"]); packet.Info.AgentID = (LLUUID)info["AgentID"]; packet.Info.RegionHandle = Helpers.BytesToUInt64((byte[])info["RegionHandle"]); packet.Info.SeedCapability = Helpers.StringToField((string)info["SeedCapability"]); packet.Info.SimPort = (ushort)(int)info["SimPort"]; packet.Info.SimAccess = (byte)(int)info["SimAccess"]; Client.DebugLog(String.Format( "Received a TeleportFinish event from {0}, SimIP: {1}, Location: {2}, RegionHandle: {3}", caps.Simulator, packet.Info.SimIP, packet.Info.LocationID, packet.Info.RegionHandle)); TeleportHandler(packet, Client.Network.CurrentSim); } } private void EstablishAgentCommunicationEventHandler(string message, Hashtable body, CapsEventQueue caps) { if (Client.Settings.MULTIPLE_SIMS && body.ContainsKey("sim-ip-and-port")) { string ipAndPort = (string)body["sim-ip-and-port"]; string[] pieces = ipAndPort.Split(':'); IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(pieces[0]), Convert.ToInt32(pieces[1])); Simulator sim = Client.Network.FindSimulator(endPoint); if (sim == null) { Client.Log("Got EstablishAgentCommunication for unknown sim " + ipAndPort, Helpers.LogLevel.Error); // FIXME: Should we use this opportunity to connect to the simulator? } else { Client.Log("Got EstablishAgentCommunication for " + sim.ToString(), Helpers.LogLevel.Info); sim.SetSeedCaps((string)body["seed-capability"]); } } } /// /// Handler for teleport Requests /// /// Incoming TeleportHandler packet /// Simulator sending teleport information private void TeleportHandler(Packet packet, Simulator simulator) { bool finished = false; TeleportFlags flags = TeleportFlags.Default; if (packet.Type == PacketType.TeleportStart) { TeleportStartPacket start = (TeleportStartPacket)packet; teleportMessage = "Teleport started"; flags = (TeleportFlags)start.Info.TeleportFlags; TeleportStat = TeleportStatus.Start; Client.DebugLog("TeleportStart received, Flags: " + flags.ToString()); } else if (packet.Type == PacketType.TeleportProgress) { TeleportProgressPacket progress = (TeleportProgressPacket)packet; teleportMessage = Helpers.FieldToUTF8String(progress.Info.Message); flags = (TeleportFlags)progress.Info.TeleportFlags; TeleportStat = TeleportStatus.Progress; Client.DebugLog("TeleportProgress received, Message: " + teleportMessage + ", Flags: " + flags.ToString()); } else if (packet.Type == PacketType.TeleportFailed) { TeleportFailedPacket failed = (TeleportFailedPacket)packet; teleportMessage = Helpers.FieldToUTF8String(failed.Info.Reason); TeleportStat = TeleportStatus.Failed; finished = true; Client.DebugLog("TeleportFailed received, Reason: " + teleportMessage); } else if (packet.Type == PacketType.TeleportFinish) { TeleportFinishPacket finish = (TeleportFinishPacket)packet; flags = (TeleportFlags)finish.Info.TeleportFlags; string seedcaps = Helpers.FieldToUTF8String(finish.Info.SeedCapability); finished = true; Client.DebugLog("TeleportFinish received, Flags: " + flags.ToString()); // Connect to the new sim Simulator newSimulator = Client.Network.Connect(new IPAddress(finish.Info.SimIP), finish.Info.SimPort, finish.Info.RegionHandle, true, seedcaps); if (newSimulator != null) { teleportMessage = "Teleport finished"; TeleportStat = TeleportStatus.Finished; // Disconnect from the previous sim Client.Network.DisconnectSim(simulator, true); Client.Log("Moved to new sim " + newSimulator.ToString(), Helpers.LogLevel.Info); } else { teleportMessage = "Failed to connect to the new sim after a teleport"; TeleportStat = TeleportStatus.Failed; // We're going to get disconnected now Client.Log(teleportMessage, Helpers.LogLevel.Error); } } else if (packet.Type == PacketType.TeleportCancel) { //TeleportCancelPacket cancel = (TeleportCancelPacket)packet; teleportMessage = "Cancelled"; TeleportStat = TeleportStatus.Cancelled; finished = true; Client.DebugLog("TeleportCancel received from " + simulator.ToString()); } else if (packet.Type == PacketType.TeleportLocal) { TeleportLocalPacket local = (TeleportLocalPacket)packet; teleportMessage = "Teleport finished"; flags = (TeleportFlags)local.Info.TeleportFlags; TeleportStat = TeleportStatus.Finished; LookAt = local.Info.LookAt; Position = local.Info.Position; // This field is apparently not used for anything //local.Info.LocationID; finished = true; Client.DebugLog("TeleportLocal received, Flags: " + flags.ToString()); } if (OnTeleport != null) { try { OnTeleport(teleportMessage, TeleportStat, flags); } catch (Exception e) { Client.Log(e.ToString(), Helpers.LogLevel.Error); } } if (finished) TeleportEvent.Set(); } private void Network_OnDisconnected(NetworkManager.DisconnectType reason, string message) { // Null out the cached fullName since it can change after logging // in again (with a different account name or different login // server but using the same SecondLife object fullName = null; } #endregion Packet Handlers } }