From 20a9bf08f51351e1e0a9de94f184ff56cd572665 Mon Sep 17 00:00:00 2001 From: Adam Frisby Date: Thu, 1 May 2008 18:04:42 +0000 Subject: * Rolled back a few changes. --- .../Region/Environment/Scenes/AvatarAnimations.cs | 6 +- .../Region/Environment/Scenes/AvatarAppearance.cs | 123 +- OpenSim/Region/Environment/Scenes/EntityBase.cs | 193 +- .../Environment/Scenes/IScenePresenceBody.cs | 2 +- OpenSim/Region/Environment/Scenes/InnerScene.cs | 198 +- .../Region/Environment/Scenes/Scene.Inventory.cs | 316 +- .../Environment/Scenes/Scene.PacketHandlers.cs | 30 +- OpenSim/Region/Environment/Scenes/Scene.cs | 561 ++-- OpenSim/Region/Environment/Scenes/SceneBase.cs | 71 +- .../Scenes/SceneCommunicationService.cs | 534 ++-- OpenSim/Region/Environment/Scenes/SceneEvents.cs | 337 +- OpenSim/Region/Environment/Scenes/SceneManager.cs | 82 +- .../Scenes/SceneObjectGroup.Inventory.cs | 59 +- .../Region/Environment/Scenes/SceneObjectGroup.cs | 377 +-- .../Scenes/SceneObjectPart.Inventory.cs | 150 +- .../Region/Environment/Scenes/SceneObjectPart.cs | 2660 ++++++++-------- OpenSim/Region/Environment/Scenes/ScenePresence.cs | 3230 ++++++++++---------- .../Region/Environment/Scenes/SceneXmlLoader.cs | 10 +- .../Environment/Scenes/Scripting/IScriptHost.cs | 2 +- .../Environment/Scenes/Scripting/NullScriptHost.cs | 8 +- .../Scenes/Scripting/ScriptEngineInterface.cs | 2 +- .../Scenes/Scripting/ScriptEngineLoader.cs | 4 +- .../Region/Environment/Scenes/SimStatsReporter.cs | 274 +- OpenSim/Region/Environment/Scenes/UndoState.cs | 20 +- 24 files changed, 4673 insertions(+), 4576 deletions(-) (limited to 'OpenSim/Region/Environment/Scenes') diff --git a/OpenSim/Region/Environment/Scenes/AvatarAnimations.cs b/OpenSim/Region/Environment/Scenes/AvatarAnimations.cs index 2fc2a10..fe9c8e7 100644 --- a/OpenSim/Region/Environment/Scenes/AvatarAnimations.cs +++ b/OpenSim/Region/Environment/Scenes/AvatarAnimations.cs @@ -46,8 +46,8 @@ namespace OpenSim.Region.Environment.Scenes { if (nod.Attributes["name"] != null) { - string name = nod.Attributes["name"].Value; - LLUUID id = (LLUUID) nod.InnerText; + string name = (string)nod.Attributes["name"].Value; + LLUUID id = (LLUUID)nod.InnerText; AnimsLLUUID.Add(name, id); AnimsNames.Add(id, name); @@ -56,4 +56,4 @@ namespace OpenSim.Region.Environment.Scenes } } } -} \ No newline at end of file +} diff --git a/OpenSim/Region/Environment/Scenes/AvatarAppearance.cs b/OpenSim/Region/Environment/Scenes/AvatarAppearance.cs index 860399c..8f29507 100644 --- a/OpenSim/Region/Environment/Scenes/AvatarAppearance.cs +++ b/OpenSim/Region/Environment/Scenes/AvatarAppearance.cs @@ -37,54 +37,14 @@ namespace OpenSim.Region.Environment.Scenes [Serializable] public class AvatarAppearance : ISerializable { - protected float m_avatarHeight; protected LLUUID m_scenePresenceID; - protected LLObject.TextureEntry m_textureEntry; - protected byte[] m_visualParams; - protected AvatarWearable[] m_wearables; - - protected int m_wearablesSerial = 1; - - public AvatarAppearance() - { - } - - public AvatarAppearance(LLUUID avatarID, AvatarWearable[] wearables, byte[] visualParams) - { - m_scenePresenceID = avatarID; - m_wearablesSerial = 1; - m_wearables = wearables; - m_visualParams = visualParams; - m_textureEntry = GetDefaultTextureEntry(); - } - - protected AvatarAppearance(SerializationInfo info, StreamingContext context) - { - //System.Console.WriteLine("AvatarAppearance Deserialize BGN"); - - if (info == null) - { - throw new ArgumentNullException("info"); - } - - m_scenePresenceID = new LLUUID((Guid) info.GetValue("m_scenePresenceID", typeof (Guid))); - m_wearablesSerial = (int) info.GetValue("m_wearablesSerial", typeof (int)); - m_visualParams = (byte[]) info.GetValue("m_visualParams", typeof (byte[])); - m_wearables = (AvatarWearable[]) info.GetValue("m_wearables", typeof (AvatarWearable[])); - - byte[] m_textureEntry_work = (byte[]) info.GetValue("m_textureEntry", typeof (byte[])); - m_textureEntry = new LLObject.TextureEntry(m_textureEntry_work, 0, m_textureEntry_work.Length); - - m_avatarHeight = (float) info.GetValue("m_avatarHeight", typeof (float)); - - //System.Console.WriteLine("AvatarAppearance Deserialize END"); - } public LLUUID ScenePresenceID { get { return m_scenePresenceID; } set { m_scenePresenceID = value; } } + protected int m_wearablesSerial = 1; public int WearablesSerial { @@ -92,51 +52,50 @@ namespace OpenSim.Region.Environment.Scenes set { m_wearablesSerial = value; } } + protected byte[] m_visualParams; + public byte[] VisualParams { get { return m_visualParams; } set { m_visualParams = value; } } + protected AvatarWearable[] m_wearables; + public AvatarWearable[] Wearables { get { return m_wearables; } set { m_wearables = value; } } + protected LLObject.TextureEntry m_textureEntry; + public LLObject.TextureEntry TextureEntry { get { return m_textureEntry; } set { m_textureEntry = value; } } + protected float m_avatarHeight = 0; + public float AvatarHeight { get { return m_avatarHeight; } set { m_avatarHeight = value; } } - #region ISerializable Members - - [SecurityPermission(SecurityAction.LinkDemand, - Flags = SecurityPermissionFlag.SerializationFormatter)] - public virtual void GetObjectData( - SerializationInfo info, StreamingContext context) + public AvatarAppearance() { - if (info == null) - { - throw new ArgumentNullException("info"); - } - - info.AddValue("m_scenePresenceID", m_scenePresenceID.UUID); - info.AddValue("m_wearablesSerial", m_wearablesSerial); - info.AddValue("m_visualParams", m_visualParams); - info.AddValue("m_wearables", m_wearables); - info.AddValue("m_textureEntry", m_textureEntry.ToBytes()); - info.AddValue("m_avatarHeight", m_avatarHeight); } - #endregion + public AvatarAppearance(LLUUID avatarID, AvatarWearable[] wearables, byte[] visualParams) + { + m_scenePresenceID = avatarID; + m_wearablesSerial = 1; + m_wearables = wearables; + m_visualParams = visualParams; + m_textureEntry = GetDefaultTextureEntry(); + } /// /// @@ -156,8 +115,8 @@ namespace OpenSim.Region.Environment.Scenes // Teravus : Nifty AV Height Getting Maaaaagical formula. Oh how we love turning 0-255 into meters. // (float)m_visualParams[25] = Height // (float)m_visualParams[125] = LegLength - m_avatarHeight = (1.50856f + ((m_visualParams[25] / 255.0f) * (2.525506f - 1.50856f))) - + ((m_visualParams[125] / 255.0f) / 1.5f); + m_avatarHeight = (1.50856f + (((float) m_visualParams[25]/255.0f)*(2.525506f - 1.50856f))) + + (((float) m_visualParams[125]/255.0f)/1.5f); } /// @@ -193,5 +152,45 @@ namespace OpenSim.Region.Environment.Scenes textu.CreateFace(6).TextureID = new LLUUID("00000000-0000-1111-9999-000000000011"); return textu; } + + protected AvatarAppearance(SerializationInfo info, StreamingContext context) + { + //System.Console.WriteLine("AvatarAppearance Deserialize BGN"); + + if (info == null) + { + throw new ArgumentNullException("info"); + } + + m_scenePresenceID = new LLUUID((Guid)info.GetValue("m_scenePresenceID", typeof(Guid))); + m_wearablesSerial = (int)info.GetValue("m_wearablesSerial", typeof(int)); + m_visualParams = (byte[])info.GetValue("m_visualParams", typeof(byte[])); + m_wearables = (AvatarWearable[])info.GetValue("m_wearables", typeof(AvatarWearable[])); + + byte[] m_textureEntry_work = (byte[])info.GetValue("m_textureEntry", typeof(byte[])); + m_textureEntry = new LLObject.TextureEntry(m_textureEntry_work, 0, m_textureEntry_work.Length); + + m_avatarHeight = (float)info.GetValue("m_avatarHeight", typeof(float)); + + //System.Console.WriteLine("AvatarAppearance Deserialize END"); + } + + [SecurityPermission(SecurityAction.LinkDemand, + Flags = SecurityPermissionFlag.SerializationFormatter)] + public virtual void GetObjectData( + SerializationInfo info, StreamingContext context) + { + if (info == null) + { + throw new ArgumentNullException("info"); + } + + info.AddValue("m_scenePresenceID", m_scenePresenceID.UUID); + info.AddValue("m_wearablesSerial", m_wearablesSerial); + info.AddValue("m_visualParams", m_visualParams); + info.AddValue("m_wearables", m_wearables); + info.AddValue("m_textureEntry", m_textureEntry.ToBytes()); + info.AddValue("m_avatarHeight", m_avatarHeight); + } } -} \ No newline at end of file +} diff --git a/OpenSim/Region/Environment/Scenes/EntityBase.cs b/OpenSim/Region/Environment/Scenes/EntityBase.cs index 7e43718..11bafb7 100644 --- a/OpenSim/Region/Environment/Scenes/EntityBase.cs +++ b/OpenSim/Region/Environment/Scenes/EntityBase.cs @@ -36,83 +36,23 @@ namespace OpenSim.Region.Environment.Scenes [Serializable] public abstract class EntityBase : ISerializable { - protected uint m_localId; - protected string m_name; - protected LLVector3 m_pos; - protected Quaternion m_rotation = new Quaternion(0, 0, 1, 0); - protected LLVector3 m_rotationalvelocity; protected Scene m_scene; - - protected LLUUID m_uuid; - protected LLVector3 m_velocity; - - /// - /// Creates a new Entity (should not occur on it's own) - /// - public EntityBase() - { - m_uuid = LLUUID.Zero; - - m_pos = new LLVector3(); - m_velocity = new LLVector3(); - Rotation = new Quaternion(); - m_name = "(basic entity)"; - m_rotationalvelocity = new LLVector3(0, 0, 0); - } - - protected EntityBase(SerializationInfo info, StreamingContext context) - { - //System.Console.WriteLine("EntityBase Deserialize BGN"); - - if (info == null) - { - throw new ArgumentNullException("info"); - } - - m_uuid = new LLUUID((Guid) info.GetValue("m_uuid", typeof (Guid))); - m_name = (string) info.GetValue("m_name", typeof (string)); - - m_pos - = new LLVector3( - (float) info.GetValue("m_pos.X", typeof (float)), - (float) info.GetValue("m_pos.Y", typeof (float)), - (float) info.GetValue("m_pos.Z", typeof (float))); - - m_velocity - = new LLVector3( - (float) info.GetValue("m_velocity.X", typeof (float)), - (float) info.GetValue("m_velocity.Y", typeof (float)), - (float) info.GetValue("m_velocity.Z", typeof (float))); - - m_rotationalvelocity - = new LLVector3( - (float) info.GetValue("m_rotationalvelocity.X", typeof (float)), - (float) info.GetValue("m_rotationalvelocity.Y", typeof (float)), - (float) info.GetValue("m_rotationalvelocity.Z", typeof (float))); - - m_rotation - = new Quaternion( - (float) info.GetValue("m_rotation.w", typeof (float)), - (float) info.GetValue("m_rotation.x", typeof (float)), - (float) info.GetValue("m_rotation.y", typeof (float)), - (float) info.GetValue("m_rotation.z", typeof (float))); - - m_localId = (uint) info.GetValue("m_localId", typeof (uint)); - - //System.Console.WriteLine("EntityBase Deserialize END"); - } - + public Scene Scene { get { return m_scene; } } + protected LLUUID m_uuid; + public virtual LLUUID UUID { get { return m_uuid; } set { m_uuid = value; } } + protected string m_name; + /// /// /// @@ -122,6 +62,8 @@ namespace OpenSim.Region.Environment.Scenes set { m_name = value; } } + protected LLVector3 m_pos; + /// /// /// @@ -131,6 +73,9 @@ namespace OpenSim.Region.Environment.Scenes set { m_pos = value; } } + protected LLVector3 m_velocity; + protected LLVector3 m_rotationalvelocity; + /// /// /// @@ -140,24 +85,104 @@ namespace OpenSim.Region.Environment.Scenes set { m_velocity = value; } } + protected Quaternion m_rotation = new Quaternion(0, 0, 1, 0); + public virtual Quaternion Rotation { get { return m_rotation; } set { m_rotation = value; } } + protected uint m_localId; + public virtual uint LocalId { get { return m_localId; } set { m_localId = value; } } - #region ISerializable Members + /// + /// Creates a new Entity (should not occur on it's own) + /// + public EntityBase() + { + m_uuid = LLUUID.Zero; + + m_pos = new LLVector3(); + m_velocity = new LLVector3(); + Rotation = new Quaternion(); + m_name = "(basic entity)"; + m_rotationalvelocity = new LLVector3(0, 0, 0); + } + + /// + /// + /// + public abstract void UpdateMovement(); + + /// + /// Performs any updates that need to be done at each frame. + /// + public abstract void Update(); + + /// + /// Copies the entity + /// + /// + public virtual EntityBase Copy() + { + return (EntityBase) MemberwiseClone(); + } + + + public abstract void SetText(string text, Vector3 color, double alpha); + + protected EntityBase(SerializationInfo info, StreamingContext context) + { + //System.Console.WriteLine("EntityBase Deserialize BGN"); + + if (info == null) + { + throw new ArgumentNullException("info"); + } + + m_uuid = new LLUUID((Guid)info.GetValue("m_uuid", typeof(Guid))); + m_name = (string)info.GetValue("m_name", typeof(string)); + + m_pos + = new LLVector3( + (float)info.GetValue("m_pos.X", typeof(float)), + (float)info.GetValue("m_pos.Y", typeof(float)), + (float)info.GetValue("m_pos.Z", typeof(float))); + + m_velocity + = new LLVector3( + (float)info.GetValue("m_velocity.X", typeof(float)), + (float)info.GetValue("m_velocity.Y", typeof(float)), + (float)info.GetValue("m_velocity.Z", typeof(float))); + + m_rotationalvelocity + = new LLVector3( + (float)info.GetValue("m_rotationalvelocity.X", typeof(float)), + (float)info.GetValue("m_rotationalvelocity.Y", typeof(float)), + (float)info.GetValue("m_rotationalvelocity.Z", typeof(float))); + + m_rotation + = new Quaternion( + (float)info.GetValue("m_rotation.w", typeof(float)), + (float)info.GetValue("m_rotation.x", typeof(float)), + (float)info.GetValue("m_rotation.y", typeof(float)), + (float)info.GetValue("m_rotation.z", typeof(float))); + + m_localId = (uint)info.GetValue("m_localId", typeof(uint)); + + //System.Console.WriteLine("EntityBase Deserialize END"); + } [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] public virtual void GetObjectData( - SerializationInfo info, StreamingContext context) + SerializationInfo info, StreamingContext context) { if (info == null) { @@ -190,42 +215,18 @@ namespace OpenSim.Region.Environment.Scenes info.AddValue("m_localId", m_localId); } - - #endregion - - /// - /// - /// - public abstract void UpdateMovement(); - - /// - /// Performs any updates that need to be done at each frame. - /// - public abstract void Update(); - - /// - /// Copies the entity - /// - /// - public virtual EntityBase Copy() - { - return (EntityBase) MemberwiseClone(); - } - - - public abstract void SetText(string text, Vector3 color, double alpha); } //Nested Classes public class EntityIntersection { - public Vector3 AAfaceNormal = new Vector3(0, 0, 0); - public float distance; - public int face = -1; - public bool HitTF; public Vector3 ipoint = new Vector3(0, 0, 0); public Vector3 normal = new Vector3(0, 0, 0); + public Vector3 AAfaceNormal = new Vector3(0, 0, 0); + public int face = -1; + public bool HitTF = false; public SceneObjectPart obj; + public float distance = 0; public EntityIntersection() { @@ -238,4 +239,4 @@ namespace OpenSim.Region.Environment.Scenes HitTF = _HitTF; } } -} \ No newline at end of file +} diff --git a/OpenSim/Region/Environment/Scenes/IScenePresenceBody.cs b/OpenSim/Region/Environment/Scenes/IScenePresenceBody.cs index 508eb67..3a20190 100644 --- a/OpenSim/Region/Environment/Scenes/IScenePresenceBody.cs +++ b/OpenSim/Region/Environment/Scenes/IScenePresenceBody.cs @@ -34,4 +34,4 @@ namespace OpenSim.Region.Environment.Scenes { void processMovement(IClientAPI remoteClient, uint flags, LLQuaternion bodyRotation); } -} \ No newline at end of file +} diff --git a/OpenSim/Region/Environment/Scenes/InnerScene.cs b/OpenSim/Region/Environment/Scenes/InnerScene.cs index 3889741..da286ad 100644 --- a/OpenSim/Region/Environment/Scenes/InnerScene.cs +++ b/OpenSim/Region/Environment/Scenes/InnerScene.cs @@ -46,33 +46,36 @@ namespace OpenSim.Region.Environment.Scenes #region Events - private PhysicsCrash handlerPhysicsCrash; public event PhysicsCrash UnRecoverableError; + private PhysicsCrash handlerPhysicsCrash = null; #endregion #region Fields + public Dictionary ScenePresences; // SceneObjects is not currently populated or used. //public Dictionary SceneObjects; - public PhysicsScene _PhyScene; public Dictionary Entities; - protected int m_activeScripts; - protected int m_numChildAgents; - protected int m_numPrim; - protected int m_numRootAgents; - protected Scene m_parentScene; - protected int m_physicalPrim; + public Dictionary RestorePresences; + + public BasicQuadTreeNode QuadTree; + protected RegionInfo m_regInfo; + protected Scene m_parentScene; + protected PermissionManager PermissionsMngr; + protected List m_updateList = new List(); + protected int m_numRootAgents = 0; + protected int m_numPrim = 0; + protected int m_numChildAgents = 0; + protected int m_physicalPrim = 0; - protected int m_scriptLPS; + protected int m_activeScripts = 0; + protected int m_scriptLPS = 0; internal object m_syncRoot = new object(); - protected List m_updateList = new List(); - protected PermissionManager PermissionsMngr; - public BasicQuadTreeNode QuadTree; - public Dictionary RestorePresences; - public Dictionary ScenePresences; + + public PhysicsScene _PhyScene; #endregion @@ -81,7 +84,7 @@ namespace OpenSim.Region.Environment.Scenes m_parentScene = parent; m_regInfo = regInfo; PermissionsMngr = permissionsMngr; - QuadTree = new BasicQuadTreeNode(null, "/0/", 0, 0, (short) Constants.RegionSize, (short) Constants.RegionSize); + QuadTree = new BasicQuadTreeNode(null, "/0/", 0, 0, (short)Constants.RegionSize, (short)Constants.RegionSize); QuadTree.Subdivide(); QuadTree.Subdivide(); } @@ -159,7 +162,7 @@ namespace OpenSim.Region.Environment.Scenes { lock (m_syncRoot) { - return _PhyScene.Simulate((float) elapsed); + return _PhyScene.Simulate((float)elapsed); } } @@ -184,6 +187,7 @@ namespace OpenSim.Region.Environment.Scenes foreach (SceneObjectPart part in sceneObject.Children.Values) { part.LocalId = m_parentScene.PrimIDAllocate(); + } sceneObject.UpdateParentIDs(); AddEntity(sceneObject); @@ -229,7 +233,7 @@ namespace OpenSim.Region.Environment.Scenes for (int i = 0; i < m_updateList.Count; i++) { EntityBase entity = m_updateList[i]; - + // Don't abort the whole update if one entity happens to give us an exception. try { @@ -245,7 +249,7 @@ namespace OpenSim.Region.Environment.Scenes } catch (Exception e) { - m_log.ErrorFormat("[INNER SCENE]: Failed to update {0}, - {1}", entity.Name, e); //entity.m_uuid + m_log.ErrorFormat("[INNER SCENE]: Failed to update {0}, - {1}", entity.Name, e);//entity.m_uuid } } m_updateList.Clear(); @@ -280,16 +284,15 @@ namespace OpenSim.Region.Environment.Scenes { if (obj is SceneObjectGroup) { - if ((obj).LocalId == localID) + if (((SceneObjectGroup)obj).LocalId == localID) { - m_parentScene.RemoveEntity((SceneObjectGroup) obj); + m_parentScene.RemoveEntity((SceneObjectGroup)obj); m_numPrim--; return; } } } } - public void DetachObject(uint objectLocalID, IClientAPI remoteClient) { List EntityList = GetEntities(); @@ -298,25 +301,29 @@ namespace OpenSim.Region.Environment.Scenes { if (obj is SceneObjectGroup) { - if ((obj).LocalId == objectLocalID) + if (((SceneObjectGroup)obj).LocalId == objectLocalID) { - SceneObjectGroup group = (SceneObjectGroup) obj; + SceneObjectGroup group = (SceneObjectGroup)obj; //group.DetachToGround(); - DetachSingleAttachmentToInv(group.GetFromAssetID(), remoteClient); + DetachSingleAttachmentToInv(group.GetFromAssetID(),remoteClient); } } } + } public void HandleUndo(IClientAPI remoteClient, LLUUID primId) { if (primId != LLUUID.Zero) { - SceneObjectPart part = m_parentScene.GetSceneObjectPart(primId); + SceneObjectPart part = m_parentScene.GetSceneObjectPart(primId); if (part != null) part.Undo(); + } + + } /// @@ -331,29 +338,27 @@ namespace OpenSim.Region.Environment.Scenes // Calls attach with a Zero position AttachObject(remoteClient, objectLocalID, AttachmentPt, rot, LLVector3.Zero); } - - public void RezSingleAttachment(IClientAPI remoteClient, LLUUID itemID, uint AttachmentPt, uint ItemFlags, uint NextOwnerMask) + public void RezSingleAttachment(IClientAPI remoteClient, LLUUID itemID, uint AttachmentPt,uint ItemFlags, uint NextOwnerMask) { - SceneObjectGroup objatt = m_parentScene.RezObject(remoteClient, itemID, LLVector3.Zero, LLVector3.Zero, LLUUID.Zero, 1, true, - (uint) - (PermissionMask.Copy | PermissionMask.Move | PermissionMask.Modify | PermissionMask.Transfer), - (uint) - (PermissionMask.Copy | PermissionMask.Move | PermissionMask.Modify | PermissionMask.Transfer), - (uint) - (PermissionMask.Copy | PermissionMask.Move | PermissionMask.Modify | PermissionMask.Transfer), - ItemFlags, false, false, remoteClient.AgentId, true); + SceneObjectGroup objatt = m_parentScene.RezObject(remoteClient, itemID, LLVector3.Zero, LLVector3.Zero, LLUUID.Zero, (byte)1, true, + (uint)(PermissionMask.Copy | PermissionMask.Move | PermissionMask.Modify | PermissionMask.Transfer), + (uint)(PermissionMask.Copy | PermissionMask.Move | PermissionMask.Modify | PermissionMask.Transfer), + (uint)(PermissionMask.Copy | PermissionMask.Move | PermissionMask.Modify | PermissionMask.Transfer), + ItemFlags, false, false, remoteClient.AgentId, true); if (objatt != null) { - AttachObject(remoteClient, objatt.LocalId, AttachmentPt, new LLQuaternion(0, 0, 0, 1), objatt.AbsolutePosition); + AttachObject(remoteClient,objatt.LocalId,AttachmentPt,new LLQuaternion(0,0,0,1),objatt.AbsolutePosition); objatt.ScheduleGroupForFullUpdate(); } + } // What makes this method odd and unique is it tries to detach using an LLUUID.... Yay for standards. // To LocalId or LLUUID, *THAT* is the question. How now Brown LLUUID?? public void DetachSingleAttachmentToInv(LLUUID itemID, IClientAPI remoteClient) { + if (itemID == LLUUID.Zero) // If this happened, someone made a mistake.... return; @@ -363,16 +368,17 @@ namespace OpenSim.Region.Environment.Scenes { if (obj is SceneObjectGroup) { - if (((SceneObjectGroup) obj).GetFromAssetID() == itemID) + if (((SceneObjectGroup)obj).GetFromAssetID() == itemID) { - SceneObjectGroup group = (SceneObjectGroup) obj; + SceneObjectGroup group = (SceneObjectGroup)obj; group.DetachToInventoryPrep(); - m_log.Debug("[DETACH]: Saving attachpoint: " + ((uint) group.GetAttachmentPoint())); - m_parentScene.updateKnownAsset(remoteClient, group, group.GetFromAssetID(), group.OwnerID); + m_log.Debug("[DETACH]: Saving attachpoint: " + ((uint)group.GetAttachmentPoint()).ToString()); + m_parentScene.updateKnownAsset(remoteClient, group, group.GetFromAssetID(),group.OwnerID); m_parentScene.DeleteSceneObjectGroup(group); } } } + } public void AttachObject(IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, LLQuaternion rot, LLVector3 attachPos) @@ -382,34 +388,39 @@ namespace OpenSim.Region.Environment.Scenes { if (obj is SceneObjectGroup) { - if ((obj).LocalId == objectLocalID) + if (((SceneObjectGroup)obj).LocalId == objectLocalID) { - SceneObjectGroup group = (SceneObjectGroup) obj; - + SceneObjectGroup group = (SceneObjectGroup)obj; + // If the attachment point isn't the same as the one previously used // set it's offset position = 0 so that it appears on the attachment point // and not in a weird location somewhere unknown. - if (AttachmentPt != 0 && AttachmentPt != group.GetAttachmentPoint()) + if (AttachmentPt != 0 && AttachmentPt != (uint)group.GetAttachmentPoint()) { + attachPos = LLVector3.Zero; } // AttachmentPt 0 means the client chose to 'wear' the attachment. if (AttachmentPt == 0) { + // Check object for stored attachment point - AttachmentPt = group.GetAttachmentPoint(); + AttachmentPt = (uint)group.GetAttachmentPoint(); + + } // if we still didn't find a suitable attachment point....... if (AttachmentPt == 0) { // Stick it on left hand with Zero Offset from the attachment point. - AttachmentPt = (uint) AttachmentPoint.LeftHand; + AttachmentPt = (uint)AttachmentPoint.LeftHand; attachPos = LLVector3.Zero; } - m_log.Debug("[ATTACH]: Using attachpoint: " + AttachmentPt); - + m_log.Debug("[ATTACH]: Using attachpoint: " + AttachmentPt.ToString()); + + // Saves and gets assetID if (group.GetFromAssetID() == LLUUID.Zero) @@ -420,14 +431,16 @@ namespace OpenSim.Region.Environment.Scenes group.SetFromAssetID(newAssetID); } group.AttachToAgent(remoteClient.AgentId, AttachmentPt, attachPos); + } + } } - } + } // Use the above method. - public void AttachObject(IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, LLQuaternion rot, - bool deadMethod) + public void AttachObject(IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, LLQuaternion rot, + bool deadMethod) { Console.WriteLine("Attaching object " + objectLocalID + " to " + AttachmentPt); SceneObjectPart p = GetSceneObjectPart(objectLocalID); @@ -476,14 +489,14 @@ namespace OpenSim.Region.Environment.Scenes objupdate.ObjectData[0].ParentID = 0; objupdate.ObjectData[0].OwnerID = LLUUID.Zero; objupdate.ObjectData[0].Scale = new LLVector3(1, 1, 1); - objupdate.ObjectData[0].PCode = (byte) PCode.Avatar; + objupdate.ObjectData[0].PCode = (byte)PCode.Avatar; objupdate.ObjectData[0].TextureEntry = ScenePresence.DefaultTexture; objupdate.ObjectData[0].ID = av.LocalId; objupdate.ObjectData[0].FullID = remoteClient.AgentId; objupdate.ObjectData[0].ParentID = 0; objupdate.ObjectData[0].NameValue = - Helpers.StringToField("FirstName STRING RW SV " + av.Firstname + "\nLastName STRING RW SV " + av.Lastname); + Helpers.StringToField("FirstName STRING RW SV " + av.Firstname + "\nLastName STRING RW SV " + av.Lastname); LLVector3 pos2 = av.AbsolutePosition; // new LLVector3((float) Pos.X, (float) Pos.Y, (float) Pos.Z); byte[] pb = pos2.GetBytes(); @@ -516,7 +529,7 @@ namespace OpenSim.Region.Environment.Scenes objupdate.ObjectData[1].TextureEntry = primData.TextureEntry; objupdate.ObjectData[1].PCode = primData.PCode; - objupdate.ObjectData[1].State = (byte) (((byte) AttachmentPt) << 4); + objupdate.ObjectData[1].State = (byte)(((byte)AttachmentPt) << 4); objupdate.ObjectData[1].PathBegin = primData.PathBegin; objupdate.ObjectData[1].PathEnd = primData.PathEnd; objupdate.ObjectData[1].PathScaleX = primData.PathScaleX; @@ -553,8 +566,8 @@ namespace OpenSim.Region.Environment.Scenes //objupdate.ObjectData[1].ClickAction = clickAction; objupdate.ObjectData[1].Radius = 20; objupdate.ObjectData[1].NameValue = - Helpers.StringToField("AttachItemID STRING RW SV " + p.UUID); - LLVector3 pos = new LLVector3((float) 0.0, (float) 0.0, (float) 0.0); + Helpers.StringToField("AttachItemID STRING RW SV " + p.UUID); + LLVector3 pos = new LLVector3((float)0.0, (float)0.0, (float)0.0); pb = pos.GetBytes(); Array.Copy(pb, 0, objupdate.ObjectData[1].ObjectData, 0, pb.Length); @@ -725,7 +738,6 @@ namespace OpenSim.Region.Environment.Scenes m_scriptLPS = 0; return returnval; } - #endregion #region Get Methods @@ -753,7 +765,7 @@ namespace OpenSim.Region.Environment.Scenes return result; } - + /// /// Get the controlling client for the given avatar, if there is one. /// @@ -767,12 +779,12 @@ namespace OpenSim.Region.Environment.Scenes public IClientAPI GetControllingClient(LLUUID agentId) { ScenePresence presence = GetScenePresence(agentId); - + if (presence != null) { return presence.ControllingClient; } - + return null; } @@ -807,7 +819,7 @@ namespace OpenSim.Region.Environment.Scenes { return ScenePresences[agentID]; } - + return null; } @@ -819,8 +831,8 @@ namespace OpenSim.Region.Environment.Scenes { if (ent is SceneObjectGroup) { - if (((SceneObjectGroup) ent).HasChildPrim(localID)) - return (SceneObjectGroup) ent; + if (((SceneObjectGroup)ent).HasChildPrim(localID)) + return (SceneObjectGroup)ent; } } return null; @@ -834,8 +846,8 @@ namespace OpenSim.Region.Environment.Scenes { if (ent is SceneObjectGroup) { - if (((SceneObjectGroup) ent).HasChildPrim(fullID)) - return (SceneObjectGroup) ent; + if (((SceneObjectGroup)ent).HasChildPrim(fullID)) + return (SceneObjectGroup)ent; } } return null; @@ -850,7 +862,7 @@ namespace OpenSim.Region.Environment.Scenes { if (ent is SceneObjectGroup) { - SceneObjectGroup reportingG = (SceneObjectGroup) ent; + SceneObjectGroup reportingG = (SceneObjectGroup)ent; EntityIntersection result = reportingG.TestIntersection(hray, frontFacesOnly, faceCenters); if (result.HitTF) { @@ -890,13 +902,13 @@ namespace OpenSim.Region.Environment.Scenes { if (!presence.IsChildAgent) { - avatar = presence; + avatar = presence; return true; } else { m_log.WarnFormat( - "[INNER SCENE]: Requested avatar {0} could not be found in scene {1} since it is only registered as a child agent!", + "[INNER SCENE]: Requested avatar {0} could not be found in scene {1} since it is only registered as a child agent!", avatarId, m_parentScene.RegionInfo.RegionName); } } @@ -975,8 +987,8 @@ namespace OpenSim.Region.Environment.Scenes if (presence.IsChildAgent && m_parentScene.m_seeIntoRegionFromNeighbor) { - LLVector3 oLoc = (ent).AbsolutePosition; - float distResult = (float) Util.GetDistanceTo(presence.AbsolutePosition, oLoc); + LLVector3 oLoc = ((SceneObjectGroup)ent).AbsolutePosition; + float distResult = (float)Util.GetDistanceTo(presence.AbsolutePosition, oLoc); //m_log.Info("[DISTANCE]: " + distResult.ToString()); @@ -984,13 +996,13 @@ namespace OpenSim.Region.Environment.Scenes { // Send Only if we don't already know about it. // KnownPrim also makes the prim known when called. - if (!presence.KnownPrim((ent).UUID)) - ((SceneObjectGroup) ent).ScheduleFullUpdateToAvatar(presence); + if (!presence.KnownPrim(((SceneObjectGroup)ent).UUID)) + ((SceneObjectGroup)ent).ScheduleFullUpdateToAvatar(presence); } } else { - ((SceneObjectGroup) ent).ScheduleFullUpdateToAvatar(presence); + ((SceneObjectGroup)ent).ScheduleFullUpdateToAvatar(presence); } } } @@ -1025,7 +1037,6 @@ namespace OpenSim.Region.Environment.Scenes } } } - public void UpdatePrimGroupScale(uint localID, LLVector3 scale, IClientAPI remoteClient) { SceneObjectGroup group = GetGroupByPrim(localID); @@ -1140,12 +1151,13 @@ namespace OpenSim.Region.Environment.Scenes SceneObjectGroup group = GetGroupByPrim(localID); if (group != null) { + LLVector3 oldPos = group.AbsolutePosition; if (group.RootPart.m_IsAttachment) { group.UpdateGroupPosition(pos); } - else + else { if (!PermissionsMngr.CanObjectEntry(remoteClient.AgentId, oldPos, pos) && !group.RootPart.m_IsAttachment) { @@ -1191,7 +1203,7 @@ namespace OpenSim.Region.Environment.Scenes { if (PermissionsMngr.CanEditObject(remoteClient.AgentId, group.UUID)) { - group.UpdatePrimFlags(localID, (ushort) packet.Type, true, packet.ToBytes()); + group.UpdatePrimFlags(localID, (ushort)packet.Type, true, packet.ToBytes()); } } } @@ -1201,7 +1213,7 @@ namespace OpenSim.Region.Environment.Scenes SceneObjectGroup group = GetGroupByPrim(objectID); if (group != null) { - if (PermissionsMngr.CanEditObjectPosition(remoteClient.AgentId, group.UUID)) // && PermissionsMngr.) + if (PermissionsMngr.CanEditObjectPosition(remoteClient.AgentId, group.UUID))// && PermissionsMngr.) { group.GrabMovement(offset, pos, remoteClient); } @@ -1292,9 +1304,9 @@ namespace OpenSim.Region.Environment.Scenes { if (ent is SceneObjectGroup) { - if ((ent).LocalId == parentPrim) + if (((SceneObjectGroup)ent).LocalId == parentPrim) { - parenPrim = (SceneObjectGroup) ent; + parenPrim = (SceneObjectGroup)ent; break; } } @@ -1309,9 +1321,9 @@ namespace OpenSim.Region.Environment.Scenes { if (ent is SceneObjectGroup) { - if ((ent).LocalId == childPrims[i]) + if (((SceneObjectGroup)ent).LocalId == childPrims[i]) { - children.Add((SceneObjectGroup) ent); + children.Add((SceneObjectGroup)ent); } } } @@ -1322,7 +1334,7 @@ namespace OpenSim.Region.Environment.Scenes { parenPrim.LinkToGroup(sceneObj); } - + // We need to explicitly resend the newly link prim's object properties since no other actions // occur on link to invoke this elsewhere (such as object selection) parenPrim.GetProperties(client); @@ -1348,16 +1360,19 @@ namespace OpenSim.Region.Environment.Scenes { if (ent is SceneObjectGroup) { - SceneObjectGroup obj = (SceneObjectGroup) ent; + SceneObjectGroup obj = (SceneObjectGroup)ent; sceneObjects.Add(obj.LocalId, obj); + } } // Find the root prim among the prim ids we've been given for (int i = 0; i < primIds.Count; i++) { + if (sceneObjects.ContainsKey(primIds[i])) { + parenPrim = sceneObjects[primIds[i]]; primIds.RemoveAt(i); break; @@ -1387,13 +1402,14 @@ namespace OpenSim.Region.Environment.Scenes grp.DelinkFromGroup(primIds[i]); delinkedSomething = true; } + } } if (!delinkedSomething) { m_log.InfoFormat("[SCENE]: " + - "DelinkObjects(): Could not find a root prim out of {0} as given to a delink request!", - primIds); + "DelinkObjects(): Could not find a root prim out of {0} as given to a delink request!", + primIds); } } } @@ -1409,7 +1425,7 @@ namespace OpenSim.Region.Environment.Scenes { if (ent is SceneObjectGroup) { - foreach (KeyValuePair subent in ((SceneObjectGroup) ent).Children) + foreach (KeyValuePair subent in ((SceneObjectGroup)ent).Children) { if (subent.Value.LocalId == localID) { @@ -1419,7 +1435,7 @@ namespace OpenSim.Region.Environment.Scenes } } } - + //Protip: In my day, we didn't call them searchable objects, we called them limited point-to-point joints //aka ObjectFlags.JointWheel = IncludeInSearch @@ -1451,7 +1467,7 @@ namespace OpenSim.Region.Environment.Scenes public void DuplicateObject(uint originalPrim, LLVector3 offset, uint flags, LLUUID AgentID, LLUUID GroupID) { m_log.DebugFormat("[SCENE]: Duplication of object {0} at offset {1} requested by agent {2}", originalPrim, offset, AgentID); - + List EntityList = GetEntities(); SceneObjectGroup originPrim = null; @@ -1459,9 +1475,9 @@ namespace OpenSim.Region.Environment.Scenes { if (ent is SceneObjectGroup) { - if ((ent).LocalId == originalPrim) + if (((SceneObjectGroup)ent).LocalId == originalPrim) { - originPrim = (SceneObjectGroup) ent; + originPrim = (SceneObjectGroup)ent; break; } } @@ -1510,4 +1526,4 @@ namespace OpenSim.Region.Environment.Scenes #endregion } -} \ No newline at end of file +} diff --git a/OpenSim/Region/Environment/Scenes/Scene.Inventory.cs b/OpenSim/Region/Environment/Scenes/Scene.Inventory.cs index 1e6ebf9..6bd5d1a 100644 --- a/OpenSim/Region/Environment/Scenes/Scene.Inventory.cs +++ b/OpenSim/Region/Environment/Scenes/Scene.Inventory.cs @@ -40,7 +40,7 @@ namespace OpenSim.Region.Environment.Scenes { public partial class Scene { - private static readonly ILog m_log + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// @@ -49,11 +49,11 @@ namespace OpenSim.Region.Environment.Scenes public void StartScripts() { m_log.Info("[PRIM INVENTORY]: Starting scripts in scene"); - + foreach (SceneObjectGroup group in Entities.Values) { group.StartScripts(); - } + } } /// @@ -64,9 +64,9 @@ namespace OpenSim.Region.Environment.Scenes /// in which the item is to be placed. public void AddInventoryItem(IClientAPI remoteClient, InventoryItemBase item) { - CachedUserInfo userInfo + CachedUserInfo userInfo = CommsManager.UserProfileCacheService.GetUserDetails(remoteClient.AgentId); - + if (userInfo != null) { userInfo.AddItem(remoteClient.AgentId, item); @@ -88,9 +88,9 @@ namespace OpenSim.Region.Environment.Scenes m_log.ErrorFormat( "[AGENT INVENTORY]: Agent {0} {1} was not found for add of item {2} {3}", remoteClient.Name, remoteClient.AgentId, item.Name, item.ID); - + return; - } + } } /// @@ -190,7 +190,7 @@ namespace OpenSim.Region.Environment.Scenes { // Retrieve group SceneObjectPart part = GetSceneObjectPart(primId); - SceneObjectGroup group = part.ParentGroup; + SceneObjectGroup group = part.ParentGroup; if (null == group) { m_log.ErrorFormat( @@ -200,30 +200,30 @@ namespace OpenSim.Region.Environment.Scenes return; } - + // Retrieve item TaskInventoryItem item = group.GetInventoryItem(part.LocalId, itemId); if (null == item) { return; } - + // Create new asset // XXX Hardcoding the numbers is a temporary measure - need an enumeration for this // There may well be one in libsecondlife AssetBase asset = CreateAsset(item.Name, item.Description, 10, 10, data); AssetCache.AddAsset(asset); - + // Update item with new asset item.AssetID = asset.FullID; group.UpdateInventoryItem(item); group.GetProperties(remoteClient); - + // Trigger rerunning of script (use TriggerRezScript event, see RezScript) if (isScriptRunning) { group.StopScript(part.LocalId, item.ItemID); - group.StartScript(part.LocalId, item.ItemID); + group.StartScript(part.LocalId, item.ItemID); } } @@ -272,7 +272,7 @@ namespace OpenSim.Region.Environment.Scenes if (userInfo != null && userInfo.RootFolder != null) { InventoryItemBase item = userInfo.RootFolder.HasItem(itemID); - + if (item != null) { if (LLUUID.Zero == transactionID) @@ -298,11 +298,11 @@ namespace OpenSim.Region.Environment.Scenes } else { - IAgentAssetTransactions agentTransactions = RequestModuleInterface(); + IAgentAssetTransactions agentTransactions = this.RequestModuleInterface(); if (agentTransactions != null) { agentTransactions.HandleItemUpdateFromTransaction( - remoteClient, transactionID, item); + remoteClient, transactionID, item); } } } @@ -318,7 +318,7 @@ namespace OpenSim.Region.Environment.Scenes "[AGENT INVENTORY]: Agent ID " + remoteClient.AgentId + " not found for an inventory item update."); } } - + /// /// Give an inventory item from one avatar to another /// @@ -328,13 +328,13 @@ namespace OpenSim.Region.Environment.Scenes public void GiveInventoryItem(IClientAPI recipientClient, LLUUID senderId, LLUUID itemId) { // Retrieve the item from the sender - CachedUserInfo senderUserInfo = CommsManager.UserProfileCacheService.GetUserDetails(senderId); - + CachedUserInfo senderUserInfo = CommsManager.UserProfileCacheService.GetUserDetails(senderId); + if (senderUserInfo == null) { m_log.ErrorFormat( - "[AGENT INVENTORY]: Failed to find sending user {0} for item {1}", senderId, itemId); - + "[AGENT INVENTORY]: Failed to find sending user {0} for item {1}", senderId, itemId); + return; } @@ -342,11 +342,11 @@ namespace OpenSim.Region.Environment.Scenes { InventoryItemBase item = senderUserInfo.RootFolder.HasItem(itemId); if (item != null) - { + { // TODO get recipient's root folder - CachedUserInfo recipientUserInfo - = CommsManager.UserProfileCacheService.GetUserDetails(recipientClient.AgentId); - + CachedUserInfo recipientUserInfo + = CommsManager.UserProfileCacheService.GetUserDetails(recipientClient.AgentId); + if (recipientUserInfo != null) { // Insert a copy of the item into the recipient @@ -373,15 +373,15 @@ namespace OpenSim.Region.Environment.Scenes itemCopy.SaleType = item.SaleType; recipientUserInfo.AddItem(recipientClient.AgentId, itemCopy); - + // Let the recipient client know about this new item - recipientClient.SendBulkUpdateInventory(itemCopy); + recipientClient.SendBulkUpdateInventory(itemCopy); } else { m_log.ErrorFormat( - "[AGENT INVENTORY]: Could not find userinfo for recipient user {0}, {1} of item {2}, {3} from {4}", - recipientClient.Name, recipientClient.AgentId, item.Name, + "[AGENT INVENTORY]: Could not find userinfo for recipient user {0}, {1} of item {2}, {3} from {4}", + recipientClient.Name, recipientClient.AgentId, item.Name, item.ID, senderId); } } @@ -389,15 +389,15 @@ namespace OpenSim.Region.Environment.Scenes { m_log.ErrorFormat( "[AGENT INVENTORY]: Failed to find item {0} to give to {1}", itemId, senderId); - + return; } } else { - m_log.Error("[AGENT INVENTORY]: Failed to find item " + itemId + ", no root folder"); + m_log.Error("[AGENT INVENTORY]: Failed to find item " + itemId.ToString() + ", no root folder"); return; - } + } } public void CopyInventoryItem(IClientAPI remoteClient, uint callbackID, LLUUID oldAgentID, LLUUID oldItemID, @@ -406,14 +406,14 @@ namespace OpenSim.Region.Environment.Scenes m_log.DebugFormat( "[AGENT INVENTORY]: CopyInventoryItem received by {0} with oldAgentID {1}, oldItemID {2}, new FolderID {3}, newName {4}", remoteClient.AgentId, oldAgentID, oldItemID, newFolderID, newName); - + InventoryItemBase item = CommsManager.UserProfileCacheService.libraryRoot.HasItem(oldItemID); if (item == null) { CachedUserInfo userInfo = CommsManager.UserProfileCacheService.GetUserDetails(oldAgentID); if (userInfo == null) { - m_log.Error("[AGENT INVENTORY]: Failed to find user " + oldAgentID); + m_log.Error("[AGENT INVENTORY]: Failed to find user " + oldAgentID.ToString()); return; } @@ -422,20 +422,20 @@ namespace OpenSim.Region.Environment.Scenes item = userInfo.RootFolder.HasItem(oldItemID); if (item == null) { - m_log.Error("[AGENT INVENTORY]: Failed to find item " + oldItemID); + m_log.Error("[AGENT INVENTORY]: Failed to find item " + oldItemID.ToString()); return; } } else { - m_log.Error("[AGENT INVENTORY]: Failed to find item " + oldItemID); + m_log.Error("[AGENT INVENTORY]: Failed to find item " + oldItemID.ToString()); return; } } - - AssetBase asset + + AssetBase asset = AssetCache.GetAsset( - item.AssetID, (item.AssetType == (int) AssetType.Texture ? true : false)); + item.AssetID, (item.AssetType == (int)AssetType.Texture ? true : false)); if (asset != null) { @@ -447,7 +447,7 @@ namespace OpenSim.Region.Environment.Scenes { m_log.ErrorFormat( "[AGENT INVENTORY]: Could not copy item {0} since asset {1} could not be found", - item.Name, item.AssetID); + item.Name, item.AssetID); } } @@ -472,7 +472,7 @@ namespace OpenSim.Region.Environment.Scenes CachedUserInfo userInfo = CommsManager.UserProfileCacheService.GetUserDetails(remoteClient.AgentId); if (userInfo == null) { - m_log.Error("[AGENT INVENTORY]: Failed to find user " + remoteClient.AgentId); + m_log.Error("[AGENT INVENTORY]: Failed to find user " + remoteClient.AgentId.ToString()); return; } @@ -493,13 +493,13 @@ namespace OpenSim.Region.Environment.Scenes } else { - m_log.Error("[AGENT INVENTORY]: Failed to find item " + itemID); + m_log.Error("[AGENT INVENTORY]: Failed to find item " + itemID.ToString()); return; } } else { - m_log.Error("[AGENT INVENTORY]: Failed to find item " + itemID + ", no root folder"); + m_log.Error("[AGENT INVENTORY]: Failed to find item " + itemID.ToString() + ", no root folder"); return; } } @@ -515,9 +515,9 @@ namespace OpenSim.Region.Environment.Scenes private void CreateNewInventoryItem(IClientAPI remoteClient, LLUUID folderID, uint callbackID, AssetBase asset, uint nextOwnerMask) { - CachedUserInfo userInfo + CachedUserInfo userInfo = CommsManager.UserProfileCacheService.GetUserDetails(remoteClient.AgentId); - + if (userInfo != null) { InventoryItemBase item = new InventoryItemBase(); @@ -539,8 +539,8 @@ namespace OpenSim.Region.Environment.Scenes else { m_log.WarnFormat( - "No user details associated with client {0} uuid {1} in CreateNewInventoryItem!", - remoteClient.Name, remoteClient.AgentId); + "No user details associated with client {0} uuid {1} in CreateNewInventoryItem!", + remoteClient.Name, remoteClient.AgentId); } } @@ -564,25 +564,25 @@ namespace OpenSim.Region.Environment.Scenes byte wearableType, uint nextOwnerMask) { // m_log.DebugFormat("[AGENT INVENTORY]: Received request to create inventory item {0} in folder {1}", name, folderID); - + if (transactionID == LLUUID.Zero) { - CachedUserInfo userInfo + CachedUserInfo userInfo = CommsManager.UserProfileCacheService.GetUserDetails(remoteClient.AgentId); - + if (userInfo != null) { ScenePresence presence; TryGetAvatar(remoteClient.AgentId, out presence); byte[] data = null; - if (invType == 3 && presence != null) // libsecondlife.asset.assettype.landmark = 3 - needs to be turned into an enum + if(invType == 3 && presence != null) // libsecondlife.asset.assettype.landmark = 3 - needs to be turned into an enum { - LLVector3 pos = presence.AbsolutePosition; - string strdata = String.Format("Landmark version 2\nregion_id {0}\nlocal_pos {1} {2} {3}\nregion_handle {4}\n", - presence.Scene.RegionInfo.RegionID, - pos.X, pos.Y, pos.Z, - presence.RegionHandle); - data = Encoding.ASCII.GetBytes(strdata); + LLVector3 pos=presence.AbsolutePosition; + string strdata=String.Format("Landmark version 2\nregion_id {0}\nlocal_pos {1} {2} {3}\nregion_handle {4}\n", + presence.Scene.RegionInfo.RegionID, + pos.X, pos.Y, pos.Z, + presence.RegionHandle); + data=Encoding.ASCII.GetBytes(strdata); } AssetBase asset = CreateAsset(name, description, invType, assetType, data); @@ -593,19 +593,21 @@ namespace OpenSim.Region.Environment.Scenes else { m_log.ErrorFormat( - "userInfo for agent uuid {0} unexpectedly null in CreateNewInventoryItem", + "userInfo for agent uuid {0} unexpectedly null in CreateNewInventoryItem", remoteClient.AgentId); } } else { - IAgentAssetTransactions agentTransactions = RequestModuleInterface(); + IAgentAssetTransactions agentTransactions = this.RequestModuleInterface(); if (agentTransactions != null) { agentTransactions.HandleItemCreationFromTransaction( - remoteClient, transactionID, folderID, callbackID, description, - name, invType, assetType, wearableType, nextOwnerMask); + remoteClient, transactionID, folderID, callbackID, description, + name, invType, assetType, wearableType, nextOwnerMask); } + + } } @@ -615,7 +617,7 @@ namespace OpenSim.Region.Environment.Scenes = CommsManager.UserProfileCacheService.GetUserDetails(remoteClient.AgentId); if (userInfo == null) { - m_log.Error("[AGENT INVENTORY]: Failed to find user " + remoteClient.AgentId); + m_log.Error("[AGENT INVENTORY]: Failed to find user " + remoteClient.AgentId.ToString()); return; } @@ -639,7 +641,7 @@ namespace OpenSim.Region.Environment.Scenes = CommsManager.UserProfileCacheService.GetUserDetails(remoteClient.AgentId); if (userInfo == null) { - m_log.Error("[AGENT INVENTORY]: Failed to find user " + remoteClient.AgentId); + m_log.Error("[AGENT INVENTORY]: Failed to find user " + remoteClient.AgentId.ToString()); return; } @@ -675,7 +677,7 @@ namespace OpenSim.Region.Environment.Scenes /// /// public void RequestTaskInventory(IClientAPI remoteClient, uint primLocalID) - { + { SceneObjectGroup group = GetGroupByPrim(primLocalID); if (group != null) { @@ -723,7 +725,7 @@ namespace OpenSim.Region.Environment.Scenes localID); } } - + /// /// Move the given item in the given prim to a folder in the client's inventory /// @@ -734,43 +736,43 @@ namespace OpenSim.Region.Environment.Scenes public void MoveTaskInventoryItem(IClientAPI remoteClient, LLUUID folderId, uint primLocalId, LLUUID itemId) { SceneObjectGroup group = GetGroupByPrim(primLocalId); - + if (null == group) { m_log.WarnFormat( "[PRIM INVENTORY]: " + "Move of inventory item {0} from prim with local id {1} failed because the prim could not be found", itemId, primLocalId); - + return; - } - + } + TaskInventoryItem taskItem = group.GetInventoryItem(primLocalId, itemId); - + if (null == taskItem) { // Console already notified of error in GetInventoryItem return; } - + // bool permission; // permission = PermissionsMngr.CanCopyObject(remoteClient.AgentId, // ((SceneObjectGroup) selectedEnt).UUID); - + // Pending resolving upstream problems with permissions, we just won't allow anybody who is not the owner // to copy if (remoteClient.AgentId != taskItem.OwnerID) { m_log.InfoFormat( "[PRIM INVENTORY]: Attempt made by {0} {1} to copy inventory item {2} {3} in prim {4} {5}," - + " but temporarily not allowed pending upstream bugfixes/feature implementation", + + " but temporarily not allowed pending upstream bugfixes/feature implementation", remoteClient.Name, remoteClient.AgentId, taskItem.Name, taskItem.ItemID, group.Name, group.UUID); return; } - + InventoryItemBase agentItem = new InventoryItemBase(); - + agentItem.ID = LLUUID.Random(); agentItem.Creator = taskItem.CreatorID; agentItem.Owner = remoteClient.AgentId; @@ -781,9 +783,8 @@ namespace OpenSim.Region.Environment.Scenes agentItem.InvType = taskItem.InvType; agentItem.Folder = folderId; agentItem.EveryOnePermissions = taskItem.EveryoneMask; - - if (remoteClient.AgentId != taskItem.OwnerID) - { + + if (remoteClient.AgentId != taskItem.OwnerID) { agentItem.BasePermissions = taskItem.NextOwnerMask; agentItem.CurrentPermissions = taskItem.NextOwnerMask; agentItem.NextPermissions = taskItem.NextOwnerMask; @@ -792,9 +793,9 @@ namespace OpenSim.Region.Environment.Scenes { agentItem.BasePermissions = taskItem.BaseMask; agentItem.CurrentPermissions = taskItem.OwnerMask; - agentItem.NextPermissions = taskItem.NextOwnerMask; + agentItem.NextPermissions = taskItem.NextOwnerMask; } - + AddInventoryItem(remoteClient, agentItem); } @@ -833,7 +834,7 @@ namespace OpenSim.Region.Environment.Scenes { group.AddInventoryItem(remoteClient, primLocalID, item, copyID); m_log.InfoFormat( - "[PRIM INVENTORY]: Update with item {0} requested of prim {1} for {2}", + "[PRIM INVENTORY]: Update with item {0} requested of prim {1} for {2}", item.Name, primLocalID, remoteClient.Name); group.GetProperties(remoteClient); } @@ -864,22 +865,22 @@ namespace OpenSim.Region.Environment.Scenes public void RezScript(IClientAPI remoteClient, LLUUID itemID, uint localID) { LLUUID copyID = LLUUID.Random(); - + if (itemID != LLUUID.Zero) { CachedUserInfo userInfo = CommsManager.UserProfileCacheService.GetUserDetails(remoteClient.AgentId); - + if (userInfo != null && userInfo.RootFolder != null) { InventoryItemBase item = userInfo.RootFolder.HasItem(itemID); - + // Try library // XXX clumsy, possibly should be one call if (null == item) { item = CommsManager.UserProfileCacheService.libraryRoot.HasItem(itemID); } - + if (item != null) { SceneObjectGroup group = GetGroupByPrim(localID); @@ -888,10 +889,10 @@ namespace OpenSim.Region.Environment.Scenes group.AddInventoryItem(remoteClient, localID, item, copyID); group.StartScript(localID, copyID); group.GetProperties(remoteClient); - - // m_log.InfoFormat("[PRIMINVENTORY]: " + - // "Rezzed script {0} into prim local ID {1} for user {2}", - // item.inventoryName, localID, remoteClient.Name); + + // m_log.InfoFormat("[PRIMINVENTORY]: " + + // "Rezzed script {0} into prim local ID {1} for user {2}", + // item.inventoryName, localID, remoteClient.Name); } else { @@ -910,7 +911,7 @@ namespace OpenSim.Region.Environment.Scenes } } } - else // If the itemID is zero then the script has been rezzed directly in an object's inventory + else // If the itemID is zero then the script has been rezzed directly in an object's inventory { // not yet implemented // TODO Need to get more details from original RezScript packet @@ -926,7 +927,7 @@ namespace OpenSim.Region.Environment.Scenes /// /// public virtual void DeRezObject(Packet packet, IClientAPI remoteClient) - { + { DeRezObjectPacket DeRezPacket = (DeRezObjectPacket) packet; if (DeRezPacket.AgentBlock.DestinationID == LLUUID.Zero) @@ -936,11 +937,11 @@ namespace OpenSim.Region.Environment.Scenes else { foreach (DeRezObjectPacket.ObjectDataBlock Data in DeRezPacket.ObjectData) - { + { // m_log.DebugFormat( // "[AGENT INVENTORY]: Received request to derez {0} into folder {1}", // Data.ObjectLocalID, DeRezPacket.AgentBlock.DestinationID); - + EntityBase selectedEnt = null; //m_log.Info("[CLIENT]: LocalID:" + Data.ObjectLocalID.ToString()); @@ -958,16 +959,14 @@ namespace OpenSim.Region.Environment.Scenes { bool permission; if (DeRezPacket.AgentBlock.Destination == 1) - { - // Take Copy - permission = PermissionsMngr.CanCopyObject(remoteClient.AgentId, - (selectedEnt).UUID); + { // Take Copy + permission = PermissionsMngr.CanCopyObject(remoteClient.AgentId, + ((SceneObjectGroup) selectedEnt).UUID); } else - { - // Take - permission = PermissionsMngr.CanDeRezObject(remoteClient.AgentId, - (selectedEnt).UUID); + { // Take + permission = PermissionsMngr.CanDeRezObject(remoteClient.AgentId, + ((SceneObjectGroup) selectedEnt).UUID); } if (permission) @@ -998,8 +997,7 @@ namespace OpenSim.Region.Environment.Scenes item.InvType = asset.InvType; item.Folder = DeRezPacket.AgentBlock.DestinationID; item.EveryOnePermissions = objectGroup.RootPart.EveryoneMask; - if (remoteClient.AgentId != objectGroup.RootPart.OwnerID) - { + if (remoteClient.AgentId != objectGroup.RootPart.OwnerID) { item.BasePermissions = objectGroup.RootPart.NextOwnerMask; item.CurrentPermissions = objectGroup.RootPart.NextOwnerMask; item.NextPermissions = objectGroup.RootPart.NextOwnerMask; @@ -1027,7 +1025,6 @@ namespace OpenSim.Region.Environment.Scenes } } } - public void updateKnownAsset(IClientAPI remoteClient, SceneObjectGroup grp, LLUUID assetID, LLUUID agentID) { SceneObjectGroup objectGroup = grp; @@ -1047,6 +1044,7 @@ namespace OpenSim.Region.Environment.Scenes // search through folders to find the asset. while (searchfolders.Count > 0) { + InventoryFolderImpl fld = searchfolders.Dequeue(); lock (fld) { @@ -1071,8 +1069,8 @@ namespace OpenSim.Region.Environment.Scenes AssetBase asset = CreateAsset( objectGroup.GetPartName(objectGroup.LocalId), objectGroup.GetPartDescription(objectGroup.LocalId), - (sbyte) InventoryType.Object, - (sbyte) AssetType.Object, + (sbyte)InventoryType.Object, + (sbyte)AssetType.Object, Helpers.StringToField(sceneObjectXml)); AssetCache.AddAsset(asset); @@ -1088,7 +1086,7 @@ namespace OpenSim.Region.Environment.Scenes // Sticking it in root folder for now.. objects folder later? - item.Folder = foundFolder; // DeRezPacket.AgentBlock.DestinationID; + item.Folder = foundFolder;// DeRezPacket.AgentBlock.DestinationID; item.EveryOnePermissions = objectGroup.RootPart.EveryoneMask; if (agentID != objectGroup.RootPart.OwnerID) { @@ -1110,10 +1108,10 @@ namespace OpenSim.Region.Environment.Scenes { remoteClient.SendInventoryItemCreateUpdate(item); } + } } } - public LLUUID attachObjectAssetStore(IClientAPI remoteClient, SceneObjectGroup grp, LLUUID AgentId) { SceneObjectGroup objectGroup = grp; @@ -1128,8 +1126,8 @@ namespace OpenSim.Region.Environment.Scenes AssetBase asset = CreateAsset( objectGroup.GetPartName(objectGroup.LocalId), objectGroup.GetPartDescription(objectGroup.LocalId), - (sbyte) InventoryType.Object, - (sbyte) AssetType.Object, + (sbyte)InventoryType.Object, + (sbyte)AssetType.Object, Helpers.StringToField(sceneObjectXml)); AssetCache.AddAsset(asset); @@ -1142,10 +1140,10 @@ namespace OpenSim.Region.Environment.Scenes item.Name = asset.Name; item.AssetType = asset.Type; item.InvType = asset.InvType; - + // Sticking it in root folder for now.. objects folder later? - item.Folder = userInfo.RootFolder.ID; // DeRezPacket.AgentBlock.DestinationID; + item.Folder = userInfo.RootFolder.ID;// DeRezPacket.AgentBlock.DestinationID; item.EveryOnePermissions = objectGroup.RootPart.EveryoneMask; if (remoteClient.AgentId != objectGroup.RootPart.OwnerID) { @@ -1167,6 +1165,7 @@ namespace OpenSim.Region.Environment.Scenes return LLUUID.Zero; } return LLUUID.Zero; + } /// @@ -1188,63 +1187,64 @@ namespace OpenSim.Region.Environment.Scenes /// /// public virtual void RezObject(IClientAPI remoteClient, LLUUID itemID, LLVector3 RayEnd, LLVector3 RayStart, - LLUUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection, - uint EveryoneMask, uint GroupMask, uint NextOwnerMask, uint ItemFlags, - bool RezSelected, bool RemoveItem, LLUUID fromTaskID) + LLUUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection, + uint EveryoneMask, uint GroupMask, uint NextOwnerMask, uint ItemFlags, + bool RezSelected, bool RemoveItem, LLUUID fromTaskID) { SceneObjectGroup sog = RezObject(remoteClient, itemID, RayEnd, RayStart, - RayTargetID, BypassRayCast, RayEndIsIntersection, - EveryoneMask, GroupMask, NextOwnerMask, ItemFlags, - RezSelected, RemoveItem, fromTaskID, false); + RayTargetID, BypassRayCast, RayEndIsIntersection, + EveryoneMask, GroupMask, NextOwnerMask, ItemFlags, + RezSelected, RemoveItem, fromTaskID, false); } - /// - /// Returns SceneObjectGroup or null from asset request. - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// + + /// + /// Returns SceneObjectGroup or null from asset request. + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// public virtual SceneObjectGroup RezObject(IClientAPI remoteClient, LLUUID itemID, LLVector3 RayEnd, LLVector3 RayStart, - LLUUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection, - uint EveryoneMask, uint GroupMask, uint NextOwnerMask, uint ItemFlags, - bool RezSelected, bool RemoveItem, LLUUID fromTaskID, bool attachment) + LLUUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection, + uint EveryoneMask, uint GroupMask, uint NextOwnerMask, uint ItemFlags, + bool RezSelected, bool RemoveItem, LLUUID fromTaskID, bool attachment) { // Work out position details - byte bRayEndIsIntersection = 0; + byte bRayEndIsIntersection = (byte)0; if (RayEndIsIntersection) { - bRayEndIsIntersection = 1; + bRayEndIsIntersection = (byte)1; } else { - bRayEndIsIntersection = 0; + bRayEndIsIntersection = (byte)0; } LLVector3 scale = new LLVector3(0.5f, 0.5f, 0.5f); - + LLVector3 pos = GetNewRezLocation( - RayStart, RayEnd, RayTargetID, new LLQuaternion(0, 0, 0, 1), - BypassRayCast, bRayEndIsIntersection, true, scale, false); - + RayStart, RayEnd, RayTargetID, new LLQuaternion(0, 0, 0, 1), + BypassRayCast, bRayEndIsIntersection,true,scale, false); + if (!PermissionsMngr.CanRezObject(remoteClient.AgentId, pos) && !attachment) { - return null; + return null; } // Rez object @@ -1260,7 +1260,7 @@ namespace OpenSim.Region.Environment.Scenes if (rezAsset != null) { - string xmlData = Helpers.FieldToUTF8String(rezAsset.Data); + string xmlData = Helpers.FieldToUTF8String(rezAsset.Data); SceneObjectGroup group = new SceneObjectGroup(this, m_regionHandle, xmlData); group.ResetIDs(); AddEntity(group); @@ -1270,8 +1270,8 @@ namespace OpenSim.Region.Environment.Scenes if (!attachment) { pos = GetNewRezLocation( - RayStart, RayEnd, RayTargetID, new LLQuaternion(0, 0, 0, 1), - BypassRayCast, bRayEndIsIntersection, true, group.GroupScale(), false); + RayStart, RayEnd, RayTargetID, new LLQuaternion(0, 0, 0, 1), + BypassRayCast, bRayEndIsIntersection, true, group.GroupScale(), false); group.AbsolutePosition = pos; } else @@ -1280,7 +1280,7 @@ namespace OpenSim.Region.Environment.Scenes } SceneObjectPart rootPart = group.GetChildPart(group.UUID); - + // Since renaming the item in the inventory does not affect the name stored // in the serialization, transfer the correct name from the inventory to the // object itself before we rez. @@ -1301,22 +1301,22 @@ namespace OpenSim.Region.Environment.Scenes part.ChangeInventoryOwner(item.Owner); } } - + rootPart.TrimPermissions(); if (!attachment) { - if (group.RootPart.Shape.PCode == (byte) PCode.Prim) + if (group.RootPart.Shape.PCode == (byte)PCode.Prim) { group.ClearPartAttachmentData(); } group.ApplyPhysics(m_physicalPrim); } - + group.StartScripts(); - + if (!attachment) rootPart.ScheduleFullUpdate(); @@ -1327,5 +1327,7 @@ namespace OpenSim.Region.Environment.Scenes } return null; } + + } -} \ No newline at end of file +} diff --git a/OpenSim/Region/Environment/Scenes/Scene.PacketHandlers.cs b/OpenSim/Region/Environment/Scenes/Scene.PacketHandlers.cs index b052096..dccc09a 100644 --- a/OpenSim/Region/Environment/Scenes/Scene.PacketHandlers.cs +++ b/OpenSim/Region/Environment/Scenes/Scene.PacketHandlers.cs @@ -78,12 +78,11 @@ namespace OpenSim.Region.Environment.Scenes foreach (EntityBase ent in EntitieList) { if (ent is SceneObjectGroup) - { - if ((ent).LocalId == primLocalID) + { + if (((SceneObjectGroup) ent).LocalId == primLocalID) { // A prim is only tainted if it's allowed to be edited by the person clicking it. - if (m_permissionManager.CanEditObjectPosition(remoteClient.AgentId, (ent).UUID) || - m_permissionManager.CanEditObject(remoteClient.AgentId, (ent).UUID)) + if (m_permissionManager.CanEditObjectPosition(remoteClient.AgentId, ((SceneObjectGroup)ent).UUID) || m_permissionManager.CanEditObject(remoteClient.AgentId, ((SceneObjectGroup)ent).UUID)) { ((SceneObjectGroup) ent).GetProperties(remoteClient); ((SceneObjectGroup) ent).IsSelected = true; @@ -108,10 +107,9 @@ namespace OpenSim.Region.Environment.Scenes { if (ent is SceneObjectGroup) { - if ((ent).LocalId == primLocalID) + if (((SceneObjectGroup) ent).LocalId == primLocalID) { - if (m_permissionManager.CanEditObjectPosition(remoteClient.AgentId, (ent).UUID) || - m_permissionManager.CanEditObject(remoteClient.AgentId, (ent).UUID)) + if (m_permissionManager.CanEditObjectPosition(remoteClient.AgentId, ((SceneObjectGroup)ent).UUID) || m_permissionManager.CanEditObject(remoteClient.AgentId, ((SceneObjectGroup)ent).UUID)) { ((SceneObjectGroup) ent).IsSelected = false; LandChannel.setPrimsTainted(); @@ -131,20 +129,21 @@ namespace OpenSim.Region.Environment.Scenes } public virtual void ProcessParcelBuy(LLUUID agentId, LLUUID groupId, bool final, bool groupOwned, - bool removeContribution, int parcelLocalID, int parcelArea, int parcelPrice, bool authenticated) + bool removeContribution, int parcelLocalID, int parcelArea, int parcelPrice, bool authenticated) { EventManager.LandBuyArgs args = new EventManager.LandBuyArgs( - agentId, groupId, final, groupOwned, removeContribution, parcelLocalID, parcelArea, parcelPrice, authenticated); + agentId, groupId, final, groupOwned, removeContribution, parcelLocalID, parcelArea, parcelPrice, authenticated); // First, allow all validators a stab at it - m_eventManager.TriggerValidateLandBuy(this, args); + m_eventManager.TriggerValidateLandBuy(this, args); // Then, check validation and transfer - m_eventManager.TriggerLandBuy(this, args); + m_eventManager.TriggerLandBuy(this, args); } public virtual void ProcessObjectGrab(uint localID, LLVector3 offsetPos, IClientAPI remoteClient) { + List EntitieList = GetEntities(); foreach (EntityBase ent in EntitieList) @@ -179,6 +178,7 @@ namespace OpenSim.Region.Environment.Scenes public virtual void ProcessObjectDeGrab(uint localID, IClientAPI remoteClient) { + List EntitieList = GetEntities(); foreach (EntityBase ent in EntitieList) @@ -190,7 +190,7 @@ namespace OpenSim.Region.Environment.Scenes // Is this prim part of the group if (obj.HasChildPrim(localID)) { - SceneObjectPart part = obj.GetChildPart(localID); + SceneObjectPart part=obj.GetChildPart(localID); if (part != null) { // If the touched prim handles touches, deliver it @@ -233,8 +233,8 @@ namespace OpenSim.Region.Environment.Scenes LLUUID translatedIDtem = item.AvatarID; searchData[i] = new AvatarPickerReplyPacket.DataBlock(); searchData[i].AvatarID = translatedIDtem; - searchData[i].FirstName = Helpers.StringToField(item.firstName); - searchData[i].LastName = Helpers.StringToField(item.lastName); + searchData[i].FirstName = Helpers.StringToField((string) item.firstName); + searchData[i].LastName = Helpers.StringToField((string) item.lastName); i++; } if (AvatarResponses.Count == 0) @@ -245,4 +245,4 @@ namespace OpenSim.Region.Environment.Scenes client.SendAvatarPickerReply(replyPacket); } } -} \ No newline at end of file +} diff --git a/OpenSim/Region/Environment/Scenes/Scene.cs b/OpenSim/Region/Environment/Scenes/Scene.cs index 6617995..3113831 100644 --- a/OpenSim/Region/Environment/Scenes/Scene.cs +++ b/OpenSim/Region/Environment/Scenes/Scene.cs @@ -53,99 +53,107 @@ namespace OpenSim.Region.Environment.Scenes public partial class Scene : SceneBase { - #region Delegates - public delegate void SynchronizeSceneHandler(Scene scene); + public SynchronizeSceneHandler SynchronizeScene = null; + public int splitID = 0; - #endregion + #region Fields - public int splitID; - public SynchronizeSceneHandler SynchronizeScene; + protected Timer m_heartbeatTimer = new Timer(); + protected Timer m_restartWaitTimer = new Timer(); - #region Fields + protected SimStatsReporter m_statsReporter; + + protected List m_regionRestartNotifyList = new List(); + protected List m_neighbours = new List(); + + public InnerScene m_innerScene; + private Random Rand = new Random(); + private uint _primCount = 720000; private readonly Mutex _primAllocateMutex = new Mutex(false); - private readonly Timer m_restartTimer = new Timer(15000); // Wait before firing + private int m_timePhase = 24; + private readonly Mutex updateLock; - private uint _primCount = 720000; - public CommunicationsManager CommsManager; - private int frameMS; + public bool m_physicalPrim; + public bool m_seeIntoRegionFromNeighbor; + public int MaxUndoCount = 5; + private int m_RestartTimerCounter; + private readonly Timer m_restartTimer = new Timer(15000); // Wait before firing + private int m_incrementsof15seconds = 0; + + public string m_simulatorVersion = "OpenSimulator 0.5"; + + protected ModuleLoader m_moduleLoader; + protected StorageManager m_storageManager; protected AgentCircuitManager m_authenticateHandler; + public CommunicationsManager CommsManager; // protected XferManager xferManager; - protected IAvatarFactory m_AvatarFactory; + protected SceneCommunicationService m_sceneGridService; + protected SceneXmlLoader m_sceneXmlLoader; /// /// Each agent has its own capabilities handler. /// protected Dictionary m_capsHandlers = new Dictionary(); + + protected BaseHttpServer m_httpListener; + + protected Dictionary Modules = new Dictionary(); + public Dictionary ModuleInterfaces = new Dictionary(); + protected Dictionary ModuleAPIMethods = new Dictionary(); + public Dictionary m_moduleCommanders = new Dictionary(); + + //API module interfaces + + public IXfer XferManager; + + protected IHttpRequests m_httpRequestModule; + protected ISimChat m_simChatModule; + protected IXMLRPC m_xmlrpcModule; + protected IWorldComm m_worldCommModule; + protected IAvatarFactory m_AvatarFactory; // Central Update Loop protected int m_fps = 10; - protected int m_frame; - protected Timer m_heartbeatTimer = new Timer(); - protected BaseHttpServer m_httpListener; - protected IHttpRequests m_httpRequestModule; - private int m_incrementsof15seconds; - public InnerScene m_innerScene; + protected int m_frame = 0; + protected float m_timespan = 0.089f; protected DateTime m_lastupdate = DateTime.Now; - public Dictionary m_moduleCommanders = new Dictionary(); - protected ModuleLoader m_moduleLoader; - protected List m_neighbours = new List(); - public bool m_physicalPrim; - private bool m_physics_enabled = true; - protected List m_regionRestartNotifyList = new List(); - private int m_RestartTimerCounter; - protected Timer m_restartWaitTimer = new Timer(); - protected SceneCommunicationService m_sceneGridService; - protected SceneXmlLoader m_sceneXmlLoader; - private bool m_scripts_enabled = true; - public bool m_seeIntoRegionFromNeighbor; - protected ISimChat m_simChatModule; - public string m_simulatorVersion = "OpenSimulator 0.5"; - protected SimStatsReporter m_statsReporter; - protected StorageManager m_storageManager; protected float m_timedilation = 1.0f; - private int m_timePhase = 24; - protected float m_timespan = 0.089f; - private int m_update_backup = 200; + private int m_update_physics = 1; + private int m_update_entitymovement = 1; private int m_update_entities = 1; // Run through all objects checking for updates private int m_update_entitiesquick = 200; // Run through objects that have scheduled updates checking for updates - private int m_update_entitymovement = 1; - private int m_update_events = 1; - private int m_update_land = 1; - private int m_update_physics = 1; private int m_update_presences = 1; // Update scene presence movements + private int m_update_events = 1; + private int m_update_backup = 200; private int m_update_terrain = 50; - protected IWorldComm m_worldCommModule; - protected IXMLRPC m_xmlrpcModule; - public int MaxUndoCount = 5; - protected Dictionary ModuleAPIMethods = new Dictionary(); - public Dictionary ModuleInterfaces = new Dictionary(); - protected Dictionary Modules = new Dictionary(); + private int m_update_land = 1; + + private int frameMS = 0; + private int physicsMS2 = 0; + private int physicsMS = 0; + private int otherMS = 0; + + private bool m_physics_enabled = true; + private bool m_scripts_enabled = true; + - private int otherMS; - private int physicsMS; - private int physicsMS2; - private Random Rand = new Random(); - public IXfer XferManager; #endregion #region Properties - protected readonly EstateManager m_estateManager; - protected readonly PermissionManager m_permissionManager; - public int objectCapacity = 45000; - public AgentCircuitManager AuthenticateHandler { get { return m_authenticateHandler; } } + protected readonly EstateManager m_estateManager; // an instance to the physics plugin's Scene object. public PhysicsScene PhysicsScene { @@ -169,6 +177,7 @@ namespace OpenSim.Region.Environment.Scenes get { return m_timedilation; } } + protected readonly PermissionManager m_permissionManager; // This is the instance to the permissions manager. // This manages permissions to clients on in world objects @@ -206,13 +215,14 @@ namespace OpenSim.Region.Environment.Scenes get { return m_innerScene.Entities; } set { m_innerScene.Entities = value; } } - public Dictionary m_restorePresences { get { return m_innerScene.RestorePresences; } set { m_innerScene.RestorePresences = value; } } + public int objectCapacity = 45000; + #endregion #region Constructors @@ -242,9 +252,9 @@ namespace OpenSim.Region.Environment.Scenes //Bind Storage Manager functions to some land manager functions for this scene EventManager.OnLandObjectAdded += - m_storageManager.DataStore.StoreLandObject; + new EventManager.LandObjectAdded(m_storageManager.DataStore.StoreLandObject); EventManager.OnLandObjectRemoved += - m_storageManager.DataStore.RemoveLandObject; + new EventManager.LandObjectRemoved(m_storageManager.DataStore.RemoveLandObject); m_estateManager = new EstateManager(this, m_regInfo); @@ -311,7 +321,7 @@ namespace OpenSim.Region.Environment.Scenes OSString = OSString.Substring(0, 45); } - m_simulatorVersion = "OpenSimulator v0.5-SVN on " + OSString + " ChilTasks:" + m_seeIntoRegionFromNeighbor + " PhysPrim:" + m_physicalPrim; + m_simulatorVersion = "OpenSimulator v0.5-SVN on " + OSString + " ChilTasks:" + m_seeIntoRegionFromNeighbor.ToString() + " PhysPrim:" + m_physicalPrim.ToString(); } #endregion @@ -372,23 +382,23 @@ namespace OpenSim.Region.Environment.Scenes } // If these are cast to INT because long + negative values + abs returns invalid data - int resultX = Math.Abs((int) otherRegion.RegionLocX - (int) RegionInfo.RegionLocX); - int resultY = Math.Abs((int) otherRegion.RegionLocY - (int) RegionInfo.RegionLocY); + int resultX = Math.Abs((int)otherRegion.RegionLocX - (int)RegionInfo.RegionLocX); + int resultY = Math.Abs((int)otherRegion.RegionLocY - (int)RegionInfo.RegionLocY); if ((resultX <= 1) && (resultY <= 1)) { try { ForEachScenePresence(delegate(ScenePresence agent) + { + // If agent is a root agent. + if (!agent.IsChildAgent) { - // If agent is a root agent. - if (!agent.IsChildAgent) - { - //agent.ControllingClient.new - //this.CommsManager.InterRegion.InformRegionOfChildAgent(otherRegion.RegionHandle, agent.ControllingClient.RequestClientInfo()); - InformClientOfNeighbor(agent, otherRegion); - } + //agent.ControllingClient.new + //this.CommsManager.InterRegion.InformRegionOfChildAgent(otherRegion.RegionHandle, agent.ControllingClient.RequestClientInfo()); + InformClientOfNeighbor(agent, otherRegion); } + } ); } catch (NullReferenceException) @@ -400,9 +410,9 @@ namespace OpenSim.Region.Environment.Scenes } else { - m_log.Info("[INTERGRID]: Got notice about far away Region: " + otherRegion.RegionName + - " at (" + otherRegion.RegionLocX + ", " + - otherRegion.RegionLocY + ")"); + m_log.Info("[INTERGRID]: Got notice about far away Region: " + otherRegion.RegionName.ToString() + + " at (" + otherRegion.RegionLocX.ToString() + ", " + + otherRegion.RegionLocY.ToString() + ")"); } } return true; @@ -426,10 +436,10 @@ namespace OpenSim.Region.Environment.Scenes { // Now we figure out what to set the timer to that does the notifications and calls, RestartNow() m_restartTimer.Interval = 15000; - m_incrementsof15seconds = (int) seconds / 15; + m_incrementsof15seconds = (int)seconds / 15; m_RestartTimerCounter = 0; m_restartTimer.AutoReset = true; - m_restartTimer.Elapsed += RestartTimer_Elapsed; + m_restartTimer.Elapsed += new ElapsedEventHandler(RestartTimer_Elapsed); m_log.Error("[REGION]: Restarting Region in " + (seconds / 60) + " minutes"); m_restartTimer.Start(); SendRegionMessageFromEstateTools(LLUUID.Random(), LLUUID.Random(), String.Empty, RegionInfo.RegionName + ": Restarting in 2 Minutes"); @@ -448,7 +458,7 @@ namespace OpenSim.Region.Environment.Scenes { if (m_RestartTimerCounter == 4 || m_RestartTimerCounter == 6 || m_RestartTimerCounter == 7) SendRegionMessageFromEstateTools(LLUUID.Random(), LLUUID.Random(), String.Empty, RegionInfo.RegionName + ": Restarting in " + - ((8 - m_RestartTimerCounter) * 15) + " seconds"); + ((8 - m_RestartTimerCounter) * 15) + " seconds"); // SendGeneralAlert(RegionInfo.RegionName + ": Restarting in " + ((8 - m_RestartTimerCounter)*15) + //" seconds"); @@ -490,15 +500,15 @@ namespace OpenSim.Region.Environment.Scenes try { ForEachScenePresence(delegate(ScenePresence agent) + { + // If agent is a root agent. + if (!agent.IsChildAgent) { - // If agent is a root agent. - if (!agent.IsChildAgent) - { - //agent.ControllingClient.new - //this.CommsManager.InterRegion.InformRegionOfChildAgent(otherRegion.RegionHandle, agent.ControllingClient.RequestClientInfo()); - InformClientOfNeighbor(agent, region); - } + //agent.ControllingClient.new + //this.CommsManager.InterRegion.InformRegionOfChildAgent(otherRegion.RegionHandle, agent.ControllingClient.RequestClientInfo()); + InformClientOfNeighbor(agent, region); } + } ); } catch (NullReferenceException) @@ -527,7 +537,7 @@ namespace OpenSim.Region.Environment.Scenes { if (ent is SceneObjectGroup) { - ((SceneObjectGroup) ent).StopScripts(); + ((SceneObjectGroup)ent).StopScripts(); } } } @@ -541,10 +551,12 @@ namespace OpenSim.Region.Environment.Scenes { if (ent is SceneObjectGroup) { - ((SceneObjectGroup) ent).StartScripts(); + ((SceneObjectGroup)ent).StartScripts(); } } } + + } m_scripts_enabled = !ScriptEngine; m_log.Info("[TOTEDD]: Here is the method to trigger disabling of the scripting engine"); @@ -552,7 +564,9 @@ namespace OpenSim.Region.Environment.Scenes if (m_physics_enabled != !PhysicsEngine) { m_physics_enabled = !PhysicsEngine; + } + } // This is the method that shuts down the scene. @@ -561,16 +575,16 @@ namespace OpenSim.Region.Environment.Scenes m_log.Warn("[SCENE]: Closing down the single simulator: " + RegionInfo.RegionName); // Kick all ROOT agents with the message, 'The simulator is going down' ForEachScenePresence(delegate(ScenePresence avatar) - { - if (avatar.KnownChildRegions.Contains(RegionInfo.RegionHandle)) - avatar.KnownChildRegions.Remove(RegionInfo.RegionHandle); + { + if (avatar.KnownChildRegions.Contains(RegionInfo.RegionHandle)) + avatar.KnownChildRegions.Remove(RegionInfo.RegionHandle); - if (!avatar.IsChildAgent) - avatar.ControllingClient.Kick("The simulator is going down."); + if (!avatar.IsChildAgent) + avatar.ControllingClient.Kick("The simulator is going down."); - avatar.ControllingClient.OutPacket(PacketPool.Instance.GetPacket(PacketType.DisableSimulator), - ThrottleOutPacketType.Task); - }); + avatar.ControllingClient.OutPacket(PacketPool.Instance.GetPacket(PacketType.DisableSimulator), + ThrottleOutPacketType.Task); + }); // Wait here, or the kick messages won't actually get to the agents before the scene terminates. Thread.Sleep(500); @@ -605,8 +619,8 @@ namespace OpenSim.Region.Environment.Scenes { m_log.Debug("[SCENE]: Starting timer"); m_heartbeatTimer.Enabled = true; - m_heartbeatTimer.Interval = (int) (m_timespan * 1000); - m_heartbeatTimer.Elapsed += Heartbeat; + m_heartbeatTimer.Interval = (int)(m_timespan * 1000); + m_heartbeatTimer.Elapsed += new ElapsedEventHandler(Heartbeat); } public void SetModuleInterfaces() @@ -708,13 +722,13 @@ namespace OpenSim.Region.Environment.Scenes { if (m_frame % m_update_events == 0) UpdateEvents(); - + if (m_frame % m_update_backup == 0) UpdateStorageBackup(); - + if (m_frame % m_update_terrain == 0) UpdateTerrain(); - + if (m_frame % m_update_land == 0) UpdateLand(); otherMS = System.Environment.TickCount - otherMS; @@ -742,25 +756,28 @@ namespace OpenSim.Region.Environment.Scenes } catch (AccessViolationException e) { - m_log.Error("[Scene]: Failed with exception " + e + " On Region: " + RegionInfo.RegionName); + m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName); + } catch (NullReferenceException e) { - m_log.Error("[Scene]: Failed with exception " + e + " On Region: " + RegionInfo.RegionName); + m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName); + } catch (InvalidOperationException e) { - m_log.Error("[Scene]: Failed with exception " + e + " On Region: " + RegionInfo.RegionName); + m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName); + } catch (Exception e) { - m_log.Error("[Scene]: Failed with exception " + e + " On Region: " + RegionInfo.RegionName); + m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName); } finally { updateLock.ReleaseMutex(); // Get actual time dilation - float tmpval = (m_timespan / (float) SinceLastFrame.TotalSeconds); + float tmpval = (m_timespan / (float)SinceLastFrame.TotalSeconds); // If actual time dilation is greater then one, we're catching up, so subtract // the amount that's greater then 1 from the time dilation @@ -769,7 +786,7 @@ namespace OpenSim.Region.Environment.Scenes tmpval = tmpval - (tmpval - 1.0f); } m_timedilation = tmpval; - + m_lastupdate = DateTime.Now; } } @@ -839,10 +856,10 @@ namespace OpenSim.Region.Environment.Scenes public void ExportWorldMap(string fileName) { List mapBlocks = - m_sceneGridService.RequestNeighbourMapBlocks((int) (RegionInfo.RegionLocX - 9), - (int) (RegionInfo.RegionLocY - 9), - (int) (RegionInfo.RegionLocX + 9), - (int) (RegionInfo.RegionLocY + 9)); + m_sceneGridService.RequestNeighbourMapBlocks((int)(RegionInfo.RegionLocX - 9), + (int)(RegionInfo.RegionLocY - 9), + (int)(RegionInfo.RegionLocX + 9), + (int)(RegionInfo.RegionLocY + 9)); List textures = new List(); List bitImages = new List(); @@ -877,8 +894,8 @@ namespace OpenSim.Region.Environment.Scenes for (int i = 0; i < mapBlocks.Count; i++) { - ushort x = (ushort) ((mapBlocks[i].X - RegionInfo.RegionLocX) + 10); - ushort y = (ushort) ((mapBlocks[i].Y - RegionInfo.RegionLocY) + 10); + ushort x = (ushort)((mapBlocks[i].X - RegionInfo.RegionLocX) + 10); + ushort y = (ushort)((mapBlocks[i].Y - RegionInfo.RegionLocY) + 10); g.DrawImage(bitImages[i], (x * 128), (y * 128), 128, 128); } mapTexture.Save(fileName, ImageFormat.Jpeg); @@ -909,10 +926,11 @@ namespace OpenSim.Region.Environment.Scenes { Heightmap = new TerrainChannel(map); } + } catch (Exception e) { - m_log.Warn("[terrain]: Scene.cs: LoadWorldMap() - Failed with exception " + e); + m_log.Warn("[terrain]: Scene.cs: LoadWorldMap() - Failed with exception " + e.ToString()); } } @@ -973,7 +991,7 @@ namespace OpenSim.Region.Environment.Scenes { for (int y = 0; y < 256; y++) { - float hmval = (float) hm[x, y]; + float hmval = (float)hm[x, y]; if (hmval < low) low = hmval; if (hmval > high) @@ -1003,10 +1021,10 @@ namespace OpenSim.Region.Environment.Scenes //} //else //{ - float tmpval = (float) hm[x, y]; - heightvalue = (float) hm[x, y]; + float tmpval = (float)hm[x, y]; + heightvalue = (float)hm[x, y]; - if (heightvalue > m_regInfo.EstateSettings.waterHeight) + if ((float)heightvalue > m_regInfo.EstateSettings.waterHeight) { // scale height value heightvalue = low + mid * (heightvalue - low) / mid; @@ -1018,7 +1036,7 @@ namespace OpenSim.Region.Environment.Scenes heightvalue = 0; - Color green = Color.FromArgb((int) heightvalue, 100, (int) heightvalue); + Color green = Color.FromArgb((int)heightvalue, 100, (int)heightvalue); // Y flip the cordinates mapbmp.SetPixel(x, (256 - y) - 1, green); @@ -1040,10 +1058,12 @@ namespace OpenSim.Region.Environment.Scenes if (heightvalue < 0) heightvalue = 0; - Color water = Color.FromArgb((int) heightvalue, (int) heightvalue, 255); + Color water = Color.FromArgb((int)heightvalue, (int)heightvalue, 255); mapbmp.SetPixel(x, (256 - y) - 1, water); } //} + + } //tc = System.Environment.TickCount - tc; //m_log.Info("[MAPTILE]: Completed One row in " + tc + " ms"); @@ -1067,6 +1087,7 @@ namespace OpenSim.Region.Environment.Scenes asset.Type = 0; asset.Temporary = temporary; AssetCache.AddAsset(asset); + } else { @@ -1084,6 +1105,7 @@ namespace OpenSim.Region.Environment.Scenes AssetCache.AddAsset(asset); } } + } #endregion @@ -1121,14 +1143,14 @@ namespace OpenSim.Region.Environment.Scenes { AddEntityFromStorage(group); SceneObjectPart rootPart = group.GetChildPart(group.UUID); - rootPart.ObjectFlags &= ~(uint) LLObject.ObjectFlags.Scripted; + rootPart.ObjectFlags &= ~(uint)LLObject.ObjectFlags.Scripted; rootPart.TrimPermissions(); group.ApplyPhysics(m_physicalPrim); //rootPart.DoPhysicsPropertyUpdate(UsePhysics, true); } - m_log.Info("[SCENE]: Loaded " + PrimsFromDB.Count + " SceneObject(s)"); + m_log.Info("[SCENE]: Loaded " + PrimsFromDB.Count.ToString() + " SceneObject(s)"); } /// @@ -1147,11 +1169,10 @@ namespace OpenSim.Region.Environment.Scenes return myID; } - public LLVector3 GetNewRezLocation(LLVector3 RayStart, LLVector3 RayEnd, LLUUID RayTargetID, LLQuaternion rot, byte bypassRayCast, - byte RayEndIsIntersection, bool frontFacesOnly, LLVector3 scale, bool FaceCenter) + public LLVector3 GetNewRezLocation(LLVector3 RayStart, LLVector3 RayEnd, LLUUID RayTargetID, LLQuaternion rot, byte bypassRayCast, byte RayEndIsIntersection, bool frontFacesOnly, LLVector3 scale, bool FaceCenter) { LLVector3 pos = LLVector3.Zero; - if (RayEndIsIntersection == 1) + if (RayEndIsIntersection == (byte)1) { pos = RayEnd; return pos; @@ -1159,7 +1180,7 @@ namespace OpenSim.Region.Environment.Scenes if (RayTargetID != LLUUID.Zero) { SceneObjectPart target = GetSceneObjectPart(RayTargetID); - + LLVector3 direction = LLVector3.Norm(RayEnd - RayStart); Vector3 AXOrigin = new Vector3(RayStart.X, RayStart.Y, RayStart.Z); Vector3 AXdirection = new Vector3(direction.X, direction.Y, direction.Z); @@ -1168,17 +1189,17 @@ namespace OpenSim.Region.Environment.Scenes { pos = target.AbsolutePosition; //m_log.Info("[OBJECT_REZ]: TargetPos: " + pos.ToString() + ", RayStart: " + RayStart.ToString() + ", RayEnd: " + RayEnd.ToString() + ", Volume: " + Util.GetDistanceTo(RayStart,RayEnd).ToString() + ", mag1: " + Util.GetMagnitude(RayStart).ToString() + ", mag2: " + Util.GetMagnitude(RayEnd).ToString()); - + // TODO: Raytrace better here - + //EntityIntersection ei = m_innerScene.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection)); Ray NewRay = new Ray(AXOrigin, AXdirection); // Ray Trace against target here - EntityIntersection ei = target.TestIntersectionOBB(NewRay, new Quaternion(1, 0, 0, 0), frontFacesOnly, FaceCenter); + EntityIntersection ei = target.TestIntersectionOBB(NewRay, new Quaternion(1,0,0,0), frontFacesOnly, FaceCenter); // Un-comment out the following line to Get Raytrace results printed to the console. - // m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString()); + // m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString()); float ScaleOffset = 0.5f; // If we hit something @@ -1194,12 +1215,13 @@ namespace OpenSim.Region.Environment.Scenes // Set the position to the intersection point LLVector3 offset = (normal * (ScaleOffset / 2f)); pos = (intersectionpoint + offset); - + // Un-offset the prim (it gets offset later by the consumer method) pos.Z -= 0.25F; - } - - + + } + + return pos; } else @@ -1214,8 +1236,8 @@ namespace OpenSim.Region.Environment.Scenes if (ei.HitTF) { pos = new LLVector3(ei.ipoint.x, ei.ipoint.y, ei.ipoint.z); - } - + } + return pos; } } @@ -1231,8 +1253,8 @@ namespace OpenSim.Region.Environment.Scenes byte bypassRaycast, LLVector3 RayStart, LLUUID RayTargetID, byte RayEndIsIntersection) { - LLVector3 pos = GetNewRezLocation(RayStart, RayEnd, RayTargetID, rot, bypassRaycast, RayEndIsIntersection, true, new LLVector3(0.5f, 0.5f, 0.5f), - false); + + LLVector3 pos = GetNewRezLocation(RayStart, RayEnd, RayTargetID, rot, bypassRaycast, RayEndIsIntersection, true, new LLVector3(0.5f,0.5f,0.5f), false); if (PermissionsMngr.CanRezObject(ownerID, pos)) { @@ -1252,7 +1274,7 @@ namespace OpenSim.Region.Environment.Scenes SceneObjectPart rootPart = sceneOb.GetChildPart(sceneOb.UUID); // if grass or tree, make phantom //rootPart.TrimPermissions(); - if ((rootPart.Shape.PCode == (byte) PCode.Grass) || (rootPart.Shape.PCode == (byte) PCode.Tree) || (rootPart.Shape.PCode == (byte) PCode.NewTree)) + if ((rootPart.Shape.PCode == (byte)PCode.Grass) || (rootPart.Shape.PCode == (byte)PCode.Tree) || (rootPart.Shape.PCode == (byte)PCode.NewTree)) { rootPart.AddFlag(LLObject.ObjectFlags.Phantom); //rootPart.ObjectFlags += (uint)LLObject.ObjectFlags.Phantom; @@ -1267,13 +1289,13 @@ namespace OpenSim.Region.Environment.Scenes public SceneObjectGroup AddTree(LLVector3 scale, LLQuaternion rotation, LLVector3 position, Tree treeType, bool newTree) { - LLUUID uuid = RegionInfo.MasterAvatarAssignedUUID; + LLUUID uuid = this.RegionInfo.MasterAvatarAssignedUUID; PrimitiveBaseShape treeShape = new PrimitiveBaseShape(); treeShape.PathCurve = 16; treeShape.PathEnd = 49900; - treeShape.PCode = newTree ? (byte) PCode.NewTree : (byte) PCode.Tree; + treeShape.PCode = newTree ? (byte)PCode.NewTree : (byte)PCode.Tree; treeShape.Scale = scale; - treeShape.State = (byte) treeType; + treeShape.State = (byte)treeType; return AddNewPrim(uuid, position, rotation, treeShape); } @@ -1338,11 +1360,12 @@ namespace OpenSim.Region.Environment.Scenes /// /// current position of Group /// Scene Object Group that we're crossing + public void CrossPrimGroupIntoNewRegion(LLVector3 position, SceneObjectGroup grp) { - m_log.Warn("Prim crossing: " + grp.UUID); - int thisx = (int) RegionInfo.RegionLocX; - int thisy = (int) RegionInfo.RegionLocY; + m_log.Warn("Prim crossing: " + grp.UUID.ToString()); + int thisx = (int)RegionInfo.RegionLocX; + int thisy = (int)RegionInfo.RegionLocY; ulong newRegionHandle = 0; LLVector3 pos = position; @@ -1351,44 +1374,43 @@ namespace OpenSim.Region.Environment.Scenes { pos.X = ((pos.X - Constants.RegionSize)); - newRegionHandle = Util.UIntsToLong((uint) ((thisx + 1) * Constants.RegionSize), (uint) (thisy * Constants.RegionSize)); - + newRegionHandle = Util.UIntsToLong((uint)((thisx + 1) * Constants.RegionSize), (uint)(thisy * Constants.RegionSize)); + // x + 1 } else if (position.X < -0.1f) { pos.X = ((pos.X + Constants.RegionSize)); - newRegionHandle = Util.UIntsToLong((uint) ((thisx - 1) * Constants.RegionSize), (uint) (thisy * Constants.RegionSize)); + newRegionHandle = Util.UIntsToLong((uint)((thisx - 1) * Constants.RegionSize), (uint)(thisy * Constants.RegionSize)); // x - 1 } if (position.Y > Constants.RegionSize + 0.1f) { pos.Y = ((pos.Y - Constants.RegionSize)); - newRegionHandle = Util.UIntsToLong((uint) (thisx * Constants.RegionSize), (uint) ((thisy + 1) * Constants.RegionSize)); + newRegionHandle = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy + 1) * Constants.RegionSize)); // y + 1 } else if (position.Y < -1f) { pos.Y = ((pos.Y + Constants.RegionSize)); - newRegionHandle = Util.UIntsToLong((uint) (thisx * Constants.RegionSize), (uint) ((thisy - 1) * Constants.RegionSize)); + newRegionHandle = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy - 1) * Constants.RegionSize)); // y - 1 } // Offset the positions for the new region across the border grp.OffsetForNewRegion(pos); - + CrossPrimGroupIntoNewRegion(newRegionHandle, grp); - } + } public void CrossPrimGroupIntoNewRegion(ulong newRegionHandle, SceneObjectGroup grp) { int primcrossingXMLmethod = 0; if (newRegionHandle != 0) { bool successYN = false; - successYN = m_sceneGridService.PrimCrossToNeighboringRegion(newRegionHandle, grp.UUID, m_sceneXmlLoader.SavePrimGroupToXML2String(grp), - primcrossingXMLmethod); + successYN = m_sceneGridService.PrimCrossToNeighboringRegion(newRegionHandle, grp.UUID, m_sceneXmlLoader.SavePrimGroupToXML2String(grp), primcrossingXMLmethod); if (successYN) { // We remove the object here @@ -1424,7 +1446,7 @@ namespace OpenSim.Region.Environment.Scenes SceneObjectPart RootPrim = GetSceneObjectPart(primID); if (RootPrim != null) { - if (RootPrim.Shape.PCode == (byte) PCode.Prim) + if (RootPrim.Shape.PCode == (byte)PCode.Prim) { SceneObjectGroup grp = RootPrim.ParentGroup; if (grp != null) @@ -1440,10 +1462,12 @@ namespace OpenSim.Region.Environment.Scenes // with the deeded object, it goes back to them grp.SetFromAssetID(grp.RootPart.LastOwnerID); - m_innerScene.AttachObject(sp.ControllingClient, grp.LocalId, 0, grp.GroupRotation, grp.AbsolutePosition); + m_innerScene.AttachObject(sp.ControllingClient, grp.LocalId, (uint)0, grp.GroupRotation, grp.AbsolutePosition); } } } + + } } return true; @@ -1452,6 +1476,7 @@ namespace OpenSim.Region.Environment.Scenes { return false; } + } #endregion @@ -1466,9 +1491,9 @@ namespace OpenSim.Region.Environment.Scenes public override void AddNewClient(IClientAPI client, bool child) { m_log.DebugFormat( - "[CONNECTION DEBUGGING]: Creating new client for {0} at {1}", + "[CONNECTION DEBUGGING]: Creating new client for {0} at {1}", client.AgentId, RegionInfo.RegionName); - + SubscribeToClientEvents(client); ScenePresence presence = null; @@ -1538,19 +1563,19 @@ namespace OpenSim.Region.Environment.Scenes client.OnObjectDuplicateOnRay += doObjectDuplicateOnRay; client.OnUpdatePrimFlags += m_innerScene.UpdatePrimFlags; client.OnRequestObjectPropertiesFamily += m_innerScene.RequestObjectPropertiesFamily; - client.OnParcelPropertiesRequest += LandChannel.handleParcelPropertiesRequest; - client.OnParcelDivideRequest += LandChannel.handleParcelDivideRequest; - client.OnParcelJoinRequest += LandChannel.handleParcelJoinRequest; + client.OnParcelPropertiesRequest += new ParcelPropertiesRequest(LandChannel.handleParcelPropertiesRequest); + client.OnParcelDivideRequest += new ParcelDivideRequest(LandChannel.handleParcelDivideRequest); + client.OnParcelJoinRequest += new ParcelJoinRequest(LandChannel.handleParcelJoinRequest); client.OnParcelPropertiesUpdateRequest += - LandChannel.handleParcelPropertiesUpdateRequest; - client.OnParcelSelectObjects += LandChannel.handleParcelSelectObjectsRequest; + new ParcelPropertiesUpdateRequest(LandChannel.handleParcelPropertiesUpdateRequest); + client.OnParcelSelectObjects += new ParcelSelectObjects(LandChannel.handleParcelSelectObjectsRequest); client.OnParcelObjectOwnerRequest += - LandChannel.handleParcelObjectOwnersRequest; - client.OnParcelAccessListRequest += LandChannel.handleParcelAccessRequest; + new ParcelObjectOwnerRequest(LandChannel.handleParcelObjectOwnersRequest); + client.OnParcelAccessListRequest += new ParcelAccessListRequest(LandChannel.handleParcelAccessRequest); client.OnParcelAccessListUpdateRequest += - LandChannel.handleParcelAccessUpdateRequest; + new ParcelAccessListUpdateRequest(LandChannel.handleParcelAccessUpdateRequest); - client.OnEstateOwnerMessage += m_estateManager.handleEstateOwnerMessage; + client.OnEstateOwnerMessage += new EstateOwnerMessageRequest(m_estateManager.handleEstateOwnerMessage); client.OnRegionInfoRequest += m_estateManager.HandleRegionInfoRequest; client.OnEstateCovenantRequest += m_estateManager.HandleEstateCovenantRequest; client.OnRequestGodlikePowers += handleRequestGodlikePowers; @@ -1591,38 +1616,41 @@ namespace OpenSim.Region.Environment.Scenes client.OnSetStartLocationRequest += SetHomeRezPoint; client.OnUndo += m_innerScene.HandleUndo; - + EventManager.TriggerOnNewClient(client); } - public virtual void TeleportClientHome(LLUUID AgentId, IClientAPI client) { UserProfileData UserProfile = CommsManager.UserService.GetUserProfile(AgentId); if (UserProfile != null) { ulong homeRegion = UserProfile.HomeRegion; - LLVector3 homePostion = new LLVector3(UserProfile.HomeLocationX, UserProfile.HomeLocationY, UserProfile.HomeLocationZ); + LLVector3 homePostion = new LLVector3(UserProfile.HomeLocationX,UserProfile.HomeLocationY,UserProfile.HomeLocationZ); LLVector3 homeLookat = new LLVector3(UserProfile.HomeLookAt); - RequestTeleportLocation(client, homeRegion, homePostion, homeLookat, 0); + RequestTeleportLocation(client, homeRegion, homePostion,homeLookat,(uint)0); + } - } + + } public void doObjectDuplicateOnRay(uint localID, uint dupeFlags, LLUUID AgentID, LLUUID GroupID, - LLUUID RayTargetObj, LLVector3 RayEnd, LLVector3 RayStart, - bool BypassRaycast, bool RayEndIsIntersection, bool CopyCenters, bool CopyRotates) + LLUUID RayTargetObj, LLVector3 RayEnd, LLVector3 RayStart, + bool BypassRaycast, bool RayEndIsIntersection, bool CopyCenters, bool CopyRotates) { + LLVector3 pos = LLVector3.Zero; bool frontFacesOnly = true; - + SceneObjectPart target = GetSceneObjectPart(localID); if (target != null) { + LLVector3 direction = LLVector3.Norm(RayEnd - RayStart); Vector3 AXOrigin = new Vector3(RayStart.X, RayStart.Y, RayStart.Z); Vector3 AXdirection = new Vector3(direction.X, direction.Y, direction.Z); - + if (target != null) { if (target.ParentGroup != null) @@ -1652,8 +1680,9 @@ namespace OpenSim.Region.Environment.Scenes if (scaleComponent.Z != 0) ScaleOffset = scale.Z; ScaleOffset = Math.Abs(ScaleOffset); LLVector3 intersectionpoint = new LLVector3(ei.ipoint.x, ei.ipoint.y, ei.ipoint.z); - - + + + if (CopyCenters) { // now we cast a ray from inside the prim(absolute position) to one of it's faces along the face normal. @@ -1665,7 +1694,7 @@ namespace OpenSim.Region.Environment.Scenes if (ei2.HitTF) { //m_log.Info("[RAYTRACERESULTS]: Hit:" + ei2.HitTF.ToString() + " Point: " + ei2.ipoint.ToString() + " Normal: " + ei2.normal.ToString()); - pos = new LLVector3(ei2.ipoint.x, ei2.ipoint.y, ei2.ipoint.z); + pos = new LLVector3(ei2.ipoint.x,ei2.ipoint.y,ei2.ipoint.z); } } LLVector3 normal = new LLVector3(ei.normal.x, ei.normal.y, ei.normal.z); @@ -1678,14 +1707,18 @@ namespace OpenSim.Region.Environment.Scenes m_innerScene.DuplicateObject(target.ParentGroup.LocalId, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID); } - + return; } return; } + } - } + + + + } public virtual void SetHomeRezPoint(IClientAPI remoteClient, ulong regionHandle, LLVector3 position, LLVector3 lookAt, uint flags) { UserProfileData UserProfile = CommsManager.UserService.GetUserProfile(remoteClient.AgentId); @@ -1698,22 +1731,22 @@ namespace OpenSim.Region.Environment.Scenes // We cast these to an int so as not to cause a breaking change with old regions // Newer regions treat this as a float on the ExpectUser method.. so we need to wait a few // releases before setting these to floats. (r4257) - UserProfile.HomeLocationX = (int) position.X; - UserProfile.HomeLocationY = (int) position.Y; - UserProfile.HomeLocationZ = (int) position.Z; - UserProfile.HomeLookAtX = (int) lookAt.X; - UserProfile.HomeLookAtY = (int) lookAt.Y; - UserProfile.HomeLookAtZ = (int) lookAt.Z; + UserProfile.HomeLocationX = (int)position.X; + UserProfile.HomeLocationY = (int)position.Y; + UserProfile.HomeLocationZ = (int)position.Z; + UserProfile.HomeLookAtX = (int)lookAt.X; + UserProfile.HomeLookAtY = (int)lookAt.Y; + UserProfile.HomeLookAtZ = (int)lookAt.Z; CommsManager.UserService.UpdateUserProfileProperties(UserProfile); - - remoteClient.SendAgentAlertMessage("Set home to here if supported by login service", false); + + remoteClient.SendAgentAlertMessage("Set home to here if supported by login service",false); } else { - remoteClient.SendAgentAlertMessage("Set Home request Failed", false); + remoteClient.SendAgentAlertMessage("Set Home request Failed",false); } - } + } protected virtual ScenePresence CreateAndAddScenePresence(IClientAPI client, bool child) { ScenePresence avatar = null; @@ -1779,7 +1812,7 @@ namespace OpenSim.Region.Environment.Scenes m_sceneGridService.SendCloseChildAgentConnections(agentID, childknownRegions); RemoveCapsHandler(agentID); - + CommsManager.UserProfileCacheService.RemoveUser(agentID); } @@ -1792,21 +1825,21 @@ namespace OpenSim.Region.Environment.Scenes } m_eventManager.TriggerOnRemovePresence(agentID); Broadcast(delegate(IClientAPI client) + { + try + { + client.SendKillObject(avatar.RegionHandle, avatar.LocalId); + } + catch (NullReferenceException) { - try - { - client.SendKillObject(avatar.RegionHandle, avatar.LocalId); - } - catch (NullReferenceException) - { - //We can safely ignore null reference exceptions. It means the avatar are dead and cleaned up anyway. - } - }); + //We can safely ignore null reference exceptions. It means the avatar are dead and cleaned up anyway. + } + }); ForEachScenePresence( delegate(ScenePresence presence) { presence.CoarseLocationChange(); }); - - IAgentAssetTransactions agentTransactions = RequestModuleInterface(); + + IAgentAssetTransactions agentTransactions = this.RequestModuleInterface(); if (agentTransactions != null) { agentTransactions.RemoveAgentAssetTransactions(agentID); @@ -1846,7 +1879,7 @@ namespace OpenSim.Region.Environment.Scenes } catch (Exception e) { - m_log.Error("[SCENE] Scene.cs:RemoveClient exception: " + e); + m_log.Error("[SCENE] Scene.cs:RemoveClient exception: " + e.ToString()); } // Remove client agent from profile, so new logins will work @@ -1866,12 +1899,14 @@ namespace OpenSim.Region.Environment.Scenes { lock (av) { + for (int i = 0; i < regionslst.Count; i++) { av.KnownChildRegions.Remove(regionslst[i]); } } } + } public override void CloseAllAgents(uint circuitcode) @@ -1959,7 +1994,7 @@ namespace OpenSim.Region.Environment.Scenes if (regionHandle == m_regInfo.RegionHandle) { capsPaths[agent.AgentID] = agent.CapsPath; - + if (!agent.child) { AddCapsHandler(agent.AgentID); @@ -1968,26 +2003,26 @@ namespace OpenSim.Region.Environment.Scenes ILandObject land = LandChannel.getLandObject(agent.startpos.X, agent.startpos.Y); if (land != null) { - if (land.landData.landingType == 1 && land.landData.userLocation != LLVector3.Zero) + if (land.landData.landingType == (byte)1 && land.landData.userLocation != LLVector3.Zero) { agent.startpos = land.landData.userLocation; } } } - + m_log.DebugFormat( "[CONNECTION DEBUGGING]: Creating new circuit code ({0}) for avatar {1} at {2}", agent.circuitcode, agent.AgentID, RegionInfo.RegionName); - + m_authenticateHandler.AddNewCircuit(agent.circuitcode, agent); } else { m_log.WarnFormat( - "[CONNECTION DEBUGGING]: Skipping this region for welcoming avatar {0} [{1}] at {2}", + "[CONNECTION DEBUGGING]: Skipping this region for welcoming avatar {0} [{1}] at {2}", agent.AgentID, regionHandle, RegionInfo.RegionName); } - } + } /// /// Add a caps handler for the given agent. If the CAPS handler already exists for this agent, @@ -2000,18 +2035,18 @@ namespace OpenSim.Region.Environment.Scenes /// /// public void AddCapsHandler(LLUUID agentId) - { - String capsObjectPath = GetCapsPath(agentId); + { + String capsObjectPath = GetCapsPath(agentId); m_log.DebugFormat( "[CAPS]: Setting up CAPS handler for root agent {0} in {1}", agentId, RegionInfo.RegionName); - + Caps cap = new Caps(AssetCache, m_httpListener, m_regInfo.ExternalHostName, m_httpListener.Port, capsObjectPath, agentId, m_dumpAssetsToFile, RegionInfo.RegionName); cap.RegisterHandlers(); - + EventManager.TriggerOnRegisterCaps(agentId, cap); cap.AddNewInventoryItem = AddInventoryItem; @@ -2020,7 +2055,7 @@ namespace OpenSim.Region.Environment.Scenes cap.CAPSFetchInventoryDescendents = CommsManager.UserProfileCacheService.HandleFetchInventoryDescendentsCAPS; cap.GetClient = m_innerScene.GetControllingClient; m_capsHandlers[agentId] = cap; - } + } /// /// Remove the caps handler for a given agent. @@ -2033,9 +2068,9 @@ namespace OpenSim.Region.Environment.Scenes if (m_capsHandlers.ContainsKey(agentId)) { m_log.DebugFormat( - "[CAPS]: Removing CAPS handler for root agent {0} in {1}", + "[CAPS]: Removing CAPS handler for root agent {0} in {1}", agentId, RegionInfo.RegionName); - + m_capsHandlers[agentId].DeregisterHandlers(); EventManager.TriggerOnDeregisterCaps(agentId, m_capsHandlers[agentId]); @@ -2070,7 +2105,7 @@ namespace OpenSim.Region.Environment.Scenes catch (Exception e) { m_log.Info("[SCENE]: Unable to do Agent Crossing."); - m_log.Debug("[SCENE]: " + e); + m_log.Debug("[SCENE]: " + e.ToString()); } //m_innerScene.SwapRootChildAgent(false); } @@ -2086,14 +2121,15 @@ namespace OpenSim.Region.Environment.Scenes // however to avoid a race condition crossing borders.. if (childAgentUpdate.IsChildAgent) { - uint rRegionX = (uint) (cAgentData.regionHandle >> 40); - uint rRegionY = (((uint) (cAgentData.regionHandle)) >> 8); + uint rRegionX = (uint)(cAgentData.regionHandle >> 40); + uint rRegionY = (((uint)(cAgentData.regionHandle)) >> 8); uint tRegionX = RegionInfo.RegionLocX; uint tRegionY = RegionInfo.RegionLocY; //Send Data to ScenePresence childAgentUpdate.ChildAgentDataUpdate(cAgentData, tRegionX, tRegionY, rRegionX, rRegionY); // Not Implemented: //TODO: Do we need to pass the message on to one of our neighbors? + } return true; } @@ -2121,7 +2157,7 @@ namespace OpenSim.Region.Environment.Scenes m_innerScene.removeUserCount(true); } // Tell a single agent to disconnect from the region. - DisableSimulatorPacket disable = (DisableSimulatorPacket) PacketPool.Instance.GetPacket(PacketType.DisableSimulator); + DisableSimulatorPacket disable = (DisableSimulatorPacket)PacketPool.Instance.GetPacket(PacketType.DisableSimulator); presence.ControllingClient.OutPacket(disable, ThrottleOutPacketType.Unknown); presence.ControllingClient.Close(true); } @@ -2271,9 +2307,9 @@ namespace OpenSim.Region.Environment.Scenes /// public void RegisterModuleInterface(M mod) { - if (!ModuleInterfaces.ContainsKey(typeof (M))) + if (!ModuleInterfaces.ContainsKey(typeof(M))) { - ModuleInterfaces.Add(typeof (M), mod); + ModuleInterfaces.Add(typeof(M), mod); } } @@ -2283,9 +2319,9 @@ namespace OpenSim.Region.Environment.Scenes /// public T RequestModuleInterface() { - if (ModuleInterfaces.ContainsKey(typeof (T))) + if (ModuleInterfaces.ContainsKey(typeof(T))) { - return (T) ModuleInterfaces[typeof (T)]; + return (T)ModuleInterfaces[typeof(T)]; } else { @@ -2300,12 +2336,14 @@ namespace OpenSim.Region.Environment.Scenes m_statsReporter.SetObjectCapacity(objects); } objectCapacity = objects; + } public List GetFriendList(LLUUID avatarID) { return CommsManager.GetUserFriendList(avatarID); } + #endregion @@ -2340,8 +2378,7 @@ namespace OpenSim.Region.Environment.Scenes } } - public void SendDialogToUser(LLUUID avatarID, string objectName, LLUUID objectID, LLUUID ownerID, string message, LLUUID TextureID, int ch, - string[] buttonlabels) + public void SendDialogToUser(LLUUID avatarID, string objectName, LLUUID objectID, LLUUID ownerID, string message, LLUUID TextureID, int ch, string[] buttonlabels) { if (m_scenePresences.ContainsKey(avatarID)) { @@ -2364,7 +2401,7 @@ namespace OpenSim.Region.Environment.Scenes } return LLUUID.Zero; } - + /// /// This method is a way for the Friends Module to create an instant @@ -2399,7 +2436,6 @@ namespace OpenSim.Region.Environment.Scenes // TODO: m_sceneGridService.DoStuff; m_sceneGridService.RemoveUserFriend(ownerID, ExfriendID); } - public virtual List StoreGetFriendsForUser(LLUUID ownerID) { // TODO: m_sceneGridService.DoStuff; @@ -2412,13 +2448,11 @@ namespace OpenSim.Region.Environment.Scenes m_statsReporter.AddOutPackets(outPackets); m_statsReporter.AddunAckedBytes(unAckedBytes); } - public void AddAgentTime(int ms) { m_statsReporter.addFrameMS(ms); m_statsReporter.addAgentMS(ms); } - public void AddAgentUpdates(int count) { m_statsReporter.AddAgentUpdates(count); @@ -2512,6 +2546,7 @@ namespace OpenSim.Region.Environment.Scenes /// The Message being sent to the user public void SendRegionMessageFromEstateTools(LLUUID FromAvatarID, LLUUID fromSessionID, String FromAvatarName, String Message) { + List presenceList = GetScenePresences(); foreach (ScenePresence presence in presenceList) @@ -2531,7 +2566,11 @@ namespace OpenSim.Region.Environment.Scenes /// The Message being sent to the user public void SendEstateMessageFromEstateTools(LLUUID FromAvatarID, LLUUID fromSessionID, String FromAvatarName, String Message) { - ClientManager.ForEachClient(delegate(IClientAPI controller) { controller.SendBlueBoxMessage(FromAvatarID, fromSessionID, FromAvatarName, Message); } + + ClientManager.ForEachClient(delegate(IClientAPI controller) + { + controller.SendBlueBoxMessage(FromAvatarID, fromSessionID, FromAvatarName, Message); + } ); } @@ -2557,24 +2596,27 @@ namespace OpenSim.Region.Environment.Scenes if (agentID == kickUserID) { ClientManager.ForEachClient(delegate(IClientAPI controller) - { - if (controller.AgentId != godID) - controller.Kick(Helpers.FieldToUTF8String(reason)); - } + { + if (controller.AgentId != godID) + controller.Kick(Helpers.FieldToUTF8String(reason)); + + + + } ); // This is a bit crude. It seems the client will be null before it actually stops the thread // The thread will kill itself eventually :/ // Is there another way to make sure *all* clients get this 'inter region' message? ClientManager.ForEachClient(delegate(IClientAPI controller) + { + ScenePresence p = GetScenePresence(controller.AgentId); + bool childagent = !p.Equals(null) && p.IsChildAgent; + if (controller.AgentId != godID && !childagent) + // Do we really want to kick the initiator of this madness? { - ScenePresence p = GetScenePresence(controller.AgentId); - bool childagent = !p.Equals(null) && p.IsChildAgent; - if (controller.AgentId != godID && !childagent) - // Do we really want to kick the initiator of this madness? - { - controller.Close(true); - } + controller.Close(true); } + } ); } else @@ -2605,6 +2647,7 @@ namespace OpenSim.Region.Environment.Scenes // Check for spoofing.. since this is permissions we're talking about here! if ((controller.SessionId == sessionID) && (controller.AgentId == agentID)) { + // Tell the object to do permission update if (localId != 0) { @@ -2614,6 +2657,7 @@ namespace OpenSim.Region.Environment.Scenes chObjectGroup.UpdatePermissions(agentID, field, localId, mask, set); } } + } } @@ -2679,7 +2723,7 @@ namespace OpenSim.Region.Environment.Scenes { if (ent is SceneObjectGroup) { - ((SceneObjectGroup) ent).ScheduleGroupForFullUpdate(); + ((SceneObjectGroup)ent).ScheduleGroupForFullUpdate(); } } } @@ -2699,7 +2743,7 @@ namespace OpenSim.Region.Environment.Scenes { if (ent is SceneObjectGroup) { - SceneObjectPart part = ((SceneObjectGroup) ent).GetChildPart((ent).UUID); + SceneObjectPart part = ((SceneObjectGroup)ent).GetChildPart(((SceneObjectGroup)ent).UUID); if (part != null) { if (part.Name == cmdparams[0]) @@ -2823,8 +2867,8 @@ namespace OpenSim.Region.Environment.Scenes #region Script Engine - private readonly bool m_dumpAssetsToFile; - private readonly List ScriptEngines = new List(); + private List ScriptEngines = new List(); + private bool m_dumpAssetsToFile; /// /// @@ -2838,11 +2882,13 @@ namespace OpenSim.Region.Environment.Scenes public void TriggerObjectChanged(uint localID, uint change) { + m_eventManager.TriggerOnScriptChangedEvent(localID, change); } public void TriggerAtTargetEvent(uint localID, uint handle, LLVector3 targetpos, LLVector3 currentpos) { + m_eventManager.TriggerAtTargetEvent(localID, handle, targetpos, currentpos); } @@ -2851,21 +2897,20 @@ namespace OpenSim.Region.Environment.Scenes m_eventManager.TriggerNotAtTargetEvent(localID); } - private bool scriptDanger(SceneObjectPart part, LLVector3 pos) + private bool scriptDanger(SceneObjectPart part,LLVector3 pos) { ILandObject parcel = LandChannel.getLandObject(pos.X, pos.Y); if (part != null) { if (parcel != null) { - if ((parcel.landData.landFlags & (uint) Parcel.ParcelFlags.AllowOtherScripts) != 0) + if ((parcel.landData.landFlags & (uint)Parcel.ParcelFlags.AllowOtherScripts) != 0) { return true; } - else if ((parcel.landData.landFlags & (uint) Parcel.ParcelFlags.AllowGroupScripts) != 0) + else if ((parcel.landData.landFlags & (uint)Parcel.ParcelFlags.AllowGroupScripts) != 0) { - if (part.OwnerID == parcel.landData.ownerID || (parcel.landData.isGroupOwned && part.GroupID == parcel.landData.groupID) || - PermissionsMngr.GenericEstatePermission(part.OwnerID)) + if (part.OwnerID == parcel.landData.ownerID || (parcel.landData.isGroupOwned && part.GroupID == parcel.landData.groupID) || PermissionsMngr.GenericEstatePermission(part.OwnerID)) { return true; } @@ -2873,7 +2918,7 @@ namespace OpenSim.Region.Environment.Scenes { return false; } - } + } else { if (part.OwnerID == parcel.landData.ownerID) @@ -2888,6 +2933,7 @@ namespace OpenSim.Region.Environment.Scenes } else { + if (pos.X > 0f && pos.X < Constants.RegionSize && pos.Y > 0f && pos.Y < Constants.RegionSize) { // The only time parcel != null when an object is inside a region is when @@ -2906,7 +2952,6 @@ namespace OpenSim.Region.Environment.Scenes return false; } } - public bool scriptDanger(uint localID, LLVector3 pos) { SceneObjectPart part = GetSceneObjectPart(localID); @@ -2922,11 +2967,13 @@ namespace OpenSim.Region.Environment.Scenes public bool pipeEventsForScript(uint localID) { + SceneObjectPart part = GetSceneObjectPart(localID); if (part != null) { LLVector3 pos = part.GetWorldPosition(); return scriptDanger(part, pos); + } else { @@ -3043,17 +3090,17 @@ namespace OpenSim.Region.Environment.Scenes } catch (Exception e) { - m_log.Info("[BUG]: " + e); + m_log.Info("[BUG]: " + e.ToString()); } } } - + /// /// Delete this object from the scene. /// /// public void DeleteSceneObjectGroup(SceneObjectGroup group) - { + { SceneObjectPart rootPart = (group).GetChildPart(group.UUID); if (rootPart.PhysActor != null) { @@ -3070,15 +3117,15 @@ namespace OpenSim.Region.Environment.Scenes m_innerScene.RemoveAPrimCount(); } group.DeleteParts(); - + // In case anybody else retains a reference to this group, signal deletion by changing the name // to null. We can't zero out the UUID because this is taken from the root part, which has already // been removed. // FIXME: This is a really poor temporary solution, since it still leaves plenty of scope for race // conditions where a user deletes an entity while it is being stored. Really, the update // code needs a redesign. - group.Name = null; - } + group.Name = null; + } /// /// @@ -3098,6 +3145,7 @@ namespace OpenSim.Region.Environment.Scenes // action(presence); // } // } + /// /// /// @@ -3187,7 +3235,6 @@ namespace OpenSim.Region.Environment.Scenes } return visualParams; } - #endregion } -} \ No newline at end of file +} diff --git a/OpenSim/Region/Environment/Scenes/SceneBase.cs b/OpenSim/Region/Environment/Scenes/SceneBase.cs index 435dc8b..d9dc1da 100644 --- a/OpenSim/Region/Environment/Scenes/SceneBase.cs +++ b/OpenSim/Region/Environment/Scenes/SceneBase.cs @@ -40,11 +40,6 @@ namespace OpenSim.Region.Environment.Scenes { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - /// - /// XXX These two methods are very temporary - /// - protected Dictionary capsPaths = new Dictionary(); - #region Events public event restart OnRestart; @@ -55,38 +50,41 @@ namespace OpenSim.Region.Environment.Scenes private readonly ClientManager m_clientManager = new ClientManager(); + public ClientManager ClientManager + { + get { return m_clientManager; } + } + + protected ulong m_regionHandle; + protected string m_regionName; + protected RegionInfo m_regInfo; + //public TerrainEngine Terrain; public ITerrainChannel Heightmap; public ILandChannel LandChannel; - private AssetCache m_assetCache; - - protected string m_datastore; protected EventManager m_eventManager; - private uint m_nextLocalId = 8880000; - protected RegionInfo m_regInfo; - protected ulong m_regionHandle; - protected string m_regionName; - - protected RegionStatus m_regStatus; - public EventManager EventManager { get { return m_eventManager; } } + + protected string m_datastore; + + private uint m_nextLocalId = 8880000; + + private AssetCache m_assetCache; + public AssetCache AssetCache { get { return m_assetCache; } set { m_assetCache = value; } } - - public ClientManager ClientManager - { - get { return m_clientManager; } - } + + protected RegionStatus m_regStatus; public RegionStatus Region_Status { @@ -143,8 +141,6 @@ namespace OpenSim.Region.Environment.Scenes #endregion - #region IScene Members - /// /// /// @@ -159,18 +155,6 @@ namespace OpenSim.Region.Environment.Scenes get { return m_nextLocalId++; } } - public string GetCapsPath(LLUUID agentId) - { - if (capsPaths.ContainsKey(agentId)) - { - return capsPaths[agentId]; - } - - return null; - } - - #endregion - #region admin stuff /// @@ -189,7 +173,6 @@ namespace OpenSim.Region.Environment.Scenes { return false; } - public abstract bool OtherRegionUp(RegionInfo thisRegion); public virtual string GetSimulatorVersion() @@ -212,10 +195,24 @@ namespace OpenSim.Region.Environment.Scenes } catch (Exception e) { - m_log.Error("[SCENE]: SceneBase.cs: Close() - Failed with exception " + e); + m_log.Error("[SCENE]: SceneBase.cs: Close() - Failed with exception " + e.ToString()); } } #endregion + + /// + /// XXX These two methods are very temporary + /// + protected Dictionary capsPaths = new Dictionary(); + public string GetCapsPath(LLUUID agentId) + { + if (capsPaths.ContainsKey(agentId)) + { + return capsPaths[agentId]; + } + + return null; + } } -} \ No newline at end of file +} diff --git a/OpenSim/Region/Environment/Scenes/SceneCommunicationService.cs b/OpenSim/Region/Environment/Scenes/SceneCommunicationService.cs index b44847b..91bbdb7 100644 --- a/OpenSim/Region/Environment/Scenes/SceneCommunicationService.cs +++ b/OpenSim/Region/Environment/Scenes/SceneCommunicationService.cs @@ -43,47 +43,13 @@ namespace OpenSim.Region.Environment.Scenes public class SceneCommunicationService //one instance per region { - #region Delegates - - public delegate void InformNeighbourThatRegionUpDelegate(RegionInfo region, ulong regionhandle); - - public delegate void SendChildAgentDataUpdateDelegate(ChildAgentDataUpdate cAgentData, ScenePresence presence); - - public delegate void SendCloseChildAgentDelegate(LLUUID agentID, List regionlst); - - #endregion - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - public string _debugRegionName = String.Empty; - private AgentCrossing handlerAvatarCrossingIntoRegion; // OnAvatarCrossingIntoRegion; - private ChildAgentUpdate handlerChildAgentUpdate; // OnChildAgentUpdate; - private CloseAgentConnection handlerCloseAgentConnection; // OnCloseAgentConnection; - private ExpectPrimDelegate handlerExpectPrim; // OnExpectPrim; - private ExpectUserDelegate handlerExpectUser; // OnExpectUser; - private PrimCrossing handlerPrimCrossingIntoRegion; // OnPrimCrossingIntoRegion; - private RegionUp handlerRegionUp; // OnRegionUp; - private RemoveKnownRegionsFromAvatarList handlerRemoveKnownRegionFromAvatar; // OnRemoveKnownRegionFromAvatar; - - public KillObjectDelegate KillObject; protected CommunicationsManager m_commsProvider; protected RegionInfo m_regionInfo; protected RegionCommsListener regionCommsHost; - public SceneCommunicationService(CommunicationsManager commsMan) - { - m_commsProvider = commsMan; - m_commsProvider.GridService.gdebugRegionName = _debugRegionName; - m_commsProvider.InterRegion.rdebugRegionName = _debugRegionName; - } - - public string debugRegionName - { - get { return _debugRegionName; } - set { _debugRegionName = value; } - } - public event AgentCrossing OnAvatarCrossingIntoRegion; public event ExpectUserDelegate OnExpectUser; public event ExpectPrimDelegate OnExpectPrim; @@ -93,6 +59,31 @@ namespace OpenSim.Region.Environment.Scenes public event ChildAgentUpdate OnChildAgentUpdate; public event RemoveKnownRegionsFromAvatarList OnRemoveKnownRegionFromAvatar; + private AgentCrossing handlerAvatarCrossingIntoRegion = null; // OnAvatarCrossingIntoRegion; + private ExpectUserDelegate handlerExpectUser = null; // OnExpectUser; + private ExpectPrimDelegate handlerExpectPrim = null; // OnExpectPrim; + private CloseAgentConnection handlerCloseAgentConnection = null; // OnCloseAgentConnection; + private PrimCrossing handlerPrimCrossingIntoRegion = null; // OnPrimCrossingIntoRegion; + private RegionUp handlerRegionUp = null; // OnRegionUp; + private ChildAgentUpdate handlerChildAgentUpdate = null; // OnChildAgentUpdate; + private RemoveKnownRegionsFromAvatarList handlerRemoveKnownRegionFromAvatar = null; // OnRemoveKnownRegionFromAvatar; + + public KillObjectDelegate KillObject; + public string _debugRegionName = String.Empty; + + public string debugRegionName + { + get { return _debugRegionName; } + set { _debugRegionName = value; } + } + + public SceneCommunicationService(CommunicationsManager commsMan) + { + m_commsProvider = commsMan; + m_commsProvider.GridService.gdebugRegionName = _debugRegionName; + m_commsProvider.InterRegion.rdebugRegionName = _debugRegionName; + } + public void RegisterRegion(RegionInfo regionInfos) { m_regionInfo = regionInfos; @@ -108,7 +99,7 @@ namespace OpenSim.Region.Environment.Scenes regionCommsHost.OnAvatarCrossingIntoRegion += AgentCrossing; regionCommsHost.OnCloseAgentConnection += CloseConnection; regionCommsHost.OnRegionUp += newRegionUp; - regionCommsHost.OnChildAgentUpdate += ChildAgentUpdate; + regionCommsHost.OnChildAgentUpdate += ChildAgentUpdate; } else { @@ -131,6 +122,218 @@ namespace OpenSim.Region.Environment.Scenes } } + #region CommsManager Event handlers + + /// + /// + /// + /// + /// + /// + protected void NewUserConnection(ulong regionHandle, AgentCircuitData agent) + { + handlerExpectUser = OnExpectUser; + if (handlerExpectUser != null) + { + //m_log.Info("[INTER]: " + debugRegionName + ": SceneCommunicationService: OnExpectUser Fired for User:" + agent.firstname + " " + agent.lastname); + handlerExpectUser(regionHandle, agent); + } + } + + protected bool newRegionUp(RegionInfo region) + { + handlerRegionUp = OnRegionUp; + if (handlerRegionUp != null) + { + //m_log.Info("[INTER]: " + debugRegionName + ": SceneCommunicationService: newRegionUp Fired for User:" + region.RegionName); + handlerRegionUp(region); + } + return true; + } + + protected bool ChildAgentUpdate(ulong regionHandle, ChildAgentDataUpdate cAgentData) + { + handlerChildAgentUpdate = OnChildAgentUpdate; + if (handlerChildAgentUpdate != null) + handlerChildAgentUpdate(regionHandle, cAgentData); + + + return true; + } + + protected void AgentCrossing(ulong regionHandle, LLUUID agentID, LLVector3 position, bool isFlying) + { + handlerAvatarCrossingIntoRegion = OnAvatarCrossingIntoRegion; + if (handlerAvatarCrossingIntoRegion != null) + { + handlerAvatarCrossingIntoRegion(regionHandle, agentID, position, isFlying); + } + } + + protected bool IncomingPrimCrossing(ulong regionHandle, LLUUID primID, String objXMLData, int XMLMethod) + { + handlerExpectPrim = OnExpectPrim; + if (handlerExpectPrim != null) + { + return handlerExpectPrim(regionHandle, primID, objXMLData, XMLMethod); + } + else + { + return false; + } + + } + + protected void PrimCrossing(ulong regionHandle, LLUUID primID, LLVector3 position, bool isPhysical) + { + handlerPrimCrossingIntoRegion = OnPrimCrossingIntoRegion; + if (handlerPrimCrossingIntoRegion != null) + { + handlerPrimCrossingIntoRegion(regionHandle, primID, position, isPhysical); + } + } + + protected bool CloseConnection(ulong regionHandle, LLUUID agentID) + { + m_log.Info("[INTERREGION]: Incoming Agent Close Request for agent: " + agentID.ToString()); + handlerCloseAgentConnection = OnCloseAgentConnection; + if (handlerCloseAgentConnection != null) + { + return handlerCloseAgentConnection(regionHandle, agentID); + } + return false; + } + + #endregion + + #region Inform Client of Neighbours + + private delegate void InformClientOfNeighbourDelegate( + ScenePresence avatar, AgentCircuitData a, ulong regionHandle, IPEndPoint endPoint); + + private void InformClientOfNeighbourCompleted(IAsyncResult iar) + { + InformClientOfNeighbourDelegate icon = (InformClientOfNeighbourDelegate) iar.AsyncState; + icon.EndInvoke(iar); + } + + /// + /// Async compnent for informing client of which neighbours exists + /// + /// + /// This needs to run asynchronesously, as a network timeout may block the thread for a long while + /// + /// + /// + /// + /// + private void InformClientOfNeighbourAsync(ScenePresence avatar, AgentCircuitData a, ulong regionHandle, + IPEndPoint endPoint) + { + m_log.Info("[INTERGRID]: Starting to inform client about neighbours"); + bool regionAccepted = m_commsProvider.InterRegion.InformRegionOfChildAgent(regionHandle, a); + + if (regionAccepted) + { + avatar.ControllingClient.InformClientOfNeighbour(regionHandle, endPoint); + avatar.AddNeighbourRegion(regionHandle); + m_log.Info("[INTERGRID]: Completed inform client about neighbours"); + } + } + + public void RequestNeighbors(RegionInfo region) + { + List neighbours = + m_commsProvider.GridService.RequestNeighbours(m_regionInfo.RegionLocX, m_regionInfo.RegionLocY); + //IPEndPoint blah = new IPEndPoint(); + + //blah.Address = region.RemotingAddress; + //blah.Port = region.RemotingPort; + } + + /// + /// This informs all neighboring regions about agent "avatar". + /// Calls an asynchronous method to do so.. so it doesn't lag the sim. + /// + public void EnableNeighbourChildAgents(ScenePresence avatar, List lstneighbours) + { + List neighbours = new List(); + + //m_commsProvider.GridService.RequestNeighbours(m_regionInfo.RegionLocX, m_regionInfo.RegionLocY); + for (int i = 0; i < lstneighbours.Count; i++) + { + // We don't want to keep sending to regions that consistently fail on comms. + if (!(lstneighbours[i].commFailTF)) + { + neighbours.Add(new SimpleRegionInfo(lstneighbours[i])); + } + } + // we're going to be using the above code once neighbour cache is correct. Currently it doesn't appear to be + // So we're temporarily going back to the old method of grabbing it from the Grid Server Every time :/ + neighbours = + m_commsProvider.GridService.RequestNeighbours(m_regionInfo.RegionLocX, m_regionInfo.RegionLocY); + + if (neighbours != null) + { + for (int i = 0; i < neighbours.Count; i++) + { + AgentCircuitData agent = avatar.ControllingClient.RequestClientInfo(); + agent.BaseFolder = LLUUID.Zero; + agent.InventoryFolder = LLUUID.Zero; + agent.startpos = new LLVector3(128, 128, 70); + agent.child = true; + + InformClientOfNeighbourDelegate d = InformClientOfNeighbourAsync; + + try + { + d.BeginInvoke(avatar, agent, neighbours[i].RegionHandle, neighbours[i].ExternalEndPoint, + InformClientOfNeighbourCompleted, + d); + } + catch (Exception e) + { + m_log.ErrorFormat( + "[REGIONINFO]: Could not resolve external hostname {0} for region {1} ({2}, {3}). {4}", + neighbours[i].ExternalHostName, + neighbours[i].RegionHandle, + neighbours[i].RegionLocX, + neighbours[i].RegionLocY, + e); + + // FIXME: Okay, even though we've failed, we're still going to throw the exception on, + // since I don't know what will happen if we just let the client continue + + // XXX: Well, decided to swallow the exception instead for now. Let us see how that goes. + // throw e; + + } + } + } + } + + /// + /// This informs a single neighboring region about agent "avatar". + /// Calls an asynchronous method to do so.. so it doesn't lag the sim. + /// + public void InformNeighborChildAgent(ScenePresence avatar, RegionInfo region, List neighbours) + { + AgentCircuitData agent = avatar.ControllingClient.RequestClientInfo(); + agent.BaseFolder = LLUUID.Zero; + agent.InventoryFolder = LLUUID.Zero; + agent.startpos = new LLVector3(128, 128, 70); + agent.child = true; + + InformClientOfNeighbourDelegate d = InformClientOfNeighbourAsync; + d.BeginInvoke(avatar, agent, region.RegionHandle, region.ExternalEndPoint, + InformClientOfNeighbourCompleted, + d); + } + + #endregion + + public delegate void InformNeighbourThatRegionUpDelegate(RegionInfo region, ulong regionhandle); + private void InformNeighborsThatRegionisUpCompleted(IAsyncResult iar) { InformNeighbourThatRegionUpDelegate icon = (InformNeighbourThatRegionUpDelegate) iar.AsyncState; @@ -187,6 +390,8 @@ namespace OpenSim.Region.Environment.Scenes //bool val = m_commsProvider.InterRegion.RegionUp(new SearializableRegionInfo(region)); } + public delegate void SendChildAgentDataUpdateDelegate(ChildAgentDataUpdate cAgentData, ScenePresence presence); + /// /// This informs all neighboring regions about the settings of it's child agent. /// Calls an asynchronous method to do so.. so it doesn't lag the sim. @@ -217,6 +422,7 @@ namespace OpenSim.Region.Environment.Scenes { // We're ignoring a collection was modified error because this data gets old and outdated fast. } + } private void SendChildAgentDataUpdateCompleted(IAsyncResult iar) @@ -229,17 +435,20 @@ namespace OpenSim.Region.Environment.Scenes { // This assumes that we know what our neighbors are. SendChildAgentDataUpdateDelegate d = SendChildAgentDataUpdateAsync; - d.BeginInvoke(cAgentData, presence, + d.BeginInvoke(cAgentData,presence, SendChildAgentDataUpdateCompleted, d); } + public delegate void SendCloseChildAgentDelegate( LLUUID agentID, List regionlst); + /// /// This Closes child agents on neighboring regions /// Calls an asynchronous method to do so.. so it doesn't lag the sim. /// private void SendCloseChildAgentAsync(LLUUID agentID, List regionlst) { + foreach (ulong regionHandle in regionlst) { bool regionAccepted = m_commsProvider.InterRegion.TellRegionToCloseChildConnection(regionHandle, agentID); @@ -247,11 +456,14 @@ namespace OpenSim.Region.Environment.Scenes if (regionAccepted) { m_log.Info("[INTERGRID]: Completed sending agent Close agent Request to neighbor"); + } else { m_log.Info("[INTERGRID]: Failed sending agent Close agent Request to neighbor"); + } + } // We remove the list of known regions from the agent's known region list through an event // to scene, because, if an agent logged of, it's likely that there will be no scene presence @@ -265,7 +477,7 @@ namespace OpenSim.Region.Environment.Scenes private void SendCloseChildAgentCompleted(IAsyncResult iar) { - SendCloseChildAgentDelegate icon = (SendCloseChildAgentDelegate) iar.AsyncState; + SendCloseChildAgentDelegate icon = (SendCloseChildAgentDelegate)iar.AsyncState; icon.EndInvoke(iar); } @@ -344,28 +556,28 @@ namespace OpenSim.Region.Environment.Scenes // assume local regions are always up destRegionUp = true; } - if (destRegionUp) + if(destRegionUp) { avatar.Close(); - + // Compared to ScenePresence.CrossToNewRegion(), there's no obvious code to handle a teleport // failure at this point (unlike a border crossing failure). So perhaps this can never fail // once we reach here... avatar.Scene.RemoveCapsHandler(avatar.UUID); - + m_commsProvider.InterRegion.InformRegionOfChildAgent(regionHandle, agent); m_commsProvider.InterRegion.ExpectAvatarCrossing(regionHandle, avatar.ControllingClient.AgentId, - position, false); + position, false); AgentCircuitData circuitdata = avatar.ControllingClient.RequestClientInfo(); - + // TODO Should construct this behind a method - string capsPath = - "http://" + reg.ExternalHostName + ":" + reg.HttpPort - + "/CAPS/" + circuitdata.CapsPath + "0000/"; - + string capsPath = + "http://" + reg.ExternalHostName + ":" + reg.HttpPort + + "/CAPS/" + circuitdata.CapsPath + "0000/"; + m_log.DebugFormat( - "[CAPS]: Sending new CAPS seed url {0} to client {1}", capsPath, avatar.UUID); - + "[CAPS]: Sending new CAPS seed url {0} to client {1}", capsPath, avatar.UUID); + avatar.ControllingClient.SendRegionTeleport(regionHandle, 13, reg.ExternalEndPoint, 4, (1 << 4), capsPath); avatar.MakeChildAgent(); @@ -375,13 +587,13 @@ namespace OpenSim.Region.Environment.Scenes { KillObject(avatar.LocalId); } - uint newRegionX = (uint) (regionHandle >> 40); - uint newRegionY = (((uint) (regionHandle)) >> 8); - uint oldRegionX = (uint) (m_regionInfo.RegionHandle >> 40); - uint oldRegionY = (((uint) (m_regionInfo.RegionHandle)) >> 8); - if (Util.fast_distance2d((int) (newRegionX - oldRegionX), (int) (newRegionY - oldRegionY)) > 3) + uint newRegionX = (uint)(regionHandle >> 40); + uint newRegionY = (((uint)(regionHandle)) >> 8); + uint oldRegionX = (uint)(m_regionInfo.RegionHandle >> 40); + uint oldRegionY = (((uint)(m_regionInfo.RegionHandle)) >> 8); + if (Util.fast_distance2d((int)(newRegionX - oldRegionX), (int)(newRegionY - oldRegionY)) > 3) { - SendCloseChildAgentConnections(avatar.UUID, avatar.GetKnownRegionList()); + SendCloseChildAgentConnections(avatar.UUID,avatar.GetKnownRegionList()); } } else @@ -416,7 +628,7 @@ namespace OpenSim.Region.Environment.Scenes public void LogOffUser(LLUUID userid, LLUUID regionid, ulong regionhandle, float posx, float posy, float posz) { - m_commsProvider.LogOffUser(userid, regionid, regionhandle, posx, posy, posz); + m_commsProvider.LogOffUser(userid, regionid, regionhandle, posx, posy, posz); } public void ClearUserAgent(LLUUID avatarID) @@ -444,7 +656,7 @@ namespace OpenSim.Region.Environment.Scenes return m_commsProvider.GetUserFriendList(friendlistowner); } - public List RequestNeighbourMapBlocks(int minX, int minY, int maxX, int maxY) + public List RequestNeighbourMapBlocks(int minX, int minY, int maxX, int maxY) { return m_commsProvider.GridService.RequestNeighbourMapBlocks(minX, minY, maxX, maxY); } @@ -453,213 +665,5 @@ namespace OpenSim.Region.Environment.Scenes { return m_commsProvider.GenerateAgentPickerRequestResponse(queryID, query); } - - #region CommsManager Event handlers - - /// - /// - /// - /// - /// - /// - protected void NewUserConnection(ulong regionHandle, AgentCircuitData agent) - { - handlerExpectUser = OnExpectUser; - if (handlerExpectUser != null) - { - //m_log.Info("[INTER]: " + debugRegionName + ": SceneCommunicationService: OnExpectUser Fired for User:" + agent.firstname + " " + agent.lastname); - handlerExpectUser(regionHandle, agent); - } - } - - protected bool newRegionUp(RegionInfo region) - { - handlerRegionUp = OnRegionUp; - if (handlerRegionUp != null) - { - //m_log.Info("[INTER]: " + debugRegionName + ": SceneCommunicationService: newRegionUp Fired for User:" + region.RegionName); - handlerRegionUp(region); - } - return true; - } - - protected bool ChildAgentUpdate(ulong regionHandle, ChildAgentDataUpdate cAgentData) - { - handlerChildAgentUpdate = OnChildAgentUpdate; - if (handlerChildAgentUpdate != null) - handlerChildAgentUpdate(regionHandle, cAgentData); - - - return true; - } - - protected void AgentCrossing(ulong regionHandle, LLUUID agentID, LLVector3 position, bool isFlying) - { - handlerAvatarCrossingIntoRegion = OnAvatarCrossingIntoRegion; - if (handlerAvatarCrossingIntoRegion != null) - { - handlerAvatarCrossingIntoRegion(regionHandle, agentID, position, isFlying); - } - } - - protected bool IncomingPrimCrossing(ulong regionHandle, LLUUID primID, String objXMLData, int XMLMethod) - { - handlerExpectPrim = OnExpectPrim; - if (handlerExpectPrim != null) - { - return handlerExpectPrim(regionHandle, primID, objXMLData, XMLMethod); - } - else - { - return false; - } - } - - protected void PrimCrossing(ulong regionHandle, LLUUID primID, LLVector3 position, bool isPhysical) - { - handlerPrimCrossingIntoRegion = OnPrimCrossingIntoRegion; - if (handlerPrimCrossingIntoRegion != null) - { - handlerPrimCrossingIntoRegion(regionHandle, primID, position, isPhysical); - } - } - - protected bool CloseConnection(ulong regionHandle, LLUUID agentID) - { - m_log.Info("[INTERREGION]: Incoming Agent Close Request for agent: " + agentID); - handlerCloseAgentConnection = OnCloseAgentConnection; - if (handlerCloseAgentConnection != null) - { - return handlerCloseAgentConnection(regionHandle, agentID); - } - return false; - } - - #endregion - - #region Inform Client of Neighbours - - private void InformClientOfNeighbourCompleted(IAsyncResult iar) - { - InformClientOfNeighbourDelegate icon = (InformClientOfNeighbourDelegate) iar.AsyncState; - icon.EndInvoke(iar); - } - - /// - /// Async compnent for informing client of which neighbours exists - /// - /// - /// This needs to run asynchronesously, as a network timeout may block the thread for a long while - /// - /// - /// - /// - /// - private void InformClientOfNeighbourAsync(ScenePresence avatar, AgentCircuitData a, ulong regionHandle, - IPEndPoint endPoint) - { - m_log.Info("[INTERGRID]: Starting to inform client about neighbours"); - bool regionAccepted = m_commsProvider.InterRegion.InformRegionOfChildAgent(regionHandle, a); - - if (regionAccepted) - { - avatar.ControllingClient.InformClientOfNeighbour(regionHandle, endPoint); - avatar.AddNeighbourRegion(regionHandle); - m_log.Info("[INTERGRID]: Completed inform client about neighbours"); - } - } - - public void RequestNeighbors(RegionInfo region) - { - List neighbours = - m_commsProvider.GridService.RequestNeighbours(m_regionInfo.RegionLocX, m_regionInfo.RegionLocY); - //IPEndPoint blah = new IPEndPoint(); - - //blah.Address = region.RemotingAddress; - //blah.Port = region.RemotingPort; - } - - /// - /// This informs all neighboring regions about agent "avatar". - /// Calls an asynchronous method to do so.. so it doesn't lag the sim. - /// - public void EnableNeighbourChildAgents(ScenePresence avatar, List lstneighbours) - { - List neighbours = new List(); - - //m_commsProvider.GridService.RequestNeighbours(m_regionInfo.RegionLocX, m_regionInfo.RegionLocY); - for (int i = 0; i < lstneighbours.Count; i++) - { - // We don't want to keep sending to regions that consistently fail on comms. - if (!(lstneighbours[i].commFailTF)) - { - neighbours.Add(new SimpleRegionInfo(lstneighbours[i])); - } - } - // we're going to be using the above code once neighbour cache is correct. Currently it doesn't appear to be - // So we're temporarily going back to the old method of grabbing it from the Grid Server Every time :/ - neighbours = - m_commsProvider.GridService.RequestNeighbours(m_regionInfo.RegionLocX, m_regionInfo.RegionLocY); - - if (neighbours != null) - { - for (int i = 0; i < neighbours.Count; i++) - { - AgentCircuitData agent = avatar.ControllingClient.RequestClientInfo(); - agent.BaseFolder = LLUUID.Zero; - agent.InventoryFolder = LLUUID.Zero; - agent.startpos = new LLVector3(128, 128, 70); - agent.child = true; - - InformClientOfNeighbourDelegate d = InformClientOfNeighbourAsync; - - try - { - d.BeginInvoke(avatar, agent, neighbours[i].RegionHandle, neighbours[i].ExternalEndPoint, - InformClientOfNeighbourCompleted, - d); - } - catch (Exception e) - { - m_log.ErrorFormat( - "[REGIONINFO]: Could not resolve external hostname {0} for region {1} ({2}, {3}). {4}", - neighbours[i].ExternalHostName, - neighbours[i].RegionHandle, - neighbours[i].RegionLocX, - neighbours[i].RegionLocY, - e); - - // FIXME: Okay, even though we've failed, we're still going to throw the exception on, - // since I don't know what will happen if we just let the client continue - - // XXX: Well, decided to swallow the exception instead for now. Let us see how that goes. - // throw e; - } - } - } - } - - /// - /// This informs a single neighboring region about agent "avatar". - /// Calls an asynchronous method to do so.. so it doesn't lag the sim. - /// - public void InformNeighborChildAgent(ScenePresence avatar, RegionInfo region, List neighbours) - { - AgentCircuitData agent = avatar.ControllingClient.RequestClientInfo(); - agent.BaseFolder = LLUUID.Zero; - agent.InventoryFolder = LLUUID.Zero; - agent.startpos = new LLVector3(128, 128, 70); - agent.child = true; - - InformClientOfNeighbourDelegate d = InformClientOfNeighbourAsync; - d.BeginInvoke(avatar, agent, region.RegionHandle, region.ExternalEndPoint, - InformClientOfNeighbourCompleted, - d); - } - - private delegate void InformClientOfNeighbourDelegate( - ScenePresence avatar, AgentCircuitData a, ulong regionHandle, IPEndPoint endPoint); - - #endregion } -} \ No newline at end of file +} diff --git a/OpenSim/Region/Environment/Scenes/SceneEvents.cs b/OpenSim/Region/Environment/Scenes/SceneEvents.cs index 297d796..002fc5d 100644 --- a/OpenSim/Region/Environment/Scenes/SceneEvents.cs +++ b/OpenSim/Region/Environment/Scenes/SceneEvents.cs @@ -38,186 +38,236 @@ namespace OpenSim.Region.Environment.Scenes /// public class EventManager { - #region Delegates - - public delegate void AvatarEnteringNewParcel(ScenePresence avatar, int localLandID, LLUUID regionID); + public delegate void OnFrameDelegate(); - public delegate void ClientClosed(LLUUID clientID); + public event OnFrameDelegate OnFrame; public delegate void ClientMovement(ScenePresence client); - /// - /// DeregisterCapsEvent is called by Scene when the caps - /// handler for an agent are removed. - /// - public delegate void DeregisterCapsEvent(LLUUID agentID, Caps caps); - - public delegate void LandBuy(Object sender, LandBuyArgs e); - - public delegate void LandObjectAdded(ILandObject newParcel); - - public delegate void LandObjectRemoved(LLUUID globalID); - - public delegate void MoneyTransferEvent(Object sender, MoneyTransferArgs e); - - public delegate void NewGridInstantMessage(GridInstantMessage message); - - public delegate void NewInventoryItemUploadComplete(LLUUID avatarID, LLUUID assetID, string name, int userlevel); - - public delegate void NewRezScript(uint localID, LLUUID itemID, string script); + public event ClientMovement OnClientMovement; - public delegate void ObjectDeGrabDelegate(uint localID, IClientAPI remoteClient); + public delegate void OnTerrainTickDelegate(); - public delegate void ObjectGrabDelegate(uint localID, LLVector3 offsetPos, IClientAPI remoteClient); + public event OnTerrainTickDelegate OnTerrainTick; public delegate void OnBackupDelegate(IRegionDataStore datastore); - public delegate void OnFrameDelegate(); + public event OnBackupDelegate OnBackup; public delegate void OnNewClientDelegate(IClientAPI client); - public delegate void OnNewPresenceDelegate(ScenePresence presence); - - public delegate void OnParcelPrimCountAddDelegate(SceneObjectGroup obj); - - public delegate void OnParcelPrimCountUpdateDelegate(); + public event OnNewClientDelegate OnNewClient; - public delegate void OnPermissionErrorDelegate(LLUUID user, string reason); + public delegate void OnNewPresenceDelegate(ScenePresence presence); - public delegate void OnPluginConsoleDelegate(string[] args); + public event OnNewPresenceDelegate OnNewPresence; public delegate void OnRemovePresenceDelegate(LLUUID agentId); - public delegate void OnShutdownDelegate(); - - public delegate void OnTerrainTickDelegate(); - - /// - /// RegisterCapsEvent is called by Scene after the Caps object - /// has been instantiated and before it is return to the - /// client and provides region modules to add their caps. - /// - public delegate void RegisterCapsEvent(LLUUID agentID, Caps caps); - - public delegate void RemoveScript(uint localID, LLUUID itemID); - - public delegate void SceneGroupGrabed(LLUUID groupID, LLVector3 offset, LLUUID userID); - - public delegate bool SceneGroupMoved(LLUUID groupID, LLVector3 delta); - - public delegate void ScriptAtTargetEvent(uint localID, uint handle, LLVector3 targetpos, LLVector3 atpos); - - public delegate void ScriptChangedEvent(uint localID, uint change); - - public delegate void ScriptNotAtTargetEvent(uint localID); - - #endregion - - private AvatarEnteringNewParcel handlerAvatarEnteringNewParcel; //OnAvatarEnteringNewParcel; - private OnBackupDelegate handlerBackup; //OnBackup; - private ClientClosed handlerClientClosed; //OnClientClosed; - private ClientMovement handlerClientMovement; //OnClientMovement; - private DeregisterCapsEvent handlerDeregisterCaps; // OnDeregisterCaps; - private OnFrameDelegate handlerFrame; //OnFrame; - private NewGridInstantMessage handlerGridInstantMessageToFriends; //OnGridInstantMessageToFriendsModule; - private NewGridInstantMessage handlerGridInstantMessageToIM; //OnGridInstantMessageToIMModule; - private LandBuy handlerLandBuy; - private LandObjectAdded handlerLandObjectAdded; //OnLandObjectAdded; - private LandObjectRemoved handlerLandObjectRemoved; //OnLandObjectRemoved; - private OnNewPresenceDelegate handlerMakeChildAgent; //OnMakeChildAgent; - private MoneyTransferEvent handlerMoneyTransfer; //OnMoneyTransfer; - private OnNewClientDelegate handlerNewClient; //OnNewClient; - private NewInventoryItemUploadComplete handlerNewInventoryItemUpdateComplete; - private OnNewPresenceDelegate handlerNewPresence; //OnNewPresence; - private ObjectDeGrabDelegate handlerObjectDeGrab; //OnObjectDeGrab; - private ObjectGrabDelegate handlerObjectGrab; //OnObjectGrab; - private OnParcelPrimCountAddDelegate handlerParcelPrimCountAdd; //OnParcelPrimCountAdd; - private OnParcelPrimCountUpdateDelegate handlerParcelPrimCountUpdate; //OnParcelPrimCountUpdate; - private OnPermissionErrorDelegate handlerPermissionError; //OnPermissionError; - private OnPluginConsoleDelegate handlerPluginConsole; //OnPluginConsole; - private RegisterCapsEvent handlerRegisterCaps; // OnRegisterCaps; - private OnRemovePresenceDelegate handlerRemovePresence; //OnRemovePresence; - private RemoveScript handlerRemoveScript; //OnRemoveScript; - private NewRezScript handlerRezScript; //OnRezScript; - private SceneGroupGrabed handlerSceneGroupGrab; //OnSceneGroupGrab; - private SceneGroupMoved handlerSceneGroupMove; //OnSceneGroupMove; - private ScriptAtTargetEvent handlerScriptAtTargetEvent; - private ScriptChangedEvent handlerScriptChangedEvent; //OnScriptChangedEvent; - private ScriptNotAtTargetEvent handlerScriptNotAtTargetEvent; - private OnShutdownDelegate handlerShutdown; //OnShutdown; - private OnTerrainTickDelegate handlerTerrainTick; // OnTerainTick; - private LandBuy handlerValidateLandBuy; - - public event OnFrameDelegate OnFrame; + public event OnRemovePresenceDelegate OnRemovePresence; - public event ClientMovement OnClientMovement; + public delegate void OnParcelPrimCountUpdateDelegate(); - public event OnTerrainTickDelegate OnTerrainTick; + public event OnParcelPrimCountUpdateDelegate OnParcelPrimCountUpdate; - public event OnBackupDelegate OnBackup; + public delegate void OnParcelPrimCountAddDelegate(SceneObjectGroup obj); - public event OnNewClientDelegate OnNewClient; + public event OnParcelPrimCountAddDelegate OnParcelPrimCountAdd; - public event OnNewPresenceDelegate OnNewPresence; + public delegate void OnPluginConsoleDelegate(string[] args); - public event OnRemovePresenceDelegate OnRemovePresence; + public event OnPluginConsoleDelegate OnPluginConsole; - public event OnParcelPrimCountUpdateDelegate OnParcelPrimCountUpdate; + public delegate void OnShutdownDelegate(); - public event OnParcelPrimCountAddDelegate OnParcelPrimCountAdd; + public event OnShutdownDelegate OnShutdown; - public event OnPluginConsoleDelegate OnPluginConsole; + public delegate void ObjectGrabDelegate(uint localID, LLVector3 offsetPos, IClientAPI remoteClient); + public delegate void ObjectDeGrabDelegate(uint localID, IClientAPI remoteClient); - public event OnShutdownDelegate OnShutdown; + public delegate void OnPermissionErrorDelegate(LLUUID user, string reason); public event ObjectGrabDelegate OnObjectGrab; public event ObjectDeGrabDelegate OnObjectDeGrab; public event OnPermissionErrorDelegate OnPermissionError; + public delegate void NewRezScript(uint localID, LLUUID itemID, string script); + public event NewRezScript OnRezScript; + public delegate void RemoveScript(uint localID, LLUUID itemID); + public event RemoveScript OnRemoveScript; + public delegate bool SceneGroupMoved(LLUUID groupID, LLVector3 delta); + public event SceneGroupMoved OnSceneGroupMove; + public delegate void SceneGroupGrabed(LLUUID groupID, LLVector3 offset, LLUUID userID); + public event SceneGroupGrabed OnSceneGroupGrab; + public delegate void LandObjectAdded(ILandObject newParcel); + public event LandObjectAdded OnLandObjectAdded; + public delegate void LandObjectRemoved(LLUUID globalID); + public event LandObjectRemoved OnLandObjectRemoved; + public delegate void AvatarEnteringNewParcel(ScenePresence avatar, int localLandID, LLUUID regionID); + public event AvatarEnteringNewParcel OnAvatarEnteringNewParcel; + public delegate void NewGridInstantMessage(GridInstantMessage message); + public event NewGridInstantMessage OnGridInstantMessageToIMModule; public event NewGridInstantMessage OnGridInstantMessageToFriendsModule; public event NewGridInstantMessage OnGridInstantMessageToGroupsModule; + public delegate void ClientClosed(LLUUID clientID); + public event ClientClosed OnClientClosed; + public delegate void ScriptChangedEvent(uint localID, uint change); + public event ScriptChangedEvent OnScriptChangedEvent; + public delegate void ScriptAtTargetEvent(uint localID, uint handle, LLVector3 targetpos, LLVector3 atpos); + public event ScriptAtTargetEvent OnScriptAtTargetEvent; + public delegate void ScriptNotAtTargetEvent(uint localID); + public event ScriptNotAtTargetEvent OnScriptNotAtTargetEvent; public event OnNewPresenceDelegate OnMakeChildAgent; + public delegate void NewInventoryItemUploadComplete(LLUUID avatarID, LLUUID assetID, string name, int userlevel); + public event NewInventoryItemUploadComplete OnNewInventoryItemUploadComplete; + /// + /// RegisterCapsEvent is called by Scene after the Caps object + /// has been instantiated and before it is return to the + /// client and provides region modules to add their caps. + /// + public delegate void RegisterCapsEvent(LLUUID agentID, Caps caps); public event RegisterCapsEvent OnRegisterCaps; - + /// + /// DeregisterCapsEvent is called by Scene when the caps + /// handler for an agent are removed. + /// + public delegate void DeregisterCapsEvent(LLUUID agentID, Caps caps); public event DeregisterCapsEvent OnDeregisterCaps; + public class MoneyTransferArgs : EventArgs + { + public LLUUID sender; + public LLUUID receiver; + + // Always false. The SL protocol sucks. + public bool authenticated = false; + + public int amount; + public int transactiontype; + public string description; + + public MoneyTransferArgs(LLUUID asender, LLUUID areceiver, int aamount, int atransactiontype, string adescription) { + sender = asender; + receiver = areceiver; + amount = aamount; + transactiontype = atransactiontype; + description = adescription; + } + } + + public class LandBuyArgs : EventArgs + { + public LLUUID agentId = LLUUID.Zero; + + public LLUUID groupId = LLUUID.Zero; + + public LLUUID parcelOwnerID = LLUUID.Zero; + + public bool final = false; + public bool groupOwned = false; + public bool removeContribution = false; + public int parcelLocalID = 0; + public int parcelArea = 0; + public int parcelPrice = 0; + public bool authenticated = false; + public bool landValidated = false; + public bool economyValidated = false; + public int transactionID = 0; + public int amountDebited = 0; + + + public LandBuyArgs(LLUUID pagentId, LLUUID pgroupId, bool pfinal, bool pgroupOwned, + bool premoveContribution, int pparcelLocalID, int pparcelArea, int pparcelPrice, + bool pauthenticated) + { + agentId = pagentId; + groupId = pgroupId; + final = pfinal; + groupOwned = pgroupOwned; + removeContribution = premoveContribution; + parcelLocalID = pparcelLocalID; + parcelArea = pparcelArea; + parcelPrice = pparcelPrice; + authenticated = pauthenticated; + } + } + + public delegate void MoneyTransferEvent(Object sender, MoneyTransferArgs e); + + public delegate void LandBuy(Object sender, LandBuyArgs e); + public event MoneyTransferEvent OnMoneyTransfer; public event LandBuy OnLandBuy; public event LandBuy OnValidateLandBuy; /* Designated Event Deletage Instances */ + private ScriptChangedEvent handlerScriptChangedEvent = null; //OnScriptChangedEvent; + private ScriptAtTargetEvent handlerScriptAtTargetEvent = null; + private ScriptNotAtTargetEvent handlerScriptNotAtTargetEvent = null; + private ClientMovement handlerClientMovement = null; //OnClientMovement; + private OnPermissionErrorDelegate handlerPermissionError = null; //OnPermissionError; + private OnPluginConsoleDelegate handlerPluginConsole = null; //OnPluginConsole; + private OnFrameDelegate handlerFrame = null; //OnFrame; + private OnNewClientDelegate handlerNewClient = null; //OnNewClient; + private OnNewPresenceDelegate handlerNewPresence = null; //OnNewPresence; + private OnRemovePresenceDelegate handlerRemovePresence = null; //OnRemovePresence; + private OnBackupDelegate handlerBackup = null; //OnBackup; + private OnParcelPrimCountUpdateDelegate handlerParcelPrimCountUpdate = null; //OnParcelPrimCountUpdate; + private MoneyTransferEvent handlerMoneyTransfer = null; //OnMoneyTransfer; + private OnParcelPrimCountAddDelegate handlerParcelPrimCountAdd = null; //OnParcelPrimCountAdd; + private OnShutdownDelegate handlerShutdown = null; //OnShutdown; + private ObjectGrabDelegate handlerObjectGrab = null; //OnObjectGrab; + private ObjectDeGrabDelegate handlerObjectDeGrab = null; //OnObjectDeGrab; + private NewRezScript handlerRezScript = null; //OnRezScript; + private RemoveScript handlerRemoveScript = null; //OnRemoveScript; + private SceneGroupMoved handlerSceneGroupMove = null; //OnSceneGroupMove; + private SceneGroupGrabed handlerSceneGroupGrab = null; //OnSceneGroupGrab; + private LandObjectAdded handlerLandObjectAdded = null; //OnLandObjectAdded; + private LandObjectRemoved handlerLandObjectRemoved = null; //OnLandObjectRemoved; + private AvatarEnteringNewParcel handlerAvatarEnteringNewParcel = null; //OnAvatarEnteringNewParcel; + private NewGridInstantMessage handlerGridInstantMessageToIM = null; //OnGridInstantMessageToIMModule; + private NewGridInstantMessage handlerGridInstantMessageToFriends = null; //OnGridInstantMessageToFriendsModule; + private ClientClosed handlerClientClosed = null; //OnClientClosed; + private OnNewPresenceDelegate handlerMakeChildAgent = null; //OnMakeChildAgent; + private OnTerrainTickDelegate handlerTerrainTick = null; // OnTerainTick; + private RegisterCapsEvent handlerRegisterCaps = null; // OnRegisterCaps; + private DeregisterCapsEvent handlerDeregisterCaps = null; // OnDeregisterCaps; + private NewInventoryItemUploadComplete handlerNewInventoryItemUpdateComplete = null; + private LandBuy handlerLandBuy = null; + private LandBuy handlerValidateLandBuy = null; + public void TriggerOnScriptChangedEvent(uint localID, uint change) { handlerScriptChangedEvent = OnScriptChangedEvent; @@ -293,7 +343,7 @@ namespace OpenSim.Region.Environment.Scenes if (handlerParcelPrimCountUpdate != null) { handlerParcelPrimCountUpdate(); - } + } } public void TriggerMoneyTransfer(Object sender, MoneyTransferArgs e) @@ -442,6 +492,7 @@ namespace OpenSim.Region.Environment.Scenes { handlerGridInstantMessageToFriends(message); } + } } @@ -463,7 +514,7 @@ namespace OpenSim.Region.Environment.Scenes } } - public void TriggerOnRegisterCaps(LLUUID agentID, Caps caps) + public void TriggerOnRegisterCaps(LLUUID agentID, Caps caps) { handlerRegisterCaps = OnRegisterCaps; if (handlerRegisterCaps != null) @@ -472,7 +523,7 @@ namespace OpenSim.Region.Environment.Scenes } } - public void TriggerOnDeregisterCaps(LLUUID agentID, Caps caps) + public void TriggerOnDeregisterCaps(LLUUID agentID, Caps caps) { handlerDeregisterCaps = OnDeregisterCaps; if (handlerDeregisterCaps != null) @@ -489,8 +540,7 @@ namespace OpenSim.Region.Environment.Scenes handlerNewInventoryItemUpdateComplete(agentID, AssetID, AssetName, userlevel); } } - - public void TriggerLandBuy(Object sender, LandBuyArgs e) + public void TriggerLandBuy (Object sender, LandBuyArgs e) { handlerLandBuy = OnLandBuy; if (handlerLandBuy != null) @@ -498,7 +548,6 @@ namespace OpenSim.Region.Environment.Scenes handlerLandBuy(sender, e); } } - public void TriggerValidateLandBuy(Object sender, LandBuyArgs e) { handlerValidateLandBuy = OnValidateLandBuy; @@ -507,7 +556,7 @@ namespace OpenSim.Region.Environment.Scenes handlerValidateLandBuy(sender, e); } } - + public void TriggerAtTargetEvent(uint localID, uint handle, LLVector3 targetpos, LLVector3 currentpos) { handlerScriptAtTargetEvent = OnScriptAtTargetEvent; @@ -525,67 +574,5 @@ namespace OpenSim.Region.Environment.Scenes handlerScriptNotAtTargetEvent(localID); } } - - #region Nested type: LandBuyArgs - - public class LandBuyArgs : EventArgs - { - public LLUUID agentId = LLUUID.Zero; - public int amountDebited; - public bool authenticated; - public bool economyValidated; - - public bool final; - public LLUUID groupId = LLUUID.Zero; - public bool groupOwned; - public bool landValidated; - public int parcelArea; - public int parcelLocalID; - public LLUUID parcelOwnerID = LLUUID.Zero; - public int parcelPrice; - public bool removeContribution; - public int transactionID; - - - public LandBuyArgs(LLUUID pagentId, LLUUID pgroupId, bool pfinal, bool pgroupOwned, - bool premoveContribution, int pparcelLocalID, int pparcelArea, int pparcelPrice, - bool pauthenticated) - { - agentId = pagentId; - groupId = pgroupId; - final = pfinal; - groupOwned = pgroupOwned; - removeContribution = premoveContribution; - parcelLocalID = pparcelLocalID; - parcelArea = pparcelArea; - parcelPrice = pparcelPrice; - authenticated = pauthenticated; - } - } - - #endregion - - #region Nested type: MoneyTransferArgs - - public class MoneyTransferArgs : EventArgs - { - public int amount; - public bool authenticated; - public string description; - public LLUUID receiver; - public LLUUID sender; - public int transactiontype; - - public MoneyTransferArgs(LLUUID asender, LLUUID areceiver, int aamount, int atransactiontype, string adescription) - { - sender = asender; - receiver = areceiver; - amount = aamount; - transactiontype = atransactiontype; - description = adescription; - } - } - - #endregion } -} \ No newline at end of file +} diff --git a/OpenSim/Region/Environment/Scenes/SceneManager.cs b/OpenSim/Region/Environment/Scenes/SceneManager.cs index 2325ed4..2dfea2a 100644 --- a/OpenSim/Region/Environment/Scenes/SceneManager.cs +++ b/OpenSim/Region/Environment/Scenes/SceneManager.cs @@ -41,13 +41,10 @@ namespace OpenSim.Region.Environment.Scenes { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - private readonly List m_localScenes; - private Scene m_currentScene; + public event RestartSim OnRestartSim; - public SceneManager() - { - m_localScenes = new List(); - } + private readonly List m_localScenes; + private Scene m_currentScene = null; public List Scenes { @@ -74,7 +71,10 @@ namespace OpenSim.Region.Environment.Scenes } } - public event RestartSim OnRestartSim; + public SceneManager() + { + m_localScenes = new List(); + } public void Close() { @@ -180,7 +180,7 @@ namespace OpenSim.Region.Environment.Scenes [Obsolete("TODO: Remove this warning by 0.7")] public bool RunTerrainCmdOnCurrentScene(string[] cmdparams, ref string result) { - m_log.Warn("DEPRECIATED: The terrain engine has been replaced with a new terrain plugin module. Please type 'plugin terrain help' for new commands."); + m_log.Warn("DEPRECIATED: The terrain engine has been replaced with a new terrain plugin module. Please type 'plugin terrain help' for new commands."); return false; } @@ -252,8 +252,8 @@ namespace OpenSim.Region.Environment.Scenes public bool TrySetCurrentScene(LLUUID regionID) { - Console.WriteLine("Searching for Region: '{0}'", regionID); - + Console.WriteLine("Searching for Region: '{0}'", regionID.ToString()); + foreach (Scene scene in m_localScenes) { if (scene.RegionInfo.RegionID == regionID) @@ -262,7 +262,7 @@ namespace OpenSim.Region.Environment.Scenes return true; } } - + return false; } @@ -313,7 +313,7 @@ namespace OpenSim.Region.Environment.Scenes { foreach (Scene mscene in m_localScenes) { - if ((mscene.RegionInfo.InternalEndPoint.Equals(ipEndPoint.Address)) && + if((mscene.RegionInfo.InternalEndPoint.Equals(ipEndPoint.Address)) && (mscene.RegionInfo.InternalEndPoint.Port == ipEndPoint.Port)) { scene = mscene; @@ -327,22 +327,22 @@ namespace OpenSim.Region.Environment.Scenes public void SetDebugPacketOnCurrentScene(int newDebug) { ForEachCurrentScene(delegate(Scene scene) - { - List scenePresences = scene.GetScenePresences(); + { + List scenePresences = scene.GetScenePresences(); - foreach (ScenePresence scenePresence in scenePresences) + foreach (ScenePresence scenePresence in scenePresences) + { + if (!scenePresence.IsChildAgent) { - if (!scenePresence.IsChildAgent) - { - m_log.ErrorFormat("Packet debug for {0} {1} set to {2}", - scenePresence.Firstname, - scenePresence.Lastname, - newDebug); - - scenePresence.ControllingClient.SetDebug(newDebug); - } + m_log.ErrorFormat("Packet debug for {0} {1} set to {2}", + scenePresence.Firstname, + scenePresence.Lastname, + newDebug); + + scenePresence.ControllingClient.SetDebug(newDebug); } - }); + } + }); } public List GetCurrentSceneAvatars() @@ -350,17 +350,17 @@ namespace OpenSim.Region.Environment.Scenes List avatars = new List(); ForEachCurrentScene(delegate(Scene scene) - { - List scenePresences = scene.GetScenePresences(); + { + List scenePresences = scene.GetScenePresences(); - foreach (ScenePresence scenePresence in scenePresences) - { - if (!scenePresence.IsChildAgent) - { - avatars.Add(scenePresence); - } - } - }); + foreach (ScenePresence scenePresence in scenePresences) + { + if (!scenePresence.IsChildAgent) + { + avatars.Add(scenePresence); + } + } + }); return avatars; } @@ -381,11 +381,11 @@ namespace OpenSim.Region.Environment.Scenes public void SetCurrentSceneTimePhase(int timePhase) { ForEachCurrentScene(delegate(Scene scene) - { - scene.SetTimePhase( - timePhase) - ; - }); + { + scene.SetTimePhase( + timePhase) + ; + }); } public void ForceCurrentSceneClientUpdate() @@ -453,4 +453,4 @@ namespace OpenSim.Region.Environment.Scenes m_localScenes.ForEach(action); } } -} \ No newline at end of file +} diff --git a/OpenSim/Region/Environment/Scenes/SceneObjectGroup.Inventory.cs b/OpenSim/Region/Environment/Scenes/SceneObjectGroup.Inventory.cs index d051ed9..824a536 100644 --- a/OpenSim/Region/Environment/Scenes/SceneObjectGroup.Inventory.cs +++ b/OpenSim/Region/Environment/Scenes/SceneObjectGroup.Inventory.cs @@ -49,6 +49,7 @@ namespace OpenSim.Region.Environment.Scenes if (part != null) { part.StartScript(itemID); + } else { @@ -56,9 +57,9 @@ namespace OpenSim.Region.Environment.Scenes "[PRIMINVENTORY]: " + "Couldn't find part {0} in object group {1}, {2} to start script with ID {3}", localID, Name, UUID, itemID); - } + } } - + // /// Start a given script. // /// // /// @@ -79,7 +80,7 @@ namespace OpenSim.Region.Environment.Scenes // localID, Name, UUID, itemID); // } // } - + /// /// Start the scripts contained in all the prims in this group. /// @@ -105,7 +106,7 @@ namespace OpenSim.Region.Environment.Scenes } } } - + /// Start a given script. /// /// @@ -125,9 +126,9 @@ namespace OpenSim.Region.Environment.Scenes "[PRIMINVENTORY]: " + "Couldn't find part {0} in object group {1}, {2} to stop script with ID {3}", partID, Name, UUID, itemID); - } - } - + } + } + /// /// /// @@ -170,7 +171,7 @@ namespace OpenSim.Region.Environment.Scenes localID, Name, UUID); } } - + /// /// Add an inventory item to a prim in this group. /// @@ -179,7 +180,7 @@ namespace OpenSim.Region.Environment.Scenes /// /// The item UUID that should be used by the new item. /// - public bool AddInventoryItem(IClientAPI remoteClient, uint localID, + public bool AddInventoryItem(IClientAPI remoteClient, uint localID, InventoryItemBase item, LLUUID copyItemID) { LLUUID newItemId = (copyItemID != LLUUID.Zero) ? copyItemID : item.ID; @@ -188,8 +189,8 @@ namespace OpenSim.Region.Environment.Scenes if (part != null) { TaskInventoryItem taskItem = new TaskInventoryItem(); - - taskItem.ItemID = newItemId; + + taskItem.ItemID = newItemId; taskItem.AssetID = item.AssetID; taskItem.Name = item.Name; taskItem.Description = item.Description; @@ -197,15 +198,15 @@ namespace OpenSim.Region.Environment.Scenes taskItem.CreatorID = item.Creator; taskItem.Type = item.AssetType; taskItem.InvType = item.InvType; - + taskItem.BaseMask = item.BasePermissions; taskItem.OwnerMask = item.CurrentPermissions; // FIXME: ignoring group permissions for now as they aren't stored in item taskItem.EveryoneMask = item.EveryOnePermissions; taskItem.NextOwnerMask = item.NextPermissions; - + part.AddInventoryItem(taskItem); - + return true; } else @@ -218,7 +219,7 @@ namespace OpenSim.Region.Environment.Scenes return false; } - + /// /// Returns an existing inventory item. Returns the original, so any changes will be live. /// @@ -238,11 +239,11 @@ namespace OpenSim.Region.Environment.Scenes "[PRIMINVENTORY]: " + "Couldn't find prim local ID {0} in prim {1}, {2} to get inventory item ID {3}", primID, part.Name, part.UUID, itemID); - } - + } + return null; - } - + } + /// /// Update an existing inventory item. /// @@ -254,8 +255,8 @@ namespace OpenSim.Region.Environment.Scenes SceneObjectPart part = GetChildPart(item.ParentPartID); if (part != null) { - part.UpdateInventoryItem(item); - + part.UpdateInventoryItem(item); + return true; } else @@ -264,22 +265,22 @@ namespace OpenSim.Region.Environment.Scenes "[PRIMINVENTORY]: " + "Couldn't find prim ID {0} to update item {1}, {2}", item.ParentPartID, item.Name, item.ItemID); - } - + } + return false; - } + } public int RemoveInventoryItem(uint localID, LLUUID itemID) { SceneObjectPart part = GetChildPart(localID); if (part != null) - { + { int type = part.RemoveInventoryItem(itemID); - + return type; } - + return -1; - } + } } -} \ No newline at end of file +} diff --git a/OpenSim/Region/Environment/Scenes/SceneObjectGroup.cs b/OpenSim/Region/Environment/Scenes/SceneObjectGroup.cs index 1ea2f24..5d39790 100644 --- a/OpenSim/Region/Environment/Scenes/SceneObjectGroup.cs +++ b/OpenSim/Region/Environment/Scenes/SceneObjectGroup.cs @@ -72,7 +72,7 @@ namespace OpenSim.Region.Environment.Scenes object_rez = 4194304 } - internal struct scriptPosTarget + struct scriptPosTarget { public LLVector3 targetPos; public float tolerance; @@ -82,14 +82,14 @@ namespace OpenSim.Region.Environment.Scenes public partial class SceneObjectGroup : EntityBase { - private readonly Dictionary m_targets = new Dictionary(); - private PrimCountTaintedDelegate handlerPrimCountTainted; + private PrimCountTaintedDelegate handlerPrimCountTainted = null; /// /// Signal whether the non-inventory attributes of any prims in the group have changed /// since the group's last persistent backup /// - public bool HasGroupChanged; + public bool HasGroupChanged = false; + private LLVector3 lastPhysGroupPos; @@ -104,8 +104,11 @@ namespace OpenSim.Region.Environment.Scenes protected SceneObjectPart m_rootPart; private Dictionary m_scriptEvents = new Dictionary(); - private bool m_scriptListens_atTarget; - private bool m_scriptListens_notAtTarget; + private Dictionary m_targets = new Dictionary(); + + private bool m_scriptListens_atTarget = false; + private bool m_scriptListens_notAtTarget = false; + #region Properties @@ -116,7 +119,7 @@ namespace OpenSim.Region.Environment.Scenes /// think really there should be a list (or whatever) in each scenepresence /// saying what prim(s) that user has selected. /// - protected bool m_isSelected; + protected bool m_isSelected = false; /// /// @@ -183,6 +186,7 @@ namespace OpenSim.Region.Environment.Scenes string.Format("[SCENE OBJECT GROUP]: Object {0} has no root part.", m_uuid)); } + return m_rootPart.GroupPosition; } @@ -202,7 +206,7 @@ namespace OpenSim.Region.Environment.Scenes part.GroupPosition = val; } } - + //if (m_rootPart.PhysActor != null) //{ //m_rootPart.PhysActor.Position = @@ -212,7 +216,7 @@ namespace OpenSim.Region.Environment.Scenes //} } } - + public override uint LocalId { get @@ -511,11 +515,10 @@ namespace OpenSim.Region.Environment.Scenes m_scene.EventManager.OnBackup += ProcessBackup; } } - public LLVector3 GroupScale() { - LLVector3 minScale = new LLVector3(Constants.RegionSize, Constants.RegionSize, Constants.RegionSize); - LLVector3 maxScale = new LLVector3(0f, 0f, 0f); + LLVector3 minScale = new LLVector3(Constants.RegionSize,Constants.RegionSize,Constants.RegionSize); + LLVector3 maxScale = new LLVector3(0f,0f,0f); LLVector3 finalScale = new LLVector3(0.5f, 0.5f, 0.5f); lock (m_parts) @@ -538,8 +541,8 @@ namespace OpenSim.Region.Environment.Scenes finalScale.Y = (minScale.Y > maxScale.Y) ? minScale.Y : maxScale.Y; finalScale.Z = (minScale.Z > maxScale.Z) ? minScale.Z : maxScale.Z; return finalScale; - } + } public EntityIntersection TestIntersection(Ray hRay, bool frontFacesOnly, bool faceCenters) { // We got a request from the inner_scene to raytrace along the Ray hRay @@ -562,7 +565,7 @@ namespace OpenSim.Region.Environment.Scenes // Telling the prim to raytrace. //EntityIntersection inter = part.TestIntersection(hRay, parentrotation); - EntityIntersection inter = part.TestIntersectionOBB(hRay, parentrotation, frontFacesOnly, faceCenters); + EntityIntersection inter = part.TestIntersectionOBB(hRay, parentrotation,frontFacesOnly, faceCenters); // This may need to be updated to the maximum draw distance possible.. // We might (and probably will) be checking for prim creation from other sims @@ -681,11 +684,12 @@ namespace OpenSim.Region.Environment.Scenes DetachFromBackup(this); m_rootPart.m_attachedAvatar = agentID; - + if (m_rootPart.PhysActor != null) { m_scene.PhysicsScene.RemovePrim(m_rootPart.PhysActor); m_rootPart.PhysActor = null; + } AbsolutePosition = AttachOffset; @@ -705,28 +709,27 @@ namespace OpenSim.Region.Environment.Scenes m_rootPart.ScheduleFullUpdate(); } } - public byte GetAttachmentPoint() { if (m_rootPart != null) { return m_rootPart.Shape.State; } - return 0; + return (byte)0; } public void ClearPartAttachmentData() { foreach (SceneObjectPart part in m_parts.Values) { - part.SetAttachmentPoint(0); + part.SetAttachmentPoint((Byte)0); } } public void DetachToGround() { ScenePresence avatar = m_scene.GetScenePresence(m_rootPart.m_attachedAvatar); - LLVector3 detachedpos = new LLVector3(127f, 127f, 127f); + LLVector3 detachedpos = new LLVector3(127f,127f,127f); if (avatar != null) { detachedpos = avatar.AbsolutePosition; @@ -735,14 +738,14 @@ namespace OpenSim.Region.Environment.Scenes AbsolutePosition = detachedpos; m_rootPart.m_attachedAvatar = LLUUID.Zero; m_rootPart.SetParentLocalId(0); - m_rootPart.SetAttachmentPoint(0); + m_rootPart.SetAttachmentPoint((byte)0); m_rootPart.m_IsAttachment = false; m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_scene.m_physicalPrim); AttachToBackup(); m_rootPart.ScheduleFullUpdate(); m_rootPart.ClearUndoState(); + } - public void DetachToInventoryPrep() { ScenePresence avatar = m_scene.GetScenePresence(m_rootPart.m_attachedAvatar); @@ -752,7 +755,7 @@ namespace OpenSim.Region.Environment.Scenes //detachedpos = avatar.AbsolutePosition; avatar.RemoveAttachment(this); } - + m_rootPart.m_attachedAvatar = LLUUID.Zero; m_rootPart.SetParentLocalId(0); //m_rootPart.SetAttachmentPoint((byte)0); @@ -761,8 +764,8 @@ namespace OpenSim.Region.Environment.Scenes //m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_scene.m_physicalPrim); //AttachToBackup(); //m_rootPart.ScheduleFullUpdate(); + } - /// /// /// @@ -823,6 +826,7 @@ namespace OpenSim.Region.Environment.Scenes try { m_parts.Add(part.UUID, part); + } catch (Exception e) { @@ -843,6 +847,7 @@ namespace OpenSim.Region.Environment.Scenes if (part.UUID != m_rootPart.UUID) { part.ParentID = m_rootPart.LocalId; + } } } @@ -855,10 +860,10 @@ namespace OpenSim.Region.Environment.Scenes foreach (SceneObjectPart part in m_parts.Values) { part.UUID = LLUUID.Random(); + } } } - // helper provided for parts. public int GetSceneMaxUndo() { @@ -866,7 +871,6 @@ namespace OpenSim.Region.Environment.Scenes return m_scene.MaxUndoCount; return 5; } - public void ResetChildPrimPhysicsPositions() { AbsolutePosition = AbsolutePosition; @@ -893,6 +897,7 @@ namespace OpenSim.Region.Environment.Scenes { SceneObjectPart part = GetChildPart(localId); OnGrabPart(part, offsetPos, remoteClient); + } } @@ -900,6 +905,7 @@ namespace OpenSim.Region.Environment.Scenes { part.StoreUndoState(); part.OnGrab(offsetPos, remoteClient); + } public virtual void OnGrabGroup(LLVector3 offsetPos, IClientAPI remoteClient) @@ -963,19 +969,19 @@ namespace OpenSim.Region.Environment.Scenes public void aggregateScriptEvents() { - uint objectflagupdate = RootPart.GetEffectiveObjectFlags(); + uint objectflagupdate=(uint)RootPart.GetEffectiveObjectFlags(); - scriptEvents aggregateScriptEvents = 0; + scriptEvents aggregateScriptEvents=0; lock (m_parts) { foreach (SceneObjectPart part in m_parts.Values) { - if (part == null) - continue; - if (part != RootPart) - part.ObjectFlags = objectflagupdate; - aggregateScriptEvents |= part.m_aggregateScriptEvents; + if(part == null) + continue; + if(part != RootPart) + part.ObjectFlags = objectflagupdate; + aggregateScriptEvents |= part.m_aggregateScriptEvents; } } @@ -1059,139 +1065,6 @@ namespace OpenSim.Region.Environment.Scenes } } - internal void SetAxisRotation(int axis, int rotate10) - { - bool setX = false; - bool setY = false; - bool setZ = false; - - int xaxis = 2; - int yaxis = 4; - int zaxis = 8; - - if (m_rootPart != null) - { - setX = ((axis & xaxis) != 0) ? true : false; - setY = ((axis & yaxis) != 0) ? true : false; - setZ = ((axis & zaxis) != 0) ? true : false; - - float setval = (rotate10 > 0) ? 1f : 0f; - - if (setX) - m_rootPart.m_rotationAxis.X = setval; - if (setY) - m_rootPart.m_rotationAxis.Y = setval; - if (setZ) - m_rootPart.m_rotationAxis.Z = setval; - - if (setX || setY || setZ) - { - m_rootPart.SetPhysicsAxisRotation(); - } - } - } - - public int registerTargetWaypoint(LLVector3 target, float tolerance) - { - scriptPosTarget waypoint = new scriptPosTarget(); - waypoint.targetPos = target; - waypoint.tolerance = tolerance; - uint handle = m_scene.PrimIDAllocate(); - lock (m_targets) - { - m_targets.Add(handle, waypoint); - } - return (int) handle; - } - - public void unregisterTargetWaypoint(int handle) - { - lock (m_targets) - { - if (m_targets.ContainsKey((uint) handle)) - m_targets.Remove((uint) handle); - } - } - - private void checkAtTargets() - { - if (m_scriptListens_atTarget || m_scriptListens_notAtTarget) - { - if (m_targets.Count > 0) - { - bool at_target = false; - //LLVector3 targetPos; - //uint targetHandle; - Dictionary atTargets = new Dictionary(); - lock (m_targets) - { - foreach (uint idx in m_targets.Keys) - { - scriptPosTarget target = m_targets[idx]; - if (Util.GetDistanceTo(target.targetPos, m_rootPart.GroupPosition) <= target.tolerance) - { - // trigger at_target - if (m_scriptListens_atTarget) - { - // Reusing att.tolerance to hold the index of the target in the targets dictionary - // to avoid deadlocking the sim. - at_target = true; - scriptPosTarget att = new scriptPosTarget(); - att.targetPos = target.targetPos; - att.tolerance = idx; - atTargets.Add(idx, att); - } - } - } - } - if (atTargets.Count > 0) - { - uint[] localids = new uint[0]; - lock (m_parts) - { - localids = new uint[m_parts.Count]; - int cntr = 0; - foreach (SceneObjectPart part in m_parts.Values) - { - localids[cntr] = part.LocalId; - cntr++; - } - } - for (int ctr = 0; ctr < localids.Length; ctr++) - { - foreach (uint target in atTargets.Keys) - { - scriptPosTarget att = atTargets[target]; - // Reusing att.tolerance to hold the index of the target in the targets dictionary - // to avoid deadlocking the sim. - m_scene.TriggerAtTargetEvent(localids[ctr], (uint) att.tolerance, att.targetPos, m_rootPart.GroupPosition); - } - } - return; - } - if (m_scriptListens_notAtTarget && !at_target) - { - //trigger not_at_target - uint[] localids = new uint[0]; - lock (m_parts) - { - localids = new uint[m_parts.Count]; - int cntr = 0; - foreach (SceneObjectPart part in m_parts.Values) - { - localids[cntr] = part.LocalId; - cntr++; - } - } - for (int ctr = 0; ctr < localids.Length; ctr++) - { - m_scene.TriggerNotAtTargetEvent(localids[ctr]); - } - } - } - } - } - #region Events /// @@ -1489,8 +1362,9 @@ namespace OpenSim.Region.Environment.Scenes { m_parts.Add(newPart.UUID, newPart); } - + SetPartAsNonRoot(newPart); + } /// @@ -1560,30 +1434,32 @@ namespace OpenSim.Region.Environment.Scenes /// public override void Update() { + lock (m_parts) { //if (m_rootPart.m_IsAttachment) //{ - //foreach (SceneObjectPart part in m_parts.Values) - //{ - //part.SendScheduledUpdates(); + //foreach (SceneObjectPart part in m_parts.Values) + //{ + //part.SendScheduledUpdates(); + //} + //return; //} - //return; - //} - + if (Util.GetDistanceTo(lastPhysGroupPos, AbsolutePosition) > 0.02) { m_rootPart.UpdateFlag = 1; lastPhysGroupPos = AbsolutePosition; } - //foreach (SceneObjectPart part in m_parts.Values) - //{ - //if (part.UpdateFlag == 0) part.UpdateFlag = 1; - //} - - - checkAtTargets(); + //foreach (SceneObjectPart part in m_parts.Values) + //{ + //if (part.UpdateFlag == 0) part.UpdateFlag = 1; + //} + + + checkAtTargets(); + if ((Math.Abs(lastPhysGroupRot.W - GroupRotation.W) > 0.1) || (Math.Abs(lastPhysGroupRot.X - GroupRotation.X) > 0.1) @@ -1887,7 +1763,7 @@ namespace OpenSim.Region.Environment.Scenes public void DelinkFromGroup(uint partID) { SceneObjectPart linkPart = GetChildPart(partID); - + if (null != linkPart) { linkPart.ClearUndoState(); @@ -2072,10 +1948,10 @@ namespace OpenSim.Region.Environment.Scenes proper.ObjectData[0].FromTaskID = LLUUID.Zero; proper.ObjectData[0].GroupID = LLUUID.Zero; proper.ObjectData[0].InventorySerial = (short) m_rootPart.InventorySerial; - + proper.ObjectData[0].LastOwnerID = m_rootPart.LastOwnerID; // proper.ObjectData[0].LastOwnerID = LLUUID.Zero; - + proper.ObjectData[0].ObjectID = UUID; proper.ObjectData[0].OwnerID = m_rootPart.OwnerID; proper.ObjectData[0].TouchName = Helpers.StringToField(m_rootPart.TouchName); @@ -2515,5 +2391,140 @@ namespace OpenSim.Region.Environment.Scenes } #endregion + + internal void SetAxisRotation(int axis, int rotate10) + { + bool setX = false; + bool setY = false; + bool setZ = false; + + int xaxis = 2; + int yaxis = 4; + int zaxis = 8; + + if (m_rootPart != null) + { + setX = ((axis & xaxis) != 0) ? true : false; + setY = ((axis & yaxis) != 0) ? true : false; + setZ = ((axis & zaxis) != 0) ? true : false; + + float setval = (rotate10 > 0) ? 1f : 0f; + + if (setX) + m_rootPart.m_rotationAxis.X = setval; + if (setY) + m_rootPart.m_rotationAxis.Y = setval; + if (setZ) + m_rootPart.m_rotationAxis.Z = setval; + + if (setX || setY || setZ) + { + m_rootPart.SetPhysicsAxisRotation(); + } + + } + } + + public int registerTargetWaypoint(LLVector3 target, float tolerance) + { + scriptPosTarget waypoint = new scriptPosTarget(); + waypoint.targetPos = target; + waypoint.tolerance = tolerance; + uint handle = m_scene.PrimIDAllocate(); + lock (m_targets) + { + m_targets.Add(handle, waypoint); + } + return (int)handle; + } + public void unregisterTargetWaypoint(int handle) + { + lock (m_targets) + { + if (m_targets.ContainsKey((uint)handle)) + m_targets.Remove((uint)handle); + } + } + + private void checkAtTargets() + { + if (m_scriptListens_atTarget || m_scriptListens_notAtTarget) + { + if (m_targets.Count > 0) + { + bool at_target = false; + //LLVector3 targetPos; + //uint targetHandle; + Dictionary atTargets = new Dictionary(); + lock (m_targets) + { + foreach (uint idx in m_targets.Keys) + { + scriptPosTarget target = m_targets[idx]; + if (Util.GetDistanceTo(target.targetPos, m_rootPart.GroupPosition) <= target.tolerance) + { + // trigger at_target + if (m_scriptListens_atTarget) + { + // Reusing att.tolerance to hold the index of the target in the targets dictionary + // to avoid deadlocking the sim. + at_target = true; + scriptPosTarget att = new scriptPosTarget(); + att.targetPos = target.targetPos; + att.tolerance = (float)idx; + atTargets.Add(idx, att); + } + } + } + } + if (atTargets.Count > 0) + { + uint[] localids = new uint[0]; + lock (m_parts) + { + localids = new uint[m_parts.Count]; + int cntr = 0; + foreach (SceneObjectPart part in m_parts.Values) + { + localids[cntr] = part.LocalId; + cntr++; + } + } + for (int ctr = 0; ctr < localids.Length; ctr++) + { + foreach (uint target in atTargets.Keys) + { + scriptPosTarget att = atTargets[target]; + // Reusing att.tolerance to hold the index of the target in the targets dictionary + // to avoid deadlocking the sim. + m_scene.TriggerAtTargetEvent(localids[ctr], (uint)att.tolerance, att.targetPos, m_rootPart.GroupPosition); + + + } + } + return; + } + if (m_scriptListens_notAtTarget && !at_target) + { + //trigger not_at_target + uint[] localids = new uint[0]; + lock (m_parts) + { + localids = new uint[m_parts.Count]; + int cntr = 0; + foreach (SceneObjectPart part in m_parts.Values) + { + localids[cntr] = part.LocalId; + cntr++; + } + } + for (int ctr = 0; ctr < localids.Length; ctr++) + { + m_scene.TriggerNotAtTargetEvent(localids[ctr]); + } + } + } + } + } } -} \ No newline at end of file +} diff --git a/OpenSim/Region/Environment/Scenes/SceneObjectPart.Inventory.cs b/OpenSim/Region/Environment/Scenes/SceneObjectPart.Inventory.cs index c8a8f95..0215cec 100644 --- a/OpenSim/Region/Environment/Scenes/SceneObjectPart.Inventory.cs +++ b/OpenSim/Region/Environment/Scenes/SceneObjectPart.Inventory.cs @@ -41,12 +41,7 @@ namespace OpenSim.Region.Environment.Scenes { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - private readonly string m_inventoryFileName = String.Empty; - - /// - /// Tracks whether inventory has changed since the last persistent backup - /// - private bool HasInventoryChanged; + private string m_inventoryFileName = String.Empty; /// /// The inventory folder for this prim @@ -54,17 +49,6 @@ namespace OpenSim.Region.Environment.Scenes private LLUUID m_folderID = LLUUID.Zero; /// - /// Serial count for inventory file , used to tell if inventory has changed - /// no need for this to be part of Database backup - /// - protected uint m_inventorySerial; - - /// - /// Holds in memory prim inventory - /// - protected TaskInventoryDictionary m_taskInventory = new TaskInventoryDictionary(); - - /// /// Exposing this is not particularly good, but it's one of the least evils at the moment to see /// folder id from prim inventory item data, since it's not (yet) actually stored with the prim. /// @@ -74,12 +58,23 @@ namespace OpenSim.Region.Environment.Scenes set { m_folderID = value; } } + /// + /// Serial count for inventory file , used to tell if inventory has changed + /// no need for this to be part of Database backup + /// + protected uint m_inventorySerial = 0; + public uint InventorySerial { get { return m_inventorySerial; } set { m_inventorySerial = value; } } + /// + /// Holds in memory prim inventory + /// + protected TaskInventoryDictionary m_taskInventory = new TaskInventoryDictionary(); + public TaskInventoryDictionary TaskInventory { get { return m_taskInventory; } @@ -87,6 +82,11 @@ namespace OpenSim.Region.Environment.Scenes } /// + /// Tracks whether inventory has changed since the last persistent backup + /// + private bool HasInventoryChanged; + + /// /// Reset LLUUIDs for all the items in the prim's inventory. This involves either generating /// new ones or setting existing UUIDs to the correct parent UUIDs. /// @@ -96,14 +96,14 @@ namespace OpenSim.Region.Environment.Scenes public void ResetInventoryIDs() { lock (TaskInventory) - { + { if (0 == TaskInventory.Count) { - return; + return; } - - HasInventoryChanged = true; - + + HasInventoryChanged = true; + IList items = new List(TaskInventory.Values); TaskInventory.Clear(); @@ -132,9 +132,9 @@ namespace OpenSim.Region.Environment.Scenes if (ownerId != item.OwnerID) { item.LastOwnerID = item.OwnerID; - item.OwnerID = ownerId; - item.BaseMask = item.NextOwnerMask & (uint) PermissionMask.All; - item.OwnerMask = item.NextOwnerMask & (uint) PermissionMask.All; + item.OwnerID = ownerId; + item.BaseMask = item.NextOwnerMask & (uint)PermissionMask.All; + item.OwnerMask = item.NextOwnerMask & (uint)PermissionMask.All; } } } @@ -194,22 +194,22 @@ namespace OpenSim.Region.Environment.Scenes AssetCache cache = m_parentGroup.Scene.AssetCache; cache.GetAsset(item.AssetID, delegate(LLUUID assetID, AssetBase asset) - { - if (null == asset) - { - m_log.ErrorFormat( - "[PRIMINVENTORY]: " + - "Couldn't start script {0}, {1} since asset ID {2} could not be found", - item.Name, item.ItemID, item.AssetID); - } - else - { - string script = Helpers.FieldToUTF8String(asset.Data); - m_parentGroup.Scene.EventManager.TriggerRezScript(LocalId, item.ItemID, script); - m_parentGroup.AddActiveScriptCount(1); - ScheduleFullUpdate(); - } - }, false); + { + if (null == asset) + { + m_log.ErrorFormat( + "[PRIMINVENTORY]: " + + "Couldn't start script {0}, {1} since asset ID {2} could not be found", + item.Name, item.ItemID, item.AssetID); + } + else + { + string script = Helpers.FieldToUTF8String(asset.Data); + m_parentGroup.Scene.EventManager.TriggerRezScript(LocalId,item.ItemID,script); + m_parentGroup.AddActiveScriptCount(1); + ScheduleFullUpdate(); + } + }, false); } } @@ -226,6 +226,7 @@ namespace OpenSim.Region.Environment.Scenes if (m_taskInventory.ContainsKey(itemId)) { StartScript(m_taskInventory[itemId]); + } else { @@ -262,7 +263,7 @@ namespace OpenSim.Region.Environment.Scenes { foreach (TaskInventoryItem item in m_taskInventory.Values) { - if (item.Name == name) + if(item.Name == name) return true; } return false; @@ -270,14 +271,14 @@ namespace OpenSim.Region.Environment.Scenes private string FindAvailableInventoryName(string name) { - if (!InventoryContainsName(name)) + if(!InventoryContainsName(name)) return name; - int suffix = 1; - while (suffix < 256) + int suffix=1; + while(suffix < 256) { - string tryName = String.Format("{0} {1}", name, suffix); - if (!InventoryContainsName(tryName)) + string tryName=String.Format("{0} {1}", name, suffix); + if(!InventoryContainsName(tryName)) return tryName; suffix++; } @@ -294,11 +295,11 @@ namespace OpenSim.Region.Environment.Scenes item.CreationDate = 1000; item.ParentPartID = UUID; - string name = FindAvailableInventoryName(item.Name); - if (name == String.Empty) + string name=FindAvailableInventoryName(item.Name); + if(name == String.Empty) return; - item.Name = name; + item.Name=name; lock (m_taskInventory) { @@ -346,7 +347,7 @@ namespace OpenSim.Region.Environment.Scenes // m_log.DebugFormat( // "[PRIM INVENTORY]: Retrieved task inventory item {0}, {1} from prim {2}, {3}", // m_taskInventory[itemID].Name, itemID, Name, UUID); - + return m_taskInventory[itemID]; } else @@ -427,6 +428,7 @@ namespace OpenSim.Region.Environment.Scenes scriptcount++; } } + } if (scriptcount <= 0) { @@ -455,14 +457,14 @@ namespace OpenSim.Region.Environment.Scenes /// /// public bool GetInventoryFileName(IClientAPI client, uint localID) - { + { // m_log.DebugFormat( // "[PRIM INVENTORY]: Received request from client {0} for inventory file name of {1}, {2}", // client.AgentId, Name, UUID); - + if (m_inventorySerial > 0) { - client.SendTaskInventory(m_uuid, (short) m_inventorySerial, + client.SendTaskInventory(m_uuid, (short)m_inventorySerial, Helpers.StringToField(m_inventoryFileName)); return true; } @@ -478,9 +480,9 @@ namespace OpenSim.Region.Environment.Scenes /// /// public void RequestInventoryFile(IXfer xferManager) - { + { byte[] fileData = new byte[0]; - + // Confusingly, the folder item has to be the object id, while the 'parent id' has to be zero. This matches // what appears to happen in the Second Life protocol. If this isn't the case. then various functionality // isn't available (such as drag from prim inventory to agent inventory) @@ -491,53 +493,53 @@ namespace OpenSim.Region.Environment.Scenes foreach (TaskInventoryItem item in m_taskInventory.Values) { invString.AddItemStart(); - invString.AddNameValueLine("item_id", item.ItemID.ToString()); + invString.AddNameValueLine("item_id", item.ItemID.ToString()); invString.AddNameValueLine("parent_id", m_folderID.ToString()); invString.AddPermissionsStart(); - + // FIXME: Temporary until permissions are properly sorted. invString.AddNameValueLine("base_mask", "7fffffff"); invString.AddNameValueLine("owner_mask", "7fffffff"); invString.AddNameValueLine("group_mask", "7fffffff"); invString.AddNameValueLine("everyone_mask", "7fffffff"); invString.AddNameValueLine("next_owner_mask", "7fffffff"); - + // invString.AddNameValueLine("group_mask", "00000000"); // invString.AddNameValueLine("everyone_mask", "00000000"); // invString.AddNameValueLine("next_owner_mask", "00086000"); - + // invString.AddNameValueLine("base_mask", Helpers.UIntToHexString(item.BaseMask)); // invString.AddNameValueLine("owner_mask", Helpers.UIntToHexString(item.OwnerMask)); // invString.AddNameValueLine("group_mask", Helpers.UIntToHexString(item.GroupMask)); // invString.AddNameValueLine("everyone_mask", Helpers.UIntToHexString(item.EveryoneMask)); // invString.AddNameValueLine("next_owner_mask", Helpers.UIntToHexString(item.NextOwnerMask)); - + invString.AddNameValueLine("creator_id", item.CreatorID.ToString()); invString.AddNameValueLine("owner_id", item.OwnerID.ToString()); - + invString.AddNameValueLine("last_owner_id", item.LastOwnerID.ToString()); // invString.AddNameValueLine("last_owner_id", item.OwnerID.ToString()); - + invString.AddNameValueLine("group_id", item.GroupID.ToString()); invString.AddSectionEnd(); - + invString.AddNameValueLine("asset_id", item.AssetID.ToString()); invString.AddNameValueLine("type", TaskInventoryItem.Types[item.Type]); invString.AddNameValueLine("inv_type", TaskInventoryItem.InvTypes[item.InvType]); invString.AddNameValueLine("flags", "00000000"); - + invString.AddSaleStart(); invString.AddNameValueLine("sale_type", "not"); invString.AddNameValueLine("sale_price", "0"); invString.AddSectionEnd(); - + invString.AddNameValueLine("name", item.Name + "|"); invString.AddNameValueLine("desc", item.Description + "|"); - + invString.AddNameValueLine("creation_date", item.CreationDate.ToString()); // invString.AddNameValueLine("creation_date", "1209151453"); - + invString.AddSectionEnd(); } } @@ -569,8 +571,6 @@ namespace OpenSim.Region.Environment.Scenes } } - #region Nested type: InventoryStringBuilder - public class InventoryStringBuilder { public string BuildString = String.Empty; @@ -596,13 +596,13 @@ namespace OpenSim.Region.Environment.Scenes BuildString += "\tpermissions 0\n"; AddSectionStart(); } - + public void AddSaleStart() { BuildString += "\tsale_info\t0\n"; AddSectionStart(); - } - + } + protected void AddSectionStart() { BuildString += "\t{\n"; @@ -629,7 +629,5 @@ namespace OpenSim.Region.Environment.Scenes { } } - - #endregion } -} \ No newline at end of file +} diff --git a/OpenSim/Region/Environment/Scenes/SceneObjectPart.cs b/OpenSim/Region/Environment/Scenes/SceneObjectPart.cs index 3a9e1c2..3dbd809 100644 --- a/OpenSim/Region/Environment/Scenes/SceneObjectPart.cs +++ b/OpenSim/Region/Environment/Scenes/SceneObjectPart.cs @@ -56,7 +56,6 @@ namespace OpenSim.Region.Environment.Scenes Something5 = 64, Something6 = 128 } - [Flags] public enum Changed : uint { @@ -69,7 +68,6 @@ namespace OpenSim.Region.Environment.Scenes ALLOWED_DROP = 64, OWNER = 128 } - [Flags] public enum TextureAnimFlags : byte { @@ -83,36 +81,70 @@ namespace OpenSim.Region.Environment.Scenes SCALE = 0x40 } - + [Serializable] public partial class SceneObjectPart : IScriptHost, ISerializable { - public uint Category; - public Int32 CreationDate; - [XmlIgnore] public LLUUID fromAssetID = LLUUID.Zero; - public LLUUID GroupID; - public LLUUID LastOwnerID; + [XmlIgnore] public PhysicsActor PhysActor = null; + + public LLUUID LastOwnerID; + public LLUUID OwnerID; + public LLUUID GroupID; + public int OwnershipCost; + public byte ObjectSaleType; + public int SalePrice; + public uint Category; + // TODO: This needs to be persisted in next XML version update! + [XmlIgnore] public int[] PayPrice = {-2,-2,-2,-2,-2}; + [XmlIgnore] private Dictionary m_scriptEvents = new Dictionary(); + [XmlIgnore] public scriptEvents m_aggregateScriptEvents=0; [XmlIgnore] private LLObject.ObjectFlags LocalFlags = LLObject.ObjectFlags.None; - [XmlIgnore] public scriptEvents m_aggregateScriptEvents = 0; + [XmlIgnore] public bool m_IsAttachment = false; + [XmlIgnore] public uint m_attachmentPoint = (byte)0; [XmlIgnore] public LLUUID m_attachedAvatar = LLUUID.Zero; [XmlIgnore] public LLVector3 m_attachedPos = LLVector3.Zero; - [XmlIgnore] public uint m_attachmentPoint = 0; - [XmlIgnore] public bool m_IsAttachment; + [XmlIgnore] public LLUUID fromAssetID = LLUUID.Zero; + + [XmlIgnore] public bool m_undoing = false; + + public Int32 CreationDate; + public uint ParentID = 0; private PhysicsVector m_lastRotationalVelocity = PhysicsVector.Zero; - protected SceneObjectGroup m_parentGroup; + private Vector3 m_sitTargetPosition = new Vector3(0, 0, 0); + private Quaternion m_sitTargetOrientation = new Quaternion(0, 0, 0, 1); + public LLUUID m_sitTargetAvatar = LLUUID.Zero; + [XmlIgnore] public PhysicsVector m_rotationAxis = new PhysicsVector(1f,1f,1f); + + #region Permissions + + public uint BaseMask = (uint)PermissionMask.All; + public uint OwnerMask = (uint)PermissionMask.All; + public uint GroupMask = (uint)PermissionMask.None; + public uint EveryoneMask = (uint)PermissionMask.None; + public uint NextOwnerMask = (uint)PermissionMask.All; + + private UndoStack m_undo = new UndoStack(5); + + public LLObject.ObjectFlags Flags = LLObject.ObjectFlags.None; + + public uint ObjectFlags + { + get { return (uint)Flags; } + set { Flags = (LLObject.ObjectFlags)value; } + } + + #endregion protected byte[] m_particleSystem = new byte[0]; - [XmlIgnore] public PhysicsVector m_rotationAxis = new PhysicsVector(1f, 1f, 1f); - [XmlIgnore] private Dictionary m_scriptEvents = new Dictionary(); - public LLUUID m_sitTargetAvatar = LLUUID.Zero; - private Quaternion m_sitTargetOrientation = new Quaternion(0, 0, 0, 1); - private Vector3 m_sitTargetPosition = new Vector3(0, 0, 0); - [XmlIgnore] public bool m_undoing; + + [XmlIgnore] public uint TimeStampFull = 0; + [XmlIgnore] public uint TimeStampTerse = 0; + [XmlIgnore] public uint TimeStampLastActivity = 0; // Will be used for AutoReturn /// /// Only used internally to schedule client updates. @@ -124,44 +156,24 @@ namespace OpenSim.Region.Environment.Scenes /// private byte m_updateFlag; - public byte ObjectSaleType; - public LLUUID OwnerID; - public int OwnershipCost; - public uint ParentID; - [XmlIgnore] public int[] PayPrice = {-2, -2, -2, -2, -2}; - [XmlIgnore] public PhysicsActor PhysActor; - public int SalePrice; - - [XmlIgnore] public uint TimeStampFull; - [XmlIgnore] public uint TimeStampLastActivity; // Will be used for AutoReturn - [XmlIgnore] public uint TimeStampTerse; - #region Properties - + public LLUUID CreatorID; - protected LLVector3 m_acceleration; - protected LLVector3 m_angularVelocity; - private byte m_clickAction; - private Color m_color = Color.Black; - private string m_description = String.Empty; - protected LLVector3 m_groupPosition; - private int m_linkNum; - protected uint m_localId; - protected LLObject.MaterialType m_material = 0; + public LLUUID ObjectCreator + { + get { return CreatorID; } + } - protected string m_name; - protected LLVector3 m_offsetPosition; - protected ulong m_regionHandle; - protected LLVector3 m_rotationalvelocity; - protected LLQuaternion m_rotationOffset; - protected PrimitiveBaseShape m_shape; - private string m_sitName = String.Empty; - private string m_text = String.Empty; - private byte[] m_TextureAnimation; - private string m_touchName = String.Empty; protected LLUUID m_uuid; - protected LLVector3 m_velocity; + + public LLUUID UUID + { + get { return m_uuid; } + set { m_uuid = value; } + } + + protected uint m_localId; public uint LocalId { @@ -169,23 +181,145 @@ namespace OpenSim.Region.Environment.Scenes set { m_localId = value; } } - public scriptEvents ScriptEvents + protected string m_name; + + public virtual string Name { - get { return m_aggregateScriptEvents; } + get { return m_name; } + set { m_name = value; } } + public scriptEvents ScriptEvents + { + get { return m_aggregateScriptEvents; } + } + + protected LLObject.MaterialType m_material = 0; + public byte Material { get { return (byte) m_material; } set { m_material = (LLObject.MaterialType) value; } } + protected ulong m_regionHandle; + public ulong RegionHandle { get { return m_regionHandle; } set { m_regionHandle = value; } } + public uint GetEffectiveObjectFlags() + { + LLObject.ObjectFlags f=Flags; + if(m_parentGroup == null || m_parentGroup.RootPart == this) + f &= ~(LLObject.ObjectFlags.Touch | LLObject.ObjectFlags.Money); + + return (uint)Flags | (uint)LocalFlags; + } + + //unkown if this will be kept, added as a way of removing the group position from the group class + protected LLVector3 m_groupPosition; + + /// + /// Method for a prim to get it's world position from the group. + /// Remember, the Group Position simply gives the position of the group itself + /// + /// A Linked Child Prim objects position in world + public LLVector3 GetWorldPosition() + { + + Quaternion parentRot = new Quaternion( + ParentGroup.RootPart.RotationOffset.W, + ParentGroup.RootPart.RotationOffset.X, + ParentGroup.RootPart.RotationOffset.Y, + ParentGroup.RootPart.RotationOffset.Z); + + Vector3 axPos + = new Vector3( + OffsetPosition.X, + OffsetPosition.Y, + OffsetPosition.Z); + + axPos = parentRot * axPos; + LLVector3 translationOffsetPosition = new LLVector3(axPos.x, axPos.y, axPos.z); + return GroupPosition + translationOffsetPosition; + + //return (new LLVector3(axiomPos.x, axiomPos.y, axiomPos.z) + AbsolutePosition); + } + + /// + /// Gets the rotation of this prim offset by the group rotation + /// + /// + public LLQuaternion GetWorldRotation() + { + + Quaternion newRot; + + if (this.LinkNum == 0) + { + newRot = new Quaternion(RotationOffset.W,RotationOffset.X,RotationOffset.Y,RotationOffset.Z); + + } + else + { + Quaternion parentRot = new Quaternion( + ParentGroup.RootPart.RotationOffset.W, + ParentGroup.RootPart.RotationOffset.X, + ParentGroup.RootPart.RotationOffset.Y, + ParentGroup.RootPart.RotationOffset.Z); + + Quaternion oldRot + = new Quaternion( + RotationOffset.W, + RotationOffset.X, + RotationOffset.Y, + RotationOffset.Z); + + newRot = parentRot * oldRot; + } + return new LLQuaternion(newRot.x, newRot.y, newRot.z, newRot.w); + + //return new LLQuaternion(axiomPartRotation.x, axiomPartRotation.y, axiomPartRotation.z, axiomPartRotation.w); + + } + + public void StoreUndoState() + { + if (!m_undoing) + { + if (m_parentGroup != null) + { + if (m_undo.Count > 0) + { + UndoState last = m_undo.Peek(); + if (last != null) + { + if (last.Compare(this)) + return; + } + } + + + if (m_parentGroup.GetSceneMaxUndo() > 0) + { + UndoState nUndo = new UndoState(this); + + m_undo.Push(nUndo); + + } + } + } + } + + public void ClearUndoState() + { + m_undo.Clear(); + StoreUndoState(); + } + public LLVector3 GroupPosition { get @@ -218,13 +352,16 @@ namespace OpenSim.Region.Environment.Scenes { try { + // Root prim actually goes at Position if (ParentID == 0) { PhysActor.Position = new PhysicsVector(value.X, value.Y, value.Z); + } else { + // To move the child prim in respect to the group position and rotation we have to calculate LLVector3 resultingposition = GetWorldPosition(); @@ -232,7 +369,7 @@ namespace OpenSim.Region.Environment.Scenes LLQuaternion resultingrot = GetWorldRotation(); PhysActor.Orientation = new Quaternion(resultingrot.W, resultingrot.X, resultingrot.Y, resultingrot.Z); } - + // Tell the physics engines that this prim changed. m_parentGroup.Scene.PhysicsScene.AddPhysicsActorTaint(PhysActor); } @@ -241,9 +378,14 @@ namespace OpenSim.Region.Environment.Scenes Console.WriteLine(e.Message); } } + } } + private byte[] m_TextureAnimation; + + protected LLVector3 m_offsetPosition; + public LLVector3 OffsetPosition { get { return m_offsetPosition; } @@ -251,19 +393,31 @@ namespace OpenSim.Region.Environment.Scenes { StoreUndoState(); m_offsetPosition = value; - try - { - // Hack to get the child prim to update world positions in the physics engine - ParentGroup.ResetChildPrimPhysicsPositions(); - } - catch (NullReferenceException) - { - // Ignore, and skip over. - } - //m_log.Info("[PART]: OFFSET:" + m_offsetPosition.ToString()); + try + { + // Hack to get the child prim to update world positions in the physics engine + ParentGroup.ResetChildPrimPhysicsPositions(); + + } + catch (NullReferenceException) + { + // Ignore, and skip over. + } + //m_log.Info("[PART]: OFFSET:" + m_offsetPosition.ToString()); } } + public LLVector3 AbsolutePosition + { + get { + if (m_IsAttachment) + return GroupPosition; + + return m_offsetPosition + m_groupPosition; } + } + + protected LLQuaternion m_rotationOffset; + public LLQuaternion RotationOffset { get @@ -312,9 +466,13 @@ namespace OpenSim.Region.Environment.Scenes Console.WriteLine(ex.Message); } } + } } + protected LLVector3 m_velocity; + protected LLVector3 m_rotationalvelocity; + /// public LLVector3 Velocity { @@ -335,8 +493,8 @@ namespace OpenSim.Region.Environment.Scenes return m_velocity; } - set - { + set { + m_velocity = value; if (PhysActor != null) { @@ -346,6 +504,7 @@ namespace OpenSim.Region.Environment.Scenes m_parentGroup.Scene.PhysicsScene.AddPhysicsActorTaint(PhysActor); } } + } } @@ -360,7 +519,7 @@ namespace OpenSim.Region.Environment.Scenes { if (PhysActor.IsPhysical) { - m_rotationalvelocity.FromBytes(PhysActor.RotationalVelocity.GetBytes(), 0); + m_rotationalvelocity.FromBytes(PhysActor.RotationalVelocity.GetBytes(),0); } } @@ -370,6 +529,8 @@ namespace OpenSim.Region.Environment.Scenes } + protected LLVector3 m_angularVelocity; + /// public LLVector3 AngularVelocity { @@ -377,6 +538,8 @@ namespace OpenSim.Region.Environment.Scenes set { m_angularVelocity = value; } } + protected LLVector3 m_acceleration; + /// public LLVector3 Acceleration { @@ -384,6 +547,16 @@ namespace OpenSim.Region.Environment.Scenes set { m_acceleration = value; } } + private string m_description = String.Empty; + + public string Description + { + get { return m_description; } + set { m_description = value; } + } + + private Color m_color = Color.Black; + public Color Color { get { return m_color; } @@ -391,7 +564,7 @@ namespace OpenSim.Region.Environment.Scenes { m_color = value; TriggerScriptChangedEvent(Changed.COLOR); - + /* ScheduleFullUpdate() need not be called b/c after * setting the color, the text will be set, so then * ScheduleFullUpdate() will be called. */ @@ -399,6 +572,8 @@ namespace OpenSim.Region.Environment.Scenes } } + private string m_text = String.Empty; + public Vector3 SitTargetPosition { get { return m_sitTargetPosition; } @@ -412,207 +587,53 @@ namespace OpenSim.Region.Environment.Scenes public string Text { get { return m_text; } - set { m_text = value; } + set + { + m_text = value; + } + } + + private string m_sitName = String.Empty; + + public string SitName + { + get { return m_sitName; } + set { m_sitName = value; } + } + + private string m_touchName = String.Empty; + + public string TouchName + { + get { return m_touchName; } + set { m_touchName = value; } } + private int m_linkNum = 0; + public int LinkNum { get { return m_linkNum; } - set - { + set + { m_linkNum = value; TriggerScriptChangedEvent(Changed.LINK); + } } + private byte m_clickAction = 0; + public byte ClickAction { get { return m_clickAction; } - set { m_clickAction = value; } - } - - public PrimitiveBaseShape Shape - { - get { return m_shape; } set { - m_shape = value; - TriggerScriptChangedEvent(Changed.SHAPE); + m_clickAction = value; } } - public LLVector3 Scale - { - get { return m_shape.Scale; } - set - { - StoreUndoState(); - m_shape.Scale = value; - TriggerScriptChangedEvent(Changed.SCALE); - } - } - - public bool Stopped - { - get - { - double threshold = 0.02; - return (Math.Abs(Velocity.X) < threshold && - Math.Abs(Velocity.Y) < threshold && - Math.Abs(Velocity.Z) < threshold && - Math.Abs(AngularVelocity.X) < threshold && - Math.Abs(AngularVelocity.Y) < threshold && - Math.Abs(AngularVelocity.Z) < threshold); - } - } - - public LLUUID ObjectCreator - { - get { return CreatorID; } - } - - public LLUUID UUID - { - get { return m_uuid; } - set { m_uuid = value; } - } - - public virtual string Name - { - get { return m_name; } - set { m_name = value; } - } - - public LLVector3 AbsolutePosition - { - get - { - if (m_IsAttachment) - return GroupPosition; - - return m_offsetPosition + m_groupPosition; - } - } - - public string Description - { - get { return m_description; } - set { m_description = value; } - } - - public string SitName - { - get { return m_sitName; } - set { m_sitName = value; } - } - - public string TouchName - { - get { return m_touchName; } - set { m_touchName = value; } - } - - public uint GetEffectiveObjectFlags() - { - LLObject.ObjectFlags f = Flags; - if (m_parentGroup == null || m_parentGroup.RootPart == this) - f &= ~(LLObject.ObjectFlags.Touch | LLObject.ObjectFlags.Money); - - return (uint) Flags | (uint) LocalFlags; - } - - /// - /// Method for a prim to get it's world position from the group. - /// Remember, the Group Position simply gives the position of the group itself - /// - /// A Linked Child Prim objects position in world - public LLVector3 GetWorldPosition() - { - Quaternion parentRot = new Quaternion( - ParentGroup.RootPart.RotationOffset.W, - ParentGroup.RootPart.RotationOffset.X, - ParentGroup.RootPart.RotationOffset.Y, - ParentGroup.RootPart.RotationOffset.Z); - - Vector3 axPos - = new Vector3( - OffsetPosition.X, - OffsetPosition.Y, - OffsetPosition.Z); - - axPos = parentRot * axPos; - LLVector3 translationOffsetPosition = new LLVector3(axPos.x, axPos.y, axPos.z); - return GroupPosition + translationOffsetPosition; - - //return (new LLVector3(axiomPos.x, axiomPos.y, axiomPos.z) + AbsolutePosition); - } - - /// - /// Gets the rotation of this prim offset by the group rotation - /// - /// - public LLQuaternion GetWorldRotation() - { - Quaternion newRot; - - if (LinkNum == 0) - { - newRot = new Quaternion(RotationOffset.W, RotationOffset.X, RotationOffset.Y, RotationOffset.Z); - } - else - { - Quaternion parentRot = new Quaternion( - ParentGroup.RootPart.RotationOffset.W, - ParentGroup.RootPart.RotationOffset.X, - ParentGroup.RootPart.RotationOffset.Y, - ParentGroup.RootPart.RotationOffset.Z); - - Quaternion oldRot - = new Quaternion( - RotationOffset.W, - RotationOffset.X, - RotationOffset.Y, - RotationOffset.Z); - - newRot = parentRot * oldRot; - } - return new LLQuaternion(newRot.x, newRot.y, newRot.z, newRot.w); - - //return new LLQuaternion(axiomPartRotation.x, axiomPartRotation.y, axiomPartRotation.z, axiomPartRotation.w); - } - - public void StoreUndoState() - { - if (!m_undoing) - { - if (m_parentGroup != null) - { - if (m_undo.Count > 0) - { - UndoState last = m_undo.Peek(); - if (last != null) - { - if (last.Compare(this)) - return; - } - } - - - if (m_parentGroup.GetSceneMaxUndo() > 0) - { - UndoState nUndo = new UndoState(this); - - m_undo.Push(nUndo); - } - } - } - } - - public void ClearUndoState() - { - m_undo.Clear(); - StoreUndoState(); - } + protected PrimitiveBaseShape m_shape; /// /// hook to the physics scene to apply impulse @@ -624,17 +645,20 @@ namespace OpenSim.Region.Environment.Scenes public void ApplyImpulse(LLVector3 impulsei, bool localGlobalTF) { PhysicsVector impulse = new PhysicsVector(impulsei.X, impulsei.Y, impulsei.Z); - + if (localGlobalTF) { + LLQuaternion grot = GetWorldRotation(); - Quaternion AXgrot = new Quaternion(grot.W, grot.X, grot.Y, grot.Z); + Quaternion AXgrot = new Quaternion(grot.W,grot.X,grot.Y,grot.Z); Vector3 AXimpulsei = new Vector3(impulsei.X, impulsei.Y, impulsei.Z); Vector3 newimpulse = AXgrot * AXimpulsei; impulse = new PhysicsVector(newimpulse.x, newimpulse.y, newimpulse.z); + } else { + if (m_parentGroup != null) { m_parentGroup.applyImpulse(impulse); @@ -652,6 +676,7 @@ namespace OpenSim.Region.Environment.Scenes { StopMoveToTarget(); } + } public void StopMoveToTarget() @@ -664,48 +689,56 @@ namespace OpenSim.Region.Environment.Scenes if (m_parentGroup != null) { if (m_parentGroup.Scene != null) - m_parentGroup.Scene.TriggerObjectChanged(LocalId, (uint) val); + m_parentGroup.Scene.TriggerObjectChanged(LocalId, (uint)val); } - } - - #endregion - - #region Permissions - - private readonly UndoStack m_undo = new UndoStack(5); - public uint BaseMask = (uint) PermissionMask.All; - public uint EveryoneMask = (uint) PermissionMask.None; - public LLObject.ObjectFlags Flags = LLObject.ObjectFlags.None; - public uint GroupMask = (uint) PermissionMask.None; - public uint NextOwnerMask = (uint) PermissionMask.All; - public uint OwnerMask = (uint) PermissionMask.All; + } - public uint ObjectFlags + public PrimitiveBaseShape Shape { - get { return (uint) Flags; } - set { Flags = (LLObject.ObjectFlags) value; } + get { return m_shape; } + set + { + + m_shape = value; + TriggerScriptChangedEvent(Changed.SHAPE); + } } - #endregion - - protected SceneObjectPart(SerializationInfo info, StreamingContext context) + public LLVector3 Scale { - //System.Console.WriteLine("SceneObjectPart Deserialize BGN"); - - if (info == null) + get { return m_shape.Scale; } + set { - throw new ArgumentNullException("info"); + StoreUndoState(); + m_shape.Scale = value; + TriggerScriptChangedEvent(Changed.SCALE); } + } - /* - m_queue = (Queue)info.GetValue("m_queue", typeof(Queue)); - m_ids = (List)info.GetValue("m_ids", typeof(List)); - */ + public bool Stopped + { + get { + double threshold = 0.02; + return (Math.Abs(Velocity.X) < threshold && + Math.Abs(Velocity.Y) < threshold && + Math.Abs(Velocity.Z) < threshold && + Math.Abs(AngularVelocity.X) < threshold && + Math.Abs(AngularVelocity.Y) < threshold && + Math.Abs(AngularVelocity.Z) < threshold); + } + } - //System.Console.WriteLine("SceneObjectPart Deserialize END"); + #endregion + + public LLUUID ObjectOwner + { + get { return OwnerID; } } + // FIXME, TODO, ERROR: 'ParentGroup' can't be in here, move it out. + protected SceneObjectGroup m_parentGroup; + public SceneObjectGroup ParentGroup { get { return m_parentGroup; } @@ -725,7 +758,7 @@ namespace OpenSim.Region.Environment.Scenes public SceneObjectPart() { // It's not necessary to persist this - m_inventoryFileName = "inventory_" + LLUUID.Random() + ".tmp"; + m_inventoryFileName = "inventory_" + LLUUID.Random().ToString() + ".tmp"; m_TextureAnimation = new byte[0]; } @@ -757,13 +790,13 @@ namespace OpenSim.Region.Environment.Scenes CreatorID = OwnerID; LastOwnerID = LLUUID.Zero; UUID = LLUUID.Random(); - LocalId = (localID); + LocalId = (uint) (localID); Shape = shape; // Todo: Add More Object Parameter from above! OwnershipCost = 0; - ObjectSaleType = 0; + ObjectSaleType = (byte) 0; SalePrice = 0; - Category = 0; + Category = (uint) 0; LastOwnerID = CreatorID; // End Todo: /// GroupPosition = groupPosition; @@ -774,20 +807,20 @@ namespace OpenSim.Region.Environment.Scenes AngularVelocity = new LLVector3(0, 0, 0); Acceleration = new LLVector3(0, 0, 0); m_TextureAnimation = new byte[0]; - m_inventoryFileName = "inventory_" + LLUUID.Random() + ".tmp"; - + m_inventoryFileName = "inventory_" + LLUUID.Random().ToString() + ".tmp"; + // Prims currently only contain a single folder (Contents). From looking at the Second Life protocol, // this appears to have the same UUID (!) as the prim. If this isn't the case, one can't drag items from // the prim into an agent inventory (Linden client reports that the "Object not found for drop" in its log m_folderID = UUID; Flags = 0; - Flags |= LLObject.ObjectFlags.AllowInventoryDrop | - LLObject.ObjectFlags.CreateSelected; + Flags |= LLObject.ObjectFlags.AllowInventoryDrop | + LLObject.ObjectFlags.CreateSelected; TrimPermissions(); //m_undo = new UndoStack(ParentGroup.GetSceneMaxUndo()); - + ScheduleFullUpdate(); } @@ -813,172 +846,53 @@ namespace OpenSim.Region.Environment.Scenes CreatorID = creatorID; LastOwnerID = lastOwnerID; UUID = LLUUID.Random(); - LocalId = (localID); + LocalId = (uint) (localID); Shape = shape; OwnershipCost = 0; - ObjectSaleType = 0; + ObjectSaleType = (byte) 0; SalePrice = 0; - Category = 0; + Category = (uint) 0; LastOwnerID = CreatorID; OffsetPosition = position; RotationOffset = rotation; ObjectFlags = flags; - + // Since we don't store script state, this is only a 'temporary' objectflag now // If the object is scripted, the script will get loaded and this will be set again - ObjectFlags &= ~(uint) (LLObject.ObjectFlags.Scripted | LLObject.ObjectFlags.Touch); - + ObjectFlags &= ~(uint)(LLObject.ObjectFlags.Scripted | LLObject.ObjectFlags.Touch); + TrimPermissions(); // ApplyPhysics(); - + ScheduleFullUpdate(); } #endregion - #region IScriptHost Members - - public LLUUID ObjectOwner + /// + /// Restore this part from the serialized xml representation. + /// + /// + /// + public static SceneObjectPart FromXml(XmlReader xmlReader) { - get { return OwnerID; } - } + XmlSerializer serializer = new XmlSerializer(typeof (SceneObjectPart)); + SceneObjectPart newobject = (SceneObjectPart) serializer.Deserialize(xmlReader); - public void SetText(string text, Vector3 color, double alpha) - { - Color = Color.FromArgb(0xff - (int) (alpha * 0xff), - (int) (color.x * 0xff), - (int) (color.y * 0xff), - (int) (color.z * 0xff)); - SetText(text); + return newobject; } - - #endregion - - #region ISerializable Members - - [SecurityPermission(SecurityAction.LinkDemand, - Flags = SecurityPermissionFlag.SerializationFormatter)] - public virtual void GetObjectData( - SerializationInfo info, StreamingContext context) + + public void ApplyPhysics(uint rootObjectFlags, bool m_physicalPrim) { - if (info == null) - { - throw new ArgumentNullException("info"); - } - info.AddValue("m_inventoryFileName", m_inventoryFileName); - info.AddValue("m_folderID", m_folderID.UUID); - info.AddValue("PhysActor", PhysActor); + bool isPhysical = (((rootObjectFlags & (uint) LLObject.ObjectFlags.Physics) != 0) && m_physicalPrim); + bool isPhantom = ((rootObjectFlags & (uint) LLObject.ObjectFlags.Phantom) != 0); - Dictionary TaskInventory_work = new Dictionary(); + // Added clarification.. since A rigid body is an object that you can kick around, etc. + bool RigidBody = isPhysical && !isPhantom; - foreach (LLUUID id in TaskInventory.Keys) - { - TaskInventory_work.Add(id.UUID, TaskInventory[id]); - } - - info.AddValue("TaskInventory", TaskInventory_work); - - info.AddValue("LastOwnerID", LastOwnerID.UUID); - info.AddValue("OwnerID", OwnerID.UUID); - info.AddValue("GroupID", GroupID.UUID); - - info.AddValue("OwnershipCost", OwnershipCost); - info.AddValue("ObjectSaleType", ObjectSaleType); - info.AddValue("SalePrice", SalePrice); - info.AddValue("Category", Category); - - info.AddValue("CreationDate", CreationDate); - info.AddValue("ParentID", ParentID); - - info.AddValue("OwnerMask", OwnerMask); - info.AddValue("NextOwnerMask", NextOwnerMask); - info.AddValue("GroupMask", GroupMask); - info.AddValue("EveryoneMask", EveryoneMask); - info.AddValue("BaseMask", BaseMask); - - info.AddValue("m_particleSystem", m_particleSystem); - - info.AddValue("TimeStampFull", TimeStampFull); - info.AddValue("TimeStampTerse", TimeStampTerse); - info.AddValue("TimeStampLastActivity", TimeStampLastActivity); - - info.AddValue("m_updateFlag", m_updateFlag); - info.AddValue("CreatorID", CreatorID.UUID); - - info.AddValue("m_inventorySerial", m_inventorySerial); - info.AddValue("m_uuid", m_uuid.UUID); - info.AddValue("m_localID", m_localId); - info.AddValue("m_name", m_name); - info.AddValue("m_flags", Flags); - info.AddValue("m_material", m_material); - info.AddValue("m_regionHandle", m_regionHandle); - - info.AddValue("m_groupPosition.X", m_groupPosition.X); - info.AddValue("m_groupPosition.Y", m_groupPosition.Y); - info.AddValue("m_groupPosition.Z", m_groupPosition.Z); - - info.AddValue("m_offsetPosition.X", m_offsetPosition.X); - info.AddValue("m_offsetPosition.Y", m_offsetPosition.Y); - info.AddValue("m_offsetPosition.Z", m_offsetPosition.Z); - - info.AddValue("m_rotationOffset.W", m_rotationOffset.W); - info.AddValue("m_rotationOffset.X", m_rotationOffset.X); - info.AddValue("m_rotationOffset.Y", m_rotationOffset.Y); - info.AddValue("m_rotationOffset.Z", m_rotationOffset.Z); - - info.AddValue("m_velocity.X", m_velocity.X); - info.AddValue("m_velocity.Y", m_velocity.Y); - info.AddValue("m_velocity.Z", m_velocity.Z); - - info.AddValue("m_rotationalvelocity.X", m_rotationalvelocity.X); - info.AddValue("m_rotationalvelocity.Y", m_rotationalvelocity.Y); - info.AddValue("m_rotationalvelocity.Z", m_rotationalvelocity.Z); - - info.AddValue("m_angularVelocity.X", m_angularVelocity.X); - info.AddValue("m_angularVelocity.Y", m_angularVelocity.Y); - info.AddValue("m_angularVelocity.Z", m_angularVelocity.Z); - - info.AddValue("m_acceleration.X", m_acceleration.X); - info.AddValue("m_acceleration.Y", m_acceleration.Y); - info.AddValue("m_acceleration.Z", m_acceleration.Z); - - info.AddValue("m_description", m_description); - info.AddValue("m_color", m_color); - info.AddValue("m_text", m_text); - info.AddValue("m_sitName", m_sitName); - info.AddValue("m_touchName", m_touchName); - info.AddValue("m_clickAction", m_clickAction); - info.AddValue("m_shape", m_shape); - info.AddValue("m_parentGroup", m_parentGroup); - info.AddValue("PayPrice", PayPrice); - } - - #endregion - - /// - /// Restore this part from the serialized xml representation. - /// - /// - /// - public static SceneObjectPart FromXml(XmlReader xmlReader) - { - XmlSerializer serializer = new XmlSerializer(typeof (SceneObjectPart)); - SceneObjectPart newobject = (SceneObjectPart) serializer.Deserialize(xmlReader); - - return newobject; - } - - public void ApplyPhysics(uint rootObjectFlags, bool m_physicalPrim) - { - bool isPhysical = (((rootObjectFlags & (uint) LLObject.ObjectFlags.Physics) != 0) && m_physicalPrim); - bool isPhantom = ((rootObjectFlags & (uint) LLObject.ObjectFlags.Phantom) != 0); - - // Added clarification.. since A rigid body is an object that you can kick around, etc. - bool RigidBody = isPhysical && !isPhantom; - - // The only time the physics scene shouldn't know about the prim is if it's phantom - if (!isPhantom) + // The only time the physics scene shouldn't know about the prim is if it's phantom + if (!isPhantom) { PhysActor = m_parentGroup.Scene.PhysicsScene.AddPrimShape( Name, @@ -988,7 +902,7 @@ namespace OpenSim.Region.Environment.Scenes new PhysicsVector(Scale.X, Scale.Y, Scale.Z), new Quaternion(RotationOffset.W, RotationOffset.X, RotationOffset.Y, RotationOffset.Z), RigidBody); - + // Basic Physics returns null.. joy joy joy. if (PhysActor != null) { @@ -1004,15 +918,18 @@ namespace OpenSim.Region.Environment.Scenes OwnerMask = NextOwnerMask; TriggerScriptChangedEvent(Changed.OWNER); + } public void TrimPermissions() { - BaseMask &= (uint) PermissionMask.All; - OwnerMask &= (uint) PermissionMask.All; - GroupMask &= (uint) PermissionMask.All; - EveryoneMask &= (uint) PermissionMask.All; - NextOwnerMask &= (uint) PermissionMask.All; + + BaseMask &= (uint)PermissionMask.All; + OwnerMask &= (uint)PermissionMask.All; + GroupMask &= (uint)PermissionMask.All; + EveryoneMask &= (uint)PermissionMask.All; + NextOwnerMask &= (uint)PermissionMask.All; + } /// @@ -1046,24 +963,25 @@ namespace OpenSim.Region.Environment.Scenes Vector3 rOrigin = iray.Origin; Vector3 rDirection = iray.Direction; + //rDirection = rDirection.Normalize(); // Buidling the first part of the Quadratic equation - Vector3 r2ndDirection = rDirection * rDirection; + Vector3 r2ndDirection = rDirection*rDirection; float itestPart1 = r2ndDirection.x + r2ndDirection.y + r2ndDirection.z; // Buidling the second part of the Quadratic equation Vector3 tmVal2 = rOrigin - vAbsolutePosition; - Vector3 r2Direction = rDirection * 2.0f; - Vector3 tmVal3 = r2Direction * tmVal2; + Vector3 r2Direction = rDirection*2.0f; + Vector3 tmVal3 = r2Direction*tmVal2; float itestPart2 = tmVal3.x + tmVal3.y + tmVal3.z; // Buidling the third part of the Quadratic equation - Vector3 tmVal4 = rOrigin * rOrigin; - Vector3 tmVal5 = vAbsolutePosition * vAbsolutePosition; + Vector3 tmVal4 = rOrigin*rOrigin; + Vector3 tmVal5 = vAbsolutePosition*vAbsolutePosition; - Vector3 tmVal6 = vAbsolutePosition * rOrigin; + Vector3 tmVal6 = vAbsolutePosition*rOrigin; // Set Radius to the largest dimention of the prim @@ -1085,21 +1003,21 @@ namespace OpenSim.Region.Environment.Scenes //radius = radius; float itestPart3 = tmVal4.x + tmVal4.y + tmVal4.z + tmVal5.x + tmVal5.y + tmVal5.z - - (2.0f * (tmVal6.x + tmVal6.y + tmVal6.z + (radius * radius))); + (2.0f*(tmVal6.x + tmVal6.y + tmVal6.z + (radius*radius))); // Yuk Quadradrics.. Solve first - float rootsqr = (itestPart2 * itestPart2) - (4.0f * itestPart1 * itestPart3); + float rootsqr = (itestPart2*itestPart2) - (4.0f*itestPart1*itestPart3); if (rootsqr < 0.0f) { // No intersection return returnresult; } - float root = ((-itestPart2) - (float) Math.Sqrt(rootsqr)) / (itestPart1 * 2.0f); + float root = ((-itestPart2) - (float) Math.Sqrt((double) rootsqr))/(itestPart1*2.0f); if (root < 0.0f) { // perform second quadratic root solution - root = ((-itestPart2) + (float) Math.Sqrt(rootsqr)) / (itestPart1 * 2.0f); + root = ((-itestPart2) + (float) Math.Sqrt((double) rootsqr))/(itestPart1*2.0f); // is there any intersection? if (root < 0.0f) @@ -1112,8 +1030,8 @@ namespace OpenSim.Region.Environment.Scenes // We got an intersection. putting together an EntityIntersection object with the // intersection information Vector3 ipoint = - new Vector3(iray.Origin.x + (iray.Direction.x * root), iray.Origin.y + (iray.Direction.y * root), - iray.Origin.z + (iray.Direction.z * root)); + new Vector3(iray.Origin.x + (iray.Direction.x*root), iray.Origin.y + (iray.Direction.y*root), + iray.Origin.z + (iray.Direction.z*root)); returnresult.HitTF = true; returnresult.ipoint = ipoint; @@ -1174,7 +1092,7 @@ namespace OpenSim.Region.Environment.Scenes // Variables prefixed with AX are Axiom.Math copies of the LL variety. - Quaternion AXrot = new Quaternion(rot.W, rot.X, rot.Y, rot.Z); + Quaternion AXrot = new Quaternion(rot.W,rot.X,rot.Y,rot.Z); AXrot.Normalize(); Vector3 AXpos = new Vector3(pos.X, pos.Y, pos.Z); @@ -1183,33 +1101,31 @@ namespace OpenSim.Region.Environment.Scenes // it's different for each vertex because we've got to rotate it // to get the world position of the vertex to produce the Oriented Bounding Box - Vector3 tScale = new Vector3(); + Vector3 tScale = new Vector3(); Vector3 AXscale = new Vector3(m_shape.Scale.X * 0.5f, m_shape.Scale.Y * 0.5f, m_shape.Scale.Z * 0.5f); //Vector3 pScale = (AXscale) - (AXrot.Inverse() * (AXscale)); //Vector3 nScale = (AXscale * -1) - (AXrot.Inverse() * (AXscale * -1)); - + // rScale is the rotated offset to find a vertex based on the scale and the world rotation. Vector3 rScale = new Vector3(); // Get Vertexes for Faces Stick them into ABCD for each Face // Form: Face[face] that corresponds to the below diagram - #region ABCD Face Vertex Map Comment Diagram - // A _________ B // | | // | 4 top | // |_________| // C D - + // A _________ B // | Back | // | 3 | // |_________| // C D - + // A _________ B B _________ A // | Left | | Right | // | 0 | | 2 | @@ -1227,15 +1143,13 @@ namespace OpenSim.Region.Environment.Scenes // | 5 bot | // |_________| // A B - #endregion #region Plane Decomposition of Oriented Bounding Box - tScale = new Vector3(AXscale.x, -AXscale.y, AXscale.z); rScale = ((AXrot * tScale)); vertexes[0] = (new Vector3((pos.X + rScale.x), (pos.Y + rScale.y), (pos.Z + rScale.z))); - // vertexes[0].x = pos.X + vertexes[0].x; + // vertexes[0].x = pos.X + vertexes[0].x; //vertexes[0].y = pos.Y + vertexes[0].y; //vertexes[0].z = pos.Z + vertexes[0].z; @@ -1247,8 +1161,8 @@ namespace OpenSim.Region.Environment.Scenes rScale = ((AXrot * tScale)); vertexes[1] = (new Vector3((pos.X + rScale.x), (pos.Y + rScale.y), (pos.Z + rScale.z))); - // vertexes[1].x = pos.X + vertexes[1].x; - // vertexes[1].y = pos.Y + vertexes[1].y; + // vertexes[1].x = pos.X + vertexes[1].x; + // vertexes[1].y = pos.Y + vertexes[1].y; //vertexes[1].z = pos.Z + vertexes[1].z; FaceB[0] = vertexes[1]; @@ -1273,8 +1187,8 @@ namespace OpenSim.Region.Environment.Scenes vertexes[3] = (new Vector3((pos.X + rScale.x), (pos.Y + rScale.y), (pos.Z + rScale.z))); //vertexes[3].x = pos.X + vertexes[3].x; - // vertexes[3].y = pos.Y + vertexes[3].y; - // vertexes[3].z = pos.Z + vertexes[3].z; + // vertexes[3].y = pos.Y + vertexes[3].y; + // vertexes[3].z = pos.Z + vertexes[3].z; FaceD[0] = vertexes[3]; FaceC[1] = vertexes[3]; @@ -1284,9 +1198,9 @@ namespace OpenSim.Region.Environment.Scenes rScale = ((AXrot * tScale)); vertexes[4] = (new Vector3((pos.X + rScale.x), (pos.Y + rScale.y), (pos.Z + rScale.z))); - // vertexes[4].x = pos.X + vertexes[4].x; - // vertexes[4].y = pos.Y + vertexes[4].y; - // vertexes[4].z = pos.Z + vertexes[4].z; + // vertexes[4].x = pos.X + vertexes[4].x; + // vertexes[4].y = pos.Y + vertexes[4].y; + // vertexes[4].z = pos.Z + vertexes[4].z; FaceB[1] = vertexes[4]; FaceA[2] = vertexes[4]; @@ -1296,9 +1210,9 @@ namespace OpenSim.Region.Environment.Scenes rScale = ((AXrot * tScale)); vertexes[5] = (new Vector3((pos.X + rScale.x), (pos.Y + rScale.y), (pos.Z + rScale.z))); - // vertexes[5].x = pos.X + vertexes[5].x; - // vertexes[5].y = pos.Y + vertexes[5].y; - // vertexes[5].z = pos.Z + vertexes[5].z; + // vertexes[5].x = pos.X + vertexes[5].x; + // vertexes[5].y = pos.Y + vertexes[5].y; + // vertexes[5].z = pos.Z + vertexes[5].z; FaceD[1] = vertexes[5]; FaceC[2] = vertexes[5]; @@ -1308,9 +1222,9 @@ namespace OpenSim.Region.Environment.Scenes rScale = ((AXrot * tScale)); vertexes[6] = (new Vector3((pos.X + rScale.x), (pos.Y + rScale.y), (pos.Z + rScale.z))); - // vertexes[6].x = pos.X + vertexes[6].x; - // vertexes[6].y = pos.Y + vertexes[6].y; - // vertexes[6].z = pos.Z + vertexes[6].z; + // vertexes[6].x = pos.X + vertexes[6].x; + // vertexes[6].y = pos.Y + vertexes[6].y; + // vertexes[6].z = pos.Z + vertexes[6].z; FaceB[2] = vertexes[6]; FaceA[3] = vertexes[6]; @@ -1320,36 +1234,35 @@ namespace OpenSim.Region.Environment.Scenes rScale = ((AXrot * tScale)); vertexes[7] = (new Vector3((pos.X + rScale.x), (pos.Y + rScale.y), (pos.Z + rScale.z))); - // vertexes[7].x = pos.X + vertexes[7].x; - // vertexes[7].y = pos.Y + vertexes[7].y; - // vertexes[7].z = pos.Z + vertexes[7].z; + // vertexes[7].x = pos.X + vertexes[7].x; + // vertexes[7].y = pos.Y + vertexes[7].y; + // vertexes[7].z = pos.Z + vertexes[7].z; FaceD[2] = vertexes[7]; FaceC[3] = vertexes[7]; FaceD[5] = vertexes[7]; - #endregion // Get our plane normals for (int i = 0; i < 6; i++) { //m_log.Info("[FACECALCULATION]: FaceA[" + i + "]=" + FaceA[i] + " FaceB[" + i + "]=" + FaceB[i] + " FaceC[" + i + "]=" + FaceC[i] + " FaceD[" + i + "]=" + FaceD[i]); - + // Our Plane direction AmBa = FaceA[i] - FaceB[i]; AmBb = FaceB[i] - FaceC[i]; - + cross = AmBb.Cross(AmBa); // normalize the cross product to get the normal. - normals[i] = cross / cross.Length; - + normals[i] = cross / cross.Length; + //m_log.Info("[NORMALS]: normals[ " + i + "]" + normals[i].ToString()); //distance[i] = (normals[i].x * AmBa.x + normals[i].y * AmBa.y + normals[i].z * AmBa.z) * -1; } EntityIntersection returnresult = new EntityIntersection(); - + returnresult.distance = 1024; float c = 0; float a = 0; @@ -1357,59 +1270,57 @@ namespace OpenSim.Region.Environment.Scenes Vector3 q = new Vector3(); #region OBB Version 2 Experiment - //float fmin = 999999; //float fmax = -999999; //float s = 0; //for (int i=0;i<6;i++) //{ - //s = iray.Direction.Dot(normals[i]); - //d = normals[i].Dot(FaceB[i]); + //s = iray.Direction.Dot(normals[i]); + //d = normals[i].Dot(FaceB[i]); - //if (s == 0) - //{ - //if (iray.Origin.Dot(normals[i]) > d) - //{ - //return returnresult; - //} - // else - //{ - //continue; - //} - //} - //a = (d - iray.Origin.Dot(normals[i])) / s; - //if ( iray.Direction.Dot(normals[i]) < 0) - //{ - //if (a > fmax) - //{ - //if (a > fmin) - //{ - //return returnresult; - //} - //fmax = a; - //} + //if (s == 0) + //{ + //if (iray.Origin.Dot(normals[i]) > d) + //{ + //return returnresult; + //} + // else + //{ + //continue; + //} + //} + //a = (d - iray.Origin.Dot(normals[i])) / s; + //if ( iray.Direction.Dot(normals[i]) < 0) + //{ + //if (a > fmax) + //{ + //if (a > fmin) + //{ + //return returnresult; + //} + //fmax = a; + //} - //} - //else - //{ - //if (a < fmin) - //{ - //if (a < 0 || a < fmax) - //{ - //return returnresult; - //} - //fmin = a; - //} - //} + //} + //else + //{ + //if (a < fmin) + //{ + //if (a < 0 || a < fmax) + //{ + //return returnresult; + //} + //fmin = a; + //} + //} //} //if (fmax > 0) // a= fmax; //else - // a=fmin; + // a=fmin; //q = iray.Origin + a * iray.Direction; - #endregion // Loop over faces (6 of them) @@ -1430,6 +1341,7 @@ namespace OpenSim.Region.Environment.Scenes // If the normal is pointing outside the object if (iray.Direction.Dot(normals[i]) < 0 || !frontFacesOnly) { + if (faceCenters) { q = AXpos + a * AAfacenormals[i]; //(FaceA[i] + FaceB[i] + FaceC[1] + FaceD[i]) / 4f; @@ -1439,13 +1351,13 @@ namespace OpenSim.Region.Environment.Scenes q = iray.Origin + a * iray.Direction; } - float distance2 = (float) GetDistanceTo(q, AXpos); + float distance2 = (float)GetDistanceTo(q, AXpos); // Is this the closest hit to the object's origin? if (faceCenters) { - distance2 = (float) GetDistanceTo(q, iray.Origin); + distance2 = (float)GetDistanceTo(q, iray.Origin); } - + if (distance2 < returnresult.distance) { @@ -1456,12 +1368,14 @@ namespace OpenSim.Region.Environment.Scenes //m_log.Info("[POINT]: " + q.ToString()); returnresult.normal = normals[i]; returnresult.AAfaceNormal = AAfacenormals[i]; + } } + } return returnresult; } - + // Use this for attachments! LocalID should be avatar's localid public void SetParentLocalId(uint localID) { @@ -1471,14 +1385,14 @@ namespace OpenSim.Region.Environment.Scenes public void SetAttachmentPoint(uint AttachmentPoint) { m_attachmentPoint = AttachmentPoint; - + // save the attachment point. //if (AttachmentPoint != 0) //{ - m_shape.State = (byte) AttachmentPoint; + m_shape.State = (byte)AttachmentPoint; //} + } - /// /// /// @@ -1500,12 +1414,13 @@ namespace OpenSim.Region.Environment.Scenes PhysActor.Buoyancy = fvalue; } } - + public void SetAxisRotation(int axis, int rotate) { if (m_parentGroup != null) { m_parentGroup.SetAxisRotation(axis, rotate); + } } @@ -1527,9 +1442,10 @@ namespace OpenSim.Region.Environment.Scenes { PhysActor.FloatOnWater = false; } + } } - + public LLVector3 GetSitTargetPositionLL() { @@ -1600,6 +1516,53 @@ namespace OpenSim.Region.Environment.Scenes return part; } + #region Copying + + /// + /// Duplicates this part. + /// + /// + public SceneObjectPart Copy(uint localID, LLUUID AgentID, LLUUID GroupID, int linkNum) + { + SceneObjectPart dupe = (SceneObjectPart) MemberwiseClone(); + dupe.m_shape = m_shape.Copy(); + dupe.m_regionHandle = m_regionHandle; + dupe.UUID = LLUUID.Random(); + dupe.LocalId = localID; + dupe.OwnerID = AgentID; + dupe.GroupID = GroupID; + dupe.GroupPosition = new LLVector3(GroupPosition.X, GroupPosition.Y, GroupPosition.Z); + dupe.OffsetPosition = new LLVector3(OffsetPosition.X, OffsetPosition.Y, OffsetPosition.Z); + dupe.RotationOffset = + new LLQuaternion(RotationOffset.X, RotationOffset.Y, RotationOffset.Z, RotationOffset.W); + dupe.Velocity = new LLVector3(0, 0, 0); + dupe.Acceleration = new LLVector3(0, 0, 0); + dupe.AngularVelocity = new LLVector3(0, 0, 0); + dupe.ObjectFlags = ObjectFlags; + + dupe.OwnershipCost = OwnershipCost; + dupe.ObjectSaleType = ObjectSaleType; + dupe.SalePrice = SalePrice; + dupe.Category = Category; + + dupe.TaskInventory = (TaskInventoryDictionary)dupe.TaskInventory.Clone(); + + dupe.ResetIDs(linkNum); + + // This may be wrong... it might have to be applied in SceneObjectGroup to the object that's being duplicated. + dupe.LastOwnerID = ObjectOwner; + + byte[] extraP = new byte[Shape.ExtraParams.Length]; + Array.Copy(Shape.ExtraParams, extraP, extraP.Length); + dupe.Shape.ExtraParams = extraP; + bool UsePhysics = ((dupe.ObjectFlags & (uint) LLObject.ObjectFlags.Physics) != 0); + dupe.DoPhysicsPropertyUpdate(UsePhysics, true); + + return dupe; + } + + #endregion + /// /// Reset LLUUIDs for this part. This involves generate this part's own LLUUID and /// generating new LLUUIDs for all the items in the inventory. @@ -1608,1056 +1571,1123 @@ namespace OpenSim.Region.Environment.Scenes public void ResetIDs(int linkNum) { UUID = LLUUID.Random(); - LinkNum = linkNum; - + LinkNum = linkNum; + ResetInventoryIDs(); } - public void UpdatePermissions(LLUUID AgentID, byte field, uint localID, uint mask, byte addRemTF) - { - bool set = addRemTF == 1; - - // Are we the owner? - if (AgentID == OwnerID) - { - switch (field) - { - case 2: - OwnerMask = ApplyMask(OwnerMask, set, mask); - break; - case 4: - GroupMask = ApplyMask(GroupMask, set, mask); - break; - case 8: - EveryoneMask = ApplyMask(EveryoneMask, set, mask); - break; - case 16: - NextOwnerMask = ApplyMask(NextOwnerMask, set, mask); - break; - } - SendFullUpdateToAllClients(); - - SendObjectPropertiesToClient(AgentID); - } - } + #region Update Scheduling - private void SendObjectPropertiesToClient(LLUUID AgentID) + /// + /// Clear all pending updates + /// + private void ClearUpdateSchedule() { - List avatars = m_parentGroup.GetScenePresences(); - for (int i = 0; i < avatars.Count; i++) - { - // Ugly reference :( - if (avatars[i].UUID == AgentID) - { - m_parentGroup.GetProperties(avatars[i].ControllingClient); - } - } + m_updateFlag = 0; } - private uint ApplyMask(uint val, bool set, uint mask) + /// + /// Schedules this prim for a full update + /// + public void ScheduleFullUpdate() { - if (set) - { - return val |= mask; - } - else + if (m_parentGroup != null) { - return val &= ~mask; + m_parentGroup.HasGroupChanged = true; + m_parentGroup.QueueForUpdateCheck(); } - } - - public virtual void UpdateMovement() - { - } - - public void PhysicsOutOfBounds(PhysicsVector pos) - { - m_log.Info("[PHYSICS]: Physical Object went out of bounds."); - RemFlag(LLObject.ObjectFlags.Physics); - DoPhysicsPropertyUpdate(false, true); - //m_parentGroup.Scene.PhysicsScene.AddPhysicsActorTaint(PhysActor); - } - - public virtual void OnGrab(LLVector3 offsetPos, IClientAPI remoteClient) - { - } - - - public void SetText(string text) - { - Text = text; - ScheduleFullUpdate(); - } - - public int registerTargetWaypoint(LLVector3 target, float tolerance) - { - if (m_parentGroup != null) + + int timeNow = Util.UnixTimeSinceEpoch(); + + // If multiple updates are scheduled on the same second, we still need to perform all of them + // So we'll force the issue by bumping up the timestamp so that later processing sees these need + // to be performed. + if (timeNow <= TimeStampFull) { - return m_parentGroup.registerTargetWaypoint(target, tolerance); + TimeStampFull += 1; } - return 0; - } - - public void unregisterTargetWaypoint(int handle) - { - if (m_parentGroup != null) + else { - m_parentGroup.unregisterTargetWaypoint(handle); + TimeStampFull = (uint)timeNow; } + + m_updateFlag = 2; + +// m_log.DebugFormat( +// "[SCENE OBJECT PART]: Scheduling full update for {0}, {1} at {2}", +// UUID, Name, TimeStampFull); } - - public void Undo() + public void AddFlag(LLObject.ObjectFlags flag) { - if (m_undo.Count > 0) + LLObject.ObjectFlags prevflag = Flags; + //uint objflags = Flags; + if ((ObjectFlags & (uint) flag) == 0) { - UndoState goback = m_undo.Pop(); - if (goback != null) - goback.PlaybackState(this); + //Console.WriteLine("Adding flag: " + ((LLObject.ObjectFlags) flag).ToString()); + Flags |= flag; } + //uint currflag = (uint)Flags; + //System.Console.WriteLine("Aprev: " + prevflag.ToString() + " curr: " + Flags.ToString()); + //ScheduleFullUpdate(); } - public void SetScriptEvents(LLUUID scriptid, int events) + public void RemFlag(LLObject.ObjectFlags flag) { - scriptEvents oldparts; - lock (m_scriptEvents) + LLObject.ObjectFlags prevflag = Flags; + if ((ObjectFlags & (uint) flag) != 0) { - if (m_scriptEvents.ContainsKey(scriptid)) - { - oldparts = m_scriptEvents[scriptid]; - - // remove values from aggregated script events - m_scriptEvents[scriptid] = (scriptEvents) events; - } - else - { - m_scriptEvents.Add(scriptid, (scriptEvents) events); - } + //Console.WriteLine("Removing flag: " + ((LLObject.ObjectFlags)flag).ToString()); + Flags &= ~flag; } - aggregateScriptEvents(); + //System.Console.WriteLine("prev: " + prevflag.ToString() + " curr: " + Flags.ToString()); + //ScheduleFullUpdate(); } - public void RemoveScriptEvents(LLUUID scriptid) + /// + /// Schedule a terse update for this prim. Terse updates only send position, + /// rotation, velocity, rotational velocity and shape information. + /// + public void ScheduleTerseUpdate() { - lock (m_scriptEvents) + if (m_updateFlag < 1) { - if (m_scriptEvents.ContainsKey(scriptid)) + if (m_parentGroup != null) { - scriptEvents oldparts = scriptEvents.None; - oldparts = m_scriptEvents[scriptid]; - - // remove values from aggregated script events - m_aggregateScriptEvents &= ~oldparts; - m_scriptEvents.Remove(scriptid); + m_parentGroup.HasGroupChanged = true; + m_parentGroup.QueueForUpdateCheck(); } + TimeStampTerse = (uint) Util.UnixTimeSinceEpoch(); + m_updateFlag = 1; + +// m_log.DebugFormat( +// "[SCENE OBJECT PART]: Scheduling terse update for {0}, {1} at {2}", +// UUID, Name, TimeStampTerse); } - aggregateScriptEvents(); } - public void aggregateScriptEvents() + /// + /// Tell all the prims which have had updates scheduled + /// + public void SendScheduledUpdates() { - // Aggregate script events - lock (m_scriptEvents) - { - foreach (scriptEvents s in m_scriptEvents.Values) - { - m_aggregateScriptEvents |= s; - } - } - - uint objectflagupdate = 0; - - if ( - ((m_aggregateScriptEvents & scriptEvents.touch) != 0) || - ((m_aggregateScriptEvents & scriptEvents.touch_end) != 0) || - ((m_aggregateScriptEvents & scriptEvents.touch_start) != 0) - ) - { - objectflagupdate |= (uint) LLObject.ObjectFlags.Touch; - } - - if ((m_aggregateScriptEvents & scriptEvents.money) != 0) + if (m_updateFlag == 1) //some change has been made so update the clients { - objectflagupdate |= (uint) LLObject.ObjectFlags.Money; - } + AddTerseUpdateToAllAvatars(); + ClearUpdateSchedule(); - if ( - ((m_aggregateScriptEvents & scriptEvents.collision) != 0) || - ((m_aggregateScriptEvents & scriptEvents.collision_end) != 0) || - ((m_aggregateScriptEvents & scriptEvents.collision_start) != 0) - ) - { - // subscribe to physics updates. + // This causes the Scene to 'poll' physical objects every couple of frames + // bad, so it's been replaced by an event driven method. + //if ((ObjectFlags & (uint)LLObject.ObjectFlags.Physics) != 0) + //{ + // Only send the constant terse updates on physical objects! + //ScheduleTerseUpdate(); + //} } - - LocalFlags = (LLObject.ObjectFlags) objectflagupdate; - - if (m_parentGroup != null && m_parentGroup.RootPart == this) - m_parentGroup.aggregateScriptEvents(); else - ScheduleFullUpdate(); - } - - #region Events - - public void PhysicsRequestingTerseUpdate() - { - if (PhysActor != null) { - LLVector3 newpos = new LLVector3(PhysActor.Position.GetBytes(), 0); - if (newpos.X > 257f || newpos.X < -1f || newpos.Y > 257f || newpos.Y < -1f) + if (m_updateFlag == 2) // is a new prim, just created/reloaded or has major changes { - m_parentGroup.AbsolutePosition = newpos; - return; + AddFullUpdateToAllAvatars(); + ClearUpdateSchedule(); } } - ScheduleTerseUpdate(); - - //SendTerseUpdateToAllClients(); } #endregion - #region Client Update Methods + #region Shape /// - /// Tell all scene presences that they should send updates for this part to their clients + /// /// - public void AddFullUpdateToAllAvatars() + /// + public void UpdateShape(ObjectShapePacket.ObjectDataBlock shapeBlock) { - List avatars = m_parentGroup.GetScenePresences(); - for (int i = 0; i < avatars.Count; i++) + m_shape.PathBegin = shapeBlock.PathBegin; + m_shape.PathEnd = shapeBlock.PathEnd; + m_shape.PathScaleX = shapeBlock.PathScaleX; + m_shape.PathScaleY = shapeBlock.PathScaleY; + m_shape.PathShearX = shapeBlock.PathShearX; + m_shape.PathShearY = shapeBlock.PathShearY; + m_shape.PathSkew = shapeBlock.PathSkew; + m_shape.ProfileBegin = shapeBlock.ProfileBegin; + m_shape.ProfileEnd = shapeBlock.ProfileEnd; + m_shape.PathCurve = shapeBlock.PathCurve; + m_shape.ProfileCurve = shapeBlock.ProfileCurve; + m_shape.ProfileHollow = shapeBlock.ProfileHollow; + m_shape.PathRadiusOffset = shapeBlock.PathRadiusOffset; + m_shape.PathRevolutions = shapeBlock.PathRevolutions; + m_shape.PathTaperX = shapeBlock.PathTaperX; + m_shape.PathTaperY = shapeBlock.PathTaperY; + m_shape.PathTwist = shapeBlock.PathTwist; + m_shape.PathTwistBegin = shapeBlock.PathTwistBegin; + if (PhysActor != null) { - avatars[i].QueuePartForUpdate(this); + PhysActor.Shape = m_shape; } + ScheduleFullUpdate(); } - public void SendFullUpdateToAllClientsExcept(LLUUID agentID) - { - List avatars = m_parentGroup.GetScenePresences(); - for (int i = 0; i < avatars.Count; i++) - { - // Ugly reference :( - if (avatars[i].UUID != agentID) - { - m_parentGroup.SendPartFullUpdate(avatars[i].ControllingClient, this, - avatars[i].GenerateClientFlags(UUID)); - } - } - } + #endregion + #region ExtraParams - public void AddFullUpdateToAvatar(ScenePresence presence) + public void UpdatePrimFlags(ushort type, bool inUse, byte[] data) { - presence.QueuePartForUpdate(this); - } - /// - /// - /// - public void SendFullUpdateToAllClients() - { - List avatars = m_parentGroup.GetScenePresences(); - for (int i = 0; i < avatars.Count; i++) + + //m_log.Info("TSomething1:" + ((type & (ushort)ExtraParamType.Something1) == (ushort)ExtraParamType.Something1)); + //m_log.Info("TSomething2:" + ((type & (ushort)ExtraParamType.Something2) == (ushort)ExtraParamType.Something2)); + //m_log.Info("TSomething3:" + ((type & (ushort)ExtraParamType.Something3) == (ushort)ExtraParamType.Something3)); + //m_log.Info("TSomething4:" + ((type & (ushort)ExtraParamType.Something4) == (ushort)ExtraParamType.Something4)); + //m_log.Info("TSomething5:" + ((type & (ushort)ExtraParamType.Something5) == (ushort)ExtraParamType.Something5)); + //m_log.Info("TSomething6:" + ((type & (ushort)ExtraParamType.Something6) == (ushort)ExtraParamType.Something6)); + + bool usePhysics = false; + bool IsTemporary = false; + bool IsPhantom = false; + bool castsShadows = false; + bool wasUsingPhysics = ((ObjectFlags & (uint) LLObject.ObjectFlags.Physics) != 0); + //bool IsLocked = false; + int i = 0; + + + try { - // Ugly reference :( - m_parentGroup.SendPartFullUpdate(avatars[i].ControllingClient, this, - avatars[i].GenerateClientFlags(UUID)); + i += 46; + //IsLocked = (data[i++] != 0) ? true : false; + usePhysics = ((data[i++] != 0) && m_parentGroup.Scene.m_physicalPrim) ? true : false; + //System.Console.WriteLine("U" + packet.ToBytes().Length.ToString()); + IsTemporary = (data[i++] != 0) ? true : false; + IsPhantom = (data[i++] != 0) ? true : false; + castsShadows = (data[i++] != 0) ? true : false; + } + catch (Exception) + { + Console.WriteLine("Ignoring invalid Packet:"); + //Silently ignore it - TODO: FIXME Quick } - } - /// - /// - /// - /// - public void SendFullUpdate(IClientAPI remoteClient, uint clientFlags) - { - m_parentGroup.SendPartFullUpdate(remoteClient, this, clientFlags); - } - - /// - /// Sends a full update to the client - /// - /// - /// - public void SendFullUpdateToClient(IClientAPI remoteClient, uint clientflags) - { - LLVector3 lPos; - lPos = OffsetPosition; - SendFullUpdateToClient(remoteClient, lPos, clientflags); - } + if (usePhysics) + { + AddFlag(LLObject.ObjectFlags.Physics); + if (!wasUsingPhysics) + { + DoPhysicsPropertyUpdate(usePhysics, false); + } + } + else + { + RemFlag(LLObject.ObjectFlags.Physics); + if (wasUsingPhysics) + { + DoPhysicsPropertyUpdate(usePhysics, false); + } + } - /// - /// Sends a full update to the client - /// - /// - /// - /// - public void SendFullUpdateToClient(IClientAPI remoteClient, LLVector3 lPos, uint clientFlags) - { - LLQuaternion lRot; - lRot = RotationOffset; - clientFlags &= ~(uint) LLObject.ObjectFlags.CreateSelected; - if (remoteClient.AgentId == OwnerID) + if (IsPhantom) { - if ((uint) (Flags & LLObject.ObjectFlags.CreateSelected) != 0) + AddFlag(LLObject.ObjectFlags.Phantom); + if (PhysActor != null) { - clientFlags |= (uint) LLObject.ObjectFlags.CreateSelected; - Flags &= ~LLObject.ObjectFlags.CreateSelected; + m_parentGroup.Scene.PhysicsScene.RemovePrim(PhysActor); + /// that's not wholesome. Had to make Scene public + PhysActor = null; } } + else + { + RemFlag(LLObject.ObjectFlags.Phantom); + if (PhysActor == null) + { + PhysActor = m_parentGroup.Scene.PhysicsScene.AddPrimShape( + Name, + Shape, + new PhysicsVector(AbsolutePosition.X, AbsolutePosition.Y, + AbsolutePosition.Z), + new PhysicsVector(Scale.X, Scale.Y, Scale.Z), + new Quaternion(RotationOffset.W, RotationOffset.X, + RotationOffset.Y, RotationOffset.Z), usePhysics); + if (PhysActor != null) + { + PhysActor.LocalID = LocalId; + DoPhysicsPropertyUpdate(usePhysics, true); + } + } + else + { + PhysActor.IsPhysical = usePhysics; + DoPhysicsPropertyUpdate(usePhysics, false); + } + } - byte[] color = new[] {m_color.R, m_color.G, m_color.B, m_color.A}; - remoteClient.SendPrimitiveToClient(m_regionHandle, (ushort) (m_parentGroup.GetTimeDilation() * ushort.MaxValue), LocalId, m_shape, lPos, clientFlags, - m_uuid, - OwnerID, - m_text, color, ParentID, m_particleSystem, lRot, m_clickAction, m_TextureAnimation, m_IsAttachment, - m_attachmentPoint, fromAssetID); + if (IsTemporary) + { + AddFlag(LLObject.ObjectFlags.TemporaryOnRez); + } + else + { + RemFlag(LLObject.ObjectFlags.TemporaryOnRez); + } + // System.Console.WriteLine("Update: PHY:" + UsePhysics.ToString() + ", T:" + IsTemporary.ToString() + ", PHA:" + IsPhantom.ToString() + " S:" + CastsShadows.ToString()); + ScheduleFullUpdate(); } - - /// Terse updates - public void AddTerseUpdateToAllAvatars() + public void ScriptSetPhysicsStatus(bool UsePhysics) { - List avatars = m_parentGroup.GetScenePresences(); - for (int i = 0; i < avatars.Count; i++) + if (m_parentGroup != null) { - avatars[i].QueuePartForUpdate(this); + m_parentGroup.ScriptSetPhysicsStatus(UsePhysics); } } - - public void AddTerseUpdateToAvatar(ScenePresence presence) + public void ScriptSetPhantomStatus(bool Phantom) { - presence.QueuePartForUpdate(this); + if (m_parentGroup != null) + { + m_parentGroup.ScriptSetPhantomStatus(Phantom); + } } - - /// - /// - /// - public void SendTerseUpdateToAllClients() + public void DoPhysicsPropertyUpdate(bool UsePhysics, bool isNew) { - List avatars = m_parentGroup.GetScenePresences(); - for (int i = 0; i < avatars.Count; i++) + if (PhysActor != null) { - m_parentGroup.SendPartTerseUpdate(avatars[i].ControllingClient, this); + if (UsePhysics != PhysActor.IsPhysical || isNew) + { + if (PhysActor.IsPhysical) + { + if (!isNew) + ParentGroup.Scene.RemovePhysicalPrim(1); + + PhysActor.OnRequestTerseUpdate -= PhysicsRequestingTerseUpdate; + PhysActor.OnOutOfBounds -= PhysicsOutOfBounds; + PhysActor.delink(); + } + + PhysActor.IsPhysical = UsePhysics; + + + // If we're not what we're supposed to be in the physics scene, recreate ourselves. + //m_parentGroup.Scene.PhysicsScene.RemovePrim(PhysActor); + /// that's not wholesome. Had to make Scene public + //PhysActor = null; + + + if ((ObjectFlags & (uint) LLObject.ObjectFlags.Phantom) == 0) + { + //PhysActor = m_parentGroup.Scene.PhysicsScene.AddPrimShape( + //Name, + //Shape, + //new PhysicsVector(AbsolutePosition.X, AbsolutePosition.Y, + //AbsolutePosition.Z), + //new PhysicsVector(Scale.X, Scale.Y, Scale.Z), + //new Quaternion(RotationOffset.W, RotationOffset.X, + //RotationOffset.Y, RotationOffset.Z), UsePhysics); + if (UsePhysics) + { + ParentGroup.Scene.AddPhysicalPrim(1); + + PhysActor.OnRequestTerseUpdate += PhysicsRequestingTerseUpdate; + PhysActor.OnOutOfBounds += PhysicsOutOfBounds; + if (ParentID != 0 && ParentID != LocalId) + { + if (ParentGroup.RootPart.PhysActor != null) + { + PhysActor.link(ParentGroup.RootPart.PhysActor); + } + } + + } + } + } + m_parentGroup.Scene.PhysicsScene.AddPhysicsActorTaint(PhysActor); } } - /// - /// Send a terse update to the client. - /// - /// - public void SendTerseUpdate(IClientAPI remoteClient) + public void UpdateExtraParam(ushort type, bool inUse, byte[] data) { - m_parentGroup.SendPartTerseUpdate(remoteClient, this); + m_shape.ExtraParams = new byte[data.Length + 7]; + int i = 0; + uint length = (uint) data.Length; + m_shape.ExtraParams[i++] = 1; + m_shape.ExtraParams[i++] = (byte) (type%256); + m_shape.ExtraParams[i++] = (byte) ((type >> 8)%256); + + m_shape.ExtraParams[i++] = (byte) (length%256); + m_shape.ExtraParams[i++] = (byte) ((length >> 8)%256); + m_shape.ExtraParams[i++] = (byte) ((length >> 16)%256); + m_shape.ExtraParams[i++] = (byte) ((length >> 24)%256); + Array.Copy(data, 0, m_shape.ExtraParams, i, data.Length); + + ScheduleFullUpdate(); } - public void SendTerseUpdateToClient(IClientAPI remoteClient) + #endregion + + #region Physics + + public float GetMass() { - LLVector3 lPos; - lPos = OffsetPosition; - LLQuaternion mRot = RotationOffset; - if ((ObjectFlags & (uint) LLObject.ObjectFlags.Physics) == 0) + if (PhysActor != null) { - remoteClient.SendPrimTerseUpdate(m_regionHandle, (ushort) (m_parentGroup.GetTimeDilation() * ushort.MaxValue), LocalId, lPos, mRot, Shape.State, - fromAssetID); + return PhysActor.Mass; } else { - remoteClient.SendPrimTerseUpdate(m_regionHandle, (ushort) (m_parentGroup.GetTimeDilation() * ushort.MaxValue), LocalId, lPos, mRot, Velocity, - RotationalVelocity); - //System.Console.WriteLine("LID: " + LocalID + " RVel:" + RotationalVelocity.ToString() + " TD: " + ((ushort)(m_parentGroup.Scene.TimeDilation * 500000f)).ToString() + ":" + m_parentGroup.Scene.TimeDilation.ToString()); + return 0; } } - public void SendTerseUpdateToClient(IClientAPI remoteClient, LLVector3 lPos) + public LLVector3 GetGeometricCenter() { - LLQuaternion mRot = RotationOffset; - if (m_IsAttachment) + if (PhysActor != null) { - remoteClient.SendPrimTerseUpdate(m_regionHandle, (ushort) (m_parentGroup.GetTimeDilation() * ushort.MaxValue), LocalId, lPos, mRot, - (byte) ((m_attachmentPoint % 16) * 16 + (m_attachmentPoint / 16)), fromAssetID); + return new LLVector3(PhysActor.CenterOfMass.X, PhysActor.CenterOfMass.Y, PhysActor.CenterOfMass.Z); } else { - if ((ObjectFlags & (uint) LLObject.ObjectFlags.Physics) == 0) - { - remoteClient.SendPrimTerseUpdate(m_regionHandle, (ushort) (m_parentGroup.GetTimeDilation() * ushort.MaxValue), LocalId, lPos, mRot, - Shape.State, fromAssetID); - } - else - { - remoteClient.SendPrimTerseUpdate(m_regionHandle, (ushort) (m_parentGroup.GetTimeDilation() * ushort.MaxValue), LocalId, lPos, mRot, Velocity, - RotationalVelocity); - //System.Console.WriteLine("LID: " + LocalID + "RVel:" + RotationalVelocity.ToString() + " TD: " + ((ushort)(m_parentGroup.Scene.TimeDilation * 500000f)).ToString() + ":" + m_parentGroup.Scene.TimeDilation.ToString()); - } + return new LLVector3(0, 0, 0); } } #endregion - #region Update Scheduling + #region Texture /// - /// Clear all pending updates + /// /// - private void ClearUpdateSchedule() + /// + public void UpdateTextureEntry(byte[] textureEntry) { - m_updateFlag = 0; + m_shape.TextureEntry = textureEntry; + TriggerScriptChangedEvent(Changed.TEXTURE); + ScheduleFullUpdate(); } - /// - /// Schedules this prim for a full update - /// - public void ScheduleFullUpdate() + // Added to handle bug in libsecondlife's TextureEntry.ToBytes() + // not handling RGBA properly. Cycles through, and "fixes" the color + // info + public void UpdateTexture(LLObject.TextureEntry tex) { - if (m_parentGroup != null) - { - m_parentGroup.HasGroupChanged = true; - m_parentGroup.QueueForUpdateCheck(); - } - - int timeNow = Util.UnixTimeSinceEpoch(); - - // If multiple updates are scheduled on the same second, we still need to perform all of them - // So we'll force the issue by bumping up the timestamp so that later processing sees these need - // to be performed. - if (timeNow <= TimeStampFull) - { - TimeStampFull += 1; - } - else - { - TimeStampFull = (uint) timeNow; - } - - m_updateFlag = 2; - -// m_log.DebugFormat( -// "[SCENE OBJECT PART]: Scheduling full update for {0}, {1} at {2}", -// UUID, Name, TimeStampFull); - } - - public void AddFlag(LLObject.ObjectFlags flag) - { - LLObject.ObjectFlags prevflag = Flags; - //uint objflags = Flags; - if ((ObjectFlags & (uint) flag) == 0) - { - //Console.WriteLine("Adding flag: " + ((LLObject.ObjectFlags) flag).ToString()); - Flags |= flag; - } - //uint currflag = (uint)Flags; - //System.Console.WriteLine("Aprev: " + prevflag.ToString() + " curr: " + Flags.ToString()); - //ScheduleFullUpdate(); + //LLColor tmpcolor; + //for (uint i = 0; i < 32; i++) + //{ + // if (tex.FaceTextures[i] != null) + // { + // tmpcolor = tex.GetFace((uint) i).RGBA; + // tmpcolor.A = tmpcolor.A*255; + // tmpcolor.R = tmpcolor.R*255; + // tmpcolor.G = tmpcolor.G*255; + // tmpcolor.B = tmpcolor.B*255; + // tex.FaceTextures[i].RGBA = tmpcolor; + // } + //} + //tmpcolor = tex.DefaultTexture.RGBA; + //tmpcolor.A = tmpcolor.A*255; + //tmpcolor.R = tmpcolor.R*255; + //tmpcolor.G = tmpcolor.G*255; + //tmpcolor.B = tmpcolor.B*255; + //tex.DefaultTexture.RGBA = tmpcolor; + UpdateTextureEntry(tex.ToBytes()); } - public void RemFlag(LLObject.ObjectFlags flag) + public byte ConvertScriptUintToByte(uint indata) { - LLObject.ObjectFlags prevflag = Flags; - if ((ObjectFlags & (uint) flag) != 0) - { - //Console.WriteLine("Removing flag: " + ((LLObject.ObjectFlags)flag).ToString()); - Flags &= ~flag; - } - //System.Console.WriteLine("prev: " + prevflag.ToString() + " curr: " + Flags.ToString()); - //ScheduleFullUpdate(); + byte outdata = (byte)TextureAnimFlags.NONE; + if ((indata & 1) != 0) outdata |= (byte)TextureAnimFlags.ANIM_ON; + if ((indata & 2) != 0) outdata |= (byte)TextureAnimFlags.LOOP; + if ((indata & 4) != 0) outdata |= (byte)TextureAnimFlags.REVERSE; + if ((indata & 8) != 0) outdata |= (byte)TextureAnimFlags.PING_PONG; + if ((indata & 16) != 0) outdata |= (byte)TextureAnimFlags.SMOOTH; + if ((indata & 32) != 0) outdata |= (byte)TextureAnimFlags.ROTATE; + if ((indata & 64) != 0) outdata |= (byte)TextureAnimFlags.SCALE; + return outdata; } - /// - /// Schedule a terse update for this prim. Terse updates only send position, - /// rotation, velocity, rotational velocity and shape information. - /// - public void ScheduleTerseUpdate() + public void AddTextureAnimation(Primitive.TextureAnimation pTexAnim) { - if (m_updateFlag < 1) - { - if (m_parentGroup != null) - { - m_parentGroup.HasGroupChanged = true; - m_parentGroup.QueueForUpdateCheck(); - } - TimeStampTerse = (uint) Util.UnixTimeSinceEpoch(); - m_updateFlag = 1; + byte[] data = new byte[16]; + int pos = 0; -// m_log.DebugFormat( -// "[SCENE OBJECT PART]: Scheduling terse update for {0}, {1} at {2}", -// UUID, Name, TimeStampTerse); - } + // The flags don't like conversion from uint to byte, so we have to do + // it the crappy way. See the above function :( + + data[pos] = ConvertScriptUintToByte(pTexAnim.Flags); pos++; + data[pos] = (byte)pTexAnim.Face; pos++; + data[pos] = (byte)pTexAnim.SizeX; pos++; + data[pos] = (byte)pTexAnim.SizeY; pos++; + + Helpers.FloatToBytes(pTexAnim.Start).CopyTo(data, pos); + Helpers.FloatToBytes(pTexAnim.Length ).CopyTo(data, pos + 4); + Helpers.FloatToBytes(pTexAnim.Rate).CopyTo(data, pos + 8); + + m_TextureAnimation = data; } - /// - /// Tell all the prims which have had updates scheduled - /// - public void SendScheduledUpdates() - { - if (m_updateFlag == 1) //some change has been made so update the clients - { - AddTerseUpdateToAllAvatars(); - ClearUpdateSchedule(); + #endregion - // This causes the Scene to 'poll' physical objects every couple of frames - // bad, so it's been replaced by an event driven method. - //if ((ObjectFlags & (uint)LLObject.ObjectFlags.Physics) != 0) - //{ - // Only send the constant terse updates on physical objects! - //ScheduleTerseUpdate(); - //} - } - else - { - if (m_updateFlag == 2) // is a new prim, just created/reloaded or has major changes - { - AddFullUpdateToAllAvatars(); - ClearUpdateSchedule(); - } - } + #region ParticleSystem + + public void AddNewParticleSystem(Primitive.ParticleSystem pSystem) + { + m_particleSystem = pSystem.GetBytes(); } #endregion - #region Shape + #region Position /// /// /// - /// - public void UpdateShape(ObjectShapePacket.ObjectDataBlock shapeBlock) + /// + public void UpdateOffSet(LLVector3 pos) { - m_shape.PathBegin = shapeBlock.PathBegin; - m_shape.PathEnd = shapeBlock.PathEnd; - m_shape.PathScaleX = shapeBlock.PathScaleX; - m_shape.PathScaleY = shapeBlock.PathScaleY; - m_shape.PathShearX = shapeBlock.PathShearX; - m_shape.PathShearY = shapeBlock.PathShearY; - m_shape.PathSkew = shapeBlock.PathSkew; - m_shape.ProfileBegin = shapeBlock.ProfileBegin; - m_shape.ProfileEnd = shapeBlock.ProfileEnd; - m_shape.PathCurve = shapeBlock.PathCurve; - m_shape.ProfileCurve = shapeBlock.ProfileCurve; - m_shape.ProfileHollow = shapeBlock.ProfileHollow; - m_shape.PathRadiusOffset = shapeBlock.PathRadiusOffset; - m_shape.PathRevolutions = shapeBlock.PathRevolutions; - m_shape.PathTaperX = shapeBlock.PathTaperX; - m_shape.PathTaperY = shapeBlock.PathTaperY; - m_shape.PathTwist = shapeBlock.PathTwist; - m_shape.PathTwistBegin = shapeBlock.PathTwistBegin; - if (PhysActor != null) - { - PhysActor.Shape = m_shape; - } - ScheduleFullUpdate(); + LLVector3 newPos = new LLVector3(pos.X, pos.Y, pos.Z); + OffsetPosition = newPos; + ScheduleTerseUpdate(); + } + + public void UpdateGroupPosition(LLVector3 pos) + { + LLVector3 newPos = new LLVector3(pos.X, pos.Y, pos.Z); + GroupPosition = newPos; + ScheduleTerseUpdate(); } #endregion - #region ExtraParams + #region rotation - public void UpdatePrimFlags(ushort type, bool inUse, byte[] data) + public void UpdateRotation(LLQuaternion rot) { - //m_log.Info("TSomething1:" + ((type & (ushort)ExtraParamType.Something1) == (ushort)ExtraParamType.Something1)); - //m_log.Info("TSomething2:" + ((type & (ushort)ExtraParamType.Something2) == (ushort)ExtraParamType.Something2)); - //m_log.Info("TSomething3:" + ((type & (ushort)ExtraParamType.Something3) == (ushort)ExtraParamType.Something3)); - //m_log.Info("TSomething4:" + ((type & (ushort)ExtraParamType.Something4) == (ushort)ExtraParamType.Something4)); - //m_log.Info("TSomething5:" + ((type & (ushort)ExtraParamType.Something5) == (ushort)ExtraParamType.Something5)); - //m_log.Info("TSomething6:" + ((type & (ushort)ExtraParamType.Something6) == (ushort)ExtraParamType.Something6)); + //StoreUndoState(); + RotationOffset = new LLQuaternion(rot.X, rot.Y, rot.Z, rot.W); + ScheduleTerseUpdate(); + } - bool usePhysics = false; - bool IsTemporary = false; - bool IsPhantom = false; - bool castsShadows = false; - bool wasUsingPhysics = ((ObjectFlags & (uint) LLObject.ObjectFlags.Physics) != 0); - //bool IsLocked = false; - int i = 0; + #endregion + #region Sound + public void PreloadSound(string sound) + { + LLUUID ownerID = OwnerID; + LLUUID objectID = UUID; + LLUUID soundID = LLUUID.Zero; - try + if (!LLUUID.TryParse(sound, out soundID)) { - i += 46; - //IsLocked = (data[i++] != 0) ? true : false; - usePhysics = ((data[i++] != 0) && m_parentGroup.Scene.m_physicalPrim) ? true : false; - //System.Console.WriteLine("U" + packet.ToBytes().Length.ToString()); - IsTemporary = (data[i++] != 0) ? true : false; - IsPhantom = (data[i++] != 0) ? true : false; - castsShadows = (data[i++] != 0) ? true : false; + //Trys to fetch sound id from prim's inventory. + //Prim's inventory doesn't support non script items yet + SceneObjectPart op = this; + foreach (KeyValuePair item in op.TaskInventory) + { + if (item.Value.Name == sound) + { + soundID = item.Value.ItemID; + break; + } + } } - catch (Exception) + + List avatarts = m_parentGroup.Scene.GetAvatars(); + foreach (ScenePresence p in avatarts) { - Console.WriteLine("Ignoring invalid Packet:"); - //Silently ignore it - TODO: FIXME Quick + // TODO: some filtering by distance of avatar + + p.ControllingClient.SendPreLoadSound(objectID, objectID, soundID); } + } - if (usePhysics) + public void AdjustSoundGain(double volume) + { + if (volume > 1) + volume = 1; + if (volume < 0) + volume = 0; + + List avatarts = m_parentGroup.Scene.GetAvatars(); + foreach (ScenePresence p in avatarts) { - AddFlag(LLObject.ObjectFlags.Physics); - if (!wasUsingPhysics) - { - DoPhysicsPropertyUpdate(usePhysics, false); - } + p.ControllingClient.SendAttachedSoundGainChange(UUID, (float)volume); } - else + } + + public void SendSound(string sound, double volume, bool triggered, byte flags) + { + if (volume > 1) + volume = 1; + if (volume < 0) + volume = 0; + + LLUUID ownerID = OwnerID; + LLUUID objectID = UUID; + LLUUID parentID = GetRootPartUUID(); + LLUUID soundID = LLUUID.Zero; + LLVector3 position = AbsolutePosition; // region local + ulong regionHandle = m_parentGroup.Scene.RegionInfo.RegionHandle; + + //byte flags = 0; + + if (!LLUUID.TryParse(sound, out soundID)) { - RemFlag(LLObject.ObjectFlags.Physics); - if (wasUsingPhysics) + // search sound file from inventory + SceneObjectPart op = this; + foreach (KeyValuePair item in op.TaskInventory) { - DoPhysicsPropertyUpdate(usePhysics, false); + if (item.Value.Name == sound && item.Value.Type == (int)AssetType.Sound) + { + soundID = item.Value.ItemID; + break; + } } } + if(soundID == LLUUID.Zero) + return; - if (IsPhantom) + List avatarts = m_parentGroup.Scene.GetAvatars(); + foreach (ScenePresence p in avatarts) { - AddFlag(LLObject.ObjectFlags.Phantom); - if (PhysActor != null) + double dis=Util.GetDistanceTo(p.AbsolutePosition, position); + if(dis > 100.0) // Max audio distance + continue; + + // Scale by distance + volume*=((100.0-dis)/100.0); + + if (triggered) { - m_parentGroup.Scene.PhysicsScene.RemovePrim(PhysActor); - /// that's not wholesome. Had to make Scene public - PhysActor = null; - } - } - else - { - RemFlag(LLObject.ObjectFlags.Phantom); - if (PhysActor == null) - { - PhysActor = m_parentGroup.Scene.PhysicsScene.AddPrimShape( - Name, - Shape, - new PhysicsVector(AbsolutePosition.X, AbsolutePosition.Y, - AbsolutePosition.Z), - new PhysicsVector(Scale.X, Scale.Y, Scale.Z), - new Quaternion(RotationOffset.W, RotationOffset.X, - RotationOffset.Y, RotationOffset.Z), usePhysics); - - if (PhysActor != null) - { - PhysActor.LocalID = LocalId; - DoPhysicsPropertyUpdate(usePhysics, true); - } + p.ControllingClient.SendTriggeredSound(soundID, ownerID, objectID, parentID, regionHandle, position, (float)volume); } else { - PhysActor.IsPhysical = usePhysics; - DoPhysicsPropertyUpdate(usePhysics, false); + p.ControllingClient.SendPlayAttachedSound(soundID, objectID, ownerID, (float)volume, flags); } } - - if (IsTemporary) - { - AddFlag(LLObject.ObjectFlags.TemporaryOnRez); - } - else - { - RemFlag(LLObject.ObjectFlags.TemporaryOnRez); - } - // System.Console.WriteLine("Update: PHY:" + UsePhysics.ToString() + ", T:" + IsTemporary.ToString() + ", PHA:" + IsPhantom.ToString() + " S:" + CastsShadows.ToString()); - ScheduleFullUpdate(); } - public void ScriptSetPhysicsStatus(bool UsePhysics) - { - if (m_parentGroup != null) - { - m_parentGroup.ScriptSetPhysicsStatus(UsePhysics); - } - } + #endregion - public void ScriptSetPhantomStatus(bool Phantom) + #region Resizing/Scale + + /// + /// + /// + /// + public void Resize(LLVector3 scale) { - if (m_parentGroup != null) - { - m_parentGroup.ScriptSetPhantomStatus(Phantom); - } + StoreUndoState(); + m_shape.Scale = scale; + + ScheduleFullUpdate(); } - public void DoPhysicsPropertyUpdate(bool UsePhysics, bool isNew) + #endregion + + public void UpdatePermissions(LLUUID AgentID, byte field, uint localID, uint mask, byte addRemTF) { - if (PhysActor != null) + bool set = addRemTF == 1; + + // Are we the owner? + if (AgentID == OwnerID) { - if (UsePhysics != PhysActor.IsPhysical || isNew) + switch (field) { - if (PhysActor.IsPhysical) - { - if (!isNew) - ParentGroup.Scene.RemovePhysicalPrim(1); - - PhysActor.OnRequestTerseUpdate -= PhysicsRequestingTerseUpdate; - PhysActor.OnOutOfBounds -= PhysicsOutOfBounds; - PhysActor.delink(); - } - - PhysActor.IsPhysical = UsePhysics; - - - // If we're not what we're supposed to be in the physics scene, recreate ourselves. - //m_parentGroup.Scene.PhysicsScene.RemovePrim(PhysActor); - /// that's not wholesome. Had to make Scene public - //PhysActor = null; - + case 2: + OwnerMask = ApplyMask(OwnerMask, set, mask); + break; + case 4: + GroupMask = ApplyMask(GroupMask, set, mask); + break; + case 8: + EveryoneMask = ApplyMask(EveryoneMask, set, mask); + break; + case 16: + NextOwnerMask = ApplyMask(NextOwnerMask, set, mask); + break; + } + SendFullUpdateToAllClients(); - if ((ObjectFlags & (uint) LLObject.ObjectFlags.Phantom) == 0) - { - //PhysActor = m_parentGroup.Scene.PhysicsScene.AddPrimShape( - //Name, - //Shape, - //new PhysicsVector(AbsolutePosition.X, AbsolutePosition.Y, - //AbsolutePosition.Z), - //new PhysicsVector(Scale.X, Scale.Y, Scale.Z), - //new Quaternion(RotationOffset.W, RotationOffset.X, - //RotationOffset.Y, RotationOffset.Z), UsePhysics); - if (UsePhysics) - { - ParentGroup.Scene.AddPhysicalPrim(1); + SendObjectPropertiesToClient(AgentID); - PhysActor.OnRequestTerseUpdate += PhysicsRequestingTerseUpdate; - PhysActor.OnOutOfBounds += PhysicsOutOfBounds; - if (ParentID != 0 && ParentID != LocalId) - { - if (ParentGroup.RootPart.PhysActor != null) - { - PhysActor.link(ParentGroup.RootPart.PhysActor); - } - } - } - } - } - m_parentGroup.Scene.PhysicsScene.AddPhysicsActorTaint(PhysActor); } } - public void UpdateExtraParam(ushort type, bool inUse, byte[] data) + private void SendObjectPropertiesToClient(LLUUID AgentID) { - m_shape.ExtraParams = new byte[data.Length + 7]; - int i = 0; - uint length = (uint) data.Length; - m_shape.ExtraParams[i++] = 1; - m_shape.ExtraParams[i++] = (byte) (type % 256); - m_shape.ExtraParams[i++] = (byte) ((type >> 8) % 256); - - m_shape.ExtraParams[i++] = (byte) (length % 256); - m_shape.ExtraParams[i++] = (byte) ((length >> 8) % 256); - m_shape.ExtraParams[i++] = (byte) ((length >> 16) % 256); - m_shape.ExtraParams[i++] = (byte) ((length >> 24) % 256); - Array.Copy(data, 0, m_shape.ExtraParams, i, data.Length); - - ScheduleFullUpdate(); + List avatars = m_parentGroup.GetScenePresences(); + for (int i = 0; i < avatars.Count; i++) + { + // Ugly reference :( + if (avatars[i].UUID == AgentID) + { + m_parentGroup.GetProperties(avatars[i].ControllingClient); + } + } } - #endregion - - #region Physics - - public float GetMass() + private uint ApplyMask(uint val, bool set, uint mask) { - if (PhysActor != null) + if (set) { - return PhysActor.Mass; + return val |= mask; } else { - return 0; + return val &= ~mask; } } - public LLVector3 GetGeometricCenter() + #region Client Update Methods + + /// + /// Tell all scene presences that they should send updates for this part to their clients + /// + public void AddFullUpdateToAllAvatars() { - if (PhysActor != null) + List avatars = m_parentGroup.GetScenePresences(); + for (int i = 0; i < avatars.Count; i++) { - return new LLVector3(PhysActor.CenterOfMass.X, PhysActor.CenterOfMass.Y, PhysActor.CenterOfMass.Z); + avatars[i].QueuePartForUpdate(this); } - else + } + + public void SendFullUpdateToAllClientsExcept(LLUUID agentID) + { + List avatars = m_parentGroup.GetScenePresences(); + for (int i = 0; i < avatars.Count; i++) { - return new LLVector3(0, 0, 0); + // Ugly reference :( + if (avatars[i].UUID != agentID) + { + m_parentGroup.SendPartFullUpdate(avatars[i].ControllingClient, this, + avatars[i].GenerateClientFlags(UUID)); + } } } + - #endregion - - #region Texture + public void AddFullUpdateToAvatar(ScenePresence presence) + { + presence.QueuePartForUpdate(this); + } /// /// /// - /// - public void UpdateTextureEntry(byte[] textureEntry) + public void SendFullUpdateToAllClients() { - m_shape.TextureEntry = textureEntry; - TriggerScriptChangedEvent(Changed.TEXTURE); - ScheduleFullUpdate(); + List avatars = m_parentGroup.GetScenePresences(); + for (int i = 0; i < avatars.Count; i++) + { + // Ugly reference :( + m_parentGroup.SendPartFullUpdate(avatars[i].ControllingClient, this, + avatars[i].GenerateClientFlags(UUID)); + } } - // Added to handle bug in libsecondlife's TextureEntry.ToBytes() - // not handling RGBA properly. Cycles through, and "fixes" the color - // info - public void UpdateTexture(LLObject.TextureEntry tex) + /// + /// + /// + /// + public void SendFullUpdate(IClientAPI remoteClient, uint clientFlags) { - //LLColor tmpcolor; - //for (uint i = 0; i < 32; i++) - //{ - // if (tex.FaceTextures[i] != null) - // { - // tmpcolor = tex.GetFace((uint) i).RGBA; - // tmpcolor.A = tmpcolor.A*255; - // tmpcolor.R = tmpcolor.R*255; - // tmpcolor.G = tmpcolor.G*255; - // tmpcolor.B = tmpcolor.B*255; - // tex.FaceTextures[i].RGBA = tmpcolor; - // } - //} - //tmpcolor = tex.DefaultTexture.RGBA; - //tmpcolor.A = tmpcolor.A*255; - //tmpcolor.R = tmpcolor.R*255; - //tmpcolor.G = tmpcolor.G*255; - //tmpcolor.B = tmpcolor.B*255; - //tex.DefaultTexture.RGBA = tmpcolor; - UpdateTextureEntry(tex.ToBytes()); + m_parentGroup.SendPartFullUpdate(remoteClient, this, clientFlags); } - public byte ConvertScriptUintToByte(uint indata) + /// + /// Sends a full update to the client + /// + /// + /// + public void SendFullUpdateToClient(IClientAPI remoteClient, uint clientflags) { - byte outdata = (byte) TextureAnimFlags.NONE; - if ((indata & 1) != 0) outdata |= (byte) TextureAnimFlags.ANIM_ON; - if ((indata & 2) != 0) outdata |= (byte) TextureAnimFlags.LOOP; - if ((indata & 4) != 0) outdata |= (byte) TextureAnimFlags.REVERSE; - if ((indata & 8) != 0) outdata |= (byte) TextureAnimFlags.PING_PONG; - if ((indata & 16) != 0) outdata |= (byte) TextureAnimFlags.SMOOTH; - if ((indata & 32) != 0) outdata |= (byte) TextureAnimFlags.ROTATE; - if ((indata & 64) != 0) outdata |= (byte) TextureAnimFlags.SCALE; - return outdata; + LLVector3 lPos; + lPos = OffsetPosition; + SendFullUpdateToClient(remoteClient, lPos, clientflags); } - - public void AddTextureAnimation(Primitive.TextureAnimation pTexAnim) + + /// + /// Sends a full update to the client + /// + /// + /// + /// + public void SendFullUpdateToClient(IClientAPI remoteClient, LLVector3 lPos, uint clientFlags) { - byte[] data = new byte[16]; - int pos = 0; - - // The flags don't like conversion from uint to byte, so we have to do - // it the crappy way. See the above function :( + LLQuaternion lRot; + lRot = RotationOffset; + clientFlags &= ~(uint) LLObject.ObjectFlags.CreateSelected; - data[pos] = ConvertScriptUintToByte(pTexAnim.Flags); - pos++; - data[pos] = (byte) pTexAnim.Face; - pos++; - data[pos] = (byte) pTexAnim.SizeX; - pos++; - data[pos] = (byte) pTexAnim.SizeY; - pos++; + if (remoteClient.AgentId == OwnerID) + { + if ((uint) (Flags & LLObject.ObjectFlags.CreateSelected) != 0) + { + clientFlags |= (uint) LLObject.ObjectFlags.CreateSelected; + Flags &= ~LLObject.ObjectFlags.CreateSelected; + } + } - Helpers.FloatToBytes(pTexAnim.Start).CopyTo(data, pos); - Helpers.FloatToBytes(pTexAnim.Length).CopyTo(data, pos + 4); - Helpers.FloatToBytes(pTexAnim.Rate).CopyTo(data, pos + 8); - m_TextureAnimation = data; + byte[] color = new byte[] {m_color.R, m_color.G, m_color.B, m_color.A}; + remoteClient.SendPrimitiveToClient(m_regionHandle, (ushort)(m_parentGroup.GetTimeDilation() * (float)ushort.MaxValue), LocalId, m_shape, lPos, clientFlags, m_uuid, + OwnerID, + m_text, color, ParentID, m_particleSystem, lRot, m_clickAction, m_TextureAnimation, m_IsAttachment, m_attachmentPoint,fromAssetID); } - #endregion - - #region ParticleSystem - - public void AddNewParticleSystem(Primitive.ParticleSystem pSystem) + /// Terse updates + public void AddTerseUpdateToAllAvatars() { - m_particleSystem = pSystem.GetBytes(); + List avatars = m_parentGroup.GetScenePresences(); + for (int i = 0; i < avatars.Count; i++) + { + avatars[i].QueuePartForUpdate(this); + } } - #endregion - - #region Position + public void AddTerseUpdateToAvatar(ScenePresence presence) + { + presence.QueuePartForUpdate(this); + } /// /// /// - /// - public void UpdateOffSet(LLVector3 pos) + public void SendTerseUpdateToAllClients() { - LLVector3 newPos = new LLVector3(pos.X, pos.Y, pos.Z); - OffsetPosition = newPos; - ScheduleTerseUpdate(); + List avatars = m_parentGroup.GetScenePresences(); + for (int i = 0; i < avatars.Count; i++) + { + m_parentGroup.SendPartTerseUpdate(avatars[i].ControllingClient, this); + } } - public void UpdateGroupPosition(LLVector3 pos) + /// + /// Send a terse update to the client. + /// + /// + public void SendTerseUpdate(IClientAPI remoteClient) { - LLVector3 newPos = new LLVector3(pos.X, pos.Y, pos.Z); - GroupPosition = newPos; - ScheduleTerseUpdate(); + m_parentGroup.SendPartTerseUpdate(remoteClient, this); + } + + public void SendTerseUpdateToClient(IClientAPI remoteClient) + { + LLVector3 lPos; + lPos = OffsetPosition; + LLQuaternion mRot = RotationOffset; + if ((ObjectFlags & (uint) LLObject.ObjectFlags.Physics) == 0) + { + remoteClient.SendPrimTerseUpdate(m_regionHandle, (ushort)(m_parentGroup.GetTimeDilation() * (float)ushort.MaxValue), LocalId, lPos, mRot, Shape.State, fromAssetID); + } + else + { + remoteClient.SendPrimTerseUpdate(m_regionHandle, (ushort)(m_parentGroup.GetTimeDilation() * (float)ushort.MaxValue), LocalId, lPos, mRot, Velocity, + RotationalVelocity); + //System.Console.WriteLine("LID: " + LocalID + " RVel:" + RotationalVelocity.ToString() + " TD: " + ((ushort)(m_parentGroup.Scene.TimeDilation * 500000f)).ToString() + ":" + m_parentGroup.Scene.TimeDilation.ToString()); + } + } + + public void SendTerseUpdateToClient(IClientAPI remoteClient, LLVector3 lPos) + { + LLQuaternion mRot = RotationOffset; + if (m_IsAttachment) + { + remoteClient.SendPrimTerseUpdate(m_regionHandle, (ushort)(m_parentGroup.GetTimeDilation() * (float)ushort.MaxValue), LocalId, lPos, mRot, (byte)((m_attachmentPoint % 16) * 16 + (m_attachmentPoint / 16)),fromAssetID); + } + else + { + if ((ObjectFlags & (uint)LLObject.ObjectFlags.Physics) == 0) + { + remoteClient.SendPrimTerseUpdate(m_regionHandle, (ushort)(m_parentGroup.GetTimeDilation() * (float)ushort.MaxValue), LocalId, lPos, mRot, Shape.State, fromAssetID); + } + else + { + remoteClient.SendPrimTerseUpdate(m_regionHandle, (ushort)(m_parentGroup.GetTimeDilation() * (float)ushort.MaxValue), LocalId, lPos, mRot, Velocity, + RotationalVelocity); + //System.Console.WriteLine("LID: " + LocalID + "RVel:" + RotationalVelocity.ToString() + " TD: " + ((ushort)(m_parentGroup.Scene.TimeDilation * 500000f)).ToString() + ":" + m_parentGroup.Scene.TimeDilation.ToString()); + } + } } #endregion - #region rotation + public virtual void UpdateMovement() + { + } - public void UpdateRotation(LLQuaternion rot) + #region Events + + public void PhysicsRequestingTerseUpdate() { - //StoreUndoState(); - RotationOffset = new LLQuaternion(rot.X, rot.Y, rot.Z, rot.W); + if (PhysActor != null) + { + LLVector3 newpos = new LLVector3(PhysActor.Position.GetBytes(), 0); + if (newpos.X > 257f || newpos.X < -1f || newpos.Y > 257f || newpos.Y < -1f) + { + m_parentGroup.AbsolutePosition = newpos; + return; + } + + } ScheduleTerseUpdate(); + + //SendTerseUpdateToAllClients(); } #endregion - #region Sound + public void PhysicsOutOfBounds(PhysicsVector pos) + { + m_log.Info("[PHYSICS]: Physical Object went out of bounds."); + RemFlag(LLObject.ObjectFlags.Physics); + DoPhysicsPropertyUpdate(false, true); + //m_parentGroup.Scene.PhysicsScene.AddPhysicsActorTaint(PhysActor); + } - public void PreloadSound(string sound) + public virtual void OnGrab(LLVector3 offsetPos, IClientAPI remoteClient) { - LLUUID ownerID = OwnerID; - LLUUID objectID = UUID; - LLUUID soundID = LLUUID.Zero; + } - if (!LLUUID.TryParse(sound, out soundID)) + + public void SetText(string text) + { + Text = text; + ScheduleFullUpdate(); + } + + public void SetText(string text, Vector3 color, double alpha) + { + Color = Color.FromArgb(0xff - (int) (alpha*0xff), + (int) (color.x*0xff), + (int) (color.y*0xff), + (int) (color.z*0xff)); + SetText( text ); + } + + public int registerTargetWaypoint(LLVector3 target, float tolerance) + { + if (m_parentGroup != null) { - //Trys to fetch sound id from prim's inventory. - //Prim's inventory doesn't support non script items yet - SceneObjectPart op = this; - foreach (KeyValuePair item in op.TaskInventory) - { - if (item.Value.Name == sound) - { - soundID = item.Value.ItemID; - break; - } - } + return m_parentGroup.registerTargetWaypoint(target, tolerance); } - - List avatarts = m_parentGroup.Scene.GetAvatars(); - foreach (ScenePresence p in avatarts) + return 0; + } + public void unregisterTargetWaypoint(int handle) + { + if (m_parentGroup != null) { - // TODO: some filtering by distance of avatar - - p.ControllingClient.SendPreLoadSound(objectID, objectID, soundID); + m_parentGroup.unregisterTargetWaypoint(handle); } } - - public void AdjustSoundGain(double volume) + protected SceneObjectPart(SerializationInfo info, StreamingContext context) { - if (volume > 1) - volume = 1; - if (volume < 0) - volume = 0; + //System.Console.WriteLine("SceneObjectPart Deserialize BGN"); - List avatarts = m_parentGroup.Scene.GetAvatars(); - foreach (ScenePresence p in avatarts) + if (info == null) { - p.ControllingClient.SendAttachedSoundGainChange(UUID, (float) volume); + throw new ArgumentNullException("info"); } + + /* + m_queue = (Queue)info.GetValue("m_queue", typeof(Queue)); + m_ids = (List)info.GetValue("m_ids", typeof(List)); + */ + + //System.Console.WriteLine("SceneObjectPart Deserialize END"); } - public void SendSound(string sound, double volume, bool triggered, byte flags) + [SecurityPermission(SecurityAction.LinkDemand, + Flags = SecurityPermissionFlag.SerializationFormatter)] + public virtual void GetObjectData( + SerializationInfo info, StreamingContext context) { - if (volume > 1) - volume = 1; - if (volume < 0) - volume = 0; + if (info == null) + { + throw new ArgumentNullException("info"); + } - LLUUID ownerID = OwnerID; - LLUUID objectID = UUID; - LLUUID parentID = GetRootPartUUID(); - LLUUID soundID = LLUUID.Zero; - LLVector3 position = AbsolutePosition; // region local - ulong regionHandle = m_parentGroup.Scene.RegionInfo.RegionHandle; + info.AddValue("m_inventoryFileName", m_inventoryFileName); + info.AddValue("m_folderID", m_folderID.UUID); + info.AddValue("PhysActor", PhysActor); - //byte flags = 0; + Dictionary TaskInventory_work = new Dictionary(); - if (!LLUUID.TryParse(sound, out soundID)) + foreach (LLUUID id in TaskInventory.Keys) { - // search sound file from inventory - SceneObjectPart op = this; - foreach (KeyValuePair item in op.TaskInventory) - { - if (item.Value.Name == sound && item.Value.Type == (int) AssetType.Sound) - { - soundID = item.Value.ItemID; - break; - } - } + TaskInventory_work.Add(id.UUID, TaskInventory[id]); } - if (soundID == LLUUID.Zero) - return; + info.AddValue("TaskInventory", TaskInventory_work); - List avatarts = m_parentGroup.Scene.GetAvatars(); - foreach (ScenePresence p in avatarts) - { - double dis = Util.GetDistanceTo(p.AbsolutePosition, position); - if (dis > 100.0) // Max audio distance - continue; + info.AddValue("LastOwnerID", LastOwnerID.UUID); + info.AddValue("OwnerID", OwnerID.UUID); + info.AddValue("GroupID", GroupID.UUID); - // Scale by distance - volume *= ((100.0 - dis) / 100.0); + info.AddValue("OwnershipCost", OwnershipCost); + info.AddValue("ObjectSaleType", ObjectSaleType); + info.AddValue("SalePrice", SalePrice); + info.AddValue("Category", Category); - if (triggered) - { - p.ControllingClient.SendTriggeredSound(soundID, ownerID, objectID, parentID, regionHandle, position, (float) volume); - } - else - { - p.ControllingClient.SendPlayAttachedSound(soundID, objectID, ownerID, (float) volume, flags); - } - } - } + info.AddValue("CreationDate", CreationDate); + info.AddValue("ParentID", ParentID); - #endregion + info.AddValue("OwnerMask", OwnerMask); + info.AddValue("NextOwnerMask", NextOwnerMask); + info.AddValue("GroupMask", GroupMask); + info.AddValue("EveryoneMask", EveryoneMask); + info.AddValue("BaseMask", BaseMask); - #region Resizing/Scale + info.AddValue("m_particleSystem", m_particleSystem); - /// - /// - /// - /// - public void Resize(LLVector3 scale) - { - StoreUndoState(); - m_shape.Scale = scale; + info.AddValue("TimeStampFull", TimeStampFull); + info.AddValue("TimeStampTerse", TimeStampTerse); + info.AddValue("TimeStampLastActivity", TimeStampLastActivity); - ScheduleFullUpdate(); + info.AddValue("m_updateFlag", m_updateFlag); + info.AddValue("CreatorID", CreatorID.UUID); + + info.AddValue("m_inventorySerial", m_inventorySerial); + info.AddValue("m_uuid", m_uuid.UUID); + info.AddValue("m_localID", m_localId); + info.AddValue("m_name", m_name); + info.AddValue("m_flags", Flags); + info.AddValue("m_material", m_material); + info.AddValue("m_regionHandle", m_regionHandle); + + info.AddValue("m_groupPosition.X", m_groupPosition.X); + info.AddValue("m_groupPosition.Y", m_groupPosition.Y); + info.AddValue("m_groupPosition.Z", m_groupPosition.Z); + + info.AddValue("m_offsetPosition.X", m_offsetPosition.X); + info.AddValue("m_offsetPosition.Y", m_offsetPosition.Y); + info.AddValue("m_offsetPosition.Z", m_offsetPosition.Z); + + info.AddValue("m_rotationOffset.W", m_rotationOffset.W); + info.AddValue("m_rotationOffset.X", m_rotationOffset.X); + info.AddValue("m_rotationOffset.Y", m_rotationOffset.Y); + info.AddValue("m_rotationOffset.Z", m_rotationOffset.Z); + + info.AddValue("m_velocity.X", m_velocity.X); + info.AddValue("m_velocity.Y", m_velocity.Y); + info.AddValue("m_velocity.Z", m_velocity.Z); + + info.AddValue("m_rotationalvelocity.X", m_rotationalvelocity.X); + info.AddValue("m_rotationalvelocity.Y", m_rotationalvelocity.Y); + info.AddValue("m_rotationalvelocity.Z", m_rotationalvelocity.Z); + + info.AddValue("m_angularVelocity.X", m_angularVelocity.X); + info.AddValue("m_angularVelocity.Y", m_angularVelocity.Y); + info.AddValue("m_angularVelocity.Z", m_angularVelocity.Z); + + info.AddValue("m_acceleration.X", m_acceleration.X); + info.AddValue("m_acceleration.Y", m_acceleration.Y); + info.AddValue("m_acceleration.Z", m_acceleration.Z); + + info.AddValue("m_description", m_description); + info.AddValue("m_color", m_color); + info.AddValue("m_text", m_text); + info.AddValue("m_sitName", m_sitName); + info.AddValue("m_touchName", m_touchName); + info.AddValue("m_clickAction", m_clickAction); + info.AddValue("m_shape", m_shape); + info.AddValue("m_parentGroup", m_parentGroup); + info.AddValue("PayPrice", PayPrice); } - #endregion - #region Copying + public void Undo() + { + if (m_undo.Count > 0) + { + UndoState goback = m_undo.Pop(); + if (goback != null) + goback.PlaybackState(this); + } + } - /// - /// Duplicates this part. - /// - /// - public SceneObjectPart Copy(uint localID, LLUUID AgentID, LLUUID GroupID, int linkNum) + public void SetScriptEvents(LLUUID scriptid, int events) + { + scriptEvents oldparts; + lock (m_scriptEvents) + { + if (m_scriptEvents.ContainsKey(scriptid)) + { + oldparts = m_scriptEvents[scriptid]; + + // remove values from aggregated script events + m_scriptEvents[scriptid] = (scriptEvents) events; + } + else + { + m_scriptEvents.Add(scriptid, (scriptEvents) events); + } + } + aggregateScriptEvents(); + } + + public void RemoveScriptEvents(LLUUID scriptid) { - SceneObjectPart dupe = (SceneObjectPart) MemberwiseClone(); - dupe.m_shape = m_shape.Copy(); - dupe.m_regionHandle = m_regionHandle; - dupe.UUID = LLUUID.Random(); - dupe.LocalId = localID; - dupe.OwnerID = AgentID; - dupe.GroupID = GroupID; - dupe.GroupPosition = new LLVector3(GroupPosition.X, GroupPosition.Y, GroupPosition.Z); - dupe.OffsetPosition = new LLVector3(OffsetPosition.X, OffsetPosition.Y, OffsetPosition.Z); - dupe.RotationOffset = - new LLQuaternion(RotationOffset.X, RotationOffset.Y, RotationOffset.Z, RotationOffset.W); - dupe.Velocity = new LLVector3(0, 0, 0); - dupe.Acceleration = new LLVector3(0, 0, 0); - dupe.AngularVelocity = new LLVector3(0, 0, 0); - dupe.ObjectFlags = ObjectFlags; + lock (m_scriptEvents) + { + if (m_scriptEvents.ContainsKey(scriptid)) + { + scriptEvents oldparts = scriptEvents.None; + oldparts = (scriptEvents) m_scriptEvents[scriptid]; - dupe.OwnershipCost = OwnershipCost; - dupe.ObjectSaleType = ObjectSaleType; - dupe.SalePrice = SalePrice; - dupe.Category = Category; + // remove values from aggregated script events + m_aggregateScriptEvents &= ~oldparts; + m_scriptEvents.Remove(scriptid); + } + } + aggregateScriptEvents(); + } - dupe.TaskInventory = (TaskInventoryDictionary) dupe.TaskInventory.Clone(); + public void aggregateScriptEvents() + { + // Aggregate script events + lock (m_scriptEvents) + { + foreach (scriptEvents s in m_scriptEvents.Values) + { + m_aggregateScriptEvents |= s; + } + } - dupe.ResetIDs(linkNum); + uint objectflagupdate = 0; - // This may be wrong... it might have to be applied in SceneObjectGroup to the object that's being duplicated. - dupe.LastOwnerID = ObjectOwner; + if ( + ((m_aggregateScriptEvents & scriptEvents.touch) != 0) || + ((m_aggregateScriptEvents & scriptEvents.touch_end) != 0) || + ((m_aggregateScriptEvents & scriptEvents.touch_start) != 0) + ) + { + objectflagupdate |= (uint) LLObject.ObjectFlags.Touch; + } - byte[] extraP = new byte[Shape.ExtraParams.Length]; - Array.Copy(Shape.ExtraParams, extraP, extraP.Length); - dupe.Shape.ExtraParams = extraP; - bool UsePhysics = ((dupe.ObjectFlags & (uint) LLObject.ObjectFlags.Physics) != 0); - dupe.DoPhysicsPropertyUpdate(UsePhysics, true); + if ((m_aggregateScriptEvents & scriptEvents.money) != 0) + { + objectflagupdate |= (uint) LLObject.ObjectFlags.Money; + } - return dupe; - } + if ( + ((m_aggregateScriptEvents & scriptEvents.collision) != 0) || + ((m_aggregateScriptEvents & scriptEvents.collision_end) != 0) || + ((m_aggregateScriptEvents & scriptEvents.collision_start) != 0) + ) + { + // subscribe to physics updates. + } - #endregion + LocalFlags=(LLObject.ObjectFlags)objectflagupdate; + + if(m_parentGroup != null && m_parentGroup.RootPart == this) + m_parentGroup.aggregateScriptEvents(); + else + ScheduleFullUpdate(); + } } -} \ No newline at end of file +} diff --git a/OpenSim/Region/Environment/Scenes/ScenePresence.cs b/OpenSim/Region/Environment/Scenes/ScenePresence.cs index 4cdf7f1..74e9cdc 100644 --- a/OpenSim/Region/Environment/Scenes/ScenePresence.cs +++ b/OpenSim/Region/Environment/Scenes/ScenePresence.cs @@ -40,111 +40,117 @@ using OpenSim.Region.Physics.Manager; namespace OpenSim.Region.Environment.Scenes { - [Serializable] + [Serializable] public class ScenePresence : EntityBase, ISerializable { // ~ScenePresence() // { // System.Console.WriteLine("[ScenePresence] Destructor called"); // } - - #region Delegates - - public delegate void SignificantClientMovement(IClientAPI remote_client); - - #endregion - + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public static AvatarAnimations Animations = new AvatarAnimations(); public static byte[] DefaultTexture; - private readonly Vector3[] Dir_Vectors = new Vector3[6]; - private readonly uint m_AgentControlFlags = 0; - private readonly List m_animations = new List(); - private readonly List m_animationSeqs = new List(); - private readonly List m_forcesList = new List(); - private readonly List m_knownChildRegions = new List(); - private readonly List m_knownPrimUUID = new List(); - private readonly UpdateQueue m_partsUpdateQueue = new UpdateQueue(); - private readonly byte m_state = 0; - private readonly Dictionary m_updateTimes = new Dictionary(); - protected ulong crossingFromRegion; public LLUUID currentParcelUUID = LLUUID.Zero; - private SignificantClientMovement handlerSignificantClientMovement; //OnSignificantClientMovement; + private List m_animations = new List(); + private List m_animationSeqs = new List(); + public Vector3 lastKnownAllowedPosition = new Vector3(); + public bool sentMessageAboutRestrictedParcelFlyingDown = false; + + private bool m_updateflag = false; + private byte m_movementflag = 0; + private readonly List m_forcesList = new List(); + private short m_updateCount = 0; + private uint m_requestedSitTargetID = 0; + private LLVector3 m_requestedSitOffset = new LLVector3(); + private float m_sitAvatarHeight = 2.0f; + private float m_godlevel = 0; + private LLVector3 m_LastChildAgentUpdatePosition = new LLVector3(); + + private int m_perfMonMS = 0; + + private bool m_setAlwaysRun = false; + + private Quaternion m_bodyRot; - public bool IsRestrictedToRegion; + public bool IsRestrictedToRegion = false; public string JID = string.Empty; - public Vector3 lastKnownAllowedPosition; // Agent moves with a PID controller causing a force to be exerted. - private LLVector3 lastPhysPos; - protected AvatarAppearance m_appearance; + private bool m_newForce = false; + private bool m_newCoarseLocations = true; + private bool m_gotAllObjectsInScene = false; - protected List m_attachments = new List(); + private LLVector3 m_lastVelocity = LLVector3.Zero; + + // Default AV Height private float m_avHeight = 127.0f; - private Quaternion m_bodyRot; + + protected RegionInfo m_regionInfo; + protected ulong crossingFromRegion = 0; + + private readonly Vector3[] Dir_Vectors = new Vector3[6]; + private LLVector3 lastPhysPos = new LLVector3(); // Position of agent's camera in world (region cordinates) + protected Vector3 m_CameraCenter = new Vector3(0, 0, 0); // Use these three vectors to figure out what the agent is looking at // Convert it to a Matrix and/or Quaternion protected Vector3 m_CameraAtAxis = new Vector3(0, 0, 0); - protected Vector3 m_CameraCenter = new Vector3(0, 0, 0); protected Vector3 m_CameraLeftAxis = new Vector3(0, 0, 0); protected Vector3 m_CameraUpAxis = new Vector3(0, 0, 0); - protected float m_DrawDistance; - private float m_godlevel; - private bool m_gotAllObjectsInScene; - private LLQuaternion m_headrotation; - private LLVector3 m_LastChildAgentUpdatePosition; - private LLVector3 m_lastVelocity = LLVector3.Zero; - private byte m_movementflag; - private bool m_newCoarseLocations = true; - private bool m_newForce; - private int m_perfMonMS; - protected RegionInfo m_regionInfo; - private LLVector3 m_requestedSitOffset; - private uint m_requestedSitTargetID; - private bool m_setAlwaysRun; - private float m_sitAvatarHeight = 2.0f; - private short m_updateCount; - private bool m_updateflag; + private uint m_AgentControlFlags = (uint) 0; + private LLQuaternion m_headrotation = new LLQuaternion(); + private byte m_state = (byte) 0; //Reuse the LLVector3 instead of creating a new one on the UpdateMovement method - private LLVector3 movementvector; + private LLVector3 movementvector = new LLVector3(); - /// - /// Position at which a significant movement was made - /// - private LLVector3 posLastSignificantMove; + private List m_knownPrimUUID = new List(); - public bool sentMessageAboutRestrictedParcelFlyingDown; + // Agent's Draw distance. + protected float m_DrawDistance = 0f; - #region Properties + protected AvatarAppearance m_appearance; - private readonly string m_firstname; - private readonly string m_lastname; - private readonly ulong m_regionHandle; - protected bool m_allowMovement = true; + protected List m_attachments = new List(); + + //neighbouring regions we have enabled a child agent in + private readonly List m_knownChildRegions = new List(); + + private SignificantClientMovement handlerSignificantClientMovement = null; //OnSignificantClientMovement; /// - /// This works out to be the ClientView object associated with this avatar, or it's UDP connection manager + /// Implemented Control Flags /// - private IClientAPI m_controllingClient; + private enum Dir_ControlFlags + { + DIR_CONTROL_FLAG_FORWARD = AgentManager.ControlFlags.AGENT_CONTROL_AT_POS, + DIR_CONTROL_FLAG_BACK = AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG, + DIR_CONTROL_FLAG_LEFT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS, + DIR_CONTROL_FLAG_RIGHT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG, + DIR_CONTROL_FLAG_UP = AgentManager.ControlFlags.AGENT_CONTROL_UP_POS, + DIR_CONTROL_FLAG_DOWN = AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG, + DIR_CONTROL_FLAG_DOWN_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG + } /// - /// If this is true, agent doesn't have a representation in this scene. - /// this is an agent 'looking into' this scene from a nearby scene(region) - /// - /// if False, this agent has a representation in this scene + /// Position at which a significant movement was made /// - private bool m_isChildAgent = true; + private LLVector3 posLastSignificantMove = new LLVector3(); - private uint m_parentID; - protected LLVector3 m_parentPosition; - protected PhysicsActor m_physicsActor; + public delegate void SignificantClientMovement(IClientAPI remote_client); + + public event SignificantClientMovement OnSignificantClientMovement; + + private UpdateQueue m_partsUpdateQueue = new UpdateQueue(); + private Dictionary m_updateTimes = new Dictionary(); + + #region Properties /// /// Physical scene representation of this Avatar. @@ -161,6 +167,16 @@ namespace OpenSim.Region.Environment.Scenes get { return m_movementflag; } } + public bool KnownPrim(LLUUID primID) + { + if (m_knownPrimUUID.Contains(primID)) + { + return true; + } + m_knownPrimUUID.Add(primID); + return false; + } + public bool Updated { @@ -168,6 +184,8 @@ namespace OpenSim.Region.Environment.Scenes get { return m_updateflag; } } + private readonly ulong m_regionHandle; + public ulong RegionHandle { get { return m_regionHandle; } @@ -178,11 +196,15 @@ namespace OpenSim.Region.Environment.Scenes get { return m_CameraCenter; } } + private readonly string m_firstname; + public string Firstname { get { return m_firstname; } } + private readonly string m_lastname; + public string Lastname { get { return m_lastname; } @@ -193,18 +215,29 @@ namespace OpenSim.Region.Environment.Scenes get { return m_DrawDistance; } } + protected bool m_allowMovement = true; + public bool AllowMovement { get { return m_allowMovement; } set { m_allowMovement = value; } } + /// + /// This works out to be the ClientView object associated with this avatar, or it's UDP connection manager + /// + private IClientAPI m_controllingClient; + + protected PhysicsActor m_physicsActor; + public IClientAPI ControllingClient { get { return m_controllingClient; } set { m_controllingClient = value; } } + protected LLVector3 m_parentPosition = new LLVector3(); + /// /// Absolute position of this avatar in 'region cordinates' /// @@ -239,7 +272,7 @@ namespace OpenSim.Region.Environment.Scenes } m_pos = value; - m_parentPosition = new LLVector3(0, 0, 0); + m_parentPosition=new LLVector3(0, 0, 0); } } @@ -280,12 +313,22 @@ namespace OpenSim.Region.Environment.Scenes } } + /// + /// If this is true, agent doesn't have a representation in this scene. + /// this is an agent 'looking into' this scene from a nearby scene(region) + /// + /// if False, this agent has a representation in this scene + /// + private bool m_isChildAgent = true; + public bool IsChildAgent { get { return m_isChildAgent; } set { m_isChildAgent = value; } } + private uint m_parentID = 0; + public uint ParentID { get { return m_parentID; } @@ -300,16 +343,6 @@ namespace OpenSim.Region.Environment.Scenes get { return m_knownChildRegions; } } - public bool KnownPrim(LLUUID primID) - { - if (m_knownPrimUUID.Contains(primID)) - { - return true; - } - m_knownPrimUUID.Add(primID); - return false; - } - #endregion #region Constructor(s) @@ -387,1947 +420,1920 @@ namespace OpenSim.Region.Environment.Scenes #endregion - static ScenePresence() + /// + /// Add the part to the queue of parts for which we need to send an update to the client + /// + /// + public void QueuePartForUpdate(SceneObjectPart part) { - LLObject.TextureEntry textu = AvatarAppearance.GetDefaultTextureEntry(); - DefaultTexture = textu.ToBytes(); + //if (InterestList.Contains(part.ParentGroup)) + //{ + lock (m_partsUpdateQueue) + { + m_partsUpdateQueue.Enqueue(part); + } + // } } - public ScenePresence() + public uint GenerateClientFlags(LLUUID ObjectID) { -/* JB - if (Animations == null) - { - Animations = new AvatarAnimations(); - Animations.LoadAnims(); - } -*/ - if (DefaultTexture == null) - { - LLObject.TextureEntry textu = AvatarAppearance.GetDefaultTextureEntry(); - DefaultTexture = textu.ToBytes(); - } + return m_scene.PermissionsMngr.GenerateClientFlags(m_uuid, ObjectID); } - protected ScenePresence(SerializationInfo info, StreamingContext context) - : base(info, context) + /// + /// Send updates to the client about prims which have been placed on the update queue. We don't + /// necessarily send updates for all the parts on the queue, e.g. if an updates with a more recent + /// timestamp has already been sent. + /// + public void SendPrimUpdates() { - //System.Console.WriteLine("ScenePresence Deserialize BGN"); + // if (m_scene.QuadTree.GetNodeID(this.AbsolutePosition.X, this.AbsolutePosition.Y) != m_currentQuadNode) + //{ + // this.UpdateQuadTreeNode(); + //this.RefreshQuadObject(); + //} + m_perfMonMS = System.Environment.TickCount; - if (info == null) - { - throw new ArgumentNullException("info"); - } -/* JB - if (Animations == null) - { - Animations = new AvatarAnimations(); - Animations.LoadAnims(); - } -*/ - if (DefaultTexture == null) + if (!m_gotAllObjectsInScene) { - LLObject.TextureEntry textu = AvatarAppearance.GetDefaultTextureEntry(); - DefaultTexture = textu.ToBytes(); + if (!m_isChildAgent || m_scene.m_seeIntoRegionFromNeighbor) + { + m_scene.SendAllSceneObjectsToClient(this); + m_gotAllObjectsInScene = true; + } } - - List animations_work = (List) info.GetValue("m_animations", typeof (List)); - - foreach (Guid guid in animations_work) + + if (m_partsUpdateQueue.Count > 0) { - m_animations.Add(new LLUUID(guid)); - } - - m_animationSeqs = (List) info.GetValue("m_animationSeqs", typeof (List)); - m_updateflag = (bool) info.GetValue("m_updateflag", typeof (bool)); - m_movementflag = (byte) info.GetValue("m_movementflag", typeof (byte)); - m_forcesList = (List) info.GetValue("m_forcesList", typeof (List)); - m_updateCount = (short) info.GetValue("m_updateCount", typeof (short)); - m_requestedSitTargetID = (uint) info.GetValue("m_requestedSitTargetID", typeof (uint)); - - m_requestedSitOffset - = new LLVector3( - (float) info.GetValue("m_requestedSitOffset.X", typeof (float)), - (float) info.GetValue("m_requestedSitOffset.Y", typeof (float)), - (float) info.GetValue("m_requestedSitOffset.Z", typeof (float))); + bool runUpdate = true; + int updateCount = 0; + while (runUpdate) + { + SceneObjectPart part = m_partsUpdateQueue.Dequeue(); + if (m_updateTimes.ContainsKey(part.UUID)) + { + ScenePartUpdate update = m_updateTimes[part.UUID]; - m_sitAvatarHeight = (float) info.GetValue("m_sitAvatarHeight", typeof (float)); - m_godlevel = (float) info.GetValue("m_godlevel", typeof (float)); - m_setAlwaysRun = (bool) info.GetValue("m_setAlwaysRun", typeof (bool)); + // We deal with the possibility that two updates occur at the same unix time + // at the update point itself. + if (update.LastFullUpdateTime < part.TimeStampFull) + { +// m_log.DebugFormat( +// "[SCENE PRESENCE]: Fully updating prim {0}, {1} - part timestamp {2}", +// part.Name, part.UUID, part.TimeStampFull); + + part.SendFullUpdate(ControllingClient, GenerateClientFlags(part.UUID)); - m_bodyRot - = new Quaternion( - (float) info.GetValue("m_bodyRot.w", typeof (float)), - (float) info.GetValue("m_bodyRot.x", typeof (float)), - (float) info.GetValue("m_bodyRot.y", typeof (float)), - (float) info.GetValue("m_bodyRot.z", typeof (float))); + // We'll update to the part's timestamp rather than the current time to + // avoid the race condition whereby the next tick occurs while we are + // doing this update. If this happened, then subsequent updates which occurred + // on the same tick or the next tick of the last update would be ignored. + update.LastFullUpdateTime = part.TimeStampFull; - IsRestrictedToRegion = (bool) info.GetValue("IsRestrictedToRegion", typeof (bool)); - m_newForce = (bool) info.GetValue("m_newForce", typeof (bool)); - //m_newAvatar = (bool)info.GetValue("m_newAvatar", typeof(bool)); - m_newCoarseLocations = (bool) info.GetValue("m_newCoarseLocations", typeof (bool)); - m_gotAllObjectsInScene = (bool) info.GetValue("m_gotAllObjectsInScene", typeof (bool)); - m_avHeight = (float) info.GetValue("m_avHeight", typeof (float)); - crossingFromRegion = (ulong) info.GetValue("crossingFromRegion", typeof (ulong)); + updateCount++; + } + else if (update.LastTerseUpdateTime <= part.TimeStampTerse) + { +// m_log.DebugFormat( +// "[SCENE PRESENCE]: Tersely updating prim {0}, {1} - part timestamp {2}", +// part.Name, part.UUID, part.TimeStampTerse); + + part.SendTerseUpdate(ControllingClient); - List Dir_Vectors_work = (List) info.GetValue("Dir_Vectors", typeof (List)); - List Dir_Vectors_work2 = new List(); + update.LastTerseUpdateTime = part.TimeStampTerse; + updateCount++; + } + } + else + { + //never been sent to client before so do full update + part.SendFullUpdate(ControllingClient, GenerateClientFlags(part.UUID)); + ScenePartUpdate update = new ScenePartUpdate(); + update.FullID = part.UUID; + update.LastFullUpdateTime = part.TimeStampFull; + m_updateTimes.Add(part.UUID, update); + updateCount++; + } - foreach (float[] f3 in Dir_Vectors_work) - { - Dir_Vectors_work2.Add(new Vector3(f3[0], f3[1], f3[2])); + if (m_partsUpdateQueue.Count < 1 || updateCount > 60) + { + runUpdate = false; + } + } } - Dir_Vectors = Dir_Vectors_work2.ToArray(); - - lastPhysPos - = new LLVector3( - (float) info.GetValue("lastPhysPos.X", typeof (float)), - (float) info.GetValue("lastPhysPos.Y", typeof (float)), - (float) info.GetValue("lastPhysPos.Z", typeof (float))); + m_scene.AddAgentTime(System.Environment.TickCount - m_perfMonMS); + } - m_CameraCenter - = new Vector3( - (float) info.GetValue("m_CameraCenter.X", typeof (float)), - (float) info.GetValue("m_CameraCenter.Y", typeof (float)), - (float) info.GetValue("m_CameraCenter.Z", typeof (float))); + public void forceAvatarMovement(Vector3 position, Quaternion rotation) + { + AddNewMovement(position, rotation); + } - m_CameraAtAxis - = new Vector3( - (float) info.GetValue("m_CameraAtAxis.X", typeof (float)), - (float) info.GetValue("m_CameraAtAxis.Y", typeof (float)), - (float) info.GetValue("m_CameraAtAxis.Z", typeof (float))); + #region Status Methods - m_CameraLeftAxis - = new Vector3( - (float) info.GetValue("m_CameraLeftAxis.X", typeof (float)), - (float) info.GetValue("m_CameraLeftAxis.Y", typeof (float)), - (float) info.GetValue("m_CameraLeftAxis.Z", typeof (float))); - - m_CameraUpAxis - = new Vector3( - (float) info.GetValue("m_CameraUpAxis.X", typeof (float)), - (float) info.GetValue("m_CameraUpAxis.Y", typeof (float)), - (float) info.GetValue("m_CameraUpAxis.Z", typeof (float))); - - m_DrawDistance = (float) info.GetValue("m_DrawDistance", typeof (float)); - m_appearance = (AvatarAppearance) info.GetValue("m_appearance", typeof (AvatarAppearance)); - m_knownChildRegions = (List) info.GetValue("m_knownChildRegions", typeof (List)); + /// + /// This turns a child agent, into a root agent + /// This is called when an agent teleports into a region, or if an + /// agent crosses into this region from a neighbor over the border + /// + public void MakeRootAgent(LLVector3 pos, bool isFlying) + { +// m_log.DebugFormat( +// "[SCENEPRESENCE]: Upgrading child agent {0}, {1} to a root agent in {2}", +// Name, UUID, m_scene.RegionInfo.RegionName); + + m_isChildAgent = false; - posLastSignificantMove - = new LLVector3( - (float) info.GetValue("posLastSignificantMove.X", typeof (float)), - (float) info.GetValue("posLastSignificantMove.Y", typeof (float)), - (float) info.GetValue("posLastSignificantMove.Z", typeof (float))); + AbsolutePosition = pos; - // m_partsUpdateQueue = (UpdateQueue)info.GetValue("m_partsUpdateQueue", typeof(UpdateQueue)); + AddToPhysicalScene(); + m_physicsActor.Flying = isFlying; + SendAnimPack(); - /* - Dictionary updateTimes_work - = (Dictionary)info.GetValue("m_updateTimes", typeof(Dictionary)); + m_scene.SwapRootAgentCount(false); + m_scene.CommsManager.UserProfileCacheService.RequestInventoryForUser(m_uuid); + m_scene.AddCapsHandler(m_uuid); + //if (!m_gotAllObjectsInScene) + //{ + m_scene.SendAllSceneObjectsToClient(this); + m_scene.LandChannel.sendLandUpdate(this, true); + + //m_gotAllObjectsInScene = true; + //} + } - foreach (Guid id in updateTimes_work.Keys) + /// + /// This turns a root agent into a child agent + /// when an agent departs this region for a neighbor, this gets called. + /// + /// It doesn't get called for a teleport. Reason being, an agent that + /// teleports out may not be anywhere near this region + /// + public void MakeChildAgent() + { + if(m_animations.Count > 0) { - m_updateTimes.Add(new LLUUID(id), updateTimes_work[id]); - } - */ - m_regionHandle = (ulong) info.GetValue("m_regionHandle", typeof (ulong)); - m_firstname = (string) info.GetValue("m_firstname", typeof (string)); - m_lastname = (string) info.GetValue("m_lastname", typeof (string)); - m_allowMovement = (bool) info.GetValue("m_allowMovement", typeof (bool)); - m_parentPosition = new LLVector3((float) info.GetValue("m_parentPosition.X", typeof (float)), - (float) info.GetValue("m_parentPosition.Y", typeof (float)), - (float) info.GetValue("m_parentPosition.Z", typeof (float))); + LLUUID movement=m_animations[0]; - m_isChildAgent = (bool) info.GetValue("m_isChildAgent", typeof (bool)); - m_parentID = (uint) info.GetValue("m_parentID", typeof (uint)); + m_animations.Clear(); + m_animationSeqs.Clear(); -// for OpenSim_v0.5 - currentParcelUUID = new LLUUID((Guid) info.GetValue("currentParcelUUID", typeof (Guid))); + SetMovementAnimation(movement); + } +// m_log.DebugFormat( +// "[SCENEPRESENCE]: Downgrading child agent {0}, {1} to a root agent in {2}", +// Name, UUID, m_scene.RegionInfo.RegionName); + + Velocity = new LLVector3(0, 0, 0); + m_isChildAgent = true; + m_scene.SwapRootAgentCount(true); + RemoveFromPhysicalScene(); + m_scene.EventManager.TriggerOnMakeChildAgent(this); + //this.Pos = new LLVector3(128, 128, 70); + } - lastKnownAllowedPosition - = new Vector3( - (float) info.GetValue("lastKnownAllowedPosition.X", typeof (float)), - (float) info.GetValue("lastKnownAllowedPosition.Y", typeof (float)), - (float) info.GetValue("lastKnownAllowedPosition.Z", typeof (float))); + /// + /// Removes physics plugin scene representation of this agent if it exists. + /// + private void RemoveFromPhysicalScene() + { + if (PhysicsActor != null) + { + m_scene.PhysicsScene.RemoveAvatar(PhysicsActor); + m_physicsActor.OnRequestTerseUpdate -= SendTerseUpdateToAllClients; + m_physicsActor.OnCollisionUpdate -= PhysicsCollisionUpdate; + PhysicsActor = null; + } + } - sentMessageAboutRestrictedParcelFlyingDown = (bool) info.GetValue("sentMessageAboutRestrictedParcelFlyingDown", typeof (bool)); + /// + /// + /// + /// + public void Teleport(LLVector3 pos) + { + RemoveFromPhysicalScene(); + Velocity = new LLVector3(0, 0, 0); + AbsolutePosition = pos; + AddToPhysicalScene(); + SendTerseUpdateToAllClients(); + } - m_LastChildAgentUpdatePosition - = new LLVector3( - (float) info.GetValue("m_LastChildAgentUpdatePosition.X", typeof (float)), - (float) info.GetValue("m_LastChildAgentUpdatePosition.Y", typeof (float)), - (float) info.GetValue("m_LastChildAgentUpdatePosition.Z", typeof (float))); + /// + /// + /// + public void StopMovement() + { + } - m_perfMonMS = (int) info.GetValue("m_perfMonMS", typeof (int)); - m_AgentControlFlags = (uint) info.GetValue("m_AgentControlFlags", typeof (uint)); + public void StopFlying() + { + // It turns out to get the agent to stop flying, you have to feed it stop flying velocities + // and send a full object update. + // There's no message to send the client to tell it to stop flying - m_headrotation - = new LLQuaternion( - (float) info.GetValue("m_headrotation.W", typeof (float)), - (float) info.GetValue("m_headrotation.X", typeof (float)), - (float) info.GetValue("m_headrotation.Y", typeof (float)), - (float) info.GetValue("m_headrotation.Z", typeof (float))); + // Add 1/6 the avatar's height to it's position so it doesn't shoot into the air + // when the avatar stands up - m_state = (byte) info.GetValue("m_state", typeof (byte)); + if (m_avHeight != 127.0f) + { + AbsolutePosition = AbsolutePosition + new LLVector3(0, 0, (m_avHeight / 6)); + } + else + { + AbsolutePosition = AbsolutePosition + new LLVector3(0, 0, (1.56f / 6)); + } + SetMovementAnimation(Animations.AnimsLLUUID["LAND"]); + SendFullUpdateToAllClients(); + } - List knownPrimUUID_work = (List) info.GetValue("m_knownPrimUUID", typeof (List)); + public void AddNeighbourRegion(ulong regionHandle) + { + if (!m_knownChildRegions.Contains(regionHandle)) + { + m_knownChildRegions.Add(regionHandle); + } + } - foreach (Guid id in knownPrimUUID_work) + public void RemoveNeighbourRegion(ulong regionHandle) + { + if (!m_knownChildRegions.Contains(regionHandle)) { - m_knownPrimUUID.Add(new LLUUID(id)); + m_knownChildRegions.Remove(regionHandle); } + } - //System.Console.WriteLine("ScenePresence Deserialize END"); + public List GetKnownRegionList() + { + return m_knownChildRegions; } - #region ISerializable Members + #endregion - [SecurityPermission(SecurityAction.LinkDemand, - Flags = SecurityPermissionFlag.SerializationFormatter)] - public override void GetObjectData( - SerializationInfo info, StreamingContext context) + #region Event Handlers + + /// + /// Sets avatar height in the phyiscs plugin + /// + internal void SetHeight(float height) { - if (info == null) + m_avHeight = height; + if (PhysicsActor != null) { - throw new ArgumentNullException("info"); + PhysicsVector SetSize = new PhysicsVector(0.45f, 0.6f, m_avHeight); + PhysicsActor.Size = SetSize; } + } - base.GetObjectData(info, context); + /// + /// Complete Avatar's movement into the region + /// + public void CompleteMovement() + { + LLVector3 look = Velocity; + if ((look.X == 0) && (look.Y == 0) && (look.Z == 0)) + { + look = new LLVector3(0.99f, 0.042f, 0); + } - List animations_work = new List(); + m_controllingClient.MoveAgentIntoRegion(m_regionInfo, AbsolutePosition, look); - foreach (LLUUID uuid in m_animations) + if (m_isChildAgent) { - animations_work.Add(uuid.UUID); + m_isChildAgent = false; + + //this.m_scene.SendAllSceneObjectsToClient(this.ControllingClient); + MakeRootAgent(AbsolutePosition, false); } + } - info.AddValue("m_animations", animations_work); + /// + /// This is the event handler for client movement. If a client is moving, this event is triggering. + /// + public void HandleAgentUpdate(IClientAPI remoteClient, AgentUpdatePacket agentData) + { + //if (m_isChildAgent) + //{ + // // Console.WriteLine("DEBUG: HandleAgentUpdate: child agent"); + // return; + //} - info.AddValue("m_animationSeqs", m_animationSeqs); - info.AddValue("m_updateflag", m_updateflag); - info.AddValue("m_movementflag", m_movementflag); - info.AddValue("m_forcesList", m_forcesList); - info.AddValue("m_updateCount", m_updateCount); - info.AddValue("m_requestedSitTargetID", m_requestedSitTargetID); + // Must check for standing up even when PhysicsActor is null, + // since sitting currently removes avatar from physical scene - // LLVector3 - info.AddValue("m_requestedSitOffset.X", m_requestedSitOffset.X); - info.AddValue("m_requestedSitOffset.Y", m_requestedSitOffset.Y); - info.AddValue("m_requestedSitOffset.Z", m_requestedSitOffset.Z); + m_perfMonMS = System.Environment.TickCount; - info.AddValue("m_sitAvatarHeight", m_sitAvatarHeight); - info.AddValue("m_godlevel", m_godlevel); - info.AddValue("m_setAlwaysRun", m_setAlwaysRun); + uint flags = agentData.AgentData.ControlFlags; + LLQuaternion bodyRotation = agentData.AgentData.BodyRotation; - // Quaternion - info.AddValue("m_bodyRot.w", m_bodyRot.w); - info.AddValue("m_bodyRot.x", m_bodyRot.x); - info.AddValue("m_bodyRot.y", m_bodyRot.y); - info.AddValue("m_bodyRot.z", m_bodyRot.z); + // Camera location in world. We'll need to raytrace + // from this location from time to time. + m_CameraCenter.x = agentData.AgentData.CameraCenter.X; + m_CameraCenter.y = agentData.AgentData.CameraCenter.Y; + m_CameraCenter.z = agentData.AgentData.CameraCenter.Z; - info.AddValue("IsRestrictedToRegion", IsRestrictedToRegion); - info.AddValue("m_newForce", m_newForce); - //info.AddValue("m_newAvatar", m_newAvatar); - info.AddValue("m_newCoarseLocations", m_newCoarseLocations); - info.AddValue("m_gotAllObjectsInScene", m_gotAllObjectsInScene); - info.AddValue("m_avHeight", m_avHeight); + // Use these three vectors to figure out what the agent is looking at + // Convert it to a Matrix and/or Quaternion + m_CameraAtAxis.x = agentData.AgentData.CameraAtAxis.X; + m_CameraAtAxis.y = agentData.AgentData.CameraAtAxis.Y; + m_CameraAtAxis.z = agentData.AgentData.CameraAtAxis.Z; - // info.AddValue("m_regionInfo", m_regionInfo); + m_CameraLeftAxis.x = agentData.AgentData.CameraLeftAxis.X; + m_CameraLeftAxis.y = agentData.AgentData.CameraLeftAxis.Y; + m_CameraLeftAxis.z = agentData.AgentData.CameraLeftAxis.Z; - info.AddValue("crossingFromRegion", crossingFromRegion); + m_CameraUpAxis.x = agentData.AgentData.CameraUpAxis.X; + m_CameraUpAxis.y = agentData.AgentData.CameraUpAxis.Y; + m_CameraUpAxis.z = agentData.AgentData.CameraUpAxis.Z; - List Dir_Vectors_work = new List(); + // The Agent's Draw distance setting + m_DrawDistance = agentData.AgentData.Far; - foreach (Vector3 v3 in Dir_Vectors) + if ((flags & (uint) AgentManager.ControlFlags.AGENT_CONTROL_STAND_UP) != 0) { - Dir_Vectors_work.Add(new[] {v3.x, v3.y, v3.z}); + StandUp(); } - info.AddValue("Dir_Vectors", Dir_Vectors_work); + if (PhysicsActor == null) + { + return; + } - // LLVector3 - info.AddValue("lastPhysPos.X", lastPhysPos.X); - info.AddValue("lastPhysPos.Y", lastPhysPos.Y); - info.AddValue("lastPhysPos.Z", lastPhysPos.Z); + if ((flags & (uint) AgentManager.ControlFlags.AGENT_CONTROL_SIT_ON_GROUND) != 0) + { + // TODO: This doesn't quite work yet -- probably a parent ID problem + // m_parentID = (what should this be?) + SetMovementAnimation(Animations.AnimsLLUUID["SIT_GROUND"]); + } + // In the future, these values might need to go global. + // Here's where you get them. - // Vector3 - info.AddValue("m_CameraCenter.X", m_CameraCenter.x); - info.AddValue("m_CameraCenter.Y", m_CameraCenter.y); - info.AddValue("m_CameraCenter.Z", m_CameraCenter.z); + // m_AgentControlFlags = flags; + // m_headrotation = agentData.AgentData.HeadRotation; + // m_state = agentData.AgentData.State; - // Vector3 - info.AddValue("m_CameraAtAxis.X", m_CameraAtAxis.x); - info.AddValue("m_CameraAtAxis.Y", m_CameraAtAxis.y); - info.AddValue("m_CameraAtAxis.Z", m_CameraAtAxis.z); + if (m_allowMovement) + { + int i = 0; + bool update_movementflag = false; + bool update_rotation = false; + bool DCFlagKeyPressed = false; + Vector3 agent_control_v3 = new Vector3(0, 0, 0); + Quaternion q = new Quaternion(bodyRotation.W, bodyRotation.X, bodyRotation.Y, bodyRotation.Z); + bool oldflying = PhysicsActor.Flying; - // Vector3 - info.AddValue("m_CameraLeftAxis.X", m_CameraLeftAxis.x); - info.AddValue("m_CameraLeftAxis.Y", m_CameraLeftAxis.y); - info.AddValue("m_CameraLeftAxis.Z", m_CameraLeftAxis.z); + PhysicsActor.Flying = ((flags & (uint) AgentManager.ControlFlags.AGENT_CONTROL_FLY) != 0); + if (PhysicsActor.Flying != oldflying) + { + update_movementflag = true; + } - // Vector3 - info.AddValue("m_CameraUpAxis.X", m_CameraUpAxis.x); - info.AddValue("m_CameraUpAxis.Y", m_CameraUpAxis.y); - info.AddValue("m_CameraUpAxis.Z", m_CameraUpAxis.z); + if (q != m_bodyRot) + { + m_bodyRot = q; + update_rotation = true; + } - info.AddValue("m_DrawDistance", m_DrawDistance); - info.AddValue("m_appearance", m_appearance); - info.AddValue("m_knownChildRegions", m_knownChildRegions); + if (m_parentID == 0) + { + foreach (Dir_ControlFlags DCF in Enum.GetValues(typeof (Dir_ControlFlags))) + { + if ((flags & (uint) DCF) != 0) + { + DCFlagKeyPressed = true; + try + { + agent_control_v3 += Dir_Vectors[i]; + } + catch (IndexOutOfRangeException) + { + // Why did I get this? + } + if ((m_movementflag & (uint) DCF) == 0) + { + m_movementflag += (byte) (uint) DCF; + update_movementflag = true; + } + } + else + { + if ((m_movementflag & (uint) DCF) != 0) + { + m_movementflag -= (byte) (uint) DCF; + update_movementflag = true; + } + } + i++; + } + } + // Cause the avatar to stop flying if it's colliding + // with something with the down arrow pressed. - // LLVector3 - info.AddValue("posLastSignificantMove.X", posLastSignificantMove.X); - info.AddValue("posLastSignificantMove.Y", posLastSignificantMove.Y); - info.AddValue("posLastSignificantMove.Z", posLastSignificantMove.Z); + // Skip if there's no physicsactor + if (m_physicsActor != null) + { + // Only do this if we're flying + if (m_physicsActor.Flying) + { + // Are the landing controls requirements filled? + bool controlland = (((flags & (uint) AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0) || + ((flags & (uint) AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG) != 0)); - //info.AddValue("m_partsUpdateQueue", m_partsUpdateQueue); + // Are the collision requirements fulfilled? + bool colliding = (m_physicsActor.IsColliding == true); - /* - Dictionary updateTimes_work = new Dictionary(); + - foreach ( LLUUID id in m_updateTimes.Keys) + if (m_physicsActor.Flying && colliding && controlland) + { + StopFlying(); + } + } + } + if ((update_movementflag) || (update_rotation && DCFlagKeyPressed)) + { + AddNewMovement(agent_control_v3, q); + UpdateMovementAnimations(update_movementflag); + } + } + + m_scene.EventManager.TriggerOnClientMovement(this); + + m_scene.AddAgentTime(System.Environment.TickCount - m_perfMonMS); + } + + /// + /// Perform the logic necessary to stand the client up. This method also executes + /// the stand animation. + /// + public void StandUp() + { + if (m_parentID != 0) { - updateTimes_work.Add(id.UUID, m_updateTimes[id]); + SceneObjectPart part = m_scene.GetSceneObjectPart(m_parentID); + if (part != null) + { + // Reset sit target. + if (part.GetAvatarOnSitTarget() == UUID) + part.SetAvatarOnSitTarget(LLUUID.Zero); + + m_parentPosition = part.GetWorldPosition(); + } + + if (m_physicsActor == null) + { + AddToPhysicalScene(); + } + + m_pos += m_parentPosition + new LLVector3(0.0f, 0.0f, 2.0f*m_sitAvatarHeight); + m_parentPosition = new LLVector3(); + + m_parentID = 0; + SendFullUpdateToAllClients(); + + if (m_physicsActor != null) + { + SetHeight(m_avHeight); + } } - info.AddValue("m_updateTimes", updateTimes_work); - */ + SetMovementAnimation(Animations.AnimsLLUUID["STAND"]); + } - info.AddValue("m_regionHandle", m_regionHandle); - info.AddValue("m_firstname", m_firstname); - info.AddValue("m_lastname", m_lastname); - info.AddValue("m_allowMovement", m_allowMovement); - //info.AddValue("m_physicsActor", m_physicsActor); - info.AddValue("m_parentPosition.X", m_parentPosition.X); - info.AddValue("m_parentPosition.Y", m_parentPosition.Y); - info.AddValue("m_parentPosition.Z", m_parentPosition.Z); - info.AddValue("m_isChildAgent", m_isChildAgent); - info.AddValue("m_parentID", m_parentID); + private void SendSitResponse(IClientAPI remoteClient, LLUUID targetID, LLVector3 offset) + { + AvatarSitResponsePacket avatarSitResponse = new AvatarSitResponsePacket(); -// for OpenSim_v0.5 - info.AddValue("currentParcelUUID", currentParcelUUID.UUID); + avatarSitResponse.SitObject.ID = targetID; - info.AddValue("lastKnownAllowedPosition.X", lastKnownAllowedPosition.x); - info.AddValue("lastKnownAllowedPosition.Y", lastKnownAllowedPosition.y); - info.AddValue("lastKnownAllowedPosition.Z", lastKnownAllowedPosition.z); + bool autopilot = true; + LLVector3 pos = new LLVector3(); + LLQuaternion sitOrientation = new LLQuaternion(0, 0, 0, 1); - info.AddValue("sentMessageAboutRestrictedParcelFlyingDown", sentMessageAboutRestrictedParcelFlyingDown); + SceneObjectPart part = m_scene.GetSceneObjectPart(targetID); + if (part != null) + { + // TODO: determine position to sit at based on scene geometry; don't trust offset from client + // see http://wiki.secondlife.com/wiki/User:Andrew_Linden/Office_Hours/2007_11_06 for details on how LL does it - info.AddValue("m_LastChildAgentUpdatePosition.X", m_LastChildAgentUpdatePosition.X); - info.AddValue("m_LastChildAgentUpdatePosition.Y", m_LastChildAgentUpdatePosition.Y); - info.AddValue("m_LastChildAgentUpdatePosition.Z", m_LastChildAgentUpdatePosition.Z); + // Is a sit target available? + Vector3 avSitOffSet = part.GetSitTargetPosition(); + Quaternion avSitOrientation = part.GetSitTargetOrientation(); + LLUUID avOnTargetAlready = part.GetAvatarOnSitTarget(); - info.AddValue("m_perfMonMS", m_perfMonMS); - info.AddValue("m_AgentControlFlags", m_AgentControlFlags); + bool SitTargetUnOccupied = (!(avOnTargetAlready != LLUUID.Zero)); + bool SitTargetisSet = + (!(avSitOffSet.x == 0 && avSitOffSet.y == 0 && avSitOffSet.z == 0 && avSitOrientation.w == 0 && + avSitOrientation.x == 0 && avSitOrientation.y == 0 && avSitOrientation.z == 1)); - info.AddValue("m_headrotation.W", m_headrotation.W); - info.AddValue("m_headrotation.X", m_headrotation.X); - info.AddValue("m_headrotation.Y", m_headrotation.Y); - info.AddValue("m_headrotation.Z", m_headrotation.Z); + if (SitTargetisSet && SitTargetUnOccupied) + { + part.SetAvatarOnSitTarget(UUID); + offset = new LLVector3(avSitOffSet.x, avSitOffSet.y, avSitOffSet.z); + sitOrientation = + new LLQuaternion(avSitOrientation.w, avSitOrientation.x, avSitOrientation.y, avSitOrientation.z); + autopilot = false; + } - info.AddValue("m_state", m_state); + pos = part.AbsolutePosition + offset; - List knownPrimUUID_work = new List(); + if (m_physicsActor != null) + { + // If we're not using the client autopilot, we're immediately warping the avatar to the location + // We can remove the physicsActor until they stand up. + m_sitAvatarHeight = m_physicsActor.Size.Z; - foreach (LLUUID id in m_knownPrimUUID) - { - knownPrimUUID_work.Add(id.UUID); + if (autopilot) + { + if (Util.GetDistanceTo(AbsolutePosition, pos) < 4.5) + { + autopilot = false; + + RemoveFromPhysicalScene(); + AbsolutePosition = pos + new LLVector3(0.0f, 0.0f, m_sitAvatarHeight); + } + } + else + { + RemoveFromPhysicalScene(); + } + } } - info.AddValue("m_knownPrimUUID", knownPrimUUID_work); - } + avatarSitResponse.SitTransform.AutoPilot = autopilot; + avatarSitResponse.SitTransform.SitPosition = offset; + avatarSitResponse.SitTransform.SitRotation = sitOrientation; - #endregion + remoteClient.OutPacket(avatarSitResponse, ThrottleOutPacketType.Task); - public event SignificantClientMovement OnSignificantClientMovement; + // This calls HandleAgentSit twice, once from here, and the client calls + // HandleAgentSit itself after it gets to the location + // It doesn't get to the location until we've moved them there though + // which happens in HandleAgentSit :P + if (!autopilot) + HandleAgentSit(remoteClient, UUID); + } - /// - /// Add the part to the queue of parts for which we need to send an update to the client - /// - /// - public void QueuePartForUpdate(SceneObjectPart part) + public void HandleAgentRequestSit(IClientAPI remoteClient, LLUUID agentID, LLUUID targetID, LLVector3 offset) { - //if (InterestList.Contains(part.ParentGroup)) - //{ - lock (m_partsUpdateQueue) + if (m_parentID != 0) { - m_partsUpdateQueue.Enqueue(part); + StandUp(); } - // } - } - public uint GenerateClientFlags(LLUUID ObjectID) - { - return m_scene.PermissionsMngr.GenerateClientFlags(m_uuid, ObjectID); - } - - /// - /// Send updates to the client about prims which have been placed on the update queue. We don't - /// necessarily send updates for all the parts on the queue, e.g. if an updates with a more recent - /// timestamp has already been sent. - /// - public void SendPrimUpdates() - { - // if (m_scene.QuadTree.GetNodeID(this.AbsolutePosition.X, this.AbsolutePosition.Y) != m_currentQuadNode) - //{ - // this.UpdateQuadTreeNode(); - //this.RefreshQuadObject(); - //} - m_perfMonMS = System.Environment.TickCount; + SceneObjectPart part = m_scene.GetSceneObjectPart(targetID); - if (!m_gotAllObjectsInScene) + if (part != null) { - if (!m_isChildAgent || m_scene.m_seeIntoRegionFromNeighbor) - { - m_scene.SendAllSceneObjectsToClient(this); - m_gotAllObjectsInScene = true; - } + m_requestedSitTargetID = part.LocalId; + m_requestedSitOffset = offset; } - - if (m_partsUpdateQueue.Count > 0) + else { - bool runUpdate = true; - int updateCount = 0; - while (runUpdate) - { - SceneObjectPart part = m_partsUpdateQueue.Dequeue(); - if (m_updateTimes.ContainsKey(part.UUID)) - { - ScenePartUpdate update = m_updateTimes[part.UUID]; - - // We deal with the possibility that two updates occur at the same unix time - // at the update point itself. - if (update.LastFullUpdateTime < part.TimeStampFull) - { -// m_log.DebugFormat( -// "[SCENE PRESENCE]: Fully updating prim {0}, {1} - part timestamp {2}", -// part.Name, part.UUID, part.TimeStampFull); + m_log.Warn("Sit requested on unknown object: " + targetID.ToString()); + } + SendSitResponse(remoteClient, targetID, offset); + } - part.SendFullUpdate(ControllingClient, GenerateClientFlags(part.UUID)); + public void HandleAgentSit(IClientAPI remoteClient, LLUUID agentID) + { + SceneObjectPart part = m_scene.GetSceneObjectPart(m_requestedSitTargetID); - // We'll update to the part's timestamp rather than the current time to - // avoid the race condition whereby the next tick occurs while we are - // doing this update. If this happened, then subsequent updates which occurred - // on the same tick or the next tick of the last update would be ignored. - update.LastFullUpdateTime = part.TimeStampFull; + if (part != null) + { + if (part.GetAvatarOnSitTarget() == UUID) + { + Vector3 sitTargetPos = part.GetSitTargetPosition(); + Quaternion sitTargetOrient = part.GetSitTargetOrientation(); - updateCount++; - } - else if (update.LastTerseUpdateTime <= part.TimeStampTerse) - { -// m_log.DebugFormat( -// "[SCENE PRESENCE]: Tersely updating prim {0}, {1} - part timestamp {2}", -// part.Name, part.UUID, part.TimeStampTerse); + //Quaternion vq = new Quaternion(sitTargetPos.x, sitTargetPos.y+0.2f, sitTargetPos.z+0.2f, 0); + //Quaternion nq = new Quaternion(sitTargetOrient.w, -sitTargetOrient.x, -sitTargetOrient.y, -sitTargetOrient.z); - part.SendTerseUpdate(ControllingClient); + //Quaternion result = (sitTargetOrient * vq) * nq; - update.LastTerseUpdateTime = part.TimeStampTerse; - updateCount++; - } - } - else - { - //never been sent to client before so do full update - part.SendFullUpdate(ControllingClient, GenerateClientFlags(part.UUID)); - ScenePartUpdate update = new ScenePartUpdate(); - update.FullID = part.UUID; - update.LastFullUpdateTime = part.TimeStampFull; - m_updateTimes.Add(part.UUID, update); - updateCount++; - } + m_pos = new LLVector3(sitTargetPos.x, sitTargetPos.y, sitTargetPos.z); + m_bodyRot = sitTargetOrient; + //Rotation = sitTargetOrient; + m_parentPosition = part.AbsolutePosition; - if (m_partsUpdateQueue.Count < 1 || updateCount > 60) - { - runUpdate = false; - } + //SendTerseUpdateToAllClients(); + } + else + { + m_pos -= part.AbsolutePosition; + m_parentPosition = part.AbsolutePosition; } } - m_scene.AddAgentTime(System.Environment.TickCount - m_perfMonMS); - } + m_parentID = m_requestedSitTargetID; - public void forceAvatarMovement(Vector3 position, Quaternion rotation) - { - AddNewMovement(position, rotation); + Velocity = new LLVector3(0, 0, 0); + RemoveFromPhysicalScene(); + + SetMovementAnimation(Animations.AnimsLLUUID["SIT"]); + SendFullUpdateToAllClients(); + // This may seem stupid, but Our Full updates don't send avatar rotation :P + // So we're also sending a terse update (which has avatar rotation) + SendTerseUpdateToAllClients(); } /// - /// This allows the Sim owner the abiility to kick users from their sim currently. - /// It tells the client that the agent has permission to do so. + /// Event handler for the 'Always run' setting on the client + /// Tells the physics plugin to increase speed of movement. /// - public void GrantGodlikePowers(LLUUID agentID, LLUUID sessionID, LLUUID token, bool godStatus) + public void HandleSetAlwaysRun(IClientAPI remoteClient, bool SetAlwaysRun) { - GrantGodlikePowersPacket respondPacket = new GrantGodlikePowersPacket(); - GrantGodlikePowersPacket.GrantDataBlock gdb = new GrantGodlikePowersPacket.GrantDataBlock(); - GrantGodlikePowersPacket.AgentDataBlock adb = new GrantGodlikePowersPacket.AgentDataBlock(); - - adb.AgentID = agentID; - adb.SessionID = sessionID; // More security - - if (godStatus) - { - gdb.GodLevel = 250; - m_godlevel = 250; - } - else + m_setAlwaysRun = SetAlwaysRun; + if (PhysicsActor != null) { - gdb.GodLevel = 0; - m_godlevel = 0; + PhysicsActor.SetAlwaysRun = SetAlwaysRun; } - - gdb.Token = token; - //respondPacket.AgentData = (GrantGodlikePowersPacket.AgentDataBlock)ablock; - respondPacket.GrantData = gdb; - respondPacket.AgentData = adb; - ControllingClient.OutPacket(respondPacket, ThrottleOutPacketType.Task); } - /// - /// This updates important decision making data about a child agent - /// The main purpose is to figure out what objects to send to a child agent that's in a neighboring region - /// - public void ChildAgentDataUpdate(ChildAgentDataUpdate cAgentData, uint tRegionX, uint tRegionY, uint rRegionX, uint rRegionY) + public void AddAnimation(LLUUID animID) { - // - int shiftx = ((int) rRegionX - (int) tRegionX) * (int) Constants.RegionSize; - int shifty = ((int) rRegionY - (int) tRegionY) * (int) Constants.RegionSize; - - m_DrawDistance = cAgentData.drawdistance; - m_pos = new LLVector3(cAgentData.Position.x + shiftx, cAgentData.Position.y + shifty, cAgentData.Position.z); - - // It's hard to say here.. We can't really tell where the camera position is unless it's in world cordinates from the sending region - m_CameraCenter = - new Vector3(cAgentData.cameraPosition.x, cAgentData.cameraPosition.y, cAgentData.cameraPosition.z); - - - m_godlevel = cAgentData.godlevel; - SetHeight(cAgentData.AVHeight); - - ControllingClient.SetChildAgentThrottle(cAgentData.throttles); + if(m_isChildAgent) + return; + // Don't let this animation become the movement animation + if(m_animations.Count < 1) + SetMovementAnimation(Animations.AnimsLLUUID["STAND"]); - // Sends out the objects in the user's draw distance if m_sendTasksToChild is true. - if (m_scene.m_seeIntoRegionFromNeighbor) - m_scene.SendAllSceneObjectsToClient(this); - //cAgentData.AVHeight; - //cAgentData.regionHandle; - //m_velocity = cAgentData.Velocity; + if (!m_animations.Contains(animID)) + { + m_animations.Add(animID); + m_animationSeqs.Add(m_controllingClient.NextAnimationSequenceNumber); + SendAnimPack(); + } } - /// - /// Handles part of the PID controller function for moving an avatar. - /// - public override void UpdateMovement() + public void RemoveAnimation(LLUUID animID) { - m_newForce = false; - lock (m_forcesList) + if(m_isChildAgent) + return; + + if (m_animations.Contains(animID)) { - if (m_forcesList.Count > 0) + if (m_animations[0] == animID) { - for (int i = 0; i < m_forcesList.Count; i++) - { - NewForce force = m_forcesList[i]; + SetMovementAnimation(Animations.AnimsLLUUID["STAND"]); + } + else + { + // What a HACK!! Anim list really needs to be an object! + int idx; - m_updateflag = true; - try - { - movementvector.X = force.X; - movementvector.Y = force.Y; - movementvector.Z = force.Z; - Velocity = movementvector; - } - catch (NullReferenceException) + for(idx=0;idx < m_animations.Count;idx++) + { + if(m_animations[idx] == animID) { - // Under extreme load, this returns a NullReference Exception that we can ignore. - // Ignoring this causes no movement to be sent to the physics engine... - // which when the scene is moving at 1 frame every 10 seconds, it doesn't really matter! + int seq=m_animationSeqs[idx]; + + m_animations.Remove(animID); + m_animationSeqs.Remove(seq); + SendAnimPack(); + break; } - m_newForce = true; - } - for (int i = 0; i < m_forcesList.Count; i++) - { - m_forcesList.RemoveAt(0); } } } } - public override void SetText(string text, Vector3 color, double alpha) + public void HandleStartAnim(IClientAPI remoteClient, LLUUID animID) { - throw new Exception("Can't set Text on avatar."); + AddAnimation(animID); + } + + public void HandleStopAnim(IClientAPI remoteClient, LLUUID animID) + { + RemoveAnimation(animID); } /// - /// Adds a physical representation of the avatar to the Physics plugin + /// The movement animation is the first element of the animation list, + /// reserved for "main" animations that are mutually exclusive, + /// like flying and sitting, for example. /// - public void AddToPhysicalScene() + protected void SetMovementAnimation(LLUUID anim) { - PhysicsScene scene = m_scene.PhysicsScene; - - PhysicsVector pVec = - new PhysicsVector(AbsolutePosition.X, AbsolutePosition.Y, - AbsolutePosition.Z); - if (m_avHeight == 127.0f) + if(m_animations.Count < 1) { - m_physicsActor = scene.AddAvatar(Firstname + "." + Lastname, pVec, new PhysicsVector(0, 0, 1.56f)); + m_animations.Add(Animations.AnimsLLUUID["STAND"]); + m_animationSeqs.Add(1); + + SendAnimPack(); } else { - m_physicsActor = scene.AddAvatar(Firstname + "." + Lastname, pVec, new PhysicsVector(0, 0, m_avHeight)); - } - //m_physicsActor.OnRequestTerseUpdate += SendTerseUpdateToAllClients; - m_physicsActor.OnCollisionUpdate += PhysicsCollisionUpdate; - m_physicsActor.LocalID = LocalId; - } - - // Event called by the physics plugin to tell the avatar about a collision. - private void PhysicsCollisionUpdate(EventArgs e) - { - bool isUserMoving = Velocity.X > 0 || Velocity.Y > 0; - UpdateMovementAnimations(isUserMoving); + try + { + if (m_animations[0] != anim) + { + m_animations[0] = anim; + m_animationSeqs[0] = m_controllingClient.NextAnimationSequenceNumber; + } + SendAnimPack(); + } + catch + { + m_log.Warn("[AVATAR]: SetMovementAnimation for avatar failed. Attempting recovery..."); + m_animations[0] = anim; + m_animationSeqs[0] = m_controllingClient.NextAnimationSequenceNumber; + SendAnimPack(); + } + } } - internal void Close() + /// + /// This method handles agent movement related animations + /// + protected void UpdateMovementAnimations(bool update_movementflag) { - lock (m_attachments) + + + if (update_movementflag) { - foreach (SceneObjectGroup grp in m_attachments) + // Are we moving? + if (m_movementflag != 0) { - // ControllingClient may be null at this point! - m_scene.m_innerScene.DetachSingleAttachmentToInv(grp.GetFromAssetID(), ControllingClient); + // We are moving + + if (m_physicsActor.Flying) + { + // We are flying + SetMovementAnimation(Animations.AnimsLLUUID["FLY"]); + } + else if (((m_movementflag & (uint) AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0) && + PhysicsActor.IsColliding) + { + // Client is pressing the page down button and moving and is colliding with something + SetMovementAnimation(Animations.AnimsLLUUID["CROUCHWALK"]); + } + else if (!PhysicsActor.IsColliding && m_physicsActor.Velocity.Z < -6) + { + // Client is moving and falling at a velocity greater then 6 meters per unit + SetMovementAnimation(Animations.AnimsLLUUID["FALLDOWN"]); + } + else if (!PhysicsActor.IsColliding && Velocity.Z > 0 && + (m_movementflag & (uint) AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) != 0) + { + // Client is moving, and colliding and pressing the page up button but isn't flying + try + { + SetMovementAnimation(Animations.AnimsLLUUID["JUMP"]); + } + catch (KeyNotFoundException) + { } + } + else if (m_setAlwaysRun) + { + // We are running + try + { + SetMovementAnimation(Animations.AnimsLLUUID["RUN"]); + } + catch (KeyNotFoundException) + { } + } + else + { + // We're moving, but we're not doing anything else.. so play the stand animation + try + { + SetMovementAnimation(Animations.AnimsLLUUID["WALK"]); + } + catch (KeyNotFoundException) + { } + + } + } + else + { + // Not moving + + if (((m_movementflag & (uint) AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0) && + PhysicsActor.IsColliding) + { + // Client pressing the page down button + SetMovementAnimation(Animations.AnimsLLUUID["CROUCH"]); + } + else if (!PhysicsActor.IsColliding && m_physicsActor.Velocity.Z < -6 && !m_physicsActor.Flying) + { + // Not colliding and not flying, and we're falling at high speed + SetMovementAnimation(Animations.AnimsLLUUID["FALLDOWN"]); + } + else if (!PhysicsActor.IsColliding && Velocity.Z > 0 && !m_physicsActor.Flying && + (m_movementflag & (uint) AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) != 0) + { + // This is the standing jump + SetMovementAnimation(Animations.AnimsLLUUID["JUMP"]); + } + else if (m_physicsActor.Flying) + { + // We're flying but not moving + SetMovementAnimation(Animations.AnimsLLUUID["HOVER"]); + } + else + { + // We're not moving.. and we're not doing anything.. so play the stand animation + try + { + + SetMovementAnimation(Animations.AnimsLLUUID["STAND"]); + } + catch (KeyNotFoundException) + { } + } } - m_attachments.Clear(); - } - lock (m_knownPrimUUID) - { - m_knownPrimUUID.Clear(); } - lock (m_knownChildRegions) + + } + + /// + /// Adds a new movement + /// + protected void AddNewMovement(Vector3 vec, Quaternion rotation) + { + if (m_isChildAgent) { - m_knownChildRegions.Clear(); + Console.WriteLine("DEBUG: AddNewMovement: child agent"); + return; } - lock (m_updateTimes) + + m_perfMonMS = System.Environment.TickCount; + + m_rotation = rotation; + NewForce newVelocity = new NewForce(); + Vector3 direc = rotation*vec; + direc.Normalize(); + + direc *= 0.03f*128f; + if (m_physicsActor.Flying) { - m_updateTimes.Clear(); + direc *= 4; + //bool controlland = (((m_AgentControlFlags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0) || ((m_AgentControlFlags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG) != 0)); + //bool colliding = (m_physicsActor.IsColliding==true); + //if (controlland) + // m_log.Info("[AGENT]: landCommand"); + //if (colliding ) + // m_log.Info("[AGENT]: colliding"); + //if (m_physicsActor.Flying && colliding && controlland) + //{ + // StopFlying(); + // m_log.Info("[AGENT]: Stop FLying"); + //} } - lock (m_partsUpdateQueue) + else { - m_partsUpdateQueue.Clear(); + if (!m_physicsActor.Flying && m_physicsActor.IsColliding) + { + //direc.z *= 40; + if (direc.z > 2.0f) + { + direc.z *= 3; + //System.Console.WriteLine("Jump"); + // PreJump and jump happen too quickly. Many times prejump gets ignored. + try + { + SetMovementAnimation(Animations.AnimsLLUUID["PREJUMP"]); + SetMovementAnimation(Animations.AnimsLLUUID["JUMP"]); + } + catch (KeyNotFoundException) + { } + } + } } - RemoveFromPhysicalScene(); - GC.Collect(); + newVelocity.X = direc.x; + newVelocity.Y = direc.y; + newVelocity.Z = direc.z; + m_forcesList.Add(newVelocity); + + m_scene.AddAgentTime(System.Environment.TickCount - m_perfMonMS); } - public void AddAttachment(SceneObjectGroup gobj) + #endregion + + #region Overridden Methods + + /// + /// + /// + public override void Update() { - lock (m_attachments) + SendPrimUpdates(); + + if (m_newCoarseLocations) { - m_attachments.Add(gobj); + SendCoarseLocations(); + m_newCoarseLocations = false; } - } - public void RemoveAttachment(SceneObjectGroup gobj) - { - lock (m_attachments) + if (m_isChildAgent == false) { - if (m_attachments.Contains(gobj)) + if (m_newForce) // user movement 'forces' (ie commands to move) { - m_attachments.Remove(gobj); + SendTerseUpdateToAllClients(); + m_updateCount = 0; } - } - } - - public void CrossAttachmentsIntoNewRegion(ulong regionHandle) - { - lock (m_attachments) - { - foreach (SceneObjectGroup gobj in m_attachments) + else if (m_movementflag != 0) // scripted movement (?) { - // If the prim group is null then something must have happened to it! - if (gobj != null) + m_updateCount++; + if (m_updateCount > 3) { - // Set the parent localID to 0 so it transfers over properly. - gobj.RootPart.SetParentLocalId(0); - gobj.RootPart.m_IsAttachment = false; - gobj.AbsolutePosition = gobj.RootPart.m_attachedPos; - gobj.RootPart.LastOwnerID = gobj.GetFromAssetID(); - m_scene.CrossPrimGroupIntoNewRegion(regionHandle, gobj); + SendTerseUpdateToAllClients(); + m_updateCount = 0; } } - m_attachments.Clear(); - } - } + else if ((Util.GetDistanceTo(lastPhysPos, AbsolutePosition) > 0.02) || (Util.GetDistanceTo(m_lastVelocity, m_velocity) > 0.02)) // physics-related movement + { - public void initializeScenePresence(IClientAPI client, RegionInfo region, Scene scene) - { - m_controllingClient = client; - m_regionInfo = region; - m_scene = scene; - RegisterToEvents(); + + // Send Terse Update to all clients updates lastPhysPos and m_lastVelocity + // doing the above assures us that we know what we sent the clients last + SendTerseUpdateToAllClients(); + m_updateCount = 0; + - /* - AbsolutePosition = client.StartPos; + + } - Animations = new AvatarAnimations(); - Animations.LoadAnims(); + // followed suggestion from mic bowman. reversed the two lines below. + CheckForBorderCrossing(); + CheckForSignificantMovement(); // sends update to the modules. + + } + } - m_animations = new List(); - m_animations.Add(Animations.AnimsLLUUID["STAND"]); - m_animationSeqs.Add(m_controllingClient.NextAnimationSequenceNumber); + #endregion - SetDirectionVectors(); - */ - } + #region Update Client(s) - #region Status Methods + /// + /// Sends a location update to the client connected to this scenePresence + /// + /// + public void SendTerseUpdateToClient(IClientAPI remoteClient) + { + m_perfMonMS = System.Environment.TickCount; + + LLVector3 pos = m_pos; + LLVector3 vel = Velocity; + LLQuaternion rot = new LLQuaternion(m_bodyRot.x, m_bodyRot.y, m_bodyRot.z, m_bodyRot.w); + remoteClient.SendAvatarTerseUpdate(m_regionHandle, (ushort)(m_scene.TimeDilation * (float)ushort.MaxValue), LocalId, new LLVector3(pos.X, pos.Y, pos.Z), + new LLVector3(vel.X, vel.Y, vel.Z), rot); + + m_scene.AddAgentTime(System.Environment.TickCount - m_perfMonMS); + m_scene.AddAgentUpdates(1); + } /// - /// This turns a child agent, into a root agent - /// This is called when an agent teleports into a region, or if an - /// agent crosses into this region from a neighbor over the border + /// Send a location/velocity/accelleration update to all agents in scene /// - public void MakeRootAgent(LLVector3 pos, bool isFlying) + public void SendTerseUpdateToAllClients() { -// m_log.DebugFormat( -// "[SCENEPRESENCE]: Upgrading child agent {0}, {1} to a root agent in {2}", -// Name, UUID, m_scene.RegionInfo.RegionName); + m_perfMonMS = System.Environment.TickCount; - m_isChildAgent = false; + m_scene.Broadcast(SendTerseUpdateToClient); - AbsolutePosition = pos; + m_lastVelocity = m_velocity; + lastPhysPos = AbsolutePosition; - AddToPhysicalScene(); - m_physicsActor.Flying = isFlying; - SendAnimPack(); + m_scene.AddAgentTime(System.Environment.TickCount - m_perfMonMS); + + } - m_scene.SwapRootAgentCount(false); - m_scene.CommsManager.UserProfileCacheService.RequestInventoryForUser(m_uuid); - m_scene.AddCapsHandler(m_uuid); - //if (!m_gotAllObjectsInScene) - //{ - m_scene.SendAllSceneObjectsToClient(this); - m_scene.LandChannel.sendLandUpdate(this, true); + public void SendCoarseLocations() + { + m_perfMonMS = System.Environment.TickCount; - //m_gotAllObjectsInScene = true; - //} + List CoarseLocations = new List(); + List avatars = m_scene.GetAvatars(); + for (int i = 0; i < avatars.Count; i++) + { + if (avatars[i] != this) + { + CoarseLocations.Add(avatars[i].m_pos); + } + } + + m_controllingClient.SendCoarseLocationUpdate(CoarseLocations); + + m_scene.AddAgentTime(System.Environment.TickCount - m_perfMonMS); + } + + public void CoarseLocationChange() + { + m_newCoarseLocations = true; } /// - /// This turns a root agent into a child agent - /// when an agent departs this region for a neighbor, this gets called. - /// - /// It doesn't get called for a teleport. Reason being, an agent that - /// teleports out may not be anywhere near this region + /// Tell other client about this avatar (The client previously didn't know or had outdated details about this avatar) /// - public void MakeChildAgent() + /// + public void SendFullUpdateToOtherClient(ScenePresence remoteAvatar) { - if (m_animations.Count > 0) - { - LLUUID movement = m_animations[0]; + remoteAvatar.m_controllingClient.SendAvatarData(m_regionInfo.RegionHandle, m_firstname, m_lastname, m_uuid, + LocalId, m_pos, m_appearance.TextureEntry.ToBytes(), + m_parentID); + m_scene.AddAgentUpdates(1); + } - m_animations.Clear(); - m_animationSeqs.Clear(); + /// + /// Tell *ALL* agents about this agent + /// + public void SendFullUpdateToAllClients() + { + m_perfMonMS = System.Environment.TickCount; - SetMovementAnimation(movement); + List avatars = m_scene.GetScenePresences(); + foreach (ScenePresence avatar in avatars) + { + SendFullUpdateToOtherClient(avatar); + if (avatar.LocalId != LocalId) + { + if (!avatar.m_isChildAgent || m_scene.m_seeIntoRegionFromNeighbor) + { + avatar.SendFullUpdateToOtherClient(this); + avatar.SendAppearanceToOtherAgent(this); + } + } } -// m_log.DebugFormat( -// "[SCENEPRESENCE]: Downgrading child agent {0}, {1} to a root agent in {2}", -// Name, UUID, m_scene.RegionInfo.RegionName); - - Velocity = new LLVector3(0, 0, 0); - m_isChildAgent = true; - m_scene.SwapRootAgentCount(true); - RemoveFromPhysicalScene(); - m_scene.EventManager.TriggerOnMakeChildAgent(this); - //this.Pos = new LLVector3(128, 128, 70); + m_scene.AddAgentUpdates(avatars.Count); + m_scene.AddAgentTime(System.Environment.TickCount - m_perfMonMS); } /// - /// Removes physics plugin scene representation of this agent if it exists. + /// /// - private void RemoveFromPhysicalScene() + public void SendInitialData() { - if (PhysicsActor != null) + m_controllingClient.SendAvatarData(m_regionInfo.RegionHandle, m_firstname, m_lastname, m_uuid, LocalId, + m_pos, m_appearance.TextureEntry.ToBytes(), m_parentID); + if (!m_isChildAgent) { - m_scene.PhysicsScene.RemoveAvatar(PhysicsActor); - m_physicsActor.OnRequestTerseUpdate -= SendTerseUpdateToAllClients; - m_physicsActor.OnCollisionUpdate -= PhysicsCollisionUpdate; - PhysicsActor = null; + m_scene.InformClientOfNeighbours(this); } + + SendFullUpdateToAllClients(); + SendAppearanceToAllOtherAgents(); } /// /// /// - /// - public void Teleport(LLVector3 pos) + /// + public void SendOwnAppearance() { - RemoveFromPhysicalScene(); - Velocity = new LLVector3(0, 0, 0); - AbsolutePosition = pos; - AddToPhysicalScene(); - SendTerseUpdateToAllClients(); + m_appearance.SendOwnWearables(ControllingClient); + + // TODO: remove this once the SunModule is slightly more tested + // m_controllingClient.SendViewerTime(m_scene.TimePhase); } /// /// /// - public void StopMovement() + public void SendAppearanceToAllOtherAgents() { + m_perfMonMS=System.Environment.TickCount; + + m_scene.ForEachScenePresence(delegate(ScenePresence scenePresence) + { + if (scenePresence.UUID != UUID) + { + m_appearance.SendAppearanceToOtherAgent(scenePresence); + } + }); + m_scene.AddAgentTime(System.Environment.TickCount - m_perfMonMS); } - public void StopFlying() + public void SendAppearanceToOtherAgent(ScenePresence avatar) { - // It turns out to get the agent to stop flying, you have to feed it stop flying velocities - // and send a full object update. - // There's no message to send the client to tell it to stop flying + m_appearance.SendAppearanceToOtherAgent(avatar); + } - // Add 1/6 the avatar's height to it's position so it doesn't shoot into the air - // when the avatar stands up + public void SetAppearance(byte[] texture, AgentSetAppearancePacket.VisualParamBlock[] visualParam) + { + m_appearance.SetAppearance(texture, visualParam); + SetHeight(m_appearance.AvatarHeight); - if (m_avHeight != 127.0f) - { - AbsolutePosition = AbsolutePosition + new LLVector3(0, 0, (m_avHeight / 6)); - } - else - { - AbsolutePosition = AbsolutePosition + new LLVector3(0, 0, (1.56f / 6)); - } - SetMovementAnimation(Animations.AnimsLLUUID["LAND"]); - SendFullUpdateToAllClients(); + SendAppearanceToAllOtherAgents(); } - public void AddNeighbourRegion(ulong regionHandle) + public void SetWearable(int wearableId, AvatarWearable wearable) { - if (!m_knownChildRegions.Contains(regionHandle)) - { - m_knownChildRegions.Add(regionHandle); - } + m_appearance.SetWearable(ControllingClient, wearableId, wearable); } - public void RemoveNeighbourRegion(ulong regionHandle) + /// + /// + /// + /// + /// + public void SendAnimPack(LLUUID[] animations, int[] seqs) { - if (!m_knownChildRegions.Contains(regionHandle)) - { - m_knownChildRegions.Remove(regionHandle); - } + if(m_isChildAgent) + return; + + m_scene.Broadcast( + delegate(IClientAPI client) { client.SendAnimations(animations, seqs, m_controllingClient.AgentId); }); } - public List GetKnownRegionList() + /// + /// + /// + public void SendAnimPack() { - return m_knownChildRegions; + SendAnimPack(m_animations.ToArray(), m_animationSeqs.ToArray()); } #endregion - #region Event Handlers + #region Significant Movement Method /// - /// Sets avatar height in the phyiscs plugin + /// This checks for a significant movement and sends a courselocationchange update /// - internal void SetHeight(float height) + protected void CheckForSignificantMovement() { - m_avHeight = height; - if (PhysicsActor != null) + if (Util.GetDistanceTo(AbsolutePosition, posLastSignificantMove) > 0.5) { - PhysicsVector SetSize = new PhysicsVector(0.45f, 0.6f, m_avHeight); - PhysicsActor.Size = SetSize; + posLastSignificantMove = AbsolutePosition; + handlerSignificantClientMovement = OnSignificantClientMovement; + if (handlerSignificantClientMovement != null) + { + handlerSignificantClientMovement(m_controllingClient); + m_scene.NotifyMyCoarseLocationChange(); + } } - } - /// - /// Complete Avatar's movement into the region - /// - public void CompleteMovement() - { - LLVector3 look = Velocity; - if ((look.X == 0) && (look.Y == 0) && (look.Z == 0)) + // Minimum Draw distance is 64 meters, the Radius of the draw distance sphere is 32m + if (Util.GetDistanceTo(AbsolutePosition,m_LastChildAgentUpdatePosition) > 32) { - look = new LLVector3(0.99f, 0.042f, 0); + ChildAgentDataUpdate cadu = new ChildAgentDataUpdate(); + cadu.ActiveGroupID=LLUUID.Zero.UUID; + cadu.AgentID = UUID.UUID; + cadu.alwaysrun = m_setAlwaysRun; + cadu.AVHeight = m_avHeight; + LLVector3 tempCameraCenter = new LLVector3(m_CameraCenter.x, m_CameraCenter.y, m_CameraCenter.z); + cadu.cameraPosition = new sLLVector3(tempCameraCenter); + cadu.drawdistance = m_DrawDistance; + cadu.godlevel = m_godlevel; + cadu.GroupAccess = 0; + cadu.Position = new sLLVector3(AbsolutePosition); + cadu.regionHandle = m_scene.RegionInfo.RegionHandle; + cadu.throttles = ControllingClient.GetThrottlesPacked(1f); + cadu.Velocity = new sLLVector3(Velocity); + m_scene.SendOutChildAgentUpdates(cadu,this); + m_LastChildAgentUpdatePosition.X = AbsolutePosition.X; + m_LastChildAgentUpdatePosition.Y = AbsolutePosition.Y; + m_LastChildAgentUpdatePosition.Z = AbsolutePosition.Z; } + } - m_controllingClient.MoveAgentIntoRegion(m_regionInfo, AbsolutePosition, look); + #endregion - if (m_isChildAgent) - { - m_isChildAgent = false; - - //this.m_scene.SendAllSceneObjectsToClient(this.ControllingClient); - MakeRootAgent(AbsolutePosition, false); - } - } + #region Border Crossing Methods /// - /// This is the event handler for client movement. If a client is moving, this event is triggering. + /// Checks to see if the avatar is in range of a border and calls CrossToNewRegion /// - public void HandleAgentUpdate(IClientAPI remoteClient, AgentUpdatePacket agentData) + protected void CheckForBorderCrossing() { - //if (m_isChildAgent) - //{ - // // Console.WriteLine("DEBUG: HandleAgentUpdate: child agent"); - // return; - //} - - // Must check for standing up even when PhysicsActor is null, - // since sitting currently removes avatar from physical scene - - m_perfMonMS = System.Environment.TickCount; + LLVector3 pos2 = AbsolutePosition; + LLVector3 vel = Velocity; - uint flags = agentData.AgentData.ControlFlags; - LLQuaternion bodyRotation = agentData.AgentData.BodyRotation; + float timeStep = 0.1f; + pos2.X = pos2.X + (vel.X*timeStep); + pos2.Y = pos2.Y + (vel.Y*timeStep); + pos2.Z = pos2.Z + (vel.Z*timeStep); - // Camera location in world. We'll need to raytrace - // from this location from time to time. - m_CameraCenter.x = agentData.AgentData.CameraCenter.X; - m_CameraCenter.y = agentData.AgentData.CameraCenter.Y; - m_CameraCenter.z = agentData.AgentData.CameraCenter.Z; + if ((pos2.X < 0) || (pos2.X > Constants.RegionSize)) + { + CrossToNewRegion(); + } - // Use these three vectors to figure out what the agent is looking at - // Convert it to a Matrix and/or Quaternion - m_CameraAtAxis.x = agentData.AgentData.CameraAtAxis.X; - m_CameraAtAxis.y = agentData.AgentData.CameraAtAxis.Y; - m_CameraAtAxis.z = agentData.AgentData.CameraAtAxis.Z; + if ((pos2.Y < 0) || (pos2.Y > Constants.RegionSize)) + { + CrossToNewRegion(); + } + } - m_CameraLeftAxis.x = agentData.AgentData.CameraLeftAxis.X; - m_CameraLeftAxis.y = agentData.AgentData.CameraLeftAxis.Y; - m_CameraLeftAxis.z = agentData.AgentData.CameraLeftAxis.Z; + /// + /// Moves the agent outside the region bounds + /// Tells neighbor region that we're crossing to it + /// If the neighbor accepts, remove the agent's viewable avatar from this scene + /// set them to a child agent. + /// + protected void CrossToNewRegion() + { + LLVector3 pos = AbsolutePosition; + LLVector3 newpos = new LLVector3(pos.X, pos.Y, pos.Z); + uint neighbourx = m_regionInfo.RegionLocX; + uint neighboury = m_regionInfo.RegionLocY; - m_CameraUpAxis.x = agentData.AgentData.CameraUpAxis.X; - m_CameraUpAxis.y = agentData.AgentData.CameraUpAxis.Y; - m_CameraUpAxis.z = agentData.AgentData.CameraUpAxis.Z; + // distance to edge that will trigger crossing + const float boundaryDistance = 1.7f; - // The Agent's Draw distance setting - m_DrawDistance = agentData.AgentData.Far; + // distance into new region to place avatar + const float enterDistance = 0.1f; - if ((flags & (uint) AgentManager.ControlFlags.AGENT_CONTROL_STAND_UP) != 0) + if (pos.X < boundaryDistance) { - StandUp(); + neighbourx--; + newpos.X = Constants.RegionSize - enterDistance; } - - if (PhysicsActor == null) + else if (pos.X > Constants.RegionSize - boundaryDistance) { - return; + neighbourx++; + newpos.X = enterDistance; } - if ((flags & (uint) AgentManager.ControlFlags.AGENT_CONTROL_SIT_ON_GROUND) != 0) + if (pos.Y < boundaryDistance) { - // TODO: This doesn't quite work yet -- probably a parent ID problem - // m_parentID = (what should this be?) - SetMovementAnimation(Animations.AnimsLLUUID["SIT_GROUND"]); + neighboury--; + newpos.Y = Constants.RegionSize - enterDistance; } - // In the future, these values might need to go global. - // Here's where you get them. - - // m_AgentControlFlags = flags; - // m_headrotation = agentData.AgentData.HeadRotation; - // m_state = agentData.AgentData.State; - - if (m_allowMovement) + else if (pos.Y > Constants.RegionSize - boundaryDistance) { - int i = 0; - bool update_movementflag = false; - bool update_rotation = false; - bool DCFlagKeyPressed = false; - Vector3 agent_control_v3 = new Vector3(0, 0, 0); - Quaternion q = new Quaternion(bodyRotation.W, bodyRotation.X, bodyRotation.Y, bodyRotation.Z); - bool oldflying = PhysicsActor.Flying; - - PhysicsActor.Flying = ((flags & (uint) AgentManager.ControlFlags.AGENT_CONTROL_FLY) != 0); - if (PhysicsActor.Flying != oldflying) - { - update_movementflag = true; - } - - if (q != m_bodyRot) - { - m_bodyRot = q; - update_rotation = true; - } - - if (m_parentID == 0) - { - foreach (Dir_ControlFlags DCF in Enum.GetValues(typeof (Dir_ControlFlags))) - { - if ((flags & (uint) DCF) != 0) - { - DCFlagKeyPressed = true; - try - { - agent_control_v3 += Dir_Vectors[i]; - } - catch (IndexOutOfRangeException) - { - // Why did I get this? - } - if ((m_movementflag & (uint) DCF) == 0) - { - m_movementflag += (byte) (uint) DCF; - update_movementflag = true; - } - } - else - { - if ((m_movementflag & (uint) DCF) != 0) - { - m_movementflag -= (byte) (uint) DCF; - update_movementflag = true; - } - } - i++; - } - } - // Cause the avatar to stop flying if it's colliding - // with something with the down arrow pressed. - - // Skip if there's no physicsactor - if (m_physicsActor != null) - { - // Only do this if we're flying - if (m_physicsActor.Flying) - { - // Are the landing controls requirements filled? - bool controlland = (((flags & (uint) AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0) || - ((flags & (uint) AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG) != 0)); - - // Are the collision requirements fulfilled? - bool colliding = m_physicsActor.IsColliding; - - - if (m_physicsActor.Flying && colliding && controlland) - { - StopFlying(); - } - } - } - if ((update_movementflag) || (update_rotation && DCFlagKeyPressed)) - { - AddNewMovement(agent_control_v3, q); - UpdateMovementAnimations(update_movementflag); - } + neighboury++; + newpos.Y = enterDistance; } - m_scene.EventManager.TriggerOnClientMovement(this); - - m_scene.AddAgentTime(System.Environment.TickCount - m_perfMonMS); - } - - /// - /// Perform the logic necessary to stand the client up. This method also executes - /// the stand animation. - /// - public void StandUp() - { - if (m_parentID != 0) - { - SceneObjectPart part = m_scene.GetSceneObjectPart(m_parentID); - if (part != null) - { - // Reset sit target. - if (part.GetAvatarOnSitTarget() == UUID) - part.SetAvatarOnSitTarget(LLUUID.Zero); - - m_parentPosition = part.GetWorldPosition(); - } + LLVector3 vel = m_velocity; + ulong neighbourHandle = Helpers.UIntsToLong((uint)(neighbourx * Constants.RegionSize), (uint)(neighboury * Constants.RegionSize)); + SimpleRegionInfo neighbourRegion = m_scene.RequestNeighbouringRegionInfo(neighbourHandle); + if (neighbourRegion != null) + { + // When the neighbour is informed of the border crossing, it will set up CAPS handlers for the avatar + // This means we need to remove the current caps handler here and possibly compensate later, + // in case both scenes are being hosted on the same region server. Messy + m_scene.RemoveCapsHandler(UUID); + newpos = newpos + (vel); + bool res = + m_scene.InformNeighbourOfCrossing(neighbourHandle, m_controllingClient.AgentId, newpos, + m_physicsActor.Flying); + if (res) + { + AgentCircuitData circuitdata = m_controllingClient.RequestClientInfo(); - if (m_physicsActor == null) - { - AddToPhysicalScene(); + // TODO Should construct this behind a method + string capsPath = + "http://" + neighbourRegion.ExternalHostName + ":" + neighbourRegion.HttpPort + + "/CAPS/" + circuitdata.CapsPath + "0000/"; + + m_log.DebugFormat( + "[CAPS]: Sending new CAPS seed url {0} to client {1}", capsPath, m_uuid); + + m_controllingClient.CrossRegion(neighbourHandle, newpos, vel, neighbourRegion.ExternalEndPoint, + capsPath); + MakeChildAgent(); + CrossAttachmentsIntoNewRegion(neighbourHandle); + m_scene.SendKillObject(m_localId); + m_scene.NotifyMyCoarseLocationChange(); } - - m_pos += m_parentPosition + new LLVector3(0.0f, 0.0f, 2.0f * m_sitAvatarHeight); - m_parentPosition = new LLVector3(); - - m_parentID = 0; - SendFullUpdateToAllClients(); - - if (m_physicsActor != null) + else { - SetHeight(m_avHeight); + m_scene.AddCapsHandler(UUID); } } - - SetMovementAnimation(Animations.AnimsLLUUID["STAND"]); } - private void SendSitResponse(IClientAPI remoteClient, LLUUID targetID, LLVector3 offset) - { - AvatarSitResponsePacket avatarSitResponse = new AvatarSitResponsePacket(); - - avatarSitResponse.SitObject.ID = targetID; - - bool autopilot = true; - LLVector3 pos = new LLVector3(); - LLQuaternion sitOrientation = new LLQuaternion(0, 0, 0, 1); - - SceneObjectPart part = m_scene.GetSceneObjectPart(targetID); - if (part != null) - { - // TODO: determine position to sit at based on scene geometry; don't trust offset from client - // see http://wiki.secondlife.com/wiki/User:Andrew_Linden/Office_Hours/2007_11_06 for details on how LL does it - - // Is a sit target available? - Vector3 avSitOffSet = part.GetSitTargetPosition(); - Quaternion avSitOrientation = part.GetSitTargetOrientation(); - LLUUID avOnTargetAlready = part.GetAvatarOnSitTarget(); - - bool SitTargetUnOccupied = (!(avOnTargetAlready != LLUUID.Zero)); - bool SitTargetisSet = - (!(avSitOffSet.x == 0 && avSitOffSet.y == 0 && avSitOffSet.z == 0 && avSitOrientation.w == 0 && - avSitOrientation.x == 0 && avSitOrientation.y == 0 && avSitOrientation.z == 1)); - - if (SitTargetisSet && SitTargetUnOccupied) - { - part.SetAvatarOnSitTarget(UUID); - offset = new LLVector3(avSitOffSet.x, avSitOffSet.y, avSitOffSet.z); - sitOrientation = - new LLQuaternion(avSitOrientation.w, avSitOrientation.x, avSitOrientation.y, avSitOrientation.z); - autopilot = false; - } - - pos = part.AbsolutePosition + offset; - - if (m_physicsActor != null) - { - // If we're not using the client autopilot, we're immediately warping the avatar to the location - // We can remove the physicsActor until they stand up. - m_sitAvatarHeight = m_physicsActor.Size.Z; - - if (autopilot) - { - if (Util.GetDistanceTo(AbsolutePosition, pos) < 4.5) - { - autopilot = false; - - RemoveFromPhysicalScene(); - AbsolutePosition = pos + new LLVector3(0.0f, 0.0f, m_sitAvatarHeight); - } - } - else - { - RemoveFromPhysicalScene(); - } - } - } - - avatarSitResponse.SitTransform.AutoPilot = autopilot; - avatarSitResponse.SitTransform.SitPosition = offset; - avatarSitResponse.SitTransform.SitRotation = sitOrientation; - - remoteClient.OutPacket(avatarSitResponse, ThrottleOutPacketType.Task); - - // This calls HandleAgentSit twice, once from here, and the client calls - // HandleAgentSit itself after it gets to the location - // It doesn't get to the location until we've moved them there though - // which happens in HandleAgentSit :P - if (!autopilot) - HandleAgentSit(remoteClient, UUID); - } - - public void HandleAgentRequestSit(IClientAPI remoteClient, LLUUID agentID, LLUUID targetID, LLVector3 offset) - { - if (m_parentID != 0) - { - StandUp(); - } - - SceneObjectPart part = m_scene.GetSceneObjectPart(targetID); - - if (part != null) - { - m_requestedSitTargetID = part.LocalId; - m_requestedSitOffset = offset; - } - else - { - m_log.Warn("Sit requested on unknown object: " + targetID); - } - SendSitResponse(remoteClient, targetID, offset); - } - - public void HandleAgentSit(IClientAPI remoteClient, LLUUID agentID) - { - SceneObjectPart part = m_scene.GetSceneObjectPart(m_requestedSitTargetID); - - if (part != null) - { - if (part.GetAvatarOnSitTarget() == UUID) - { - Vector3 sitTargetPos = part.GetSitTargetPosition(); - Quaternion sitTargetOrient = part.GetSitTargetOrientation(); - - //Quaternion vq = new Quaternion(sitTargetPos.x, sitTargetPos.y+0.2f, sitTargetPos.z+0.2f, 0); - //Quaternion nq = new Quaternion(sitTargetOrient.w, -sitTargetOrient.x, -sitTargetOrient.y, -sitTargetOrient.z); - - //Quaternion result = (sitTargetOrient * vq) * nq; - - m_pos = new LLVector3(sitTargetPos.x, sitTargetPos.y, sitTargetPos.z); - m_bodyRot = sitTargetOrient; - //Rotation = sitTargetOrient; - m_parentPosition = part.AbsolutePosition; - - //SendTerseUpdateToAllClients(); - } - else - { - m_pos -= part.AbsolutePosition; - m_parentPosition = part.AbsolutePosition; - } - } - - m_parentID = m_requestedSitTargetID; - - Velocity = new LLVector3(0, 0, 0); - RemoveFromPhysicalScene(); - - SetMovementAnimation(Animations.AnimsLLUUID["SIT"]); - SendFullUpdateToAllClients(); - // This may seem stupid, but Our Full updates don't send avatar rotation :P - // So we're also sending a terse update (which has avatar rotation) - SendTerseUpdateToAllClients(); - } + #endregion /// - /// Event handler for the 'Always run' setting on the client - /// Tells the physics plugin to increase speed of movement. - /// - public void HandleSetAlwaysRun(IClientAPI remoteClient, bool SetAlwaysRun) - { - m_setAlwaysRun = SetAlwaysRun; - if (PhysicsActor != null) - { - PhysicsActor.SetAlwaysRun = SetAlwaysRun; - } - } - - public void AddAnimation(LLUUID animID) - { - if (m_isChildAgent) - return; - - // Don't let this animation become the movement animation - if (m_animations.Count < 1) - SetMovementAnimation(Animations.AnimsLLUUID["STAND"]); - - if (!m_animations.Contains(animID)) - { - m_animations.Add(animID); - m_animationSeqs.Add(m_controllingClient.NextAnimationSequenceNumber); - SendAnimPack(); - } - } - - public void RemoveAnimation(LLUUID animID) - { - if (m_isChildAgent) - return; - - if (m_animations.Contains(animID)) - { - if (m_animations[0] == animID) - { - SetMovementAnimation(Animations.AnimsLLUUID["STAND"]); - } - else - { - // What a HACK!! Anim list really needs to be an object! - int idx; - - for (idx = 0; idx < m_animations.Count; idx++) - { - if (m_animations[idx] == animID) - { - int seq = m_animationSeqs[idx]; - - m_animations.Remove(animID); - m_animationSeqs.Remove(seq); - SendAnimPack(); - break; - } - } - } - } - } - - public void HandleStartAnim(IClientAPI remoteClient, LLUUID animID) - { - AddAnimation(animID); - } - - public void HandleStopAnim(IClientAPI remoteClient, LLUUID animID) - { - RemoveAnimation(animID); - } - - /// - /// The movement animation is the first element of the animation list, - /// reserved for "main" animations that are mutually exclusive, - /// like flying and sitting, for example. - /// - protected void SetMovementAnimation(LLUUID anim) - { - if (m_animations.Count < 1) - { - m_animations.Add(Animations.AnimsLLUUID["STAND"]); - m_animationSeqs.Add(1); - - SendAnimPack(); - } - else - { - try - { - if (m_animations[0] != anim) - { - m_animations[0] = anim; - m_animationSeqs[0] = m_controllingClient.NextAnimationSequenceNumber; - } - SendAnimPack(); - } - catch - { - m_log.Warn("[AVATAR]: SetMovementAnimation for avatar failed. Attempting recovery..."); - m_animations[0] = anim; - m_animationSeqs[0] = m_controllingClient.NextAnimationSequenceNumber; - SendAnimPack(); - } - } - } - - /// - /// This method handles agent movement related animations + /// This allows the Sim owner the abiility to kick users from their sim currently. + /// It tells the client that the agent has permission to do so. /// - protected void UpdateMovementAnimations(bool update_movementflag) - { - if (update_movementflag) - { - // Are we moving? - if (m_movementflag != 0) - { - // We are moving - - if (m_physicsActor.Flying) - { - // We are flying - SetMovementAnimation(Animations.AnimsLLUUID["FLY"]); - } - else if (((m_movementflag & (uint) AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0) && - PhysicsActor.IsColliding) - { - // Client is pressing the page down button and moving and is colliding with something - SetMovementAnimation(Animations.AnimsLLUUID["CROUCHWALK"]); - } - else if (!PhysicsActor.IsColliding && m_physicsActor.Velocity.Z < -6) - { - // Client is moving and falling at a velocity greater then 6 meters per unit - SetMovementAnimation(Animations.AnimsLLUUID["FALLDOWN"]); - } - else if (!PhysicsActor.IsColliding && Velocity.Z > 0 && - (m_movementflag & (uint) AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) != 0) - { - // Client is moving, and colliding and pressing the page up button but isn't flying - try - { - SetMovementAnimation(Animations.AnimsLLUUID["JUMP"]); - } - catch (KeyNotFoundException) - { - } - } - else if (m_setAlwaysRun) - { - // We are running - try - { - SetMovementAnimation(Animations.AnimsLLUUID["RUN"]); - } - catch (KeyNotFoundException) - { - } - } - else - { - // We're moving, but we're not doing anything else.. so play the stand animation - try - { - SetMovementAnimation(Animations.AnimsLLUUID["WALK"]); - } - catch (KeyNotFoundException) - { - } - } - } - else - { - // Not moving - - if (((m_movementflag & (uint) AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0) && - PhysicsActor.IsColliding) - { - // Client pressing the page down button - SetMovementAnimation(Animations.AnimsLLUUID["CROUCH"]); - } - else if (!PhysicsActor.IsColliding && m_physicsActor.Velocity.Z < -6 && !m_physicsActor.Flying) - { - // Not colliding and not flying, and we're falling at high speed - SetMovementAnimation(Animations.AnimsLLUUID["FALLDOWN"]); - } - else if (!PhysicsActor.IsColliding && Velocity.Z > 0 && !m_physicsActor.Flying && - (m_movementflag & (uint) AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) != 0) - { - // This is the standing jump - SetMovementAnimation(Animations.AnimsLLUUID["JUMP"]); - } - else if (m_physicsActor.Flying) - { - // We're flying but not moving - SetMovementAnimation(Animations.AnimsLLUUID["HOVER"]); - } - else - { - // We're not moving.. and we're not doing anything.. so play the stand animation - try - { - SetMovementAnimation(Animations.AnimsLLUUID["STAND"]); - } - catch (KeyNotFoundException) - { - } - } - } + public void GrantGodlikePowers(LLUUID agentID, LLUUID sessionID, LLUUID token, bool godStatus) + { + GrantGodlikePowersPacket respondPacket = new GrantGodlikePowersPacket(); + GrantGodlikePowersPacket.GrantDataBlock gdb = new GrantGodlikePowersPacket.GrantDataBlock(); + GrantGodlikePowersPacket.AgentDataBlock adb = new GrantGodlikePowersPacket.AgentDataBlock(); + + adb.AgentID = agentID; + adb.SessionID = sessionID; // More security + + if (godStatus) + { + gdb.GodLevel = (byte)250; + m_godlevel = 250; + } + else + { + gdb.GodLevel = (byte)0; + m_godlevel = 0; } + + gdb.Token = token; + //respondPacket.AgentData = (GrantGodlikePowersPacket.AgentDataBlock)ablock; + respondPacket.GrantData = gdb; + respondPacket.AgentData = adb; + ControllingClient.OutPacket(respondPacket, ThrottleOutPacketType.Task); } /// - /// Adds a new movement + /// This updates important decision making data about a child agent + /// The main purpose is to figure out what objects to send to a child agent that's in a neighboring region /// - protected void AddNewMovement(Vector3 vec, Quaternion rotation) + public void ChildAgentDataUpdate(ChildAgentDataUpdate cAgentData, uint tRegionX, uint tRegionY, uint rRegionX, uint rRegionY) { - if (m_isChildAgent) - { - Console.WriteLine("DEBUG: AddNewMovement: child agent"); - return; - } + // + int shiftx = ((int)rRegionX - (int)tRegionX) * (int)Constants.RegionSize; + int shifty = ((int)rRegionY - (int)tRegionY) * (int)Constants.RegionSize; + + m_DrawDistance = cAgentData.drawdistance; + m_pos = new LLVector3(cAgentData.Position.x + shiftx, cAgentData.Position.y + shifty, cAgentData.Position.z); - m_perfMonMS = System.Environment.TickCount; + // It's hard to say here.. We can't really tell where the camera position is unless it's in world cordinates from the sending region + m_CameraCenter = + new Vector3(cAgentData.cameraPosition.x, cAgentData.cameraPosition.y, cAgentData.cameraPosition.z); + - m_rotation = rotation; - NewForce newVelocity = new NewForce(); - Vector3 direc = rotation * vec; - direc.Normalize(); + m_godlevel = cAgentData.godlevel; + SetHeight(cAgentData.AVHeight); - direc *= 0.03f * 128f; - if (m_physicsActor.Flying) - { - direc *= 4; - //bool controlland = (((m_AgentControlFlags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0) || ((m_AgentControlFlags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG) != 0)); - //bool colliding = (m_physicsActor.IsColliding==true); - //if (controlland) - // m_log.Info("[AGENT]: landCommand"); - //if (colliding ) - // m_log.Info("[AGENT]: colliding"); - //if (m_physicsActor.Flying && colliding && controlland) - //{ - // StopFlying(); - // m_log.Info("[AGENT]: Stop FLying"); - //} - } - else + ControllingClient.SetChildAgentThrottle(cAgentData.throttles); + + + + // Sends out the objects in the user's draw distance if m_sendTasksToChild is true. + if (m_scene.m_seeIntoRegionFromNeighbor) + m_scene.SendAllSceneObjectsToClient(this); + //cAgentData.AVHeight; + //cAgentData.regionHandle; + //m_velocity = cAgentData.Velocity; + } + + /// + /// Handles part of the PID controller function for moving an avatar. + /// + public override void UpdateMovement() + { + m_newForce = false; + lock (m_forcesList) { - if (!m_physicsActor.Flying && m_physicsActor.IsColliding) + if (m_forcesList.Count > 0) { - //direc.z *= 40; - if (direc.z > 2.0f) + for (int i = 0; i < m_forcesList.Count; i++) { - direc.z *= 3; - //System.Console.WriteLine("Jump"); - // PreJump and jump happen too quickly. Many times prejump gets ignored. + NewForce force = m_forcesList[i]; + + m_updateflag = true; try { - SetMovementAnimation(Animations.AnimsLLUUID["PREJUMP"]); - SetMovementAnimation(Animations.AnimsLLUUID["JUMP"]); + movementvector.X = force.X; + movementvector.Y = force.Y; + movementvector.Z = force.Z; + Velocity = movementvector; } - catch (KeyNotFoundException) + catch (NullReferenceException) { + // Under extreme load, this returns a NullReference Exception that we can ignore. + // Ignoring this causes no movement to be sent to the physics engine... + // which when the scene is moving at 1 frame every 10 seconds, it doesn't really matter! } + m_newForce = true; + } + for (int i = 0; i < m_forcesList.Count; i++) + { + m_forcesList.RemoveAt(0); } } } + } - newVelocity.X = direc.x; - newVelocity.Y = direc.y; - newVelocity.Z = direc.z; - m_forcesList.Add(newVelocity); - - m_scene.AddAgentTime(System.Environment.TickCount - m_perfMonMS); + static ScenePresence() + { + LLObject.TextureEntry textu = AvatarAppearance.GetDefaultTextureEntry(); + DefaultTexture = textu.ToBytes(); } - #endregion + [Serializable] + public class NewForce + { + public float X; + public float Y; + public float Z; - #region Overridden Methods + public NewForce() + { + } + } - /// - /// - /// - public override void Update() + [Serializable] + public class ScenePartUpdate : ISerializable { - SendPrimUpdates(); + public LLUUID FullID; + public uint LastFullUpdateTime; + public uint LastTerseUpdateTime; - if (m_newCoarseLocations) + public ScenePartUpdate() { - SendCoarseLocations(); - m_newCoarseLocations = false; + FullID = LLUUID.Zero; + LastFullUpdateTime = 0; + LastTerseUpdateTime = 0; } - if (m_isChildAgent == false) + protected ScenePartUpdate(SerializationInfo info, StreamingContext context) { - if (m_newForce) // user movement 'forces' (ie commands to move) - { - SendTerseUpdateToAllClients(); - m_updateCount = 0; - } - else if (m_movementflag != 0) // scripted movement (?) + //System.Console.WriteLine("ScenePartUpdate Deserialize BGN"); + + if (info == null) { - m_updateCount++; - if (m_updateCount > 3) - { - SendTerseUpdateToAllClients(); - m_updateCount = 0; - } + throw new ArgumentNullException("info"); } - else if ((Util.GetDistanceTo(lastPhysPos, AbsolutePosition) > 0.02) || (Util.GetDistanceTo(m_lastVelocity, m_velocity) > 0.02)) - // physics-related movement + + FullID = new LLUUID((Guid)info.GetValue("FullID", typeof(Guid))); + LastFullUpdateTime = (uint)info.GetValue("LastFullUpdateTime", typeof(uint)); + LastTerseUpdateTime = (uint)info.GetValue("LastTerseUpdateTime", typeof(uint)); + + //System.Console.WriteLine("ScenePartUpdate Deserialize END"); + } + + [SecurityPermission(SecurityAction.LinkDemand, + Flags = SecurityPermissionFlag.SerializationFormatter)] + public virtual void GetObjectData( + SerializationInfo info, StreamingContext context) + { + if (info == null) { - // Send Terse Update to all clients updates lastPhysPos and m_lastVelocity - // doing the above assures us that we know what we sent the clients last - SendTerseUpdateToAllClients(); - m_updateCount = 0; + throw new ArgumentNullException("info"); } - // followed suggestion from mic bowman. reversed the two lines below. - CheckForBorderCrossing(); - CheckForSignificantMovement(); // sends update to the modules. + info.AddValue("FullID", FullID.UUID); + info.AddValue("LastFullUpdateTime", LastFullUpdateTime); + info.AddValue("LastTerseUpdateTime", LastTerseUpdateTime); } } - #endregion - - #region Update Client(s) - - /// - /// Sends a location update to the client connected to this scenePresence - /// - /// - public void SendTerseUpdateToClient(IClientAPI remoteClient) + public override void SetText(string text, Vector3 color, double alpha) { - m_perfMonMS = System.Environment.TickCount; - - LLVector3 pos = m_pos; - LLVector3 vel = Velocity; - LLQuaternion rot = new LLQuaternion(m_bodyRot.x, m_bodyRot.y, m_bodyRot.z, m_bodyRot.w); - remoteClient.SendAvatarTerseUpdate(m_regionHandle, (ushort) (m_scene.TimeDilation * ushort.MaxValue), LocalId, new LLVector3(pos.X, pos.Y, pos.Z), - new LLVector3(vel.X, vel.Y, vel.Z), rot); - - m_scene.AddAgentTime(System.Environment.TickCount - m_perfMonMS); - m_scene.AddAgentUpdates(1); + throw new Exception("Can't set Text on avatar."); } /// - /// Send a location/velocity/accelleration update to all agents in scene + /// Adds a physical representation of the avatar to the Physics plugin /// - public void SendTerseUpdateToAllClients() + public void AddToPhysicalScene() { - m_perfMonMS = System.Environment.TickCount; - - m_scene.Broadcast(SendTerseUpdateToClient); - - m_lastVelocity = m_velocity; - lastPhysPos = AbsolutePosition; - - m_scene.AddAgentTime(System.Environment.TickCount - m_perfMonMS); + PhysicsScene scene = m_scene.PhysicsScene; + + PhysicsVector pVec = + new PhysicsVector(AbsolutePosition.X, AbsolutePosition.Y, + AbsolutePosition.Z); + if (m_avHeight == 127.0f) + { + m_physicsActor = scene.AddAvatar(Firstname + "." + Lastname, pVec, new PhysicsVector(0, 0, 1.56f)); + } + else + { + m_physicsActor = scene.AddAvatar(Firstname + "." + Lastname, pVec, new PhysicsVector(0, 0, m_avHeight)); + } + //m_physicsActor.OnRequestTerseUpdate += SendTerseUpdateToAllClients; + m_physicsActor.OnCollisionUpdate += PhysicsCollisionUpdate; + m_physicsActor.LocalID = LocalId; } - public void SendCoarseLocations() + // Event called by the physics plugin to tell the avatar about a collision. + private void PhysicsCollisionUpdate(EventArgs e) { - m_perfMonMS = System.Environment.TickCount; + bool isUserMoving = Velocity.X > 0 || Velocity.Y > 0; + UpdateMovementAnimations(isUserMoving); + } - List CoarseLocations = new List(); - List avatars = m_scene.GetAvatars(); - for (int i = 0; i < avatars.Count; i++) + internal void Close() + { + lock (m_attachments) + { + foreach (SceneObjectGroup grp in m_attachments) + { + // ControllingClient may be null at this point! + m_scene.m_innerScene.DetachSingleAttachmentToInv(grp.GetFromAssetID(), ControllingClient); + } + m_attachments.Clear(); + } + lock (m_knownPrimUUID) + { + m_knownPrimUUID.Clear(); + } + lock (m_knownChildRegions) + { + m_knownChildRegions.Clear(); + } + lock (m_updateTimes) { - if (avatars[i] != this) - { - CoarseLocations.Add(avatars[i].m_pos); - } + m_updateTimes.Clear(); + } + lock (m_partsUpdateQueue) + { + m_partsUpdateQueue.Clear(); } - m_controllingClient.SendCoarseLocationUpdate(CoarseLocations); - - m_scene.AddAgentTime(System.Environment.TickCount - m_perfMonMS); + RemoveFromPhysicalScene(); + GC.Collect(); } - public void CoarseLocationChange() + public ScenePresence() { - m_newCoarseLocations = true; +/* JB + if (Animations == null) + { + Animations = new AvatarAnimations(); + Animations.LoadAnims(); + } +*/ + if (DefaultTexture == null) + { + LLObject.TextureEntry textu = AvatarAppearance.GetDefaultTextureEntry(); + DefaultTexture = textu.ToBytes(); + } } - - /// - /// Tell other client about this avatar (The client previously didn't know or had outdated details about this avatar) - /// - /// - public void SendFullUpdateToOtherClient(ScenePresence remoteAvatar) + public void AddAttachment(SceneObjectGroup gobj) { - remoteAvatar.m_controllingClient.SendAvatarData(m_regionInfo.RegionHandle, m_firstname, m_lastname, m_uuid, - LocalId, m_pos, m_appearance.TextureEntry.ToBytes(), - m_parentID); - m_scene.AddAgentUpdates(1); + lock (m_attachments) + { + m_attachments.Add(gobj); + } } - - /// - /// Tell *ALL* agents about this agent - /// - public void SendFullUpdateToAllClients() + public void RemoveAttachment(SceneObjectGroup gobj) { - m_perfMonMS = System.Environment.TickCount; - - List avatars = m_scene.GetScenePresences(); - foreach (ScenePresence avatar in avatars) + lock (m_attachments) { - SendFullUpdateToOtherClient(avatar); - if (avatar.LocalId != LocalId) + if (m_attachments.Contains(gobj)) { - if (!avatar.m_isChildAgent || m_scene.m_seeIntoRegionFromNeighbor) - { - avatar.SendFullUpdateToOtherClient(this); - avatar.SendAppearanceToOtherAgent(this); - } + m_attachments.Remove(gobj); } } - m_scene.AddAgentUpdates(avatars.Count); - m_scene.AddAgentTime(System.Environment.TickCount - m_perfMonMS); } - - /// - /// - /// - public void SendInitialData() + public void CrossAttachmentsIntoNewRegion(ulong regionHandle) { - m_controllingClient.SendAvatarData(m_regionInfo.RegionHandle, m_firstname, m_lastname, m_uuid, LocalId, - m_pos, m_appearance.TextureEntry.ToBytes(), m_parentID); - if (!m_isChildAgent) + lock (m_attachments) { - m_scene.InformClientOfNeighbours(this); + foreach (SceneObjectGroup gobj in m_attachments) + { + // If the prim group is null then something must have happened to it! + if (gobj != null) + { + // Set the parent localID to 0 so it transfers over properly. + gobj.RootPart.SetParentLocalId(0); + gobj.RootPart.m_IsAttachment = false; + gobj.AbsolutePosition = gobj.RootPart.m_attachedPos; + gobj.RootPart.LastOwnerID = gobj.GetFromAssetID(); + m_scene.CrossPrimGroupIntoNewRegion(regionHandle, gobj); + } + } + m_attachments.Clear(); } - SendFullUpdateToAllClients(); - SendAppearanceToAllOtherAgents(); } - - /// - /// - /// - /// - public void SendOwnAppearance() + public void initializeScenePresence(IClientAPI client, RegionInfo region, Scene scene) { - m_appearance.SendOwnWearables(ControllingClient); + m_controllingClient = client; + m_regionInfo = region; + m_scene = scene; + RegisterToEvents(); - // TODO: remove this once the SunModule is slightly more tested - // m_controllingClient.SendViewerTime(m_scene.TimePhase); - } + /* + AbsolutePosition = client.StartPos; - /// - /// - /// - public void SendAppearanceToAllOtherAgents() - { - m_perfMonMS = System.Environment.TickCount; + Animations = new AvatarAnimations(); + Animations.LoadAnims(); - m_scene.ForEachScenePresence(delegate(ScenePresence scenePresence) - { - if (scenePresence.UUID != UUID) - { - m_appearance.SendAppearanceToOtherAgent(scenePresence); - } - }); - m_scene.AddAgentTime(System.Environment.TickCount - m_perfMonMS); - } + m_animations = new List(); + m_animations.Add(Animations.AnimsLLUUID["STAND"]); + m_animationSeqs.Add(m_controllingClient.NextAnimationSequenceNumber); - public void SendAppearanceToOtherAgent(ScenePresence avatar) - { - m_appearance.SendAppearanceToOtherAgent(avatar); + SetDirectionVectors(); + */ } - public void SetAppearance(byte[] texture, AgentSetAppearancePacket.VisualParamBlock[] visualParam) + protected ScenePresence(SerializationInfo info, StreamingContext context) + : base (info, context) { - m_appearance.SetAppearance(texture, visualParam); - SetHeight(m_appearance.AvatarHeight); + //System.Console.WriteLine("ScenePresence Deserialize BGN"); - SendAppearanceToAllOtherAgents(); - } + if (info == null) + { + throw new ArgumentNullException("info"); + } +/* JB + if (Animations == null) + { + Animations = new AvatarAnimations(); + Animations.LoadAnims(); + } +*/ + if (DefaultTexture == null) + { + LLObject.TextureEntry textu = AvatarAppearance.GetDefaultTextureEntry(); + DefaultTexture = textu.ToBytes(); + } - public void SetWearable(int wearableId, AvatarWearable wearable) - { - m_appearance.SetWearable(ControllingClient, wearableId, wearable); - } + List animations_work = (List)info.GetValue("m_animations", typeof(List)); - /// - /// - /// - /// - /// - public void SendAnimPack(LLUUID[] animations, int[] seqs) - { - if (m_isChildAgent) - return; + foreach (Guid guid in animations_work) + { + m_animations.Add(new LLUUID(guid)); + } - m_scene.Broadcast( - delegate(IClientAPI client) { client.SendAnimations(animations, seqs, m_controllingClient.AgentId); }); - } + m_animationSeqs = (List)info.GetValue("m_animationSeqs", typeof(List)); + m_updateflag = (bool)info.GetValue("m_updateflag", typeof(bool)); + m_movementflag = (byte)info.GetValue("m_movementflag", typeof(byte)); + m_forcesList = (List)info.GetValue("m_forcesList", typeof(List)); + m_updateCount = (short)info.GetValue("m_updateCount", typeof(short)); + m_requestedSitTargetID = (uint)info.GetValue("m_requestedSitTargetID", typeof(uint)); - /// - /// - /// - public void SendAnimPack() - { - SendAnimPack(m_animations.ToArray(), m_animationSeqs.ToArray()); - } + m_requestedSitOffset + = new LLVector3( + (float)info.GetValue("m_requestedSitOffset.X", typeof(float)), + (float)info.GetValue("m_requestedSitOffset.Y", typeof(float)), + (float)info.GetValue("m_requestedSitOffset.Z", typeof(float))); - #endregion + m_sitAvatarHeight = (float)info.GetValue("m_sitAvatarHeight", typeof(float)); + m_godlevel = (float)info.GetValue("m_godlevel", typeof(float)); + m_setAlwaysRun = (bool)info.GetValue("m_setAlwaysRun", typeof(bool)); - #region Significant Movement Method + m_bodyRot + = new Quaternion( + (float)info.GetValue("m_bodyRot.w", typeof(float)), + (float)info.GetValue("m_bodyRot.x", typeof(float)), + (float)info.GetValue("m_bodyRot.y", typeof(float)), + (float)info.GetValue("m_bodyRot.z", typeof(float))); - /// - /// This checks for a significant movement and sends a courselocationchange update - /// - protected void CheckForSignificantMovement() - { - if (Util.GetDistanceTo(AbsolutePosition, posLastSignificantMove) > 0.5) + IsRestrictedToRegion = (bool)info.GetValue("IsRestrictedToRegion", typeof(bool)); + m_newForce = (bool)info.GetValue("m_newForce", typeof(bool)); + //m_newAvatar = (bool)info.GetValue("m_newAvatar", typeof(bool)); + m_newCoarseLocations = (bool)info.GetValue("m_newCoarseLocations", typeof(bool)); + m_gotAllObjectsInScene = (bool)info.GetValue("m_gotAllObjectsInScene", typeof(bool)); + m_avHeight = (float)info.GetValue("m_avHeight", typeof(float)); + crossingFromRegion = (ulong)info.GetValue("crossingFromRegion", typeof(ulong)); + + List Dir_Vectors_work = (List)info.GetValue("Dir_Vectors", typeof(List)); + List Dir_Vectors_work2 = new List(); + + foreach (float[] f3 in Dir_Vectors_work) { - posLastSignificantMove = AbsolutePosition; - handlerSignificantClientMovement = OnSignificantClientMovement; - if (handlerSignificantClientMovement != null) - { - handlerSignificantClientMovement(m_controllingClient); - m_scene.NotifyMyCoarseLocationChange(); - } + Dir_Vectors_work2.Add(new Vector3(f3[0], f3[1], f3[2])); } - // Minimum Draw distance is 64 meters, the Radius of the draw distance sphere is 32m - if (Util.GetDistanceTo(AbsolutePosition, m_LastChildAgentUpdatePosition) > 32) + Dir_Vectors = Dir_Vectors_work2.ToArray(); + + lastPhysPos + = new LLVector3( + (float)info.GetValue("lastPhysPos.X", typeof(float)), + (float)info.GetValue("lastPhysPos.Y", typeof(float)), + (float)info.GetValue("lastPhysPos.Z", typeof(float))); + + m_CameraCenter + = new Vector3( + (float)info.GetValue("m_CameraCenter.X", typeof(float)), + (float)info.GetValue("m_CameraCenter.Y", typeof(float)), + (float)info.GetValue("m_CameraCenter.Z", typeof(float))); + + m_CameraAtAxis + = new Vector3( + (float)info.GetValue("m_CameraAtAxis.X", typeof(float)), + (float)info.GetValue("m_CameraAtAxis.Y", typeof(float)), + (float)info.GetValue("m_CameraAtAxis.Z", typeof(float))); + + m_CameraLeftAxis + = new Vector3( + (float)info.GetValue("m_CameraLeftAxis.X", typeof(float)), + (float)info.GetValue("m_CameraLeftAxis.Y", typeof(float)), + (float)info.GetValue("m_CameraLeftAxis.Z", typeof(float))); + + m_CameraUpAxis + = new Vector3( + (float)info.GetValue("m_CameraUpAxis.X", typeof(float)), + (float)info.GetValue("m_CameraUpAxis.Y", typeof(float)), + (float)info.GetValue("m_CameraUpAxis.Z", typeof(float))); + + m_DrawDistance = (float)info.GetValue("m_DrawDistance", typeof(float)); + m_appearance = (AvatarAppearance)info.GetValue("m_appearance", typeof(AvatarAppearance)); + m_knownChildRegions = (List)info.GetValue("m_knownChildRegions", typeof(List)); + + posLastSignificantMove + = new LLVector3( + (float)info.GetValue("posLastSignificantMove.X", typeof(float)), + (float)info.GetValue("posLastSignificantMove.Y", typeof(float)), + (float)info.GetValue("posLastSignificantMove.Z", typeof(float))); + + // m_partsUpdateQueue = (UpdateQueue)info.GetValue("m_partsUpdateQueue", typeof(UpdateQueue)); + + /* + Dictionary updateTimes_work + = (Dictionary)info.GetValue("m_updateTimes", typeof(Dictionary)); + + foreach (Guid id in updateTimes_work.Keys) { - ChildAgentDataUpdate cadu = new ChildAgentDataUpdate(); - cadu.ActiveGroupID = LLUUID.Zero.UUID; - cadu.AgentID = UUID.UUID; - cadu.alwaysrun = m_setAlwaysRun; - cadu.AVHeight = m_avHeight; - LLVector3 tempCameraCenter = new LLVector3(m_CameraCenter.x, m_CameraCenter.y, m_CameraCenter.z); - cadu.cameraPosition = new sLLVector3(tempCameraCenter); - cadu.drawdistance = m_DrawDistance; - cadu.godlevel = m_godlevel; - cadu.GroupAccess = 0; - cadu.Position = new sLLVector3(AbsolutePosition); - cadu.regionHandle = m_scene.RegionInfo.RegionHandle; - cadu.throttles = ControllingClient.GetThrottlesPacked(1f); - cadu.Velocity = new sLLVector3(Velocity); - m_scene.SendOutChildAgentUpdates(cadu, this); - m_LastChildAgentUpdatePosition.X = AbsolutePosition.X; - m_LastChildAgentUpdatePosition.Y = AbsolutePosition.Y; - m_LastChildAgentUpdatePosition.Z = AbsolutePosition.Z; + m_updateTimes.Add(new LLUUID(id), updateTimes_work[id]); } - } + */ + m_regionHandle = (ulong)info.GetValue("m_regionHandle", typeof(ulong)); + m_firstname = (string)info.GetValue("m_firstname", typeof(string)); + m_lastname = (string)info.GetValue("m_lastname", typeof(string)); + m_allowMovement = (bool)info.GetValue("m_allowMovement", typeof(bool)); + m_parentPosition = new LLVector3((float)info.GetValue("m_parentPosition.X", typeof(float)), + (float)info.GetValue("m_parentPosition.Y", typeof(float)), + (float)info.GetValue("m_parentPosition.Z", typeof(float))); + + m_isChildAgent = (bool)info.GetValue("m_isChildAgent", typeof(bool)); + m_parentID = (uint)info.GetValue("m_parentID", typeof(uint)); + +// for OpenSim_v0.5 + currentParcelUUID = new LLUUID((Guid)info.GetValue("currentParcelUUID", typeof(Guid))); + + lastKnownAllowedPosition + = new Vector3( + (float)info.GetValue("lastKnownAllowedPosition.X", typeof(float)), + (float)info.GetValue("lastKnownAllowedPosition.Y", typeof(float)), + (float)info.GetValue("lastKnownAllowedPosition.Z", typeof(float))); + + sentMessageAboutRestrictedParcelFlyingDown = (bool)info.GetValue("sentMessageAboutRestrictedParcelFlyingDown", typeof(bool)); - #endregion + m_LastChildAgentUpdatePosition + = new LLVector3( + (float)info.GetValue("m_LastChildAgentUpdatePosition.X", typeof(float)), + (float)info.GetValue("m_LastChildAgentUpdatePosition.Y", typeof(float)), + (float)info.GetValue("m_LastChildAgentUpdatePosition.Z", typeof(float))); + + m_perfMonMS = (int)info.GetValue("m_perfMonMS", typeof(int)); + m_AgentControlFlags = (uint)info.GetValue("m_AgentControlFlags", typeof(uint)); - #region Border Crossing Methods + m_headrotation + = new LLQuaternion( + (float)info.GetValue("m_headrotation.W", typeof(float)), + (float)info.GetValue("m_headrotation.X", typeof(float)), + (float)info.GetValue("m_headrotation.Y", typeof(float)), + (float)info.GetValue("m_headrotation.Z", typeof(float))); - /// - /// Checks to see if the avatar is in range of a border and calls CrossToNewRegion - /// - protected void CheckForBorderCrossing() - { - LLVector3 pos2 = AbsolutePosition; - LLVector3 vel = Velocity; + m_state = (byte)info.GetValue("m_state", typeof(byte)); - float timeStep = 0.1f; - pos2.X = pos2.X + (vel.X * timeStep); - pos2.Y = pos2.Y + (vel.Y * timeStep); - pos2.Z = pos2.Z + (vel.Z * timeStep); + List knownPrimUUID_work = (List)info.GetValue("m_knownPrimUUID", typeof(List)); - if ((pos2.X < 0) || (pos2.X > Constants.RegionSize)) + foreach (Guid id in knownPrimUUID_work) { - CrossToNewRegion(); + m_knownPrimUUID.Add(new LLUUID(id)); } - if ((pos2.Y < 0) || (pos2.Y > Constants.RegionSize)) - { - CrossToNewRegion(); - } + //System.Console.WriteLine("ScenePresence Deserialize END"); } - /// - /// Moves the agent outside the region bounds - /// Tells neighbor region that we're crossing to it - /// If the neighbor accepts, remove the agent's viewable avatar from this scene - /// set them to a child agent. - /// - protected void CrossToNewRegion() + [SecurityPermission(SecurityAction.LinkDemand, + Flags = SecurityPermissionFlag.SerializationFormatter)] + public override void GetObjectData( + SerializationInfo info, StreamingContext context) { - LLVector3 pos = AbsolutePosition; - LLVector3 newpos = new LLVector3(pos.X, pos.Y, pos.Z); - uint neighbourx = m_regionInfo.RegionLocX; - uint neighboury = m_regionInfo.RegionLocY; + if (info == null) + { + throw new ArgumentNullException("info"); + } - // distance to edge that will trigger crossing - const float boundaryDistance = 1.7f; + base.GetObjectData(info, context); - // distance into new region to place avatar - const float enterDistance = 0.1f; + List animations_work = new List(); - if (pos.X < boundaryDistance) - { - neighbourx--; - newpos.X = Constants.RegionSize - enterDistance; - } - else if (pos.X > Constants.RegionSize - boundaryDistance) + foreach (LLUUID uuid in m_animations) { - neighbourx++; - newpos.X = enterDistance; + animations_work.Add(uuid.UUID); } - if (pos.Y < boundaryDistance) - { - neighboury--; - newpos.Y = Constants.RegionSize - enterDistance; - } - else if (pos.Y > Constants.RegionSize - boundaryDistance) - { - neighboury++; - newpos.Y = enterDistance; - } + info.AddValue("m_animations", animations_work); - LLVector3 vel = m_velocity; - ulong neighbourHandle = Helpers.UIntsToLong((neighbourx * Constants.RegionSize), (neighboury * Constants.RegionSize)); - SimpleRegionInfo neighbourRegion = m_scene.RequestNeighbouringRegionInfo(neighbourHandle); - if (neighbourRegion != null) - { - // When the neighbour is informed of the border crossing, it will set up CAPS handlers for the avatar - // This means we need to remove the current caps handler here and possibly compensate later, - // in case both scenes are being hosted on the same region server. Messy - m_scene.RemoveCapsHandler(UUID); - newpos = newpos + (vel); - bool res = - m_scene.InformNeighbourOfCrossing(neighbourHandle, m_controllingClient.AgentId, newpos, - m_physicsActor.Flying); - if (res) - { - AgentCircuitData circuitdata = m_controllingClient.RequestClientInfo(); + info.AddValue("m_animationSeqs", m_animationSeqs); + info.AddValue("m_updateflag", m_updateflag); + info.AddValue("m_movementflag", m_movementflag); + info.AddValue("m_forcesList", m_forcesList); + info.AddValue("m_updateCount", m_updateCount); + info.AddValue("m_requestedSitTargetID", m_requestedSitTargetID); - // TODO Should construct this behind a method - string capsPath = - "http://" + neighbourRegion.ExternalHostName + ":" + neighbourRegion.HttpPort - + "/CAPS/" + circuitdata.CapsPath + "0000/"; + // LLVector3 + info.AddValue("m_requestedSitOffset.X", m_requestedSitOffset.X); + info.AddValue("m_requestedSitOffset.Y", m_requestedSitOffset.Y); + info.AddValue("m_requestedSitOffset.Z", m_requestedSitOffset.Z); - m_log.DebugFormat( - "[CAPS]: Sending new CAPS seed url {0} to client {1}", capsPath, m_uuid); + info.AddValue("m_sitAvatarHeight", m_sitAvatarHeight); + info.AddValue("m_godlevel", m_godlevel); + info.AddValue("m_setAlwaysRun", m_setAlwaysRun); + + // Quaternion + info.AddValue("m_bodyRot.w", m_bodyRot.w); + info.AddValue("m_bodyRot.x", m_bodyRot.x); + info.AddValue("m_bodyRot.y", m_bodyRot.y); + info.AddValue("m_bodyRot.z", m_bodyRot.z); - m_controllingClient.CrossRegion(neighbourHandle, newpos, vel, neighbourRegion.ExternalEndPoint, - capsPath); - MakeChildAgent(); - CrossAttachmentsIntoNewRegion(neighbourHandle); - m_scene.SendKillObject(m_localId); - m_scene.NotifyMyCoarseLocationChange(); - } - else - { - m_scene.AddCapsHandler(UUID); - } + info.AddValue("IsRestrictedToRegion", IsRestrictedToRegion); + info.AddValue("m_newForce", m_newForce); + //info.AddValue("m_newAvatar", m_newAvatar); + info.AddValue("m_newCoarseLocations", m_newCoarseLocations); + info.AddValue("m_gotAllObjectsInScene", m_gotAllObjectsInScene); + info.AddValue("m_avHeight", m_avHeight); + + // info.AddValue("m_regionInfo", m_regionInfo); + + info.AddValue("crossingFromRegion", crossingFromRegion); + + List Dir_Vectors_work = new List(); + + foreach (Vector3 v3 in Dir_Vectors) + { + Dir_Vectors_work.Add(new float[] { v3.x, v3.y, v3.z }); } - } - #endregion + info.AddValue("Dir_Vectors", Dir_Vectors_work); - #region Nested type: Dir_ControlFlags + // LLVector3 + info.AddValue("lastPhysPos.X", lastPhysPos.X); + info.AddValue("lastPhysPos.Y", lastPhysPos.Y); + info.AddValue("lastPhysPos.Z", lastPhysPos.Z); - /// - /// Implemented Control Flags - /// - private enum Dir_ControlFlags - { - DIR_CONTROL_FLAG_FORWARD = AgentManager.ControlFlags.AGENT_CONTROL_AT_POS, - DIR_CONTROL_FLAG_BACK = AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG, - DIR_CONTROL_FLAG_LEFT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS, - DIR_CONTROL_FLAG_RIGHT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG, - DIR_CONTROL_FLAG_UP = AgentManager.ControlFlags.AGENT_CONTROL_UP_POS, - DIR_CONTROL_FLAG_DOWN = AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG, - DIR_CONTROL_FLAG_DOWN_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG - } + // Vector3 + info.AddValue("m_CameraCenter.X", m_CameraCenter.x); + info.AddValue("m_CameraCenter.Y", m_CameraCenter.y); + info.AddValue("m_CameraCenter.Z", m_CameraCenter.z); - #endregion + // Vector3 + info.AddValue("m_CameraAtAxis.X", m_CameraAtAxis.x); + info.AddValue("m_CameraAtAxis.Y", m_CameraAtAxis.y); + info.AddValue("m_CameraAtAxis.Z", m_CameraAtAxis.z); - #region Nested type: NewForce + // Vector3 + info.AddValue("m_CameraLeftAxis.X", m_CameraLeftAxis.x); + info.AddValue("m_CameraLeftAxis.Y", m_CameraLeftAxis.y); + info.AddValue("m_CameraLeftAxis.Z", m_CameraLeftAxis.z); - [Serializable] - public class NewForce - { - public float X; - public float Y; - public float Z; - } + // Vector3 + info.AddValue("m_CameraUpAxis.X", m_CameraUpAxis.x); + info.AddValue("m_CameraUpAxis.Y", m_CameraUpAxis.y); + info.AddValue("m_CameraUpAxis.Z", m_CameraUpAxis.z); - #endregion + info.AddValue("m_DrawDistance", m_DrawDistance); + info.AddValue("m_appearance", m_appearance); + info.AddValue("m_knownChildRegions", m_knownChildRegions); - #region Nested type: ScenePartUpdate + // LLVector3 + info.AddValue("posLastSignificantMove.X", posLastSignificantMove.X); + info.AddValue("posLastSignificantMove.Y", posLastSignificantMove.Y); + info.AddValue("posLastSignificantMove.Z", posLastSignificantMove.Z); - [Serializable] - public class ScenePartUpdate : ISerializable - { - public LLUUID FullID; - public uint LastFullUpdateTime; - public uint LastTerseUpdateTime; + //info.AddValue("m_partsUpdateQueue", m_partsUpdateQueue); - public ScenePartUpdate() + /* + Dictionary updateTimes_work = new Dictionary(); + + foreach ( LLUUID id in m_updateTimes.Keys) { - FullID = LLUUID.Zero; - LastFullUpdateTime = 0; - LastTerseUpdateTime = 0; + updateTimes_work.Add(id.UUID, m_updateTimes[id]); } - protected ScenePartUpdate(SerializationInfo info, StreamingContext context) - { - //System.Console.WriteLine("ScenePartUpdate Deserialize BGN"); + info.AddValue("m_updateTimes", updateTimes_work); + */ - if (info == null) - { - throw new ArgumentNullException("info"); - } + info.AddValue("m_regionHandle", m_regionHandle); + info.AddValue("m_firstname", m_firstname); + info.AddValue("m_lastname", m_lastname); + info.AddValue("m_allowMovement", m_allowMovement); + //info.AddValue("m_physicsActor", m_physicsActor); + info.AddValue("m_parentPosition.X", m_parentPosition.X); + info.AddValue("m_parentPosition.Y", m_parentPosition.Y); + info.AddValue("m_parentPosition.Z", m_parentPosition.Z); + info.AddValue("m_isChildAgent", m_isChildAgent); + info.AddValue("m_parentID", m_parentID); - FullID = new LLUUID((Guid) info.GetValue("FullID", typeof (Guid))); - LastFullUpdateTime = (uint) info.GetValue("LastFullUpdateTime", typeof (uint)); - LastTerseUpdateTime = (uint) info.GetValue("LastTerseUpdateTime", typeof (uint)); +// for OpenSim_v0.5 + info.AddValue("currentParcelUUID", currentParcelUUID.UUID); - //System.Console.WriteLine("ScenePartUpdate Deserialize END"); - } + info.AddValue("lastKnownAllowedPosition.X", lastKnownAllowedPosition.x); + info.AddValue("lastKnownAllowedPosition.Y", lastKnownAllowedPosition.y); + info.AddValue("lastKnownAllowedPosition.Z", lastKnownAllowedPosition.z); + + info.AddValue("sentMessageAboutRestrictedParcelFlyingDown", sentMessageAboutRestrictedParcelFlyingDown); - #region ISerializable Members + info.AddValue("m_LastChildAgentUpdatePosition.X", m_LastChildAgentUpdatePosition.X); + info.AddValue("m_LastChildAgentUpdatePosition.Y", m_LastChildAgentUpdatePosition.Y); + info.AddValue("m_LastChildAgentUpdatePosition.Z", m_LastChildAgentUpdatePosition.Z); - [SecurityPermission(SecurityAction.LinkDemand, - Flags = SecurityPermissionFlag.SerializationFormatter)] - public virtual void GetObjectData( - SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new ArgumentNullException("info"); - } + info.AddValue("m_perfMonMS", m_perfMonMS); + info.AddValue("m_AgentControlFlags", m_AgentControlFlags); - info.AddValue("FullID", FullID.UUID); - info.AddValue("LastFullUpdateTime", LastFullUpdateTime); - info.AddValue("LastTerseUpdateTime", LastTerseUpdateTime); + info.AddValue("m_headrotation.W", m_headrotation.W); + info.AddValue("m_headrotation.X", m_headrotation.X); + info.AddValue("m_headrotation.Y", m_headrotation.Y); + info.AddValue("m_headrotation.Z", m_headrotation.Z); + + info.AddValue("m_state", m_state); + + List knownPrimUUID_work = new List(); + + foreach (LLUUID id in m_knownPrimUUID) + { + knownPrimUUID_work.Add(id.UUID); } - #endregion + info.AddValue("m_knownPrimUUID", knownPrimUUID_work); } - - #endregion } -} \ No newline at end of file +} diff --git a/OpenSim/Region/Environment/Scenes/SceneXmlLoader.cs b/OpenSim/Region/Environment/Scenes/SceneXmlLoader.cs index 386d87b..8390f64 100644 --- a/OpenSim/Region/Environment/Scenes/SceneXmlLoader.cs +++ b/OpenSim/Region/Environment/Scenes/SceneXmlLoader.cs @@ -39,8 +39,8 @@ namespace OpenSim.Region.Environment.Scenes public class SceneXmlLoader // can move to a module? { protected InnerScene m_innerScene; - protected Scene m_parentScene; protected RegionInfo m_regInfo; + protected Scene m_parentScene; public SceneXmlLoader(Scene parentScene, InnerScene innerScene, RegionInfo regionInfo) { @@ -136,13 +136,14 @@ namespace OpenSim.Region.Environment.Scenes returnstring += grp.ToXmlString2(); returnstring += "\n"; return returnstring; + } public void LoadGroupFromXml2String(string xmlString) { XmlDocument doc = new XmlDocument(); XmlNode rootNode; - + XmlTextReader reader = new XmlTextReader(new StringReader(xmlString)); reader.WhitespaceHandling = WhitespaceHandling.None; doc.Load(reader); @@ -152,6 +153,7 @@ namespace OpenSim.Region.Environment.Scenes { CreatePrimFromXml(aPrimNode.OuterXml); } + } public void LoadPrimsFromXml2(string fileName) @@ -204,7 +206,7 @@ namespace OpenSim.Region.Environment.Scenes rootPart.PhysActor.LocalID = rootPart.LocalId; rootPart.DoPhysicsPropertyUpdate(UsePhysics, true); } - rootPart.Velocity = receivedVelocity; + rootPart.Velocity = receivedVelocity; } obj.ScheduleGroupForFullUpdate(); @@ -232,4 +234,4 @@ namespace OpenSim.Region.Environment.Scenes file.Close(); } } -} \ No newline at end of file +} diff --git a/OpenSim/Region/Environment/Scenes/Scripting/IScriptHost.cs b/OpenSim/Region/Environment/Scenes/Scripting/IScriptHost.cs index ccb2aa7..dbe2516 100644 --- a/OpenSim/Region/Environment/Scenes/Scripting/IScriptHost.cs +++ b/OpenSim/Region/Environment/Scenes/Scripting/IScriptHost.cs @@ -44,4 +44,4 @@ namespace OpenSim.Region.Environment.Scenes.Scripting string TouchName { get; set; } void SetText(string text, Vector3 color, double alpha); } -} \ No newline at end of file +} diff --git a/OpenSim/Region/Environment/Scenes/Scripting/NullScriptHost.cs b/OpenSim/Region/Environment/Scenes/Scripting/NullScriptHost.cs index a37ce53..4b1b56a 100644 --- a/OpenSim/Region/Environment/Scenes/Scripting/NullScriptHost.cs +++ b/OpenSim/Region/Environment/Scenes/Scripting/NullScriptHost.cs @@ -33,9 +33,7 @@ namespace OpenSim.Region.Environment.Scenes.Scripting { public class NullScriptHost : IScriptHost { - private readonly LLVector3 m_pos = new LLVector3(128, 128, 30); - - #region IScriptHost Members + private LLVector3 m_pos = new LLVector3(128, 128, 30); public string Name { @@ -85,7 +83,5 @@ namespace OpenSim.Region.Environment.Scenes.Scripting { Console.WriteLine("Tried to SetText [{0}] on NullScriptHost", text); } - - #endregion } -} \ No newline at end of file +} diff --git a/OpenSim/Region/Environment/Scenes/Scripting/ScriptEngineInterface.cs b/OpenSim/Region/Environment/Scenes/Scripting/ScriptEngineInterface.cs index cb0e1e8..b1ee519 100644 --- a/OpenSim/Region/Environment/Scenes/Scripting/ScriptEngineInterface.cs +++ b/OpenSim/Region/Environment/Scenes/Scripting/ScriptEngineInterface.cs @@ -35,4 +35,4 @@ namespace OpenSim.Region.Environment.Scenes.Scripting void Shutdown(); // void StartScript(string ScriptID, IScriptHost ObjectID); } -} \ No newline at end of file +} diff --git a/OpenSim/Region/Environment/Scenes/Scripting/ScriptEngineLoader.cs b/OpenSim/Region/Environment/Scenes/Scripting/ScriptEngineLoader.cs index 0048e6b..6216e2c 100644 --- a/OpenSim/Region/Environment/Scenes/Scripting/ScriptEngineLoader.cs +++ b/OpenSim/Region/Environment/Scenes/Scripting/ScriptEngineLoader.cs @@ -51,7 +51,7 @@ namespace OpenSim.Region.Environment.Scenes.Scripting { m_log.Error("[ScriptEngine]: " + "Error loading assembly \"" + EngineName + "\": " + e.Message + ", " + - e.StackTrace); + e.StackTrace.ToString()); } return ret; } @@ -116,4 +116,4 @@ namespace OpenSim.Region.Environment.Scenes.Scripting return ret; } } -} \ No newline at end of file +} diff --git a/OpenSim/Region/Environment/Scenes/SimStatsReporter.cs b/OpenSim/Region/Environment/Scenes/SimStatsReporter.cs index 1f02f23..a53bfcd 100644 --- a/OpenSim/Region/Environment/Scenes/SimStatsReporter.cs +++ b/OpenSim/Region/Environment/Scenes/SimStatsReporter.cs @@ -34,68 +34,105 @@ namespace OpenSim.Region.Environment.Scenes { public class SimStatsReporter { - #region Delegates - public delegate void SendStatResult(SimStatsPacket pack); - #endregion + public event SendStatResult OnSendStatsResult; - private readonly Timer m_report = new Timer(); - private readonly SimStatsPacket.RegionBlock rb = new SimStatsPacket.RegionBlock(); - private readonly RegionInfo ReportingRegion; - private readonly SimStatsPacket.StatBlock[] sb = new SimStatsPacket.StatBlock[21]; - private readonly SimStatsPacket statpack = (SimStatsPacket) PacketPool.Instance.GetPacket(PacketType.SimStats); - - private SendStatResult handlerSendStatResult; - private int m_activePrim; - private int m_activeScripts; - private int m_agentMS; - - private int m_agentUpdates; - private int m_childAgents; - private int m_fps; - - private int m_frameMS; - private int m_imageMS; - private int m_inPacketsPerSecond; - private int m_netMS; - private int m_numPrim; - private int m_otherMS; - private int m_outPacketsPerSecond; - private int m_pendingDownloads; - private int m_pendingUploads; - private float m_pfps; - private int m_physicsMS; - private int m_rootAgents; - private int m_scriptLinesPerSecond; - private float m_timeDilation; - private int m_unAckedBytes; + private SendStatResult handlerSendStatResult = null; - private int objectCapacity = 45000; - private float statsUpdateFactor; + private enum Stats : uint + { + TimeDilation = 0, + SimFPS = 1, + PhysicsFPS = 2, + AgentUpdates = 3, + FrameMS = 4, + NetMS = 5, + OtherMS = 6, + PhysicsMS = 7, + AgentMS = 8, + ImageMS = 9, + ScriptMS = 10, + TotalPrim = 11, + ActivePrim = 12, + Agents = 13, + ChildAgents = 14, + ActiveScripts = 15, + ScriptLinesPerSecond = 16, + InPacketsPerSecond = 17, + OutPacketsPerSecond = 18, + PendingDownloads = 19, + PendingUploads = 20, + UnAckedBytes = 24, + + // Havok4 related... May or may not be in upcoming LLclients + // (kelly added them sometime late in January 2008) + NumRCCSLODReduced = 25, + NumRCCSFixed = 26 + } + + // Sending a stats update every 3 seconds private int statsUpdatesEveryMS = 3000; + private float statsUpdateFactor = 0; + private float m_timeDilation = 0; + private int m_fps = 0; + private float m_pfps = 0; + private int m_agentUpdates = 0; + + private int m_frameMS = 0; + private int m_netMS = 0; + private int m_agentMS = 0; + private int m_physicsMS = 0; + private int m_imageMS = 0; + private int m_otherMS = 0; + +//Ckrinke: (3-21-08) Comment out to remove a compiler warning. Bring back into play when needed. +//Ckrinke private int m_scriptMS = 0; + + private int m_rootAgents = 0; + private int m_childAgents = 0; + private int m_numPrim = 0; + private int m_inPacketsPerSecond = 0; + private int m_outPacketsPerSecond = 0; + private int m_activePrim = 0; + private int m_unAckedBytes = 0; + private int m_pendingDownloads = 0; + private int m_pendingUploads = 0; + private int m_activeScripts = 0; + private int m_scriptLinesPerSecond = 0; + + private int objectCapacity = 45000; + + + SimStatsPacket.StatBlock[] sb = new SimStatsPacket.StatBlock[21]; + SimStatsPacket.RegionBlock rb = new SimStatsPacket.RegionBlock(); + SimStatsPacket statpack = (SimStatsPacket)PacketPool.Instance.GetPacket(PacketType.SimStats); + + + private RegionInfo ReportingRegion; + + private Timer m_report = new Timer(); public SimStatsReporter(RegionInfo regionData) { - statsUpdateFactor = (statsUpdatesEveryMS / 1000); + + statsUpdateFactor = (float)(statsUpdatesEveryMS / 1000); ReportingRegion = regionData; - for (int i = 0; i < 21; i++) + for (int i = 0; i<21;i++) { sb[i] = new SimStatsPacket.StatBlock(); } m_report.AutoReset = true; m_report.Interval = statsUpdatesEveryMS; - m_report.Elapsed += statsHeartBeat; + m_report.Elapsed += new ElapsedEventHandler(statsHeartBeat); m_report.Enabled = true; } - public event SendStatResult OnSendStatsResult; - public void SetUpdateMS(int ms) { statsUpdatesEveryMS = ms; - statsUpdateFactor = (statsUpdatesEveryMS / 1000); + statsUpdateFactor = (float)(statsUpdatesEveryMS / 1000); m_report.Interval = statsUpdatesEveryMS; } @@ -106,8 +143,8 @@ namespace OpenSim.Region.Environment.Scenes lock (m_report) { // Packet is already initialized and ready for data insert - - + + statpack.Region = rb; statpack.Region.RegionX = ReportingRegion.RegionLocX; statpack.Region.RegionY = ReportingRegion.RegionLocY; @@ -117,102 +154,102 @@ namespace OpenSim.Region.Environment.Scenes } catch (Exception) { - statpack.Region.RegionFlags = 0; + statpack.Region.RegionFlags = (uint) 0; } statpack.Region.ObjectCapacity = (uint) objectCapacity; - - #region various statistic googly moogly - + +#region various statistic googly moogly + // Our FPS is actually 10fps, so multiplying by 5 to get the amount that people expect there // 0-50 is pretty close to 0-45 - float simfps = ((m_fps * 5)); - + float simfps = (int) ((m_fps * 5)); + //if (simfps > 45) //simfps = simfps - (simfps - 45); //if (simfps < 0) //simfps = 0; - + // float physfps = ((m_pfps / 1000)); - + //if (physfps > 600) //physfps = physfps - (physfps - 600); - + if (physfps < 0) physfps = 0; - - #endregion - + +#endregion + //Our time dilation is 0.91 when we're running a full speed, // therefore to make sure we get an appropriate range, // we have to factor in our error. (0.10f * statsUpdateFactor) // multiplies the fix for the error times the amount of times it'll occur a second // / 10 divides the value by the number of times the sim heartbeat runs (10fps) // Then we divide the whole amount by the amount of seconds pass in between stats updates. - + sb[0].StatID = (uint) Stats.TimeDilation; - sb[0].StatValue = m_timeDilation; //((((m_timeDilation + (0.10f * statsUpdateFactor)) /10) / statsUpdateFactor)); - + sb[0].StatValue = m_timeDilation ; //((((m_timeDilation + (0.10f * statsUpdateFactor)) /10) / statsUpdateFactor)); + sb[1].StatID = (uint) Stats.SimFPS; - sb[1].StatValue = simfps / statsUpdateFactor; - + sb[1].StatValue = simfps/statsUpdateFactor; + sb[2].StatID = (uint) Stats.PhysicsFPS; sb[2].StatValue = physfps / statsUpdateFactor; - + sb[3].StatID = (uint) Stats.AgentUpdates; sb[3].StatValue = (m_agentUpdates / statsUpdateFactor); - + sb[4].StatID = (uint) Stats.Agents; sb[4].StatValue = m_rootAgents; - + sb[5].StatID = (uint) Stats.ChildAgents; sb[5].StatValue = m_childAgents; - + sb[6].StatID = (uint) Stats.TotalPrim; sb[6].StatValue = m_numPrim; - + sb[7].StatID = (uint) Stats.ActivePrim; sb[7].StatValue = m_activePrim; - - sb[8].StatID = (uint) Stats.FrameMS; + + sb[8].StatID = (uint)Stats.FrameMS; sb[8].StatValue = m_frameMS / statsUpdateFactor; - - sb[9].StatID = (uint) Stats.NetMS; + + sb[9].StatID = (uint)Stats.NetMS; sb[9].StatValue = m_netMS / statsUpdateFactor; - - sb[10].StatID = (uint) Stats.PhysicsMS; + + sb[10].StatID = (uint)Stats.PhysicsMS; sb[10].StatValue = m_physicsMS / statsUpdateFactor; - - sb[11].StatID = (uint) Stats.ImageMS; + + sb[11].StatID = (uint)Stats.ImageMS ; sb[11].StatValue = m_imageMS / statsUpdateFactor; - - sb[12].StatID = (uint) Stats.OtherMS; + + sb[12].StatID = (uint)Stats.OtherMS; sb[12].StatValue = m_otherMS / statsUpdateFactor; - - sb[13].StatID = (uint) Stats.InPacketsPerSecond; + + sb[13].StatID = (uint)Stats.InPacketsPerSecond; sb[13].StatValue = (m_inPacketsPerSecond); - - sb[14].StatID = (uint) Stats.OutPacketsPerSecond; + + sb[14].StatID = (uint)Stats.OutPacketsPerSecond; sb[14].StatValue = (m_outPacketsPerSecond / statsUpdateFactor); - - sb[15].StatID = (uint) Stats.UnAckedBytes; + + sb[15].StatID = (uint)Stats.UnAckedBytes; sb[15].StatValue = m_unAckedBytes; - - sb[16].StatID = (uint) Stats.AgentMS; + + sb[16].StatID = (uint)Stats.AgentMS; sb[16].StatValue = m_agentMS / statsUpdateFactor; - - sb[17].StatID = (uint) Stats.PendingDownloads; + + sb[17].StatID = (uint)Stats.PendingDownloads; sb[17].StatValue = m_pendingDownloads; - - sb[18].StatID = (uint) Stats.PendingUploads; + + sb[18].StatID = (uint)Stats.PendingUploads; sb[18].StatValue = m_pendingUploads; - - sb[19].StatID = (uint) Stats.ActiveScripts; + + sb[19].StatID = (uint)Stats.ActiveScripts; sb[19].StatValue = m_activeScripts; - - sb[20].StatID = (uint) Stats.ScriptLinesPerSecond; + + sb[20].StatID = (uint)Stats.ScriptLinesPerSecond; sb[20].StatValue = m_scriptLinesPerSecond / statsUpdateFactor; - + statpack.Stat = sb; handlerSendStatResult = OnSendStatsResult; @@ -223,7 +260,7 @@ namespace OpenSim.Region.Environment.Scenes resetvalues(); } } - + private void resetvalues() { m_timeDilation = 0; @@ -247,7 +284,6 @@ namespace OpenSim.Region.Environment.Scenes } # region methods called from Scene - // The majority of these functions are additive // so that you can easily change the amount of // seconds in between sim stats updates @@ -256,10 +292,10 @@ namespace OpenSim.Region.Environment.Scenes { //float tdsetting = td; //if (tdsetting > 1.0f) - //tdsetting = (tdsetting - (tdsetting - 0.91f)); + //tdsetting = (tdsetting - (tdsetting - 0.91f)); //if (tdsetting < 0) - //tdsetting = 0.0f; + //tdsetting = 0.0f; m_timeDilation = td; } @@ -317,35 +353,30 @@ namespace OpenSim.Region.Environment.Scenes { m_frameMS += ms; } - public void addNetMS(int ms) { m_netMS += ms; } - public void addAgentMS(int ms) { m_agentMS += ms; } - public void addPhysicsMS(int ms) { m_physicsMS += ms; } - public void addImageMS(int ms) { m_imageMS += ms; } - public void addOtherMS(int ms) { m_otherMS += ms; } - + // private static readonly log4net.ILog m_log // = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - + public void addPendingDownload(int count) { m_pendingDownloads += count; @@ -368,40 +399,5 @@ namespace OpenSim.Region.Environment.Scenes } #endregion - - #region Nested type: Stats - - private enum Stats : uint - { - TimeDilation = 0, - SimFPS = 1, - PhysicsFPS = 2, - AgentUpdates = 3, - FrameMS = 4, - NetMS = 5, - OtherMS = 6, - PhysicsMS = 7, - AgentMS = 8, - ImageMS = 9, - ScriptMS = 10, - TotalPrim = 11, - ActivePrim = 12, - Agents = 13, - ChildAgents = 14, - ActiveScripts = 15, - ScriptLinesPerSecond = 16, - InPacketsPerSecond = 17, - OutPacketsPerSecond = 18, - PendingDownloads = 19, - PendingUploads = 20, - UnAckedBytes = 24, - - // Havok4 related... May or may not be in upcoming LLclients - // (kelly added them sometime late in January 2008) - NumRCCSLODReduced = 25, - NumRCCSFixed = 26 - } - - #endregion } -} \ No newline at end of file +} diff --git a/OpenSim/Region/Environment/Scenes/UndoState.cs b/OpenSim/Region/Environment/Scenes/UndoState.cs index f16bb34..daabd8d 100644 --- a/OpenSim/Region/Environment/Scenes/UndoState.cs +++ b/OpenSim/Region/Environment/Scenes/UndoState.cs @@ -32,8 +32,8 @@ namespace OpenSim.Region.Environment.Scenes public class UndoState { public LLVector3 Position = LLVector3.Zero; - public LLQuaternion Rotation = LLQuaternion.Identity; public LLVector3 Scale = LLVector3.Zero; + public LLQuaternion Rotation = LLQuaternion.Identity; public UndoState(LLVector3 pos, LLQuaternion rot, LLVector3 scale) { @@ -41,7 +41,7 @@ namespace OpenSim.Region.Environment.Scenes Rotation = rot; Scale = scale; } - + public UndoState(SceneObjectPart part) { if (part != null) @@ -50,20 +50,18 @@ namespace OpenSim.Region.Environment.Scenes { Position = part.AbsolutePosition; Rotation = part.RotationOffset; + } else { Position = part.GroupPosition; Rotation = part.RotationOffset; Scale = part.Shape.Scale; + } } } - public UndoState() - { - } - public bool Compare(SceneObjectPart part) { if (part != null) @@ -81,6 +79,7 @@ namespace OpenSim.Region.Environment.Scenes return true; else return false; + } } return false; @@ -91,7 +90,7 @@ namespace OpenSim.Region.Environment.Scenes if (part != null) { part.m_undoing = true; - + if (part.ParentID == 0) { part.ParentGroup.AbsolutePosition = Position; @@ -106,7 +105,12 @@ namespace OpenSim.Region.Environment.Scenes part.ScheduleTerseUpdate(); } part.m_undoing = false; + } } + + public UndoState() + { + } } -} \ No newline at end of file +} -- cgit v1.1