Преглед изворни кода

Merge branch 'master' of brain.opensimulator.org:/var/git/opensim

Melanie пре 3 година
родитељ
комит
bd92b2f8ad
100 измењених фајлова са 4058 додато и 4093 уклоњено
  1. 3 0
      CONTRIBUTORS.txt
  2. 34 43
      OpenSim/Addons/Groups/GroupsMessagingModule.cs
  3. 225 74
      OpenSim/Addons/Groups/GroupsModule.cs
  4. 9 2
      OpenSim/Addons/Groups/Hypergrid/GroupsServiceHGConnector.cs
  5. 2 2
      OpenSim/Addons/Groups/Hypergrid/GroupsServiceHGConnectorModule.cs
  6. 1 1
      OpenSim/Addons/Groups/IGroupsServicesConnector.cs
  7. 2 2
      OpenSim/Addons/Groups/Local/GroupsServiceLocalConnectorModule.cs
  8. 2 2
      OpenSim/Addons/Groups/Remote/GroupsServiceRemoteConnector.cs
  9. 2 2
      OpenSim/Addons/Groups/Remote/GroupsServiceRemoteConnectorModule.cs
  10. 10 2
      OpenSim/Addons/Groups/Service/GroupsService.cs
  11. 1 2
      OpenSim/Addons/OfflineIM/Service/OfflineIMService.cs
  12. 37 13
      OpenSim/Capabilities/Caps.cs
  13. 53 14
      OpenSim/Capabilities/CapsHandlers.cs
  14. 0 116
      OpenSim/Capabilities/Handlers/AvatarPickerSearch/AvatarPickerSearchHandler.cs
  15. 160 82
      OpenSim/Capabilities/Handlers/FetchInventory/FetchInvDescHandler.cs
  16. 12 9
      OpenSim/Capabilities/Handlers/FetchInventory/FetchInvDescServerConnector.cs
  17. 65 10
      OpenSim/Capabilities/Handlers/FetchInventory/FetchInventory2Handler.cs
  18. 19 16
      OpenSim/Capabilities/Handlers/FetchInventory/Tests/FetchInventoryDescendents2HandlerTests.cs
  19. 78 67
      OpenSim/Capabilities/Handlers/GetAssets/GetAssetsHandler.cs
  20. 0 117
      OpenSim/Capabilities/Handlers/GetDisplayNames/GetDisplayNamesHandler.cs
  21. 0 69
      OpenSim/Capabilities/Handlers/GetDisplayNames/GetDisplayNamesServerConnector.cs
  22. 1 1
      OpenSim/Capabilities/Handlers/GetMesh/GetMeshServerConnector.cs
  23. 17 13
      OpenSim/Capabilities/Handlers/GetTexture/GetTextureRobustHandler.cs
  24. 1 1
      OpenSim/Capabilities/Handlers/GetTexture/GetTextureServerConnector.cs
  25. 0 171
      OpenSim/Capabilities/Handlers/UploadBakedTexture/UploadBakedTextureHandler.cs
  26. 0 76
      OpenSim/Capabilities/Handlers/UploadBakedTexture/UploadBakedTextureServerConnector.cs
  27. 0 41
      OpenSim/Capabilities/LLSDItemUpdate.cs
  28. 0 51
      OpenSim/Capabilities/LLSDParcelVoiceInfoResponse.cs
  29. 0 50
      OpenSim/Capabilities/LLSDTaskScriptUpdate.cs
  30. 0 57
      OpenSim/Capabilities/LLSDVoiceAccountResponse.cs
  31. 1 1
      OpenSim/ConsoleClient/ConsoleClient.cs
  32. 2 3
      OpenSim/ConsoleClient/Requester.cs
  33. 2 0
      OpenSim/Data/IRegionData.cs
  34. 1 1
      OpenSim/Data/MySQL/MySQLGroupsData.cs
  35. 8 7
      OpenSim/Data/MySQL/MySQLRegionData.cs
  36. 169 345
      OpenSim/Data/MySQL/MySQLSimulationData.cs
  37. 5 0
      OpenSim/Data/MySQL/Resources/EstateStore.migrations
  38. 6 0
      OpenSim/Data/MySQL/Resources/HGTravelStore.migrations
  39. 76 0
      OpenSim/Data/MySQL/Resources/RegionStore.migrations
  40. 1 1
      OpenSim/Data/MySQL/Resources/os_groups_Store.migrations
  41. 23 1
      OpenSim/Data/Null/NullRegionData.cs
  42. 2 2
      OpenSim/Data/PGSQL/PGSQLGroupsData.cs
  43. 21 0
      OpenSim/Data/PGSQL/PGSQLRegionData.cs
  44. 92 500
      OpenSim/Data/PGSQL/PGSQLSimulationData.cs
  45. 6 0
      OpenSim/Data/PGSQL/Resources/EstateStore.migrations
  46. 23 0
      OpenSim/Data/PGSQL/Resources/RegionStore.migrations
  47. 6 0
      OpenSim/Data/SQLite/Resources/EstateStore.migrations
  48. 30 8
      OpenSim/Data/SQLite/Resources/RegionStore.migrations
  49. 33 41
      OpenSim/Data/SQLite/SQLiteEstateData.cs
  50. 100 249
      OpenSim/Data/SQLite/SQLiteSimulationData.cs
  51. 0 4
      OpenSim/Data/Tests/EstateTests.cs
  52. 23 30
      OpenSim/Data/Tests/RegionTests.cs
  53. 53 86
      OpenSim/Framework/AgentCircuitManager.cs
  54. 7 6
      OpenSim/Framework/Animation.cs
  55. 2 1
      OpenSim/Framework/AssetBase.cs
  56. 8 2
      OpenSim/Framework/AvatarAppearance.cs
  57. 104 108
      OpenSim/Framework/ChildAgentDataUpdate.cs
  58. 20 23
      OpenSim/Framework/ClientManager.cs
  59. 25 1
      OpenSim/Framework/Console/CommandConsole.cs
  60. 80 8
      OpenSim/Framework/Console/ConsoleBase.cs
  61. 10 10
      OpenSim/Framework/Console/ConsoleUtil.cs
  62. 38 2
      OpenSim/Framework/Console/LocalConsole.cs
  63. 2 1
      OpenSim/Framework/Console/MockConsole.cs
  64. 3 1
      OpenSim/Framework/Console/OpenSimAppender.cs
  65. 33 7
      OpenSim/Framework/Console/RemoteConsole.cs
  66. 16 3
      OpenSim/Framework/Constants.cs
  67. 0 12
      OpenSim/Framework/DoubleDictionaryThreadAbortSafe.cs
  68. 15 5
      OpenSim/Framework/EstateSettings.cs
  69. 487 0
      OpenSim/Framework/ExpiringCacheOS.cs
  70. 352 0
      OpenSim/Framework/ExpiringKey.cs
  71. 569 0
      OpenSim/Framework/GridInfo.cs
  72. 1 1
      OpenSim/Framework/IAssetCache.cs
  73. 17 88
      OpenSim/Framework/IClientAPI.cs
  74. 2 0
      OpenSim/Framework/ICommandConsole.cs
  75. 4 2
      OpenSim/Framework/IConsole.cs
  76. 2 1
      OpenSim/Framework/ILandChannel.cs
  77. 15 3
      OpenSim/Framework/ILandObject.cs
  78. 9 7
      OpenSim/Framework/IPeople.cs
  79. 37 42
      OpenSim/Framework/InventoryItemBase.cs
  80. 4 3
      OpenSim/Framework/InventoryNodeBase.cs
  81. 166 37
      OpenSim/Framework/LLSDxmlEncode.cs
  82. 33 23
      OpenSim/Framework/LandData.cs
  83. 5 0
      OpenSim/Framework/LandStatReportItem.cs
  84. 0 420
      OpenSim/Framework/MinHeap.cs
  85. 13 13
      OpenSim/Framework/Monitoring/BaseStatsCollector.cs
  86. 1 1
      OpenSim/Framework/Monitoring/ChecksManager.cs
  87. 14 5
      OpenSim/Framework/Monitoring/JobEngine.cs
  88. 10 12
      OpenSim/Framework/Monitoring/SimExtraStatsCollector.cs
  89. 2 2
      OpenSim/Framework/Monitoring/StatsLogger.cs
  90. 4 4
      OpenSim/Framework/Monitoring/StatsManager.cs
  91. 6 9
      OpenSim/Framework/Monitoring/Watchdog.cs
  92. 6 6
      OpenSim/Framework/Monitoring/WorkManager.cs
  93. 3 3
      OpenSim/Framework/PluginManager.cs
  94. 1 1
      OpenSim/Framework/PrimitiveBaseShape.cs
  95. 0 393
      OpenSim/Framework/PriorityQueue.cs
  96. 0 80
      OpenSim/Framework/RegionInfo.cs
  97. 8 41
      OpenSim/Framework/RegionSettings.cs
  98. 56 98
      OpenSim/Framework/RestClient.cs
  99. 448 222
      OpenSim/Framework/SLUtil.cs
  100. 3 1
      OpenSim/Framework/Serialization/ArchiveConstants.cs

+ 3 - 0
CONTRIBUTORS.txt

@@ -185,15 +185,18 @@ what it is today.
 * SpotOn3D
 * Stefan_Boom / stoehr
 * Steven Zielinski (MOSES)
+* Stolen Ruby 
 * Strawberry Fride
 * Talun
 * TechplexEngineer (Blake Bourque)
 * TBG Renfold
+* Terry Ford
 * tglion
 * tlaukkan/Tommil (Tommi S. E. Laukkanen, Bubble Cloud)
 * TomDataWorks
 * TomTheDragon (muckwaddle)
 * tyre
+* uriesk
 * Vegaslon <[email protected]>
 * Vincent Sylvester
 * VikingErik

+ 34 - 43
OpenSim/Addons/Groups/GroupsMessagingModule.cs

@@ -252,7 +252,7 @@ namespace OpenSim.Groups
 
             m_debugEnabled = verbose;
 
-            MainConsole.Instance.Output("{0} verbose logging set to {1}", null, Name, m_debugEnabled);
+            MainConsole.Instance.Output("{0} verbose logging set to {1}", Name, m_debugEnabled);
         }
 
         /// <summary>
@@ -296,13 +296,13 @@ namespace OpenSim.Groups
 
             // In V2 we always only send to online members.
             // Sending to offline members is not an option.
-            string[] t1 = groupMembers.ConvertAll<string>(gmd => gmd.AgentID.ToString()).ToArray();
 
             // We cache in order not to overwhelm the presence service on large grids with many groups.  This does
             // mean that members coming online will not see all group members until after m_usersOnlineCacheExpirySeconds has elapsed.
             // (assuming this is the same across all grid simulators).
             if (!m_usersOnlineCache.TryGetValue(groupID, out onlineAgents))
             {
+                string[] t1 = groupMembers.ConvertAll<string>(gmd => gmd.AgentID.ToString()).ToArray();
                 onlineAgents = m_presenceService.GetAgents(t1);
                 m_usersOnlineCache.Add(groupID, onlineAgents, m_usersOnlineCacheExpirySeconds);
             }
@@ -599,36 +599,34 @@ namespace OpenSim.Groups
                 {
                     if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: Sending chatterbox invite instant message");
 
+                    UUID fromAgent = new UUID(msg.fromAgentID);
                     // Force? open the group session dialog???
                     // and simultanously deliver the message, so we don't need to do a seperate client.SendInstantMessage(msg);
                     IEventQueue eq = activeClient.Scene.RequestModuleInterface<IEventQueue>();
-                    eq.ChatterboxInvitation(
-                        GroupID
-                        , groupInfo.GroupName
-                        , new UUID(msg.fromAgentID)
-                        , msg.message
-                        , AgentID
-                        , msg.fromAgentName
-                        , msg.dialog
-                        , msg.timestamp
-                        , msg.offline == 1
-                        , (int)msg.ParentEstateID
-                        , msg.Position
-                        , 1
-                        , new UUID(msg.imSessionID)
-                        , msg.fromGroup
-                        , OpenMetaverse.Utils.StringToBytes(groupInfo.GroupName)
-                        );
-
-                    eq.ChatterBoxSessionAgentListUpdates(
-                        new UUID(GroupID)
-                        , AgentID
-                        , new UUID(msg.toAgentID)
-                        , false //canVoiceChat
-                        , false //isModerator
-                        , false //text mute
-                        , true // Enter
-                        );
+                    if (eq != null)
+                    {
+                        eq.ChatterboxInvitation(
+                            GroupID
+                            , groupInfo.GroupName
+                            , fromAgent
+                            , msg.message
+                            , AgentID
+                            , msg.fromAgentName
+                            , msg.dialog
+                            , msg.timestamp
+                            , msg.offline == 1
+                            , (int)msg.ParentEstateID
+                            , msg.Position
+                            , 1
+                            , new UUID(msg.imSessionID)
+                            , msg.fromGroup
+                            , OpenMetaverse.Utils.StringToBytes(groupInfo.GroupName)
+                            );
+
+                        var update = new GroupChatListAgentUpdateData(AgentID);
+                        var updates = new List<GroupChatListAgentUpdateData> { update };
+                        eq.ChatterBoxSessionAgentListUpdates(GroupID, new UUID(msg.toAgentID), updates);
+                    }
                 }
             }
         }
@@ -663,15 +661,12 @@ namespace OpenSim.Groups
                     ChatterBoxSessionStartReplyViaCaps(remoteClient, groupInfo.GroupName, GroupID);
 
                     IEventQueue queue = remoteClient.Scene.RequestModuleInterface<IEventQueue>();
-                    queue.ChatterBoxSessionAgentListUpdates(
-                        GroupID
-                        , AgentID
-                        , new UUID(im.toAgentID)
-                        , false //canVoiceChat
-                        , false //isModerator
-                        , false //text mute
-                        , true
-                        );
+                    if (queue != null)
+                    {
+                        var update = new GroupChatListAgentUpdateData(AgentID);
+                        var updates = new List<GroupChatListAgentUpdateData> { update };
+                        queue.ChatterBoxSessionAgentListUpdates(GroupID, remoteClient.AgentId, updates);
+                    }
                 }
             }
 
@@ -713,11 +708,7 @@ namespace OpenSim.Groups
             bodyMap.Add("session_info", sessionMap);
 
             IEventQueue queue = remoteClient.Scene.RequestModuleInterface<IEventQueue>();
-
-            if (queue != null)
-            {
-                queue.Enqueue(queue.BuildEvent("ChatterBoxSessionStartReply", bodyMap), remoteClient.AgentId);
-            }
+            queue?.Enqueue(queue.BuildEvent("ChatterBoxSessionStartReply", bodyMap), remoteClient.AgentId);
         }
 
         private void DebugGridInstantMessage(GridInstantMessage im)

+ 225 - 74
OpenSim/Addons/Groups/GroupsModule.cs

@@ -38,7 +38,7 @@ using OpenSim.Framework;
 using OpenSim.Region.Framework.Interfaces;
 using OpenSim.Region.Framework.Scenes;
 using OpenSim.Services.Interfaces;
-using DirFindFlags = OpenMetaverse.DirectoryManager.DirFindFlags;
+using PermissionMask = OpenSim.Framework.PermissionMask;
 
 namespace OpenSim.Groups
 {
@@ -127,7 +127,7 @@ namespace OpenSim.Groups
 
             m_debugEnabled = verbose;
 
-            MainConsole.Instance.Output("{0} verbose logging set to {1}", null, Name, m_debugEnabled);
+            MainConsole.Instance.Output("{0} verbose logging set to {1}", Name, m_debugEnabled);
         }
 
         public void RegionLoaded(Scene scene)
@@ -233,7 +233,7 @@ namespace OpenSim.Groups
             if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
 
             client.OnAgentDataUpdateRequest += OnAgentDataUpdateRequest;
-            client.OnRequestAvatarProperties += OnRequestAvatarProperties;
+            //client.OnRequestAvatarProperties += OnRequestAvatarProperties;
         }
 
 
@@ -261,7 +261,7 @@ namespace OpenSim.Groups
             // Used for Notices and Group Invites/Accept/Reject
             sp.ControllingClient.OnInstantMessage -= OnInstantMessage;
         }
-
+        /*
         private void OnRequestAvatarProperties(IClientAPI remoteClient, UUID avatarID)
         {
             if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
@@ -269,7 +269,7 @@ namespace OpenSim.Groups
             GroupMembershipData[] avatarGroups = GetProfileListedGroupMemberships(remoteClient, avatarID);
             remoteClient.SendAvatarGroupsReply(avatarID, avatarGroups);
         }
-
+        */
         private void OnClientClosed(UUID AgentId, Scene scene)
         {
             if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
@@ -281,7 +281,7 @@ namespace OpenSim.Groups
             if (client != null)
             {
                 client.OnAgentDataUpdateRequest -= OnAgentDataUpdateRequest;
-                client.OnRequestAvatarProperties -= OnRequestAvatarProperties;
+                //client.OnRequestAvatarProperties -= OnRequestAvatarProperties;
                 // make child possible not called?
                 client.OnUUIDGroupNameRequest -= HandleUUIDGroupNameRequest;
                 client.OnInstantMessage -= OnInstantMessage;
@@ -344,14 +344,24 @@ namespace OpenSim.Groups
 
         private void OnInstantMessage(IClientAPI remoteClient, GridInstantMessage im)
         {
-            if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
+            if (m_debugEnabled)
+                m_log.DebugFormat("[Groups]: OnInstantMessage called");
+
+            if(remoteClient == null || !remoteClient.IsActive || remoteClient.AgentId == UUID.Zero)
+                return;
+
+            Scene scene = (Scene)remoteClient.Scene;
+            if (scene == null)
+                return;
+
+            string remoteAgentIDstr = remoteClient.AgentId.ToString();
 
             //m_log.DebugFormat("[Groups]: IM From {0} to {1} msg {2} type {3}", im.fromAgentID, im.toAgentID, im.message, (InstantMessageDialog)im.dialog);
             // Group invitations
             if ((im.dialog == (byte)InstantMessageDialog.GroupInvitationAccept) || (im.dialog == (byte)InstantMessageDialog.GroupInvitationDecline))
             {
                 UUID inviteID = new UUID(im.imSessionID);
-                GroupInviteInfo inviteInfo = m_groupData.GetAgentToGroupInvite(GetRequestingAgentIDStr(remoteClient), inviteID);
+                GroupInviteInfo inviteInfo = m_groupData.GetAgentToGroupInvite(remoteAgentIDstr, inviteID);
 
                 if (inviteInfo == null)
                 {
@@ -374,7 +384,7 @@ namespace OpenSim.Groups
 
                         // and the sessionid is the role
                         string reason = string.Empty;
-                        if (!m_groupData.AddAgentToGroup(GetRequestingAgentIDStr(remoteClient), invitee.ToString(), inviteInfo.GroupID, inviteInfo.RoleID, string.Empty, out reason))
+                        if (!m_groupData.AddAgentToGroup(remoteAgentIDstr, invitee.ToString(), inviteInfo.GroupID, inviteInfo.RoleID, string.Empty, out reason))
                             remoteClient.SendAgentAlertMessage("Unable to add you to the group: " + reason, false);
                         else
                         {
@@ -401,79 +411,106 @@ namespace OpenSim.Groups
                             }
                         }
 
-                        m_groupData.RemoveAgentToGroupInvite(GetRequestingAgentIDStr(remoteClient), inviteID);
+                        m_groupData.RemoveAgentToGroupInvite(remoteAgentIDstr, inviteID);
                     }
 
                     // Reject
                     if (im.dialog == (byte)InstantMessageDialog.GroupInvitationDecline)
                     {
-                        if (m_debugEnabled) m_log.DebugFormat("[Groups]: Received a reject invite notice.");
-                        m_groupData.RemoveAgentToGroupInvite(GetRequestingAgentIDStr(remoteClient), inviteID);
+                        if (m_debugEnabled)
+                            m_log.DebugFormat("[Groups]: Received a reject invite notice.");
 
-                        m_groupData.RemoveAgentFromGroup(GetRequestingAgentIDStr(remoteClient), inviteInfo.AgentID, inviteInfo.GroupID);
+                        m_groupData.RemoveAgentToGroupInvite(remoteAgentIDstr, inviteID);
+                        m_groupData.RemoveAgentFromGroup(remoteAgentIDstr, inviteInfo.AgentID, inviteInfo.GroupID);
                     }
                 }
             }
 
             // Group notices
-            if ((im.dialog == (byte)InstantMessageDialog.GroupNotice))
+            else if ((im.dialog == (byte)InstantMessageDialog.GroupNotice))
             {
                 if (!m_groupNoticesEnabled)
+                    return;
+
+                UUID GroupID = new UUID(im.toAgentID);
+                GroupMembershipData grpMemberData = m_groupData.GetAgentGroupMembership(remoteAgentIDstr, remoteAgentIDstr, GroupID);
+                if (grpMemberData == null)
                 {
+                    remoteClient.SendAgentAlertMessage("Group membership not found", false);
                     return;
                 }
 
-                UUID GroupID = new UUID(im.toAgentID);
-                if (m_groupData.GetGroupRecord(GetRequestingAgentIDStr(remoteClient), GroupID, null) != null)
+                if ((grpMemberData.GroupPowers & (ulong)GroupPowers.SendNotices) == 0)
                 {
-                    UUID NoticeID = UUID.Random();
-                    string Subject = im.message.Substring(0, im.message.IndexOf('|'));
-                    string Message = im.message.Substring(Subject.Length + 1);
+                    remoteClient.SendAgentAlertMessage("No permission to send notice to group", false);
+                    return;
+                }
 
-                    InventoryItemBase item = null;
-                    bool hasAttachment = false;
+                int index = im.message.IndexOf('|');
+                if (index < 0)
+                    return;
 
-                    if (im.binaryBucket.Length >= 1 && im.binaryBucket[0] > 0)
-                    {
-                        hasAttachment = true;
-                        string binBucket = OpenMetaverse.Utils.BytesToString(im.binaryBucket);
-                        binBucket = binBucket.Remove(0, 14).Trim();
+                string Subject = im.message.Substring(0, index);
+                string Message = im.message.Substring(index + 1);
 
-                        OSD binBucketOSD = OSDParser.DeserializeLLSDXml(binBucket);
-                        if (binBucketOSD is OSDMap)
-                        {
-                            OSDMap binBucketMap = (OSDMap)binBucketOSD;
+                UUID NoticeID = UUID.Random();
 
-                            UUID itemID = binBucketMap["item_id"].AsUUID();
-                            UUID ownerID = binBucketMap["owner_id"].AsUUID();
-                            item = m_sceneList[0].InventoryService.GetItem(ownerID, itemID);
-                        }
-                        else
-                            m_log.DebugFormat("[Groups]: Received OSD with unexpected type: {0}", binBucketOSD.GetType());
+                InventoryItemBase item = null;
+                bool hasAttachment = false;
+
+                if (im.binaryBucket.Length >= 1 && im.binaryBucket[0] > 0)
+                {
+                    UUID itemID = UUID.Zero;
+                    UUID ownerID = UUID.Zero;
+                    try
+                    {
+                        string binBucket = Utils.BytesToString(im.binaryBucket);
+                        binBucket = binBucket.Substring(15); // remove extra LLSD pre header
+
+                        OSDMap binBucketMAP = (OSDMap)OSDParser.DeserializeLLSDXml(binBucket);
+                        itemID = binBucketMAP["item_id"].AsUUID();
+                        ownerID = binBucketMAP["owner_id"].AsUUID();
+                    }
+                    catch
+                    {
+                        m_log.DebugFormat("[GROUPS]: failed to decode group notice bucket");
+                        return;
                     }
 
-                    if (m_groupData.AddGroupNotice(GetRequestingAgentIDStr(remoteClient), GroupID, NoticeID, im.fromAgentName, Subject, Message,
-                        hasAttachment,
-                        (byte)(item == null ? 0 : item.AssetType),
-                        item == null ? null : item.Name,
-                        item == null ? UUID.Zero : item.ID,
-                        item == null ? UUID.Zero.ToString() : item.Owner.ToString()))
+                    if (itemID != UUID.Zero && ownerID != UUID.Zero)
                     {
-                        if (OnNewGroupNotice != null)
+                        item = scene.InventoryService.GetItem(ownerID, itemID);
+                        if(item != null)
                         {
-                            OnNewGroupNotice(GroupID, NoticeID);
+                            if ((item.CurrentPermissions & (uint)(PermissionMask.Transfer | PermissionMask.Copy)) !=
+                                    (uint)(PermissionMask.Transfer | PermissionMask.Copy))
+                            {
+                                remoteClient.SendAgentAlertMessage("Item must be have Copy and Transfer rights to attach to group notice", false);
+                                return;
+                            }
                         }
+                        hasAttachment = true;
+                    }
+                }
+
+                if (m_groupData.AddGroupNotice(remoteAgentIDstr, GroupID, NoticeID, im.fromAgentName, Subject, Message,
+                    hasAttachment,
+                    (byte)(item == null ? 0 : item.AssetType),
+                    item == null ? null : item.Name,
+                    item == null ? UUID.Zero : item.ID,
+                    item == null ? UUID.Zero.ToString() : item.Owner.ToString()))
+                {
+                    OnNewGroupNotice?.Invoke(GroupID, NoticeID);
 
-                        // Send notice out to everyone that wants notices
-                        foreach (GroupMembersData member in m_groupData.GetGroupMembers(GetRequestingAgentIDStr(remoteClient), GroupID))
+                    // Send notice out to everyone that wants notices
+                    foreach (GroupMembersData member in m_groupData.GetGroupMembers(remoteAgentIDstr, GroupID))
+                    {
+                        GridInstantMessage msg = CreateGroupNoticeIM(UUID.Zero, NoticeID, (byte)InstantMessageDialog.GroupNotice);
+                        if (member.AcceptNotices)
                         {
-                            if (member.AcceptNotices)
-                            {
-                                // Build notice IIM, one of reach, because the sending may be async
-                                GridInstantMessage msg = CreateGroupNoticeIM(UUID.Zero, NoticeID, (byte)OpenMetaverse.InstantMessageDialog.GroupNotice);
-                                msg.toAgentID = member.AgentID.Guid;
-                                OutgoingInstantMessage(msg, member.AgentID);
-                            }
+                            // Build notice IIM, one of reach, because the sending may be async
+                            msg.toAgentID = member.AgentID.Guid;
+                            OutgoingInstantMessage(msg, member.AgentID);
                         }
                     }
                 }
@@ -481,41 +518,130 @@ namespace OpenSim.Groups
 
             if (im.dialog == (byte)InstantMessageDialog.GroupNoticeInventoryAccepted)
             {
-                if (im.binaryBucket.Length < 16) // Invalid
+                if (!m_groupNoticesEnabled)
                     return;
 
-                //// 16 bytes are the UUID. Maybe.
-//                UUID folderID = new UUID(im.binaryBucket, 0);
                 UUID noticeID = new UUID(im.imSessionID);
 
-                GroupNoticeInfo notice = m_groupData.GetGroupNotice(remoteClient.AgentId.ToString(), noticeID);
-                if (notice != null)
+                if (m_debugEnabled)
+                    m_log.DebugFormat("[xmlGROUPS]: Accepted notice {0} for {1}", noticeID, remoteClient.AgentId);
+
+                if (noticeID == UUID.Zero)
+                    return;
+
+                UUID folderID = UUID.Zero;
+                try
                 {
-                    UUID giver = new UUID(im.toAgentID);
-                    string tmp = string.Empty;
-                    Util.ParseUniversalUserIdentifier(notice.noticeData.AttachmentOwnerID, out giver, out tmp, out tmp, out tmp, out tmp);
+                    if (im.binaryBucket != null && im.binaryBucket.Length >= 16)
+                        folderID = new UUID(im.binaryBucket, 0);
+                }
+                catch
+                {
+                    m_log.DebugFormat("[xmlGROUPS]: GroupNoticeInventoryAccepted failed to decode target folder");
+                    return;
+                }
 
-                    m_log.DebugFormat("[Groups]: Giving inventory from {0} to {1}", giver, remoteClient.AgentId);
-                    string message;
-                    InventoryItemBase itemCopy = ((Scene)(remoteClient.Scene)).GiveInventoryItem(remoteClient.AgentId,
-                        giver, notice.noticeData.AttachmentItemID, out message);
+                GroupNoticeInfo notice = m_groupData.GetGroupNotice(remoteAgentIDstr, noticeID);
+                if (notice == null)
+                {
+                    if (m_debugEnabled)
+                        m_log.DebugFormat(
+                            "[GROUPS]: Could not find notice {0} for {1} on GroupNoticeInventoryAccepted.",
+                            noticeID, remoteClient.AgentId);
+                    return;
+                }
 
-                    if (itemCopy == null)
-                    {
-                        remoteClient.SendAgentAlertMessage(message, false);
-                        return;
-                    }
+                string tmp;
+                UUID giver = new UUID(im.toAgentID);
+                Util.ParseUniversalUserIdentifier(notice.noticeData.AttachmentOwnerID, out giver, out tmp, out tmp, out tmp, out tmp);
+
+                m_log.DebugFormat("[Groups]: Giving inventory from {0} to {1}", giver, remoteClient.AgentId);
 
-                    remoteClient.SendInventoryItemCreateUpdate(itemCopy, 0);
+                string message = "Could not find group notice attached item";
+                InventoryItemBase itemCopy = scene.GiveInventoryItem(remoteClient.AgentId,
+                    giver, notice.noticeData.AttachmentItemID, folderID, out message);
+
+                if (itemCopy == null)
+                {
+                    remoteClient.SendAgentAlertMessage(message, false);
+                    return;
                 }
+
+                remoteClient.SendInventoryItemCreateUpdate(itemCopy, 0);
             }
 
+            else if (im.dialog == (byte)InstantMessageDialog.GroupNoticeInventoryDeclined)
+            {
+                if (!m_groupNoticesEnabled)
+                    return;
+
+                UUID noticeID = new UUID(im.imSessionID);
+
+                if (m_debugEnabled)
+                    m_log.DebugFormat("[GROUPS]: Accepted notice {0} for {1}", noticeID, remoteAgentIDstr);
+
+                if (noticeID == UUID.Zero)
+                    return;
+
+                UUID remoteAgentID = remoteClient.AgentId;
+
+                GroupNoticeInfo notice = m_groupData.GetGroupNotice(remoteAgentIDstr, noticeID);
+                if (notice == null)
+                {
+                    if (m_debugEnabled)
+                        m_log.DebugFormat(
+                            "[GROUPS]: Could not find notice {0} for {1} on GroupNoticeInventoryAccepted.",
+                            noticeID, remoteClient.AgentId);
+                    return;
+                }
+                string giver = notice.noticeData.AttachmentOwnerID;
+                UUID attachmentUUID = notice.noticeData.AttachmentItemID;
+
+                if (attachmentUUID == null ||
+                        attachmentUUID == UUID.Zero ||
+                        giver == null ||
+                        giver == UUID.Zero.ToString()
+                        )
+                    return;
+
+                if (m_debugEnabled)
+                    m_log.DebugFormat("[xmlGroups]: Deny inventory from {0} to {1}", giver, remoteAgentIDstr);
+
+                string message = String.Empty;
+
+                InventoryItemBase itemCopy = scene.InventoryService.GetItem(remoteAgentID, attachmentUUID);
+                if (itemCopy == null)
+                    return;
+
+                InventoryFolderBase trash = scene.InventoryService.GetFolderForType(remoteAgentID, FolderType.Trash);
+                if (trash == null)
+                {
+                    m_log.DebugFormat("[GROUPS]: failed to find trash folder for {0} ", remoteAgentID);
+                    return;
+                }
+
+                if (itemCopy.Folder == trash.ID || remoteAgentIDstr == notice.noticeData.AttachmentOwnerID)
+                    return;
+
+                itemCopy.Folder = trash.ID;
+                scene.InventoryService.MoveItems(itemCopy.Owner, new List<InventoryItemBase>() { itemCopy });
+
+                if (itemCopy == null)
+                {
+                    remoteClient.SendAgentAlertMessage(message, false);
+                    return;
+                }
+
+                remoteClient.SendInventoryItemCreateUpdate(itemCopy, 0);
+            }
+
+
             // Interop, received special 210 code for ejecting a group member
             // this only works within the comms servers domain, and won't work hypergrid
             // TODO:FIXME: Use a presense server of some kind to find out where the
             // client actually is, and try contacting that region directly to notify them,
             // or provide the notification via xmlrpc update queue
-            if ((im.dialog == 210))
+            else if ((im.dialog == 210))
             {
                 // This is sent from the region that the ejectee was ejected from
                 // if it's being delivered here, then the ejectee is here
@@ -637,6 +763,31 @@ namespace OpenSim.Groups
             return data;
         }
 
+        public ulong GetFullGroupPowers(UUID agentID, UUID groupID)
+        {
+            if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
+
+            List<GroupRolesData> data = m_groupData.GetGroupRoles(agentID.ToString(), groupID);
+            if (data == null || data.Count == 0)
+                return 0;
+
+            ulong powers = 0;
+            for (int i = 0; i < data.Count; ++i)
+            {
+                powers |= data[i].Powers;
+            }
+            return powers;
+        }
+
+        public List<GroupRolesData> GroupRoleDataRequest(UUID agentID, UUID groupID)
+        {
+            if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
+
+            List<GroupRolesData> data = m_groupData.GetGroupRoles(agentID.ToString(), groupID);
+
+            return data;
+        }
+
         public List<GroupRolesData> GroupRoleDataRequest(IClientAPI remoteClient, UUID groupID)
         {
             if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
@@ -949,6 +1100,7 @@ namespace OpenSim.Groups
                     bucket = new byte[19 + name.Length];
                     bucket[0] = 1; // has attachment?
                     bucket[1] = info.noticeData.AttachmentType; // attachment type
+                    info.GroupID.ToBytes(bucket, 2);
                     name.CopyTo(bucket, 18);
                 }
                 else
@@ -959,7 +1111,6 @@ namespace OpenSim.Groups
                     bucket[18] = 0; // null terminated
                 }
 
-                info.GroupID.ToBytes(bucket, 2);
                 msg.binaryBucket = bucket;
             }
             else
@@ -1208,7 +1359,7 @@ namespace OpenSim.Groups
 
         public List<DirGroupsReplyData> FindGroups(IClientAPI remoteClient, string query)
         {
-            return m_groupData.FindGroups(GetRequestingAgentIDStr(remoteClient), query);
+            return m_groupData.FindGroups(remoteClient.AgentId.ToString(), query);
         }
 
         #endregion

+ 9 - 2
OpenSim/Addons/Groups/Hypergrid/GroupsServiceHGConnector.cs

@@ -268,10 +268,17 @@ namespace OpenSim.Groups
             sendData["METHOD"] = method;
 
             string reply = string.Empty;
-            lock (m_Lock)
-                reply = SynchronousRestFormsRequester.MakeRequest("POST",
+            try
+            {
+                lock (m_Lock)
+                    reply = SynchronousRestFormsRequester.MakeRequest("POST",
                          m_ServerURI + "hg-groups",
                          ServerUtils.BuildQueryString(sendData));
+            }
+            catch
+            {
+                return null;
+            }
 
             //m_log.DebugFormat("[XXX]: reply was {0}", reply);
 

+ 2 - 2
OpenSim/Addons/Groups/Hypergrid/GroupsServiceHGConnectorModule.cs

@@ -246,9 +246,9 @@ namespace OpenSim.Groups
             return null;
         }
 
-        public List<DirGroupsReplyData> FindGroups(string RequestingAgentID, string search)
+        public List<DirGroupsReplyData> FindGroups(string RequestingAgentIDstr, string search)
         {
-            return m_LocalGroupsConnector.FindGroups(AgentUUI(RequestingAgentID), search);
+            return m_LocalGroupsConnector.FindGroups(RequestingAgentIDstr, search);
         }
 
         public List<GroupMembersData> GetGroupMembers(string RequestingAgentID, UUID GroupID)

+ 1 - 1
OpenSim/Addons/Groups/IGroupsServicesConnector.cs

@@ -39,7 +39,7 @@ namespace OpenSim.Groups
         bool UpdateGroup(string RequestingAgentID, UUID groupID, string charter, bool showInList, UUID insigniaID, int membershipFee,
             bool openEnrollment, bool allowPublish, bool maturePublish, out string reason);
         ExtendedGroupRecord GetGroupRecord(string RequestingAgentID, UUID GroupID, string GroupName);
-        List<DirGroupsReplyData> FindGroups(string RequestingAgentID, string search);
+        List<DirGroupsReplyData> FindGroups(string RequestingAgentIDstr, string search);
         List<GroupMembersData> GetGroupMembers(string RequestingAgentID, UUID GroupID);
 
         bool AddGroupRole(string RequestingAgentID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers, out string reason);

+ 2 - 2
OpenSim/Addons/Groups/Local/GroupsServiceLocalConnectorModule.cs

@@ -173,9 +173,9 @@ namespace OpenSim.Groups
             return null;
         }
 
-        public List<DirGroupsReplyData> FindGroups(string RequestingAgentID, string search)
+        public List<DirGroupsReplyData> FindGroups(string RequestingAgentIDstr, string search)
         {
-            return m_GroupsService.FindGroups(RequestingAgentID, search);
+            return m_GroupsService.FindGroups(RequestingAgentIDstr, search);
         }
 
         public List<GroupMembersData> GetGroupMembers(string RequestingAgentID, UUID GroupID)

+ 2 - 2
OpenSim/Addons/Groups/Remote/GroupsServiceRemoteConnector.cs

@@ -153,7 +153,7 @@ namespace OpenSim.Groups
             return GroupsDataUtils.GroupRecord((Dictionary<string, object>)ret["RESULT"]);
         }
 
-        public List<DirGroupsReplyData> FindGroups(string RequestingAgentID, string query)
+        public List<DirGroupsReplyData> FindGroups(string RequestingAgentIDstr, string query)
         {
             List<DirGroupsReplyData> hits = new List<DirGroupsReplyData>();
             if (string.IsNullOrEmpty(query))
@@ -161,7 +161,7 @@ namespace OpenSim.Groups
 
             Dictionary<string, object> sendData = new Dictionary<string, object>();
             sendData["Query"] = query;
-            sendData["RequestingAgentID"] = RequestingAgentID;
+            sendData["RequestingAgentID"] = RequestingAgentIDstr;
 
             Dictionary<string, object> ret = MakeRequest("FINDGROUPS", sendData);
 

+ 2 - 2
OpenSim/Addons/Groups/Remote/GroupsServiceRemoteConnectorModule.cs

@@ -192,10 +192,10 @@ namespace OpenSim.Groups
             });
         }
 
-        public List<DirGroupsReplyData> FindGroups(string RequestingAgentID, string search)
+        public List<DirGroupsReplyData> FindGroups(string RequestingAgentIDstr, string search)
         {
             // TODO!
-            return m_GroupsService.FindGroups(RequestingAgentID, search);
+            return m_GroupsService.FindGroups(RequestingAgentIDstr, search);
         }
 
         public bool AddAgentToGroup(string RequestingAgentID, string AgentID, UUID GroupID, UUID RoleID, string token, out string reason)

+ 10 - 2
OpenSim/Addons/Groups/Service/GroupsService.cs

@@ -68,6 +68,7 @@ namespace OpenSim.Groups
             GroupPowers.LandDeed |
             GroupPowers.LandDivideJoin |
             GroupPowers.LandEdit |
+            GroupPowers.AllowEnvironment |
             GroupPowers.LandEjectAndFreeze |
             GroupPowers.LandGardening |
             GroupPowers.LandManageAllowed |
@@ -230,15 +231,22 @@ namespace OpenSim.Groups
                     if (d.Data.ContainsKey("Location") && d.Data["Location"] != string.Empty)
                         continue;
 
+                    int nmembers = m_Database.MemberCount(d.GroupID);
+                    if(nmembers == 0)
+                        continue;
+
                     DirGroupsReplyData g = new DirGroupsReplyData();
-                    g.groupID = d.GroupID;
 
                     if (d.Data.ContainsKey("Name"))
                         g.groupName = d.Data["Name"];
                     else
+                    {
                         m_log.DebugFormat("[Groups]: Key Name not found");
+                        continue;
+                    }
 
-                    g.members = m_Database.MemberCount(d.GroupID);
+                    g.groupID = d.GroupID;
+                    g.members = nmembers;
 
                     groups.Add(g);
                 }

+ 1 - 2
OpenSim/Addons/OfflineIM/Service/OfflineIMService.cs

@@ -110,9 +110,8 @@ namespace OpenSim.OfflineIM
                 {
                     m_serializer.Serialize(writer, im);
                     writer.Flush();
+                    imXml = Util.UTF8NoBomEncoding.GetString(mstream.ToArray());
                 }
-
-                imXml = Util.UTF8NoBomEncoding.GetString(mstream.ToArray());
             }
 
             OfflineIMData data = new OfflineIMData();

+ 37 - 13
OpenSim/Capabilities/Caps.cs

@@ -28,6 +28,7 @@
 using System;
 using System.Collections;
 using System.Collections.Generic;
+using System.Collections.Concurrent;
 using System.IO;
 using System.Reflection;
 using System.Threading;
@@ -49,9 +50,9 @@ namespace OpenSim.Framework.Capabilities
     /// </summary>
     public delegate IClientAPI GetClientDelegate(UUID agentID);
 
-    public class Caps
+    public class Caps : IDisposable
     {
-//        private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
+        private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
 
         private string m_httpListenerHostName;
         private uint m_httpListenPort;
@@ -64,8 +65,8 @@ namespace OpenSim.Framework.Capabilities
 
         private CapsHandlers m_capsHandlers;
 
-        private Dictionary<string, PollServiceEventArgs> m_pollServiceHandlers
-            = new Dictionary<string, PollServiceEventArgs>();
+        private ConcurrentDictionary<string, PollServiceEventArgs> m_pollServiceHandlers
+            = new ConcurrentDictionary<string, PollServiceEventArgs>();
 
         private Dictionary<string, string> m_externalCapsHandlers = new Dictionary<string, string>();
 
@@ -125,7 +126,9 @@ namespace OpenSim.Framework.Capabilities
             None =          0,
             SentSeeds =     1,
 
-            ObjectAnim = 0x10
+            ObjectAnim =    0x100,
+            WLEnv =         0x200,
+            AdvEnv =        0x400
         }
 
         public CapsFlags Flags { get; set;}
@@ -154,10 +157,22 @@ namespace OpenSim.Framework.Capabilities
         }
 
         ~Caps()
+        {
+            Dispose(false);
+        }
+        
+        public void Dispose()
+        {
+            Dispose(true);
+            GC.SuppressFinalize(this);
+        }
+
+        protected void Dispose(bool disposing)
         {
             Flags = CapsFlags.None;
-            if (m_capsActive!= null)
+            if (m_capsActive != null)
             {
+                DeregisterHandlers();
                 m_capsActive.Dispose();
                 m_capsActive = null;
             }
@@ -174,15 +189,27 @@ namespace OpenSim.Framework.Capabilities
             m_capsHandlers[capName] = handler;
         }
 
+        public void RegisterSimpleHandler(string capName, ISimpleStreamHandler handler, bool addToListener = true)
+        {
+            //m_log.DebugFormat("[CAPS]: Registering handler for \"{0}\": path {1}", capName, handler.Path);
+            m_capsHandlers.AddSimpleHandler(capName, handler, addToListener);
+        }
+
         public void RegisterPollHandler(string capName, PollServiceEventArgs pollServiceHandler)
         {
 //            m_log.DebugFormat(
 //                "[CAPS]: Registering handler with name {0}, url {1} for {2}",
 //                capName, pollServiceHandler.Url, m_agentID, m_regionName);
 
-            m_pollServiceHandlers.Add(capName, pollServiceHandler);
+            if(!m_pollServiceHandlers.TryAdd(capName, pollServiceHandler))
+            {
+                m_log.ErrorFormat(
+                    "[CAPS]: Handler with name {0} already registered (ulr {1}, agent {2}, region {3}",
+                    capName, pollServiceHandler.Url, m_agentID, m_regionName);
+                return;
+            }
 
-            m_httpListener.AddPollServiceHTTPHandler(pollServiceHandler.Url, pollServiceHandler);
+            m_httpListener.AddPollServiceHTTPHandler(pollServiceHandler);
 
 //            uint port = (MainServer.Instance == null) ? 0 : MainServer.Instance.Port;
 //            string protocol = "http";
@@ -222,7 +249,7 @@ namespace OpenSim.Framework.Capabilities
 
             foreach (PollServiceEventArgs handler in m_pollServiceHandlers.Values)
             {
-                m_httpListener.RemovePollServiceHTTPHandler("", handler.Url);
+                m_httpListener.RemovePollServiceHTTPHandler(handler.Url);
             }
             m_pollServiceHandlers.Clear();
         }
@@ -263,9 +290,6 @@ namespace OpenSim.Framework.Capabilities
                             port = MainServer.Instance.SSLPort;
                             protocol = "https";
                         }
-    //
-    //            caps.RegisterHandler("FetchInventoryDescendents2", String.Format("{0}://{1}:{2}{3}", protocol, hostName, port, capUrl));
-
                         caps[kvp.Key] = string.Format("{0}://{1}:{2}{3}", protocol, hostName, port, kvp.Value.Url);
                 }
             }
@@ -279,7 +303,7 @@ namespace OpenSim.Framework.Capabilities
                 caps[kvp.Key] = kvp.Value;
             }
 
-            Flags |= CapsFlags.SentSeeds;
+
             return caps;
         }
 

+ 53 - 14
OpenSim/Capabilities/CapsHandlers.cs

@@ -27,6 +27,7 @@
 
 using System.Collections;
 using System.Collections.Generic;
+using System.Collections.Concurrent;
 using OpenSim.Framework.Servers;
 using OpenSim.Framework.Servers.HttpServer;
 
@@ -40,6 +41,7 @@ namespace OpenSim.Framework.Capabilities
     public class CapsHandlers
     {
         private Dictionary<string, IRequestHandler> m_capsHandlers = new Dictionary<string, IRequestHandler>();
+        private ConcurrentDictionary<string, ISimpleStreamHandler> m_capsSimpleHandlers = new ConcurrentDictionary<string, ISimpleStreamHandler>();
         private IHttpServer m_httpListener;
         private string m_httpListenerHostName;
         private uint m_httpListenerPort;
@@ -73,17 +75,35 @@ namespace OpenSim.Framework.Capabilities
         {
             lock (m_capsHandlers)
             {
-                m_httpListener.RemoveStreamHandler("POST", m_capsHandlers[capsName].Path);
-                m_httpListener.RemoveStreamHandler("PUT", m_capsHandlers[capsName].Path);
-                m_httpListener.RemoveStreamHandler("GET", m_capsHandlers[capsName].Path);
-                m_capsHandlers.Remove(capsName);
+                if(m_capsHandlers.ContainsKey(capsName))
+                {
+                    m_httpListener.RemoveStreamHandler("POST", m_capsHandlers[capsName].Path);
+                    m_httpListener.RemoveStreamHandler("PUT", m_capsHandlers[capsName].Path);
+                    m_httpListener.RemoveStreamHandler("GET", m_capsHandlers[capsName].Path);
+                    m_httpListener.RemoveStreamHandler("DELETE", m_capsHandlers[capsName].Path);
+                    m_capsHandlers.Remove(capsName);
+                }
             }
+            if(m_capsSimpleHandlers.TryRemove(capsName, out ISimpleStreamHandler hdr))
+            {
+                m_httpListener.RemoveSimpleStreamHandler(hdr.Path);
+            }
+        }
+
+        public void AddSimpleHandler(string capName, ISimpleStreamHandler handler, bool addToListener = true)
+        {
+            if(ContainsCap(capName))
+                Remove(capName);
+            if(m_capsSimpleHandlers.TryAdd(capName, handler) && addToListener)
+                m_httpListener.AddSimpleStreamHandler(handler);
         }
 
         public bool ContainsCap(string cap)
         {
             lock (m_capsHandlers)
-                return m_capsHandlers.ContainsKey(cap);
+                if (m_capsHandlers.ContainsKey(cap))
+                    return true;
+            return m_capsSimpleHandlers.ContainsKey(cap);
         }
 
         /// <summary>
@@ -110,6 +130,9 @@ namespace OpenSim.Framework.Capabilities
                     if (m_capsHandlers.ContainsKey(idx))
                     {
                         m_httpListener.RemoveStreamHandler("POST", m_capsHandlers[idx].Path);
+                        m_httpListener.RemoveStreamHandler("PUT", m_capsHandlers[idx].Path);
+                        m_httpListener.RemoveStreamHandler("GET", m_capsHandlers[idx].Path);
+                        m_httpListener.RemoveStreamHandler("DELETE", m_capsHandlers[idx].Path);
                         m_capsHandlers.Remove(idx);
                     }
 
@@ -131,8 +154,9 @@ namespace OpenSim.Framework.Capabilities
             {
                 lock (m_capsHandlers)
                 {
-                    string[] __keys = new string[m_capsHandlers.Keys.Count];
+                    string[] __keys = new string[m_capsHandlers.Keys.Count + m_capsSimpleHandlers.Keys.Count];
                     m_capsHandlers.Keys.CopyTo(__keys, 0);
+                    m_capsSimpleHandlers.Keys.CopyTo(__keys, m_capsHandlers.Keys.Count);
                     return __keys;
                 }
             }
@@ -146,24 +170,39 @@ namespace OpenSim.Framework.Capabilities
         public Hashtable GetCapsDetails(bool excludeSeed, List<string> requestedCaps)
         {
             Hashtable caps = new Hashtable();
-            string protocol = "http://";
-
-            if (m_useSSL)
-                protocol = "https://";
 
+            string protocol = m_useSSL ? "https://" : "http://";
             string baseUrl = protocol + m_httpListenerHostName + ":" + m_httpListenerPort.ToString();
 
+            if (requestedCaps == null)
+            {
+                lock (m_capsHandlers)
+                {
+                    foreach (KeyValuePair<string, ISimpleStreamHandler> kvp in m_capsSimpleHandlers)
+                        caps[kvp.Key] = baseUrl + kvp.Value.Path;
+                    foreach (KeyValuePair<string, IRequestHandler> kvp in m_capsHandlers)
+                        caps[kvp.Key] = baseUrl + kvp.Value.Path;
+                }
+                return caps;
+            }
+
             lock (m_capsHandlers)
             {
-                foreach (string capsName in m_capsHandlers.Keys)
+                for(int i = 0; i < requestedCaps.Count; ++i)
                 {
+                    string capsName = requestedCaps[i];
                     if (excludeSeed && "SEED" == capsName)
                         continue;
 
-                    if (requestedCaps != null && !requestedCaps.Contains(capsName))
+                    if (m_capsSimpleHandlers.TryGetValue(capsName, out ISimpleStreamHandler shdr))
+                    {
+                        caps[capsName] = baseUrl + shdr.Path;
                         continue;
-
-                    caps[capsName] = baseUrl + m_capsHandlers[capsName].Path;
+                    }
+                    if (m_capsHandlers.TryGetValue(capsName, out IRequestHandler chdr))
+                    {
+                        caps[capsName] = baseUrl + chdr.Path;
+                    }
                 }
             }
 

+ 0 - 116
OpenSim/Capabilities/Handlers/AvatarPickerSearch/AvatarPickerSearchHandler.cs

@@ -1,116 +0,0 @@
-/*
- * Copyright (c) Contributors, http://opensimulator.org/
- * See CONTRIBUTORS.TXT for a full list of copyright holders.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of the OpenSimulator Project nor the
- *       names of its contributors may be used to endorse or promote products
- *       derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-using System;
-using System.Collections.Generic;
-using System.Collections.Specialized;
-using System.IO;
-using System.Reflection;
-using System.Web;
-using log4net;
-using Nini.Config;
-using OpenMetaverse;
-using OpenSim.Framework;
-using OpenSim.Framework.Capabilities;
-using OpenSim.Framework.Servers;
-using OpenSim.Framework.Servers.HttpServer;
-//using OpenSim.Region.Framework.Interfaces;
-using OpenSim.Services.Interfaces;
-using Caps = OpenSim.Framework.Capabilities.Caps;
-
-namespace OpenSim.Capabilities.Handlers
-{
-    public class AvatarPickerSearchHandler : BaseStreamHandler
-    {
-        private static readonly ILog m_log =
-            LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
-        private IPeople m_PeopleService;
-
-        public AvatarPickerSearchHandler(string path, IPeople peopleService, string name, string description)
-            : base("GET", path, name, description)
-        {
-            m_PeopleService = peopleService;
-        }
-
-        protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
-        {
-            // Try to parse the texture ID from the request URL
-            NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query);
-            string names = query.GetOne("names");
-            string psize = query.GetOne("page_size");
-            string pnumber = query.GetOne("page");
-
-            if (m_PeopleService == null)
-                return FailureResponse(names, (int)System.Net.HttpStatusCode.InternalServerError, httpResponse);
-
-            if (string.IsNullOrEmpty(names) || names.Length < 3)
-                return FailureResponse(names, (int)System.Net.HttpStatusCode.BadRequest, httpResponse);
-
-            m_log.DebugFormat("[AVATAR PICKER SEARCH]: search for {0}", names);
-
-            int page_size = (string.IsNullOrEmpty(psize) ? 500 : Int32.Parse(psize));
-            int page_number = (string.IsNullOrEmpty(pnumber) ? 1 : Int32.Parse(pnumber));
-
-            // Full content request
-            httpResponse.StatusCode = (int)System.Net.HttpStatusCode.OK;
-            //httpResponse.ContentLength = ??;
-            httpResponse.ContentType = "application/llsd+xml";
-
-            List<UserData> users = m_PeopleService.GetUserData(names, page_size, page_number);
-
-            LLSDAvatarPicker osdReply = new LLSDAvatarPicker();
-            osdReply.next_page_url = httpRequest.RawUrl;
-            foreach (UserData u in users)
-                osdReply.agents.Array.Add(ConvertUserData(u));
-
-            string reply = LLSDHelpers.SerialiseLLSDReply(osdReply);
-            return System.Text.Encoding.UTF8.GetBytes(reply);
-        }
-
-        private LLSDPerson ConvertUserData(UserData user)
-        {
-            LLSDPerson p = new LLSDPerson();
-            p.legacy_first_name = user.FirstName;
-            p.legacy_last_name = user.LastName;
-            p.display_name = user.FirstName + " " + user.LastName;
-            if (user.LastName.StartsWith("@"))
-                p.username = user.FirstName.ToLower() + user.LastName.ToLower();
-            else
-                p.username = user.FirstName.ToLower() + "." + user.LastName.ToLower();
-            p.id = user.Id;
-            p.is_display_name_default = false;
-            return p;
-        }
-
-        private byte[] FailureResponse(string names, int statuscode, IOSHttpResponse httpResponse)
-        {
-            m_log.Error("[AVATAR PICKER SEARCH]: Error searching for " + names);
-            httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
-            return System.Text.Encoding.UTF8.GetBytes(string.Empty);
-        }
-    }
-}

+ 160 - 82
OpenSim/Capabilities/Handlers/FetchInventory/FetchInvDescHandler.cs

@@ -28,6 +28,7 @@
 using System;
 using System.Collections;
 using System.Collections.Generic;
+using System.IO;
 using System.Linq;
 using System.Reflection;
 using System.Text;
@@ -37,10 +38,10 @@ using OpenMetaverse;
 using OpenMetaverse.StructuredData;
 using OpenSim.Framework;
 using OpenSim.Framework.Capabilities;
-using OpenSim.Region.Framework.Interfaces;
 using OpenSim.Framework.Servers.HttpServer;
 using OpenSim.Services.Interfaces;
-using Caps = OpenSim.Framework.Capabilities.Caps;
+using OSDMap = OpenMetaverse.StructuredData.OSDMap;
+using OSDArray = OpenMetaverse.StructuredData.OSDArray;
 
 namespace OpenSim.Capabilities.Handlers
 {
@@ -49,10 +50,10 @@ namespace OpenSim.Capabilities.Handlers
         private static readonly ILog m_log =
             LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
 
+        private static byte[] EmptyResponse = Util.UTF8NBGetbytes("<llsd><map><key>folders</key><array /></map></llsd>");
         private IInventoryService m_InventoryService;
         private ILibraryService m_LibraryService;
         private IScene m_Scene;
-//        private object m_fetchLock = new Object();
 
         public FetchInvDescHandler(IInventoryService invService, ILibraryService libService, IScene s)
         {
@@ -61,52 +62,116 @@ namespace OpenSim.Capabilities.Handlers
             m_Scene = s;
         }
 
-        public string FetchInventoryDescendentsRequest(string request, string path, string param, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
+        public void FetchInventoryDescendentsRequest(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse, ExpiringKey<UUID> BadRequests)
         {
             //m_log.DebugFormat("[XXX]: FetchInventoryDescendentsRequest in {0}, {1}", (m_Scene == null) ? "none" : m_Scene.Name, request);
 
-            Hashtable hash = new Hashtable();
+            List<LLSDFetchInventoryDescendents> folders = null;
+            List<UUID> bad_folders = new List<UUID>();
             try
             {
-                hash = (Hashtable)LLSD.LLSDDeserialize(Utils.StringToBytes(request));
+                OSDArray foldersrequested = null;
+                OSD tmp = OSDParser.DeserializeLLSDXml(httpRequest.InputStream);
+                httpRequest.InputStream.Dispose();
+
+                OSDMap map = (OSDMap)tmp;
+                if(map.TryGetValue("folders", out tmp) && tmp is OSDArray)
+                    foldersrequested = tmp as OSDArray;
+
+                if (foldersrequested == null || foldersrequested.Count == 0)
+                {
+                    httpResponse.RawBuffer = EmptyResponse;
+                    return;
+                }
+
+                folders = new List<LLSDFetchInventoryDescendents>(foldersrequested.Count);
+                for (int i = 0; i < foldersrequested.Count; i++)
+                {
+                    OSDMap mfolder = foldersrequested[i] as OSDMap;
+                    UUID id = mfolder["folder_id"].AsUUID();
+                    if(BadRequests.ContainsKey(id))
+                    {
+                        bad_folders.Add(id);
+                    }
+                    else
+                    {
+                        LLSDFetchInventoryDescendents llsdRequest = new LLSDFetchInventoryDescendents();
+                        try
+                        {
+                            llsdRequest.folder_id = id;
+                            llsdRequest.owner_id = mfolder["owner_id"].AsUUID();
+                            llsdRequest.sort_order = mfolder["sort_order"].AsInteger();
+                            llsdRequest.fetch_folders = mfolder["fetch_folders"].AsBoolean();
+                            llsdRequest.fetch_items = mfolder["fetch_items"].AsBoolean();
+                        }
+                        catch (Exception e)
+                        {
+                            m_log.Debug("[WEB FETCH INV DESC HANDLER]: caught exception doing OSD deserialize" + e.Message);
+                            continue;
+                        }
+                        folders.Add(llsdRequest);
+                    }
+                }
+                foldersrequested = null;
+                map.Clear();
+                map = null;
             }
-            catch (LLSD.LLSDParseException e)
+            catch (Exception e)
             {
-                m_log.ErrorFormat("[WEB FETCH INV DESC HANDLER]: Fetch error: {0}{1}" + e.Message, e.StackTrace);
-                m_log.Error("Request: " + request);
+                m_log.ErrorFormat("[FETCH INV DESC]: fail parsing request: {0}", e.Message);
+                httpResponse.RawBuffer = EmptyResponse;
+                return;
             }
 
-            ArrayList foldersrequested = (ArrayList)hash["folders"];
-            hash.Clear();
- 
-            List<LLSDFetchInventoryDescendents> folders = new List<LLSDFetchInventoryDescendents>();
-            for (int i = 0; i < foldersrequested.Count; i++)
+            if (folders == null || folders.Count == 0)
             {
-                Hashtable inventoryhash = (Hashtable)foldersrequested[i];
-                LLSDFetchInventoryDescendents llsdRequest = new LLSDFetchInventoryDescendents();
-
-                try
+                if(bad_folders.Count == 0)
                 {
-                    LLSDHelpers.DeserialiseOSDMap(inventoryhash, llsdRequest);
+                    httpResponse.RawBuffer = EmptyResponse;
+                    return;
                 }
-                catch (Exception e)
+
+                osUTF8 osu = OSUTF8Cached.Acquire();
+                osu.AppendASCII("[WEB FETCH INV DESC HANDLER]: Unable to fetch folders owned by Unknown user:");
+                int limit = 5;
+                int count = 0;
+                foreach (UUID bad in bad_folders)
                 {
-                    m_log.Debug("[WEB FETCH INV DESC HANDLER]: caught exception doing OSD deserialize" + e);
-                    continue;
+                    if (BadRequests.ContainsKey(bad))
+                        continue;
+                    osu.Append((byte)' ');
+                    osu.AppendASCII(bad.ToString());
+                    ++count;
+                    if (--limit < 0)
+                        break;
                 }
 
-                folders.Add(llsdRequest);
-            }
-
-            foldersrequested.Clear();
+                if(count > 0)
+                {
+                    if (limit < 0)
+                        osu.AppendASCII(" ...");
+                    m_log.Warn(osu.ToString());
+                }
 
-            if(folders.Count == 0)
-                return "<llsd><map><key>folders</key><array /></map></llsd>";
+                osu.Clear();
 
-            List<UUID> bad_folders = new List<UUID>();
+                osu.AppendASCII("<llsd><map><key>folders</key><array /></map><map><key>bad_folders</key><array>");
+                foreach (UUID bad in bad_folders)
+                {
+                    osu.AppendASCII("<map><key>folder_id</key><uuid>");
+                    osu.AppendASCII(bad.ToString());
+                    osu.AppendASCII("</uuid><key>error</key><string>Unknown</string></map>");
+                }
+                osu.AppendASCII("</array></map></llsd>");
+                httpResponse.RawBuffer = OSUTF8Cached.GetArrayAndRelease(osu);
+                return;
+            }
 
             int total_folders = 0;
             int total_items = 0;
+
+            UUID requester = folders[0].owner_id;
+
             List<InventoryCollection> invcollSet = Fetch(folders, bad_folders, ref total_folders, ref total_items);
             //m_log.DebugFormat("[XXX]: Got {0} folders from a request of {1}", invcollSet.Count, folders.Count);
 
@@ -119,87 +184,101 @@ namespace OpenSim.Capabilities.Handlers
                                 1024 * total_items +
                                 128 * bad_folders.Count) & 0x7ffff000);
 
-            StringBuilder lastresponse = new StringBuilder(mem);
-            lastresponse.Append("<llsd>");
+            osUTF8 lastresponse = LLSDxmlEncode2.Start(mem);
 
-            if(invcollSetCount > 0)
+            if (invcollSetCount > 0)
             {
-                lastresponse.Append("<map><key>folders</key><array>");
+                lastresponse.AppendASCII("<map><key>folders</key><array>");
                 int i = 0;
                 InventoryCollection thiscoll;
-                for(i = 0; i < invcollSetCount; i++)
+                for (i = 0; i < invcollSetCount; i++)
                 {
                     thiscoll = invcollSet[i];
                     invcollSet[i] = null;
 
-                    LLSDxmlEncode.AddMap(lastresponse);
-                        LLSDxmlEncode.AddElem("agent_id", thiscoll.OwnerID, lastresponse);
-                        LLSDxmlEncode.AddElem("descendents", thiscoll.Descendents, lastresponse);
-                        LLSDxmlEncode.AddElem("folder_id", thiscoll.FolderID, lastresponse);
+                    LLSDxmlEncode2.AddMap(lastresponse);
+                    LLSDxmlEncode2.AddElem_agent_id(thiscoll.OwnerID, lastresponse);
+                    LLSDxmlEncode2.AddElem("descendents", thiscoll.Descendents, lastresponse);
+                    LLSDxmlEncode2.AddElem_folder_id(thiscoll.FolderID, lastresponse);
 
-                        if(thiscoll.Folders == null || thiscoll.Folders.Count == 0)
-                            LLSDxmlEncode.AddEmptyArray("categories", lastresponse);
-                        else
+                    if (thiscoll.Folders == null || thiscoll.Folders.Count == 0)
+                        LLSDxmlEncode2.AddEmptyArray("categories", lastresponse);
+                    else
+                    {
+                        LLSDxmlEncode2.AddArray("categories", lastresponse);
+                        foreach (InventoryFolderBase invFolder in thiscoll.Folders)
                         {
-                            LLSDxmlEncode.AddArray("categories", lastresponse);
-                            foreach (InventoryFolderBase invFolder in thiscoll.Folders)
-                            {
-                                LLSDxmlEncode.AddMap(lastresponse);
-
-                                LLSDxmlEncode.AddElem("folder_id", invFolder.ID, lastresponse);
-                                LLSDxmlEncode.AddElem("parent_id", invFolder.ParentID, lastresponse);
-                                LLSDxmlEncode.AddElem("name", invFolder.Name, lastresponse);
-                                LLSDxmlEncode.AddElem("type", invFolder.Type, lastresponse);
-                                LLSDxmlEncode.AddElem("preferred_type", (int)-1, lastresponse);
-                                LLSDxmlEncode.AddElem("version", invFolder.Version, lastresponse);
-
-                                LLSDxmlEncode.AddEndMap(lastresponse);
-                            }  
-                            LLSDxmlEncode.AddEndArray(lastresponse);
+                            LLSDxmlEncode2.AddMap(lastresponse);
+
+                            LLSDxmlEncode2.AddElem_folder_id(invFolder.ID, lastresponse);
+                            LLSDxmlEncode2.AddElem_parent_id(invFolder.ParentID, lastresponse);
+                            LLSDxmlEncode2.AddElem_name(invFolder.Name, lastresponse);
+                            LLSDxmlEncode2.AddElem("type", invFolder.Type, lastresponse);
+                            LLSDxmlEncode2.AddElem("preferred_type", (int)-1, lastresponse);
+                            LLSDxmlEncode2.AddElem("version", invFolder.Version, lastresponse);
+
+                            LLSDxmlEncode2.AddEndMap(lastresponse);
                         }
+                        LLSDxmlEncode2.AddEndArray(lastresponse);
+                    }
 
-                        if(thiscoll.Items == null || thiscoll.Items.Count == 0)
-                            LLSDxmlEncode.AddEmptyArray("items", lastresponse);
-                        else
+                    if (thiscoll.Items == null || thiscoll.Items.Count == 0)
+                        LLSDxmlEncode2.AddEmptyArray("items", lastresponse);
+                    else
+                    {
+                        LLSDxmlEncode2.AddArray("items", lastresponse);
+                        foreach (InventoryItemBase invItem in thiscoll.Items)
                         {
-                            LLSDxmlEncode.AddArray("items", lastresponse);
-                            foreach (InventoryItemBase invItem in thiscoll.Items)
-                            {
-                                invItem.ToLLSDxml(lastresponse);
-                            }
-
-                            LLSDxmlEncode.AddEndArray(lastresponse);
+                            invItem.ToLLSDxml(lastresponse);
                         }
 
-                        LLSDxmlEncode.AddElem("owner_id", thiscoll.OwnerID, lastresponse);
-                        LLSDxmlEncode.AddElem("version", thiscoll.Version, lastresponse);
+                        LLSDxmlEncode2.AddEndArray(lastresponse);
+                    }
+
+                    LLSDxmlEncode2.AddElem_owner_id(thiscoll.OwnerID, lastresponse);
+                    LLSDxmlEncode2.AddElem("version", thiscoll.Version, lastresponse);
 
-                    LLSDxmlEncode.AddEndMap(lastresponse);
+                    LLSDxmlEncode2.AddEndMap(lastresponse);
                     invcollSet[i] = null;
                 }
-                lastresponse.Append("</array></map>");
+                LLSDxmlEncode2.AddEndArrayAndMap(lastresponse);
                 thiscoll = null;
             }
             else
             {
-                lastresponse.Append("<map><key>folders</key><array /></map>");
+                lastresponse.AppendASCII("<map><key>folders</key><array /></map>");
             }
 
-            //m_log.DebugFormat("[WEB FETCH INV DESC HANDLER]: Bad folders {0}", string.Join(", ", bad_folders));
-            if(bad_folders.Count > 0)
+            if (bad_folders.Count > 0)
             {
-                lastresponse.Append("<map><key>bad_folders</key><array>");
+                lastresponse.AppendASCII("<map><key>bad_folders</key><array>");
+                foreach (UUID bad in bad_folders)
+                {
+                    BadRequests.Add(bad);
+                    lastresponse.AppendASCII("<map><key>folder_id</key><uuid>");
+                    lastresponse.AppendASCII(bad.ToString());
+                    lastresponse.AppendASCII("</uuid><key>error</key><string>Unknown</string></map>");
+                }
+                lastresponse.AppendASCII("</array></map>");
+
+                StringBuilder sb = osStringBuilderCache.Acquire();
+                sb.Append("[WEB FETCH INV DESC HANDLER]: Unable to fetch folders owned by ");
+                sb.Append(requester.ToString());
+                sb.Append(" :");
+                int limit = 9;
                 foreach (UUID bad in bad_folders)
                 {
-                    lastresponse.Append("<map><key>folder_id</key><uuid>");
-                    lastresponse.Append(bad.ToString());
-                    lastresponse.Append("</uuid><key>error</key><string>Unknown</string></map>");
+                    sb.Append(" ");
+                    sb.Append(bad.ToString());
+                    if(--limit < 0)
+                        break;
                 }
-                lastresponse.Append("</array></map>");
+                if(limit < 0)
+                    sb.Append(" ...");
+                m_log.Warn(osStringBuilderCache.GetStringAndRelease(sb));
             }
-            lastresponse.Append("</llsd>");
 
-            return lastresponse.ToString();
+            httpResponse.RawBuffer = LLSDxmlEncode2.EndToBytes(lastresponse);
         }
 
         private void AddLibraryFolders(List<LLSDFetchInventoryDescendents> libFolders, List<InventoryCollection> result, ref int total_folders, ref int total_items)
@@ -354,7 +433,6 @@ namespace OpenSim.Capabilities.Handlers
                 InventoryFolderBase containingFolder = m_InventoryService.GetFolder(freq.owner_id, freq.folder_id);
                 if (containingFolder == null)
                 {
-                    m_log.WarnFormat("[WEB FETCH INV DESC HANDLER]: Unable to fetch folder {0}", freq.folder_id);
                     bad_folders.Add(freq.folder_id);
                     return true;
                 }
@@ -389,7 +467,7 @@ namespace OpenSim.Capabilities.Handlers
                     
                 if (linked != null)
                 {
-                    List<InventoryItemBase> linkedItems = new List<InventoryItemBase>();
+                    List<InventoryItemBase> linkedItems = new List<InventoryItemBase>(linked.Length);
                     // check for broken
                     foreach (InventoryItemBase linkedItem in linked)
                     {

+ 12 - 9
OpenSim/Capabilities/Handlers/FetchInventory/FetchInvDescServerConnector.cs

@@ -29,9 +29,12 @@ using System;
 using Nini.Config;
 using OpenSim.Server.Base;
 using OpenSim.Services.Interfaces;
+using OpenSim.Framework;
 using OpenSim.Framework.Servers.HttpServer;
 using OpenSim.Server.Handlers.Base;
 using OpenMetaverse;
+using OpenMetaverse.StructuredData;
+
 
 namespace OpenSim.Capabilities.Handlers
 {
@@ -67,16 +70,16 @@ namespace OpenSim.Capabilities.Handlers
             m_LibraryService =
                     ServerUtils.LoadPlugin<ILibraryService>(libService, args);
 
+            ExpiringKey<UUID> m_badRequests = new ExpiringKey<UUID>(30000);
+
             FetchInvDescHandler webFetchHandler = new FetchInvDescHandler(m_InventoryService, m_LibraryService, null);
-            IRequestHandler reqHandler
-                = new RestStreamHandler(
-                    "POST",
-                    "/CAPS/WebFetchInvDesc/" /*+ UUID.Random()*/,
-                    webFetchHandler.FetchInventoryDescendentsRequest,
-                    "FetchInvDescendents",
-                    null);
-            server.AddStreamHandler(reqHandler);
-        }
+            ISimpleStreamHandler reqHandler
+                = new SimpleStreamHandler("/CAPS/WebFetchInvDesc/", delegate(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
+                { 
+                    webFetchHandler.FetchInventoryDescendentsRequest(httpRequest, httpResponse, m_badRequests);
+                });
 
+            server.AddSimpleStreamHandler(reqHandler);
+        }
     }
 }

+ 65 - 10
OpenSim/Capabilities/Handlers/FetchInventory/FetchInventory2Handler.cs

@@ -25,12 +25,12 @@
  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
+using System.Net;
 using System.Reflection;
 using System.Text;
 using OpenMetaverse;
 using OpenMetaverse.StructuredData;
 using OpenSim.Framework;
-using OpenSim.Framework.Capabilities;
 using OpenSim.Framework.Servers.HttpServer;
 using OpenSim.Services.Interfaces;
 using OSDArray = OpenMetaverse.StructuredData.OSDArray;
@@ -81,31 +81,86 @@ namespace OpenSim.Capabilities.Handlers
                     items[i++] = m_inventoryService.GetItem(UUID.Zero, id);
             }
 
-            StringBuilder lsl = LLSDxmlEncode.Start(4096);
-            LLSDxmlEncode.AddMap(lsl);
+            osUTF8 lsl = LLSDxmlEncode2.Start(4096);
+            LLSDxmlEncode2.AddMap(lsl);
 
             if(m_agentID == UUID.Zero && items.Length > 0)
-                LLSDxmlEncode.AddElem("agent_id", items[0].Owner, lsl);
+                LLSDxmlEncode2.AddElem("agent_id", items[0].Owner, lsl);
             else
-                LLSDxmlEncode.AddElem("agent_id", m_agentID, lsl);
+                LLSDxmlEncode2.AddElem("agent_id", m_agentID, lsl);
 
             if(items == null || items.Length == 0)
             {
-                LLSDxmlEncode.AddEmptyArray("items", lsl);
+                LLSDxmlEncode2.AddEmptyArray("items", lsl);
             }
             else
             {
-                LLSDxmlEncode.AddArray("items", lsl);
+                LLSDxmlEncode2.AddArray("items", lsl);
                 foreach (InventoryItemBase item in items)
                 {
                     if (item != null)
                         item.ToLLSDxml(lsl, 0xff);
                 }
-                LLSDxmlEncode.AddEndArray(lsl);
+                LLSDxmlEncode2.AddEndArray(lsl);
             }            
 
-            LLSDxmlEncode.AddEndMap(lsl);
-            return LLSDxmlEncode.End(lsl);;
+            LLSDxmlEncode2.AddEndMap(lsl);
+            return LLSDxmlEncode2.End(lsl);
+        }
+
+        public void FetchInventorySimpleRequest(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse, OSDMap requestmap, ExpiringKey<UUID> BadRequests)
+        {
+            //m_log.DebugFormat("[FETCH INVENTORY HANDLER]: Received FetchInventory capability request {0}", request);
+
+            if(BadRequests == null)
+            {
+                httpResponse.StatusCode = (int)HttpStatusCode.NotFound;
+                return;
+            }
+
+            OSDArray itemsRequested = (OSDArray)requestmap["items"];
+
+            UUID[] itemIDs = new UUID[itemsRequested.Count];
+            int i = 0;
+            foreach (OSDMap osdItemId in itemsRequested)
+            {
+                UUID id = osdItemId["item_id"].AsUUID();
+                if(!BadRequests.ContainsKey(id))
+                    itemIDs[i++] = id;
+            }
+
+            InventoryItemBase[] items = null;
+            try
+            {
+                // badrequests still not filled
+                items = m_inventoryService.GetMultipleItems(m_agentID, itemIDs);
+            }
+            catch{ }
+
+            osUTF8 lsl = LLSDxmlEncode2.Start(4096);
+            LLSDxmlEncode2.AddMap(lsl);
+
+            LLSDxmlEncode2.AddElem("agent_id", m_agentID, lsl);
+
+            if (items == null || items.Length == 0)
+            {
+                LLSDxmlEncode2.AddEmptyArray("items", lsl);
+            }
+            else
+            {
+                LLSDxmlEncode2.AddArray("items", lsl);
+                foreach (InventoryItemBase item in items)
+                {
+                    if (item != null)
+                        item.ToLLSDxml(lsl, 0xff);
+                }
+                LLSDxmlEncode2.AddEndArray(lsl);
+            }
+
+            LLSDxmlEncode2.AddEndMap(lsl);
+            httpResponse.RawBuffer = LLSDxmlEncode2.EndToBytes(lsl);
+            httpResponse.StatusCode = (int)HttpStatusCode.OK;
         }
     }
 }
+

+ 19 - 16
OpenSim/Capabilities/Handlers/FetchInventory/Tests/FetchInventoryDescendents2HandlerTests.cs

@@ -28,7 +28,7 @@
 using System;
 using System.Collections.Generic;
 using System.Linq;
-using System.Net;
+using System.IO;
 using System.Text.RegularExpressions;
 using log4net;
 using log4net.Config;
@@ -127,6 +127,19 @@ namespace OpenSim.Capabilities.Handlers.FetchInventory.Tests
             Console.WriteLine("Number of descendents: " + m_rootDescendents);
         }
 
+        private string dorequest(FetchInvDescHandler handler, string request)
+        {
+            TestOSHttpRequest req = new TestOSHttpRequest();
+            TestOSHttpResponse resp = new TestOSHttpResponse();
+            using(ExpiringKey<UUID> bad = new ExpiringKey<UUID>(5000)) // bad but this is test
+            using (MemoryStream ms = new MemoryStream(Utils.StringToBytes(request), false))
+            {
+                req.InputStream = ms;
+                handler.FetchInventoryDescendentsRequest(req, resp, bad);
+            }
+            return Util.UTF8.GetString(resp.RawBuffer);
+        }
+
         [Test]
         public void Test_001_SimpleFolder()
         {
@@ -135,8 +148,6 @@ namespace OpenSim.Capabilities.Handlers.FetchInventory.Tests
             Init();
 
             FetchInvDescHandler handler = new FetchInvDescHandler(m_scene.InventoryService, null, m_scene);
-            TestOSHttpRequest req = new TestOSHttpRequest();
-            TestOSHttpResponse resp = new TestOSHttpResponse();
 
             string request = "<llsd><map><key>folders</key><array><map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>";
             request += m_rootFolderID;
@@ -144,7 +155,7 @@ namespace OpenSim.Capabilities.Handlers.FetchInventory.Tests
             request += m_userID.ToString();
             request += "</uuid><key>sort_order</key><integer>1</integer></map></array></map></llsd>";
 
-            string llsdresponse = handler.FetchInventoryDescendentsRequest(request, "/FETCH", string.Empty, req, resp);
+            string llsdresponse = dorequest(handler, request);
 
             Assert.That(llsdresponse != null, Is.True, "Incorrect null response");
             Assert.That(llsdresponse != string.Empty, Is.True, "Incorrect empty response");
@@ -161,8 +172,6 @@ namespace OpenSim.Capabilities.Handlers.FetchInventory.Tests
             TestHelpers.InMethod();
 
             FetchInvDescHandler handler = new FetchInvDescHandler(m_scene.InventoryService, null, m_scene);
-            TestOSHttpRequest req = new TestOSHttpRequest();
-            TestOSHttpResponse resp = new TestOSHttpResponse();
 
             string request = "<llsd><map><key>folders</key><array>";
             request += "<map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>";
@@ -173,7 +182,7 @@ namespace OpenSim.Capabilities.Handlers.FetchInventory.Tests
             request += "</uuid><key>owner_id</key><uuid>00000000-0000-0000-0000-000000000001</uuid><key>sort_order</key><integer>1</integer></map>";
             request += "</array></map></llsd>";
 
-            string llsdresponse = handler.FetchInventoryDescendentsRequest(request, "/FETCH", string.Empty, req, resp);
+            string llsdresponse = dorequest(handler, request);
             Console.WriteLine(llsdresponse);
 
             string descendents = "descendents</key><integer>" + m_rootDescendents + "</integer>";
@@ -191,14 +200,12 @@ namespace OpenSim.Capabilities.Handlers.FetchInventory.Tests
             TestHelpers.InMethod();
 
             FetchInvDescHandler handler = new FetchInvDescHandler(m_scene.InventoryService, null, m_scene);
-            TestOSHttpRequest req = new TestOSHttpRequest();
-            TestOSHttpResponse resp = new TestOSHttpResponse();
 
             string request = "<llsd><map><key>folders</key><array><map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>";
             request += "f0000000-0000-0000-0000-00000000000f";
             request += "</uuid><key>owner_id</key><uuid>00000000-0000-0000-0000-000000000001</uuid><key>sort_order</key><integer>1</integer></map></array></map></llsd>";
 
-            string llsdresponse = handler.FetchInventoryDescendentsRequest(request, "/FETCH", string.Empty, req, resp);
+            string llsdresponse = dorequest(handler, request);
             Console.WriteLine(llsdresponse);
 
             string descendents = "descendents</key><integer>2</integer>";
@@ -235,8 +242,6 @@ namespace OpenSim.Capabilities.Handlers.FetchInventory.Tests
             TestHelpers.InMethod();
 
             FetchInvDescHandler handler = new FetchInvDescHandler(m_scene.InventoryService, null, m_scene);
-            TestOSHttpRequest req = new TestOSHttpRequest();
-            TestOSHttpResponse resp = new TestOSHttpResponse();
 
             string request = "<llsd><map><key>folders</key><array>";
             request += "<map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>";
@@ -253,7 +258,7 @@ namespace OpenSim.Capabilities.Handlers.FetchInventory.Tests
             request += "</uuid><key>owner_id</key><uuid>00000000-0000-0000-0000-000000000000</uuid><key>sort_order</key><integer>1</integer></map>";
             request += "</array></map></llsd>";
 
-            string llsdresponse = handler.FetchInventoryDescendentsRequest(request, "/FETCH", string.Empty, req, resp);
+            string llsdresponse = dorequest(handler, request);
             Console.WriteLine(llsdresponse);
 
             string root_folder = "<key>folder_id</key><uuid>" + m_rootFolderID + "</uuid>";
@@ -276,14 +281,12 @@ namespace OpenSim.Capabilities.Handlers.FetchInventory.Tests
             Init();
 
             FetchInvDescHandler handler = new FetchInvDescHandler(m_scene.InventoryService, null, m_scene);
-            TestOSHttpRequest req = new TestOSHttpRequest();
-            TestOSHttpResponse resp = new TestOSHttpResponse();
 
             string request = "<llsd><map><key>folders</key><array><map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>";
             request += UUID.Zero;
             request += "</uuid><key>owner_id</key><uuid>00000000-0000-0000-0000-000000000000</uuid><key>sort_order</key><integer>1</integer></map></array></map></llsd>";
 
-            string llsdresponse = handler.FetchInventoryDescendentsRequest(request, "/FETCH", string.Empty, req, resp);
+            string llsdresponse = dorequest(handler, request);
 
             Assert.That(llsdresponse != null, Is.True, "Incorrect null response");
             Assert.That(llsdresponse != string.Empty, Is.True, "Incorrect empty response");

+ 78 - 67
OpenSim/Capabilities/Handlers/GetAssets/GetAssetsHandler.cs

@@ -28,10 +28,8 @@
 using System;
 using System.Collections;
 using System.Collections.Generic;
-using System.Collections.Specialized;
+using System.Net;
 using System.Reflection;
-using System.IO;
-using System.Web;
 using log4net;
 using Nini.Config;
 using OpenMetaverse;
@@ -68,7 +66,8 @@ namespace OpenSim.Capabilities.Handlers
             {"jpeg_id", AssetType.ImageJPEG},
             {"animatn_id", AssetType.Animation},
             {"gesture_id", AssetType.Gesture},
-            {"mesh_id", AssetType.Mesh}
+            {"mesh_id", AssetType.Mesh},
+            {"settings_id", AssetType.Settings}
         };
 
         private IAssetService m_assetService;
@@ -78,82 +77,81 @@ namespace OpenSim.Capabilities.Handlers
             m_assetService = assService;
         }
 
-        public Hashtable Handle(Hashtable request)
+        public void Handle(OSHttpRequest req, OSHttpResponse response, string serviceURL = null)
         {
-            Hashtable responsedata = new Hashtable();
-            responsedata["content_type"] = "text/plain";
-            responsedata["int_bytes"] = 0;
+            response.ContentType = "text/plain";
 
             if (m_assetService == null)
             {
-                responsedata["int_response_code"] = (int)System.Net.HttpStatusCode.ServiceUnavailable;
-                responsedata["str_response_string"] = "The asset service is unavailable";
-                responsedata["keepalive"] = false;
-                return responsedata;
+                response.StatusCode = (int)HttpStatusCode.ServiceUnavailable;
+                response.KeepAlive = false;
+                return;
             }
 
-            responsedata["int_response_code"] = (int)System.Net.HttpStatusCode.BadRequest;
+            response.StatusCode = (int)HttpStatusCode.BadRequest;
 
-            string[] queries = null;
-            if(request.Contains("querystringkeys"))
-                queries = (string[])request["querystringkeys"];
-            
-            if(queries == null || queries.Length == 0)
-                return responsedata;
+            var queries = req.QueryAsDictionary;
+            if(queries.Count == 0)
+                return;
 
-            string query = queries[0];
-            if(!queryTypes.ContainsKey(query))
+            AssetType type = AssetType.Unknown;
+            string assetStr = string.Empty;
+            foreach (KeyValuePair<string,string> kvp in queries)
             {
-                m_log.Warn("[GETASSET]: Unknown type: " + query);
-                return responsedata;
+                if (queryTypes.ContainsKey(kvp.Key))
+                {
+                    type = queryTypes[kvp.Key];
+                    assetStr = kvp.Value;
+                    break;
+                }
             }
 
-            AssetType type = queryTypes[query];
-
-            string assetStr = string.Empty;
-            if (request.ContainsKey(query))
-                assetStr = request[query].ToString();
+            if(type == AssetType.Unknown)
+            {
+                //m_log.Warn("[GETASSET]: Unknown type: " + query);
+                m_log.Warn("[GETASSET]: Unknown type");
+                response.StatusCode = (int)HttpStatusCode.NotFound;
+                return;
+            }
 
             if (String.IsNullOrEmpty(assetStr))
-                return responsedata;
+                return;
 
             UUID assetID = UUID.Zero;
             if(!UUID.TryParse(assetStr, out assetID))
-                return responsedata;
+                return;
 
             AssetBase asset = m_assetService.Get(assetID.ToString());
-            if(asset == null)
+            if (asset == null)
             {
+                if (String.IsNullOrWhiteSpace(serviceURL))
+                {
+                    // m_log.Warn("[GETASSET]: not found: " + query + " " + assetStr);
+                    response.StatusCode = (int)HttpStatusCode.NotFound;
+                    return;
+                }
+
+                string newid = serviceURL + "/" + assetID.ToString();
+                asset = m_assetService.Get(newid);
+                if (asset == null)
+                {
+                    // m_log.Warn("[GETASSET]: not found: " + query + " " + assetStr);
+                    response.StatusCode = (int)HttpStatusCode.NotFound;
+                    return;
+                }
                 // m_log.Warn("[GETASSET]: not found: " + query + " " + assetStr);
-                responsedata["int_response_code"] = (int)System.Net.HttpStatusCode.NotFound;
-                responsedata["str_response_string"] = "Asset not found.";
-                return responsedata;
             }
 
             if (asset.Type != (sbyte)type)
-            {
-                responsedata["str_response_string"] = "Got wrong asset type";
-                return responsedata;
-            }
-
-            if(type == AssetType.Mesh || type == AssetType.Texture)
-                responsedata["throttle"] = true;
+                return;
 
-            responsedata["content_type"] = asset.Metadata.ContentType;
-            responsedata["bin_response_data"] = asset.Data;
-            responsedata["int_bytes"] = asset.Data.Length;
-            responsedata["int_response_code"] = (int)System.Net.HttpStatusCode.OK;
+            int len = asset.Data.Length;
 
-            string range = String.Empty;
-            if (((Hashtable)request["headers"])["range"] != null)
-               range = (string)((Hashtable)request["headers"])["range"];
-            else if (((Hashtable)request["headers"])["Range"] != null)
-                range = (string)((Hashtable)request["headers"])["Range"];
-            else
-                return responsedata; // full asset
-
-            if (String.IsNullOrEmpty(range))
-                return responsedata; // full asset
+            string range = null;
+            if (req.Headers["Range"] != null)
+                range = req.Headers["Range"];
+            else if (req.Headers["range"] != null)
+                range = req.Headers["range"];
 
             // range request
             int start, end;
@@ -163,8 +161,8 @@ namespace OpenSim.Capabilities.Handlers
                 // sending back the last byte instead of an error status
                 if (start >= asset.Data.Length)
                 {
-                    responsedata["str_response_string"] = "This range doesnt exist.";
-                    return responsedata;
+                    response.StatusCode = (int)HttpStatusCode.RequestedRangeNotSatisfiable;
+                    return;
                 }
 
                 if (end == -1)
@@ -173,20 +171,33 @@ namespace OpenSim.Capabilities.Handlers
                     end = Utils.Clamp(end, 0, asset.Data.Length - 1);
 
                 start = Utils.Clamp(start, 0, end);
-                int len = end - start + 1;
+                len = end - start + 1;
 
                 //m_log.Debug("Serving " + start + " to " + end + " of " + texture.Data.Length + " bytes for texture " + texture.ID);
-                Hashtable headers = new Hashtable();
-                headers["Content-Range"] = String.Format("bytes {0}-{1}/{2}", start, end, asset.Data.Length);
-                responsedata["headers"] = headers;
-                responsedata["int_response_code"] = (int)System.Net.HttpStatusCode.PartialContent;
-                responsedata["bin_start"] = start;
-                responsedata["int_bytes"] = len;
-                return responsedata;
+                response.AddHeader("Content-Range", String.Format("bytes {0}-{1}/{2}", start, end, asset.Data.Length));
+                response.StatusCode = (int)HttpStatusCode.PartialContent;
+                response.RawBufferStart = start;
             }
+            else
+                response.StatusCode = (int)HttpStatusCode.OK;
 
-            m_log.Warn("[GETASSETS]: Failed to parse a range, sending full asset: " + assetStr);
-            return responsedata;
+            response.ContentType = asset.Metadata.ContentType;
+            response.RawBuffer = asset.Data;
+            response.RawBufferLen = len;
+            if (type == AssetType.Mesh || type == AssetType.Texture)
+            {
+                if(len > 8196)
+                {
+                    //if(type == AssetType.Texture && ((asset.Flags & AssetFlags.AvatarBake)!= 0))
+                    //    responsedata["prio"] = 1;
+                    //else
+                    response.Priority = 2;
+                }
+                else
+                    response.Priority = 1;
+            }
+            else
+                response.Priority = -1;
         }
     }
 }

+ 0 - 117
OpenSim/Capabilities/Handlers/GetDisplayNames/GetDisplayNamesHandler.cs

@@ -1,117 +0,0 @@
-/*
- * Copyright (c) Contributors, http://opensimulator.org/
- * See CONTRIBUTORS.TXT for a full list of copyright holders.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of the OpenSimulator Project nor the
- *       names of its contributors may be used to endorse or promote products
- *       derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Collections.Specialized;
-using System.Reflection;
-using System.IO;
-using System.Web;
-using log4net;
-using Nini.Config;
-using OpenMetaverse;
-using OpenMetaverse.StructuredData;
-using OpenSim.Framework.Servers.HttpServer;
-using OpenSim.Services.Interfaces;
-using Caps = OpenSim.Framework.Capabilities.Caps;
-using OSDMap = OpenMetaverse.StructuredData.OSDMap;
-using OSDArray = OpenMetaverse.StructuredData.OSDArray;
-
-namespace OpenSim.Capabilities.Handlers
-{
-    public class GetDisplayNamesHandler : BaseStreamHandler
-    {
-        private static readonly ILog m_log =
-            LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
-        protected IUserManagement m_UserManagement;
-
-        public GetDisplayNamesHandler(string path, IUserManagement umService, string name, string description)
-            : base("GET", path, name, description)
-        {
-            m_UserManagement = umService;
-        }
-
-        protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
-        {
-//            m_log.DebugFormat("[GET_DISPLAY_NAMES]: called {0}", httpRequest.Url.Query);
-
-            NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query);
-            string[] ids = query.GetValues("ids");
-
-            if (m_UserManagement == null)
-            {
-                m_log.Error("[GET_DISPLAY_NAMES]: Cannot fetch display names without a user management component");
-                httpResponse.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
-                return new byte[0];
-            }
-
-            Dictionary<UUID,string> names = m_UserManagement.GetUsersNames(ids, UUID.Zero);
-
-            OSDMap osdReply = new OSDMap();
-            OSDArray agents = new OSDArray();
-
-            osdReply["agents"] = agents;
-            foreach (KeyValuePair<UUID,string> kvp in names)
-            {
-                if (string.IsNullOrEmpty(kvp.Value))
-                    continue;
-                if(kvp.Key == UUID.Zero)
-                    continue;
-
-                string[] parts = kvp.Value.Split(new char[] {' '});
-                OSDMap osdname = new OSDMap();
-                if(parts[0] == "Unknown")
-                {
-                    osdname["display_name_next_update"] = OSD.FromDate(DateTime.UtcNow.AddHours(1));
-                    osdname["display_name_expires"] = OSD.FromDate(DateTime.UtcNow.AddHours(2));
-                }
-                else
-                {
-                    osdname["display_name_next_update"] = OSD.FromDate(DateTime.UtcNow.AddDays(8));
-                    osdname["display_name_expires"] = OSD.FromDate(DateTime.UtcNow.AddMonths(1));
-                }
-                osdname["display_name"] = OSD.FromString(kvp.Value);
-                osdname["legacy_first_name"] = parts[0];
-                osdname["legacy_last_name"] = parts[1];
-                osdname["username"] = OSD.FromString(kvp.Value);
-                osdname["id"] = OSD.FromUUID(kvp.Key);
-                osdname["is_display_name_default"] = OSD.FromBoolean(true);
-
-                agents.Add(osdname);
-            }
-
-            // Full content request
-            httpResponse.StatusCode = (int)System.Net.HttpStatusCode.OK;
-            //httpResponse.ContentLength = ??;
-            httpResponse.ContentType = "application/llsd+xml";
-
-            string reply = OSDParser.SerializeLLSDXmlString(osdReply);
-            return System.Text.Encoding.UTF8.GetBytes(reply);
-        }
-    }
-}

+ 0 - 69
OpenSim/Capabilities/Handlers/GetDisplayNames/GetDisplayNamesServerConnector.cs

@@ -1,69 +0,0 @@
-/*
- * Copyright (c) Contributors, http://opensimulator.org/
- * See CONTRIBUTORS.TXT for a full list of copyright holders.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of the OpenSimulator Project nor the
- *       names of its contributors may be used to endorse or promote products
- *       derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-using System;
-using Nini.Config;
-using OpenSim.Server.Base;
-using OpenSim.Services.Interfaces;
-using OpenSim.Framework.Servers.HttpServer;
-using OpenSim.Server.Handlers.Base;
-using OpenMetaverse;
-
-namespace OpenSim.Capabilities.Handlers
-{
-    public class GetDisplayNamesServerConnector : ServiceConnector
-    {
-        private IUserManagement m_UserManagement;
-        private string m_ConfigName = "CapsService";
-
-        public GetDisplayNamesServerConnector(IConfigSource config, IHttpServer server, string configName) :
-                base(config, server, configName)
-        {
-            if (configName != String.Empty)
-                m_ConfigName = configName;
-
-            IConfig serverConfig = config.Configs[m_ConfigName];
-            if (serverConfig == null)
-                throw new Exception(String.Format("No section '{0}' in config file", m_ConfigName));
-
-            string umService = serverConfig.GetString("AssetService", String.Empty);
-
-            if (umService == String.Empty)
-                throw new Exception("No AssetService in config file");
-
-            Object[] args = new Object[] { config };
-            m_UserManagement =
-                    ServerUtils.LoadPlugin<IUserManagement>(umService, args);
-
-            if (m_UserManagement == null)
-                throw new Exception(String.Format("Failed to load UserManagement from {0}; config is {1}", umService, m_ConfigName));
-
-            server.AddStreamHandler(
-                new GetDisplayNamesHandler("/CAPS/agents/", m_UserManagement, "GetDisplayNames", null));
-        }
-    }
-}

+ 1 - 1
OpenSim/Capabilities/Handlers/GetMesh/GetMeshServerConnector.cs

@@ -68,7 +68,7 @@ namespace OpenSim.Capabilities.Handlers
             IRequestHandler reqHandler
                 = new RestHTTPHandler(
                     "GET",
-                    "/CAPS/" + UUID.Random(),
+                    "/" + UUID.Random(),
                     httpMethod => gmeshHandler.ProcessGetMesh(httpMethod, UUID.Zero, null),
                     "GetMesh",
                     null);

+ 17 - 13
OpenSim/Capabilities/Handlers/GetTexture/GetTextureRobustHandler.cs

@@ -32,6 +32,7 @@ using System.Drawing;
 using System.Drawing.Imaging;
 using System.Reflection;
 using System.IO;
+using System.Net;
 using System.Web;
 using log4net;
 using Nini.Config;
@@ -136,8 +137,8 @@ namespace OpenSim.Capabilities.Handlers
             {
                 string textureUrl = m_RedirectURL + "?texture_id=" + textureID.ToString();
                 m_log.Debug("[GETTEXTURE]: Redirecting texture request to " + textureUrl);
-                httpResponse.StatusCode = (int)OSHttpStatusCode.RedirectMovedPermanently;
-                httpResponse.RedirectLocation = textureUrl;
+                httpResponse.StatusCode = (int)HttpStatusCode.Moved;
+                httpResponse.AddHeader("Location:", textureUrl);
                 return true;
             }
 
@@ -238,8 +239,9 @@ namespace OpenSim.Capabilities.Handlers
                         response.ContentLength = len;
                         response.ContentType = texture.Metadata.ContentType;
                         response.AddHeader("Content-Range", String.Format("bytes {0}-{1}/{2}", start, end, texture.Data.Length));
-
-                        response.Body.Write(texture.Data, start, len);
+                        response.RawBuffer = texture.Data;
+                        response.RawBufferStart = start;
+                        response.RawBufferLen = len;
                     }
                 }
                 else
@@ -257,17 +259,19 @@ namespace OpenSim.Capabilities.Handlers
                     response.ContentType = texture.Metadata.ContentType;
                 else
                     response.ContentType = "image/" + format;
-                response.Body.Write(texture.Data, 0, texture.Data.Length);
+                response.RawBuffer = texture.Data;
+                response.RawBufferStart = 0;
+                response.RawBufferLen = texture.Data.Length;
             }
 
-//            if (response.StatusCode < 200 || response.StatusCode > 299)
-//                m_log.WarnFormat(
-//                    "[GETTEXTURE]: For texture {0} requested range {1} responded {2} with content length {3} (actual {4})",
-//                    texture.FullID, range, response.StatusCode, response.ContentLength, texture.Data.Length);
-//            else
-//                m_log.DebugFormat(
-//                    "[GETTEXTURE]: For texture {0} requested range {1} responded {2} with content length {3} (actual {4})",
-//                    texture.FullID, range, response.StatusCode, response.ContentLength, texture.Data.Length);
+            //            if (response.StatusCode < 200 || response.StatusCode > 299)
+            //                m_log.WarnFormat(
+            //                    "[GETTEXTURE]: For texture {0} requested range {1} responded {2} with content length {3} (actual {4})",
+            //                    texture.FullID, range, response.StatusCode, response.ContentLength, texture.Data.Length);
+            //            else
+            //                m_log.DebugFormat(
+            //                    "[GETTEXTURE]: For texture {0} requested range {1} responded {2} with content length {3} (actual {4})",
+            //                    texture.FullID, range, response.StatusCode, response.ContentLength, texture.Data.Length);
         }
 
         /// <summary>

+ 1 - 1
OpenSim/Capabilities/Handlers/GetTexture/GetTextureServerConnector.cs

@@ -66,7 +66,7 @@ namespace OpenSim.Capabilities.Handlers
             string rurl = serverConfig.GetString("GetTextureRedirectURL");
             ;
             server.AddStreamHandler(
-                new GetTextureRobustHandler("/CAPS/GetTexture/", m_AssetService, "GetTexture", null, rurl));
+                new GetTextureRobustHandler("/CAPS/GetTexture", m_AssetService, "GetTexture", null, rurl));
         }
     }
 }

+ 0 - 171
OpenSim/Capabilities/Handlers/UploadBakedTexture/UploadBakedTextureHandler.cs

@@ -1,171 +0,0 @@
-/*
- * Copyright (c) Contributors, http://opensimulator.org/
- * See CONTRIBUTORS.TXT for a full list of copyright holders.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of the OpenSimulator Project nor the
- *       names of its contributors may be used to endorse or promote products
- *       derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-using System;
-using System.Reflection;
-using log4net;
-using OpenMetaverse;
-using OpenSim.Framework;
-using OpenSim.Framework.Capabilities;
-using OpenSim.Framework.Servers.HttpServer;
-using OpenSim.Services.Interfaces;
-using Caps = OpenSim.Framework.Capabilities.Caps;
-
-namespace OpenSim.Capabilities.Handlers
-{
-    public class UploadBakedTextureHandler
-    {
-
-        private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
-
-        private Caps m_HostCapsObj;
-        private IAssetService m_assetService;
-
-        public UploadBakedTextureHandler(Caps caps, IAssetService assetService)
-        {
-            m_HostCapsObj = caps;
-            m_assetService = assetService;
-        }
-
-        /// <summary>
-        /// Handle a request from the client for a Uri to upload a baked texture.
-        /// </summary>
-        /// <param name="request"></param>
-        /// <param name="path"></param>
-        /// <param name="param"></param>
-        /// <param name="httpRequest"></param>
-        /// <param name="httpResponse"></param>
-        /// <returns>The upload response if the request is successful, null otherwise.</returns>
-        public string UploadBakedTexture(
-            string request, string path, string param, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
-        {
-            try
-            {
-                string capsBase = "/CAPS/" + m_HostCapsObj.CapsObjectPath;
-                string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000");
-
-                BakedTextureUploader uploader =
-                    new BakedTextureUploader(capsBase + uploaderPath, m_HostCapsObj.HttpListener, m_HostCapsObj.AgentID);
-                uploader.OnUpLoad += BakedTextureUploaded;
-
-                m_HostCapsObj.HttpListener.AddStreamHandler(
-                    new BinaryStreamHandler(
-                        "POST", capsBase + uploaderPath, uploader.uploaderCaps, "UploadBakedTexture", null));
-
-                string protocol = "http://";
-
-                if (m_HostCapsObj.SSLCaps)
-                    protocol = "https://";
-
-                string uploaderURL = protocol + m_HostCapsObj.HostName + ":" +
-                        m_HostCapsObj.Port.ToString() + capsBase + uploaderPath;
-
-                LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse();
-                uploadResponse.uploader = uploaderURL;
-                uploadResponse.state = "upload";
-
-                return LLSDHelpers.SerialiseLLSDReply(uploadResponse);
-            }
-            catch (Exception e)
-            {
-                m_log.ErrorFormat("[UPLOAD BAKED TEXTURE HANDLER]: {0}{1}", e.Message, e.StackTrace);
-            }
-
-            return null;
-        }
-
-        /// <summary>
-        /// Called when a baked texture has been successfully uploaded by a client.
-        /// </summary>
-        /// <param name="assetID"></param>
-        /// <param name="data"></param>
-        private void BakedTextureUploaded(UUID assetID, byte[] data)
-        {
-            m_log.DebugFormat("[UPLOAD BAKED TEXTURE HANDLER]: Received baked texture {0}", assetID.ToString());
-
-            AssetBase asset;
-            asset = new AssetBase(assetID, "Baked Texture", (sbyte)AssetType.Texture, m_HostCapsObj.AgentID.ToString());
-            asset.Data = data;
-            asset.Temporary = true;
-            asset.Local = true;
-            m_assetService.Store(asset);
-        }
-    }
-
-    class BakedTextureUploader
-    {
-//        private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
-
-        public event Action<UUID, byte[]> OnUpLoad;
-
-        private string uploaderPath = String.Empty;
-        private UUID newAssetID;
-        private IHttpServer httpListener;
-        private UUID AgentId = UUID.Zero;
-
-        public BakedTextureUploader(string path, IHttpServer httpServer, UUID uUID)
-        {
-            newAssetID = UUID.Random();
-            uploaderPath = path;
-            httpListener = httpServer;
-            AgentId = uUID;
-            //                m_log.InfoFormat("[CAPS] baked texture upload starting for {0}",newAssetID);
-        }
-
-        /// <summary>
-        /// Handle raw uploaded baked texture data.
-        /// </summary>
-        /// <param name="data"></param>
-        /// <param name="path"></param>
-        /// <param name="param"></param>
-        /// <returns></returns>
-        public string uploaderCaps(byte[] data, string path, string param)
-        {
-            Action<UUID, byte[]> handlerUpLoad = OnUpLoad;
-
-            // Don't do this asynchronously, otherwise it's possible for the client to send set appearance information
-            // on another thread which might send out avatar updates before the asset has been put into the asset
-            // service.
-            if (handlerUpLoad != null)
-                handlerUpLoad(newAssetID, data);
-
-            string res = String.Empty;
-            LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete();
-            uploadComplete.new_asset = newAssetID.ToString();
-            uploadComplete.new_inventory_item = UUID.Zero;
-            uploadComplete.state = "complete";
-
-            res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
-
-            httpListener.RemoveStreamHandler("POST", uploaderPath);
-
-//            m_log.DebugFormat("[BAKED TEXTURE UPLOADER]: baked texture upload completed for {0}", newAssetID);
-
-            return res;
-        }
-    }
-}

+ 0 - 76
OpenSim/Capabilities/Handlers/UploadBakedTexture/UploadBakedTextureServerConnector.cs

@@ -1,76 +0,0 @@
-/*
- * Copyright (c) Contributors, http://opensimulator.org/
- * See CONTRIBUTORS.TXT for a full list of copyright holders.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of the OpenSimulator Project nor the
- *       names of its contributors may be used to endorse or promote products
- *       derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-using System;
-using Nini.Config;
-using OpenSim.Server.Base;
-using OpenSim.Services.Interfaces;
-using OpenSim.Framework.Servers.HttpServer;
-using OpenSim.Server.Handlers.Base;
-using OpenMetaverse;
-
-namespace OpenSim.Capabilities.Handlers
-{
-    public class UploadBakedTextureServerConnector : ServiceConnector
-    {
-        private IAssetService m_AssetService;
-        private string m_ConfigName = "CapsService";
-
-        public UploadBakedTextureServerConnector(IConfigSource config, IHttpServer server, string configName) :
-                base(config, server, configName)
-        {
-            if (configName != String.Empty)
-                m_ConfigName = configName;
-
-            IConfig serverConfig = config.Configs[m_ConfigName];
-            if (serverConfig == null)
-                throw new Exception(String.Format("No section '{0}' in config file", m_ConfigName));
-
-            string assetService = serverConfig.GetString("AssetService", String.Empty);
-
-            if (assetService == String.Empty)
-                throw new Exception("No AssetService in config file");
-
-            Object[] args = new Object[] { config };
-            m_AssetService =
-                    ServerUtils.LoadPlugin<IAssetService>(assetService, args);
-
-            if (m_AssetService == null)
-                throw new Exception(String.Format("Failed to load AssetService from {0}; config is {1}", assetService, m_ConfigName));
-
-            // NEED TO FIX THIS
-            OpenSim.Framework.Capabilities.Caps caps = new OpenSim.Framework.Capabilities.Caps(server, "", server.Port, "", UUID.Zero, "");
-            server.AddStreamHandler(new RestStreamHandler(
-                        "POST",
-                        "/CAPS/UploadBakedTexture/",
-                        new UploadBakedTextureHandler(caps, m_AssetService).UploadBakedTexture,
-                        "UploadBakedTexture",
-                        "Upload Baked Texture Capability"));
-
-         }
-    }
-}

+ 0 - 41
OpenSim/Capabilities/LLSDItemUpdate.cs

@@ -1,41 +0,0 @@
-/*
- * Copyright (c) Contributors, http://opensimulator.org/
- * See CONTRIBUTORS.TXT for a full list of copyright holders.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of the OpenSimulator Project nor the
- *       names of its contributors may be used to endorse or promote products
- *       derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-using OpenMetaverse;
-
-namespace OpenSim.Framework.Capabilities
-{
-    [OSDMap]
-    public class LLSDItemUpdate
-    {
-        public UUID item_id;
-
-        public LLSDItemUpdate()
-        {
-        }
-    }
-}

+ 0 - 51
OpenSim/Capabilities/LLSDParcelVoiceInfoResponse.cs

@@ -1,51 +0,0 @@
-/*
-* Copyright (c) Contributors, http://opensimulator.org/
-* See CONTRIBUTORS.TXT for a full list of copyright holders.
-*
-* Redistribution and use in source and binary forms, with or without
-* modification, are permitted provided that the following conditions are met:
-*     * Redistributions of source code must retain the above copyright
-*       notice, this list of conditions and the following disclaimer.
-*     * Redistributions in binary form must reproduce the above copyright
-*       notice, this list of conditions and the following disclaimer in the
-*       documentation and/or other materials provided with the distribution.
-*     * Neither the name of the OpenSimulator Project nor the
-*       names of its contributors may be used to endorse or promote products
-*       derived from this software without specific prior written permission.
-*
-* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
-* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
-* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*
-*/
-
-using System.Collections;
-
-namespace OpenSim.Framework.Capabilities
-{
-    [OSDMap]
-    public class LLSDParcelVoiceInfoResponse
-    {
-        public int parcel_local_id;
-        public string region_name;
-        public Hashtable voice_credentials;
-
-        public LLSDParcelVoiceInfoResponse()
-        {
-        }
-
-        public LLSDParcelVoiceInfoResponse(string region, int localID, Hashtable creds)
-        {
-            region_name = region;
-            parcel_local_id = localID;
-            voice_credentials = creds;
-        }
-    }
-}

+ 0 - 50
OpenSim/Capabilities/LLSDTaskScriptUpdate.cs

@@ -1,50 +0,0 @@
-/*
- * Copyright (c) Contributors, http://opensimulator.org/
- * See CONTRIBUTORS.TXT for a full list of copyright holders.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of the OpenSimulator Project nor the
- *       names of its contributors may be used to endorse or promote products
- *       derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-using OpenMetaverse;
-
-namespace OpenSim.Framework.Capabilities
-{
-    [OSDMap]
-    public class LLSDTaskScriptUpdate
-    {
-        /// <summary>
-        /// The item containing the script to update
-        /// </summary>
-        public UUID item_id;
-
-        /// <summary>
-        /// The task containing the script
-        /// </summary>
-        public UUID task_id;
-
-        /// <summary>
-        /// Signals whether the script is currently active
-        /// </summary>
-        public int is_script_running;
-    }
-}

+ 0 - 57
OpenSim/Capabilities/LLSDVoiceAccountResponse.cs

@@ -1,57 +0,0 @@
-/*
-* Copyright (c) Contributors, http://opensimulator.org/
-* See CONTRIBUTORS.TXT for a full list of copyright holders.
-*
-* Redistribution and use in source and binary forms, with or without
-* modification, are permitted provided that the following conditions are met:
-*     * Redistributions of source code must retain the above copyright
-*       notice, this list of conditions and the following disclaimer.
-*     * Redistributions in binary form must reproduce the above copyright
-*       notice, this list of conditions and the following disclaimer in the
-*       documentation and/or other materials provided with the distribution.
-*     * Neither the name of the OpenSimulator Project nor the
-*       names of its contributors may be used to endorse or promote products
-*       derived from this software without specific prior written permission.
-*
-* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
-* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
-* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*
-*/
-
-namespace OpenSim.Framework.Capabilities
-{
-    [OSDMap]
-    public class LLSDVoiceAccountResponse
-    {
-        public string username;
-        public string password;
-        public string voice_sip_uri_hostname;
-        public string voice_account_server_name;
-
-        public LLSDVoiceAccountResponse()
-        {
-        }
-
-        public LLSDVoiceAccountResponse(string user, string pass)
-        {
-            username = user;
-            password = pass;
-        }
-
-        public LLSDVoiceAccountResponse(string user, string pass, string sipUriHost, string accountServer)
-        {
-            username = user;
-            password = pass;
-            voice_sip_uri_hostname = sipUriHost;
-            voice_account_server_name = accountServer;
-        }
-    }
-}

+ 1 - 1
OpenSim/ConsoleClient/ConsoleClient.cs

@@ -80,7 +80,7 @@ namespace OpenSim.ConsoleClient
             while (m_Server.Running)
             {
                 System.Threading.Thread.Sleep(500);
-                // MainConsole.Instance.Prompt();
+                MainConsole.Instance.Prompt();
             }
 
             if (pidFile != String.Empty)

+ 2 - 3
OpenSim/ConsoleClient/Requester.cs

@@ -67,9 +67,8 @@ namespace OpenSim.ConsoleClient
                     {
                         try
                         {
-                            using (Stream s = response.GetResponseStream())
-                                using (StreamReader r = new StreamReader(s))
-                                    reply = r.ReadToEnd();
+                            using (StreamReader r = new StreamReader(response.GetResponseStream()))
+                                reply = r.ReadToEnd();
 
                         }
                         catch (System.InvalidOperationException)

+ 2 - 0
OpenSim/Data/IRegionData.cs

@@ -71,6 +71,8 @@ namespace OpenSim.Data
     {
         RegionData Get(UUID regionID, UUID ScopeID);
         List<RegionData> Get(string regionName, UUID ScopeID);
+        RegionData GetSpecific(string regionName, UUID ScopeID);
+
         RegionData Get(int x, int y, UUID ScopeID);
         List<RegionData> Get(int xStart, int yStart, int xEnd, int yEnd, UUID ScopeID);
 

+ 1 - 1
OpenSim/Data/MySQL/MySQLGroupsData.cs

@@ -90,7 +90,7 @@ namespace OpenSim.Data.MySQL
             else
                 pattern = string.Format("Name LIKE '%{0}%'", MySqlHelper.EscapeString(pattern));
 
-            return m_Groups.Get(string.Format("ShowInList=1 AND ({0}) ORDER BY Name LIMIT 100", pattern));
+            return m_Groups.Get(string.Format("ShowInList=1 AND ({0})", pattern));
         }
 
         public bool DeleteGroup(UUID groupID)

+ 8 - 7
OpenSim/Data/MySQL/MySQLRegionData.cs

@@ -81,17 +81,15 @@ namespace OpenSim.Data.MySQL
             }
         }
 
-        public RegionData Get(int posX, int posY, UUID scopeID)
+        public RegionData GetSpecific(string regionName, UUID scopeID)
         {
-/* fixed size regions
-            string command = "select * from `"+m_Realm+"` where locX = ?posX and locY = ?posY";
+            string command = "select * from `" + m_Realm + "` where regionName = ?regionName";
             if (scopeID != UUID.Zero)
                 command += " and ScopeID = ?scopeID";
 
             using (MySqlCommand cmd = new MySqlCommand(command))
             {
-                cmd.Parameters.AddWithValue("?posX", posX.ToString());
-                cmd.Parameters.AddWithValue("?posY", posY.ToString());
+                cmd.Parameters.AddWithValue("?regionName", regionName);
                 cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
 
                 List<RegionData> ret = RunCommand(cmd);
@@ -100,8 +98,11 @@ namespace OpenSim.Data.MySQL
 
                 return ret[0];
             }
-*/
-            // extend database search for maximum region size area
+
+        }
+
+        public RegionData Get(int posX, int posY, UUID scopeID)
+        {
             string command = "select * from `" + m_Realm + "` where locX between ?startX and ?endX and locY between ?startY and ?endY";
             if (scopeID != UUID.Zero)
                 command += " and ScopeID = ?scopeID";

+ 169 - 345
OpenSim/Data/MySQL/MySQLSimulationData.cs

@@ -29,16 +29,13 @@ using System;
 using System.Collections.Generic;
 using System.Data;
 using System.Drawing;
-using System.IO;
 using System.Reflection;
-using System.Threading;
 using log4net;
 using MySql.Data.MySqlClient;
 using OpenMetaverse;
 using OpenSim.Framework;
 using OpenSim.Region.Framework.Interfaces;
 using OpenSim.Region.Framework.Scenes;
-using OpenSim.Data;
 
 namespace OpenSim.Data.MySQL
 {
@@ -130,10 +127,6 @@ namespace OpenSim.Data.MySQL
 
             // Eligibility check
             //
-            // PrimFlags.Temporary is not used in OpenSim code and cannot
-            // be guaranteed to always be clear. Don't check it.
-//            if ((flags & (uint)PrimFlags.Temporary) != 0)
-//                return;
             if ((flags & (uint)PrimFlags.TemporaryOnRez) != 0)
                 return;
 
@@ -154,16 +147,15 @@ namespace OpenSim.Data.MySQL
                                     "Name, Text, Description, " +
                                     "SitName, TouchName, ObjectFlags, " +
                                     "OwnerMask, NextOwnerMask, GroupMask, " +
-                                    "EveryoneMask, BaseMask, PositionX, " +
-                                    "PositionY, PositionZ, GroupPositionX, " +
-                                    "GroupPositionY, GroupPositionZ, VelocityX, " +
-                                    "VelocityY, VelocityZ, AngularVelocityX, " +
-                                    "AngularVelocityY, AngularVelocityZ, " +
-                                    "AccelerationX, AccelerationY, " +
-                                    "AccelerationZ, RotationX, " +
-                                    "RotationY, RotationZ, " +
-                                    "RotationW, SitTargetOffsetX, " +
-                                    "SitTargetOffsetY, SitTargetOffsetZ, " +
+                                    "EveryoneMask, BaseMask, " +
+                                    "PositionX, PositionY, PositionZ, " +
+                                    "GroupPositionX, GroupPositionY, GroupPositionZ, " +
+                                    "VelocityX, VelocityY, VelocityZ, " +
+                                    "AngularVelocityX, AngularVelocityY, AngularVelocityZ, " +
+                                    "AccelerationX, AccelerationY, AccelerationZ, " +
+                                    "standtargetx, standtargety, standtargetz, " +
+                                    "RotationX, RotationY, RotationZ, RotationW, " +
+                                    "SitTargetOffsetX, SitTargetOffsetY, SitTargetOffsetZ, " +
                                     "SitTargetOrientW, SitTargetOrientX, " +
                                     "SitTargetOrientY, SitTargetOrientZ, " +
                                     "RegionUUID, CreatorID, " +
@@ -173,7 +165,6 @@ namespace OpenSim.Data.MySQL
                                     "PayButton2, PayButton3, " +
                                     "PayButton4, LoopedSound, " +
                                     "LoopedSoundGain, TextureAnimation, " +
-                                    "OmegaX, OmegaY, OmegaZ, " +
                                     "CameraEyeOffsetX, CameraEyeOffsetY, " +
                                     "CameraEyeOffsetZ, CameraAtOffsetX, " +
                                     "CameraAtOffsetY, CameraAtOffsetZ, " +
@@ -189,20 +180,19 @@ namespace OpenSim.Data.MySQL
                                     "AttachedPosY, AttachedPosZ, " +
                                     "PhysicsShapeType, Density, GravityModifier, " +
                                     "Friction, Restitution, Vehicle, PhysInertia, DynAttrs, " +
-                                    "RotationAxisLocks, sopanims" +
+                                    "RotationAxisLocks, sopanims, sitactrange, pseudocrc" + 
                                     ") values (" + "?UUID, " +
                                     "?CreationDate, ?Name, ?Text, " +
                                     "?Description, ?SitName, ?TouchName, " +
                                     "?ObjectFlags, ?OwnerMask, ?NextOwnerMask, " +
                                     "?GroupMask, ?EveryoneMask, ?BaseMask, " +
                                     "?PositionX, ?PositionY, ?PositionZ, " +
-                                    "?GroupPositionX, ?GroupPositionY, " +
-                                    "?GroupPositionZ, ?VelocityX, " +
-                                    "?VelocityY, ?VelocityZ, ?AngularVelocityX, " +
-                                    "?AngularVelocityY, ?AngularVelocityZ, " +
-                                    "?AccelerationX, ?AccelerationY, " +
-                                    "?AccelerationZ, ?RotationX, " +
-                                    "?RotationY, ?RotationZ, " +
+                                    "?GroupPositionX, ?GroupPositionY, ?GroupPositionZ, " +
+                                    "?VelocityX, ?VelocityY, ?VelocityZ, "+
+                                    "?AngularVelocityX, ?AngularVelocityY, ?AngularVelocityZ, " +
+                                    "?AccelerationX, ?AccelerationY, ?AccelerationZ, " +
+                                    "?standtargetx, ?standtargety, ?standtargetz, " +
+                                    "?RotationX, ?RotationY, ?RotationZ, " +
                                     "?RotationW, ?SitTargetOffsetX, " +
                                     "?SitTargetOffsetY, ?SitTargetOffsetZ, " +
                                     "?SitTargetOrientW, ?SitTargetOrientX, " +
@@ -212,7 +202,6 @@ namespace OpenSim.Data.MySQL
                                     "?PayPrice, ?PayButton1, ?PayButton2, " +
                                     "?PayButton3, ?PayButton4, ?LoopedSound, " +
                                     "?LoopedSoundGain, ?TextureAnimation, " +
-                                    "?OmegaX, ?OmegaY, ?OmegaZ, " +
                                     "?CameraEyeOffsetX, ?CameraEyeOffsetY, " +
                                     "?CameraEyeOffsetZ, ?CameraAtOffsetX, " +
                                     "?CameraAtOffsetY, ?CameraAtOffsetZ, " +
@@ -226,7 +215,7 @@ namespace OpenSim.Data.MySQL
                                     "?AttachedPosY, ?AttachedPosZ, " +
                                     "?PhysicsShapeType, ?Density, ?GravityModifier, " +
                                     "?Friction, ?Restitution, ?Vehicle, ?PhysInertia, ?DynAttrs," +
-                                    "?RotationAxisLocks, ?sopanims)";
+                                    "?RotationAxisLocks, ?sopanims, ?sitactrange, ?pseudocrc)";
 
                             FillPrimCommand(cmd, prim, obj.UUID, regionUUID);
 
@@ -830,7 +819,7 @@ namespace OpenSim.Data.MySQL
                             "UserLookAtX, UserLookAtY, UserLookAtZ, " +
                             "AuthbuyerID, OtherCleanTime, Dwell, MediaType, MediaDescription, " +
                             "MediaSize, MediaLoop, ObscureMusic, ObscureMedia, " +
-                            "SeeAVs, AnyAVSounds, GroupAVSounds) values (" +
+                            "SeeAVs, AnyAVSounds, GroupAVSounds, environment) values (" +
                             "?UUID, ?RegionUUID, " +
                             "?LocalLandID, ?Bitmap, ?Name, ?Description, " +
                             "?OwnerUUID, ?IsGroupOwned, ?Area, ?AuctionID, " +
@@ -842,7 +831,7 @@ namespace OpenSim.Data.MySQL
                             "?UserLookAtX, ?UserLookAtY, ?UserLookAtZ, " +
                             "?AuthbuyerID, ?OtherCleanTime, ?Dwell, ?MediaType, ?MediaDescription, "+
                             "CONCAT(?MediaWidth, ',', ?MediaHeight), ?MediaLoop, ?ObscureMusic, ?ObscureMedia, " +
-                            "?SeeAVs, ?AnyAVSounds, ?GroupAVSounds)";
+                            "?SeeAVs, ?AnyAVSounds, ?GroupAVSounds, ?environment)";
 
                         FillLandCommand(cmd, parcel.LandData, parcel.RegionUUID);
 
@@ -869,107 +858,6 @@ namespace OpenSim.Data.MySQL
             }
         }
 
-        public virtual RegionLightShareData LoadRegionWindlightSettings(UUID regionUUID)
-        {
-            RegionLightShareData nWP = new RegionLightShareData();
-            nWP.OnSave += StoreRegionWindlightSettings;
-
-            using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
-            {
-                dbcon.Open();
-
-                string command = "select * from `regionwindlight` where region_id = ?regionID";
-
-                using (MySqlCommand cmd = new MySqlCommand(command))
-                {
-                    cmd.Connection = dbcon;
-
-                    cmd.Parameters.AddWithValue("?regionID", regionUUID.ToString());
-
-                    using(IDataReader result = ExecuteReader(cmd))
-                    {
-                        if(!result.Read())
-                        {
-                            //No result, so store our default windlight profile and return it
-                            nWP.regionID = regionUUID;
-                            //                            StoreRegionWindlightSettings(nWP);
-                            return nWP;
-                        }
-                        else
-                        {
-                            nWP.regionID = DBGuid.FromDB(result["region_id"]);
-                            nWP.waterColor.X = Convert.ToSingle(result["water_color_r"]);
-                            nWP.waterColor.Y = Convert.ToSingle(result["water_color_g"]);
-                            nWP.waterColor.Z = Convert.ToSingle(result["water_color_b"]);
-                            nWP.waterFogDensityExponent = Convert.ToSingle(result["water_fog_density_exponent"]);
-                            nWP.underwaterFogModifier = Convert.ToSingle(result["underwater_fog_modifier"]);
-                            nWP.reflectionWaveletScale.X = Convert.ToSingle(result["reflection_wavelet_scale_1"]);
-                            nWP.reflectionWaveletScale.Y = Convert.ToSingle(result["reflection_wavelet_scale_2"]);
-                            nWP.reflectionWaveletScale.Z = Convert.ToSingle(result["reflection_wavelet_scale_3"]);
-                            nWP.fresnelScale = Convert.ToSingle(result["fresnel_scale"]);
-                            nWP.fresnelOffset = Convert.ToSingle(result["fresnel_offset"]);
-                            nWP.refractScaleAbove = Convert.ToSingle(result["refract_scale_above"]);
-                            nWP.refractScaleBelow = Convert.ToSingle(result["refract_scale_below"]);
-                            nWP.blurMultiplier = Convert.ToSingle(result["blur_multiplier"]);
-                            nWP.bigWaveDirection.X = Convert.ToSingle(result["big_wave_direction_x"]);
-                            nWP.bigWaveDirection.Y = Convert.ToSingle(result["big_wave_direction_y"]);
-                            nWP.littleWaveDirection.X = Convert.ToSingle(result["little_wave_direction_x"]);
-                            nWP.littleWaveDirection.Y = Convert.ToSingle(result["little_wave_direction_y"]);
-                            UUID.TryParse(result["normal_map_texture"].ToString(),out nWP.normalMapTexture);
-                            nWP.horizon.X = Convert.ToSingle(result["horizon_r"]);
-                            nWP.horizon.Y = Convert.ToSingle(result["horizon_g"]);
-                            nWP.horizon.Z = Convert.ToSingle(result["horizon_b"]);
-                            nWP.horizon.W = Convert.ToSingle(result["horizon_i"]);
-                            nWP.hazeHorizon = Convert.ToSingle(result["haze_horizon"]);
-                            nWP.blueDensity.X = Convert.ToSingle(result["blue_density_r"]);
-                            nWP.blueDensity.Y = Convert.ToSingle(result["blue_density_g"]);
-                            nWP.blueDensity.Z = Convert.ToSingle(result["blue_density_b"]);
-                            nWP.blueDensity.W = Convert.ToSingle(result["blue_density_i"]);
-                            nWP.hazeDensity = Convert.ToSingle(result["haze_density"]);
-                            nWP.densityMultiplier = Convert.ToSingle(result["density_multiplier"]);
-                            nWP.distanceMultiplier = Convert.ToSingle(result["distance_multiplier"]);
-                            nWP.maxAltitude = Convert.ToUInt16(result["max_altitude"]);
-                            nWP.sunMoonColor.X = Convert.ToSingle(result["sun_moon_color_r"]);
-                            nWP.sunMoonColor.Y = Convert.ToSingle(result["sun_moon_color_g"]);
-                            nWP.sunMoonColor.Z = Convert.ToSingle(result["sun_moon_color_b"]);
-                            nWP.sunMoonColor.W = Convert.ToSingle(result["sun_moon_color_i"]);
-                            nWP.sunMoonPosition = Convert.ToSingle(result["sun_moon_position"]);
-                            nWP.ambient.X = Convert.ToSingle(result["ambient_r"]);
-                            nWP.ambient.Y = Convert.ToSingle(result["ambient_g"]);
-                            nWP.ambient.Z = Convert.ToSingle(result["ambient_b"]);
-                            nWP.ambient.W = Convert.ToSingle(result["ambient_i"]);
-                            nWP.eastAngle = Convert.ToSingle(result["east_angle"]);
-                            nWP.sunGlowFocus = Convert.ToSingle(result["sun_glow_focus"]);
-                            nWP.sunGlowSize = Convert.ToSingle(result["sun_glow_size"]);
-                            nWP.sceneGamma = Convert.ToSingle(result["scene_gamma"]);
-                            nWP.starBrightness = Convert.ToSingle(result["star_brightness"]);
-                            nWP.cloudColor.X = Convert.ToSingle(result["cloud_color_r"]);
-                            nWP.cloudColor.Y = Convert.ToSingle(result["cloud_color_g"]);
-                            nWP.cloudColor.Z = Convert.ToSingle(result["cloud_color_b"]);
-                            nWP.cloudColor.W = Convert.ToSingle(result["cloud_color_i"]);
-                            nWP.cloudXYDensity.X = Convert.ToSingle(result["cloud_x"]);
-                            nWP.cloudXYDensity.Y = Convert.ToSingle(result["cloud_y"]);
-                            nWP.cloudXYDensity.Z = Convert.ToSingle(result["cloud_density"]);
-                            nWP.cloudCoverage = Convert.ToSingle(result["cloud_coverage"]);
-                            nWP.cloudScale = Convert.ToSingle(result["cloud_scale"]);
-                            nWP.cloudDetailXYDensity.X = Convert.ToSingle(result["cloud_detail_x"]);
-                            nWP.cloudDetailXYDensity.Y = Convert.ToSingle(result["cloud_detail_y"]);
-                            nWP.cloudDetailXYDensity.Z = Convert.ToSingle(result["cloud_detail_density"]);
-                            nWP.cloudScrollX = Convert.ToSingle(result["cloud_scroll_x"]);
-                            nWP.cloudScrollXLock = Convert.ToBoolean(result["cloud_scroll_x_lock"]);
-                            nWP.cloudScrollY = Convert.ToSingle(result["cloud_scroll_y"]);
-                            nWP.cloudScrollYLock = Convert.ToBoolean(result["cloud_scroll_y_lock"]);
-                            nWP.drawClassicClouds = Convert.ToBoolean(result["draw_classic_clouds"]);
-                            nWP.valid = true;
-                        }
-                    }
-                }
-                dbcon.Close();
-            }
-
-            return nWP;
-        }
-
         public virtual RegionSettings LoadRegionSettings(UUID regionUUID)
         {
             RegionSettings rs = null;
@@ -1015,127 +903,6 @@ namespace OpenSim.Data.MySQL
             return rs;
         }
 
-        public virtual void StoreRegionWindlightSettings(RegionLightShareData wl)
-        {
-            using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
-            {
-                dbcon.Open();
-
-                using (MySqlCommand cmd = dbcon.CreateCommand())
-                {
-                    cmd.CommandText = "REPLACE INTO `regionwindlight` (`region_id`, `water_color_r`, `water_color_g`, "
-                            + "`water_color_b`, `water_fog_density_exponent`, `underwater_fog_modifier`, "
-                            + "`reflection_wavelet_scale_1`, `reflection_wavelet_scale_2`, `reflection_wavelet_scale_3`, "
-                            + "`fresnel_scale`, `fresnel_offset`, `refract_scale_above`, `refract_scale_below`, "
-                            + "`blur_multiplier`, `big_wave_direction_x`, `big_wave_direction_y`, `little_wave_direction_x`, "
-                            + "`little_wave_direction_y`, `normal_map_texture`, `horizon_r`, `horizon_g`, `horizon_b`, "
-                            + "`horizon_i`, `haze_horizon`, `blue_density_r`, `blue_density_g`, `blue_density_b`, "
-                            + "`blue_density_i`, `haze_density`, `density_multiplier`, `distance_multiplier`, `max_altitude`, "
-                            + "`sun_moon_color_r`, `sun_moon_color_g`, `sun_moon_color_b`, `sun_moon_color_i`, `sun_moon_position`, "
-                            + "`ambient_r`, `ambient_g`, `ambient_b`, `ambient_i`, `east_angle`, `sun_glow_focus`, `sun_glow_size`, "
-                            + "`scene_gamma`, `star_brightness`, `cloud_color_r`, `cloud_color_g`, `cloud_color_b`, `cloud_color_i`, "
-                            + "`cloud_x`, `cloud_y`, `cloud_density`, `cloud_coverage`, `cloud_scale`, `cloud_detail_x`, "
-                            + "`cloud_detail_y`, `cloud_detail_density`, `cloud_scroll_x`, `cloud_scroll_x_lock`, `cloud_scroll_y`, "
-                            + "`cloud_scroll_y_lock`, `draw_classic_clouds`) VALUES (?region_id, ?water_color_r, "
-                            + "?water_color_g, ?water_color_b, ?water_fog_density_exponent, ?underwater_fog_modifier, ?reflection_wavelet_scale_1, "
-                            + "?reflection_wavelet_scale_2, ?reflection_wavelet_scale_3, ?fresnel_scale, ?fresnel_offset, ?refract_scale_above, "
-                            + "?refract_scale_below, ?blur_multiplier, ?big_wave_direction_x, ?big_wave_direction_y, ?little_wave_direction_x, "
-                            + "?little_wave_direction_y, ?normal_map_texture, ?horizon_r, ?horizon_g, ?horizon_b, ?horizon_i, ?haze_horizon, "
-                            + "?blue_density_r, ?blue_density_g, ?blue_density_b, ?blue_density_i, ?haze_density, ?density_multiplier, "
-                            + "?distance_multiplier, ?max_altitude, ?sun_moon_color_r, ?sun_moon_color_g, ?sun_moon_color_b, "
-                            + "?sun_moon_color_i, ?sun_moon_position, ?ambient_r, ?ambient_g, ?ambient_b, ?ambient_i, ?east_angle, "
-                            + "?sun_glow_focus, ?sun_glow_size, ?scene_gamma, ?star_brightness, ?cloud_color_r, ?cloud_color_g, "
-                            + "?cloud_color_b, ?cloud_color_i, ?cloud_x, ?cloud_y, ?cloud_density, ?cloud_coverage, ?cloud_scale, "
-                            + "?cloud_detail_x, ?cloud_detail_y, ?cloud_detail_density, ?cloud_scroll_x, ?cloud_scroll_x_lock, "
-                            + "?cloud_scroll_y, ?cloud_scroll_y_lock, ?draw_classic_clouds)"
-                            ;
-
-                    cmd.Parameters.AddWithValue("region_id", wl.regionID);
-                    cmd.Parameters.AddWithValue("water_color_r", wl.waterColor.X);
-                    cmd.Parameters.AddWithValue("water_color_g", wl.waterColor.Y);
-                    cmd.Parameters.AddWithValue("water_color_b", wl.waterColor.Z);
-                    cmd.Parameters.AddWithValue("water_fog_density_exponent", wl.waterFogDensityExponent);
-                    cmd.Parameters.AddWithValue("underwater_fog_modifier", wl.underwaterFogModifier);
-                    cmd.Parameters.AddWithValue("reflection_wavelet_scale_1", wl.reflectionWaveletScale.X);
-                    cmd.Parameters.AddWithValue("reflection_wavelet_scale_2", wl.reflectionWaveletScale.Y);
-                    cmd.Parameters.AddWithValue("reflection_wavelet_scale_3", wl.reflectionWaveletScale.Z);
-                    cmd.Parameters.AddWithValue("fresnel_scale", wl.fresnelScale);
-                    cmd.Parameters.AddWithValue("fresnel_offset", wl.fresnelOffset);
-                    cmd.Parameters.AddWithValue("refract_scale_above", wl.refractScaleAbove);
-                    cmd.Parameters.AddWithValue("refract_scale_below", wl.refractScaleBelow);
-                    cmd.Parameters.AddWithValue("blur_multiplier", wl.blurMultiplier);
-                    cmd.Parameters.AddWithValue("big_wave_direction_x", wl.bigWaveDirection.X);
-                    cmd.Parameters.AddWithValue("big_wave_direction_y", wl.bigWaveDirection.Y);
-                    cmd.Parameters.AddWithValue("little_wave_direction_x", wl.littleWaveDirection.X);
-                    cmd.Parameters.AddWithValue("little_wave_direction_y", wl.littleWaveDirection.Y);
-                    cmd.Parameters.AddWithValue("normal_map_texture", wl.normalMapTexture);
-                    cmd.Parameters.AddWithValue("horizon_r", wl.horizon.X);
-                    cmd.Parameters.AddWithValue("horizon_g", wl.horizon.Y);
-                    cmd.Parameters.AddWithValue("horizon_b", wl.horizon.Z);
-                    cmd.Parameters.AddWithValue("horizon_i", wl.horizon.W);
-                    cmd.Parameters.AddWithValue("haze_horizon", wl.hazeHorizon);
-                    cmd.Parameters.AddWithValue("blue_density_r", wl.blueDensity.X);
-                    cmd.Parameters.AddWithValue("blue_density_g", wl.blueDensity.Y);
-                    cmd.Parameters.AddWithValue("blue_density_b", wl.blueDensity.Z);
-                    cmd.Parameters.AddWithValue("blue_density_i", wl.blueDensity.W);
-                    cmd.Parameters.AddWithValue("haze_density", wl.hazeDensity);
-                    cmd.Parameters.AddWithValue("density_multiplier", wl.densityMultiplier);
-                    cmd.Parameters.AddWithValue("distance_multiplier", wl.distanceMultiplier);
-                    cmd.Parameters.AddWithValue("max_altitude", wl.maxAltitude);
-                    cmd.Parameters.AddWithValue("sun_moon_color_r", wl.sunMoonColor.X);
-                    cmd.Parameters.AddWithValue("sun_moon_color_g", wl.sunMoonColor.Y);
-                    cmd.Parameters.AddWithValue("sun_moon_color_b", wl.sunMoonColor.Z);
-                    cmd.Parameters.AddWithValue("sun_moon_color_i", wl.sunMoonColor.W);
-                    cmd.Parameters.AddWithValue("sun_moon_position", wl.sunMoonPosition);
-                    cmd.Parameters.AddWithValue("ambient_r", wl.ambient.X);
-                    cmd.Parameters.AddWithValue("ambient_g", wl.ambient.Y);
-                    cmd.Parameters.AddWithValue("ambient_b", wl.ambient.Z);
-                    cmd.Parameters.AddWithValue("ambient_i", wl.ambient.W);
-                    cmd.Parameters.AddWithValue("east_angle", wl.eastAngle);
-                    cmd.Parameters.AddWithValue("sun_glow_focus", wl.sunGlowFocus);
-                    cmd.Parameters.AddWithValue("sun_glow_size", wl.sunGlowSize);
-                    cmd.Parameters.AddWithValue("scene_gamma", wl.sceneGamma);
-                    cmd.Parameters.AddWithValue("star_brightness", wl.starBrightness);
-                    cmd.Parameters.AddWithValue("cloud_color_r", wl.cloudColor.X);
-                    cmd.Parameters.AddWithValue("cloud_color_g", wl.cloudColor.Y);
-                    cmd.Parameters.AddWithValue("cloud_color_b", wl.cloudColor.Z);
-                    cmd.Parameters.AddWithValue("cloud_color_i", wl.cloudColor.W);
-                    cmd.Parameters.AddWithValue("cloud_x", wl.cloudXYDensity.X);
-                    cmd.Parameters.AddWithValue("cloud_y", wl.cloudXYDensity.Y);
-                    cmd.Parameters.AddWithValue("cloud_density", wl.cloudXYDensity.Z);
-                    cmd.Parameters.AddWithValue("cloud_coverage", wl.cloudCoverage);
-                    cmd.Parameters.AddWithValue("cloud_scale", wl.cloudScale);
-                    cmd.Parameters.AddWithValue("cloud_detail_x", wl.cloudDetailXYDensity.X);
-                    cmd.Parameters.AddWithValue("cloud_detail_y", wl.cloudDetailXYDensity.Y);
-                    cmd.Parameters.AddWithValue("cloud_detail_density", wl.cloudDetailXYDensity.Z);
-                    cmd.Parameters.AddWithValue("cloud_scroll_x", wl.cloudScrollX);
-                    cmd.Parameters.AddWithValue("cloud_scroll_x_lock", wl.cloudScrollXLock);
-                    cmd.Parameters.AddWithValue("cloud_scroll_y", wl.cloudScrollY);
-                    cmd.Parameters.AddWithValue("cloud_scroll_y_lock", wl.cloudScrollYLock);
-                    cmd.Parameters.AddWithValue("draw_classic_clouds", wl.drawClassicClouds);
-
-                    ExecuteNonQuery(cmd);
-                }
-                dbcon.Close();
-            }
-        }
-
-        public virtual void RemoveRegionWindlightSettings(UUID regionID)
-        {
-            using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
-            {
-                dbcon.Open();
-
-                using (MySqlCommand cmd = dbcon.CreateCommand())
-                {
-                    cmd.CommandText = "delete from `regionwindlight` where `region_id`=?regionID";
-                    cmd.Parameters.AddWithValue("?regionID", regionID.ToString());
-                    ExecuteNonQuery(cmd);
-                }
-                dbcon.Close();
-            }
-        }
-
         #region RegionEnvironmentSettings
         public string LoadRegionEnvironmentSettings(UUID regionUUID)
         {
@@ -1231,7 +998,7 @@ namespace OpenSim.Data.MySQL
                          "covenant, covenant_datetime, Sandbox, sunvectorx, sunvectory, " +
                          "sunvectorz, loaded_creation_datetime, " +
                          "loaded_creation_id, map_tile_ID, block_search, casino, " +
-                         "TelehubObject, parcel_tile_ID) " +
+                         "TelehubObject, parcel_tile_ID, cacheID) " +
                           "values (?RegionUUID, ?BlockTerraform, " +
                          "?BlockFly, ?AllowDamage, ?RestrictPushing, " +
                          "?AllowLandResell, ?AllowLandJoinDivide, " +
@@ -1248,7 +1015,7 @@ namespace OpenSim.Data.MySQL
                          "?SunVectorX, ?SunVectorY, ?SunVectorZ, " +
                          "?LoadedCreationDateTime, ?LoadedCreationID, " +
                          "?TerrainImageID, ?block_search, ?casino, " +
-                         "?TelehubObject, ?ParcelImageID)";
+                         "?TelehubObject, ?ParcelImageID, ?cacheID)";
 
                     FillRegionSettingsCommand(cmd, rs);
                     ExecuteNonQuery(cmd);
@@ -1352,49 +1119,57 @@ namespace OpenSim.Data.MySQL
 
             // Vectors
             prim.OffsetPosition = new Vector3(
-                (float)(double)row["PositionX"],
-                (float)(double)row["PositionY"],
-                (float)(double)row["PositionZ"]
+                (float)row["PositionX"],
+                (float)row["PositionY"],
+                (float)row["PositionZ"]
                 );
             prim.GroupPosition = new Vector3(
-                (float)(double)row["GroupPositionX"],
-                (float)(double)row["GroupPositionY"],
-                (float)(double)row["GroupPositionZ"]
+                (float)row["GroupPositionX"],
+                (float)row["GroupPositionY"],
+                (float)row["GroupPositionZ"]
                 );
             prim.Velocity = new Vector3(
-                (float)(double)row["VelocityX"],
-                (float)(double)row["VelocityY"],
-                (float)(double)row["VelocityZ"]
+                (float)row["VelocityX"],
+                (float)row["VelocityY"],
+                (float)row["VelocityZ"]
                 );
             prim.AngularVelocity = new Vector3(
-                (float)(double)row["AngularVelocityX"],
-                (float)(double)row["AngularVelocityY"],
-                (float)(double)row["AngularVelocityZ"]
+                (float)row["AngularVelocityX"],
+                (float)row["AngularVelocityY"],
+                (float)row["AngularVelocityZ"]
                 );
             prim.Acceleration = new Vector3(
-                (float)(double)row["AccelerationX"],
-                (float)(double)row["AccelerationY"],
-                (float)(double)row["AccelerationZ"]
+                (float)row["AccelerationX"],
+                (float)row["AccelerationY"],
+                (float)row["AccelerationZ"]
                 );
             // quaternions
             prim.RotationOffset = new Quaternion(
-                (float)(double)row["RotationX"],
-                (float)(double)row["RotationY"],
-                (float)(double)row["RotationZ"],
-                (float)(double)row["RotationW"]
+                (float)row["RotationX"],
+                (float)row["RotationY"],
+                (float)row["RotationZ"],
+                (float)row["RotationW"]
                 );
             prim.SitTargetPositionLL = new Vector3(
-                (float)(double)row["SitTargetOffsetX"],
-                (float)(double)row["SitTargetOffsetY"],
-                (float)(double)row["SitTargetOffsetZ"]
+                (float)row["SitTargetOffsetX"],
+                (float)row["SitTargetOffsetY"],
+                (float)row["SitTargetOffsetZ"]
                 );
             prim.SitTargetOrientationLL = new Quaternion(
-                (float)(double)row["SitTargetOrientX"],
-                (float)(double)row["SitTargetOrientY"],
-                (float)(double)row["SitTargetOrientZ"],
-                (float)(double)row["SitTargetOrientW"]
+                (float)row["SitTargetOrientX"],
+                (float)row["SitTargetOrientY"],
+                (float)row["SitTargetOrientZ"],
+                (float)row["SitTargetOrientW"]
+                );
+
+            prim.StandOffset = new Vector3(
+                (float)row["standtargetx"],
+                (float)row["standtargety"],
+                (float)row["standtargetz"]
                 );
 
+            prim.SitActiveRange = (float)row["sitactrange"];
+
             prim.PayPrice[0] = (int)row["PayPrice"];
             prim.PayPrice[1] = (int)row["PayButton1"];
             prim.PayPrice[2] = (int)row["PayButton2"];
@@ -1402,7 +1177,7 @@ namespace OpenSim.Data.MySQL
             prim.PayPrice[4] = (int)row["PayButton4"];
 
             prim.Sound = DBGuid.FromDB(row["LoopedSound"].ToString());
-            prim.SoundGain = (float)(double)row["LoopedSoundGain"];
+            prim.SoundGain = (float)row["LoopedSoundGain"];
             if (prim.Sound != UUID.Zero)
                 prim.SoundFlags = 1; // If it's persisted at all, it's looped
             else
@@ -1413,22 +1188,16 @@ namespace OpenSim.Data.MySQL
             if (!(row["ParticleSystem"] is DBNull))
                 prim.ParticleSystem = (byte[])row["ParticleSystem"];
 
-            prim.AngularVelocity = new Vector3(
-                (float)(double)row["OmegaX"],
-                (float)(double)row["OmegaY"],
-                (float)(double)row["OmegaZ"]
-                );
-
             prim.SetCameraEyeOffset(new Vector3(
-                (float)(double)row["CameraEyeOffsetX"],
-                (float)(double)row["CameraEyeOffsetY"],
-                (float)(double)row["CameraEyeOffsetZ"]
+                (float)row["CameraEyeOffsetX"],
+                (float)row["CameraEyeOffsetY"],
+                (float)row["CameraEyeOffsetZ"]
                 ));
 
             prim.SetCameraAtOffset(new Vector3(
-                (float)(double)row["CameraAtOffsetX"],
-                (float)(double)row["CameraAtOffsetY"],
-                (float)(double)row["CameraAtOffsetZ"]
+                (float)row["CameraAtOffsetX"],
+                (float)row["CameraAtOffsetY"],
+                (float)row["CameraAtOffsetZ"]
                 ));
 
             prim.SetForceMouselook((sbyte)row["ForceMouselook"] != 0);
@@ -1457,9 +1226,9 @@ namespace OpenSim.Data.MySQL
             if (!(row["AttachedPosX"] is System.DBNull))
             {
                 prim.AttachedPos = new Vector3(
-                    (float)(double)row["AttachedPosX"],
-                    (float)(double)row["AttachedPosY"],
-                    (float)(double)row["AttachedPosZ"]
+                    (float)row["AttachedPosX"],
+                    (float)row["AttachedPosY"],
+                    (float)row["AttachedPosZ"]
                     );
             }
 
@@ -1482,10 +1251,10 @@ namespace OpenSim.Data.MySQL
             }
 
             prim.PhysicsShapeType = (byte)Convert.ToInt32(row["PhysicsShapeType"].ToString());
-            prim.Density = (float)(double)row["Density"];
-            prim.GravityModifier = (float)(double)row["GravityModifier"];
-            prim.Friction = (float)(double)row["Friction"];
-            prim.Restitution = (float)(double)row["Restitution"];
+            prim.Density = (float)row["Density"];
+            prim.GravityModifier = (float)row["GravityModifier"];
+            prim.Friction = (float)row["Friction"];
+            prim.Restitution = (float)row["Restitution"];
             prim.RotationAxisLocks = (byte)Convert.ToInt32(row["RotationAxisLocks"].ToString());
 
             SOPVehicle vehicle = null;
@@ -1515,6 +1284,12 @@ namespace OpenSim.Data.MySQL
                 prim.Animations = null;
             }
 
+            prim.SitActiveRange = (float)row["sitactrange"];
+
+            int pseudocrc = (int)row["pseudocrc"];
+            if(pseudocrc != 0)
+                prim.PseudoCRC = pseudocrc;
+
             return prim;
         }
 
@@ -1619,6 +1394,10 @@ namespace OpenSim.Data.MySQL
             newSettings.GodBlockSearch = Convert.ToBoolean(row["block_search"]);
             newSettings.Casino = Convert.ToBoolean(row["casino"]);
 
+            if (!(row["cacheID"] is DBNull))
+                newSettings.CacheID = DBGuid.FromDB(row["cacheID"]);
+
+
             return newSettings;
         }
 
@@ -1702,6 +1481,34 @@ namespace OpenSim.Data.MySQL
             if (!(row["GroupAVSounds"] is System.DBNull))
                 newData.GroupAVSounds = Convert.ToInt32(row["GroupAVSounds"]) != 0 ? true : false;
 
+            if (row["environment"] is DBNull)
+            {
+                newData.Environment = null;
+                newData.EnvironmentVersion = -1;
+            }
+            else
+            {
+                string env = (string)row["environment"];
+                if(string.IsNullOrEmpty(env))
+                {
+                    newData.Environment = null;
+                    newData.EnvironmentVersion = -1;
+                }
+                else
+                {
+                    try
+                    {
+                        ViewerEnvironment VEnv = ViewerEnvironment.FromOSDString(env);
+                        newData.Environment = VEnv;
+                        newData.EnvironmentVersion = VEnv.version;
+                    }
+                    catch
+                    {
+                        newData.Environment = null;
+                        newData.EnvironmentVersion = -1;
+                    }
+                }
+            }
             return newData;
         }
 
@@ -1756,38 +1563,43 @@ namespace OpenSim.Data.MySQL
             cmd.Parameters.AddWithValue("EveryoneMask", prim.EveryoneMask);
             cmd.Parameters.AddWithValue("BaseMask", prim.BaseMask);
             // vectors
-            cmd.Parameters.AddWithValue("PositionX", (double)prim.OffsetPosition.X);
-            cmd.Parameters.AddWithValue("PositionY", (double)prim.OffsetPosition.Y);
-            cmd.Parameters.AddWithValue("PositionZ", (double)prim.OffsetPosition.Z);
-            cmd.Parameters.AddWithValue("GroupPositionX", (double)prim.GroupPosition.X);
-            cmd.Parameters.AddWithValue("GroupPositionY", (double)prim.GroupPosition.Y);
-            cmd.Parameters.AddWithValue("GroupPositionZ", (double)prim.GroupPosition.Z);
-            cmd.Parameters.AddWithValue("VelocityX", (double)prim.Velocity.X);
-            cmd.Parameters.AddWithValue("VelocityY", (double)prim.Velocity.Y);
-            cmd.Parameters.AddWithValue("VelocityZ", (double)prim.Velocity.Z);
-            cmd.Parameters.AddWithValue("AngularVelocityX", (double)prim.AngularVelocity.X);
-            cmd.Parameters.AddWithValue("AngularVelocityY", (double)prim.AngularVelocity.Y);
-            cmd.Parameters.AddWithValue("AngularVelocityZ", (double)prim.AngularVelocity.Z);
-            cmd.Parameters.AddWithValue("AccelerationX", (double)prim.Acceleration.X);
-            cmd.Parameters.AddWithValue("AccelerationY", (double)prim.Acceleration.Y);
-            cmd.Parameters.AddWithValue("AccelerationZ", (double)prim.Acceleration.Z);
+            cmd.Parameters.AddWithValue("PositionX", prim.OffsetPosition.X);
+            cmd.Parameters.AddWithValue("PositionY", prim.OffsetPosition.Y);
+            cmd.Parameters.AddWithValue("PositionZ", prim.OffsetPosition.Z);
+            cmd.Parameters.AddWithValue("GroupPositionX", prim.GroupPosition.X);
+            cmd.Parameters.AddWithValue("GroupPositionY", prim.GroupPosition.Y);
+            cmd.Parameters.AddWithValue("GroupPositionZ", prim.GroupPosition.Z);
+            cmd.Parameters.AddWithValue("VelocityX", prim.Velocity.X);
+            cmd.Parameters.AddWithValue("VelocityY", prim.Velocity.Y);
+            cmd.Parameters.AddWithValue("VelocityZ", prim.Velocity.Z);
+            cmd.Parameters.AddWithValue("AngularVelocityX", prim.AngularVelocity.X);
+            cmd.Parameters.AddWithValue("AngularVelocityY", prim.AngularVelocity.Y);
+            cmd.Parameters.AddWithValue("AngularVelocityZ", prim.AngularVelocity.Z);
+            cmd.Parameters.AddWithValue("AccelerationX", prim.Acceleration.X);
+            cmd.Parameters.AddWithValue("AccelerationY", prim.Acceleration.Y);
+            cmd.Parameters.AddWithValue("AccelerationZ", prim.Acceleration.Z);
+
+            cmd.Parameters.AddWithValue("standtargetx", prim.StandOffset.X);
+            cmd.Parameters.AddWithValue("standtargety", prim.StandOffset.Y);
+            cmd.Parameters.AddWithValue("standtargetz", prim.StandOffset.Z);
+
             // quaternions
-            cmd.Parameters.AddWithValue("RotationX", (double)prim.RotationOffset.X);
-            cmd.Parameters.AddWithValue("RotationY", (double)prim.RotationOffset.Y);
-            cmd.Parameters.AddWithValue("RotationZ", (double)prim.RotationOffset.Z);
-            cmd.Parameters.AddWithValue("RotationW", (double)prim.RotationOffset.W);
+            cmd.Parameters.AddWithValue("RotationX", prim.RotationOffset.X);
+            cmd.Parameters.AddWithValue("RotationY", prim.RotationOffset.Y);
+            cmd.Parameters.AddWithValue("RotationZ", prim.RotationOffset.Z);
+            cmd.Parameters.AddWithValue("RotationW", prim.RotationOffset.W);
 
             // Sit target
             Vector3 sitTargetPos = prim.SitTargetPositionLL;
-            cmd.Parameters.AddWithValue("SitTargetOffsetX", (double)sitTargetPos.X);
-            cmd.Parameters.AddWithValue("SitTargetOffsetY", (double)sitTargetPos.Y);
-            cmd.Parameters.AddWithValue("SitTargetOffsetZ", (double)sitTargetPos.Z);
+            cmd.Parameters.AddWithValue("SitTargetOffsetX", sitTargetPos.X);
+            cmd.Parameters.AddWithValue("SitTargetOffsetY", sitTargetPos.Y);
+            cmd.Parameters.AddWithValue("SitTargetOffsetZ", sitTargetPos.Z);
 
             Quaternion sitTargetOrient = prim.SitTargetOrientationLL;
-            cmd.Parameters.AddWithValue("SitTargetOrientW", (double)sitTargetOrient.W);
-            cmd.Parameters.AddWithValue("SitTargetOrientX", (double)sitTargetOrient.X);
-            cmd.Parameters.AddWithValue("SitTargetOrientY", (double)sitTargetOrient.Y);
-            cmd.Parameters.AddWithValue("SitTargetOrientZ", (double)sitTargetOrient.Z);
+            cmd.Parameters.AddWithValue("SitTargetOrientW", sitTargetOrient.W);
+            cmd.Parameters.AddWithValue("SitTargetOrientX", sitTargetOrient.X);
+            cmd.Parameters.AddWithValue("SitTargetOrientY", sitTargetOrient.Y);
+            cmd.Parameters.AddWithValue("SitTargetOrientZ", sitTargetOrient.Z);
 
             cmd.Parameters.AddWithValue("PayPrice", prim.PayPrice[0]);
             cmd.Parameters.AddWithValue("PayButton1", prim.PayPrice[1]);
@@ -1798,7 +1610,7 @@ namespace OpenSim.Data.MySQL
             if ((prim.SoundFlags & 1) != 0) // Looped
             {
                 cmd.Parameters.AddWithValue("LoopedSound", prim.Sound.ToString());
-                cmd.Parameters.AddWithValue("LoopedSoundGain", prim.SoundGain);
+                cmd.Parameters.AddWithValue("LoopedSoundGain", (float)prim.SoundGain);
             }
             else
             {
@@ -1809,17 +1621,13 @@ namespace OpenSim.Data.MySQL
             cmd.Parameters.AddWithValue("TextureAnimation", prim.TextureAnimation);
             cmd.Parameters.AddWithValue("ParticleSystem", prim.ParticleSystem);
 
-            cmd.Parameters.AddWithValue("OmegaX", (double)prim.AngularVelocity.X);
-            cmd.Parameters.AddWithValue("OmegaY", (double)prim.AngularVelocity.Y);
-            cmd.Parameters.AddWithValue("OmegaZ", (double)prim.AngularVelocity.Z);
-
-            cmd.Parameters.AddWithValue("CameraEyeOffsetX", (double)prim.GetCameraEyeOffset().X);
-            cmd.Parameters.AddWithValue("CameraEyeOffsetY", (double)prim.GetCameraEyeOffset().Y);
-            cmd.Parameters.AddWithValue("CameraEyeOffsetZ", (double)prim.GetCameraEyeOffset().Z);
+            cmd.Parameters.AddWithValue("CameraEyeOffsetX", prim.GetCameraEyeOffset().X);
+            cmd.Parameters.AddWithValue("CameraEyeOffsetY", prim.GetCameraEyeOffset().Y);
+            cmd.Parameters.AddWithValue("CameraEyeOffsetZ", prim.GetCameraEyeOffset().Z);
 
-            cmd.Parameters.AddWithValue("CameraAtOffsetX", (double)prim.GetCameraAtOffset().X);
-            cmd.Parameters.AddWithValue("CameraAtOffsetY", (double)prim.GetCameraAtOffset().Y);
-            cmd.Parameters.AddWithValue("CameraAtOffsetZ", (double)prim.GetCameraAtOffset().Z);
+            cmd.Parameters.AddWithValue("CameraAtOffsetX", prim.GetCameraAtOffset().X);
+            cmd.Parameters.AddWithValue("CameraAtOffsetY", prim.GetCameraAtOffset().Y);
+            cmd.Parameters.AddWithValue("CameraAtOffsetZ", prim.GetCameraAtOffset().Z);
 
             if (prim.GetForceMouselook())
                 cmd.Parameters.AddWithValue("ForceMouselook", 1);
@@ -1863,9 +1671,9 @@ namespace OpenSim.Data.MySQL
             cmd.Parameters.AddWithValue("MediaURL", prim.MediaUrl);
             if (prim.AttachedPos != null)
             {
-                cmd.Parameters.AddWithValue("AttachedPosX", (double)prim.AttachedPos.X);
-                cmd.Parameters.AddWithValue("AttachedPosY", (double)prim.AttachedPos.Y);
-                cmd.Parameters.AddWithValue("AttachedPosZ", (double)prim.AttachedPos.Z);
+                cmd.Parameters.AddWithValue("AttachedPosX", prim.AttachedPos.X);
+                cmd.Parameters.AddWithValue("AttachedPosY", prim.AttachedPos.Y);
+                cmd.Parameters.AddWithValue("AttachedPosZ", prim.AttachedPos.Z);
             }
 
             if (prim.KeyframeMotion != null)
@@ -1889,16 +1697,19 @@ namespace OpenSim.Data.MySQL
                 cmd.Parameters.AddWithValue("DynAttrs", null);
 
             cmd.Parameters.AddWithValue("PhysicsShapeType", prim.PhysicsShapeType);
-            cmd.Parameters.AddWithValue("Density", (double)prim.Density);
-            cmd.Parameters.AddWithValue("GravityModifier", (double)prim.GravityModifier);
-            cmd.Parameters.AddWithValue("Friction", (double)prim.Friction);
-            cmd.Parameters.AddWithValue("Restitution", (double)prim.Restitution);
+            cmd.Parameters.AddWithValue("Density", prim.Density);
+            cmd.Parameters.AddWithValue("GravityModifier", prim.GravityModifier);
+            cmd.Parameters.AddWithValue("Friction", prim.Friction);
+            cmd.Parameters.AddWithValue("Restitution", prim.Restitution);
             cmd.Parameters.AddWithValue("RotationAxisLocks", prim.RotationAxisLocks);
 
             if (prim.Animations!= null)
                 cmd.Parameters.AddWithValue("sopanims", prim.SerializeAnimations());
             else
                 cmd.Parameters.AddWithValue("sopanims", null);
+
+            cmd.Parameters.AddWithValue("sitactrange", prim.SitActiveRange);
+            cmd.Parameters.AddWithValue("pseudocrc", prim.PseudoCRC);
         }
 
         /// <summary>
@@ -1982,6 +1793,7 @@ namespace OpenSim.Data.MySQL
 
             cmd.Parameters.AddWithValue("ParcelImageID", settings.ParcelImageID);
             cmd.Parameters.AddWithValue("TelehubObject", settings.TelehubObject);
+            cmd.Parameters.AddWithValue("cacheID", settings.CacheID);
         }
 
         /// <summary>
@@ -2039,7 +1851,19 @@ namespace OpenSim.Data.MySQL
             cmd.Parameters.AddWithValue("SeeAVs", land.SeeAVs ? 1 : 0);
             cmd.Parameters.AddWithValue("AnyAVSounds", land.AnyAVSounds ? 1 : 0);
             cmd.Parameters.AddWithValue("GroupAVSounds", land.GroupAVSounds ? 1 : 0);
-
+            if (land.Environment == null)
+                cmd.Parameters.AddWithValue("environment", "");
+            else
+            {
+                try
+                {
+                    cmd.Parameters.AddWithValue("environment", ViewerEnvironment.ToOSDString(land.Environment));
+                }
+                catch
+                {
+                    cmd.Parameters.AddWithValue("environment", "");
+                }
+            }
         }
 
         /// <summary>

+ 5 - 0
OpenSim/Data/MySQL/Resources/EstateStore.migrations

@@ -76,3 +76,8 @@ ALTER TABLE `estateban`
     ADD COLUMN `banTime` int(11) NOT NULL DEFAULT 0;
 COMMIT;
 
+:VERSION 36
+BEGIN;
+ALTER TABLE `estate_settings`
+    ADD COLUMN `AllowEnviromentOverride` tinyint(4) NOT NULL DEFAULT '0';
+COMMIT;

+ 6 - 0
OpenSim/Data/MySQL/Resources/HGTravelStore.migrations

@@ -16,3 +16,9 @@ CREATE TABLE `hg_traveling_data` (
 
 COMMIT;
 
+:VERSION 2         # -------------------------- 
+
+ALTER TABLE `hg_traveling_data` MODIFY `TMStamp` timestamp NOT NULL default CURRENT_TIMESTAMP;
+
+COMMIT;
+

+ 76 - 0
OpenSim/Data/MySQL/Resources/RegionStore.migrations

@@ -474,3 +474,79 @@ BEGIN;
 ALTER TABLE `prims` ADD COLUMN `sopanims` blob default NULL;
 COMMIT;
 
+:VERSION 59         #----- Add standtarget and sit range
+
+BEGIN;
+ALTER TABLE `prims` 
+ADD COLUMN `standtargetx` float DEFAULT '0.0',
+ADD COLUMN `standtargety` float DEFAULT '0.0',
+ADD COLUMN `standtargetz` float DEFAULT '0.0',
+ADD COLUMN `sitactrange` float DEFAULT '0.0';
+COMMIT;
+
+:VERSION 60         #----- don't store float on double
+
+BEGIN;
+ALTER TABLE `prims` 
+MODIFY `PositionX` float DEFAULT '0.0',
+MODIFY `PositionY` float DEFAULT '0.0',
+MODIFY `PositionZ` float DEFAULT '0.0',
+MODIFY `GroupPositionX` float DEFAULT '0.0',
+MODIFY `GroupPositionY` float DEFAULT '0.0',
+MODIFY `GroupPositionZ` float DEFAULT '0.0',
+MODIFY `VelocityX` float DEFAULT '0.0',
+MODIFY `VelocityY` float DEFAULT '0.0',
+MODIFY `VelocityZ` float DEFAULT '0.0',
+MODIFY `AngularVelocityX` float DEFAULT '0.0',
+MODIFY `AngularVelocityY` float DEFAULT '0.0',
+MODIFY `AngularVelocityZ` float DEFAULT '0.0',
+MODIFY `AccelerationX` float DEFAULT '0.0',
+MODIFY `AccelerationY` float DEFAULT '0.0',
+MODIFY `AccelerationZ` float DEFAULT '0.0',
+MODIFY `RotationX` float DEFAULT '0.0',
+MODIFY `RotationY` float DEFAULT '0.0',
+MODIFY `RotationZ` float DEFAULT '0.0',
+MODIFY `RotationW` float DEFAULT '0.0',
+MODIFY `SitTargetOffsetX` float DEFAULT '0.0',
+MODIFY `SitTargetOffsetY` float DEFAULT '0.0',
+MODIFY `SitTargetOffsetZ` float DEFAULT '0.0',
+MODIFY `SitTargetOrientX` float DEFAULT '0.0',
+MODIFY `SitTargetOrientY` float DEFAULT '0.0',
+MODIFY `SitTargetOrientZ` float DEFAULT '0.0',
+MODIFY `SitTargetOrientW` float DEFAULT '0.0',
+MODIFY `OmegaX` float DEFAULT '0.0',
+MODIFY `OmegaY` float DEFAULT '0.0',
+MODIFY `OmegaZ` float DEFAULT '0.0',
+MODIFY `CameraEyeOffsetX` float DEFAULT '0.0',
+MODIFY `CameraEyeOffsetY` float DEFAULT '0.0',
+MODIFY `CameraEyeOffsetZ` float DEFAULT '0.0',
+MODIFY `CameraAtOffsetX` float DEFAULT '0.0',
+MODIFY `CameraAtOffsetY` float DEFAULT '0.0',
+MODIFY `CameraAtOffsetZ` float DEFAULT '0.0',
+MODIFY `Density` float DEFAULT '1000.0',
+MODIFY `GravityModifier` float DEFAULT '1.0',
+MODIFY `Friction` float DEFAULT '0.6',
+MODIFY `Restitution` float DEFAULT '0.5',
+MODIFY `AttachedPosX` float DEFAULT '0',
+MODIFY `AttachedPosY` float DEFAULT '0',
+MODIFY `AttachedPosZ` float DEFAULT '0',
+MODIFY `LoopedSoundGain` float DEFAULT '0';
+COMMIT;
+
+:VERSION 61         #----- Add pseudo CRC and region cache id
+
+BEGIN;
+ALTER TABLE `prims` ADD COLUMN `pseudocrc` int DEFAULT '0';
+ALTER TABLE `regionsettings` ADD COLUMN `cacheID` char(36) DEFAULT NULL;
+COMMIT;
+
+:VERSION 62         #----- increase size of environment settings
+BEGIN;
+ALTER TABLE `regionenvironment` MODIFY `llsd_settings` MEDIUMTEXT;
+COMMIT;
+
+:VERSION 63         #----- parcel environment store
+BEGIN;
+ALTER TABLE `land` ADD COLUMN `environment` MEDIUMTEXT default NULL;
+COMMIT;
+

+ 1 - 1
OpenSim/Data/MySQL/Resources/os_groups_Store.migrations

@@ -118,6 +118,6 @@ COMMIT;
 
 ALTER TABLE `os_groups_invites`
 
-MODIFY `TMStamp` timestamp NOT NULL, default CURRENT_TIMESTAMP;
+MODIFY `TMStamp` timestamp NOT NULL default CURRENT_TIMESTAMP;
 
 COMMIT;

+ 23 - 1
OpenSim/Data/Null/NullRegionData.cs

@@ -68,12 +68,34 @@ namespace OpenSim.Data.Null
 
         private delegate bool Matcher(string value);
 
+        public RegionData GetSpecific(string regionName, UUID scopeID)
+        {
+            if (m_useStaticInstance && Instance != this)
+                return Instance.GetSpecific(regionName, scopeID);
+
+            string cleanName = regionName.ToLower();
+            Matcher queryMatch;
+            queryMatch = delegate (string s) { return s.Equals(cleanName); };
+
+            lock (m_regionData)
+            {
+                foreach (RegionData r in m_regionData.Values)
+                {
+                    // m_log.DebugFormat("[NULL REGION DATA]: comparing {0} to {1}", cleanName, r.RegionName.ToLower());
+                    if (queryMatch(r.RegionName.ToLower()))
+                        return(r);
+                }
+            }
+
+            return null;
+        }
+
         public List<RegionData> Get(string regionName, UUID scopeID)
         {
             if (m_useStaticInstance && Instance != this)
                 return Instance.Get(regionName, scopeID);
 
-//            m_log.DebugFormat("[NULL REGION DATA]: Getting region {0}, scope {1}", regionName, scopeID);
+            // m_log.DebugFormat("[NULL REGION DATA]: Getting region {0}, scope {1}", regionName, scopeID);
 
             string cleanName = regionName.ToLower();
 

+ 2 - 2
OpenSim/Data/PGSQL/PGSQLGroupsData.cs

@@ -86,13 +86,13 @@ namespace OpenSim.Data.PGSQL
 
             if (string.IsNullOrEmpty(pattern)) // True for where clause
             {
-                pattern = " 1 ORDER BY lower(\"Name\") LIMIT 100";
+                pattern = "1";
 
                 return m_Groups.Get(pattern);
             }
             else
             {
-                pattern = " \"ShowInList\" = 1 AND lower(\"Name\") LIKE lower('%" + pattern + "%') ORDER BY lower(\"Name\") LIMIT 100";
+                pattern = " \"ShowInList\" = 1 AND lower(\"Name\") LIKE lower('%" + pattern + "%')";
 
                 return m_Groups.Get(pattern, new NpgsqlParameter("pattern", pattern));
             }

+ 21 - 0
OpenSim/Data/PGSQL/PGSQLRegionData.cs

@@ -114,6 +114,27 @@ namespace OpenSim.Data.PGSQL
             }
         }
 
+        public RegionData GetSpecific(string regionName, UUID scopeID)
+        {
+            string sql = "select * from " + m_Realm + " where lower(\"regionName\") = lower(:regionName) ";
+            if (scopeID != UUID.Zero)
+                sql += " and \"ScopeID\" = :scopeID";
+
+            using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
+            using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
+            {
+                cmd.Parameters.Add(m_database.CreateParameter("regionName", regionName));
+                if (scopeID != UUID.Zero)
+                    cmd.Parameters.Add(m_database.CreateParameter("scopeID", scopeID));
+                conn.Open();
+                List<RegionData> ret = RunCommand(cmd);
+                if (ret.Count == 0)
+                    return null;
+
+                return ret[0];
+            }
+        }
+
         public RegionData Get(int posX, int posY, UUID scopeID)
         {
             // extend database search for maximum region size area

+ 92 - 500
OpenSim/Data/PGSQL/PGSQLSimulationData.cs

@@ -346,7 +346,7 @@ namespace OpenSim.Data.PGSQL
             ""SitTargetOrientZ"" = :SitTargetOrientZ, ""RegionUUID"" = :RegionUUID, ""CreatorID"" = :CreatorID, ""OwnerID"" = :OwnerID, ""GroupID"" = :GroupID,
             ""LastOwnerID"" = :LastOwnerID, ""SceneGroupID"" = :SceneGroupID, ""PayPrice"" = :PayPrice, ""PayButton1"" = :PayButton1, ""PayButton2"" = :PayButton2,
             ""PayButton3"" = :PayButton3, ""PayButton4"" = :PayButton4, ""LoopedSound"" = :LoopedSound, ""LoopedSoundGain"" = :LoopedSoundGain,
-            ""TextureAnimation"" = :TextureAnimation, ""OmegaX"" = :OmegaX, ""OmegaY"" = :OmegaY, ""OmegaZ"" = :OmegaZ, ""CameraEyeOffsetX"" = :CameraEyeOffsetX,
+            ""TextureAnimation"" = :TextureAnimation, ""CameraEyeOffsetX"" = :CameraEyeOffsetX,
             ""CameraEyeOffsetY"" = :CameraEyeOffsetY, ""CameraEyeOffsetZ"" = :CameraEyeOffsetZ, ""CameraAtOffsetX"" = :CameraAtOffsetX,
             ""CameraAtOffsetY"" = :CameraAtOffsetY, ""CameraAtOffsetZ"" = :CameraAtOffsetZ, ""ForceMouselook"" = :ForceMouselook,
             ""ScriptAccessPin"" = :ScriptAccessPin, ""AllowedDrop"" = :AllowedDrop, ""DieAtEdge"" = :DieAtEdge, ""SalePrice"" = :SalePrice,
@@ -354,7 +354,9 @@ namespace OpenSim.Data.PGSQL
             ""PassCollisions"" = :PassCollisions, ""RotationAxisLocks"" = :RotationAxisLocks, ""RezzerID"" = :RezzerID,
             ""ClickAction"" = :ClickAction, ""Material"" = :Material, ""CollisionSound"" = :CollisionSound, ""CollisionSoundVolume"" = :CollisionSoundVolume, ""PassTouches"" = :PassTouches,
             ""LinkNumber"" = :LinkNumber, ""MediaURL"" = :MediaURL, ""DynAttrs"" = :DynAttrs, ""Vehicle"" = :Vehicle,
-            ""PhysInertia"" = :PhysInertia
+            ""PhysInertia"" = :PhysInertia, ""standtargetx"" =:standtargetx, ""standtargety"" =:standtargety, ""standtargetz"" =:standtargetz,
+            ""sitactrange"" =:sitactrange, ""pseudocrc"" = :pseudocrc
+
         WHERE ""UUID"" = :UUID ;
 
         INSERT INTO
@@ -364,22 +366,24 @@ namespace OpenSim.Data.PGSQL
             ""VelocityY"", ""VelocityZ"", ""AngularVelocityX"", ""AngularVelocityY"", ""AngularVelocityZ"", ""AccelerationX"", ""AccelerationY"", ""AccelerationZ"",
             ""RotationX"", ""RotationY"", ""RotationZ"", ""RotationW"", ""SitTargetOffsetX"", ""SitTargetOffsetY"", ""SitTargetOffsetZ"", ""SitTargetOrientW"",
             ""SitTargetOrientX"", ""SitTargetOrientY"", ""SitTargetOrientZ"", ""RegionUUID"", ""CreatorID"", ""OwnerID"", ""GroupID"", ""LastOwnerID"", ""SceneGroupID"",
-            ""PayPrice"", ""PayButton1"", ""PayButton2"", ""PayButton3"", ""PayButton4"", ""LoopedSound"", ""LoopedSoundGain"", ""TextureAnimation"", ""OmegaX"",
-            ""OmegaY"", ""OmegaZ"", ""CameraEyeOffsetX"", ""CameraEyeOffsetY"", ""CameraEyeOffsetZ"", ""CameraAtOffsetX"", ""CameraAtOffsetY"", ""CameraAtOffsetZ"",
+            ""PayPrice"", ""PayButton1"", ""PayButton2"", ""PayButton3"", ""PayButton4"", ""LoopedSound"", ""LoopedSoundGain"", ""TextureAnimation"",
+            ""CameraEyeOffsetX"", ""CameraEyeOffsetY"", ""CameraEyeOffsetZ"", ""CameraAtOffsetX"", ""CameraAtOffsetY"", ""CameraAtOffsetZ"",
             ""ForceMouselook"", ""ScriptAccessPin"", ""AllowedDrop"", ""DieAtEdge"", ""SalePrice"", ""SaleType"", ""ColorR"", ""ColorG"", ""ColorB"", ""ColorA"",
             ""ParticleSystem"", ""ClickAction"", ""Material"", ""CollisionSound"", ""CollisionSoundVolume"", ""PassTouches"", ""LinkNumber"", ""MediaURL"", ""DynAttrs"",
-            ""PhysicsShapeType"", ""Density"", ""GravityModifier"", ""Friction"", ""Restitution"", ""PassCollisions"", ""RotationAxisLocks"", ""RezzerID"" , ""Vehicle"", ""PhysInertia""
+            ""PhysicsShapeType"", ""Density"", ""GravityModifier"", ""Friction"", ""Restitution"", ""PassCollisions"", ""RotationAxisLocks"", ""RezzerID"" , ""Vehicle"", ""PhysInertia"",
+            ""standtargetx"", ""standtargety"", ""standtargetz"", ""sitactrange"", ""pseudocrc""
             ) Select
             :UUID, :CreationDate, :Name, :Text, :Description, :SitName, :TouchName, :ObjectFlags, :OwnerMask, :NextOwnerMask, :GroupMask,
             :EveryoneMask, :BaseMask, :PositionX, :PositionY, :PositionZ, :GroupPositionX, :GroupPositionY, :GroupPositionZ, :VelocityX,
             :VelocityY, :VelocityZ, :AngularVelocityX, :AngularVelocityY, :AngularVelocityZ, :AccelerationX, :AccelerationY, :AccelerationZ,
             :RotationX, :RotationY, :RotationZ, :RotationW, :SitTargetOffsetX, :SitTargetOffsetY, :SitTargetOffsetZ, :SitTargetOrientW,
             :SitTargetOrientX, :SitTargetOrientY, :SitTargetOrientZ, :RegionUUID, :CreatorID, :OwnerID, :GroupID, :LastOwnerID, :SceneGroupID,
-            :PayPrice, :PayButton1, :PayButton2, :PayButton3, :PayButton4, :LoopedSound, :LoopedSoundGain, :TextureAnimation, :OmegaX,
-            :OmegaY, :OmegaZ, :CameraEyeOffsetX, :CameraEyeOffsetY, :CameraEyeOffsetZ, :CameraAtOffsetX, :CameraAtOffsetY, :CameraAtOffsetZ,
+            :PayPrice, :PayButton1, :PayButton2, :PayButton3, :PayButton4, :LoopedSound, :LoopedSoundGain, :TextureAnimation,
+            :CameraEyeOffsetX, :CameraEyeOffsetY, :CameraEyeOffsetZ, :CameraAtOffsetX, :CameraAtOffsetY, :CameraAtOffsetZ,
             :ForceMouselook, :ScriptAccessPin, :AllowedDrop, :DieAtEdge, :SalePrice, :SaleType, :ColorR, :ColorG, :ColorB, :ColorA,
             :ParticleSystem, :ClickAction, :Material, :CollisionSound, :CollisionSoundVolume, :PassTouches, :LinkNumber, :MediaURL, :DynAttrs,
-            :PhysicsShapeType, :Density, :GravityModifier, :Friction, :Restitution, :PassCollisions, :RotationAxisLocks, :RezzerID, :Vehicle, :PhysInertia
+            :PhysicsShapeType, :Density, :GravityModifier, :Friction, :Restitution, :PassCollisions, :RotationAxisLocks, :RezzerID, :Vehicle, :PhysInertia,
+            :standtargetx, :standtargety, :standtargetz,:sitactrange, :pseudocrc 
             where not EXISTS (SELECT ""UUID"" FROM prims WHERE ""UUID"" = :UUID);
         ";
 
@@ -766,13 +770,14 @@ namespace OpenSim.Data.PGSQL
                 (""UUID"",""RegionUUID"",""LocalLandID"",""Bitmap"",""Name"",""Description"",""OwnerUUID"",""IsGroupOwned"",""Area"",""AuctionID"",""Category"",""ClaimDate"",""ClaimPrice"",
                  ""GroupUUID"",""SalePrice"",""LandStatus"",""LandFlags"",""LandingType"",""MediaAutoScale"",""MediaTextureUUID"",""MediaURL"",""MusicURL"",""PassHours"",""PassPrice"",
                  ""SnapshotUUID"",""UserLocationX"",""UserLocationY"",""UserLocationZ"",""UserLookAtX"",""UserLookAtY"",""UserLookAtZ"",""AuthbuyerID"",""OtherCleanTime"",""Dwell"",
-                 ""MediaType"",""MediaDescription"",""MediaSize"",""MediaLoop"",""ObscureMusic"",""ObscureMedia"",""SeeAVs"",""AnyAVSounds"",""GroupAVSounds"")
+                 ""MediaType"",""MediaDescription"",""MediaSize"",""MediaLoop"",""ObscureMusic"",""ObscureMedia"",""SeeAVs"",""AnyAVSounds"",""GroupAVSounds"",
+                 ""environment"")
                 VALUES
                 (:UUID,:RegionUUID,:LocalLandID,:Bitmap,:Name,:Description,:OwnerUUID,:IsGroupOwned,:Area,:AuctionID,:Category,:ClaimDate,:ClaimPrice,
                  :GroupUUID,:SalePrice,:LandStatus,:LandFlags,:LandingType,:MediaAutoScale,:MediaTextureUUID,:MediaURL,:MusicURL,:PassHours,:PassPrice,
                  :SnapshotUUID,:UserLocationX,:UserLocationY,:UserLocationZ,:UserLookAtX,:UserLookAtY,:UserLookAtZ,:AuthbuyerID,:OtherCleanTime,:Dwell,
                  :MediaType,:MediaDescription,:MediaWidth::text || ',' || :MediaHeight::text,:MediaLoop,:ObscureMusic,:ObscureMedia,:SeeAVs::int::smallint,
-                 :AnyAVSounds::int::smallint,:GroupAVSounds::int::smallint)";
+                 :AnyAVSounds::int::smallint,:GroupAVSounds::int::smallint,:environment)";
 
             using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
             using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
@@ -821,477 +826,6 @@ namespace OpenSim.Data.PGSQL
                 cmd.ExecuteNonQuery();
             }
         }
-        public RegionLightShareData LoadRegionWindlightSettings(UUID regionUUID)
-        {
-            RegionLightShareData nWP = new RegionLightShareData();
-            nWP.OnSave += StoreRegionWindlightSettings;
-
-            string sql = @"select * from regionwindlight where ""region_id"" = :regionID";
-
-            using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
-            using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
-            {
-                cmd.Parameters.Add(_Database.CreateParameter("regionID", regionUUID.ToString() ));
-                conn.Open();
-                using (NpgsqlDataReader result = cmd.ExecuteReader())
-                {
-                    if (!result.Read())
-                    {
-                        //No result, so store our default windlight profile and return it
-                        nWP.regionID = regionUUID;
-                        StoreRegionWindlightSettings(nWP);
-                        return nWP;
-                    }
-                    else
-                    {
-                        nWP.regionID = DBGuid.FromDB(result["region_id"]);
-                        nWP.waterColor.X = Convert.ToSingle(result["water_color_r"]);
-                        nWP.waterColor.Y = Convert.ToSingle(result["water_color_g"]);
-                        nWP.waterColor.Z = Convert.ToSingle(result["water_color_b"]);
-                        nWP.waterFogDensityExponent = Convert.ToSingle(result["water_fog_density_exponent"]);
-                        nWP.underwaterFogModifier = Convert.ToSingle(result["underwater_fog_modifier"]);
-                        nWP.reflectionWaveletScale.X = Convert.ToSingle(result["reflection_wavelet_scale_1"]);
-                        nWP.reflectionWaveletScale.Y = Convert.ToSingle(result["reflection_wavelet_scale_2"]);
-                        nWP.reflectionWaveletScale.Z = Convert.ToSingle(result["reflection_wavelet_scale_3"]);
-                        nWP.fresnelScale = Convert.ToSingle(result["fresnel_scale"]);
-                        nWP.fresnelOffset = Convert.ToSingle(result["fresnel_offset"]);
-                        nWP.refractScaleAbove = Convert.ToSingle(result["refract_scale_above"]);
-                        nWP.refractScaleBelow = Convert.ToSingle(result["refract_scale_below"]);
-                        nWP.blurMultiplier = Convert.ToSingle(result["blur_multiplier"]);
-                        nWP.bigWaveDirection.X = Convert.ToSingle(result["big_wave_direction_x"]);
-                        nWP.bigWaveDirection.Y = Convert.ToSingle(result["big_wave_direction_y"]);
-                        nWP.littleWaveDirection.X = Convert.ToSingle(result["little_wave_direction_x"]);
-                        nWP.littleWaveDirection.Y = Convert.ToSingle(result["little_wave_direction_y"]);
-                        UUID.TryParse(result["normal_map_texture"].ToString(), out nWP.normalMapTexture);
-                        nWP.horizon.X = Convert.ToSingle(result["horizon_r"]);
-                        nWP.horizon.Y = Convert.ToSingle(result["horizon_g"]);
-                        nWP.horizon.Z = Convert.ToSingle(result["horizon_b"]);
-                        nWP.horizon.W = Convert.ToSingle(result["horizon_i"]);
-                        nWP.hazeHorizon = Convert.ToSingle(result["haze_horizon"]);
-                        nWP.blueDensity.X = Convert.ToSingle(result["blue_density_r"]);
-                        nWP.blueDensity.Y = Convert.ToSingle(result["blue_density_g"]);
-                        nWP.blueDensity.Z = Convert.ToSingle(result["blue_density_b"]);
-                        nWP.blueDensity.W = Convert.ToSingle(result["blue_density_i"]);
-                        nWP.hazeDensity = Convert.ToSingle(result["haze_density"]);
-                        nWP.densityMultiplier = Convert.ToSingle(result["density_multiplier"]);
-                        nWP.distanceMultiplier = Convert.ToSingle(result["distance_multiplier"]);
-                        nWP.maxAltitude = Convert.ToUInt16(result["max_altitude"]);
-                        nWP.sunMoonColor.X = Convert.ToSingle(result["sun_moon_color_r"]);
-                        nWP.sunMoonColor.Y = Convert.ToSingle(result["sun_moon_color_g"]);
-                        nWP.sunMoonColor.Z = Convert.ToSingle(result["sun_moon_color_b"]);
-                        nWP.sunMoonColor.W = Convert.ToSingle(result["sun_moon_color_i"]);
-                        nWP.sunMoonPosition = Convert.ToSingle(result["sun_moon_position"]);
-                        nWP.ambient.X = Convert.ToSingle(result["ambient_r"]);
-                        nWP.ambient.Y = Convert.ToSingle(result["ambient_g"]);
-                        nWP.ambient.Z = Convert.ToSingle(result["ambient_b"]);
-                        nWP.ambient.W = Convert.ToSingle(result["ambient_i"]);
-                        nWP.eastAngle = Convert.ToSingle(result["east_angle"]);
-                        nWP.sunGlowFocus = Convert.ToSingle(result["sun_glow_focus"]);
-                        nWP.sunGlowSize = Convert.ToSingle(result["sun_glow_size"]);
-                        nWP.sceneGamma = Convert.ToSingle(result["scene_gamma"]);
-                        nWP.starBrightness = Convert.ToSingle(result["star_brightness"]);
-                        nWP.cloudColor.X = Convert.ToSingle(result["cloud_color_r"]);
-                        nWP.cloudColor.Y = Convert.ToSingle(result["cloud_color_g"]);
-                        nWP.cloudColor.Z = Convert.ToSingle(result["cloud_color_b"]);
-                        nWP.cloudColor.W = Convert.ToSingle(result["cloud_color_i"]);
-                        nWP.cloudXYDensity.X = Convert.ToSingle(result["cloud_x"]);
-                        nWP.cloudXYDensity.Y = Convert.ToSingle(result["cloud_y"]);
-                        nWP.cloudXYDensity.Z = Convert.ToSingle(result["cloud_density"]);
-                        nWP.cloudCoverage = Convert.ToSingle(result["cloud_coverage"]);
-                        nWP.cloudScale = Convert.ToSingle(result["cloud_scale"]);
-                        nWP.cloudDetailXYDensity.X = Convert.ToSingle(result["cloud_detail_x"]);
-                        nWP.cloudDetailXYDensity.Y = Convert.ToSingle(result["cloud_detail_y"]);
-                        nWP.cloudDetailXYDensity.Z = Convert.ToSingle(result["cloud_detail_density"]);
-                        nWP.cloudScrollX = Convert.ToSingle(result["cloud_scroll_x"]);
-                        nWP.cloudScrollXLock = Convert.ToBoolean(result["cloud_scroll_x_lock"]);
-                        nWP.cloudScrollY = Convert.ToSingle(result["cloud_scroll_y"]);
-                        nWP.cloudScrollYLock = Convert.ToBoolean(result["cloud_scroll_y_lock"]);
-                        nWP.drawClassicClouds = Convert.ToBoolean(result["draw_classic_clouds"]);
-                        nWP.valid = true;
-                    }
-                }
-            }
-            return nWP;
-        }
-
-        public void RemoveRegionWindlightSettings(UUID regionID)
-        {
-            string sql = @"delete from regionwindlight where ""region_id"" = :region_id";
-            using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
-            using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
-            {
-                conn.Open();
-                cmd.Parameters.Add(_Database.CreateParameter("region_id", regionID.ToString()));
-                cmd.ExecuteNonQuery();
-            }
-        }
-
-        public void StoreRegionWindlightSettings(RegionLightShareData wl)
-        {
-            string sql = @"select region_id from regionwindlight where ""region_id"" = :region_id limit 1;";
-            bool exists = false;
-            using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
-            {
-                conn.Open();
-                using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
-                {
-                    cmd.Parameters.Add(_Database.CreateParameter("region_id", wl.regionID.ToString() ));
-                    NpgsqlDataReader dr = cmd.ExecuteReader();
-                    exists = dr.Read();
-                }
-            }
-            if (exists)
-            {
-                RemoveRegionWindlightSettings(wl.regionID);
-            }
-
-            // sql insert
-            sql = @"INSERT INTO regionwindlight
-                       (region_id
-                       ,water_color_r
-                       ,water_color_g
-                       ,water_color_b
-                       ,water_fog_density_exponent
-                       ,underwater_fog_modifier
-                       ,reflection_wavelet_scale_1
-                       ,reflection_wavelet_scale_2
-                       ,reflection_wavelet_scale_3
-                       ,fresnel_scale
-                       ,fresnel_offset
-                       ,refract_scale_above
-                       ,refract_scale_below
-                       ,blur_multiplier
-                       ,big_wave_direction_x
-                       ,big_wave_direction_y
-                       ,little_wave_direction_x
-                       ,little_wave_direction_y
-                       ,normal_map_texture
-                       ,horizon_r
-                       ,horizon_g
-                       ,horizon_b
-                       ,horizon_i
-                       ,haze_horizon
-                       ,blue_density_r
-                       ,blue_density_g
-                       ,blue_density_b
-                       ,blue_density_i
-                       ,haze_density
-                       ,density_multiplier
-                       ,distance_multiplier
-                       ,max_altitude
-                       ,sun_moon_color_r
-                       ,sun_moon_color_g
-                       ,sun_moon_color_b
-                       ,sun_moon_color_i
-                       ,sun_moon_position
-                       ,ambient_r
-                       ,ambient_g
-                       ,ambient_b
-                       ,ambient_i
-                       ,east_angle
-                       ,sun_glow_focus
-                       ,sun_glow_size
-                       ,scene_gamma
-                       ,star_brightness
-                       ,cloud_color_r
-                       ,cloud_color_g
-                       ,cloud_color_b
-                       ,cloud_color_i
-                       ,cloud_x
-                       ,cloud_y
-                       ,cloud_density
-                       ,cloud_coverage
-                       ,cloud_scale
-                       ,cloud_detail_x
-                       ,cloud_detail_y
-                       ,cloud_detail_density
-                       ,cloud_scroll_x
-                       ,cloud_scroll_x_lock
-                       ,cloud_scroll_y
-                       ,cloud_scroll_y_lock
-                       ,draw_classic_clouds)
-                 VALUES
-                       (:region_id
-                       ,:water_color_r
-                       ,:water_color_g
-                       ,:water_color_b
-                       ,:water_fog_density_exponent
-                       ,:underwater_fog_modifier
-                       ,:reflection_wavelet_scale_1
-                       ,:reflection_wavelet_scale_2
-                       ,:reflection_wavelet_scale_3
-                       ,:fresnel_scale
-                       ,:fresnel_offset
-                       ,:refract_scale_above
-                       ,:refract_scale_below
-                       ,:blur_multiplier
-                       ,:big_wave_direction_x
-                       ,:big_wave_direction_y
-                       ,:little_wave_direction_x
-                       ,:little_wave_direction_y
-                       ,:normal_map_texture
-                       ,:horizon_r
-                       ,:horizon_g
-                       ,:horizon_b
-                       ,:horizon_i
-                       ,:haze_horizon
-                       ,:blue_density_r
-                       ,:blue_density_g
-                       ,:blue_density_b
-                       ,:blue_density_i
-                       ,:haze_density
-                       ,:density_multiplier
-                       ,:distance_multiplier
-                       ,:max_altitude
-                       ,:sun_moon_color_r
-                       ,:sun_moon_color_g
-                       ,:sun_moon_color_b
-                       ,:sun_moon_color_i
-                       ,:sun_moon_position
-                       ,:ambient_r
-                       ,:ambient_g
-                       ,:ambient_b
-                       ,:ambient_i
-                       ,:east_angle
-                       ,:sun_glow_focus
-                       ,:sun_glow_size
-                       ,:scene_gamma
-                       ,:star_brightness
-                       ,:cloud_color_r
-                       ,:cloud_color_g
-                       ,:cloud_color_b
-                       ,:cloud_color_i
-                       ,:cloud_x
-                       ,:cloud_y
-                       ,:cloud_density
-                       ,:cloud_coverage
-                       ,:cloud_scale
-                       ,:cloud_detail_x
-                       ,:cloud_detail_y
-                       ,:cloud_detail_density
-                       ,:cloud_scroll_x
-                       ,:cloud_scroll_x_lock
-                       ,:cloud_scroll_y
-                       ,:cloud_scroll_y_lock
-                       ,:draw_classic_clouds);";
-
-            using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
-            {
-                conn.Open();
-                using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
-                {
-                    cmd.Parameters.Add(_Database.CreateParameter("region_id", wl.regionID.ToString()));
-                    cmd.Parameters.Add(_Database.CreateParameter("water_color_r", wl.waterColor.X));
-                    cmd.Parameters.Add(_Database.CreateParameter("water_color_g", wl.waterColor.Y));
-                    cmd.Parameters.Add(_Database.CreateParameter("water_color_b", wl.waterColor.Z));
-                    cmd.Parameters.Add(_Database.CreateParameter("water_fog_density_exponent", wl.waterFogDensityExponent));
-                    cmd.Parameters.Add(_Database.CreateParameter("underwater_fog_modifier", wl.underwaterFogModifier));
-                    cmd.Parameters.Add(_Database.CreateParameter("reflection_wavelet_scale_1", wl.reflectionWaveletScale.X));
-                    cmd.Parameters.Add(_Database.CreateParameter("reflection_wavelet_scale_2", wl.reflectionWaveletScale.Y));
-                    cmd.Parameters.Add(_Database.CreateParameter("reflection_wavelet_scale_3", wl.reflectionWaveletScale.Z));
-                    cmd.Parameters.Add(_Database.CreateParameter("fresnel_scale", wl.fresnelScale));
-                    cmd.Parameters.Add(_Database.CreateParameter("fresnel_offset", wl.fresnelOffset));
-                    cmd.Parameters.Add(_Database.CreateParameter("refract_scale_above", wl.refractScaleAbove));
-                    cmd.Parameters.Add(_Database.CreateParameter("refract_scale_below", wl.refractScaleBelow));
-                    cmd.Parameters.Add(_Database.CreateParameter("blur_multiplier", wl.blurMultiplier));
-                    cmd.Parameters.Add(_Database.CreateParameter("big_wave_direction_x", wl.bigWaveDirection.X));
-                    cmd.Parameters.Add(_Database.CreateParameter("big_wave_direction_y", wl.bigWaveDirection.Y));
-                    cmd.Parameters.Add(_Database.CreateParameter("little_wave_direction_x", wl.littleWaveDirection.X));
-                    cmd.Parameters.Add(_Database.CreateParameter("little_wave_direction_y", wl.littleWaveDirection.Y));
-                    cmd.Parameters.Add(_Database.CreateParameter("normal_map_texture", wl.normalMapTexture.ToString()));
-                    cmd.Parameters.Add(_Database.CreateParameter("horizon_r", wl.horizon.X));
-                    cmd.Parameters.Add(_Database.CreateParameter("horizon_g", wl.horizon.Y));
-                    cmd.Parameters.Add(_Database.CreateParameter("horizon_b", wl.horizon.Z));
-                    cmd.Parameters.Add(_Database.CreateParameter("horizon_i", wl.horizon.W));
-                    cmd.Parameters.Add(_Database.CreateParameter("haze_horizon", wl.hazeHorizon));
-                    cmd.Parameters.Add(_Database.CreateParameter("blue_density_r", wl.blueDensity.X));
-                    cmd.Parameters.Add(_Database.CreateParameter("blue_density_g", wl.blueDensity.Y));
-                    cmd.Parameters.Add(_Database.CreateParameter("blue_density_b", wl.blueDensity.Z));
-                    cmd.Parameters.Add(_Database.CreateParameter("blue_density_i", wl.blueDensity.W));
-                    cmd.Parameters.Add(_Database.CreateParameter("haze_density", wl.hazeDensity));
-                    cmd.Parameters.Add(_Database.CreateParameter("density_multiplier", wl.densityMultiplier));
-                    cmd.Parameters.Add(_Database.CreateParameter("distance_multiplier", wl.distanceMultiplier));
-                    cmd.Parameters.Add(_Database.CreateParameter("max_altitude", wl.maxAltitude));
-                    cmd.Parameters.Add(_Database.CreateParameter("sun_moon_color_r", wl.sunMoonColor.X));
-                    cmd.Parameters.Add(_Database.CreateParameter("sun_moon_color_g", wl.sunMoonColor.Y));
-                    cmd.Parameters.Add(_Database.CreateParameter("sun_moon_color_b", wl.sunMoonColor.Z));
-                    cmd.Parameters.Add(_Database.CreateParameter("sun_moon_color_i", wl.sunMoonColor.W));
-                    cmd.Parameters.Add(_Database.CreateParameter("sun_moon_position", wl.sunMoonPosition));
-                    cmd.Parameters.Add(_Database.CreateParameter("ambient_r", wl.ambient.X));
-                    cmd.Parameters.Add(_Database.CreateParameter("ambient_g", wl.ambient.Y));
-                    cmd.Parameters.Add(_Database.CreateParameter("ambient_b", wl.ambient.Z));
-                    cmd.Parameters.Add(_Database.CreateParameter("ambient_i", wl.ambient.W));
-                    cmd.Parameters.Add(_Database.CreateParameter("east_angle", wl.eastAngle));
-                    cmd.Parameters.Add(_Database.CreateParameter("sun_glow_focus", wl.sunGlowFocus));
-                    cmd.Parameters.Add(_Database.CreateParameter("sun_glow_size", wl.sunGlowSize));
-                    cmd.Parameters.Add(_Database.CreateParameter("scene_gamma", wl.sceneGamma));
-                    cmd.Parameters.Add(_Database.CreateParameter("star_brightness", wl.starBrightness));
-                    cmd.Parameters.Add(_Database.CreateParameter("cloud_color_r", wl.cloudColor.X));
-                    cmd.Parameters.Add(_Database.CreateParameter("cloud_color_g", wl.cloudColor.Y));
-                    cmd.Parameters.Add(_Database.CreateParameter("cloud_color_b", wl.cloudColor.Z));
-                    cmd.Parameters.Add(_Database.CreateParameter("cloud_color_i", wl.cloudColor.W));
-                    cmd.Parameters.Add(_Database.CreateParameter("cloud_x", wl.cloudXYDensity.X));
-                    cmd.Parameters.Add(_Database.CreateParameter("cloud_y", wl.cloudXYDensity.Y));
-                    cmd.Parameters.Add(_Database.CreateParameter("cloud_density", wl.cloudXYDensity.Z));
-                    cmd.Parameters.Add(_Database.CreateParameter("cloud_coverage", wl.cloudCoverage));
-                    cmd.Parameters.Add(_Database.CreateParameter("cloud_scale", wl.cloudScale));
-                    cmd.Parameters.Add(_Database.CreateParameter("cloud_detail_x", wl.cloudDetailXYDensity.X));
-                    cmd.Parameters.Add(_Database.CreateParameter("cloud_detail_y", wl.cloudDetailXYDensity.Y));
-                    cmd.Parameters.Add(_Database.CreateParameter("cloud_detail_density", wl.cloudDetailXYDensity.Z));
-                    cmd.Parameters.Add(_Database.CreateParameter("cloud_scroll_x", wl.cloudScrollX));
-                    cmd.Parameters.Add(_Database.CreateParameter("cloud_scroll_x_lock", wl.cloudScrollXLock));
-                    cmd.Parameters.Add(_Database.CreateParameter("cloud_scroll_y", wl.cloudScrollY));
-                    cmd.Parameters.Add(_Database.CreateParameter("cloud_scroll_y_lock", wl.cloudScrollYLock));
-                    cmd.Parameters.Add(_Database.CreateParameter("draw_classic_clouds", wl.drawClassicClouds));
-
-                    cmd.ExecuteNonQuery();
-                }
-            }
-            #region update
-            //            }
-            //            else
-            //            {
-            //                // sql update
-            //                sql = @"UPDATE [OpenSim].[dbo].[regionwindlight]
-            //   SET [region_id] =                   @region_id
-            //      ,[water_color_r] =               @water_color_r
-            //      ,[water_color_g] =               @water_color_g
-            //      ,[water_color_b] =               @water_color_b
-            //      ,[water_fog_density_exponent] =  @water_fog_density_exponent
-            //      ,[underwater_fog_modifier] =     @underwater_fog_modifier
-            //      ,[reflection_wavelet_scale_1] =  @reflection_wavelet_scale_1
-            //      ,[reflection_wavelet_scale_2] =  @reflection_wavelet_scale_2
-            //      ,[reflection_wavelet_scale_3] =  @reflection_wavelet_scale_3
-            //      ,[fresnel_scale] =               @fresnel_scale
-            //      ,[fresnel_offset] =              @fresnel_offset
-            //      ,[refract_scale_above] =         @refract_scale_above
-            //      ,[refract_scale_below] =         @refract_scale_below
-            //      ,[blur_multiplier] =             @blur_multiplier
-            //      ,[big_wave_direction_x] =        @big_wave_direction_x
-            //      ,[big_wave_direction_y] =        @big_wave_direction_y
-            //      ,[little_wave_direction_x] =     @little_wave_direction_x
-            //      ,[little_wave_direction_y] =     @little_wave_direction_y
-            //      ,[normal_map_texture] =          @normal_map_texture
-            //      ,[horizon_r] =                   @horizon_r
-            //      ,[horizon_g] =                   @horizon_g
-            //      ,[horizon_b] =                   @horizon_b
-            //      ,[horizon_i] =                   @horizon_i
-            //      ,[haze_horizon] =                @haze_horizon
-            //      ,[blue_density_r] =              @blue_density_r
-            //      ,[blue_density_g] =              @blue_density_g
-            //      ,[blue_density_b] =              @blue_density_b
-            //      ,[blue_density_i] =              @blue_density_i
-            //      ,[haze_density] =                @haze_density
-            //      ,[density_multiplier] =          @density_multiplier
-            //      ,[distance_multiplier] =         @distance_multiplier
-            //      ,[max_altitude] =                @max_altitude
-            //      ,[sun_moon_color_r] =            @sun_moon_color_r
-            //      ,[sun_moon_color_g] =            @sun_moon_color_g
-            //      ,[sun_moon_color_b] =            @sun_moon_color_b
-            //      ,[sun_moon_color_i] =            @sun_moon_color_i
-            //      ,[sun_moon_position] =           @sun_moon_position
-            //      ,[ambient_r] =                   @ambient_r
-            //      ,[ambient_g] =                   @ambient_g
-            //      ,[ambient_b] =                   @ambient_b
-            //      ,[ambient_i] =                   @ambient_i
-            //      ,[east_angle] =                  @east_angle
-            //      ,[sun_glow_focus] =              @sun_glow_focus
-            //      ,[sun_glow_size] =               @sun_glow_size
-            //      ,[scene_gamma] =                 @scene_gamma
-            //      ,[star_brightness] =             @star_brightness
-            //      ,[cloud_color_r] =               @cloud_color_r
-            //      ,[cloud_color_g] =               @cloud_color_g
-            //      ,[cloud_color_b] =               @cloud_color_b
-            //      ,[cloud_color_i] =               @cloud_color_i
-            //      ,[cloud_x] =                     @cloud_x
-            //      ,[cloud_y] =                     @cloud_y
-            //      ,[cloud_density] =               @cloud_density
-            //      ,[cloud_coverage] =              @cloud_coverage
-            //      ,[cloud_scale] =                 @cloud_scale
-            //      ,[cloud_detail_x] =              @cloud_detail_x
-            //      ,[cloud_detail_y] =              @cloud_detail_y
-            //      ,[cloud_detail_density] =        @cloud_detail_density
-            //      ,[cloud_scroll_x] =              @cloud_scroll_x
-            //      ,[cloud_scroll_x_lock] =         @cloud_scroll_x_lock
-            //      ,[cloud_scroll_y] =              @cloud_scroll_y
-            //      ,[cloud_scroll_y_lock] =         @cloud_scroll_y_lock
-            //      ,[draw_classic_clouds] =         @draw_classic_clouds
-            // WHERE region_id = @region_id";
-            //                using (SqlConnection conn = new SqlConnection(m_connectionString))
-            //                {
-            //                    conn.Open();
-            //                    using (SqlCommand cmd = new SqlCommand(sql, conn))
-            //                    {
-            //                        cmd.Parameters.AddWithValue("region_id", wl.regionID);
-            //                        cmd.Parameters.AddWithValue("water_color_r", wl.waterColor.X);
-            //                        cmd.Parameters.AddWithValue("water_color_g", wl.waterColor.Y);
-            //                        cmd.Parameters.AddWithValue("water_color_b", wl.waterColor.Z);
-            //                        cmd.Parameters.AddWithValue("water_fog_density_exponent", wl.waterFogDensityExponent);
-            //                        cmd.Parameters.AddWithValue("underwater_fog_modifier", wl.underwaterFogModifier);
-            //                        cmd.Parameters.AddWithValue("reflection_wavelet_scale_1", wl.reflectionWaveletScale.X);
-            //                        cmd.Parameters.AddWithValue("reflection_wavelet_scale_2", wl.reflectionWaveletScale.Y);
-            //                        cmd.Parameters.AddWithValue("reflection_wavelet_scale_3", wl.reflectionWaveletScale.Z);
-            //                        cmd.Parameters.AddWithValue("fresnel_scale", wl.fresnelScale);
-            //                        cmd.Parameters.AddWithValue("fresnel_offset", wl.fresnelOffset);
-            //                        cmd.Parameters.AddWithValue("refract_scale_above", wl.refractScaleAbove);
-            //                        cmd.Parameters.AddWithValue("refract_scale_below", wl.refractScaleBelow);
-            //                        cmd.Parameters.AddWithValue("blur_multiplier", wl.blurMultiplier);
-            //                        cmd.Parameters.AddWithValue("big_wave_direction_x", wl.bigWaveDirection.X);
-            //                        cmd.Parameters.AddWithValue("big_wave_direction_y", wl.bigWaveDirection.Y);
-            //                        cmd.Parameters.AddWithValue("little_wave_direction_x", wl.littleWaveDirection.X);
-            //                        cmd.Parameters.AddWithValue("little_wave_direction_y", wl.littleWaveDirection.Y);
-            //                        cmd.Parameters.AddWithValue("normal_map_texture", wl.normalMapTexture);
-            //                        cmd.Parameters.AddWithValue("horizon_r", wl.horizon.X);
-            //                        cmd.Parameters.AddWithValue("horizon_g", wl.horizon.Y);
-            //                        cmd.Parameters.AddWithValue("horizon_b", wl.horizon.Z);
-            //                        cmd.Parameters.AddWithValue("horizon_i", wl.horizon.W);
-            //                        cmd.Parameters.AddWithValue("haze_horizon", wl.hazeHorizon);
-            //                        cmd.Parameters.AddWithValue("blue_density_r", wl.blueDensity.X);
-            //                        cmd.Parameters.AddWithValue("blue_density_g", wl.blueDensity.Y);
-            //                        cmd.Parameters.AddWithValue("blue_density_b", wl.blueDensity.Z);
-            //                        cmd.Parameters.AddWithValue("blue_density_i", wl.blueDensity.W);
-            //                        cmd.Parameters.AddWithValue("haze_density", wl.hazeDensity);
-            //                        cmd.Parameters.AddWithValue("density_multiplier", wl.densityMultiplier);
-            //                        cmd.Parameters.AddWithValue("distance_multiplier", wl.distanceMultiplier);
-            //                        cmd.Parameters.AddWithValue("max_altitude", wl.maxAltitude);
-            //                        cmd.Parameters.AddWithValue("sun_moon_color_r", wl.sunMoonColor.X);
-            //                        cmd.Parameters.AddWithValue("sun_moon_color_g", wl.sunMoonColor.Y);
-            //                        cmd.Parameters.AddWithValue("sun_moon_color_b", wl.sunMoonColor.Z);
-            //                        cmd.Parameters.AddWithValue("sun_moon_color_i", wl.sunMoonColor.W);
-            //                        cmd.Parameters.AddWithValue("sun_moon_position", wl.sunMoonPosition);
-            //                        cmd.Parameters.AddWithValue("ambient_r", wl.ambient.X);
-            //                        cmd.Parameters.AddWithValue("ambient_g", wl.ambient.Y);
-            //                        cmd.Parameters.AddWithValue("ambient_b", wl.ambient.Z);
-            //                        cmd.Parameters.AddWithValue("ambient_i", wl.ambient.W);
-            //                        cmd.Parameters.AddWithValue("east_angle", wl.eastAngle);
-            //                        cmd.Parameters.AddWithValue("sun_glow_focus", wl.sunGlowFocus);
-            //                        cmd.Parameters.AddWithValue("sun_glow_size", wl.sunGlowSize);
-            //                        cmd.Parameters.AddWithValue("scene_gamma", wl.sceneGamma);
-            //                        cmd.Parameters.AddWithValue("star_brightness", wl.starBrightness);
-            //                        cmd.Parameters.AddWithValue("cloud_color_r", wl.cloudColor.X);
-            //                        cmd.Parameters.AddWithValue("cloud_color_g", wl.cloudColor.Y);
-            //                        cmd.Parameters.AddWithValue("cloud_color_b", wl.cloudColor.Z);
-            //                        cmd.Parameters.AddWithValue("cloud_color_i", wl.cloudColor.W);
-            //                        cmd.Parameters.AddWithValue("cloud_x", wl.cloudXYDensity.X);
-            //                        cmd.Parameters.AddWithValue("cloud_y", wl.cloudXYDensity.Y);
-            //                        cmd.Parameters.AddWithValue("cloud_density", wl.cloudXYDensity.Z);
-            //                        cmd.Parameters.AddWithValue("cloud_coverage", wl.cloudCoverage);
-            //                        cmd.Parameters.AddWithValue("cloud_scale", wl.cloudScale);
-            //                        cmd.Parameters.AddWithValue("cloud_detail_x", wl.cloudDetailXYDensity.X);
-            //                        cmd.Parameters.AddWithValue("cloud_detail_y", wl.cloudDetailXYDensity.Y);
-            //                        cmd.Parameters.AddWithValue("cloud_detail_density", wl.cloudDetailXYDensity.Z);
-            //                        cmd.Parameters.AddWithValue("cloud_scroll_x", wl.cloudScrollX);
-            //                        cmd.Parameters.AddWithValue("cloud_scroll_x_lock", wl.cloudScrollXLock);
-            //                        cmd.Parameters.AddWithValue("cloud_scroll_y", wl.cloudScrollY);
-            //                        cmd.Parameters.AddWithValue("cloud_scroll_y_lock", wl.cloudScrollYLock);
-            //                        cmd.Parameters.AddWithValue("draw_classic_clouds", wl.drawClassicClouds);
-
-            //                        cmd.ExecuteNonQuery();
-            //                    }
-            //                }
-            //            }
-            #endregion
-        }
 
         #region Environment Settings
         public string LoadRegionEnvironmentSettings(UUID regionUUID)
@@ -1432,7 +966,7 @@ namespace OpenSim.Data.PGSQL
 ,terrain_lower_limit = :terrain_lower_limit ,use_estate_sun = :use_estate_sun ,fixed_sun = :fixed_sun ,sun_position = :sun_position
 ,covenant = :covenant ,covenant_datetime = :covenant_datetime, sunvectorx = :sunvectorx, sunvectory = :sunvectory, sunvectorz = :sunvectorz,
 ""Sandbox"" = :Sandbox, loaded_creation_datetime = :loaded_creation_datetime, loaded_creation_id = :loaded_creation_id, ""map_tile_ID"" = :TerrainImageID,
-""TelehubObject"" = :telehubobject, ""parcel_tile_ID"" = :ParcelImageID
+""TelehubObject"" = :telehubobject, ""parcel_tile_ID"" = :ParcelImageID, ""cacheID"" = :cacheID
  WHERE ""regionUUID"" = :regionUUID";
 
                 using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
@@ -1547,6 +1081,8 @@ namespace OpenSim.Data.PGSQL
             newSettings.ParcelImageID = new UUID((Guid)row["parcel_tile_ID"]);
             newSettings.TelehubObject = new UUID((Guid)row["TelehubObject"]);
 
+            if (!(row["cacheID"] is DBNull))
+                newSettings.CacheID = new UUID((Guid)row["cacheID"]);
             return newSettings;
         }
 
@@ -1602,7 +1138,6 @@ namespace OpenSim.Data.PGSQL
             newData.OtherCleanTime = Convert.ToInt32(row["OtherCleanTime"]);
             newData.Dwell = Convert.ToSingle(row["Dwell"]);
 
-
             try
             {
                 newData.UserLocation =
@@ -1632,6 +1167,35 @@ namespace OpenSim.Data.PGSQL
             newData.AnyAVSounds = Convert.ToBoolean(row["AnyAVSounds"]);
             newData.GroupAVSounds = Convert.ToBoolean(row["GroupAVSounds"]);
 
+            if (row["environment"] is DBNull)
+            {
+                newData.Environment = null;
+                newData.EnvironmentVersion = -1;
+            }
+            else
+            {
+                string env = (string)row["environment"];
+                if (string.IsNullOrEmpty(env))
+                {
+                    newData.Environment = null;
+                    newData.EnvironmentVersion = -1;
+                }
+                else
+                {
+                    try
+                    {
+                        ViewerEnvironment VEnv = ViewerEnvironment.FromOSDString(env);
+                        newData.Environment = VEnv;
+                        newData.EnvironmentVersion = VEnv.version;
+                    }
+                    catch
+                    {
+                        newData.Environment = null;
+                        newData.EnvironmentVersion = -1;
+                    }
+                }
+            }
+
             return newData;
         }
 
@@ -1692,9 +1256,9 @@ namespace OpenSim.Data.PGSQL
             prim.BaseMask = Convert.ToUInt32(primRow["BaseMask"]);
             // vectors
             prim.OffsetPosition = new Vector3(
-                                    Convert.ToSingle(primRow["PositionX"]),
-                                    Convert.ToSingle(primRow["PositionY"]),
-                                    Convert.ToSingle(primRow["PositionZ"]));
+                                Convert.ToSingle(primRow["PositionX"]),
+                                Convert.ToSingle(primRow["PositionY"]),
+                                Convert.ToSingle(primRow["PositionZ"]));
 
             prim.GroupPosition = new Vector3(
                                     Convert.ToSingle(primRow["GroupPositionX"]),
@@ -1707,9 +1271,9 @@ namespace OpenSim.Data.PGSQL
                                 Convert.ToSingle(primRow["VelocityZ"]));
 
             prim.AngularVelocity = new Vector3(
-                                    Convert.ToSingle(primRow["AngularVelocityX"]),
-                                    Convert.ToSingle(primRow["AngularVelocityY"]),
-                                    Convert.ToSingle(primRow["AngularVelocityZ"]));
+                                Convert.ToSingle(primRow["AngularVelocityX"]),
+                                Convert.ToSingle(primRow["AngularVelocityY"]),
+                                Convert.ToSingle(primRow["AngularVelocityZ"]));
 
             prim.Acceleration = new Vector3(
                                 Convert.ToSingle(primRow["AccelerationX"]),
@@ -1728,12 +1292,20 @@ namespace OpenSim.Data.PGSQL
                                 Convert.ToSingle(primRow["SitTargetOffsetY"]),
                                 Convert.ToSingle(primRow["SitTargetOffsetZ"]));
 
+
             prim.SitTargetOrientationLL = new Quaternion(
                                 Convert.ToSingle(primRow["SitTargetOrientX"]),
                                 Convert.ToSingle(primRow["SitTargetOrientY"]),
                                 Convert.ToSingle(primRow["SitTargetOrientZ"]),
                                 Convert.ToSingle(primRow["SitTargetOrientW"]));
 
+            prim.StandOffset = new Vector3(
+                               Convert.ToSingle(primRow["standtargetx"]),
+                               Convert.ToSingle(primRow["standtargety"]),
+                               Convert.ToSingle(primRow["standtargetz"]));
+
+            prim.SitActiveRange = Convert.ToSingle(primRow["sitactrange"]);
+
             prim.PayPrice[0] = Convert.ToInt32(primRow["PayPrice"]);
             prim.PayPrice[1] = Convert.ToInt32(primRow["PayButton1"]);
             prim.PayPrice[2] = Convert.ToInt32(primRow["PayButton2"]);
@@ -1752,11 +1324,6 @@ namespace OpenSim.Data.PGSQL
             if (!(primRow["ParticleSystem"] is DBNull))
                 prim.ParticleSystem = (Byte[])primRow["ParticleSystem"];
 
-            prim.AngularVelocity = new Vector3(
-                                        Convert.ToSingle(primRow["OmegaX"]),
-                                        Convert.ToSingle(primRow["OmegaY"]),
-                                        Convert.ToSingle(primRow["OmegaZ"]));
-
             prim.SetCameraEyeOffset(new Vector3(
                                         Convert.ToSingle(primRow["CameraEyeOffsetX"]),
                                         Convert.ToSingle(primRow["CameraEyeOffsetY"]),
@@ -1822,6 +1389,10 @@ namespace OpenSim.Data.PGSQL
                 pdata = PhysicsInertiaData.FromXml2(primRow["PhysInertia"].ToString());
             prim.PhysicsInertia = pdata;
 
+            int pseudocrc = Convert.ToInt32(primRow["pseudocrc"]);
+            if(pseudocrc != 0)
+                prim.PseudoCRC = pseudocrc;
+
             return prim;
         }
 
@@ -2008,6 +1579,8 @@ namespace OpenSim.Data.PGSQL
             parameters.Add(_Database.CreateParameter("ParcelImageID", settings.ParcelImageID));
             parameters.Add(_Database.CreateParameter("TelehubObject", settings.TelehubObject));
 
+            parameters.Add(_Database.CreateParameter("cacheID", settings.CacheID));
+
             return parameters.ToArray();
         }
 
@@ -2069,6 +1642,20 @@ namespace OpenSim.Data.PGSQL
             parameters.Add(_Database.CreateParameter("AnyAVSounds", land.AnyAVSounds));
             parameters.Add(_Database.CreateParameter("GroupAVSounds", land.GroupAVSounds));
 
+            if (land.Environment == null)
+                parameters.Add(_Database.CreateParameter("environment", ""));
+            else
+            {
+                try
+                {
+                    parameters.Add(_Database.CreateParameter("environment", ViewerEnvironment.ToOSDString(land.Environment)));
+                }
+                catch
+                {
+                    parameters.Add(_Database.CreateParameter("environment", ""));
+                }
+            }
+
             return parameters.ToArray();
         }
 
@@ -2162,6 +1749,13 @@ namespace OpenSim.Data.PGSQL
             parameters.Add(_Database.CreateParameter("SitTargetOrientY", sitTargetOrient.Y));
             parameters.Add(_Database.CreateParameter("SitTargetOrientZ", sitTargetOrient.Z));
 
+            Vector3 standTargetPos = prim.StandOffset;
+            parameters.Add(_Database.CreateParameter("standtargetx", standTargetPos.X));
+            parameters.Add(_Database.CreateParameter("standtargety", standTargetPos.Y));
+            parameters.Add(_Database.CreateParameter("standtargetz", standTargetPos.Z));
+
+            parameters.Add(_Database.CreateParameter("sitactrange", prim.SitActiveRange));
+
             parameters.Add(_Database.CreateParameter("PayPrice", prim.PayPrice[0]));
             parameters.Add(_Database.CreateParameter("PayButton1", prim.PayPrice[1]));
             parameters.Add(_Database.CreateParameter("PayButton2", prim.PayPrice[2]));
@@ -2182,10 +1776,6 @@ namespace OpenSim.Data.PGSQL
             parameters.Add(_Database.CreateParameter("TextureAnimation", prim.TextureAnimation));
             parameters.Add(_Database.CreateParameter("ParticleSystem", prim.ParticleSystem));
 
-            parameters.Add(_Database.CreateParameter("OmegaX", prim.AngularVelocity.X));
-            parameters.Add(_Database.CreateParameter("OmegaY", prim.AngularVelocity.Y));
-            parameters.Add(_Database.CreateParameter("OmegaZ", prim.AngularVelocity.Z));
-
             parameters.Add(_Database.CreateParameter("CameraEyeOffsetX", prim.GetCameraEyeOffset().X));
             parameters.Add(_Database.CreateParameter("CameraEyeOffsetY", prim.GetCameraEyeOffset().Y));
             parameters.Add(_Database.CreateParameter("CameraEyeOffsetZ", prim.GetCameraEyeOffset().Z));
@@ -2241,12 +1831,12 @@ namespace OpenSim.Data.PGSQL
             if (prim.VehicleParams != null)
                 parameters.Add(_Database.CreateParameter("Vehicle", prim.VehicleParams.ToXml2()));
             else
-                parameters.Add(_Database.CreateParameter("Vehicle", String.Empty));
+                parameters.Add(_Database.CreateParameter("Vehicle", string.Empty));
 
             if (prim.PhysicsInertia != null)
                 parameters.Add(_Database.CreateParameter("PhysInertia", prim.PhysicsInertia.ToXml2()));
             else
-                parameters.Add(_Database.CreateParameter("PhysInertia", String.Empty));
+                parameters.Add(_Database.CreateParameter("PhysInertia", string.Empty));
 
             if (prim.DynAttrs != null && prim.DynAttrs.CountNamespaces > 0)
                 parameters.Add(_Database.CreateParameter("DynAttrs", prim.DynAttrs.ToXml()));
@@ -2260,6 +1850,8 @@ namespace OpenSim.Data.PGSQL
             parameters.Add(_Database.CreateParameter("Restitution", (double)prim.Restitution));
             parameters.Add(_Database.CreateParameter("RotationAxisLocks", prim.RotationAxisLocks));
 
+            parameters.Add(_Database.CreateParameter("pseudocrc", prim.PseudoCRC));
+
             return parameters.ToArray();
         }
 

+ 6 - 0
OpenSim/Data/PGSQL/Resources/EstateStore.migrations

@@ -133,3 +133,9 @@ ALTER TABLE "public"."estateban"
     ADD COLUMN "banningUUID" uuid NOT NULL,
     ADD COLUMN "banTime" int4 NOT NULL DEFAULT 0;
 COMMIT;
+
+:VERSION 15
+BEGIN TRANSACTION;
+ALTER TABLE "public"."estate_settings"
+    ADD COLUMN "AllowEnviromentOverride" bool NOT NULL;
+COMMIT;

+ 23 - 0
OpenSim/Data/PGSQL/Resources/RegionStore.migrations

@@ -1232,3 +1232,26 @@ BEGIN TRANSACTION;
 
 ALTER TABLE prims ADD "Vehicle" TEXT;
 COMMIT;
+
+:VERSION 49         #----- Add standtarget and sit range
+
+BEGIN;
+ALTER TABLE `prims` 
+ADD COLUMN `standtargetx` real DEFAULT '0.0',
+ADD COLUMN `standtargety` real DEFAULT '0.0',
+ADD COLUMN `standtargetz` real DEFAULT '0.0',
+ADD COLUMN `sitactrange` real DEFAULT '0.0';
+COMMIT;
+
+
+:VERSION 50         #----- Add pseudo CRC and region cache id
+
+BEGIN;
+ALTER TABLE `prims` ADD COLUMN `pseudocrc` integer DEFAULT '0';
+ALTER TABLE `regionsettings` ADD COLUMN `cacheID` uuid DEFAULT NULL;
+COMMIT;
+
+:VERSION 51         #----- parcel environment store
+BEGIN;
+ALTER TABLE `land` ADD COLUMN `environment` varchar default NULL;
+COMMIT;

+ 6 - 0
OpenSim/Data/SQLite/Resources/EstateStore.migrations

@@ -74,4 +74,10 @@ ALTER TABLE `estateban` ADD COLUMN `banningUUID` varchar(36) NOT NULL DEFAULT '0
 ALTER TABLE `estateban` ADD COLUMN `banTime` integer NOT NULL DEFAULT 0;
 COMMIT;
 
+:VERSION 12
+BEGIN;
+ALTER TABLE `estate_settings`
+    ADD COLUMN `AllowEnviromentOverride` tinyint not null default 0;
+COMMIT;
+
 

+ 30 - 8
OpenSim/Data/SQLite/Resources/RegionStore.migrations

@@ -183,14 +183,14 @@ CREATE TABLE IF NOT EXISTS land(
        UserLookAtY float,
        UserLookAtZ float,
        AuthbuyerID varchar(36) NOT NULL default  '00000000-0000-0000-0000-000000000000', 
-	   OtherCleanTime INTEGER NOT NULL default 0, 
-	   Dwell INTEGER NOT NULL default 0, 
-	   `MediaType` VARCHAR(32) NOT NULL DEFAULT 'none/none', 
-	   `MediaDescription` VARCHAR(255) NOT NULL DEFAULT '', 
-	   `MediaSize` VARCHAR(16) NOT NULL DEFAULT '0,0', 
-	   `MediaLoop` BOOLEAN NOT NULL DEFAULT FALSE, 
-	   `ObscureMusic` BOOLEAN NOT NULL DEFAULT FALSE, 
-	   `ObscureMedia` BOOLEAN NOT NULL DEFAULT FALSE);
+       OtherCleanTime INTEGER NOT NULL default 0, 
+       Dwell INTEGER NOT NULL default 0, 
+       `MediaType` VARCHAR(32) NOT NULL DEFAULT 'none/none', 
+       `MediaDescription` VARCHAR(255) NOT NULL DEFAULT '', 
+       `MediaSize` VARCHAR(16) NOT NULL DEFAULT '0,0', 
+       `MediaLoop` BOOLEAN NOT NULL DEFAULT FALSE, 
+       `ObscureMusic` BOOLEAN NOT NULL DEFAULT FALSE, 
+       `ObscureMedia` BOOLEAN NOT NULL DEFAULT FALSE);
 
 CREATE TABLE IF NOT EXISTS landaccesslist(
        LandUUID varchar(255),
@@ -377,3 +377,25 @@ COMMIT;
 BEGIN;
 ALTER TABLE `prims` ADD COLUMN `PhysInertia` TEXT default NULL;
 COMMIT;
+
+:VERSION 37         #----- Add standtarget and sit range
+
+BEGIN;
+ALTER TABLE `prims` ADD COLUMN `standtargetx` float NOT NULL DEFAULT '0.0';
+ALTER TABLE `prims` ADD COLUMN `standtargety` float NOT NULL DEFAULT '0.0';
+ALTER TABLE `prims` ADD COLUMN `standtargetz` float NOT NULL DEFAULT '0.0';
+ALTER TABLE `prims` ADD COLUMN `sitactrange` float NOT NULL DEFAULT '0.0';
+COMMIT;
+
+
+:VERSION 38         #----- Add pseudo CRC and region cache id
+
+BEGIN;
+ALTER TABLE `prims` ADD COLUMN `pseudocrc` integer DEFAULT '0';
+ALTER TABLE `regionsettings` ADD COLUMN `cacheID` char(36) DEFAULT NULL;
+COMMIT;
+
+:VERSION 39         #----- parcel environment store
+BEGIN;
+ALTER TABLE `land` ADD COLUMN `environment` TEXT default NULL;
+COMMIT;

+ 33 - 41
OpenSim/Data/SQLite/SQLiteEstateData.cs

@@ -186,13 +186,10 @@ namespace OpenSim.Data.SQLite
         private void DoCreate(EstateSettings es)
         {
             List<string> names = new List<string>(FieldList);
-
-            IDataReader r = null;
+            names.Remove("EstateID");
 
             using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
             {
-                names.Remove("EstateID");
-
                 string sql = "insert into estate_settings ("+String.Join(",", names.ToArray())+") values ( :"+String.Join(", :", names.ToArray())+")";
 
                 cmd.CommandText = sql;
@@ -217,17 +214,12 @@ namespace OpenSim.Data.SQLite
 
                 cmd.CommandText = "select LAST_INSERT_ROWID() as id";
                 cmd.Parameters.Clear();
-
-                r = cmd.ExecuteReader();
+                using(IDataReader r = cmd.ExecuteReader())
+                {
+                    r.Read();
+                    es.EstateID = Convert.ToUInt32(r["id"]);
+                }
             }
-
-            r.Read();
-
-            es.EstateID = Convert.ToUInt32(r["id"]);
-
-            r.Close();
-
-            es.Save();
         }
 
         public void StoreEstateSettings(EstateSettings es)
@@ -240,11 +232,10 @@ namespace OpenSim.Data.SQLite
             foreach (string f in fields)
                 terms.Add(f+" = :"+f);
 
-            string sql = "update estate_settings set "+String.Join(", ", terms.ToArray())+" where EstateID = :EstateID";
-
             using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
             {
-                cmd.CommandText = sql;
+                cmd.CommandText = "update estate_settings set " + String.Join(", ", terms.ToArray()) + " where EstateID = :EstateID"; ;
+                cmd.Parameters.AddWithValue(":EstateID", es.EstateID);
 
                 foreach (string name in FieldList)
                 {
@@ -472,34 +463,35 @@ namespace OpenSim.Data.SQLite
 
         public bool LinkRegion(UUID regionID, int estateID)
         {
-            SqliteTransaction transaction = m_connection.BeginTransaction();
-
-            // Delete any existing estate mapping for this region.
-            using(SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
-            {
-                cmd.CommandText = "delete from estate_map where RegionID = :RegionID";
-                cmd.Transaction = transaction;
-                cmd.Parameters.AddWithValue(":RegionID", regionID.ToString());
-
-                cmd.ExecuteNonQuery();
-            }
-
-            using(SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
+            using(SqliteTransaction transaction = m_connection.BeginTransaction())
             {
-                cmd.CommandText = "insert into estate_map values (:RegionID, :EstateID)";
-                cmd.Transaction = transaction;
-                cmd.Parameters.AddWithValue(":RegionID", regionID.ToString());
-                cmd.Parameters.AddWithValue(":EstateID", estateID.ToString());
-
-                if (cmd.ExecuteNonQuery() == 0)
+                // Delete any existing estate mapping for this region.
+                using(SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
                 {
-                    transaction.Rollback();
-                    return false;
+                    cmd.CommandText = "delete from estate_map where RegionID = :RegionID";
+                    cmd.Transaction = transaction;
+                    cmd.Parameters.AddWithValue(":RegionID", regionID.ToString());
+
+                    cmd.ExecuteNonQuery();
                 }
-                else
+
+                using(SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
                 {
-                    transaction.Commit();
-                    return true;
+                    cmd.CommandText = "insert into estate_map values (:RegionID, :EstateID)";
+                    cmd.Transaction = transaction;
+                    cmd.Parameters.AddWithValue(":RegionID", regionID.ToString());
+                    cmd.Parameters.AddWithValue(":EstateID", estateID.ToString());
+
+                    if (cmd.ExecuteNonQuery() == 0)
+                    {
+                        transaction.Rollback();
+                        return false;
+                    }
+                    else
+                    {
+                        transaction.Commit();
+                        return true;
+                    }
                 }
             }
         }

+ 100 - 249
OpenSim/Data/SQLite/SQLiteSimulationData.cs

@@ -429,75 +429,6 @@ namespace OpenSim.Data.SQLite
             }
         }
 
-        /// <summary>
-        /// Load windlight settings from region storage
-        /// </summary>
-        /// <param name="regionUUID">RegionID</param>
-        public RegionLightShareData LoadRegionWindlightSettings(UUID regionUUID)
-        {
-            RegionLightShareData wl = null;
-
-            lock (ds)
-            {
-                DataTable windlightTable = ds.Tables["regionwindlight"];
-                DataRow windlightRow = windlightTable.Rows.Find(regionUUID.ToString());
-                if (windlightRow == null)
-                {
-                    wl = new RegionLightShareData();
-                    wl.regionID = regionUUID;
-                    StoreRegionWindlightSettings(wl);
-                    return wl;
-                }
-                wl = buildRegionWindlight(windlightRow);
-                return wl;
-            }
-        }
-
-        /// <summary>
-        /// Remove windlight settings from region storage
-        /// </summary>
-        /// <param name="regionID">RegionID</param>
-        public void RemoveRegionWindlightSettings(UUID regionID)
-        {
-            lock (ds)
-            {
-                DataTable windlightTable = ds.Tables["regionwindlight"];
-                DataRow windlightRow = windlightTable.Rows.Find(regionID.ToString());
-
-                if (windlightRow != null)
-                {
-                    windlightRow.Delete();
-                }
-            }
-            Commit();
-        }
-
-        /// <summary>
-        /// Adds an windlight into region storage
-        /// </summary>
-        /// <param name="wl">RegionLightShareData</param>
-        public void StoreRegionWindlightSettings(RegionLightShareData wl)
-        {
-            lock (ds)
-            {
-                DataTable windlightTable = ds.Tables["regionwindlight"];
-                DataRow windlightRow = windlightTable.Rows.Find(wl.regionID.ToString());
-
-                if (windlightRow == null)
-                {
-                    windlightRow = windlightTable.NewRow();
-                    fillRegionWindlightRow(windlightRow, wl);
-                    windlightTable.Rows.Add(windlightRow);
-                }
-                else
-                {
-                    fillRegionWindlightRow(windlightRow, wl);
-                }
-
-                Commit();
-            }
-        }
-
         #region Region Environment Settings
         public string LoadRegionEnvironmentSettings(UUID regionUUID)
         {
@@ -626,10 +557,13 @@ namespace OpenSim.Data.SQLite
 //                    m_log.Info("[REGION DB]: Adding obj: " + obj.UUID + " to region: " + regionUUID);
                     addPrim(prim, obj.UUID, regionUUID);
                 }
+                primDa.Update(ds, "prims");
+                shapeDa.Update(ds, "primshapes");
+                itemsDa.Update(ds, "primitems");
+                ds.AcceptChanges();
             }
 
-            Commit();
-//            m_log.Info("[Dump of prims]: " + ds.GetXml());
+            // m_log.Info("[Dump of prims]: " + ds.GetXml());
         }
 
         /// <summary>
@@ -1057,12 +991,9 @@ namespace OpenSim.Data.SQLite
                     if (rowToCheck["LandUUID"].ToString() == parcel.LandData.GlobalID.ToString())
                         rowsToDelete.Add(rowToCheck);
                 }
-                for (int iter = 0; iter < rowsToDelete.Count; iter++)
-                {
+                for (int iter = 0; iter < rowsToDelete.Count; ++iter)
                     rowsToDelete[iter].Delete();
-                    landaccesslist.Rows.Remove(rowsToDelete[iter]);
-                }
-                rowsToDelete.Clear();
+
                 foreach (LandAccessEntry entry in parcel.LandData.ParcelAccessList)
                 {
                     DataRow newAccessRow = landaccesslist.NewRow();
@@ -1264,10 +1195,6 @@ namespace OpenSim.Data.SQLite
             createCol(prims, "TextureAnimation", typeof(String));
             createCol(prims, "ParticleSystem", typeof(String));
 
-            createCol(prims, "OmegaX", typeof(Double));
-            createCol(prims, "OmegaY", typeof(Double));
-            createCol(prims, "OmegaZ", typeof(Double));
-
             createCol(prims, "CameraEyeOffsetX", typeof(Double));
             createCol(prims, "CameraEyeOffsetY", typeof(Double));
             createCol(prims, "CameraEyeOffsetZ", typeof(Double));
@@ -1312,6 +1239,21 @@ namespace OpenSim.Data.SQLite
 
             createCol(prims, "KeyframeMotion", typeof(Byte[]));
 
+            createCol(prims, "PassTouches", typeof(bool));
+            createCol(prims, "PassCollisions", typeof(bool));
+            createCol(prims, "Vehicle", typeof(string));
+
+            createCol(prims, "RotationAxisLocks", typeof(byte));
+
+            createCol(prims, "PhysInertia", typeof(string));
+
+            createCol(prims, "standtargetx", typeof(float));
+            createCol(prims, "standtargety", typeof(float));
+            createCol(prims, "standtargetz", typeof(float));
+            createCol(prims, "sitactrange", typeof(float));
+
+            createCol(prims, "pseudocrc", typeof(int));
+
             // Add in contraints
             prims.PrimaryKey = new DataColumn[] { prims.Columns["UUID"] };
 
@@ -1354,6 +1296,7 @@ namespace OpenSim.Data.SQLite
             createCol(shapes, "ProfileCurve", typeof(Int32));
             createCol(shapes, "ProfileHollow", typeof(Int32));
             createCol(shapes, "State", typeof(Int32));
+            createCol(shapes, "LastAttachPoint", typeof(Int32));
             // text TODO: this isn't right, but I'm not sure the right
             // way to specify this as a blob atm
             createCol(shapes, "Texture", typeof(Byte[]));
@@ -1455,6 +1398,7 @@ namespace OpenSim.Data.SQLite
             createCol(land, "SeeAVs", typeof(Boolean));
             createCol(land, "AnyAVSounds", typeof(Boolean));
             createCol(land, "GroupAVSounds", typeof(Boolean));
+            createCol(land, "environment", typeof(string));
 
             land.PrimaryKey = new DataColumn[] { land.Columns["UUID"] };
 
@@ -1519,6 +1463,9 @@ namespace OpenSim.Data.SQLite
             createCol(regionsettings, "map_tile_ID", typeof(String));
             createCol(regionsettings, "TelehubObject", typeof(String));
             createCol(regionsettings, "parcel_tile_ID", typeof(String));
+            createCol(regionsettings, "block_search", typeof(Boolean));
+            createCol(regionsettings, "casino", typeof(Boolean));
+            createCol(regionsettings, "cacheID", typeof(string));
             regionsettings.PrimaryKey = new DataColumn[] { regionsettings.Columns["regionUUID"] };
             return regionsettings;
         }
@@ -1724,14 +1671,18 @@ namespace OpenSim.Data.SQLite
                                                    Convert.ToSingle(row["SitTargetOffsetY"]),
                                                    Convert.ToSingle(row["SitTargetOffsetZ"]));
             prim.SitTargetOrientationLL = new Quaternion(
-                                                         Convert.ToSingle(
-                                                                          row["SitTargetOrientX"]),
-                                                         Convert.ToSingle(
-                                                                          row["SitTargetOrientY"]),
-                                                         Convert.ToSingle(
-                                                                          row["SitTargetOrientZ"]),
-                                                         Convert.ToSingle(
-                                                                          row["SitTargetOrientW"]));
+                                                         Convert.ToSingle(row["SitTargetOrientX"]),
+                                                         Convert.ToSingle(row["SitTargetOrientY"]),
+                                                         Convert.ToSingle(row["SitTargetOrientZ"]),
+                                                         Convert.ToSingle(row["SitTargetOrientW"]));
+
+            prim.StandOffset = new Vector3(
+                            Convert.ToSingle(row["standtargetx"]),
+                            Convert.ToSingle(row["standtargety"]),
+                            Convert.ToSingle(row["standtargetz"])
+                            );
+
+            prim.SitActiveRange = Convert.ToSingle(row["sitactrange"]);
 
             prim.ClickAction = Convert.ToByte(row["ClickAction"]);
             prim.PayPrice[0] = Convert.ToInt32(row["PayPrice"]);
@@ -1752,12 +1703,6 @@ namespace OpenSim.Data.SQLite
             if (!row.IsNull("ParticleSystem"))
                 prim.ParticleSystem = Convert.FromBase64String(row["ParticleSystem"].ToString());
 
-            prim.AngularVelocity = new Vector3(
-                Convert.ToSingle(row["OmegaX"]),
-                Convert.ToSingle(row["OmegaY"]),
-                Convert.ToSingle(row["OmegaZ"])
-                );
-
             prim.SetCameraEyeOffset(new Vector3(
                 Convert.ToSingle(row["CameraEyeOffsetX"]),
                 Convert.ToSingle(row["CameraEyeOffsetY"]),
@@ -1851,6 +1796,10 @@ namespace OpenSim.Data.SQLite
                 pdata = PhysicsInertiaData.FromXml2(row["PhysInertia"].ToString());
             prim.PhysicsInertia = pdata;
 
+            int pseudocrc = Convert.ToInt32(row["pseudocrc"]);
+            if(pseudocrc != 0)
+                prim.PseudoCRC = pseudocrc;
+
             return prim;
         }
 
@@ -1962,6 +1911,36 @@ namespace OpenSim.Data.SQLite
 
             newData.OtherCleanTime = Convert.ToInt32(row["OtherCleanTime"]);
 
+            if (row["environment"] is DBNull)
+            {
+                newData.Environment = null;
+                newData.EnvironmentVersion = -1;
+            }
+            else
+            {
+                string env = (string)row["environment"];
+                if (string.IsNullOrEmpty(env))
+                {
+                    newData.Environment = null;
+                    newData.EnvironmentVersion = -1;
+                }
+                else
+                {
+                    try
+                    {
+                        ViewerEnvironment VEnv = ViewerEnvironment.FromOSDString(env);
+                        newData.Environment = VEnv;
+                        newData.EnvironmentVersion = VEnv.version;
+                    }
+                    catch
+                    {
+                        newData.Environment = null;
+                        newData.EnvironmentVersion = -1;
+                    }
+                }
+            }
+
+
             return newData;
         }
 
@@ -2014,84 +1993,10 @@ namespace OpenSim.Data.SQLite
             newSettings.ParcelImageID = new UUID((String)row["parcel_tile_ID"]);
             newSettings.GodBlockSearch = Convert.ToBoolean(row["block_search"]);
             newSettings.Casino = Convert.ToBoolean(row["casino"]);
-            return newSettings;
-        }
+            if (!(row["cacheID"] is System.DBNull))
+                newSettings.CacheID = new UUID((String)row["cacheID"]);
 
-        /// <summary>
-        /// Build a windlight entry from the persisted data.
-        /// </summary>
-        /// <param name="row"></param>
-        /// <returns>RegionLightShareData</returns>
-        private RegionLightShareData buildRegionWindlight(DataRow row)
-        {
-            RegionLightShareData windlight = new RegionLightShareData();
-
-            windlight.regionID = new UUID((string)row["region_id"]);
-            windlight.waterColor.X = Convert.ToSingle(row["water_color_r"]);
-            windlight.waterColor.Y = Convert.ToSingle(row["water_color_g"]);
-            windlight.waterColor.Z = Convert.ToSingle(row["water_color_b"]);
-            //windlight.waterColor.W = Convert.ToSingle(row["water_color_i"]); //not implemented
-            windlight.waterFogDensityExponent = Convert.ToSingle(row["water_fog_density_exponent"]);
-            windlight.underwaterFogModifier = Convert.ToSingle(row["underwater_fog_modifier"]);
-            windlight.reflectionWaveletScale.X = Convert.ToSingle(row["reflection_wavelet_scale_1"]);
-            windlight.reflectionWaveletScale.Y = Convert.ToSingle(row["reflection_wavelet_scale_2"]);
-            windlight.reflectionWaveletScale.Z = Convert.ToSingle(row["reflection_wavelet_scale_3"]);
-            windlight.fresnelScale = Convert.ToSingle(row["fresnel_scale"]);
-            windlight.fresnelOffset = Convert.ToSingle(row["fresnel_offset"]);
-            windlight.refractScaleAbove = Convert.ToSingle(row["refract_scale_above"]);
-            windlight.refractScaleBelow = Convert.ToSingle(row["refract_scale_below"]);
-            windlight.blurMultiplier = Convert.ToSingle(row["blur_multiplier"]);
-            windlight.bigWaveDirection.X = Convert.ToSingle(row["big_wave_direction_x"]);
-            windlight.bigWaveDirection.Y = Convert.ToSingle(row["big_wave_direction_y"]);
-            windlight.littleWaveDirection.X = Convert.ToSingle(row["little_wave_direction_x"]);
-            windlight.littleWaveDirection.Y = Convert.ToSingle(row["little_wave_direction_y"]);
-            windlight.normalMapTexture = new UUID((string)row["normal_map_texture"]);
-            windlight.horizon.X = Convert.ToSingle(row["horizon_r"]);
-            windlight.horizon.Y = Convert.ToSingle(row["horizon_g"]);
-            windlight.horizon.Z = Convert.ToSingle(row["horizon_b"]);
-            windlight.horizon.W = Convert.ToSingle(row["horizon_i"]);
-            windlight.hazeHorizon = Convert.ToSingle(row["haze_horizon"]);
-            windlight.blueDensity.X = Convert.ToSingle(row["blue_density_r"]);
-            windlight.blueDensity.Y = Convert.ToSingle(row["blue_density_g"]);
-            windlight.blueDensity.Z = Convert.ToSingle(row["blue_density_b"]);
-            windlight.blueDensity.W = Convert.ToSingle(row["blue_density_i"]);
-            windlight.hazeDensity = Convert.ToSingle(row["haze_density"]);
-            windlight.densityMultiplier = Convert.ToSingle(row["density_multiplier"]);
-            windlight.distanceMultiplier = Convert.ToSingle(row["distance_multiplier"]);
-            windlight.maxAltitude = Convert.ToUInt16(row["max_altitude"]);
-            windlight.sunMoonColor.X = Convert.ToSingle(row["sun_moon_color_r"]);
-            windlight.sunMoonColor.Y = Convert.ToSingle(row["sun_moon_color_g"]);
-            windlight.sunMoonColor.Z = Convert.ToSingle(row["sun_moon_color_b"]);
-            windlight.sunMoonColor.W = Convert.ToSingle(row["sun_moon_color_i"]);
-            windlight.sunMoonPosition = Convert.ToSingle(row["sun_moon_position"]);
-            windlight.ambient.X = Convert.ToSingle(row["ambient_r"]);
-            windlight.ambient.Y = Convert.ToSingle(row["ambient_g"]);
-            windlight.ambient.Z = Convert.ToSingle(row["ambient_b"]);
-            windlight.ambient.W = Convert.ToSingle(row["ambient_i"]);
-            windlight.eastAngle = Convert.ToSingle(row["east_angle"]);
-            windlight.sunGlowFocus = Convert.ToSingle(row["sun_glow_focus"]);
-            windlight.sunGlowSize = Convert.ToSingle(row["sun_glow_size"]);
-            windlight.sceneGamma = Convert.ToSingle(row["scene_gamma"]);
-            windlight.starBrightness = Convert.ToSingle(row["star_brightness"]);
-            windlight.cloudColor.X = Convert.ToSingle(row["cloud_color_r"]);
-            windlight.cloudColor.Y = Convert.ToSingle(row["cloud_color_g"]);
-            windlight.cloudColor.Z = Convert.ToSingle(row["cloud_color_b"]);
-            windlight.cloudColor.W = Convert.ToSingle(row["cloud_color_i"]);
-            windlight.cloudXYDensity.X = Convert.ToSingle(row["cloud_x"]);
-            windlight.cloudXYDensity.Y = Convert.ToSingle(row["cloud_y"]);
-            windlight.cloudXYDensity.Z = Convert.ToSingle(row["cloud_density"]);
-            windlight.cloudCoverage = Convert.ToSingle(row["cloud_coverage"]);
-            windlight.cloudScale = Convert.ToSingle(row["cloud_scale"]);
-            windlight.cloudDetailXYDensity.X = Convert.ToSingle(row["cloud_detail_x"]);
-            windlight.cloudDetailXYDensity.Y = Convert.ToSingle(row["cloud_detail_y"]);
-            windlight.cloudDetailXYDensity.Z = Convert.ToSingle(row["cloud_detail_density"]);
-            windlight.cloudScrollX = Convert.ToSingle(row["cloud_scroll_x"]);
-            windlight.cloudScrollXLock = Convert.ToBoolean(row["cloud_scroll_x_lock"]);
-            windlight.cloudScrollY = Convert.ToSingle(row["cloud_scroll_y"]);
-            windlight.cloudScrollYLock = Convert.ToBoolean(row["cloud_scroll_y_lock"]);
-            windlight.drawClassicClouds = Convert.ToBoolean(row["draw_classic_clouds"]);
-
-            return windlight;
+            return newSettings;
         }
 
         /// <summary>
@@ -2174,6 +2079,14 @@ namespace OpenSim.Data.SQLite
             row["SitTargetOrientX"] = sitTargetOrient.X;
             row["SitTargetOrientY"] = sitTargetOrient.Y;
             row["SitTargetOrientZ"] = sitTargetOrient.Z;
+
+            Vector3 standTarget = prim.StandOffset;
+            row["standtargetx"] = standTarget.X;
+            row["standtargety"] = standTarget.Y;
+            row["standtargetz"] = standTarget.Z;
+
+            row["sitactrange"] = prim.SitActiveRange;
+
             row["ColorR"] = Convert.ToInt32(prim.Color.R);
             row["ColorG"] = Convert.ToInt32(prim.Color.G);
             row["ColorB"] = Convert.ToInt32(prim.Color.B);
@@ -2187,10 +2100,6 @@ namespace OpenSim.Data.SQLite
             row["TextureAnimation"] = Convert.ToBase64String(prim.TextureAnimation);
             row["ParticleSystem"] = Convert.ToBase64String(prim.ParticleSystem);
 
-            row["OmegaX"] = prim.AngularVelocity.X;
-            row["OmegaY"] = prim.AngularVelocity.Y;
-            row["OmegaZ"] = prim.AngularVelocity.Z;
-
             row["CameraEyeOffsetX"] = prim.GetCameraEyeOffset().X;
             row["CameraEyeOffsetY"] = prim.GetCameraEyeOffset().Y;
             row["CameraEyeOffsetZ"] = prim.GetCameraEyeOffset().Z;
@@ -2199,7 +2108,6 @@ namespace OpenSim.Data.SQLite
             row["CameraAtOffsetY"] = prim.GetCameraAtOffset().Y;
             row["CameraAtOffsetZ"] = prim.GetCameraAtOffset().Z;
 
-
             if ((prim.SoundFlags & 1) != 0) // Looped
             {
                 row["LoopedSound"] = prim.Sound.ToString();
@@ -2279,6 +2187,7 @@ namespace OpenSim.Data.SQLite
             else
                 row["PhysInertia"] = String.Empty;
 
+            row["pseudocrc"] = prim.PseudoCRC;
         }
 
         /// <summary>
@@ -2366,6 +2275,20 @@ namespace OpenSim.Data.SQLite
             row["AnyAVSounds"] = land.AnyAVSounds;
             row["GroupAVSounds"] = land.GroupAVSounds;
 
+            if (land.Environment == null)
+                row["environment"] = "";
+            else
+            {
+                try
+                {
+                    row["environment"] = ViewerEnvironment.ToOSDString(land.Environment);
+                }
+                catch
+                {
+                    row["environment"] = "";
+                }
+            }
+
         }
 
         /// <summary>
@@ -2426,79 +2349,7 @@ namespace OpenSim.Data.SQLite
             row["parcel_tile_ID"] = settings.ParcelImageID.ToString();
             row["block_search"] = settings.GodBlockSearch;
             row["casino"] = settings.Casino;
-        }
-
-        /// <summary>
-        ///
-        /// </summary>
-        /// <param name="row"></param>
-        /// <param name="windlight"></param>
-        private static void fillRegionWindlightRow(DataRow row, RegionLightShareData windlight)
-        {
-            row["region_id"] = windlight.regionID.ToString();
-            row["water_color_r"] = windlight.waterColor.X;
-            row["water_color_g"] = windlight.waterColor.Y;
-            row["water_color_b"] = windlight.waterColor.Z;
-            row["water_color_i"] = 1; //windlight.waterColor.W;  //not implemented
-            row["water_fog_density_exponent"] = windlight.waterFogDensityExponent;
-            row["underwater_fog_modifier"] = windlight.underwaterFogModifier;
-            row["reflection_wavelet_scale_1"] = windlight.reflectionWaveletScale.X;
-            row["reflection_wavelet_scale_2"] = windlight.reflectionWaveletScale.Y;
-            row["reflection_wavelet_scale_3"] = windlight.reflectionWaveletScale.Z;
-            row["fresnel_scale"] = windlight.fresnelScale;
-            row["fresnel_offset"] = windlight.fresnelOffset;
-            row["refract_scale_above"] = windlight.refractScaleAbove;
-            row["refract_scale_below"] = windlight.refractScaleBelow;
-            row["blur_multiplier"] = windlight.blurMultiplier;
-            row["big_wave_direction_x"] = windlight.bigWaveDirection.X;
-            row["big_wave_direction_y"] = windlight.bigWaveDirection.Y;
-            row["little_wave_direction_x"] = windlight.littleWaveDirection.X;
-            row["little_wave_direction_y"] = windlight.littleWaveDirection.Y;
-            row["normal_map_texture"] = windlight.normalMapTexture.ToString();
-            row["horizon_r"] = windlight.horizon.X;
-            row["horizon_g"] = windlight.horizon.Y;
-            row["horizon_b"] = windlight.horizon.Z;
-            row["horizon_i"] = windlight.horizon.W;
-            row["haze_horizon"] = windlight.hazeHorizon;
-            row["blue_density_r"] = windlight.blueDensity.X;
-            row["blue_density_g"] = windlight.blueDensity.Y;
-            row["blue_density_b"] = windlight.blueDensity.Z;
-            row["blue_density_i"] = windlight.blueDensity.W;
-            row["haze_density"] = windlight.hazeDensity;
-            row["density_multiplier"] = windlight.densityMultiplier;
-            row["distance_multiplier"] = windlight.distanceMultiplier;
-            row["max_altitude"] = windlight.maxAltitude;
-            row["sun_moon_color_r"] = windlight.sunMoonColor.X;
-            row["sun_moon_color_g"] = windlight.sunMoonColor.Y;
-            row["sun_moon_color_b"] = windlight.sunMoonColor.Z;
-            row["sun_moon_color_i"] = windlight.sunMoonColor.W;
-            row["sun_moon_position"] = windlight.sunMoonPosition;
-            row["ambient_r"] = windlight.ambient.X;
-            row["ambient_g"] = windlight.ambient.Y;
-            row["ambient_b"] = windlight.ambient.Z;
-            row["ambient_i"] = windlight.ambient.W;
-            row["east_angle"] = windlight.eastAngle;
-            row["sun_glow_focus"] = windlight.sunGlowFocus;
-            row["sun_glow_size"] = windlight.sunGlowSize;
-            row["scene_gamma"] = windlight.sceneGamma;
-            row["star_brightness"] = windlight.starBrightness;
-            row["cloud_color_r"] = windlight.cloudColor.X;
-            row["cloud_color_g"] = windlight.cloudColor.Y;
-            row["cloud_color_b"] = windlight.cloudColor.Z;
-            row["cloud_color_i"] = windlight.cloudColor.W;
-            row["cloud_x"] = windlight.cloudXYDensity.X;
-            row["cloud_y"] = windlight.cloudXYDensity.Y;
-            row["cloud_density"] = windlight.cloudXYDensity.Z;
-            row["cloud_coverage"] = windlight.cloudCoverage;
-            row["cloud_scale"] = windlight.cloudScale;
-            row["cloud_detail_x"] = windlight.cloudDetailXYDensity.X;
-            row["cloud_detail_y"] = windlight.cloudDetailXYDensity.Y;
-            row["cloud_detail_density"] = windlight.cloudDetailXYDensity.Z;
-            row["cloud_scroll_x"] = windlight.cloudScrollX;
-            row["cloud_scroll_x_lock"] = windlight.cloudScrollXLock;
-            row["cloud_scroll_y"] = windlight.cloudScrollY;
-            row["cloud_scroll_y_lock"] = windlight.cloudScrollYLock;
-            row["draw_classic_clouds"] = windlight.drawClassicClouds;
+            row["cacheID"] = settings.CacheID;
         }
 
         /// <summary>

+ 0 - 4
OpenSim/Data/Tests/EstateTests.cs

@@ -495,10 +495,6 @@ namespace OpenSim.Data.Tests
             Assert.AreEqual(pricePerMeter, estateSettings.PricePerMeter);
             Assert.AreEqual(redirectGridX, estateSettings.RedirectGridX);
             Assert.AreEqual(redirectGridY, estateSettings.RedirectGridY);
-            Assert.AreEqual(useGlobalTime, estateSettings.UseGlobalTime);
-            Assert.AreEqual(fixedSun, estateSettings.FixedSun);
-
-            DataTestUtil.AssertDoubleEqualsWithTolerance(sunPosition, estateSettings.SunPosition);
 
             Assert.AreEqual(allowVoice, estateSettings.AllowVoice);
             Assert.AreEqual(allowDirectTeleport, estateSettings.AllowDirectTeleport);

+ 23 - 30
OpenSim/Data/Tests/RegionTests.cs

@@ -269,12 +269,12 @@ namespace OpenSim.Data.Tests
             random.NextBytes(partsys);
             DateTime expires = new DateTime(2008, 12, 20);
             DateTime rezzed = new DateTime(2009, 07, 15);
-            Vector3 groupos = new Vector3(random.Next(),random.Next(),random.Next());
-            Vector3 offset = new Vector3(random.Next(),random.Next(),random.Next());
-            Quaternion rotoff = new Quaternion(random.Next(),random.Next(),random.Next(),random.Next());
-            Vector3 velocity = new Vector3(random.Next(),random.Next(),random.Next());
-            Vector3 angvelo = new Vector3(random.Next(),random.Next(),random.Next());
-            Vector3 accel = new Vector3(random.Next(),random.Next(),random.Next());
+            Vector3 groupos = new Vector3(random.Next(100000),random.Next(100000),random.Next(100000));
+            Vector3 offset = new Vector3(random.Next(100000),random.Next(100000),random.Next(100000));
+            Quaternion rotoff = new Quaternion(random.Next(1),random.Next(1),random.Next(1),random.Next(1));
+            Vector3 velocity = new Vector3(random.Next(100000),random.Next(100000),random.Next(100000));
+            Vector3 angvelo = new Vector3(random.Next(100000),random.Next(100000),random.Next(100000));
+            Vector3 accel = new Vector3(random.Next(100000),random.Next(100000),random.Next(100000));
             string description = name;
             Color color = Color.FromArgb(255, 165, 50, 100);
             string text = "All Your Base Are Belong to Us";
@@ -289,7 +289,7 @@ namespace OpenSim.Data.Tests
             pbshap.ProfileBegin = ushort.MaxValue;
             pbshap.ProfileEnd = ushort.MaxValue;
             pbshap.ProfileHollow = ushort.MaxValue;
-            Vector3 scale = new Vector3(random.Next(),random.Next(),random.Next());
+            Vector3 scale = new Vector3(random.Next(100000),random.Next(100000),random.Next(100000));
 
             RegionInfo regionInfo = new RegionInfo();
             regionInfo.RegionID = region3;
@@ -378,9 +378,9 @@ namespace OpenSim.Data.Tests
             SceneObjectPart p = sogs[0].RootPart;
             Assert.That(regionh,Is.EqualTo(p.RegionHandle), "Assert.That(regionh,Is.EqualTo(p.RegionHandle))");
             //Assert.That(localid,Is.EqualTo(p.LocalId), "Assert.That(localid,Is.EqualTo(p.LocalId))");
-            Assert.That(groupos,Is.EqualTo(p.GroupPosition), "Assert.That(groupos,Is.EqualTo(p.GroupPosition))");
+            Assert.That(groupos, Is.EqualTo(p.GroupPosition), "Assert.That(groupos,Is.EqualTo(p.GroupPosition))");
             Assert.That(name,Is.EqualTo(p.Name), "Assert.That(name,Is.EqualTo(p.Name))");
-            Assert.That(rotoff,Is.EqualTo(p.RotationOffset), "Assert.That(rotoff,Is.EqualTo(p.RotationOffset))");
+            Assert.That(rotoff, Is.EqualTo(p.RotationOffset), "Assert.That(rotoff,Is.EqualTo(p.RotationOffset))");
             Assert.That(uuid,Is.EqualTo(p.UUID), "Assert.That(uuid,Is.EqualTo(p.UUID))");
             Assert.That(creator,Is.EqualTo(p.CreatorID), "Assert.That(creator,Is.EqualTo(p.CreatorID))");
             //Assert.That(iserial,Is.EqualTo(p.InventorySerial), "Assert.That(iserial,Is.EqualTo(p.InventorySerial))");
@@ -443,12 +443,12 @@ namespace OpenSim.Data.Tests
             random.NextBytes(partsys);
             DateTime expires = new DateTime(2010, 12, 20);
             DateTime rezzed = new DateTime(2005, 07, 15);
-            Vector3 groupos = new Vector3(random.Next(),random.Next(),random.Next());
-            Vector3 offset = new Vector3(random.Next(),random.Next(),random.Next());
-            Quaternion rotoff = new Quaternion(random.Next(),random.Next(),random.Next(),random.Next());
-            Vector3 velocity = new Vector3(random.Next(),random.Next(),random.Next());
-            Vector3 angvelo = new Vector3(random.Next(),random.Next(),random.Next());
-            Vector3 accel = new Vector3(random.Next(),random.Next(),random.Next());
+            Vector3 groupos = new Vector3(random.Next(100000),random.Next(100000),random.Next(100000));
+            Vector3 offset = new Vector3(random.Next(100000),random.Next(100000),random.Next(100000));
+            Quaternion rotoff = new Quaternion(random.Next(100000),random.Next(100000),random.Next(100000),random.Next(100000));
+            Vector3 velocity = new Vector3(random.Next(100000),random.Next(100000),random.Next(100000));
+            Vector3 angvelo = new Vector3(random.Next(100000),random.Next(100000),random.Next(100000));
+            Vector3 accel = new Vector3(random.Next(100000),random.Next(100000),random.Next(100000));
             string description = name;
             Color color = Color.FromArgb(255, 255, 255, 0);
             string text = "What You Say?{]\vz~";
@@ -536,12 +536,12 @@ namespace OpenSim.Data.Tests
             {
                 UUID tmp = UUID.Random();
                 SceneObjectPart sop = NewSOP(("Test SOP " + i.ToString()),tmp);
-                Vector3 groupos = new Vector3(random.Next(),random.Next(),random.Next());
-                Vector3 offset = new Vector3(random.Next(),random.Next(),random.Next());
-                Quaternion rotoff = new Quaternion(random.Next(),random.Next(),random.Next(),random.Next());
-                Vector3 velocity = new Vector3(random.Next(),random.Next(),random.Next());
-                Vector3 angvelo = new Vector3(random.Next(),random.Next(),random.Next());
-                Vector3 accel = new Vector3(random.Next(),random.Next(),random.Next());
+                Vector3 groupos = new Vector3(random.Next(100000),random.Next(100000),random.Next(100000));
+                Vector3 offset = new Vector3(random.Next(100000),random.Next(100000),random.Next(100000));
+                Quaternion rotoff = new Quaternion(random.Next(100000),random.Next(100000),random.Next(100000),random.Next(100000));
+                Vector3 velocity = new Vector3(random.Next(100000),random.Next(100000),random.Next(100000));
+                Vector3 angvelo = new Vector3(random.Next(100000),random.Next(100000),random.Next(100000));
+                Vector3 accel = new Vector3(random.Next(100000),random.Next(100000),random.Next(100000));
 
                 sop.GroupPosition = groupos;
                 sop.RotationOffset = rotoff;
@@ -869,7 +869,6 @@ namespace OpenSim.Data.Tests
             double terrainlower = random.Next();
             Vector3 sunvector = new Vector3((float)Math.Round(random.NextDouble(),5),(float)Math.Round(random.NextDouble(),5),(float)Math.Round(random.NextDouble(),5));
             UUID terimgid = UUID.Random();
-            double sunpos = random.Next();
             UUID cov = UUID.Random();
 
             RegionSettings r1 = db.LoadRegionSettings(region1);
@@ -903,10 +902,8 @@ namespace OpenSim.Data.Tests
             r1.TerrainLowerLimit = terrainlower;
             r1.UseEstateSun = false;
             r1.Sandbox = true;
-            r1.SunVector = sunvector;
             r1.TerrainImageID = terimgid;
             r1.FixedSun = true;
-            r1.SunPosition = sunpos;
             r1.Covenant = cov;
 
             db.StoreRegionSettings(r1);
@@ -941,12 +938,8 @@ namespace OpenSim.Data.Tests
             Assert.That(r1a.WaterHeight,Is.EqualTo(waterh), "Assert.That(r1a.WaterHeight,Is.EqualTo(waterh))");
             Assert.That(r1a.TerrainRaiseLimit,Is.EqualTo(terrainraise), "Assert.That(r1a.TerrainRaiseLimit,Is.EqualTo(terrainraise))");
             Assert.That(r1a.TerrainLowerLimit,Is.EqualTo(terrainlower), "Assert.That(r1a.TerrainLowerLimit,Is.EqualTo(terrainlower))");
-            Assert.That(r1a.UseEstateSun,Is.False);
             Assert.That(r1a.Sandbox,Is.True);
-            Assert.That(r1a.SunVector,Is.EqualTo(sunvector), "Assert.That(r1a.SunVector,Is.EqualTo(sunvector))");
             //Assert.That(r1a.TerrainImageID,Is.EqualTo(terimgid), "Assert.That(r1a.TerrainImageID,Is.EqualTo(terimgid))");
-            Assert.That(r1a.FixedSun,Is.True);
-            Assert.That(r1a.SunPosition, Is.EqualTo(sunpos), "Assert.That(r1a.SunPosition, Is.EqualTo(sunpos))");
             Assert.That(r1a.Covenant, Is.EqualTo(cov), "Assert.That(r1a.Covenant, Is.EqualTo(cov))");
         }
 
@@ -970,7 +963,7 @@ namespace OpenSim.Data.Tests
             db.StoreTerrain(t1, region1);
 
             // store terrain is async
-            Thread.Sleep(1000);
+            Thread.Sleep(500);
 
             Assert.That(db.LoadTerrain(zero), Is.Null);
             Assert.That(db.LoadTerrain(region1), Is.Not.Null);
@@ -1000,7 +993,7 @@ namespace OpenSim.Data.Tests
             db.StoreTerrain(baseterrain2, region1);
 
             // store terrain is async
-            Thread.Sleep(1000);
+            Thread.Sleep(500);
 
             double[,] t1 = db.LoadTerrain(region1);
             Assert.That(CompareTerrain(t1, baseterrain1), Is.False);

+ 53 - 86
OpenSim/Framework/AgentCircuitManager.cs

@@ -26,6 +26,7 @@
  */
 
 using System.Collections.Generic;
+using System.Collections.Concurrent;
 using OpenMetaverse;
 
 namespace OpenSim.Framework
@@ -41,26 +42,17 @@ namespace OpenSim.Framework
         /// <remarks>
         /// We lock this for operations both on this dictionary and on m_agentCircuitsByUUID
         /// </remarks>
-        private Dictionary<uint, AgentCircuitData> m_agentCircuits = new Dictionary<uint, AgentCircuitData>();
+        private ConcurrentDictionary<uint, AgentCircuitData> m_agentCircuits = new ConcurrentDictionary<uint, AgentCircuitData>();
 
         /// <summary>
         /// Agent circuits indexed by agent UUID.
         /// </summary>
-        private Dictionary<UUID, AgentCircuitData> m_agentCircuitsByUUID = new Dictionary<UUID, AgentCircuitData>();
+        private ConcurrentDictionary<UUID, AgentCircuitData> m_agentCircuitsByUUID = new ConcurrentDictionary<UUID, AgentCircuitData>();
 
         public virtual AuthenticateResponse AuthenticateSession(UUID sessionID, UUID agentID, uint circuitcode)
         {
-            AgentCircuitData validcircuit = null;
-
-            lock (m_agentCircuits)
-            {
-                if (m_agentCircuits.ContainsKey(circuitcode))
-                    validcircuit = m_agentCircuits[circuitcode];
-            }
-
             AuthenticateResponse user = new AuthenticateResponse();
-
-            if (validcircuit == null)
+            if (!m_agentCircuits.TryGetValue(circuitcode, out AgentCircuitData validcircuit) || validcircuit == null)
             {
                 //don't have this circuit code in our list
                 user.Authorised = false;
@@ -86,7 +78,6 @@ namespace OpenSim.Framework
                 // Invalid
                 user.Authorised = false;
             }
-
             return user;
         }
 
@@ -95,67 +86,56 @@ namespace OpenSim.Framework
         /// </summary>
         /// <param name="circuitCode"></param>
         /// <param name="agentData"></param>
+        public virtual void AddNewCircuit(AgentCircuitData agentData)
+        {
+            RemoveCircuit(agentData.AgentID); // no duplications
+            m_agentCircuits[agentData.circuitcode] = agentData;
+            m_agentCircuitsByUUID[agentData.AgentID] = agentData;
+        }
+
         public virtual void AddNewCircuit(uint circuitCode, AgentCircuitData agentData)
         {
-            lock (m_agentCircuits)
-            {
-                if (m_agentCircuits.ContainsKey(circuitCode))
-                {
-                    m_agentCircuits[circuitCode] = agentData;
-                    m_agentCircuitsByUUID[agentData.AgentID] = agentData;
-                }
-                else
-                {
-                    m_agentCircuits.Add(circuitCode, agentData);
-                    m_agentCircuitsByUUID[agentData.AgentID] = agentData;
-                }
-            }
+            RemoveCircuit(agentData.AgentID); // no duplications
+            m_agentCircuits[circuitCode] = agentData;
+            m_agentCircuitsByUUID[agentData.AgentID] = agentData;
         }
 
         public virtual void RemoveCircuit(uint circuitCode)
         {
-            lock (m_agentCircuits)
+            if (m_agentCircuits.TryRemove(circuitCode, out AgentCircuitData ac))
             {
-                if (m_agentCircuits.ContainsKey(circuitCode))
-                {
-                    UUID agentID = m_agentCircuits[circuitCode].AgentID;
-                    m_agentCircuits.Remove(circuitCode);
-                    m_agentCircuitsByUUID.Remove(agentID);
-                }
+                m_agentCircuitsByUUID.TryRemove(ac.AgentID, out AgentCircuitData dummy);
             }
         }
 
         public virtual void RemoveCircuit(UUID agentID)
         {
-            lock (m_agentCircuits)
+            if (m_agentCircuitsByUUID.TryRemove(agentID, out AgentCircuitData ac))
             {
-                if (m_agentCircuitsByUUID.ContainsKey(agentID))
-                {
-                    uint circuitCode = m_agentCircuitsByUUID[agentID].circuitcode;
-                    m_agentCircuits.Remove(circuitCode);
-                    m_agentCircuitsByUUID.Remove(agentID);
-                }
+                m_agentCircuits.TryRemove(ac.circuitcode, out AgentCircuitData dummy);
             }
         }
 
-        public AgentCircuitData GetAgentCircuitData(uint circuitCode)
+        public virtual void RemoveCircuit(AgentCircuitData ac)
         {
-            AgentCircuitData agentCircuit = null;
-
-            lock (m_agentCircuits)
-                m_agentCircuits.TryGetValue(circuitCode, out agentCircuit);
+            m_agentCircuitsByUUID.TryRemove(ac.AgentID, out AgentCircuitData dummy);
+            m_agentCircuits.TryRemove(ac.circuitcode, out AgentCircuitData dummyb);
+            if (dummy.circuitcode != ac.circuitcode) //??
+                m_agentCircuits.TryRemove(dummy.circuitcode, out AgentCircuitData dummyc);
+        }
 
-            return agentCircuit;
+        public AgentCircuitData GetAgentCircuitData(uint circuitCode)
+        {
+            if(m_agentCircuits.TryGetValue(circuitCode, out AgentCircuitData agentCircuit))
+                return agentCircuit;
+            return null;
         }
 
         public AgentCircuitData GetAgentCircuitData(UUID agentID)
         {
-            AgentCircuitData agentCircuit = null;
-
-            lock (m_agentCircuits)
-                m_agentCircuitsByUUID.TryGetValue(agentID, out agentCircuit);
-
-            return agentCircuit;
+            if(m_agentCircuitsByUUID.TryGetValue(agentID, out AgentCircuitData agentCircuit))
+                return agentCircuit;
+            return null;
         }
 
         /// <summary>
@@ -170,21 +150,16 @@ namespace OpenSim.Framework
 
         public void UpdateAgentData(AgentCircuitData agentData)
         {
-            lock (m_agentCircuits)
+            if (m_agentCircuits.TryGetValue(agentData.circuitcode, out AgentCircuitData ac))
             {
-                if (m_agentCircuits.ContainsKey((uint) agentData.circuitcode))
-                {
-                    m_agentCircuits[(uint) agentData.circuitcode].firstname = agentData.firstname;
-                    m_agentCircuits[(uint) agentData.circuitcode].lastname = agentData.lastname;
-                    m_agentCircuits[(uint)agentData.circuitcode].startpos = agentData.startpos;
-                    m_agentCircuits[(uint)agentData.circuitcode].startfar = agentData.startfar;
-
-                    // Updated for when we don't know them before calling Scene.NewUserConnection
-                    m_agentCircuits[(uint) agentData.circuitcode].SecureSessionID = agentData.SecureSessionID;
-                    m_agentCircuits[(uint) agentData.circuitcode].SessionID = agentData.SessionID;
-
-                    // m_log.Debug("update user start pos is " + agentData.startpos.X + " , " + agentData.startpos.Y + " , " + agentData.startpos.Z);
-                }
+                ac.firstname = agentData.firstname;
+                ac.lastname = agentData.lastname;
+                ac.startpos = agentData.startpos;
+                ac.startfar = agentData.startfar;
+
+                // Updated for when we don't know them before calling Scene.NewUserConnection
+                ac.SecureSessionID = agentData.SecureSessionID;
+                ac.SessionID = agentData.SessionID;
             }
         }
 
@@ -193,38 +168,30 @@ namespace OpenSim.Framework
         /// </summary>
         /// <param name="circuitcode"></param>
         /// <param name="newcircuitcode"></param>
-        public bool TryChangeCiruitCode(uint circuitcode, uint newcircuitcode)
+        public bool TryChangeCircuitCode(uint circuitcode, uint newcircuitcode)
         {
-            lock (m_agentCircuits)
+            if(m_agentCircuits.ContainsKey(newcircuitcode))
+                return false;
+            if (m_agentCircuits.TryRemove(circuitcode, out AgentCircuitData agentData))
             {
-                if (m_agentCircuits.ContainsKey((uint)circuitcode) && !m_agentCircuits.ContainsKey((uint)newcircuitcode))
-                {
-                    AgentCircuitData agentData = m_agentCircuits[(uint)circuitcode];
-
-                    agentData.circuitcode = newcircuitcode;
-
-                    m_agentCircuits.Remove((uint)circuitcode);
-                    m_agentCircuits.Add(newcircuitcode, agentData);
-                    return true;
-                }
+                agentData.circuitcode = newcircuitcode;
+                m_agentCircuits[newcircuitcode] = agentData;
+                m_agentCircuitsByUUID[agentData.AgentID] = agentData;
+                return true;
             }
-
             return false;
         }
 
         public void UpdateAgentChildStatus(uint circuitcode, bool childstatus)
         {
-            lock (m_agentCircuits)
-                if (m_agentCircuits.ContainsKey(circuitcode))
-                    m_agentCircuits[circuitcode].child = childstatus;
+            if (m_agentCircuits.TryGetValue(circuitcode, out AgentCircuitData ac))
+                ac.child = childstatus;
         }
 
         public bool GetAgentChildStatus(uint circuitcode)
         {
-            lock (m_agentCircuits)
-                if (m_agentCircuits.ContainsKey(circuitcode))
-                    return m_agentCircuits[circuitcode].child;
-
+            if (m_agentCircuits.TryGetValue(circuitcode, out AgentCircuitData ac))
+                return ac.child;
             return false;
         }
     }

+ 7 - 6
OpenSim/Framework/Animation.cs

@@ -112,12 +112,13 @@ namespace OpenSim.Framework
         /// <param name="args"></param>
         public void UnpackUpdateMessage(OSDMap args)
         {
-            if (args["animation"] != null)
-                animID = args["animation"].AsUUID();
-            if (args["object_id"] != null)
-                objectID = args["object_id"].AsUUID();
-            if (args["seq_num"] != null)
-                sequenceNum = args["seq_num"].AsInteger();
+            OSD tmp;
+            if (args.TryGetValue("animation", out tmp))
+                animID = tmp.AsUUID();
+            if (args.TryGetValue("object_id", out tmp))
+                objectID = tmp.AsUUID();
+            if (args.TryGetValue("seq_num", out tmp))
+                sequenceNum = tmp.AsInteger();
         }
 
         public override bool Equals(object obj)

+ 2 - 1
OpenSim/Framework/AssetBase.cs

@@ -34,12 +34,13 @@ using OpenMetaverse;
 namespace OpenSim.Framework
 {
     [Flags]
+    // this enum is stuck, can not be changed or will break compatibilty with any version older than that change
     public enum AssetFlags : int
     {
         Normal = 0,         // Immutable asset
         Maptile = 1,        // What it says
         Rewritable = 2,     // Content can be rewritten
-        Collectable = 4     // Can be GC'ed after some time
+        Collectable = 4,     // Can be GC'ed after some time
     }
 
     /// <summary>

+ 8 - 2
OpenSim/Framework/AvatarAppearance.cs

@@ -55,7 +55,7 @@ namespace OpenSim.Framework
 
         // regions and viewer compatibility
         public readonly static int TEXTURE_COUNT = 45;
-        public const int TEXTURE_COUNT_PV7 = 26;
+        public const int TEXTURE_COUNT_PV7 = 29;
         public const int BAKES_COUNT_PV7 = 6;
         public const int MAXWEARABLE_PV7 = 16;
         public const int MAXWEARABLE_LEGACY = 15;
@@ -817,7 +817,7 @@ namespace OpenSim.Framework
             return data;
         }
 
-        public OSDMap PackForNotecard()
+        public OSDMap PackForNotecard(bool NoHuds = true)
         {
             OSDMap data = new OSDMap();
 
@@ -868,7 +868,13 @@ namespace OpenSim.Framework
                 // Attachments
                 OSDArray attachs = new OSDArray(m_attachments.Count);
                 foreach (AvatarAttachment attach in GetAttachments())
+                {
+                    if (NoHuds &&
+                            attach.AttachPoint >= (uint)AttachmentPoint.HUDCenter2 &&
+                            attach.AttachPoint <= (uint)AttachmentPoint.HUDBottomRight)
+                        continue;
                     attachs.Add(attach.Pack());
+                }
                 data["attachments"] = attachs;
             }
 

+ 104 - 108
OpenSim/Framework/ChildAgentDataUpdate.cs

@@ -571,145 +571,141 @@ namespace OpenSim.Framework
         public virtual void Unpack(OSDMap args, IScene scene, EntityTransferContext ctx)
         {
             //m_log.InfoFormat("[CHILDAGENTDATAUPDATE] Unpack data");
+            OSD tmp;
+            if (args.TryGetValue("region_id", out tmp) && tmp != null)
+                UUID.TryParse(tmp.AsString(), out RegionID);
 
-            if (args.ContainsKey("region_id"))
-                UUID.TryParse(args["region_id"].AsString(), out RegionID);
+            if (args.TryGetValue("circuit_code", out tmp) && tmp != null)
+                UInt32.TryParse(tmp.AsString(), out CircuitCode);
 
-            if (args["circuit_code"] != null)
-                UInt32.TryParse((string)args["circuit_code"].AsString(), out CircuitCode);
+            if (args.TryGetValue("agent_uuid", out tmp) && tmp != null)
+                AgentID = tmp.AsUUID();
 
-            if (args["agent_uuid"] != null)
-                AgentID = args["agent_uuid"].AsUUID();
+            if (args.TryGetValue("session_uuid", out tmp) && tmp != null)
+                SessionID = tmp.AsUUID();
 
-            if (args["session_uuid"] != null)
-                SessionID = args["session_uuid"].AsUUID();
+            if (args.TryGetValue("position", out tmp) && tmp != null)
+                Vector3.TryParse(tmp.AsString(), out Position);
 
-            if (args["position"] != null)
-                Vector3.TryParse(args["position"].AsString(), out Position);
+            if (args.TryGetValue("velocity", out tmp) && tmp != null)
+                Vector3.TryParse(tmp.AsString(), out Velocity);
 
-            if (args["velocity"] != null)
-                Vector3.TryParse(args["velocity"].AsString(), out Velocity);
+            if (args.TryGetValue("center", out tmp) && tmp != null)
+                Vector3.TryParse(tmp.AsString(), out Center);
 
-            if (args["center"] != null)
-                Vector3.TryParse(args["center"].AsString(), out Center);
-
-            if (args["size"] != null)
-                Vector3.TryParse(args["size"].AsString(), out Size);
+            if (args.TryGetValue("size", out tmp) && tmp != null)
+                Vector3.TryParse(tmp.AsString(), out Size);
 
-            if (args["at_axis"] != null)
-                Vector3.TryParse(args["at_axis"].AsString(), out AtAxis);
-
-            if (args["left_axis"] != null)
-                Vector3.TryParse(args["left_axis"].AsString(), out AtAxis);
+            if (args.TryGetValue("at_axis", out tmp) && tmp != null)
+                Vector3.TryParse(tmp.AsString(), out AtAxis);
 
-            if (args["up_axis"] != null)
-                Vector3.TryParse(args["up_axis"].AsString(), out AtAxis);
+            if (args.TryGetValue("left_axis", out tmp) && tmp != null)
+                Vector3.TryParse(tmp.AsString(), out AtAxis);
 
-            if (args.ContainsKey("wait_for_root") && args["wait_for_root"] != null)
-                SenderWantsToWaitForRoot = args["wait_for_root"].AsBoolean();
+            if (args.TryGetValue("up_axis", out tmp) && tmp != null)
+                Vector3.TryParse(tmp.AsString(), out AtAxis);
 
-            if (args["far"] != null)
-                Far = (float)(args["far"].AsReal());
+            if (args.TryGetValue("wait_for_root", out tmp) && tmp != null)
+                SenderWantsToWaitForRoot = tmp.AsBoolean();
 
-            if (args["aspect"] != null)
-                Aspect = (float)args["aspect"].AsReal();
+            if (args.TryGetValue("far", out tmp) && tmp != null)
+                Far = (float)(tmp.AsReal());
 
-            if (args["throttles"] != null)
-                Throttles = args["throttles"].AsBinary();
+            if (args.TryGetValue("aspect", out tmp) && tmp != null)
+                Aspect = (float)tmp.AsReal();
 
-            if (args["locomotion_state"] != null)
-                UInt32.TryParse(args["locomotion_state"].AsString(), out LocomotionState);
+            if (args.TryGetValue("throttles", out tmp) && tmp != null)
+                Throttles = tmp.AsBinary();
 
-            if (args["head_rotation"] != null)
-                Quaternion.TryParse(args["head_rotation"].AsString(), out HeadRotation);
+            if (args.TryGetValue("locomotion_state", out tmp) && tmp != null)
+                UInt32.TryParse(tmp.AsString(), out LocomotionState);
 
-            if (args["body_rotation"] != null)
-                Quaternion.TryParse(args["body_rotation"].AsString(), out BodyRotation);
+            if (args.TryGetValue("head_rotation", out tmp) && tmp != null)
+                Quaternion.TryParse(tmp.AsString(), out HeadRotation);
 
-            if (args["control_flags"] != null)
-                UInt32.TryParse(args["control_flags"].AsString(), out ControlFlags);
+            if (args.TryGetValue("body_rotation", out tmp) && tmp != null)
+                Quaternion.TryParse(tmp.AsString(), out BodyRotation);
 
-            if (args["energy_level"] != null)
-                EnergyLevel = (float)(args["energy_level"].AsReal());
+            if (args.TryGetValue("control_flags", out tmp) && tmp != null)
+                UInt32.TryParse(tmp.AsString(), out ControlFlags);
 
-            //if (args["god_level"] != null)
-            //    Byte.TryParse(args["god_level"].AsString(), out GodLevel);
+            if (args.TryGetValue("energy_level", out tmp) && tmp != null)
+                EnergyLevel = (float)(tmp.AsReal());
 
-            if (args.ContainsKey("god_data") && args["god_data"] != null)
-                GodData = args["god_data"];
+            if (args.TryGetValue("god_data", out tmp) && tmp != null)
+                GodData = tmp;
 
-            if (args["always_run"] != null)
-                AlwaysRun = args["always_run"].AsBoolean();
+            if (args.TryGetValue("always_run", out tmp) && tmp != null)
+                AlwaysRun = tmp.AsBoolean();
 
-            if (args["prey_agent"] != null)
-                PreyAgent = args["prey_agent"].AsUUID();
+            if (args.TryGetValue("prey_agent", out tmp) && tmp != null)
+                PreyAgent = tmp.AsUUID();
 
-            if (args["agent_access"] != null)
-                Byte.TryParse(args["agent_access"].AsString(), out AgentAccess);
+            if (args.TryGetValue("agent_access", out tmp) && tmp != null)
+                Byte.TryParse(tmp.AsString(), out AgentAccess);
 
-            if (args.ContainsKey("agent_cof") && args["agent_cof"] != null)
-                agentCOF = args["agent_cof"].AsUUID();
+            if (args.TryGetValue("agent_cof", out tmp) && tmp != null)
+                agentCOF = tmp.AsUUID();
 
-            if (args.ContainsKey("crossingflags") && args["crossingflags"] != null)
-                CrossingFlags = (byte)args["crossingflags"].AsInteger();
+            if (args.TryGetValue("crossingflags", out tmp) && tmp != null)
+                CrossingFlags = (byte)tmp.AsInteger();
 
             if(CrossingFlags != 0)
             {
-                if (args.ContainsKey("crossExtraFlags") && args["crossExtraFlags"] != null)
-                    CrossExtraFlags = (byte)args["crossExtraFlags"].AsInteger();
+                if (args.TryGetValue("crossExtraFlags", out tmp) && tmp != null)
+                    CrossExtraFlags = (byte)tmp.AsInteger();
             }
 
-            if (args.ContainsKey("active_group_id") && args["active_group_id"] != null)
-                ActiveGroupID = args["active_group_id"].AsUUID();
+            if (args.TryGetValue("active_group_id", out tmp) && tmp != null)
+                ActiveGroupID = tmp.AsUUID();
 
-            if (args.ContainsKey("active_group_name") && args["active_group_name"] != null)
-                ActiveGroupName = args["active_group_name"].AsString();
+            if (args.TryGetValue("active_group_name", out tmp) && tmp != null)
+                ActiveGroupName = tmp.AsString();
 
-            if(args.ContainsKey("active_group_title") && args["active_group_title"] != null)
-                ActiveGroupTitle = args["active_group_title"].AsString();
+            if(args.TryGetValue("active_group_title", out tmp) && tmp != null)
+                ActiveGroupTitle = tmp.AsString();
 
-            if (args.ContainsKey("children_seeds") && (args["children_seeds"] != null) &&
-                            (args["children_seeds"].Type == OSDType.Array))
+            if (args.TryGetValue("children_seeds", out tmp) && tmp is OSDArray)
             {
-                OSDArray childrenSeeds = (OSDArray)(args["children_seeds"]);
+                OSDArray childrenSeeds = (OSDArray)tmp;
                 ChildrenCapSeeds = new Dictionary<ulong, string>();
                 foreach (OSD o in childrenSeeds)
                 {
-                    if (o.Type == OSDType.Map)
+                    if (o is OSDMap)
                     {
                         ulong handle = 0;
                         string seed = "";
                         OSDMap pair = (OSDMap)o;
-                        if (pair["handle"] != null)
-                            if (!UInt64.TryParse(pair["handle"].AsString(), out handle))
+                        if (pair.TryGetValue("handle", out tmp))
+                            if (!UInt64.TryParse(tmp.AsString(), out handle))
                                 continue;
-                        if (pair["seed"] != null)
-                            seed = pair["seed"].AsString();
+                        if (pair.TryGetValue("seed", out tmp))
+                            seed = tmp.AsString();
                         if (!ChildrenCapSeeds.ContainsKey(handle))
                             ChildrenCapSeeds.Add(handle, seed);
                     }
                 }
             }
 
-            if ((args["animations"] != null) && (args["animations"]).Type == OSDType.Array)
+            if (args.TryGetValue("animations", out tmp) && tmp is OSDArray)
             {
-                OSDArray anims = (OSDArray)(args["animations"]);
+                OSDArray anims = (OSDArray)tmp;
                 Anims = new Animation[anims.Count];
                 int i = 0;
                 foreach (OSD o in anims)
                 {
-                    if (o.Type == OSDType.Map)
+                    if (o is OSDMap)
                     {
                         Anims[i++] = new Animation((OSDMap)o);
                     }
                 }
             }
 
-            if (args["default_animation"] != null)
+            if (args.TryGetValue("default_animation", out tmp) && tmp is OSDMap)
             {
                 try
                 {
-                    DefaultAnim = new Animation((OSDMap)args["default_animation"]);
+                    DefaultAnim = new Animation((OSDMap)tmp);
                 }
                 catch
                 {
@@ -717,11 +713,11 @@ namespace OpenSim.Framework
                 }
             }
 
-            if (args["animation_state"] != null)
+            if (args.TryGetValue("animation_state", out tmp) && tmp is OSDMap)
             {
                 try
                 {
-                    AnimState = new Animation((OSDMap)args["animation_state"]);
+                    AnimState = new Animation((OSDMap)tmp);
                 }
                 catch
                 {
@@ -731,9 +727,9 @@ namespace OpenSim.Framework
 
             MovementAnimationOverRides.Clear();
 
-            if (args["movementAO"] != null && args["movementAO"].Type == OSDType.Array)
+            if (args.TryGetValue("movementAO", out tmp) && tmp is OSDArray)
             {
-                OSDArray AOs = (OSDArray)(args["movementAO"]);
+                OSDArray AOs = (OSDArray)tmp;
                 int count = AOs.Count;
 
                 for (int i = 0; i < count; i++)
@@ -748,8 +744,8 @@ namespace OpenSim.Framework
                 }
             }
 
-            if (args.ContainsKey("motion_state"))
-                MotionState = (byte)args["motion_state"].AsInteger();
+            if (args.TryGetValue("motion_state", out tmp) && tmp != null)
+                MotionState = (byte)tmp.AsInteger();
 
             //if ((args["agent_textures"] != null) && (args["agent_textures"]).Type == OSDType.Array)
             //{
@@ -762,10 +758,10 @@ namespace OpenSim.Framework
 
 
             // packed_appearence should contain all appearance information
-            if (args.ContainsKey("packed_appearance") && (args["packed_appearance"]).Type == OSDType.Map)
+            if (args.TryGetValue("packed_appearance", out tmp) && tmp is OSDMap)
             {
                 m_log.WarnFormat("[CHILDAGENTDATAUPDATE] got packed appearance");
-                Appearance = new AvatarAppearance((OSDMap)args["packed_appearance"]);
+                Appearance = new AvatarAppearance((OSDMap)tmp);
             }
             else
             {
@@ -777,19 +773,19 @@ namespace OpenSim.Framework
                 // The code to unpack textures, visuals, wearables and attachments
                 // should be removed; packed appearance contains the full appearance
                 // This is retained for backward compatibility only
-                if (args["texture_entry"] != null)
+                if (args.TryGetValue("texture_entry", out tmp) && tmp != null)
                 {
-                    byte[] rawtextures = args["texture_entry"].AsBinary();
+                    byte[] rawtextures = tmp.AsBinary();
                     Primitive.TextureEntry textures = new Primitive.TextureEntry(rawtextures, 0, rawtextures.Length);
                     Appearance.SetTextureEntries(textures);
                 }
 
-                if (args["visual_params"] != null)
-                    Appearance.SetVisualParams(args["visual_params"].AsBinary());
+                if (args.TryGetValue("visual_params", out tmp) && tmp != null)
+                    Appearance.SetVisualParams(tmp.AsBinary());
 
-                if ((args["wearables"] != null) && (args["wearables"]).Type == OSDType.Array)
+                if (args.TryGetValue("wearables", out tmp) && tmp is OSDArray)
                 {
-                    OSDArray wears = (OSDArray)(args["wearables"]);
+                    OSDArray wears = (OSDArray)tmp;
 
                     for (int i = 0; i < wears.Count / 2; i++)
                     {
@@ -798,12 +794,12 @@ namespace OpenSim.Framework
                     }
                 }
 
-                if ((args["attachments"] != null) && (args["attachments"]).Type == OSDType.Array)
+                if (args.TryGetValue("attachments", out tmp) && tmp is OSDArray)
                 {
-                    OSDArray attachs = (OSDArray)(args["attachments"]);
+                    OSDArray attachs = (OSDArray)tmp;
                     foreach (OSD o in attachs)
                     {
-                        if (o.Type == OSDType.Map)
+                        if (o is OSDMap)
                         {
                             // We know all of these must end up as attachments so we
                             // append rather than replace to ensure multiple attachments
@@ -816,35 +812,35 @@ namespace OpenSim.Framework
                 // end of code to remove
             }
 
-            if ((args["controllers"] != null) && (args["controllers"]).Type == OSDType.Array)
+            if (args.TryGetValue("controllers", out tmp) && tmp is OSDArray)
             {
-                OSDArray controls = (OSDArray)(args["controllers"]);
+                OSDArray controls = (OSDArray)tmp;
                 Controllers = new ControllerData[controls.Count];
                 int i = 0;
                 foreach (OSD o in controls)
                 {
-                    if (o.Type == OSDType.Map)
+                    if (o is OSDMap)
                     {
                         Controllers[i++] = new ControllerData((OSDMap)o);
                     }
                 }
             }
 
-            if (args["callback_uri"] != null)
-                CallbackURI = args["callback_uri"].AsString();
+            if (args.TryGetValue("callback_uri", out tmp) && tmp != null)
+                CallbackURI = tmp.AsString();
 
-            if (args["cb_uri"] != null)
-                NewCallbackURI = args["cb_uri"].AsString();
+            if (args.TryGetValue("cb_uri", out tmp) && tmp != null)
+                NewCallbackURI = tmp.AsString();
 
             // Attachment objects
-            if (args["attach_objects"] != null && args["attach_objects"].Type == OSDType.Array)
+            if (args.TryGetValue("attach_objects", out tmp) && tmp is OSDArray)
             {
-                OSDArray attObjs = (OSDArray)(args["attach_objects"]);
+                OSDArray attObjs = (OSDArray)tmp;
                 AttachmentObjects = new List<ISceneObject>();
                 AttachmentObjectStates = new List<string>();
                 foreach (OSD o in attObjs)
                 {
-                    if (o.Type == OSDType.Map)
+                    if (o is OSDMap)
                     {
                         OSDMap info = (OSDMap)o;
                         ISceneObject so = scene.DeserializeObject(info["sog"].AsString());
@@ -856,10 +852,10 @@ namespace OpenSim.Framework
                 }
             }
 
-            if (args["parent_part"] != null)
-                ParentPart = args["parent_part"].AsUUID();
-            if (args["sit_offset"] != null)
-                Vector3.TryParse(args["sit_offset"].AsString(), out SitOffset);
+            if (args.TryGetValue("parent_part", out tmp) && tmp != null)
+                ParentPart = tmp.AsUUID();
+            if (args.TryGetValue("sit_offset", out tmp) && tmp != null)
+                Vector3.TryParse(tmp.AsString(), out SitOffset);
         }
 
         public AgentData()

+ 20 - 23
OpenSim/Framework/ClientManager.cs

@@ -40,15 +40,15 @@ namespace OpenSim.Framework
     {
         /// <summary>A dictionary mapping from <seealso cref="UUID"/>
         /// to <seealso cref="IClientAPI"/> references</summary>
-        private Dictionary<UUID, IClientAPI> m_dict1;
+        private readonly Dictionary<UUID, IClientAPI> m_dictbyUUID = new Dictionary<UUID, IClientAPI>();
         /// <summary>A dictionary mapping from <seealso cref="IPEndPoint"/>
         /// to <seealso cref="IClientAPI"/> references</summary>
-        private Dictionary<IPEndPoint, IClientAPI> m_dict2;
-        /// <summary>An immutable collection of <seealso cref="IClientAPI"/>
+        private readonly Dictionary<IPEndPoint, IClientAPI> m_dictbyIPe= new Dictionary<IPEndPoint, IClientAPI>();
+        /// <summary>snapshot collection of current <seealso cref="IClientAPI"/>
         /// references</summary>
-        private IClientAPI[] m_array;
+        private IClientAPI[] m_array = null;
         /// <summary>Synchronization object for writing to the collections</summary>
-        private object m_syncRoot = new object();
+        private readonly object m_syncRoot = new object();
 
         /// <summary>Number of clients in the collection</summary>
         public int Count
@@ -56,7 +56,7 @@ namespace OpenSim.Framework
             get
             {
                 lock (m_syncRoot) 
-                    return m_dict1.Count;
+                    return m_dictbyUUID.Count;
             }
         }
 
@@ -65,9 +65,6 @@ namespace OpenSim.Framework
         /// </summary>
         public ClientManager()
         {
-            m_dict1 = new Dictionary<UUID, IClientAPI>();
-            m_dict2 = new Dictionary<IPEndPoint, IClientAPI>();
-            m_array = null;
         }
 
         /// <summary>
@@ -81,8 +78,8 @@ namespace OpenSim.Framework
         {
             lock (m_syncRoot)
             {
-                m_dict1[value.AgentId] = value;
-                m_dict2[value.RemoteEndPoint] = value;
+                m_dictbyUUID[value.AgentId] = value;
+                m_dictbyIPe[value.RemoteEndPoint] = value;
                 m_array = null;
             }
 
@@ -100,10 +97,10 @@ namespace OpenSim.Framework
             lock (m_syncRoot)
             {
                 IClientAPI value;
-                if (m_dict1.TryGetValue(key, out value))
+                if (m_dictbyUUID.TryGetValue(key, out value))
                 {
-                    m_dict1.Remove(key);
-                    m_dict2.Remove(value.RemoteEndPoint);
+                    m_dictbyUUID.Remove(key);
+                    m_dictbyIPe.Remove(value.RemoteEndPoint);
                     m_array = null;
                     return true;
                 }
@@ -118,8 +115,8 @@ namespace OpenSim.Framework
         {
             lock (m_syncRoot)
             {
-                m_dict1.Clear();
-                m_dict2.Clear();
+                m_dictbyUUID.Clear();
+                m_dictbyIPe.Clear();
                 m_array = null;
             }
         }
@@ -132,7 +129,7 @@ namespace OpenSim.Framework
         public bool ContainsKey(UUID key)
         {
             lock (m_syncRoot)
-                return m_dict1.ContainsKey(key);
+                return m_dictbyUUID.ContainsKey(key);
         }
 
         /// <summary>
@@ -143,7 +140,7 @@ namespace OpenSim.Framework
         public bool ContainsKey(IPEndPoint key)
         {
             lock (m_syncRoot)
-                return m_dict2.ContainsKey(key);
+                return m_dictbyIPe.ContainsKey(key);
         }
 
         /// <summary>
@@ -157,7 +154,7 @@ namespace OpenSim.Framework
             try
             {
                 lock (m_syncRoot)
-                    return m_dict1.TryGetValue(key, out value);
+                    return m_dictbyUUID.TryGetValue(key, out value);
             }
             catch
             {
@@ -177,7 +174,7 @@ namespace OpenSim.Framework
             try
             {
                 lock (m_syncRoot)
-                    return m_dict2.TryGetValue(key, out value);
+                    return m_dictbyIPe.TryGetValue(key, out value);
             }
             catch
             {
@@ -198,11 +195,11 @@ namespace OpenSim.Framework
             {
                 if (m_array == null)
                 {
-                    if (m_dict1.Count == 0)
+                    if (m_dictbyUUID.Count == 0)
                         return;
 
-                    m_array = new IClientAPI[m_dict1.Count];
-                    m_dict1.Values.CopyTo(m_array, 0);
+                    m_array = new IClientAPI[m_dictbyUUID.Count];
+                    m_dictbyUUID.Values.CopyTo(m_array, 0);
                 }
                 localArray = m_array;
             }

+ 25 - 1
OpenSim/Framework/Console/CommandConsole.cs

@@ -720,9 +720,10 @@ namespace OpenSim.Framework.Console
     /// </summary>
     public class CommandConsole : ConsoleBase, ICommandConsole
     {
-//        private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
+        //        private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
 
         public event OnOutputDelegate OnOutput;
+        public static event OnCntrCCelegate OnCntrC;
 
         public ICommands Commands { get; private set; }
 
@@ -794,5 +795,28 @@ namespace OpenSim.Framework.Console
         public virtual void ReadConfig(IConfigSource configSource)
         {
         }
+
+        public virtual void SetCntrCHandler(OnCntrCCelegate handler)
+        {
+            if(OnCntrC == null)
+            {
+                OnCntrC += handler;
+                System.Console.CancelKeyPress += CancelKeyPressed;
+            }
+        }
+
+        protected static void CancelKeyPressed(object sender, ConsoleCancelEventArgs args)
+        {
+            if (OnCntrC != null && args.SpecialKey == ConsoleSpecialKey.ControlC)
+            {
+                OnCntrC?.Invoke();
+                args.Cancel = false;
+            }
+        }
+
+        protected static void LocalCancelKeyPressed()
+        {
+            OnCntrC?.Invoke();
+        }
     }
 }

+ 80 - 8
OpenSim/Framework/Console/ConsoleBase.cs

@@ -35,6 +35,32 @@ using log4net;
 
 namespace OpenSim.Framework.Console
 {
+    public class ConsoleLevel
+    {
+        public string m_string;
+
+        ConsoleLevel(string v)
+        {
+            m_string = v;
+        }
+
+        static public implicit operator ConsoleLevel(string s)
+        {
+            return new ConsoleLevel(s);
+        }
+
+        public static string ToString(ConsoleLevel s)
+        {
+            return s.m_string;
+        }
+
+        public override string ToString()
+        {
+            return m_string;
+        }
+    }
+
+
     public class ConsoleBase : IConsole
     {
 //        private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
@@ -58,29 +84,75 @@ namespace OpenSim.Framework.Console
         {
         }
 
-        public void Output(string format, params object[] components)
+        public virtual void Output(string format)
         {
-            Output(format, null, components);
+            System.Console.WriteLine(format);
         }
 
-        public virtual void Output(string format, string level, params object[] components)
+        public virtual void Output(string format, params object[] components)
         {
-            System.Console.WriteLine(format, components);
+            string level = null;
+            if (components != null && components.Length > 0)
+            {
+                if (components[0] == null || components[0] is ConsoleLevel)
+                {
+                    if (components[0] is ConsoleLevel)
+                        level = ((ConsoleLevel)components[0]).ToString();
+
+                    if (components.Length > 1)
+                    {
+                        object[] tmp = new object[components.Length - 1];
+                        Array.Copy(components, 1, tmp, 0, components.Length - 1);
+                        components = tmp;
+                    }
+                    else
+                        components = null;
+                }
+
+            }
+            string text;
+            if (components == null || components.Length == 0)
+                text = format;
+            else
+                text = String.Format(format, components);
+
+            System.Console.WriteLine(text);
         }
 
         public string Prompt(string p)
         {
-            return Prompt(p, null, null, true);
+            return ReadLine(String.Format("{0}: ", p), false, true);
         }
 
         public string Prompt(string p, string def)
         {
-            return Prompt(p, def, null, true);
+            string ret = ReadLine(String.Format("{0} [{1}]: ", p, def), false, true);
+            if (ret == String.Empty)
+                ret = def;
+
+            return ret;
         }
 
         public string Prompt(string p, List<char> excludedCharacters)
         {
-            return Prompt(p, null, excludedCharacters, true);
+            bool itisdone = false;
+            string ret = String.Empty;
+            while (!itisdone)
+            {
+                itisdone = true;
+                ret = Prompt(p);
+
+                foreach (char c in excludedCharacters)
+                {
+                    if (ret.Contains(c.ToString()))
+                    {
+                        System.Console.WriteLine("The character \"" + c.ToString() + "\" is not permitted.");
+                        itisdone = false;
+                    }
+                }
+            }
+
+            return ret;
         }
 
         public virtual string Prompt(string p, string def, List<char> excludedCharacters, bool echo = true)
@@ -91,7 +163,7 @@ namespace OpenSim.Framework.Console
             {
                 itisdone = true;
 
-                if (def != null)
+                if (def == null)
                     ret = ReadLine(String.Format("{0}: ", p), false, echo);
                 else
                     ret = ReadLine(String.Format("{0} [{1}]: ", p, def), false, echo);

+ 10 - 10
OpenSim/Framework/Console/ConsoleUtil.cs

@@ -75,7 +75,7 @@ namespace OpenSim.Framework.Console
         {
             if (File.Exists(path))
             {
-                console.Output("File {0} already exists.  Please move or remove it.", null, path);
+                console.Output("File {0} already exists.  Please move or remove it.", path);
                 return false;
             }
 
@@ -97,7 +97,7 @@ namespace OpenSim.Framework.Console
             if (!UUID.TryParse(rawUuid, out uuid))
             {
                 if (console != null)
-                    console.Output("ERROR: {0} is not a valid uuid", null, rawUuid);
+                    console.Output("ERROR: {0} is not a valid uuid", rawUuid);
 
                 return false;
             }
@@ -110,7 +110,7 @@ namespace OpenSim.Framework.Console
             if (!uint.TryParse(rawLocalId, out localId))
             {
                 if (console != null)
-                    console.Output("ERROR: {0} is not a valid local id", null, localId);
+                    console.Output("ERROR: {0} is not a valid local id", localId);
 
                 return false;
             }
@@ -118,7 +118,7 @@ namespace OpenSim.Framework.Console
             if (localId == 0)
             {
                 if (console != null)
-                    console.Output("ERROR: {0} is not a valid local id - it must be greater than 0", null, localId);
+                    console.Output("ERROR: {0} is not a valid local id - it must be greater than 0", localId);
 
                 return false;
             }
@@ -150,7 +150,7 @@ namespace OpenSim.Framework.Console
             }
 
             if (console != null)
-                console.Output("ERROR: {0} is not a valid UUID or local id", null, rawId);
+                console.Output("ERROR: {0} is not a valid UUID or local id", rawId);
 
             return false;
         }
@@ -167,7 +167,7 @@ namespace OpenSim.Framework.Console
             if (!bool.TryParse(rawConsoleString, out b))
             {
                 if (console != null)
-                    console.Output("ERROR: {0} is not a true or false value", null, rawConsoleString);
+                    console.Output("ERROR: {0} is not a true or false value", rawConsoleString);
 
                 return false;
             }
@@ -187,7 +187,7 @@ namespace OpenSim.Framework.Console
             if (!int.TryParse(rawConsoleInt, out i))
             {
                 if (console != null)
-                    console.Output("ERROR: {0} is not a valid integer", null, rawConsoleInt);
+                    console.Output("ERROR: {0} is not a valid integer", rawConsoleInt);
 
                 return false;
             }
@@ -207,7 +207,7 @@ namespace OpenSim.Framework.Console
             if (!float.TryParse(rawConsoleInput, out i))
             {
                 if (console != null)
-                    console.Output("ERROR: {0} is not a valid float", null, rawConsoleInput);
+                    console.Output("ERROR: {0} is not a valid float", rawConsoleInput);
 
                 return false;
             }
@@ -227,7 +227,7 @@ namespace OpenSim.Framework.Console
             if (!double.TryParse(rawConsoleInput, out i))
             {
                 if (console != null)
-                    console.Output("ERROR: {0} is not a valid double", null, rawConsoleInput);
+                    console.Output("ERROR: {0} is not a valid double", rawConsoleInput);
 
                 return false;
             }
@@ -249,7 +249,7 @@ namespace OpenSim.Framework.Console
                 if (i < 0)
                 {
                     if (console != null)
-                        console.Output("ERROR: {0} is not a positive integer", null, rawConsoleInt);
+                        console.Output("ERROR: {0} is not a positive integer", rawConsoleInt);
 
                     return false;
                 }

+ 38 - 2
OpenSim/Framework/Console/LocalConsole.cs

@@ -150,6 +150,8 @@ namespace OpenSim.Framework.Console
                 m_log.InfoFormat("[LOCAL CONSOLE]: Creating new empty command line history file {0}", m_historyPath);
                 File.Create(m_historyPath).Dispose();
             }
+
+            System.Console.TreatControlCAsInput = true;
         }
 
         private void AddToHistory(string text)
@@ -389,9 +391,36 @@ namespace OpenSim.Framework.Console
             System.Console.WriteLine();
         }
 
-        public override void Output(string format, string level, params object[] components)
+        public override void Output(string format)
+        {
+            Output(format, null);
+        }
+
+        public override void Output(string format, params object[] components)
         {
-            string text = String.Format(format, components);
+            string level = null;
+            if(components != null && components.Length > 0)
+            {
+                if(components[0] == null || components[0] is ConsoleLevel)
+                {
+                    if(components[0] is ConsoleLevel)
+                        level = ((ConsoleLevel)components[0]).ToString();
+
+                    if (components.Length > 1)
+                    {
+                        object[] tmp = new object[components.Length - 1];
+                        Array.Copy(components, 1, tmp, 0, components.Length - 1);
+                        components = tmp;
+                    }
+                    else
+                        components = null;
+                }
+            }
+            string text;
+            if (components == null || components.Length == 0)
+                text = format;
+            else
+                text = String.Format(format, components);
 
             FireOnOutput(text);
 
@@ -464,6 +493,13 @@ namespace OpenSim.Framework.Console
                 Show();
 
                 ConsoleKeyInfo key = System.Console.ReadKey(true);
+
+                if((key.Modifiers & ConsoleModifiers.Control) != 0 && key.Key == ConsoleKey.C)
+                {
+                    System.Console.Write(Environment.NewLine);
+                    LocalCancelKeyPressed();
+                    return string.Empty;
+                }
                 char enteredChar = key.KeyChar;
 
                 if (!Char.IsControl(enteredChar))

+ 2 - 1
OpenSim/Framework/Console/MockConsole.cs

@@ -62,8 +62,8 @@ namespace OpenSim.Framework.Console
             set {}
         }
 
+        public void Output(string format) { }
         public void Output(string format, params object[] components) { }
-        public void Output(string format, string level, params object[] components) { }
 
         public string Prompt(string p) { return ""; }
         public string Prompt(string p, string def) { return ""; }
@@ -75,6 +75,7 @@ namespace OpenSim.Framework.Console
         public string PasswdPrompt(string p) { return ""; }
 
         public void ReadConfig(IConfigSource configSource) { }
+        public void SetCntrCHandler(OnCntrCCelegate handler) { }
     }
 
     public class MockCommands : ICommands

+ 3 - 1
OpenSim/Framework/Console/OpenSimAppender.cs

@@ -55,12 +55,14 @@ namespace OpenSim.Framework.Console
             {
                 if (m_console != null)
                 {
-                    string level = "normal";
+                    ConsoleLevel level;
 
                     if (le.Level == Level.Error)
                         level = "error";
                     else if (le.Level == Level.Warn)
                         level = "warn";
+                    else
+                        level = "normal";
 
                     m_console.Output(loggingMessage, level);
                 }

+ 33 - 7
OpenSim/Framework/Console/RemoteConsole.cs

@@ -190,12 +190,39 @@ namespace OpenSim.Framework.Console
             m_Server.AddHTTPHandler("/SessionCommand/", HandleHttpSessionCommand);
         }
 
-        public override void Output(string format, string level = null, params object[] components)
+        public override void Output(string format)
         {
-            if (components.Length == 0)
-                Output(format, level, false, false, false);
+            Output(format, null);
+        }
+
+        public override void Output(string format, params object[] components)
+        {
+            string level = null;
+            if (components != null && components.Length > 0)
+            {
+                if (components[0] == null || components[0] is ConsoleLevel)
+                {
+                    if (components[0] is ConsoleLevel)
+                        level = ((ConsoleLevel)components[0]).ToString();
+
+                    if (components.Length > 1)
+                    {
+                        object[] tmp = new object[components.Length - 1];
+                        Array.Copy(components, 1, tmp, 0, components.Length - 1);
+                        components = tmp;
+                    }
+                    else
+                        components = null;
+                }
+            }
+
+            string text;
+            if (components == null || components.Length == 0)
+                text = format;
             else
-                Output(String.Format(format, components), level, false, false, false);
+                text = String.Format(format, components);
+
+            Output(text, level, false, false, false);
         }
 
         protected void Output(string text, string level, bool isPrompt, bool isCommand, bool isInput)
@@ -402,10 +429,9 @@ namespace OpenSim.Framework.Console
             }
 
             // This call is a CAP. The URL is the authentication.
-            string uri = "/ReadResponses/" + sessionID.ToString() + "/";
+            string uri = "/ReadResponses/" + sessionID.ToString();
 
-            m_Server.AddPollServiceHTTPHandler(
-                uri, new PollServiceEventArgs(null, uri, HasEvents, GetEvents, NoEvents, null, sessionID,25000)); // 25 secs timeout
+            m_Server.AddPollServiceHTTPHandler(new PollServiceEventArgs(null, uri, HasEvents, GetEvents, NoEvents, null, sessionID,25000)); // 25 secs timeout
 
             // Our reply is an XML document.
             // TODO: Change this to Linq.Xml

+ 16 - 3
OpenSim/Framework/Constants.cs

@@ -25,25 +25,38 @@
  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 using System;
+using OpenMetaverse;
 
 namespace OpenSim.Framework
 {
     public class Constants
     {
+        public const int MaxAgentAttachments = 38;
+        public const int MaxAgentGroups = 60;
+
         // 'RegionSize' is the legacy region size.
         // DO NOT USE THIS FOR ANY NEW CODE. Use Scene.RegionInfo.RegionSize[XYZ] as a region might not
         //      be the legacy region size.
         public const uint RegionSize = 256;
         public const uint RegionHeight = 4096;
-        // This could be a parameters but, really, a region of greater than this is pretty unmanageable
-        public const uint MaximumRegionSize = 8192;
+
+        public const uint MaximumRegionSize = 4096;
 
         // Since terrain is stored in 16x16 heights, regions must be a multiple of this number and that is the minimum
-        public const int MinRegionSize = 16;
+        // but for placement on a grid min must be 256m
+        public const int MinRegionSize = 256;
         public const int TerrainPatchSize = 16;
 
+        public const float MinSimulationHeight = -100f;
+        public const float MaxSimulationHeight = 50000f;
+        public const float MinTerrainHeightmap = -100f;
+        public const float MaxTerrainHeightmap = 4000f;
+
         public const string DefaultTexture = "89556747-24cb-43ed-920b-47caed15465f";
 
+        public static readonly UUID m_MrOpenSimID = new UUID("11111111-1111-0000-0000-000100bba000");
+        public static readonly DateTime m_MrOpenSimBorn = new DateTime(2007, 1, 1, 0, 0, 0, DateTimeKind.Utc);
+
         public enum EstateAccessCodex : uint
         {
             AllowedAccess = 1,

+ 0 - 12
OpenSim/Framework/DoubleDictionaryThreadAbortSafe.cs

@@ -80,18 +80,6 @@ namespace OpenSim.Framework
                     rwLock.EnterWriteLock();
                     gotLock = true;
                 }
-/*
-                    if (Dictionary1.ContainsKey(key1))
-                    {
-                        if (!Dictionary2.ContainsKey(key2))
-                            throw new ArgumentException("key1 exists in the dictionary but not key2");
-                    }
-                    else if (Dictionary2.ContainsKey(key2))
-                    {
-                        if (!Dictionary1.ContainsKey(key1))
-                            throw new ArgumentException("key2 exists in the dictionary but not key1");
-                    }
-*/
                     Dictionary1[key1] = value;
                     Dictionary2[key2] = value;
                     m_array = null;

+ 15 - 5
OpenSim/Framework/EstateSettings.cs

@@ -115,25 +115,28 @@ namespace OpenSim.Framework
 
         // Used by the sim
         //
-        private bool m_UseGlobalTime = true;
+        private bool m_UseGlobalTime = false;
         public bool UseGlobalTime
         {
             get { return m_UseGlobalTime; }
-            set { m_UseGlobalTime = value; }
+            //set { m_UseGlobalTime = value; }
+            set { m_UseGlobalTime = false; }
         }
 
         private bool m_FixedSun = false;
         public bool FixedSun
         {
             get { return m_FixedSun; }
-            set { m_FixedSun = value; }
+            // set { m_FixedSun = value; }
+            set { m_FixedSun = false; }
         }
 
         private double m_SunPosition = 0.0;
         public double SunPosition
         {
             get { return m_SunPosition; }
-            set { m_SunPosition = value; }
+            //set { m_SunPosition = value; }
+            set { m_SunPosition = 0; }
         }
 
         private bool m_AllowVoice = true;
@@ -202,7 +205,7 @@ namespace OpenSim.Framework
         }
 
         private bool m_TaxFree = false;
-        public bool TaxFree // this is now AllowAccessOverride, keeping same name to reuse DB entries
+        public bool TaxFree // this is now !AllowAccessOverride, keeping same name to reuse DB entries
         {
             get { return m_TaxFree; }
             set { m_TaxFree = value; }
@@ -237,6 +240,13 @@ namespace OpenSim.Framework
             set { m_DenyMinors = value; }
         }
 
+        private bool m_AllowEnviromentOverride = false; //keep the mispell so not to go change the dbs
+        public bool AllowEnvironmentOverride
+        {
+            get { return m_AllowEnviromentOverride; }
+            set { m_AllowEnviromentOverride = value; }
+        }
+
         // All those lists...
         //
         private List<UUID> l_EstateManagers = new List<UUID>();

+ 487 - 0
OpenSim/Framework/ExpiringCacheOS.cs

@@ -0,0 +1,487 @@
+/*
+ * Copyright (c) Contributors, http://opensimulator.org/
+ * See CONTRIBUTORS.TXT for a full list of copyright holders.
+ *
+ * - Redistribution and use in source and binary forms, with or without
+ *   modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ * - Neither the name of the openmetaverse.org nor the names
+ *   of its contributors may be used to endorse or promote products derived from
+ *   this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+// this is a lighter alternative to libomv, no sliding option
+
+using System;
+using System.Threading;
+using System.Collections.Generic;
+using Timer = System.Threading.Timer ;
+
+namespace OpenSim.Framework
+{
+    public sealed class ExpiringCacheOS<TKey1, TValue1> : IDisposable
+    {
+        private const int MINEXPIRECHECK = 500;
+
+        private Timer m_purgeTimer;
+        private ReaderWriterLockSlim m_rwLock;
+        private readonly Dictionary<TKey1, int> m_expireControl;
+        private readonly Dictionary<TKey1, TValue1> m_values;
+        private readonly double m_startTS;
+        private readonly int m_expire;
+
+        public ExpiringCacheOS()
+        {
+            m_expireControl = new Dictionary<TKey1, int>();
+            m_values = new Dictionary<TKey1, TValue1>();
+            m_rwLock = new ReaderWriterLockSlim();
+            m_expire = MINEXPIRECHECK;
+            m_startTS = Util.GetTimeStampMS();
+        }
+
+        public ExpiringCacheOS(int expireCheckTimeinMS)
+        {
+            m_expireControl = new Dictionary<TKey1, int>();
+            m_values = new Dictionary<TKey1, TValue1>();
+            m_rwLock = new ReaderWriterLockSlim();
+            m_startTS = Util.GetTimeStampMS();
+            m_expire = (expireCheckTimeinMS > MINEXPIRECHECK) ? m_expire = expireCheckTimeinMS : MINEXPIRECHECK;
+        }
+
+        [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
+        private void CheckTimer()
+        {
+            if (m_purgeTimer == null)
+            {
+                m_purgeTimer = new Timer(Purge, null, m_expire, Timeout.Infinite);
+            }
+        }
+
+        [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
+        private void DisposeTimer()
+        {
+            if (m_purgeTimer != null)
+            {
+                m_purgeTimer.Dispose();
+                m_purgeTimer = null;
+            }
+        }
+
+        ~ExpiringCacheOS()
+        {
+            Dispose(false);
+        }
+
+        public void Dispose()
+        {
+            Dispose(true);
+            GC.SuppressFinalize(this);
+        }
+
+        private void Dispose(bool disposing)
+        {
+            if (m_rwLock != null)
+            {
+                DisposeTimer();
+                m_rwLock.Dispose();
+                m_rwLock = null;
+            }
+        }
+
+        private void Purge(object ignored)
+        {
+            bool gotLock = false;
+
+            try
+            {
+                try { }
+                finally
+                {
+                    m_rwLock.EnterUpgradeableReadLock();
+                    gotLock = true;
+                }
+
+                if (m_expireControl.Count == 0)
+                {
+                    DisposeTimer();
+                    return;
+                }
+
+                int now = (int)(Util.GetTimeStampMS() - m_startTS);
+                List<TKey1> expired = new List<TKey1>(m_expireControl.Count);
+                foreach(KeyValuePair<TKey1, int> kvp in m_expireControl)
+                {
+                    if(kvp.Value < now)
+                        expired.Add(kvp.Key);
+                }
+
+                if(expired.Count > 0)
+                {
+                    bool gotWriteLock = false;
+                    try
+                    {
+                        try { }
+                        finally
+                        {
+                            m_rwLock.EnterWriteLock();
+                            gotWriteLock = true;
+                        }
+
+                        foreach (TKey1 key in expired)
+                        {
+                            m_expireControl.Remove(key);
+                            m_values.Remove(key);
+                        }
+                    }
+                    finally
+                    {
+                        if (gotWriteLock)
+                            m_rwLock.ExitWriteLock();
+                    }
+                    if (m_expireControl.Count == 0)
+                        DisposeTimer();
+                    else
+                        m_purgeTimer.Change(m_expire, Timeout.Infinite);
+                }
+                else
+                    m_purgeTimer.Change(m_expire, Timeout.Infinite);
+            }
+            finally
+            {
+                if (gotLock)
+                    m_rwLock.ExitUpgradeableReadLock();
+            }
+        }
+
+        [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
+        public void AddOrUpdate(TKey1 key, TValue1 val)
+        {
+            Add(key, val);
+        }
+
+        public void Add(TKey1 key, TValue1 val)
+        {
+            bool gotLock = false;
+            int now = (int)(Util.GetTimeStampMS() - m_startTS) + m_expire;
+
+            try
+            {
+                try { }
+                finally
+                {
+                    m_rwLock.EnterWriteLock();
+                    gotLock = true;
+                }
+
+                m_expireControl[key] = now;
+                m_values[key] = val;
+                CheckTimer();
+            }
+            finally
+            {
+                if (gotLock)
+                    m_rwLock.ExitWriteLock();
+            }
+        }
+
+        [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
+        public void AddOrUpdate(TKey1 key, TValue1 val, int expireSeconds)
+        {
+            Add(key, val, expireSeconds * 1000);
+        }
+
+        [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
+        public void AddOrUpdate(TKey1 key, TValue1 val, double expireSeconds)
+        {
+            Add(key, val, (int)(expireSeconds * 1000));
+        }
+
+        public void Add(TKey1 key, TValue1 val, int expireMS)
+        {
+            bool gotLock = false;
+            expireMS = (expireMS > m_expire) ? expireMS : m_expire;
+            int now = (int)(Util.GetTimeStampMS() - m_startTS) + expireMS;
+
+            try
+            {
+                try { }
+                finally
+                {
+                    m_rwLock.EnterWriteLock();
+                    gotLock = true;
+                }
+
+                m_expireControl[key] = now;
+                m_values[key] = val;
+                CheckTimer();
+            }
+            finally
+            {
+                if (gotLock)
+                    m_rwLock.ExitWriteLock();
+            }
+        }
+
+        public bool Remove(TKey1 key)
+        {
+            bool success;
+            bool gotLock = false;
+
+            try
+            {
+                try {}
+                finally
+                {
+                    m_rwLock.EnterWriteLock();
+                    gotLock = true;
+                }
+                success = m_expireControl.Remove(key);
+                success |= m_values.Remove(key);
+                if(m_expireControl.Count == 0)
+                    DisposeTimer();
+            }
+            finally
+            {
+                if (gotLock)
+                    m_rwLock.ExitWriteLock();
+            }
+
+            return success;
+        }
+
+        public void Clear()
+        {
+            bool gotLock = false;
+
+            try
+            {
+                try {}
+                finally
+                {
+                    m_rwLock.EnterWriteLock();
+                    gotLock = true;
+                }
+                DisposeTimer();
+                m_expireControl.Clear();
+                m_values.Clear();
+            }
+            finally
+            {
+                if (gotLock)
+                    m_rwLock.ExitWriteLock();
+            }
+        }
+
+        public int Count
+        {
+            get { return m_expireControl.Count; }
+        }
+
+        [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
+        public bool Contains(TKey1 key)
+        {
+            return ContainsKey(key);
+        }
+
+        public bool ContainsKey(TKey1 key)
+        {
+            bool gotLock = false;
+            try
+            {
+                try { }
+                finally
+                {
+                    m_rwLock.EnterReadLock();
+                    gotLock = true;
+                }
+                return m_expireControl.ContainsKey(key);
+            }
+            finally
+            {
+                if (gotLock)
+                    m_rwLock.ExitReadLock();
+            }
+        }
+
+        [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
+        public bool Contains(TKey1 key, int expireMS)
+        {
+            return ContainsKey(key, expireMS);
+        }
+
+        public bool ContainsKey(TKey1 key, int expireMS)
+        {
+            bool gotLock = false;
+            try
+            {
+                try { }
+                finally
+                {
+                    m_rwLock.EnterUpgradeableReadLock();
+                    gotLock = true;
+                }
+                if(m_expireControl.ContainsKey(key))
+                {
+                    bool gotWriteLock = false;
+                    try
+                    {
+                        try { }
+                        finally
+                        {
+                            m_rwLock.EnterWriteLock();
+                            gotWriteLock = true;
+                        }
+                        expireMS = (expireMS > m_expire) ? expireMS : m_expire;
+                        int now = (int)(Util.GetTimeStampMS() - m_startTS) + expireMS;
+
+                        m_expireControl[key] = now;
+                        return true;
+                    }
+                    finally
+                    {
+                        if (gotWriteLock)
+                            m_rwLock.ExitWriteLock();
+                    }
+                }
+                return false;
+            }
+            finally
+            {
+                if (gotLock)
+                    m_rwLock.ExitUpgradeableReadLock();
+            }
+        }
+
+        public bool TryGetValue(TKey1 key, out TValue1 value)
+        {
+            bool success;
+            bool gotLock = false;
+
+            try
+            {
+                try {}
+                finally
+                {
+                    m_rwLock.EnterReadLock();
+                    gotLock = true;
+                }
+
+                success = m_values.TryGetValue(key, out value);
+            }
+            finally
+            {
+                if (gotLock)
+                    m_rwLock.ExitReadLock();
+            }
+
+            return success;
+        }
+
+        public bool TryGetValue(TKey1 key, int expireMS, out TValue1 value)
+        {
+            bool success;
+            bool gotLock = false;
+
+            try
+            {
+                try { }
+                finally
+                {
+                    m_rwLock.EnterUpgradeableReadLock();
+                    gotLock = true;
+                }
+
+                success = m_values.TryGetValue(key, out value);
+                if(success)
+                {
+                    bool gotWriteLock = false;
+                    try
+                    {
+                        try { }
+                        finally
+                        {
+                            m_rwLock.EnterWriteLock();
+                            gotWriteLock = true;
+                        }
+                        expireMS = (expireMS > m_expire) ? expireMS : m_expire;
+                        int now = (int)(Util.GetTimeStampMS() - m_startTS) + expireMS;
+
+                        m_expireControl[key] = now;
+                    }
+                    finally
+                    {
+                        if (gotWriteLock)
+                            m_rwLock.ExitWriteLock();
+                    }
+                }
+            }
+            finally
+            {
+                if (gotLock)
+                    m_rwLock.ExitUpgradeableReadLock();
+            }
+
+            return success;
+        }
+
+        public ICollection<TValue1> Values
+        {
+            get
+            {
+                bool gotLock = false;
+                try
+                {
+                    try { }
+                    finally
+                    {
+                        m_rwLock.EnterUpgradeableReadLock();
+                        gotLock = true;
+                    }
+                    return m_values.Values;
+                }
+                finally
+                {
+                    if (gotLock)
+                        m_rwLock.ExitUpgradeableReadLock();
+                }
+            }
+        }
+
+        public ICollection<TKey1> Keys
+        {
+            get
+            {
+                bool gotLock = false;
+                try
+                {
+                    try { }
+                    finally
+                    {
+                        m_rwLock.EnterUpgradeableReadLock();
+                        gotLock = true;
+                    }
+                    return m_values.Keys;
+                }
+                finally
+                {
+                    if (gotLock)
+                        m_rwLock.ExitUpgradeableReadLock();
+                }
+            }
+        }
+    }
+}

+ 352 - 0
OpenSim/Framework/ExpiringKey.cs

@@ -0,0 +1,352 @@
+/*
+ * Copyright (c) Contributors, http://opensimulator.org/
+ * See CONTRIBUTORS.TXT for a full list of copyright holders.
+ *
+ * - Redistribution and use in source and binary forms, with or without
+ *   modification, are permitted provided that the following conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ * - Neither the name of the openmetaverse.org nor the names
+ *   of its contributors may be used to endorse or promote products derived from
+ *   this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+using System;
+using System.Threading;
+using System.Collections.Generic;
+using Timer = System.Threading.Timer ;
+
+namespace OpenSim.Framework
+{
+    public sealed class ExpiringKey<Tkey1> : IDisposable
+    {
+        private const int MINEXPIRECHECK = 500;
+
+        private Timer m_purgeTimer;
+        private ReaderWriterLockSlim m_rwLock;
+        private readonly Dictionary<Tkey1, int> m_dictionary;
+        private readonly double m_startTS;
+        private readonly int m_expire;
+
+        public ExpiringKey()
+        {
+            m_dictionary = new Dictionary<Tkey1, int>();
+            m_rwLock = new ReaderWriterLockSlim();
+            m_expire = MINEXPIRECHECK;
+            m_startTS = Util.GetTimeStampMS();
+        }
+
+        public ExpiringKey(int expireCheckTimeinMS)
+        {
+            m_dictionary = new Dictionary<Tkey1, int>();
+            m_rwLock = new ReaderWriterLockSlim();
+            m_startTS = Util.GetTimeStampMS();
+            m_expire = (expireCheckTimeinMS > MINEXPIRECHECK) ? m_expire = expireCheckTimeinMS : MINEXPIRECHECK;
+        }
+
+        [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
+        private void CheckTimer()
+        {
+            if (m_purgeTimer == null)
+            {
+                m_purgeTimer = new Timer(Purge, null, m_expire, Timeout.Infinite);
+            }
+        }
+
+        [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
+        private void DisposeTimer()
+        {
+            if (m_purgeTimer != null)
+            {
+                m_purgeTimer.Dispose();
+                m_purgeTimer = null;
+            }
+        }
+
+        ~ExpiringKey()
+        {
+            Dispose(false);
+        }
+
+        public void Dispose()
+        {
+            Dispose(true);
+            GC.SuppressFinalize(this);
+        }
+
+        private void Dispose(bool disposing)
+        {
+            if (m_rwLock != null)
+            {
+                DisposeTimer();
+                m_rwLock.Dispose();
+                m_rwLock = null;
+            }
+        }
+
+        private void Purge(object ignored)
+        {
+            bool gotLock = false;
+
+            try
+            {
+                try { }
+                finally
+                {
+                    m_rwLock.EnterUpgradeableReadLock();
+                    gotLock = true;
+                }
+
+                if (m_dictionary.Count == 0)
+                {
+                    DisposeTimer();
+                    return;
+                }
+
+                int now = (int)(Util.GetTimeStampMS() - m_startTS);
+                List<Tkey1> expired = new List<Tkey1>(m_dictionary.Count);
+                foreach(KeyValuePair<Tkey1,int> kvp in m_dictionary)
+                {
+                    if(kvp.Value < now)
+                        expired.Add(kvp.Key);
+                }
+
+                if (expired.Count > 0)
+                {
+                    bool gotWriteLock = false;
+                    try
+                    {
+                        try { }
+                        finally
+                        {
+                            m_rwLock.EnterWriteLock();
+                            gotWriteLock = true;
+                        }
+
+                        foreach (Tkey1 key in expired)
+                            m_dictionary.Remove(key);
+                    }
+                    finally
+                    {
+                        if (gotWriteLock)
+                            m_rwLock.ExitWriteLock();
+                    }
+                    if (m_dictionary.Count == 0)
+                        DisposeTimer();
+                    else
+                        m_purgeTimer.Change(m_expire, Timeout.Infinite);
+                }
+                else
+                    m_purgeTimer.Change(m_expire, Timeout.Infinite);
+            }
+            finally
+            {
+                if (gotLock)
+                    m_rwLock.ExitUpgradeableReadLock();
+            }
+        }
+
+        public void Add(Tkey1 key)
+        {
+            bool gotLock = false;
+            int now = (int)(Util.GetTimeStampMS() - m_startTS) + m_expire;
+
+            try
+            {
+                try { }
+                finally
+                {
+                    m_rwLock.EnterWriteLock();
+                    gotLock = true;
+                }
+
+                m_dictionary[key] = now;
+                CheckTimer();
+            }
+            finally
+            {
+                if (gotLock)
+                    m_rwLock.ExitWriteLock();
+            }
+        }
+
+        public void Add(Tkey1 key, int expireMS)
+        {
+            bool gotLock = false;
+            expireMS = (expireMS > m_expire) ? expireMS : m_expire;
+            int now = (int)(Util.GetTimeStampMS() - m_startTS) + expireMS;
+
+            try
+            {
+                try { }
+                finally
+                {
+                    m_rwLock.EnterWriteLock();
+                    gotLock = true;
+                }
+
+                m_dictionary[key] = now;
+                CheckTimer();
+            }
+            finally
+            {
+                if (gotLock)
+                    m_rwLock.ExitWriteLock();
+            }
+        }
+
+        public bool Remove(Tkey1 key)
+        {
+            bool success;
+            bool gotLock = false;
+
+            try
+            {
+                try {}
+                finally
+                {
+                    m_rwLock.EnterWriteLock();
+                    gotLock = true;
+                }
+                success = m_dictionary.Remove(key);
+                if(m_dictionary.Count == 0)
+                    DisposeTimer();
+            }
+            finally
+            {
+                if (gotLock)
+                    m_rwLock.ExitWriteLock();
+            }
+
+            return success;
+        }
+
+        public void Clear()
+        {
+            bool gotLock = false;
+
+            try
+            {
+                try {}
+                finally
+                {
+                    m_rwLock.EnterWriteLock();
+                    gotLock = true;
+                }
+                m_dictionary.Clear();
+                DisposeTimer();
+            }
+            finally
+            {
+                if (gotLock)
+                    m_rwLock.ExitWriteLock();
+            }
+        }
+
+        public int Count
+        {
+            get { return m_dictionary.Count; }
+        }
+
+        public bool ContainsKey(Tkey1 key)
+        {
+            bool gotLock = false;
+            try
+            {
+                try { }
+                finally
+                {
+                    m_rwLock.EnterReadLock();
+                    gotLock = true;
+                }
+                return m_dictionary.ContainsKey(key);
+            }
+            finally
+            {
+                if (gotLock)
+                    m_rwLock.ExitReadLock();
+            }
+        }
+
+        public bool ContainsKey(Tkey1 key, int expireMS)
+        {
+            bool gotLock = false;
+            try
+            {
+                try { }
+                finally
+                {
+                    m_rwLock.EnterUpgradeableReadLock();
+                    gotLock = true;
+                }
+                if (m_dictionary.ContainsKey(key))
+                {
+                    bool gotWriteLock = false;
+                    try
+                    {
+                        try { }
+                        finally
+                        {
+                            m_rwLock.EnterWriteLock();
+                            gotWriteLock = true;
+                        }
+                        expireMS = (expireMS > m_expire) ? expireMS : m_expire;
+                        int now = (int)(Util.GetTimeStampMS() - m_startTS) + expireMS;
+
+                        m_dictionary[key] = now;
+                        return true;
+                    }
+                    finally
+                    {
+                        if (gotWriteLock)
+                            m_rwLock.ExitWriteLock();
+                    }
+                }
+                return false;
+            }
+            finally
+            {
+                if (gotLock)
+                    m_rwLock.EnterUpgradeableReadLock();
+            }
+        }
+
+        public bool TryGetValue(Tkey1 key, out int value)
+        {
+            bool success;
+            bool gotLock = false;
+
+            try
+            {
+                try {}
+                finally
+                {
+                    m_rwLock.EnterReadLock();
+                    gotLock = true;
+                }
+
+                success = m_dictionary.TryGetValue(key, out value);
+            }
+            finally
+            {
+                if (gotLock)
+                    m_rwLock.ExitReadLock();
+            }
+
+            return success;
+        }
+    }
+}

+ 569 - 0
OpenSim/Framework/GridInfo.cs

@@ -0,0 +1,569 @@
+/*
+ * Copyright (c) Contributors, http://opensimulator.org/
+ * See CONTRIBUTORS.TXT for a full list of copyright holders.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *     * Redistributions of source code must retain the above copyright
+ *       notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above copyright
+ *       notice, this list of conditions and the following disclaimer in the
+ *       documentation and/or other materials provided with the distribution.
+ *     * Neither the name of the OpenSimulator Project nor the
+ *       names of its contributors may be used to endorse or promote products
+ *       derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+using System;
+using System.Collections.Generic;
+using System.Net;
+using System.Reflection;
+using log4net;
+using Nini.Config;
+
+namespace OpenSim.Framework
+{
+    public enum OSHTTPURIFlags : byte
+    {
+        None        = 0,
+        ValidHost   = 1,
+        Resolved    = 1 << 1,
+
+        ValidResolved = ValidHost | Resolved
+    }
+
+    // full http or https schema, server host, port and possible server path any query is ignored.
+    public struct OSHTTPURI:IComparable<OSHTTPURI>, IEquatable<OSHTTPURI>
+    {
+        public OSHTTPURIFlags Flags;
+        public int Port;
+        public IPAddress IP;
+        public readonly string Host;
+        public readonly string URI;
+        public readonly string Path;
+
+        public OSHTTPURI(string uri, bool withDNSResolve = false)
+        {
+            Flags = OSHTTPURIFlags.None;
+            Port = -1;
+            IP = null;
+            Host = string.Empty;
+            URI = string.Empty;
+            Path = string.Empty;
+
+            if (string.IsNullOrEmpty(uri))
+                return;
+
+            try
+            {
+                Uri m_checkuri = new Uri(uri);
+
+                if(m_checkuri.Scheme != Uri.UriSchemeHttp && m_checkuri.Scheme != Uri.UriSchemeHttps)
+                    return;
+
+                Flags = OSHTTPURIFlags.ValidHost;
+                Host = m_checkuri.DnsSafeHost.ToLowerInvariant();
+
+                Port = m_checkuri.Port;
+                Path = m_checkuri.AbsolutePath;
+                if (Path[Path.Length - 1] == '/')
+                    Path = Path.Substring(0, Path.Length - 1);
+
+                URI = m_checkuri.Scheme + "://" + Host + ":" + Port + Path;
+
+                if (withDNSResolve)
+                {
+                    IPAddress ip = Util.GetHostFromDNS(Host);
+                    if (ip != null)
+                    {
+                        IP = ip;
+                        Flags = OSHTTPURIFlags.ValidResolved;
+                    }
+                }
+            }
+            catch
+            {
+                Flags = OSHTTPURIFlags.None;
+                IP = null;
+                URI = string.Empty;
+            }
+        }
+
+        public bool ResolveDNS()
+        {
+            IPAddress ip = Util.GetHostFromDNS(Host);
+            if (ip == null)
+            {
+                Flags &= ~OSHTTPURIFlags.Resolved;
+                return false;
+            }
+            Flags |= OSHTTPURIFlags.Resolved;
+            return true;
+        }
+
+        public bool IsValidHost
+        {
+            get { return Flags != OSHTTPURIFlags.None;}
+        }
+
+        public bool ValidAndResolved(out string error)
+        {
+            if (Flags == OSHTTPURIFlags.None)
+            {
+                error = "failed to parse uri";
+                return false;
+            }
+            if ((Flags & OSHTTPURIFlags.Resolved) == 0)
+            {
+                error = "failed DNS resolve of uri host";
+                return false;
+            }
+            error = string.Empty;
+            return true;
+        }
+
+        public bool IsResolvedHost
+        {
+            get {return (Flags & OSHTTPURIFlags.Resolved) != 0; }
+        }
+
+        public string URIwEndSlash
+        {
+            get { return Flags != OSHTTPURIFlags.None ? "" : URI + "/";}
+        }
+
+        public int CompareTo(OSHTTPURI other)
+        {
+            if (Port == other.Port && ((Flags & other.Flags) & OSHTTPURIFlags.ValidHost) != 0)
+            {
+                if (Path.Equals(other.Path))
+                    return Host.CompareTo(other.Host);
+            }
+            return -1;
+        }
+
+        public bool Equals(OSHTTPURI other)
+        {
+            if (Port == other.Port && ((Flags & other.Flags) & OSHTTPURIFlags.ValidHost) != 0)
+            {
+                if (Path.Equals(other.Path))
+                    return Host.Equals(other.Host);
+            }
+            return false;
+        }
+
+        public override int GetHashCode()
+        {
+            return URI.GetHashCode();
+        }
+    }
+
+    //host and port. Can not have server internal path or query. http scheme is assumed if not present
+    public struct OSHHTPHost : IComparable<OSHHTPHost>, IEquatable<OSHHTPHost>
+    {
+        public OSHTTPURIFlags Flags;
+        public int Port;
+        public IPAddress IP;
+        public readonly string Host;
+        public readonly string URI;
+
+        public OSHHTPHost(string url, bool withDNSResolve = false)
+        {
+            Flags = OSHTTPURIFlags.None;
+            Port = 80;
+            IP = null;
+            Host = string.Empty;
+            URI = string.Empty;
+
+            bool secureHTTP = false;
+
+            if (string.IsNullOrEmpty(url))
+                return;
+
+            url = url.ToLowerInvariant();
+
+            try
+            {
+                int urllen = url.Length;
+                if (url[urllen - 1] == '/')
+                    --urllen;
+                int start;
+                if (url.StartsWith("http"))
+                {
+                    if (url[4] == 's')
+                    {
+                        start = 8;
+                        secureHTTP = true;
+                    }
+                    else
+                        start = 7;
+                }
+                else
+                    start = 0;
+
+                string host;
+                UriHostNameType type;
+                int indx = url.IndexOf(':', start, urllen - start);
+                if (indx > 0)
+                {
+                    host = url.Substring(start, indx - start);
+                    type = Uri.CheckHostName(host);
+                    if (type == UriHostNameType.Unknown || type == UriHostNameType.Basic)
+                        return;
+                    ++indx;
+                    string sport = url.Substring(indx, urllen - indx);
+                    int tmp;
+                    if (!int.TryParse(sport, out tmp) || tmp < 0 || tmp > 65535)
+                        return;
+
+                    Flags = OSHTTPURIFlags.ValidHost;
+                    Host = host;
+                    Port = tmp;
+                    URI = (secureHTTP ? "https://" : "http://") + Host + ":" + Port.ToString();
+                }
+                else
+                {
+                    host = url.Substring(start, urllen - start);
+                    type = Uri.CheckHostName(host);
+                    if (type == UriHostNameType.Unknown || type == UriHostNameType.Basic)
+                        return;
+
+                    Flags = OSHTTPURIFlags.ValidHost;
+                    Host = host;
+                    if (secureHTTP)
+                    {
+                        Port = 443;
+                        URI = "https://" + Host + ":443";
+                    }
+                    else
+                    {
+                        Port = 80;
+                        URI = "http://" + Host + ":80";
+                    }
+                }
+
+                if (withDNSResolve)
+                {
+                    IPAddress ip = Util.GetHostFromDNS(host);
+                    if (ip != null)
+                    {
+                        Flags = OSHTTPURIFlags.ValidResolved;
+                        IP = ip;
+                    }
+                }
+            }
+            catch
+            {
+                Flags = OSHTTPURIFlags.None;
+                IP = null;
+                URI = string.Empty;
+            }
+        }
+
+        public bool ResolveDNS()
+        {
+            IPAddress ip = Util.GetHostFromDNS(Host);
+            if (ip == null)
+            {
+                Flags &= ~OSHTTPURIFlags.Resolved;
+                return false;
+            }
+            Flags |= OSHTTPURIFlags.Resolved;
+            return true;
+        }
+
+        public bool IsValidHost
+        {
+            get { return Flags != OSHTTPURIFlags.None; }
+        }
+
+        public bool IsResolvedHost
+        {
+            get { return (Flags & OSHTTPURIFlags.Resolved) != 0; }
+        }
+
+        public bool ValidAndResolved(out string error)
+        {
+            if (Flags == OSHTTPURIFlags.None)
+            {
+                error = "failed to parse uri";
+                return false;
+            }
+            if ((Flags & OSHTTPURIFlags.Resolved) == 0)
+            {
+                error = "failed DNS resolve of uri host";
+                return false;
+            }
+            error = string.Empty;
+            return true;
+        }
+
+        public string URIwEndSlash
+        {
+            get { return (Flags == OSHTTPURIFlags.None) ? "" : URI + "/"; }
+        }
+
+        public int CompareTo(OSHHTPHost other)
+        {
+            if (Port == other.Port && ((Flags & other.Flags) & OSHTTPURIFlags.ValidHost) != 0)
+            {
+                return Host.CompareTo(other.Host);
+            }
+            return -1;
+        }
+
+        public bool Equals(OSHHTPHost other)
+        {
+            if (Port == other.Port && ((Flags & other.Flags) & OSHTTPURIFlags.ValidHost) != 0)
+            {
+                return Host.Equals(other.Host);
+            }
+            return false;
+        }
+
+        public override int GetHashCode()
+        {
+            return URI.GetHashCode();
+        }
+    }
+
+    public class GridInfo
+    {
+        private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
+
+        private bool m_hasHGconfig;
+        private OSHHTPHost m_gateKeeperURL;
+        private HashSet<OSHHTPHost> m_gateKeeperAlias;
+
+        private OSHHTPHost m_homeURL;
+        private HashSet<OSHHTPHost> m_homeURLAlias;
+
+        public GridInfo (IConfigSource config, string defaultURI = "")
+        {
+            string[] sections = new string[] { "Startup", "Hypergrid"};
+
+            string gatekeeper = Util.GetConfigVarFromSections<string>(config, "GatekeeperURI", sections, String.Empty);
+            if (string.IsNullOrEmpty(gatekeeper))
+            {
+                IConfig serverConfig = config.Configs["GatekeeperService"];
+                if (serverConfig != null)
+                    gatekeeper = serverConfig.GetString("ExternalName", string.Empty);
+            }
+            if (string.IsNullOrEmpty(gatekeeper))
+            {
+                IConfig gridConfig = config.Configs["GridService"];
+                if (gridConfig != null)
+                    gatekeeper = gridConfig.GetString("Gatekeeper", string.Empty);
+            }
+            if (string.IsNullOrEmpty(gatekeeper))
+            {
+                m_hasHGconfig = false;
+                if (!string.IsNullOrEmpty(defaultURI))
+                    m_gateKeeperURL = new OSHHTPHost(defaultURI, true);
+            }
+            else
+            {
+                m_gateKeeperURL = new OSHHTPHost(gatekeeper, true);
+                m_hasHGconfig = true;
+            }
+
+            if (!m_gateKeeperURL.IsResolvedHost)
+            {
+                m_log.Error(m_gateKeeperURL.IsValidHost ?  "Could not resolve GatekeeperURI" : "GatekeeperURI is a invalid host");
+                throw new Exception("GatekeeperURI configuration error");
+            }
+
+            string gatekeeperURIAlias = Util.GetConfigVarFromSections<string>(config, "GatekeeperURIAlias", sections, String.Empty);
+
+            if (!string.IsNullOrWhiteSpace(gatekeeperURIAlias))
+            {
+                string[] alias = gatekeeperURIAlias.Split(',');
+                for (int i = 0; i < alias.Length; ++i)
+                {
+                    OSHHTPHost tmp = new OSHHTPHost(alias[i].Trim(), false);
+                    if (tmp.IsValidHost)
+                    {
+                        if (m_gateKeeperAlias == null)
+                            m_gateKeeperAlias = new HashSet<OSHHTPHost>();
+                        m_gateKeeperAlias.Add(tmp);
+                    }
+                }
+            }
+
+            string home = Util.GetConfigVarFromSections<string>(config, "HomeURI", sections, string.Empty);
+
+            if (string.IsNullOrEmpty(home))
+            {
+                if (!string.IsNullOrEmpty(gatekeeper))
+                    m_homeURL = m_gateKeeperURL;
+                else if (!string.IsNullOrEmpty(defaultURI))
+                    m_homeURL = new OSHHTPHost(defaultURI, true);
+            }
+            else
+                m_homeURL = new OSHHTPHost(home, true);
+
+            if (!m_homeURL.IsResolvedHost)
+            {
+                m_log.Error(m_homeURL.IsValidHost ?  "Could not resolve HomeURI" : "HomeURI is a invalid host");
+                throw new Exception("HomeURI configuration error");
+            }
+
+            string homeAlias = Util.GetConfigVarFromSections<string>(config, "HomeURIAlias", sections, String.Empty);
+            if (!string.IsNullOrWhiteSpace(homeAlias))
+            {
+                string[] alias = homeAlias.Split(',');
+                for (int i = 0; i < alias.Length; ++i)
+                {
+                    OSHHTPHost tmp = new OSHHTPHost(alias[i].Trim(), false);
+                    if (tmp.IsValidHost)
+                    {
+                        if (m_homeURLAlias == null)
+                            m_homeURLAlias = new HashSet<OSHHTPHost>();
+                        m_homeURLAlias.Add(tmp);
+                    }
+                }
+            }
+        }
+
+        public bool HasHGConfig
+        {
+            get { return m_hasHGconfig; }
+        }
+
+        public string GateKeeperURL
+        {
+            get { return m_gateKeeperURL.URIwEndSlash; }
+        }
+
+        public string GateKeeperURLNoEndSlash
+        {
+            get { return m_gateKeeperURL.URI; }
+        }
+
+        public string HGGateKeeperURL
+        {
+            get
+            {
+                if (m_hasHGconfig)
+                    return m_gateKeeperURL.URIwEndSlash;
+                return string.Empty;
+            }
+        }
+
+        public string HGGateKeeperURLNoEndSlash
+        {
+            get
+            {
+                if (m_hasHGconfig)
+                    return m_gateKeeperURL.URI;
+                return string.Empty;
+            }
+        }
+
+        public string HomeURL
+        {
+            get { return m_homeURL.URIwEndSlash; }
+        }
+
+        public string HomeURLNoEndSlash
+        {
+            get { return m_homeURL.URI; }
+        }
+
+        public string HGHomeURL
+        {
+            get
+            {
+                if (m_hasHGconfig)
+                    return m_homeURL.URIwEndSlash;
+                return string.Empty;
+            }
+        }
+
+        public string HGHomeURLNoEndSlash
+        {
+            get
+            {
+                if (m_hasHGconfig)
+                    return m_homeURL.URI;
+                return string.Empty;
+            }
+        }
+
+        // -2 dns failed
+        // -1 if bad url
+        // 0 if not local
+        // 1 if local
+        public int IsLocalGrid(string othergatekeeper)
+        {
+            OSHHTPHost tmp = new OSHHTPHost(othergatekeeper, false);
+            if (!tmp.IsValidHost)
+                return -1;
+            if (tmp.Equals(m_gateKeeperURL))
+                return 1;
+            if (m_gateKeeperAlias != null && m_gateKeeperAlias.Contains(tmp))
+                return 1;
+            return 0;
+        }
+
+        public int IsLocalGrid(string othergatekeeper, bool withResolveCheck)
+        {
+            OSHHTPHost tmp = new OSHHTPHost(othergatekeeper, false);
+            if (!tmp.IsValidHost)
+                return -1;
+            if (tmp.Equals(m_gateKeeperURL))
+                return 1;
+            if (m_gateKeeperAlias != null && m_gateKeeperAlias.Contains(tmp))
+                return 1;
+            if (withResolveCheck)
+            {
+                if (tmp.IsResolvedHost)
+                    return 0;
+                return tmp.ResolveDNS() ? 0 : -2;
+            }
+            return 0;
+        }
+
+        public int IsLocalHome(string otherhome)
+        {
+            OSHHTPHost tmp = new OSHHTPHost(otherhome, false);
+            if (!tmp.IsValidHost)
+                return -1;
+            if (tmp.Equals(m_homeURL))
+                return 1;
+            if (m_homeURLAlias != null && m_homeURLAlias.Contains(tmp))
+                return 1;
+            return 0;
+        }
+
+        public int IsLocalHome(string otherhome, bool withResolveCheck)
+        {
+            OSHHTPHost tmp = new OSHHTPHost(otherhome, false);
+            if (!tmp.IsValidHost)
+                return -1;
+            if (tmp.Equals(m_homeURL))
+                return 1;
+            if (m_homeURLAlias != null && m_homeURLAlias.Contains(tmp))
+                return 1;
+
+            if (withResolveCheck)
+            {
+                if (tmp.IsResolvedHost)
+                    return 0;
+                return tmp.ResolveDNS() ? 0 : -2;
+            }
+            return 0;
+        }
+    }
+}

+ 1 - 1
OpenSim/Framework/IAssetCache.cs

@@ -35,7 +35,7 @@ namespace OpenSim.Framework
         /// Cache the specified asset.
         /// </summary>
         /// <param name='asset'></param>
-        void Cache(AssetBase asset);
+        void Cache(AssetBase asset, bool replace = false);
 
         /// <summary>
         /// Cache that the specified asset wasn't found.

+ 17 - 88
OpenSim/Framework/IClientAPI.cs

@@ -60,9 +60,8 @@ namespace OpenSim.Framework
     public delegate void ObjectAttach(
         IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, bool silent);
 
-    public delegate void ModifyTerrain(UUID user,
-        float height, float seconds, byte size, byte action, float north, float west, float south, float east,
-        UUID agentId);
+    public delegate void ModifyTerrain(UUID user, float height, float seconds, float brushSize,
+        byte action, float north, float west, float south, float east, int parcelLocalID);
 
     public delegate void NetworkStats(int inPackets, int outPackets, int unAckedBytes);
 
@@ -222,7 +221,9 @@ namespace OpenSim.Framework
     public delegate void AddNewPrim(
         UUID ownerID, UUID groupID, Vector3 RayEnd, Quaternion rot, PrimitiveBaseShape shape, byte bypassRaycast, Vector3 RayStart,
         UUID RayTargetID,
-        byte RayEndIsIntersection);
+        byte RayEndIsIntersection, uint addflags);
+
+    public delegate void AgentDataUpdate(IClientAPI remoteClient, UUID itemID, UUID ownerID);
 
     public delegate void RequestGodlikePowers(
         UUID AgentID, UUID SessionID, UUID token, bool GodLike);
@@ -253,7 +254,7 @@ namespace OpenSim.Framework
     public delegate void PurgeInventoryDescendents(
         IClientAPI remoteClient, UUID folderID);
 
-    public delegate void FetchInventory(IClientAPI remoteClient, UUID itemID, UUID ownerID);
+    public delegate void FetchInventory(IClientAPI remoteClient, UUID[] items, UUID[] owner);
 
     public delegate void RequestTaskInventory(IClientAPI remoteClient, uint localID);
 
@@ -315,7 +316,6 @@ namespace OpenSim.Framework
                                    bool removeContribution, int parcelLocalID, int parcelArea, int parcelPrice,
                                    bool authenticated);
 
-    // We keep all this information for fraud purposes in the future.
     public delegate void MoneyBalanceRequest(IClientAPI remoteClient, UUID agentID, UUID sessionID, UUID TransactionID);
 
     public delegate void ObjectPermissions(
@@ -355,8 +355,7 @@ namespace OpenSim.Framework
 
     public delegate void SetEstateTerrainDetailTexture(IClientAPI remoteClient, int corner, UUID side);
 
-    public delegate void SetEstateTerrainTextureHeights(IClientAPI remoteClient, int corner, float lowVal, float highVal
-        );
+    public delegate void SetEstateTerrainTextureHeights(IClientAPI remoteClient, int corner, float lowVal, float highVal);
 
     public delegate void CommitEstateTerrainTextureRequest(IClientAPI remoteClient);
 
@@ -583,58 +582,6 @@ namespace OpenSim.Framework
         public float dwell;
     }
 
-    public class EntityUpdate
-    {
-        private ISceneEntity m_entity;
-        private PrimUpdateFlags m_flags;
-
-        public ISceneEntity Entity
-        {
-            get { return m_entity; }
-        }
-
-        public PrimUpdateFlags Flags
-        {
-            get { return m_flags; }
-            set { m_flags = value; }
-        }
-
-        public virtual void Update()
-        {
-            // we are on the new one
-            if (m_flags.HasFlag(PrimUpdateFlags.CancelKill))
-            {
-                if (m_flags.HasFlag(PrimUpdateFlags.UpdateProbe))
-                    m_flags = PrimUpdateFlags.UpdateProbe;
-                else
-                    m_flags = PrimUpdateFlags.FullUpdatewithAnim;
-            }
-        }
-
-        public virtual void Update(EntityUpdate oldupdate)
-        {
-            // we are on the new one
-            PrimUpdateFlags updateFlags = oldupdate.Flags;
-            if (updateFlags.HasFlag(PrimUpdateFlags.UpdateProbe))
-                updateFlags &= ~PrimUpdateFlags.UpdateProbe;
-            if (m_flags.HasFlag(PrimUpdateFlags.CancelKill))
-            {
-                if(m_flags.HasFlag(PrimUpdateFlags.UpdateProbe))
-                    m_flags = PrimUpdateFlags.UpdateProbe;
-                else
-                    m_flags = PrimUpdateFlags.FullUpdatewithAnim;
-            }
-            else
-                m_flags |= updateFlags;
-        }
-
-        public EntityUpdate(ISceneEntity entity, PrimUpdateFlags flags)
-        {
-            m_entity = entity;
-            m_flags = flags;
-        }
-    }
-
     public class PlacesReplyData
     {
         public UUID OwnerID;
@@ -696,15 +643,6 @@ namespace OpenSim.Framework
         Kill =          0x80000000 // 1 << 31
     }
 
-/* included in .net 4.0
-    public static class PrimUpdateFlagsExtensions
-    {
-        public static bool HasFlag(this PrimUpdateFlags updateFlags, PrimUpdateFlags flag)
-        {
-            return (updateFlags & flag) == flag;
-        }
-    }
-*/
     public interface IClientAPI
     {
         Vector3 StartPos { get; set; }
@@ -847,7 +785,7 @@ namespace OpenSim.Framework
         event Action<IClientAPI> OnRequestAvatarsData;
         event AddNewPrim OnAddPrim;
 
-        event FetchInventory OnAgentDataUpdateRequest;
+        event AgentDataUpdate OnAgentDataUpdateRequest;
         event TeleportLocationRequest OnSetStartLocationRequest;
 
         event RequestGodlikePowers OnRequestGodlikePowers;
@@ -1075,6 +1013,7 @@ namespace OpenSim.Framework
         /// Close this client
         /// </summary>
         void Close();
+        void Disconnect(string reason);
 
         /// <summary>
         /// Close this client
@@ -1206,10 +1145,10 @@ namespace OpenSim.Framework
         void FlushPrimUpdates();
 
         void SendInventoryFolderDetails(UUID ownerID, UUID folderID, List<InventoryItemBase> items,
-                                        List<InventoryFolderBase> folders, int version, bool fetchFolders,
-                                        bool fetchItems);
+                                        List<InventoryFolderBase> folders, int version, int descendents, 
+                                        bool fetchFolders, bool fetchItems);
 
-        void SendInventoryItemDetails(UUID ownerID, InventoryItemBase item);
+        void SendInventoryItemDetails(InventoryItemBase[] items);
 
         /// <summary>
         /// Tell the client that we have created the item it requested.
@@ -1219,6 +1158,7 @@ namespace OpenSim.Framework
         void SendInventoryItemCreateUpdate(InventoryItemBase Item, UUID transactionID, uint callbackId);
 
         void SendRemoveInventoryItem(UUID itemID);
+        void SendRemoveInventoryItems(UUID[] items);
 
         void SendTakeControls(int controls, bool passToAgent, bool TakeControls);
 
@@ -1234,7 +1174,8 @@ namespace OpenSim.Framework
         /// (including all descendent folders) as well as the folder itself.
         ///
         /// <param name="node"></param>
-        void SendBulkUpdateInventory(InventoryNodeBase node);
+        void SendBulkUpdateInventory(InventoryNodeBase node, UUID? transactionID = null);
+        void SendBulkUpdateInventory(InventoryFolderBase[] folders, InventoryItemBase[] items);
 
         void SendXferPacket(ulong xferID, uint packet,
                 byte[] XferData, int XferDataOffset, int XferDatapktLen, bool isTaskInventory);
@@ -1249,7 +1190,7 @@ namespace OpenSim.Framework
                              int PricePublicObjectDelete, int PriceRentLight, int PriceUpload, int TeleportMinPrice,
                              float TeleportPriceExponent);
 
-        void SendAvatarPickerReply(AvatarPickerReplyAgentDataArgs AgentData, List<AvatarPickerReplyDataArgs> Data);
+        void SendAvatarPickerReply(UUID QueryID, List<UserData> users);
 
         void SendAgentDataUpdate(UUID agentid, UUID activegroupid, string firstname, string lastname, ulong grouppowers,
                                  string groupname, string grouptitle);
@@ -1285,20 +1226,8 @@ namespace OpenSim.Framework
         void SendDialog(string objectname, UUID objectID, UUID ownerID, string ownerFirstName, string ownerLastName, string msg, UUID textureID, int ch,
                         string[] buttonlabels);
 
-        /// <summary>
-        /// Update the client as to where the sun is currently located.
-        /// </summary>
-        /// <param name="sunPos"></param>
-        /// <param name="sunVel"></param>
-        /// <param name="CurrentTime">Seconds since Unix Epoch 01/01/1970 00:00:00</param>
-        /// <param name="SecondsPerSunCycle"></param>
-        /// <param name="SecondsPerYear"></param>
-        /// <param name="OrbitalPosition">The orbital position is given in radians, and must be "adjusted" for the linden client, see LLClientView</param>
-        void SendSunPos(Vector3 sunPos, Vector3 sunVel, ulong CurrentTime, uint SecondsPerSunCycle, uint SecondsPerYear,
-                        float OrbitalPosition);
-
+        void SendViewerTime(Vector3 sunDir, float sunphase);
         void SendViewerEffect(ViewerEffectPacket.EffectBlock[] effectBlocks);
-        void SendViewerTime(int phase);
 
         void SendAvatarProperties(UUID avatarID, string aboutText, string bornOn, Byte[] membershipType, string flAbout,
                                   uint flags, UUID flImageID, UUID imageID, string profileURL, UUID partnerID);

+ 2 - 0
OpenSim/Framework/ICommandConsole.cs

@@ -83,6 +83,7 @@ namespace OpenSim.Framework
     }
 
     public delegate void OnOutputDelegate(string message);
+    public delegate void OnCntrCCelegate();
 
     public interface ICommandConsole : IConsole
     {
@@ -105,5 +106,6 @@ namespace OpenSim.Framework
         string ReadLine(string p, bool isCommand, bool e);
 
         void ReadConfig(IConfigSource configSource);
+        void SetCntrCHandler(OnCntrCCelegate handler);
     }
 }

+ 4 - 2
OpenSim/Framework/IConsole.cs

@@ -32,11 +32,13 @@ namespace OpenSim.Framework
 {
     public interface IConsole
     {
+
+
         IScene ConsoleScene { get; set; }
 
+        void Output(string format);
         void Output(string format, params object[] components);
-        void Output(string format, string level, params object[] components);
-
+ 
         string Prompt(string p);
         string Prompt(string p, string def);
         string Prompt(string p, List<char> excludedCharacters);

+ 2 - 1
OpenSim/Framework/ILandChannel.cs

@@ -56,7 +56,7 @@ namespace OpenSim.Region.Framework.Interfaces
         /// <param name="y">Value between 0 - 256 on the y axis of the point</param>
         /// <returns>Land object at the point supplied</returns>
         ILandObject GetLandObject(float x, float y);
-
+        ILandObject GetLandObjectClippedXY(float x, float y);
         /// <summary>
         /// Get the parcel at the specified point
         /// </summary>
@@ -99,5 +99,6 @@ namespace OpenSim.Region.Framework.Interfaces
         void Join(int start_x, int start_y, int end_x, int end_y, UUID attempting_user_id);
         void Subdivide(int start_x, int start_y, int end_x, int end_y, UUID attempting_user_id);
         void sendClientInitialLandInfo(IClientAPI remoteClient, bool overlay);
+        void ClearAllEnvironments();
     }
 }

+ 15 - 3
OpenSim/Framework/ILandObject.cs

@@ -44,6 +44,12 @@ namespace OpenSim.Framework
         bool[,] LandBitmap { get; set; }
         UUID RegionUUID { get; }
 
+        UUID GlobalID { get; }
+        UUID FakeID { get; }
+        int LocalID { get; }
+        UUID OwnerID { get; }
+        UUID GroupID { get; }
+
         /// <summary>
         /// Prim counts for this land object.
         /// </summary>
@@ -73,6 +79,7 @@ namespace OpenSim.Framework
         ILandObject Copy();
 
         void SendLandUpdateToAvatarsOverMe();
+        void SendLandUpdateToAvatars();
 
         void SendLandProperties(int sequence_id, bool snap_selection, int request_result, IClientAPI remote_client);
         bool UpdateLandProperties(LandUpdateArgs args, IClientAPI remote_client, out bool snap_selection, out bool needOverlay);
@@ -99,7 +106,8 @@ namespace OpenSim.Framework
         bool[,] BasicFullRegionLandBitmap();
 
         /// <summary>
-        /// Create a square land bitmap.
+        /// Create a land bitmap.
+        /// Square name is wrong kept bc legacy
         /// </summary>
         /// <remarks>
         /// Land co-ordinates are zero indexed.  The inputs are treated as points.  So if you want to create a bitmap
@@ -116,6 +124,7 @@ namespace OpenSim.Framework
         /// <param name="end_y"></param>
         /// <param name="set_value"></param>
         /// <returns>The bitmap created.</returns>
+        
         bool[,] GetSquareLandBitmap(int start_x, int start_y, int end_x, int end_y, bool set_value = true);
 
         bool[,] ModifyLandBitmapSquare(bool[,] land_bitmap, int start_x, int start_y, int end_x, int end_y, bool set_value);
@@ -142,7 +151,7 @@ namespace OpenSim.Framework
         /// <param name="AABBMin">out: parcel.AABBMin &lt;x,y,0&gt</param>
         /// <param name="AABBMax">out: parcel.AABBMax &lt;x,y,0&gt</param>
         /// <returns>New parcel bitmap</returns>
-        bool[,] RemapLandBitmap(bool[,] bitmap_base, Vector2 displacement, float rotationDegrees, Vector2 boundingOrigin, Vector2 boundingSize, Vector2 regionSize, out bool isEmptyNow, out Vector3 AABBMin, out Vector3 AABBMax);
+        bool[,] RemapLandBitmap(bool[,] bitmap_base, Vector2 displacement, float rotationDegrees, Vector2 boundingOrigin, Vector2 boundingSize, Vector2 regionSize, out bool isEmptyNow);
 
         /// <summary>
         /// Clears any parcel data in bitmap_base where there exists parcel data in bitmap_new. In other words the parcel data
@@ -154,7 +163,7 @@ namespace OpenSim.Framework
         /// <param name="AABBMin">out: parcel.AABBMin &lt;x,y,0&gt;</param>
         /// <param name="AABBMax">out: parcel.AABBMax &lt;x,y,0&gt</param>
         /// <returns>New parcel bitmap</returns>
-        bool[,] RemoveFromLandBitmap(bool[,] bitmap_base, bool[,] bitmap_new, out bool isEmptyNow, out Vector3 AABBMin, out Vector3 AABBMax);
+        bool[,] RemoveFromLandBitmap(bool[,] bitmap_base, bool[,] bitmap_new, out bool isEmptyNow);
 
         byte[] ConvertLandBitmapToBytes();
         bool[,] ConvertBytesToLandBitmap(bool overrideRegionSize = false);
@@ -171,6 +180,8 @@ namespace OpenSim.Framework
 
         void SetParcelObjectMaxOverride(overrideParcelMaxPrimCountDelegate overrideDel);
         void SetSimulatorObjectMaxOverride(overrideSimulatorMaxPrimCountDelegate overrideDel);
+        
+        void StoreEnvironment(ViewerEnvironment VEnv);
 
         /// <summary>
         /// Set the media url for this land parcel
@@ -191,5 +202,6 @@ namespace OpenSim.Framework
         string GetMusicUrl();
 
         void Clear();
+        ISceneObject[] GetSceneObjectGroups();
     }
 }

+ 9 - 7
OpenSim/Framework/IPeople.cs

@@ -33,13 +33,15 @@ namespace OpenSim.Framework
 {
     public class UserData
     {
-        public UUID Id { get; set; }
-        public string FirstName { get; set; }
-        public string LastName { get; set; }
-        public string HomeURL { get; set; }
-        public Dictionary<string, object> ServerURLs { get; set; }
-        public bool IsUnknownUser { get; set; }
-        public bool HasGridUserTried { get; set; }
+        public UUID Id;
+        public string FirstName;
+        public string LastName;
+        public string HomeURL;
+        public Dictionary<string, object> ServerURLs;
+        public bool IsUnknownUser;
+        public bool HasGridUserTried;
+        public bool IsLocal;
+        public double LastWebFail = -1;
     }
 
     public interface IPeople

+ 37 - 42
OpenSim/Framework/InventoryItemBase.cs

@@ -28,6 +28,7 @@
 using System;
 using System.Text;
 using OpenMetaverse;
+using OpenMetaverse.StructuredData;
 
 namespace OpenSim.Framework
 {
@@ -162,19 +163,13 @@ namespace OpenSim.Framework
         /// <value>
         /// The description of the inventory item (must be less than 64 characters)
         /// </value>
+        
+        public osUTF8 UTF8Description;
         public string Description
         {
-            get
-            {
-                return m_description;
-            }
-
-            set
-            {
-                m_description = value;
-            }
+            get { return UTF8Description == null ? string.Empty : UTF8Description.ToString();}
+            set { UTF8Description = string.IsNullOrWhiteSpace(value) ? null : new osUTF8(value);}
         }
-        protected string m_description = String.Empty;
 
         /// <value>
         ///
@@ -417,39 +412,39 @@ namespace OpenSim.Framework
             return MemberwiseClone();
         }
 
-        public void ToLLSDxml(StringBuilder lsl, uint flagsMask = 0xffffffff)
+        public void ToLLSDxml(osUTF8 lsl, uint flagsMask = 0xffffffff)
         {
-            LLSDxmlEncode.AddMap(lsl);
-                LLSDxmlEncode.AddElem("parent_id", Folder, lsl);
-                LLSDxmlEncode.AddElem("asset_id", AssetID, lsl);
-                LLSDxmlEncode.AddElem("item_id", ID, lsl);
-
-                LLSDxmlEncode.AddMap("permissions",lsl);
-                    LLSDxmlEncode.AddElem("creator_id", CreatorIdAsUuid, lsl);
-                    LLSDxmlEncode.AddElem("owner_id", Owner, lsl);
-                    LLSDxmlEncode.AddElem("group_id", GroupID, lsl);
-                    LLSDxmlEncode.AddElem("base_mask", (int)CurrentPermissions, lsl);
-                    LLSDxmlEncode.AddElem("owner_mask", (int)CurrentPermissions, lsl);
-                    LLSDxmlEncode.AddElem("group_mask", (int)GroupPermissions, lsl);
-                    LLSDxmlEncode.AddElem("everyone_mask", (int)EveryOnePermissions, lsl);
-                    LLSDxmlEncode.AddElem("next_owner_mask", (int)NextPermissions, lsl);
-                    LLSDxmlEncode.AddElem("is_owner_group", GroupOwned, lsl);
-                LLSDxmlEncode.AddEndMap(lsl);
-
-                LLSDxmlEncode.AddElem("type", AssetType, lsl);
-                LLSDxmlEncode.AddElem("inv_type", InvType, lsl);
-                LLSDxmlEncode.AddElem("flags", (int)(Flags & flagsMask), lsl);
-
-                LLSDxmlEncode.AddMap("sale_info",lsl);
-                    LLSDxmlEncode.AddElem("sale_price", SalePrice, lsl);
-                    LLSDxmlEncode.AddElem("sale_type", SaleType, lsl);
-                LLSDxmlEncode.AddEndMap(lsl);
-
-                LLSDxmlEncode.AddElem("name", Name, lsl);
-                LLSDxmlEncode.AddElem("desc", Description, lsl);
-                LLSDxmlEncode.AddElem("created_at", CreationDate, lsl);
-
-            LLSDxmlEncode.AddEndMap(lsl);
+            LLSDxmlEncode2.AddMap(lsl);
+                LLSDxmlEncode2.AddElem_parent_id(Folder, lsl);
+                LLSDxmlEncode2.AddElem("asset_id", AssetID, lsl);
+                LLSDxmlEncode2.AddElem("item_id", ID, lsl);
+
+                LLSDxmlEncode2.AddMap("permissions",lsl);
+                    LLSDxmlEncode2.AddElem("creator_id", CreatorIdAsUuid, lsl);
+                    LLSDxmlEncode2.AddElem_owner_id( Owner, lsl);
+                    LLSDxmlEncode2.AddElem("group_id", GroupID, lsl);
+                    LLSDxmlEncode2.AddElem("base_mask", (int)CurrentPermissions, lsl);
+                    LLSDxmlEncode2.AddElem("owner_mask", (int)CurrentPermissions, lsl);
+                    LLSDxmlEncode2.AddElem("group_mask", (int)GroupPermissions, lsl);
+                    LLSDxmlEncode2.AddElem("everyone_mask", (int)EveryOnePermissions, lsl);
+                    LLSDxmlEncode2.AddElem("next_owner_mask", (int)NextPermissions, lsl);
+                    LLSDxmlEncode2.AddElem("is_owner_group", GroupOwned, lsl);
+                LLSDxmlEncode2.AddEndMap(lsl);
+
+                LLSDxmlEncode2.AddElem("type", AssetType, lsl);
+                LLSDxmlEncode2.AddElem("inv_type", InvType, lsl);
+                LLSDxmlEncode2.AddElem("flags", (int)(Flags & flagsMask), lsl);
+
+                LLSDxmlEncode2.AddMap("sale_info",lsl);
+                    LLSDxmlEncode2.AddElem("sale_price", SalePrice, lsl);
+                    LLSDxmlEncode2.AddElem("sale_type", SaleType, lsl);
+                LLSDxmlEncode2.AddEndMap(lsl);
+
+                LLSDxmlEncode2.AddElem_name(Name, lsl);
+                LLSDxmlEncode2.AddElem("desc", Description, lsl);
+                LLSDxmlEncode2.AddElem("created_at", CreationDate, lsl);
+
+            LLSDxmlEncode2.AddEndMap(lsl);
         }
     }
 }

+ 4 - 3
OpenSim/Framework/InventoryNodeBase.cs

@@ -37,12 +37,13 @@ namespace OpenSim.Framework
         /// <summary>
         /// The name of the node (64 characters or less)
         /// </summary>
+
         public virtual string Name
         {
-            get { return m_name; }
-            set { m_name = value; }
+            get { return UTF8Name == null ? string.Empty : UTF8Name.ToString(); }
+            set { UTF8Name = string.IsNullOrEmpty(value) ? null : new osUTF8(value); }
         }
-        private string m_name = string.Empty;
+        public osUTF8 UTF8Name;
 
         /// <summary>
         /// A UUID containing the ID for the inventory node itself

+ 166 - 37
OpenSim/Framework/LLSDxmlEncode.cs

@@ -51,9 +51,9 @@ namespace OpenSim.Framework
         public const string LLSDEmpty = "<llsd><map /></llsd>";
 
         // got tired of creating a stringbuilder all the time;
-        public static StringBuilder Start(int size = 256, bool addxmlversion = false)
+        public static StringBuilder Start(int size = 4096, bool addxmlversion = false)
         {
-            StringBuilder sb = new StringBuilder(size);
+            StringBuilder sb = osStringBuilderCache.Acquire(size);
             if(addxmlversion)
                 sb.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><llsd>"); // legacy llsd xml name still valid
             else
@@ -69,7 +69,13 @@ namespace OpenSim.Framework
         public static string End(StringBuilder sb)
         {
             sb.Append("</llsd>");
-            return sb.ToString();
+            return osStringBuilderCache.GetStringAndRelease(sb);
+        }
+
+        public static byte[] EndToNBBytes(StringBuilder sb)
+        {
+            sb.Append("</llsd>");
+            return Util.UTF8NBGetbytes(osStringBuilderCache.GetStringAndRelease(sb));
         }
 
         // map == a list of key value pairs
@@ -120,7 +126,7 @@ namespace OpenSim.Framework
             if(e)
                 sb.Append("<boolean>1</boolean>");
             else
-                sb.Append("<boolean />");
+                sb.Append("<boolean>0</boolean>");
         }
 
         public static void AddElem(byte e, StringBuilder sb)
@@ -142,7 +148,22 @@ namespace OpenSim.Framework
             else
             {
                 sb.Append("<binary>"); // encode64 is default
-                sb.Append(Convert.ToBase64String(e,Base64FormattingOptions.None));     
+                base64Encode(e, sb);
+                sb.Append("</binary>");
+            }
+        }
+
+        public static void AddElem(byte[] e, int start, int length, StringBuilder sb)
+        {
+            if (start + length >= e.Length)
+                length = e.Length - start;
+
+            if (e == null || e.Length == 0 || length <= 0)
+                sb.Append("binary />");
+            else
+            {
+                sb.Append("<binary>"); // encode64 is default
+                base64Encode(e, start, length, sb);
                 sb.Append("</binary>");
             }
         }
@@ -172,7 +193,7 @@ namespace OpenSim.Framework
         public static void AddElem(float e, StringBuilder sb)
         {
             if(e == 0)
-                sb.Append("<real />");
+                sb.Append("<real>0</real>");
             else
             {
                 sb.Append("<real>");
@@ -186,7 +207,7 @@ namespace OpenSim.Framework
             sb.Append("<array>");
 
             if(e.X == 0)
-                sb.Append("<real />");
+                sb.Append("<real>0</real>");
             else
             {
                 sb.Append("<real>");
@@ -195,7 +216,7 @@ namespace OpenSim.Framework
             }
 
             if(e.Y == 0)
-                sb.Append("<real /></array>");
+                sb.Append("<real>0</real></array>");
             else
             {
                 sb.Append("<real>");
@@ -209,7 +230,7 @@ namespace OpenSim.Framework
             sb.Append("<array>");
 
             if(e.X == 0)
-                sb.Append("<real />");
+                sb.Append("<real>0</real>");
             else
             {
                 sb.Append("<real>");
@@ -218,7 +239,7 @@ namespace OpenSim.Framework
             }
 
             if(e.Y == 0)
-                sb.Append("<real />");
+                sb.Append("<real>0</real>");
             else
             {
                 sb.Append("<real>");
@@ -227,7 +248,7 @@ namespace OpenSim.Framework
             }
 
             if(e.Z == 0)
-                sb.Append("<real /></array>");
+                sb.Append("<real>0</real></array>");
             else
             {
                 sb.Append("<real>");
@@ -238,10 +259,10 @@ namespace OpenSim.Framework
 
         public static void AddElem(Quaternion e, StringBuilder sb)
         {
-            sb.Append("<array><key>x</key>");
+            sb.Append("<array>");
 
             if(e.X == 0)
-                sb.Append("<real />");
+                sb.Append("<real>0</real>");
             else
             {
                 sb.Append("<real>");
@@ -250,7 +271,7 @@ namespace OpenSim.Framework
             }
 
             if(e.Y == 0)
-                sb.Append("<real />");
+                sb.Append("<real>0</real>");
             else
             {
                 sb.Append("<real>");
@@ -258,7 +279,7 @@ namespace OpenSim.Framework
                 sb.Append("</real>");
             }
             if(e.Z == 0)
-                sb.Append("<real />");
+                sb.Append("<real>0</real>");
             else
             {
                 sb.Append("<real>");
@@ -267,7 +288,7 @@ namespace OpenSim.Framework
             }
 
             if(e.W == 0)
-                sb.Append("<real /></array>");
+                sb.Append("<real>0</real></array>");
             else
             {
                 sb.Append("<real>");
@@ -279,7 +300,7 @@ namespace OpenSim.Framework
         public static void AddElem(double e, StringBuilder sb)
         {
             if(e == 0)
-                sb.Append("<real />");
+                sb.Append("<real>0</real>");
             else
             {
                 sb.Append("<real>");
@@ -295,7 +316,7 @@ namespace OpenSim.Framework
             else
             {
                 sb.Append("<uuid>");
-                EscapeToXML(e.ToString(), sb);     
+                EscapeToXML(e.ToString(), sb);
                 sb.Append("</uuid>");
             }
         }
@@ -317,7 +338,7 @@ namespace OpenSim.Framework
             if(String.IsNullOrEmpty(e))
                 return;
 
-            sb.Append(e);     
+            sb.Append(e);
         }
 
         public static void AddElem(Uri e, StringBuilder sb)
@@ -420,7 +441,7 @@ namespace OpenSim.Framework
             if(e)
                 sb.Append("<boolean>1</boolean>");
             else
-                sb.Append("<boolean />");
+                sb.Append("<boolean>0</boolean>");
         }
 
         public static void AddElem(string name, byte e, StringBuilder sb)
@@ -445,12 +466,31 @@ namespace OpenSim.Framework
             sb.Append(name);
             sb.Append("</key>");
 
-            if(e == null || e.Length == 0)
+            if (e == null || e.Length == 0)
+                sb.Append("binary />");
+            else
+            {
+                sb.Append("<binary>"); // encode64 is default
+                base64Encode(e, sb);
+                sb.Append("</binary>");
+            }
+        }
+
+        public static void AddElem(string name, byte[] e, int start, int length, StringBuilder sb)
+        {
+            sb.Append("<key>");
+            sb.Append(name);
+            sb.Append("</key>");
+
+            if (start + length >= e.Length)
+                length = e.Length - start;
+
+            if (e == null || e.Length == 0 || length <= 0)
                 sb.Append("binary />");
             else
             {
                 sb.Append("<binary>"); // encode64 is default
-                sb.Append(Convert.ToBase64String(e,Base64FormattingOptions.None));
+                base64Encode(e, start, length, sb);
                 sb.Append("</binary>");
             }
         }
@@ -488,7 +528,7 @@ namespace OpenSim.Framework
             sb.Append("</key>");
 
             if(e == 0)
-                sb.Append("<real />");
+                sb.Append("<real>0</real>");
             else
             {
                 sb.Append("<real>");
@@ -504,7 +544,7 @@ namespace OpenSim.Framework
             sb.Append("</key><array>>");
 
             if(e.X == 0)
-                sb.Append("<real />");
+                sb.Append("<real>0</real>");
             else
             {
                 sb.Append("<real>");
@@ -513,7 +553,7 @@ namespace OpenSim.Framework
             }
 
             if(e.Y == 0)
-                sb.Append("<real /></array>");
+                sb.Append("<real>0</real></array>");
             else
             {
                 sb.Append("<real>");
@@ -529,7 +569,7 @@ namespace OpenSim.Framework
             sb.Append("</key><array>");
 
             if(e.X == 0)
-                sb.Append("<real />");
+                sb.Append("<real>0</real>");
             else
             {
                 sb.Append("<real>");
@@ -538,7 +578,7 @@ namespace OpenSim.Framework
             }
 
             if(e.Y == 0)
-                sb.Append("<real />");
+                sb.Append("<real>0</real>");
             else
             {
                 sb.Append("<real>");
@@ -547,7 +587,7 @@ namespace OpenSim.Framework
             }
 
             if(e.Z == 0)
-                sb.Append("<real /></array>");
+                sb.Append("<real>0</real></array>");
             else
             {
                 sb.Append("<real>");
@@ -563,7 +603,7 @@ namespace OpenSim.Framework
             sb.Append("</key><array>");
 
             if(e.X == 0)
-                sb.Append("<real />");
+                sb.Append("<real>0</real>");
             else
             {
                 sb.Append("<real>");
@@ -572,7 +612,7 @@ namespace OpenSim.Framework
             }
 
             if(e.Y == 0)
-                sb.Append("<real />");
+                sb.Append("<real>0</real>");
             else
             {
                 sb.Append("<real>");
@@ -580,7 +620,7 @@ namespace OpenSim.Framework
                 sb.Append("</real>");
             }
             if(e.Z == 0)
-                sb.Append("<real />");
+                sb.Append("<real>0</real>");
             else
             {
                 sb.Append("<real>");
@@ -589,7 +629,7 @@ namespace OpenSim.Framework
             }
 
             if(e.W == 0)
-                sb.Append("<real /></array>");
+                sb.Append("<real>0</real></array>");
             else
             {
                 sb.Append("<real>");
@@ -605,7 +645,7 @@ namespace OpenSim.Framework
             sb.Append("</key>");
 
             if(e == 0)
-                sb.Append("<real />");
+                sb.Append("<real>0</real>");
             else
             {
                 sb.Append("<real>");
@@ -724,11 +764,8 @@ namespace OpenSim.Framework
 
         public static void EscapeToXML(string s, StringBuilder sb)
         {
-            int i;
             char c;
-            int len = s.Length;
-
-            for (i = 0; i < len; i++)
+            for (int i = 0; i < s.Length; ++i)
             {
                 c = s[i];
                 switch (c)
@@ -780,5 +817,97 @@ namespace OpenSim.Framework
                 (byte)value
             };
         }
+
+        static readonly char[] base64Chars = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O',
+                                              'P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d',
+                                              'e','f','g','h','i','j','k','l','m','n','o','p','q','r','s',
+                                              't','u','v','w','x','y','z','0','1','2','3','4','5','6','7',
+                                              '8','9','+','/'};
+
+        public static unsafe void base64Encode(byte[] data, StringBuilder sb)
+        {
+            int lenMod3 = data.Length % 3;
+            int len = data.Length - lenMod3;
+
+            fixed (byte* d = data)
+            {
+                fixed (char* b64 = base64Chars)
+                {
+                    int i = 0;
+                    while(i < len)
+                    {
+                        sb.Append(b64[d[i] >> 2]);
+                        sb.Append(b64[((d[i] & 0x03) << 4) | ((d[i + 1] & 0xf0) >> 4)]);
+                        sb.Append(b64[((d[i + 1] & 0x0f) << 2) | ((d[i + 2] & 0xc0) >> 6)]);
+                        sb.Append(b64[d[i + 2] & 0x3f]);
+                        i += 3;
+                    }
+
+                    switch (lenMod3)
+                    {
+                        case 2:
+                        {
+                            i = len;
+                            sb.Append(b64[d[i] >> 2]);
+                            sb.Append(b64[((d[i] & 0x03) << 4) | ((d[i + 1] & 0xf0) >> 4)]);
+                            sb.Append(b64[((d[i + 1] & 0x0f) << 2)]);
+                            sb.Append('=');
+                            break;
+                        }
+                        case 1:
+                        {
+                            i = len;
+                            sb.Append(b64[d[i] >> 2]);
+                            sb.Append(b64[(d[i] & 0x03) << 4]);
+                            sb.Append("==");
+                            break;
+                        }
+                    }
+                }
+            }
+        }
+
+        public static unsafe void base64Encode(byte[] data, int start, int length, StringBuilder sb)
+        {
+            int lenMod3 = length % 3;
+            int len = start + (length - lenMod3);
+
+            fixed (byte* d = data)
+            {
+                fixed (char* b64 = base64Chars)
+                {
+                    int i = start;
+                    while(i < len)
+                    {
+                        sb.Append(b64[(d[i] & 0xfc) >> 2]);
+                        sb.Append(b64[((d[i] & 0x03) << 4) | (d[i + 1] >> 4)]);
+                        sb.Append(b64[((d[i + 1] & 0x0f) << 2) | (d[i + 2] >> 6)]);
+                        sb.Append(b64[d[i + 2] & 0x3f]);
+                        i += 3;
+                    }
+
+                    switch (lenMod3)
+                    {
+                        case 2:
+                        {
+                            i = len;
+                            sb.Append(b64[d[i] >> 2]);
+                            sb.Append(b64[((d[i] & 0x03) << 4) | (d[i + 1] >> 4)]);
+                            sb.Append(b64[((d[i + 1] & 0x0f) << 2)]);
+                            sb.Append('=');
+                            break;
+                        }
+                        case 1:
+                        {
+                            i = len;
+                            sb.Append(b64[d[i] >> 2]);
+                            sb.Append(b64[(d[i] & 0x03) << 4]);
+                            sb.Append("==");
+                            break;
+                        }
+                    }
+                }
+            }
+        }
     }
 }

+ 33 - 23
OpenSim/Framework/LandData.cs

@@ -46,11 +46,6 @@ namespace OpenSim.Framework
     /// </summary>
     public class LandData
     {
-        // use only one serializer to give the runtime a chance to
-        // optimize it (it won't do that if you use a new instance
-        // every time)
-        private static XmlSerializer serializer = new XmlSerializer(typeof(LandData));
-
         private Vector3 _AABBMax = new Vector3();
         private Vector3 _AABBMin = new Vector3();
         private int _area = 0;
@@ -105,6 +100,19 @@ namespace OpenSim.Framework
         public bool AnyAVSounds { get; set; }
         public bool GroupAVSounds { get; set; }
 
+        private UUID m_fakeID = UUID.Zero;
+        public UUID FakeID
+        {
+            get
+            {
+                return m_fakeID;
+            }
+            set
+            {
+                m_fakeID = value;
+            }
+        }
+
         /// <summary>
         /// Traffic count of parcel
         /// </summary>
@@ -369,7 +377,7 @@ namespace OpenSim.Framework
         }
 
         /// <summary>
-        /// jp2 data for the image representative of the parcel in the parcel dialog
+        /// parcel shape in bits per ocupied location
         /// </summary>
         public byte[] Bitmap
         {
@@ -732,6 +740,11 @@ namespace OpenSim.Framework
             }
         }
 
+        public int EnvironmentVersion = -1;
+
+        [XmlIgnore] //this needs to be added by hand
+        public ViewerEnvironment Environment { get; set;}
+
         public LandData()
         {
             _globalID = UUID.Random();
@@ -739,6 +752,8 @@ namespace OpenSim.Framework
             AnyAVSounds = true;
             GroupAVSounds = true;
             LastDwellTimeMS = Util.GetTimeStampMS();
+            EnvironmentVersion = -1;
+            Environment = null;
         }
 
         /// <summary>
@@ -758,6 +773,7 @@ namespace OpenSim.Framework
             landData._claimDate = _claimDate;
             landData._claimPrice = _claimPrice;
             landData._globalID = _globalID;
+            landData.m_fakeID = m_fakeID;
             landData._groupID = _groupID;
             landData._isGroupOwned = _isGroupOwned;
             landData._localID = _localID;
@@ -804,24 +820,18 @@ namespace OpenSim.Framework
                 landData._parcelAccessList.Add(newEntry);
             }
 
+            if (Environment == null)
+            {
+                landData.Environment = null;
+                landData.EnvironmentVersion = -1;
+            }
+            else
+            {
+                landData.Environment = Environment.Clone();
+                landData.EnvironmentVersion = EnvironmentVersion;
+            }
+
             return landData;
         }
-
-//        public void ToXml(XmlWriter xmlWriter)
-//        {
-//            serializer.Serialize(xmlWriter, this);
-//        }
-
-        /// <summary>
-        /// Restore a LandData object from the serialized xml representation.
-        /// </summary>
-        /// <param name="xmlReader"></param>
-        /// <returns></returns>
-//        public static LandData FromXml(XmlReader xmlReader)
-//        {
-//            LandData land = (LandData)serializer.Deserialize(xmlReader);
-//
-//            return land;
-//        }
     }
 }

+ 5 - 0
OpenSim/Framework/LandStatReportItem.cs

@@ -36,10 +36,15 @@ namespace OpenSim.Framework
         public float LocationY;
         public float LocationZ;
         public string OwnerName;
+        public UUID OwnerID;
         public float Score;
         public UUID TaskID;
         public uint TaskLocalID;
         public string TaskName;
+        public int Bytes;
+        public int Urls;
+        public uint Time;
+        public string Parcel;
 
         public LandStatReportItem()
         {

+ 0 - 420
OpenSim/Framework/MinHeap.cs

@@ -1,420 +0,0 @@
-/*
- * Copyright (c) Contributors, http://opensimulator.org/
- * See CONTRIBUTORS.TXT for a full list of copyright holders.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of the OpenSimulator Project nor the
- *       names of its contributors may be used to endorse or promote products
- *       derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-using System;
-using System.Threading;
-using System.Collections;
-using System.Collections.Generic;
-using System.Runtime.InteropServices;
-
-namespace OpenSim.Framework
-{
-    public interface IHandle { }
-
-    [Serializable, ComVisible(false)]
-    public class MinHeap<T> : ICollection<T>, ICollection
-    {
-        private class Handle : IHandle
-        {
-            internal int index = -1;
-            internal MinHeap<T> heap = null;
-
-            internal void Clear()
-            {
-                index = -1;
-                heap = null;
-            }
-        }
-
-        private struct HeapItem
-        {
-            internal T value;
-            internal Handle handle;
-
-            internal HeapItem(T _value, Handle _handle)
-            {
-                value = _value;
-                handle = _handle;
-            }
-
-            internal void Clear()
-            {
-                if (handle != null)
-                {
-                    handle.heap = null;
-                    handle = null;
-                }               
-                value = default(T);
-            }
-
-            internal void ClearRef()
-            {
-                value = default(T);
-                handle = null;
-            }
-        }
-
-        public const int DEFAULT_CAPACITY = 4;
-
-        private HeapItem[] items;
-        private int size;
-        private object sync_root;
-        private int version;
-        private int minCapacity;
-
-        private Comparison<T> comparison;
-
-        public MinHeap() : this(DEFAULT_CAPACITY, Comparer<T>.Default) { }
-        public MinHeap(int capacity) : this(capacity, Comparer<T>.Default) { }
-        public MinHeap(IComparer<T> comparer) : this(DEFAULT_CAPACITY, comparer) { }
-        public MinHeap(int capacity, IComparer<T> comparer) :
-            this(capacity, new Comparison<T>(comparer.Compare)) { }
-        public MinHeap(Comparison<T> comparison) : this(DEFAULT_CAPACITY, comparison) { }
-        public MinHeap(int _capacity, Comparison<T> _comparison)
-        {
-            minCapacity = 16;
-            items = new HeapItem[_capacity];
-            comparison = _comparison;
-            size = version = 0;
-        }
-
-        public int Count { get { return size; } }
-
-        public bool IsReadOnly { get { return false; } }
-
-        public bool IsSynchronized { get { return false; } }
-
-        public T this[IHandle key]
-        {
-            get
-            {
-                Handle handle = ValidateThisHandle(key);
-                return items[handle.index].value;
-            }
-
-            set
-            {
-                Handle handle = ValidateThisHandle(key);
-                int indx = handle.index;
-                items[indx].value = value;
-                if (!BubbleUp(indx))
-                    BubbleDown(indx);
-            }
-        }
-
-        public object SyncRoot
-        {
-            get
-            {
-                if (sync_root == null)
-                    Interlocked.CompareExchange<object>(ref sync_root, new object(), null);
-                return sync_root;
-            }
-        }
-
-        private Handle ValidateHandle(IHandle ihandle)
-        {
-            if (ihandle == null)
-                throw new ArgumentNullException("handle");
-            Handle handle = ihandle as Handle;
-            if (handle == null)
-                throw new InvalidOperationException("handle is not valid");
-            return handle;
-        }
-
-        private Handle ValidateThisHandle(IHandle ihandle)
-        {
-            Handle handle = ValidateHandle(ihandle);
-            if (!object.ReferenceEquals(handle.heap, this))
-                throw new InvalidOperationException("handle is not valid for this heap");
-            if (handle.index < 0)
-                throw new InvalidOperationException("handle is not associated to a value");
-            return handle;
-        }
-
-        private void Set(HeapItem item, int index)
-        {
-            items[index] = item;
-            if (item.handle != null)
-                item.handle.index = index;
-        }
-
-        private bool BubbleUp(int index)
-        {
-            HeapItem item = items[index];
-            int current, parent;
-
-            for (current = index, parent = (current - 1) / 2;
-                    (current > 0) && (comparison(items[parent].value, item.value)) > 0;
-                    current = parent, parent = (current - 1) / 2)
-            {
-                Set(items[parent], current);
-            }
-
-            if (current != index)
-            {
-                Set(item, current);
-                ++version;
-                return true;
-            }
-            return false;
-        }
-
-        private void BubbleDown(int index)
-        {
-            HeapItem item = items[index];
-            int current;
-            int child;
-
-            for(current = index , child = (2 * current) + 1;
-                        current < size / 2;
-                        current = child, child = (2 * current) + 1)
-            {
-                if ((child < size - 1) && comparison(items[child].value, items[child + 1].value) > 0)
-                    ++child;
-                if (comparison(items[child].value, item.value) >= 0)
-                    break;
-                Set(items[child], current);
-            }
-
-            if (current != index)
-            {
-                Set(item, current);
-                ++version;
-            }
-        }
-
-        public bool TryGetValue(IHandle key, out T value)
-        {
-            Handle handle = ValidateHandle(key);
-            if (handle.index > -1)
-            {
-                value = items[handle.index].value;
-                return true;
-            }
-            value = default(T);
-            return false;
-        }
-
-        public bool ContainsHandle(IHandle ihandle)
-        {
-            Handle handle = ValidateHandle(ihandle);
-            return object.ReferenceEquals(handle.heap, this) && handle.index > -1;
-        }
-
-        public void Add(T value, ref IHandle handle)
-        {
-            if (handle == null)
-                handle = new Handle();
-            Add(value, handle);
-        }
-
-        public void Add(T value, IHandle ihandle)
-        {
-            if (size == items.Length)
-            {
-                int newcapacity = (int)((items.Length * 200L) / 100L);
-                if (newcapacity < (items.Length + DEFAULT_CAPACITY))
-                    newcapacity = items.Length + DEFAULT_CAPACITY;
-                Array.Resize<HeapItem>(ref items, newcapacity);
-            }
-
-            Handle handle = null;
-            if (ihandle != null)
-            {
-                handle = ValidateHandle(ihandle);
-                handle.heap = this;
-            }
-
-            HeapItem item = new MinHeap<T>.HeapItem(value, handle);
-
-            Set(item, size);
-            BubbleUp(size++);
-        }
-
-        public void Add(T value)
-        {
-            Add(value, null);
-        }
-
-        public T Min()
-        {
-            if (size == 0)
-                throw new InvalidOperationException("Heap is empty");
-
-            return items[0].value;
-        }
-
-        public void Clear()
-        {
-            for (int index = 0; index < size; ++index)
-                items[index].Clear();
-            size = 0;
-            if(items.Length > minCapacity)
-                items = new HeapItem[minCapacity];
-            ++version;
-        }
-
-        public void TrimExcess()
-        {
-            int length = (int)(items.Length * 0.9);
-            if (size < length)
-                Array.Resize<HeapItem>(ref items, Math.Min(size, minCapacity));
-        }
-
-        private void RemoveAt(int index)
-        {
-            if (size == 0)
-                throw new InvalidOperationException("Heap is empty");
-            if (index >= size)
-                throw new ArgumentOutOfRangeException("index");
-
-            items[index].Clear();
-            --size;
-            if (size > 0)
-            {   if(index != size)
-                {
-                    Set(items[size], index);
-                    items[size].ClearRef();
-                    if (!BubbleUp(index))
-                        BubbleDown(index);
-                }
-            }
-            else if(items.Length > 4 * minCapacity)
-                items = new HeapItem[minCapacity];
-        }
-
-        public T RemoveMin()
-        {
-            if (size == 0)
-                throw new InvalidOperationException("Heap is empty");
-
-            HeapItem item = items[0];
-            RemoveAt(0);
-            return item.value;
-        }
-
-        public T Remove(IHandle ihandle)
-        {
-            Handle handle = ValidateThisHandle(ihandle);
-            HeapItem item = items[handle.index];
-            RemoveAt(handle.index);
-            return item.value;
-        }
-
-        private int GetIndex(T value)
-        {
-            EqualityComparer<T> comparer = EqualityComparer<T>.Default;
-            int index;
-
-            for (index = 0; index < size; ++index)
-            {
-                if (comparer.Equals(items[index].value, value))
-                    return index;
-            }
-            return -1;
-        }
-
-        public bool Contains(T value)
-        {
-            return GetIndex(value) != -1;
-        }
-
-        public bool Remove(T value)
-        {
-            int index = GetIndex(value);
-            if (index != -1)
-            {
-                RemoveAt(index);
-                return true;
-            }
-            return false;
-        }
-
-        public void CopyTo(T[] array, int index)
-        {
-            if (array == null)
-                throw new ArgumentNullException("array");
-            if (array.Rank != 1)
-                throw new ArgumentException("Multidimensional array not supported");
-            if (array.GetLowerBound(0) != 0)
-                throw new ArgumentException("Non-zero lower bound array not supported");
-
-            int length = array.Length;
-            if ((index < 0) || (index > length))
-                throw new ArgumentOutOfRangeException("index");
-            if ((length - index) < this.size)
-                throw new ArgumentException("Not enough space available in array starting at index");
-
-            for (int i = 0; i < size; ++i)
-                array[index + i] = items[i].value;
-        }
-
-        public void CopyTo(Array array, int index)
-        {
-            if (array == null)
-                throw new ArgumentNullException("array");
-            if (array.Rank != 1)
-                throw new ArgumentException("Multidimensional array not supported");
-            if (array.GetLowerBound(0) != 0)
-                throw new ArgumentException("Non-zero lower bound array not supported");
-
-            int length = array.Length;
-            if ((index < 0) || (index > length))
-                throw new ArgumentOutOfRangeException("index");
-            if ((length - index) < size)
-                throw new ArgumentException("Not enough space available in array starting at index");
-
-            try
-            {
-                for (int i = 0; i < size; ++i)
-                    array.SetValue(items[i].value, index + i);
-            }
-            catch (ArrayTypeMismatchException)
-            {
-                throw new ArgumentException("Invalid array type");
-            }
-        }
-
-        public IEnumerator<T> GetEnumerator()
-        {
-            int cversion = version;
-
-            for (int index = 0; index < size; ++index)
-            {
-                if (cversion != version)
-                    throw new InvalidOperationException("Heap was modified while enumerating");
-                yield return items[index].value;
-            }
-        }
-
-        IEnumerator IEnumerable.GetEnumerator()
-        {
-            return GetEnumerator();
-        }
-    }
-}

+ 13 - 13
OpenSim/Framework/Monitoring/BaseStatsCollector.cs

@@ -52,21 +52,21 @@ namespace OpenSim.Framework.Monitoring
                 Math.Round((MemoryWatchdog.LastHeapAllocationRate * 1000) / 1048576.0, 3),
                 Math.Round((MemoryWatchdog.AverageHeapAllocationRate * 1000) / 1048576.0, 3));
 
-            Process myprocess = Process.GetCurrentProcess();
-//            if (!myprocess.HasExited)
             try
             {
-                myprocess.Refresh();
-                sb.AppendFormat(
-                        "Process memory:      Physical {0} MB \t Paged {1} MB \t Virtual {2} MB\n",
-                        Math.Round(myprocess.WorkingSet64 / 1024.0 / 1024.0),
-                        Math.Round(myprocess.PagedMemorySize64 / 1024.0 / 1024.0),
-                        Math.Round(myprocess.VirtualMemorySize64 / 1024.0 / 1024.0));
-                sb.AppendFormat(
-                        "Peak process memory: Physical {0} MB \t Paged {1} MB \t Virtual {2} MB\n",
-                        Math.Round(myprocess.PeakWorkingSet64 / 1024.0 / 1024.0),
-                        Math.Round(myprocess.PeakPagedMemorySize64 / 1024.0 / 1024.0),
-                        Math.Round(myprocess.PeakVirtualMemorySize64 / 1024.0 / 1024.0));
+                using (Process myprocess = Process.GetCurrentProcess())
+                {
+                    sb.AppendFormat(
+                            "Process memory:      Physical {0} MB \t Paged {1} MB \t Virtual {2} MB\n",
+                            Math.Round(myprocess.WorkingSet64 / 1024.0 / 1024.0),
+                            Math.Round(myprocess.PagedMemorySize64 / 1024.0 / 1024.0),
+                            Math.Round(myprocess.VirtualMemorySize64 / 1024.0 / 1024.0));
+                    sb.AppendFormat(
+                            "Peak process memory: Physical {0} MB \t Paged {1} MB \t Virtual {2} MB\n",
+                            Math.Round(myprocess.PeakWorkingSet64 / 1024.0 / 1024.0),
+                            Math.Round(myprocess.PeakPagedMemorySize64 / 1024.0 / 1024.0),
+                            Math.Round(myprocess.PeakVirtualMemorySize64 / 1024.0 / 1024.0));
+                }
             }
             catch
             { }

+ 1 - 1
OpenSim/Framework/Monitoring/ChecksManager.cs

@@ -88,7 +88,7 @@ namespace OpenSim.Framework.Monitoring
                         con.Output("check categories available are:");
 
                         foreach (string category in RegisteredChecks.Keys)
-                            con.Output("  {0}", null, category);
+                            con.Output("  {0}", category);
                     }
 //                    else
 //                    {

+ 14 - 5
OpenSim/Framework/Monitoring/JobEngine.cs

@@ -131,7 +131,15 @@ namespace OpenSim.Framework.Monitoring
                 finally
                 {
                     if(m_cancelSource != null)
+                    {
                         m_cancelSource.Dispose();
+                        m_cancelSource = null;
+                    }
+                    if (m_jobQueue != null)
+                    {
+                        m_jobQueue.Dispose();
+                        m_jobQueue = null;
+                    }
                 }
             }
         }
@@ -238,13 +246,13 @@ namespace OpenSim.Framework.Monitoring
                         break;
                     }
                 }
-                catch(ObjectDisposedException)
+                catch (OperationCanceledException)
                 {
-                    m_log.DebugFormat("[JobEngine] {0} stopping ignoring {1} jobs in queue",
-                        Name,m_jobQueue.Count);
+                    m_log.DebugFormat("[JobEngine] {0} Canceled ignoring {1} jobs in queue",
+                        Name, m_jobQueue.Count);
                     break;
                 }
-                catch(OperationCanceledException)
+                catch
                 {
                     break;
                 }
@@ -266,6 +274,7 @@ namespace OpenSim.Framework.Monitoring
                 if(LogLevel >= 1)
                     m_log.DebugFormat("[{0}]: Processed job {1}",LoggingName,m_currentJob.Name);
 
+                m_currentJob.Action = null;
                 m_currentJob = null;
             }
         }
@@ -292,7 +301,7 @@ namespace OpenSim.Framework.Monitoring
             /// <summary>
             /// Action to perform when this job is processed.
             /// </summary>
-            public Action Action { get; private set; }
+            public Action Action { get; set; }
 
             private Job(string name, string commonId, Action action)
             {

+ 10 - 12
OpenSim/Framework/Monitoring/SimExtraStatsCollector.cs

@@ -435,21 +435,19 @@ Asset service request failures: {3}" + Environment.NewLine,
             // Get the amount of physical memory, allocated with the instance of this program, in kilobytes;
             // the working set is the set of memory pages currently visible to this program in physical RAM
             // memory and includes both shared (e.g. system libraries) and private data
-            double memUsage = Process.GetCurrentProcess().WorkingSet64 / 1024.0;
-
-            // Get the number of threads from the system that are currently
-            // running
             int numberThreadsRunning = 0;
-            foreach (ProcessThread currentThread in
-                Process.GetCurrentProcess().Threads)
+            double memUsage = 0;
+            using(Process p = Process.GetCurrentProcess())
             {
-                // A known issue with the current process .Threads property is
-                // that it can return null threads, thus don't count those as
-                // running threads and prevent the program function from failing
-                if (currentThread != null &&
-                    currentThread.ThreadState == ThreadState.Running)
+                memUsage = p.WorkingSet64 / 1024.0;
+
+                // Get the number of threads from the system that are currently
+                // running
+                
+                foreach (ProcessThread currentThread in p.Threads)
                 {
-                    numberThreadsRunning++;
+                    if (currentThread != null && currentThread.ThreadState == ThreadState.Running)
+                        numberThreadsRunning++;
                 }
             }
 

+ 2 - 2
OpenSim/Framework/Monitoring/StatsLogger.cs

@@ -79,7 +79,7 @@ namespace OpenSim.Framework.Monitoring
             if (cmd[2] == "start")
             {
                 Start();
-                con.Output("Now recording all stats to file every {0}ms", null, m_statsLogIntervalMs);
+                con.Output("Now recording all stats to file every {0}ms", m_statsLogIntervalMs);
             }
             else if (cmd[2] == "stop")
             {
@@ -106,7 +106,7 @@ namespace OpenSim.Framework.Monitoring
                     sw.WriteLine(line);
             }
 
-            MainConsole.Instance.Output("Stats saved to file {0}", null, path);
+            MainConsole.Instance.Output("Stats saved to file {0}", path);
         }
 
         public static void Start()

+ 4 - 4
OpenSim/Framework/Monitoring/StatsManager.cs

@@ -117,14 +117,14 @@ namespace OpenSim.Framework.Monitoring
                     {
                         con.Output("Statistic categories available are:");
                         foreach (string category in RegisteredStats.Keys)
-                            con.Output("  {0}", null, category);
+                            con.Output("  {0}", category);
                     }
                     else
                     {
                         SortedDictionary<string, SortedDictionary<string, Stat>> category;
                         if (!RegisteredStats.TryGetValue(categoryName, out category))
                         {
-                            con.Output("No such category as {0}", null, categoryName);
+                            con.Output("No such category as {0}", categoryName);
                         }
                         else
                         {
@@ -151,13 +151,13 @@ namespace OpenSim.Framework.Monitoring
                                         else
                                         {
                                             con.Output(
-                                                "No such stat {0} in {1}.{2}", null, statName, categoryName, containerName);
+                                                "No such stat {0} in {1}.{2}", statName, categoryName, containerName);
                                         }
                                     }
                                 }
                                 else
                                 {
-                                    con.Output("No such container {0} in category {1}", null, containerName, categoryName);
+                                    con.Output("No such container {0} in category {1}", containerName, categoryName);
                                 }
                             }
                         }

+ 6 - 9
OpenSim/Framework/Monitoring/Watchdog.cs

@@ -41,7 +41,7 @@ namespace OpenSim.Framework.Monitoring
         private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
 
         /// <summary>Timer interval in milliseconds for the watchdog timer</summary>
-        public const double WATCHDOG_INTERVAL_MS = 2500.0d;
+        public const int WATCHDOG_INTERVAL_MS = 2500;
 
         /// <summary>Default timeout in milliseconds before a thread is considered dead</summary>
         public const int DEFAULT_WATCHDOG_TIMEOUT_MS = 5000;
@@ -154,15 +154,14 @@ namespace OpenSim.Framework.Monitoring
                 {
                     // Set now so we don't get alerted on the first run
                     LastWatchdogThreadTick = Environment.TickCount & Int32.MaxValue;
+                    m_watchdogTimer.Change(WATCHDOG_INTERVAL_MS, Timeout.Infinite);
                 }
-
-                m_watchdogTimer.Enabled = m_enabled;
             }
         }
 
         private static bool m_enabled;
         private static Dictionary<int, ThreadWatchdogInfo> m_threads;
-        private static System.Timers.Timer m_watchdogTimer;
+        private static Timer m_watchdogTimer;
 
         /// <summary>
         /// Last time the watchdog thread ran.
@@ -175,9 +174,7 @@ namespace OpenSim.Framework.Monitoring
         static Watchdog()
         {
             m_threads = new Dictionary<int, ThreadWatchdogInfo>();
-            m_watchdogTimer = new System.Timers.Timer(WATCHDOG_INTERVAL_MS);
-            m_watchdogTimer.AutoReset = false;
-            m_watchdogTimer.Elapsed += WatchdogTimerElapsed;
+            m_watchdogTimer = new Timer(WatchdogTimerElapsed, null, WATCHDOG_INTERVAL_MS, Timeout.Infinite);
         }
 
         public static void Stop()
@@ -340,7 +337,7 @@ namespace OpenSim.Framework.Monitoring
         /// </summary>
         /// <param name="sender"></param>
         /// <param name="e"></param>
-        private static void WatchdogTimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
+        private static void WatchdogTimerElapsed(object sender)
         {
             if(!m_enabled)
                 return;
@@ -414,7 +411,7 @@ namespace OpenSim.Framework.Monitoring
             ChecksManager.CheckChecks();
             StatsManager.RecordStats();
 
-            m_watchdogTimer.Start();
+            m_watchdogTimer.Change(WATCHDOG_INTERVAL_MS, Timeout.Infinite);
         }
     }
 }

+ 6 - 6
OpenSim/Framework/Monitoring/WorkManager.cs

@@ -224,14 +224,14 @@ namespace OpenSim.Framework.Monitoring
             }
             else if (subCommand == "status")
             {
-                MainConsole.Instance.Output("Job engine running: {0}", null, JobEngine.IsRunning);
+                MainConsole.Instance.Output("Job engine running: {0}", JobEngine.IsRunning);
 
                 JobEngine.Job job = JobEngine.CurrentJob;
-                MainConsole.Instance.Output("Current job {0}", null, job != null ? job.Name : "none");
+                MainConsole.Instance.Output("Current job {0}", job != null ? job.Name : "none");
 
                 MainConsole.Instance.Output(
-                    "Jobs waiting: {0}", null, JobEngine.IsRunning ? JobEngine.JobsWaiting.ToString() : "n/a");
-                MainConsole.Instance.Output("Log Level: {0}", null, JobEngine.LogLevel);
+                    "Jobs waiting: {0}", JobEngine.IsRunning ? JobEngine.JobsWaiting.ToString() : "n/a");
+                MainConsole.Instance.Output("Log Level: {0}", JobEngine.LogLevel);
             }
             else if (subCommand == "log")
             {
@@ -246,12 +246,12 @@ namespace OpenSim.Framework.Monitoring
                 //                if (ConsoleUtil.TryParseConsoleInt(MainConsole.Instance, args[4], out logLevel))
                 //                {
                 JobEngine.LogLevel = logLevel;
-                MainConsole.Instance.Output("Set debug log level to {0}", null, JobEngine.LogLevel);
+                MainConsole.Instance.Output("Set debug log level to {0}", JobEngine.LogLevel);
                 //                }
             }
             else
             {
-                MainConsole.Instance.Output("Unrecognized job engine subcommand {0}", null, subCommand);
+                MainConsole.Instance.Output("Unrecognized job engine subcommand {0}", subCommand);
             }
         }
     }

+ 3 - 3
OpenSim/Framework/PluginManager.cs

@@ -129,7 +129,7 @@ namespace OpenSim.Framework
             }
 
             Addin addin = addins[ndx];
-            MainConsole.Instance.Output("Uninstalling plugin {0}", null, addin.Id);
+            MainConsole.Instance.Output("Uninstalling plugin {0}", addin.Id);
             AddinManager.Registry.DisableAddin(addin.Id);
             addin.Enabled = false;
             IProgressStatus ps = new ConsoleProgressStatus(false);
@@ -487,7 +487,7 @@ namespace OpenSim.Framework
             }
             else
             {
-                MainConsole.Instance.Output("Not Enabled in this domain {0}", null, addin.Name);
+                MainConsole.Instance.Output("Not Enabled in this domain {0}", addin.Name);
             }
             return;
         }
@@ -503,7 +503,7 @@ namespace OpenSim.Framework
 
             foreach (Addin addin in addins)
             {
-                MainConsole.Instance.Output("Addin {0}", null, addin.Name);
+                MainConsole.Instance.Output("Addin {0}", addin.Name);
             }
         }
 

+ 1 - 1
OpenSim/Framework/PrimitiveBaseShape.cs

@@ -1242,7 +1242,7 @@ namespace OpenSim.Framework
 
             byte extraParamCount = data[0];
             int i = 1;
-            for (int k = 0; k < extraParamCount; k++)
+            for (int k = 0; k < extraParamCount; ++k)
             {
                 byte epType = data[i];
                 i += 6;

+ 0 - 393
OpenSim/Framework/PriorityQueue.cs

@@ -1,393 +0,0 @@
-/*
- * Copyright (c) Contributors, http://opensimulator.org/
- * See CONTRIBUTORS.TXT for a full list of copyright holders.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of the OpenSimulator Project nor the
- *       names of its contributors may be used to endorse or promote products
- *       derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Reflection;
-
-using OpenSim.Framework;
-using OpenSim.Framework.Client;
-using log4net;
-
-namespace OpenSim.Framework
-{
-    public class PriorityQueue
-    {
-//        private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
-
-        public delegate bool UpdatePriorityHandler(ref uint priority, ISceneEntity entity);
-
-        /// <summary>
-        /// Total number of queues (priorities) available
-        /// </summary>
-
-        public const uint NumberOfQueues = 13; // includes immediate queues, m_queueCounts need to be set acording
-
-        /// <summary>
-        /// Number of queuest (priorities) that are processed immediately
-        /// </summary.
-        public const uint NumberOfImmediateQueues = 2;
-        // first queues are immediate, so no counts
-        private static readonly uint[] m_queueCounts = {0, 0, 8, 8, 5, 4, 3, 2, 1, 1, 1, 1, 1 };
-        // this is                     ava, ava, attach, <10m, 20,40,80,160m,320,640,1280, +
-
-        private MinHeap<MinHeapItem>[] m_heaps = new MinHeap<MinHeapItem>[NumberOfQueues];
-        private Dictionary<uint, LookupItem> m_lookupTable;
-
-        // internal state used to ensure the deqeues are spread across the priority
-        // queues "fairly". queuecounts is the amount to pull from each queue in
-        // each pass. weighted towards the higher priority queues
-        private uint m_nextQueue = 0;
-        private uint m_countFromQueue = 0;
-        private int m_capacity;
-        private int m_added;
-
-        // next request is a counter of the number of updates queued, it provides
-        // a total ordering on the updates coming through the queue and is more
-        // lightweight (and more discriminating) than tick count
-        private UInt64 m_nextRequest = 0;
-
-        /// <summary>
-        /// Lock for enqueue and dequeue operations on the priority queue
-        /// </summary>
-        private object m_syncRoot = new object();
-        public object SyncRoot {
-            get { return this.m_syncRoot; }
-        }
-
-#region constructor
-        public PriorityQueue() : this(MinHeap<MinHeapItem>.DEFAULT_CAPACITY) { }
-
-        public PriorityQueue(int capacity)
-        {
-            m_capacity = 16;
-            capacity /= 4;
-
-            for (int i = 0; i < m_heaps.Length; ++i)
-                m_heaps[i] = new MinHeap<MinHeapItem>(capacity);
-
-            m_lookupTable = new Dictionary<uint, LookupItem>(m_capacity);
-            m_nextQueue = NumberOfImmediateQueues;
-            m_countFromQueue = m_queueCounts[m_nextQueue];
-            m_added = 0;
-        }
-#endregion Constructor
-
-#region PublicMethods
-        public void Close()
-        {
-            for (int i = 0; i < m_heaps.Length; ++i)
-                m_heaps[i] = null;
-            m_heaps = null;
-            m_lookupTable.Clear();
-            m_lookupTable = null;
-        }
-
-        /// <summary>
-        /// Return the number of items in the queues
-        /// </summary>
-        public int Count
-        {
-            get
-            {
-                int count = 0;
-                for (int i = 0; i < m_heaps.Length; ++i)
-                    count += m_heaps[i].Count;
-
-                return count;
-            }
-        }
-
-        /// <summary>
-        /// Enqueue an item into the specified priority queue
-        /// </summary>
-        public bool Enqueue(uint pqueue, EntityUpdate value)
-        {
-            LookupItem lookup;
-            IHandle lookupH; 
-            UInt64 entry;
-
-            uint localid = value.Entity.LocalId;
-            if (m_lookupTable.TryGetValue(localid, out lookup))
-            {
-                lookupH = lookup.Handle;
-                entry = lookup.Heap[lookupH].EntryOrder;
-                EntityUpdate up = lookup.Heap[lookupH].Value;
-                value.Update(lookup.Heap[lookupH].Value);
-                lookup.Heap.Remove(lookupH);
-
-                if((up.Flags & PrimUpdateFlags.CancelKill) != 0)
-                    entry = m_nextRequest++;
-
-                pqueue = Util.Clamp<uint>(pqueue, 0, NumberOfQueues - 1);
-                lookup.Heap = m_heaps[pqueue];
-                lookup.Heap.Add(new MinHeapItem(pqueue, entry, value), ref lookup.Handle);
-                m_lookupTable[localid] = lookup;
-                return true;
-            }
-
-            value.Update();
-
-            entry = m_nextRequest++;
-            ++m_added;
-
-            pqueue = Util.Clamp<uint>(pqueue, 0, NumberOfQueues - 1);
-            lookup.Heap = m_heaps[pqueue];
-            lookup.Heap.Add(new MinHeapItem(pqueue, entry, value), ref lookup.Handle);
-            m_lookupTable[localid] = lookup;
-
-            return true;
-        }
-
-        public void Remove(List<uint> ids)
-        {
-            LookupItem lookup;
-
-            foreach (uint localid in ids)
-            {
-                if (m_lookupTable.TryGetValue(localid, out lookup))
-                {
-                    lookup.Heap.Remove(lookup.Handle);
-                    m_lookupTable.Remove(localid);
-                }
-            }
-            if(m_lookupTable.Count == 0 && m_added > 8 * m_capacity)
-            {
-                m_lookupTable = new Dictionary<uint, LookupItem>(m_capacity);
-                m_added = 0;
-            }
-        }
-
-        /// <summary>
-        /// Remove an item from one of the queues. Specifically, it removes the
-        /// oldest item from the next queue in order to provide fair access to
-        /// all of the queues
-        /// </summary>
-        public bool TryDequeue(out EntityUpdate value)
-        {
-            // If there is anything in immediate queues, return it first no
-            // matter what else. Breaks fairness. But very useful.
-            
-            for (int iq = 0; iq < NumberOfImmediateQueues; iq++)
-            {
-                if (m_heaps[iq].Count > 0)
-                {
-                    MinHeapItem item = m_heaps[iq].RemoveMin();
-                    m_lookupTable.Remove(item.Value.Entity.LocalId);
-                    value = item.Value;
-
-                    return true;
-                }
-            }
-
-            // To get the fair queing, we cycle through each of the
-            // queues when finding an element to dequeue.
-            // We pull (NumberOfQueues - QueueIndex) items from each queue in order
-            // to give lower numbered queues a higher priority and higher percentage
-            // of the bandwidth.
-
-            MinHeap<MinHeapItem> curheap = m_heaps[m_nextQueue];
-            // Check for more items to be pulled from the current queue
-            if (m_countFromQueue > 0 && curheap.Count > 0)
-            {
-                --m_countFromQueue;
-
-                MinHeapItem item = curheap.RemoveMin();
-                m_lookupTable.Remove(item.Value.Entity.LocalId);
-                value = item.Value;
-                return true;
-            }
-
-            // Find the next non-immediate queue with updates in it
-            for (uint i = NumberOfImmediateQueues; i < NumberOfQueues; ++i)
-            {
-                m_nextQueue++;
-                if(m_nextQueue >= NumberOfQueues)
-                    m_nextQueue = NumberOfImmediateQueues;
- 
-                curheap = m_heaps[m_nextQueue];
-                if (curheap.Count == 0)
-                    continue;
-
-                m_countFromQueue = m_queueCounts[m_nextQueue];
-                --m_countFromQueue;
-
-                MinHeapItem item = curheap.RemoveMin();
-                m_lookupTable.Remove(item.Value.Entity.LocalId);
-                value = item.Value;
-                return true;
-            }
-
-            value = default(EntityUpdate);
-            if(m_lookupTable.Count == 0 && m_added > 8 * m_capacity)
-            {
-                m_lookupTable = new Dictionary<uint, LookupItem>(m_capacity);
-                m_added = 0;
-            }
-            return false;
-        }
-
-        public bool TryOrderedDequeue(out EntityUpdate value)
-        {
-            for (int iq = 0; iq < NumberOfQueues; ++iq)
-            {
-                MinHeap<MinHeapItem> curheap = m_heaps[iq];
-                if (curheap.Count > 0)
-                {
-                    MinHeapItem item = curheap.RemoveMin();
-                    m_lookupTable.Remove(item.Value.Entity.LocalId);
-                    value = item.Value;
-                    return true;
-                }
-            }
-
-            value = default(EntityUpdate);
-            if(m_lookupTable.Count == 0 && m_added > 8 * m_capacity)
-            {
-                m_lookupTable = new Dictionary<uint, LookupItem>(m_capacity);
-                m_added = 0;
-            }
-            return false;
-        }
-
-        /// <summary>
-        /// Reapply the prioritization function to each of the updates currently
-        /// stored in the priority queues.
-        /// </summary
-        public void Reprioritize(UpdatePriorityHandler handler)
-        {
-            MinHeapItem item;
-            uint pqueue = 0;
-            foreach (LookupItem lookup in new List<LookupItem>(m_lookupTable.Values))
-            {
-                if (lookup.Heap.TryGetValue(lookup.Handle, out item))
-                {
-                    if (handler(ref pqueue, item.Value.Entity))
-                    {
-                        // unless the priority queue has changed, there is no need to modify
-                        // the entry
-                        pqueue = Util.Clamp<uint>(pqueue, 0, NumberOfQueues - 1);
-                        if (pqueue != item.PriorityQueue)
-                        {
-                            lookup.Heap.Remove(lookup.Handle);
-
-                            LookupItem litem = lookup;
-                            litem.Heap = m_heaps[pqueue];
-                            litem.Heap.Add(new MinHeapItem(pqueue, item), ref litem.Handle);
-                            m_lookupTable[item.Value.Entity.LocalId] = litem;
-                        }
-                    }
-                    else
-                    {
-                        // m_log.WarnFormat("[PQUEUE]: UpdatePriorityHandler returned false for {0}",item.Value.Entity.UUID);
-                        lookup.Heap.Remove(lookup.Handle);
-                        m_lookupTable.Remove(item.Value.Entity.LocalId);
-                    }
-                }
-            }
-        }
-
-        /// <summary>
-        /// </summary>
-        public override string ToString()
-        {
-            string s = "";
-            for (int i = 0; i < NumberOfQueues; i++)
-                s += String.Format("{0,7} ", m_heaps[i].Count);
-            return s;
-        }
-
-#endregion PublicMethods
-
-#region MinHeapItem
-        private struct MinHeapItem : IComparable<MinHeapItem>
-        {
-            private EntityUpdate value;
-            internal EntityUpdate Value
-            {
-                get
-                {
-                    return value;
-                }
-            }
-
-            private uint pqueue;
-            internal uint PriorityQueue
-            {
-                get
-                {
-                    return pqueue;
-                }
-            }
-
-            private UInt64 entryorder;
-            internal UInt64 EntryOrder
-            {
-                get
-                {
-                    return entryorder;
-                }
-            }
-
-            internal MinHeapItem(uint _pqueue, MinHeapItem other)
-            {
-                entryorder = other.entryorder;
-                value = other.value;
-                pqueue = _pqueue;
-            }
-
-            internal MinHeapItem(uint _pqueue, UInt64 _entryorder, EntityUpdate _value)
-            {
-                entryorder = _entryorder;
-                value = _value;
-                pqueue = _pqueue;
-            }
-
-            public override string ToString()
-            {
-                return String.Format("[{0},{1},{2}]",pqueue,entryorder,value.Entity.LocalId);
-            }
-
-            public int CompareTo(MinHeapItem other)
-            {
-                // I'm assuming that the root part of an SOG is added to the update queue
-                // before the component parts
-                return Comparer<UInt64>.Default.Compare(this.EntryOrder, other.EntryOrder);
-            }
-        }
-#endregion
-
-#region LookupItem
-        private struct LookupItem
-        {
-            internal MinHeap<MinHeapItem> Heap;
-            internal IHandle Handle;
-        }
-#endregion
-    }
-}

+ 0 - 80
OpenSim/Framework/RegionInfo.cs

@@ -40,69 +40,12 @@ using OpenMetaverse.StructuredData;
 
 namespace OpenSim.Framework
 {
-    [Serializable]
-    public class RegionLightShareData : ICloneable
-    {
-        public bool valid = false;
-        public UUID regionID = UUID.Zero;
-        public Vector3 waterColor = new Vector3(4.0f,38.0f,64.0f);
-        public float waterFogDensityExponent = 4.0f;
-        public float underwaterFogModifier = 0.25f;
-        public Vector3 reflectionWaveletScale = new Vector3(2.0f,2.0f,2.0f);
-        public float fresnelScale = 0.40f;
-        public float fresnelOffset = 0.50f;
-        public float refractScaleAbove = 0.03f;
-        public float refractScaleBelow = 0.20f;
-        public float blurMultiplier = 0.040f;
-        public Vector2 bigWaveDirection = new Vector2(1.05f,-0.42f);
-        public Vector2 littleWaveDirection = new Vector2(1.11f,-1.16f);
-        public UUID normalMapTexture = new UUID("822ded49-9a6c-f61c-cb89-6df54f42cdf4");
-        public Vector4 horizon = new Vector4(0.25f, 0.25f, 0.32f, 0.32f);
-        public float hazeHorizon = 0.19f;
-        public Vector4 blueDensity = new Vector4(0.12f, 0.22f, 0.38f, 0.38f);
-        public float hazeDensity = 0.70f;
-        public float densityMultiplier = 0.18f;
-        public float distanceMultiplier = 0.8f;
-        public UInt16 maxAltitude = 1605;
-        public Vector4 sunMoonColor = new Vector4(0.24f, 0.26f, 0.30f, 0.30f);
-        public float sunMoonPosition = 0.317f;
-        public Vector4 ambient = new Vector4(0.35f,0.35f,0.35f,0.35f);
-        public float eastAngle = 0.0f;
-        public float sunGlowFocus = 0.10f;
-        public float sunGlowSize = 1.75f;
-        public float sceneGamma = 1.0f;
-        public float starBrightness = 0.0f;
-        public Vector4 cloudColor = new Vector4(0.41f, 0.41f, 0.41f, 0.41f);
-        public Vector3 cloudXYDensity = new Vector3(1.00f, 0.53f, 1.00f);
-        public float cloudCoverage = 0.27f;
-        public float cloudScale = 0.42f;
-        public Vector3 cloudDetailXYDensity = new Vector3(1.00f, 0.53f, 0.12f);
-        public float cloudScrollX = 0.20f;
-        public bool cloudScrollXLock = false;
-        public float cloudScrollY = 0.01f;
-        public bool cloudScrollYLock = false;
-        public bool drawClassicClouds = true;
-
-        public delegate void SaveDelegate(RegionLightShareData wl);
-        public event SaveDelegate OnSave;
-        public void Save()
-        {
-            if (OnSave != null)
-                OnSave(this);
-        }
-        public object Clone()
-        {
-            return this.MemberwiseClone();      // call clone method
-        }
-
-    }
 
     public class RegionInfo
     {
         private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
         private static readonly string LogHeader = "[REGION INFO]";
 
-
         public bool commFailTF = false;
         public ConfigurationMember configMember;
         public string DataStore = String.Empty;
@@ -134,7 +77,6 @@ namespace OpenSim.Framework
         private int m_maxPrimsPerUser = -1;
         private int m_linksetCapacity = 0;
         private string m_regionType = String.Empty;
-        private RegionLightShareData m_windlight = new RegionLightShareData();
         protected uint m_httpPort;
         protected string m_serverURI;
         protected string m_regionName = String.Empty;
@@ -180,7 +122,6 @@ namespace OpenSim.Framework
 
         private Dictionary<String, String> m_extraSettings = new Dictionary<string, string>();
 
-        public UUID CacheID { get; set;}
         // Apparently, we're applying the same estatesettings regardless of whether it's local or remote.
 
         // MT: Yes. Estates can't span trust boundaries. Therefore, it can be
@@ -197,8 +138,6 @@ namespace OpenSim.Framework
         public RegionInfo(string description, string filename, bool skipConsoleConfig, IConfigSource configSource, string configName)
         {
             // m_configSource = configSource;
-            CacheID = UUID.Random();
-
             if (filename.ToLower().EndsWith(".ini"))
             {
                 if (!File.Exists(filename)) // New region config request
@@ -225,7 +164,6 @@ namespace OpenSim.Framework
                     source.Save(filename);
 
                 RegionFile = filename;
-
                 return;
             }
 
@@ -257,7 +195,6 @@ namespace OpenSim.Framework
             ReadNiniConfig(source, name);
 
             m_serverURI = string.Empty;
-            CacheID = UUID.Random();
         }
 
         public RegionInfo(uint legacyRegionLocX, uint legacyRegionLocY, IPEndPoint internalEndPoint, string externalUri)
@@ -269,13 +206,11 @@ namespace OpenSim.Framework
             m_internalEndPoint = internalEndPoint;
             m_externalHostName = externalUri;
             m_serverURI = string.Empty;
-            CacheID = UUID.Random();
         }
 
         public RegionInfo()
         {
             m_serverURI = string.Empty;
-            CacheID = UUID.Random();
         }
 
         public EstateSettings EstateSettings
@@ -308,21 +243,6 @@ namespace OpenSim.Framework
             set { m_regionSettings = value; }
         }
 
-        public RegionLightShareData WindlightSettings
-        {
-            get
-            {
-                if (m_windlight == null)
-                {
-                    m_windlight = new RegionLightShareData();
-                }
-
-                return m_windlight;
-            }
-
-            set { m_windlight = value; }
-        }
-
         public float NonphysPrimMin
         {
             get { return m_nonphysPrimMin; }

+ 8 - 41
OpenSim/Framework/RegionSettings.cs

@@ -121,15 +121,15 @@ namespace OpenSim.Framework
         }
 
         private UUID m_RegionUUID = UUID.Zero;
-
         public UUID RegionUUID
         {
             get { return m_RegionUUID; }
             set { m_RegionUUID = value; }
         }
 
-        private bool m_BlockTerraform = false;
+        public UUID CacheID { get; set; } = UUID.Random();
 
+        private bool m_BlockTerraform = false;
         public bool BlockTerraform
         {
             get { return m_BlockTerraform; }
@@ -137,7 +137,6 @@ namespace OpenSim.Framework
         }
 
         private bool m_BlockFly = false;
-
         public bool BlockFly
         {
             get { return m_BlockFly; }
@@ -145,7 +144,6 @@ namespace OpenSim.Framework
         }
 
         private bool m_AllowDamage = false;
-
         public bool AllowDamage
         {
             get { return m_AllowDamage; }
@@ -153,7 +151,6 @@ namespace OpenSim.Framework
         }
 
         private bool m_RestrictPushing = false;
-
         public bool RestrictPushing
         {
             get { return m_RestrictPushing; }
@@ -161,7 +158,6 @@ namespace OpenSim.Framework
         }
 
         private bool m_AllowLandResell = true;
-
         public bool AllowLandResell
         {
             get { return m_AllowLandResell; }
@@ -169,7 +165,6 @@ namespace OpenSim.Framework
         }
 
         private bool m_AllowLandJoinDivide = true;
-
         public bool AllowLandJoinDivide
         {
             get { return m_AllowLandJoinDivide; }
@@ -177,7 +172,6 @@ namespace OpenSim.Framework
         }
 
         private bool m_BlockShowInSearch = false;
-
         public bool BlockShowInSearch
         {
             get { return m_BlockShowInSearch; }
@@ -185,7 +179,6 @@ namespace OpenSim.Framework
         }
 
         private int m_AgentLimit = 40;
-
         public int AgentLimit
         {
             get { return m_AgentLimit; }
@@ -193,7 +186,6 @@ namespace OpenSim.Framework
         }
 
         private double m_ObjectBonus = 1.0;
-
         public double ObjectBonus
         {
             get { return m_ObjectBonus; }
@@ -201,7 +193,6 @@ namespace OpenSim.Framework
         }
 
         private int m_Maturity = 0;
-
         public int Maturity
         {
             get { return m_Maturity; }
@@ -209,7 +200,6 @@ namespace OpenSim.Framework
         }
 
         private bool m_DisableScripts = false;
-
         public bool DisableScripts
         {
             get { return m_DisableScripts; }
@@ -217,7 +207,6 @@ namespace OpenSim.Framework
         }
 
         private bool m_DisableCollisions = false;
-
         public bool DisableCollisions
         {
             get { return m_DisableCollisions; }
@@ -225,7 +214,6 @@ namespace OpenSim.Framework
         }
 
         private bool m_DisablePhysics = false;
-
         public bool DisablePhysics
         {
             get { return m_DisablePhysics; }
@@ -289,7 +277,6 @@ namespace OpenSim.Framework
         }
 
         private double m_Elevation1NW = 10;
-
         public double Elevation1NW
         {
             get { return m_Elevation1NW; }
@@ -297,7 +284,6 @@ namespace OpenSim.Framework
         }
 
         private double m_Elevation2NW = 60;
-
         public double Elevation2NW
         {
             get { return m_Elevation2NW; }
@@ -305,7 +291,6 @@ namespace OpenSim.Framework
         }
 
         private double m_Elevation1NE = 10;
-
         public double Elevation1NE
         {
             get { return m_Elevation1NE; }
@@ -313,7 +298,6 @@ namespace OpenSim.Framework
         }
 
         private double m_Elevation2NE = 60;
-
         public double Elevation2NE
         {
             get { return m_Elevation2NE; }
@@ -321,7 +305,6 @@ namespace OpenSim.Framework
         }
 
         private double m_Elevation1SE = 10;
-
         public double Elevation1SE
         {
             get { return m_Elevation1SE; }
@@ -329,7 +312,6 @@ namespace OpenSim.Framework
         }
 
         private double m_Elevation2SE = 60;
-
         public double Elevation2SE
         {
             get { return m_Elevation2SE; }
@@ -337,7 +319,6 @@ namespace OpenSim.Framework
         }
 
         private double m_Elevation1SW = 10;
-
         public double Elevation1SW
         {
             get { return m_Elevation1SW; }
@@ -345,7 +326,6 @@ namespace OpenSim.Framework
         }
 
         private double m_Elevation2SW = 60;
-
         public double Elevation2SW
         {
             get { return m_Elevation2SW; }
@@ -353,7 +333,6 @@ namespace OpenSim.Framework
         }
 
         private double m_WaterHeight = 20;
-
         public double WaterHeight
         {
             get { return m_WaterHeight; }
@@ -361,7 +340,6 @@ namespace OpenSim.Framework
         }
 
         private double m_TerrainRaiseLimit = 100;
-
         public double TerrainRaiseLimit
         {
             get { return m_TerrainRaiseLimit; }
@@ -369,7 +347,6 @@ namespace OpenSim.Framework
         }
 
         private double m_TerrainLowerLimit = -100;
-
         public double TerrainLowerLimit
         {
             get { return m_TerrainLowerLimit; }
@@ -377,7 +354,6 @@ namespace OpenSim.Framework
         }
 
         private bool m_UseEstateSun = true;
-
         public bool UseEstateSun
         {
             get { return m_UseEstateSun; }
@@ -385,23 +361,19 @@ namespace OpenSim.Framework
         }
 
         private bool m_Sandbox = false;
-
         public bool Sandbox
         {
             get { return m_Sandbox; }
             set { m_Sandbox = value; }
         }
 
-        private Vector3 m_SunVector;
-
         public Vector3 SunVector
         {
-            get { return m_SunVector; }
-            set { m_SunVector = value; }
+            get { return Vector3.Zero; }
+            set { }
         }
 
         private UUID m_ParcelImageID;
-
         public UUID ParcelImageID
         {
             get { return m_ParcelImageID; }
@@ -409,27 +381,22 @@ namespace OpenSim.Framework
         }
 
         private UUID m_TerrainImageID;
-
         public UUID TerrainImageID
         {
             get { return m_TerrainImageID; }
             set { m_TerrainImageID = value; }
         }
 
-        private bool m_FixedSun = false;
-
         public bool FixedSun
         {
-            get { return m_FixedSun; }
-            set { m_FixedSun = value; }
+            get { return false; }
+            set { }
         }
 
-        private double m_SunPosition = 0.0;
-
         public double SunPosition
         {
-            get { return m_SunPosition; }
-            set { m_SunPosition = value; }
+            get { return 0; }
+            set { }
         }
 
         private UUID m_Covenant = UUID.Zero;

+ 56 - 98
OpenSim/Framework/RestClient.cs

@@ -32,6 +32,7 @@ using System.Net;
 using System.Reflection;
 using System.Text;
 using System.Threading;
+using System.Threading.Tasks;
 using System.Web;
 using log4net;
 
@@ -92,7 +93,7 @@ namespace OpenSim.Framework
         /// <summary>
         /// MemoryStream representing the resulting resource
         /// </summary>
-        private Stream _resource;
+        private MemoryStream _resource;
 
         /// <summary>
         /// WebRequest object, held as a member variable
@@ -117,8 +118,7 @@ namespace OpenSim.Framework
         /// <summary>
         /// Default Buffer size of a block requested from the web-server
         /// </summary>
-        private const int BufferSize = 4096; // Read blocks of 4 KB.
-
+        private const int BufferSize = 4 * 4096; // Read blocks of 4 * 4 KB.
 
         /// <summary>
         /// if an exception occours during async processing, we need to save it, so it can be
@@ -181,10 +181,7 @@ namespace OpenSim.Framework
         /// <param name="element">path entry</param>
         public void AddResourcePath(string element)
         {
-            if (isSlashed(element))
-                _pathElements.Add(element.Substring(0, element.Length - 1));
-            else
-                _pathElements.Add(element);
+            _pathElements.Add(Util.TrimEndSlash(element));
         }
 
         /// <summary>
@@ -237,16 +234,6 @@ namespace OpenSim.Framework
             set { _method = value; }
         }
 
-        /// <summary>
-        /// True if string contains a trailing slash '/'
-        /// </summary>
-        /// <param name="s">string to be examined</param>
-        /// <returns>true if slash is present</returns>
-        private static bool isSlashed(string s)
-        {
-            return s.Substring(s.Length - 1, 1) == "/";
-        }
-
         /// <summary>
         /// Build a Uri based on the initial Url, path elements and parameters
         /// </summary>
@@ -326,7 +313,7 @@ namespace OpenSim.Framework
         /// <summary>
         /// Perform a synchronous request
         /// </summary>
-        public Stream Request()
+        public MemoryStream Request()
         {
             return Request(null);
         }
@@ -334,27 +321,24 @@ namespace OpenSim.Framework
         /// <summary>
         /// Perform a synchronous request
         /// </summary>
-        public Stream Request(IServiceAuth auth)
+        public MemoryStream Request(IServiceAuth auth)
         {
             lock (_lock)
             {
-                _request = (HttpWebRequest) WebRequest.Create(buildUri());
-                _request.KeepAlive = false;
-                _request.ContentType = "application/xml";
-                _request.Timeout = 200000;
-                _request.Method = RequestMethod;
-                _asyncException = null;
-                if (auth != null)
-                    auth.AddAuthorization(_request.Headers);
-
                 int reqnum = WebUtil.RequestNumber++;
-                if (WebUtil.DebugLevel >= 3)
-                    m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} REST {1} to {2}", reqnum, _request.Method, _request.RequestUri);
-
-//                IAsyncResult responseAsyncResult = _request.BeginGetResponse(new AsyncCallback(ResponseIsReadyDelegate), _request);
-
                 try
                 {
+                    _request = (HttpWebRequest) WebRequest.Create(buildUri());
+                    _request.ContentType = "application/xml";
+                    _request.Timeout = 90000;
+                    _request.Method = RequestMethod;
+                    _asyncException = null;
+                    if (auth != null)
+                        auth.AddAuthorization(_request.Headers);
+
+                    if (WebUtil.DebugLevel >= 3)
+                        m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} REST {1} to {2}", reqnum, _request.Method, _request.RequestUri);
+
                     using (_response = (HttpWebResponse) _request.GetResponse())
                     {
                         using (Stream src = _response.GetResponseStream())
@@ -365,12 +349,6 @@ namespace OpenSim.Framework
                                 _resource.Write(_readbuf, 0, length);
                                 length = src.Read(_readbuf, 0, BufferSize);
                             }
-
-                            // TODO! Implement timeout, without killing the server
-                            // this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted
-                            //ThreadPool.RegisterWaitForSingleObject(responseAsyncResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true);
-
-                            //                _allDone.WaitOne();
                         }
                     }
                 }
@@ -391,7 +369,6 @@ namespace OpenSim.Framework
                     return null;
                 }
 
-
                 if (_asyncException != null)
                     throw _asyncException;
 
@@ -408,81 +385,62 @@ namespace OpenSim.Framework
             }
         }
 
-        public Stream Request(Stream src, IServiceAuth auth)
+        // just post data, ignoring result
+        public async Task AsyncPOSTRequest(byte[] src, IServiceAuth auth)
         {
-            _request = (HttpWebRequest) WebRequest.Create(buildUri());
-            _request.KeepAlive = false;
-            _request.ContentType = "application/xml";
-            _request.Timeout = 90000;
-            _request.Method = RequestMethod;
-            _asyncException = null;
-            _request.ContentLength = src.Length;
-            if (auth != null)
-                auth.AddAuthorization(_request.Headers);
-
-            src.Seek(0, SeekOrigin.Begin);
-
             int reqnum = WebUtil.RequestNumber++;
-            if (WebUtil.DebugLevel >= 3)
-                m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} REST {1} to {2}", reqnum, _request.Method, _request.RequestUri);
-            if (WebUtil.DebugLevel >= 5)
-                WebUtil.LogOutgoingDetail(string.Format("SEND {0}: ", reqnum), src);
+            try
+            {
+                _request = (HttpWebRequest)WebRequest.Create(buildUri());
+                _request.ContentType = "application/xml";
+                _request.Timeout = 90000;
+                _request.Method = "POST";
+                _asyncException = null;
+                _request.ContentLength = src.Length;
+                if (auth != null)
+                    auth.AddAuthorization(_request.Headers);
+            }
+            catch (Exception e)
+            {
+                m_log.WarnFormat("[REST]: AsyncPOST {0} failed with exception {1} {2}",
+                                _request.RequestUri, e.Message, e.StackTrace);
+                return;
+            }
 
-            
             try
             {
                 using (Stream dst = _request.GetRequestStream())
                 {
-//                    m_log.Debug("[REST]: GetRequestStream is ok");
+                    await dst.WriteAsync(src, 0, src.Length).ConfigureAwait(false);
+                }
 
-                    byte[] buf = new byte[1024];
-                    int length = src.Read(buf, 0, 1024);
-//                    m_log.Debug("[REST]: First Read is ok");
-                    while (length > 0)
+                using(HttpWebResponse response = (HttpWebResponse)await _request.GetResponseAsync().ConfigureAwait(false))
+                {
+                    if (WebUtil.DebugLevel >= 5)
                     {
-                        dst.Write(buf, 0, length);
-                        length = src.Read(buf, 0, 1024);
+                        using (Stream responseStream = response.GetResponseStream())
+                        {
+                            using (StreamReader reader = new StreamReader(responseStream))
+                            {
+                                string responseStr = await reader.ReadToEndAsync().ConfigureAwait(false);
+                                WebUtil.LogResponseDetail(reqnum, responseStr);
+                            }
+                        }
                     }
                 }
-
-                _response = (HttpWebResponse)_request.GetResponse();
             }
             catch (WebException e)
             {
-                m_log.WarnFormat("[REST]: Request {0} {1} failed with status {2} and message {3}",
-                                  RequestMethod, _request.RequestUri, e.Status, e.Message);
-                return null;
+                m_log.WarnFormat("[REST]: AsyncPOST {0} failed with status {1} and message {2}",
+                                  _request.RequestUri, e.Status, e.Message);
+                return;
             }
             catch (Exception e)
             {
-                m_log.WarnFormat(
-                    "[REST]: Request {0} {1} failed with exception {2} {3}",
-                    RequestMethod, _request.RequestUri, e.Message, e.StackTrace);
-                return null;
-            }
-
-            if (WebUtil.DebugLevel >= 5)
-            {
-                using (Stream responseStream = _response.GetResponseStream())
-                {
-                    using (StreamReader reader = new StreamReader(responseStream))
-                    {
-                        string responseStr = reader.ReadToEnd();
-                        WebUtil.LogResponseDetail(reqnum, responseStr);
-                    }
-                }
+                m_log.WarnFormat("[REST]: AsyncPOST {0} failed with exception {1} {2}",
+                                _request.RequestUri, e.Message, e.StackTrace);
+                return;
             }
-
-            if (_response != null)
-                _response.Close();
-
-//            IAsyncResult responseAsyncResult = _request.BeginGetResponse(new AsyncCallback(ResponseIsReadyDelegate), _request);
-
-            // TODO! Implement timeout, without killing the server
-            // this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted
-            //ThreadPool.RegisterWaitForSingleObject(responseAsyncResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true);
-
-            return null;
         }
 
         #region Async Invocation
@@ -513,7 +471,7 @@ namespace OpenSim.Framework
             try
             {
                 // Perform the operation; if sucessful set the result
-                Stream s = Request(null);
+                MemoryStream s = Request(null);
                 ar.SetAsCompleted(s, false);
             }
             catch (Exception e)

+ 448 - 222
OpenSim/Framework/SLUtil.cs

@@ -28,6 +28,7 @@
 using OpenMetaverse;
 using System;
 using System.Collections.Generic;
+using System.Globalization;
 
 namespace OpenSim.Framework
 {
@@ -44,7 +45,6 @@ namespace OpenSim.Framework
             Material = -2
         }
 
-
         #region SL / file extension / content-type conversions
 
         /// <summary>
@@ -190,6 +190,56 @@ namespace OpenSim.Framework
         private static Dictionary<sbyte, string> inventory2Content;
         private static Dictionary<string, sbyte> content2Asset;
         private static Dictionary<string, sbyte> content2Inventory;
+        private static Dictionary<string, AssetType> name2Asset = new Dictionary<string, AssetType>()
+        {
+            {"texture", AssetType.Texture },
+            {"sound", AssetType.Sound},
+            {"callcard", AssetType.CallingCard},
+            {"landmark", AssetType.Landmark},
+            {"script", (AssetType)4},
+            {"clothing", AssetType.Clothing},
+            {"object", AssetType.Object},
+            {"notecard", AssetType.Notecard},
+            {"category", AssetType.Folder},
+            {"lsltext", AssetType.LSLText},
+            {"lslbyte", AssetType.LSLBytecode},
+            {"txtr_tga", AssetType.TextureTGA},
+            {"bodypart", AssetType.Bodypart},
+            {"snd_wav", AssetType.SoundWAV},
+            {"img_tga", AssetType.ImageTGA},
+            {"jpeg", AssetType.ImageJPEG},
+            {"animatn", AssetType.Animation},
+            {"gesture", AssetType.Gesture},
+            {"simstate", AssetType.Simstate},
+            {"mesh", AssetType.Mesh},
+            {"settings", AssetType.Settings}
+        };
+        private static Dictionary<string, FolderType> name2Inventory = new Dictionary<string, FolderType>()
+        {
+            {"texture", FolderType.Texture},
+            {"sound", FolderType.Sound},
+            {"callcard", FolderType.CallingCard},
+            {"landmark", FolderType.Landmark},
+            {"script", (FolderType)4},
+            {"clothing", FolderType.Clothing},
+            {"object", FolderType.Object},
+            {"notecard", FolderType.Notecard},
+            {"root", FolderType.Root},
+            {"lsltext", FolderType.LSLText},
+            {"bodypart", FolderType.BodyPart},
+            {"trash", FolderType.Trash},
+            {"snapshot", FolderType.Snapshot},
+            {"lostandfound", FolderType.LostAndFound},
+            {"animatn", FolderType.Animation},
+            {"gesture", FolderType.Gesture},
+            {"favorites", FolderType.Favorites},
+            {"currentoutfit", FolderType.CurrentOutfit},
+            {"outfit", FolderType.Outfit},
+            {"myoutfits", FolderType.MyOutfits},
+            {"mesh", FolderType.Mesh},
+            {"settings", FolderType.Settings},
+            {"suitcase", FolderType.Suitcase}
+        };
 
         static SLUtil()
         {
@@ -227,6 +277,20 @@ namespace OpenSim.Framework
             }
         }
 
+        public static AssetType SLAssetName2Type(string name)
+        {
+            if (name2Asset.TryGetValue(name, out AssetType type))
+                return type;
+            return AssetType.Unknown;
+        }
+
+        public static FolderType SLInvName2Type(string name)
+        {
+            if (name2Inventory.TryGetValue(name, out FolderType type))
+                return type;
+            return FolderType.None;
+        }
+
         public static string SLAssetTypeToContentType(int assetType)
         {
             string contentType;
@@ -269,270 +333,432 @@ namespace OpenSim.Framework
 
         #endregion SL / file extension / content-type conversions
 
-        private class NotecardReader
-        {
-            private string rawInput;
-            private int lineNumber;
-
-            public int LineNumber
-            {
-                get
-                {
-                    return lineNumber;
-                }
-            }
-
-            public NotecardReader(string _rawInput)
-            {
-                rawInput = (string)_rawInput.Clone();
-                lineNumber = 0;
-            }
+        static char[] seps = new char[] { '\t', '\n' };
+        static char[] stringseps = new char[] { '|', '\n' };
 
-            public string getLine()
-            {
-                if(rawInput.Length == 0)
-                {
-                    throw new NotANotecardFormatException(lineNumber + 1);
-                }
-
-                int pos = rawInput.IndexOf('\n');
-                if(pos < 0)
-                {
-                    pos = rawInput.Length;
-                }
-
-                /* cut line from rest */
-                ++lineNumber;
-                string line = rawInput.Substring(0, pos);
-                if (pos + 1 >= rawInput.Length)
-                {
-                    rawInput = string.Empty;
-                }
-                else
-                {
-                    rawInput = rawInput.Substring(pos + 1);
-                }
-                /* clean up line from double spaces and tabs */
-                line = line.Replace("\t", " ");
-                while(line.IndexOf("  ") >= 0)
-                {
-                    line = line.Replace("  ", " ");
-                }
-                return line.Replace("\r", "").Trim();
-            }
-
-            public string getBlock(int length)
-            {
-                /* cut line from rest */
-                if(length > rawInput.Length)
-                {
-                    throw new NotANotecardFormatException(lineNumber);
-                }
-                string line = rawInput.Substring(0, length);
-                rawInput = rawInput.Substring(length);
-                return line;
-            }
-        }
+        static byte[] moronize = new byte[16]
+        {
+            60, 17, 94, 81, 4, 244, 82, 60, 159, 166, 152, 175, 241, 3, 71, 48
+        };
 
-        public class NotANotecardFormatException : Exception
+        static int getField(string note, int start, string name, bool isString, out string value)
         {
-            public int lineNumber;
-            public NotANotecardFormatException(int _lineNumber)
-                : base()
-            {
-               lineNumber = _lineNumber;
-            }
+            value = String.Empty;
+            int end = -1;
+            int limit = note.Length - start;
+            if (limit > 64)
+                limit = 64;
+            int indx = note.IndexOf(name, start, limit);
+            if (indx < 0)
+                return -1;
+            indx += name.Length + 1; // eat \t
+            limit = note.Length - indx - 2;
+            if (limit > 129)
+                limit = 129;
+            if (isString)
+                end = note.IndexOfAny(stringseps, indx, limit);
+            else
+                end = note.IndexOfAny(seps, indx, limit);
+            if (end < 0)
+                return -1;
+            value = note.Substring(indx, end - indx);
+            return end;
         }
 
-        private static void skipSection(NotecardReader reader)
+        private static UUID deMoronize(UUID id)
         {
-            if (reader.getLine() != "{")
-                throw new NotANotecardFormatException(reader.LineNumber);
+            byte[] data = new byte[16];
+            id.ToBytes(data,0);
+            for(int i = 0; i < 16; ++i)
+                data[i] ^= moronize[i];
 
-            string line;
-            while ((line = reader.getLine()) != "}")
-            {
-                if(line.IndexOf('{')>=0)
-                {
-                    throw new NotANotecardFormatException(reader.LineNumber);
-                }
-            }
+            return new UUID(data,0);
         }
 
-        private static void skipInventoryItem(NotecardReader reader)
+        public static InventoryItemBase GetEmbeddedItem(byte[] data, UUID itemID)
         {
-            if (reader.getLine() != "{")
-                throw new NotANotecardFormatException(reader.LineNumber);
-
-            string line;
-            while((line = reader.getLine()) != "}")
+            if(data == null || data.Length < 300)
+                return null;
+
+            string note = Util.UTF8.GetString(data);
+            if (String.IsNullOrWhiteSpace(note))
+                return null;
+
+            // waste some time checking rigid versions
+            string version = note.Substring(0,21);
+            if (!version.Equals("Linden text version 2"))
+                return null;
+
+            version = note.Substring(24, 25);
+            if (!version.Equals("LLEmbeddedItems version 1"))
+                return null;
+
+            int indx = note.IndexOf(itemID.ToString(), 100);
+            if (indx < 0)
+                return null;
+
+            indx = note.IndexOf("permissions", indx, 100); // skip parentID
+            if (indx < 0)
+                return null;
+
+            string valuestr;
+
+            indx = getField(note, indx, "base_mask", false, out valuestr);
+            if (indx < 0)
+                return null;
+            if (!uint.TryParse(valuestr, NumberStyles.HexNumber, Culture.NumberFormatInfo, out uint basemask))
+                return null;
+
+            indx = getField(note, indx, "owner_mask", false, out valuestr);
+            if (indx < 0)
+                return null;
+            if (!uint.TryParse(valuestr, NumberStyles.HexNumber, Culture.NumberFormatInfo, out uint ownermask))
+                return null;
+
+            indx = getField(note, indx, "group_mask", false, out valuestr);
+            if (indx < 0)
+                return null;
+            if (!uint.TryParse(valuestr, NumberStyles.HexNumber, Culture.NumberFormatInfo, out uint groupmask))
+                return null;
+
+            indx = getField(note, indx, "everyone_mask", false, out valuestr);
+            if (indx < 0)
+                return null;
+            if (!uint.TryParse(valuestr, NumberStyles.HexNumber, Culture.NumberFormatInfo, out uint everyonemask))
+                return null;
+
+            indx = getField(note, indx, "next_owner_mask", false, out valuestr);
+            if (indx < 0)
+                return null;
+            if (!uint.TryParse(valuestr, NumberStyles.HexNumber, Culture.NumberFormatInfo, out uint nextownermask))
+                return null;
+
+            indx = getField(note, indx, "creator_id", false, out valuestr);
+            if (indx < 0)
+                return null;
+            if (!UUID.TryParse(valuestr, out UUID creatorID))
+                return null;
+
+            indx = getField(note, indx, "owner_id", false, out valuestr);
+            if (indx < 0)
+                return null;
+            if (!UUID.TryParse(valuestr, out UUID ownerID))
+                return null;
+
+            int limit = note.Length - indx;
+            if (limit > 120)
+                limit = 120;
+            indx = note.IndexOf('}', indx, limit); // last owner
+            if (indx < 0)
+                return null;
+
+            int curindx = indx;
+            UUID assetID = UUID.Zero;
+            indx = getField(note, indx, "asset_id", false, out valuestr);
+            if (indx < 0)
             {
-                string[] data = line.Split(' ');
-                if(data.Length == 0)
-                {
-                    continue;
-                }
-                if(data[0] == "permissions")
-                {
-                    skipSection(reader);
-                }
-                else if(data[0] == "sale_info")
-                {
-                    skipSection(reader);
-                }
-                else if (line.IndexOf('{') >= 0)
-                {
-                    throw new NotANotecardFormatException(reader.LineNumber);
-                }
+                indx = getField(note, curindx, "shadow_id", false, out valuestr);
+                if (indx < 0)
+                    return null;
+                if (!UUID.TryParse(valuestr, out assetID))
+                    return null;
+                assetID = deMoronize(assetID);
             }
+            else
+            {
+                if (!UUID.TryParse(valuestr, out assetID))
+                    return null;
+            }
+
+            indx = getField(note, indx, "type", false, out valuestr);
+            if (indx < 0)
+                return null;
+
+            AssetType assetType = SLAssetName2Type(valuestr);
+
+            indx = getField(note, indx, "inv_type", false, out valuestr);
+            if (indx < 0)
+                return null;
+            FolderType invType = SLInvName2Type(valuestr);
+
+            indx = getField(note, indx, "flags", false, out valuestr);
+            if (indx < 0)
+                return null;
+            if (!uint.TryParse(valuestr, NumberStyles.HexNumber, Culture.NumberFormatInfo, out uint flags))
+                return null;
+
+            limit = note.Length - indx;
+            if (limit > 120)
+                limit = 120;
+            indx = note.IndexOf('}', indx, limit); // skip sale
+            if (indx < 0)
+                return null;
+
+            indx = getField(note, indx, "name", true, out valuestr);
+            if (indx < 0)
+                return null;
+
+            string name = valuestr;
+
+            indx = getField(note, indx, "desc", true, out valuestr);
+            if (indx < 0)
+                return null;
+            string desc = valuestr;
+
+            InventoryItemBase item = new InventoryItemBase();
+            item.AssetID = assetID;
+            item.AssetType = (sbyte)assetType;
+            item.BasePermissions = basemask;
+            item.CreationDate = Util.UnixTimeSinceEpoch();
+            item.CreatorData = "";
+            item.CreatorId = creatorID.ToString();
+            item.CurrentPermissions = ownermask;
+            item.Description = desc;
+            item.Flags = flags;
+            item.Folder = UUID.Zero;
+            item.GroupID = UUID.Zero;
+            item.GroupOwned = false;
+            item.GroupPermissions = groupmask;
+            item.InvType = (sbyte)invType;
+            item.Name = name;
+            item.NextPermissions = nextownermask;
+            item.Owner = ownerID;
+            item.SalePrice = 0;
+            item.SaleType = (byte)SaleType.Not;
+            item.ID = UUID.Random();
+            return item;
         }
 
-        private static void skipInventoryItems(NotecardReader reader)
+        public static List<UUID> GetEmbeddedAssetIDs(byte[] data)
         {
-            if(reader.getLine() != "{")
-            {
-                throw new NotANotecardFormatException(reader.LineNumber);
-            }
+            if (data == null || data.Length < 79)
+                return null;
 
-            string line;
-            while((line = reader.getLine()) != "}")
-            {
-                string[] data = line.Split(' ');
-                if(data.Length == 0)
-                {
-                    continue;
-                }
+            string note = Util.UTF8.GetString(data);
+            if (String.IsNullOrWhiteSpace(note))
+                return null;
 
-                if(data[0] == "inv_item")
-                {
-                    skipInventoryItem(reader);
-                }
-                else if (line.IndexOf('{') >= 0)
-                {
-                    throw new NotANotecardFormatException(reader.LineNumber);
-                }
+            // waste some time checking rigid versions
+            string tmpStr = note.Substring(0, 21);
+            if (!tmpStr.Equals("Linden text version 2"))
+                return null;
 
-            }
-        }
+            tmpStr = note.Substring(24, 25);
+            if (!tmpStr.Equals("LLEmbeddedItems version 1"))
+                return null;
 
-        private static void skipInventory(NotecardReader reader)
-        {
-            if (reader.getLine() != "{")
-                throw new NotANotecardFormatException(reader.LineNumber);
+            tmpStr = note.Substring(52,5);
+            if (!tmpStr.Equals("count"))
+                return null;
 
-            string line;
-            while((line = reader.getLine()) != "}")
-            {
-                string[] data = line.Split(' ');
-                if(data[0] == "count")
-                {
-                    int count = Int32.Parse(data[1]);
-                    for(int i = 0; i < count; ++i)
-                    {
-                        skipInventoryItems(reader);
-                    }
-                }
-                else if (line.IndexOf('{') >= 0)
-                {
-                    throw new NotANotecardFormatException(reader.LineNumber);
-                }
-            }
-        }
+            int limit = note.Length - 57 - 2;
+            if (limit > 8)
+                limit = 8;
 
-        private static string readNotecardText(NotecardReader reader)
-        {
-            if (reader.getLine() != "{")
-                throw new NotANotecardFormatException(reader.LineNumber);
+            int indx = note.IndexOfAny(seps, 57, limit);
+            if(indx < 0)
+                return null;
 
-            string notecardString = string.Empty;
-            string line;
-            while((line = reader.getLine()) != "}")
-            {
-                string[] data = line.Split(' ');
-                if (data.Length == 0)
-                {
-                    continue;
-                }
+            if (!int.TryParse(note.Substring(57, indx - 57), out int count))
+                return null;
 
-                if (data[0] == "LLEmbeddedItems")
+            List<UUID> ids = new List<UUID>();
+            while(count > 0)
+            {
+                string valuestr;
+                UUID assetID = UUID.Zero;
+                indx = note.IndexOf('}',indx); // skip to end of permissions
+                if (indx < 0)
+                    return null;
+
+                int curindx = indx;
+                indx = getField(note, indx, "asset_id", false, out valuestr);
+                if (indx < 0)
                 {
-                    skipInventory(reader);
+                    indx = getField(note, curindx, "shadow_id", false, out valuestr);
+                    if (indx < 0)
+                        return null;
+                    if (!UUID.TryParse(valuestr, out assetID))
+                        return null;
+                    assetID = deMoronize(assetID);
                 }
-                else if(data[0] == "Text" && data.Length == 3)
+                else
                 {
-                    int length = Int32.Parse(data[2]);
-                    notecardString = reader.getBlock(length);
+                    if (!UUID.TryParse(valuestr, out assetID))
+                        return null;
                 }
-                else if (line.IndexOf('{') >= 0)
+                ids.Add(assetID);
+
+                indx = note.IndexOf('}', indx); // skip to end of sale
+                if (indx < 0)
+                    return null;
+                indx = getField(note, indx, "name", false, out valuestr); // avoid name contents
+                if (indx < 0)
+                    return null;
+                indx = getField(note, indx, "desc", false, out valuestr); // avoid desc contents
+                if (indx < 0)
+                    return null;
+
+                if(count > 1)
                 {
-                    throw new NotANotecardFormatException(reader.LineNumber);
+                    indx = note.IndexOf("ext char index", indx); // skip to next
+                    if (indx < 0)
+                        return null;
                 }
-
-            }
-            return notecardString;
-        }
-
-        private static string readNotecard(byte[] rawInput)
-        {
-            string rawIntermedInput = string.Empty;
-
-            /* make up a Raw Encoding here */
-            foreach(byte c in rawInput)
-            {
-                char d = (char)c;
-                rawIntermedInput += d;
+                --count;
             }
 
-            NotecardReader reader = new NotecardReader(rawIntermedInput);
-            string line;
-            try
-            {
-                line = reader.getLine();
-            }
-            catch(Exception)
+            indx = note.IndexOf("Text length",indx);
+            if(indx > 0)
             {
-                return System.Text.Encoding.UTF8.GetString(rawInput);
-            }
-            string[] versioninfo = line.Split(' ');
-            if(versioninfo.Length < 3)
-            {
-                return System.Text.Encoding.UTF8.GetString(rawInput);
-            }
-            else if(versioninfo[0] != "Linden" || versioninfo[1] != "text")
-            {
-                return System.Text.Encoding.UTF8.GetString(rawInput);
-            }
-            else
-            {
-                /* now we actually decode the Encoding, before we needed it in raw */
-                string o = readNotecardText(reader);
-                byte[] a = new byte[o.Length];
-                for(int i = 0; i < o.Length; ++i)
-                {
-                    a[i] = (byte)o[i];
-                }
-                return System.Text.Encoding.UTF8.GetString(a);
+                indx += 14;
+                List<UUID> textIDs = Util.GetUUIDsOnString(ref note, indx, note.Length - indx);
+                if(textIDs.Count > 0)
+                    ids.AddRange(textIDs);
             }
+            if (ids.Count == 0)
+                return null;
+            return ids;
         }
 
         /// <summary>
-        /// Parse a notecard in Linden format to a string of ordinary text.
+        /// Parse a notecard in Linden format to a list of ordinary lines for LSL
         /// </summary>
         /// <param name="rawInput"></param>
         /// <returns></returns>
-        public static string ParseNotecardToString(byte[] rawInput)
+
+        public static string[] ParseNotecardToArray(byte[] data)
         {
-            return readNotecard(rawInput);
+            // check of a valid notecard
+            if (data == null || data.Length < 79)
+                return new string[0];
+
+            //LSL can't read notecards with embedded items
+            if (data[58] != '0' || data[59] != '\n')
+                return new string[0];
+
+            string note = Util.UTF8.GetString(data);
+            if (String.IsNullOrWhiteSpace(note))
+                return new string[0];
+
+            // waste some time checking rigid versions
+            string tmpStr = note.Substring(0, 21);
+            if (!tmpStr.Equals("Linden text version 2"))
+                return new string[0];
+
+            tmpStr = note.Substring(24, 25);
+            if (!tmpStr.Equals("LLEmbeddedItems version 1"))
+                return new string[0];
+
+            tmpStr = note.Substring(52, 5);
+            if (!tmpStr.Equals("count"))
+                return new string[0];
+
+            int indx = note.IndexOf("Text length", 60);
+            if(indx < 0)
+                return new string[0];
+
+            indx += 12;
+            int end = indx + 1;
+            for (; end < note.Length && note[end] != '\n'; ++end);
+            if (note[end] != '\n')
+                return new string[0];
+
+            tmpStr = note.Substring(indx, end - indx);
+            if (!int.TryParse(tmpStr, out int textLen) || textLen == 0)
+                return new string[0];
+
+            indx = end + 1;
+            if (textLen + indx > data.Length)
+                return new string[0];
+            // yeackk
+            note = Util.UTF8.GetString(data, indx, textLen);
+            textLen = note.Length;
+            indx = 0;
+            var lines = new List<string>();
+            while (indx < textLen)
+            {
+                end = indx;
+                for (; end < textLen && note[end] != '\n'; ++end);
+                if(end == indx)
+                    lines.Add(String.Empty);
+                else
+                    lines.Add(note.Substring(indx, end - indx));
+                indx = end + 1;
+            }
+            // notes only seem to have one text section
+
+            if(lines.Count == 0)
+                return new string[0];
+            return lines.ToArray();
         }
 
-        /// <summary>
-        /// Parse a notecard in Linden format to a list of ordinary lines.
-        /// </summary>
-        /// <param name="rawInput"></param>
-        /// <returns></returns>
-        public static string[] ParseNotecardToArray(byte[] rawInput)
+        // libomv has old names on ATTACH_LEFT_PEC and ATTACH_RIGHT_PEC
+        public static readonly string[] AttachmentPointNames = new string[]
+        {
+            string.Empty,
+            "ATTACH_CHEST", // 1
+            "ATTACH_HEAD", // 2
+            "ATTACH_LSHOULDER", // 3
+            "ATTACH_RSHOULDER", // 4
+            "ATTACH_LHAND", // 5
+            "ATTACH_RHAND", // 6
+            "ATTACH_LFOOT", // 7
+            "ATTACH_RFOOT", // 8
+            "ATTACH_BACK", // 9
+            "ATTACH_PELVIS", // 10
+            "ATTACH_MOUTH", // 11
+            "ATTACH_CHIN", // 12
+            "ATTACH_LEAR", // 13
+            "ATTACH_REAR", // 14
+            "ATTACH_LEYE", // 15
+            "ATTACH_REYE", // 16
+            "ATTACH_NOSE", // 17
+            "ATTACH_RUARM", // 18
+            "ATTACH_RLARM", // 19
+            "ATTACH_LUARM", // 20
+            "ATTACH_LLARM", // 21
+            "ATTACH_RHIP", // 22
+            "ATTACH_RULEG", // 23
+            "ATTACH_RLLEG", // 24
+            "ATTACH_LHIP", // 25
+            "ATTACH_LULEG", // 26
+            "ATTACH_LLLEG", // 27
+            "ATTACH_BELLY", // 28
+            "ATTACH_LEFT_PEC", // 29
+            "ATTACH_RIGHT_PEC", // 30
+            "ATTACH_HUD_CENTER_2", // 31
+            "ATTACH_HUD_TOP_RIGHT", // 32
+            "ATTACH_HUD_TOP_CENTER", // 33
+            "ATTACH_HUD_TOP_LEFT", // 34
+            "ATTACH_HUD_CENTER_1", // 35
+            "ATTACH_HUD_BOTTOM_LEFT", // 36
+            "ATTACH_HUD_BOTTOM", // 37
+            "ATTACH_HUD_BOTTOM_RIGHT", // 38
+            "ATTACH_NECK", // 39
+            "ATTACH_AVATAR_CENTER", // 40
+            "ATTACH_LHAND_RING1", // 41
+            "ATTACH_RHAND_RING1", // 42
+            "ATTACH_TAIL_BASE", // 43
+            "ATTACH_TAIL_TIP", // 44
+            "ATTACH_LWING", // 45
+            "ATTACH_RWING", // 46
+            "ATTACH_FACE_JAW", // 47
+            "ATTACH_FACE_LEAR", // 48
+            "ATTACH_FACE_REAR", // 49
+            "ATTACH_FACE_LEYE", // 50
+            "ATTACH_FACE_REYE", // 51
+            "ATTACH_FACE_TONGUE", // 52
+            "ATTACH_GROIN", // 53
+            "ATTACH_HIND_LFOOT", // 54
+            "ATTACH_HIND_RFOOT" // 55
+        };
+
+        public static string GetAttachmentName(int point)
         {
-            return readNotecard(rawInput).Replace("\r", "").Split('\n');
+            if(point < AttachmentPointNames.Length)
+                return AttachmentPointNames[point];
+            return "Unknown";
         }
     }
 }

+ 3 - 1
OpenSim/Framework/Serialization/ArchiveConstants.cs

@@ -125,7 +125,8 @@ namespace OpenSim.Framework.Serialization
             ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.SoundWAV]            = ASSET_EXTENSION_SEPARATOR + "sound.wav";
             ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.Texture]             = ASSET_EXTENSION_SEPARATOR + "texture.jp2";
             ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.TextureTGA]          = ASSET_EXTENSION_SEPARATOR + "texture.tga";
-            ASSET_TYPE_TO_EXTENSION[(sbyte)OpenSimAssetType.Material]     = ASSET_EXTENSION_SEPARATOR + "material.xml";   // Not sure if we'll ever see this
+            ASSET_TYPE_TO_EXTENSION[(sbyte)OpenSimAssetType.Material]     = ASSET_EXTENSION_SEPARATOR + "material.xml";
+            ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.Settings]            = ASSET_EXTENSION_SEPARATOR + "settings.bin";
 
             EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "animation.bvh"]            = (sbyte)AssetType.Animation;
             EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "bodypart.txt"]             = (sbyte)AssetType.Bodypart;
@@ -147,6 +148,7 @@ namespace OpenSim.Framework.Serialization
             EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "texture.jp2"]              = (sbyte)AssetType.Texture;
             EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "texture.tga"]              = (sbyte)AssetType.TextureTGA;
             EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "material.xml"]             = (sbyte)OpenSimAssetType.Material;
+            EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "settings.bin"]             = (sbyte)AssetType.Settings;
         }
 
         public static string CreateOarLandDataPath(LandData ld)

Неке датотеке нису приказане због велике количине промена