diff --git a/.nant/local.include b/.nant/local.include
index 5ff96446c5..be79d1cfce 100644
--- a/.nant/local.include
+++ b/.nant/local.include
@@ -145,7 +145,12 @@
-
+
+
+
+
+
+
@@ -260,6 +265,11 @@
+
+
+
+
+
@@ -271,6 +281,7 @@
+
diff --git a/OpenSim/Addons/Groups/GroupsModule.cs b/OpenSim/Addons/Groups/GroupsModule.cs
index 0e3a1729b5..5b76e0a5b8 100644
--- a/OpenSim/Addons/Groups/GroupsModule.cs
+++ b/OpenSim/Addons/Groups/GroupsModule.cs
@@ -787,7 +787,7 @@ namespace OpenSim.Groups
remoteClient.SendCreateGroupReply(groupID, true, "Group created successfully");
// Update the founder with new group information.
- SendAgentGroupDataUpdate(remoteClient, false);
+ SendAgentGroupDataUpdate(remoteClient, true);
}
else
remoteClient.SendCreateGroupReply(groupID, false, reason);
diff --git a/OpenSim/Addons/Groups/Hypergrid/HGGroupsServiceRobustConnector.cs b/OpenSim/Addons/Groups/Hypergrid/HGGroupsServiceRobustConnector.cs
index af007709be..51f3ec15e0 100644
--- a/OpenSim/Addons/Groups/Hypergrid/HGGroupsServiceRobustConnector.cs
+++ b/OpenSim/Addons/Groups/Hypergrid/HGGroupsServiceRobustConnector.cs
@@ -115,9 +115,10 @@ namespace OpenSim.Groups
protected override byte[] ProcessRequest(string path, Stream requestData,
IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
- StreamReader sr = new StreamReader(requestData);
- string body = sr.ReadToEnd();
- sr.Close();
+ string body;
+ using(StreamReader sr = new StreamReader(requestData))
+ body = sr.ReadToEnd();
+
body = body.Trim();
//m_log.DebugFormat("[XXX]: query String: {0}", body);
diff --git a/OpenSim/Addons/Groups/Remote/GroupsServiceRobustConnector.cs b/OpenSim/Addons/Groups/Remote/GroupsServiceRobustConnector.cs
index 598e7a5a9d..8502bb5bda 100644
--- a/OpenSim/Addons/Groups/Remote/GroupsServiceRobustConnector.cs
+++ b/OpenSim/Addons/Groups/Remote/GroupsServiceRobustConnector.cs
@@ -91,9 +91,10 @@ namespace OpenSim.Groups
protected override byte[] ProcessRequest(string path, Stream requestData,
IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
- StreamReader sr = new StreamReader(requestData);
- string body = sr.ReadToEnd();
- sr.Close();
+ string body;
+ using(StreamReader sr = new StreamReader(requestData))
+ body = sr.ReadToEnd();
+
body = body.Trim();
//m_log.DebugFormat("[XXX]: query String: {0}", body);
diff --git a/OpenSim/ApplicationPlugins/RemoteController/RemoteAdminPlugin.cs b/OpenSim/ApplicationPlugins/RemoteController/RemoteAdminPlugin.cs
index 597b4397c5..510905f64e 100644
--- a/OpenSim/ApplicationPlugins/RemoteController/RemoteAdminPlugin.cs
+++ b/OpenSim/ApplicationPlugins/RemoteController/RemoteAdminPlugin.cs
@@ -359,6 +359,42 @@ namespace OpenSim.ApplicationPlugins.RemoteController
notice = false;
}
+ if (startupConfig.GetBoolean("SkipDelayOnEmptyRegion", false))
+ {
+ m_log.Info("[RADMIN]: Counting affected avatars");
+ int agents = 0;
+
+ if (restartAll)
+ {
+ foreach (Scene s in m_application.SceneManager.Scenes)
+ {
+ foreach (ScenePresence sp in s.GetScenePresences())
+ {
+ if (!sp.IsChildAgent && !sp.IsNPC)
+ agents++;
+ }
+ }
+ }
+ else
+ {
+ foreach (ScenePresence sp in rebootedScene.GetScenePresences())
+ {
+ if (!sp.IsChildAgent && !sp.IsNPC)
+ agents++;
+ }
+ }
+
+ m_log.InfoFormat("[RADMIN]: Avatars in region: {0}", agents);
+
+ if (agents == 0)
+ {
+ m_log.Info("[RADMIN]: No avatars detected, shutting down without delay");
+
+ times.Clear();
+ times.Add(0);
+ }
+ }
+
List restartList;
if (restartAll)
@@ -376,10 +412,10 @@ namespace OpenSim.ApplicationPlugins.RemoteController
}
catch (Exception e)
{
-// m_log.ErrorFormat("[RADMIN]: Restart region: failed: {0} {1}", e.Message, e.StackTrace);
+ m_log.ErrorFormat("[RADMIN]: Restart region: failed: {0} {1}", e.Message, e.StackTrace);
responseData["rebooting"] = false;
- throw e;
+ throw;
}
m_log.Info("[RADMIN]: Restart Region request complete");
@@ -3051,15 +3087,13 @@ namespace OpenSim.ApplicationPlugins.RemoteController
///
private void ApplyNextOwnerPermissions(InventoryItemBase item)
{
- if (item.InvType == (int)InventoryType.Object && (item.CurrentPermissions & 7) != 0)
+ if (item.InvType == (int)InventoryType.Object)
{
- if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0)
- item.CurrentPermissions &= ~(uint)PermissionMask.Copy;
- if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0)
- item.CurrentPermissions &= ~(uint)PermissionMask.Transfer;
- if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0)
- item.CurrentPermissions &= ~(uint)PermissionMask.Modify;
+ uint perms = item.CurrentPermissions;
+ PermissionsUtil.ApplyFoldedPermissions(item.CurrentPermissions, ref perms);
+ item.CurrentPermissions = perms;
}
+
item.CurrentPermissions &= item.NextPermissions;
item.BasePermissions &= item.NextPermissions;
item.EveryOnePermissions &= item.NextPermissions;
diff --git a/OpenSim/Capabilities/Handlers/GetTexture/GetTextureHandler.cs b/OpenSim/Capabilities/Handlers/GetTexture/GetTextureHandler.cs
index 062a842748..e73cf9eca0 100644
--- a/OpenSim/Capabilities/Handlers/GetTexture/GetTextureHandler.cs
+++ b/OpenSim/Capabilities/Handlers/GetTexture/GetTextureHandler.cs
@@ -362,8 +362,6 @@ namespace OpenSim.Capabilities.Handlers
{
// Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular data
- imgstream = new MemoryStream();
-
// Decode image to System.Drawing.Image
if (OpenJPEG.DecodeToImage(texture.Data, out managedImage, out image) && image != null)
{
@@ -404,10 +402,7 @@ namespace OpenSim.Capabilities.Handlers
if(managedImage != null)
managedImage.Clear();
if (imgstream != null)
- {
- imgstream.Close();
imgstream.Dispose();
- }
}
return data;
diff --git a/OpenSim/Capabilities/Handlers/GetTexture/GetTextureRobustHandler.cs b/OpenSim/Capabilities/Handlers/GetTexture/GetTextureRobustHandler.cs
index d5df7a29bd..c339ec5d7e 100644
--- a/OpenSim/Capabilities/Handlers/GetTexture/GetTextureRobustHandler.cs
+++ b/OpenSim/Capabilities/Handlers/GetTexture/GetTextureRobustHandler.cs
@@ -368,9 +368,6 @@ namespace OpenSim.Capabilities.Handlers
try
{
// Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular data
-
- imgstream = new MemoryStream();
-
// Decode image to System.Drawing.Image
if (OpenJPEG.DecodeToImage(texture.Data, out managedImage, out image) && image != null)
{
@@ -412,10 +409,7 @@ namespace OpenSim.Capabilities.Handlers
managedImage.Clear();
if (imgstream != null)
- {
- imgstream.Close();
imgstream.Dispose();
- }
}
return data;
diff --git a/OpenSim/Capabilities/Handlers/UploadBakedTexture/UploadBakedTextureHandler.cs b/OpenSim/Capabilities/Handlers/UploadBakedTexture/UploadBakedTextureHandler.cs
index 80b83069e2..48274c1ae5 100644
--- a/OpenSim/Capabilities/Handlers/UploadBakedTexture/UploadBakedTextureHandler.cs
+++ b/OpenSim/Capabilities/Handlers/UploadBakedTexture/UploadBakedTextureHandler.cs
@@ -26,24 +26,12 @@
*/
using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Collections.Specialized;
-using System.Drawing;
-using System.Drawing.Imaging;
using System.Reflection;
-using System.IO;
-using System.Web;
using log4net;
-using Nini.Config;
using OpenMetaverse;
-using OpenMetaverse.StructuredData;
-using OpenMetaverse.Imaging;
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;
@@ -56,13 +44,11 @@ namespace OpenSim.Capabilities.Handlers
private Caps m_HostCapsObj;
private IAssetService m_assetService;
- private bool m_persistBakedTextures;
- public UploadBakedTextureHandler(Caps caps, IAssetService assetService, bool persistBakedTextures)
+ public UploadBakedTextureHandler(Caps caps, IAssetService assetService)
{
m_HostCapsObj = caps;
m_assetService = assetService;
- m_persistBakedTextures = persistBakedTextures;
}
///
@@ -125,9 +111,8 @@ namespace OpenSim.Capabilities.Handlers
asset = new AssetBase(assetID, "Baked Texture", (sbyte)AssetType.Texture, m_HostCapsObj.AgentID.ToString());
asset.Data = data;
asset.Temporary = true;
- asset.Local = !m_persistBakedTextures; // Local assets aren't persisted, non-local are
+ asset.Local = true;
m_assetService.Store(asset);
-
}
}
@@ -151,8 +136,6 @@ namespace OpenSim.Capabilities.Handlers
// m_log.InfoFormat("[CAPS] baked texture upload starting for {0}",newAssetID);
}
-
-
///
/// Handle raw uploaded baked texture data.
///
diff --git a/OpenSim/Capabilities/Handlers/UploadBakedTexture/UploadBakedTextureServerConnector.cs b/OpenSim/Capabilities/Handlers/UploadBakedTexture/UploadBakedTextureServerConnector.cs
index 10ea8eefe6..fd484bad8e 100644
--- a/OpenSim/Capabilities/Handlers/UploadBakedTexture/UploadBakedTextureServerConnector.cs
+++ b/OpenSim/Capabilities/Handlers/UploadBakedTexture/UploadBakedTextureServerConnector.cs
@@ -67,7 +67,7 @@ namespace OpenSim.Capabilities.Handlers
server.AddStreamHandler(new RestStreamHandler(
"POST",
"/CAPS/UploadBakedTexture/",
- new UploadBakedTextureHandler(caps, m_AssetService, true).UploadBakedTexture,
+ new UploadBakedTextureHandler(caps, m_AssetService).UploadBakedTexture,
"UploadBakedTexture",
"Upload Baked Texture Capability"));
diff --git a/OpenSim/Capabilities/LLSD.cs b/OpenSim/Capabilities/LLSD.cs
index c59cede3f4..76e439f9e7 100644
--- a/OpenSim/Capabilities/LLSD.cs
+++ b/OpenSim/Capabilities/LLSD.cs
@@ -566,7 +566,7 @@ namespace OpenSim.Framework.Capabilities
endPos = FindEnd(llsd, 1);
if (Double.TryParse(llsd.Substring(1, endPos - 1), NumberStyles.Float,
- Utils.EnUsCulture.NumberFormat, out value))
+ Culture.NumberFormatInfo, out value))
return value;
else
throw new LLSDParseException("Failed to parse double value type");
diff --git a/OpenSim/Capabilities/LLSDHelpers.cs b/OpenSim/Capabilities/LLSDHelpers.cs
index 8f1a40e632..d5822675ae 100644
--- a/OpenSim/Capabilities/LLSDHelpers.cs
+++ b/OpenSim/Capabilities/LLSDHelpers.cs
@@ -157,6 +157,11 @@ namespace OpenSim.Framework.Capabilities
// the LLSD map/array types in the array need to be deserialised
// but first we need to know the right class to deserialise them into.
}
+ else if(enumerator.Value is Boolean && field.FieldType == typeof(int) )
+ {
+ int i = (bool)enumerator.Value ? 1 : 0;
+ field.SetValue(obj, (object)i);
+ }
else
{
field.SetValue(obj, enumerator.Value);
diff --git a/OpenSim/Data/MySQL/MySQLAssetData.cs b/OpenSim/Data/MySQL/MySQLAssetData.cs
index f16cd913e7..8569c903a6 100644
--- a/OpenSim/Data/MySQL/MySQLAssetData.cs
+++ b/OpenSim/Data/MySQL/MySQLAssetData.cs
@@ -75,6 +75,7 @@ namespace OpenSim.Data.MySQL
dbcon.Open();
Migration m = new Migration(dbcon, Assembly, "AssetStore");
m.Update();
+ dbcon.Close();
}
}
@@ -144,6 +145,7 @@ namespace OpenSim.Data.MySQL
string.Format("[ASSETS DB]: MySql failure fetching asset {0}. Exception ", assetID), e);
}
}
+ dbcon.Close();
}
return asset;
@@ -156,28 +158,27 @@ namespace OpenSim.Data.MySQL
/// On failure : Throw an exception and attempt to reconnect to database
override public bool StoreAsset(AssetBase asset)
{
+ string assetName = asset.Name;
+ if (asset.Name.Length > AssetBase.MAX_ASSET_NAME)
+ {
+ assetName = asset.Name.Substring(0, AssetBase.MAX_ASSET_NAME);
+ m_log.WarnFormat(
+ "[ASSET DB]: Name '{0}' for asset {1} truncated from {2} to {3} characters on add",
+ asset.Name, asset.ID, asset.Name.Length, assetName.Length);
+ }
+
+ string assetDescription = asset.Description;
+ if (asset.Description.Length > AssetBase.MAX_ASSET_DESC)
+ {
+ assetDescription = asset.Description.Substring(0, AssetBase.MAX_ASSET_DESC);
+ m_log.WarnFormat(
+ "[ASSET DB]: Description '{0}' for asset {1} truncated from {2} to {3} characters on add",
+ asset.Description, asset.ID, asset.Description.Length, assetDescription.Length);
+ }
+
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
-
- string assetName = asset.Name;
- if (asset.Name.Length > AssetBase.MAX_ASSET_NAME)
- {
- assetName = asset.Name.Substring(0, AssetBase.MAX_ASSET_NAME);
- m_log.WarnFormat(
- "[ASSET DB]: Name '{0}' for asset {1} truncated from {2} to {3} characters on add",
- asset.Name, asset.ID, asset.Name.Length, assetName.Length);
- }
-
- string assetDescription = asset.Description;
- if (asset.Description.Length > AssetBase.MAX_ASSET_DESC)
- {
- assetDescription = asset.Description.Substring(0, AssetBase.MAX_ASSET_DESC);
- m_log.WarnFormat(
- "[ASSET DB]: Description '{0}' for asset {1} truncated from {2} to {3} characters on add",
- asset.Description, asset.ID, asset.Description.Length, assetDescription.Length);
- }
-
using (MySqlCommand cmd =
new MySqlCommand(
"replace INTO assets(id, name, description, assetType, local, temporary, create_time, access_time, asset_flags, CreatorID, data)" +
@@ -200,15 +201,17 @@ namespace OpenSim.Data.MySQL
cmd.Parameters.AddWithValue("?asset_flags", (int)asset.Flags);
cmd.Parameters.AddWithValue("?data", asset.Data);
cmd.ExecuteNonQuery();
+ dbcon.Close();
return true;
}
catch (Exception e)
{
m_log.ErrorFormat("[ASSET DB]: MySQL failure creating asset {0} with name \"{1}\". Error: {2}",
asset.FullID, asset.Name, e.Message);
+ dbcon.Close();
return false;
}
- }
+ }
}
}
@@ -238,6 +241,7 @@ namespace OpenSim.Data.MySQL
e);
}
}
+ dbcon.Close();
}
}
@@ -270,6 +274,7 @@ namespace OpenSim.Data.MySQL
}
}
}
+ dbcon.Close();
}
bool[] results = new bool[uuids.Length];
@@ -334,6 +339,7 @@ namespace OpenSim.Data.MySQL
e);
}
}
+ dbcon.Close();
}
return retList;
@@ -350,6 +356,7 @@ namespace OpenSim.Data.MySQL
cmd.Parameters.AddWithValue("?id", id);
cmd.ExecuteNonQuery();
}
+ dbcon.Close();
}
return true;
diff --git a/OpenSim/Data/MySQL/MySQLAuthenticationData.cs b/OpenSim/Data/MySQL/MySQLAuthenticationData.cs
index af6be75bf7..fef582e809 100644
--- a/OpenSim/Data/MySQL/MySQLAuthenticationData.cs
+++ b/OpenSim/Data/MySQL/MySQLAuthenticationData.cs
@@ -59,6 +59,7 @@ namespace OpenSim.Data.MySQL
dbcon.Open();
Migration m = new Migration(dbcon, Assembly, "AuthStore");
m.Update();
+ dbcon.Close();
}
}
@@ -76,27 +77,30 @@ namespace OpenSim.Data.MySQL
{
cmd.Parameters.AddWithValue("?principalID", principalID.ToString());
- IDataReader result = cmd.ExecuteReader();
-
- if (result.Read())
+ using(IDataReader result = cmd.ExecuteReader())
{
- ret.PrincipalID = principalID;
-
- CheckColumnNames(result);
-
- foreach (string s in m_ColumnNames)
+ if(result.Read())
{
- if (s == "UUID")
- continue;
+ ret.PrincipalID = principalID;
- ret.Data[s] = result[s].ToString();
+ CheckColumnNames(result);
+
+ foreach(string s in m_ColumnNames)
+ {
+ if(s == "UUID")
+ continue;
+
+ ret.Data[s] = result[s].ToString();
+ }
+
+ dbcon.Close();
+ return ret;
+ }
+ else
+ {
+ dbcon.Close();
+ return null;
}
-
- return ret;
- }
- else
- {
- return null;
}
}
}
diff --git a/OpenSim/Data/MySQL/MySQLEstateData.cs b/OpenSim/Data/MySQL/MySQLEstateData.cs
index a5c8d24de5..eeedf02b29 100644
--- a/OpenSim/Data/MySQL/MySQLEstateData.cs
+++ b/OpenSim/Data/MySQL/MySQLEstateData.cs
@@ -82,6 +82,7 @@ namespace OpenSim.Data.MySQL
Migration m = new Migration(dbcon, Assembly, "EstateStore");
m.Update();
+ dbcon.Close();
Type t = typeof(EstateSettings);
m_Fields = t.GetFields(BindingFlags.NonPublic |
@@ -143,7 +144,6 @@ namespace OpenSim.Data.MySQL
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
-
cmd.Connection = dbcon;
bool found = false;
@@ -171,6 +171,8 @@ namespace OpenSim.Data.MySQL
}
}
}
+ dbcon.Close();
+ cmd.Connection = null;
if (!found && create)
{
@@ -231,6 +233,7 @@ namespace OpenSim.Data.MySQL
es.Save();
}
+ dbcon.Close();
}
}
@@ -263,6 +266,7 @@ namespace OpenSim.Data.MySQL
cmd.ExecuteNonQuery();
}
+ dbcon.Close();
}
SaveBanList(es);
@@ -300,6 +304,7 @@ namespace OpenSim.Data.MySQL
}
}
}
+ dbcon.Close();
}
}
@@ -329,6 +334,7 @@ namespace OpenSim.Data.MySQL
cmd.Parameters.Clear();
}
}
+ dbcon.Close();
}
}
@@ -358,6 +364,7 @@ namespace OpenSim.Data.MySQL
cmd.Parameters.Clear();
}
}
+ dbcon.Close();
}
}
@@ -383,6 +390,7 @@ namespace OpenSim.Data.MySQL
}
}
}
+ dbcon.Close();
}
return uuids.ToArray();
@@ -437,7 +445,6 @@ namespace OpenSim.Data.MySQL
reader.Close();
}
}
-
dbcon.Close();
}
@@ -466,7 +473,6 @@ namespace OpenSim.Data.MySQL
reader.Close();
}
}
-
dbcon.Close();
}
diff --git a/OpenSim/Data/MySQL/MySQLFSAssetData.cs b/OpenSim/Data/MySQL/MySQLFSAssetData.cs
index 2837ce31be..6c486077d3 100644
--- a/OpenSim/Data/MySQL/MySQLFSAssetData.cs
+++ b/OpenSim/Data/MySQL/MySQLFSAssetData.cs
@@ -78,6 +78,7 @@ namespace OpenSim.Data.MySQL
conn.Open();
Migration m = new Migration(conn, Assembly, "FSAssetStore");
m.Update();
+ conn.Close();
}
}
catch (MySqlException e)
@@ -121,9 +122,13 @@ namespace OpenSim.Data.MySQL
}
catch (MySqlException e)
{
+ cmd.Connection = null;
+ conn.Close();
m_log.ErrorFormat("[FSASSETS]: Query {0} failed with {1}", cmd.CommandText, e.ToString());
return false;
}
+ conn.Close();
+ cmd.Connection = null;
}
return true;
@@ -175,7 +180,7 @@ namespace OpenSim.Data.MySQL
UpdateAccessTime(id, AccessTime);
}
}
-
+ conn.Close();
}
return meta;
@@ -206,6 +211,7 @@ namespace OpenSim.Data.MySQL
cmd.Parameters.AddWithValue("?id", AssetID);
cmd.ExecuteNonQuery();
}
+ conn.Close();
}
}
@@ -299,6 +305,7 @@ namespace OpenSim.Data.MySQL
}
}
}
+ conn.Close();
}
for (int i = 0; i < uuids.Length; i++)
@@ -333,6 +340,7 @@ namespace OpenSim.Data.MySQL
count = Convert.ToInt32(reader["count"]);
}
}
+ conn.Close();
}
return count;
@@ -413,8 +421,8 @@ namespace OpenSim.Data.MySQL
imported++;
}
}
-
}
+ importConn.Close();
}
MainConsole.Instance.Output(String.Format("Import done, {0} assets imported", imported));
diff --git a/OpenSim/Data/MySQL/MySQLFramework.cs b/OpenSim/Data/MySQL/MySQLFramework.cs
index 34791cf6be..98106f0057 100644
--- a/OpenSim/Data/MySQL/MySQLFramework.cs
+++ b/OpenSim/Data/MySQL/MySQLFramework.cs
@@ -36,7 +36,7 @@ using MySql.Data.MySqlClient;
namespace OpenSim.Data.MySQL
{
///
- /// A database interface class to a user profile storage system
+ /// Common code for a number of database modules
///
public class MySqlFramework
{
@@ -44,14 +44,24 @@ namespace OpenSim.Data.MySQL
log4net.LogManager.GetLogger(
System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
- protected string m_connectionString;
- protected object m_dbLock = new object();
+ protected string m_connectionString = String.Empty;
+ protected MySqlTransaction m_trans = null;
+ // Constructor using a connection string. Instances constructed
+ // this way will open a new connection for each call.
protected MySqlFramework(string connectionString)
{
m_connectionString = connectionString;
}
+ // Constructor using a connection object. Instances constructed
+ // this way will use the connection object and never create
+ // new connections.
+ protected MySqlFramework(MySqlTransaction trans)
+ {
+ m_trans = trans;
+ }
+
//////////////////////////////////////////////////////////////
//
// All non queries are funneled through one connection
@@ -59,33 +69,53 @@ namespace OpenSim.Data.MySQL
//
protected int ExecuteNonQuery(MySqlCommand cmd)
{
- lock (m_dbLock)
+ if (m_trans == null)
{
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
- try
- {
- dbcon.Open();
- cmd.Connection = dbcon;
-
- try
- {
- return cmd.ExecuteNonQuery();
- }
- catch (Exception e)
- {
- m_log.Error(e.Message, e);
- m_log.Error(Environment.StackTrace.ToString());
- return 0;
- }
- }
- catch (Exception e)
- {
- m_log.Error(e.Message, e);
- return 0;
- }
+ dbcon.Open();
+ int ret = ExecuteNonQueryWithConnection(cmd, dbcon);
+ dbcon.Close();
+ return ret;
}
}
+ else
+ {
+ return ExecuteNonQueryWithTransaction(cmd, m_trans);
+ }
+ }
+
+ private int ExecuteNonQueryWithTransaction(MySqlCommand cmd, MySqlTransaction trans)
+ {
+ cmd.Transaction = trans;
+ return ExecuteNonQueryWithConnection(cmd, trans.Connection);
+ }
+
+ private int ExecuteNonQueryWithConnection(MySqlCommand cmd, MySqlConnection dbcon)
+ {
+ try
+ {
+ cmd.Connection = dbcon;
+
+ try
+ {
+ int ret = cmd.ExecuteNonQuery();
+ cmd.Connection = null;
+ return ret;
+ }
+ catch (Exception e)
+ {
+ m_log.Error(e.Message, e);
+ m_log.Error(Environment.StackTrace.ToString());
+ cmd.Connection = null;
+ return 0;
+ }
+ }
+ catch (Exception e)
+ {
+ m_log.Error(e.Message, e);
+ return 0;
+ }
}
}
-}
\ No newline at end of file
+}
diff --git a/OpenSim/Data/MySQL/MySQLGenericTableHandler.cs b/OpenSim/Data/MySQL/MySQLGenericTableHandler.cs
index 6aae9c644b..9bd3c0cc26 100644
--- a/OpenSim/Data/MySQL/MySQLGenericTableHandler.cs
+++ b/OpenSim/Data/MySQL/MySQLGenericTableHandler.cs
@@ -53,14 +53,27 @@ namespace OpenSim.Data.MySQL
get { return GetType().Assembly; }
}
+ public MySQLGenericTableHandler(MySqlTransaction trans,
+ string realm, string storeName) : base(trans)
+ {
+ m_Realm = realm;
+
+ CommonConstruct(storeName);
+ }
+
public MySQLGenericTableHandler(string connectionString,
string realm, string storeName) : base(connectionString)
{
m_Realm = realm;
- m_connectionString = connectionString;
+ CommonConstruct(storeName);
+ }
+
+ protected void CommonConstruct(string storeName)
+ {
if (storeName != String.Empty)
{
+ // We always use a new connection for any Migrations
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
@@ -110,6 +123,11 @@ namespace OpenSim.Data.MySQL
}
public virtual T[] Get(string[] fields, string[] keys)
+ {
+ return Get(fields, keys, String.Empty);
+ }
+
+ public virtual T[] Get(string[] fields, string[] keys, string options)
{
if (fields.Length != keys.Length)
return new T[0];
@@ -126,8 +144,8 @@ namespace OpenSim.Data.MySQL
string where = String.Join(" and ", terms.ToArray());
- string query = String.Format("select * from {0} where {1}",
- m_Realm, where);
+ string query = String.Format("select * from {0} where {1} {2}",
+ m_Realm, where, options);
cmd.CommandText = query;
@@ -137,75 +155,96 @@ namespace OpenSim.Data.MySQL
protected T[] DoQuery(MySqlCommand cmd)
{
- List result = new List();
-
- using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
+ if (m_trans == null)
{
- dbcon.Open();
- cmd.Connection = dbcon;
-
- using (IDataReader reader = cmd.ExecuteReader())
+ using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
- if (reader == null)
- return new T[0];
-
- CheckColumnNames(reader);
-
- while (reader.Read())
- {
- T row = new T();
-
- foreach (string name in m_Fields.Keys)
- {
- if (reader[name] is DBNull)
- {
- continue;
- }
- if (m_Fields[name].FieldType == typeof(bool))
- {
- int v = Convert.ToInt32(reader[name]);
- m_Fields[name].SetValue(row, v != 0 ? true : false);
- }
- else if (m_Fields[name].FieldType == typeof(UUID))
- {
- m_Fields[name].SetValue(row, DBGuid.FromDB(reader[name]));
- }
- else if (m_Fields[name].FieldType == typeof(int))
- {
- int v = Convert.ToInt32(reader[name]);
- m_Fields[name].SetValue(row, v);
- }
- else if (m_Fields[name].FieldType == typeof(uint))
- {
- uint v = Convert.ToUInt32(reader[name]);
- m_Fields[name].SetValue(row, v);
- }
- else
- {
- m_Fields[name].SetValue(row, reader[name]);
- }
- }
-
- if (m_DataField != null)
- {
- Dictionary data =
- new Dictionary();
-
- foreach (string col in m_ColumnNames)
- {
- data[col] = reader[col].ToString();
- if (data[col] == null)
- data[col] = String.Empty;
- }
-
- m_DataField.SetValue(row, data);
- }
-
- result.Add(row);
- }
+ dbcon.Open();
+ T[] ret = DoQueryWithConnection(cmd, dbcon);
+ dbcon.Close();
+ return ret;
}
}
+ else
+ {
+ return DoQueryWithTransaction(cmd, m_trans);
+ }
+ }
+ protected T[] DoQueryWithTransaction(MySqlCommand cmd, MySqlTransaction trans)
+ {
+ cmd.Transaction = trans;
+
+ return DoQueryWithConnection(cmd, trans.Connection);
+ }
+
+ protected T[] DoQueryWithConnection(MySqlCommand cmd, MySqlConnection dbcon)
+ {
+ List result = new List();
+
+ cmd.Connection = dbcon;
+
+ using (IDataReader reader = cmd.ExecuteReader())
+ {
+ if (reader == null)
+ return new T[0];
+
+ CheckColumnNames(reader);
+
+ while (reader.Read())
+ {
+ T row = new T();
+
+ foreach (string name in m_Fields.Keys)
+ {
+ if (reader[name] is DBNull)
+ {
+ continue;
+ }
+ if (m_Fields[name].FieldType == typeof(bool))
+ {
+ int v = Convert.ToInt32(reader[name]);
+ m_Fields[name].SetValue(row, v != 0 ? true : false);
+ }
+ else if (m_Fields[name].FieldType == typeof(UUID))
+ {
+ m_Fields[name].SetValue(row, DBGuid.FromDB(reader[name]));
+ }
+ else if (m_Fields[name].FieldType == typeof(int))
+ {
+ int v = Convert.ToInt32(reader[name]);
+ m_Fields[name].SetValue(row, v);
+ }
+ else if (m_Fields[name].FieldType == typeof(uint))
+ {
+ uint v = Convert.ToUInt32(reader[name]);
+ m_Fields[name].SetValue(row, v);
+ }
+ else
+ {
+ m_Fields[name].SetValue(row, reader[name]);
+ }
+ }
+
+ if (m_DataField != null)
+ {
+ Dictionary data =
+ new Dictionary();
+
+ foreach (string col in m_ColumnNames)
+ {
+ data[col] = reader[col].ToString();
+ if (data[col] == null)
+ data[col] = String.Empty;
+ }
+
+ m_DataField.SetValue(row, data);
+ }
+
+ result.Add(row);
+ }
+ }
+ cmd.Connection = null;
return result.ToArray();
}
@@ -357,14 +396,26 @@ namespace OpenSim.Data.MySQL
public object DoQueryScalar(MySqlCommand cmd)
{
- using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
+ if (m_trans == null)
{
- dbcon.Open();
- cmd.Connection = dbcon;
+ using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
+ {
+ dbcon.Open();
+ cmd.Connection = dbcon;
+
+ Object ret = cmd.ExecuteScalar();
+ cmd.Connection = null;
+ dbcon.Close();
+ return ret;
+ }
+ }
+ else
+ {
+ cmd.Connection = m_trans.Connection;
+ cmd.Transaction = m_trans;
return cmd.ExecuteScalar();
}
}
-
}
}
diff --git a/OpenSim/Data/MySQL/MySQLInventoryData.cs b/OpenSim/Data/MySQL/MySQLInventoryData.cs
index 382d4a5c33..cc787ccde8 100644
--- a/OpenSim/Data/MySQL/MySQLInventoryData.cs
+++ b/OpenSim/Data/MySQL/MySQLInventoryData.cs
@@ -78,6 +78,7 @@ namespace OpenSim.Data.MySQL
dbcon.Open();
Migration m = new Migration(dbcon, assem, "InventoryStore");
m.Update();
+ dbcon.Close();
}
}
@@ -130,6 +131,7 @@ namespace OpenSim.Data.MySQL
items.Add(item);
}
+ dbcon.Close();
return items;
}
}
@@ -170,6 +172,7 @@ namespace OpenSim.Data.MySQL
while (reader.Read())
items.Add(readInventoryFolder(reader));
+ dbcon.Close();
return items;
}
}
@@ -221,6 +224,7 @@ namespace OpenSim.Data.MySQL
if (items.Count > 0)
rootFolder = items[0];
+ dbcon.Close();
return rootFolder;
}
}
@@ -261,6 +265,7 @@ namespace OpenSim.Data.MySQL
while (reader.Read())
items.Add(readInventoryFolder(reader));
+ dbcon.Close();
return items;
}
}
@@ -352,6 +357,7 @@ namespace OpenSim.Data.MySQL
if (reader.Read())
item = readInventoryItem(reader);
+ dbcon.Close();
return item;
}
}
@@ -417,6 +423,7 @@ namespace OpenSim.Data.MySQL
if (reader.Read())
folder = readInventoryFolder(reader);
+ dbcon.Close();
return folder;
}
}
@@ -504,6 +511,7 @@ namespace OpenSim.Data.MySQL
lock (m_dbLock)
result.ExecuteNonQuery();
}
+ dbcon.Close();
}
}
catch (MySqlException e)
@@ -540,6 +548,7 @@ namespace OpenSim.Data.MySQL
lock (m_dbLock)
cmd.ExecuteNonQuery();
}
+ dbcon.Close();
}
}
catch (MySqlException e)
@@ -600,6 +609,7 @@ namespace OpenSim.Data.MySQL
m_log.Error(e.ToString());
}
}
+ dbcon.Close();
}
}
@@ -643,6 +653,7 @@ namespace OpenSim.Data.MySQL
m_log.Error(e.ToString());
}
}
+ dbcon.Close();
}
}
@@ -806,6 +817,7 @@ namespace OpenSim.Data.MySQL
lock (m_dbLock)
cmd.ExecuteNonQuery();
}
+ dbcon.Close();
}
}
catch (MySqlException e)
@@ -833,6 +845,7 @@ namespace OpenSim.Data.MySQL
lock (m_dbLock)
cmd.ExecuteNonQuery();
}
+ dbcon.Close();
}
}
catch (MySqlException e)
@@ -886,6 +899,7 @@ namespace OpenSim.Data.MySQL
if (item != null)
list.Add(item);
}
+ dbcon.Close();
return list;
}
}
diff --git a/OpenSim/Data/MySQL/MySQLRegionData.cs b/OpenSim/Data/MySQL/MySQLRegionData.cs
index 0e55285451..46df421352 100644
--- a/OpenSim/Data/MySQL/MySQLRegionData.cs
+++ b/OpenSim/Data/MySQL/MySQLRegionData.cs
@@ -60,6 +60,7 @@ namespace OpenSim.Data.MySQL
dbcon.Open();
Migration m = new Migration(dbcon, Assembly, "GridStore");
m.Update();
+ dbcon.Close();
}
}
@@ -260,6 +261,8 @@ namespace OpenSim.Data.MySQL
retList.Add(ret);
}
}
+ cmd.Connection = null;
+ dbcon.Close();
}
return retList;
diff --git a/OpenSim/Data/MySQL/MySQLSimulationData.cs b/OpenSim/Data/MySQL/MySQLSimulationData.cs
index 8278c0ec20..e754522f44 100644
--- a/OpenSim/Data/MySQL/MySQLSimulationData.cs
+++ b/OpenSim/Data/MySQL/MySQLSimulationData.cs
@@ -88,6 +88,7 @@ namespace OpenSim.Data.MySQL
//
Migration m = new Migration(dbcon, Assembly, "RegionStore");
m.Update();
+ dbcon.Close();
}
}
@@ -187,7 +188,7 @@ namespace OpenSim.Data.MySQL
"LinkNumber, MediaURL, KeyframeMotion, AttachedPosX, " +
"AttachedPosY, AttachedPosZ, " +
"PhysicsShapeType, Density, GravityModifier, " +
- "Friction, Restitution, Vehicle, DynAttrs, " +
+ "Friction, Restitution, Vehicle, PhysInertia, DynAttrs, " +
"RotationAxisLocks" +
") values (" + "?UUID, " +
"?CreationDate, ?Name, ?Text, " +
@@ -224,7 +225,7 @@ namespace OpenSim.Data.MySQL
"?LinkNumber, ?MediaURL, ?KeyframeMotion, ?AttachedPosX, " +
"?AttachedPosY, ?AttachedPosZ, " +
"?PhysicsShapeType, ?Density, ?GravityModifier, " +
- "?Friction, ?Restitution, ?Vehicle, ?DynAttrs," +
+ "?Friction, ?Restitution, ?Vehicle, ?PhysInertia, ?DynAttrs," +
"?RotationAxisLocks)";
FillPrimCommand(cmd, prim, obj.UUID, regionUUID);
@@ -261,6 +262,7 @@ namespace OpenSim.Data.MySQL
ExecuteNonQuery(cmd);
}
}
+ dbcon.Close();
}
}
}
@@ -300,6 +302,7 @@ namespace OpenSim.Data.MySQL
cmd.CommandText = "delete from prims where SceneGroupID= ?UUID";
ExecuteNonQuery(cmd);
}
+ dbcon.Close();
}
}
@@ -334,6 +337,7 @@ namespace OpenSim.Data.MySQL
ExecuteNonQuery(cmd);
}
+ dbcon.Close();
}
}
}
@@ -372,6 +376,7 @@ namespace OpenSim.Data.MySQL
ExecuteNonQuery(cmd);
}
+ dbcon.Close();
}
}
}
@@ -411,6 +416,7 @@ namespace OpenSim.Data.MySQL
ExecuteNonQuery(cmd);
}
+ dbcon.Close();
}
}
}
@@ -460,6 +466,7 @@ namespace OpenSim.Data.MySQL
}
}
}
+ dbcon.Close();
}
}
@@ -535,6 +542,7 @@ namespace OpenSim.Data.MySQL
}
}
}
+ dbcon.Close();
}
}
@@ -580,6 +588,7 @@ namespace OpenSim.Data.MySQL
}
}
}
+ dbcon.Close();
}
prim.Inventory.RestoreInventoryItems(inventory);
@@ -598,6 +607,10 @@ namespace OpenSim.Data.MySQL
{
m_log.Info("[REGION DB]: Storing terrain");
+ int terrainDBRevision;
+ Array terrainDBblob;
+ terrData.GetDatabaseBlob(out terrainDBRevision, out terrainDBblob);
+
lock (m_dbLock)
{
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
@@ -617,10 +630,6 @@ namespace OpenSim.Data.MySQL
"Revision, Heightfield) values (?RegionUUID, " +
"?Revision, ?Heightfield)";
- int terrainDBRevision;
- Array terrainDBblob;
- terrData.GetDatabaseBlob(out terrainDBRevision, out terrainDBblob);
-
cmd2.Parameters.AddWithValue("RegionUUID", regionID.ToString());
cmd2.Parameters.AddWithValue("Revision", terrainDBRevision);
cmd2.Parameters.AddWithValue("Heightfield", terrainDBblob);
@@ -634,6 +643,7 @@ namespace OpenSim.Data.MySQL
}
}
}
+ dbcon.Close();
}
}
});
@@ -645,6 +655,10 @@ namespace OpenSim.Data.MySQL
{
m_log.Info("[REGION DB]: Storing Baked terrain");
+ int terrainDBRevision;
+ Array terrainDBblob;
+ terrData.GetDatabaseBlob(out terrainDBRevision, out terrainDBblob);
+
lock (m_dbLock)
{
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
@@ -664,10 +678,6 @@ namespace OpenSim.Data.MySQL
"Revision, Heightfield) values (?RegionUUID, " +
"?Revision, ?Heightfield)";
- int terrainDBRevision;
- Array terrainDBblob;
- terrData.GetDatabaseBlob(out terrainDBRevision, out terrainDBblob);
-
cmd2.Parameters.AddWithValue("RegionUUID", regionID.ToString());
cmd2.Parameters.AddWithValue("Revision", terrainDBRevision);
cmd2.Parameters.AddWithValue("Heightfield", terrainDBblob);
@@ -681,6 +691,7 @@ namespace OpenSim.Data.MySQL
}
}
}
+ dbcon.Close();
}
}
});
@@ -700,9 +711,12 @@ namespace OpenSim.Data.MySQL
public TerrainData LoadTerrain(UUID regionID, int pSizeX, int pSizeY, int pSizeZ)
{
TerrainData terrData = null;
+ byte[] blob = null;
+ int rev = 0;
lock (m_dbLock)
{
+
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
@@ -718,24 +732,29 @@ namespace OpenSim.Data.MySQL
{
while (reader.Read())
{
- int rev = Convert.ToInt32(reader["Revision"]);
+ rev = Convert.ToInt32(reader["Revision"]);
if ((reader["Heightfield"] != DBNull.Value))
{
- byte[] blob = (byte[])reader["Heightfield"];
- terrData = TerrainData.CreateFromDatabaseBlobFactory(pSizeX, pSizeY, pSizeZ, rev, blob);
+ blob = (byte[])reader["Heightfield"];
}
}
}
}
+ dbcon.Close();
}
}
+ if(blob != null)
+ terrData = TerrainData.CreateFromDatabaseBlobFactory(pSizeX, pSizeY, pSizeZ, rev, blob);
+
return terrData;
}
public TerrainData LoadBakedTerrain(UUID regionID, int pSizeX, int pSizeY, int pSizeZ)
{
TerrainData terrData = null;
+ byte[] blob = null;
+ int rev = 0;
lock (m_dbLock)
{
@@ -753,17 +772,19 @@ namespace OpenSim.Data.MySQL
{
while (reader.Read())
{
- int rev = Convert.ToInt32(reader["Revision"]);
+ rev = Convert.ToInt32(reader["Revision"]);
if ((reader["Heightfield"] != DBNull.Value))
{
- byte[] blob = (byte[])reader["Heightfield"];
- terrData = TerrainData.CreateFromDatabaseBlobFactory(pSizeX, pSizeY, pSizeZ, rev, blob);
+ blob = (byte[])reader["Heightfield"];
}
}
}
}
+ dbcon.Close();
}
}
+ if(blob != null)
+ terrData = TerrainData.CreateFromDatabaseBlobFactory(pSizeX, pSizeY, pSizeZ, rev, blob);
return terrData;
}
@@ -783,6 +804,7 @@ namespace OpenSim.Data.MySQL
ExecuteNonQuery(cmd);
}
+ dbcon.Close();
}
}
}
@@ -842,6 +864,7 @@ namespace OpenSim.Data.MySQL
cmd.Parameters.Clear();
}
}
+ dbcon.Close();
}
}
}
@@ -863,82 +886,85 @@ namespace OpenSim.Data.MySQL
cmd.Parameters.AddWithValue("?regionID", regionUUID.ToString());
- IDataReader result = ExecuteReader(cmd);
- if (!result.Read())
+ using(IDataReader result = ExecuteReader(cmd))
{
- //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;
+ 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;
@@ -947,6 +973,7 @@ namespace OpenSim.Data.MySQL
public virtual RegionSettings LoadRegionSettings(UUID regionUUID)
{
RegionSettings rs = null;
+ bool needStore = false;
lock (m_dbLock)
{
@@ -972,13 +999,17 @@ namespace OpenSim.Data.MySQL
rs.RegionUUID = regionUUID;
rs.OnSave += StoreRegionSettings;
- StoreRegionSettings(rs);
+ needStore = true;
}
}
}
+ dbcon.Close();
}
}
+ if(needStore)
+ StoreRegionSettings(rs);
+
LoadSpawnPoints(rs);
return rs;
@@ -992,31 +1023,32 @@ namespace OpenSim.Data.MySQL
using (MySqlCommand cmd = dbcon.CreateCommand())
{
- cmd.CommandText = "REPLACE INTO `regionwindlight` (`region_id`, `water_color_r`, `water_color_g`, ";
- cmd.CommandText += "`water_color_b`, `water_fog_density_exponent`, `underwater_fog_modifier`, ";
- cmd.CommandText += "`reflection_wavelet_scale_1`, `reflection_wavelet_scale_2`, `reflection_wavelet_scale_3`, ";
- cmd.CommandText += "`fresnel_scale`, `fresnel_offset`, `refract_scale_above`, `refract_scale_below`, ";
- cmd.CommandText += "`blur_multiplier`, `big_wave_direction_x`, `big_wave_direction_y`, `little_wave_direction_x`, ";
- cmd.CommandText += "`little_wave_direction_y`, `normal_map_texture`, `horizon_r`, `horizon_g`, `horizon_b`, ";
- cmd.CommandText += "`horizon_i`, `haze_horizon`, `blue_density_r`, `blue_density_g`, `blue_density_b`, ";
- cmd.CommandText += "`blue_density_i`, `haze_density`, `density_multiplier`, `distance_multiplier`, `max_altitude`, ";
- cmd.CommandText += "`sun_moon_color_r`, `sun_moon_color_g`, `sun_moon_color_b`, `sun_moon_color_i`, `sun_moon_position`, ";
- cmd.CommandText += "`ambient_r`, `ambient_g`, `ambient_b`, `ambient_i`, `east_angle`, `sun_glow_focus`, `sun_glow_size`, ";
- cmd.CommandText += "`scene_gamma`, `star_brightness`, `cloud_color_r`, `cloud_color_g`, `cloud_color_b`, `cloud_color_i`, ";
- cmd.CommandText += "`cloud_x`, `cloud_y`, `cloud_density`, `cloud_coverage`, `cloud_scale`, `cloud_detail_x`, ";
- cmd.CommandText += "`cloud_detail_y`, `cloud_detail_density`, `cloud_scroll_x`, `cloud_scroll_x_lock`, `cloud_scroll_y`, ";
- cmd.CommandText += "`cloud_scroll_y_lock`, `draw_classic_clouds`) VALUES (?region_id, ?water_color_r, ";
- cmd.CommandText += "?water_color_g, ?water_color_b, ?water_fog_density_exponent, ?underwater_fog_modifier, ?reflection_wavelet_scale_1, ";
- cmd.CommandText += "?reflection_wavelet_scale_2, ?reflection_wavelet_scale_3, ?fresnel_scale, ?fresnel_offset, ?refract_scale_above, ";
- cmd.CommandText += "?refract_scale_below, ?blur_multiplier, ?big_wave_direction_x, ?big_wave_direction_y, ?little_wave_direction_x, ";
- cmd.CommandText += "?little_wave_direction_y, ?normal_map_texture, ?horizon_r, ?horizon_g, ?horizon_b, ?horizon_i, ?haze_horizon, ";
- cmd.CommandText += "?blue_density_r, ?blue_density_g, ?blue_density_b, ?blue_density_i, ?haze_density, ?density_multiplier, ";
- cmd.CommandText += "?distance_multiplier, ?max_altitude, ?sun_moon_color_r, ?sun_moon_color_g, ?sun_moon_color_b, ";
- cmd.CommandText += "?sun_moon_color_i, ?sun_moon_position, ?ambient_r, ?ambient_g, ?ambient_b, ?ambient_i, ?east_angle, ";
- cmd.CommandText += "?sun_glow_focus, ?sun_glow_size, ?scene_gamma, ?star_brightness, ?cloud_color_r, ?cloud_color_g, ";
- cmd.CommandText += "?cloud_color_b, ?cloud_color_i, ?cloud_x, ?cloud_y, ?cloud_density, ?cloud_coverage, ?cloud_scale, ";
- cmd.CommandText += "?cloud_detail_x, ?cloud_detail_y, ?cloud_detail_density, ?cloud_scroll_x, ?cloud_scroll_x_lock, ";
- cmd.CommandText += "?cloud_scroll_y, ?cloud_scroll_y_lock, ?draw_classic_clouds)";
+ 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);
@@ -1084,6 +1116,7 @@ namespace OpenSim.Data.MySQL
ExecuteNonQuery(cmd);
}
+ dbcon.Close();
}
}
@@ -1099,6 +1132,7 @@ namespace OpenSim.Data.MySQL
cmd.Parameters.AddWithValue("?regionID", regionID.ToString());
ExecuteNonQuery(cmd);
}
+ dbcon.Close();
}
}
@@ -1117,14 +1151,19 @@ namespace OpenSim.Data.MySQL
cmd.Parameters.AddWithValue("?region_id", regionUUID.ToString());
- IDataReader result = ExecuteReader(cmd);
- if (!result.Read())
+ using(IDataReader result = ExecuteReader(cmd))
{
- return String.Empty;
- }
- else
- {
- return Convert.ToString(result["llsd_settings"]);
+ if(!result.Read())
+ {
+ dbcon.Close();
+ return String.Empty;
+ }
+ else
+ {
+ string ret = Convert.ToString(result["llsd_settings"]);
+ dbcon.Close();
+ return ret;
+ }
}
}
}
@@ -1145,6 +1184,7 @@ namespace OpenSim.Data.MySQL
ExecuteNonQuery(cmd);
}
+ dbcon.Close();
}
}
@@ -1160,6 +1200,7 @@ namespace OpenSim.Data.MySQL
cmd.Parameters.AddWithValue("?region_id", regionUUID.ToString());
ExecuteNonQuery(cmd);
}
+ dbcon.Close();
}
}
#endregion
@@ -1212,7 +1253,7 @@ namespace OpenSim.Data.MySQL
FillRegionSettingsCommand(cmd, rs);
ExecuteNonQuery(cmd);
}
-
+ dbcon.Close();
SaveSpawnPoints(rs);
}
}
@@ -1259,6 +1300,7 @@ namespace OpenSim.Data.MySQL
}
}
}
+ dbcon.Close();
}
}
@@ -1452,6 +1494,11 @@ namespace OpenSim.Data.MySQL
prim.VehicleParams = vehicle;
}
+ PhysicsInertiaData pdata = null;
+ if (row["PhysInertia"].ToString() != String.Empty)
+ pdata = PhysicsInertiaData.FromXml2(row["PhysInertia"].ToString());
+ prim.PhysicsInertia = pdata;
+
return prim;
}
@@ -1810,6 +1857,11 @@ namespace OpenSim.Data.MySQL
else
cmd.Parameters.AddWithValue("KeyframeMotion", new Byte[0]);
+ if (prim.PhysicsInertia != null)
+ cmd.Parameters.AddWithValue("PhysInertia", prim.PhysicsInertia.ToXml2());
+ else
+ cmd.Parameters.AddWithValue("PhysInertia", String.Empty);
+
if (prim.VehicleParams != null)
cmd.Parameters.AddWithValue("Vehicle", prim.VehicleParams.ToXml2());
else
@@ -2113,6 +2165,7 @@ namespace OpenSim.Data.MySQL
ExecuteNonQuery(cmd);
}
}
+ dbcon.Close();
}
}
}
@@ -2142,6 +2195,7 @@ namespace OpenSim.Data.MySQL
}
}
}
+ dbcon.Close();
}
}
@@ -2177,6 +2231,7 @@ namespace OpenSim.Data.MySQL
}
}
}
+ dbcon.Close();
}
}
}
@@ -2211,6 +2266,7 @@ namespace OpenSim.Data.MySQL
cmd.Parameters.Clear();
}
}
+ dbcon.Close();
}
}
}
@@ -2230,6 +2286,7 @@ namespace OpenSim.Data.MySQL
cmd.ExecuteNonQuery();
}
+ dbcon.Close();
}
}
@@ -2247,6 +2304,7 @@ namespace OpenSim.Data.MySQL
cmd.ExecuteNonQuery();
}
+ dbcon.Close();
}
}
@@ -2270,6 +2328,7 @@ namespace OpenSim.Data.MySQL
}
}
}
+ dbcon.Close();
}
return ret;
diff --git a/OpenSim/Data/MySQL/MySQLUserProfilesData.cs b/OpenSim/Data/MySQL/MySQLUserProfilesData.cs
index 8af2a3ef29..c98e0173a2 100644
--- a/OpenSim/Data/MySQL/MySQLUserProfilesData.cs
+++ b/OpenSim/Data/MySQL/MySQLUserProfilesData.cs
@@ -69,6 +69,7 @@ namespace OpenSim.Data.MySQL
Migration m = new Migration(dbcon, Assembly, "UserProfiles");
m.Update();
+ dbcon.Close();
}
}
#endregion Member Functions
@@ -89,7 +90,7 @@ namespace OpenSim.Data.MySQL
using (MySqlConnection dbcon = new MySqlConnection(ConnectionString))
{
- string query = "SELECT classifieduuid, name FROM classifieds WHERE creatoruuid = ?Id";
+ const string query = "SELECT classifieduuid, name FROM classifieds WHERE creatoruuid = ?Id";
dbcon.Open();
using (MySqlCommand cmd = new MySqlCommand(query, dbcon))
{
@@ -121,58 +122,58 @@ namespace OpenSim.Data.MySQL
}
}
}
+ dbcon.Close();
}
return data;
}
public bool UpdateClassifiedRecord(UserClassifiedAdd ad, ref string result)
{
- string query = string.Empty;
-
-
- query += "INSERT INTO classifieds (";
- query += "`classifieduuid`,";
- query += "`creatoruuid`,";
- query += "`creationdate`,";
- query += "`expirationdate`,";
- query += "`category`,";
- query += "`name`,";
- query += "`description`,";
- query += "`parceluuid`,";
- query += "`parentestate`,";
- query += "`snapshotuuid`,";
- query += "`simname`,";
- query += "`posglobal`,";
- query += "`parcelname`,";
- query += "`classifiedflags`,";
- query += "`priceforlisting`) ";
- query += "VALUES (";
- query += "?ClassifiedId,";
- query += "?CreatorId,";
- query += "?CreatedDate,";
- query += "?ExpirationDate,";
- query += "?Category,";
- query += "?Name,";
- query += "?Description,";
- query += "?ParcelId,";
- query += "?ParentEstate,";
- query += "?SnapshotId,";
- query += "?SimName,";
- query += "?GlobalPos,";
- query += "?ParcelName,";
- query += "?Flags,";
- query += "?ListingPrice ) ";
- query += "ON DUPLICATE KEY UPDATE ";
- query += "category=?Category, ";
- query += "expirationdate=?ExpirationDate, ";
- query += "name=?Name, ";
- query += "description=?Description, ";
- query += "parentestate=?ParentEstate, ";
- query += "posglobal=?GlobalPos, ";
- query += "parcelname=?ParcelName, ";
- query += "classifiedflags=?Flags, ";
- query += "priceforlisting=?ListingPrice, ";
- query += "snapshotuuid=?SnapshotId";
+ const string query =
+ "INSERT INTO classifieds ("
+ + "`classifieduuid`,"
+ + "`creatoruuid`,"
+ + "`creationdate`,"
+ + "`expirationdate`,"
+ + "`category`,"
+ + "`name`,"
+ + "`description`,"
+ + "`parceluuid`,"
+ + "`parentestate`,"
+ + "`snapshotuuid`,"
+ + "`simname`,"
+ + "`posglobal`,"
+ + "`parcelname`,"
+ + "`classifiedflags`,"
+ + "`priceforlisting`) "
+ + "VALUES ("
+ + "?ClassifiedId,"
+ + "?CreatorId,"
+ + "?CreatedDate,"
+ + "?ExpirationDate,"
+ + "?Category,"
+ + "?Name,"
+ + "?Description,"
+ + "?ParcelId,"
+ + "?ParentEstate,"
+ + "?SnapshotId,"
+ + "?SimName,"
+ + "?GlobalPos,"
+ + "?ParcelName,"
+ + "?Flags,"
+ + "?ListingPrice ) "
+ + "ON DUPLICATE KEY UPDATE "
+ + "category=?Category, "
+ + "expirationdate=?ExpirationDate, "
+ + "name=?Name, "
+ + "description=?Description, "
+ + "parentestate=?ParentEstate, "
+ + "posglobal=?GlobalPos, "
+ + "parcelname=?ParcelName, "
+ + "classifiedflags=?Flags, "
+ + "priceforlisting=?ListingPrice, "
+ + "snapshotuuid=?SnapshotId"
+ ;
if(string.IsNullOrEmpty(ad.ParcelName))
ad.ParcelName = "Unknown";
@@ -228,6 +229,7 @@ namespace OpenSim.Data.MySQL
cmd.ExecuteNonQuery();
}
+ dbcon.Close();
}
}
catch (Exception e)
@@ -242,10 +244,7 @@ namespace OpenSim.Data.MySQL
public bool DeleteClassifiedRecord(UUID recordId)
{
- string query = string.Empty;
-
- query += "DELETE FROM classifieds WHERE ";
- query += "classifieduuid = ?recordId";
+ const string query = "DELETE FROM classifieds WHERE classifieduuid = ?recordId";
try
{
@@ -258,6 +257,7 @@ namespace OpenSim.Data.MySQL
cmd.Parameters.AddWithValue("?recordId", recordId.ToString());
cmd.ExecuteNonQuery();
}
+ dbcon.Close();
}
}
catch (Exception e)
@@ -271,10 +271,8 @@ namespace OpenSim.Data.MySQL
public bool GetClassifiedInfo(ref UserClassifiedAdd ad, ref string result)
{
- string query = string.Empty;
- query += "SELECT * FROM classifieds WHERE ";
- query += "classifieduuid = ?AdId";
+ const string query = "SELECT * FROM classifieds WHERE classifieduuid = ?AdId";
try
{
@@ -322,10 +320,8 @@ namespace OpenSim.Data.MySQL
#region Picks Queries
public OSDArray GetAvatarPicks(UUID avatarId)
{
- string query = string.Empty;
+ const string query = "SELECT `pickuuid`,`name` FROM userpicks WHERE creatoruuid = ?Id";
- query += "SELECT `pickuuid`,`name` FROM userpicks WHERE ";
- query += "creatoruuid = ?Id";
OSDArray data = new OSDArray();
try
@@ -352,6 +348,7 @@ namespace OpenSim.Data.MySQL
}
}
}
+ dbcon.Close();
}
}
catch (Exception e)
@@ -364,12 +361,8 @@ namespace OpenSim.Data.MySQL
public UserProfilePick GetPickInfo(UUID avatarId, UUID pickId)
{
- string query = string.Empty;
UserProfilePick pick = new UserProfilePick();
-
- query += "SELECT * FROM userpicks WHERE ";
- query += "creatoruuid = ?CreatorId AND ";
- query += "pickuuid = ?PickId";
+ const string query = "SELECT * FROM userpicks WHERE creatoruuid = ?CreatorId AND pickuuid = ?PickId";
try
{
@@ -422,33 +415,33 @@ namespace OpenSim.Data.MySQL
public bool UpdatePicksRecord(UserProfilePick pick)
{
- string query = string.Empty;
-
- query += "INSERT INTO userpicks VALUES (";
- query += "?PickId,";
- query += "?CreatorId,";
- query += "?TopPick,";
- query += "?ParcelId,";
- query += "?Name,";
- query += "?Desc,";
- query += "?SnapshotId,";
- query += "?User,";
- query += "?Original,";
- query += "?SimName,";
- query += "?GlobalPos,";
- query += "?SortOrder,";
- query += "?Enabled,";
- query += "?Gatekeeper)";
- query += "ON DUPLICATE KEY UPDATE ";
- query += "parceluuid=?ParcelId,";
- query += "name=?Name,";
- query += "description=?Desc,";
- query += "user=?User,";
- query += "simname=?SimName,";
- query += "snapshotuuid=?SnapshotId,";
- query += "pickuuid=?PickId,";
- query += "posglobal=?GlobalPos,";
- query += "gatekeeper=?Gatekeeper";
+ const string query =
+ "INSERT INTO userpicks VALUES ("
+ + "?PickId,"
+ + "?CreatorId,"
+ + "?TopPick,"
+ + "?ParcelId,"
+ + "?Name,"
+ + "?Desc,"
+ + "?SnapshotId,"
+ + "?User,"
+ + "?Original,"
+ + "?SimName,"
+ + "?GlobalPos,"
+ + "?SortOrder,"
+ + "?Enabled,"
+ + "?Gatekeeper)"
+ + "ON DUPLICATE KEY UPDATE "
+ + "parceluuid=?ParcelId,"
+ + "name=?Name,"
+ + "description=?Desc,"
+ + "user=?User,"
+ + "simname=?SimName,"
+ + "snapshotuuid=?SnapshotId,"
+ + "pickuuid=?PickId,"
+ + "posglobal=?GlobalPos,"
+ + "gatekeeper=?Gatekeeper"
+ ;
try
{
@@ -474,6 +467,7 @@ namespace OpenSim.Data.MySQL
cmd.ExecuteNonQuery();
}
+ dbcon.Close();
}
}
catch (Exception e)
@@ -487,10 +481,7 @@ namespace OpenSim.Data.MySQL
public bool DeletePicksRecord(UUID pickId)
{
- string query = string.Empty;
-
- query += "DELETE FROM userpicks WHERE ";
- query += "pickuuid = ?PickId";
+ string query = "DELETE FROM userpicks WHERE pickuuid = ?PickId";
try
{
@@ -504,6 +495,7 @@ namespace OpenSim.Data.MySQL
cmd.ExecuteNonQuery();
}
+ dbcon.Close();
}
}
catch (Exception e)
@@ -519,11 +511,7 @@ namespace OpenSim.Data.MySQL
#region Avatar Notes Queries
public bool GetAvatarNotes(ref UserProfileNotes notes)
{ // WIP
- string query = string.Empty;
-
- query += "SELECT `notes` FROM usernotes WHERE ";
- query += "useruuid = ?Id AND ";
- query += "targetuuid = ?TargetId";
+ const string query = "SELECT `notes` FROM usernotes WHERE useruuid = ?Id AND targetuuid = ?TargetId";
try
{
@@ -548,6 +536,7 @@ namespace OpenSim.Data.MySQL
}
}
}
+ dbcon.Close();
}
}
catch (Exception e)
@@ -560,26 +549,25 @@ namespace OpenSim.Data.MySQL
public bool UpdateAvatarNotes(ref UserProfileNotes note, ref string result)
{
- string query = string.Empty;
+ string query;
bool remove;
if(string.IsNullOrEmpty(note.Notes))
{
remove = true;
- query += "DELETE FROM usernotes WHERE ";
- query += "useruuid=?UserId AND ";
- query += "targetuuid=?TargetId";
+ query = "DELETE FROM usernotes WHERE useruuid=?UserId AND targetuuid=?TargetId";
}
else
{
remove = false;
- query += "INSERT INTO usernotes VALUES ( ";
- query += "?UserId,";
- query += "?TargetId,";
- query += "?Notes )";
- query += "ON DUPLICATE KEY ";
- query += "UPDATE ";
- query += "notes=?Notes";
+ query = "INSERT INTO usernotes VALUES ("
+ + "?UserId,"
+ + "?TargetId,"
+ + "?Notes )"
+ + "ON DUPLICATE KEY "
+ + "UPDATE "
+ + "notes=?Notes"
+ ;
}
try
@@ -596,6 +584,7 @@ namespace OpenSim.Data.MySQL
cmd.ExecuteNonQuery();
}
+ dbcon.Close();
}
}
catch (Exception e)
@@ -612,10 +601,7 @@ namespace OpenSim.Data.MySQL
#region Avatar Properties
public bool GetAvatarProperties(ref UserProfileProperties props, ref string result)
{
- string query = string.Empty;
-
- query += "SELECT * FROM userprofile WHERE ";
- query += "useruuid = ?Id";
+ string query = "SELECT * FROM userprofile WHERE useruuid = ?Id";
try
{
@@ -664,35 +650,36 @@ namespace OpenSim.Data.MySQL
props.PublishProfile = false;
props.PublishMature = false;
- query = "INSERT INTO userprofile (";
- query += "useruuid, ";
- query += "profilePartner, ";
- query += "profileAllowPublish, ";
- query += "profileMaturePublish, ";
- query += "profileURL, ";
- query += "profileWantToMask, ";
- query += "profileWantToText, ";
- query += "profileSkillsMask, ";
- query += "profileSkillsText, ";
- query += "profileLanguages, ";
- query += "profileImage, ";
- query += "profileAboutText, ";
- query += "profileFirstImage, ";
- query += "profileFirstText) VALUES (";
- query += "?userId, ";
- query += "?profilePartner, ";
- query += "?profileAllowPublish, ";
- query += "?profileMaturePublish, ";
- query += "?profileURL, ";
- query += "?profileWantToMask, ";
- query += "?profileWantToText, ";
- query += "?profileSkillsMask, ";
- query += "?profileSkillsText, ";
- query += "?profileLanguages, ";
- query += "?profileImage, ";
- query += "?profileAboutText, ";
- query += "?profileFirstImage, ";
- query += "?profileFirstText)";
+ query = "INSERT INTO userprofile ("
+ + "useruuid, "
+ + "profilePartner, "
+ + "profileAllowPublish, "
+ + "profileMaturePublish, "
+ + "profileURL, "
+ + "profileWantToMask, "
+ + "profileWantToText, "
+ + "profileSkillsMask, "
+ + "profileSkillsText, "
+ + "profileLanguages, "
+ + "profileImage, "
+ + "profileAboutText, "
+ + "profileFirstImage, "
+ + "profileFirstText) VALUES ("
+ + "?userId, "
+ + "?profilePartner, "
+ + "?profileAllowPublish, "
+ + "?profileMaturePublish, "
+ + "?profileURL, "
+ + "?profileWantToMask, "
+ + "?profileWantToText, "
+ + "?profileSkillsMask, "
+ + "?profileSkillsText, "
+ + "?profileLanguages, "
+ + "?profileImage, "
+ + "?profileAboutText, "
+ + "?profileFirstImage, "
+ + "?profileFirstText)"
+ ;
dbcon.Close();
dbcon.Open();
@@ -719,6 +706,7 @@ namespace OpenSim.Data.MySQL
}
}
}
+ dbcon.Close();
}
}
catch (Exception e)
@@ -733,15 +721,10 @@ namespace OpenSim.Data.MySQL
public bool UpdateAvatarProperties(ref UserProfileProperties props, ref string result)
{
- string query = string.Empty;
-
- query += "UPDATE userprofile SET ";
- query += "profileURL=?profileURL, ";
- query += "profileImage=?image, ";
- query += "profileAboutText=?abouttext,";
- query += "profileFirstImage=?firstlifeimage,";
- query += "profileFirstText=?firstlifetext ";
- query += "WHERE useruuid=?uuid";
+ const string query = "UPDATE userprofile SET profileURL=?profileURL,"
+ + "profileImage=?image, profileAboutText=?abouttext,"
+ + "profileFirstImage=?firstlifeimage, profileFirstText=?firstlifetext "
+ + "WHERE useruuid=?uuid";
try
{
@@ -759,6 +742,7 @@ namespace OpenSim.Data.MySQL
cmd.ExecuteNonQuery();
}
+ dbcon.Close();
}
}
catch (Exception e)
@@ -775,15 +759,13 @@ namespace OpenSim.Data.MySQL
#region Avatar Interests
public bool UpdateAvatarInterests(UserProfileProperties up, ref string result)
{
- string query = string.Empty;
-
- query += "UPDATE userprofile SET ";
- query += "profileWantToMask=?WantMask, ";
- query += "profileWantToText=?WantText,";
- query += "profileSkillsMask=?SkillsMask,";
- query += "profileSkillsText=?SkillsText, ";
- query += "profileLanguages=?Languages ";
- query += "WHERE useruuid=?uuid";
+ const string query = "UPDATE userprofile SET "
+ + "profileWantToMask=?WantMask, "
+ + "profileWantToText=?WantText,"
+ + "profileSkillsMask=?SkillsMask,"
+ + "profileSkillsText=?SkillsText, "
+ + "profileLanguages=?Languages "
+ + "WHERE useruuid=?uuid";
try
{
@@ -817,18 +799,17 @@ namespace OpenSim.Data.MySQL
public OSDArray GetUserImageAssets(UUID avatarId)
{
OSDArray data = new OSDArray();
- string query = "SELECT `snapshotuuid` FROM {0} WHERE `creatoruuid` = ?Id";
+ const string queryA = "SELECT `snapshotuuid` FROM {0} WHERE `creatoruuid` = ?Id";
// Get classified image assets
-
try
{
using (MySqlConnection dbcon = new MySqlConnection(ConnectionString))
{
dbcon.Open();
- using (MySqlCommand cmd = new MySqlCommand(string.Format (query,"`classifieds`"), dbcon))
+ using (MySqlCommand cmd = new MySqlCommand(string.Format (queryA,"`classifieds`"), dbcon))
{
cmd.Parameters.AddWithValue("?Id", avatarId.ToString());
@@ -847,7 +828,7 @@ namespace OpenSim.Data.MySQL
dbcon.Close();
dbcon.Open();
- using (MySqlCommand cmd = new MySqlCommand(string.Format (query,"`userpicks`"), dbcon))
+ using (MySqlCommand cmd = new MySqlCommand(string.Format (queryA,"`userpicks`"), dbcon))
{
cmd.Parameters.AddWithValue("?Id", avatarId.ToString());
@@ -866,9 +847,9 @@ namespace OpenSim.Data.MySQL
dbcon.Close();
dbcon.Open();
- query = "SELECT `profileImage`, `profileFirstImage` FROM `userprofile` WHERE `useruuid` = ?Id";
+ const string queryB = "SELECT `profileImage`, `profileFirstImage` FROM `userprofile` WHERE `useruuid` = ?Id";
- using (MySqlCommand cmd = new MySqlCommand(string.Format (query,"`userpicks`"), dbcon))
+ using (MySqlCommand cmd = new MySqlCommand(string.Format (queryB,"`userpicks`"), dbcon))
{
cmd.Parameters.AddWithValue("?Id", avatarId.ToString());
@@ -884,6 +865,7 @@ namespace OpenSim.Data.MySQL
}
}
}
+ dbcon.Close();
}
}
catch (Exception e)
@@ -897,11 +879,7 @@ namespace OpenSim.Data.MySQL
#region User Preferences
public bool GetUserPreferences(ref UserPreferences pref, ref string result)
{
- string query = string.Empty;
-
- query += "SELECT imviaemail,visible,email FROM ";
- query += "usersettings WHERE ";
- query += "useruuid = ?Id";
+ const string query = "SELECT imviaemail,visible,email FROM usersettings WHERE useruuid = ?Id";
try
{
@@ -925,10 +903,9 @@ namespace OpenSim.Data.MySQL
dbcon.Close();
dbcon.Open();
- query = "INSERT INTO usersettings VALUES ";
- query += "(?uuid,'false','false', ?Email)";
+ const string queryB = "INSERT INTO usersettings VALUES (?uuid,'false','false', ?Email)";
- using (MySqlCommand put = new MySqlCommand(query, dbcon))
+ using (MySqlCommand put = new MySqlCommand(queryB, dbcon))
{
put.Parameters.AddWithValue("?Email", pref.EMail);
@@ -939,6 +916,7 @@ namespace OpenSim.Data.MySQL
}
}
}
+ dbcon.Close();
}
}
catch (Exception e)
@@ -953,13 +931,9 @@ namespace OpenSim.Data.MySQL
public bool UpdateUserPreferences(ref UserPreferences pref, ref string result)
{
- string query = string.Empty;
-
- query += "UPDATE usersettings SET ";
- query += "imviaemail=?ImViaEmail, ";
- query += "visible=?Visible, ";
- query += "email=?EMail ";
- query += "WHERE useruuid=?uuid";
+ const string query = "UPDATE usersettings SET imviaemail=?ImViaEmail,"
+ + "visible=?Visible, email=?EMail "
+ + "WHERE useruuid=?uuid";
try
{
@@ -975,6 +949,7 @@ namespace OpenSim.Data.MySQL
cmd.ExecuteNonQuery();
}
+ dbcon.Close();
}
}
catch (Exception e)
@@ -991,11 +966,7 @@ namespace OpenSim.Data.MySQL
#region Integration
public bool GetUserAppData(ref UserAppData props, ref string result)
{
- string query = string.Empty;
-
- query += "SELECT * FROM `userdata` WHERE ";
- query += "UserId = ?Id AND ";
- query += "TagId = ?TagId";
+ const string query = "SELECT * FROM `userdata` WHERE UserId = ?Id AND TagId = ?TagId";
try
{
@@ -1017,13 +988,8 @@ namespace OpenSim.Data.MySQL
}
else
{
- query += "INSERT INTO userdata VALUES ( ";
- query += "?UserId,";
- query += "?TagId,";
- query += "?DataKey,";
- query += "?DataVal) ";
-
- using (MySqlCommand put = new MySqlCommand(query, dbcon))
+ const string queryB = "INSERT INTO userdata VALUES (?UserId, ?TagId, ?DataKey, ?DataVal)";
+ using (MySqlCommand put = new MySqlCommand(queryB, dbcon))
{
put.Parameters.AddWithValue("?UserId", props.UserId.ToString());
put.Parameters.AddWithValue("?TagId", props.TagId.ToString());
@@ -1035,6 +1001,7 @@ namespace OpenSim.Data.MySQL
}
}
}
+ dbcon.Close();
}
}
catch (Exception e)
@@ -1049,14 +1016,7 @@ namespace OpenSim.Data.MySQL
public bool SetUserAppData(UserAppData props, ref string result)
{
- string query = string.Empty;
-
- query += "UPDATE userdata SET ";
- query += "TagId = ?TagId, ";
- query += "DataKey = ?DataKey, ";
- query += "DataVal = ?DataVal WHERE ";
- query += "UserId = ?UserId AND ";
- query += "TagId = ?TagId";
+ const string query = "UPDATE userdata SET TagId = ?TagId, DataKey = ?DataKey, DataVal = ?DataVal WHERE UserId = ?UserId AND TagId = ?TagId";
try
{
@@ -1072,6 +1032,7 @@ namespace OpenSim.Data.MySQL
cmd.ExecuteNonQuery();
}
+ dbcon.Close();
}
}
catch (Exception e)
diff --git a/OpenSim/Data/MySQL/MySQLXAssetData.cs b/OpenSim/Data/MySQL/MySQLXAssetData.cs
index 2c6acdef32..9f9c9cf4fa 100644
--- a/OpenSim/Data/MySQL/MySQLXAssetData.cs
+++ b/OpenSim/Data/MySQL/MySQLXAssetData.cs
@@ -97,6 +97,7 @@ namespace OpenSim.Data.MySQL
dbcon.Open();
Migration m = new Migration(dbcon, Assembly, "XAssetStore");
m.Update();
+ dbcon.Close();
}
}
@@ -130,6 +131,7 @@ namespace OpenSim.Data.MySQL
// m_log.DebugFormat("[MYSQL XASSET DATA]: Looking for asset {0}", assetID);
AssetBase asset = null;
+ int accessTime = 0;
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
@@ -140,7 +142,6 @@ namespace OpenSim.Data.MySQL
dbcon))
{
cmd.Parameters.AddWithValue("?ID", assetID.ToString());
-
try
{
using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
@@ -159,23 +160,7 @@ namespace OpenSim.Data.MySQL
asset.Temporary = Convert.ToBoolean(dbReader["Temporary"]);
asset.Flags = (AssetFlags)Convert.ToInt32(dbReader["AssetFlags"]);
-
- if (m_enableCompression)
- {
- using (GZipStream decompressionStream = new GZipStream(new MemoryStream(asset.Data), CompressionMode.Decompress))
- {
- MemoryStream outputStream = new MemoryStream();
- WebUtil.CopyStream(decompressionStream, outputStream, int.MaxValue);
-// int compressedLength = asset.Data.Length;
- asset.Data = outputStream.ToArray();
-
-// m_log.DebugFormat(
-// "[XASSET DB]: Decompressed {0} {1} to {2} bytes from {3}",
-// asset.ID, asset.Name, asset.Data.Length, compressedLength);
- }
- }
-
- UpdateAccessTime(asset.Metadata, (int)dbReader["AccessTime"]);
+ accessTime = (int)dbReader["AccessTime"];
}
}
}
@@ -184,9 +169,38 @@ namespace OpenSim.Data.MySQL
m_log.Error(string.Format("[MYSQL XASSET DATA]: Failure fetching asset {0}", assetID), e);
}
}
+ dbcon.Close();
}
- return asset;
+ if(asset == null)
+ return asset;
+
+ if(accessTime > 0)
+ {
+ try
+ {
+ UpdateAccessTime(asset.Metadata, accessTime);
+ }
+ catch { }
+ }
+
+ if (m_enableCompression && asset.Data != null)
+ {
+ using(MemoryStream ms = new MemoryStream(asset.Data))
+ using(GZipStream decompressionStream = new GZipStream(ms, CompressionMode.Decompress))
+ {
+ using(MemoryStream outputStream = new MemoryStream())
+ {
+ decompressionStream.CopyTo(outputStream, int.MaxValue);
+// int compressedLength = asset.Data.Length;
+ asset.Data = outputStream.ToArray();
+ }
+// m_log.DebugFormat(
+// "[XASSET DB]: Decompressed {0} {1} to {2} bytes from {3}",
+// asset.ID, asset.Name, asset.Data.Length, compressedLength);
+ }
+ }
+ return asset;
}
///
@@ -303,6 +317,7 @@ namespace OpenSim.Data.MySQL
transaction.Commit();
}
+ dbcon.Close();
}
}
@@ -344,6 +359,7 @@ namespace OpenSim.Data.MySQL
"[XASSET MYSQL DB]: Failure updating access_time for asset {0} with name {1}",
assetMetadata.ID, assetMetadata.Name);
}
+ dbcon.Close();
}
}
@@ -474,6 +490,7 @@ namespace OpenSim.Data.MySQL
m_log.Error("[XASSETS DB]: MySql failure fetching asset set" + Environment.NewLine + e.ToString());
}
}
+ dbcon.Close();
}
return retList;
@@ -492,9 +509,9 @@ namespace OpenSim.Data.MySQL
cmd.Parameters.AddWithValue("?ID", id);
cmd.ExecuteNonQuery();
}
-
// TODO: How do we deal with data from deleted assets? Probably not easily reapable unless we
// keep a reference count (?)
+ dbcon.Close();
}
return true;
diff --git a/OpenSim/Data/MySQL/MySQLXInventoryData.cs b/OpenSim/Data/MySQL/MySQLXInventoryData.cs
index 4e41fec9cd..501999425d 100644
--- a/OpenSim/Data/MySQL/MySQLXInventoryData.cs
+++ b/OpenSim/Data/MySQL/MySQLXInventoryData.cs
@@ -328,7 +328,6 @@ namespace OpenSim.Data.MySQL
{
return false;
}
- cmd.Dispose();
}
dbcon.Close();
diff --git a/OpenSim/Data/MySQL/Resources/RegionStore.migrations b/OpenSim/Data/MySQL/Resources/RegionStore.migrations
index c63cc95d22..0577392184 100644
--- a/OpenSim/Data/MySQL/Resources/RegionStore.migrations
+++ b/OpenSim/Data/MySQL/Resources/RegionStore.migrations
@@ -461,3 +461,9 @@ BEGIN;
ALTER TABLE `prims` ADD COLUMN `RezzerID` char(36) DEFAULT NULL;
COMMIT;
+
+:VERSION 57 #----- Add physics inertia data
+
+BEGIN;
+ALTER TABLE `prims` ADD COLUMN `PhysInertia` TEXT default NULL;
+COMMIT;
diff --git a/OpenSim/Data/MySQL/Resources/os_groups_Store.migrations b/OpenSim/Data/MySQL/Resources/os_groups_Store.migrations
index 1a499000fb..6ec89144b5 100644
--- a/OpenSim/Data/MySQL/Resources/os_groups_Store.migrations
+++ b/OpenSim/Data/MySQL/Resources/os_groups_Store.migrations
@@ -18,7 +18,7 @@ CREATE TABLE `os_groups_groups` (
PRIMARY KEY (`GroupID`),
UNIQUE KEY `Name` (`Name`),
FULLTEXT KEY `Name_2` (`Name`)
-) ENGINE=InnoDB;
+) ENGINE=MyISAM;
CREATE TABLE `os_groups_membership` (
diff --git a/OpenSim/Data/PGSQL/PGSQLGroupsData.cs b/OpenSim/Data/PGSQL/PGSQLGroupsData.cs
index 6ef576bccc..f398256863 100755
--- a/OpenSim/Data/PGSQL/PGSQLGroupsData.cs
+++ b/OpenSim/Data/PGSQL/PGSQLGroupsData.cs
@@ -435,7 +435,7 @@ namespace OpenSim.Data.PGSQL
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
- cmd.CommandText = String.Format("delete from {0} where \"TMStamp\" < CURRENT_DATE - INTERVAL '2 week'", m_Realm);
+ cmd.CommandText = String.Format("delete from {0} where \"TMStamp\"::abstime::timestamp < now() - INTERVAL '2 week'", m_Realm);
ExecuteNonQuery(cmd);
}
@@ -461,7 +461,7 @@ namespace OpenSim.Data.PGSQL
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
- cmd.CommandText = String.Format("delete from {0} where \"TMStamp\" < CURRENT_DATE - INTERVAL '2 week'", m_Realm);
+ cmd.CommandText = String.Format("delete from {0} where \"TMStamp\"::abstime::timestamp < now() - INTERVAL '2 week'", m_Realm);
ExecuteNonQuery(cmd);
}
diff --git a/OpenSim/Data/PGSQL/PGSQLSimulationData.cs b/OpenSim/Data/PGSQL/PGSQLSimulationData.cs
index 33d12bd71e..f4af40ba88 100755
--- a/OpenSim/Data/PGSQL/PGSQLSimulationData.cs
+++ b/OpenSim/Data/PGSQL/PGSQLSimulationData.cs
@@ -350,10 +350,11 @@ namespace OpenSim.Data.PGSQL
""CameraEyeOffsetY"" = :CameraEyeOffsetY, ""CameraEyeOffsetZ"" = :CameraEyeOffsetZ, ""CameraAtOffsetX"" = :CameraAtOffsetX,
""CameraAtOffsetY"" = :CameraAtOffsetY, ""CameraAtOffsetZ"" = :CameraAtOffsetZ, ""ForceMouselook"" = :ForceMouselook,
""ScriptAccessPin"" = :ScriptAccessPin, ""AllowedDrop"" = :AllowedDrop, ""DieAtEdge"" = :DieAtEdge, ""SalePrice"" = :SalePrice,
- ""SaleType"" = :SaleType, ""ColorR"" = :ColorR, ""ColorG"" = :ColorG, ""ColorB"" = :ColorB, ""ColorA"" = :ColorA, ""ParticleSystem"" = :ParticleSystem,
+ ""PhysicsShapeType"" = :PhysicsShapeType, ""Density"" = :Density, ""GravityModifier"" = :GravityModifier, ""Friction"" = :Friction, ""Restitution"" = :Restitution,
+ ""PassCollisions"" = :PassCollisions, ""RotationAxisLocks"" = :RotationAxisLocks, ""RezzerID"" = :RezzerID,
""ClickAction"" = :ClickAction, ""Material"" = :Material, ""CollisionSound"" = :CollisionSound, ""CollisionSoundVolume"" = :CollisionSoundVolume, ""PassTouches"" = :PassTouches,
""LinkNumber"" = :LinkNumber, ""MediaURL"" = :MediaURL, ""DynAttrs"" = :DynAttrs,
- ""PhysicsShapeType"" = :PhysicsShapeType, ""Density"" = :Density, ""GravityModifier"" = :GravityModifier, ""Friction"" = :Friction, ""Restitution"" = :Restitution
+ ""PhysInertia"" = :PhysInertia
WHERE ""UUID"" = :UUID ;
INSERT INTO
@@ -367,7 +368,7 @@ namespace OpenSim.Data.PGSQL
""OmegaY"", ""OmegaZ"", ""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""
+ ""PhysicsShapeType"", ""Density"", ""GravityModifier"", ""Friction"", ""Restitution"", ""PassCollisions"", ""RotationAxisLocks"", ""RezzerID"" , ""PhysInertia""
) Select
:UUID, :CreationDate, :Name, :Text, :Description, :SitName, :TouchName, :ObjectFlags, :OwnerMask, :NextOwnerMask, :GroupMask,
:EveryoneMask, :BaseMask, :PositionX, :PositionY, :PositionZ, :GroupPositionX, :GroupPositionY, :GroupPositionZ, :VelocityX,
@@ -378,7 +379,7 @@ namespace OpenSim.Data.PGSQL
:OmegaY, :OmegaZ, :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
+ :PhysicsShapeType, :Density, :GravityModifier, :Friction, :Restitution, :PassCollisions, :RotationAxisLocks, :RezzerID, :PhysInertia
where not EXISTS (SELECT ""UUID"" FROM prims WHERE ""UUID"" = :UUID);
";
@@ -1678,6 +1679,12 @@ namespace OpenSim.Data.PGSQL
prim.OwnerID = new UUID((Guid)primRow["OwnerID"]);
prim.GroupID = new UUID((Guid)primRow["GroupID"]);
prim.LastOwnerID = new UUID((Guid)primRow["LastOwnerID"]);
+
+ if (primRow["RezzerID"] != DBNull.Value)
+ prim.RezzerID = new UUID((Guid)primRow["RezzerID"]);
+ else
+ prim.RezzerID = UUID.Zero;
+
prim.OwnerMask = Convert.ToUInt32(primRow["OwnerMask"]);
prim.NextOwnerMask = Convert.ToUInt32(primRow["NextOwnerMask"]);
prim.GroupMask = Convert.ToUInt32(primRow["GroupMask"]);
@@ -1782,6 +1789,7 @@ namespace OpenSim.Data.PGSQL
prim.CollisionSoundVolume = Convert.ToSingle(primRow["CollisionSoundVolume"]);
prim.PassTouches = (bool)primRow["PassTouches"];
+ prim.PassCollisions = (bool)primRow["PassCollisions"];
if (!(primRow["MediaURL"] is System.DBNull))
prim.MediaUrl = (string)primRow["MediaURL"];
@@ -1796,6 +1804,13 @@ namespace OpenSim.Data.PGSQL
prim.GravityModifier = Convert.ToSingle(primRow["GravityModifier"]);
prim.Friction = Convert.ToSingle(primRow["Friction"]);
prim.Restitution = Convert.ToSingle(primRow["Restitution"]);
+ prim.RotationAxisLocks = Convert.ToByte(primRow["RotationAxisLocks"]);
+
+
+ PhysicsInertiaData pdata = null;
+ if (!(primRow["PhysInertia"] is System.DBNull))
+ pdata = PhysicsInertiaData.FromXml2(primRow["PhysInertia"].ToString());
+ prim.PhysicsInertia = pdata;
return prim;
}
@@ -2097,6 +2112,7 @@ namespace OpenSim.Data.PGSQL
parameters.Add(_Database.CreateParameter("OwnerID", prim.OwnerID));
parameters.Add(_Database.CreateParameter("GroupID", prim.GroupID));
parameters.Add(_Database.CreateParameter("LastOwnerID", prim.LastOwnerID));
+ parameters.Add(_Database.CreateParameter("RezzerID", prim.RezzerID));
parameters.Add(_Database.CreateParameter("OwnerMask", prim.OwnerMask));
parameters.Add(_Database.CreateParameter("NextOwnerMask", prim.NextOwnerMask));
parameters.Add(_Database.CreateParameter("GroupMask", prim.GroupMask));
@@ -2196,10 +2212,28 @@ namespace OpenSim.Data.PGSQL
parameters.Add(_Database.CreateParameter("CollisionSound", prim.CollisionSound));
parameters.Add(_Database.CreateParameter("CollisionSoundVolume", prim.CollisionSoundVolume));
- parameters.Add(_Database.CreateParameter("PassTouches", prim.PassTouches));
+ parameters.Add(_Database.CreateParameter("PassTouches", (bool)prim.PassTouches));
+ parameters.Add(_Database.CreateParameter("PassCollisions", (bool)prim.PassCollisions));
+
+
+ if (prim.PassTouches)
+ parameters.Add(_Database.CreateParameter("PassTouches", true));
+ else
+ parameters.Add(_Database.CreateParameter("PassTouches", false));
+
+ if (prim.PassCollisions)
+ parameters.Add(_Database.CreateParameter("PassCollisions", true));
+ else
+ parameters.Add(_Database.CreateParameter("PassCollisions", false));
parameters.Add(_Database.CreateParameter("LinkNumber", prim.LinkNum));
parameters.Add(_Database.CreateParameter("MediaURL", prim.MediaUrl));
+
+ if (prim.PhysicsInertia != null)
+ parameters.Add(_Database.CreateParameter("PhysInertia", prim.PhysicsInertia.ToXml2()));
+ else
+ parameters.Add(_Database.CreateParameter("PhysInertia", String.Empty));
+
if (prim.DynAttrs.CountNamespaces > 0)
parameters.Add(_Database.CreateParameter("DynAttrs", prim.DynAttrs.ToXml()));
@@ -2211,12 +2245,13 @@ namespace OpenSim.Data.PGSQL
parameters.Add(_Database.CreateParameter("GravityModifier", (double)prim.GravityModifier));
parameters.Add(_Database.CreateParameter("Friction", (double)prim.Friction));
parameters.Add(_Database.CreateParameter("Restitution", (double)prim.Restitution));
+ parameters.Add(_Database.CreateParameter("RotationAxisLocks", prim.RotationAxisLocks));
return parameters.ToArray();
}
///
- /// Creates the primshape parameters for stroing in DB.
+ /// Creates the primshape parameters for storing in DB.
///
/// Basic data of SceneObjectpart prim.
/// The scene group ID.
diff --git a/OpenSim/Data/PGSQL/PGSQLXAssetData.cs b/OpenSim/Data/PGSQL/PGSQLXAssetData.cs
index 6e884898f5..1798d20508 100644
--- a/OpenSim/Data/PGSQL/PGSQLXAssetData.cs
+++ b/OpenSim/Data/PGSQL/PGSQLXAssetData.cs
@@ -173,16 +173,18 @@ namespace OpenSim.Data.PGSQL
if (m_enableCompression)
{
- using (GZipStream decompressionStream = new GZipStream(new MemoryStream(asset.Data), CompressionMode.Decompress))
+ using(MemoryStream ms = new MemoryStream(asset.Data))
+ using(GZipStream decompressionStream = new GZipStream(ms, CompressionMode.Decompress))
{
- MemoryStream outputStream = new MemoryStream();
- WebUtil.CopyStream(decompressionStream, outputStream, int.MaxValue);
- // int compressedLength = asset.Data.Length;
- asset.Data = outputStream.ToArray();
-
- // m_log.DebugFormat(
- // "[XASSET DB]: Decompressed {0} {1} to {2} bytes from {3}",
- // asset.ID, asset.Name, asset.Data.Length, compressedLength);
+ using(MemoryStream outputStream = new MemoryStream())
+ {
+ decompressionStream.CopyTo(outputStream,int.MaxValue);
+ // int compressedLength = asset.Data.Length;
+ asset.Data = outputStream.ToArray();
+ }
+ // m_log.DebugFormat(
+ // "[XASSET DB]: Decompressed {0} {1} to {2} bytes from {3}",
+ // asset.ID, asset.Name, asset.Data.Length, compressedLength);
}
}
diff --git a/OpenSim/Data/PGSQL/PGSQLXInventoryData.cs b/OpenSim/Data/PGSQL/PGSQLXInventoryData.cs
index 55a1996f51..4c10ac99b7 100644
--- a/OpenSim/Data/PGSQL/PGSQLXInventoryData.cs
+++ b/OpenSim/Data/PGSQL/PGSQLXInventoryData.cs
@@ -206,7 +206,7 @@ namespace OpenSim.Data.PGSQL
cmd.CommandText = String.Format(@"select bit_or(""inventoryCurrentPermissions"") as ""inventoryCurrentPermissions""
from inventoryitems
where ""avatarID""::uuid = :PrincipalID
- and ""assetID"" = :AssetID
+ and ""assetID""::uuid = :AssetID
group by ""assetID"" ");
cmd.Parameters.Add(m_database.CreateParameter("PrincipalID", principalID));
diff --git a/OpenSim/Data/PGSQL/Resources/AgentPrefs.migrations b/OpenSim/Data/PGSQL/Resources/AgentPrefs.migrations
new file mode 100644
index 0000000000..ca3cca21f6
--- /dev/null
+++ b/OpenSim/Data/PGSQL/Resources/AgentPrefs.migrations
@@ -0,0 +1,19 @@
+:VERSION 1
+
+BEGIN TRANSACTION;
+
+CREATE TABLE IF NOT EXISTS "public"."agentprefs" (
+ "PrincipalID" uuid NOT NULL,
+ "AccessPrefs" char(2) NOT NULL DEFAULT 'M'::bpchar COLLATE "default",
+ "HoverHeight" float8 NOT NULL DEFAULT 0,
+ "Language" char(5) NOT NULL DEFAULT 'en-us'::bpchar COLLATE "default",
+ "LanguageIsPublic" bool NOT NULL DEFAULT true,
+ "PermEveryone" int4 NOT NULL DEFAULT 0,
+ "PermGroup" int4 NOT NULL DEFAULT 0,
+ "PermNextOwner" int4 NOT NULL DEFAULT 532480
+)
+WITH (OIDS=FALSE);
+
+ALTER TABLE "public"."agentprefs" ADD PRIMARY KEY ("PrincipalID") NOT DEFERRABLE INITIALLY IMMEDIATE;
+
+COMMIT;
diff --git a/OpenSim/Data/PGSQL/Resources/EstateStore.migrations b/OpenSim/Data/PGSQL/Resources/EstateStore.migrations
index 59270f8b01..63b70bd555 100644
--- a/OpenSim/Data/PGSQL/Resources/EstateStore.migrations
+++ b/OpenSim/Data/PGSQL/Resources/EstateStore.migrations
@@ -1,307 +1,112 @@
-:VERSION 1
+:VERSION 12
BEGIN TRANSACTION;
-CREATE TABLE estate_managers(
- "EstateID" int NOT NULL Primary Key,
- uuid varchar(36) NOT NULL
- );
-
-CREATE TABLE estate_groups(
- "EstateID" int NOT NULL,
- uuid varchar(36) NOT NULL
- );
+-- ----------------------------
+-- Table structure for estate_groups
+-- ----------------------------
+CREATE TABLE IF NOT EXISTS "public"."estate_groups" (
+ "EstateID" int4 NOT NULL,
+ "uuid" uuid NOT NULL
+)
+WITH (OIDS=FALSE);
+-- Indexes structure for table estate_groups
+-- ----------------------------
+CREATE INDEX IF NOT EXISTS "ix_estate_groups" ON "public"."estate_groups" USING btree("EstateID" "pg_catalog"."int4_ops" ASC NULLS LAST);
-CREATE TABLE estate_users(
- "EstateID" int NOT NULL,
- uuid varchar(36) NOT NULL
- );
+-- ----------------------------
+-- Table structure for estate_managers
+-- ----------------------------
+CREATE TABLE IF NOT EXISTS "public"."estate_managers" (
+ "EstateID" int4 NOT NULL,
+ "uuid" uuid NOT NULL
+)
+WITH (OIDS=FALSE);
+-- Indexes structure for table estate_managers
+-- ----------------------------
+CREATE INDEX IF NOT EXISTS "ix_estate_managers" ON "public"."estate_managers" USING btree("EstateID" "pg_catalog"."int4_ops" ASC NULLS LAST);
-CREATE TABLE estateban(
- "EstateID" int NOT NULL,
- "bannedUUID" varchar(36) NOT NULL,
- "bannedIp" varchar(16) NOT NULL,
- "bannedIpHostMask" varchar(16) NOT NULL,
- "bannedNameMask" varchar(64) NULL DEFAULT NULL
- );
+-- ----------------------------
+-- Table structure for estate_map
+-- ----------------------------
+CREATE TABLE IF NOT EXISTS "public"."estate_map" (
+ "RegionID" uuid NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000'::uuid,
+ "EstateID" int4 NOT NULL
+)
+WITH (OIDS=FALSE);
-Create Sequence estate_settings_id increment by 100 start with 100;
+-- Primary key structure for table estate_map
+-- ----------------------------
+ALTER TABLE "public"."estate_map" ADD PRIMARY KEY ("RegionID") NOT DEFERRABLE INITIALLY IMMEDIATE;
-CREATE TABLE estate_settings(
- "EstateID" integer DEFAULT nextval('estate_settings_id') NOT NULL,
- "EstateName" varchar(64) NULL DEFAULT (NULL),
- "AbuseEmailToEstateOwner" boolean NOT NULL,
- "DenyAnonymous" boolean NOT NULL,
- "ResetHomeOnTeleport" boolean NOT NULL,
- "FixedSun" boolean NOT NULL,
- "DenyTransacted" boolean NOT NULL,
- "BlockDwell" boolean NOT NULL,
- "DenyIdentified" boolean NOT NULL,
- "AllowVoice" boolean NOT NULL,
- "UseGlobalTime" boolean NOT NULL,
- "PricePerMeter" int NOT NULL,
- "TaxFree" boolean NOT NULL,
- "AllowDirectTeleport" boolean NOT NULL,
- "RedirectGridX" int NOT NULL,
- "RedirectGridY" int NOT NULL,
- "ParentEstateID" int NOT NULL,
- "SunPosition" double precision NOT NULL,
- "EstateSkipScripts" boolean NOT NULL,
- "BillableFactor" double precision NOT NULL,
- "PublicAccess" boolean NOT NULL,
- "AbuseEmail" varchar(255) NOT NULL,
- "EstateOwner" varchar(36) NOT NULL,
- "DenyMinors" boolean NOT NULL
- );
-
-
-CREATE TABLE estate_map(
- "RegionID" varchar(36) NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000'),
- "EstateID" int NOT NULL
- );
-
-COMMIT;
-
-:VERSION 2
-
-BEGIN TRANSACTION;
-
-CREATE INDEX IX_estate_managers ON estate_managers
- (
- "EstateID"
- );
-
-
-CREATE INDEX IX_estate_groups ON estate_groups
- (
- "EstateID"
- );
-
-
-CREATE INDEX IX_estate_users ON estate_users
- (
- "EstateID"
- );
-
-COMMIT;
-
-:VERSION 3
-
-BEGIN TRANSACTION;
-
-CREATE TABLE Tmp_estateban
- (
- "EstateID" int NOT NULL,
- "bannedUUID" varchar(36) NOT NULL,
- "bannedIp" varchar(16) NULL,
- "bannedIpHostMask" varchar(16) NULL,
- "bannedNameMask" varchar(64) NULL
- );
-
- INSERT INTO Tmp_estateban ("EstateID", "bannedUUID", "bannedIp", "bannedIpHostMask", "bannedNameMask")
- SELECT "EstateID", "bannedUUID", "bannedIp", "bannedIpHostMask", "bannedNameMask" FROM estateban;
-
-DROP TABLE estateban;
-
-Alter table Tmp_estateban
- rename to estateban;
-
-CREATE INDEX IX_estateban ON estateban
- (
- "EstateID"
- );
-
-COMMIT;
-
-
-:VERSION 4
-
-BEGIN TRANSACTION;
-
-CREATE TABLE Tmp_estate_managers
- (
- "EstateID" int NOT NULL,
- uuid uuid NOT NULL
- );
-
-INSERT INTO Tmp_estate_managers ("EstateID", uuid)
- SELECT "EstateID", cast(uuid as uuid) FROM estate_managers;
-
-DROP TABLE estate_managers;
-
-Alter table Tmp_estate_managers
- rename to estate_managers;
-
-CREATE INDEX IX_estate_managers ON estate_managers
- (
- "EstateID"
- );
-
-COMMIT;
-
-
-:VERSION 5
-
-BEGIN TRANSACTION;
-
-CREATE TABLE Tmp_estate_groups
- (
- "EstateID" int NOT NULL,
- uuid uuid NOT NULL
- ) ;
-
- INSERT INTO Tmp_estate_groups ("EstateID", uuid)
- SELECT "EstateID", cast(uuid as uuid) FROM estate_groups;
-
-DROP TABLE estate_groups;
-
-Alter table Tmp_estate_groups
- rename to estate_groups;
-
-CREATE INDEX IX_estate_groups ON estate_groups
- (
- "EstateID"
- );
-
-COMMIT;
-
-
-:VERSION 6
-
-BEGIN TRANSACTION;
-
-CREATE TABLE Tmp_estate_users
- (
- "EstateID" int NOT NULL,
- uuid uuid NOT NULL
- );
-
-INSERT INTO Tmp_estate_users ("EstateID", uuid)
- SELECT "EstateID", cast(uuid as uuid) FROM estate_users ;
-
-DROP TABLE estate_users;
-
-Alter table Tmp_estate_users
- rename to estate_users;
-
-CREATE INDEX IX_estate_users ON estate_users
- (
- "EstateID"
- );
-
-COMMIT;
-
-
-:VERSION 7
-
-BEGIN TRANSACTION;
-
-CREATE TABLE Tmp_estateban
- (
- "EstateID" int NOT NULL,
- "bannedUUID" uuid NOT NULL,
- "bannedIp" varchar(16) NULL,
- "bannedIpHostMask" varchar(16) NULL,
- "bannedNameMask" varchar(64) NULL
- );
-
-INSERT INTO Tmp_estateban ("EstateID", "bannedUUID", "bannedIp", "bannedIpHostMask", "bannedNameMask")
- SELECT "EstateID", cast("bannedUUID" as uuid), "bannedIp", "bannedIpHostMask", "bannedNameMask" FROM estateban ;
-
-DROP TABLE estateban;
-
-Alter table Tmp_estateban
- rename to estateban;
-
-CREATE INDEX IX_estateban ON estateban
- (
- "EstateID"
- );
-
-COMMIT;
-
-
-:VERSION 8
-
-BEGIN TRANSACTION;
-
-CREATE TABLE Tmp_estate_settings
- (
- "EstateID" integer default nextval('estate_settings_id') NOT NULL,
- "EstateName" varchar(64) NULL DEFAULT (NULL),
- "AbuseEmailToEstateOwner" boolean NOT NULL,
- "DenyAnonymous" boolean NOT NULL,
- "ResetHomeOnTeleport" boolean NOT NULL,
- "FixedSun" boolean NOT NULL,
- "DenyTransacted" boolean NOT NULL,
- "BlockDwell" boolean NOT NULL,
- "DenyIdentified" boolean NOT NULL,
- "AllowVoice" boolean NOT NULL,
- "UseGlobalTime" boolean NOT NULL,
- "PricePerMeter" int NOT NULL,
- "TaxFree" boolean NOT NULL,
- "AllowDirectTeleport" boolean NOT NULL,
- "RedirectGridX" int NOT NULL,
- "RedirectGridY" int NOT NULL,
- "ParentEstateID" int NOT NULL,
- "SunPosition" double precision NOT NULL,
- "EstateSkipScripts" boolean NOT NULL,
- "BillableFactor" double precision NOT NULL,
- "PublicAccess" boolean NOT NULL,
- "AbuseEmail" varchar(255) NOT NULL,
+-- ----------------------------
+-- Table structure for estate_settings
+-- ----------------------------
+CREATE TABLE IF NOT EXISTS "public"."estate_settings" (
+ "EstateID" int4 NOT NULL DEFAULT nextval('estate_settings_id'::regclass),
+ "EstateName" varchar(64) DEFAULT NULL::character varying COLLATE "default",
+ "AbuseEmailToEstateOwner" bool NOT NULL,
+ "DenyAnonymous" bool NOT NULL,
+ "ResetHomeOnTeleport" bool NOT NULL,
+ "FixedSun" bool NOT NULL,
+ "DenyTransacted" bool NOT NULL,
+ "BlockDwell" bool NOT NULL,
+ "DenyIdentified" bool NOT NULL,
+ "AllowVoice" bool NOT NULL,
+ "UseGlobalTime" bool NOT NULL,
+ "PricePerMeter" int4 NOT NULL,
+ "TaxFree" bool NOT NULL,
+ "AllowDirectTeleport" bool NOT NULL,
+ "RedirectGridX" int4 NOT NULL,
+ "RedirectGridY" int4 NOT NULL,
+ "ParentEstateID" int4 NOT NULL,
+ "SunPosition" float8 NOT NULL,
+ "EstateSkipScripts" bool NOT NULL,
+ "BillableFactor" float8 NOT NULL,
+ "PublicAccess" bool NOT NULL,
+ "AbuseEmail" varchar(255) NOT NULL COLLATE "default",
"EstateOwner" uuid NOT NULL,
- "DenyMinors" boolean NOT NULL
- );
+ "DenyMinors" bool NOT NULL,
+ "AllowLandmark" bool NOT NULL DEFAULT true,
+ "AllowParcelChanges" bool NOT NULL DEFAULT true,
+ "AllowSetHome" bool NOT NULL DEFAULT true
+)
+WITH (OIDS=FALSE);
-INSERT INTO Tmp_estate_settings ("EstateID", "EstateName", "AbuseEmailToEstateOwner", "DenyAnonymous", "ResetHomeOnTeleport", "FixedSun", "DenyTransacted", "BlockDwell", "DenyIdentified", "AllowVoice", "UseGlobalTime", "PricePerMeter", "TaxFree", "AllowDirectTeleport", "RedirectGridX", "RedirectGridY", "ParentEstateID", "SunPosition", "EstateSkipScripts", "BillableFactor", "PublicAccess", "AbuseEmail", "EstateOwner", "DenyMinors")
- SELECT "EstateID", "EstateName", "AbuseEmailToEstateOwner", "DenyAnonymous", "ResetHomeOnTeleport", "FixedSun", "DenyTransacted", "BlockDwell", "DenyIdentified", "AllowVoice", "UseGlobalTime", "PricePerMeter", "TaxFree", "AllowDirectTeleport", "RedirectGridX", "RedirectGridY", "ParentEstateID", "SunPosition", "EstateSkipScripts", "BillableFactor", "PublicAccess", "AbuseEmail", cast("EstateOwner" as uuid), "DenyMinors" FROM estate_settings ;
+-- Primary key structure for table estate_settings
+-- ----------------------------
+ALTER TABLE "public"."estate_settings" ADD PRIMARY KEY ("EstateID") NOT DEFERRABLE INITIALLY IMMEDIATE;
-DROP TABLE estate_settings;
+-- ----------------------------
+-- Table structure for estate_users
+-- ----------------------------
+CREATE TABLE IF NOT EXISTS "public"."estate_users" (
+ "EstateID" int4 NOT NULL,
+ "uuid" uuid NOT NULL
+)
+WITH (OIDS=FALSE);
+-- Indexes structure for table estate_users
+-- ----------------------------
+CREATE INDEX IF NOT EXISTS "ix_estate_users" ON "public"."estate_users" USING btree("EstateID" "pg_catalog"."int4_ops" ASC NULLS LAST);
-Alter table Tmp_estate_settings
- rename to estate_settings;
+-- ----------------------------
+-- Table structure for estateban
+-- ----------------------------
+CREATE TABLE IF NOT EXISTS "public"."estateban" (
+ "EstateID" int4 NOT NULL,
+ "bannedUUID" uuid NOT NULL,
+ "bannedIp" varchar(16) COLLATE "default",
+ "bannedIpHostMask" varchar(16) COLLATE "default",
+ "bannedNameMask" varchar(64) COLLATE "default"
+)
+WITH (OIDS=FALSE);
-
-Create index on estate_settings (lower("EstateName"));
+-- Indexes structure for table estateban
+-- ----------------------------
+CREATE INDEX IF NOT EXISTS "ix_estateban" ON "public"."estateban" USING btree("EstateID" "pg_catalog"."int4_ops" ASC NULLS LAST);
COMMIT;
-
-:VERSION 9
-
-BEGIN TRANSACTION;
-
-CREATE TABLE Tmp_estate_map
- (
- "RegionID" uuid NOT NULL DEFAULT ('00000000-0000-0000-0000-000000000000'),
- "EstateID" int NOT NULL
- );
-
-INSERT INTO Tmp_estate_map ("RegionID", "EstateID")
- SELECT cast("RegionID" as uuid), "EstateID" FROM estate_map ;
-
-DROP TABLE estate_map;
-
-Alter table Tmp_estate_map
- rename to estate_map;
-
-COMMIT;
-
-:VERSION 10
-
-BEGIN TRANSACTION;
-ALTER TABLE estate_settings ADD COLUMN "AllowLandmark" boolean NOT NULL default true;
-ALTER TABLE estate_settings ADD COLUMN "AllowParcelChanges" boolean NOT NULL default true;
-ALTER TABLE estate_settings ADD COLUMN "AllowSetHome" boolean NOT NULL default true;
-COMMIT;
-
-:VERSION 11
-
-Begin transaction;
-
-
-Commit;
-
diff --git a/OpenSim/Data/PGSQL/Resources/RegionStore.migrations b/OpenSim/Data/PGSQL/Resources/RegionStore.migrations
index c08593917d..fcefb6baa3 100644
--- a/OpenSim/Data/PGSQL/Resources/RegionStore.migrations
+++ b/OpenSim/Data/PGSQL/Resources/RegionStore.migrations
@@ -1195,3 +1195,33 @@ CREATE TABLE bakedterrain
);
COMMIT;
+
+:VERSION 45 #---- Add RezzerID filed in table prims
+
+BEGIN TRANSACTION;
+
+ALTER TABLE prims ADD "RezzerID" uuid NULL;
+
+COMMIT;
+
+:VERSION 46 #---- Add physics inertia data to table prims
+
+BEGIN TRANSACTION;
+
+ALTER TABLE prims ADD "PhysInertia" TEXT;
+
+COMMIT;
+
+
+:VERSION 47 #---- Convert field PassCollisions in table prims to BOOLEAN
+
+BEGIN TRANSACTION;
+
+ALTER TABLE "public"."prims" ALTER COLUMN "PassCollisions" DROP DEFAULT;
+ALTER TABLE "public"."prims"
+ ALTER COLUMN "PassCollisions" TYPE BOOLEAN
+ USING CASE WHEN "PassCollisions" = 0 THEN FALSE
+ WHEN "PassCollisions" = 1 THEN TRUE
+ ELSE NULL
+ END;
+COMMIT;
diff --git a/OpenSim/Data/SQLite/Resources/RegionStore.migrations b/OpenSim/Data/SQLite/Resources/RegionStore.migrations
index eef14d6a46..fb154cf84a 100644
--- a/OpenSim/Data/SQLite/Resources/RegionStore.migrations
+++ b/OpenSim/Data/SQLite/Resources/RegionStore.migrations
@@ -371,3 +371,9 @@ BEGIN;
ALTER TABLE `prims` ADD COLUMN `RezzerID` char(36) DEFAULT NULL;
COMMIT;
+
+:VERSION 36 #----- Add physics inertia data
+
+BEGIN;
+ALTER TABLE `prims` ADD COLUMN `PhysInertia` TEXT default NULL;
+COMMIT;
diff --git a/OpenSim/Data/SQLite/SQLiteSimulationData.cs b/OpenSim/Data/SQLite/SQLiteSimulationData.cs
index eec386fcb0..19880dec20 100644
--- a/OpenSim/Data/SQLite/SQLiteSimulationData.cs
+++ b/OpenSim/Data/SQLite/SQLiteSimulationData.cs
@@ -1843,6 +1843,12 @@ namespace OpenSim.Data.SQLite
if (vehicle != null)
prim.VehicleParams = vehicle;
}
+
+ PhysicsInertiaData pdata = null;
+ if (!(row["PhysInertia"] is DBNull) && row["PhysInertia"].ToString() != String.Empty)
+ pdata = PhysicsInertiaData.FromXml2(row["PhysInertia"].ToString());
+ prim.PhysicsInertia = pdata;
+
return prim;
}
@@ -2266,6 +2272,11 @@ namespace OpenSim.Data.SQLite
else
row["Vehicle"] = String.Empty;
+ if (prim.PhysicsInertia != null)
+ row["PhysInertia"] = prim.PhysicsInertia.ToXml2();
+ else
+ row["PhysInertia"] = String.Empty;
+
}
///
diff --git a/OpenSim/Data/SQLite/SQLiteXInventoryData.cs b/OpenSim/Data/SQLite/SQLiteXInventoryData.cs
index 7f44a651e9..4ef1f30a8d 100644
--- a/OpenSim/Data/SQLite/SQLiteXInventoryData.cs
+++ b/OpenSim/Data/SQLite/SQLiteXInventoryData.cs
@@ -305,17 +305,11 @@ namespace OpenSim.Data.SQLite
using (SqliteCommand cmd = new SqliteCommand())
{
- cmd.CommandText = "update inventoryfolders set version=version+1 where folderID = ?folderID";
+ cmd.CommandText = "update inventoryfolders set version=version+1 where folderID = :folderID";
cmd.Parameters.Add(new SqliteParameter(":folderID", folderID));
- try
- {
- cmd.ExecuteNonQuery();
- }
- catch (Exception)
- {
+ if(ExecuteNonQuery(cmd, m_Connection) == 0)
return false;
- }
}
return true;
diff --git a/OpenSim/Framework/AnimationSet.cs b/OpenSim/Framework/AnimationSet.cs
index 87c4a78ea9..8753088cc7 100644
--- a/OpenSim/Framework/AnimationSet.cs
+++ b/OpenSim/Framework/AnimationSet.cs
@@ -31,7 +31,8 @@ using OpenMetaverse;
namespace OpenSim.Framework
{
- public delegate bool AnimationSetValidator(UUID animID);
+// public delegate bool AnimationSetValidator(UUID animID);
+ public delegate uint AnimationSetValidator(UUID animID);
public class AnimationSet
{
@@ -141,7 +142,7 @@ namespace OpenSim.Framework
assetData += String.Format("{0} {1} {2}\n", kvp.Key, kvp.Value.Value.ToString(), kvp.Value.Key);
return System.Text.Encoding.ASCII.GetBytes(assetData);
}
-
+/*
public bool Validate(AnimationSetValidator val)
{
if (m_parseError)
@@ -164,5 +165,22 @@ namespace OpenSim.Framework
return allOk;
}
+*/
+ public uint Validate(AnimationSetValidator val)
+ {
+ if (m_parseError)
+ return 0;
+
+ uint ret = 0x7fffffff;
+ uint t;
+ foreach (KeyValuePair> kvp in m_animations)
+ {
+ t = val(kvp.Value.Value);
+ if (t == 0)
+ return 0;
+ ret &= t;
+ }
+ return ret;
+ }
}
}
diff --git a/OpenSim/Framework/ChildAgentDataUpdate.cs b/OpenSim/Framework/ChildAgentDataUpdate.cs
index d6d8dde6fe..ee5007abf8 100644
--- a/OpenSim/Framework/ChildAgentDataUpdate.cs
+++ b/OpenSim/Framework/ChildAgentDataUpdate.cs
@@ -375,6 +375,7 @@ namespace OpenSim.Framework
public string ActiveGroupTitle = null;
public UUID agentCOF;
public byte CrossingFlags;
+ public byte CrossExtraFlags;
public Dictionary ChildrenCapSeeds = null;
public Animation[] Anims;
@@ -454,6 +455,8 @@ namespace OpenSim.Framework
args["agent_cof"] = OSD.FromUUID(agentCOF);
args["crossingflags"] = OSD.FromInteger(CrossingFlags);
+ if(CrossingFlags != 0)
+ args["crossExtraFlags"] = OSD.FromInteger(CrossExtraFlags);
args["active_group_id"] = OSD.FromUUID(ActiveGroupID);
args["active_group_name"] = OSD.FromString(ActiveGroupName);
@@ -646,6 +649,12 @@ namespace OpenSim.Framework
if (args.ContainsKey("crossingflags") && args["crossingflags"] != null)
CrossingFlags = (byte)args["crossingflags"].AsInteger();
+ if(CrossingFlags != 0)
+ {
+ if (args.ContainsKey("crossExtraFlags") && args["crossExtraFlags"] != null)
+ CrossExtraFlags = (byte)args["crossExtraFlags"].AsInteger();
+ }
+
if (args.ContainsKey("active_group_id") && args["active_group_id"] != null)
ActiveGroupID = args["active_group_id"].AsUUID();
diff --git a/OpenSim/Framework/Client/IClientIPEndpoint.cs b/OpenSim/Framework/Client/IClientIPEndpoint.cs
index 2b99bf0a99..2194616a02 100644
--- a/OpenSim/Framework/Client/IClientIPEndpoint.cs
+++ b/OpenSim/Framework/Client/IClientIPEndpoint.cs
@@ -34,6 +34,6 @@ namespace OpenSim.Framework.Client
{
public interface IClientIPEndpoint
{
- IPAddress EndPoint { get; }
+ IPEndPoint RemoteEndPoint { get; }
}
}
diff --git a/OpenSim/Framework/ClientInfo.cs b/OpenSim/Framework/ClientInfo.cs
index 98e4465cf8..a1ca9bc32b 100644
--- a/OpenSim/Framework/ClientInfo.cs
+++ b/OpenSim/Framework/ClientInfo.cs
@@ -36,14 +36,8 @@ namespace OpenSim.Framework
public readonly DateTime StartedTime = DateTime.Now;
public AgentCircuitData agentcircuit = null;
- public Dictionary needAck;
-
- public List out_packets = new List();
- public Dictionary pendingAcks = new Dictionary();
public EndPoint proxyEP;
- public uint sequence;
- public byte[] usecircuit;
public EndPoint userEP;
public int resendThrottle;
@@ -59,9 +53,5 @@ namespace OpenSim.Framework
public int targetThrottle;
public int maxThrottle;
-
- public Dictionary SyncRequests = new Dictionary();
- public Dictionary AsyncRequests = new Dictionary();
- public Dictionary GenericRequests = new Dictionary();
}
}
diff --git a/OpenSim/Framework/ClientManager.cs b/OpenSim/Framework/ClientManager.cs
index baff2f4354..45c54e4989 100644
--- a/OpenSim/Framework/ClientManager.cs
+++ b/OpenSim/Framework/ClientManager.cs
@@ -27,10 +27,8 @@
using System;
using System.Collections.Generic;
-using System.Reflection;
using System.Net;
using OpenMetaverse;
-using OpenMetaverse.Packets;
namespace OpenSim.Framework
{
@@ -76,20 +74,16 @@ namespace OpenSim.Framework
{
lock (m_syncRoot)
{
- if (m_dict1.ContainsKey(value.AgentId) || m_dict2.ContainsKey(value.RemoteEndPoint))
- return false;
+ // allow self healing
+// if (m_dict1.ContainsKey(value.AgentId) || m_dict2.ContainsKey(value.RemoteEndPoint))
+// return false;
m_dict1[value.AgentId] = value;
m_dict2[value.RemoteEndPoint] = value;
- IClientAPI[] oldArray = m_array;
- int oldLength = oldArray.Length;
-
- IClientAPI[] newArray = new IClientAPI[oldLength + 1];
- for (int i = 0; i < oldLength; i++)
- newArray[i] = oldArray[i];
- newArray[oldLength] = value;
-
+ // dict1 is the master
+ IClientAPI[] newArray = new IClientAPI[m_dict1.Count];
+ m_dict1.Values.CopyTo(newArray, 0);
m_array = newArray;
}
@@ -112,22 +106,12 @@ namespace OpenSim.Framework
m_dict1.Remove(key);
m_dict2.Remove(value.RemoteEndPoint);
- IClientAPI[] oldArray = m_array;
- int oldLength = oldArray.Length;
-
- IClientAPI[] newArray = new IClientAPI[oldLength - 1];
- int j = 0;
- for (int i = 0; i < oldLength; i++)
- {
- if (oldArray[i] != value)
- newArray[j++] = oldArray[i];
- }
-
+ IClientAPI[] newArray = new IClientAPI[m_dict1.Count];
+ m_dict1.Values.CopyTo(newArray, 0);
m_array = newArray;
return true;
}
}
-
return false;
}
@@ -196,26 +180,12 @@ namespace OpenSim.Framework
}
}
- ///
- /// Performs a given task in parallel for each of the elements in the
- /// collection
- ///
- /// Action to perform on each element
- public void ForEach(Action action)
- {
- IClientAPI[] localArray = m_array;
- Parallel.For(0, localArray.Length,
- delegate(int i)
- { action(localArray[i]); }
- );
- }
-
///
/// Performs a given task synchronously for each of the elements in
/// the collection
///
/// Action to perform on each element
- public void ForEachSync(Action action)
+ public void ForEach(Action action)
{
IClientAPI[] localArray = m_array;
for (int i = 0; i < localArray.Length; i++)
diff --git a/OpenSim/Framework/DoubleDictionaryThreadAbortSafe.cs b/OpenSim/Framework/DoubleDictionaryThreadAbortSafe.cs
index 55ec13e5d3..816523b770 100644
--- a/OpenSim/Framework/DoubleDictionaryThreadAbortSafe.cs
+++ b/OpenSim/Framework/DoubleDictionaryThreadAbortSafe.cs
@@ -74,21 +74,19 @@ 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;
}
-
- 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;
}
finally
{
@@ -112,10 +110,9 @@ namespace OpenSim.Framework
{
rwLock.EnterWriteLock();
gotLock = true;
+ Dictionary1.Remove(key1);
+ success = Dictionary2.Remove(key2);
}
-
- Dictionary1.Remove(key1);
- success = Dictionary2.Remove(key2);
}
finally
{
@@ -151,8 +148,12 @@ namespace OpenSim.Framework
{
if (kvp.Value.Equals(value))
{
- Dictionary1.Remove(key1);
- Dictionary2.Remove(kvp.Key);
+ try { }
+ finally
+ {
+ Dictionary1.Remove(key1);
+ Dictionary2.Remove(kvp.Key);
+ }
found = true;
break;
}
@@ -193,8 +194,12 @@ namespace OpenSim.Framework
{
if (kvp.Value.Equals(value))
{
- Dictionary2.Remove(key2);
- Dictionary1.Remove(kvp.Key);
+ try { }
+ finally
+ {
+ Dictionary2.Remove(key2);
+ Dictionary1.Remove(kvp.Key);
+ }
found = true;
break;
}
@@ -224,10 +229,9 @@ namespace OpenSim.Framework
{
rwLock.EnterWriteLock();
gotLock = true;
+ Dictionary1.Clear();
+ Dictionary2.Clear();
}
-
- Dictionary1.Clear();
- Dictionary2.Clear();
}
finally
{
@@ -485,15 +489,15 @@ namespace OpenSim.Framework
try {}
finally
{
- rwLock.EnterUpgradeableReadLock();
+ rwLock.EnterWriteLock();
gotWriteLock = true;
+
+ for (int i = 0; i < list.Count; i++)
+ Dictionary1.Remove(list[i]);
+
+ for (int i = 0; i < list2.Count; i++)
+ Dictionary2.Remove(list2[i]);
}
-
- for (int i = 0; i < list.Count; i++)
- Dictionary1.Remove(list[i]);
-
- for (int i = 0; i < list2.Count; i++)
- Dictionary2.Remove(list2[i]);
}
finally
{
diff --git a/OpenSim/Framework/IAssetCache.cs b/OpenSim/Framework/IAssetCache.cs
index 8477116403..2df9199a26 100644
--- a/OpenSim/Framework/IAssetCache.cs
+++ b/OpenSim/Framework/IAssetCache.cs
@@ -47,8 +47,9 @@ namespace OpenSim.Framework
/// Get an asset by its id.
///
///
- /// null if the asset does not exist.
- AssetBase Get(string id);
+ /// Will be set to null if no asset was found
+ /// False if the asset has been negative-cached
+ bool Get(string id, out AssetBase asset);
///
/// Check whether an asset with the specified id exists in the cache.
diff --git a/OpenSim/Framework/IClientAPI.cs b/OpenSim/Framework/IClientAPI.cs
index 1267993d1f..5ca8c88ecb 100644
--- a/OpenSim/Framework/IClientAPI.cs
+++ b/OpenSim/Framework/IClientAPI.cs
@@ -107,7 +107,7 @@ namespace OpenSim.Framework
public delegate void GenericCall4(Packet packet, IClientAPI remoteClient);
public delegate void DeRezObject(
- IClientAPI remoteClient, List localIDs, UUID groupID, DeRezAction action, UUID destinationID);
+ IClientAPI remoteClient, List localIDs, UUID groupID, DeRezAction action, UUID destinationID, bool AddToReturns = true);
public delegate void GenericCall5(IClientAPI remoteClient, bool status);
@@ -685,9 +685,10 @@ namespace OpenSim.Framework
ExtraData = 1 << 20,
Sound = 1 << 21,
Joint = 1 << 22,
- FullUpdate = 0x3fffffff,
- CancelKill = 0x7fffffff,
- Kill = 0x80000000
+ FullUpdate = 0x0fffffff,
+ SendInTransit = 0x20000000,
+ CancelKill = 0x4fffffff, // 1 << 30
+ Kill = 0x80000000 // 1 << 31
}
/* included in .net 4.0
@@ -1112,7 +1113,7 @@ namespace OpenSim.Framework
///
void SendKillObject(List localID);
- void SendPartFullUpdate(ISceneEntity ent, uint? parentID);
+// void SendPartFullUpdate(ISceneEntity ent, uint? parentID);
void SendAnimations(UUID[] animID, int[] seqs, UUID sourceAgentId, UUID[] objectIDs);
void SendRegionHandshake(RegionInfo regionInfo, RegionHandshakeArgs args);
@@ -1187,7 +1188,8 @@ namespace OpenSim.Framework
void SetAgentThrottleSilent(int throttle, int setting);
int GetAgentThrottleSilent(int throttle);
- void SendAvatarDataImmediate(ISceneEntity avatar);
+ void SendEntityFullUpdateImmediate(ISceneEntity entity);
+ void SendEntityTerseUpdateImmediate(ISceneEntity entity);
///
/// Send a positional, velocity, etc. update to the viewer for a given entity.
diff --git a/OpenSim/Framework/ILandChannel.cs b/OpenSim/Framework/ILandChannel.cs
index 44a24b94a3..866783751c 100644
--- a/OpenSim/Framework/ILandChannel.cs
+++ b/OpenSim/Framework/ILandChannel.cs
@@ -76,6 +76,8 @@ namespace OpenSim.Region.Framework.Interfaces
///
ILandObject GetLandObject(int localID);
+ ILandObject GetLandObject(UUID GlobalID);
+
///
/// Clear the land channel of all parcels.
///
@@ -86,6 +88,7 @@ namespace OpenSim.Region.Framework.Interfaces
bool IsForcefulBansAllowed();
void UpdateLandObject(int localID, LandData data);
+ void SendParcelsOverlay(IClientAPI client);
void ReturnObjectsInParcel(int localID, uint returnType, UUID[] agentIDs, UUID[] taskIDs, IClientAPI remoteClient);
void setParcelObjectMaxOverride(overrideParcelMaxPrimCountDelegate overrideDel);
void setSimulatorObjectMaxOverride(overrideSimulatorMaxPrimCountDelegate overrideDel);
diff --git a/OpenSim/Framework/ILandObject.cs b/OpenSim/Framework/ILandObject.cs
index f3b850d528..a7832568a2 100644
--- a/OpenSim/Framework/ILandObject.cs
+++ b/OpenSim/Framework/ILandObject.cs
@@ -189,5 +189,7 @@ namespace OpenSim.Framework
///
/// The music url.
string GetMusicUrl();
+
+ void Clear();
}
}
diff --git a/OpenSim/Framework/IMoneyModule.cs b/OpenSim/Framework/IMoneyModule.cs
index be454385db..c72c742151 100644
--- a/OpenSim/Framework/IMoneyModule.cs
+++ b/OpenSim/Framework/IMoneyModule.cs
@@ -41,6 +41,7 @@ namespace OpenSim.Framework
void ApplyCharge(UUID agentID, int amount, MoneyTransactionType type, string extraData = "");
void ApplyUploadCharge(UUID agentID, int amount, string text);
void MoveMoney(UUID fromUser, UUID toUser, int amount, string text);
+ bool MoveMoney(UUID fromUser, UUID toUser, int amount, MoneyTransactionType type, string text);
int UploadCharge { get; }
int GroupCreationCharge { get; }
diff --git a/OpenSim/Framework/LandData.cs b/OpenSim/Framework/LandData.cs
index 13d29776c5..13b58be3dd 100644
--- a/OpenSim/Framework/LandData.cs
+++ b/OpenSim/Framework/LandData.cs
@@ -97,7 +97,9 @@ namespace OpenSim.Framework
private bool _mediaLoop = false;
private bool _obscureMusic = false;
private bool _obscureMedia = false;
- private float _dwell = 0;
+
+ private float m_dwell = 0;
+ public double LastDwellTimeMS;
public bool SeeAVs { get; set; }
public bool AnyAVSounds { get; set; }
@@ -111,11 +113,12 @@ namespace OpenSim.Framework
{
get
{
- return _dwell;
+ return m_dwell;
}
set
{
- _dwell = value;
+ m_dwell = value;
+ LastDwellTimeMS = Util.GetTimeStampMS();
}
}
@@ -735,6 +738,7 @@ namespace OpenSim.Framework
SeeAVs = true;
AnyAVSounds = true;
GroupAVSounds = true;
+ LastDwellTimeMS = Util.GetTimeStampMS();
}
///
@@ -784,7 +788,7 @@ namespace OpenSim.Framework
landData._obscureMedia = _obscureMedia;
landData._simwideArea = _simwideArea;
landData._simwidePrims = _simwidePrims;
- landData._dwell = _dwell;
+ landData.m_dwell = m_dwell;
landData.SeeAVs = SeeAVs;
landData.AnyAVSounds = AnyAVSounds;
landData.GroupAVSounds = GroupAVSounds;
diff --git a/OpenSim/Framework/Monitoring/JobEngine.cs b/OpenSim/Framework/Monitoring/JobEngine.cs
index 0a39e4b6be..115871e4a7 100644
--- a/OpenSim/Framework/Monitoring/JobEngine.cs
+++ b/OpenSim/Framework/Monitoring/JobEngine.cs
@@ -57,7 +57,8 @@ namespace OpenSim.Framework.Monitoring
///
/// Will be null if no job is currently running.
///
- public Job CurrentJob { get; private set; }
+ private Job m_currentJob;
+ public Job CurrentJob { get { return m_currentJob;} }
///
/// Number of jobs waiting to be processed.
@@ -82,16 +83,15 @@ namespace OpenSim.Framework.Monitoring
private CancellationTokenSource m_cancelSource;
- ///
- /// Used to signal that we are ready to complete stop.
- ///
- private ManualResetEvent m_finishedProcessingAfterStop = new ManualResetEvent(false);
+ private int m_timeout = -1;
- public JobEngine(string name, string loggingName)
+ private bool m_threadRunnig = false;
+
+ public JobEngine(string name, string loggingName, int timeout = -1)
{
Name = name;
LoggingName = loggingName;
-
+ m_timeout = timeout;
RequestProcessTimeoutOnStop = 5000;
}
@@ -104,18 +104,9 @@ namespace OpenSim.Framework.Monitoring
IsRunning = true;
- m_finishedProcessingAfterStop.Reset();
-
m_cancelSource = new CancellationTokenSource();
-
- WorkManager.StartThread(
- ProcessRequests,
- Name,
- ThreadPriority.Normal,
- false,
- true,
- null,
- int.MaxValue);
+ WorkManager.RunInThreadPool(ProcessRequests, null, Name, false);
+ m_threadRunnig = true;
}
}
@@ -131,17 +122,16 @@ namespace OpenSim.Framework.Monitoring
m_log.DebugFormat("[JobEngine] Stopping {0}", Name);
IsRunning = false;
-
- m_finishedProcessingAfterStop.Reset();
- if(m_jobQueue.Count <= 0)
+ if(m_threadRunnig)
+ {
m_cancelSource.Cancel();
-
- if(m_finishedProcessingAfterStop.WaitOne(RequestProcessTimeoutOnStop))
- m_finishedProcessingAfterStop.Close();
+ m_threadRunnig = false;
+ }
}
finally
{
- m_cancelSource.Dispose();
+ if(m_cancelSource != null)
+ m_cancelSource.Dispose();
}
}
}
@@ -200,6 +190,18 @@ namespace OpenSim.Framework.Monitoring
///
public bool QueueJob(Job job)
{
+ lock(JobLock)
+ {
+ if(!IsRunning)
+ return false;
+
+ if(!m_threadRunnig)
+ {
+ WorkManager.RunInThreadPool(ProcessRequests, null, Name, false);
+ m_threadRunnig = true;
+ }
+ }
+
if (m_jobQueue.Count < m_jobQueue.BoundedCapacity)
{
m_jobQueue.Add(job);
@@ -219,31 +221,28 @@ namespace OpenSim.Framework.Monitoring
m_warnOverMaxQueue = false;
}
-
return false;
}
}
- private void ProcessRequests()
+ private void ProcessRequests(Object o)
{
- while(IsRunning || m_jobQueue.Count > 0)
+ while(IsRunning)
{
try
{
- CurrentJob = m_jobQueue.Take(m_cancelSource.Token);
+ if(!m_jobQueue.TryTake(out m_currentJob, m_timeout, m_cancelSource.Token))
+ {
+ lock(JobLock)
+ m_threadRunnig = false;
+ break;
+ }
}
catch(ObjectDisposedException e)
{
- // If we see this whilst not running then it may be due to a race where this thread checks
- // IsRunning after the stopping thread sets it to false and disposes of the cancellation source.
- if(IsRunning)
- throw e;
- else
- {
- m_log.DebugFormat("[JobEngine] {0} stopping ignoring {1} jobs in queue",
- Name,m_jobQueue.Count);
- break;
- }
+ m_log.DebugFormat("[JobEngine] {0} stopping ignoring {1} jobs in queue",
+ Name,m_jobQueue.Count);
+ break;
}
catch(OperationCanceledException)
{
@@ -251,27 +250,24 @@ namespace OpenSim.Framework.Monitoring
}
if(LogLevel >= 1)
- m_log.DebugFormat("[{0}]: Processing job {1}",LoggingName,CurrentJob.Name);
+ m_log.DebugFormat("[{0}]: Processing job {1}",LoggingName,m_currentJob.Name);
try
{
- CurrentJob.Action();
+ m_currentJob.Action();
}
catch(Exception e)
{
m_log.Error(
string.Format(
- "[{0}]: Job {1} failed, continuing. Exception ",LoggingName,CurrentJob.Name),e);
+ "[{0}]: Job {1} failed, continuing. Exception ",LoggingName,m_currentJob.Name),e);
}
if(LogLevel >= 1)
- m_log.DebugFormat("[{0}]: Processed job {1}",LoggingName,CurrentJob.Name);
+ m_log.DebugFormat("[{0}]: Processed job {1}",LoggingName,m_currentJob.Name);
- CurrentJob = null;
+ m_currentJob = null;
}
-
- Watchdog.RemoveThread(false);
- m_finishedProcessingAfterStop.Set();
}
public class Job
diff --git a/OpenSim/Framework/Monitoring/ServerStatsCollector.cs b/OpenSim/Framework/Monitoring/ServerStatsCollector.cs
index 3391240ce5..a26a6e0366 100644
--- a/OpenSim/Framework/Monitoring/ServerStatsCollector.cs
+++ b/OpenSim/Framework/Monitoring/ServerStatsCollector.cs
@@ -88,7 +88,7 @@ namespace OpenSim.Framework.Monitoring
IConfig cfg = source.Configs["Monitoring"];
if (cfg != null)
- Enabled = cfg.GetBoolean("ServerStatsEnabled", true);
+ Enabled = cfg.GetBoolean("ServerStatsEnabled", false);
if (Enabled)
{
@@ -98,12 +98,18 @@ namespace OpenSim.Framework.Monitoring
public void Start()
{
+ if(!Enabled)
+ return;
+
if (RegisteredStats.Count == 0)
RegisterServerStats();
}
public void Close()
{
+ if(!Enabled)
+ return;
+
if (RegisteredStats.Count > 0)
{
foreach (Stat stat in RegisteredStats.Values)
diff --git a/OpenSim/Framework/Monitoring/StatsManager.cs b/OpenSim/Framework/Monitoring/StatsManager.cs
index 55c327656a..a6b341f21c 100644
--- a/OpenSim/Framework/Monitoring/StatsManager.cs
+++ b/OpenSim/Framework/Monitoring/StatsManager.cs
@@ -47,6 +47,8 @@ namespace OpenSim.Framework.Monitoring
// Subcommand used to list other stats.
public const string ListSubCommand = "list";
+ public static string StatsPassword { get; set; }
+
// All subcommands
public static HashSet SubCommands = new HashSet { AllSubCommand, ListSubCommand };
@@ -302,6 +304,17 @@ namespace OpenSim.Framework.Monitoring
int response_code = 200;
string contenttype = "text/json";
+ if (StatsPassword != String.Empty && (!request.ContainsKey("pass") || request["pass"].ToString() != StatsPassword))
+ {
+ responsedata["int_response_code"] = response_code;
+ responsedata["content_type"] = "text/plain";
+ responsedata["keepalive"] = false;
+ responsedata["str_response_string"] = "Access denied";
+ responsedata["access_control_allow_origin"] = "*";
+
+ return responsedata;
+ }
+
string pCategoryName = StatsManager.AllSubCommand;
string pContainerName = StatsManager.AllSubCommand;
string pStatName = StatsManager.AllSubCommand;
diff --git a/OpenSim/Framework/Monitoring/Watchdog.cs b/OpenSim/Framework/Monitoring/Watchdog.cs
index 9cc61ee62d..9cac451c63 100644
--- a/OpenSim/Framework/Monitoring/Watchdog.cs
+++ b/OpenSim/Framework/Monitoring/Watchdog.cs
@@ -180,6 +180,30 @@ namespace OpenSim.Framework.Monitoring
m_watchdogTimer.Elapsed += WatchdogTimerElapsed;
}
+ public static void Stop()
+ {
+ if(m_threads == null)
+ return;
+
+ lock(m_threads)
+ {
+ m_enabled = false;
+ if(m_watchdogTimer != null)
+ {
+ m_watchdogTimer.Dispose();
+ m_watchdogTimer = null;
+ }
+
+ foreach(ThreadWatchdogInfo twi in m_threads.Values)
+ {
+ Thread t = twi.Thread;
+ if(t.IsAlive)
+ t.Abort();
+ }
+ m_threads.Clear();
+ }
+ }
+
///
/// Add a thread to the watchdog tracker.
///
@@ -230,14 +254,12 @@ namespace OpenSim.Framework.Monitoring
twi.Cleanup();
m_threads.Remove(threadID);
-
return true;
}
else
{
m_log.WarnFormat(
"[WATCHDOG]: Requested to remove thread with ID {0} but this is not being monitored", threadID);
-
return false;
}
}
@@ -317,6 +339,8 @@ namespace OpenSim.Framework.Monitoring
///
private static void WatchdogTimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
{
+ if(!m_enabled)
+ return;
int now = Environment.TickCount & Int32.MaxValue;
int msElapsed = now - LastWatchdogThreadTick;
@@ -334,21 +358,26 @@ namespace OpenSim.Framework.Monitoring
List callbackInfos = null;
List threadsToRemove = null;
+ const ThreadState thgone = ThreadState.Stopped;
+
lock (m_threads)
{
foreach(ThreadWatchdogInfo threadInfo in m_threads.Values)
{
- if(threadInfo.Thread.ThreadState == ThreadState.Stopped)
+ if(!m_enabled)
+ return;
+ if((threadInfo.Thread.ThreadState & thgone) != 0)
{
if(threadsToRemove == null)
threadsToRemove = new List();
threadsToRemove.Add(threadInfo);
-
+/*
if(callbackInfos == null)
callbackInfos = new List();
callbackInfos.Add(threadInfo);
+*/
}
else if(!threadInfo.IsTimedOut && now - threadInfo.LastTick >= threadInfo.Timeout)
{
diff --git a/OpenSim/Framework/Monitoring/WorkManager.cs b/OpenSim/Framework/Monitoring/WorkManager.cs
index 43130f9a0b..5d9b185f29 100644
--- a/OpenSim/Framework/Monitoring/WorkManager.cs
+++ b/OpenSim/Framework/Monitoring/WorkManager.cs
@@ -57,7 +57,7 @@ namespace OpenSim.Framework.Monitoring
static WorkManager()
{
- JobEngine = new JobEngine("Non-blocking non-critical job engine", "JOB ENGINE");
+ JobEngine = new JobEngine("Non-blocking non-critical job engine", "JOB ENGINE", 30000);
StatsManager.RegisterStat(
new Stat(
@@ -82,6 +82,12 @@ namespace OpenSim.Framework.Monitoring
HandleControlCommand);
}
+ public static void Stop()
+ {
+ JobEngine.Stop();
+ Watchdog.Stop();
+ }
+
///
/// Start a new long-lived thread.
///
@@ -131,7 +137,6 @@ namespace OpenSim.Framework.Monitoring
thread.Start();
-
return thread;
}
@@ -177,9 +182,9 @@ namespace OpenSim.Framework.Monitoring
///
///
/// The name of the job. This is used in monitoring and debugging.
- public static void RunInThreadPool(System.Threading.WaitCallback callback, object obj, string name)
+ public static void RunInThreadPool(System.Threading.WaitCallback callback, object obj, string name, bool timeout = true)
{
- Util.FireAndForget(callback, obj, name);
+ Util.FireAndForget(callback, obj, name, timeout);
}
///
@@ -226,10 +231,8 @@ namespace OpenSim.Framework.Monitoring
JobEngine.QueueJob(name, () => callback(obj));
else if (canRunInThisThread)
callback(obj);
- else if (mustNotTimeout)
- RunInThread(callback, obj, name, log);
else
- Util.FireAndForget(callback, obj, name);
+ Util.FireAndForget(callback, obj, name, !mustNotTimeout);
}
private static void HandleControlCommand(string module, string[] args)
diff --git a/OpenSim/Framework/OutboundUrlFilter.cs b/OpenSim/Framework/OutboundUrlFilter.cs
index ee4707fa8c..63ae361448 100644
--- a/OpenSim/Framework/OutboundUrlFilter.cs
+++ b/OpenSim/Framework/OutboundUrlFilter.cs
@@ -212,7 +212,17 @@ namespace OpenSim.Framework
// Check that we are permitted to make calls to this endpoint.
bool foundIpv4Address = false;
- IPAddress[] addresses = Dns.GetHostAddresses(url.Host);
+ IPAddress[] addresses = null;
+
+ try
+ {
+ addresses = Dns.GetHostAddresses(url.Host);
+ }
+ catch
+ {
+ // If there is a DNS error, we can't stop the script!
+ return true;
+ }
foreach (IPAddress addr in addresses)
{
@@ -253,4 +263,4 @@ namespace OpenSim.Framework
return allowed;
}
}
-}
\ No newline at end of file
+}
diff --git a/OpenSim/Framework/PermissionsUtil.cs b/OpenSim/Framework/PermissionsUtil.cs
index 3dce04dde0..e50d4df8ea 100644
--- a/OpenSim/Framework/PermissionsUtil.cs
+++ b/OpenSim/Framework/PermissionsUtil.cs
@@ -60,9 +60,57 @@ namespace OpenSim.Framework
str += "C";
if ((perms & (int)PermissionMask.Transfer) != 0)
str += "T";
+ if ((perms & (int)PermissionMask.Export) != 0)
+ str += "X";
if (str == "")
str = ".";
return str;
}
+
+ public static void ApplyFoldedPermissions(uint foldedSourcePerms, ref uint targetPerms)
+ {
+ uint folded = foldedSourcePerms & (uint)PermissionMask.FoldedMask;
+ if(folded == 0 || folded == (uint)PermissionMask.FoldedMask) // invalid we need to ignore, or nothing to do
+ return;
+
+ folded <<= (int)PermissionMask.FoldingShift;
+ folded |= ~(uint)PermissionMask.UnfoldedMask;
+
+ uint tmp = targetPerms;
+ tmp &= folded;
+ targetPerms = tmp;
+ }
+
+ // do not touch MOD
+ public static void ApplyNoModFoldedPermissions(uint foldedSourcePerms, ref uint target)
+ {
+ uint folded = foldedSourcePerms & (uint)PermissionMask.FoldedMask;
+ if(folded == 0 || folded == (uint)PermissionMask.FoldedMask) // invalid we need to ignore, or nothing to do
+ return;
+
+ folded <<= (int)PermissionMask.FoldingShift;
+ folded |= (~(uint)PermissionMask.UnfoldedMask | (uint)PermissionMask.Modify);
+
+ uint tmp = target;
+ tmp &= folded;
+ target = tmp;
+ }
+
+ public static uint FixAndFoldPermissions(uint perms)
+ {
+ uint tmp = perms;
+
+ // C & T rule
+ if((tmp & (uint)(PermissionMask.Copy | PermissionMask.Transfer)) == 0)
+ tmp |= (uint)PermissionMask.Transfer;
+
+ // unlock
+ tmp |= (uint)PermissionMask.Move;
+
+ tmp &= ~(uint)PermissionMask.FoldedMask;
+ tmp |= ((tmp >> (int)PermissionMask.FoldingShift) & (uint)PermissionMask.FoldedMask);
+
+ return tmp;
+ }
}
}
diff --git a/OpenSim/Framework/PhysicsInertia.cs b/OpenSim/Framework/PhysicsInertia.cs
new file mode 100644
index 0000000000..6e1579136c
--- /dev/null
+++ b/OpenSim/Framework/PhysicsInertia.cs
@@ -0,0 +1,262 @@
+/*
+ * 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 OpenMetaverse;
+using System.Text;
+using System.IO;
+using System.Xml;
+
+namespace OpenSim.Framework
+{
+ public class PhysicsInertiaData
+ {
+ public float TotalMass; // the total mass of a linkset
+ public Vector3 CenterOfMass; // the center of mass position relative to root part position
+ public Vector3 Inertia; // (Ixx, Iyy, Izz) moment of inertia relative to center of mass and principal axis in local coords
+ public Vector4 InertiaRotation; // if principal axis don't match local axis, the principal axis rotation
+ // or the upper triangle of the inertia tensor
+ // Ixy (= Iyx), Ixz (= Izx), Iyz (= Izy))
+
+ public PhysicsInertiaData()
+ {
+ }
+
+ public PhysicsInertiaData(PhysicsInertiaData source)
+ {
+ TotalMass = source.TotalMass;
+ CenterOfMass = source.CenterOfMass;
+ Inertia = source.Inertia;
+ InertiaRotation = source.InertiaRotation;
+ }
+
+ private XmlTextWriter writer;
+
+ private void XWint(string name, int i)
+ {
+ writer.WriteElementString(name, i.ToString());
+ }
+
+ private void XWfloat(string name, float f)
+ {
+ writer.WriteElementString(name, f.ToString(Culture.FormatProvider));
+ }
+
+ private void XWVector(string name, Vector3 vec)
+ {
+ writer.WriteStartElement(name);
+ writer.WriteElementString("X", vec.X.ToString(Culture.FormatProvider));
+ writer.WriteElementString("Y", vec.Y.ToString(Culture.FormatProvider));
+ writer.WriteElementString("Z", vec.Z.ToString(Culture.FormatProvider));
+ writer.WriteEndElement();
+ }
+
+ private void XWVector4(string name, Vector4 quat)
+ {
+ writer.WriteStartElement(name);
+ writer.WriteElementString("X", quat.X.ToString(Culture.FormatProvider));
+ writer.WriteElementString("Y", quat.Y.ToString(Culture.FormatProvider));
+ writer.WriteElementString("Z", quat.Z.ToString(Culture.FormatProvider));
+ writer.WriteElementString("W", quat.W.ToString(Culture.FormatProvider));
+ writer.WriteEndElement();
+ }
+
+ public void ToXml2(XmlTextWriter twriter)
+ {
+ writer = twriter;
+ writer.WriteStartElement("PhysicsInertia");
+
+ XWfloat("MASS", TotalMass);
+ XWVector("CM", CenterOfMass);
+ XWVector("INERTIA", Inertia);
+ XWVector4("IROT", InertiaRotation);
+
+ writer.WriteEndElement();
+ writer = null;
+ }
+
+ XmlReader reader;
+
+ private int XRint()
+ {
+ return reader.ReadElementContentAsInt();
+ }
+
+ private float XRfloat()
+ {
+ return reader.ReadElementContentAsFloat();
+ }
+
+ public Vector3 XRvector()
+ {
+ Vector3 vec;
+ reader.ReadStartElement();
+ vec.X = reader.ReadElementContentAsFloat();
+ vec.Y = reader.ReadElementContentAsFloat();
+ vec.Z = reader.ReadElementContentAsFloat();
+ reader.ReadEndElement();
+ return vec;
+ }
+
+ public Vector4 XRVector4()
+ {
+ Vector4 q;
+ reader.ReadStartElement();
+ q.X = reader.ReadElementContentAsFloat();
+ q.Y = reader.ReadElementContentAsFloat();
+ q.Z = reader.ReadElementContentAsFloat();
+ q.W = reader.ReadElementContentAsFloat();
+ reader.ReadEndElement();
+ return q;
+ }
+
+ public static bool EReadProcessors(
+ Dictionary processors,
+ XmlReader xtr)
+ {
+ bool errors = false;
+
+ string nodeName = string.Empty;
+ while (xtr.NodeType != XmlNodeType.EndElement)
+ {
+ nodeName = xtr.Name;
+
+ Action p = null;
+ if (processors.TryGetValue(xtr.Name, out p))
+ {
+ try
+ {
+ p();
+ }
+ catch
+ {
+ errors = true;
+ if (xtr.NodeType == XmlNodeType.EndElement)
+ xtr.Read();
+ }
+ }
+ else
+ {
+ xtr.ReadOuterXml(); // ignore
+ }
+ }
+
+ return errors;
+ }
+
+ public string ToXml2()
+ {
+ using (StringWriter sw = new StringWriter())
+ {
+ using (XmlTextWriter xwriter = new XmlTextWriter(sw))
+ {
+ ToXml2(xwriter);
+ }
+
+ return sw.ToString();
+ }
+ }
+
+ public static PhysicsInertiaData FromXml2(string text)
+ {
+ if (text == String.Empty)
+ return null;
+
+ UTF8Encoding enc = new UTF8Encoding();
+ MemoryStream ms = new MemoryStream(enc.GetBytes(text));
+ XmlTextReader xreader = new XmlTextReader(ms);
+
+ PhysicsInertiaData v = new PhysicsInertiaData();
+ bool error;
+
+ v.FromXml2(xreader, out error);
+
+ xreader.Close();
+
+ if (error)
+ return null;
+
+ return v;
+ }
+
+ public static PhysicsInertiaData FromXml2(XmlReader reader)
+ {
+ PhysicsInertiaData data = new PhysicsInertiaData();
+
+ bool errors = false;
+
+ data.FromXml2(reader, out errors);
+ if (errors)
+ return null;
+
+ return data;
+ }
+
+ private void FromXml2(XmlReader _reader, out bool errors)
+ {
+ errors = false;
+ reader = _reader;
+
+ Dictionary m_XmlProcessors = new Dictionary();
+
+ m_XmlProcessors.Add("MASS", ProcessXR_Mass);
+ m_XmlProcessors.Add("CM", ProcessXR_CM);
+ m_XmlProcessors.Add("INERTIA", ProcessXR_Inertia);
+ m_XmlProcessors.Add("IROT", ProcessXR_InertiaRotation);
+
+ reader.ReadStartElement("PhysicsInertia", String.Empty);
+
+ errors = EReadProcessors(
+ m_XmlProcessors,
+ reader);
+
+ reader.ReadEndElement();
+ reader = null;
+ }
+
+ private void ProcessXR_Mass()
+ {
+ TotalMass = XRfloat();
+ }
+
+ private void ProcessXR_CM()
+ {
+ CenterOfMass = XRvector();
+ }
+
+ private void ProcessXR_Inertia()
+ {
+ Inertia = XRvector();
+ }
+
+ private void ProcessXR_InertiaRotation()
+ {
+ InertiaRotation = XRVector4();
+ }
+ }
+}
diff --git a/OpenSim/Framework/PrimitiveBaseShape.cs b/OpenSim/Framework/PrimitiveBaseShape.cs
index 29985d2586..96d78d3eed 100644
--- a/OpenSim/Framework/PrimitiveBaseShape.cs
+++ b/OpenSim/Framework/PrimitiveBaseShape.cs
@@ -328,6 +328,70 @@ namespace OpenSim.Framework
return shape;
}
+ public static PrimitiveBaseShape CreateMesh(int numberOfFaces, UUID meshAssetID)
+ {
+ PrimitiveBaseShape shape = new PrimitiveBaseShape();
+
+ shape._pathScaleX = 100;
+ shape._pathScaleY = 100;
+
+ if(numberOfFaces <= 0) // oops ?
+ numberOfFaces = 1;
+
+ switch(numberOfFaces)
+ {
+ case 1: // torus
+ shape.ProfileCurve = (byte)ProfileShape.Circle | (byte)HollowShape.Triangle;
+ shape.PathCurve = (byte)Extrusion.Curve1;
+ break;
+
+ case 2: // torus with hollow (a sl viewer whould see 4 faces on a hollow sphere)
+ shape.ProfileCurve = (byte)ProfileShape.Circle | (byte)HollowShape.Triangle;
+ shape.PathCurve = (byte)Extrusion.Curve1;
+ shape.ProfileHollow = 1;
+ break;
+
+ case 3: // cylinder
+ shape.ProfileCurve = (byte)ProfileShape.Circle | (byte)HollowShape.Triangle;
+ shape.PathCurve = (byte)Extrusion.Straight;
+ break;
+
+ case 4: // cylinder with hollow
+ shape.ProfileCurve = (byte)ProfileShape.Circle | (byte)HollowShape.Triangle;
+ shape.PathCurve = (byte)Extrusion.Straight;
+ shape.ProfileHollow = 1;
+ break;
+
+ case 5: // prism
+ shape.ProfileCurve = (byte)ProfileShape.EquilateralTriangle | (byte)HollowShape.Triangle;
+ shape.PathCurve = (byte)Extrusion.Straight;
+ break;
+
+ case 6: // box
+ shape.ProfileCurve = (byte)ProfileShape.Square | (byte)HollowShape.Triangle;
+ shape.PathCurve = (byte)Extrusion.Straight;
+ break;
+
+ case 7: // box with hollow
+ shape.ProfileCurve = (byte)ProfileShape.Square | (byte)HollowShape.Triangle;
+ shape.PathCurve = (byte)Extrusion.Straight;
+ shape.ProfileHollow = 1;
+ break;
+
+ default: // 8 faces box with cut
+ shape.ProfileCurve = (byte)ProfileShape.Square | (byte)HollowShape.Triangle;
+ shape.PathCurve = (byte)Extrusion.Straight;
+ shape.ProfileBegin = 1;
+ break;
+ }
+
+ shape.SculptEntry = true;
+ shape.SculptType = (byte)OpenMetaverse.SculptType.Mesh;
+ shape.SculptTexture = meshAssetID;
+
+ return shape;
+ }
+
public void SetScale(float side)
{
_scale = new Vector3(side, side, side);
@@ -1516,35 +1580,48 @@ namespace OpenSim.Framework
{
MediaList ml = new MediaList();
ml.ReadXml(rawXml);
+ if(ml.Count == 0)
+ return null;
return ml;
}
public void ReadXml(string rawXml)
{
- using (StringReader sr = new StringReader(rawXml))
+ try
{
- using (XmlTextReader xtr = new XmlTextReader(sr))
+ using (StringReader sr = new StringReader(rawXml))
{
- xtr.MoveToContent();
-
- string type = xtr.GetAttribute("type");
- //m_log.DebugFormat("[MOAP]: Loaded media texture entry with type {0}", type);
-
- if (type != MEDIA_TEXTURE_TYPE)
- return;
-
- xtr.ReadStartElement("OSMedia");
-
- OSDArray osdMeArray = (OSDArray)OSDParser.DeserializeLLSDXml(xtr.ReadInnerXml());
- foreach (OSD osdMe in osdMeArray)
+ using (XmlTextReader xtr = new XmlTextReader(sr))
{
- MediaEntry me = (osdMe is OSDMap ? MediaEntry.FromOSD(osdMe) : new MediaEntry());
- Add(me);
- }
+ xtr.MoveToContent();
- xtr.ReadEndElement();
+ string type = xtr.GetAttribute("type");
+ //m_log.DebugFormat("[MOAP]: Loaded media texture entry with type {0}", type);
+
+ if (type != MEDIA_TEXTURE_TYPE)
+ return;
+
+ xtr.ReadStartElement("OSMedia");
+ OSD osdp = OSDParser.DeserializeLLSDXml(xtr.ReadInnerXml());
+ if(osdp == null || !(osdp is OSDArray))
+ return;
+
+ OSDArray osdMeArray = osdp as OSDArray;
+ if(osdMeArray.Count == 0)
+ return;
+
+ foreach (OSD osdMe in osdMeArray)
+ {
+ MediaEntry me = (osdMe is OSDMap ? MediaEntry.FromOSD(osdMe) : new MediaEntry());
+ Add(me);
+ }
+ }
}
}
+ catch
+ {
+ m_log.Debug("PrimitiveBaseShape] error decoding MOAP xml" );
+ }
}
public void ReadXml(XmlReader reader)
diff --git a/OpenSim/Framework/PriorityQueue.cs b/OpenSim/Framework/PriorityQueue.cs
index 5b9185e5c8..22ffcdc8b6 100644
--- a/OpenSim/Framework/PriorityQueue.cs
+++ b/OpenSim/Framework/PriorityQueue.cs
@@ -216,6 +216,27 @@ namespace OpenSim.Framework
return false;
}
+ public bool TryOrderedDequeue(out EntityUpdate value, out Int32 timeinqueue)
+ {
+ // If there is anything in imediate queues, return it first no
+ // matter what else. Breaks fairness. But very useful.
+ for (int iq = 0; iq < NumberOfQueues; iq++)
+ {
+ if (m_heaps[iq].Count > 0)
+ {
+ MinHeapItem item = m_heaps[iq].RemoveMin();
+ m_lookupTable.Remove(item.Value.Entity.LocalId);
+ timeinqueue = Util.EnvironmentTickCountSubtract(item.EntryTime);
+ value = item.Value;
+ return true;
+ }
+ }
+
+ timeinqueue = 0;
+ value = default(EntityUpdate);
+ return false;
+ }
+
///
/// Reapply the prioritization function to each of the updates currently
/// stored in the priority queues.
diff --git a/OpenSim/Framework/RegionInfo.cs b/OpenSim/Framework/RegionInfo.cs
index 99e97e8b51..75ed999601 100644
--- a/OpenSim/Framework/RegionInfo.cs
+++ b/OpenSim/Framework/RegionInfo.cs
@@ -130,7 +130,7 @@ namespace OpenSim.Framework
private float m_physPrimMin = 0;
private int m_physPrimMax = 0;
private bool m_clampPrimSize = false;
- private int m_objectCapacity = 0;
+ private int m_objectCapacity = 15000;
private int m_maxPrimsPerUser = -1;
private int m_linksetCapacity = 0;
private string m_regionType = String.Empty;
@@ -420,6 +420,7 @@ namespace OpenSim.Framework
set { m_remotingPort = value; }
}
+
///
/// This accessor can throw all the exceptions that Dns.GetHostAddresses can throw.
///
@@ -427,42 +428,7 @@ namespace OpenSim.Framework
///
public IPEndPoint ExternalEndPoint
{
- get
- {
- // Old one defaults to IPv6
- //return new IPEndPoint(Dns.GetHostAddresses(m_externalHostName)[0], m_internalEndPoint.Port);
-
- IPAddress ia = null;
- // If it is already an IP, don't resolve it - just return directly
- if (IPAddress.TryParse(m_externalHostName, out ia))
- return new IPEndPoint(ia, m_internalEndPoint.Port);
-
- // Reset for next check
- ia = null;
- try
- {
- foreach (IPAddress Adr in Dns.GetHostAddresses(m_externalHostName))
- {
- if (ia == null)
- ia = Adr;
-
- if (Adr.AddressFamily == AddressFamily.InterNetwork)
- {
- ia = Adr;
- break;
- }
- }
- }
- catch (SocketException e)
- {
- throw new Exception(
- "Unable to resolve local hostname " + m_externalHostName + " innerException of type '" +
- e + "' attached to this exception", e);
- }
-
- return new IPEndPoint(ia, m_internalEndPoint.Port);
- }
-
+ get { return Util.getEndPoint(m_externalHostName, m_internalEndPoint.Port); }
set { m_externalHostName = value.ToString(); }
}
@@ -753,7 +719,7 @@ namespace OpenSim.Framework
m_clampPrimSize = config.GetBoolean("ClampPrimSize", false);
allKeys.Remove("ClampPrimSize");
- m_objectCapacity = config.GetInt("MaxPrims", 15000);
+ m_objectCapacity = config.GetInt("MaxPrims", m_objectCapacity);
allKeys.Remove("MaxPrims");
m_maxPrimsPerUser = config.GetInt("MaxPrimsPerUser", -1);
diff --git a/OpenSim/Framework/RestClient.cs b/OpenSim/Framework/RestClient.cs
index 0166d9d37e..4939cf7bfd 100644
--- a/OpenSim/Framework/RestClient.cs
+++ b/OpenSim/Framework/RestClient.cs
@@ -428,22 +428,23 @@ namespace OpenSim.Framework
if (WebUtil.DebugLevel >= 5)
WebUtil.LogOutgoingDetail(string.Format("SEND {0}: ", reqnum), src);
- using (Stream dst = _request.GetRequestStream())
- {
- m_log.Debug("[REST]: GetRequestStream is ok");
-
- byte[] buf = new byte[1024];
- int length = src.Read(buf, 0, 1024);
- m_log.Debug("[REST]: First Read is ok");
- while (length > 0)
- {
- dst.Write(buf, 0, length);
- length = src.Read(buf, 0, 1024);
- }
- }
-
+
try
{
+ using (Stream dst = _request.GetRequestStream())
+ {
+// m_log.Debug("[REST]: GetRequestStream is ok");
+
+ byte[] buf = new byte[1024];
+ int length = src.Read(buf, 0, 1024);
+// m_log.Debug("[REST]: First Read is ok");
+ while (length > 0)
+ {
+ dst.Write(buf, 0, length);
+ length = src.Read(buf, 0, 1024);
+ }
+ }
+
_response = (HttpWebResponse)_request.GetResponse();
}
catch (WebException e)
diff --git a/OpenSim/Framework/Servers/BaseOpenSimServer.cs b/OpenSim/Framework/Servers/BaseOpenSimServer.cs
index f761813560..81dd3574ad 100644
--- a/OpenSim/Framework/Servers/BaseOpenSimServer.cs
+++ b/OpenSim/Framework/Servers/BaseOpenSimServer.cs
@@ -108,13 +108,21 @@ namespace OpenSim.Framework.Servers
protected override void ShutdownSpecific()
{
- m_log.Info("[SHUTDOWN]: Shutdown processing on main thread complete. Exiting...");
+ Watchdog.Enabled = false;
+ base.ShutdownSpecific();
+
+ MainServer.Stop();
+ Thread.Sleep(5000);
+ Util.StopThreadPool();
+ WorkManager.Stop();
+
+ Thread.Sleep(1000);
RemovePIDFile();
- base.ShutdownSpecific();
+ m_log.Info("[SHUTDOWN]: Shutdown processing on main thread complete. Exiting...");
- if (!SuppressExit)
+ if (!SuppressExit)
Environment.Exit(0);
}
@@ -163,8 +171,7 @@ namespace OpenSim.Framework.Servers
}
catch(Exception e)
{
- m_log.FatalFormat("Fatal error: {0}",
- (e.Message == null || e.Message == String.Empty) ? "Unknown reason":e.Message );
+ m_log.Fatal("Fatal error: " + e.ToString());
Environment.Exit(1);
}
diff --git a/OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs b/OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs
index fb92b9237a..f4ba02faba 100644
--- a/OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs
+++ b/OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs
@@ -399,11 +399,10 @@ namespace OpenSim.Framework.Servers.HttpServer
Stream requestStream = req.InputStream;
+ string requestBody;
Encoding encoding = Encoding.UTF8;
- StreamReader reader = new StreamReader(requestStream, encoding);
-
- string requestBody = reader.ReadToEnd();
- reader.Close();
+ using(StreamReader reader = new StreamReader(requestStream, encoding))
+ requestBody = reader.ReadToEnd();
Hashtable keysvals = new Hashtable();
Hashtable headervals = new Hashtable();
@@ -567,13 +566,10 @@ namespace OpenSim.Framework.Servers.HttpServer
IGenericHTTPHandler HTTPRequestHandler = requestHandler as IGenericHTTPHandler;
Stream requestStream = request.InputStream;
+ string requestBody;
Encoding encoding = Encoding.UTF8;
- StreamReader reader = new StreamReader(requestStream, encoding);
-
- string requestBody = reader.ReadToEnd();
-
- reader.Close();
- //requestStream.Close();
+ using(StreamReader reader = new StreamReader(requestStream, encoding))
+ requestBody = reader.ReadToEnd();
Hashtable keysvals = new Hashtable();
Hashtable headervals = new Hashtable();
@@ -690,7 +686,8 @@ namespace OpenSim.Framework.Servers.HttpServer
}
}
- request.InputStream.Close();
+ if(request.InputStream.CanRead)
+ request.InputStream.Dispose();
if (buffer != null)
{
@@ -998,7 +995,7 @@ namespace OpenSim.Framework.Servers.HttpServer
{
String requestBody;
- Stream requestStream = request.InputStream;
+ Stream requestStream = Util.Copy(request.InputStream);
Stream innerStream = null;
try
{
@@ -1009,9 +1006,8 @@ namespace OpenSim.Framework.Servers.HttpServer
}
using (StreamReader reader = new StreamReader(requestStream, Encoding.UTF8))
- {
requestBody = reader.ReadToEnd();
- }
+
}
finally
{
@@ -1263,12 +1259,10 @@ namespace OpenSim.Framework.Servers.HttpServer
//m_log.Warn("[BASE HTTP SERVER]: We've figured out it's a LLSD Request");
Stream requestStream = request.InputStream;
+ string requestBody;
Encoding encoding = Encoding.UTF8;
- StreamReader reader = new StreamReader(requestStream, encoding);
-
- string requestBody = reader.ReadToEnd();
- reader.Close();
- requestStream.Close();
+ using(StreamReader reader = new StreamReader(requestStream, encoding))
+ requestBody= reader.ReadToEnd();
//m_log.DebugFormat("[OGP]: {0}:{1}", request.RawUrl, requestBody);
response.KeepAlive = true;
@@ -1592,15 +1586,10 @@ namespace OpenSim.Framework.Servers.HttpServer
byte[] buffer;
Stream requestStream = request.InputStream;
-
+ string requestBody;
Encoding encoding = Encoding.UTF8;
- StreamReader reader = new StreamReader(requestStream, encoding);
-
- string requestBody = reader.ReadToEnd();
- // avoid warning for now
- reader.ReadToEnd();
- reader.Close();
- requestStream.Close();
+ using(StreamReader reader = new StreamReader(requestStream, encoding))
+ requestBody = reader.ReadToEnd();
Hashtable keysvals = new Hashtable();
Hashtable headervals = new Hashtable();
@@ -1838,7 +1827,7 @@ namespace OpenSim.Framework.Servers.HttpServer
Hashtable headerdata = (Hashtable)responsedata["headers"];
foreach (string header in headerdata.Keys)
- response.AddHeader(header, (string)headerdata[header]);
+ response.AddHeader(header, headerdata[header].ToString());
}
byte[] buffer;
@@ -2028,7 +2017,8 @@ namespace OpenSim.Framework.Servers.HttpServer
try
{
- PollServiceRequestManager.Stop();
+ if(PollServiceRequestManager != null)
+ PollServiceRequestManager.Stop();
m_httpListener2.ExceptionThrown -= httpServerException;
//m_httpListener2.DisconnectHandler = null;
diff --git a/OpenSim/Framework/Servers/HttpServer/PollServiceEventArgs.cs b/OpenSim/Framework/Servers/HttpServer/PollServiceEventArgs.cs
index 8ace7a99d0..7150aad1d6 100644
--- a/OpenSim/Framework/Servers/HttpServer/PollServiceEventArgs.cs
+++ b/OpenSim/Framework/Servers/HttpServer/PollServiceEventArgs.cs
@@ -50,7 +50,7 @@ namespace OpenSim.Framework.Servers.HttpServer
public enum EventType : int
{
- LongPoll = 0,
+ Poll = 0,
LslHttp = 1,
Inventory = 2,
Texture = 3,
@@ -82,7 +82,7 @@ namespace OpenSim.Framework.Servers.HttpServer
NoEvents = pNoEvents;
Id = pId;
TimeOutms = pTimeOutms;
- Type = EventType.LongPoll;
+ Type = EventType.Poll;
}
}
}
diff --git a/OpenSim/Framework/Servers/HttpServer/PollServiceHttpRequest.cs b/OpenSim/Framework/Servers/HttpServer/PollServiceHttpRequest.cs
index 0e4a9413d0..fefcb20aa0 100644
--- a/OpenSim/Framework/Servers/HttpServer/PollServiceHttpRequest.cs
+++ b/OpenSim/Framework/Servers/HttpServer/PollServiceHttpRequest.cs
@@ -82,6 +82,9 @@ namespace OpenSim.Framework.Servers.HttpServer
byte[] buffer = server.DoHTTPGruntWork(responsedata, response);
+ if(Request.Body.CanRead)
+ Request.Body.Dispose();
+
response.SendChunked = false;
response.ContentLength64 = buffer.Length;
response.ContentEncoding = Encoding.UTF8;
@@ -107,6 +110,9 @@ namespace OpenSim.Framework.Servers.HttpServer
OSHttpResponse response
= new OSHttpResponse(new HttpResponse(HttpContext, Request), HttpContext);
+ if(Request.Body.CanRead)
+ Request.Body.Dispose();
+
response.SendChunked = false;
response.ContentLength64 = 0;
response.ContentEncoding = Encoding.UTF8;
diff --git a/OpenSim/Framework/Servers/HttpServer/PollServiceRequestManager.cs b/OpenSim/Framework/Servers/HttpServer/PollServiceRequestManager.cs
index 936146d904..c6a3e65154 100644
--- a/OpenSim/Framework/Servers/HttpServer/PollServiceRequestManager.cs
+++ b/OpenSim/Framework/Servers/HttpServer/PollServiceRequestManager.cs
@@ -48,7 +48,6 @@ namespace OpenSim.Framework.Servers.HttpServer
private Dictionary> m_bycontext;
private BlockingQueue m_requests = new BlockingQueue();
- private static Queue m_slowRequests = new Queue();
private static Queue m_retryRequests = new Queue();
private uint m_WorkerThreadCount = 0;
@@ -56,11 +55,9 @@ namespace OpenSim.Framework.Servers.HttpServer
private Thread m_retrysThread;
private bool m_running = false;
- private int slowCount = 0;
private SmartThreadPool m_threadPool;
-
public PollServiceRequestManager(
BaseHttpServer pSrv, bool performResponsesAsync, uint pWorkerThreadCount, int pTimeout)
{
@@ -80,7 +77,6 @@ namespace OpenSim.Framework.Servers.HttpServer
startInfo.ThreadPoolName = "PoolService";
m_threadPool = new SmartThreadPool(startInfo);
-
}
public void Start()
@@ -95,7 +91,7 @@ namespace OpenSim.Framework.Servers.HttpServer
PoolWorkerJob,
string.Format("PollServiceWorkerThread {0}:{1}", i, m_server.Port),
ThreadPriority.Normal,
- false,
+ true,
false,
null,
int.MaxValue);
@@ -105,7 +101,7 @@ namespace OpenSim.Framework.Servers.HttpServer
this.CheckRetries,
string.Format("PollServiceWatcherThread:{0}", m_server.Port),
ThreadPriority.Normal,
- false,
+ true,
true,
null,
1000 * 60 * 10);
@@ -163,17 +159,7 @@ namespace OpenSim.Framework.Servers.HttpServer
public void EnqueueInt(PollServiceHttpRequest req)
{
if (m_running)
- {
- if (req.PollServiceArgs.Type != PollServiceEventArgs.EventType.LongPoll)
- {
- m_requests.Enqueue(req);
- }
- else
- {
- lock (m_slowRequests)
- m_slowRequests.Enqueue(req);
- }
- }
+ m_requests.Enqueue(req);
}
private void CheckRetries()
@@ -188,17 +174,6 @@ namespace OpenSim.Framework.Servers.HttpServer
while (m_retryRequests.Count > 0 && m_running)
m_requests.Enqueue(m_retryRequests.Dequeue());
}
- slowCount++;
- if (slowCount >= 10)
- {
- slowCount = 0;
-
- lock (m_slowRequests)
- {
- while (m_slowRequests.Count > 0 && m_running)
- m_requests.Enqueue(m_slowRequests.Dequeue());
- }
- }
}
}
@@ -206,11 +181,13 @@ namespace OpenSim.Framework.Servers.HttpServer
{
m_running = false;
- Thread.Sleep(1000); // let the world move
+ Thread.Sleep(100); // let the world move
foreach (Thread t in m_workerThreads)
Watchdog.AbortThread(t.ManagedThreadId);
+ m_threadPool.Shutdown();
+
// any entry in m_bycontext should have a active request on the other queues
// so just delete contents to easy GC
foreach (Queue qu in m_bycontext.Values)
@@ -229,22 +206,15 @@ namespace OpenSim.Framework.Servers.HttpServer
}
PollServiceHttpRequest wreq;
+
m_retryRequests.Clear();
- lock (m_slowRequests)
- {
- while (m_slowRequests.Count > 0)
- m_requests.Enqueue(m_slowRequests.Dequeue());
-
- }
-
while (m_requests.Count() > 0)
{
try
{
wreq = m_requests.Dequeue(0);
wreq.DoHTTPstop(m_server);
-
}
catch
{
@@ -260,8 +230,7 @@ namespace OpenSim.Framework.Servers.HttpServer
{
while (m_running)
{
- PollServiceHttpRequest req = m_requests.Dequeue(5000);
-
+ PollServiceHttpRequest req = m_requests.Dequeue(4500);
Watchdog.UpdateThread();
if (req != null)
{
@@ -276,11 +245,13 @@ namespace OpenSim.Framework.Servers.HttpServer
try
{
req.DoHTTPGruntWork(m_server, responsedata);
- byContextDequeue(req);
}
- catch (ObjectDisposedException) // Browser aborted before we could read body, server closed the stream
+ catch (ObjectDisposedException)
{
- // Ignore it, no need to reply
+ }
+ finally
+ {
+ byContextDequeue(req);
}
return null;
}, null);
@@ -295,12 +266,15 @@ namespace OpenSim.Framework.Servers.HttpServer
{
req.DoHTTPGruntWork(m_server,
req.PollServiceArgs.NoEvents(req.RequestID, req.PollServiceArgs.Id));
- byContextDequeue(req);
}
catch (ObjectDisposedException)
{
// Ignore it, no need to reply
}
+ finally
+ {
+ byContextDequeue(req);
+ }
return null;
}, null);
}
diff --git a/OpenSim/Framework/Servers/HttpServer/RestStreamHandler.cs b/OpenSim/Framework/Servers/HttpServer/RestStreamHandler.cs
index 0305dee118..dfc27157a3 100644
--- a/OpenSim/Framework/Servers/HttpServer/RestStreamHandler.cs
+++ b/OpenSim/Framework/Servers/HttpServer/RestStreamHandler.cs
@@ -50,11 +50,10 @@ namespace OpenSim.Framework.Servers.HttpServer
protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
+ string requestBody;
Encoding encoding = Encoding.UTF8;
- StreamReader streamReader = new StreamReader(request, encoding);
-
- string requestBody = streamReader.ReadToEnd();
- streamReader.Close();
+ using(StreamReader streamReader = new StreamReader(request,encoding))
+ requestBody = streamReader.ReadToEnd();
string param = GetParam(path);
string responseString = m_restMethod(requestBody, path, param, httpRequest, httpResponse);
diff --git a/OpenSim/Framework/Servers/MainServer.cs b/OpenSim/Framework/Servers/MainServer.cs
index ea7b2b56c4..9b1d9068c7 100644
--- a/OpenSim/Framework/Servers/MainServer.cs
+++ b/OpenSim/Framework/Servers/MainServer.cs
@@ -353,5 +353,17 @@ namespace OpenSim.Framework.Servers
return m_Servers[port];
}
}
+
+ public static void Stop()
+ {
+ lock (m_Servers)
+ {
+ foreach (BaseHttpServer httpServer in m_Servers.Values)
+ {
+ httpServer.Stop();
+ }
+ }
+ }
+
}
}
\ No newline at end of file
diff --git a/OpenSim/Framework/Servers/ServerBase.cs b/OpenSim/Framework/Servers/ServerBase.cs
index 8965e71a34..3c2dce81c8 100644
--- a/OpenSim/Framework/Servers/ServerBase.cs
+++ b/OpenSim/Framework/Servers/ServerBase.cs
@@ -57,6 +57,7 @@ namespace OpenSim.Framework.Servers
protected OpenSimAppender m_consoleAppender;
protected FileAppender m_logFileAppender;
+ protected FileAppender m_statsLogFileAppender;
protected DateTime m_startuptime;
protected string m_startupDirectory = Environment.CurrentDirectory;
@@ -156,6 +157,10 @@ namespace OpenSim.Framework.Servers
{
m_logFileAppender = (FileAppender)appender;
}
+ else if (appender.Name == "StatsLogFileAppender")
+ {
+ m_statsLogFileAppender = (FileAppender)appender;
+ }
}
if (null == m_consoleAppender)
@@ -185,6 +190,18 @@ namespace OpenSim.Framework.Servers
m_log.InfoFormat("[SERVER BASE]: Logging started to file {0}", m_logFileAppender.File);
}
+
+ if (m_statsLogFileAppender != null && startupConfig != null)
+ {
+ string cfgStatsFileName = startupConfig.GetString("StatsLogFile", null);
+ if (cfgStatsFileName != null)
+ {
+ m_statsLogFileAppender.File = cfgStatsFileName;
+ m_statsLogFileAppender.ActivateOptions();
+ }
+
+ m_log.InfoFormat("[SERVER BASE]: Stats Logging started to file {0}", m_statsLogFileAppender.File);
+ }
}
///
@@ -257,18 +274,6 @@ namespace OpenSim.Framework.Servers
"Show thread status. Synonym for \"show threads\"",
(string module, string[] args) => Notice(GetThreadsReport()));
- m_console.Commands.AddCommand (
- "Debug", false, "debug comms set",
- "debug comms set serialosdreq true|false",
- "Set comms parameters. For debug purposes.",
- HandleDebugCommsSet);
-
- m_console.Commands.AddCommand (
- "Debug", false, "debug comms status",
- "debug comms status",
- "Show current debug comms parameters.",
- HandleDebugCommsStatus);
-
m_console.Commands.AddCommand (
"Debug", false, "debug threadpool set",
"debug threadpool set worker|iocp min|max ",
@@ -326,47 +331,13 @@ namespace OpenSim.Framework.Servers
public void RegisterCommonComponents(IConfigSource configSource)
{
- IConfig networkConfig = configSource.Configs["Network"];
-
- if (networkConfig != null)
- {
- WebUtil.SerializeOSDRequestsPerEndpoint = networkConfig.GetBoolean("SerializeOSDRequests", false);
- }
+// IConfig networkConfig = configSource.Configs["Network"];
m_serverStatsCollector = new ServerStatsCollector();
m_serverStatsCollector.Initialise(configSource);
m_serverStatsCollector.Start();
}
- private void HandleDebugCommsStatus(string module, string[] args)
- {
- Notice("serialosdreq is {0}", WebUtil.SerializeOSDRequestsPerEndpoint);
- }
-
- private void HandleDebugCommsSet(string module, string[] args)
- {
- if (args.Length != 5)
- {
- Notice("Usage: debug comms set serialosdreq true|false");
- return;
- }
-
- if (args[3] != "serialosdreq")
- {
- Notice("Usage: debug comms set serialosdreq true|false");
- return;
- }
-
- bool setSerializeOsdRequests;
-
- if (!ConsoleUtil.TryParseConsoleBool(m_console, args[4], out setSerializeOsdRequests))
- return;
-
- WebUtil.SerializeOSDRequestsPerEndpoint = setSerializeOsdRequests;
-
- Notice("serialosdreq is now {0}", setSerializeOsdRequests);
- }
-
private void HandleShowThreadpoolCallsActive(string module, string[] args)
{
List> calls = Util.GetFireAndForgetCallsInProgress().ToList();
@@ -911,16 +882,12 @@ namespace OpenSim.Framework.Servers
sb.Append("\n");
}
- sb.Append("\n");
+ sb.Append(GetThreadPoolReport());
- // For some reason mono 2.6.7 returns an empty threads set! Not going to confuse people by reporting
- // zero active threads.
+ sb.Append("\n");
int totalThreads = Process.GetCurrentProcess().Threads.Count;
if (totalThreads > 0)
- sb.AppendFormat("Total threads active: {0}\n\n", totalThreads);
-
- sb.Append("Main threadpool (excluding script engine pools)\n");
- sb.Append(GetThreadPoolReport());
+ sb.AppendFormat("Total process threads active: {0}\n\n", totalThreads);
return sb.ToString();
}
@@ -931,15 +898,46 @@ namespace OpenSim.Framework.Servers
///
public static string GetThreadPoolReport()
{
+
+ StringBuilder sb = new StringBuilder();
+
+ // framework pool is alwasy active
+ int maxWorkers;
+ int minWorkers;
+ int curWorkers;
+ int maxComp;
+ int minComp;
+ int curComp;
+
+ try
+ {
+ ThreadPool.GetMaxThreads(out maxWorkers, out maxComp);
+ ThreadPool.GetMinThreads(out minWorkers, out minComp);
+ ThreadPool.GetAvailableThreads(out curWorkers, out curComp);
+ curWorkers = maxWorkers - curWorkers;
+ curComp = maxComp - curComp;
+
+ sb.Append("\nFramework main threadpool \n");
+ sb.AppendFormat("workers: {0} ({1} / {2})\n", curWorkers, maxWorkers, minWorkers);
+ sb.AppendFormat("Completion: {0} ({1} / {2})\n", curComp, maxComp, minComp);
+ }
+ catch { }
+
+ if (
+ Util.FireAndForgetMethod == FireAndForgetMethod.QueueUserWorkItem
+ || Util.FireAndForgetMethod == FireAndForgetMethod.UnsafeQueueUserWorkItem)
+ {
+ sb.AppendFormat("\nThread pool used: Framework main threadpool\n");
+ return sb.ToString();
+ }
+
string threadPoolUsed = null;
int maxThreads = 0;
int minThreads = 0;
int allocatedThreads = 0;
int inUseThreads = 0;
int waitingCallbacks = 0;
- int completionPortThreads = 0;
- StringBuilder sb = new StringBuilder();
if (Util.FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool)
{
STPInfo stpi = Util.GetSmartThreadPoolInfo();
@@ -955,22 +953,10 @@ namespace OpenSim.Framework.Servers
waitingCallbacks = stpi.WaitingCallbacks;
}
}
- else if (
- Util.FireAndForgetMethod == FireAndForgetMethod.QueueUserWorkItem
- || Util.FireAndForgetMethod == FireAndForgetMethod.UnsafeQueueUserWorkItem)
- {
- threadPoolUsed = "BuiltInThreadPool";
- ThreadPool.GetMaxThreads(out maxThreads, out completionPortThreads);
- ThreadPool.GetMinThreads(out minThreads, out completionPortThreads);
- int availableThreads;
- ThreadPool.GetAvailableThreads(out availableThreads, out completionPortThreads);
- inUseThreads = maxThreads - availableThreads;
- allocatedThreads = -1;
- waitingCallbacks = -1;
- }
-
+
if (threadPoolUsed != null)
{
+ sb.Append("\nThreadpool (excluding script engine pools)\n");
sb.AppendFormat("Thread pool used : {0}\n", threadPoolUsed);
sb.AppendFormat("Max threads : {0}\n", maxThreads);
sb.AppendFormat("Min threads : {0}\n", minThreads);
diff --git a/OpenSim/Framework/Util.cs b/OpenSim/Framework/Util.cs
index 6d679f2c12..a42dcc6f6c 100644
--- a/OpenSim/Framework/Util.cs
+++ b/OpenSim/Framework/Util.cs
@@ -63,22 +63,37 @@ namespace OpenSim.Framework
None = 0,
// folded perms
- foldedTransfer = 1,
- foldedModify = 1 << 1,
- foldedCopy = 1 << 2,
+ FoldedTransfer = 1,
+ FoldedModify = 1 << 1,
+ FoldedCopy = 1 << 2,
+ FoldedExport = 1 << 3,
- foldedMask = 0x07,
+ // DO NOT USE THIS FOR NEW WORK. IT IS DEPRECATED AND
+ // EXISTS ONLY TO REACT TO EXISTING OBJECTS HAVING IT.
+ // NEW CODE SHOULD NEVER SET THIS BIT!
+ // Use InventoryItemFlags.ObjectSlamPerm in the Flags field of
+ // this legacy slam bit. It comes from prior incomplete
+ // understanding of the code and the prohibition on
+ // reading viewer code that used to be in place.
+ Slam = (1 << 4),
- //
- Transfer = 1 << 13,
- Modify = 1 << 14,
- Copy = 1 << 15,
- Export = 1 << 16,
- Move = 1 << 19,
- Damage = 1 << 20,
+ FoldedMask = 0x0f,
+
+ FoldingShift = 13 , // number of bit shifts from normal perm to folded or back (same as Transfer shift below)
+ // when doing as a block
+
+ Transfer = 1 << 13, // 0x02000
+ Modify = 1 << 14, // 0x04000
+ Copy = 1 << 15, // 0x08000
+ Export = 1 << 16, // 0x10000
+ Move = 1 << 19, // 0x80000
+ Damage = 1 << 20, // 0x100000 does not seem to be in use
// All does not contain Export, which is special and must be
// explicitly given
- All = (1 << 13) | (1 << 14) | (1 << 15) | (1 << 19)
+ All = 0x8e000,
+ AllAndExport = 0x9e000,
+ AllEffective = 0x9e000,
+ UnfoldedMask = 0x1e000
}
///
@@ -141,12 +156,14 @@ namespace OpenSim.Framework
public static readonly int MAX_THREADPOOL_LEVEL = 3;
public static double TimeStampClockPeriodMS;
+ public static double TimeStampClockPeriod;
static Util()
{
LogThreadPool = 0;
LogOverloads = true;
- TimeStampClockPeriodMS = 1000.0D / (double)Stopwatch.Frequency;
+ TimeStampClockPeriod = 1.0D/ (double)Stopwatch.Frequency;
+ TimeStampClockPeriodMS = 1e3 * TimeStampClockPeriod;
m_log.InfoFormat("[UTIL] TimeStamp clock with period of {0}ms", Math.Round(TimeStampClockPeriodMS,6,MidpointRounding.AwayFromZero));
}
@@ -414,6 +431,7 @@ namespace OpenSim.Framework
return regionCoord << 8;
}
+
public static bool checkServiceURI(string uristr, out string serviceURI)
{
serviceURI = string.Empty;
@@ -975,6 +993,8 @@ namespace OpenSim.Framework
return output.ToString();
}
+ private static ExpiringCache dnscache = new ExpiringCache();
+
///
/// Converts a URL to a IPAddress
///
@@ -992,38 +1012,128 @@ namespace OpenSim.Framework
/// An IP address, or null
public static IPAddress GetHostFromDNS(string dnsAddress)
{
- // Is it already a valid IP? No need to look it up.
- IPAddress ipa;
- if (IPAddress.TryParse(dnsAddress, out ipa))
- return ipa;
+ if(String.IsNullOrWhiteSpace(dnsAddress))
+ return null;
- IPAddress[] hosts = null;
+ IPAddress ia = null;
+ if(dnscache.TryGetValue(dnsAddress, out ia) && ia != null)
+ {
+ dnscache.AddOrUpdate(dnsAddress, ia, 300);
+ return ia;
+ }
- // Not an IP, lookup required
+ ia = null;
+ // If it is already an IP, don't let GetHostEntry see it
+ if (IPAddress.TryParse(dnsAddress, out ia) && ia != null)
+ {
+ if (ia.Equals(IPAddress.Any) || ia.Equals(IPAddress.IPv6Any))
+ return null;
+ dnscache.AddOrUpdate(dnsAddress, ia, 300);
+ return ia;
+ }
+
+ IPHostEntry IPH;
try
{
- hosts = Dns.GetHostEntry(dnsAddress).AddressList;
+ IPH = Dns.GetHostEntry(dnsAddress);
}
- catch (Exception e)
+ catch // (SocketException e)
{
- m_log.WarnFormat("[UTIL]: An error occurred while resolving host name {0}, {1}", dnsAddress, e);
-
- // Still going to throw the exception on for now, since this was what was happening in the first place
- throw e;
+ return null;
}
- foreach (IPAddress host in hosts)
+ if(IPH == null || IPH.AddressList.Length == 0)
+ return null;
+
+ ia = null;
+ foreach (IPAddress Adr in IPH.AddressList)
{
- if (host.AddressFamily == AddressFamily.InterNetwork)
+ if (ia == null)
+ ia = Adr;
+
+ if (Adr.AddressFamily == AddressFamily.InterNetwork)
{
- return host;
+ ia = Adr;
+ break;
+ }
+ }
+ if(ia != null)
+ dnscache.AddOrUpdate(dnsAddress, ia, 300);
+ return ia;
+ }
+
+ public static IPEndPoint getEndPoint(IPAddress ia, int port)
+ {
+ if(ia == null)
+ return null;
+
+ IPEndPoint newEP = null;
+ try
+ {
+ newEP = new IPEndPoint(ia, port);
+ }
+ catch
+ {
+ newEP = null;
+ }
+ return newEP;
+ }
+
+ public static IPEndPoint getEndPoint(string hostname, int port)
+ {
+ if(String.IsNullOrWhiteSpace(hostname))
+ return null;
+
+ IPAddress ia = null;
+ if(dnscache.TryGetValue(hostname, out ia) && ia != null)
+ {
+ dnscache.AddOrUpdate(hostname, ia, 300);
+ return getEndPoint(ia, port);
+ }
+
+ ia = null;
+
+ // If it is already an IP, don't let GetHostEntry see it
+ if (IPAddress.TryParse(hostname, out ia) && ia != null)
+ {
+ if (ia.Equals(IPAddress.Any) || ia.Equals(IPAddress.IPv6Any))
+ return null;
+
+ dnscache.AddOrUpdate(hostname, ia, 300);
+ return getEndPoint(ia, port);
+ }
+
+
+ IPHostEntry IPH;
+ try
+ {
+ IPH = Dns.GetHostEntry(hostname);
+ }
+ catch // (SocketException e)
+ {
+ return null;
+ }
+
+ if(IPH == null || IPH.AddressList.Length == 0)
+ return null;
+
+ ia = null;
+ foreach (IPAddress Adr in IPH.AddressList)
+ {
+ if (ia == null)
+ ia = Adr;
+
+ if (Adr.AddressFamily == AddressFamily.InterNetwork)
+ {
+ ia = Adr;
+ break;
}
}
- if (hosts.Length > 0)
- return hosts[0];
+ if(ia != null)
+ dnscache.AddOrUpdate(hostname, ia, 300);
- return null;
+ return getEndPoint(ia,port);
}
public static Uri GetURI(string protocol, string hostname, int port, string path)
@@ -1180,7 +1290,7 @@ namespace OpenSim.Framework
{
foreach (IAppender appender in LogManager.GetRepository().GetAppenders())
{
- if (appender is FileAppender)
+ if (appender is FileAppender && appender.Name == "LogFileAppender")
{
return ((FileAppender)appender).File;
}
@@ -1189,6 +1299,19 @@ namespace OpenSim.Framework
return "./OpenSim.log";
}
+ public static string statsLogFile()
+ {
+ foreach (IAppender appender in LogManager.GetRepository().GetAppenders())
+ {
+ if (appender is FileAppender && appender.Name == "StatsLogFileAppender")
+ {
+ return ((FileAppender)appender).File;
+ }
+ }
+
+ return "./OpenSimStats.log";
+ }
+
public static string logDir()
{
return Path.GetDirectoryName(logFile());
@@ -2100,9 +2223,9 @@ namespace OpenSim.Framework
// might have gotten an oversized array even after the string trim
byte[] data = UTF8.GetBytes(str);
- if (data.Length > 256)
+ if (data.Length > 255) //play safe
{
- int cut = 255;
+ int cut = 254;
if((data[cut] & 0x80 ) != 0 )
{
while(cut > 0 && (data[cut] & 0xc0) != 0xc0)
@@ -2204,7 +2327,7 @@ namespace OpenSim.Framework
if (data.Length > MaxLength)
{
- int cut = MaxLength -1 ;
+ int cut = MaxLength - 1 ;
if((data[cut] & 0x80 ) != 0 )
{
while(cut > 0 && (data[cut] & 0xc0) != 0xc0)
@@ -2371,8 +2494,9 @@ namespace OpenSim.Framework
public bool Running { get; set; }
public bool Aborted { get; set; }
private int started;
+ public bool DoTimeout;
- public ThreadInfo(long threadFuncNum, string context)
+ public ThreadInfo(long threadFuncNum, string context, bool dotimeout = true)
{
ThreadFuncNum = threadFuncNum;
this.context = context;
@@ -2380,6 +2504,7 @@ namespace OpenSim.Framework
Thread = null;
Running = false;
Aborted = false;
+ DoTimeout = dotimeout;
}
public void Started()
@@ -2450,7 +2575,7 @@ namespace OpenSim.Framework
foreach (KeyValuePair entry in activeThreads)
{
ThreadInfo t = entry.Value;
- if (t.Running && !t.Aborted && (t.Elapsed() >= THREAD_TIMEOUT))
+ if (t.DoTimeout && t.Running && !t.Aborted && (t.Elapsed() >= THREAD_TIMEOUT))
{
m_log.WarnFormat("Timeout in threadfunc {0} ({1}) {2}", t.ThreadFuncNum, t.Thread.Name, t.GetStackTrace());
t.Abort();
@@ -2491,10 +2616,10 @@ namespace OpenSim.Framework
FireAndForget(callback, obj, null);
}
- public static void FireAndForget(System.Threading.WaitCallback callback, object obj, string context)
+ public static void FireAndForget(System.Threading.WaitCallback callback, object obj, string context, bool dotimeout = true)
{
Interlocked.Increment(ref numTotalThreadFuncsCalled);
-
+/*
if (context != null)
{
if (!m_fireAndForgetCallsMade.ContainsKey(context))
@@ -2507,13 +2632,13 @@ namespace OpenSim.Framework
else
m_fireAndForgetCallsInProgress[context]++;
}
-
+*/
WaitCallback realCallback;
bool loggingEnabled = LogThreadPool > 0;
long threadFuncNum = Interlocked.Increment(ref nextThreadFuncNum);
- ThreadInfo threadInfo = new ThreadInfo(threadFuncNum, context);
+ ThreadInfo threadInfo = new ThreadInfo(threadFuncNum, context, dotimeout);
if (FireAndForgetMethod == FireAndForgetMethod.RegressionTest)
{
@@ -2524,8 +2649,8 @@ namespace OpenSim.Framework
Culture.SetCurrentCulture();
callback(o);
- if (context != null)
- m_fireAndForgetCallsInProgress[context]--;
+// if (context != null)
+// m_fireAndForgetCallsInProgress[context]--;
};
}
else
@@ -2551,7 +2676,6 @@ namespace OpenSim.Framework
}
catch (ThreadAbortException e)
{
- m_log.Error(string.Format("Aborted threadfunc {0} ", threadFuncNum), e);
}
catch (Exception e)
{
@@ -2566,8 +2690,8 @@ namespace OpenSim.Framework
if ((loggingEnabled || (threadFuncOverloadMode == 1)) && threadInfo.LogThread)
m_log.DebugFormat("Exit threadfunc {0} ({1})", threadFuncNum, FormatDuration(threadInfo.Elapsed()));
- if (context != null)
- m_fireAndForgetCallsInProgress[context]--;
+// if (context != null)
+// m_fireAndForgetCallsInProgress[context]--;
}
};
}
@@ -2824,6 +2948,16 @@ namespace OpenSim.Framework
return stpi;
}
+ public static void StopThreadPool()
+ {
+ if (m_ThreadPool == null)
+ return;
+ SmartThreadPool pool = m_ThreadPool;
+ m_ThreadPool = null;
+
+ try { pool.Shutdown(); } catch {}
+ }
+
#endregion FireAndForget Threading Pattern
///
@@ -2837,6 +2971,7 @@ namespace OpenSim.Framework
{
return Environment.TickCount & EnvironmentTickCountMask;
}
+
const Int32 EnvironmentTickCountMask = 0x3fffffff;
///
@@ -2883,6 +3018,11 @@ namespace OpenSim.Framework
// returns a timestamp in ms as double
// using the time resolution avaiable to StopWatch
+ public static double GetTimeStamp()
+ {
+ return (double)Stopwatch.GetTimestamp() * TimeStampClockPeriod;
+ }
+
public static double GetTimeStampMS()
{
return (double)Stopwatch.GetTimestamp() * TimeStampClockPeriodMS;
diff --git a/OpenSim/Framework/WearableCacheItem.cs b/OpenSim/Framework/WearableCacheItem.cs
index ccaf69edfd..427e149f69 100644
--- a/OpenSim/Framework/WearableCacheItem.cs
+++ b/OpenSim/Framework/WearableCacheItem.cs
@@ -113,7 +113,8 @@ namespace OpenSim.Framework
{
if (dataCache.Check(item.TextureID.ToString()))
{
- AssetBase assetItem = dataCache.Get(item.TextureID.ToString());
+ AssetBase assetItem;
+ dataCache.Get(item.TextureID.ToString(), out assetItem);
if (assetItem != null)
{
itemmap.Add("assetdata", OSD.FromBinary(assetItem.Data));
diff --git a/OpenSim/Framework/WebUtil.cs b/OpenSim/Framework/WebUtil.cs
index 12f58feb79..48078ada97 100644
--- a/OpenSim/Framework/WebUtil.cs
+++ b/OpenSim/Framework/WebUtil.cs
@@ -71,11 +71,6 @@ namespace OpenSim.Framework
///
public static int RequestNumber { get; set; }
- ///
- /// Control where OSD requests should be serialized per endpoint.
- ///
- public static bool SerializeOSDRequestsPerEndpoint { get; set; }
-
///
/// this is the header field used to communicate the local request id
/// used for performance and debugging
@@ -98,31 +93,6 @@ namespace OpenSim.Framework
///
public const int MaxRequestDiagLength = 200;
- ///
- /// Dictionary of end points
- ///
- private static Dictionary m_endpointSerializer = new Dictionary();
-
- private static object EndPointLock(string url)
- {
- System.Uri uri = new System.Uri(url);
- string endpoint = string.Format("{0}:{1}",uri.Host,uri.Port);
-
- lock (m_endpointSerializer)
- {
- object eplock = null;
-
- if (! m_endpointSerializer.TryGetValue(endpoint,out eplock))
- {
- eplock = new object();
- m_endpointSerializer.Add(endpoint,eplock);
- // m_log.WarnFormat("[WEB UTIL] add a new host to end point serializer {0}",endpoint);
- }
-
- return eplock;
- }
- }
-
#region JSONRequest
///
@@ -154,21 +124,6 @@ namespace OpenSim.Framework
return ServiceOSDRequest(url, null, "GET", timeout, false, false);
}
- public static OSDMap ServiceOSDRequest(string url, OSDMap data, string method, int timeout, bool compressed, bool rpc)
- {
- if (SerializeOSDRequestsPerEndpoint)
- {
- lock (EndPointLock(url))
- {
- return ServiceOSDRequestWorker(url, data, method, timeout, compressed, rpc);
- }
- }
- else
- {
- return ServiceOSDRequestWorker(url, data, method, timeout, compressed, rpc);
- }
- }
-
public static void LogOutgoingDetail(Stream outputStream)
{
LogOutgoingDetail("", outputStream);
@@ -222,7 +177,7 @@ namespace OpenSim.Framework
LogOutgoingDetail(string.Format("RESPONSE {0}: ", reqnum), input);
}
- private static OSDMap ServiceOSDRequestWorker(string url, OSDMap data, string method, int timeout, bool compressed, bool rpc)
+ public static OSDMap ServiceOSDRequest(string url, OSDMap data, string method, int timeout, bool compressed, bool rpc)
{
int reqnum = RequestNumber++;
@@ -421,14 +376,6 @@ namespace OpenSim.Framework
}
public static OSDMap ServiceFormRequest(string url, NameValueCollection data, int timeout)
- {
- lock (EndPointLock(url))
- {
- return ServiceFormRequestWorker(url,data,timeout);
- }
- }
-
- private static OSDMap ServiceFormRequestWorker(string url, NameValueCollection data, int timeout)
{
int reqnum = RequestNumber++;
string method = (data != null && data["RequestMethod"] != null) ? data["RequestMethod"] : "unknown";
@@ -1315,18 +1262,24 @@ namespace OpenSim.Framework
{
if (hwr.StatusCode == HttpStatusCode.NotFound)
return deserial;
+
if (hwr.StatusCode == HttpStatusCode.Unauthorized)
{
- m_log.Error(string.Format(
- "[SynchronousRestObjectRequester]: Web request {0} requires authentication ",
- requestUrl));
- return deserial;
+ m_log.ErrorFormat("[SynchronousRestObjectRequester]: Web request {0} requires authentication",
+ requestUrl);
+ }
+ else
+ {
+ m_log.WarnFormat("[SynchronousRestObjectRequester]: Web request {0} returned error: {1}",
+ requestUrl, hwr.StatusCode);
}
}
else
- m_log.Error(string.Format(
- "[SynchronousRestObjectRequester]: WebException for {0} {1} {2} ",
- verb, requestUrl, typeof(TResponse).ToString()), e);
+ m_log.ErrorFormat(
+ "[SynchronousRestObjectRequester]: WebException for {0} {1} {2} {3}",
+ verb, requestUrl, typeof(TResponse).ToString(), e.Message);
+
+ return deserial;
}
}
catch (System.InvalidOperationException)
diff --git a/OpenSim/Region/Application/Application.cs b/OpenSim/Region/Application/Application.cs
index 5cb6a88e94..66ce8e5e3d 100644
--- a/OpenSim/Region/Application/Application.cs
+++ b/OpenSim/Region/Application/Application.cs
@@ -74,7 +74,15 @@ namespace OpenSim
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
- ServicePointManager.DefaultConnectionLimit = 12;
+ if(Util.IsWindows())
+ ServicePointManager.DefaultConnectionLimit = 32;
+ else
+ {
+ ServicePointManager.DefaultConnectionLimit = 12;
+ }
+
+ try { ServicePointManager.DnsRefreshTimeout = 300000; } catch { }
+ ServicePointManager.Expect100Continue = false;
ServicePointManager.UseNagleAlgorithm = false;
// Add the arguments supplied when running the application to the configuration
diff --git a/OpenSim/Region/Application/OpenSim.cs b/OpenSim/Region/Application/OpenSim.cs
index 8022b1e587..fcc87177a6 100644
--- a/OpenSim/Region/Application/OpenSim.cs
+++ b/OpenSim/Region/Application/OpenSim.cs
@@ -33,6 +33,7 @@ using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
+using System.Runtime;
using System.Text;
using System.Text.RegularExpressions;
using System.Timers;
@@ -124,8 +125,11 @@ namespace OpenSim
Util.InitThreadPool(stpMinThreads, stpMaxThreads);
m_log.Info("[OPENSIM MAIN]: Using async_call_method " + Util.FireAndForgetMethod);
+
+ m_log.InfoFormat("[OPENSIM MAIN] Running GC in {0} mode", GCSettings.IsServerGC ? "server":"workstation");
}
+#if (_MONO)
private static Mono.Unix.UnixSignal[] signals;
@@ -139,7 +143,8 @@ namespace OpenSim
//Mono.Unix.Native.Signum signal = signals [index].Signum;
MainConsole.Instance.RunCommand("shutdown");
}
- });
+ });
+#endif
///
/// Performs initialisation of the scene, such as loading configuration from disk.
@@ -150,6 +155,7 @@ namespace OpenSim
m_log.Info("========================= STARTING OPENSIM =========================");
m_log.Info("====================================================================");
+#if (_MONO)
if(!Util.IsWindows())
{
try
@@ -159,6 +165,7 @@ namespace OpenSim
{
new Mono.Unix.UnixSignal(Mono.Unix.Native.Signum.SIGTERM)
};
+ signal_thread.IsBackground = true;
signal_thread.Start();
}
catch (Exception e)
@@ -168,6 +175,7 @@ namespace OpenSim
m_log.Debug("Exception was: ", e);
}
}
+#endif
//m_log.InfoFormat("[OPENSIM MAIN]: GC Is Server GC: {0}", GCSettings.IsServerGC.ToString());
// http://msdn.microsoft.com/en-us/library/bb384202.aspx
//GCSettings.LatencyMode = GCLatencyMode.Batch;
@@ -211,6 +219,7 @@ namespace OpenSim
if (managedStatsURI != String.Empty)
{
string urlBase = String.Format("/{0}/", managedStatsURI);
+ StatsManager.StatsPassword = managedStatsPassword;
MainServer.Instance.AddHTTPHandler(urlBase, StatsManager.HandleStatsRequest);
m_log.InfoFormat("[OPENSIM] Enabling remote managed stats fetch. URL = {0}", urlBase);
}
@@ -477,6 +486,12 @@ namespace OpenSim
RunCommandScript(m_shutdownCommandsFile);
}
+ if (m_timedScript != "disabled")
+ {
+ m_scriptTimer.Dispose();
+ m_timedScript = "disabled";
+ }
+
base.ShutdownSpecific();
}
@@ -496,7 +511,6 @@ namespace OpenSim
private void WatchdogTimeoutHandler(Watchdog.ThreadWatchdogInfo twi)
{
int now = Environment.TickCount & Int32.MaxValue;
-
m_log.ErrorFormat(
"[WATCHDOG]: Timeout detected for thread \"{0}\". ThreadState={1}. Last tick was {2}ms ago. {3}",
twi.Thread.Name,
diff --git a/OpenSim/Region/Application/OpenSimBase.cs b/OpenSim/Region/Application/OpenSimBase.cs
index b33e2c2784..0862fcf302 100644
--- a/OpenSim/Region/Application/OpenSimBase.cs
+++ b/OpenSim/Region/Application/OpenSimBase.cs
@@ -88,6 +88,7 @@ namespace OpenSim
public string userStatsURI = String.Empty;
public string managedStatsURI = String.Empty;
+ public string managedStatsPassword = String.Empty;
protected bool m_autoCreateClientStack = true;
@@ -236,9 +237,10 @@ namespace OpenSim
string permissionModules = Util.GetConfigVarFromSections(Config, "permissionmodules",
new string[] { "Startup", "Permissions" }, "DefaultPermissionsModule");
- m_permsModules = new List(permissionModules.Split(','));
+ m_permsModules = new List(permissionModules.Split(',').Select(m => m.Trim()));
managedStatsURI = startupConfig.GetString("ManagedStatsRemoteFetchURI", String.Empty);
+ managedStatsPassword = startupConfig.GetString("ManagedStatsRemoteFetchPassword", String.Empty);
}
// Load the simulation data service
@@ -459,15 +461,14 @@ namespace OpenSim
while (regionInfo.EstateSettings.EstateOwner == UUID.Zero && MainConsole.Instance != null)
SetUpEstateOwner(scene);
+ scene.loadAllLandObjectsFromStorage(regionInfo.originRegionID);
+
// Prims have to be loaded after module configuration since some modules may be invoked during the load
scene.LoadPrimsFromStorage(regionInfo.originRegionID);
// TODO : Try setting resource for region xstats here on scene
MainServer.Instance.AddStreamHandler(new RegionStatsHandler(regionInfo));
- scene.loadAllLandObjectsFromStorage(regionInfo.originRegionID);
- scene.EventManager.TriggerParcelPrimCountUpdate();
-
if (scene.SnmpService != null)
{
scene.SnmpService.BootInfo("Grid Registration in progress", scene);
diff --git a/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/BunchOfCaps.cs b/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/BunchOfCaps.cs
index 58b7b00169..6f5775ad3d 100644
--- a/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/BunchOfCaps.cs
+++ b/OpenSim/Region/ClientStack/Linden/Caps/BunchOfCaps/BunchOfCaps.cs
@@ -946,17 +946,26 @@ namespace OpenSim.Region.ClientStack.Linden
continue;
}
- PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox();
+ OSDArray face_list = (OSDArray)inner_instance_list["face_list"];
+
+ PrimitiveBaseShape pbs = null;
+ if (inner_instance_list.ContainsKey("mesh")) // seems to happen always but ...
+ {
+ int meshindx = inner_instance_list["mesh"].AsInteger();
+ if (meshAssets.Count > meshindx)
+ pbs = PrimitiveBaseShape.CreateMesh(face_list.Count, meshAssets[meshindx]);
+ }
+ if(pbs == null) // fallback
+ pbs = PrimitiveBaseShape.CreateBox();
Primitive.TextureEntry textureEntry
= new Primitive.TextureEntry(Primitive.TextureEntry.WHITE_TEXTURE);
-
- OSDArray face_list = (OSDArray)inner_instance_list["face_list"];
for (uint face = 0; face < face_list.Count; face++)
{
OSDMap faceMap = (OSDMap)face_list[(int)face];
- Primitive.TextureEntryFace f = pbs.Textures.CreateFace(face);
+
+ Primitive.TextureEntryFace f = textureEntry.CreateFace(face); //clone the default
if (faceMap.ContainsKey("fullbright"))
f.Fullbright = faceMap["fullbright"].AsBoolean();
if (faceMap.ContainsKey("diffuse_color"))
@@ -986,51 +995,11 @@ namespace OpenSim.Region.ClientStack.Linden
if (textures.Count > textureNum)
f.TextureID = textures[textureNum];
- else
- f.TextureID = Primitive.TextureEntry.WHITE_TEXTURE;
-
+
textureEntry.FaceTextures[face] = f;
}
-
pbs.TextureEntry = textureEntry.GetBytes();
- if (inner_instance_list.ContainsKey("mesh")) // seems to happen always but ...
- {
- int meshindx = inner_instance_list["mesh"].AsInteger();
- if (meshAssets.Count > meshindx)
- {
- pbs.SculptEntry = true;
- pbs.SculptType = (byte)SculptType.Mesh;
- pbs.SculptTexture = meshAssets[meshindx]; // actual asset UUID after meshs suport introduction
- // data will be requested from asset on rez (i hope)
- }
- }
-
- // faces number to pbs shape
- switch(face_list.Count)
- {
- case 1:
- case 2:
- pbs.ProfileCurve = (byte)ProfileCurve.Circle;
- pbs.PathCurve = (byte)PathCurve.Circle;
- break;
-
- case 3:
- case 4:
- pbs.ProfileCurve = (byte)ProfileCurve.Circle;
- pbs.PathCurve = (byte)PathCurve.Line;
- break;
- case 5:
- pbs.ProfileCurve = (byte)ProfileCurve.EqualTriangle;
- pbs.PathCurve = (byte)PathCurve.Line;
- break;
-
- default:
- pbs.ProfileCurve = (byte)ProfileCurve.Square;
- pbs.PathCurve = (byte)PathCurve.Line;
- break;
- }
-
Vector3 position = inner_instance_list["position"].AsVector3();
Quaternion rotation = inner_instance_list["rotation"].AsQuaternion();
@@ -1608,7 +1577,10 @@ namespace OpenSim.Region.ClientStack.Linden
break;
m_Scene.TryGetScenePresence(m_AgentID, out sp);
- if(sp == null || sp.IsChildAgent || sp.IsDeleted || sp.IsInTransit)
+ if(sp == null || sp.IsChildAgent || sp.IsDeleted)
+ break;
+
+ if(sp.IsInTransit && !sp.IsInLocalTransit)
break;
client = sp.ControllingClient;
@@ -1730,7 +1702,10 @@ namespace OpenSim.Region.ClientStack.Linden
break;
m_Scene.TryGetScenePresence(m_AgentID, out sp);
- if(sp == null || sp.IsChildAgent || sp.IsDeleted || sp.IsInTransit)
+ if(sp == null || sp.IsChildAgent || sp.IsDeleted)
+ break;
+
+ if(sp.IsInTransit && !sp.IsInLocalTransit)
break;
client = sp.ControllingClient;
@@ -1838,7 +1813,7 @@ namespace OpenSim.Region.ClientStack.Linden
if(sp == null || sp.IsDeleted)
return "";
- if(sp.IsInTransit)
+ if(sp.IsInTransit && !sp.IsInLocalTransit)
{
httpResponse.StatusCode = (int)System.Net.HttpStatusCode.ServiceUnavailable;
httpResponse.AddHeader("Retry-After","30");
@@ -1848,7 +1823,6 @@ namespace OpenSim.Region.ClientStack.Linden
NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query);
string[] ids = query.GetValues("ids");
-
Dictionary names = m_UserManager.GetUsersNames(ids);
OSDMap osdReply = new OSDMap();
@@ -1864,12 +1838,18 @@ namespace OpenSim.Region.ClientStack.Linden
string[] parts = kvp.Value.Split(new char[] {' '});
OSDMap osdname = new OSDMap();
+
+ // dont tell about unknown users, we can't send them back on Bad either
+ if(parts[0] == "Unknown")
+ continue;
+/*
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));
diff --git a/OpenSim/Region/ClientStack/Linden/Caps/EventQueue/EventQueueGetModule.cs b/OpenSim/Region/ClientStack/Linden/Caps/EventQueue/EventQueueGetModule.cs
index 1feece1f70..7c9a1c4bf8 100644
--- a/OpenSim/Region/ClientStack/Linden/Caps/EventQueue/EventQueueGetModule.cs
+++ b/OpenSim/Region/ClientStack/Linden/Caps/EventQueue/EventQueueGetModule.cs
@@ -500,13 +500,13 @@ namespace OpenSim.Region.ClientStack.Linden
responsedata["http_protocol_version"] = "HTTP/1.0";
return responsedata;
}
-
+/* this is not a event message
public void DisableSimulator(ulong handle, UUID avatarID)
{
OSD item = EventQueueHelper.DisableSimulator(handle);
Enqueue(item, avatarID);
}
-
+*/
public virtual void EnableSimulator(ulong handle, IPEndPoint endPoint, UUID avatarID, int regionSizeX, int regionSizeY)
{
if (DebugLevel > 0)
diff --git a/OpenSim/Region/ClientStack/Linden/Caps/EventQueue/EventQueueHelper.cs b/OpenSim/Region/ClientStack/Linden/Caps/EventQueue/EventQueueHelper.cs
index e1e88aedb8..461f776eb2 100644
--- a/OpenSim/Region/ClientStack/Linden/Caps/EventQueue/EventQueueHelper.cs
+++ b/OpenSim/Region/ClientStack/Linden/Caps/EventQueue/EventQueueHelper.cs
@@ -90,7 +90,7 @@ namespace OpenSim.Region.ClientStack.Linden
return BuildEvent("EnableSimulator", llsdBody);
}
-
+/*
public static OSD DisableSimulator(ulong handle)
{
//OSDMap llsdSimInfo = new OSDMap(1);
@@ -105,7 +105,7 @@ namespace OpenSim.Region.ClientStack.Linden
return BuildEvent("DisableSimulator", llsdBody);
}
-
+*/
public static OSD CrossRegion(ulong handle, Vector3 pos, Vector3 lookAt,
IPEndPoint newRegionExternalEndPoint,
string capsURL, UUID agentID, UUID sessionID,
diff --git a/OpenSim/Region/ClientStack/Linden/Caps/GetMeshModule.cs b/OpenSim/Region/ClientStack/Linden/Caps/GetMeshModule.cs
index 69ff713c77..ba917e3952 100644
--- a/OpenSim/Region/ClientStack/Linden/Caps/GetMeshModule.cs
+++ b/OpenSim/Region/ClientStack/Linden/Caps/GetMeshModule.cs
@@ -89,8 +89,8 @@ namespace OpenSim.Region.ClientStack.Linden
private Dictionary m_capsDict = new Dictionary();
private static Thread[] m_workerThreads = null;
private static int m_NumberScenes = 0;
- private static OpenMetaverse.BlockingQueue m_queue =
- new OpenMetaverse.BlockingQueue();
+ private static OpenSim.Framework.BlockingQueue m_queue =
+ new OpenSim.Framework.BlockingQueue();
private Dictionary m_pollservices = new Dictionary();
@@ -171,7 +171,7 @@ namespace OpenSim.Region.ClientStack.Linden
m_workerThreads[i] = WorkManager.StartThread(DoMeshRequests,
String.Format("GetMeshWorker{0}", i),
ThreadPriority.Normal,
- false,
+ true,
false,
null,
int.MaxValue);
@@ -204,9 +204,12 @@ namespace OpenSim.Region.ClientStack.Linden
{
while(true)
{
- aPollRequest poolreq = m_queue.Dequeue();
+ aPollRequest poolreq = m_queue.Dequeue(4500);
Watchdog.UpdateThread();
- poolreq.thepoll.Process(poolreq);
+ if(m_NumberScenes <= 0)
+ return;
+ if(poolreq.reqID != UUID.Zero)
+ poolreq.thepoll.Process(poolreq);
}
}
@@ -218,7 +221,7 @@ namespace OpenSim.Region.ClientStack.Linden
PollServiceMeshEventArgs args;
if (m_pollservices.TryGetValue(user, out args))
{
- args.UpdateThrottle(imagethrottle, p);
+ args.UpdateThrottle(imagethrottle);
}
}
@@ -235,14 +238,13 @@ namespace OpenSim.Region.ClientStack.Linden
base(null, uri, null, null, null, pId, int.MaxValue)
{
m_scene = scene;
- m_throttler = new MeshCapsDataThrottler(100000, 1400000, 10000, scene, pId);
+ m_throttler = new MeshCapsDataThrottler(100000);
// x is request id, y is userid
HasEvents = (x, y) =>
{
lock (responses)
{
bool ret = m_throttler.hasEvents(x, responses);
- m_throttler.ProcessTime();
return ret;
}
@@ -257,8 +259,8 @@ namespace OpenSim.Region.ClientStack.Linden
}
finally
{
- m_throttler.ProcessTime();
responses.Remove(x);
+ m_throttler.PassTime();
}
}
};
@@ -271,6 +273,7 @@ namespace OpenSim.Region.ClientStack.Linden
reqinfo.request = y;
m_queue.Enqueue(reqinfo);
+ m_throttler.PassTime();
};
// this should never happen except possible on shutdown
@@ -332,12 +335,15 @@ namespace OpenSim.Region.ClientStack.Linden
};
}
- m_throttler.ProcessTime();
+ m_throttler.PassTime();
}
- internal void UpdateThrottle(int pimagethrottle, ScenePresence p)
+ internal void UpdateThrottle(int pthrottle)
{
- m_throttler.UpdateThrottle(pimagethrottle, p);
+ int tmp = 2 * pthrottle;
+ if(tmp < 10000)
+ tmp = 10000;
+ m_throttler.ThrottleBytes = tmp;
}
}
@@ -391,25 +397,15 @@ namespace OpenSim.Region.ClientStack.Linden
internal sealed class MeshCapsDataThrottler
{
+ private double lastTimeElapsed = 0;
+ private double BytesSent = 0;
- private volatile int currenttime = 0;
- private volatile int lastTimeElapsed = 0;
- private volatile int BytesSent = 0;
- private int CapSetThrottle = 0;
- private float CapThrottleDistributon = 0.30f;
- private readonly Scene m_scene;
- private ThrottleOutPacketType Throttle;
- private readonly UUID User;
-
- public MeshCapsDataThrottler(int pBytes, int max, int min, Scene pScene, UUID puser)
+ public MeshCapsDataThrottler(int pBytes)
{
+ if(pBytes < 10000)
+ pBytes = 10000;
ThrottleBytes = pBytes;
- if(ThrottleBytes < 10000)
- ThrottleBytes = 10000;
- lastTimeElapsed = Util.EnvironmentTickCount();
- Throttle = ThrottleOutPacketType.Asset;
- m_scene = pScene;
- User = puser;
+ lastTimeElapsed = Util.GetTimeStampMS();
}
public bool hasEvents(UUID key, Dictionary responses)
@@ -439,46 +435,22 @@ namespace OpenSim.Region.ClientStack.Linden
return haskey;
}
- public void ProcessTime()
+ public void PassTime()
{
- PassTime();
- }
-
- private void PassTime()
- {
- currenttime = Util.EnvironmentTickCount();
- int timeElapsed = Util.EnvironmentTickCountSubtract(currenttime, lastTimeElapsed);
- if (timeElapsed >= 100)
+ double currenttime = Util.GetTimeStampMS();
+ double timeElapsed = currenttime - lastTimeElapsed;
+ if(timeElapsed < 50.0)
+ return;
+ int add = (int)(ThrottleBytes * timeElapsed * 0.001);
+ if (add >= 1000)
{
lastTimeElapsed = currenttime;
- BytesSent -= (ThrottleBytes * timeElapsed / 1000);
+ BytesSent -= add;
if (BytesSent < 0) BytesSent = 0;
}
}
- private void AlterThrottle(int setting, ScenePresence p)
- {
- p.ControllingClient.SetAgentThrottleSilent((int)Throttle,setting);
- }
-
- public int ThrottleBytes
- {
- get { return CapSetThrottle; }
- set
- {
- if (value > 10000)
- CapSetThrottle = value;
- else
- CapSetThrottle = 10000;
- }
- }
-
- internal void UpdateThrottle(int pimagethrottle, ScenePresence p)
- {
- // Client set throttle !
- CapSetThrottle = 2 * pimagethrottle;
- ProcessTime();
- }
+ public int ThrottleBytes;
}
}
}
diff --git a/OpenSim/Region/ClientStack/Linden/Caps/GetTextureModule.cs b/OpenSim/Region/ClientStack/Linden/Caps/GetTextureModule.cs
index 0c20e0417e..b01c7dc3c1 100644
--- a/OpenSim/Region/ClientStack/Linden/Caps/GetTextureModule.cs
+++ b/OpenSim/Region/ClientStack/Linden/Caps/GetTextureModule.cs
@@ -77,8 +77,8 @@ namespace OpenSim.Region.ClientStack.Linden
private Dictionary m_capsDict = new Dictionary();
private static Thread[] m_workerThreads = null;
private static int m_NumberScenes = 0;
- private static OpenMetaverse.BlockingQueue m_queue =
- new OpenMetaverse.BlockingQueue();
+ private static OpenSim.Framework.BlockingQueue m_queue =
+ new OpenSim.Framework.BlockingQueue();
private Dictionary m_pollservices = new Dictionary();
@@ -139,7 +139,7 @@ namespace OpenSim.Region.ClientStack.Linden
m_workerThreads[i] = WorkManager.StartThread(DoTextureRequests,
String.Format("GetTextureWorker{0}", i),
ThreadPriority.Normal,
- false,
+ true,
false,
null,
int.MaxValue);
@@ -220,7 +220,7 @@ namespace OpenSim.Region.ClientStack.Linden
new Dictionary();
private Scene m_scene;
- private CapsDataThrottler m_throttler = new CapsDataThrottler(100000, 1400000,10000);
+ private CapsDataThrottler m_throttler = new CapsDataThrottler(100000);
public PollServiceTextureEventArgs(UUID pId, Scene scene) :
base(null, "", null, null, null, pId, int.MaxValue)
{
@@ -231,7 +231,6 @@ namespace OpenSim.Region.ClientStack.Linden
lock (responses)
{
bool ret = m_throttler.hasEvents(x, responses);
- m_throttler.ProcessTime();
return ret;
}
@@ -247,6 +246,7 @@ namespace OpenSim.Region.ClientStack.Linden
finally
{
responses.Remove(x);
+ m_throttler.PassTime();
}
}
};
@@ -263,7 +263,7 @@ namespace OpenSim.Region.ClientStack.Linden
{
if (responses.Count > 0)
{
- if (m_queue.Count >= 4)
+ if (m_queue.Count() >= 4)
{
// Never allow more than 4 fetches to wait
reqinfo.send503 = true;
@@ -271,6 +271,7 @@ namespace OpenSim.Region.ClientStack.Linden
}
}
m_queue.Enqueue(reqinfo);
+ m_throttler.PassTime();
};
// this should never happen except possible on shutdown
@@ -351,14 +352,15 @@ namespace OpenSim.Region.ClientStack.Linden
};
}
- m_throttler.ProcessTime();
+ m_throttler.PassTime();
}
internal void UpdateThrottle(int pimagethrottle)
{
- m_throttler.ThrottleBytes = 2 * pimagethrottle;
- if(m_throttler.ThrottleBytes < 10000)
- m_throttler.ThrottleBytes = 10000;
+ int tmp = 2 * pimagethrottle;
+ if(tmp < 10000)
+ tmp = 10000;
+ m_throttler.ThrottleBytes = tmp;
}
}
@@ -415,24 +417,25 @@ namespace OpenSim.Region.ClientStack.Linden
{
while (true)
{
- aPollRequest poolreq = m_queue.Dequeue();
+ aPollRequest poolreq = m_queue.Dequeue(4500);
Watchdog.UpdateThread();
- poolreq.thepoll.Process(poolreq);
+ if(m_NumberScenes <= 0)
+ return;
+ if(poolreq.reqID != UUID.Zero)
+ poolreq.thepoll.Process(poolreq);
}
}
internal sealed class CapsDataThrottler
{
-
- private volatile int currenttime = 0;
- private volatile int lastTimeElapsed = 0;
+ private double lastTimeElapsed = 0;
private volatile int BytesSent = 0;
- public CapsDataThrottler(int pBytes, int max, int min)
+ public CapsDataThrottler(int pBytes)
{
+ if(pBytes < 10000)
+ pBytes = 10000;
ThrottleBytes = pBytes;
- if(ThrottleBytes < 10000)
- ThrottleBytes = 10000;
- lastTimeElapsed = Util.EnvironmentTickCount();
+ lastTimeElapsed = Util.GetTimeStampMS();
}
public bool hasEvents(UUID key, Dictionary responses)
{
@@ -465,20 +468,17 @@ namespace OpenSim.Region.ClientStack.Linden
return haskey;
}
- public void ProcessTime()
+ public void PassTime()
{
- PassTime();
- }
-
- private void PassTime()
- {
- currenttime = Util.EnvironmentTickCount();
- int timeElapsed = Util.EnvironmentTickCountSubtract(currenttime, lastTimeElapsed);
- //processTimeBasedActions(responses);
- if (timeElapsed >= 100)
+ double currenttime = Util.GetTimeStampMS();
+ double timeElapsed = currenttime - lastTimeElapsed;
+ if(timeElapsed < 50.0)
+ return;
+ int add = (int)(ThrottleBytes * timeElapsed * 0.001);
+ if (add >= 1000)
{
lastTimeElapsed = currenttime;
- BytesSent -= (ThrottleBytes * timeElapsed / 1000);
+ BytesSent -= add;
if (BytesSent < 0) BytesSent = 0;
}
}
diff --git a/OpenSim/Region/ClientStack/Linden/Caps/ObjectCaps/ObjectAdd.cs b/OpenSim/Region/ClientStack/Linden/Caps/ObjectCaps/ObjectAdd.cs
index 189fa36376..b044e564fb 100644
--- a/OpenSim/Region/ClientStack/Linden/Caps/ObjectCaps/ObjectAdd.cs
+++ b/OpenSim/Region/ClientStack/Linden/Caps/ObjectCaps/ObjectAdd.cs
@@ -121,6 +121,9 @@ namespace OpenSim.Region.ClientStack.Linden
OSD r = OSDParser.DeserializeLLSDXml((string)request["requestbody"]);
+ if (r.Type != OSDType.Map) // not a proper req
+ return responsedata;
+
//UUID session_id = UUID.Zero;
bool bypass_raycast = false;
uint everyone_mask = 0;
@@ -157,9 +160,6 @@ namespace OpenSim.Region.ClientStack.Linden
int state = 0;
int lastattach = 0;
- if (r.Type != OSDType.Map) // not a proper req
- return responsedata;
-
OSDMap rm = (OSDMap)r;
if (rm.ContainsKey("ObjectData")) //v2
@@ -307,8 +307,6 @@ namespace OpenSim.Region.ClientStack.Linden
}
}
-
-
Vector3 pos = m_scene.GetNewRezLocation(ray_start, ray_end, ray_target_id, rotation, (bypass_raycast) ? (byte)1 : (byte)0, (ray_end_is_intersection) ? (byte)1 : (byte)0, true, scale, false);
PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox();
@@ -359,6 +357,8 @@ namespace OpenSim.Region.ClientStack.Linden
rootpart.NextOwnerMask = next_owner_mask;
rootpart.Material = (byte)material;
+ obj.InvalidateDeepEffectivePerms();
+
m_scene.PhysicsScene.AddPhysicsActorTaint(rootpart.PhysActor);
responsedata["int_response_code"] = 200; //501; //410; //404;
diff --git a/OpenSim/Region/ClientStack/Linden/Caps/ObjectCaps/UploadObjectAssetModule.cs b/OpenSim/Region/ClientStack/Linden/Caps/ObjectCaps/UploadObjectAssetModule.cs
index 6874662c07..116c51f5b3 100644
--- a/OpenSim/Region/ClientStack/Linden/Caps/ObjectCaps/UploadObjectAssetModule.cs
+++ b/OpenSim/Region/ClientStack/Linden/Caps/ObjectCaps/UploadObjectAssetModule.cs
@@ -335,6 +335,7 @@ namespace OpenSim.Region.ClientStack.Linden
grp.AbsolutePosition = obj.Position;
prim.RotationOffset = obj.Rotation;
+
// Required for linking
grp.RootPart.ClearUpdateSchedule();
diff --git a/OpenSim/Region/ClientStack/Linden/Caps/RegionConsoleModule.cs b/OpenSim/Region/ClientStack/Linden/Caps/RegionConsoleModule.cs
index b3e3ac3795..e8387e3de2 100644
--- a/OpenSim/Region/ClientStack/Linden/Caps/RegionConsoleModule.cs
+++ b/OpenSim/Region/ClientStack/Linden/Caps/RegionConsoleModule.cs
@@ -185,8 +185,9 @@ namespace OpenSim.Region.ClientStack.Linden
protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
- StreamReader reader = new StreamReader(request);
- string message = reader.ReadToEnd();
+ string message;
+ using(StreamReader reader = new StreamReader(request))
+ message = reader.ReadToEnd();
OSD osd = OSDParser.DeserializeLLSDXml(message);
diff --git a/OpenSim/Region/ClientStack/Linden/Caps/UploadBakedTextureModule.cs b/OpenSim/Region/ClientStack/Linden/Caps/UploadBakedTextureModule.cs
index dfe097ef97..b406b3743a 100644
--- a/OpenSim/Region/ClientStack/Linden/Caps/UploadBakedTextureModule.cs
+++ b/OpenSim/Region/ClientStack/Linden/Caps/UploadBakedTextureModule.cs
@@ -63,9 +63,7 @@ namespace OpenSim.Region.ClientStack.Linden
private static readonly string m_uploadBakedTexturePath = "0010/";// This is in the LandManagementModule.
private Scene m_scene;
- private bool m_persistBakedTextures;
- private IBakedTextureModule m_BakedTextureModule;
private string m_URL;
public void Initialise(IConfigSource source)
@@ -76,15 +74,12 @@ namespace OpenSim.Region.ClientStack.Linden
m_URL = config.GetString("Cap_UploadBakedTexture", string.Empty);
- IConfig appearanceConfig = source.Configs["Appearance"];
- if (appearanceConfig != null)
- m_persistBakedTextures = appearanceConfig.GetBoolean("PersistBakedTextures", m_persistBakedTextures);
+// IConfig appearanceConfig = source.Configs["Appearance"];
}
public void AddRegion(Scene s)
{
m_scene = s;
-
}
public void RemoveRegion(Scene s)
@@ -92,7 +87,6 @@ namespace OpenSim.Region.ClientStack.Linden
s.EventManager.OnRegisterCaps -= RegisterCaps;
s.EventManager.OnNewPresence -= RegisterNewPresence;
s.EventManager.OnRemovePresence -= DeRegisterPresence;
- m_BakedTextureModule = null;
m_scene = null;
}
@@ -101,7 +95,6 @@ namespace OpenSim.Region.ClientStack.Linden
m_scene.EventManager.OnRegisterCaps += RegisterCaps;
m_scene.EventManager.OnNewPresence += RegisterNewPresence;
m_scene.EventManager.OnRemovePresence += DeRegisterPresence;
-
}
private void DeRegisterPresence(UUID agentId)
@@ -110,156 +103,12 @@ namespace OpenSim.Region.ClientStack.Linden
private void RegisterNewPresence(ScenePresence presence)
{
-// presence.ControllingClient.OnSetAppearance += CaptureAppearanceSettings;
}
-/* not in use. work done in AvatarFactoryModule ValidateBakedTextureCache() and UpdateBakedTextureCache()
- private void CaptureAppearanceSettings(IClientAPI remoteClient, Primitive.TextureEntry textureEntry, byte[] visualParams, Vector3 avSize, WearableCacheItem[] cacheItems)
- {
- // if cacheItems.Length > 0 viewer is giving us current textures information.
- // baked ones should had been uploaded and in assets cache as local itens
-
-
- if (cacheItems.Length == 0)
- return; // no textures information, nothing to do
-
- ScenePresence p = null;
- if (!m_scene.TryGetScenePresence(remoteClient.AgentId, out p))
- return; // what are we doing if there is no presence to cache for?
-
- if (p.IsDeleted)
- return; // does this really work?
-
- int maxCacheitemsLoop = cacheItems.Length;
- if (maxCacheitemsLoop > 20)
- {
- maxCacheitemsLoop = AvatarWearable.MAX_WEARABLES;
- m_log.WarnFormat("[CACHEDBAKES]: Too Many Cache items Provided {0}, the max is {1}. Truncating!", cacheItems.Length, AvatarWearable.MAX_WEARABLES);
- }
-
- m_BakedTextureModule = m_scene.RequestModuleInterface();
-
-
- // some nice debug
- m_log.Debug("[Cacheitems]: " + cacheItems.Length);
- for (int iter = 0; iter < maxCacheitemsLoop; iter++)
- {
- m_log.Debug("[Cacheitems] {" + iter + "/" + cacheItems[iter].TextureIndex + "}: c-" + cacheItems[iter].CacheId + ", t-" +
- cacheItems[iter].TextureID);
- }
-
- // p.Appearance.WearableCacheItems is in memory primary cashID to textures mapper
-
- WearableCacheItem[] existingitems = p.Appearance.WearableCacheItems;
-
- if (existingitems == null)
- {
- if (m_BakedTextureModule != null)
- {
- WearableCacheItem[] savedcache = null;
- try
- {
- if (p.Appearance.WearableCacheItemsDirty)
- {
- savedcache = m_BakedTextureModule.Get(p.UUID);
- p.Appearance.WearableCacheItems = savedcache;
- p.Appearance.WearableCacheItemsDirty = false;
- }
- }
-
- catch (Exception)
- {
- // The service logs a sufficient error message.
- }
-
-
- if (savedcache != null)
- existingitems = savedcache;
- }
- }
-
- // Existing items null means it's a fully new appearance
- if (existingitems == null)
- {
- for (int i = 0; i < maxCacheitemsLoop; i++)
- {
- if (textureEntry.FaceTextures.Length > cacheItems[i].TextureIndex)
- {
- Primitive.TextureEntryFace face = textureEntry.FaceTextures[cacheItems[i].TextureIndex];
- if (face == null)
- {
- textureEntry.CreateFace(cacheItems[i].TextureIndex);
- textureEntry.FaceTextures[cacheItems[i].TextureIndex].TextureID =
- AppearanceManager.DEFAULT_AVATAR_TEXTURE;
- continue;
- }
- cacheItems[i].TextureID = face.TextureID;
- if (m_scene.AssetService != null)
- cacheItems[i].TextureAsset =
- m_scene.AssetService.GetCached(cacheItems[i].TextureID.ToString());
- }
- else
- {
- m_log.WarnFormat("[CACHEDBAKES]: Invalid Texture Index Provided, Texture doesn't exist or hasn't been uploaded yet {0}, the max is {1}. Skipping!", cacheItems[i].TextureIndex, textureEntry.FaceTextures.Length);
- }
- }
- }
- else
- {
- for (int i = 0; i < maxCacheitemsLoop; i++)
- {
- if (textureEntry.FaceTextures.Length > cacheItems[i].TextureIndex)
- {
- Primitive.TextureEntryFace face = textureEntry.FaceTextures[cacheItems[i].TextureIndex];
- if (face == null)
- {
- textureEntry.CreateFace(cacheItems[i].TextureIndex);
- textureEntry.FaceTextures[cacheItems[i].TextureIndex].TextureID =
- AppearanceManager.DEFAULT_AVATAR_TEXTURE;
- continue;
- }
- cacheItems[i].TextureID =
- face.TextureID;
- }
- else
- {
- m_log.WarnFormat("[CACHEDBAKES]: Invalid Texture Index Provided, Texture doesn't exist or hasn't been uploaded yet {0}, the max is {1}. Skipping!", cacheItems[i].TextureIndex, textureEntry.FaceTextures.Length);
- }
- }
-
- for (int i = 0; i < maxCacheitemsLoop; i++)
- {
- if (cacheItems[i].TextureAsset == null)
- {
- cacheItems[i].TextureAsset =
- m_scene.AssetService.GetCached(cacheItems[i].TextureID.ToString());
- }
- }
- }
- p.Appearance.WearableCacheItems = cacheItems;
-
- if (m_BakedTextureModule != null)
- {
- m_BakedTextureModule.Store(remoteClient.AgentId, cacheItems);
- p.Appearance.WearableCacheItemsDirty = true;
-
- }
- else
- p.Appearance.WearableCacheItemsDirty = false;
-
- for (int iter = 0; iter < maxCacheitemsLoop; iter++)
- {
- m_log.Debug("[CacheitemsLeaving] {" + iter + "/" + cacheItems[iter].TextureIndex + "}: c-" + cacheItems[iter].CacheId + ", t-" +
- cacheItems[iter].TextureID);
- }
- }
- */
public void PostInitialise()
{
}
-
-
public void Close() { }
public string Name { get { return "UploadBakedTextureModule"; } }
@@ -275,7 +124,7 @@ namespace OpenSim.Region.ClientStack.Linden
if (m_URL == "localhost")
{
UploadBakedTextureHandler avatarhandler = new UploadBakedTextureHandler(
- caps, m_scene.AssetService, m_persistBakedTextures);
+ caps, m_scene.AssetService);
caps.RegisterHandler(
"UploadBakedTexture",
diff --git a/OpenSim/Region/ClientStack/Linden/Caps/WebFetchInvDescModule.cs b/OpenSim/Region/ClientStack/Linden/Caps/WebFetchInvDescModule.cs
index e0ec842c9e..8d4e561e6e 100644
--- a/OpenSim/Region/ClientStack/Linden/Caps/WebFetchInvDescModule.cs
+++ b/OpenSim/Region/ClientStack/Linden/Caps/WebFetchInvDescModule.cs
@@ -207,7 +207,7 @@ namespace OpenSim.Region.ClientStack.Linden
m_workerThreads[i] = WorkManager.StartThread(DoInventoryRequests,
String.Format("InventoryWorkerThread{0}", i),
ThreadPriority.Normal,
- false,
+ true,
true,
null,
int.MaxValue);
@@ -443,10 +443,9 @@ namespace OpenSim.Region.ClientStack.Linden
{
while (true)
{
+ aPollRequest poolreq = m_queue.Dequeue(4500);
Watchdog.UpdateThread();
- aPollRequest poolreq = m_queue.Dequeue(5000);
-
if (poolreq != null && poolreq.thepoll != null)
{
try
@@ -456,7 +455,7 @@ namespace OpenSim.Region.ClientStack.Linden
catch (Exception e)
{
m_log.ErrorFormat(
- "[INVENTORY]: Failed to process queued inventory request {0} for {1}. Exception {3}",
+ "[INVENTORY]: Failed to process queued inventory request {0} for {1}. Exception {2}",
poolreq.reqID, poolreq.presence != null ? poolreq.presence.Name : "unknown", e);
}
}
diff --git a/OpenSim/Region/ClientStack/Linden/UDP/LLClientView.cs b/OpenSim/Region/ClientStack/Linden/UDP/LLClientView.cs
index df3466815b..6dd38856bc 100644
--- a/OpenSim/Region/ClientStack/Linden/UDP/LLClientView.cs
+++ b/OpenSim/Region/ClientStack/Linden/UDP/LLClientView.cs
@@ -62,7 +62,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
/// Handles new client connections
/// Constructor takes a single Packet and authenticates everything
///
- public class LLClientView : IClientAPI, IClientCore, IClientIM, IClientChat, IClientInventory, IStatsCollector
+ public class LLClientView : IClientAPI, IClientCore, IClientIM, IClientChat, IClientInventory, IStatsCollector, IClientIPEndpoint
{
///
/// Debug packet level. See OpenSim.RegisterConsoleCommands() for more details.
@@ -325,6 +325,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
///
public LLImageManager ImageManager { get; private set; }
+ public JobEngine m_asyncPacketProcess;
private readonly LLUDPServer m_udpServer;
private readonly LLUDPClient m_udpClient;
private readonly UUID m_sessionId;
@@ -378,7 +379,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP
protected Scene m_scene;
protected string m_firstName;
protected string m_lastName;
- protected Thread m_clientThread;
protected Vector3 m_startpos;
protected UUID m_activeGroupID;
protected string m_activeGroupName = String.Empty;
@@ -529,7 +529,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP
m_prioritizer = new Prioritizer(m_scene);
RegisterLocalPacketHandlers();
-
+ string name = string.Format("AsyncInUDP-{0}",m_agentId.ToString());
+ m_asyncPacketProcess = new JobEngine(name, name, 10000);
IsActive = true;
}
@@ -592,6 +593,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
if (OnConnectionClosed != null)
OnConnectionClosed(this);
+ m_asyncPacketProcess.Stop();
// Flush all of the packets out of the UDP server for this client
if (m_udpServer != null)
@@ -703,29 +705,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP
///
/// true if the handler was added. This is currently always the case.
public bool AddLocalPacketHandler(PacketType packetType, PacketMethod handler, bool doAsync)
- {
- return AddLocalPacketHandler(packetType, handler, doAsync, false);
- }
-
- ///
- /// Add a handler for the given packet type.
- ///
- ///
- ///
- ///
- /// If true, when the packet is received handle it on a different thread. Whether this is given direct to
- /// a threadpool thread or placed in a queue depends on the inEngine parameter.
- ///
- ///
- /// If async is false then this parameter is ignored.
- /// If async is true and inEngine is false, then the packet is sent directly to a
- /// threadpool thread.
- /// If async is true and inEngine is true, then the packet is sent to the IncomingPacketAsyncHandlingEngine.
- /// This may result in slower handling but reduces the risk of overloading the simulator when there are many
- /// simultaneous async requests.
- ///
- /// true if the handler was added. This is currently always the case.
- public bool AddLocalPacketHandler(PacketType packetType, PacketMethod handler, bool doAsync, bool inEngine)
{
bool result = false;
lock (m_packetHandlers)
@@ -733,7 +712,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
if (!m_packetHandlers.ContainsKey(packetType))
{
m_packetHandlers.Add(
- packetType, new PacketProcessor() { method = handler, Async = doAsync, InEngine = inEngine });
+ packetType, new PacketProcessor() { method = handler, Async = doAsync});
result = true;
}
}
@@ -768,30 +747,16 @@ namespace OpenSim.Region.ClientStack.LindenUDP
PacketProcessor pprocessor;
if (m_packetHandlers.TryGetValue(packet.Type, out pprocessor))
{
- ClientInfo cinfo = UDPClient.GetClientInfo();
//there is a local handler for this packet type
if (pprocessor.Async)
{
- if (!cinfo.AsyncRequests.ContainsKey(packet.Type.ToString()))
- cinfo.AsyncRequests[packet.Type.ToString()] = 0;
- cinfo.AsyncRequests[packet.Type.ToString()]++;
-
object obj = new AsyncPacketProcess(this, pprocessor.method, packet);
-
- if (pprocessor.InEngine)
- m_udpServer.IpahEngine.QueueJob(packet.Type.ToString(), () => ProcessSpecificPacketAsync(obj));
- else
- Util.FireAndForget(ProcessSpecificPacketAsync, obj, packet.Type.ToString());
-
+ m_asyncPacketProcess.QueueJob(packet.Type.ToString(), () => ProcessSpecificPacketAsync(obj));
result = true;
}
else
{
- if (!cinfo.SyncRequests.ContainsKey(packet.Type.ToString()))
- cinfo.SyncRequests[packet.Type.ToString()] = 0;
- cinfo.SyncRequests[packet.Type.ToString()]++;
-
result = pprocessor.method(this, packet);
}
}
@@ -806,11 +771,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP
}
if (found)
{
- ClientInfo cinfo = UDPClient.GetClientInfo();
- if (!cinfo.GenericRequests.ContainsKey(packet.Type.ToString()))
- cinfo.GenericRequests[packet.Type.ToString()] = 0;
- cinfo.GenericRequests[packet.Type.ToString()]++;
-
result = method(this, packet);
}
}
@@ -841,6 +801,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
public virtual void Start()
{
+ m_asyncPacketProcess.Start();
m_scene.AddNewAgent(this, PresenceType.User);
// RefreshGroupMembership();
@@ -3111,10 +3072,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP
public void SendParcelInfo(RegionInfo info, LandData land, UUID parcelID, uint x, uint y)
{
- float dwell = 0.0f;
- IDwellModule dwellModule = m_scene.RequestModuleInterface();
- if (dwellModule != null)
- dwell = dwellModule.GetDwell(land.GlobalID);
ParcelInfoReplyPacket reply = (ParcelInfoReplyPacket)PacketPool.Instance.GetPacket(PacketType.ParcelInfoReply);
reply.AgentData.AgentID = m_agentId;
reply.Data.ParcelID = parcelID;
@@ -3141,7 +3098,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
reply.Data.GlobalZ = pos.Z;
reply.Data.SimName = Utils.StringToBytes(info.RegionName);
reply.Data.SnapshotID = land.SnapshotID;
- reply.Data.Dwell = dwell;
+ reply.Data.Dwell = land.Dwell;
reply.Data.SalePrice = land.SalePrice;
reply.Data.AuctionID = (int)land.AuctionID;
@@ -3950,24 +3907,68 @@ namespace OpenSim.Region.ClientStack.LindenUDP
///
/// Send an ObjectUpdate packet with information about an avatar
///
- public void SendAvatarDataImmediate(ISceneEntity avatar)
+ public void SendEntityFullUpdateImmediate(ISceneEntity ent)
{
// m_log.DebugFormat(
// "[LLCLIENTVIEW]: Sending immediate object update for avatar {0} {1} to {2} {3}",
// avatar.Name, avatar.UUID, Name, AgentId);
- ScenePresence presence = avatar as ScenePresence;
- if (presence == null)
+ if (ent == null)
return;
ObjectUpdatePacket objupdate = (ObjectUpdatePacket)PacketPool.Instance.GetPacket(PacketType.ObjectUpdate);
objupdate.Header.Zerocoded = true;
- objupdate.RegionData.RegionHandle = presence.RegionHandle;
-// objupdate.RegionData.TimeDilation = ushort.MaxValue;
objupdate.RegionData.TimeDilation = Utils.FloatToUInt16(m_scene.TimeDilation, 0.0f, 1.0f);
objupdate.ObjectData = new ObjectUpdatePacket.ObjectDataBlock[1];
- objupdate.ObjectData[0] = CreateAvatarUpdateBlock(presence);
+
+ if(ent is ScenePresence)
+ {
+ ScenePresence presence = ent as ScenePresence;
+ objupdate.RegionData.RegionHandle = presence.RegionHandle;
+ objupdate.ObjectData[0] = CreateAvatarUpdateBlock(presence);
+ }
+ else if(ent is SceneObjectPart)
+ {
+ SceneObjectPart part = ent as SceneObjectPart;
+ objupdate.RegionData.RegionHandle = m_scene.RegionInfo.RegionHandle;
+ objupdate.ObjectData[0] = CreatePrimUpdateBlock(part, (ScenePresence)SceneAgent);
+ }
+
+ OutPacket(objupdate, ThrottleOutPacketType.Task | ThrottleOutPacketType.HighPriority);
+
+ // We need to record the avatar local id since the root prim of an attachment points to this.
+// m_attachmentsSent.Add(avatar.LocalId);
+ }
+
+ public void SendEntityTerseUpdateImmediate(ISceneEntity ent)
+ {
+// m_log.DebugFormat(
+// "[LLCLIENTVIEW]: Sending immediate object update for avatar {0} {1} to {2} {3}",
+// avatar.Name, avatar.UUID, Name, AgentId);
+
+ if (ent == null)
+ return;
+
+ ImprovedTerseObjectUpdatePacket objupdate =
+ (ImprovedTerseObjectUpdatePacket)PacketPool.Instance.GetPacket(PacketType.ImprovedTerseObjectUpdate);
+ objupdate.Header.Zerocoded = true;
+
+ objupdate.RegionData.TimeDilation = Utils.FloatToUInt16(m_scene.TimeDilation, 0.0f, 1.0f);
+ objupdate.ObjectData = new ImprovedTerseObjectUpdatePacket.ObjectDataBlock[1];
+
+ if(ent is ScenePresence)
+ {
+ ScenePresence presence = ent as ScenePresence;
+ objupdate.RegionData.RegionHandle = presence.RegionHandle;
+ objupdate.ObjectData[0] = CreateImprovedTerseBlock(ent, false);
+ }
+ else if(ent is SceneObjectPart)
+ {
+ SceneObjectPart part = ent as SceneObjectPart;
+ objupdate.RegionData.RegionHandle = m_scene.RegionInfo.RegionHandle;
+ objupdate.ObjectData[0] = CreateImprovedTerseBlock(ent, false);
+ }
OutPacket(objupdate, ThrottleOutPacketType.Task | ThrottleOutPacketType.HighPriority);
@@ -4021,7 +4022,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP
#region Primitive Packet/Data Sending Methods
-
///
/// Generate one of the object update packets based on PrimUpdateFlags
/// and broadcast the packet to clients
@@ -4044,10 +4044,20 @@ namespace OpenSim.Region.ClientStack.LindenUDP
*/
if (entity is SceneObjectPart)
{
- SceneObjectPart e = (SceneObjectPart)entity;
- SceneObjectGroup g = e.ParentGroup;
+ SceneObjectPart p = (SceneObjectPart)entity;
+ SceneObjectGroup g = p.ParentGroup;
if (g.HasPrivateAttachmentPoint && g.OwnerID != AgentId)
return; // Don't send updates for other people's HUDs
+
+ if((updateFlags ^ PrimUpdateFlags.SendInTransit) == 0)
+ {
+ List partIDs = (new List {p.LocalId});
+ lock (m_entityProps.SyncRoot)
+ m_entityProps.Remove(partIDs);
+ lock (m_entityUpdates.SyncRoot)
+ m_entityUpdates.Remove(partIDs);
+ return;
+ }
}
//double priority = m_prioritizer.GetUpdatePriority(this, entity);
@@ -4126,20 +4136,34 @@ namespace OpenSim.Region.ClientStack.LindenUDP
// Vector3 mycamera = Vector3.Zero;
Vector3 mypos = Vector3.Zero;
ScenePresence mysp = (ScenePresence)SceneAgent;
- if(mysp != null && !mysp.IsDeleted)
+
+ bool orderedDequeue = m_scene.UpdatePrioritizationScheme == UpdatePrioritizationSchemes.SimpleAngularDistance;
+ // we should have a presence
+ if(mysp == null)
+ return;
+
+ if(doCulling)
{
cullingrange = mysp.DrawDistance + m_scene.ReprioritizationDistance + 16f;
// mycamera = mysp.CameraPosition;
mypos = mysp.AbsolutePosition;
}
- else
- doCulling = false;
while (maxUpdatesBytes > 0)
{
lock (m_entityUpdates.SyncRoot)
- if (!m_entityUpdates.TryDequeue(out update, out timeinqueue))
- break;
+ {
+ if(orderedDequeue)
+ {
+ if (!m_entityUpdates.TryOrderedDequeue(out update, out timeinqueue))
+ break;
+ }
+ else
+ {
+ if (!m_entityUpdates.TryDequeue(out update, out timeinqueue))
+ break;
+ }
+ }
PrimUpdateFlags updateFlags = (PrimUpdateFlags)update.Flags;
@@ -4154,9 +4178,15 @@ namespace OpenSim.Region.ClientStack.LindenUDP
{
SceneObjectPart part = (SceneObjectPart)update.Entity;
SceneObjectGroup grp = part.ParentGroup;
- if (grp.inTransit)
+ if (grp.inTransit && !update.Flags.HasFlag(PrimUpdateFlags.SendInTransit))
continue;
+/* debug
+ if (update.Flags.HasFlag(PrimUpdateFlags.SendInTransit))
+ {
+
+ }
+*/
if (grp.IsDeleted)
{
// Don't send updates for objects that have been marked deleted.
@@ -4213,14 +4243,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP
{
part.Shape.LightEntry = false;
}
-
- if (part.Shape != null && (part.Shape.SculptType == (byte)SculptType.Mesh))
- {
- // Ensure that mesh has at least 8 valid faces
- part.Shape.ProfileBegin = 12500;
- part.Shape.ProfileEnd = 0;
- part.Shape.ProfileHollow = 27500;
- }
}
if(doCulling && !grp.IsAttachment)
@@ -4248,14 +4270,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP
continue;
}
}
-
- if (part.Shape != null && (part.Shape.SculptType == (byte)SculptType.Mesh))
- {
- // Ensure that mesh has at least 8 valid faces
- part.Shape.ProfileBegin = 12500;
- part.Shape.ProfileEnd = 0;
- part.Shape.ProfileHollow = 27500;
- }
}
else if (update.Entity is ScenePresence)
{
@@ -4330,7 +4344,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
if (update.Entity is ScenePresence)
ablock = CreateAvatarUpdateBlock((ScenePresence)update.Entity);
else
- ablock = CreatePrimUpdateBlock((SceneObjectPart)update.Entity, this.m_agentId);
+ ablock = CreatePrimUpdateBlock((SceneObjectPart)update.Entity, mysp);
objectUpdateBlocks.Add(ablock);
objectUpdates.Value.Add(update);
maxUpdatesBytes -= ablock.Length;
@@ -4462,6 +4476,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
}
// hack.. dont use
+/*
public void SendPartFullUpdate(ISceneEntity ent, uint? parentID)
{
if (ent is SceneObjectPart)
@@ -4472,7 +4487,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
packet.RegionData.TimeDilation = Utils.FloatToUInt16(m_scene.TimeDilation, 0.0f, 1.0f);
packet.ObjectData = new ObjectUpdatePacket.ObjectDataBlock[1];
- ObjectUpdatePacket.ObjectDataBlock blk = CreatePrimUpdateBlock(part, this.m_agentId);
+ ObjectUpdatePacket.ObjectDataBlock blk = CreatePrimUpdateBlock(part, mysp);
if (parentID.HasValue)
{
blk.ParentID = parentID.Value;
@@ -4488,7 +4503,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
// updatesThisCall, Name, SceneAgent.IsChildAgent ? "child" : "root", Scene.Name);
//
}
-
+*/
public void ReprioritizeUpdates()
{
lock (m_entityUpdates.SyncRoot)
@@ -4846,6 +4861,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
// OpenSim.Framework.Lazy> propertyUpdates =
// new OpenSim.Framework.Lazy>();
+ bool orderedDequeue = m_scene.UpdatePrioritizationScheme == UpdatePrioritizationSchemes.SimpleAngularDistance;
EntityUpdate iupdate;
Int32 timeinqueue; // this is just debugging code & can be dropped later
@@ -4853,8 +4869,18 @@ namespace OpenSim.Region.ClientStack.LindenUDP
while (maxUpdateBytes > 0)
{
lock (m_entityProps.SyncRoot)
- if (!m_entityProps.TryDequeue(out iupdate, out timeinqueue))
- break;
+ {
+ if(orderedDequeue)
+ {
+ if (!m_entityProps.TryOrderedDequeue(out iupdate, out timeinqueue))
+ break;
+ }
+ else
+ {
+ if (!m_entityProps.TryDequeue(out iupdate, out timeinqueue))
+ break;
+ }
+ }
ObjectPropertyUpdate update = (ObjectPropertyUpdate)iupdate;
if (update.SendFamilyProps)
@@ -5522,6 +5548,26 @@ namespace OpenSim.Region.ClientStack.LindenUDP
#endregion
#region Helper Methods
+ private void ClampVectorForUint(ref Vector3 v, float max)
+ {
+ float a,b;
+
+ a = Math.Abs(v.X);
+ b = Math.Abs(v.Y);
+ if(b > a)
+ a = b;
+ b= Math.Abs(v.Z);
+ if(b > a)
+ a = b;
+
+ if (a > max)
+ {
+ a = max / a;
+ v.X *= a;
+ v.Y *= a;
+ v.Z *= a;
+ }
+ }
protected ImprovedTerseObjectUpdatePacket.ObjectDataBlock CreateImprovedTerseBlock(ISceneEntity entity, bool sendTexture)
{
@@ -5612,11 +5658,13 @@ namespace OpenSim.Region.ClientStack.LindenUDP
pos += 12;
// Velocity
+ ClampVectorForUint(ref velocity, 128f);
Utils.UInt16ToBytes(Utils.FloatToUInt16(velocity.X, -128.0f, 128.0f), data, pos); pos += 2;
Utils.UInt16ToBytes(Utils.FloatToUInt16(velocity.Y, -128.0f, 128.0f), data, pos); pos += 2;
Utils.UInt16ToBytes(Utils.FloatToUInt16(velocity.Z, -128.0f, 128.0f), data, pos); pos += 2;
// Acceleration
+ ClampVectorForUint(ref acceleration, 64f);
Utils.UInt16ToBytes(Utils.FloatToUInt16(acceleration.X, -64.0f, 64.0f), data, pos); pos += 2;
Utils.UInt16ToBytes(Utils.FloatToUInt16(acceleration.Y, -64.0f, 64.0f), data, pos); pos += 2;
Utils.UInt16ToBytes(Utils.FloatToUInt16(acceleration.Z, -64.0f, 64.0f), data, pos); pos += 2;
@@ -5628,6 +5676,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
Utils.UInt16ToBytes(Utils.FloatToUInt16(rotation.W, -1.0f, 1.0f), data, pos); pos += 2;
// Angular Velocity
+ ClampVectorForUint(ref angularVelocity, 64f);
Utils.UInt16ToBytes(Utils.FloatToUInt16(angularVelocity.X, -64.0f, 64.0f), data, pos); pos += 2;
Utils.UInt16ToBytes(Utils.FloatToUInt16(angularVelocity.Y, -64.0f, 64.0f), data, pos); pos += 2;
Utils.UInt16ToBytes(Utils.FloatToUInt16(angularVelocity.Z, -64.0f, 64.0f), data, pos); pos += 2;
@@ -5726,29 +5775,29 @@ namespace OpenSim.Region.ClientStack.LindenUDP
return update;
}
- protected ObjectUpdatePacket.ObjectDataBlock CreatePrimUpdateBlock(SceneObjectPart data, UUID recipientID)
+// protected ObjectUpdatePacket.ObjectDataBlock CreatePrimUpdateBlock(SceneObjectPart data, UUID recipientID)
+ protected ObjectUpdatePacket.ObjectDataBlock CreatePrimUpdateBlock(SceneObjectPart part, ScenePresence sp)
{
byte[] objectData = new byte[60];
- data.RelativePosition.ToBytes(objectData, 0);
- data.Velocity.ToBytes(objectData, 12);
- data.Acceleration.ToBytes(objectData, 24);
+ part.RelativePosition.ToBytes(objectData, 0);
+ part.Velocity.ToBytes(objectData, 12);
+ part.Acceleration.ToBytes(objectData, 24);
- Quaternion rotation = data.RotationOffset;
+ Quaternion rotation = part.RotationOffset;
rotation.Normalize();
rotation.ToBytes(objectData, 36);
- data.AngularVelocity.ToBytes(objectData, 48);
+ part.AngularVelocity.ToBytes(objectData, 48);
ObjectUpdatePacket.ObjectDataBlock update = new ObjectUpdatePacket.ObjectDataBlock();
- update.ClickAction = (byte)data.ClickAction;
+ update.ClickAction = (byte)part.ClickAction;
update.CRC = 0;
- update.ExtraParams = data.Shape.ExtraParams ?? Utils.EmptyBytes;
- update.FullID = data.UUID;
- update.ID = data.LocalId;
+ update.ExtraParams = part.Shape.ExtraParams ?? Utils.EmptyBytes;
+ update.FullID = part.UUID;
+ update.ID = part.LocalId;
//update.JointAxisOrAnchor = Vector3.Zero; // These are deprecated
//update.JointPivot = Vector3.Zero;
//update.JointType = 0;
- update.Material = data.Material;
- update.MediaURL = Utils.EmptyBytes; // FIXME: Support this in OpenSim
+ update.Material = part.Material;
/*
if (data.ParentGroup.IsAttachment)
{
@@ -5776,68 +5825,74 @@ namespace OpenSim.Region.ClientStack.LindenUDP
}
*/
- if (data.ParentGroup.IsAttachment)
+ if (part.ParentGroup.IsAttachment)
{
- if (data.IsRoot)
+ if (part.IsRoot)
{
- update.NameValue = Util.StringToBytes256("AttachItemID STRING RW SV " + data.ParentGroup.FromItemID);
+ update.NameValue = Util.StringToBytes256("AttachItemID STRING RW SV " + part.ParentGroup.FromItemID);
}
else
update.NameValue = Utils.EmptyBytes;
- int st = (int)data.ParentGroup.AttachmentPoint;
+ int st = (int)part.ParentGroup.AttachmentPoint;
update.State = (byte)(((st & 0xf0) >> 4) + ((st & 0x0f) << 4)); ;
}
else
{
update.NameValue = Utils.EmptyBytes;
- update.State = data.Shape.State; // not sure about this
+ update.State = part.Shape.State; // not sure about this
}
update.ObjectData = objectData;
- update.ParentID = data.ParentID;
- update.PathBegin = data.Shape.PathBegin;
- update.PathCurve = data.Shape.PathCurve;
- update.PathEnd = data.Shape.PathEnd;
- update.PathRadiusOffset = data.Shape.PathRadiusOffset;
- update.PathRevolutions = data.Shape.PathRevolutions;
- update.PathScaleX = data.Shape.PathScaleX;
- update.PathScaleY = data.Shape.PathScaleY;
- update.PathShearX = data.Shape.PathShearX;
- update.PathShearY = data.Shape.PathShearY;
- update.PathSkew = data.Shape.PathSkew;
- update.PathTaperX = data.Shape.PathTaperX;
- update.PathTaperY = data.Shape.PathTaperY;
- update.PathTwist = data.Shape.PathTwist;
- update.PathTwistBegin = data.Shape.PathTwistBegin;
- update.PCode = data.Shape.PCode;
- update.ProfileBegin = data.Shape.ProfileBegin;
- update.ProfileCurve = data.Shape.ProfileCurve;
- update.ProfileEnd = data.Shape.ProfileEnd;
- update.ProfileHollow = data.Shape.ProfileHollow;
- update.PSBlock = data.ParticleSystem ?? Utils.EmptyBytes;
- update.TextColor = data.GetTextColor().GetBytes(false);
- update.TextureAnim = data.TextureAnimation ?? Utils.EmptyBytes;
- update.TextureEntry = data.Shape.TextureEntry ?? Utils.EmptyBytes;
- update.Scale = data.Shape.Scale;
- update.Text = Util.StringToBytes256(data.Text);
- update.MediaURL = Util.StringToBytes256(data.MediaUrl);
+ update.ParentID = part.ParentID;
+ update.PathBegin = part.Shape.PathBegin;
+ update.PathCurve = part.Shape.PathCurve;
+ update.PathEnd = part.Shape.PathEnd;
+ update.PathRadiusOffset = part.Shape.PathRadiusOffset;
+ update.PathRevolutions = part.Shape.PathRevolutions;
+ update.PathScaleX = part.Shape.PathScaleX;
+ update.PathScaleY = part.Shape.PathScaleY;
+ update.PathShearX = part.Shape.PathShearX;
+ update.PathShearY = part.Shape.PathShearY;
+ update.PathSkew = part.Shape.PathSkew;
+ update.PathTaperX = part.Shape.PathTaperX;
+ update.PathTaperY = part.Shape.PathTaperY;
+ update.PathTwist = part.Shape.PathTwist;
+ update.PathTwistBegin = part.Shape.PathTwistBegin;
+ update.PCode = part.Shape.PCode;
+ update.ProfileBegin = part.Shape.ProfileBegin;
+ update.ProfileCurve = part.Shape.ProfileCurve;
+
+ if(part.Shape.SculptType == (byte)SculptType.Mesh) // filter out hack
+ update.ProfileCurve = (byte)(part.Shape.ProfileCurve & 0x0f);
+ else
+ update.ProfileCurve = part.Shape.ProfileCurve;
+
+ update.ProfileEnd = part.Shape.ProfileEnd;
+ update.ProfileHollow = part.Shape.ProfileHollow;
+ update.PSBlock = part.ParticleSystem ?? Utils.EmptyBytes;
+ update.TextColor = part.GetTextColor().GetBytes(false);
+ update.TextureAnim = part.TextureAnimation ?? Utils.EmptyBytes;
+ update.TextureEntry = part.Shape.TextureEntry ?? Utils.EmptyBytes;
+ update.Scale = part.Shape.Scale;
+ update.Text = Util.StringToBytes(part.Text, 255);
+ update.MediaURL = Util.StringToBytes(part.MediaUrl, 255);
#region PrimFlags
- PrimFlags flags = (PrimFlags)m_scene.Permissions.GenerateClientFlags(recipientID, data.UUID);
+ PrimFlags flags = (PrimFlags)m_scene.Permissions.GenerateClientFlags(part, sp);
// Don't send the CreateSelected flag to everyone
flags &= ~PrimFlags.CreateSelected;
- if (recipientID == data.OwnerID)
+ if (sp.UUID == part.OwnerID)
{
- if (data.CreateSelected)
+ if (part.CreateSelected)
{
// Only send this flag once, then unset it
flags |= PrimFlags.CreateSelected;
- data.CreateSelected = false;
+ part.CreateSelected = false;
}
}
@@ -5849,21 +5904,21 @@ namespace OpenSim.Region.ClientStack.LindenUDP
#endregion PrimFlags
- if (data.Sound != UUID.Zero)
+ if (part.Sound != UUID.Zero)
{
- update.Sound = data.Sound;
- update.OwnerID = data.OwnerID;
- update.Gain = (float)data.SoundGain;
- update.Radius = (float)data.SoundRadius;
- update.Flags = data.SoundFlags;
+ update.Sound = part.Sound;
+ update.OwnerID = part.OwnerID;
+ update.Gain = (float)part.SoundGain;
+ update.Radius = (float)part.SoundRadius;
+ update.Flags = part.SoundFlags;
}
- switch ((PCode)data.Shape.PCode)
+ switch ((PCode)part.Shape.PCode)
{
case PCode.Grass:
case PCode.Tree:
case PCode.NewTree:
- update.Data = new byte[] { data.Shape.State };
+ update.Data = new byte[] { part.Shape.State };
break;
default:
update.Data = Utils.EmptyBytes;
@@ -5941,10 +5996,10 @@ namespace OpenSim.Region.ClientStack.LindenUDP
AddLocalPacketHandler(PacketType.ParcelBuy, HandleParcelBuyRequest, false);
AddLocalPacketHandler(PacketType.UUIDGroupNameRequest, HandleUUIDGroupNameRequest);
AddLocalPacketHandler(PacketType.ObjectGroup, HandleObjectGroupRequest);
- AddLocalPacketHandler(PacketType.GenericMessage, HandleGenericMessage, true, true);
- AddLocalPacketHandler(PacketType.AvatarPropertiesRequest, HandleAvatarPropertiesRequest, true, true);
+ AddLocalPacketHandler(PacketType.GenericMessage, HandleGenericMessage);
+ AddLocalPacketHandler(PacketType.AvatarPropertiesRequest, HandleAvatarPropertiesRequest);
AddLocalPacketHandler(PacketType.ChatFromViewer, HandleChatFromViewer);
- AddLocalPacketHandler(PacketType.AvatarPropertiesUpdate, HandlerAvatarPropertiesUpdate, true, true);
+ AddLocalPacketHandler(PacketType.AvatarPropertiesUpdate, HandlerAvatarPropertiesUpdate);
AddLocalPacketHandler(PacketType.ScriptDialogReply, HandlerScriptDialogReply);
AddLocalPacketHandler(PacketType.ImprovedInstantMessage, HandlerImprovedInstantMessage);
AddLocalPacketHandler(PacketType.AcceptFriendship, HandlerAcceptFriendship);
@@ -6131,8 +6186,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP
AddLocalPacketHandler(PacketType.PickDelete, HandlePickDelete);
AddLocalPacketHandler(PacketType.PickGodDelete, HandlePickGodDelete);
AddLocalPacketHandler(PacketType.PickInfoUpdate, HandlePickInfoUpdate);
- AddLocalPacketHandler(PacketType.AvatarNotesUpdate, HandleAvatarNotesUpdate, true, true);
- AddLocalPacketHandler(PacketType.AvatarInterestsUpdate, HandleAvatarInterestsUpdate, true, true);
+ AddLocalPacketHandler(PacketType.AvatarNotesUpdate, HandleAvatarNotesUpdate);
+ AddLocalPacketHandler(PacketType.AvatarInterestsUpdate, HandleAvatarInterestsUpdate);
AddLocalPacketHandler(PacketType.GrantUserRights, HandleGrantUserRights);
AddLocalPacketHandler(PacketType.PlacesQuery, HandlePlacesQuery);
AddLocalPacketHandler(PacketType.UpdateMuteListEntry, HandleUpdateMuteListEntry);
@@ -6223,20 +6278,22 @@ namespace OpenSim.Region.ClientStack.LindenUDP
///
private bool CheckAgentCameraUpdateSignificance(AgentUpdatePacket.AgentDataBlock x)
{
- float vdelta = Vector3.Distance(x.CameraAtAxis, m_thisAgentUpdateArgs.CameraAtAxis);
- if((vdelta > VDELTA))
- return true;
+ if(Math.Abs(x.CameraCenter.X - m_thisAgentUpdateArgs.CameraCenter.X) > VDELTA ||
+ Math.Abs(x.CameraCenter.Y - m_thisAgentUpdateArgs.CameraCenter.Y) > VDELTA ||
+ Math.Abs(x.CameraCenter.Z - m_thisAgentUpdateArgs.CameraCenter.Z) > VDELTA ||
- vdelta = Vector3.Distance(x.CameraCenter, m_thisAgentUpdateArgs.CameraCenter);
- if((vdelta > VDELTA))
- return true;
+ Math.Abs(x.CameraAtAxis.X - m_thisAgentUpdateArgs.CameraAtAxis.X) > VDELTA ||
+ Math.Abs(x.CameraAtAxis.Y - m_thisAgentUpdateArgs.CameraAtAxis.Y) > VDELTA ||
+// Math.Abs(x.CameraAtAxis.Z - m_thisAgentUpdateArgs.CameraAtAxis.Z) > VDELTA ||
- vdelta = Vector3.Distance(x.CameraLeftAxis, m_thisAgentUpdateArgs.CameraLeftAxis);
- if((vdelta > VDELTA))
- return true;
+ Math.Abs(x.CameraLeftAxis.X - m_thisAgentUpdateArgs.CameraLeftAxis.X) > VDELTA ||
+ Math.Abs(x.CameraLeftAxis.Y - m_thisAgentUpdateArgs.CameraLeftAxis.Y) > VDELTA ||
+// Math.Abs(x.CameraLeftAxis.Z - m_thisAgentUpdateArgs.CameraLeftAxis.Z) > VDELTA ||
- vdelta = Vector3.Distance(x.CameraUpAxis, m_thisAgentUpdateArgs.CameraUpAxis);
- if((vdelta > VDELTA))
+ Math.Abs(x.CameraUpAxis.X - m_thisAgentUpdateArgs.CameraUpAxis.X) > VDELTA ||
+ Math.Abs(x.CameraUpAxis.Y - m_thisAgentUpdateArgs.CameraUpAxis.Y) > VDELTA
+// Math.Abs(x.CameraLeftAxis.Z - m_thisAgentUpdateArgs.CameraLeftAxis.Z) > VDELTA ||
+ )
return true;
return false;
@@ -6342,6 +6399,9 @@ namespace OpenSim.Region.ClientStack.LindenUDP
ParcelGodMarkAsContentPacket ParcelGodMarkAsContent =
(ParcelGodMarkAsContentPacket)Packet;
+ if(SessionId != ParcelGodMarkAsContent.AgentData.SessionID || AgentId != ParcelGodMarkAsContent.AgentData.AgentID)
+ return false;
+
ParcelGodMark ParcelGodMarkAsContentHandler = OnParcelGodMark;
if (ParcelGodMarkAsContentHandler != null)
{
@@ -6357,6 +6417,9 @@ namespace OpenSim.Region.ClientStack.LindenUDP
{
FreezeUserPacket FreezeUser = (FreezeUserPacket)Packet;
+ if(SessionId != FreezeUser.AgentData.SessionID || AgentId != FreezeUser.AgentData.AgentID)
+ return false;
+
FreezeUserUpdate FreezeUserHandler = OnParcelFreezeUser;
if (FreezeUserHandler != null)
{
@@ -6374,6 +6437,9 @@ namespace OpenSim.Region.ClientStack.LindenUDP
EjectUserPacket EjectUser =
(EjectUserPacket)Packet;
+ if(SessionId != EjectUser.AgentData.SessionID || AgentId != EjectUser.AgentData.AgentID)
+ return false;
+
EjectUserUpdate EjectUserHandler = OnParcelEjectUser;
if (EjectUserHandler != null)
{
@@ -6391,6 +6457,9 @@ namespace OpenSim.Region.ClientStack.LindenUDP
ParcelBuyPassPacket ParcelBuyPass =
(ParcelBuyPassPacket)Packet;
+ if(SessionId != ParcelBuyPass.AgentData.SessionID || AgentId != ParcelBuyPass.AgentData.AgentID)
+ return false;
+
ParcelBuyPass ParcelBuyPassHandler = OnParcelBuyPass;
if (ParcelBuyPassHandler != null)
{
@@ -6423,8 +6492,11 @@ namespace OpenSim.Region.ClientStack.LindenUDP
private bool HandleUUIDGroupNameRequest(IClientAPI sender, Packet Pack)
{
- UUIDGroupNameRequestPacket upack = (UUIDGroupNameRequestPacket)Pack;
+ ScenePresence sp = (ScenePresence)SceneAgent;
+ if(sp == null || sp.IsDeleted || (sp.IsInTransit && !sp.IsInLocalTransit))
+ return true;
+ UUIDGroupNameRequestPacket upack = (UUIDGroupNameRequestPacket)Pack;
for (int i = 0; i < upack.UUIDNameBlock.Length; i++)
{
@@ -7443,7 +7515,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP
SendUserInfoReply(false, true, "");
}
return true;
-
}
private bool HandleUpdateUserInfo(IClientAPI sender, Packet Pack)
@@ -7753,10 +7824,10 @@ namespace OpenSim.Region.ClientStack.LindenUDP
ObjectDuplicate handlerObjectDuplicate = null;
- for (int i = 0; i < dupe.ObjectData.Length; i++)
+ handlerObjectDuplicate = OnObjectDuplicate;
+ if (handlerObjectDuplicate != null)
{
- handlerObjectDuplicate = OnObjectDuplicate;
- if (handlerObjectDuplicate != null)
+ for (int i = 0; i < dupe.ObjectData.Length; i++)
{
UUID rezGroupID = dupe.AgentData.GroupID;
if(!IsGroupMember(rezGroupID))
@@ -7978,19 +8049,41 @@ namespace OpenSim.Region.ClientStack.LindenUDP
return true;
}
+ Dictionary objImageSeqs = null;
+ double lastobjImageSeqsMS = 0.0;
+
private bool HandleObjectImage(IClientAPI sender, Packet Pack)
{
ObjectImagePacket imagePack = (ObjectImagePacket)Pack;
- UpdatePrimTexture handlerUpdatePrimTexture = null;
+ UpdatePrimTexture handlerUpdatePrimTexture = OnUpdatePrimTexture;
+ if (handlerUpdatePrimTexture == null)
+ return true;
+
+ double now = Util.GetTimeStampMS();
+ if(objImageSeqs == null || ( now - lastobjImageSeqsMS > 30000.0))
+ {
+ objImageSeqs = null; // yeah i know superstition...
+ objImageSeqs = new Dictionary(16);
+ }
+
+ lastobjImageSeqsMS = now;
+ uint seq = Pack.Header.Sequence;
+ uint id;
+ uint lastseq;
+
+ ObjectImagePacket.ObjectDataBlock o;
for (int i = 0; i < imagePack.ObjectData.Length; i++)
{
- handlerUpdatePrimTexture = OnUpdatePrimTexture;
- if (handlerUpdatePrimTexture != null)
- {
- handlerUpdatePrimTexture(imagePack.ObjectData[i].ObjectLocalID,
- imagePack.ObjectData[i].TextureEntry, this);
- }
+ o = imagePack.ObjectData[i];
+ id = o.ObjectLocalID;
+ if(objImageSeqs.TryGetValue(id, out lastseq))
+ {
+ if(seq <= lastseq)
+ continue;
+ }
+ objImageSeqs[id] = seq;
+ handlerUpdatePrimTexture(id, o.TextureEntry, this);
}
return true;
}
@@ -9598,6 +9691,10 @@ namespace OpenSim.Region.ClientStack.LindenUDP
private bool HandleUUIDNameRequest(IClientAPI sender, Packet Pack)
{
+ ScenePresence sp = (ScenePresence)SceneAgent;
+ if(sp == null || sp.IsDeleted || (sp.IsInTransit && !sp.IsInLocalTransit))
+ return true;
+
UUIDNameRequestPacket incoming = (UUIDNameRequestPacket)Pack;
foreach (UUIDNameRequestPacket.UUIDNameBlockBlock UUIDBlock in incoming.UUIDNameBlock)
@@ -12515,11 +12612,11 @@ namespace OpenSim.Region.ClientStack.LindenUDP
}
int maxWearablesLoop = cachedtex.WearableData.Length;
- if (maxWearablesLoop > cacheItems.Length)
- maxWearablesLoop = cacheItems.Length;
if (cacheItems != null)
{
+ if (maxWearablesLoop > cacheItems.Length)
+ maxWearablesLoop = cacheItems.Length;
for (int i = 0; i < maxWearablesLoop; i++)
{
int idx = cachedtex.WearableData[i].TextureIndex;
@@ -13354,7 +13451,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP
SendAssetNotFound(req);
return;
}
-
}
if (transferRequest.TransferInfo.SourceType == (int)SourceType.Asset)
@@ -13431,11 +13527,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP
///
public bool Async { get; set; }
- ///
- /// If async is true, should this packet be handled in the async engine or given directly to a threadpool
- /// thread?
- ///
- public bool InEngine { get; set; }
}
public class AsyncPacketProcess
diff --git a/OpenSim/Region/ClientStack/Linden/UDP/LLUDPServer.cs b/OpenSim/Region/ClientStack/Linden/UDP/LLUDPServer.cs
index ec51e28488..b575ed9448 100644
--- a/OpenSim/Region/ClientStack/Linden/UDP/LLUDPServer.cs
+++ b/OpenSim/Region/ClientStack/Linden/UDP/LLUDPServer.cs
@@ -312,9 +312,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP
/// stack. Use zero to leave this value as the default
protected int m_recvBufferSize;
- /// Flag to process packets asynchronously or synchronously
- protected bool m_asyncPacketHandling;
-
/// Tracks whether or not a packet was sent each round so we know
/// whether or not to sleep
protected bool m_packetSent;
@@ -417,7 +414,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
/// Queue some low priority but potentially high volume async requests so that they don't overwhelm available
/// threadpool threads.
///
- public JobEngine IpahEngine { get; protected set; }
+// public JobEngine IpahEngine { get; protected set; }
///
/// Run queue empty processing within a single persistent thread.
@@ -473,7 +470,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP
IConfig config = configSource.Configs["ClientStack.LindenUDP"];
if (config != null)
{
- m_asyncPacketHandling = config.GetBoolean("async_packet_handling", true);
m_recvBufferSize = config.GetInt("client_socket_rcvbuf_size", 0);
sceneThrottleBps = config.GetInt("scene_throttle_max_bps", 0);
@@ -531,7 +527,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
{
StartInbound();
StartOutbound();
- IpahEngine.Start();
+// IpahEngine.Start();
OqrEngine.Start();
m_elapsedMSSinceLastStatReport = Environment.TickCount;
@@ -540,10 +536,9 @@ namespace OpenSim.Region.ClientStack.LindenUDP
public void StartInbound()
{
m_log.InfoFormat(
- "[LLUDPSERVER]: Starting inbound packet processing for the LLUDP server in {0} mode with UsePools = {1}",
- m_asyncPacketHandling ? "asynchronous" : "synchronous", UsePools);
+ "[LLUDPSERVER]: Starting inbound packet processing for the LLUDP server");
- base.StartInbound(m_recvBufferSize, m_asyncPacketHandling);
+ base.StartInbound(m_recvBufferSize);
// This thread will process the packets received that are placed on the packetInbox
WorkManager.StartThread(
@@ -577,7 +572,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
m_log.Info("[LLUDPSERVER]: Shutting down the LLUDP server for " + Scene.Name);
base.StopOutbound();
base.StopInbound();
- IpahEngine.Stop();
+// IpahEngine.Stop();
OqrEngine.Stop();
}
@@ -696,12 +691,12 @@ namespace OpenSim.Region.ClientStack.LindenUDP
Scene = (Scene)scene;
m_location = new Location(Scene.RegionInfo.RegionHandle);
-
+/*
IpahEngine
= new JobEngine(
string.Format("Incoming Packet Async Handling Engine ({0})", Scene.Name),
"INCOMING PACKET ASYNC HANDLING ENGINE");
-
+*/
OqrEngine
= new JobEngine(
string.Format("Outgoing Queue Refill Engine ({0})", Scene.Name),
@@ -786,7 +781,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
MeasuresOfInterest.AverageChangeOverTime,
stat => stat.Value = GetTotalQueuedOutgoingPackets(),
StatVerbosity.Info));
-
+/*
StatsManager.RegisterStat(
new Stat(
"IncomingPacketAsyncRequestsWaiting",
@@ -799,7 +794,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
MeasuresOfInterest.None,
stat => stat.Value = IpahEngine.JobsWaiting,
StatVerbosity.Debug));
-
+*/
StatsManager.RegisterStat(
new Stat(
"OQRERequestsWaiting",
@@ -1227,7 +1222,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP
outgoingPacket.SequenceNumber, isReliable, isResend, udpClient.AgentID, Scene.Name);
// Put the UDP payload on the wire
- AsyncBeginSend(buffer);
+// AsyncBeginSend(buffer);
+ SyncSend(buffer);
// Keep track of when this packet was sent out (right now)
outgoingPacket.TickCount = Environment.TickCount & Int32.MaxValue;
@@ -1912,7 +1908,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP
Buffer.BlockCopy(packetData, 0, buffer.Data, 0, length);
- AsyncBeginSend(buffer);
+// AsyncBeginSend(buffer);
+ SyncSend(buffer);
}
protected bool IsClientAuthorized(UseCircuitCodePacket useCircuitCode, out AuthenticateResponse sessionInfo)
diff --git a/OpenSim/Region/ClientStack/Linden/UDP/OpenSimUDPBase.cs b/OpenSim/Region/ClientStack/Linden/UDP/OpenSimUDPBase.cs
index 35a07111df..8dd96d65d6 100644
--- a/OpenSim/Region/ClientStack/Linden/UDP/OpenSimUDPBase.cs
+++ b/OpenSim/Region/ClientStack/Linden/UDP/OpenSimUDPBase.cs
@@ -57,9 +57,6 @@ namespace OpenMetaverse
/// UDP socket, used in either client or server mode
private Socket m_udpSocket;
- /// Flag to process packets asynchronously or synchronously
- private bool m_asyncPacketHandling;
-
///
/// Are we to use object pool(s) to reduce memory churn when receiving data?
///
@@ -205,10 +202,8 @@ namespace OpenMetaverse
/// manner (not throwing an exception when the remote side resets the
/// connection). This call is ignored on Mono where the flag is not
/// necessary
- public virtual void StartInbound(int recvBufferSize, bool asyncPacketHandling)
+ public virtual void StartInbound(int recvBufferSize)
{
- m_asyncPacketHandling = asyncPacketHandling;
-
if (!IsRunningInbound)
{
m_log.DebugFormat("[UDPBASE]: Starting inbound UDP loop");
@@ -407,12 +402,7 @@ namespace OpenMetaverse
if (IsRunningInbound)
{
UdpReceives++;
-
- // Asynchronous mode will start another receive before the
- // callback for this packet is even fired. Very parallel :-)
- if (m_asyncPacketHandling)
- AsyncBeginReceive();
-
+
try
{
// get the buffer that was created in AsyncBeginReceive
@@ -469,10 +459,7 @@ namespace OpenMetaverse
// if (UsePools)
// Pool.ReturnObject(buffer);
- // Synchronous mode waits until the packet callback completes
- // before starting the receive to fetch another packet
- if (!m_asyncPacketHandling)
- AsyncBeginReceive();
+ AsyncBeginReceive();
}
}
}
@@ -500,7 +487,7 @@ namespace OpenMetaverse
}
catch (SocketException) { }
catch (ObjectDisposedException) { }
-// }
+ // }
}
void AsyncEndSend(IAsyncResult result)
@@ -515,5 +502,25 @@ namespace OpenMetaverse
catch (SocketException) { }
catch (ObjectDisposedException) { }
}
+
+ public void SyncSend(UDPPacketBuffer buf)
+ {
+ try
+ {
+ m_udpSocket.SendTo(
+ buf.Data,
+ 0,
+ buf.DataLength,
+ SocketFlags.None,
+ buf.RemoteEndPoint
+ );
+ UdpSends++;
+ }
+ catch (SocketException e)
+ {
+ m_log.Warn("[UDPBASE]: sync send SocketException {0} " + e.Message);
+ }
+ catch (ObjectDisposedException) { }
+ }
}
}
diff --git a/OpenSim/Region/ClientStack/Linden/UDP/Tests/BasicCircuitTests.cs b/OpenSim/Region/ClientStack/Linden/UDP/Tests/BasicCircuitTests.cs
index 0e1a9e3d10..eb262d27f7 100644
--- a/OpenSim/Region/ClientStack/Linden/UDP/Tests/BasicCircuitTests.cs
+++ b/OpenSim/Region/ClientStack/Linden/UDP/Tests/BasicCircuitTests.cs
@@ -91,6 +91,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP.Tests
///
/// Test adding a client to the stack
///
+/*
[Test]
public void TestAddClient()
{
@@ -165,7 +166,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP.Tests
ScenePresence spAfterAckTimeout = m_scene.GetScenePresence(sp.UUID);
Assert.That(spAfterAckTimeout, Is.Null);
}
-
+*/
// ///
// /// Test removing a client from the stack
// ///
diff --git a/OpenSim/Region/CoreModules/Agent/AssetTransaction/AssetXferUploader.cs b/OpenSim/Region/CoreModules/Agent/AssetTransaction/AssetXferUploader.cs
index d2aa17793c..52b9d0ee84 100644
--- a/OpenSim/Region/CoreModules/Agent/AssetTransaction/AssetXferUploader.cs
+++ b/OpenSim/Region/CoreModules/Agent/AssetTransaction/AssetXferUploader.cs
@@ -258,24 +258,24 @@ namespace OpenSim.Region.CoreModules.Agent.AssetTransaction
{
m_uploadState = UploadState.Complete;
- ourClient.SendAssetUploadCompleteMessage(m_asset.Type, true, m_asset.FullID);
-
+ bool sucess = true;
if (m_createItem)
{
- CompleteCreateItem(m_createItemCallback);
+ sucess = CompleteCreateItem(m_createItemCallback);
}
else if (m_updateItem)
{
- CompleteItemUpdate(m_updateItemData);
+ sucess = CompleteItemUpdate(m_updateItemData);
}
else if (m_updateTaskItem)
{
- CompleteTaskItemUpdate(m_updateTaskItemData);
+ sucess = CompleteTaskItemUpdate(m_updateTaskItemData);
}
else if (m_asset.Local)
{
m_Scene.AssetService.Store(m_asset);
}
+ ourClient.SendAssetUploadCompleteMessage(m_asset.Type, sucess, m_asset.FullID);
}
m_log.DebugFormat(
@@ -411,46 +411,70 @@ namespace OpenSim.Region.CoreModules.Agent.AssetTransaction
/// Store the asset for the given item when it has been uploaded.
///
///
- private void CompleteItemUpdate(InventoryItemBase item)
+ private bool CompleteItemUpdate(InventoryItemBase item)
{
// m_log.DebugFormat(
// "[ASSET XFER UPLOADER]: Storing asset {0} for earlier item update for {1} for {2}",
// m_asset.FullID, item.Name, ourClient.Name);
- ValidateAssets();
- m_Scene.AssetService.Store(m_asset);
- if (m_asset.FullID != UUID.Zero)
+ uint perms = ValidateAssets();
+ if(perms == 0)
{
- item.AssetID = m_asset.FullID;
- m_Scene.InventoryService.UpdateItem(item);
+ string error = string.Format("Not enough permissions on asset(s) referenced by item '{0}', update failed", item.Name);
+ ourClient.SendAlertMessage(error);
+ m_transactions.RemoveXferUploader(m_transactionID);
+ ourClient.SendBulkUpdateInventory(item); // invalid the change item on viewer cache
+ }
+ else
+ {
+ m_Scene.AssetService.Store(m_asset);
+ if (m_asset.FullID != UUID.Zero)
+ {
+ item.AssetID = m_asset.FullID;
+ m_Scene.InventoryService.UpdateItem(item);
+ }
+ ourClient.SendInventoryItemCreateUpdate(item, m_transactionID, 0);
+ m_transactions.RemoveXferUploader(m_transactionID);
+ m_Scene.EventManager.TriggerOnNewInventoryItemUploadComplete(item, 0);
}
- ourClient.SendInventoryItemCreateUpdate(item, m_transactionID, 0);
-
- m_transactions.RemoveXferUploader(m_transactionID);
-
- m_Scene.EventManager.TriggerOnNewInventoryItemUploadComplete(item, 0);
+ return perms != 0;
}
///
/// Store the asset for the given task item when it has been uploaded.
///
///
- private void CompleteTaskItemUpdate(TaskInventoryItem taskItem)
+ private bool CompleteTaskItemUpdate(TaskInventoryItem taskItem)
{
// m_log.DebugFormat(
// "[ASSET XFER UPLOADER]: Storing asset {0} for earlier task item update for {1} for {2}",
// m_asset.FullID, taskItem.Name, ourClient.Name);
- ValidateAssets();
- m_Scene.AssetService.Store(m_asset);
+ if(ValidateAssets() == 0)
+ {
+ m_transactions.RemoveXferUploader(m_transactionID);
+ string error = string.Format("Not enough permissions on asset(s) referenced by task item '{0}', update failed", taskItem.Name);
+ ourClient.SendAlertMessage(error);
+ // force old asset to viewers ??
+ return false;
+ }
+ m_Scene.AssetService.Store(m_asset);
m_transactions.RemoveXferUploader(m_transactionID);
+ return true;
}
- private void CompleteCreateItem(uint callbackID)
+ private bool CompleteCreateItem(uint callbackID)
{
- ValidateAssets();
+ if(ValidateAssets() == 0)
+ {
+ m_transactions.RemoveXferUploader(m_transactionID);
+ string error = string.Format("Not enough permissions on asset(s) referenced by item '{0}', creation failed", m_name);
+ ourClient.SendAlertMessage(error);
+ return false;
+ }
+
m_Scene.AssetService.Store(m_asset);
InventoryItemBase item = new InventoryItemBase();
@@ -480,35 +504,40 @@ namespace OpenSim.Region.CoreModules.Agent.AssetTransaction
ourClient.SendAlertMessage("Unable to create inventory item");
m_transactions.RemoveXferUploader(m_transactionID);
+ return true;
}
-
- private void ValidateAssets()
+ private uint ValidateAssets()
{
+ uint retPerms = 0x7fffffff;
+// if(m_Scene.Permissions.BypassPermissions())
+// return retPerms;
+
if (m_asset.Type == (sbyte)CustomAssetType.AnimationSet)
{
+
AnimationSet animSet = new AnimationSet(m_asset.Data);
- bool allOk = animSet.Validate(x => {
- int perms = m_Scene.InventoryService.GetAssetPermissions(ourClient.AgentId, x);
- int required = (int)(PermissionMask.Transfer | PermissionMask.Copy);
+ retPerms &= animSet.Validate(x => {
+ const uint required = (uint)(PermissionMask.Transfer | PermissionMask.Copy);
+ uint perms = (uint)m_Scene.InventoryService.GetAssetPermissions(ourClient.AgentId, x);
+ // currrent yes/no rule
if ((perms & required) != required)
- return false;
- return true;
+ return 0;
+ return perms;
});
- if (!allOk)
- m_asset.Data = animSet.ToBytes();
+ return retPerms;
}
if (m_asset.Type == (sbyte)AssetType.Clothing ||
m_asset.Type == (sbyte)AssetType.Bodypart)
{
+ const uint texturesfullPermMask = (uint)(PermissionMask.Modify | PermissionMask.Transfer | PermissionMask.Copy);
string content = System.Text.Encoding.ASCII.GetString(m_asset.Data);
string[] lines = content.Split(new char[] {'\n'});
- List validated = new List();
-
+ // on current requiriment of full rigths assume old assets where accepted
Dictionary allowed = ExtractTexturesFromOldData();
int textures = 0;
@@ -518,10 +547,8 @@ namespace OpenSim.Region.CoreModules.Agent.AssetTransaction
try
{
if (line.StartsWith("textures "))
- {
textures = Convert.ToInt32(line.Substring(9));
- validated.Add(line);
- }
+
else if (textures > 0)
{
string[] parts = line.Split(new char[] {' '});
@@ -532,42 +559,35 @@ namespace OpenSim.Region.CoreModules.Agent.AssetTransaction
if (defaultIDs.Contains(tx) || tx == UUID.Zero ||
(allowed.ContainsKey(id) && allowed[id] == tx))
{
- validated.Add(parts[0] + " " + tx.ToString());
+ continue;
}
else
{
- int perms = m_Scene.InventoryService.GetAssetPermissions(ourClient.AgentId, tx);
- int full = (int)(PermissionMask.Modify | PermissionMask.Transfer | PermissionMask.Copy);
+ uint perms = (uint)m_Scene.InventoryService.GetAssetPermissions(ourClient.AgentId, tx);
- if ((perms & full) != full)
+ if ((perms & texturesfullPermMask) != texturesfullPermMask)
{
m_log.ErrorFormat("[ASSET UPLOADER]: REJECTED update with texture {0} from {1} because they do not own the texture", tx, ourClient.AgentId);
- validated.Add(parts[0] + " " + UUID.Zero.ToString());
+ return 0;
}
else
{
- validated.Add(line);
+ retPerms &= perms;
}
}
textures--;
}
- else
- {
- validated.Add(line);
- }
}
catch
{
// If it's malformed, skip it
}
}
-
- string final = String.Join("\n", validated.ToArray());
-
- m_asset.Data = System.Text.Encoding.ASCII.GetBytes(final);
}
+ return retPerms;
}
+/* not in use
///
/// Get the asset data uploaded in this transfer.
///
@@ -582,7 +602,7 @@ namespace OpenSim.Region.CoreModules.Agent.AssetTransaction
return null;
}
-
+*/
public void SetOldData(byte[] d)
{
m_oldData = d;
diff --git a/OpenSim/Region/CoreModules/Agent/IPBan/SceneBanner.cs b/OpenSim/Region/CoreModules/Agent/IPBan/SceneBanner.cs
index 8502006cd7..b4c68e2a65 100644
--- a/OpenSim/Region/CoreModules/Agent/IPBan/SceneBanner.cs
+++ b/OpenSim/Region/CoreModules/Agent/IPBan/SceneBanner.cs
@@ -53,9 +53,9 @@ namespace OpenSim.Region.CoreModules.Agent.IPBan
if (bans.Count > 0)
{
IClientIPEndpoint ipEndpoint;
- if (client.TryGet(out ipEndpoint))
+ if (client.TryGet(out ipEndpoint) && ipEndpoint.RemoteEndPoint != null)
{
- IPAddress end = ipEndpoint.EndPoint;
+ IPAddress end = ipEndpoint.RemoteEndPoint.Address;
try
{
diff --git a/OpenSim/Region/CoreModules/Agent/TextureSender/J2KDecoderModule.cs b/OpenSim/Region/CoreModules/Agent/TextureSender/J2KDecoderModule.cs
index 2242e421c4..6e4a710bf9 100644
--- a/OpenSim/Region/CoreModules/Agent/TextureSender/J2KDecoderModule.cs
+++ b/OpenSim/Region/CoreModules/Agent/TextureSender/J2KDecoderModule.cs
@@ -369,7 +369,8 @@ namespace OpenSim.Region.CoreModules.Agent.TextureSender
else if (Cache != null)
{
string assetName = "j2kCache_" + AssetId.ToString();
- AssetBase layerDecodeAsset = Cache.Get(assetName);
+ AssetBase layerDecodeAsset;
+ Cache.Get(assetName, out layerDecodeAsset);
if (layerDecodeAsset != null)
{
diff --git a/OpenSim/Region/CoreModules/Asset/CenomeAssetCache.cs b/OpenSim/Region/CoreModules/Asset/CenomeAssetCache.cs
index 23c1f035b8..403236c170 100644
--- a/OpenSim/Region/CoreModules/Asset/CenomeAssetCache.cs
+++ b/OpenSim/Region/CoreModules/Asset/CenomeAssetCache.cs
@@ -260,10 +260,9 @@ namespace OpenSim.Region.CoreModules.Asset
/// Cache doesn't guarantee in any situation that asset is stored to it.
///
///
- public AssetBase Get(string id)
+ public bool Get(string id, out AssetBase assetBase)
{
m_getCount++;
- AssetBase assetBase;
if (m_cache.TryGetValue(id, out assetBase))
m_hitCount++;
@@ -284,7 +283,7 @@ namespace OpenSim.Region.CoreModules.Asset
// if (null == assetBase)
// m_log.DebugFormat("[CENOME ASSET CACHE]: Asset {0} not in cache", id);
- return assetBase;
+ return true;
}
#endregion
diff --git a/OpenSim/Region/CoreModules/Asset/CoreAssetCache.cs b/OpenSim/Region/CoreModules/Asset/CoreAssetCache.cs
index 51fc3d1d7b..10c0e85175 100644
--- a/OpenSim/Region/CoreModules/Asset/CoreAssetCache.cs
+++ b/OpenSim/Region/CoreModules/Asset/CoreAssetCache.cs
@@ -115,7 +115,10 @@ namespace OpenSim.Region.CoreModules.Asset
public bool Check(string id)
{
// XXX This is probably not an efficient implementation.
- return Get(id) != null;
+ AssetBase asset;
+ if (!Get(id, out asset))
+ return false;
+ return asset != null;
}
public void Cache(AssetBase asset)
@@ -129,9 +132,10 @@ namespace OpenSim.Region.CoreModules.Asset
// We don't do negative caching
}
- public AssetBase Get(string id)
+ public bool Get(string id, out AssetBase asset)
{
- return (AssetBase)m_Cache.Get(id);
+ asset = (AssetBase)m_Cache.Get(id);
+ return true;
}
public void Expire(string id)
diff --git a/OpenSim/Region/CoreModules/Asset/FlotsamAssetCache.cs b/OpenSim/Region/CoreModules/Asset/FlotsamAssetCache.cs
index 187f090ec5..f2fc070c58 100644
--- a/OpenSim/Region/CoreModules/Asset/FlotsamAssetCache.cs
+++ b/OpenSim/Region/CoreModules/Asset/FlotsamAssetCache.cs
@@ -474,6 +474,8 @@ namespace OpenSim.Region.CoreModules.Asset
{
using (FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
{
+ if (stream.Length == 0) // Empty file will trigger exception below
+ return null;
BinaryFormatter bformatter = new BinaryFormatter();
asset = (AssetBase)bformatter.Deserialize(stream);
@@ -531,15 +533,26 @@ namespace OpenSim.Region.CoreModules.Asset
return found;
}
+ // For IAssetService
public AssetBase Get(string id)
{
+ AssetBase asset;
+ Get(id, out asset);
+ return asset;
+ }
+
+ public bool Get(string id, out AssetBase asset)
+ {
+ asset = null;
+
m_Requests++;
object dummy;
if (m_negativeCache.TryGetValue(id, out dummy))
- return null;
+ {
+ return false;
+ }
- AssetBase asset = null;
asset = GetFromWeakReference(id);
if (asset != null && m_updateFileTimeOnCacheHit)
{
@@ -578,13 +591,7 @@ namespace OpenSim.Region.CoreModules.Asset
GenerateCacheHitReport().ForEach(l => m_log.InfoFormat("[FLOTSAM ASSET CACHE]: {0}", l));
}
- if(asset == null)
- {
-
-
- }
-
- return asset;
+ return true;
}
public bool Check(string id)
@@ -599,7 +606,9 @@ namespace OpenSim.Region.CoreModules.Asset
public AssetBase GetCached(string id)
{
- return Get(id);
+ AssetBase asset;
+ Get(id, out asset);
+ return asset;
}
public void Expire(string id)
@@ -637,7 +646,7 @@ namespace OpenSim.Region.CoreModules.Asset
if (m_LogLevel >= 2)
m_log.Debug("[FLOTSAM ASSET CACHE]: Clearing caches.");
- if (m_FileCacheEnabled)
+ if (m_FileCacheEnabled && Directory.Exists(m_CacheDirectory))
{
foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
{
@@ -672,10 +681,10 @@ namespace OpenSim.Region.CoreModules.Asset
// before cleaning up expired files we must scan the objects in the scene to make sure that we retain
// such local assets if they have not been recently accessed.
TouchAllSceneAssets(false);
-
- foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
+ if(Directory.Exists(m_CacheDirectory))
{
- CleanExpiredFiles(dir, purgeLine);
+ foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
+ CleanExpiredFiles(dir, purgeLine);
}
lock(timerLock)
@@ -697,6 +706,9 @@ namespace OpenSim.Region.CoreModules.Asset
{
try
{
+ if(!Directory.Exists(dir))
+ return;
+
foreach (string file in Directory.GetFiles(dir))
{
if (File.GetLastAccessTime(file) < purgeLine)
@@ -797,6 +809,9 @@ namespace OpenSim.Region.CoreModules.Asset
return;
}
+ catch (UnauthorizedAccessException e)
+ {
+ }
finally
{
if (stream != null)
@@ -857,6 +872,9 @@ namespace OpenSim.Region.CoreModules.Asset
///
private int GetFileCacheCount(string dir)
{
+ if(!Directory.Exists(dir))
+ return 0;
+
int count = Directory.GetFiles(dir).Length;
foreach (string subdir in Directory.GetDirectories(dir))
@@ -975,6 +993,9 @@ namespace OpenSim.Region.CoreModules.Asset
///
private void ClearFileCache()
{
+ if(!Directory.Exists(m_CacheDirectory))
+ return;
+
foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
{
try
@@ -1147,7 +1168,7 @@ namespace OpenSim.Region.CoreModules.Asset
con.Output("FloatSam Ensuring assets are cached for all scenes.");
- WorkManager.RunInThread(delegate
+ WorkManager.RunInThreadPool(delegate
{
bool wasRunning= false;
lock(timerLock)
@@ -1227,19 +1248,23 @@ namespace OpenSim.Region.CoreModules.Asset
public AssetMetadata GetMetadata(string id)
{
- AssetBase asset = Get(id);
+ AssetBase asset;
+ Get(id, out asset);
return asset.Metadata;
}
public byte[] GetData(string id)
{
- AssetBase asset = Get(id);
+ AssetBase asset;
+ Get(id, out asset);
return asset.Data;
}
public bool Get(string id, object sender, AssetRetrieved handler)
{
- AssetBase asset = Get(id);
+ AssetBase asset;
+ if (!Get(id, out asset))
+ return false;
handler(id, sender, asset);
return true;
}
@@ -1270,7 +1295,9 @@ namespace OpenSim.Region.CoreModules.Asset
public bool UpdateContent(string id, byte[] data)
{
- AssetBase asset = Get(id);
+ AssetBase asset;
+ if (!Get(id, out asset))
+ return false;
asset.Data = data;
Cache(asset);
return true;
diff --git a/OpenSim/Region/CoreModules/Asset/GlynnTuckerAssetCache.cs b/OpenSim/Region/CoreModules/Asset/GlynnTuckerAssetCache.cs
index 208963d1f4..abe9b23770 100644
--- a/OpenSim/Region/CoreModules/Asset/GlynnTuckerAssetCache.cs
+++ b/OpenSim/Region/CoreModules/Asset/GlynnTuckerAssetCache.cs
@@ -131,14 +131,15 @@ namespace OpenSim.Region.CoreModules.Asset
// We don't do negative caching
}
- public AssetBase Get(string id)
+ public bool Get(string id, out AssetBase asset)
{
- Object asset = null;
- m_Cache.TryGet(id, out asset);
+ Object a = null;
+ m_Cache.TryGet(id, out a);
- Debug(asset);
+ Debug(a);
- return (AssetBase)asset;
+ asset = (AssetBase)a;
+ return true;
}
public void Expire(string id)
diff --git a/OpenSim/Region/CoreModules/Avatar/Attachments/AttachmentsModule.cs b/OpenSim/Region/CoreModules/Avatar/Attachments/AttachmentsModule.cs
index 8b8ac20c4d..5bca482af3 100644
--- a/OpenSim/Region/CoreModules/Avatar/Attachments/AttachmentsModule.cs
+++ b/OpenSim/Region/CoreModules/Avatar/Attachments/AttachmentsModule.cs
@@ -42,6 +42,7 @@ using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Serialization;
using OpenSim.Services.Interfaces;
+using PermissionMask = OpenSim.Framework.PermissionMask;
namespace OpenSim.Region.CoreModules.Avatar.Attachments
{
@@ -481,14 +482,6 @@ namespace OpenSim.Region.CoreModules.Avatar.Attachments
// "[ATTACHMENTS MODULE]: Attaching object {0} {1} to {2} point {3} from ground (silent = {4})",
// group.Name, group.LocalId, sp.Name, attachmentPt, silent);
- if (sp.GetAttachments().Contains(group))
- {
-// m_log.WarnFormat(
-// "[ATTACHMENTS MODULE]: Ignoring request to attach {0} {1} to {2} on {3} since it's already attached",
-// group.Name, group.LocalId, sp.Name, AttachmentPt);
-
- return false;
- }
if (group.GetSittingAvatarsCount() != 0)
{
@@ -500,6 +493,17 @@ namespace OpenSim.Region.CoreModules.Avatar.Attachments
return false;
}
+ List attachments = sp.GetAttachments(attachmentPt);
+ if (attachments.Contains(group))
+ {
+// if (DebugLevel > 0)
+// m_log.WarnFormat(
+// "[ATTACHMENTS MODULE]: Ignoring request to attach {0} {1} to {2} on {3} since it's already attached",
+// group.Name, group.LocalId, sp.Name, attachmentPt);
+
+ return false;
+ }
+
Vector3 attachPos = group.AbsolutePosition;
// TODO: this short circuits multiple attachments functionality in LL viewer 2.1+ and should
@@ -533,7 +537,6 @@ namespace OpenSim.Region.CoreModules.Avatar.Attachments
{
attachmentPt = (uint)group.RootPart.Shape.LastAttachPoint;
attachPos = group.RootPart.AttachedPos;
- group.HasGroupChanged = true;
}
// if we still didn't find a suitable attachment point.......
@@ -544,18 +547,6 @@ namespace OpenSim.Region.CoreModules.Avatar.Attachments
attachPos = Vector3.Zero;
}
- List attachments = sp.GetAttachments(attachmentPt);
-
- if (attachments.Contains(group))
- {
- if (DebugLevel > 0)
- m_log.WarnFormat(
- "[ATTACHMENTS MODULE]: Ignoring request to attach {0} {1} to {2} on {3} since it's already attached",
- group.Name, group.LocalId, sp.Name, attachmentPt);
-
- return false;
- }
-
// If we already have 5, remove the oldest until only 4 are left. Skip over temp ones
while (attachments.Count >= 5)
{
@@ -579,7 +570,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Attachments
lock (sp.AttachmentsSyncLock)
{
group.AttachmentPoint = attachmentPt;
- group.AbsolutePosition = attachPos;
+ group.RootPart.AttachedPos = attachPos;
if (addToInventory && sp.PresenceType != PresenceType.Npc)
UpdateUserInventoryWithAttachment(sp, group, attachmentPt, append);
@@ -906,6 +897,30 @@ namespace OpenSim.Region.CoreModules.Avatar.Attachments
if (item != null)
{
+ // attach is rez, need to update permissions
+ item.Flags &= ~(uint)(InventoryItemFlags.ObjectSlamPerm | InventoryItemFlags.ObjectOverwriteBase |
+ InventoryItemFlags.ObjectOverwriteOwner | InventoryItemFlags.ObjectOverwriteGroup |
+ InventoryItemFlags.ObjectOverwriteEveryone | InventoryItemFlags.ObjectOverwriteNextOwner);
+
+ uint permsBase = (uint)(PermissionMask.Copy | PermissionMask.Transfer |
+ PermissionMask.Modify | PermissionMask.Move |
+ PermissionMask.Export | PermissionMask.FoldedMask);
+
+ permsBase &= grp.CurrentAndFoldedNextPermissions();
+ permsBase |= (uint)PermissionMask.Move;
+ item.BasePermissions = permsBase;
+ item.CurrentPermissions = permsBase;
+ item.NextPermissions = permsBase & grp.RootPart.NextOwnerMask | (uint)PermissionMask.Move;
+ item.EveryOnePermissions = permsBase & grp.RootPart.EveryoneMask;
+ item.GroupPermissions = permsBase & grp.RootPart.GroupMask;
+ item.CurrentPermissions &=
+ ((uint)PermissionMask.Copy |
+ (uint)PermissionMask.Transfer |
+ (uint)PermissionMask.Modify |
+ (uint)PermissionMask.Move |
+ (uint)PermissionMask.Export |
+ (uint)PermissionMask.FoldedMask); // Preserve folded permissions ??
+
AssetBase asset = m_scene.CreateAsset(
grp.GetPartName(grp.LocalId),
grp.GetPartDescription(grp.LocalId),
@@ -956,7 +971,6 @@ namespace OpenSim.Region.CoreModules.Avatar.Attachments
m_scene.DeleteFromStorage(so.UUID);
m_scene.EventManager.TriggerParcelPrimCountTainted();
- so.AttachedAvatar = sp.UUID;
foreach (SceneObjectPart part in so.Parts)
{
@@ -969,11 +983,12 @@ namespace OpenSim.Region.CoreModules.Avatar.Attachments
}
}
- so.AbsolutePosition = attachOffset;
- so.RootPart.AttachedPos = attachOffset;
- so.IsAttachment = true;
so.RootPart.SetParentLocalId(sp.LocalId);
+ so.AttachedAvatar = sp.UUID;
so.AttachmentPoint = attachmentpoint;
+ so.RootPart.AttachedPos = attachOffset;
+ so.AbsolutePosition = attachOffset;
+ so.IsAttachment = true;
sp.AddAttachment(so);
@@ -1322,7 +1337,9 @@ namespace OpenSim.Region.CoreModules.Avatar.Attachments
if (part == null)
return;
- if (!m_scene.Permissions.CanTakeObject(part.UUID, remoteClient.AgentId))
+ SceneObjectGroup group = part.ParentGroup;
+
+ if (!m_scene.Permissions.CanTakeObject(group, sp))
{
remoteClient.SendAgentAlertMessage(
"You don't have sufficient permissions to attach this object", false);
@@ -1334,7 +1351,6 @@ namespace OpenSim.Region.CoreModules.Avatar.Attachments
AttachmentPt &= 0x7f;
// Calls attach with a Zero position
- SceneObjectGroup group = part.ParentGroup;
if (AttachObject(sp, group , AttachmentPt, false, true, append))
{
if (DebugLevel > 0)
diff --git a/OpenSim/Region/CoreModules/Avatar/AvatarFactory/AvatarFactoryModule.cs b/OpenSim/Region/CoreModules/Avatar/AvatarFactory/AvatarFactoryModule.cs
index fb408a402d..9553f5b4b8 100644
--- a/OpenSim/Region/CoreModules/Avatar/AvatarFactory/AvatarFactoryModule.cs
+++ b/OpenSim/Region/CoreModules/Avatar/AvatarFactory/AvatarFactoryModule.cs
@@ -299,7 +299,8 @@ namespace OpenSim.Region.CoreModules.Avatar.AvatarFactory
if (bakedTextureFace == null)
continue;
- AssetBase asset = cache.Get(bakedTextureFace.TextureID.ToString());
+ AssetBase asset;
+ cache.Get(bakedTextureFace.TextureID.ToString(), out asset);
if (asset != null && asset.Local)
{
@@ -368,7 +369,7 @@ namespace OpenSim.Region.CoreModules.Avatar.AvatarFactory
return true;
// uploaded baked textures will be in assets local cache
- IAssetService cache = m_scene.AssetService;
+ IAssetCache cache = m_scene.RequestModuleInterface();
IBakedTextureModule m_BakedTextureModule = m_scene.RequestModuleInterface();
int validDirtyBakes = 0;
@@ -384,7 +385,7 @@ namespace OpenSim.Region.CoreModules.Avatar.AvatarFactory
List missing = new List();
- bool haveSkirt = (wearableCache[19].TextureAsset != null);
+ bool haveSkirt = (wearableCache[19].TextureID != UUID.Zero);
bool haveNewSkirt = false;
// Process received baked textures
@@ -435,7 +436,11 @@ namespace OpenSim.Region.CoreModules.Avatar.AvatarFactory
*/
wearableCache[idx].TextureAsset = null;
if (cache != null)
- wearableCache[idx].TextureAsset = cache.GetCached(face.TextureID.ToString());
+ {
+ AssetBase asb = null;
+ cache.Get(face.TextureID.ToString(), out asb);
+ wearableCache[idx].TextureAsset = asb;
+ }
if (wearableCache[idx].TextureAsset != null)
{
@@ -480,25 +485,26 @@ namespace OpenSim.Region.CoreModules.Avatar.AvatarFactory
// if we got a full set of baked textures save all in BakedTextureModule
if (m_BakedTextureModule != null)
{
- m_log.Debug("[UpdateBakedCache] start async uploading to bakedModule cache");
+ m_log.DebugFormat("[UpdateBakedCache] Uploading to Bakes Server: cache hits: {0} changed entries: {1} rebakes {2}",
+ hits.ToString(), validDirtyBakes.ToString(), missing.Count);
m_BakedTextureModule.Store(sp.UUID, wearableCache);
}
}
+ else
+ m_log.DebugFormat("[UpdateBakedCache] cache hits: {0} changed entries: {1} rebakes {2}",
+ hits.ToString(), validDirtyBakes.ToString(), missing.Count);
-
- // debug
- m_log.Debug("[UpdateBakedCache] cache hits: " + hits.ToString() + " changed entries: " + validDirtyBakes.ToString() + " rebakes " + missing.Count);
-/*
for (int iter = 0; iter < AvatarAppearance.BAKE_INDICES.Length; iter++)
{
int j = AvatarAppearance.BAKE_INDICES[iter];
- m_log.Debug("[UpdateBCache] {" + iter + "/" +
- sp.Appearance.WearableCacheItems[j].TextureIndex + "}: c-" +
- sp.Appearance.WearableCacheItems[j].CacheId + ", t-" +
- sp.Appearance.WearableCacheItems[j].TextureID);
+ sp.Appearance.WearableCacheItems[j].TextureAsset = null;
+// m_log.Debug("[UpdateBCache] {" + iter + "/" +
+// sp.Appearance.WearableCacheItems[j].TextureIndex + "}: c-" +
+// sp.Appearance.WearableCacheItems[j].CacheId + ", t-" +
+// sp.Appearance.WearableCacheItems[j].TextureID);
}
-*/
+
return (hits == cacheItems.Length);
}
@@ -512,7 +518,7 @@ namespace OpenSim.Region.CoreModules.Avatar.AvatarFactory
lock (m_setAppearanceLock)
{
- IAssetService cache = m_scene.AssetService;
+ IAssetCache cache = m_scene.RequestModuleInterface();
IBakedTextureModule bakedModule = m_scene.RequestModuleInterface();
WearableCacheItem[] bakedModuleCache = null;
@@ -552,6 +558,7 @@ namespace OpenSim.Region.CoreModules.Avatar.AvatarFactory
}
}
*/
+
bool wearableCacheValid = false;
if (wearableCache == null)
{
@@ -576,10 +583,12 @@ namespace OpenSim.Region.CoreModules.Avatar.AvatarFactory
hits++;
wearableCache[idx].TextureAsset.Temporary = true;
wearableCache[idx].TextureAsset.Local = true;
- cache.Store(wearableCache[idx].TextureAsset);
+ cache.Cache(wearableCache[idx].TextureAsset);
+ wearableCache[idx].TextureAsset = null;
continue;
}
- if (cache.GetCached((wearableCache[idx].TextureID).ToString()) != null)
+
+ if (cache.Check((wearableCache[idx].TextureID).ToString()))
{
hits++;
continue;
@@ -644,7 +653,7 @@ namespace OpenSim.Region.CoreModules.Avatar.AvatarFactory
wearableCache[j].TextureAsset = bakedModuleCache[i].TextureAsset;
bakedModuleCache[i].TextureAsset.Temporary = true;
bakedModuleCache[i].TextureAsset.Local = true;
- cache.Store(bakedModuleCache[i].TextureAsset);
+ cache.Cache(bakedModuleCache[i].TextureAsset);
}
}
gotbacked = true;
@@ -676,6 +685,7 @@ namespace OpenSim.Region.CoreModules.Avatar.AvatarFactory
face.TextureID = wearableCache[idx].TextureID;
hits++;
+ wearableCache[idx].TextureAsset = null;
}
}
}
@@ -705,7 +715,7 @@ namespace OpenSim.Region.CoreModules.Avatar.AvatarFactory
return 0;
int texturesRebaked = 0;
-// IAssetCache cache = m_scene.RequestModuleInterface();
+ IAssetCache cache = m_scene.RequestModuleInterface();
for (int i = 0; i < AvatarAppearance.BAKE_INDICES.Length; i++)
{
@@ -721,18 +731,12 @@ namespace OpenSim.Region.CoreModules.Avatar.AvatarFactory
if (missingTexturesOnly)
{
- if (m_scene.AssetService.Get(face.TextureID.ToString()) != null)
+ if (cache != null && cache.Check(face.TextureID.ToString()))
{
continue;
}
else
{
- // On inter-simulator teleports, this occurs if baked textures are not being stored by the
- // grid asset service (which means that they are not available to the new region and so have
- // to be re-requested from the client).
- //
- // The only available core OpenSimulator behaviour right now
- // is not to store these textures, temporarily or otherwise.
m_log.DebugFormat(
"[AVFACTORY]: Missing baked texture {0} ({1}) for {2}, requesting rebake.",
face.TextureID, idx, sp.Name);
diff --git a/OpenSim/Region/CoreModules/Avatar/BakedTextures/XBakesModule.cs b/OpenSim/Region/CoreModules/Avatar/BakedTextures/XBakesModule.cs
index 27e84b0f13..cfa9581d82 100644
--- a/OpenSim/Region/CoreModules/Avatar/BakedTextures/XBakesModule.cs
+++ b/OpenSim/Region/CoreModules/Avatar/BakedTextures/XBakesModule.cs
@@ -216,6 +216,8 @@ namespace OpenSim.Region.CoreModules.Avatar.BakedTextures
rc.Request(reqStream, m_Auth);
m_log.DebugFormat("[XBakes]: stored {0} textures for user {1}", numberWears, agentId);
}
+ if(reqStream != null)
+ reqStream.Dispose();
}, null, "XBakesModule.Store"
);
}
diff --git a/OpenSim/Region/CoreModules/Avatar/Friends/FriendsModule.cs b/OpenSim/Region/CoreModules/Avatar/Friends/FriendsModule.cs
index 35b48d9924..772485cfeb 100644
--- a/OpenSim/Region/CoreModules/Avatar/Friends/FriendsModule.cs
+++ b/OpenSim/Region/CoreModules/Avatar/Friends/FriendsModule.cs
@@ -247,11 +247,10 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends
{
FriendInfo[] friends = GetFriendsFromCache(principalID);
FriendInfo finfo = GetFriend(friends, friendID);
- if (finfo != null)
+ if (finfo != null && finfo.TheirFlags != -1)
{
return finfo.TheirFlags;
}
-
return 0;
}
@@ -512,18 +511,20 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends
if (((fi.MyFlags & (int)FriendRights.CanSeeOnline) != 0) && (fi.TheirFlags != -1))
friendList.Add(fi);
}
+ if(friendList.Count > 0)
+ {
+ Util.FireAndForget(
+ delegate
+ {
+// m_log.DebugFormat(
+// "[FRIENDS MODULE]: Notifying {0} friends of {1} of online status {2}",
+// friendList.Count, agentID, online);
- Util.FireAndForget(
- delegate
- {
-// m_log.DebugFormat(
-// "[FRIENDS MODULE]: Notifying {0} friends of {1} of online status {2}",
-// friendList.Count, agentID, online);
-
- // Notify about this user status
- StatusNotify(friendList, agentID, online);
- }, null, "FriendsModule.StatusChange"
- );
+ // Notify about this user status
+ StatusNotify(friendList, agentID, online);
+ }, null, "FriendsModule.StatusChange"
+ );
+ }
}
}
@@ -552,6 +553,8 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends
// We do this regrouping so that we can efficiently send a single request rather than one for each
// friend in what may be a very large friends list.
PresenceInfo[] friendSessions = PresenceService.GetAgents(remoteFriendStringIds.ToArray());
+ if(friendSessions == null)
+ return;
foreach (PresenceInfo friendSession in friendSessions)
{
@@ -752,7 +755,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends
if (friend == null)
return;
- if((friend.TheirFlags & (int)FriendRights.CanSeeOnMap) == 0)
+ if(friend.TheirFlags == -1 || (friend.TheirFlags & (int)FriendRights.CanSeeOnMap) == 0)
return;
Scene hunterScene = (Scene)remoteClient.Scene;
diff --git a/OpenSim/Region/CoreModules/Avatar/Friends/FriendsRequestHandler.cs b/OpenSim/Region/CoreModules/Avatar/Friends/FriendsRequestHandler.cs
index 81aa8829a4..091b1975e4 100644
--- a/OpenSim/Region/CoreModules/Avatar/Friends/FriendsRequestHandler.cs
+++ b/OpenSim/Region/CoreModules/Avatar/Friends/FriendsRequestHandler.cs
@@ -65,9 +65,10 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends
protected override byte[] ProcessRequest(
string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
- StreamReader sr = new StreamReader(requestData);
- string body = sr.ReadToEnd();
- sr.Close();
+ string body;
+ using(StreamReader sr = new StreamReader(requestData))
+ body = sr.ReadToEnd();
+
body = body.Trim();
//m_log.DebugFormat("[XXX]: query String: {0}", body);
diff --git a/OpenSim/Region/CoreModules/Avatar/Friends/HGFriendsModule.cs b/OpenSim/Region/CoreModules/Avatar/Friends/HGFriendsModule.cs
index 82154bcc9e..fae1e05349 100644
--- a/OpenSim/Region/CoreModules/Avatar/Friends/HGFriendsModule.cs
+++ b/OpenSim/Region/CoreModules/Avatar/Friends/HGFriendsModule.cs
@@ -214,7 +214,9 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends
FriendInfo[] friends = GetFriendsFromCache(client.AgentId);
foreach (FriendInfo f in friends)
{
- client.SendChangeUserRights(new UUID(f.Friend), client.AgentId, f.TheirFlags);
+ int rights = f.TheirFlags;
+ if(rights != -1 )
+ client.SendChangeUserRights(new UUID(f.Friend), client.AgentId, rights);
}
}
}
diff --git a/OpenSim/Region/CoreModules/Avatar/Gods/GodsModule.cs b/OpenSim/Region/CoreModules/Avatar/Gods/GodsModule.cs
index f699c0c889..6e6974a5c8 100644
--- a/OpenSim/Region/CoreModules/Avatar/Gods/GodsModule.cs
+++ b/OpenSim/Region/CoreModules/Avatar/Gods/GodsModule.cs
@@ -59,21 +59,11 @@ namespace OpenSim.Region.CoreModules.Avatar.Gods
/// Special UUID for actions that apply to all agents
private static readonly UUID ALL_AGENTS = new UUID("44e87126-e794-4ded-05b3-7c42da3d5cdb");
+ private static readonly UUID UUID_GRID_GOD = new UUID("6571e388-6218-4574-87db-f9379718315e");
protected Scene m_scene;
protected IDialogModule m_dialogModule;
- protected IDialogModule DialogModule
- {
- get
- {
- if (m_dialogModule == null)
- m_dialogModule = m_scene.RequestModuleInterface();
-
- return m_dialogModule;
- }
- }
-
public void Initialise(IConfigSource source)
{
}
@@ -97,6 +87,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Gods
public void RegionLoaded(Scene scene)
{
+ m_dialogModule = m_scene.RequestModuleInterface();
}
public void Close() {}
@@ -152,7 +143,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Gods
if (god == null || god.ControllingClient.SessionId != godSessionID)
return String.Empty;
- KickUser(godID, agentID, kickFlags, Util.StringToBytes1024(reason));
+ KickUser(godID, agentID, kickFlags, reason);
}
else
{
@@ -173,8 +164,13 @@ namespace OpenSim.Region.CoreModules.Avatar.Gods
sp.GrantGodlikePowers(token, godLike);
- if (godLike && !sp.IsViewerUIGod && DialogModule != null)
- DialogModule.SendAlertToUser(agentID, "Request for god powers denied");
+ if (godLike && !sp.IsViewerUIGod && m_dialogModule != null)
+ m_dialogModule.SendAlertToUser(agentID, "Request for god powers denied");
+ }
+
+ public void KickUser(UUID godID, UUID agentID, uint kickflags, byte[] reason)
+ {
+ KickUser(godID, agentID, kickflags, Utils.BytesToString(reason));
}
///
@@ -184,7 +180,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Gods
/// the person that is being kicked
/// Tells what to do to the user
/// The message to send to the user after it's been turned into a field
- public void KickUser(UUID godID, UUID agentID, uint kickflags, byte[] reason)
+ public void KickUser(UUID godID, UUID agentID, uint kickflags, string reason)
{
// assuming automatic god rights on this for fast griefing reaction
// this is also needed for kick via message
@@ -200,10 +196,15 @@ namespace OpenSim.Region.CoreModules.Avatar.Gods
if(agentID == ALL_AGENTS)
{
m_scene.ForEachRootScenePresence(delegate(ScenePresence p)
+ {
+ if (p.UUID != godID)
{
- if (p.UUID != godID && godlevel > p.GodController.GodLevel)
+ if(godlevel > p.GodController.GodLevel)
doKickmodes(godID, p, kickflags, reason);
- });
+ else if(m_dialogModule != null)
+ m_dialogModule.SendAlertToUser(p.UUID, "Kick from " + godID.ToString() + " ignored, kick reason: " + reason);
+ }
+ });
return;
}
@@ -217,7 +218,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Gods
m_log.DebugFormat("[GODS]: Sending nonlocal kill for agent {0}", agentID);
transferModule.SendInstantMessage(new GridInstantMessage(
m_scene, godID, "God", agentID, (byte)250, false,
- Utils.BytesToString(reason), UUID.Zero, true,
+ reason, UUID.Zero, true,
new Vector3(), new byte[] {(byte)kickflags}, true),
delegate(bool success) {} );
}
@@ -225,7 +226,11 @@ namespace OpenSim.Region.CoreModules.Avatar.Gods
}
if (godlevel <= sp.GodController.GodLevel) // no god wars
+ {
+ if(m_dialogModule != null)
+ m_dialogModule.SendAlertToUser(sp.UUID, "Kick from " + godID.ToString() + " ignored, kick reason: " + reason);
return;
+ }
if(sp.UUID == godID)
return;
@@ -233,29 +238,34 @@ namespace OpenSim.Region.CoreModules.Avatar.Gods
doKickmodes(godID, sp, kickflags, reason);
}
- private void doKickmodes(UUID godID, ScenePresence sp, uint kickflags, byte[] reason)
+ private void doKickmodes(UUID godID, ScenePresence sp, uint kickflags, string reason)
{
switch (kickflags)
{
case 0:
- KickPresence(sp, Utils.BytesToString(reason));
+ KickPresence(sp, reason);
break;
case 1:
sp.AllowMovement = false;
- m_dialogModule.SendAlertToUser(sp.UUID, Utils.BytesToString(reason));
- m_dialogModule.SendAlertToUser(godID, "User Frozen");
+ if(m_dialogModule != null)
+ {
+ m_dialogModule.SendAlertToUser(sp.UUID, reason);
+ m_dialogModule.SendAlertToUser(godID, "User Frozen");
+ }
break;
case 2:
sp.AllowMovement = true;
- m_dialogModule.SendAlertToUser(sp.UUID, Utils.BytesToString(reason));
- m_dialogModule.SendAlertToUser(godID, "User Unfrozen");
+ if(m_dialogModule != null)
+ {
+ m_dialogModule.SendAlertToUser(sp.UUID, reason);
+ m_dialogModule.SendAlertToUser(godID, "User Unfrozen");
+ }
break;
default:
break;
}
}
-
private void KickPresence(ScenePresence sp, string reason)
{
if(sp.IsDeleted || sp.IsChildAgent)
@@ -264,6 +274,41 @@ namespace OpenSim.Region.CoreModules.Avatar.Gods
sp.Scene.CloseAgent(sp.UUID, true);
}
+ public void GridKickUser(UUID agentID, string reason)
+ {
+ int godlevel = 240; // grid god default
+
+ ScenePresence sp = m_scene.GetScenePresence(agentID);
+ if (sp == null || sp.IsChildAgent)
+ {
+ IMessageTransferModule transferModule =
+ m_scene.RequestModuleInterface();
+ if (transferModule != null)
+ {
+ m_log.DebugFormat("[GODS]: Sending nonlocal kill for agent {0}", agentID);
+ transferModule.SendInstantMessage(new GridInstantMessage(
+ m_scene, UUID_GRID_GOD, "GRID", agentID, (byte)250, false,
+ reason, UUID.Zero, true,
+ new Vector3(), new byte[] {0}, true),
+ delegate(bool success) {} );
+ }
+ return;
+ }
+
+ if(sp.IsDeleted)
+ return;
+
+ if (godlevel <= sp.GodController.GodLevel) // no god wars
+ {
+ if(m_dialogModule != null)
+ m_dialogModule.SendAlertToUser(sp.UUID, "GRID kick detected and ignored, kick reason: " + reason);
+ return;
+ }
+
+ sp.ControllingClient.Kick(reason);
+ sp.Scene.CloseAgent(sp.UUID, true);
+ }
+
private void OnIncomingInstantMessage(GridInstantMessage msg)
{
if (msg.dialog == (uint)250) // Nonlocal kick
@@ -273,7 +318,10 @@ namespace OpenSim.Region.CoreModules.Avatar.Gods
UUID godID = new UUID(msg.fromAgentID);
uint kickMode = (uint)msg.binaryBucket[0];
- KickUser(godID, agentID, kickMode, Util.StringToBytes1024(reason));
+ if(godID == UUID_GRID_GOD)
+ GridKickUser(agentID, reason);
+ else
+ KickUser(godID, agentID, kickMode, reason);
}
}
}
diff --git a/OpenSim/Region/CoreModules/Avatar/InstantMessage/OfflineMessageModule.cs b/OpenSim/Region/CoreModules/Avatar/InstantMessage/OfflineMessageModule.cs
index d1f6054106..315ce1b072 100644
--- a/OpenSim/Region/CoreModules/Avatar/InstantMessage/OfflineMessageModule.cs
+++ b/OpenSim/Region/CoreModules/Avatar/InstantMessage/OfflineMessageModule.cs
@@ -52,6 +52,7 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool enabled = true;
+ private bool m_UseNewAvnCode = false;
private List m_SceneList = new List();
private string m_RestURL = String.Empty;
IMessageTransferModule m_TransferModule = null;
@@ -82,6 +83,7 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
}
m_ForwardOfflineGroupMessages = cnf.GetBoolean("ForwardOfflineGroupMessages", m_ForwardOfflineGroupMessages);
+ m_UseNewAvnCode = cnf.GetBoolean("UseNewAvnCode", m_UseNewAvnCode);
}
public void AddRegion(Scene scene)
@@ -244,68 +246,73 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
return;
}
- Scene scene = FindScene(new UUID(im.fromAgentID));
- if (scene == null)
- scene = m_SceneList[0];
-
-// Avination new code
-// SendReply reply = SynchronousRestObjectRequester.MakeRequest(
-// "POST", m_RestURL+"/SaveMessage/?scope=" +
-// scene.RegionInfo.ScopeID.ToString(), im);
-
-// current opensim and osgrid compatible
- bool success = SynchronousRestObjectRequester.MakeRequest(
- "POST", m_RestURL+"/SaveMessage/", im, 10000);
-// current opensim and osgrid compatible end
-
- if (im.dialog == (byte)InstantMessageDialog.MessageFromAgent)
+ if(m_UseNewAvnCode)
{
- IClientAPI client = FindClient(new UUID(im.fromAgentID));
- if (client == null)
- return;
-/* Avination new code
- if (reply.Message == String.Empty)
- reply.Message = "User is not logged in. " + (reply.Success ? "Message saved." : "Message not saved");
+ Scene scene = FindScene(new UUID(im.fromAgentID));
+ if (scene == null)
+ scene = m_SceneList[0];
- bool sendReply = true;
+ UUID scopeID = scene.RegionInfo.ScopeID;
+ SendReply reply = SynchronousRestObjectRequester.MakeRequest(
+ "POST", m_RestURL+"/SaveMessage/?scope=" + scopeID.ToString(), im, 20000);
- switch (reply.Disposition)
+ if (im.dialog == (byte)InstantMessageDialog.MessageFromAgent)
{
- case 0: // Normal
- break;
- case 1: // Only once per user
- if (m_repliesSent.ContainsKey(client) && m_repliesSent[client].Contains(new UUID(im.toAgentID)))
+ IClientAPI client = FindClient(new UUID(im.fromAgentID));
+ if (client == null)
+ return;
+
+ if (string.IsNullOrEmpty(reply.Message))
+ reply.Message = "User is not logged in. " + (reply.Success ? "Message saved." : "Message not saved");
+
+ bool sendReply = true;
+
+ switch (reply.Disposition)
{
- sendReply = false;
+ case 0: // Normal
+ break;
+ case 1: // Only once per user
+ if (m_repliesSent.ContainsKey(client) && m_repliesSent[client].Contains(new UUID(im.toAgentID)))
+ sendReply = false;
+ else
+ {
+ if (!m_repliesSent.ContainsKey(client))
+ m_repliesSent[client] = new List();
+ m_repliesSent[client].Add(new UUID(im.toAgentID));
+ }
+ break;
}
- else
+
+ if (sendReply)
{
- if (!m_repliesSent.ContainsKey(client))
- m_repliesSent[client] = new List();
- m_repliesSent[client].Add(new UUID(im.toAgentID));
+ client.SendInstantMessage(new GridInstantMessage(
+ null, new UUID(im.toAgentID),
+ "System", new UUID(im.fromAgentID),
+ (byte)InstantMessageDialog.MessageFromAgent,
+ reply.Message,
+ false, new Vector3()));
}
- break;
}
+ }
+ else
+ {
+ bool success = SynchronousRestObjectRequester.MakeRequest(
+ "POST", m_RestURL+"/SaveMessage/", im, 20000);
- if (sendReply)
+ if (im.dialog == (byte)InstantMessageDialog.MessageFromAgent)
{
+ IClientAPI client = FindClient(new UUID(im.fromAgentID));
+ if (client == null)
+ return;
+
client.SendInstantMessage(new GridInstantMessage(
- null, new UUID(im.toAgentID),
- "System", new UUID(im.fromAgentID),
- (byte)InstantMessageDialog.MessageFromAgent,
- reply.Message,
- false, new Vector3()));
- }
-*/
-// current opensim and osgrid compatible
- client.SendInstantMessage(new GridInstantMessage(
null, new UUID(im.toAgentID),
"System", new UUID(im.fromAgentID),
(byte)InstantMessageDialog.MessageFromAgent,
"User is not logged in. "+
(success ? "Message saved." : "Message not saved"),
false, new Vector3()));
-// current opensim and osgrid compatible end
+ }
}
}
}
diff --git a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveWriteRequest.cs b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveWriteRequest.cs
index f002ad7a40..ad46107768 100644
--- a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveWriteRequest.cs
+++ b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveWriteRequest.cs
@@ -218,10 +218,39 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
// Count inventory items (different to asset count)
CountItems++;
-
+
// Don't chase down link asset items as they actually point to their target item IDs rather than an asset
if (SaveAssets && itemAssetType != AssetType.Link && itemAssetType != AssetType.LinkFolder)
+ {
+ int curErrorCntr = m_assetGatherer.ErrorCount;
+ int possible = m_assetGatherer.possibleNotAssetCount;
m_assetGatherer.AddForInspection(inventoryItem.AssetID);
+ m_assetGatherer.GatherAll();
+ curErrorCntr = m_assetGatherer.ErrorCount - curErrorCntr;
+ possible = m_assetGatherer.possibleNotAssetCount - possible;
+
+ if(curErrorCntr > 0 || possible > 0)
+ {
+ string spath;
+ int indx = path.IndexOf("__");
+ if(indx > 0)
+ spath = path.Substring(0,indx);
+ else
+ spath = path;
+
+ if(curErrorCntr > 0)
+ {
+ m_log.ErrorFormat("[INVENTORY ARCHIVER Warning]: item {0} '{1}', type {2}, in '{3}', contains {4} references to missing or damaged assets",
+ inventoryItem.ID, inventoryItem.Name, itemAssetType.ToString(), spath, curErrorCntr);
+ if(possible > 0)
+ m_log.WarnFormat("[INVENTORY ARCHIVER Warning]: item also contains {0} references that may be to missing or damaged assets or not a problem", possible);
+ }
+ else if(possible > 0)
+ {
+ m_log.WarnFormat("[INVENTORY ARCHIVER Warning]: item {0} '{1}', type {2}, in '{3}', contains {4} references that may be to missing or damaged assets or not a problem", inventoryItem.ID, inventoryItem.Name, itemAssetType.ToString(), spath, possible);
+ }
+ }
+ }
}
///
@@ -381,6 +410,8 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
string errorMessage = string.Format("Aborted save. Could not find inventory path {0}", m_invPath);
Exception e = new InventoryArchiverException(errorMessage);
m_module.TriggerInventoryArchiveSaved(m_id, false, m_userInfo, m_invPath, m_saveStream, e, 0, 0);
+ if(m_saveStream != null && m_saveStream.CanWrite)
+ m_saveStream.Close();
throw e;
}
@@ -420,17 +451,20 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
{
m_assetGatherer.GatherAll();
- m_log.DebugFormat(
- "[INVENTORY ARCHIVER]: Saving {0} assets for items", m_assetGatherer.GatheredUuids.Count);
+ int errors = m_assetGatherer.FailedUUIDs.Count;
- AssetsRequest ar
- = new AssetsRequest(
+ m_log.DebugFormat(
+ "[INVENTORY ARCHIVER]: The items to save reference {0} possible assets", m_assetGatherer.GatheredUuids.Count + errors);
+ if(errors > 0)
+ m_log.DebugFormat("[INVENTORY ARCHIVER]: {0} of these have problems or are not assets and will be ignored", errors);
+
+ AssetsRequest ar = new AssetsRequest(
new AssetsArchiver(m_archiveWriter),
- m_assetGatherer.GatheredUuids, m_scene.AssetService,
+ m_assetGatherer.GatheredUuids, m_assetGatherer.FailedUUIDs.Count,
+ m_scene.AssetService,
m_scene.UserAccountService, m_scene.RegionInfo.ScopeID,
options, ReceivedAllAssets);
-
- WorkManager.RunInThread(o => ar.Execute(), null, string.Format("AssetsRequest ({0})", m_scene.Name));
+ ar.Execute();
}
else
{
diff --git a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiverModule.cs b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiverModule.cs
index be59eb5957..06aec7bca5 100644
--- a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiverModule.cs
+++ b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiverModule.cs
@@ -218,7 +218,8 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
// {
try
{
- new InventoryArchiveWriteRequest(id, this, m_aScene, userInfo, invPath, saveStream).Execute(options, UserAccountService);
+ InventoryArchiveWriteRequest iarReq = new InventoryArchiveWriteRequest(id, this, m_aScene, userInfo, invPath, saveStream);
+ iarReq.Execute(options, UserAccountService);
}
catch (EntryPointNotFoundException e)
{
@@ -261,7 +262,8 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
// {
try
{
- new InventoryArchiveWriteRequest(id, this, m_aScene, userInfo, invPath, savePath).Execute(options, UserAccountService);
+ InventoryArchiveWriteRequest iarReq = new InventoryArchiveWriteRequest(id, this, m_aScene, userInfo, invPath, savePath);
+ iarReq.Execute(options, UserAccountService);
}
catch (EntryPointNotFoundException e)
{
diff --git a/OpenSim/Region/CoreModules/Avatar/UserProfiles/UserProfileModule.cs b/OpenSim/Region/CoreModules/Avatar/UserProfiles/UserProfileModule.cs
index bc8aeca002..e02ca497ed 100644
--- a/OpenSim/Region/CoreModules/Avatar/UserProfiles/UserProfileModule.cs
+++ b/OpenSim/Region/CoreModules/Avatar/UserProfiles/UserProfileModule.cs
@@ -149,7 +149,7 @@ namespace OpenSim.Region.CoreModules.Avatar.UserProfiles
if (profileConfig == null)
{
- m_log.Debug("[PROFILES]: UserProfiles disabled, no configuration");
+ //m_log.Debug("[PROFILES]: UserProfiles disabled, no configuration");
Enabled = false;
return;
}
@@ -1839,12 +1839,12 @@ namespace OpenSim.Region.CoreModules.Avatar.UserProfiles
webRequest.ContentType = "application/json-rpc";
webRequest.Method = "POST";
- using(Stream dataStream = webRequest.GetRequestStream())
- dataStream.Write(content,0,content.Length);
-
WebResponse webResponse = null;
try
{
+ using(Stream dataStream = webRequest.GetRequestStream())
+ dataStream.Write(content,0,content.Length);
+
webResponse = webRequest.GetResponse();
}
catch (WebException e)
@@ -1920,12 +1920,12 @@ namespace OpenSim.Region.CoreModules.Avatar.UserProfiles
webRequest.ContentType = "application/json-rpc";
webRequest.Method = "POST";
- using(Stream dataStream = webRequest.GetRequestStream())
- dataStream.Write(content,0,content.Length);
-
WebResponse webResponse = null;
try
{
+ using(Stream dataStream = webRequest.GetRequestStream())
+ dataStream.Write(content,0,content.Length);
+
webResponse = webRequest.GetResponse();
}
catch (WebException e)
diff --git a/OpenSim/Region/CoreModules/Framework/Caps/CapabilitiesModule.cs b/OpenSim/Region/CoreModules/Framework/Caps/CapabilitiesModule.cs
index 292099d864..c0afe7c49d 100644
--- a/OpenSim/Region/CoreModules/Framework/Caps/CapabilitiesModule.cs
+++ b/OpenSim/Region/CoreModules/Framework/Caps/CapabilitiesModule.cs
@@ -142,9 +142,9 @@ namespace OpenSim.Region.CoreModules.Framework
if (capsObjectPath == oldCaps.CapsObjectPath)
{
- m_log.WarnFormat(
- "[CAPS]: Reusing caps for agent {0} in region {1}. Old caps path {2}, new caps path {3}. ",
- agentId, m_scene.RegionInfo.RegionName, oldCaps.CapsObjectPath, capsObjectPath);
+// m_log.WarnFormat(
+// "[CAPS]: Reusing caps for agent {0} in region {1}. Old caps path {2}, new caps path {3}. ",
+// agentId, m_scene.RegionInfo.RegionName, oldCaps.CapsObjectPath, capsObjectPath);
return;
}
else
diff --git a/OpenSim/Region/CoreModules/Framework/EntityTransfer/EntityTransferModule.cs b/OpenSim/Region/CoreModules/Framework/EntityTransfer/EntityTransferModule.cs
index 6dc982be3c..c93c54d5cf 100644
--- a/OpenSim/Region/CoreModules/Framework/EntityTransfer/EntityTransferModule.cs
+++ b/OpenSim/Region/CoreModules/Framework/EntityTransfer/EntityTransferModule.cs
@@ -157,7 +157,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
m_idCache = new ExpiringCache();
m_bannedRegions.Add(pAgentID, m_idCache, TimeSpan.FromSeconds(newTime));
}
- m_idCache.Add(pRegionHandle, DateTime.UtcNow + TimeSpan.FromSeconds(extendTime), TimeSpan.FromSeconds(extendTime));
+ m_idCache.Add(pRegionHandle, DateTime.UtcNow + TimeSpan.FromSeconds(extendTime), extendTime);
}
// Remove the agent from the region's banned list
@@ -417,12 +417,13 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
}
catch (Exception e)
{
+
m_log.ErrorFormat(
"[ENTITY TRANSFER MODULE]: Exception on teleport of {0} from {1}@{2} to {3}@{4}: {5}{6}",
sp.Name, sp.AbsolutePosition, sp.Scene.RegionInfo.RegionName, position, destinationRegionName,
e.Message, e.StackTrace);
-
- sp.ControllingClient.SendTeleportFailed("Internal error");
+ if(sp != null && sp.ControllingClient != null && !sp.IsDeleted)
+ sp.ControllingClient.SendTeleportFailed("Internal error");
}
finally
{
@@ -527,15 +528,15 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
{
string homeURI = Scene.GetAgentHomeURI(sp.ControllingClient.AgentId);
- string message;
- finalDestination = GetFinalDestination(reg, sp.ControllingClient.AgentId, homeURI, out message);
+ string reason = String.Empty;
+ finalDestination = GetFinalDestination(reg, sp.ControllingClient.AgentId, homeURI, out reason);
if (finalDestination == null)
{
m_log.WarnFormat( "{0} Final destination is having problems. Unable to teleport {1} {2}: {3}",
- LogHeader, sp.Name, sp.UUID, message);
+ LogHeader, sp.Name, sp.UUID, reason);
- sp.ControllingClient.SendTeleportFailed(message);
+ sp.ControllingClient.SendTeleportFailed(reason);
return;
}
@@ -548,17 +549,12 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
return;
}
- // Validate assorted conditions
- string reason = string.Empty;
if (!ValidateGenericConditions(sp, reg, finalDestination, teleportFlags, out reason))
{
sp.ControllingClient.SendTeleportFailed(reason);
return;
}
- if (message != null)
- sp.ControllingClient.SendAgentAlertMessage(message, true);
-
//
// This is it
//
@@ -735,8 +731,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
IPEndPoint endPoint = finalDestination.ExternalEndPoint;
if (endPoint == null || endPoint.Address == null)
{
- sp.ControllingClient.SendTeleportFailed("Remote Region appears to be down");
-
+ sp.ControllingClient.SendTeleportFailed("Could not resolve destination Address");
return;
}
@@ -776,30 +771,22 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
else if (sp.Flying)
teleportFlags |= (uint)TeleportFlags.IsFlying;
+ sp.IsInLocalTransit = finalDestination.RegionLocY != 0; // HG
sp.IsInTransit = true;
+
if (DisableInterRegionTeleportCancellation)
teleportFlags |= (uint)TeleportFlags.DisableCancel;
// At least on LL 3.3.4, this is not strictly necessary - a teleport will succeed without sending this to
// the viewer. However, it might mean that the viewer does not see the black teleport screen (untested).
sp.ControllingClient.SendTeleportStart(teleportFlags);
-
- // the avatar.Close below will clear the child region list. We need this below for (possibly)
- // closing the child agents, so save it here (we need a copy as it is Clear()-ed).
- //List childRegions = avatar.KnownRegionHandles;
- // Compared to ScenePresence.CrossToNewRegion(), there's no obvious code to handle a teleport
- // failure at this point (unlike a border crossing failure). So perhaps this can never fail
- // once we reach here...
- //avatar.Scene.RemoveCapsHandler(avatar.UUID);
-
+
AgentCircuitData currentAgentCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
AgentCircuitData agentCircuit = sp.ControllingClient.RequestClientInfo();
agentCircuit.startpos = position;
agentCircuit.child = true;
-// agentCircuit.Appearance = sp.Appearance;
-// agentCircuit.Appearance = new AvatarAppearance(sp.Appearance, true, false);
agentCircuit.Appearance = new AvatarAppearance();
agentCircuit.Appearance.AvatarHeight = sp.Appearance.AvatarHeight;
@@ -813,8 +800,6 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
agentCircuit.Id0 = currentAgentCircuit.Id0;
}
- IClientIPEndpoint ipepClient;
-
uint newRegionX, newRegionY, oldRegionX, oldRegionY;
Util.RegionHandleToRegionLoc(destinationHandle, out newRegionX, out newRegionY);
Util.RegionHandleToRegionLoc(sourceRegion.RegionHandle, out oldRegionX, out oldRegionY);
@@ -833,13 +818,6 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
finalDestination.RegionName, newRegionX, newRegionY,newSizeX, newSizeY, sp.Name, Scene.Name);
//sp.ControllingClient.SendTeleportProgress(teleportFlags, "Creating agent...");
- #region IP Translation for NAT
- // Uses ipepClient above
- if (sp.ClientView.TryGet(out ipepClient))
- {
- endPoint.Address = NetworkUtil.GetIPFor(ipepClient.EndPoint, endPoint.Address);
- }
- #endregion
agentCircuit.CapsPath = CapsUtil.GetRandomCapsObjectPath();
}
else
@@ -867,6 +845,14 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
sp.Name, Scene.Name, finalDestination.RegionName);
string capsPath = finalDestination.ServerURI + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
+ List childRegionsToClose = sp.GetChildAgentsToClose(destinationHandle, finalDestination.RegionSizeX, finalDestination.RegionSizeY);
+ if(agentCircuit.ChildrenCapSeeds != null)
+ {
+ foreach(ulong handler in childRegionsToClose)
+ {
+ agentCircuit.ChildrenCapSeeds.Remove(handler);
+ }
+ }
// Let's create an agent there if one doesn't exist yet.
// NOTE: logout will always be false for a non-HG teleport.
@@ -952,7 +938,6 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
agent.Position = agentCircuit.startpos;
SetCallbackURL(agent, sp.Scene.RegionInfo);
-
// We will check for an abort before UpdateAgent since UpdateAgent will require an active viewer to
// establish th econnection to the destination which makes it return true.
if (m_entityTransferStateMachine.GetAgentTransferState(sp.UUID) == AgentTransferState.Aborting)
@@ -1051,7 +1036,6 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
return;
}
-
/*
// TODO: This may be 0.6. Check if still needed
// For backwards compatibility
@@ -1065,7 +1049,10 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
m_entityTransferStateMachine.UpdateInTransit(sp.UUID, AgentTransferState.CleaningUp);
- sp.CloseChildAgents(logout, destinationHandle, finalDestination.RegionSizeX, finalDestination.RegionSizeY);
+ if(logout)
+ sp.closeAllChildAgents();
+ else
+ sp.CloseChildAgents(childRegionsToClose);
// call HG hook
AgentHasMovedAway(sp, logout);
@@ -1091,9 +1078,6 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
// This sleep can be increased if necessary. However, whilst it's active,
// an agent cannot teleport back to this region if it has teleported away.
Thread.Sleep(2000);
-// if (m_eqModule != null && !sp.DoNotCloseAfterTeleport)
-// m_eqModule.DisableSimulator(sourceRegionHandle,sp.UUID);
- Thread.Sleep(500);
sp.Scene.CloseAgent(sp.UUID, false);
}
sp.IsInTransit = false;
@@ -1103,7 +1087,16 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
IPEndPoint endPoint, uint teleportFlags, bool OutSideViewRange, EntityTransferContext ctx, out string reason)
{
ulong destinationHandle = finalDestination.RegionHandle;
- AgentCircuitData currentAgentCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
+
+ List childRegionsToClose = sp.GetChildAgentsToClose(destinationHandle, finalDestination.RegionSizeX, finalDestination.RegionSizeY);
+
+ if(agentCircuit.ChildrenCapSeeds != null)
+ {
+ foreach(ulong handler in childRegionsToClose)
+ {
+ agentCircuit.ChildrenCapSeeds.Remove(handler);
+ }
+ }
string capsPath = finalDestination.ServerURI + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);;
@@ -1203,20 +1196,17 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
"[ENTITY TRANSFER MODULE]: UpdateAgent failed on teleport of {0} to {1}. Keeping avatar in {2}",
sp.Name, finalDestination.RegionName, sp.Scene.Name);
- Fail(sp, finalDestination, logout, currentAgentCircuit.SessionID.ToString(), "Connection between viewer and destination region could not be established.");
+ Fail(sp, finalDestination, logout, agentCircuit.SessionID.ToString(), "Connection between viewer and destination region could not be established.");
sp.IsInTransit = false;
return;
}
m_entityTransferStateMachine.UpdateInTransit(sp.UUID, AgentTransferState.CleaningUp);
- // Need to signal neighbours whether child agents may need closing irrespective of whether this
- // one needed closing. We also need to close child agents as quickly as possible to avoid complicated
- // race conditions with rapid agent releporting (e.g. from A1 to a non-neighbour B, back
- // to a neighbour A2 then off to a non-neighbour C). Closing child agents any later requires complex
- // distributed checks to avoid problems in rapid reteleporting scenarios and where child agents are
- // abandoned without proper close by viewer but then re-used by an incoming connection.
- sp.CloseChildAgents(logout, destinationHandle, finalDestination.RegionSizeX, finalDestination.RegionSizeY);
+ if(logout)
+ sp.closeAllChildAgents();
+ else
+ sp.CloseChildAgents(childRegionsToClose);
sp.HasMovedAway(!(OutSideViewRange || logout));
@@ -1243,9 +1233,6 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
// IN THE AVIE BEING PLACED IN INFINITY FOR A COUPLE OF SECONDS.
Thread.Sleep(15000);
-// if (m_eqModule != null && !sp.DoNotCloseAfterTeleport)
-// m_eqModule.DisableSimulator(sourceRegionHandle,sp.UUID);
-// Thread.Sleep(1000);
// OK, it got this agent. Let's close everything
// If we shouldn't close the agent due to some other region renewing the connection
@@ -1255,13 +1242,6 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
sp.Scene.CloseAgent(sp.UUID, false);
}
-/*
- else
- {
- // now we have a child agent in this region.
- sp.Reset();
- }
- */
sp.IsInTransit = false;
}
@@ -1513,11 +1493,11 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
Math.Max(scene.RegionInfo.RegionSizeX, scene.RegionInfo.RegionSizeY));
if (neighbourRegion == null)
- {
return null;
- }
+
if (m_bannedRegionCache.IfBanned(neighbourRegion.RegionHandle, agentID))
{
+ failureReason = "Access Denied or Temporary not possible";
return null;
}
@@ -1529,13 +1509,15 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
pos.Z);
string homeURI = scene.GetAgentHomeURI(agentID);
-
+
if (!scene.SimulationService.QueryAccess(
neighbourRegion, agentID, homeURI, false, newpos,
scene.GetFormatsOffered(), ctx, out failureReason))
{
// remember the fail
m_bannedRegionCache.Add(neighbourRegion.RegionHandle, agentID);
+ if(String.IsNullOrWhiteSpace(failureReason))
+ failureReason = "Access Denied";
return null;
}
@@ -1544,6 +1526,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
public bool Cross(ScenePresence agent, bool isFlying)
{
+ agent.IsInLocalTransit = true;
agent.IsInTransit = true;
CrossAsyncDelegate d = CrossAsync;
d.BeginInvoke(agent, isFlying, CrossCompleted, d);
@@ -1555,13 +1538,15 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
CrossAsyncDelegate icon = (CrossAsyncDelegate)iar.AsyncState;
ScenePresence agent = icon.EndInvoke(iar);
- m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Crossing agent {0} {1} completed.", agent.Firstname, agent.Lastname);
if(!agent.IsChildAgent)
{
// crossing failed
agent.CrossToNewRegionFail();
}
+ else
+ m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Crossing agent {0} {1} completed.", agent.Firstname, agent.Lastname);
+
agent.IsInTransit = false;
}
@@ -1662,7 +1647,73 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
icon.EndInvoke(iar);
}
+ public bool CrossAgentCreateFarChild(ScenePresence agent, GridRegion neighbourRegion, Vector3 pos, EntityTransferContext ctx)
+ {
+ ulong regionhandler = neighbourRegion.RegionHandle;
+ if(agent.knowsNeighbourRegion(regionhandler))
+ return true;
+
+ string reason;
+ ulong currentRegionHandler = agent.Scene.RegionInfo.RegionHandle;
+ GridRegion source = new GridRegion(agent.Scene.RegionInfo);
+
+ AgentCircuitData currentAgentCircuit =
+ agent.Scene.AuthenticateHandler.GetAgentCircuitData(agent.ControllingClient.CircuitCode);
+ AgentCircuitData agentCircuit = agent.ControllingClient.RequestClientInfo();
+ agentCircuit.startpos = pos;
+ agentCircuit.child = true;
+
+ agentCircuit.Appearance = new AvatarAppearance();
+ agentCircuit.Appearance.AvatarHeight = agent.Appearance.AvatarHeight;
+
+ if (currentAgentCircuit != null)
+ {
+ agentCircuit.ServiceURLs = currentAgentCircuit.ServiceURLs;
+ agentCircuit.IPAddress = currentAgentCircuit.IPAddress;
+ agentCircuit.Viewer = currentAgentCircuit.Viewer;
+ agentCircuit.Channel = currentAgentCircuit.Channel;
+ agentCircuit.Mac = currentAgentCircuit.Mac;
+ agentCircuit.Id0 = currentAgentCircuit.Id0;
+ }
+
+ agentCircuit.CapsPath = CapsUtil.GetRandomCapsObjectPath();
+ agent.AddNeighbourRegion(neighbourRegion, agentCircuit.CapsPath);
+
+ IPEndPoint endPoint = neighbourRegion.ExternalEndPoint;
+ if(endPoint == null)
+ {
+ m_log.DebugFormat("CrossAgentCreateFarChild failed to resolve neighbour address {0}", neighbourRegion.ExternalHostName);
+ return false;
+ }
+ if (!Scene.SimulationService.CreateAgent(source, neighbourRegion, agentCircuit, (int)TeleportFlags.Default, ctx, out reason))
+ {
+ agent.RemoveNeighbourRegion(regionhandler);
+ return false;
+ }
+
+ string capsPath = neighbourRegion.ServerURI + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
+ int newSizeX = neighbourRegion.RegionSizeX;
+ int newSizeY = neighbourRegion.RegionSizeY;
+
+ if (m_eqModule != null)
+ {
+ m_log.DebugFormat("{0} {1} is sending {2} EnableSimulator for neighbour region {3}(loc=<{4},{5}>,siz=<{6},{7}>) " +
+ "and EstablishAgentCommunication with seed cap {8}", LogHeader,
+ source.RegionName, agent.Name,
+ neighbourRegion.RegionName, neighbourRegion.RegionLocX, neighbourRegion.RegionLocY, newSizeX, newSizeY , capsPath);
+
+ m_eqModule.EnableSimulator(regionhandler,
+ endPoint, agent.UUID, newSizeX, newSizeY);
+ m_eqModule.EstablishAgentCommunication(agent.UUID, endPoint, capsPath,
+ regionhandler, newSizeX, newSizeY);
+ }
+ else
+ {
+ agent.ControllingClient.InformClientOfNeighbour(regionhandler, endPoint);
+ }
+ return true;
+ }
///
/// This Closes child agents on neighbouring regions
@@ -1683,39 +1734,51 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
return agent;
}
- m_entityTransferStateMachine.SetInTransit(agent.UUID);
- agent.RemoveFromPhysicalScene();
-
- if (!CrossAgentIntoNewRegionMain(agent, pos, neighbourRegion, isFlying, ctx))
+ IPEndPoint endpoint = neighbourRegion.ExternalEndPoint;
+ if(endpoint == null)
{
- m_log.DebugFormat("{0}: CrossAgentToNewRegionAsync: cross main failed. Resetting transfer state", LogHeader);
- m_entityTransferStateMachine.ResetFromTransit(agent.UUID);
+ m_log.DebugFormat("{0}: CrossAgentToNewRegionAsync: failed to resolve neighbour address {0} ",neighbourRegion.ExternalHostName);
return agent;
}
- CrossAgentToNewRegionPost(agent, pos, neighbourRegion, isFlying, ctx);
+ m_entityTransferStateMachine.SetInTransit(agent.UUID);
+ agent.RemoveFromPhysicalScene();
+
+ if (!CrossAgentIntoNewRegionMain(agent, pos, neighbourRegion, endpoint, isFlying, ctx))
+ {
+ m_log.DebugFormat("{0}: CrossAgentToNewRegionAsync: cross main failed. Resetting transfer state", LogHeader);
+ m_entityTransferStateMachine.ResetFromTransit(agent.UUID);
+ }
}
catch (Exception e)
{
m_log.Error(string.Format("{0}: CrossAgentToNewRegionAsync: failed with exception ", LogHeader), e);
}
-
return agent;
}
- public bool CrossAgentIntoNewRegionMain(ScenePresence agent, Vector3 pos, GridRegion neighbourRegion, bool isFlying, EntityTransferContext ctx)
+ public bool CrossAgentIntoNewRegionMain(ScenePresence agent, Vector3 pos, GridRegion neighbourRegion,
+ IPEndPoint endpoint, bool isFlying, EntityTransferContext ctx)
{
int ts = Util.EnvironmentTickCount();
+ bool sucess = true;
+ string reason = String.Empty;
+ List childRegionsToClose = null;
try
{
AgentData cAgent = new AgentData();
agent.CopyTo(cAgent,true);
-// agent.Appearance.WearableCacheItems = null;
-
cAgent.Position = pos;
cAgent.ChildrenCapSeeds = agent.KnownRegions;
+ childRegionsToClose = agent.GetChildAgentsToClose(neighbourRegion.RegionHandle, neighbourRegion.RegionSizeX, neighbourRegion.RegionSizeY);
+ if(cAgent.ChildrenCapSeeds != null)
+ {
+ foreach(ulong regh in childRegionsToClose)
+ cAgent.ChildrenCapSeeds.Remove(regh);
+ }
+
if (isFlying)
cAgent.ControlFlags |= (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY;
@@ -1725,24 +1788,31 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
// Beyond this point, extra cleanup is needed beyond removing transit state
m_entityTransferStateMachine.UpdateInTransit(agent.UUID, AgentTransferState.Transferring);
- if (!agent.Scene.SimulationService.UpdateAgent(neighbourRegion, cAgent, ctx))
+ if (sucess && !agent.Scene.SimulationService.UpdateAgent(neighbourRegion, cAgent, ctx))
+ {
+ sucess = false;
+ reason = "agent update failed";
+ }
+
+ if(!sucess)
{
// region doesn't take it
m_entityTransferStateMachine.UpdateInTransit(agent.UUID, AgentTransferState.CleaningUp);
m_log.WarnFormat(
- "[ENTITY TRANSFER MODULE]: Region {0} would not accept update for agent {1} on cross attempt. Returning to original region.",
- neighbourRegion.RegionName, agent.Name);
+ "[ENTITY TRANSFER MODULE]: agent {0} crossing to {1} failed: {2}",
+ agent.Name, neighbourRegion.RegionName, reason);
ReInstantiateScripts(agent);
if(agent.ParentID == 0 && agent.ParentUUID == UUID.Zero)
+ {
agent.AddToPhysicalScene(isFlying);
+ }
return false;
}
m_log.DebugFormat("[CrossAgentIntoNewRegionMain] ok, time {0}ms",Util.EnvironmentTickCountSubtract(ts));
-
}
catch (Exception e)
{
@@ -1754,19 +1824,12 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
return false;
}
- return true;
- }
-
- public void CrossAgentToNewRegionPost(ScenePresence agent, Vector3 pos, GridRegion neighbourRegion,
- bool isFlying, EntityTransferContext ctx)
- {
-
string agentcaps;
if (!agent.KnownRegions.TryGetValue(neighbourRegion.RegionHandle, out agentcaps))
{
m_log.ErrorFormat("[ENTITY TRANSFER MODULE]: No ENTITY TRANSFER MODULE information for region handle {0}, exiting CrossToNewRegion.",
neighbourRegion.RegionHandle);
- return;
+ return false;
}
// No turning back
@@ -1777,21 +1840,22 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Sending new CAPS seed url {0} to client {1}", capsPath, agent.UUID);
- Vector3 vel2 = new Vector3(agent.Velocity.X, agent.Velocity.Y, 0);
+ Vector3 vel2 = Vector3.Zero;
+ if((agent.crossingFlags & 2) != 0)
+ vel2 = new Vector3(agent.Velocity.X, agent.Velocity.Y, 0);
if (m_eqModule != null)
{
m_eqModule.CrossRegion(
neighbourRegion.RegionHandle, pos, vel2 /* agent.Velocity */,
- neighbourRegion.ExternalEndPoint,
- capsPath, agent.UUID, agent.ControllingClient.SessionId,
+ endpoint, capsPath, agent.UUID, agent.ControllingClient.SessionId,
neighbourRegion.RegionSizeX, neighbourRegion.RegionSizeY);
}
else
{
m_log.ErrorFormat("{0} Using old CrossRegion packet. Varregion will not work!!", LogHeader);
- agent.ControllingClient.CrossRegion(neighbourRegion.RegionHandle, pos, agent.Velocity, neighbourRegion.ExternalEndPoint,
- capsPath);
+ agent.ControllingClient.CrossRegion(neighbourRegion.RegionHandle, pos, agent.Velocity,
+ endpoint,capsPath);
}
// SUCCESS!
@@ -1800,11 +1864,12 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
// Unlike a teleport, here we do not wait for the destination region to confirm the receipt.
m_entityTransferStateMachine.UpdateInTransit(agent.UUID, AgentTransferState.CleaningUp);
- agent.CloseChildAgents(false, neighbourRegion.RegionHandle, neighbourRegion.RegionSizeX, neighbourRegion.RegionSizeY);
+ if(childRegionsToClose != null)
+ agent.CloseChildAgents(childRegionsToClose);
// this may need the attachments
- agent.HasMovedAway(true);
+ agent.HasMovedAway((agent.crossingFlags & 8) == 0);
agent.MakeChildAgent(neighbourRegion.RegionHandle);
@@ -1812,20 +1877,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
// but not sure yet what the side effects would be.
m_entityTransferStateMachine.ResetFromTransit(agent.UUID);
- // the user may change their profile information in other region,
- // so the userinfo in UserProfileCache is not reliable any more, delete it
- // REFACTORING PROBLEM. Well, not a problem, but this method is HORRIBLE!
-// if (agent.Scene.NeedSceneCacheClear(agent.UUID))
-// {
-// m_log.DebugFormat(
-// "[ENTITY TRANSFER MODULE]: User {0} is going to another region", agent.UUID);
-// }
-
- //m_log.Debug("AFTER CROSS");
- //Scene.DumpChildrenSeeds(UUID);
- //DumpKnownRegions();
-
- return;
+ return true;
}
private void CrossAgentToNewRegionCompleted(IAsyncResult iar)
@@ -1888,7 +1940,6 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
seeds.Add(regionhandler, agent.CapsPath);
-
// agent.ChildrenCapSeeds = new Dictionary(seeds);
agent.ChildrenCapSeeds = null;
@@ -2094,6 +2145,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
{
Thread.Sleep(200); // the original delay that was at InformClientOfNeighbourAsync start
int count = 0;
+ IPEndPoint ipe;
foreach (GridRegion neighbour in neighbours)
{
@@ -2102,8 +2154,13 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
{
if (newneighbours.Contains(handler))
{
- InformClientOfNeighbourAsync(sp, cagents[count], neighbour,
- neighbour.ExternalEndPoint, true);
+ ipe = neighbour.ExternalEndPoint;
+ if (ipe != null)
+ InformClientOfNeighbourAsync(sp, cagents[count], neighbour, ipe, true);
+ else
+ {
+ m_log.DebugFormat("[ENTITY TRANSFER MODULE]: lost DNS resolution for neighbour {0}", neighbour.ExternalHostName);
+ }
count++;
}
else if (!previousRegionNeighbourHandles.Contains(handler))
@@ -2135,7 +2192,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
sp.Scene.RegionInfo.WorldLocY - neighbour.RegionLocY,
0f);
}
-
+ #endregion
#region NotFoundLocationCache class
// A collection of not found locations to make future lookups 'not found' lookups quick.
@@ -2201,6 +2258,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
}
#endregion // NotFoundLocationCache class
+ #region getregions
private NotFoundLocationCache m_notFoundLocationCache = new NotFoundLocationCache();
protected GridRegion GetRegionContainingWorldLocation(IGridService pGridService, UUID pScopeID, double px, double py)
@@ -2218,9 +2276,8 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
protected GridRegion GetRegionContainingWorldLocation(IGridService pGridService, UUID pScopeID,
double px, double py, uint pSizeHint)
{
- m_log.DebugFormat("{0} GetRegionContainingWorldLocation: call, XY=<{1},{2}>", LogHeader, px, py);
+// m_log.DebugFormat("{0} GetRegionContainingWorldLocation: call, XY=<{1},{2}>", LogHeader, px, py);
GridRegion ret = null;
- const double fudge = 2.0;
if (m_notFoundLocationCache.Contains(px, py))
{
@@ -2318,17 +2375,9 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
if (m_eqModule != null)
{
- #region IP Translation for NAT
if(sp == null || sp.IsDeleted || sp.ClientView == null) // something bad already happened
return;
- IClientIPEndpoint ipepClient;
- if (sp.ClientView.TryGet(out ipepClient))
- {
- endPoint.Address = NetworkUtil.GetIPFor(ipepClient.EndPoint, endPoint.Address);
- }
- #endregion
-
m_log.DebugFormat("{0} {1} is sending {2} EnableSimulator for neighbour region {3}(loc=<{4},{5}>,siz=<{6},{7}>) " +
"and EstablishAgentCommunication with seed cap {8}", LogHeader,
scene.RegionInfo.RegionName, sp.Name,
@@ -2620,7 +2669,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
{
// FIXME: It would be better to never add the scene object at all rather than add it and then delete
// it
- if (!Scene.Permissions.CanObjectEntry(so.UUID, true, so.AbsolutePosition))
+ if (!Scene.Permissions.CanObjectEntry(so, true, so.AbsolutePosition))
{
// Deny non attachments based on parcel settings
//
diff --git a/OpenSim/Region/CoreModules/Framework/EntityTransfer/HGEntityTransferModule.cs b/OpenSim/Region/CoreModules/Framework/EntityTransfer/HGEntityTransferModule.cs
index 1ce69276b4..56c654f224 100644
--- a/OpenSim/Region/CoreModules/Framework/EntityTransfer/HGEntityTransferModule.cs
+++ b/OpenSim/Region/CoreModules/Framework/EntityTransfer/HGEntityTransferModule.cs
@@ -163,7 +163,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
m_incomingSceneObjectEngine
= new JobEngine(
string.Format("HG Incoming Scene Object Engine ({0})", scene.Name),
- "HG INCOMING SCENE OBJECT ENGINE");
+ "HG INCOMING SCENE OBJECT ENGINE", 30000);
StatsManager.RegisterStat(
new Stat(
diff --git a/OpenSim/Region/CoreModules/Framework/InventoryAccess/HGInventoryAccessModule.cs b/OpenSim/Region/CoreModules/Framework/InventoryAccess/HGInventoryAccessModule.cs
index 95e7456d3f..ba3a7c9062 100644
--- a/OpenSim/Region/CoreModules/Framework/InventoryAccess/HGInventoryAccessModule.cs
+++ b/OpenSim/Region/CoreModules/Framework/InventoryAccess/HGInventoryAccessModule.cs
@@ -541,16 +541,17 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
#region Permissions
- private bool CanTakeObject(UUID objectID, UUID stealer, Scene scene)
+ private bool CanTakeObject(SceneObjectGroup sog, ScenePresence sp)
{
if (m_bypassPermissions) return true;
- if (!m_OutboundPermission && !UserManagementModule.IsLocalGridUser(stealer))
- {
- SceneObjectGroup sog = null;
- if (m_Scene.TryGetSceneObjectGroup(objectID, out sog) && sog.OwnerID == stealer)
- return true;
+ if(sp == null || sog == null)
+ return false;
+ if (!m_OutboundPermission && !UserManagementModule.IsLocalGridUser(sp.UUID))
+ {
+ if (sog.OwnerID == sp.UUID)
+ return true;
return false;
}
diff --git a/OpenSim/Region/CoreModules/Framework/InventoryAccess/InventoryAccessModule.cs b/OpenSim/Region/CoreModules/Framework/InventoryAccess/InventoryAccessModule.cs
index 010482374c..788ed1c667 100644
--- a/OpenSim/Region/CoreModules/Framework/InventoryAccess/InventoryAccessModule.cs
+++ b/OpenSim/Region/CoreModules/Framework/InventoryAccess/InventoryAccessModule.cs
@@ -212,6 +212,8 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
if (m_Scene.TryGetScenePresence(remoteClient.AgentId, out presence))
{
byte[] data = null;
+ uint everyonemask = 0;
+ uint groupmask = 0;
if (invType == (sbyte)InventoryType.Landmark && presence != null)
{
@@ -220,6 +222,8 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
data = Encoding.ASCII.GetBytes(strdata);
name = prefix + name;
description += suffix;
+ groupmask = (uint)PermissionMask.AllAndExport;
+ everyonemask = (uint)(PermissionMask.AllAndExport & ~PermissionMask.Modify);
}
AssetBase asset = m_Scene.CreateAsset(name, description, assetType, data, remoteClient.AgentId);
@@ -227,9 +231,10 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
m_Scene.CreateNewInventoryItem(
remoteClient, remoteClient.AgentId.ToString(), string.Empty, folderID,
name, description, 0, callbackID, asset.FullID, asset.Type, invType,
- (uint)PermissionMask.All | (uint)PermissionMask.Export, // Base
- (uint)PermissionMask.All | (uint)PermissionMask.Export, // Current
- 0, nextOwnerMask, 0, creationDate, false); // Data from viewer
+ (uint)PermissionMask.AllAndExport, // Base
+ (uint)PermissionMask.AllAndExport, // Current
+ everyonemask,
+ nextOwnerMask, groupmask, creationDate, false); // Data from viewer
}
else
{
@@ -294,15 +299,18 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
else if ((CustomInventoryType)item.InvType == CustomInventoryType.AnimationSet)
{
AnimationSet animSet = new AnimationSet(data);
- if (!animSet.Validate(x => {
+ uint res = animSet.Validate(x => {
+ const int required = (int)(PermissionMask.Transfer | PermissionMask.Copy);
int perms = m_Scene.InventoryService.GetAssetPermissions(remoteClient.AgentId, x);
- int required = (int)(PermissionMask.Transfer | PermissionMask.Copy);
+ // enforce previus perm rule
if ((perms & required) != required)
- return false;
- return true;
- }))
+ return 0;
+ return (uint) perms;
+ });
+ if(res == 0)
{
- data = animSet.ToBytes();
+ remoteClient.SendAgentAlertMessage("Not enought permissions on asset(s) referenced by animation set '{0}', update failed", false);
+ return UUID.Zero;
}
}
@@ -407,7 +415,7 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
Dictionary originalPositions = new Dictionary();
Dictionary originalRotations = new Dictionary();
// this possible is not needed if keyframes are saved
- Dictionary originalKeyframes = new Dictionary();
+// Dictionary originalKeyframes = new Dictionary();
foreach (SceneObjectGroup objectGroup in objlist)
{
@@ -418,8 +426,8 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
objectGroup.RootPart.SetForce(Vector3.Zero);
objectGroup.RootPart.SetAngularImpulse(Vector3.Zero, false);
- originalKeyframes[objectGroup.UUID] = objectGroup.RootPart.KeyframeMotion;
- objectGroup.RootPart.KeyframeMotion = null;
+// originalKeyframes[objectGroup.UUID] = objectGroup.RootPart.KeyframeMotion;
+// objectGroup.RootPart.KeyframeMotion = null;
Vector3 inventoryStoredPosition = objectGroup.AbsolutePosition;
originalPositions[objectGroup.UUID] = inventoryStoredPosition;
@@ -427,20 +435,14 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
originalRotations[objectGroup.UUID] = inventoryStoredRotation;
// Restore attachment data after trip through the sim
- if (objectGroup.RootPart.AttachPoint > 0)
+ if (objectGroup.AttachmentPoint > 0)
{
inventoryStoredPosition = objectGroup.RootPart.AttachedPos;
inventoryStoredRotation = objectGroup.RootPart.AttachRotation;
- }
+ if (objectGroup.RootPart.Shape.PCode != (byte) PCode.Tree &&
+ objectGroup.RootPart.Shape.PCode != (byte) PCode.NewTree)
+ objectGroup.RootPart.Shape.LastAttachPoint = (byte)objectGroup.AttachmentPoint;
- // Trees could be attached and it's been done, but it makes
- // no sense. State must be preserved because it's the tree type
- if (objectGroup.RootPart.Shape.PCode != (byte) PCode.Tree &&
- objectGroup.RootPart.Shape.PCode != (byte) PCode.NewTree)
- {
- objectGroup.RootPart.Shape.State = objectGroup.RootPart.AttachPoint;
- if (objectGroup.RootPart.AttachPoint > 0)
- objectGroup.RootPart.Shape.LastAttachPoint = objectGroup.RootPart.AttachPoint;
}
objectGroup.AbsolutePosition = inventoryStoredPosition;
@@ -477,7 +479,7 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
{
objectGroup.AbsolutePosition = originalPositions[objectGroup.UUID];
objectGroup.RootPart.RotationOffset = originalRotations[objectGroup.UUID];
- objectGroup.RootPart.KeyframeMotion = originalKeyframes[objectGroup.UUID];
+// objectGroup.RootPart.KeyframeMotion = originalKeyframes[objectGroup.UUID];
if (objectGroup.RootPart.KeyframeMotion != null)
objectGroup.RootPart.KeyframeMotion.Resume();
}
@@ -579,41 +581,30 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
InventoryItemBase item, SceneObjectGroup so, List objsForEffectivePermissions,
IClientAPI remoteClient)
{
- uint effectivePerms = (uint)(PermissionMask.Copy | PermissionMask.Transfer | PermissionMask.Modify | PermissionMask.Move | PermissionMask.Export) | 7;
- uint allObjectsNextOwnerPerms = 0x7fffffff;
-
- // For the porposes of inventory, an object is modify if the prims
- // are modify. This allows renaming an object that contains no
- // mod items.
+ uint effectivePerms = (uint)(PermissionMask.Copy | PermissionMask.Transfer | PermissionMask.Modify | PermissionMask.Move | PermissionMask.Export | PermissionMask.FoldedMask);
+
foreach (SceneObjectGroup grp in objsForEffectivePermissions)
{
- uint groupPerms = grp.GetEffectivePermissions(true);
- if ((grp.RootPart.BaseMask & (uint)PermissionMask.Modify) != 0)
- groupPerms |= (uint)PermissionMask.Modify;
-
- effectivePerms &= groupPerms;
+ effectivePerms &= grp.CurrentAndFoldedNextPermissions();
}
- effectivePerms |= (uint)PermissionMask.Move;
-
+
if (remoteClient != null && (remoteClient.AgentId != so.RootPart.OwnerID) && m_Scene.Permissions.PropagatePermissions())
{
- uint perms = effectivePerms;
- uint nextPerms = (perms & 7) << 13;
- if ((nextPerms & (uint)PermissionMask.Copy) == 0)
- perms &= ~(uint)PermissionMask.Copy;
- if ((nextPerms & (uint)PermissionMask.Transfer) == 0)
- perms &= ~(uint)PermissionMask.Transfer;
- if ((nextPerms & (uint)PermissionMask.Modify) == 0)
- perms &= ~(uint)PermissionMask.Modify;
-
- item.BasePermissions = perms & so.RootPart.NextOwnerMask;
- item.CurrentPermissions = item.BasePermissions;
- item.NextPermissions = perms & so.RootPart.NextOwnerMask;
- item.EveryOnePermissions = so.RootPart.EveryoneMask & so.RootPart.NextOwnerMask;
- item.GroupPermissions = so.RootPart.GroupMask & so.RootPart.NextOwnerMask;
+ // apply parts inventory items next owner
+ PermissionsUtil.ApplyNoModFoldedPermissions(effectivePerms, ref effectivePerms);
+ // change to next owner
+ uint basePerms = effectivePerms & so.RootPart.NextOwnerMask;
+ // fix and update folded
+ basePerms = PermissionsUtil.FixAndFoldPermissions(basePerms);
+
+ item.BasePermissions = basePerms;
+ item.CurrentPermissions = basePerms;
+ item.NextPermissions = basePerms & so.RootPart.NextOwnerMask;
+ item.EveryOnePermissions = basePerms & so.RootPart.EveryoneMask;
+ item.GroupPermissions = basePerms & so.RootPart.GroupMask;
// apply next owner perms on rez
- item.CurrentPermissions |= SceneObjectGroup.SLAM;
+ item.Flags |= (uint)InventoryItemFlags.ObjectSlamPerm;
}
else
{
@@ -629,7 +620,7 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
(uint)PermissionMask.Modify |
(uint)PermissionMask.Move |
(uint)PermissionMask.Export |
- 7); // Preserve folded permissions
+ (uint)PermissionMask.FoldedMask); // Preserve folded permissions ??
}
return item;
@@ -1001,11 +992,11 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
// one full update during the attachment
// process causes some clients to fail to display the
// attachment properly.
- m_Scene.AddNewSceneObject(group, true, false);
if (!attachment)
{
group.AbsolutePosition = pos + veclist[i];
+ m_Scene.AddNewSceneObject(group, true, false);
// Fire on_rez
group.CreateScriptInstances(0, true, m_Scene.DefaultScriptEngine, 1);
@@ -1013,6 +1004,9 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
group.ScheduleGroupForFullUpdate();
}
+ else
+ m_Scene.AddNewSceneObject(group, true, false);
+
// m_log.DebugFormat(
// "[INVENTORY ACCESS MODULE]: Rezzed {0} {1} {2} ownermask={3:X} nextownermask={4:X} groupmask={5:X} everyonemask={6:X} for {7}",
@@ -1124,7 +1118,7 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
// rootPart.OwnerID, item.Owner, item.CurrentPermissions);
if ((rootPart.OwnerID != item.Owner) ||
- (item.CurrentPermissions & 16) != 0 ||
+ (item.CurrentPermissions & (uint)PermissionMask.Slam) != 0 ||
(item.Flags & (uint)InventoryItemFlags.ObjectSlamPerm) != 0)
{
//Need to kill the for sale here
@@ -1136,32 +1130,46 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
foreach (SceneObjectPart part in so.Parts)
{
part.GroupMask = 0; // DO NOT propagate here
-
- part.LastOwnerID = part.OwnerID;
+ if( part.OwnerID != part.GroupID)
+ part.LastOwnerID = part.OwnerID;
part.OwnerID = item.Owner;
part.RezzerID = item.Owner;
part.Inventory.ChangeInventoryOwner(item.Owner);
- // This applies the base mask from the item as the next
- // permissions for the object. This is correct because the
- // giver's base mask was masked by the giver's next owner
- // mask, so the base mask equals the original next owner mask.
- part.NextOwnerMask = item.BasePermissions;
+ // Reconstruct the original item's base permissions. They
+ // can be found in the lower (folded) bits.
+ if ((item.BasePermissions & (uint)PermissionMask.FoldedMask) != 0)
+ {
+ // We have permissions stored there so use them
+ part.NextOwnerMask = ((item.BasePermissions & (uint)PermissionMask.FoldedMask) << (int)PermissionMask.FoldingShift);
+ part.NextOwnerMask |= (uint)PermissionMask.Move;
+ }
+ else
+ {
+ // This is a legacy object and we can't avoid the issues that
+ // caused perms loss or escalation before, treat it the legacy
+ // way.
+ part.NextOwnerMask = item.NextPermissions;
+ }
}
so.ApplyNextOwnerPermissions();
// In case the user has changed flags on a received item
// we have to apply those changes after the slam. Else we
- // get a net loss of permissions
+ // get a net loss of permissions.
+ // On legacy objects, this opts for a loss of permissions rather
+ // than the previous handling that allowed escalation.
foreach (SceneObjectPart part in so.Parts)
{
if ((item.Flags & (uint)InventoryItemFlags.ObjectHasMultipleItems) == 0)
{
+ part.GroupMask = item.GroupPermissions & part.BaseMask;
part.EveryoneMask = item.EveryOnePermissions & part.BaseMask;
part.NextOwnerMask = item.NextPermissions & part.BaseMask;
}
}
+
}
}
else
@@ -1180,6 +1188,7 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
}
rootPart.TrimPermissions();
+ so.InvalidateDeepEffectivePerms();
if (isAttachment)
so.FromItemID = item.ID;
diff --git a/OpenSim/Region/CoreModules/Framework/ServiceThrottle/ServiceThrottleModule.cs b/OpenSim/Region/CoreModules/Framework/ServiceThrottle/ServiceThrottleModule.cs
index 924a1a3c1a..2c74c0e0c0 100644
--- a/OpenSim/Region/CoreModules/Framework/ServiceThrottle/ServiceThrottleModule.cs
+++ b/OpenSim/Region/CoreModules/Framework/ServiceThrottle/ServiceThrottleModule.cs
@@ -119,7 +119,15 @@ namespace OpenSim.Region.CoreModules.Framework
if(!client.IsActive)
return;
- GridRegion r = m_scenes[0].GridService.GetRegionByUUID(UUID.Zero, regionID);
+ if(m_scenes.Count == 0)
+ return;
+
+ Scene baseScene = m_scenes[0];
+
+ if(baseScene == null || baseScene.ShuttingDown)
+ return;
+
+ GridRegion r = baseScene.GridService.GetRegionByUUID(UUID.Zero, regionID);
if(!client.IsActive)
return;
diff --git a/OpenSim/Region/CoreModules/Framework/UserManagement/UserManagementModule.cs b/OpenSim/Region/CoreModules/Framework/UserManagement/UserManagementModule.cs
index 51f973a4c0..269546430f 100644
--- a/OpenSim/Region/CoreModules/Framework/UserManagement/UserManagementModule.cs
+++ b/OpenSim/Region/CoreModules/Framework/UserManagement/UserManagementModule.cs
@@ -175,6 +175,7 @@ namespace OpenSim.Region.CoreModules.Framework.UserManagement
{
client.OnNameFromUUIDRequest -= new UUIDNameRequest(HandleUUIDNameRequest);
client.OnAvatarPickerRequest -= new AvatarPickerRequest(HandleAvatarPickerRequest);
+ client.OnConnectionClosed -= new Action(HandleConnectionClosed);
}
protected virtual void HandleUUIDNameRequest(UUID uuid, IClientAPI client)
@@ -957,9 +958,14 @@ namespace OpenSim.Region.CoreModules.Framework.UserManagement
public virtual bool IsLocalGridUser(UUID uuid)
{
- UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(m_Scenes[0].RegionInfo.ScopeID, uuid);
- if (account == null || (account != null && !account.LocalToGrid))
- return false;
+ lock (m_Scenes)
+ {
+ if (m_Scenes.Count == 0)
+ return true;
+ UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(m_Scenes[0].RegionInfo.ScopeID, uuid);
+ if (account == null || (account != null && !account.LocalToGrid))
+ return false;
+ }
return true;
}
diff --git a/OpenSim/Region/CoreModules/Hypergrid/HGWorldMapModule.cs b/OpenSim/Region/CoreModules/Hypergrid/HGWorldMapModule.cs
index 5d66d34a2b..8c44ee2f93 100644
--- a/OpenSim/Region/CoreModules/Hypergrid/HGWorldMapModule.cs
+++ b/OpenSim/Region/CoreModules/Hypergrid/HGWorldMapModule.cs
@@ -106,6 +106,8 @@ namespace OpenSim.Region.CoreModules.Hypergrid
if (!m_Enabled)
return;
+ base.RemoveRegion(scene);
+
scene.EventManager.OnClientClosed -= EventManager_OnClientClosed;
}
diff --git a/OpenSim/Region/CoreModules/Scripting/DynamicTexture/DynamicTextureModule.cs b/OpenSim/Region/CoreModules/Scripting/DynamicTexture/DynamicTextureModule.cs
index c369d87b05..090cb7d447 100644
--- a/OpenSim/Region/CoreModules/Scripting/DynamicTexture/DynamicTextureModule.cs
+++ b/OpenSim/Region/CoreModules/Scripting/DynamicTexture/DynamicTextureModule.cs
@@ -135,17 +135,13 @@ namespace OpenSim.Region.CoreModules.Scripting.DynamicTexture
m_reuseableDynamicTextures.Store(
GenerateReusableTextureKey(texture.InputCommands, texture.InputParams), newTextureID);
}
+ updater.newTextureID = newTextureID;
}
- }
- if (updater.UpdateTimer == 0)
- {
lock (Updaters)
{
- if (!Updaters.ContainsKey(updater.UpdaterID))
- {
+ if (Updaters.ContainsKey(updater.UpdaterID))
Updaters.Remove(updater.UpdaterID);
- }
}
}
}
@@ -172,21 +168,20 @@ namespace OpenSim.Region.CoreModules.Scripting.DynamicTexture
}
public UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url,
- string extraParams, int updateTimer)
+ string extraParams)
{
- return AddDynamicTextureURL(simID, primID, contentType, url, extraParams, updateTimer, false, 255);
+ return AddDynamicTextureURL(simID, primID, contentType, url, extraParams, false, 255);
}
public UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url,
- string extraParams, int updateTimer, bool SetBlending, byte AlphaValue)
+ string extraParams, bool SetBlending, byte AlphaValue)
{
- return AddDynamicTextureURL(simID, primID, contentType, url,
- extraParams, updateTimer, SetBlending,
- (int)(DISP_TEMP|DISP_EXPIRE), AlphaValue, ALL_SIDES);
+ return AddDynamicTextureURL(simID, primID, contentType, url, extraParams, SetBlending,
+ (DISP_TEMP|DISP_EXPIRE), AlphaValue, ALL_SIDES);
}
public UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url,
- string extraParams, int updateTimer, bool SetBlending,
+ string extraParams, bool SetBlending,
int disp, byte AlphaValue, int face)
{
if (RenderPlugins.ContainsKey(contentType))
@@ -196,7 +191,6 @@ namespace OpenSim.Region.CoreModules.Scripting.DynamicTexture
updater.PrimID = primID;
updater.ContentType = contentType;
updater.Url = url;
- updater.UpdateTimer = updateTimer;
updater.UpdaterID = UUID.Random();
updater.Params = extraParams;
updater.BlendWithOldTexture = SetBlending;
@@ -213,26 +207,27 @@ namespace OpenSim.Region.CoreModules.Scripting.DynamicTexture
}
RenderPlugins[contentType].AsyncConvertUrl(updater.UpdaterID, url, extraParams);
- return updater.UpdaterID;
+ return updater.newTextureID;
}
return UUID.Zero;
}
public UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data,
- string extraParams, int updateTimer)
+ string extraParams)
{
- return AddDynamicTextureData(simID, primID, contentType, data, extraParams, updateTimer, false, 255);
+ return AddDynamicTextureData(simID, primID, contentType, data, extraParams, false,
+ (DISP_TEMP|DISP_EXPIRE), 255, ALL_SIDES);
}
public UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data,
- string extraParams, int updateTimer, bool SetBlending, byte AlphaValue)
+ string extraParams, bool SetBlending, byte AlphaValue)
{
- return AddDynamicTextureData(simID, primID, contentType, data, extraParams, updateTimer, SetBlending,
- (int) (DISP_TEMP|DISP_EXPIRE), AlphaValue, ALL_SIDES);
+ return AddDynamicTextureData(simID, primID, contentType, data, extraParams, SetBlending,
+ (DISP_TEMP|DISP_EXPIRE), AlphaValue, ALL_SIDES);
}
public UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data,
- string extraParams, int updateTimer, bool SetBlending, int disp, byte AlphaValue, int face)
+ string extraParams, bool SetBlending, int disp, byte AlphaValue, int face)
{
if (!RenderPlugins.ContainsKey(contentType))
return UUID.Zero;
@@ -258,7 +253,6 @@ namespace OpenSim.Region.CoreModules.Scripting.DynamicTexture
updater.PrimID = primID;
updater.ContentType = contentType;
updater.BodyData = data;
- updater.UpdateTimer = updateTimer;
updater.UpdaterID = UUID.Random();
updater.Params = extraParams;
updater.BlendWithOldTexture = SetBlending;
@@ -314,7 +308,7 @@ namespace OpenSim.Region.CoreModules.Scripting.DynamicTexture
updater.UpdatePart(part, (UUID)objReusableTextureUUID);
}
- return updater.UpdaterID;
+ return updater.newTextureID;
}
private string GenerateReusableTextureKey(string data, string extraParams)
@@ -404,17 +398,15 @@ namespace OpenSim.Region.CoreModules.Scripting.DynamicTexture
public byte FrontAlpha = 255;
public string Params;
public UUID PrimID;
- public bool SetNewFrontAlpha = false;
public UUID SimUUID;
public UUID UpdaterID;
- public int UpdateTimer;
public int Face;
public int Disp;
public string Url;
+ public UUID newTextureID;
public DynamicTextureUpdater()
{
- UpdateTimer = 0;
BodyData = null;
}
@@ -436,16 +428,23 @@ namespace OpenSim.Region.CoreModules.Scripting.DynamicTexture
// FIXME: Need to return the appropriate ID if only a single face is replaced.
oldID = tmptex.DefaultTexture.TextureID;
+ // not using parts number of faces because that fails on old meshs
if (Face == ALL_SIDES)
{
oldID = tmptex.DefaultTexture.TextureID;
tmptex.DefaultTexture.TextureID = textureID;
+ for(int i = 0; i < tmptex.FaceTextures.Length; i++)
+ {
+ if(tmptex.FaceTextures[i] != null)
+ tmptex.FaceTextures[i].TextureID = textureID;
+ }
}
else
{
try
{
Primitive.TextureEntryFace texface = tmptex.CreateFace((uint)Face);
+ oldID = texface.TextureID;
texface.TextureID = textureID;
tmptex.FaceTextures[Face] = texface;
}
@@ -455,10 +454,6 @@ namespace OpenSim.Region.CoreModules.Scripting.DynamicTexture
}
}
- // I'm pretty sure we always want to force this to true
- // I'm pretty sure noone whats to set fullbright true if it wasn't true before.
- // tmptex.DefaultTexture.Fullbright = true;
-
part.UpdateTextureEntry(tmptex.GetBytes());
}
@@ -491,13 +486,26 @@ namespace OpenSim.Region.CoreModules.Scripting.DynamicTexture
if (BlendWithOldTexture)
{
- Primitive.TextureEntryFace defaultFace = part.Shape.Textures.DefaultTexture;
- if (defaultFace != null)
+ Primitive.TextureEntryFace curFace;
+ if(Face == ALL_SIDES)
+ curFace = part.Shape.Textures.DefaultTexture;
+ else
{
- oldAsset = scene.AssetService.Get(defaultFace.TextureID.ToString());
+ try
+ {
+ curFace = part.Shape.Textures.GetFace((uint)Face);
+ }
+ catch
+ {
+ curFace = null;
+ }
+ }
+ if (curFace != null)
+ {
+ oldAsset = scene.AssetService.Get(curFace.TextureID.ToString());
if (oldAsset != null)
- assetData = BlendTextures(data, oldAsset.Data, SetNewFrontAlpha, FrontAlpha);
+ assetData = BlendTextures(data, oldAsset.Data, FrontAlpha);
}
}
@@ -548,7 +556,7 @@ namespace OpenSim.Region.CoreModules.Scripting.DynamicTexture
return asset.FullID;
}
- private byte[] BlendTextures(byte[] frontImage, byte[] backImage, bool setNewAlpha, byte newAlpha)
+ private byte[] BlendTextures(byte[] frontImage, byte[] backImage, byte newAlpha)
{
ManagedImage managedImage;
Image image;
@@ -568,7 +576,7 @@ namespace OpenSim.Region.CoreModules.Scripting.DynamicTexture
Bitmap image2 = new Bitmap(image);
image.Dispose();
- if (setNewAlpha)
+ if (newAlpha < 255)
SetAlpha(ref image1, newAlpha);
using(Bitmap joint = MergeBitMaps(image1, image2))
diff --git a/OpenSim/Region/CoreModules/Scripting/HttpRequest/ScriptsHttpRequests.cs b/OpenSim/Region/CoreModules/Scripting/HttpRequest/ScriptsHttpRequests.cs
index 09891f7876..f5b575bec3 100644
--- a/OpenSim/Region/CoreModules/Scripting/HttpRequest/ScriptsHttpRequests.cs
+++ b/OpenSim/Region/CoreModules/Scripting/HttpRequest/ScriptsHttpRequests.cs
@@ -223,20 +223,16 @@ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
if (parms.Length - i < 2)
break;
- //Have we reached the end of the list of headers?
- //End is marked by a string with a single digit.
- //We already know we have at least one parameter
- //so it is safe to do this check at top of loop.
- if (Char.IsDigit(parms[i][0]))
- break;
-
if (htc.HttpCustomHeaders == null)
htc.HttpCustomHeaders = new List();
htc.HttpCustomHeaders.Add(parms[i]);
htc.HttpCustomHeaders.Add(parms[i+1]);
+ int nexti = i + 2;
+ if (nexti >= parms.Length || Char.IsDigit(parms[nexti][0]))
+ break;
- i += 2;
+ i = nexti;
}
break;
@@ -383,9 +379,9 @@ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
if (ThreadPool == null)
{
STPStartInfo startInfo = new STPStartInfo();
- startInfo.IdleTimeout = 20000;
+ startInfo.IdleTimeout = 2000;
startInfo.MaxWorkerThreads = maxThreads;
- startInfo.MinWorkerThreads = 1;
+ startInfo.MinWorkerThreads = 0;
startInfo.ThreadPriority = ThreadPriority.BelowNormal;
startInfo.StartSuspended = true;
startInfo.ThreadPoolName = "ScriptsHttpReq";
@@ -419,6 +415,7 @@ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
public void Close()
{
+ ThreadPool.Shutdown();
}
public string Name
@@ -542,6 +539,7 @@ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
{
Request = (HttpWebRequest)WebRequest.Create(Url);
Request.AllowAutoRedirect = false;
+ Request.KeepAlive = false;
//This works around some buggy HTTP Servers like Lighttpd
Request.ServicePoint.Expect100Continue = false;
@@ -667,12 +665,6 @@ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
Status = (int)OSHttpStatusCode.ClientErrorJoker;
ResponseBody = e.Message;
}
-
- if (ResponseBody == null)
- ResponseBody = String.Empty;
-
- _finished = true;
- return;
}
catch (Exception e)
{
@@ -731,13 +723,10 @@ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
else
{
_finished = true;
+ if (ResponseBody == null)
+ ResponseBody = String.Empty;
}
}
-
- if (ResponseBody == null)
- ResponseBody = String.Empty;
-
- _finished = true;
}
public void Stop()
diff --git a/OpenSim/Region/CoreModules/Scripting/LSLHttp/UrlModule.cs b/OpenSim/Region/CoreModules/Scripting/LSLHttp/UrlModule.cs
index bb80a88298..11fc513e0d 100644
--- a/OpenSim/Region/CoreModules/Scripting/LSLHttp/UrlModule.cs
+++ b/OpenSim/Region/CoreModules/Scripting/LSLHttp/UrlModule.cs
@@ -26,10 +26,11 @@
*/
using System;
-using System.Threading;
using System.Collections.Generic;
using System.Collections;
using System.Reflection;
+using System.Net;
+using System.Net.Sockets;
using log4net;
using Mono.Addins;
using Nini.Config;
@@ -83,17 +84,19 @@ namespace OpenSim.Region.CoreModules.Scripting.LSLHttp
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
- private Dictionary m_RequestMap =
+ protected Dictionary m_RequestMap =
new Dictionary();
- private Dictionary m_UrlMap =
+ protected Dictionary m_UrlMap =
new Dictionary();
- private uint m_HttpsPort = 0;
- private IHttpServer m_HttpServer = null;
- private IHttpServer m_HttpsServer = null;
+ protected bool m_enabled = false;
+ protected string m_ErrorStr;
+ protected uint m_HttpsPort = 0;
+ protected IHttpServer m_HttpServer = null;
+ protected IHttpServer m_HttpsServer = null;
- public string ExternalHostNameForLSL { get; private set; }
+ public string ExternalHostNameForLSL { get; protected set; }
///
/// The default maximum number of urls
@@ -107,7 +110,7 @@ namespace OpenSim.Region.CoreModules.Scripting.LSLHttp
public Type ReplaceableInterface
{
- get { return null; }
+ get { return typeof(IUrlModule); }
}
public string Name
@@ -118,6 +121,7 @@ namespace OpenSim.Region.CoreModules.Scripting.LSLHttp
public void Initialise(IConfigSource config)
{
IConfig networkConfig = config.Configs["Network"];
+ m_enabled = false;
if (networkConfig != null)
{
@@ -128,9 +132,31 @@ namespace OpenSim.Region.CoreModules.Scripting.LSLHttp
if (ssl_enabled)
m_HttpsPort = (uint)config.Configs["Network"].GetInt("https_port", (int)m_HttpsPort);
}
+ else
+ {
+ m_ErrorStr = "[Network] configuration missing, HTTP listener for LSL disabled";
+ m_log.Warn("[URL MODULE]: " + m_ErrorStr);
+ return;
+ }
- if (ExternalHostNameForLSL == null)
- ExternalHostNameForLSL = System.Environment.MachineName;
+ if (String.IsNullOrWhiteSpace(ExternalHostNameForLSL))
+ {
+ m_ErrorStr = "ExternalHostNameForLSL not defined in configuration, HTTP listener for LSL disabled";
+ m_log.Warn("[URL MODULE]: " + m_ErrorStr);
+ return;
+ }
+
+ IPAddress ia = null;
+ ia = Util.GetHostFromDNS(ExternalHostNameForLSL);
+ if (ia == null)
+ {
+ m_ErrorStr = "Could not resolve ExternalHostNameForLSL, HTTP listener for LSL disabled";
+ m_log.Warn("[URL MODULE]: " + m_ErrorStr);
+ return;
+ }
+
+ m_enabled = true;
+ m_ErrorStr = String.Empty;
IConfig llFunctionsConfig = config.Configs["LL-Functions"];
@@ -146,7 +172,7 @@ namespace OpenSim.Region.CoreModules.Scripting.LSLHttp
public void AddRegion(Scene scene)
{
- if (m_HttpServer == null)
+ if (m_enabled && m_HttpServer == null)
{
// There can only be one
//
@@ -197,11 +223,18 @@ namespace OpenSim.Region.CoreModules.Scripting.LSLHttp
{
UUID urlcode = UUID.Random();
+ if(!m_enabled)
+ {
+ engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", m_ErrorStr });
+ return urlcode;
+ }
+
lock (m_UrlMap)
{
if (m_UrlMap.Count >= TotalUrls)
{
- engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", "" });
+ engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED",
+ "Too many URLs already open" });
return urlcode;
}
string url = "http://" + ExternalHostNameForLSL + ":" + m_HttpServer.Port.ToString() + "/lslhttp/" + urlcode.ToString() + "/";
@@ -243,6 +276,12 @@ namespace OpenSim.Region.CoreModules.Scripting.LSLHttp
{
UUID urlcode = UUID.Random();
+ if(!m_enabled)
+ {
+ engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", m_ErrorStr });
+ return urlcode;
+ }
+
if (m_HttpsServer == null)
{
engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", "" });
@@ -253,7 +292,8 @@ namespace OpenSim.Region.CoreModules.Scripting.LSLHttp
{
if (m_UrlMap.Count >= TotalUrls)
{
- engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", "" });
+ engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED",
+ "Too many URLs already open" });
return urlcode;
}
string url = "https://" + ExternalHostNameForLSL + ":" + m_HttpsServer.Port.ToString() + "/lslhttps/" + urlcode.ToString() + "/";
@@ -453,7 +493,7 @@ namespace OpenSim.Region.CoreModules.Scripting.LSLHttp
}
- private void RemoveUrl(UrlData data)
+ protected void RemoveUrl(UrlData data)
{
if (data.isSsl)
m_HttpsServer.RemoveHTTPHandler("", "/lslhttps/"+data.urlcode.ToString()+"/");
@@ -461,7 +501,7 @@ namespace OpenSim.Region.CoreModules.Scripting.LSLHttp
m_HttpServer.RemoveHTTPHandler("", "/lslhttp/"+data.urlcode.ToString()+"/");
}
- private Hashtable NoEvents(UUID requestID, UUID sessionID)
+ protected Hashtable NoEvents(UUID requestID, UUID sessionID)
{
Hashtable response = new Hashtable();
UrlData url;
@@ -499,7 +539,7 @@ namespace OpenSim.Region.CoreModules.Scripting.LSLHttp
return response;
}
- private bool HasEvents(UUID requestID, UUID sessionID)
+ protected bool HasEvents(UUID requestID, UUID sessionID)
{
UrlData url=null;
@@ -530,7 +570,7 @@ namespace OpenSim.Region.CoreModules.Scripting.LSLHttp
}
}
}
- private Hashtable GetEvents(UUID requestID, UUID sessionID)
+ protected Hashtable GetEvents(UUID requestID, UUID sessionID)
{
UrlData url = null;
RequestData requestData = null;
@@ -735,7 +775,7 @@ namespace OpenSim.Region.CoreModules.Scripting.LSLHttp
}
}
- private void OnScriptReset(uint localID, UUID itemID)
+ protected void OnScriptReset(uint localID, UUID itemID)
{
ScriptRemoved(itemID);
}
diff --git a/OpenSim/Region/CoreModules/Scripting/VectorRender/Tests/VectorRenderModuleTests.cs b/OpenSim/Region/CoreModules/Scripting/VectorRender/Tests/VectorRenderModuleTests.cs
index ed255bfcb3..325f7f9ccf 100644
--- a/OpenSim/Region/CoreModules/Scripting/VectorRender/Tests/VectorRenderModuleTests.cs
+++ b/OpenSim/Region/CoreModules/Scripting/VectorRender/Tests/VectorRenderModuleTests.cs
@@ -77,8 +77,7 @@ namespace OpenSim.Region.CoreModules.Scripting.VectorRender.Tests
so.UUID,
m_vrm.GetContentType(),
"PenColour BLACK; MoveTo 40,220; FontSize 32; Text Hello World;",
- "",
- 0);
+ "");
Assert.That(originalTextureID, Is.Not.EqualTo(so.RootPart.Shape.Textures.GetFace(0).TextureID));
}
@@ -98,8 +97,7 @@ namespace OpenSim.Region.CoreModules.Scripting.VectorRender.Tests
so.UUID,
m_vrm.GetContentType(),
dtText,
- "",
- 0);
+ "");
UUID firstDynamicTextureID = so.RootPart.Shape.Textures.GetFace(0).TextureID;
@@ -108,8 +106,7 @@ namespace OpenSim.Region.CoreModules.Scripting.VectorRender.Tests
so.UUID,
m_vrm.GetContentType(),
dtText,
- "",
- 0);
+ "");
Assert.That(firstDynamicTextureID, Is.Not.EqualTo(so.RootPart.Shape.Textures.GetFace(0).TextureID));
}
@@ -129,8 +126,7 @@ namespace OpenSim.Region.CoreModules.Scripting.VectorRender.Tests
so.UUID,
m_vrm.GetContentType(),
dtText,
- "",
- 0);
+ "");
UUID firstDynamicTextureID = so.RootPart.Shape.Textures.GetFace(0).TextureID;
@@ -139,8 +135,7 @@ namespace OpenSim.Region.CoreModules.Scripting.VectorRender.Tests
so.UUID,
m_vrm.GetContentType(),
dtText,
- "alpha:250",
- 0);
+ "alpha:250");
Assert.That(firstDynamicTextureID, Is.Not.EqualTo(so.RootPart.Shape.Textures.GetFace(0).TextureID));
}
@@ -161,8 +156,7 @@ namespace OpenSim.Region.CoreModules.Scripting.VectorRender.Tests
so.UUID,
m_vrm.GetContentType(),
dtText,
- "",
- 0);
+ "");
UUID firstDynamicTextureID = so.RootPart.Shape.Textures.GetFace(0).TextureID;
@@ -171,8 +165,7 @@ namespace OpenSim.Region.CoreModules.Scripting.VectorRender.Tests
so.UUID,
m_vrm.GetContentType(),
dtText,
- "",
- 0);
+ "");
Assert.That(firstDynamicTextureID, Is.Not.EqualTo(so.RootPart.Shape.Textures.GetFace(0).TextureID));
}
@@ -191,8 +184,7 @@ namespace OpenSim.Region.CoreModules.Scripting.VectorRender.Tests
so.UUID,
m_vrm.GetContentType(),
"PenColour BLACK; MoveTo 40,220; FontSize 32; Text Hello World;",
- "",
- 0);
+ "");
Assert.That(originalTextureID, Is.Not.EqualTo(so.RootPart.Shape.Textures.GetFace(0).TextureID));
}
@@ -213,8 +205,7 @@ namespace OpenSim.Region.CoreModules.Scripting.VectorRender.Tests
so.UUID,
m_vrm.GetContentType(),
dtText,
- "",
- 0);
+ "");
UUID firstDynamicTextureID = so.RootPart.Shape.Textures.GetFace(0).TextureID;
@@ -223,8 +214,7 @@ namespace OpenSim.Region.CoreModules.Scripting.VectorRender.Tests
so.UUID,
m_vrm.GetContentType(),
dtText,
- "",
- 0);
+ "");
Assert.That(firstDynamicTextureID, Is.EqualTo(so.RootPart.Shape.Textures.GetFace(0).TextureID));
}
@@ -253,8 +243,7 @@ namespace OpenSim.Region.CoreModules.Scripting.VectorRender.Tests
so.UUID,
m_vrm.GetContentType(),
dtText,
- "1024",
- 0);
+ "1024");
UUID firstDynamicTextureID = so.RootPart.Shape.Textures.GetFace(0).TextureID;
@@ -263,8 +252,7 @@ namespace OpenSim.Region.CoreModules.Scripting.VectorRender.Tests
so.UUID,
m_vrm.GetContentType(),
dtText,
- "1024",
- 0);
+ "1024");
Assert.That(firstDynamicTextureID, Is.Not.EqualTo(so.RootPart.Shape.Textures.GetFace(0).TextureID));
}
@@ -284,8 +272,7 @@ namespace OpenSim.Region.CoreModules.Scripting.VectorRender.Tests
so.UUID,
m_vrm.GetContentType(),
dtText,
- "",
- 0);
+ "");
UUID firstDynamicTextureID = so.RootPart.Shape.Textures.GetFace(0).TextureID;
@@ -294,8 +281,7 @@ namespace OpenSim.Region.CoreModules.Scripting.VectorRender.Tests
so.UUID,
m_vrm.GetContentType(),
dtText,
- "alpha:250",
- 0);
+ "alpha:250");
Assert.That(firstDynamicTextureID, Is.Not.EqualTo(so.RootPart.Shape.Textures.GetFace(0).TextureID));
}
@@ -316,8 +302,7 @@ namespace OpenSim.Region.CoreModules.Scripting.VectorRender.Tests
so.UUID,
m_vrm.GetContentType(),
dtText,
- "",
- 0);
+ "");
UUID firstDynamicTextureID = so.RootPart.Shape.Textures.GetFace(0).TextureID;
@@ -326,8 +311,7 @@ namespace OpenSim.Region.CoreModules.Scripting.VectorRender.Tests
so.UUID,
m_vrm.GetContentType(),
dtText,
- "",
- 0);
+ "");
Assert.That(firstDynamicTextureID, Is.Not.EqualTo(so.RootPart.Shape.Textures.GetFace(0).TextureID));
}
diff --git a/OpenSim/Region/CoreModules/Scripting/VectorRender/VectorRenderModule.cs b/OpenSim/Region/CoreModules/Scripting/VectorRender/VectorRenderModule.cs
index f12286dafd..8a26ab7b37 100644
--- a/OpenSim/Region/CoreModules/Scripting/VectorRender/VectorRenderModule.cs
+++ b/OpenSim/Region/CoreModules/Scripting/VectorRender/VectorRenderModule.cs
@@ -355,30 +355,22 @@ namespace OpenSim.Region.CoreModules.Scripting.VectorRender
lock (this)
{
if (alpha == 256)
- bitmap = new Bitmap(width, height, PixelFormat.Format32bppRgb);
- else
- bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
-
- graph = Graphics.FromImage(bitmap);
-
- // this is really just to save people filling the
- // background color in their scripts, only do when fully opaque
- if (alpha >= 255)
{
+ bitmap = new Bitmap(width, height, PixelFormat.Format32bppRgb);
+ graph = Graphics.FromImage(bitmap);
using (SolidBrush bgFillBrush = new SolidBrush(bgColor))
{
graph.FillRectangle(bgFillBrush, 0, 0, width, height);
}
- }
-
- for (int w = 0; w < bitmap.Width; w++)
+ }
+ else
{
- if (alpha <= 255)
+ bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
+ graph = Graphics.FromImage(bitmap);
+ Color newbg = Color.FromArgb(alpha,bgColor);
+ using (SolidBrush bgFillBrush = new SolidBrush(newbg))
{
- for (int h = 0; h < bitmap.Height; h++)
- {
- bitmap.SetPixel(w, h, Color.FromArgb(alpha, bitmap.GetPixel(w, h)));
- }
+ graph.FillRectangle(bgFillBrush, 0, 0, width, height);
}
}
@@ -519,8 +511,32 @@ namespace OpenSim.Region.CoreModules.Scripting.VectorRender
// m_log.DebugFormat("[VECTOR RENDER MODULE]: Processing line '{0}'", nextLine);
+ if (nextLine.StartsWith("ResetTransf"))
+ {
+ graph.ResetTransform();
+ }
+ else if (nextLine.StartsWith("TransTransf"))
+ {
+ float x = 0;
+ float y = 0;
+ GetParams(partsDelimiter, ref nextLine, 11, ref x, ref y);
+ graph.TranslateTransform(x, y);
+ }
+ else if (nextLine.StartsWith("ScaleTransf"))
+ {
+ float x = 0;
+ float y = 0;
+ GetParams(partsDelimiter, ref nextLine, 11, ref x, ref y);
+ graph.ScaleTransform(x, y);
+ }
+ else if (nextLine.StartsWith("RotTransf"))
+ {
+ float x = 0;
+ GetParams(partsDelimiter, ref nextLine, 9, ref x);
+ graph.RotateTransform(x);
+ }
//replace with switch, or even better, do some proper parsing
- if (nextLine.StartsWith("MoveTo"))
+ else if (nextLine.StartsWith("MoveTo"))
{
float x = 0;
float y = 0;
@@ -625,6 +641,17 @@ namespace OpenSim.Region.CoreModules.Scripting.VectorRender
startPoint.X += endPoint.X;
startPoint.Y += endPoint.Y;
}
+ else if (nextLine.StartsWith("FillEllipse"))
+ {
+ float x = 0;
+ float y = 0;
+ GetParams(partsDelimiter, ref nextLine, 11, ref x, ref y);
+ endPoint.X = (int)x;
+ endPoint.Y = (int)y;
+ graph.FillEllipse(myBrush, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y);
+ startPoint.X += endPoint.X;
+ startPoint.Y += endPoint.Y;
+ }
else if (nextLine.StartsWith("FontSize"))
{
nextLine = nextLine.Remove(0, 8);
@@ -790,6 +817,17 @@ namespace OpenSim.Region.CoreModules.Scripting.VectorRender
}
}
+ private static void GetParams(char[] partsDelimiter, ref string line, int startLength, ref float x)
+ {
+ line = line.Remove(0, startLength);
+ string[] parts = line.Split(partsDelimiter);
+ if (parts.Length > 0)
+ {
+ string xVal = parts[0].Trim();
+ x = Convert.ToSingle(xVal, CultureInfo.InvariantCulture);
+ }
+ }
+
private static void GetParams(char[] partsDelimiter, ref string line, int startLength, ref float x, ref float y)
{
line = line.Remove(0, startLength);
diff --git a/OpenSim/Region/CoreModules/Scripting/WorldComm/WorldCommModule.cs b/OpenSim/Region/CoreModules/Scripting/WorldComm/WorldCommModule.cs
index 660e03f232..a5203ea750 100644
--- a/OpenSim/Region/CoreModules/Scripting/WorldComm/WorldCommModule.cs
+++ b/OpenSim/Region/CoreModules/Scripting/WorldComm/WorldCommModule.cs
@@ -113,7 +113,7 @@ namespace OpenSim.Region.CoreModules.Scripting.WorldComm
// wrap this in a try block so that defaults will work if
// the config file doesn't specify otherwise.
int maxlisteners = 1000;
- int maxhandles = 64;
+ int maxhandles = 65;
try
{
m_whisperdistance = config.Configs["Chat"].GetInt(
@@ -130,8 +130,15 @@ namespace OpenSim.Region.CoreModules.Scripting.WorldComm
catch (Exception)
{
}
- if (maxlisteners < 1) maxlisteners = int.MaxValue;
- if (maxhandles < 1) maxhandles = int.MaxValue;
+
+ if (maxlisteners < 1)
+ maxlisteners = int.MaxValue;
+ if (maxhandles < 1)
+ maxhandles = int.MaxValue;
+
+ if (maxlisteners < maxhandles)
+ maxlisteners = maxhandles;
+
m_listenerManager = new ListenerManager(maxlisteners, maxhandles);
m_pendingQ = new Queue();
m_pending = Queue.Synchronized(m_pendingQ);
@@ -605,11 +612,9 @@ namespace OpenSim.Region.CoreModules.Scripting.WorldComm
li.GetHandle().Equals(handle))
{
lis.Value.Remove(li);
+ m_curlisteners--;
if (lis.Value.Count == 0)
- {
- m_listeners.Remove(lis.Key);
- m_curlisteners--;
- }
+ m_listeners.Remove(lis.Key); // bailing of loop so this does not smoke
// there should be only one, so we bail out early
return;
}
@@ -718,6 +723,9 @@ namespace OpenSim.Region.CoreModules.Scripting.WorldComm
}
}
+ if(handles.Count >= m_maxhandles)
+ return -1;
+
// Note: 0 is NOT a valid handle for llListen() to return
for (int i = 1; i <= m_maxhandles; i++)
{
diff --git a/OpenSim/Region/CoreModules/Scripting/XMLRPC/XMLRPCModule.cs b/OpenSim/Region/CoreModules/Scripting/XMLRPC/XMLRPCModule.cs
index aed137231d..6028eefd37 100644
--- a/OpenSim/Region/CoreModules/Scripting/XMLRPC/XMLRPCModule.cs
+++ b/OpenSim/Region/CoreModules/Scripting/XMLRPC/XMLRPCModule.cs
@@ -658,7 +658,7 @@ namespace OpenSim.Region.CoreModules.Scripting.XMLRPC
public void Process()
{
_finished = false;
- httpThread = WorkManager.StartThread(SendRequest, "HttpRequestThread", ThreadPriority.BelowNormal, true, false);
+ httpThread = WorkManager.StartThread(SendRequest, "XMLRPCreqThread", ThreadPriority.BelowNormal, true, false, null, int.MaxValue);
}
/*
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Land/LandServiceInConnectorModule.cs b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Land/LandServiceInConnectorModule.cs
index 21483c5e9e..fb8c3065d8 100644
--- a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Land/LandServiceInConnectorModule.cs
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Land/LandServiceInConnectorModule.cs
@@ -151,7 +151,11 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsIn.Land
x = rx - s.RegionInfo.WorldLocX;
y = ry - s.RegionInfo.WorldLocY;
regionAccess = s.RegionInfo.AccessLevel;
- return s.GetLandData(x, y);
+ LandData land = s.GetLandData(x, y);
+ IDwellModule dwellModule = s.RequestModuleInterface();
+ if (dwellModule != null)
+ land.Dwell = dwellModule.GetDwell(land);
+ return land;
}
}
m_log.DebugFormat("[LAND IN CONNECTOR]: region handle {0} not found", regionHandle);
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsIn/UserProfiles/LocalUserProfilesServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsIn/UserProfiles/LocalUserProfilesServiceConnector.cs
index 9e75ee2259..2e6f472399 100644
--- a/OpenSim/Region/CoreModules/ServiceConnectorsIn/UserProfiles/LocalUserProfilesServiceConnector.cs
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsIn/UserProfiles/LocalUserProfilesServiceConnector.cs
@@ -85,12 +85,12 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Profile
public LocalUserProfilesServicesConnector()
{
- m_log.Debug("[LOCAL USERPROFILES SERVICE CONNECTOR]: LocalUserProfileServicesConnector no params");
+ //m_log.Debug("[LOCAL USERPROFILES SERVICE CONNECTOR]: LocalUserProfileServicesConnector no params");
}
public LocalUserProfilesServicesConnector(IConfigSource source)
{
- m_log.Debug("[LOCAL USERPROFILES SERVICE CONNECTOR]: LocalUserProfileServicesConnector instantiated directly.");
+ //m_log.Debug("[LOCAL USERPROFILES SERVICE CONNECTOR]: LocalUserProfileServicesConnector instantiated directly.");
InitialiseService(source);
}
@@ -104,7 +104,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Profile
IConfig config = source.Configs[ConfigName];
if (config == null)
{
- m_log.Error("[LOCAL USERPROFILES SERVICE CONNECTOR]: UserProfilesService missing from OpenSim.ini");
+ //m_log.Error("[LOCAL USERPROFILES SERVICE CONNECTOR]: UserProfilesService missing from OpenSim.ini");
return;
}
@@ -225,4 +225,4 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Profile
}
#endregion
}
-}
\ No newline at end of file
+}
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Asset/HGAssetBroker.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Asset/HGAssetBroker.cs
index f5aa9716d9..92ae36fbb6 100644
--- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Asset/HGAssetBroker.cs
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Asset/HGAssetBroker.cs
@@ -209,7 +209,8 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset
if (m_Cache != null)
{
- asset = m_Cache.Get(id);
+ if (!m_Cache.Get(id, out asset))
+ return null;
if (asset != null)
return asset;
@@ -238,10 +239,11 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset
public AssetBase GetCached(string id)
{
+ AssetBase asset = null;
if (m_Cache != null)
- return m_Cache.Get(id);
+ m_Cache.Get(id, out asset);
- return null;
+ return asset;
}
public AssetMetadata GetMetadata(string id)
@@ -250,8 +252,8 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset
if (m_Cache != null)
{
- if (m_Cache != null)
- m_Cache.Get(id);
+ if (!m_Cache.Get(id, out asset))
+ return null;
if (asset != null)
return asset.Metadata;
@@ -273,8 +275,8 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset
if (m_Cache != null)
{
- if (m_Cache != null)
- m_Cache.Get(id);
+ if (!m_Cache.Get(id, out asset))
+ return null;
if (asset != null)
return asset.Data;
@@ -292,7 +294,10 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset
AssetBase asset = null;
if (m_Cache != null)
- asset = m_Cache.Get(id);
+ {
+ if (!m_Cache.Get(id, out asset))
+ return false;
+ }
if (asset != null)
{
@@ -382,7 +387,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset
AssetBase asset = null;
if (m_Cache != null)
- asset = m_Cache.Get(id);
+ m_Cache.Get(id, out asset);
if (asset != null)
{
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Asset/LocalAssetServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Asset/LocalAssetServiceConnector.cs
index 7190aa09ed..37a48bb752 100644
--- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Asset/LocalAssetServiceConnector.cs
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Asset/LocalAssetServiceConnector.cs
@@ -158,7 +158,10 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset
AssetBase asset = null;
if (m_Cache != null)
- asset = m_Cache.Get(id);
+ {
+ if (!m_Cache.Get(id, out asset))
+ return null;
+ }
if (asset == null)
{
@@ -177,17 +180,21 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset
{
// m_log.DebugFormat("[LOCAL ASSET SERVICES CONNECTOR]: Cache request for {0}", id);
+ AssetBase asset = null;
if (m_Cache != null)
- return m_Cache.Get(id);
+ m_Cache.Get(id, out asset);
- return null;
+ return asset;
}
public AssetMetadata GetMetadata(string id)
{
AssetBase asset = null;
if (m_Cache != null)
- asset = m_Cache.Get(id);
+ {
+ if (!m_Cache.Get(id, out asset))
+ return null;
+ }
if (asset != null)
return asset.Metadata;
@@ -210,7 +217,10 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset
AssetBase asset = null;
if (m_Cache != null)
- asset = m_Cache.Get(id);
+ {
+ if (!m_Cache.Get(id, out asset))
+ return null;
+ }
if (asset != null)
return asset.Data;
@@ -232,7 +242,9 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset
if (m_Cache != null)
{
- AssetBase asset = m_Cache.Get(id);
+ AssetBase asset;
+ if (!m_Cache.Get(id, out asset))
+ return false;
if (asset != null)
{
@@ -287,7 +299,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset
{
AssetBase asset = null;
if (m_Cache != null)
- m_Cache.Get(id);
+ m_Cache.Get(id, out asset);
if (asset != null)
{
asset.Data = data;
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/RegionInfoCache.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/RegionInfoCache.cs
index 84e52f7602..f6fff58aef 100644
--- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/RegionInfoCache.cs
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/RegionInfoCache.cs
@@ -385,7 +385,6 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
storage[handle] = region;
byname[region.RegionName] = handle;
byuuid[region.RegionID] = handle;
-
}
public void Remove(GridRegion region)
@@ -400,7 +399,13 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
ulong handle = region.RegionHandle & HANDLEMASK;
if(storage != null)
- storage.Remove(handle);
+ {
+ if(storage.ContainsKey(handle))
+ {
+ storage[handle] = null;
+ storage.Remove(handle);
+ }
+ }
removeFromInner(region);
if(expires != null)
{
@@ -424,6 +429,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
if(byuuid != null)
byuuid.Remove(r.RegionID);
removeFromInner(r);
+ storage[handle] = null;
}
storage.Remove(handle);
}
@@ -581,27 +587,32 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
{
if(expires == null || expires.Count == 0)
return 0;
-
+
+ int expiresCount = expires.Count;
List toexpire = new List();
+
foreach(KeyValuePair kvp in expires)
{
if(kvp.Value < now)
toexpire.Add(kvp.Key);
}
- if(toexpire.Count == 0)
- return expires.Count;
+ int toexpireCount = toexpire.Count;
+ if(toexpireCount == 0)
+ return expiresCount;
- if(toexpire.Count == expires.Count)
+ if(toexpireCount == expiresCount)
{
Clear();
return 0;
}
- foreach(ulong h in toexpire)
+ if(storage != null)
{
- if(storage != null)
+ ulong h;
+ for(int i = 0; i < toexpireCount; i++)
{
+ h = toexpire[i];
if(storage.ContainsKey(h))
{
GridRegion r = storage[h];
@@ -610,14 +621,22 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
if(byuuid != null)
byuuid.Remove(r.RegionID);
removeFromInner(r);
+
+ storage[h] = null;
+ storage.Remove(h);
}
- storage.Remove(h);
+ if(expires != null)
+ expires.Remove(h);
}
- if(expires != null)
- expires.Remove(h);
+ }
+ else
+ {
+ Clear();
+ return 0;
}
- if(expires.Count == 0)
+ expiresCount = expires.Count;
+ if(expiresCount == 0)
{
byname = null;
byuuid = null;
@@ -626,7 +645,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
return 0;
}
- return expires.Count;
+ return expiresCount;
}
public int Count()
@@ -693,7 +712,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
public class RegionsExpiringCache
{
- const double CACHE_PURGE_HZ = 60; // seconds
+ const double CACHE_PURGE_TIME = 60000; // milliseconds
const int MAX_LOCK_WAIT = 10000; // milliseconds
/// For thread safety
@@ -702,7 +721,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
object isPurging = new object();
Dictionary InfobyScope = new Dictionary();
- private System.Timers.Timer timer = new System.Timers.Timer(TimeSpan.FromSeconds(CACHE_PURGE_HZ).TotalMilliseconds);
+ private System.Timers.Timer timer = new System.Timers.Timer(CACHE_PURGE_TIME);
public RegionsExpiringCache()
{
@@ -965,7 +984,10 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
if (expiredscopes.Count > 0)
{
foreach (UUID sid in expiredscopes)
+ {
+ InfobyScope[sid] = null;
InfobyScope.Remove(sid);
+ }
}
}
finally { Monitor.Exit(syncRoot); }
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/HGInventoryBroker.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/HGInventoryBroker.cs
index 5efdd9b7cf..7a4f981da6 100644
--- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/HGInventoryBroker.cs
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/HGInventoryBroker.cs
@@ -250,7 +250,8 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
if (inventoryURL != null && inventoryURL != string.Empty)
{
inventoryURL = inventoryURL.Trim(new char[] { '/' });
- m_InventoryURLs[userID] = inventoryURL;
+ lock (m_InventoryURLs)
+ m_InventoryURLs[userID] = inventoryURL;
m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Added {0} to the cache of inventory URLs", inventoryURL);
return;
}
@@ -268,35 +269,42 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
if (!string.IsNullOrEmpty(inventoryURL))
{
inventoryURL = inventoryURL.Trim(new char[] { '/' });
- m_InventoryURLs.Add(userID, inventoryURL);
+ lock (m_InventoryURLs)
+ m_InventoryURLs[userID] = inventoryURL;
m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Added {0} to the cache of inventory URLs", inventoryURL);
}
-
}
-
}
}
private void DropInventoryServiceURL(UUID userID)
{
lock (m_InventoryURLs)
+ {
if (m_InventoryURLs.ContainsKey(userID))
{
string url = m_InventoryURLs[userID];
m_InventoryURLs.Remove(userID);
m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Removed {0} from the cache of inventory URLs", url);
}
+ }
}
public string GetInventoryServiceURL(UUID userID)
{
- if (m_InventoryURLs.ContainsKey(userID))
- return m_InventoryURLs[userID];
+ lock (m_InventoryURLs)
+ {
+ if (m_InventoryURLs.ContainsKey(userID))
+ return m_InventoryURLs[userID];
+ }
CacheInventoryServiceURL(userID);
- if (m_InventoryURLs.ContainsKey(userID))
- return m_InventoryURLs[userID];
+ lock (m_InventoryURLs)
+ {
+ if (m_InventoryURLs.ContainsKey(userID))
+ return m_InventoryURLs[userID];
+ }
return null; //it means that the methods should forward to local grid's inventory
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Land/LocalLandServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Land/LocalLandServiceConnector.cs
index cad2061946..8baf41a3d9 100644
--- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Land/LocalLandServiceConnector.cs
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Land/LocalLandServiceConnector.cs
@@ -143,6 +143,10 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Land
{
LandData land = s.GetLandData(x, y);
regionAccess = s.RegionInfo.AccessLevel;
+ IDwellModule dwellModule = s.RequestModuleInterface();
+ if (dwellModule != null)
+ land.Dwell = dwellModule.GetDwell(land);
+
return land;
}
}
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Neighbour/LocalNeighbourServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Neighbour/NeighbourServiceOutConnector.cs
similarity index 72%
rename from OpenSim/Region/CoreModules/ServiceConnectorsOut/Neighbour/LocalNeighbourServiceConnector.cs
rename to OpenSim/Region/CoreModules/ServiceConnectorsOut/Neighbour/NeighbourServiceOutConnector.cs
index e8d01b01c1..60addec12c 100644
--- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Neighbour/LocalNeighbourServiceConnector.cs
+++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Neighbour/NeighbourServiceOutConnector.cs
@@ -25,44 +25,32 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-using System;
-using System.Collections.Generic;
-using System.Reflection;
using log4net;
using Mono.Addins;
+using System;
+using System.Reflection;
+using System.Collections.Generic;
using Nini.Config;
-using OpenMetaverse;
using OpenSim.Framework;
-using OpenSim.Server.Base;
+using OpenSim.Services.Connectors;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
+
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Neighbour
{
- [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "LocalNeighbourServicesConnector")]
- public class LocalNeighbourServicesConnector :
- ISharedRegionModule, INeighbourService
+ [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "NeighbourServicesOutConnector")]
+ public class NeighbourServicesOutConnector :
+ NeighbourServicesConnector, ISharedRegionModule, INeighbourService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private List m_Scenes = new List();
-
private bool m_Enabled = false;
- public LocalNeighbourServicesConnector()
- {
- }
-
- public LocalNeighbourServicesConnector(List scenes)
- {
- m_Scenes = scenes;
- }
-
- #region ISharedRegionModule
-
public Type ReplaceableInterface
{
get { return null; }
@@ -70,7 +58,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Neighbour
public string Name
{
- get { return "LocalNeighbourServicesConnector"; }
+ get { return "NeighbourServicesOutConnector"; }
}
public void Initialise(IConfigSource source)
@@ -78,39 +66,32 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Neighbour
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
- string name = moduleConfig.GetString("NeighbourServices", this.Name);
+ string name = moduleConfig.GetString("NeighbourServices");
if (name == Name)
{
- // m_Enabled rules whether this module registers as INeighbourService or not
m_Enabled = true;
- m_log.Info("[NEIGHBOUR CONNECTOR]: Local neighbour connector enabled");
+ m_log.Info("[NEIGHBOUR CONNECTOR]: Neighbour out connector enabled");
}
}
}
+ public void PostInitialise()
+ {
+ }
+
public void Close()
{
}
public void AddRegion(Scene scene)
{
- m_Scenes.Add(scene);
-
if (!m_Enabled)
return;
+ m_Scenes.Add(scene);
scene.RegisterModuleInterface(this);
}
- public void RegionLoaded(Scene scene)
- {
- m_log.Info("[NEIGHBOUR CONNECTOR]: Local neighbour connector enabled for region " + scene.RegionInfo.RegionName);
- }
-
- public void PostInitialise()
- {
- }
-
public void RemoveRegion(Scene scene)
{
// Always remove
@@ -118,28 +99,36 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Neighbour
m_Scenes.Remove(scene);
}
- #endregion ISharedRegionModule
+ public void RegionLoaded(Scene scene)
+ {
+ if (!m_Enabled)
+ return;
+
+ m_GridService = scene.GridService;
+ m_log.InfoFormat("[NEIGHBOUR CONNECTOR]: Enabled out neighbours for region {0}", scene.RegionInfo.RegionName);
+
+ }
#region INeighbourService
- public OpenSim.Services.Interfaces.GridRegion HelloNeighbour(ulong regionHandle, RegionInfo thisRegion)
+ public override GridRegion HelloNeighbour(ulong regionHandle, RegionInfo thisRegion)
{
- uint x, y;
- Util.RegionHandleToRegionLoc(regionHandle, out x, out y);
+ if (!m_Enabled)
+ return null;
foreach (Scene s in m_Scenes)
{
if (s.RegionInfo.RegionHandle == regionHandle)
{
- m_log.DebugFormat("[LOCAL NEIGHBOUR SERVICE CONNECTOR]: HelloNeighbour from region {0} to neighbour {1} at {2}-{3}",
- thisRegion.RegionName, s.Name, x, y );
-
- //m_log.Debug("[NEIGHBOUR CONNECTOR]: Found region to SendHelloNeighbour");
+// uint x, y;
+// Util.RegionHandleToRegionLoc(regionHandle, out x, out y);
+// m_log.DebugFormat("[NEIGHBOUR SERVICE OUT CONNECTOR]: HelloNeighbour from region {0} to neighbour {1} at {2}-{3}",
+// thisRegion.RegionName, s.Name, x, y );
return s.IncomingHelloNeighbour(thisRegion);
}
}
- //m_log.DebugFormat("[NEIGHBOUR CONNECTOR]: region handle {0} not found", regionHandle);
- return null;
+
+ return base.HelloNeighbour(regionHandle, thisRegion);
}
#endregion INeighbourService
diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Neighbour/RemoteNeighourServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Neighbour/RemoteNeighourServiceConnector.cs
deleted file mode 100644
index fcb55216ec..0000000000
--- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Neighbour/RemoteNeighourServiceConnector.cs
+++ /dev/null
@@ -1,157 +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 log4net;
-using Mono.Addins;
-using System;
-using System.Collections.Generic;
-using System.Reflection;
-using Nini.Config;
-using OpenSim.Framework;
-using OpenSim.Services.Connectors;
-using OpenSim.Region.Framework.Interfaces;
-using OpenSim.Region.Framework.Scenes;
-using OpenSim.Services.Interfaces;
-using OpenSim.Server.Base;
-
-namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Neighbour
-{
- [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "RemoteNeighbourServicesConnector")]
- public class RemoteNeighbourServicesConnector :
- NeighbourServicesConnector, ISharedRegionModule, INeighbourService
- {
- private static readonly ILog m_log =
- LogManager.GetLogger(
- MethodBase.GetCurrentMethod().DeclaringType);
-
- private bool m_Enabled = false;
- private LocalNeighbourServicesConnector m_LocalService;
- //private string serviceDll;
- //private List m_Scenes = new List();
-
- public Type ReplaceableInterface
- {
- get { return null; }
- }
-
- public string Name
- {
- get { return "RemoteNeighbourServicesConnector"; }
- }
-
- public void Initialise(IConfigSource source)
- {
- IConfig moduleConfig = source.Configs["Modules"];
- if (moduleConfig != null)
- {
- string name = moduleConfig.GetString("NeighbourServices");
- if (name == Name)
- {
- m_LocalService = new LocalNeighbourServicesConnector();
-
- //IConfig neighbourConfig = source.Configs["NeighbourService"];
- //if (neighbourConfig == null)
- //{
- // m_log.Error("[NEIGHBOUR CONNECTOR]: NeighbourService missing from OpenSim.ini");
- // return;
- //}
- //serviceDll = neighbourConfig.GetString("LocalServiceModule", String.Empty);
- //if (serviceDll == String.Empty)
- //{
- // m_log.Error("[NEIGHBOUR CONNECTOR]: No LocalServiceModule named in section NeighbourService");
- // return;
- //}
-
- m_Enabled = true;
-
- m_log.Info("[NEIGHBOUR CONNECTOR]: Remote Neighbour connector enabled");
- }
- }
- }
-
- public void PostInitialise()
- {
- //if (m_Enabled)
- //{
- // Object[] args = new Object[] { m_Scenes };
- // m_LocalService =
- // ServerUtils.LoadPlugin(serviceDll,
- // args);
-
- // if (m_LocalService == null)
- // {
- // m_log.Error("[NEIGHBOUR CONNECTOR]: Can't load neighbour service");
- // Unregister();
- // return;
- // }
- //}
- }
-
- public void Close()
- {
- }
-
- public void AddRegion(Scene scene)
- {
- if (!m_Enabled)
- return;
-
- m_LocalService.AddRegion(scene);
- scene.RegisterModuleInterface(this);
- }
-
- public void RemoveRegion(Scene scene)
- {
- if (m_Enabled)
- m_LocalService.RemoveRegion(scene);
- }
-
- public void RegionLoaded(Scene scene)
- {
- if (!m_Enabled)
- return;
-
- m_GridService = scene.GridService;
-
- m_log.InfoFormat("[NEIGHBOUR CONNECTOR]: Enabled remote neighbours for region {0}", scene.RegionInfo.RegionName);
-
- }
-
- #region INeighbourService
-
- public override GridRegion HelloNeighbour(ulong regionHandle, RegionInfo thisRegion)
- {
- GridRegion region = m_LocalService.HelloNeighbour(regionHandle, thisRegion);
- if (region != null)
- return region;
-
- return base.HelloNeighbour(regionHandle, thisRegion);
- }
-
- #endregion INeighbourService
- }
-}
diff --git a/OpenSim/Region/CoreModules/World/Archiver/ArchiveReadRequest.cs b/OpenSim/Region/CoreModules/World/Archiver/ArchiveReadRequest.cs
index 6ba8cec22f..99ff9b5ac4 100644
--- a/OpenSim/Region/CoreModules/World/Archiver/ArchiveReadRequest.cs
+++ b/OpenSim/Region/CoreModules/World/Archiver/ArchiveReadRequest.cs
@@ -285,6 +285,11 @@ namespace OpenSim.Region.CoreModules.World.Archiver
/// Dearchive the region embodied in this request.
///
public void DearchiveRegion()
+ {
+ DearchiveRegion(true);
+ }
+
+ public void DearchiveRegion(bool shouldStartScripts)
{
int successfulAssetRestores = 0;
int failedAssetRestores = 0;
@@ -425,22 +430,25 @@ namespace OpenSim.Region.CoreModules.World.Archiver
// Start the scripts. We delayed this because we want the OAR to finish loading ASAP, so
// that users can enter the scene. If we allow the scripts to start in the loop above
// then they significantly increase the time until the OAR finishes loading.
- WorkManager.RunInThread(o =>
+ if (shouldStartScripts)
{
- Thread.Sleep(15000);
- m_log.Info("[ARCHIVER]: Starting scripts in scene objects");
-
- foreach (DearchiveContext sceneContext in sceneContexts.Values)
+ WorkManager.RunInThread(o =>
{
- foreach (SceneObjectGroup sceneObject in sceneContext.SceneObjects)
- {
- sceneObject.CreateScriptInstances(0, false, sceneContext.Scene.DefaultScriptEngine, 0); // StateSource.RegionStart
- sceneObject.ResumeScripts();
- }
+ Thread.Sleep(15000);
+ m_log.Info("[ARCHIVER]: Starting scripts in scene objects");
- sceneContext.SceneObjects.Clear();
- }
- }, null, string.Format("ReadArchiveStartScripts (request {0})", m_requestId));
+ foreach (DearchiveContext sceneContext in sceneContexts.Values)
+ {
+ foreach (SceneObjectGroup sceneObject in sceneContext.SceneObjects)
+ {
+ sceneObject.CreateScriptInstances(0, false, sceneContext.Scene.DefaultScriptEngine, 0); // StateSource.RegionStart
+ sceneObject.ResumeScripts();
+ }
+
+ sceneContext.SceneObjects.Clear();
+ }
+ }, null, string.Format("ReadArchiveStartScripts (request {0})", m_requestId));
+ }
m_log.InfoFormat("[ARCHIVER]: Successfully loaded archive");
diff --git a/OpenSim/Region/CoreModules/World/Archiver/ArchiveWriteRequest.cs b/OpenSim/Region/CoreModules/World/Archiver/ArchiveWriteRequest.cs
index 8dabceeba7..11c53d75d0 100644
--- a/OpenSim/Region/CoreModules/World/Archiver/ArchiveWriteRequest.cs
+++ b/OpenSim/Region/CoreModules/World/Archiver/ArchiveWriteRequest.cs
@@ -181,11 +181,13 @@ namespace OpenSim.Region.CoreModules.World.Archiver
// Archive the regions
Dictionary assetUuids = new Dictionary();
+ HashSet failedIDs = new HashSet();
+ HashSet uncertainAssetsUUIDs = new HashSet();
scenesGroup.ForEachScene(delegate(Scene scene)
{
string regionDir = MultiRegionFormat ? scenesGroup.GetRegionDir(scene.RegionInfo.RegionID) : "";
- ArchiveOneRegion(scene, regionDir, assetUuids);
+ ArchiveOneRegion(scene, regionDir, assetUuids, failedIDs, uncertainAssetsUUIDs);
});
// Archive the assets
@@ -193,23 +195,21 @@ namespace OpenSim.Region.CoreModules.World.Archiver
if (SaveAssets)
{
m_log.DebugFormat("[ARCHIVER]: Saving {0} assets", assetUuids.Count);
-
- // Asynchronously request all the assets required to perform this archive operation
- AssetsRequest ar
- = new AssetsRequest(
+
+ AssetsRequest ar = new AssetsRequest(
new AssetsArchiver(m_archiveWriter), assetUuids,
+ failedIDs.Count,
m_rootScene.AssetService, m_rootScene.UserAccountService,
- m_rootScene.RegionInfo.ScopeID, options, ReceivedAllAssets);
-
- WorkManager.RunInThread(o => ar.Execute(), null, "Archive Assets Request");
-
- // CloseArchive() will be called from ReceivedAllAssets()
+ m_rootScene.RegionInfo.ScopeID, options, null);
+ ar.Execute();
+ assetUuids = null;
}
else
{
m_log.DebugFormat("[ARCHIVER]: Not saving assets since --noassets was specified");
- CloseArchive(string.Empty);
+// CloseArchive(string.Empty);
}
+ CloseArchive(string.Empty);
}
catch (Exception e)
{
@@ -218,7 +218,8 @@ namespace OpenSim.Region.CoreModules.World.Archiver
}
}
- private void ArchiveOneRegion(Scene scene, string regionDir, Dictionary assetUuids)
+ private void ArchiveOneRegion(Scene scene, string regionDir, Dictionary assetUuids,
+ HashSet failedIDs, HashSet uncertainAssetsUUIDs)
{
m_log.InfoFormat("[ARCHIVER]: Writing region {0}", scene.Name);
@@ -237,7 +238,7 @@ namespace OpenSim.Region.CoreModules.World.Archiver
{
SceneObjectGroup sceneObject = (SceneObjectGroup)entity;
- if (!sceneObject.IsDeleted && !sceneObject.IsAttachment)
+ if (!sceneObject.IsDeleted && !sceneObject.IsAttachment && !sceneObject.IsTemporary && !sceneObject.inTransit)
{
if (!CanUserArchiveObject(scene.RegionInfo.EstateSettings.EstateOwner, sceneObject, FilterContent, permissionsModule))
{
@@ -254,17 +255,39 @@ namespace OpenSim.Region.CoreModules.World.Archiver
if (SaveAssets)
{
- UuidGatherer assetGatherer = new UuidGatherer(scene.AssetService, assetUuids);
+ UuidGatherer assetGatherer = new UuidGatherer(scene.AssetService, assetUuids, failedIDs, uncertainAssetsUUIDs);
int prevAssets = assetUuids.Count;
foreach (SceneObjectGroup sceneObject in sceneObjects)
+ {
+ int curErrorCntr = assetGatherer.ErrorCount;
+ int possible = assetGatherer.possibleNotAssetCount;
assetGatherer.AddForInspection(sceneObject);
+ assetGatherer.GatherAll();
+ curErrorCntr = assetGatherer.ErrorCount - curErrorCntr;
+ possible = assetGatherer.possibleNotAssetCount - possible;
+ if(curErrorCntr > 0)
+ {
+ m_log.ErrorFormat("[ARCHIVER]: object {0} '{1}', at {2}, contains {3} references to missing or damaged assets",
+ sceneObject.UUID, sceneObject.Name ,sceneObject.AbsolutePosition.ToString(), curErrorCntr);
+ if(possible > 0)
+ m_log.WarnFormat("[ARCHIVER Warning]: object also contains {0} references that may be to missing or damaged assets or not a problem", possible);
+ }
+ else if(possible > 0)
+ {
+ m_log.WarnFormat("[ARCHIVER Warning]: object {0} '{1}', at {2}, contains {3} references that may be to missing or damaged assets or not a problem",
+ sceneObject.UUID, sceneObject.Name ,sceneObject.AbsolutePosition.ToString(), possible);
+ }
+ }
assetGatherer.GatherAll();
+ int errors = assetGatherer.FailedUUIDs.Count;
m_log.DebugFormat(
- "[ARCHIVER]: {0} scene objects to serialize requiring save of {1} assets",
- sceneObjects.Count, assetUuids.Count - prevAssets);
+ "[ARCHIVER]: {0} region scene objects to save reference {1} possible assets",
+ sceneObjects.Count, assetUuids.Count - prevAssets + errors);
+ if(errors > 0)
+ m_log.DebugFormat("[ARCHIVER]: {0} of these have problems or are not assets and will be ignored", errors);
}
if (numObjectsSkippedPermissions > 0)
@@ -572,7 +595,8 @@ namespace OpenSim.Region.CoreModules.World.Archiver
foreach (SceneObjectGroup sceneObject in sceneObjects)
{
//m_log.DebugFormat("[ARCHIVER]: Saving {0} {1}, {2}", entity.Name, entity.UUID, entity.GetType());
-
+ if(sceneObject.IsDeleted || sceneObject.inTransit)
+ continue;
string serializedObject = serializer.SerializeGroupToXml2(sceneObject, m_options);
string objectPath = string.Format("{0}{1}", regionDir, ArchiveHelpers.CreateObjectPath(sceneObject));
m_archiveWriter.WriteFile(objectPath, serializedObject);
diff --git a/OpenSim/Region/CoreModules/World/Archiver/AssetsArchiver.cs b/OpenSim/Region/CoreModules/World/Archiver/AssetsArchiver.cs
index efacae372f..3092fe0a8d 100644
--- a/OpenSim/Region/CoreModules/World/Archiver/AssetsArchiver.cs
+++ b/OpenSim/Region/CoreModules/World/Archiver/AssetsArchiver.cs
@@ -46,7 +46,7 @@ namespace OpenSim.Region.CoreModules.World.Archiver
///
/// Post a message to the log every x assets as a progress bar
///
- protected static int LOG_ASSET_LOAD_NOTIFICATION_INTERVAL = 50;
+ protected static int LOG_ASSET_LOAD_NOTIFICATION_INTERVAL = 100;
///
/// Keep a count of the number of assets written so that we can provide status updates
diff --git a/OpenSim/Region/CoreModules/World/Archiver/AssetsRequest.cs b/OpenSim/Region/CoreModules/World/Archiver/AssetsRequest.cs
index d380da8d8a..91f4dc354f 100644
--- a/OpenSim/Region/CoreModules/World/Archiver/AssetsRequest.cs
+++ b/OpenSim/Region/CoreModules/World/Archiver/AssetsRequest.cs
@@ -61,28 +61,11 @@ namespace OpenSim.Region.CoreModules.World.Archiver
Aborted
};
- ///
- /// Timeout threshold if we still need assets or missing asset notifications but have stopped receiving them
- /// from the asset service
- ///
- protected const int TIMEOUT = 60 * 1000;
-
- ///
- /// If a timeout does occur, limit the amount of UUID information put to the console.
- ///
- protected const int MAX_UUID_DISPLAY_ON_TIMEOUT = 3;
-
- protected System.Timers.Timer m_requestCallbackTimer;
-
- ///
- /// State of this request
- ///
- private RequestState m_requestState = RequestState.Initial;
-
///
/// uuids to request
///
protected IDictionary m_uuids;
+ private int m_previousErrorsCount;
///
/// Callback used when all the assets requested have been received.
@@ -104,6 +87,9 @@ namespace OpenSim.Region.CoreModules.World.Archiver
///
private int m_repliesRequired;
+ private System.Timers.Timer m_timeOutTimer;
+ private bool m_timeout;
+
///
/// Asset service used to request the assets
///
@@ -117,205 +103,98 @@ namespace OpenSim.Region.CoreModules.World.Archiver
protected internal AssetsRequest(
AssetsArchiver assetsArchiver, IDictionary uuids,
+ int previousErrorsCount,
IAssetService assetService, IUserAccountService userService,
UUID scope, Dictionary options,
AssetsRequestCallback assetsRequestCallback)
{
m_assetsArchiver = assetsArchiver;
m_uuids = uuids;
+ m_previousErrorsCount = previousErrorsCount;
m_assetsRequestCallback = assetsRequestCallback;
m_assetService = assetService;
m_userAccountService = userService;
m_scopeID = scope;
m_options = options;
m_repliesRequired = uuids.Count;
-
- // FIXME: This is a really poor way of handling the timeout since it will always leave the original requesting thread
- // hanging. Need to restructure so an original request thread waits for a ManualResetEvent on asset received
- // so we can properly abort that thread. Or request all assets synchronously, though that would be a more
- // radical change
- m_requestCallbackTimer = new System.Timers.Timer(TIMEOUT);
- m_requestCallbackTimer.AutoReset = false;
- m_requestCallbackTimer.Elapsed += new ElapsedEventHandler(OnRequestCallbackTimeout);
}
protected internal void Execute()
{
- m_requestState = RequestState.Running;
-
- m_log.DebugFormat("[ARCHIVER]: AssetsRequest executed looking for {0} possible assets", m_repliesRequired);
-
+ Culture.SetCurrentCulture();
// We can stop here if there are no assets to fetch
if (m_repliesRequired == 0)
{
- m_requestState = RequestState.Completed;
PerformAssetsRequestCallback(false);
return;
}
- m_requestCallbackTimer.Enabled = true;
+ m_timeOutTimer = new System.Timers.Timer(60000);
+ m_timeOutTimer .AutoReset = false;
+ m_timeOutTimer.Elapsed += OnTimeout;
+ m_timeout = false;
foreach (KeyValuePair kvp in m_uuids)
{
-// m_log.DebugFormat("[ARCHIVER]: Requesting asset {0}", kvp.Key);
-
-// m_assetService.Get(kvp.Key.ToString(), kvp.Value, PreAssetRequestCallback);
- AssetBase asset = m_assetService.Get(kvp.Key.ToString());
- PreAssetRequestCallback(kvp.Key.ToString(), kvp.Value, asset);
- }
- }
-
- protected void OnRequestCallbackTimeout(object source, ElapsedEventArgs args)
- {
- bool timedOut = true;
-
- try
- {
- lock (this)
+ string thiskey = kvp.Key.ToString();
+ try
{
- // Take care of the possibilty that this thread started but was paused just outside the lock before
- // the final request came in (assuming that such a thing is possible)
- if (m_requestState == RequestState.Completed)
- {
- timedOut = false;
- return;
- }
-
- m_requestState = RequestState.Aborted;
- }
-
- // Calculate which uuids were not found. This is an expensive way of doing it, but this is a failure
- // case anyway.
- List uuids = new List();
- foreach (UUID uuid in m_uuids.Keys)
- {
- uuids.Add(uuid);
- }
-
- foreach (UUID uuid in m_foundAssetUuids)
- {
- uuids.Remove(uuid);
- }
-
- foreach (UUID uuid in m_notFoundAssetUuids)
- {
- uuids.Remove(uuid);
- }
-
- m_log.ErrorFormat(
- "[ARCHIVER]: Asset service failed to return information about {0} requested assets", uuids.Count);
-
- int i = 0;
- foreach (UUID uuid in uuids)
- {
- m_log.ErrorFormat("[ARCHIVER]: No information about asset {0} received", uuid);
-
- if (++i >= MAX_UUID_DISPLAY_ON_TIMEOUT)
+ m_timeOutTimer.Enabled = true;
+ AssetBase asset = m_assetService.Get(thiskey);
+ if(m_timeout)
break;
+
+ m_timeOutTimer.Enabled = false;
+
+ if(asset == null)
+ {
+ m_notFoundAssetUuids.Add(new UUID(thiskey));
+ continue;
+ }
+
+ sbyte assetType = kvp.Value;
+ if (asset != null && assetType == (sbyte)AssetType.Unknown)
+ {
+ m_log.InfoFormat("[ARCHIVER]: Rewriting broken asset type for {0} to {1}", thiskey, SLUtil.AssetTypeFromCode(assetType));
+ asset.Type = assetType;
+ }
+
+ m_foundAssetUuids.Add(asset.FullID);
+ m_assetsArchiver.WriteAsset(PostProcess(asset));
}
- if (uuids.Count > MAX_UUID_DISPLAY_ON_TIMEOUT)
- m_log.ErrorFormat(
- "[ARCHIVER]: (... {0} more not shown)", uuids.Count - MAX_UUID_DISPLAY_ON_TIMEOUT);
-
- m_log.Error("[ARCHIVER]: Archive save aborted. PLEASE DO NOT USE THIS ARCHIVE, IT WILL BE INCOMPLETE.");
- }
- catch (Exception e)
- {
- m_log.ErrorFormat("[ARCHIVER]: Timeout handler exception {0}{1}", e.Message, e.StackTrace);
- }
- finally
- {
- if (timedOut)
- WorkManager.RunInThread(PerformAssetsRequestCallback, true, "Archive Assets Request Callback");
- }
- }
-
- protected void PreAssetRequestCallback(string fetchedAssetID, object assetType, AssetBase fetchedAsset)
- {
- // Check for broken asset types and fix them with the AssetType gleaned by UuidGatherer
- if (fetchedAsset != null && fetchedAsset.Type == (sbyte)AssetType.Unknown)
- {
- m_log.InfoFormat("[ARCHIVER]: Rewriting broken asset type for {0} to {1}", fetchedAsset.ID, SLUtil.AssetTypeFromCode((sbyte)assetType));
- fetchedAsset.Type = (sbyte)assetType;
- }
-
- AssetRequestCallback(fetchedAssetID, this, fetchedAsset);
- }
-
- ///
- /// Called back by the asset cache when it has the asset
- ///
- ///
- ///
- public void AssetRequestCallback(string id, object sender, AssetBase asset)
- {
- Culture.SetCurrentCulture();
-
- try
- {
- lock (this)
+ catch (Exception e)
{
- //m_log.DebugFormat("[ARCHIVER]: Received callback for asset {0}", id);
-
- m_requestCallbackTimer.Stop();
-
- if ((m_requestState == RequestState.Aborted) || (m_requestState == RequestState.Completed))
- {
- m_log.WarnFormat(
- "[ARCHIVER]: Received information about asset {0} while in state {1}. Ignoring.",
- id, m_requestState);
-
- return;
- }
-
- if (asset != null)
- {
-// m_log.DebugFormat("[ARCHIVER]: Writing asset {0}", id);
- m_foundAssetUuids.Add(asset.FullID);
-
- m_assetsArchiver.WriteAsset(PostProcess(asset));
- }
- else
- {
-// m_log.DebugFormat("[ARCHIVER]: Recording asset {0} as not found", id);
- m_notFoundAssetUuids.Add(new UUID(id));
- }
-
- if (m_foundAssetUuids.Count + m_notFoundAssetUuids.Count >= m_repliesRequired)
- {
- m_requestState = RequestState.Completed;
- if(m_notFoundAssetUuids.Count == 0)
- m_log.DebugFormat(
- "[ARCHIVER]: Successfully added {0} assets",
- m_foundAssetUuids.Count);
- else
- m_log.DebugFormat(
- "[ARCHIVER]: Successfully added {0} assets ({1} assets not found but these may be expected invalid references)",
- m_foundAssetUuids.Count, m_notFoundAssetUuids.Count);
-
-
- // We want to stop using the asset cache thread asap
- // as we now need to do the work of producing the rest of the archive
- WorkManager.RunInThread(PerformAssetsRequestCallback, false, "Archive Assets Request Callback");
- }
- else
- {
- m_requestCallbackTimer.Start();
- }
+ m_log.ErrorFormat("[ARCHIVER]: Execute failed with {0}", e);
}
}
- catch (Exception e)
- {
- m_log.ErrorFormat("[ARCHIVER]: AssetRequestCallback failed with {0}", e);
- }
+
+ m_timeOutTimer.Dispose();
+ int totalerrors = m_notFoundAssetUuids.Count + m_previousErrorsCount;
+
+ if(m_timeout)
+ m_log.DebugFormat("[ARCHIVER]: Aborted because AssetService request timeout. Successfully added {0} assets", m_foundAssetUuids.Count);
+ else if(totalerrors == 0)
+ m_log.DebugFormat("[ARCHIVER]: Successfully added all {0} assets", m_foundAssetUuids.Count);
+ else
+ m_log.DebugFormat("[ARCHIVER]: Successfully added {0} assets ({1} of total possible assets requested were not found, were damaged or were not assets)",
+ m_foundAssetUuids.Count, totalerrors);
+
+ PerformAssetsRequestCallback(m_timeout);
+ }
+
+ private void OnTimeout(object source, ElapsedEventArgs args)
+ {
+ m_timeout = true;
}
///
/// Perform the callback on the original requester of the assets
///
- protected void PerformAssetsRequestCallback(object o)
+ private void PerformAssetsRequestCallback(object o)
{
+ if(m_assetsRequestCallback == null)
+ return;
Culture.SetCurrentCulture();
Boolean timedOut = (Boolean)o;
@@ -331,7 +210,7 @@ namespace OpenSim.Region.CoreModules.World.Archiver
}
}
- protected AssetBase PostProcess(AssetBase asset)
+ private AssetBase PostProcess(AssetBase asset)
{
if (asset.Type == (sbyte)AssetType.Object && asset.Data != null && m_options.ContainsKey("home"))
{
diff --git a/OpenSim/Region/CoreModules/World/Estate/EstateRequestHandler.cs b/OpenSim/Region/CoreModules/World/Estate/EstateRequestHandler.cs
index 7ab92d1a47..5eda8ab02b 100644
--- a/OpenSim/Region/CoreModules/World/Estate/EstateRequestHandler.cs
+++ b/OpenSim/Region/CoreModules/World/Estate/EstateRequestHandler.cs
@@ -60,9 +60,10 @@ namespace OpenSim.Region.CoreModules.World.Estate
protected override byte[] ProcessRequest(string path, Stream requestData,
IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
- StreamReader sr = new StreamReader(requestData);
- string body = sr.ReadToEnd();
- sr.Close();
+ string body;
+ using(StreamReader sr = new StreamReader(requestData))
+ body = sr.ReadToEnd();
+
body = body.Trim();
// m_log.DebugFormat("[XESTATE HANDLER]: query String: {0}", body);
diff --git a/OpenSim/Region/CoreModules/World/Land/DwellModule.cs b/OpenSim/Region/CoreModules/World/Land/DwellModule.cs
index 70c6028176..22480e68df 100644
--- a/OpenSim/Region/CoreModules/World/Land/DwellModule.cs
+++ b/OpenSim/Region/CoreModules/World/Land/DwellModule.cs
@@ -53,7 +53,7 @@ using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Region.CoreModules.World.Land
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "DefaultDwellModule")]
- public class DefaultDwellModule : IDwellModule, INonSharedRegionModule
+ public class DefaultDwellModule : INonSharedRegionModule, IDwellModule
{
private Scene m_scene;
private IConfigSource m_Config;
@@ -88,16 +88,21 @@ namespace OpenSim.Region.CoreModules.World.Land
return;
m_scene = scene;
-
- m_scene.EventManager.OnNewClient += OnNewClient;
+ m_scene.RegisterModuleInterface(this);
}
public void RegionLoaded(Scene scene)
{
+ if (!m_Enabled)
+ return;
+ m_scene.EventManager.OnNewClient += OnNewClient;
}
public void RemoveRegion(Scene scene)
{
+ if (!m_Enabled)
+ return;
+ m_scene.EventManager.OnNewClient -= OnNewClient;
}
public void Close()
@@ -115,12 +120,26 @@ namespace OpenSim.Region.CoreModules.World.Land
if (parcel == null)
return;
- client.SendParcelDwellReply(localID, parcel.LandData.GlobalID, parcel.LandData.Dwell);
+ LandData land = parcel.LandData;
+ if(land!= null)
+ client.SendParcelDwellReply(localID, land.GlobalID, land.Dwell);
}
+
public int GetDwell(UUID parcelID)
{
+ ILandObject parcel = m_scene.LandChannel.GetLandObject(parcelID);
+ if (parcel != null && parcel.LandData != null)
+ return (int)(parcel.LandData.Dwell);
return 0;
}
+
+ public int GetDwell(LandData land)
+ {
+ if (land != null)
+ return (int)(land.Dwell);
+ return 0;
+ }
+
}
}
diff --git a/OpenSim/Region/CoreModules/World/Land/LandChannel.cs b/OpenSim/Region/CoreModules/World/Land/LandChannel.cs
index e4c037371e..5ff063bc31 100644
--- a/OpenSim/Region/CoreModules/World/Land/LandChannel.cs
+++ b/OpenSim/Region/CoreModules/World/Land/LandChannel.cs
@@ -106,6 +106,15 @@ namespace OpenSim.Region.CoreModules.World.Land
return null;
}
+ public ILandObject GetLandObject(UUID GlobalID)
+ {
+ if (m_landManagementModule != null)
+ {
+ return m_landManagementModule.GetLandObject(GlobalID);
+ }
+ return null;
+ }
+
public ILandObject GetLandObject(Vector3 position)
{
return GetLandObject(position.X, position.Y);
@@ -167,6 +176,14 @@ namespace OpenSim.Region.CoreModules.World.Land
}
}
+ public void SendParcelsOverlay(IClientAPI client)
+ {
+ if (m_landManagementModule != null)
+ {
+ m_landManagementModule.SendParcelOverlay(client);
+ }
+ }
+
public void Join(int start_x, int start_y, int end_x, int end_y, UUID attempting_user_id)
{
if (m_landManagementModule != null)
diff --git a/OpenSim/Region/CoreModules/World/Land/LandManagementModule.cs b/OpenSim/Region/CoreModules/World/Land/LandManagementModule.cs
index 5d12f8b31a..f422708680 100644
--- a/OpenSim/Region/CoreModules/World/Land/LandManagementModule.cs
+++ b/OpenSim/Region/CoreModules/World/Land/LandManagementModule.cs
@@ -41,6 +41,7 @@ using OpenSim.Framework;
using OpenSim.Framework.Capabilities;
using OpenSim.Framework.Console;
using OpenSim.Framework.Servers;
+using OpenSim.Framework.Monitoring;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
@@ -92,6 +93,7 @@ namespace OpenSim.Region.CoreModules.World.Land
//ubit: removed the readonly so i can move it around
private Dictionary m_landList = new Dictionary();
+ private Dictionary m_landUUIDList = new Dictionary();
private int m_lastLandLocalID = LandChannel.START_LAND_LOCAL_ID - 1;
@@ -149,9 +151,11 @@ namespace OpenSim.Region.CoreModules.World.Land
parcelInfoCache.Size = 30; // the number of different parcel requests in this region to cache
parcelInfoCache.DefaultTTL = new TimeSpan(0, 5, 0);
+ m_scene.EventManager.OnObjectAddedToScene += EventManagerOnParcelPrimCountAdd;
m_scene.EventManager.OnParcelPrimCountAdd += EventManagerOnParcelPrimCountAdd;
- m_scene.EventManager.OnParcelPrimCountUpdate += EventManagerOnParcelPrimCountUpdate;
+
m_scene.EventManager.OnObjectBeingRemovedFromScene += EventManagerOnObjectBeingRemovedFromScene;
+ m_scene.EventManager.OnParcelPrimCountUpdate += EventManagerOnParcelPrimCountUpdate;
m_scene.EventManager.OnRequestParcelPrimCountUpdate += EventManagerOnRequestParcelPrimCountUpdate;
m_scene.EventManager.OnAvatarEnteringNewParcel += EventManagerOnAvatarEnteringNewParcel;
@@ -213,6 +217,7 @@ namespace OpenSim.Region.CoreModules.World.Land
client.OnParcelEjectUser += ClientOnParcelEjectUser;
client.OnParcelFreezeUser += ClientOnParcelFreezeUser;
client.OnSetStartLocationRequest += ClientOnSetHome;
+ client.OnParcelBuyPass += ClientParcelBuyPass;
}
public void EventMakeChildAgent(ScenePresence avatar)
@@ -247,7 +252,10 @@ namespace OpenSim.Region.CoreModules.World.Land
lock (m_landList)
{
if (m_landList.TryGetValue(local_id, out land))
+ {
land.LandData = newData;
+ m_landUUIDList[newData.GlobalID] = local_id;
+ }
}
if (land != null)
@@ -268,7 +276,11 @@ namespace OpenSim.Region.CoreModules.World.Land
//Remove all the land objects in the sim and add a blank, full sim land object set to public
lock (m_landList)
{
+ foreach(ILandObject parcel in m_landList.Values)
+ parcel.Clear();
+
m_landList.Clear();
+ m_landUUIDList.Clear();
m_lastLandLocalID = LandChannel.START_LAND_LOCAL_ID - 1;
m_landIDList = new int[m_scene.RegionInfo.RegionSizeX / LandUnit, m_scene.RegionInfo.RegionSizeY / LandUnit];
@@ -287,8 +299,10 @@ namespace OpenSim.Region.CoreModules.World.Land
fullSimParcel.SetLandBitmap(fullSimParcel.GetSquareLandBitmap(0, 0,
(int)m_scene.RegionInfo.RegionSizeX, (int)m_scene.RegionInfo.RegionSizeY));
- fullSimParcel.LandData.OwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner;
- fullSimParcel.LandData.ClaimDate = Util.UnixTimeSinceEpoch();
+ LandData ldata = fullSimParcel.LandData;
+ ldata.SimwideArea = ldata.Area;
+ ldata.OwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner;
+ ldata.ClaimDate = Util.UnixTimeSinceEpoch();
return AddLandObject(fullSimParcel);
}
@@ -525,6 +539,118 @@ namespace OpenSim.Region.CoreModules.World.Land
}
}
+ public void ClientParcelBuyPass(IClientAPI remote_client, UUID targetID, int landLocalID)
+ {
+ ILandObject land;
+ lock (m_landList)
+ {
+ m_landList.TryGetValue(landLocalID, out land);
+ }
+ // trivial checks
+ if(land == null)
+ return;
+
+ LandData ldata = land.LandData;
+
+ if(ldata == null)
+ return;
+
+ if(ldata.OwnerID == targetID)
+ return;
+
+ if(ldata.PassHours == 0)
+ return;
+
+ // don't allow passes on group owned until we can give money to groups
+ if(ldata.IsGroupOwned)
+ {
+ remote_client.SendAgentAlertMessage("pass to group owned parcel not suported", false);
+ return;
+ }
+
+ if((ldata.Flags & (uint)ParcelFlags.UsePassList) == 0)
+ return;
+
+ int cost = ldata.PassPrice;
+
+ int idx = land.LandData.ParcelAccessList.FindIndex(
+ delegate(LandAccessEntry e)
+ {
+ if (e.AgentID == targetID && e.Flags == AccessList.Access)
+ return true;
+ return false;
+ });
+ int now = Util.UnixTimeSinceEpoch();
+ int expires = (int)(3600.0 * ldata.PassHours + 0.5f);
+ int currenttime = -1;
+ if (idx != -1)
+ {
+ if(ldata.ParcelAccessList[idx].Expires == 0)
+ {
+ remote_client.SendAgentAlertMessage("You already have access to parcel", false);
+ return;
+ }
+
+ currenttime = ldata.ParcelAccessList[idx].Expires - now;
+ if(currenttime > (int)(0.25f * expires + 0.5f))
+ {
+ if(currenttime > 3600)
+ remote_client.SendAgentAlertMessage(string.Format("You already have a pass valid for {0:0.###} hours",
+ currenttime/3600f), false);
+ else if(currenttime > 60)
+ remote_client.SendAgentAlertMessage(string.Format("You already have a pass valid for {0:0.##} minutes",
+ currenttime/60f), false);
+ else
+ remote_client.SendAgentAlertMessage(string.Format("You already have a pass valid for {0:0.#} seconds",
+ currenttime), false);
+ return;
+ }
+ }
+
+ LandAccessEntry entry = new LandAccessEntry();
+ entry.AgentID = targetID;
+ entry.Flags = AccessList.Access;
+ entry.Expires = now + expires;
+ if(currenttime > 0)
+ entry.Expires += currenttime;
+ IMoneyModule mm = m_scene.RequestModuleInterface();
+ if(cost != 0 && mm != null)
+ {
+ WorkManager.RunInThreadPool(
+ delegate
+ {
+ string regionName = m_scene.RegionInfo.RegionName;
+
+ if (!mm.AmountCovered(remote_client.AgentId, cost))
+ {
+ remote_client.SendAgentAlertMessage(String.Format("Insufficient funds in region '{0}' money system", regionName), true);
+ return;
+ }
+
+ string payDescription = String.Format("Parcel '{0}' at region '{1} {2:0.###} hours access pass", ldata.Name, regionName, ldata.PassHours);
+
+ if(!mm.MoveMoney(remote_client.AgentId, ldata.OwnerID, cost,MoneyTransactionType.LandPassSale, payDescription))
+ {
+ remote_client.SendAgentAlertMessage("Sorry pass payment processing failed, please try again later", true);
+ return;
+ }
+
+ if (idx != -1)
+ ldata.ParcelAccessList.RemoveAt(idx);
+ ldata.ParcelAccessList.Add(entry);
+ m_scene.EventManager.TriggerLandObjectUpdated((uint)land.LandData.LocalID, land);
+ return;
+ }, null, "ParcelBuyPass");
+ }
+ else
+ {
+ if (idx != -1)
+ ldata.ParcelAccessList.RemoveAt(idx);
+ ldata.ParcelAccessList.Add(entry);
+ m_scene.EventManager.TriggerLandObjectUpdated((uint)land.LandData.LocalID, land);
+ }
+ }
+
public void ClientOnParcelAccessListRequest(UUID agentID, UUID sessionID, uint flags, int sequenceID,
int landLocalID, IClientAPI remote_client)
{
@@ -584,10 +710,8 @@ namespace OpenSim.Region.CoreModules.World.Land
/// The land object being added.
/// Will return null if this overlaps with an existing parcel that has not had its bitmap adjusted.
///
- public ILandObject AddLandObject(ILandObject land)
+ public ILandObject AddLandObject(ILandObject new_land)
{
- ILandObject new_land = land.Copy();
-
// Only now can we add the prim counts to the land object - we rely on the global ID which is generated
// as a random UUID inside LandData initialization
if (m_primCountModule != null)
@@ -652,6 +776,7 @@ namespace OpenSim.Region.CoreModules.World.Land
}
m_landList.Add(newLandLocalID, new_land);
+ m_landUUIDList[new_land.LandData.GlobalID] = newLandLocalID;
m_lastLandLocalID++;
}
@@ -668,6 +793,7 @@ namespace OpenSim.Region.CoreModules.World.Land
public void removeLandObject(int local_id)
{
ILandObject land;
+ UUID landGlobalID = UUID.Zero;
lock (m_landList)
{
for (int x = 0; x < m_landIDList.GetLength(0); x++)
@@ -686,9 +812,18 @@ namespace OpenSim.Region.CoreModules.World.Land
land = m_landList[local_id];
m_landList.Remove(local_id);
+ if(land != null && land.LandData != null)
+ {
+ landGlobalID = land.LandData.GlobalID;
+ m_landUUIDList.Remove(landGlobalID);
+ }
}
- m_scene.EventManager.TriggerLandObjectRemoved(land.LandData.GlobalID);
+ if(landGlobalID != UUID.Zero)
+ {
+ m_scene.EventManager.TriggerLandObjectRemoved(landGlobalID);
+ land.Clear();
+ }
}
///
@@ -736,11 +871,29 @@ namespace OpenSim.Region.CoreModules.World.Land
}
}
}
-
+ master.LandData.Dwell += slave.LandData.Dwell;
removeLandObject(slave.LandData.LocalID);
UpdateLandObject(master.LandData.LocalID, master.LandData);
}
+ public ILandObject GetLandObject(UUID globalID)
+ {
+ lock (m_landList)
+ {
+ int lid = -1;
+ if(m_landUUIDList.TryGetValue(globalID, out lid) && lid >= 0)
+ {
+ if (m_landList.ContainsKey(lid))
+ {
+ return m_landList[lid];
+ }
+ else
+ m_landUUIDList.Remove(globalID); // auto heal
+ }
+ }
+ return null;
+ }
+
public ILandObject GetLandObject(int parcelLocalID)
{
lock (m_landList)
@@ -813,6 +966,9 @@ namespace OpenSim.Region.CoreModules.World.Land
throw new Exception("Error: Parcel not found at point " + x + ", " + y);
}
+ if(m_landList.Count == 0 || m_landIDList == null)
+ return null;
+
lock (m_landIDList)
{
try
@@ -824,8 +980,6 @@ namespace OpenSim.Region.CoreModules.World.Land
return null;
}
}
-
- return m_landList[m_landIDList[x / 4, y / 4]];
}
// Create a 'parcel is here' bitmap for the parcel identified by the passed landID
@@ -1252,7 +1406,7 @@ namespace OpenSim.Region.CoreModules.World.Land
{
if (!temp.Contains(currentParcel))
{
- if (!currentParcel.IsEitherBannedOrRestricted(remote_client.AgentId))
+ if (!currentParcel.IsBannedFromLand(remote_client.AgentId))
{
currentParcel.ForceUpdateLandInfo();
temp.Add(currentParcel);
@@ -1346,7 +1500,7 @@ namespace OpenSim.Region.CoreModules.World.Land
public void ClientOnParcelObjectOwnerRequest(int local_id, IClientAPI remote_client)
{
- ILandObject land;
+ ILandObject land = null;
lock (m_landList)
{
m_landList.TryGetValue(local_id, out land);
@@ -1355,7 +1509,7 @@ namespace OpenSim.Region.CoreModules.World.Land
if (land != null)
{
m_scene.EventManager.TriggerParcelPrimCountUpdate();
- m_landList[local_id].SendLandObjectOwners(remote_client);
+ land.SendLandObjectOwners(remote_client);
}
else
{
@@ -1365,7 +1519,7 @@ namespace OpenSim.Region.CoreModules.World.Land
public void ClientOnParcelGodForceOwner(int local_id, UUID ownerID, IClientAPI remote_client)
{
- ILandObject land;
+ ILandObject land = null;
lock (m_landList)
{
m_landList.TryGetValue(local_id, out land);
@@ -1388,7 +1542,7 @@ namespace OpenSim.Region.CoreModules.World.Land
public void ClientOnParcelAbandonRequest(int local_id, IClientAPI remote_client)
{
- ILandObject land;
+ ILandObject land = null;
lock (m_landList)
{
m_landList.TryGetValue(local_id, out land);
@@ -1412,7 +1566,7 @@ namespace OpenSim.Region.CoreModules.World.Land
public void ClientOnParcelReclaim(int local_id, IClientAPI remote_client)
{
- ILandObject land;
+ ILandObject land = null;
lock (m_landList)
{
m_landList.TryGetValue(local_id, out land);
@@ -1498,17 +1652,16 @@ namespace OpenSim.Region.CoreModules.World.Land
void ClientOnParcelDeedToGroup(int parcelLocalID, UUID groupID, IClientAPI remote_client)
{
- ILandObject land;
+ ILandObject land = null;
lock (m_landList)
{
m_landList.TryGetValue(parcelLocalID, out land);
}
- if (!m_scene.Permissions.CanDeedParcel(remote_client.AgentId, land))
- return;
-
if (land != null)
{
+ if (!m_scene.Permissions.CanDeedParcel(remote_client.AgentId, land))
+ return;
land.DeedToGroup(groupID);
}
}
@@ -1576,13 +1729,13 @@ namespace OpenSim.Region.CoreModules.World.Land
}
}
}
+ FinalizeLandPrimCountUpdate(); // update simarea information
}
}
private void IncomingLandObjectFromStorage(LandData data)
{
- ILandObject new_land = new LandObject(data.OwnerID, data.IsGroupOwned, m_scene);
- new_land.LandData = data.Copy();
+ ILandObject new_land = new LandObject(data.OwnerID, data.IsGroupOwned, m_scene, data);
new_land.SetLandBitmapFromByteArray();
AddLandObject(new_land);
@@ -1640,9 +1793,9 @@ namespace OpenSim.Region.CoreModules.World.Land
foreach (HashSet objs in returns.Values)
{
List objs2 = new List(objs);
- if (m_scene.Permissions.CanReturnObjects(null, remoteClient.AgentId, objs2))
+ if (m_scene.Permissions.CanReturnObjects(null, remoteClient, objs2))
{
- m_scene.returnObjects(objs2.ToArray(), remoteClient.AgentId);
+ m_scene.returnObjects(objs2.ToArray(), remoteClient);
}
else
{
@@ -1730,7 +1883,7 @@ namespace OpenSim.Region.CoreModules.World.Land
land_update.MusicURL = properties.MusicURL;
land_update.Name = properties.Name;
land_update.ParcelFlags = (uint) properties.ParcelFlags;
- land_update.PassHours = (int) properties.PassHours;
+ land_update.PassHours = properties.PassHours;
land_update.PassPrice = (int) properties.PassPrice;
land_update.SalePrice = (int) properties.SalePrice;
land_update.SnapshotID = properties.SnapshotID;
@@ -1757,7 +1910,7 @@ namespace OpenSim.Region.CoreModules.World.Land
land_update.GroupAVSounds = true;
}
- ILandObject land;
+ ILandObject land = null;
lock (m_landList)
{
m_landList.TryGetValue(parcelID, out land);
@@ -1920,6 +2073,9 @@ namespace OpenSim.Region.CoreModules.World.Land
if (data.RegionHandle == m_scene.RegionInfo.RegionHandle)
{
info = new GridRegion(m_scene.RegionInfo);
+ IDwellModule dwellModule = m_scene.RequestModuleInterface();
+ if (dwellModule != null)
+ data.LandData.Dwell = dwellModule.GetDwell(data.LandData);
}
else
{
@@ -1945,7 +2101,7 @@ namespace OpenSim.Region.CoreModules.World.Land
public void setParcelOtherCleanTime(IClientAPI remoteClient, int localID, int otherCleanTime)
{
- ILandObject land;
+ ILandObject land = null;
lock (m_landList)
{
m_landList.TryGetValue(localID, out land);
@@ -2035,7 +2191,7 @@ namespace OpenSim.Region.CoreModules.World.Land
{
SceneObjectGroup[] objs = new SceneObjectGroup[1];
objs[0] = obj;
- ((Scene)client.Scene).returnObjects(objs, client.AgentId);
+ ((Scene)client.Scene).returnObjects(objs, client);
}
Dictionary Timers = new Dictionary();
@@ -2242,7 +2398,7 @@ namespace OpenSim.Region.CoreModules.World.Land
if (!ConsoleUtil.TryParseConsoleInt(MainConsole.Instance, args[2], out landLocalId))
return;
- ILandObject lo;
+ ILandObject lo = null;
lock (m_landList)
{
diff --git a/OpenSim/Region/CoreModules/World/Land/LandObject.cs b/OpenSim/Region/CoreModules/World/Land/LandObject.cs
index 73b4cb57a0..07d11f96a6 100644
--- a/OpenSim/Region/CoreModules/World/Land/LandObject.cs
+++ b/OpenSim/Region/CoreModules/World/Land/LandObject.cs
@@ -58,6 +58,7 @@ namespace OpenSim.Region.CoreModules.World.Land
protected ExpiringCache m_groupMemberCache = new ExpiringCache();
protected TimeSpan m_groupMemberCacheTimeout = TimeSpan.FromSeconds(30); // cache invalidation after 30 seconds
+ IDwellModule m_dwellModule;
private bool[,] m_landBitmap;
public bool[,] LandBitmap
@@ -268,27 +269,46 @@ namespace OpenSim.Region.CoreModules.World.Land
{
LandData = landData.Copy();
m_scene = scene;
+ m_scene.EventManager.OnFrame += OnFrame;
+ m_dwellModule = m_scene.RequestModuleInterface();
}
- public LandObject(UUID owner_id, bool is_group_owned, Scene scene)
+ public LandObject(UUID owner_id, bool is_group_owned, Scene scene, LandData data = null)
{
m_scene = scene;
if (m_scene == null)
LandBitmap = new bool[Constants.RegionSize / landUnit, Constants.RegionSize / landUnit];
else
+ {
LandBitmap = new bool[m_scene.RegionInfo.RegionSizeX / landUnit, m_scene.RegionInfo.RegionSizeY / landUnit];
+ m_dwellModule = m_scene.RequestModuleInterface();
+ }
+
+ if(data == null)
+ LandData = new LandData();
+ else
+ LandData = data;
- LandData = new LandData();
LandData.OwnerID = owner_id;
if (is_group_owned)
LandData.GroupID = owner_id;
- else
- LandData.GroupID = UUID.Zero;
+
LandData.IsGroupOwned = is_group_owned;
+ if(m_dwellModule == null)
+ LandData.Dwell = 0;
+
m_scene.EventManager.OnFrame += OnFrame;
}
+ public void Clear()
+ {
+ if(m_scene != null)
+ m_scene.EventManager.OnFrame -= OnFrame;
+ LandData = null;
+ }
+
+
#endregion
#region Member Functions
@@ -356,6 +376,7 @@ namespace OpenSim.Region.CoreModules.World.Land
}
}
+ // the total prims a parcel owner can have on a region
public int GetSimulatorMaxPrimCount()
{
if (overrideSimulatorMaxPrimCount != null)
@@ -370,7 +391,7 @@ namespace OpenSim.Region.CoreModules.World.Land
* (double)m_scene.RegionInfo.RegionSettings.ObjectBonus
/ (long)(m_scene.RegionInfo.RegionSizeX * m_scene.RegionInfo.RegionSizeY)
+0.5 );
-
+ // sanity check
if(simMax > m_scene.RegionInfo.ObjectCapacity)
simMax = m_scene.RegionInfo.ObjectCapacity;
//m_log.DebugFormat("Simwide Area: {0}, Capacity {1}, SimMax {2}, SimWidePrims {3}",
@@ -519,7 +540,8 @@ namespace OpenSim.Region.CoreModules.World.Land
ParcelFlags.UseEstateVoiceChan);
}
- if (m_scene.Permissions.CanEditParcelProperties(remote_client.AgentId,this, GroupPowers.LandManagePasses, false))
+ // don't allow passes on group owned until we can give money to groups
+ if (!newData.IsGroupOwned && m_scene.Permissions.CanEditParcelProperties(remote_client.AgentId,this, GroupPowers.LandManagePasses, false))
{
newData.PassHours = args.PassHours;
newData.PassPrice = args.PassPrice;
@@ -1043,7 +1065,8 @@ namespace OpenSim.Region.CoreModules.World.Land
else
LandData.AABBMax = new Vector3(tx, ty, (float)m_scene.Heightmap[tx - 1, ty - 1]);
- LandData.Area = tempArea * landUnit * landUnit;
+ tempArea *= landUnit * landUnit;
+ LandData.Area = tempArea;
}
#endregion
@@ -1647,8 +1670,7 @@ namespace OpenSim.Region.CoreModules.World.Land
{
foreach (SceneObjectGroup obj in primsOverMe)
{
- if (obj.OwnerID == previousOwner && obj.GroupID == UUID.Zero &&
- (obj.GetEffectivePermissions() & (uint)(OpenSim.Framework.PermissionMask.Transfer)) != 0)
+ if(m_scene.Permissions.CanSellObject(previousOwner,obj, (byte)SaleType.Original))
m_BuySellModule.BuyObject(sp.ControllingClient, UUID.Zero, obj.LocalId, 1, 0);
}
}
@@ -1662,7 +1684,7 @@ namespace OpenSim.Region.CoreModules.World.Land
{
SceneObjectGroup[] objs = new SceneObjectGroup[1];
objs[0] = obj;
- m_scene.returnObjects(objs, obj.OwnerID);
+ m_scene.returnObjects(objs, null);
}
public void ReturnLandObjects(uint type, UUID[] owners, UUID[] tasks, IClientAPI remote_client)
@@ -1693,6 +1715,8 @@ namespace OpenSim.Region.CoreModules.World.Land
{
if (obj.GroupID == LandData.GroupID)
{
+ if (obj.OwnerID == LandData.OwnerID)
+ continue;
if (!returns.ContainsKey(obj.OwnerID))
returns[obj.OwnerID] =
new List();
@@ -1734,8 +1758,8 @@ namespace OpenSim.Region.CoreModules.World.Land
foreach (List ol in returns.Values)
{
- if (m_scene.Permissions.CanReturnObjects(this, remote_client.AgentId, ol))
- m_scene.returnObjects(ol.ToArray(), remote_client.AgentId);
+ if (m_scene.Permissions.CanReturnObjects(this, remote_client, ol))
+ m_scene.returnObjects(ol.ToArray(), remote_client);
}
}
@@ -1809,6 +1833,37 @@ namespace OpenSim.Region.CoreModules.World.Land
ExpireAccessList();
m_expiryCounter = 0;
}
+
+ // need to update dwell here bc landdata has no parent info
+ if(LandData != null && m_dwellModule != null)
+ {
+ double now = Util.GetTimeStampMS();
+ double elapsed = now - LandData.LastDwellTimeMS;
+ if(elapsed > 150000) //2.5 minutes resolution / throttle
+ {
+ float dwell = LandData.Dwell;
+ double cur = dwell * 60000.0;
+ double decay = 1.5e-8 * cur * elapsed;
+ cur -= decay;
+ if(cur < 0)
+ cur = 0;
+
+ UUID lgid = LandData.GlobalID;
+ m_scene.ForEachRootScenePresence(delegate(ScenePresence sp)
+ {
+ if(sp.IsNPC || sp.IsLoggingIn || sp.IsDeleted || sp.currentParcelUUID != lgid)
+ return;
+ cur += (now - sp.ParcelDwellTickMS);
+ sp.ParcelDwellTickMS = now;
+ });
+
+ float newdwell = (float)(cur * 1.666666666667e-5);
+ LandData.Dwell = newdwell;
+
+ if(Math.Abs(newdwell - dwell) >= 0.9)
+ m_scene.EventManager.TriggerLandObjectAdded(this);
+ }
+ }
}
private void ExpireAccessList()
diff --git a/OpenSim/Region/CoreModules/World/Land/PrimCountModule.cs b/OpenSim/Region/CoreModules/World/Land/PrimCountModule.cs
index 857f919a06..2a720db660 100644
--- a/OpenSim/Region/CoreModules/World/Land/PrimCountModule.cs
+++ b/OpenSim/Region/CoreModules/World/Land/PrimCountModule.cs
@@ -92,10 +92,8 @@ namespace OpenSim.Region.CoreModules.World.Land
m_Scene.RegisterModuleInterface(this);
m_Scene.EventManager.OnObjectAddedToScene += OnParcelPrimCountAdd;
- m_Scene.EventManager.OnObjectBeingRemovedFromScene +=
- OnObjectBeingRemovedFromScene;
- m_Scene.EventManager.OnParcelPrimCountTainted +=
- OnParcelPrimCountTainted;
+ m_Scene.EventManager.OnObjectBeingRemovedFromScene += OnObjectBeingRemovedFromScene;
+ m_Scene.EventManager.OnParcelPrimCountTainted += OnParcelPrimCountTainted;
m_Scene.EventManager.OnLandObjectAdded += delegate(ILandObject lo) { OnParcelPrimCountTainted(); };
}
@@ -215,29 +213,15 @@ namespace OpenSim.Region.CoreModules.World.Land
else
parcelCounts.Users[obj.OwnerID] = partCount;
- if (obj.IsSelected)
- {
+ if (obj.IsSelected || obj.GetSittingAvatarsCount() > 0)
parcelCounts.Selected += partCount;
- }
+
+ if (obj.OwnerID == landData.OwnerID)
+ parcelCounts.Owner += partCount;
+ else if (landData.GroupID != UUID.Zero && obj.GroupID == landData.GroupID)
+ parcelCounts.Group += partCount;
else
- {
- if (landData.IsGroupOwned)
- {
- if (obj.OwnerID == landData.GroupID)
- parcelCounts.Owner += partCount;
- else if (landData.GroupID != UUID.Zero && obj.GroupID == landData.GroupID)
- parcelCounts.Group += partCount;
- else
- parcelCounts.Others += partCount;
- }
- else
- {
- if (obj.OwnerID == landData.OwnerID)
- parcelCounts.Owner += partCount;
- else
- parcelCounts.Others += partCount;
- }
- }
+ parcelCounts.Others += partCount;
}
}
@@ -393,7 +377,6 @@ namespace OpenSim.Region.CoreModules.World.Land
count = counts.Owner;
count += counts.Group;
count += counts.Others;
- count += counts.Selected;
}
}
diff --git a/OpenSim/Region/CoreModules/World/Land/Tests/PrimCountModuleTests.cs b/OpenSim/Region/CoreModules/World/Land/Tests/PrimCountModuleTests.cs
index 0d8ece7cdf..a349aa1be5 100644
--- a/OpenSim/Region/CoreModules/World/Land/Tests/PrimCountModuleTests.cs
+++ b/OpenSim/Region/CoreModules/World/Land/Tests/PrimCountModuleTests.cs
@@ -151,7 +151,7 @@ namespace OpenSim.Region.CoreModules.World.Land.Tests
SceneObjectGroup sog = SceneHelpers.CreateSceneObject(3, m_userId, "a", 0x01);
m_scene.AddNewSceneObject(sog, false);
- m_scene.SceneGraph.DuplicateObject(sog.LocalId, Vector3.Zero, 0, m_userId, UUID.Zero, Quaternion.Identity);
+ m_scene.SceneGraph.DuplicateObject(sog.LocalId, Vector3.Zero, m_userId, UUID.Zero, Quaternion.Identity, false);
Assert.That(pc.Owner, Is.EqualTo(6));
Assert.That(pc.Group, Is.EqualTo(0));
diff --git a/OpenSim/Region/CoreModules/World/Objects/BuySell/BuySellModule.cs b/OpenSim/Region/CoreModules/World/Objects/BuySell/BuySellModule.cs
index 283735889f..6a8f4c04af 100644
--- a/OpenSim/Region/CoreModules/World/Objects/BuySell/BuySellModule.cs
+++ b/OpenSim/Region/CoreModules/World/Objects/BuySell/BuySellModule.cs
@@ -89,28 +89,23 @@ namespace OpenSim.Region.CoreModules.World.Objects.BuySell
if (part == null)
return;
- if (part.ParentGroup.IsDeleted)
+ SceneObjectGroup sog = part.ParentGroup;
+ if (sog == null || sog.IsDeleted)
return;
- if (part.OwnerID != part.GroupID && part.OwnerID != client.AgentId && (!m_scene.Permissions.IsGod(client.AgentId)))
- return;
-
- if (part.OwnerID == part.GroupID) // Group owned
+ // Does the user have the power to put the object on sale?
+ if (!m_scene.Permissions.CanSellObject(client, sog, saleType))
{
- // Does the user have the power to put the object on sale?
- if (!m_scene.Permissions.CanSellGroupObject(client.AgentId, part.GroupID, m_scene))
- {
- client.SendAgentAlertMessage("You don't have permission to set group-owned objects on sale", false);
- return;
- }
+ client.SendAgentAlertMessage("You don't have permission to set object on sale", false);
+ return;
}
- part = part.ParentGroup.RootPart;
+ part = sog.RootPart;
part.ObjectSaleType = saleType;
part.SalePrice = salePrice;
- part.ParentGroup.HasGroupChanged = true;
+ sog.HasGroupChanged = true;
part.SendPropertiesToClient(client);
}
@@ -123,11 +118,16 @@ namespace OpenSim.Region.CoreModules.World.Objects.BuySell
return false;
SceneObjectGroup group = part.ParentGroup;
+ if(group == null || group.IsDeleted || group.inTransit)
+ return false;
+
+ // make sure we are not buying a child part
+ part = group.RootPart;
switch (saleType)
{
case 1: // Sell as original (in-place sale)
- uint effectivePerms = group.GetEffectivePermissions();
+ uint effectivePerms = group.EffectiveOwnerPerms;
if ((effectivePerms & (uint)PermissionMask.Transfer) == 0)
{
@@ -136,8 +136,7 @@ namespace OpenSim.Region.CoreModules.World.Objects.BuySell
return false;
}
- group.SetOwnerId(remoteClient.AgentId);
- group.SetRootPartOwner(part, remoteClient.AgentId, remoteClient.ActiveGroupId);
+ group.SetOwner(remoteClient.AgentId, remoteClient.ActiveGroupId);
if (m_scene.Permissions.PropagatePermissions())
{
@@ -147,6 +146,7 @@ namespace OpenSim.Region.CoreModules.World.Objects.BuySell
child.TriggerScriptChangedEvent(Changed.OWNER);
child.ApplyNextOwnerPermissions();
}
+ group.InvalidateDeepEffectivePerms();
}
part.ObjectSaleType = 0;
@@ -162,19 +162,7 @@ namespace OpenSim.Region.CoreModules.World.Objects.BuySell
break;
case 2: // Sell a copy
- Vector3 inventoryStoredPosition = new Vector3(
- Math.Min(group.AbsolutePosition.X, m_scene.RegionInfo.RegionSizeX - 6),
- Math.Min(group.AbsolutePosition.Y, m_scene.RegionInfo.RegionSizeY - 6),
- group.AbsolutePosition.Z);
-
- Vector3 originalPosition = group.AbsolutePosition;
-
- group.AbsolutePosition = inventoryStoredPosition;
-
- string sceneObjectXml = SceneObjectSerializer.ToOriginalXmlFormat(group);
- group.AbsolutePosition = originalPosition;
-
- uint perms = group.GetEffectivePermissions();
+ uint perms = group.EffectiveOwnerPerms;
if ((perms & (uint)PermissionMask.Transfer) == 0)
{
@@ -190,6 +178,8 @@ namespace OpenSim.Region.CoreModules.World.Objects.BuySell
return false;
}
+ string sceneObjectXml = SceneObjectSerializer.ToOriginalXmlFormat(group);
+
AssetBase asset = m_scene.CreateAsset(
group.GetPartName(localID),
group.GetPartDescription(localID),
@@ -210,22 +200,21 @@ namespace OpenSim.Region.CoreModules.World.Objects.BuySell
item.AssetType = asset.Type;
item.InvType = (int)InventoryType.Object;
item.Folder = categoryID;
+
+ perms = group.CurrentAndFoldedNextPermissions();
+ // apply parts inventory next perms
+ PermissionsUtil.ApplyNoModFoldedPermissions(perms, ref perms);
+ // change to next owner perms
+ perms &= part.NextOwnerMask;
+ // update folded
+ perms = PermissionsUtil.FixAndFoldPermissions(perms);
- uint nextPerms=(perms & 7) << 13;
- if ((nextPerms & (uint)PermissionMask.Copy) == 0)
- perms &= ~(uint)PermissionMask.Copy;
- if ((nextPerms & (uint)PermissionMask.Transfer) == 0)
- perms &= ~(uint)PermissionMask.Transfer;
- if ((nextPerms & (uint)PermissionMask.Modify) == 0)
- perms &= ~(uint)PermissionMask.Modify;
+ item.BasePermissions = perms;
+ item.CurrentPermissions = perms;
+ item.NextPermissions = part.NextOwnerMask & perms;
+ item.EveryOnePermissions = part.EveryoneMask & perms;
+ item.GroupPermissions = part.GroupMask & perms;
- item.BasePermissions = perms & part.NextOwnerMask;
- item.CurrentPermissions = perms & part.NextOwnerMask;
- item.NextPermissions = part.NextOwnerMask;
- item.EveryOnePermissions = part.EveryoneMask &
- part.NextOwnerMask;
- item.GroupPermissions = part.GroupMask &
- part.NextOwnerMask;
item.Flags |= (uint)InventoryItemFlags.ObjectSlamPerm;
item.CreationDate = Util.UnixTimeSinceEpoch();
diff --git a/OpenSim/Region/CoreModules/World/Objects/Commands/ObjectCommandsModule.cs b/OpenSim/Region/CoreModules/World/Objects/Commands/ObjectCommandsModule.cs
index 79c47133be..5a2a173835 100644
--- a/OpenSim/Region/CoreModules/World/Objects/Commands/ObjectCommandsModule.cs
+++ b/OpenSim/Region/CoreModules/World/Objects/Commands/ObjectCommandsModule.cs
@@ -123,8 +123,8 @@ namespace OpenSim.Region.CoreModules.World.Objects.Commands
"Objects",
false,
"delete object pos",
- "delete object pos to ",
- "Delete scene objects within the given area.",
+ "delete object pos ",
+ "Delete scene objects within the given volume.",
ConsoleUtil.CoordHelp,
HandleDeleteObject);
@@ -162,8 +162,8 @@ namespace OpenSim.Region.CoreModules.World.Objects.Commands
"Objects",
false,
"show object pos",
- "show object pos [--full] to ",
- "Show details of scene objects within the given area.",
+ "show object pos [--full] ",
+ "Show details of scene objects within give volume",
"The --full option will print out information on all the parts of the object.\n"
+ "For yet more detailed part information, use the \"show part\" commands.\n"
+ ConsoleUtil.CoordHelp,
@@ -189,8 +189,8 @@ namespace OpenSim.Region.CoreModules.World.Objects.Commands
"Objects",
false,
"show part pos",
- "show part pos to ",
- "Show details of scene object parts within the given area.",
+ "show part pos ",
+ "Show details of scene object parts within the given volume.",
ConsoleUtil.CoordHelp,
HandleShowPartByPos);
diff --git a/OpenSim/Region/CoreModules/World/Permissions/PermissionsModule.cs b/OpenSim/Region/CoreModules/World/Permissions/PermissionsModule.cs
index 75d90f363f..45c1c561e7 100644
--- a/OpenSim/Region/CoreModules/World/Permissions/PermissionsModule.cs
+++ b/OpenSim/Region/CoreModules/World/Permissions/PermissionsModule.cs
@@ -49,6 +49,7 @@ namespace OpenSim.Region.CoreModules.World.Permissions
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected Scene m_scene;
+ protected ScenePermissions scenePermissions;
protected bool m_Enabled;
private InventoryFolderImpl m_libraryRootFolder;
@@ -69,15 +70,6 @@ namespace OpenSim.Region.CoreModules.World.Permissions
}
#region Constants
- // These are here for testing. They will be taken out
-
- //private uint PERM_ALL = (uint)2147483647;
- private uint PERM_COPY = (uint)32768;
- //private uint PERM_MODIFY = (uint)16384;
- private uint PERM_MOVE = (uint)524288;
- private uint PERM_TRANS = (uint)8192;
- private uint PERM_LOCKED = (uint)540672;
-
///
/// Different user set names that come in from the configuration file.
///
@@ -96,14 +88,12 @@ namespace OpenSim.Region.CoreModules.World.Permissions
private bool m_bypassPermissionsValue = true;
private bool m_propagatePermissions = false;
private bool m_debugPermissions = false;
- private bool m_allowGridGods = false;
- private bool m_RegionOwnerIsGod = false;
- private bool m_RegionManagerIsGod = false;
- private bool m_forceGridGodsOnly;
- private bool m_forceGodModeAlwaysOn;
- private bool m_allowGodActionsWithoutGodMode;
-
- private bool m_SimpleBuildPermissions = false;
+ private bool m_allowGridAdmins = false;
+ private bool m_RegionOwnerIsAdmin = false;
+ private bool m_RegionManagerIsAdmin = false;
+ private bool m_forceGridAdminsOnly;
+ private bool m_forceAdminModeAlwaysOn;
+ private bool m_allowAdminActionsWithoutGodMode;
///
/// The set of users that are allowed to create scripts. This is only active if permissions are not being
@@ -172,25 +162,23 @@ namespace OpenSim.Region.CoreModules.World.Permissions
string[] sections = new string[] { "Startup", "Permissions" };
- m_allowGridGods = Util.GetConfigVarFromSections(config, "allow_grid_gods", sections, false);
+ m_allowGridAdmins = Util.GetConfigVarFromSections(config, "allow_grid_gods", sections, false);
m_bypassPermissions = !Util.GetConfigVarFromSections(config, "serverside_object_permissions", sections, true);
m_propagatePermissions = Util.GetConfigVarFromSections(config, "propagate_permissions", sections, true);
- m_forceGridGodsOnly = Util.GetConfigVarFromSections(config, "force_grid_gods_only", sections, false);
- if(!m_forceGridGodsOnly)
+ m_forceGridAdminsOnly = Util.GetConfigVarFromSections(config, "force_grid_gods_only", sections, false);
+ if(!m_forceGridAdminsOnly)
{
- m_RegionOwnerIsGod = Util.GetConfigVarFromSections(config, "region_owner_is_god",sections, true);
- m_RegionManagerIsGod = Util.GetConfigVarFromSections(config, "region_manager_is_god",sections, false);
+ m_RegionOwnerIsAdmin = Util.GetConfigVarFromSections(config, "region_owner_is_god",sections, true);
+ m_RegionManagerIsAdmin = Util.GetConfigVarFromSections(config, "region_manager_is_god",sections, false);
}
else
- m_allowGridGods = true;
+ m_allowGridAdmins = true;
- m_forceGodModeAlwaysOn = Util.GetConfigVarFromSections(config, "automatic_gods", sections, false);
- m_allowGodActionsWithoutGodMode = Util.GetConfigVarFromSections(config, "implicit_gods", sections, false);
- if(m_allowGodActionsWithoutGodMode)
- m_forceGodModeAlwaysOn = false;
-
- m_SimpleBuildPermissions = Util.GetConfigVarFromSections(config, "simple_build_permissions",sections, false);
+ m_forceAdminModeAlwaysOn = Util.GetConfigVarFromSections(config, "automatic_gods", sections, false);
+ m_allowAdminActionsWithoutGodMode = Util.GetConfigVarFromSections(config, "implicit_gods", sections, false);
+ if(m_allowAdminActionsWithoutGodMode)
+ m_forceAdminModeAlwaysOn = false;
m_allowedScriptCreators
= ParseUserSetConfigSetting(config, "allowed_script_creators", m_allowedScriptCreators);
@@ -266,63 +254,79 @@ namespace OpenSim.Region.CoreModules.World.Permissions
m_scene = scene;
scene.RegisterModuleInterface(this);
+ scenePermissions = m_scene.Permissions;
//Register functions with Scene External Checks!
- m_scene.Permissions.OnBypassPermissions += BypassPermissions;
- m_scene.Permissions.OnSetBypassPermissions += SetBypassPermissions;
- m_scene.Permissions.OnPropagatePermissions += PropagatePermissions;
- m_scene.Permissions.OnGenerateClientFlags += GenerateClientFlags;
- m_scene.Permissions.OnAbandonParcel += CanAbandonParcel;
- m_scene.Permissions.OnReclaimParcel += CanReclaimParcel;
- m_scene.Permissions.OnDeedParcel += CanDeedParcel;
- m_scene.Permissions.OnDeedObject += CanDeedObject;
- m_scene.Permissions.OnIsGod += IsGod;
- m_scene.Permissions.OnIsGridGod += IsGridGod;
- m_scene.Permissions.OnIsAdministrator += IsAdministrator;
- m_scene.Permissions.OnIsEstateManager += IsEstateManager;
- m_scene.Permissions.OnDuplicateObject += CanDuplicateObject;
- m_scene.Permissions.OnDeleteObject += CanDeleteObject;
- m_scene.Permissions.OnEditObject += CanEditObject;
- m_scene.Permissions.OnEditParcelProperties += CanEditParcelProperties;
- m_scene.Permissions.OnInstantMessage += CanInstantMessage;
- m_scene.Permissions.OnInventoryTransfer += CanInventoryTransfer;
- m_scene.Permissions.OnIssueEstateCommand += CanIssueEstateCommand;
- m_scene.Permissions.OnMoveObject += CanMoveObject;
- m_scene.Permissions.OnObjectEntry += CanObjectEntry;
- m_scene.Permissions.OnReturnObjects += CanReturnObjects;
- m_scene.Permissions.OnRezObject += CanRezObject;
- m_scene.Permissions.OnRunConsoleCommand += CanRunConsoleCommand;
- m_scene.Permissions.OnRunScript += CanRunScript;
- m_scene.Permissions.OnCompileScript += CanCompileScript;
- m_scene.Permissions.OnSellParcel += CanSellParcel;
- m_scene.Permissions.OnTakeObject += CanTakeObject;
- m_scene.Permissions.OnSellGroupObject += CanSellGroupObject;
- m_scene.Permissions.OnTakeCopyObject += CanTakeCopyObject;
- m_scene.Permissions.OnTerraformLand += CanTerraformLand;
- m_scene.Permissions.OnLinkObject += CanLinkObject;
- m_scene.Permissions.OnDelinkObject += CanDelinkObject;
- m_scene.Permissions.OnBuyLand += CanBuyLand;
+ scenePermissions.OnBypassPermissions += BypassPermissions;
+ scenePermissions.OnSetBypassPermissions += SetBypassPermissions;
+ scenePermissions.OnPropagatePermissions += PropagatePermissions;
- m_scene.Permissions.OnViewNotecard += CanViewNotecard;
- m_scene.Permissions.OnViewScript += CanViewScript;
- m_scene.Permissions.OnEditNotecard += CanEditNotecard;
- m_scene.Permissions.OnEditScript += CanEditScript;
+ scenePermissions.OnIsGridGod += IsGridAdministrator;
+ scenePermissions.OnIsAdministrator += IsAdministrator;
+ scenePermissions.OnIsEstateManager += IsEstateManager;
- m_scene.Permissions.OnCreateObjectInventory += CanCreateObjectInventory;
- m_scene.Permissions.OnEditObjectInventory += CanEditObjectInventory;
- m_scene.Permissions.OnCopyObjectInventory += CanCopyObjectInventory;
- m_scene.Permissions.OnDeleteObjectInventory += CanDeleteObjectInventory;
- m_scene.Permissions.OnResetScript += CanResetScript;
+ scenePermissions.OnGenerateClientFlags += GenerateClientFlags;
- m_scene.Permissions.OnCreateUserInventory += CanCreateUserInventory;
- m_scene.Permissions.OnCopyUserInventory += CanCopyUserInventory;
- m_scene.Permissions.OnEditUserInventory += CanEditUserInventory;
- m_scene.Permissions.OnDeleteUserInventory += CanDeleteUserInventory;
+ scenePermissions.OnIssueEstateCommand += CanIssueEstateCommand;
+ scenePermissions.OnRunConsoleCommand += CanRunConsoleCommand;
- m_scene.Permissions.OnTeleport += CanTeleport;
+ scenePermissions.OnTeleport += CanTeleport;
- m_scene.Permissions.OnControlPrimMedia += CanControlPrimMedia;
- m_scene.Permissions.OnInteractWithPrimMedia += CanInteractWithPrimMedia;
+ scenePermissions.OnInstantMessage += CanInstantMessage;
+
+ scenePermissions.OnAbandonParcel += CanAbandonParcel;
+ scenePermissions.OnReclaimParcel += CanReclaimParcel;
+ scenePermissions.OnDeedParcel += CanDeedParcel;
+ scenePermissions.OnSellParcel += CanSellParcel;
+ scenePermissions.OnEditParcelProperties += CanEditParcelProperties;
+ scenePermissions.OnTerraformLand += CanTerraformLand;
+ scenePermissions.OnBuyLand += CanBuyLand;
+
+ scenePermissions.OnReturnObjects += CanReturnObjects;
+
+ scenePermissions.OnRezObject += CanRezObject;
+ scenePermissions.OnObjectEntry += CanObjectEntry;
+ scenePermissions.OnObjectEnterWithScripts += OnObjectEnterWithScripts;
+
+ scenePermissions.OnDuplicateObject += CanDuplicateObject;
+ scenePermissions.OnDeleteObjectByIDs += CanDeleteObjectByIDs;
+ scenePermissions.OnDeleteObject += CanDeleteObject;
+ scenePermissions.OnEditObjectByIDs += CanEditObjectByIDs;
+ scenePermissions.OnEditObject += CanEditObject;
+ scenePermissions.OnEditObjectPerms += CanEditObjectPerms;
+ scenePermissions.OnInventoryTransfer += CanInventoryTransfer;
+ scenePermissions.OnMoveObject += CanMoveObject;
+ scenePermissions.OnTakeObject += CanTakeObject;
+ scenePermissions.OnTakeCopyObject += CanTakeCopyObject;
+ scenePermissions.OnLinkObject += CanLinkObject;
+ scenePermissions.OnDelinkObject += CanDelinkObject;
+ scenePermissions.OnDeedObject += CanDeedObject;
+ scenePermissions.OnSellGroupObject += CanSellGroupObject;
+ scenePermissions.OnSellObjectByUserID += CanSellObjectByUserID;
+ scenePermissions.OnSellObject += CanSellObject;
+
+ scenePermissions.OnCreateObjectInventory += CanCreateObjectInventory;
+ scenePermissions.OnEditObjectInventory += CanEditObjectInventory;
+ scenePermissions.OnCopyObjectInventory += CanCopyObjectInventory;
+ scenePermissions.OnDeleteObjectInventory += CanDeleteObjectInventory;
+ scenePermissions.OnDoObjectInvToObjectInv += CanDoObjectInvToObjectInv;
+ scenePermissions.OnDropInObjectInv += CanDropInObjectInv;
+
+ scenePermissions.OnViewNotecard += CanViewNotecard;
+ scenePermissions.OnViewScript += CanViewScript;
+ scenePermissions.OnEditNotecard += CanEditNotecard;
+ scenePermissions.OnEditScript += CanEditScript;
+ scenePermissions.OnResetScript += CanResetScript;
+ scenePermissions.OnRunScript += CanRunScript;
+ scenePermissions.OnCompileScript += CanCompileScript;
+
+ scenePermissions.OnCreateUserInventory += CanCreateUserInventory;
+ scenePermissions.OnCopyUserInventory += CanCopyUserInventory;
+ scenePermissions.OnEditUserInventory += CanEditUserInventory;
+ scenePermissions.OnDeleteUserInventory += CanDeleteUserInventory;
+
+ scenePermissions.OnControlPrimMedia += CanControlPrimMedia;
+ scenePermissions.OnInteractWithPrimMedia += CanInteractWithPrimMedia;
m_scene.AddCommand("Users", this, "bypass permissions",
"bypass permissions ",
@@ -351,6 +355,79 @@ namespace OpenSim.Region.CoreModules.World.Permissions
return;
m_scene.UnregisterModuleInterface(this);
+
+ scenePermissions.OnBypassPermissions -= BypassPermissions;
+ scenePermissions.OnSetBypassPermissions -= SetBypassPermissions;
+ scenePermissions.OnPropagatePermissions -= PropagatePermissions;
+
+ scenePermissions.OnIsGridGod -= IsGridAdministrator;
+ scenePermissions.OnIsAdministrator -= IsAdministrator;
+ scenePermissions.OnIsEstateManager -= IsEstateManager;
+
+ scenePermissions.OnGenerateClientFlags -= GenerateClientFlags;
+
+ scenePermissions.OnIssueEstateCommand -= CanIssueEstateCommand;
+ scenePermissions.OnRunConsoleCommand -= CanRunConsoleCommand;
+
+ scenePermissions.OnTeleport -= CanTeleport;
+
+ scenePermissions.OnInstantMessage -= CanInstantMessage;
+
+ scenePermissions.OnAbandonParcel -= CanAbandonParcel;
+ scenePermissions.OnReclaimParcel -= CanReclaimParcel;
+ scenePermissions.OnDeedParcel -= CanDeedParcel;
+ scenePermissions.OnSellParcel -= CanSellParcel;
+ scenePermissions.OnEditParcelProperties -= CanEditParcelProperties;
+ scenePermissions.OnTerraformLand -= CanTerraformLand;
+ scenePermissions.OnBuyLand -= CanBuyLand;
+
+ scenePermissions.OnRezObject -= CanRezObject;
+ scenePermissions.OnObjectEntry -= CanObjectEntry;
+ scenePermissions.OnObjectEnterWithScripts -= OnObjectEnterWithScripts;
+
+ scenePermissions.OnReturnObjects -= CanReturnObjects;
+
+ scenePermissions.OnDuplicateObject -= CanDuplicateObject;
+ scenePermissions.OnDeleteObjectByIDs -= CanDeleteObjectByIDs;
+ scenePermissions.OnDeleteObject -= CanDeleteObject;
+ scenePermissions.OnEditObjectByIDs -= CanEditObjectByIDs;
+ scenePermissions.OnEditObject -= CanEditObject;
+ scenePermissions.OnEditObjectPerms -= CanEditObjectPerms;
+ scenePermissions.OnInventoryTransfer -= CanInventoryTransfer;
+ scenePermissions.OnMoveObject -= CanMoveObject;
+ scenePermissions.OnTakeObject -= CanTakeObject;
+ scenePermissions.OnTakeCopyObject -= CanTakeCopyObject;
+ scenePermissions.OnLinkObject -= CanLinkObject;
+ scenePermissions.OnDelinkObject -= CanDelinkObject;
+ scenePermissions.OnDeedObject -= CanDeedObject;
+
+ scenePermissions.OnSellGroupObject -= CanSellGroupObject;
+ scenePermissions.OnSellObjectByUserID -= CanSellObjectByUserID;
+ scenePermissions.OnSellObject -= CanSellObject;
+
+ scenePermissions.OnCreateObjectInventory -= CanCreateObjectInventory;
+ scenePermissions.OnEditObjectInventory -= CanEditObjectInventory;
+ scenePermissions.OnCopyObjectInventory -= CanCopyObjectInventory;
+ scenePermissions.OnDeleteObjectInventory -= CanDeleteObjectInventory;
+ scenePermissions.OnDoObjectInvToObjectInv -= CanDoObjectInvToObjectInv;
+ scenePermissions.OnDropInObjectInv -= CanDropInObjectInv;
+
+ scenePermissions.OnViewNotecard -= CanViewNotecard;
+ scenePermissions.OnViewScript -= CanViewScript;
+ scenePermissions.OnEditNotecard -= CanEditNotecard;
+ scenePermissions.OnEditScript -= CanEditScript;
+ scenePermissions.OnResetScript -= CanResetScript;
+ scenePermissions.OnRunScript -= CanRunScript;
+ scenePermissions.OnCompileScript -= CanCompileScript;
+
+ scenePermissions.OnCreateUserInventory -= CanCreateUserInventory;
+ scenePermissions.OnCopyUserInventory -= CanCopyUserInventory;
+ scenePermissions.OnEditUserInventory -= CanEditUserInventory;
+ scenePermissions.OnDeleteUserInventory -= CanDeleteUserInventory;
+
+ scenePermissions.OnControlPrimMedia -= CanControlPrimMedia;
+ scenePermissions.OnInteractWithPrimMedia -= CanInteractWithPrimMedia;
+
}
public void Close()
@@ -480,6 +557,36 @@ namespace OpenSim.Region.CoreModules.World.Permissions
return false;
}
+ protected bool GroupMemberPowers(UUID groupID, UUID userID, ref ulong powers)
+ {
+ powers = 0;
+ if (null == GroupsModule)
+ return false;
+
+ GroupMembershipData gmd = GroupsModule.GetMembershipData(groupID, userID);
+
+ if (gmd != null)
+ {
+ powers = gmd.GroupPowers;
+ return true;
+ }
+ return false;
+ }
+
+ protected bool GroupMemberPowers(UUID groupID, ScenePresence sp, ref ulong powers)
+ {
+ powers = 0;
+ IClientAPI client = sp.ControllingClient;
+ if (client == null)
+ return false;
+
+ if(!client.IsGroupMember(groupID))
+ return false;
+
+ powers = client.GetGroupPowers(groupID);
+ return true;
+ }
+
///
/// Parse a user set configuration setting
///
@@ -526,13 +633,13 @@ namespace OpenSim.Region.CoreModules.World.Permissions
if (user == UUID.Zero)
return false;
- if (m_scene.RegionInfo.EstateSettings.EstateOwner == user && m_RegionOwnerIsGod)
+ if (m_RegionOwnerIsAdmin && m_scene.RegionInfo.EstateSettings.EstateOwner == user)
return true;
- if (IsEstateManager(user) && m_RegionManagerIsGod)
+ if (m_RegionManagerIsAdmin && IsEstateManager(user))
return true;
- if (IsGridGod(user, null))
+ if (IsGridAdministrator(user))
return true;
return false;
@@ -544,14 +651,15 @@ namespace OpenSim.Region.CoreModules.World.Permissions
/// The user
/// Unused, can be null
///
- protected bool IsGridGod(UUID user, Scene scene)
+ protected bool IsGridAdministrator(UUID user)
{
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
if (m_bypassPermissions) return m_bypassPermissionsValue;
- if (user == UUID.Zero) return false;
+ if (user == UUID.Zero)
+ return false;
- if (m_allowGridGods)
+ if (m_allowGridAdmins)
{
ScenePresence sp = m_scene.GetScenePresence(user);
if (sp != null)
@@ -567,10 +675,10 @@ namespace OpenSim.Region.CoreModules.World.Permissions
protected bool IsFriendWithPerms(UUID user, UUID objectOwner)
{
- if (user == UUID.Zero)
+ if (FriendsModule == null)
return false;
- if (FriendsModule == null)
+ if (user == UUID.Zero)
return false;
int friendPerms = FriendsModule.GetRightsGrantedByFriend(user, objectOwner);
@@ -606,75 +714,178 @@ namespace OpenSim.Region.CoreModules.World.Permissions
#region Object Permissions
- public uint GenerateClientFlags(UUID user, UUID objID)
+ const uint DEFAULT_FLAGS = (uint)(
+ PrimFlags.ObjectCopy | // Tells client you can copy the object
+ PrimFlags.ObjectModify | // tells client you can modify the object
+ PrimFlags.ObjectMove | // tells client that you can move the object (only, no mod)
+ PrimFlags.ObjectTransfer | // tells the client that you can /take/ the object if you don't own it
+ PrimFlags.ObjectYouOwner | // Tells client that you're the owner of the object
+ PrimFlags.ObjectAnyOwner | // Tells client that someone owns the object
+ PrimFlags.ObjectOwnerModify // Tells client that you're the owner of the object
+ );
+
+ const uint NOT_DEFAULT_FLAGS = (uint)~(
+ PrimFlags.ObjectCopy | // Tells client you can copy the object
+ PrimFlags.ObjectModify | // tells client you can modify the object
+ PrimFlags.ObjectMove | // tells client that you can move the object (only, no mod)
+ PrimFlags.ObjectTransfer | // tells the client that you can /take/ the object if you don't own it
+ PrimFlags.ObjectYouOwner | // Tells client that you're the owner of the object
+ PrimFlags.ObjectAnyOwner | // Tells client that someone owns the object
+ PrimFlags.ObjectOwnerModify // Tells client that you're the owner of the object
+ );
+
+ const uint EXTRAOWNERMASK = (uint)(
+ PrimFlags.ObjectYouOwner |
+ PrimFlags.ObjectAnyOwner
+ );
+
+ const uint EXTRAGODMASK = (uint)(
+ PrimFlags.ObjectYouOwner |
+ PrimFlags.ObjectAnyOwner |
+ PrimFlags.ObjectOwnerModify |
+ PrimFlags.ObjectModify |
+ PrimFlags.ObjectMove
+ );
+
+ const uint GOD_FLAGS = (uint)(
+ PrimFlags.ObjectCopy | // Tells client you can copy the object
+ PrimFlags.ObjectModify | // tells client you can modify the object
+ PrimFlags.ObjectMove | // tells client that you can move the object (only, no mod)
+ PrimFlags.ObjectTransfer | // tells the client that you can /take/ the object if you don't own it
+ PrimFlags.ObjectYouOwner | // Tells client that you're the owner of the object
+ PrimFlags.ObjectAnyOwner | // Tells client that someone owns the object
+ PrimFlags.ObjectOwnerModify // Tells client that you're the owner of the object
+ );
+
+ const uint LOCKED_GOD_FLAGS = (uint)(
+ PrimFlags.ObjectCopy | // Tells client you can copy the object
+ PrimFlags.ObjectTransfer | // tells the client that you can /take/ the object if you don't own it
+ PrimFlags.ObjectYouOwner | // Tells client that you're the owner of the object
+ PrimFlags.ObjectAnyOwner // Tells client that someone owns the object
+ );
+
+ const uint SHAREDMASK = (uint)(
+ PermissionMask.Move |
+ PermissionMask.Modify |
+ PermissionMask.Copy
+ );
+
+ public uint GenerateClientFlags(SceneObjectPart task, ScenePresence sp, uint curEffectivePerms)
{
- // Here's the way this works,
- // ObjectFlags and Permission flags are two different enumerations
- // ObjectFlags, however, tells the client to change what it will allow the user to do.
- // So, that means that all of the permissions type ObjectFlags are /temporary/ and only
- // supposed to be set when customizing the objectflags for the client.
-
- // These temporary objectflags get computed and added in this function based on the
- // Permission mask that's appropriate!
- // Outside of this method, they should never be added to objectflags!
- // -teravus
-
- SceneObjectPart task = m_scene.GetSceneObjectPart(objID);
-
- // this shouldn't ever happen.. return no permissions/objectflags.
- if (task == null)
- return (uint)0;
-
- uint objflags = task.GetEffectiveObjectFlags();
- UUID objectOwner = task.OwnerID;
-
+ if(sp == null || task == null || curEffectivePerms == 0)
+ return 0;
// Remove any of the objectFlags that are temporary. These will get added back if appropriate
- // in the next bit of code
+ uint objflags = curEffectivePerms & NOT_DEFAULT_FLAGS ;
- // libomv will moan about PrimFlags.ObjectYouOfficer being
- // deprecated
-#pragma warning disable 0612
- objflags &= (uint)
- ~(PrimFlags.ObjectCopy | // Tells client you can copy the object
- PrimFlags.ObjectModify | // tells client you can modify the object
- PrimFlags.ObjectMove | // tells client that you can move the object (only, no mod)
- PrimFlags.ObjectTransfer | // tells the client that you can /take/ the object if you don't own it
- PrimFlags.ObjectYouOwner | // Tells client that you're the owner of the object
- PrimFlags.ObjectAnyOwner | // Tells client that someone owns the object
- PrimFlags.ObjectOwnerModify | // Tells client that you're the owner of the object
- PrimFlags.ObjectYouOfficer // Tells client that you've got group object editing permission. Used when ObjectGroupOwned is set
- );
-#pragma warning restore 0612
+ uint returnMask;
- // Creating the three ObjectFlags options for this method to choose from.
- // Customize the OwnerMask
- uint objectOwnerMask = ApplyObjectModifyMasks(task.OwnerMask, objflags);
- objectOwnerMask |= (uint)PrimFlags.ObjectYouOwner | (uint)PrimFlags.ObjectAnyOwner | (uint)PrimFlags.ObjectOwnerModify;
+ SceneObjectGroup grp = task.ParentGroup;
+ if(grp == null)
+ return 0;
- // Customize the GroupMask
- uint objectGroupMask = ApplyObjectModifyMasks(task.GroupMask, objflags);
+ UUID taskOwnerID = task.OwnerID;
+ UUID spID = sp.UUID;
- // Customize the EveryoneMask
- uint objectEveryoneMask = ApplyObjectModifyMasks(task.EveryoneMask, objflags);
- if (objectOwner != UUID.Zero)
- objectEveryoneMask |= (uint)PrimFlags.ObjectAnyOwner;
+ bool unlocked = (grp.RootPart.OwnerMask & (uint)PermissionMask.Move) != 0;
- PermissionClass permissionClass = GetPermissionClass(user, task);
-
- switch (permissionClass)
+ if(sp.IsGod)
{
- case PermissionClass.Owner:
- return objectOwnerMask;
- case PermissionClass.Group:
- return objectGroupMask | objectEveryoneMask;
- case PermissionClass.Everyone:
- default:
- return objectEveryoneMask;
+ // do locked on objects owned by admin
+ if(!unlocked && spID == taskOwnerID)
+ return objflags | LOCKED_GOD_FLAGS;
+ else
+ return objflags | GOD_FLAGS;
}
+
+ //bypass option == owner rights
+ if (m_bypassPermissions)
+ {
+ returnMask = ApplyObjectModifyMasks(task.OwnerMask, objflags, true); //??
+ returnMask |= EXTRAOWNERMASK;
+ if((returnMask & (uint)PrimFlags.ObjectModify) != 0)
+ returnMask |= (uint)PrimFlags.ObjectOwnerModify;
+ return returnMask;
+ }
+
+ // owner
+ if (spID == taskOwnerID)
+ {
+ returnMask = ApplyObjectModifyMasks(grp.EffectiveOwnerPerms, objflags, unlocked);
+ returnMask |= EXTRAOWNERMASK;
+ if((returnMask & (uint)PrimFlags.ObjectModify) != 0)
+ returnMask |= (uint)PrimFlags.ObjectOwnerModify;
+ return returnMask;
+ }
+
+ // if not god or owner, do attachments as everyone
+ if(task.ParentGroup.IsAttachment)
+ {
+ returnMask = ApplyObjectModifyMasks(grp.EffectiveEveryOnePerms, objflags, unlocked);
+ if (taskOwnerID != UUID.Zero)
+ returnMask |= (uint)PrimFlags.ObjectAnyOwner;
+ return returnMask;
+ }
+
+ UUID taskGroupID = task.GroupID;
+ bool notGroupdOwned = taskOwnerID != taskGroupID;
+
+ // if friends with rights then owner
+ if (notGroupdOwned && IsFriendWithPerms(spID, taskOwnerID))
+ {
+ returnMask = ApplyObjectModifyMasks(grp.EffectiveOwnerPerms, objflags, unlocked);
+ returnMask |= EXTRAOWNERMASK;
+ if((returnMask & (uint)PrimFlags.ObjectModify) != 0)
+ returnMask |= (uint)PrimFlags.ObjectOwnerModify;
+ return returnMask;
+ }
+
+ // group owned or shared ?
+ IClientAPI client = sp.ControllingClient;
+ ulong powers = 0;
+ if(taskGroupID != UUID.Zero && GroupMemberPowers(taskGroupID, sp, ref powers))
+ {
+ if(notGroupdOwned)
+ {
+ // group sharing or everyone
+ returnMask = ApplyObjectModifyMasks(grp.EffectiveGroupOrEveryOnePerms, objflags, unlocked);
+ if (taskOwnerID != UUID.Zero)
+ returnMask |= (uint)PrimFlags.ObjectAnyOwner;
+ return returnMask;
+ }
+
+ // object is owned by group, check role powers
+ if((powers & (ulong)GroupPowers.ObjectManipulate) == 0)
+ {
+ // group sharing or everyone
+ returnMask = ApplyObjectModifyMasks(grp.EffectiveGroupOrEveryOnePerms, objflags, unlocked);
+ returnMask |=
+ (uint)PrimFlags.ObjectGroupOwned |
+ (uint)PrimFlags.ObjectAnyOwner;
+ return returnMask;
+ }
+
+ // we may have copy without transfer
+ uint grpEffectiveOwnerPerms = grp.EffectiveOwnerPerms;
+ if((grpEffectiveOwnerPerms & (uint)PermissionMask.Transfer) == 0)
+ grpEffectiveOwnerPerms &= ~(uint)PermissionMask.Copy;
+ returnMask = ApplyObjectModifyMasks(grpEffectiveOwnerPerms, objflags, unlocked);
+ returnMask |=
+ (uint)PrimFlags.ObjectGroupOwned |
+ (uint)PrimFlags.ObjectYouOwner;
+ if((returnMask & (uint)PrimFlags.ObjectModify) != 0)
+ returnMask |= (uint)PrimFlags.ObjectOwnerModify;
+ return returnMask;
+ }
+
+ // fallback is everyone rights
+ returnMask = ApplyObjectModifyMasks(grp.EffectiveEveryOnePerms, objflags, unlocked);
+ if (taskOwnerID != UUID.Zero)
+ returnMask |= (uint)PrimFlags.ObjectAnyOwner;
+ return returnMask;
}
- private uint ApplyObjectModifyMasks(uint setPermissionMask, uint objectFlagsMask)
+ private uint ApplyObjectModifyMasks(uint setPermissionMask, uint objectFlagsMask, bool unlocked)
{
// We are adding the temporary objectflags to the object's objectflags based on the
// permission flag given. These change the F flags on the client.
@@ -684,14 +895,17 @@ namespace OpenSim.Region.CoreModules.World.Permissions
objectFlagsMask |= (uint)PrimFlags.ObjectCopy;
}
- if ((setPermissionMask & (uint)PermissionMask.Move) != 0)
+ if (unlocked)
{
- objectFlagsMask |= (uint)PrimFlags.ObjectMove;
- }
+ if ((setPermissionMask & (uint)PermissionMask.Move) != 0)
+ {
+ objectFlagsMask |= (uint)PrimFlags.ObjectMove;
+ }
- if ((setPermissionMask & (uint)PermissionMask.Modify) != 0)
- {
- objectFlagsMask |= (uint)PrimFlags.ObjectModify;
+ if ((setPermissionMask & (uint)PermissionMask.Modify) != 0)
+ {
+ objectFlagsMask |= (uint)PrimFlags.ObjectModify;
+ }
}
if ((setPermissionMask & (uint)PermissionMask.Transfer) != 0)
@@ -702,6 +916,7 @@ namespace OpenSim.Region.CoreModules.World.Permissions
return objectFlagsMask;
}
+ // OARs still need this method that handles offline users
public PermissionClass GetPermissionClass(UUID user, SceneObjectPart obj)
{
if (obj == null)
@@ -715,136 +930,199 @@ namespace OpenSim.Region.CoreModules.World.Permissions
if (user == objectOwner)
return PermissionClass.Owner;
- if (IsFriendWithPerms(user, objectOwner) && !obj.ParentGroup.IsAttachment)
- return PermissionClass.Owner;
-
- // Estate users should be able to edit anything in the sim if RegionOwnerIsGod is set
- if (m_RegionOwnerIsGod && IsEstateManager(user) && !IsAdministrator(objectOwner))
- return PermissionClass.Owner;
-
// Admin should be able to edit anything in the sim (including admin objects)
if (IsAdministrator(user))
return PermissionClass.Owner;
-/* to review later
- // Users should be able to edit what is over their land.
- Vector3 taskPos = obj.AbsolutePosition;
- ILandObject parcel = m_scene.LandChannel.GetLandObject(taskPos.X, taskPos.Y);
- if (parcel != null && parcel.LandData.OwnerID == user && m_ParcelOwnerIsGod)
+ if(!obj.ParentGroup.IsAttachment)
{
- // Admin objects should not be editable by the above
- if (!IsAdministrator(objectOwner))
+ if (IsFriendWithPerms(user, objectOwner) )
return PermissionClass.Owner;
+
+ // Group permissions
+ if (obj.GroupID != UUID.Zero && IsGroupMember(obj.GroupID, user, 0))
+ return PermissionClass.Group;
}
-*/
- // Group permissions
- if ((obj.GroupID != UUID.Zero) && IsGroupMember(obj.GroupID, user, 0))
- return PermissionClass.Group;
return PermissionClass.Everyone;
}
- ///
- /// General permissions checks for any operation involving an object. These supplement more specific checks
- /// implemented by callers.
- ///
- ///
- /// This is a scene object group UUID
- ///
- ///
- protected bool GenericObjectPermission(UUID currentUser, UUID objId, bool denyOnLocked)
+ // get effective object permissions using user UUID. User rights will be fixed
+ protected uint GetObjectPermissions(UUID currentUser, SceneObjectGroup group, bool denyOnLocked)
{
- // Default: deny
- bool permission = false;
- bool locked = false;
+ if (group == null)
+ return 0;
- SceneObjectPart part = m_scene.GetSceneObjectPart(objId);
-
- if (part == null)
- return false;
-
- SceneObjectGroup group = part.ParentGroup;
+ SceneObjectPart root = group.RootPart;
+ if (root == null)
+ return 0;
UUID objectOwner = group.OwnerID;
- locked = ((group.RootPart.OwnerMask & PERM_LOCKED) == 0);
+ bool locked = denyOnLocked && ((root.OwnerMask & (uint)PermissionMask.Move) == 0);
- // People shouldn't be able to do anything with locked objects, except the Administrator
- // The 'set permissions' runs through a different permission check, so when an object owner
- // sets an object locked, the only thing that they can do is unlock it.
- //
- // Nobody but the object owner can set permissions on an object
- //
- if (locked && (!IsAdministrator(currentUser)) && denyOnLocked)
- {
- return false;
- }
-
- // Object owners should be able to edit their own content
- if (currentUser == objectOwner)
- {
- // there is no way that later code can change this back to false
- // so just return true immediately and short circuit the more
- // expensive group checks
- return true;
-
- //permission = true;
- }
- else if (group.IsAttachment)
- {
- permission = false;
- }
-
-// m_log.DebugFormat(
-// "[PERMISSIONS]: group.GroupID = {0}, part.GroupMask = {1}, isGroupMember = {2} for {3}",
-// group.GroupID,
-// m_scene.GetSceneObjectPart(objId).GroupMask,
-// IsGroupMember(group.GroupID, currentUser, 0),
-// currentUser);
-
- // Group members should be able to edit group objects
- if ((group.GroupID != UUID.Zero)
- && ((m_scene.GetSceneObjectPart(objId).GroupMask & (uint)PermissionMask.Modify) != 0)
- && IsGroupMember(group.GroupID, currentUser, 0))
- {
- // Return immediately, so that the administrator can shares group objects
- return true;
- }
-
- // Friends with benefits should be able to edit the objects too
- if (IsFriendWithPerms(currentUser, objectOwner))
- {
- // Return immediately, so that the administrator can share objects with friends
- return true;
- }
-
- // Users should be able to edit what is over their land.
- ILandObject parcel = m_scene.LandChannel.GetLandObject(group.AbsolutePosition.X, group.AbsolutePosition.Y);
- if ((parcel != null) && (parcel.LandData.OwnerID == currentUser))
- {
- permission = true;
- }
-
- // Estate users should be able to edit anything in the sim
- if (IsEstateManager(currentUser))
- {
- permission = true;
- }
-
- // Admin objects should not be editable by the above
- if (IsAdministrator(objectOwner))
- {
- permission = false;
- }
-
- // Admin should be able to edit anything in the sim (including admin objects)
if (IsAdministrator(currentUser))
{
- permission = true;
+ // do lock on admin owned objects
+ if(locked && currentUser == objectOwner)
+ return (uint)(PermissionMask.AllEffective & ~(PermissionMask.Modify | PermissionMask.Move));
+ return (uint)PermissionMask.AllEffective;
}
- return permission;
+ uint lockmask = (uint)PermissionMask.AllEffective;
+ if(locked)
+ lockmask &= ~(uint)(PermissionMask.Modify | PermissionMask.Move);
+
+ if (currentUser == objectOwner)
+ return group.EffectiveOwnerPerms & lockmask;
+
+ if (group.IsAttachment)
+ return 0;
+
+ UUID sogGroupID = group.GroupID;
+ bool notgroudOwned = sogGroupID != objectOwner;
+
+ if (notgroudOwned && IsFriendWithPerms(currentUser, objectOwner))
+ return group.EffectiveOwnerPerms & lockmask;
+
+ ulong powers = 0;
+ if (sogGroupID != UUID.Zero && GroupMemberPowers(sogGroupID, currentUser, ref powers))
+ {
+ if(notgroudOwned)
+ return group.EffectiveGroupOrEveryOnePerms & lockmask;
+
+ if((powers & (ulong)GroupPowers.ObjectManipulate) == 0)
+ return group.EffectiveGroupOrEveryOnePerms & lockmask;
+
+ uint grpEffectiveOwnerPerms = group.EffectiveOwnerPerms & lockmask;
+ if((grpEffectiveOwnerPerms & (uint)PermissionMask.Transfer) == 0)
+ grpEffectiveOwnerPerms &= ~(uint)PermissionMask.Copy;
+ return grpEffectiveOwnerPerms;
+ }
+
+ return group.EffectiveEveryOnePerms & lockmask;
}
+ // get effective object permissions using present presence. So some may depend on requested rights (ie God)
+ protected uint GetObjectPermissions(ScenePresence sp, SceneObjectGroup group, bool denyOnLocked)
+ {
+ if (sp == null || sp.IsDeleted || group == null || group.IsDeleted)
+ return 0;
+
+ SceneObjectPart root = group.RootPart;
+ if (root == null)
+ return 0;
+
+ UUID spID = sp.UUID;
+ UUID objectOwner = group.OwnerID;
+
+ bool locked = denyOnLocked && ((root.OwnerMask & (uint)PermissionMask.Move) == 0);
+
+ if (sp.IsGod)
+ {
+ if(locked && spID == objectOwner)
+ return (uint)(PermissionMask.AllEffective & ~(PermissionMask.Modify | PermissionMask.Move));
+ return (uint)PermissionMask.AllEffective;
+ }
+
+ uint lockmask = (uint)PermissionMask.AllEffective;
+ if(locked)
+ lockmask &= ~(uint)(PermissionMask.Modify | PermissionMask.Move);
+
+ if (spID == objectOwner)
+ return group.EffectiveOwnerPerms & lockmask;
+
+ if (group.IsAttachment)
+ return 0;
+
+ UUID sogGroupID = group.GroupID;
+ bool notgroudOwned = sogGroupID != objectOwner;
+
+ if (notgroudOwned && IsFriendWithPerms(spID, objectOwner))
+ return group.EffectiveOwnerPerms & lockmask;
+
+ ulong powers = 0;
+ if (sogGroupID != UUID.Zero && GroupMemberPowers(sogGroupID, sp, ref powers))
+ {
+ if(notgroudOwned)
+ return group.EffectiveGroupOrEveryOnePerms & lockmask;
+
+ if((powers & (ulong)GroupPowers.ObjectManipulate) == 0)
+ return group.EffectiveGroupOrEveryOnePerms & lockmask;
+
+ uint grpEffectiveOwnerPerms = group.EffectiveOwnerPerms & lockmask;
+ if((grpEffectiveOwnerPerms & (uint)PermissionMask.Transfer) == 0)
+ grpEffectiveOwnerPerms &= ~(uint)PermissionMask.Copy;
+ return grpEffectiveOwnerPerms;
+ }
+
+ return group.EffectiveEveryOnePerms & lockmask;
+ }
+
+ private uint GetObjectItemPermissions(UUID userID, TaskInventoryItem ti)
+ {
+ UUID tiOwnerID = ti.OwnerID;
+ if(tiOwnerID == userID)
+ return ti.CurrentPermissions;
+
+ if(IsAdministrator(userID))
+ return (uint)PermissionMask.AllEffective;
+ // ??
+ if (IsFriendWithPerms(userID, tiOwnerID))
+ return ti.CurrentPermissions;
+
+ UUID tiGroupID = ti.GroupID;
+ if(tiGroupID != UUID.Zero)
+ {
+ ulong powers = 0;
+ if(GroupMemberPowers(tiGroupID, userID, ref powers))
+ {
+ if(tiGroupID == ti.OwnerID)
+ {
+ if((powers & (ulong)GroupPowers.ObjectManipulate) != 0)
+ return ti.CurrentPermissions;
+ }
+ return ti.GroupPermissions;
+ }
+ }
+
+ return 0;
+ }
+
+ private uint GetObjectItemPermissions(ScenePresence sp, TaskInventoryItem ti, bool notEveryone)
+ {
+ UUID tiOwnerID = ti.OwnerID;
+ UUID spID = sp.UUID;
+
+ if(tiOwnerID == spID)
+ return ti.CurrentPermissions;
+
+ // ??
+ if (IsFriendWithPerms(spID, tiOwnerID))
+ return ti.CurrentPermissions;
+
+ UUID tiGroupID = ti.GroupID;
+ if(tiGroupID != UUID.Zero)
+ {
+ ulong powers = 0;
+ if(GroupMemberPowers(tiGroupID, spID, ref powers))
+ {
+ if(tiGroupID == ti.OwnerID)
+ {
+ if((powers & (ulong)GroupPowers.ObjectManipulate) != 0)
+ return ti.CurrentPermissions;
+ }
+ uint p = ti.GroupPermissions;
+ if(!notEveryone)
+ p |= ti.EveryonePermissions;
+ return p;
+ }
+ }
+
+ if(notEveryone)
+ return 0;
+
+ return ti.EveryonePermissions;
+ }
#endregion
#region Generic Permissions
@@ -869,89 +1147,37 @@ namespace OpenSim.Region.CoreModules.World.Permissions
public bool GenericEstatePermission(UUID user)
{
- // Default: deny
- bool permission = false;
-
// Estate admins should be able to use estate tools
if (IsEstateManager(user))
- permission = true;
+ return true;
// Administrators always have permission
if (IsAdministrator(user))
- permission = true;
+ return true;
- return permission;
- }
-
- protected bool GenericParcelPermission(UUID user, ILandObject parcel, ulong groupPowers)
- {
- bool permission = false;
-
- if (parcel.LandData.OwnerID == user)
- {
- permission = true;
- }
-
- if ((parcel.LandData.GroupID != UUID.Zero) && IsGroupMember(parcel.LandData.GroupID, user, groupPowers))
- {
- permission = true;
- }
-
- if (IsEstateManager(user))
- {
- permission = true;
- }
-
- if (IsAdministrator(user))
- {
- permission = true;
- }
-
- if (m_SimpleBuildPermissions &&
- (parcel.LandData.Flags & (uint)ParcelFlags.UseAccessList) == 0 && parcel.IsInLandAccessList(user))
- permission = true;
-
- return permission;
+ return false;
}
protected bool GenericParcelOwnerPermission(UUID user, ILandObject parcel, ulong groupPowers, bool allowEstateManager)
{
if (parcel.LandData.OwnerID == user)
- {
- // Returning immediately so that group deeded objects on group deeded land don't trigger a NRE on
- // the subsequent redundant checks when using lParcelMediaCommandList()
- // See http://opensimulator.org/mantis/view.php?id=3999 for more details
return true;
- }
if (parcel.LandData.IsGroupOwned && IsGroupMember(parcel.LandData.GroupID, user, groupPowers))
- {
return true;
- }
if (allowEstateManager && IsEstateManager(user))
- {
return true;
- }
if (IsAdministrator(user))
- {
return true;
- }
return false;
}
-
- protected bool GenericParcelPermission(UUID user, Vector3 pos, ulong groupPowers)
- {
- ILandObject parcel = m_scene.LandChannel.GetLandObject(pos.X, pos.Y);
- if (parcel == null) return false;
- return GenericParcelPermission(user, parcel, groupPowers);
- }
#endregion
#region Permission Checks
- private bool CanAbandonParcel(UUID user, ILandObject parcel, Scene scene)
+ private bool CanAbandonParcel(UUID user, ILandObject parcel)
{
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
if (m_bypassPermissions) return m_bypassPermissionsValue;
@@ -959,7 +1185,7 @@ namespace OpenSim.Region.CoreModules.World.Permissions
return GenericParcelOwnerPermission(user, parcel, (ulong)GroupPowers.LandRelease, false);
}
- private bool CanReclaimParcel(UUID user, ILandObject parcel, Scene scene)
+ private bool CanReclaimParcel(UUID user, ILandObject parcel)
{
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
if (m_bypassPermissions) return m_bypassPermissionsValue;
@@ -967,108 +1193,252 @@ namespace OpenSim.Region.CoreModules.World.Permissions
return GenericParcelOwnerPermission(user, parcel, 0,true);
}
- private bool CanDeedParcel(UUID user, ILandObject parcel, Scene scene)
+ private bool CanDeedParcel(UUID user, ILandObject parcel)
{
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
if (m_bypassPermissions) return m_bypassPermissionsValue;
+ if(parcel.LandData.GroupID == UUID.Zero)
+ return false;
+
+ if (IsAdministrator(user))
+ return true;
+
if (parcel.LandData.OwnerID != user) // Only the owner can deed!
return false;
- ScenePresence sp = scene.GetScenePresence(user);
- IClientAPI client = sp.ControllingClient;
-
- if ((client.GetGroupPowers(parcel.LandData.GroupID) & (ulong)GroupPowers.LandDeed) == 0)
+ ScenePresence sp = m_scene.GetScenePresence(user);
+ if(sp == null)
return false;
- return GenericParcelOwnerPermission(user, parcel, (ulong)GroupPowers.LandDeed, false);
- }
-
- private bool CanDeedObject(UUID user, UUID group, Scene scene)
- {
- DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
- if (m_bypassPermissions) return m_bypassPermissionsValue;
-
- ScenePresence sp = scene.GetScenePresence(user);
IClientAPI client = sp.ControllingClient;
-
- if ((client.GetGroupPowers(group) & (ulong)GroupPowers.DeedObject) == 0)
+ if ((client.GetGroupPowers(parcel.LandData.GroupID) & (ulong)GroupPowers.LandDeed) == 0)
return false;
return true;
}
- private bool IsGod(UUID user, Scene scene)
+ private bool CanDeedObject(ScenePresence sp, SceneObjectGroup sog, UUID targetGroupID)
{
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
if (m_bypassPermissions) return m_bypassPermissionsValue;
- return IsAdministrator(user);
+ if(sog == null || sog.IsDeleted || sp == null || sp.IsDeleted || targetGroupID == UUID.Zero)
+ return false;
+
+ // object has group already?
+ if(sog.GroupID != targetGroupID)
+ return false;
+
+ // is effectivelly shared?
+ if(sog.EffectiveGroupPerms == 0)
+ return false;
+
+ if(sp.IsGod)
+ return true;
+
+ // owned by requester?
+ if(sog.OwnerID != sp.UUID)
+ return false;
+
+ // owner can transfer?
+ if((sog.EffectiveOwnerPerms & (uint)PermissionMask.Transfer) == 0)
+ return false;
+
+ // group member ?
+ ulong powers = 0;
+ if(!GroupMemberPowers(targetGroupID, sp, ref powers))
+ return false;
+
+ // has group rights?
+ if ((powers & (ulong)GroupPowers.DeedObject) == 0)
+ return false;
+
+ return true;
}
- private bool CanDuplicateObject(int objectCount, UUID objectID, UUID owner, Scene scene, Vector3 objectPosition)
+ private bool CanDuplicateObject(SceneObjectGroup sog, ScenePresence sp)
{
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
if (m_bypassPermissions) return m_bypassPermissionsValue;
- if (!GenericObjectPermission(owner, objectID, true))
- {
- //They can't even edit the object
- return false;
- }
-
- SceneObjectPart part = scene.GetSceneObjectPart(objectID);
- if (part == null)
+ if (sog == null || sog.IsDeleted || sp == null || sp.IsDeleted)
return false;
- if (part.OwnerID == owner)
- {
- if ((part.OwnerMask & PERM_COPY) == 0)
- return false;
- }
- else if (part.GroupID != UUID.Zero)
- {
- if ((part.OwnerID == part.GroupID) && ((owner != part.LastOwnerID) || ((part.GroupMask & PERM_TRANS) == 0)))
- return false;
+ uint perms = GetObjectPermissions(sp, sog, false);
+ if((perms & (uint)PermissionMask.Copy) == 0)
+ return false;
- if ((part.GroupMask & PERM_COPY) == 0)
- return false;
- }
+ if(sog.OwnerID != sp.UUID && (perms & (uint)PermissionMask.Transfer) == 0)
+ return false;
//If they can rez, they can duplicate
- return CanRezObject(objectCount, owner, objectPosition, scene);
+ return CanRezObject(0, sp.UUID, sog.AbsolutePosition);
}
- private bool CanDeleteObject(UUID objectID, UUID deleter, Scene scene)
+ private bool CanDeleteObject(SceneObjectGroup sog, ScenePresence sp)
+ {
+ // ignoring locked. viewers should warn and ask for confirmation
+
+ DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
+ if (m_bypassPermissions) return m_bypassPermissionsValue;
+
+ if (sog == null || sog.IsDeleted || sp == null || sp.IsDeleted)
+ return false;
+
+ if(sog.IsAttachment)
+ return false;
+
+ UUID sogOwnerID = sog.OwnerID;
+ UUID spID = sp.UUID;
+
+ if(sogOwnerID == spID)
+ return true;
+
+ if (sp.IsGod)
+ return true;
+
+ if (IsFriendWithPerms(sog.UUID, sogOwnerID))
+ return true;
+
+ UUID sogGroupID = sog.GroupID;
+ if (sogGroupID != UUID.Zero)
+ {
+ ulong powers = 0;
+ if(GroupMemberPowers(sogGroupID, sp, ref powers))
+ {
+ if(sogGroupID == sogOwnerID)
+ {
+ if((powers & (ulong)GroupPowers.ObjectManipulate) != 0)
+ return true;
+ }
+ return (sog.EffectiveGroupPerms & (uint)PermissionMask.Modify) != 0;
+ }
+ }
+ return false;
+ }
+
+ private bool CanDeleteObjectByIDs(UUID objectID, UUID userID)
+ {
+ // ignoring locked. viewers should warn and ask for confirmation
+
+ DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
+ if (m_bypassPermissions) return m_bypassPermissionsValue;
+
+ SceneObjectGroup sog = m_scene.GetGroupByPrim(objectID);
+ if (sog == null)
+ return false;
+
+ if(sog.IsAttachment)
+ return false;
+
+ UUID sogOwnerID = sog.OwnerID;
+
+ if(sogOwnerID == userID)
+ return true;
+
+ if (IsAdministrator(userID))
+ return true;
+
+ if (IsFriendWithPerms(objectID, sogOwnerID))
+ return true;
+
+ UUID sogGroupID = sog.GroupID;
+ if (sogGroupID != UUID.Zero)
+ {
+ ulong powers = 0;
+ if(GroupMemberPowers(sogGroupID, userID, ref powers))
+ {
+ if(sogGroupID == sogOwnerID)
+ {
+ if((powers & (ulong)GroupPowers.ObjectManipulate) != 0)
+ return true;
+ }
+ return (sog.EffectiveGroupPerms & (uint)PermissionMask.Modify) != 0;
+ }
+ }
+ return false;
+ }
+
+ private bool CanEditObjectByIDs(UUID objectID, UUID userID)
{
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
if (m_bypassPermissions) return m_bypassPermissionsValue;
- return GenericObjectPermission(deleter, objectID, false);
+ SceneObjectGroup sog = m_scene.GetGroupByPrim(objectID);
+ if (sog == null)
+ return false;
+
+ uint perms = GetObjectPermissions(userID, sog, true);
+ if((perms & (uint)PermissionMask.Modify) == 0)
+ return false;
+ return true;
}
- private bool CanEditObject(UUID objectID, UUID editorID, Scene scene)
+ private bool CanEditObject(SceneObjectGroup sog, ScenePresence sp)
{
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
if (m_bypassPermissions) return m_bypassPermissionsValue;
- return GenericObjectPermission(editorID, objectID, false);
+ if(sog == null || sog.IsDeleted || sp == null || sp.IsDeleted)
+ return false;
+
+ uint perms = GetObjectPermissions(sp, sog, true);
+ if((perms & (uint)PermissionMask.Modify) == 0)
+ return false;
+ return true;
}
- private bool CanEditObjectInventory(UUID objectID, UUID editorID, Scene scene)
+ private bool CanEditObjectPerms(SceneObjectGroup sog, UUID userID)
{
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
if (m_bypassPermissions) return m_bypassPermissionsValue;
- return GenericObjectPermission(editorID, objectID, false);
+ if (sog == null)
+ return false;
+
+ if(sog.OwnerID == userID || IsAdministrator(userID))
+ return true;
+
+ UUID sogGroupID = sog.GroupID;
+ if(sogGroupID == UUID.Zero || sogGroupID != sog.OwnerID)
+ return false;
+
+ uint perms = sog.EffectiveOwnerPerms;
+ if((perms & (uint)PermissionMask.Modify) == 0)
+ return false;
+
+ ulong powers = 0;
+ if(GroupMemberPowers(sogGroupID, userID, ref powers))
+ {
+ if((powers & (ulong)GroupPowers.ObjectManipulate) != 0)
+ return true;
+ }
+
+ return false;
}
- private bool CanEditParcelProperties(UUID user, ILandObject parcel, GroupPowers p, Scene scene, bool allowManager)
+ private bool CanEditObjectInventory(UUID objectID, UUID userID)
{
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
if (m_bypassPermissions) return m_bypassPermissionsValue;
- return GenericParcelOwnerPermission(user, parcel, (ulong)p, false);
+ SceneObjectGroup sog = m_scene.GetGroupByPrim(objectID);
+ if (sog == null)
+ return false;
+
+ uint perms = GetObjectPermissions(userID, sog, true);
+ if((perms & (uint)PermissionMask.Modify) == 0)
+ return false;
+ return true;
+ }
+
+ private bool CanEditParcelProperties(UUID userID, ILandObject parcel, GroupPowers p, bool allowManager)
+ {
+ DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
+ if (m_bypassPermissions) return m_bypassPermissionsValue;
+
+ return GenericParcelOwnerPermission(userID, parcel, (ulong)p, false);
}
///
@@ -1079,18 +1449,18 @@ namespace OpenSim.Region.CoreModules.World.Permissions
///
///
///
- private bool CanEditScript(UUID script, UUID objectID, UUID user, Scene scene)
+ private bool CanEditScript(UUID script, UUID objectID, UUID userID)
{
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
if (m_bypassPermissions) return m_bypassPermissionsValue;
- if (m_allowedScriptEditors == UserSet.Administrators && !IsAdministrator(user))
+ if (m_allowedScriptEditors == UserSet.Administrators && !IsAdministrator(userID))
return false;
// Ordinarily, if you can view it, you can edit it
// There is no viewing a no mod script
//
- return CanViewScript(script, objectID, user, scene);
+ return CanViewScript(script, objectID, userID);
}
///
@@ -1101,7 +1471,7 @@ namespace OpenSim.Region.CoreModules.World.Permissions
///
///
///
- private bool CanEditNotecard(UUID notecard, UUID objectID, UUID user, Scene scene)
+ private bool CanEditNotecard(UUID notecard, UUID objectID, UUID user)
{
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
if (m_bypassPermissions) return m_bypassPermissionsValue;
@@ -1132,69 +1502,68 @@ namespace OpenSim.Region.CoreModules.World.Permissions
}
else // Prim inventory
{
- SceneObjectPart part = scene.GetSceneObjectPart(objectID);
-
+ SceneObjectPart part = m_scene.GetSceneObjectPart(objectID);
if (part == null)
return false;
- if (part.OwnerID != user)
- {
- if (part.GroupID == UUID.Zero)
- return false;
-
- if (!IsGroupMember(part.GroupID, user, 0))
- return false;
-
- if ((part.GroupMask & (uint)PermissionMask.Modify) == 0)
- return false;
- }
- else
- {
- if ((part.OwnerMask & (uint)PermissionMask.Modify) == 0)
+ SceneObjectGroup sog = part.ParentGroup;
+ if (sog == null)
+ return false;
+
+ // check object mod right
+ uint perms = GetObjectPermissions(user, sog, true);
+ if((perms & (uint)PermissionMask.Modify) == 0)
return false;
- }
TaskInventoryItem ti = part.Inventory.GetInventoryItem(notecard);
-
if (ti == null)
return false;
-
+
if (ti.OwnerID != user)
{
- if (ti.GroupID == UUID.Zero)
+ UUID tiGroupID = ti.GroupID;
+ if (tiGroupID == UUID.Zero)
return false;
- if (!IsGroupMember(ti.GroupID, user, 0))
+ ulong powers = 0;
+ if(!GroupMemberPowers(tiGroupID, user, ref powers))
return false;
+
+ if(tiGroupID == ti.OwnerID && (powers & (ulong)GroupPowers.ObjectManipulate) != 0)
+ {
+ if ((ti.CurrentPermissions & ((uint)PermissionMask.Modify | (uint)PermissionMask.Copy)) ==
+ ((uint)PermissionMask.Modify | (uint)PermissionMask.Copy))
+ return true;
+ }
+ if ((ti.GroupPermissions & ((uint)PermissionMask.Modify | (uint)PermissionMask.Copy)) ==
+ ((uint)PermissionMask.Modify | (uint)PermissionMask.Copy))
+ return true;
+ return false;
}
// Require full perms
- if ((ti.CurrentPermissions &
- ((uint)PermissionMask.Modify |
- (uint)PermissionMask.Copy)) !=
- ((uint)PermissionMask.Modify |
- (uint)PermissionMask.Copy))
+ if ((ti.CurrentPermissions & ((uint)PermissionMask.Modify | (uint)PermissionMask.Copy)) !=
+ ((uint)PermissionMask.Modify | (uint)PermissionMask.Copy))
return false;
}
-
return true;
}
- private bool CanInstantMessage(UUID user, UUID target, Scene startScene)
+ private bool CanInstantMessage(UUID user, UUID target)
{
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
if (m_bypassPermissions) return m_bypassPermissionsValue;
// If the sender is an object, check owner instead
//
- SceneObjectPart part = startScene.GetSceneObjectPart(user);
+ SceneObjectPart part = m_scene.GetSceneObjectPart(user);
if (part != null)
user = part.OwnerID;
return GenericCommunicationPermission(user, target);
}
- private bool CanInventoryTransfer(UUID user, UUID target, Scene startScene)
+ private bool CanInventoryTransfer(UUID user, UUID target)
{
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
if (m_bypassPermissions) return m_bypassPermissionsValue;
@@ -1202,7 +1571,7 @@ namespace OpenSim.Region.CoreModules.World.Permissions
return GenericCommunicationPermission(user, target);
}
- private bool CanIssueEstateCommand(UUID user, Scene requestFromScene, bool ownerCommand)
+ private bool CanIssueEstateCommand(UUID user, bool ownerCommand)
{
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
if (m_bypassPermissions) return m_bypassPermissionsValue;
@@ -1210,178 +1579,161 @@ namespace OpenSim.Region.CoreModules.World.Permissions
if (IsAdministrator(user))
return true;
- if (m_scene.RegionInfo.EstateSettings.IsEstateOwner(user))
- return true;
-
if (ownerCommand)
- return false;
+ return m_scene.RegionInfo.EstateSettings.IsEstateOwner(user);
- return GenericEstatePermission(user);
+ return IsEstateManager(user);
}
- private bool CanMoveObject(UUID objectID, UUID moverID, Scene scene)
+ private bool CanMoveObject(SceneObjectGroup sog, ScenePresence sp)
{
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
+
+ if(sog == null || sog.IsDeleted || sp == null || sp.IsDeleted)
+ return false;
+
if (m_bypassPermissions)
{
- SceneObjectPart part = scene.GetSceneObjectPart(objectID);
- if (part.OwnerID != moverID)
- {
- if (!part.ParentGroup.IsDeleted)
- {
- if (part.ParentGroup.IsAttachment)
- return false;
- }
- }
+ if (sog.OwnerID != sp.UUID && sog.IsAttachment)
+ return false;
return m_bypassPermissionsValue;
}
- bool permission = GenericObjectPermission(moverID, objectID, true);
- if (!permission)
- {
- if (!m_scene.Entities.ContainsKey(objectID))
- {
- return false;
- }
-
- // The client
- // may request to edit linked parts, and therefore, it needs
- // to also check for SceneObjectPart
-
- // If it's not an object, we cant edit it.
- if ((!(m_scene.Entities[objectID] is SceneObjectGroup)))
- {
- return false;
- }
-
-
- SceneObjectGroup task = (SceneObjectGroup)m_scene.Entities[objectID];
-
-
- // UUID taskOwner = null;
- // Added this because at this point in time it wouldn't be wise for
- // the administrator object permissions to take effect.
- // UUID objectOwner = task.OwnerID;
-
- // Anyone can move
- if ((task.RootPart.EveryoneMask & PERM_MOVE) != 0)
- permission = true;
-
- // Locked
- if ((task.RootPart.OwnerMask & PERM_LOCKED) == 0)
- permission = false;
- }
- else
- {
- bool locked = false;
- if (!m_scene.Entities.ContainsKey(objectID))
- {
- return false;
- }
-
- // If it's not an object, we cant edit it.
- if ((!(m_scene.Entities[objectID] is SceneObjectGroup)))
- {
- return false;
- }
-
- SceneObjectGroup group = (SceneObjectGroup)m_scene.Entities[objectID];
-
- UUID objectOwner = group.OwnerID;
- locked = ((group.RootPart.OwnerMask & PERM_LOCKED) == 0);
-
- // This is an exception to the generic object permission.
- // Administrators who lock their objects should not be able to move them,
- // however generic object permission should return true.
- // This keeps locked objects from being affected by random click + drag actions by accident
- // and allows the administrator to grab or delete a locked object.
-
- // Administrators and estate managers are still able to click+grab locked objects not
- // owned by them in the scene
- // This is by design.
-
- if (locked && (moverID == objectOwner))
- return false;
- }
- return permission;
+ uint perms = GetObjectPermissions(sp, sog, true);
+ if((perms & (uint)PermissionMask.Move) == 0)
+ return false;
+ return true;
}
- private bool CanObjectEntry(UUID objectID, bool enteringRegion, Vector3 newPoint, Scene scene)
+ private bool CanObjectEntry(SceneObjectGroup sog, bool enteringRegion, Vector3 newPoint)
{
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
- if (m_bypassPermissions) return m_bypassPermissionsValue;
+ float newX = newPoint.X;
+ float newY = newPoint.Y;
- // allow outide region??
- if (newPoint.X < -1f || newPoint.Y < -1f)
+ // allow outside region this is needed for crossings
+ if (newX < -1f || newX > (m_scene.RegionInfo.RegionSizeX + 1.0f) ||
+ newY < -1f || newY > (m_scene.RegionInfo.RegionSizeY + 1.0f) )
return true;
- if (newPoint.X > scene.RegionInfo.RegionSizeX + 1.0f || newPoint.Y > scene.RegionInfo.RegionSizeY + 1.0f)
- {
+
+ if(sog == null || sog.IsDeleted)
+ return false;
+
+ if (m_bypassPermissions)
+ return m_bypassPermissionsValue;
+
+ ILandObject parcel = m_scene.LandChannel.GetLandObject(newX, newY);
+ if (parcel == null)
+ return false;
+
+ if ((parcel.LandData.Flags & ((int)ParcelFlags.AllowAPrimitiveEntry)) != 0)
return true;
- }
-
- SceneObjectGroup task = (SceneObjectGroup)m_scene.Entities[objectID];
-
- ILandObject land = m_scene.LandChannel.GetLandObject(newPoint.X, newPoint.Y);
if (!enteringRegion)
{
- ILandObject fromland = m_scene.LandChannel.GetLandObject(task.AbsolutePosition.X, task.AbsolutePosition.Y);
-
- if (fromland == land) // Not entering
+ Vector3 oldPoint = sog.AbsolutePosition;
+ ILandObject fromparcel = m_scene.LandChannel.GetLandObject(oldPoint.X, oldPoint.Y);
+ if (fromparcel != null && fromparcel.Equals(parcel)) // it already entered parcel ????
return true;
}
- if (land == null)
- {
- return false;
- }
+ UUID userID = sog.OwnerID;
+ LandData landdata = parcel.LandData;
- if ((land.LandData.Flags & ((int)ParcelFlags.AllowAPrimitiveEntry)) != 0)
- {
+ if (landdata.OwnerID == userID)
return true;
- }
- if (!m_scene.Entities.ContainsKey(objectID))
- {
- return false;
- }
-
- // If it's not an object, we cant edit it.
- if (!(m_scene.Entities[objectID] is SceneObjectGroup))
- {
- return false;
- }
-
-
- if (GenericParcelPermission(task.OwnerID, newPoint, 0))
- {
+ if (IsAdministrator(userID))
return true;
+
+ UUID landGroupID = landdata.GroupID;
+ if (landGroupID != UUID.Zero)
+ {
+ if ((parcel.LandData.Flags & ((int)ParcelFlags.AllowGroupObjectEntry)) != 0)
+ return IsGroupMember(landGroupID, userID, 0);
+
+ if (landdata.IsGroupOwned && IsGroupMember(landGroupID, userID, (ulong)GroupPowers.AllowRez))
+ return true;
}
//Otherwise, false!
return false;
}
- private bool CanReturnObjects(ILandObject land, UUID user, List objects, Scene scene)
+ private bool OnObjectEnterWithScripts(SceneObjectGroup sog, ILandObject parcel)
+ {
+ DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
+
+ if(sog == null || sog.IsDeleted)
+ return false;
+
+ if (m_bypassPermissions)
+ return m_bypassPermissionsValue;
+
+ if (parcel == null)
+ return true;
+
+ int checkflags = ((int)ParcelFlags.AllowAPrimitiveEntry);
+ bool scripts = (sog.ScriptCount() > 0);
+ if(scripts)
+ checkflags |= ((int)ParcelFlags.AllowOtherScripts);
+
+ if ((parcel.LandData.Flags & checkflags) == checkflags)
+ return true;
+
+ UUID userID = sog.OwnerID;
+ LandData landdata = parcel.LandData;
+
+ if (landdata.OwnerID == userID)
+ return true;
+
+ if (IsAdministrator(userID))
+ return true;
+
+ UUID landGroupID = landdata.GroupID;
+ if (landGroupID != UUID.Zero)
+ {
+ checkflags = (int)ParcelFlags.AllowGroupObjectEntry;
+ if(scripts)
+ checkflags |= ((int)ParcelFlags.AllowGroupScripts);
+
+ if ((parcel.LandData.Flags & checkflags) == checkflags)
+ return IsGroupMember(landGroupID, userID, 0);
+
+ if (landdata.IsGroupOwned && IsGroupMember(landGroupID, userID, (ulong)GroupPowers.AllowRez))
+ return true;
+ }
+
+ //Otherwise, false!
+ return false;
+ }
+
+ private bool CanReturnObjects(ILandObject land, ScenePresence sp, List objects)
{
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
if (m_bypassPermissions) return m_bypassPermissionsValue;
- GroupPowers powers;
- ILandObject l;
+ if(sp == null)
+ return true; // assuming that in this case rights are as owner
- ScenePresence sp = scene.GetScenePresence(user);
- if (sp == null)
- return false;
+ UUID userID = sp.UUID;
+ bool isPrivUser = sp.IsGod || IsEstateManager(userID);
IClientAPI client = sp.ControllingClient;
+ ulong powers = 0;
+ ILandObject l;
+
foreach (SceneObjectGroup g in new List(objects))
{
- // Any user can return their own objects at any time
- //
- if (GenericObjectPermission(user, g.UUID, false))
+ if(g.IsAttachment)
+ {
+ objects.Remove(g);
+ continue;
+ }
+
+ if (isPrivUser || g.OwnerID == userID)
continue;
// This is a short cut for efficiency. If land is non-null,
@@ -1395,39 +1747,40 @@ namespace OpenSim.Region.CoreModules.World.Permissions
else
{
Vector3 pos = g.AbsolutePosition;
-
- l = scene.LandChannel.GetLandObject(pos.X, pos.Y);
+ l = m_scene.LandChannel.GetLandObject(pos.X, pos.Y);
}
// If it's not over any land, then we can't do a thing
- if (l == null)
+ if (l == null || l.LandData == null)
{
objects.Remove(g);
continue;
}
+ LandData ldata = l.LandData;
// If we own the land outright, then allow
//
- if (l.LandData.OwnerID == user)
+ if (ldata.OwnerID == userID)
continue;
// Group voodoo
//
- if (l.LandData.IsGroupOwned)
+ if (ldata.IsGroupOwned)
{
- powers = (GroupPowers)client.GetGroupPowers(l.LandData.GroupID);
+ UUID lGroupID = ldata.GroupID;
// Not a group member, or no rights at all
//
- if (powers == (GroupPowers)0)
+ powers = client.GetGroupPowers(lGroupID);
+ if(powers == 0)
{
objects.Remove(g);
continue;
}
-
+
// Group deeded object?
//
- if (g.OwnerID == l.LandData.GroupID &&
- (powers & GroupPowers.ReturnGroupOwned) == (GroupPowers)0)
+ if (g.OwnerID == lGroupID &&
+ (powers & (ulong)GroupPowers.ReturnGroupOwned) == 0)
{
objects.Remove(g);
continue;
@@ -1435,14 +1788,14 @@ namespace OpenSim.Region.CoreModules.World.Permissions
// Group set object?
//
- if (g.GroupID == l.LandData.GroupID &&
- (powers & GroupPowers.ReturnGroupSet) == (GroupPowers)0)
+ if (g.GroupID == lGroupID &&
+ (powers & (ulong)GroupPowers.ReturnGroupSet) == 0)
{
objects.Remove(g);
continue;
}
- if ((powers & GroupPowers.ReturnNonGroup) == (GroupPowers)0)
+ if ((powers & (ulong)GroupPowers.ReturnNonGroup) == 0)
{
objects.Remove(g);
continue;
@@ -1465,41 +1818,41 @@ namespace OpenSim.Region.CoreModules.World.Permissions
return true;
}
- private bool CanRezObject(int objectCount, UUID owner, Vector3 objectPosition, Scene scene)
+ private bool CanRezObject(int objectCount, UUID userID, Vector3 objectPosition)
{
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
- if (m_bypassPermissions) return m_bypassPermissionsValue;
+ if (m_bypassPermissions)
+ return m_bypassPermissionsValue;
// m_log.DebugFormat("[PERMISSIONS MODULE]: Checking rez object at {0} in {1}", objectPosition, m_scene.Name);
ILandObject parcel = m_scene.LandChannel.GetLandObject(objectPosition.X, objectPosition.Y);
- if (parcel == null)
+ if (parcel == null || parcel.LandData == null)
return false;
- if ((parcel.LandData.Flags & (uint)ParcelFlags.CreateObjects) != 0)
- {
+ LandData landdata = parcel.LandData;
+ if ((userID == landdata.OwnerID))
return true;
- }
- else if ((owner == parcel.LandData.OwnerID) || IsAdministrator(owner))
- {
+
+ if ((landdata.Flags & (uint)ParcelFlags.CreateObjects) != 0)
return true;
- }
- else if (((parcel.LandData.Flags & (uint)ParcelFlags.CreateGroupObjects) != 0)
- && (parcel.LandData.GroupID != UUID.Zero) && IsGroupMember(parcel.LandData.GroupID, owner, 0))
- {
+
+ if(IsAdministrator(userID))
return true;
- }
- else if (parcel.LandData.GroupID != UUID.Zero && IsGroupMember(parcel.LandData.GroupID, owner, (ulong)GroupPowers.AllowRez))
+
+ if(landdata.GroupID != UUID.Zero)
{
- return true;
- }
- else
- {
- return false;
+ if ((landdata.Flags & (uint)ParcelFlags.CreateGroupObjects) != 0)
+ return IsGroupMember(landdata.GroupID, userID, 0);
+
+ if (landdata.IsGroupOwned && IsGroupMember(landdata.GroupID, userID, (ulong)GroupPowers.AllowRez))
+ return true;
}
+
+ return false;
}
- private bool CanRunConsoleCommand(UUID user, Scene requestFromScene)
+ private bool CanRunConsoleCommand(UUID user)
{
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
if (m_bypassPermissions) return m_bypassPermissionsValue;
@@ -1508,15 +1861,43 @@ namespace OpenSim.Region.CoreModules.World.Permissions
return IsAdministrator(user);
}
- private bool CanRunScript(UUID script, UUID objectID, UUID user, Scene scene)
+ private bool CanRunScript(TaskInventoryItem scriptitem, SceneObjectPart part)
{
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
if (m_bypassPermissions) return m_bypassPermissionsValue;
- return true;
+ if(scriptitem == null || part == null)
+ return false;
+
+ SceneObjectGroup sog = part.ParentGroup;
+ if(sog == null)
+ return false;
+
+ Vector3 pos = sog.AbsolutePosition;
+ ILandObject parcel = m_scene.LandChannel.GetLandObject(pos.X, pos.Y);
+ if (parcel == null)
+ return false;
+
+ LandData ldata = parcel.LandData;
+ if(ldata == null)
+ return false;
+
+ uint lflags = ldata.Flags;
+
+ if ((lflags & (uint)ParcelFlags.AllowOtherScripts) != 0)
+ return true;
+
+ if ((part.OwnerID == ldata.OwnerID))
+ return true;
+
+ if (((lflags & (uint)ParcelFlags.AllowGroupScripts) != 0)
+ && (ldata.GroupID != UUID.Zero) && (ldata.GroupID == part.GroupID))
+ return true;
+
+ return GenericEstatePermission(part.OwnerID);
}
- private bool CanSellParcel(UUID user, ILandObject parcel, Scene scene)
+ private bool CanSellParcel(UUID user, ILandObject parcel)
{
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
if (m_bypassPermissions) return m_bypassPermissionsValue;
@@ -1524,7 +1905,7 @@ namespace OpenSim.Region.CoreModules.World.Permissions
return GenericParcelOwnerPermission(user, parcel, (ulong)GroupPowers.LandSetSale, true);
}
- private bool CanSellGroupObject(UUID userID, UUID groupID, Scene scene)
+ private bool CanSellGroupObject(UUID userID, UUID groupID)
{
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
if (m_bypassPermissions) return m_bypassPermissionsValue;
@@ -1532,66 +1913,162 @@ namespace OpenSim.Region.CoreModules.World.Permissions
return IsGroupMember(groupID, userID, (ulong)GroupPowers.ObjectSetForSale);
}
- private bool CanTakeObject(UUID objectID, UUID stealer, Scene scene)
+ private bool CanSellObjectByUserID(SceneObjectGroup sog, UUID userID, byte saleType)
{
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
if (m_bypassPermissions) return m_bypassPermissionsValue;
- return GenericObjectPermission(stealer,objectID, false);
+ if (sog == null || sog.IsDeleted || userID == UUID.Zero)
+ return false;
+
+ // sell is not a attachment op
+ if(sog.IsAttachment)
+ return false;
+
+ if(IsAdministrator(userID))
+ return true;
+
+ uint sogEffectiveOwnerPerms = sog.EffectiveOwnerPerms;
+ if((sogEffectiveOwnerPerms & (uint)PermissionMask.Transfer) == 0)
+ return false;
+
+ if(saleType == (byte)SaleType.Copy &&
+ (sogEffectiveOwnerPerms & (uint)PermissionMask.Copy) == 0)
+ return false;
+
+ UUID sogOwnerID = sog.OwnerID;
+
+ if(sogOwnerID == userID)
+ return true;
+
+ // else only group owned can be sold by members with powers
+ UUID sogGroupID = sog.GroupID;
+ if(sog.OwnerID != sogGroupID || sogGroupID == UUID.Zero)
+ return false;
+
+ return IsGroupMember(sogGroupID, userID, (ulong)GroupPowers.ObjectSetForSale);
}
- private bool CanTakeCopyObject(UUID objectID, UUID userID, Scene inScene)
+ private bool CanSellObject(SceneObjectGroup sog, ScenePresence sp, byte saleType)
{
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
if (m_bypassPermissions) return m_bypassPermissionsValue;
- bool permission = GenericObjectPermission(userID, objectID, false);
+ if (sog == null || sog.IsDeleted || sp == null || sp.IsDeleted)
+ return false;
- SceneObjectGroup so = (SceneObjectGroup)m_scene.Entities[objectID];
+ // sell is not a attachment op
+ if(sog.IsAttachment)
+ return false;
- if (!permission)
- {
- if (!m_scene.Entities.ContainsKey(objectID))
- {
- return false;
- }
+ if(sp.IsGod)
+ return true;
- // If it's not an object, we cant edit it.
- if (!(m_scene.Entities[objectID] is SceneObjectGroup))
- {
- return false;
- }
+ uint sogEffectiveOwnerPerms = sog.EffectiveOwnerPerms;
+ if((sogEffectiveOwnerPerms & (uint)PermissionMask.Transfer) == 0)
+ return false;
- // UUID taskOwner = null;
- // Added this because at this point in time it wouldn't be wise for
- // the administrator object permissions to take effect.
- // UUID objectOwner = task.OwnerID;
+ if(saleType == (byte)SaleType.Copy &&
+ (sogEffectiveOwnerPerms & (uint)PermissionMask.Copy) == 0)
+ return false;
- if ((so.RootPart.EveryoneMask & PERM_COPY) != 0)
- permission = true;
- }
+ UUID userID = sp.UUID;
+ UUID sogOwnerID = sog.OwnerID;
- if (so.OwnerID != userID)
- {
- if ((so.GetEffectivePermissions() & (PERM_COPY | PERM_TRANS)) != (PERM_COPY | PERM_TRANS))
- permission = false;
- }
- else
- {
- if ((so.GetEffectivePermissions() & PERM_COPY) != PERM_COPY)
- permission = false;
- }
+ if(sogOwnerID == userID)
+ return true;
- return permission;
+ // else only group owned can be sold by members with powers
+ UUID sogGroupID = sog.GroupID;
+ if(sog.OwnerID != sogGroupID || sogGroupID == UUID.Zero)
+ return false;
+
+ ulong powers = 0;
+ if(!GroupMemberPowers(sogGroupID, sp, ref powers))
+ return false;
+
+ if((powers & (ulong)GroupPowers.ObjectSetForSale) == 0)
+ return false;
+
+ return true;
}
- private bool CanTerraformLand(UUID user, Vector3 position, Scene requestFromScene)
+ private bool CanTakeObject(SceneObjectGroup sog, ScenePresence sp)
+ {
+ // ignore locked, viewers shell ask for confirmation
+ DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
+ if (m_bypassPermissions) return m_bypassPermissionsValue;
+
+ if (sog == null || sog.IsDeleted || sp == null || sp.IsDeleted)
+ return false;
+
+ // take is not a attachment op
+ if(sog.IsAttachment)
+ return false;
+
+ UUID sogOwnerID = sog.OwnerID;
+ UUID spID = sp.UUID;
+
+ if(sogOwnerID == spID)
+ return true;
+
+ if (sp.IsGod)
+ return true;
+
+ if((sog.EffectiveOwnerPerms & (uint)PermissionMask.Transfer) == 0)
+ return false;
+
+ if (IsFriendWithPerms(sog.UUID, sogOwnerID))
+ return true;
+
+ UUID sogGroupID = sog.GroupID;
+ if (sogGroupID != UUID.Zero)
+ {
+ ulong powers = 0;
+ if(GroupMemberPowers(sogGroupID, sp, ref powers))
+ {
+ if(sogGroupID == sogOwnerID)
+ {
+ if((powers & (ulong)GroupPowers.ObjectManipulate) != 0)
+ return true;
+ }
+ return (sog.EffectiveGroupPerms & (uint)PermissionMask.Modify) != 0;
+ }
+ }
+ return false;
+ }
+
+ private bool CanTakeCopyObject(SceneObjectGroup sog, ScenePresence sp)
+ {
+ DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
+ if (m_bypassPermissions) return m_bypassPermissionsValue;
+
+ if (sog == null || sog.IsDeleted || sp == null || sp.IsDeleted)
+ return false;
+
+ // refuse on attachments
+ if(sog.IsAttachment && !sp.IsGod)
+ return false;
+
+ uint perms = GetObjectPermissions(sp, sog, true);
+ if((perms & (uint)PermissionMask.Copy) == 0)
+ {
+ sp.ControllingClient.SendAgentAlertMessage("Copying this item has been denied by the permissions system", false);
+ return false;
+ }
+
+ if(sog.OwnerID != sp.UUID && (perms & (uint)PermissionMask.Transfer) == 0)
+ return false;
+ return true;
+ }
+
+ private bool CanTerraformLand(UUID userID, Vector3 position)
{
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
if (m_bypassPermissions) return m_bypassPermissionsValue;
// Estate override
- if (GenericEstatePermission(user))
+ if (GenericEstatePermission(userID))
return true;
float X = position.X;
@@ -1609,13 +2086,19 @@ namespace OpenSim.Region.CoreModules.World.Permissions
ILandObject parcel = m_scene.LandChannel.GetLandObject(X, Y);
if (parcel == null)
return false;
-
- // Others allowed to terraform?
- if ((parcel.LandData.Flags & ((int)ParcelFlags.AllowTerraform)) != 0)
+
+ LandData landdata = parcel.LandData;
+ if (landdata == null)
+ return false;
+
+ if ((landdata.Flags & ((int)ParcelFlags.AllowTerraform)) != 0)
return true;
- // Land owner can terraform too
- if (parcel != null && GenericParcelPermission(user, parcel, (ulong)GroupPowers.AllowEditLand))
+ if(landdata.OwnerID == userID)
+ return true;
+
+ if (landdata.IsGroupOwned && parcel.LandData.GroupID != UUID.Zero &&
+ IsGroupMember(landdata.GroupID, userID, (ulong)GroupPowers.AllowEditLand))
return true;
return false;
@@ -1629,15 +2112,19 @@ namespace OpenSim.Region.CoreModules.World.Permissions
///
///
///
- private bool CanViewScript(UUID script, UUID objectID, UUID user, Scene scene)
+ private bool CanViewScript(UUID script, UUID objectID, UUID userID)
{
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
if (m_bypassPermissions) return m_bypassPermissionsValue;
+ // A god is a god is a god
+ if (IsAdministrator(userID))
+ return true;
+
if (objectID == UUID.Zero) // User inventory
{
IInventoryService invService = m_scene.InventoryService;
- InventoryItemBase assetRequestItem = invService.GetItem(user, script);
+ InventoryItemBase assetRequestItem = invService.GetItem(userID, script);
if (assetRequestItem == null && LibraryRootFolder != null) // Library item
{
assetRequestItem = LibraryRootFolder.FindItem(script);
@@ -1657,60 +2144,53 @@ namespace OpenSim.Region.CoreModules.World.Permissions
// readable only if it's really full perms
//
if ((assetRequestItem.CurrentPermissions &
+/*
((uint)PermissionMask.Modify |
(uint)PermissionMask.Copy |
(uint)PermissionMask.Transfer)) !=
((uint)PermissionMask.Modify |
(uint)PermissionMask.Copy |
(uint)PermissionMask.Transfer))
+*/
+ (uint)(PermissionMask.Modify | PermissionMask.Copy)) !=
+ (uint)(PermissionMask.Modify | PermissionMask.Copy))
return false;
}
else // Prim inventory
{
- SceneObjectPart part = scene.GetSceneObjectPart(objectID);
-
+ SceneObjectPart part = m_scene.GetSceneObjectPart(objectID);
if (part == null)
return false;
- if (part.OwnerID != user)
- {
- if (part.GroupID == UUID.Zero)
- return false;
+ SceneObjectGroup sog = part.ParentGroup;
+ if (sog == null)
+ return false;
- if (!IsGroupMember(part.GroupID, user, 0))
- return false;
-
- if ((part.GroupMask & (uint)PermissionMask.Modify) == 0)
- return false;
- }
- else
- {
- if ((part.OwnerMask & (uint)PermissionMask.Modify) == 0)
- return false;
- }
+ uint perms = GetObjectPermissions(userID, sog, true);
+ if((perms & (uint)PermissionMask.Modify) == 0)
+ return false;
TaskInventoryItem ti = part.Inventory.GetInventoryItem(script);
- if (ti == null)
+// if (ti == null || ti.InvType != (int)InventoryType.LSL)
+ if (ti == null) // legacy may not have type
return false;
- if (ti.OwnerID != user)
- {
- if (ti.GroupID == UUID.Zero)
- return false;
-
- if (!IsGroupMember(ti.GroupID, user, 0))
- return false;
- }
+ uint itperms = GetObjectItemPermissions(userID, ti);
// Require full perms
- if ((ti.CurrentPermissions &
- ((uint)PermissionMask.Modify |
+
+ if ((itperms &
+/*
+ ((uint)(PermissionMask.Modify |
(uint)PermissionMask.Copy |
(uint)PermissionMask.Transfer)) !=
((uint)PermissionMask.Modify |
(uint)PermissionMask.Copy |
(uint)PermissionMask.Transfer))
+*/
+ (uint)(PermissionMask.Modify | PermissionMask.Copy)) !=
+ (uint)(PermissionMask.Modify | PermissionMask.Copy))
return false;
}
@@ -1725,15 +2205,19 @@ namespace OpenSim.Region.CoreModules.World.Permissions
///
///
///
- private bool CanViewNotecard(UUID notecard, UUID objectID, UUID user, Scene scene)
+ private bool CanViewNotecard(UUID notecard, UUID objectID, UUID userID)
{
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
if (m_bypassPermissions) return m_bypassPermissionsValue;
+ // A god is a god is a god
+ if (IsAdministrator(userID))
+ return true;
+
if (objectID == UUID.Zero) // User inventory
{
IInventoryService invService = m_scene.InventoryService;
- InventoryItemBase assetRequestItem = invService.GetItem(user, notecard);
+ InventoryItemBase assetRequestItem = invService.GetItem(userID, notecard);
if (assetRequestItem == null && LibraryRootFolder != null) // Library item
{
assetRequestItem = LibraryRootFolder.FindItem(notecard);
@@ -1751,40 +2235,29 @@ namespace OpenSim.Region.CoreModules.World.Permissions
}
else // Prim inventory
{
- SceneObjectPart part = scene.GetSceneObjectPart(objectID);
-
+ SceneObjectPart part = m_scene.GetSceneObjectPart(objectID);
if (part == null)
return false;
- if (part.OwnerID != user)
- {
- if (part.GroupID == UUID.Zero)
- return false;
+ SceneObjectGroup sog = part.ParentGroup;
+ if (sog == null)
+ return false;
- if (!IsGroupMember(part.GroupID, user, 0))
- return false;
- }
-
- if ((part.OwnerMask & (uint)PermissionMask.Modify) == 0)
+ uint perms = GetObjectPermissions(userID, sog, true);
+ if((perms & (uint)PermissionMask.Modify) == 0)
return false;
TaskInventoryItem ti = part.Inventory.GetInventoryItem(notecard);
+// if (ti == null || ti.InvType != (int)InventoryType.Notecard)
if (ti == null)
return false;
- if (ti.OwnerID != user)
- {
- if (ti.GroupID == UUID.Zero)
- return false;
-
- if (!IsGroupMember(ti.GroupID, user, 0))
- return false;
- }
+ uint itperms = GetObjectItemPermissions(userID, ti);
// Notecards are always readable unless no copy
//
- if ((ti.CurrentPermissions &
+ if ((itperms &
(uint)PermissionMask.Copy) !=
(uint)PermissionMask.Copy)
return false;
@@ -1800,7 +2273,14 @@ namespace OpenSim.Region.CoreModules.World.Permissions
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
if (m_bypassPermissions) return m_bypassPermissionsValue;
- return GenericObjectPermission(userID, objectID, false);
+ SceneObjectGroup sog = m_scene.GetGroupByPrim(objectID);
+ if (sog == null)
+ return false;
+
+ uint perms = GetObjectPermissions(userID, sog, true);
+ if((perms & (uint)PermissionMask.Modify) == 0)
+ return false;
+ return true;
}
private bool CanDelinkObject(UUID userID, UUID objectID)
@@ -1808,10 +2288,17 @@ namespace OpenSim.Region.CoreModules.World.Permissions
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
if (m_bypassPermissions) return m_bypassPermissionsValue;
- return GenericObjectPermission(userID, objectID, false);
+ SceneObjectGroup sog = m_scene.GetGroupByPrim(objectID);
+ if (sog == null)
+ return false;
+
+ uint perms = GetObjectPermissions(userID, sog, true);
+ if((perms & (uint)PermissionMask.Modify) == 0)
+ return false;
+ return true;
}
- private bool CanBuyLand(UUID userID, ILandObject parcel, Scene scene)
+ private bool CanBuyLand(UUID userID, ILandObject parcel)
{
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
if (m_bypassPermissions) return m_bypassPermissionsValue;
@@ -1824,6 +2311,138 @@ namespace OpenSim.Region.CoreModules.World.Permissions
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
if (m_bypassPermissions) return m_bypassPermissionsValue;
+ SceneObjectPart part = m_scene.GetSceneObjectPart(objectID);
+ if (part == null)
+ return false;
+
+ SceneObjectGroup sog = part.ParentGroup;
+ if (sog == null)
+ return false;
+
+ if(sog.OwnerID == userID || IsAdministrator(userID))
+ return true;
+
+ if(sog.IsAttachment)
+ return false;
+
+ UUID sogGroupID = sog.GroupID;
+
+ if(sogGroupID == UUID.Zero || sogGroupID != sog.OwnerID)
+ return false;
+
+ TaskInventoryItem ti = part.Inventory.GetInventoryItem(itemID);
+ if(ti == null)
+ return false;
+
+ ulong powers = 0;
+ if(GroupMemberPowers(sogGroupID, userID, ref powers))
+ {
+ if((powers & (ulong)GroupPowers.ObjectManipulate) != 0)
+ return true;
+
+ if((ti.EveryonePermissions & (uint)PermissionMask.Copy) != 0)
+ return true;
+ }
+ return false;
+ }
+
+ // object inventory to object inventory item drag and drop
+ private bool CanDoObjectInvToObjectInv(TaskInventoryItem item, SceneObjectPart sourcePart, SceneObjectPart destPart)
+ {
+ DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
+
+ if (sourcePart == null || destPart == null || item == null)
+ return false;
+
+ if (m_bypassPermissions)
+ return m_bypassPermissionsValue;
+
+ SceneObjectGroup srcsog = sourcePart.ParentGroup;
+ SceneObjectGroup destsog = destPart.ParentGroup;
+ if (srcsog == null || destsog == null)
+ return false;
+
+ // dest is locked
+ if((destsog.EffectiveOwnerPerms & (uint)PermissionMask.Move) == 0)
+ return false;
+
+ uint itperms = item.CurrentPermissions;
+
+ // if item is no copy the source is modifed
+ if((itperms & (uint)PermissionMask.Copy) == 0 && (srcsog.EffectiveOwnerPerms & (uint)PermissionMask.Modify) == 0)
+ return false;
+
+ UUID srcOwner = srcsog.OwnerID;
+ UUID destOwner = destsog.OwnerID;
+ bool notSameOwner = srcOwner != destOwner;
+
+ if(notSameOwner)
+ {
+ if((itperms & (uint)PermissionMask.Transfer) == 0)
+ return false;
+
+ // scripts can't be droped
+ if(item.InvType == (int)InventoryType.LSL)
+ return false;
+
+ if((destsog.RootPart.GetEffectiveObjectFlags() & (uint)PrimFlags.AllowInventoryDrop) == 0)
+ return false;
+ }
+ else
+ {
+ if((destsog.RootPart.GetEffectiveObjectFlags() & (uint)PrimFlags.AllowInventoryDrop) == 0 &&
+ (destsog.EffectiveOwnerPerms & (uint)PermissionMask.Modify) == 0)
+ return false;
+ }
+
+ return true;
+ }
+
+ private bool CanDropInObjectInv(InventoryItemBase item, ScenePresence sp, SceneObjectPart destPart)
+ {
+ DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
+
+ if (sp == null || sp.IsDeleted || destPart == null || item == null)
+ return false;
+
+ SceneObjectGroup destsog = destPart.ParentGroup;
+ if (destsog == null || destsog.IsDeleted)
+ return false;
+
+ if (m_bypassPermissions)
+ return m_bypassPermissionsValue;
+
+ if(sp.IsGod)
+ return true;
+
+ // dest is locked
+ if((destsog.EffectiveOwnerPerms & (uint)PermissionMask.Move) == 0)
+ return false;
+
+ UUID destOwner = destsog.OwnerID;
+ UUID spID = sp.UUID;
+ bool spNotOwner = spID != destOwner;
+
+ // scripts can't be droped
+ if(spNotOwner && item.InvType == (int)InventoryType.LSL)
+ return false;
+
+ if(spNotOwner || item.Owner != destOwner)
+ {
+ // no copy item will be moved if it has transfer
+ uint itperms = item.CurrentPermissions;
+ if((itperms & (uint)PermissionMask.Transfer) == 0)
+ return false;
+ }
+
+ // allowdrop is a root part thing and does bypass modify rights
+ if((destsog.RootPart.GetEffectiveObjectFlags() & (uint)PrimFlags.AllowInventoryDrop) != 0)
+ return true;
+
+ uint perms = GetObjectPermissions(spID, destsog, true);
+ if((perms & (uint)PermissionMask.Modify) == 0)
+ return false;
+
return true;
}
@@ -1832,6 +2451,23 @@ namespace OpenSim.Region.CoreModules.World.Permissions
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
if (m_bypassPermissions) return m_bypassPermissionsValue;
+ SceneObjectPart part = m_scene.GetSceneObjectPart(objectID);
+ if (part == null)
+ return false;
+
+ SceneObjectGroup sog = part.ParentGroup;
+ if (sog == null)
+ return false;
+
+ uint perms = GetObjectPermissions(userID, sog, true);
+ if((perms & (uint)PermissionMask.Modify) == 0)
+ return false;
+
+ TaskInventoryItem ti = part.Inventory.GetInventoryItem(itemID);
+ if(ti == null)
+ return false;
+
+ //TODO item perm ?
return true;
}
@@ -1848,26 +2484,23 @@ namespace OpenSim.Region.CoreModules.World.Permissions
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
if (m_bypassPermissions) return m_bypassPermissionsValue;
- SceneObjectPart part = m_scene.GetSceneObjectPart(objectID);
ScenePresence p = m_scene.GetScenePresence(userID);
- if (part == null || p == null)
+ if (p == null)
return false;
- if (!IsAdministrator(userID))
+ SceneObjectGroup sog = m_scene.GetGroupByPrim(objectID);
+ if (sog == null)
+ return false;
+
+ uint perms = GetObjectPermissions(userID, sog, true);
+ if((perms & (uint)PermissionMask.Modify) == 0)
+ return false;
+
+ if ((int)InventoryType.LSL == invType)
{
- if (part.OwnerID != userID)
- {
- // Group permissions
- if ((part.GroupID == UUID.Zero) || (p.ControllingClient.GetGroupPowers(part.GroupID) == 0) || ((part.GroupMask & (uint)PermissionMask.Modify) == 0))
- return false;
- } else {
- if ((part.OwnerMask & (uint)PermissionMask.Modify) == 0)
- return false;
- }
- if ((int)InventoryType.LSL == invType)
- if (m_allowedScriptCreators == UserSet.Administrators)
- return false;
+ if (m_allowedScriptCreators == UserSet.Administrators)
+ return false;
}
return true;
@@ -1941,22 +2574,22 @@ namespace OpenSim.Region.CoreModules.World.Permissions
return true;
}
- private bool CanResetScript(UUID prim, UUID script, UUID agentID, Scene scene)
+ private bool CanResetScript(UUID primID, UUID script, UUID agentID)
{
DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
if (m_bypassPermissions) return m_bypassPermissionsValue;
- SceneObjectPart part = m_scene.GetSceneObjectPart(prim);
+ SceneObjectGroup sog = m_scene.GetGroupByPrim(primID);
+ if (sog == null)
+ return false;
- // If we selected a sub-prim to reset, prim won't represent the object, but only a part.
- // We have to check the permissions of the object, though.
- if (part.ParentID != 0) prim = part.ParentUUID;
-
- // You can reset the scripts in any object you can edit
- return GenericObjectPermission(agentID, prim, false);
+ uint perms = GetObjectPermissions(agentID, sog, false);
+ if((perms & (uint)PermissionMask.Modify) == 0) // ??
+ return false;
+ return true;
}
- private bool CanCompileScript(UUID ownerUUID, int scriptType, Scene scene)
+ private bool CanCompileScript(UUID ownerUUID, int scriptType)
{
//m_log.DebugFormat("check if {0} is allowed to compile {1}", ownerUUID, scriptType);
switch (scriptType) {
@@ -2014,7 +2647,14 @@ namespace OpenSim.Region.CoreModules.World.Permissions
// "[PERMISSIONS]: Checking CanControlPrimMedia for {0} on {1} face {2} with control permissions {3}",
// agentID, primID, face, me.ControlPermissions);
- return GenericObjectPermission(agentID, part.ParentGroup.UUID, true);
+ SceneObjectGroup sog = part.ParentGroup;
+ if (sog == null)
+ return false;
+
+ uint perms = GetObjectPermissions(agentID, sog, false);
+ if((perms & (uint)PermissionMask.Modify) == 0)
+ return false;
+ return true;
}
private bool CanInteractWithPrimMedia(UUID agentID, UUID primID, int face)
diff --git a/OpenSim/Region/CoreModules/World/Region/RestartModule.cs b/OpenSim/Region/CoreModules/World/Region/RestartModule.cs
index 8bac9e6623..bb3b8605b5 100644
--- a/OpenSim/Region/CoreModules/World/Region/RestartModule.cs
+++ b/OpenSim/Region/CoreModules/World/Region/RestartModule.cs
@@ -61,6 +61,8 @@ namespace OpenSim.Region.CoreModules.World.Region
protected IDialogModule m_DialogModule = null;
protected string m_MarkerPath = String.Empty;
private int[] m_CurrentAlerts = null;
+ protected bool m_shortCircuitDelays = false;
+ protected bool m_rebootAll = false;
public void Initialise(IConfigSource config)
{
@@ -69,6 +71,9 @@ namespace OpenSim.Region.CoreModules.World.Region
{
m_MarkerPath = restartConfig.GetString("MarkerPath", String.Empty);
}
+ IConfig startupConfig = config.Configs["Startup"];
+ m_shortCircuitDelays = startupConfig.GetBoolean("SkipDelayOnEmptyRegion", false);
+ m_rebootAll = startupConfig.GetBoolean("InworldRestartShutsDown", false);
}
public void AddRegion(Scene scene)
@@ -250,6 +255,14 @@ namespace OpenSim.Region.CoreModules.World.Region
private void OnTimer(object source, ElapsedEventArgs e)
{
int nextInterval = DoOneNotice(true);
+ if (m_shortCircuitDelays)
+ {
+ if (CountAgents() == 0)
+ {
+ m_Scene.RestartNow();
+ return;
+ }
+ }
SetTimer(nextInterval);
}
@@ -349,5 +362,35 @@ namespace OpenSim.Region.CoreModules.World.Region
{
}
}
+
+ int CountAgents()
+ {
+ m_log.Info("[RESTART MODULE]: Counting affected avatars");
+ int agents = 0;
+
+ if (m_rebootAll)
+ {
+ foreach (Scene s in SceneManager.Instance.Scenes)
+ {
+ foreach (ScenePresence sp in s.GetScenePresences())
+ {
+ if (!sp.IsChildAgent && !sp.IsNPC)
+ agents++;
+ }
+ }
+ }
+ else
+ {
+ foreach (ScenePresence sp in m_Scene.GetScenePresences())
+ {
+ if (!sp.IsChildAgent && !sp.IsNPC)
+ agents++;
+ }
+ }
+
+ m_log.InfoFormat("[RESTART MODULE]: Avatars in region: {0}", agents);
+
+ return agents;
+ }
}
}
diff --git a/OpenSim/Region/CoreModules/World/Vegetation/VegetationModule.cs b/OpenSim/Region/CoreModules/World/Vegetation/VegetationModule.cs
index 04b6f00a39..4cee7a5f3b 100644
--- a/OpenSim/Region/CoreModules/World/Vegetation/VegetationModule.cs
+++ b/OpenSim/Region/CoreModules/World/Vegetation/VegetationModule.cs
@@ -105,8 +105,9 @@ namespace OpenSim.Region.CoreModules.World.Vegetation
if (rootPart.Shape.PCode != (byte)PCode.Grass)
AdaptTree(ref shape);
- m_scene.AddNewSceneObject(sceneObject, true);
sceneObject.SetGroup(groupID, null);
+ m_scene.AddNewSceneObject(sceneObject, true);
+ sceneObject.InvalidateDeepEffectivePerms();
return sceneObject;
}
diff --git a/OpenSim/Region/CoreModules/World/WorldMap/WorldMapModule.cs b/OpenSim/Region/CoreModules/World/WorldMap/WorldMapModule.cs
index 5dcf3266a9..03a4d3475e 100644
--- a/OpenSim/Region/CoreModules/World/WorldMap/WorldMapModule.cs
+++ b/OpenSim/Region/CoreModules/World/WorldMap/WorldMapModule.cs
@@ -215,6 +215,8 @@ namespace OpenSim.Region.CoreModules.World.WorldMap
m_scene.EventManager.OnNewClient -= OnNewClient;
m_scene.EventManager.OnRegisterCaps -= OnRegisterCaps;
+ m_scene.UnregisterModuleInterface(this);
+
string regionimage = "regionImage" + m_scene.RegionInfo.RegionID.ToString();
regionimage = regionimage.Replace("-", "");
MainServer.Instance.RemoveLLSDHandler("/MAP/MapItems/" + m_scene.RegionInfo.RegionHandle.ToString(),
@@ -714,12 +716,11 @@ namespace OpenSim.Region.CoreModules.World.WorldMap
{
while (true)
{
- Watchdog.UpdateThread();
-
av = null;
st = null;
- st = requests.Dequeue(4900); // timeout to make watchdog happy
+ st = requests.Dequeue(4500);
+ Watchdog.UpdateThread();
if (st == null || st.agentID == UUID.Zero)
continue;
@@ -1148,7 +1149,13 @@ namespace OpenSim.Region.CoreModules.World.WorldMap
List thisRunData = new List();
while (true)
{
- m_mapBlockRequestEvent.WaitOne();
+ while(!m_mapBlockRequestEvent.WaitOne(4900))
+ {
+ Watchdog.UpdateThread();
+ if(m_scene == null)
+ return;
+ }
+ Watchdog.UpdateThread();
lock (m_mapBlockRequestEvent)
{
int total = 0;
diff --git a/OpenSim/Region/Framework/Interfaces/IDwellModule.cs b/OpenSim/Region/Framework/Interfaces/IDwellModule.cs
index db504393a2..ebef5a4749 100644
--- a/OpenSim/Region/Framework/Interfaces/IDwellModule.cs
+++ b/OpenSim/Region/Framework/Interfaces/IDwellModule.cs
@@ -33,5 +33,6 @@ namespace OpenSim.Region.Framework.Interfaces
public interface IDwellModule
{
int GetDwell(UUID parcelID);
+ int GetDwell(LandData land);
}
}
diff --git a/OpenSim/Region/Framework/Interfaces/IDynamicTextureManager.cs b/OpenSim/Region/Framework/Interfaces/IDynamicTextureManager.cs
index 441076dd23..093ea9c801 100644
--- a/OpenSim/Region/Framework/Interfaces/IDynamicTextureManager.cs
+++ b/OpenSim/Region/Framework/Interfaces/IDynamicTextureManager.cs
@@ -44,14 +44,13 @@ namespace OpenSim.Region.Framework.Interfaces
///
void ReturnData(UUID id, IDynamicTexture texture);
+ UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url, string extraParams);
UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url, string extraParams,
- int updateTimer);
+ bool SetBlending, byte AlphaValue);
UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url, string extraParams,
- int updateTimer, bool SetBlending, byte AlphaValue);
- UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url, string extraParams,
- int updateTimer, bool SetBlending, int disp, byte AlphaValue, int face);
- UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data, string extraParams,
- int updateTimer);
+ bool SetBlending, int disp, byte AlphaValue, int face);
+
+ UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data, string extraParams);
/// Apply a dynamically generated texture to all sides of the given prim. The texture is not persisted to the
/// asset service.
@@ -62,8 +61,6 @@ namespace OpenSim.Region.Framework.Interfaces
/// based texture or "image" to create a texture from an image at a particular URL
/// The data for the generator
/// Parameters for the generator that don't form part of the main data.
- /// If zero, the image is never updated after the first generation. If positive
- /// the image is updated at the given interval. Not implemented for
///
/// If true, the newly generated texture is blended with the appropriate existing ones on the prim
///
@@ -76,7 +73,7 @@ namespace OpenSim.Region.Framework.Interfaces
/// can be obtained as SceneObjectPart.Shape.Textures.DefaultTexture.TextureID
///
UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data, string extraParams,
- int updateTimer, bool SetBlending, byte AlphaValue);
+ bool SetBlending, byte AlphaValue);
///
/// Apply a dynamically generated texture to the given prim.
@@ -87,8 +84,6 @@ namespace OpenSim.Region.Framework.Interfaces
/// based texture or "image" to create a texture from an image at a particular URL
/// The data for the generator
/// Parameters for the generator that don't form part of the main data.
- /// If zero, the image is never updated after the first generation. If positive
- /// the image is updated at the given interval. Not implemented for
///
/// If true, the newly generated texture is blended with the appropriate existing ones on the prim
///
@@ -109,9 +104,8 @@ namespace OpenSim.Region.Framework.Interfaces
/// to obtain it directly from the SceneObjectPart. For instance, if ALL_SIDES is set then this texture
/// can be obtained as SceneObjectPart.Shape.Textures.DefaultTexture.TextureID
///
- UUID AddDynamicTextureData(
- UUID simID, UUID primID, string contentType, string data, string extraParams,
- int updateTimer, bool SetBlending, int disp, byte AlphaValue, int face);
+ UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data, string extraParams,
+ bool SetBlending, int disp, byte AlphaValue, int face);
void GetDrawStringSize(string contentType, string text, string fontName, int fontSize,
out double xSize, out double ySize);
diff --git a/OpenSim/Region/Framework/Interfaces/IEntityInventory.cs b/OpenSim/Region/Framework/Interfaces/IEntityInventory.cs
index 0c4017eb88..e7c2428708 100644
--- a/OpenSim/Region/Framework/Interfaces/IEntityInventory.cs
+++ b/OpenSim/Region/Framework/Interfaces/IEntityInventory.cs
@@ -278,6 +278,8 @@ namespace OpenSim.Region.Framework.Interfaces
///
void ProcessInventoryBackup(ISimulationDataService datastore);
+ void AggregateInnerPerms(ref uint owner, ref uint group, ref uint everyone);
+
uint MaskEffectivePermissions();
void ApplyNextOwnerPermissions();
diff --git a/OpenSim/Region/Framework/Interfaces/IEntityTransferModule.cs b/OpenSim/Region/Framework/Interfaces/IEntityTransferModule.cs
index 9585082719..1b690bad3f 100644
--- a/OpenSim/Region/Framework/Interfaces/IEntityTransferModule.cs
+++ b/OpenSim/Region/Framework/Interfaces/IEntityTransferModule.cs
@@ -102,6 +102,8 @@ namespace OpenSim.Region.Framework.Interfaces
ScenePresence CrossAgentToNewRegionAsync(ScenePresence agent, Vector3 pos, GridRegion neighbourRegion, bool isFlying, EntityTransferContext ctx);
+ bool CrossAgentCreateFarChild(ScenePresence agent, GridRegion neighbourRegion, Vector3 pos, EntityTransferContext ctx);
+
bool HandleIncomingSceneObject(SceneObjectGroup so, Vector3 newPosition);
}
diff --git a/OpenSim/Region/Framework/Interfaces/IEtcdModule.cs b/OpenSim/Region/Framework/Interfaces/IEtcdModule.cs
new file mode 100644
index 0000000000..123cb67308
--- /dev/null
+++ b/OpenSim/Region/Framework/Interfaces/IEtcdModule.cs
@@ -0,0 +1,37 @@
+/*
+ * 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;
+
+public interface IEtcdModule
+{
+ bool Store(string k, string v);
+ bool Store(string k, string v, int ttl);
+ string Get(string k);
+ void Watch(string k, Action callback);
+ void Delete(string k);
+}
diff --git a/OpenSim/Region/Framework/Interfaces/IEventQueue.cs b/OpenSim/Region/Framework/Interfaces/IEventQueue.cs
index 7af56cb809..7edd75aaba 100644
--- a/OpenSim/Region/Framework/Interfaces/IEventQueue.cs
+++ b/OpenSim/Region/Framework/Interfaces/IEventQueue.cs
@@ -39,7 +39,7 @@ namespace OpenSim.Region.Framework.Interfaces
bool Enqueue(OSD o, UUID avatarID);
// These are required to decouple Scenes from EventQueueHelper
- void DisableSimulator(ulong handle, UUID avatarID);
+// void DisableSimulator(ulong handle, UUID avatarID);
void EnableSimulator(ulong handle, IPEndPoint endPoint, UUID avatarID, int regionSizeX, int regionSizeY);
void EstablishAgentCommunication(UUID avatarID, IPEndPoint endPoint,
string capsPath, ulong regionHandle, int regionSizeX, int regionSizeY);
diff --git a/OpenSim/Region/Framework/Scenes/Animation/ScenePresenceAnimator.cs b/OpenSim/Region/Framework/Scenes/Animation/ScenePresenceAnimator.cs
index 6b31555fb6..5c33f1272e 100644
--- a/OpenSim/Region/Framework/Scenes/Animation/ScenePresenceAnimator.cs
+++ b/OpenSim/Region/Framework/Scenes/Animation/ScenePresenceAnimator.cs
@@ -618,13 +618,147 @@ namespace OpenSim.Region.Framework.Scenes.Animation
int rnditerations = 3;
BinBVHAnimation anim = new BinBVHAnimation();
List parts = new List();
- parts.Add("mPelvis"); parts.Add("mHead"); parts.Add("mTorso");
- parts.Add("mHipLeft"); parts.Add("mHipRight"); parts.Add("mHipLeft"); parts.Add("mKneeLeft");
- parts.Add("mKneeRight"); parts.Add("mCollarLeft"); parts.Add("mCollarRight"); parts.Add("mNeck");
- parts.Add("mElbowLeft"); parts.Add("mElbowRight"); parts.Add("mWristLeft"); parts.Add("mWristRight");
- parts.Add("mShoulderLeft"); parts.Add("mShoulderRight"); parts.Add("mAnkleLeft"); parts.Add("mAnkleRight");
- parts.Add("mEyeRight"); parts.Add("mChest"); parts.Add("mToeLeft"); parts.Add("mToeRight");
- parts.Add("mFootLeft"); parts.Add("mFootRight"); parts.Add("mEyeLeft");
+
+ /// Torso and Head
+ parts.Add("mPelvis");
+ parts.Add("mTorso");
+ parts.Add("mChest");
+ parts.Add("mNeck");
+ parts.Add("mHead");
+ parts.Add("mSkull");
+ parts.Add("mEyeRight");
+ parts.Add("mEyeLeft");
+ /// Arms
+ parts.Add("mCollarLeft");
+ parts.Add("mShoulderLeft");
+ parts.Add("mElbowLeft");
+ parts.Add("mWristLeft");
+ parts.Add("mCollarRight");
+ parts.Add("mShoulderRight");
+ parts.Add("mElbowRight");
+ parts.Add("mWristRight");
+ /// Legs
+ parts.Add("mHipLeft");
+ parts.Add("mKneeLeft");
+ parts.Add("mAnkleLeft");
+ parts.Add("mFootLeft");
+ parts.Add("mToeLeft");
+ parts.Add("mHipRight");
+ parts.Add("mKneeRight");
+ parts.Add("mAnkleRight");
+ parts.Add("mFootRight");
+ parts.Add("mToeRight");
+ ///Hands
+ parts.Add("mHandThumb1Left");
+ parts.Add("mHandThumb1Right");
+ parts.Add("mHandThumb2Left");
+ parts.Add("mHandThumb2Right");
+ parts.Add("mHandThumb3Left");
+ parts.Add("mHandThumb3Right");
+ parts.Add("mHandIndex1Left");
+ parts.Add("mHandIndex1Right");
+ parts.Add("mHandIndex2Left");
+ parts.Add("mHandIndex2Right");
+ parts.Add("mHandIndex3Left");
+ parts.Add("mHandIndex3Right");
+ parts.Add("mHandMiddle1Left");
+ parts.Add("mHandMiddle1Right");
+ parts.Add("mHandMiddle2Left");
+ parts.Add("mHandMiddle2Right");
+ parts.Add("mHandMiddle3Left");
+ parts.Add("mHandMiddle3Right");
+ parts.Add("mHandRing1Left");
+ parts.Add("mHandRing1Right");
+ parts.Add("mHandRing2Left");
+ parts.Add("mHandRing2Right");
+ parts.Add("mHandRing3Left");
+ parts.Add("mHandRing3Right");
+ parts.Add("mHandPinky1Left");
+ parts.Add("mHandPinky1Right");
+ parts.Add("mHandPinky2Left");
+ parts.Add("mHandPinky2Right");
+ parts.Add("mHandPinky3Left");
+ parts.Add("mHandPinky3Right");
+ ///Face
+ parts.Add("mFaceForeheadLeft");
+ parts.Add("mFaceForeheadCenter");
+ parts.Add("mFaceForeheadRight");
+ parts.Add("mFaceEyebrowOuterLeft");
+ parts.Add("mFaceEyebrowCenterLeft");
+ parts.Add("mFaceEyebrowInnerLeft");
+ parts.Add("mFaceEyebrowOuterRight");
+ parts.Add("mFaceEyebrowCenterRight");
+ parts.Add("mFaceEyebrowInnerRight");
+ parts.Add("mFaceEyeLidUpperLeft");
+ parts.Add("mFaceEyeLidLowerLeft");
+ parts.Add("mFaceEyeLidUpperRight");
+ parts.Add("mFaceEyeLidLowerRight");
+ parts.Add("mFaceEyeAltLeft");
+ parts.Add("mFaceEyeAltRight");
+ parts.Add("mFaceEyecornerInnerLeft");
+ parts.Add("mFaceEyecornerInnerRight");
+ parts.Add("mFaceEar1Left");
+ parts.Add("mFaceEar2Left");
+ parts.Add("mFaceEar1Right");
+ parts.Add("mFaceEar2Right");
+ parts.Add("mFaceNoseLeft");
+ parts.Add("mFaceNoseCenter");
+ parts.Add("mFaceNoseRight");
+ parts.Add("mFaceNoseBase");
+ parts.Add("mFaceNoseBridge");
+ parts.Add("mFaceCheekUpperInnerLeft");
+ parts.Add("mFaceCheekUpperOuterLeft");
+ parts.Add("mFaceCheekUpperInnerRight");
+ parts.Add("mFaceCheekUpperOuterRight");
+ parts.Add("mFaceJaw");
+ parts.Add("mFaceLipUpperLeft");
+ parts.Add("mFaceLipUpperCenter");
+ parts.Add("mFaceLipUpperRight");
+ parts.Add("mFaceLipCornerLeft");
+ parts.Add("mFaceLipCornerRight");
+ parts.Add("mFaceTongueBase");
+ parts.Add("mFaceTongueTip");
+ parts.Add("mFaceLipLowerLeft");
+ parts.Add("mFaceLipLowerCenter");
+ parts.Add("mFaceLipLowerRight");
+ parts.Add("mFaceTeethLower");
+ parts.Add("mFaceTeethUpper");
+ parts.Add("mFaceChin");
+ ///Spine
+ parts.Add("mSpine1");
+ parts.Add("mSpine2");
+ parts.Add("mSpine3");
+ parts.Add("mSpine4");
+ ///Wings
+ parts.Add("mWingsRoot");
+ parts.Add("mWing1Left");
+ parts.Add("mWing2Left");
+ parts.Add("mWing3Left");
+ parts.Add("mWing4Left");
+ parts.Add("mWing1Right");
+ parts.Add("mWing2Right");
+ parts.Add("mWing3Right");
+ parts.Add("mWing4Right");
+ parts.Add("mWing4FanRight");
+ parts.Add("mWing4FanLeft");
+ ///Hind Limbs
+ parts.Add("mHindLimbsRoot");
+ parts.Add("mHindLimb1Left");
+ parts.Add("mHindLimb2Left");
+ parts.Add("mHindLimb3Left");
+ parts.Add("mHindLimb4Left");
+ parts.Add("mHindLimb1Right");
+ parts.Add("mHindLimb2Right");
+ parts.Add("mHindLimb3Right");
+ parts.Add("mHindLimb4Right");
+ ///Tail
+ parts.Add("mTail1");
+ parts.Add("mTail2");
+ parts.Add("mTail3");
+ parts.Add("mTail4");
+ parts.Add("mTail5");
+ parts.Add("mTail6");
+
anim.HandPose = 1;
anim.InPoint = 0;
anim.OutPoint = (rnditerations * .10f);
diff --git a/OpenSim/Region/Framework/Scenes/CollisionSounds.cs b/OpenSim/Region/Framework/Scenes/CollisionSounds.cs
index e76fef4a79..63aafcd066 100644
--- a/OpenSim/Region/Framework/Scenes/CollisionSounds.cs
+++ b/OpenSim/Region/Framework/Scenes/CollisionSounds.cs
@@ -116,16 +116,20 @@ namespace OpenSim.Region.Framework.Scenes
public static void PartCollisionSound(SceneObjectPart part, List collidersinfolist)
{
+ if (part.CollisionSoundType < 0)
+ return;
+
if (collidersinfolist.Count == 0 || part == null)
return;
if (part.VolumeDetectActive || (part.Flags & PrimFlags.Physics) == 0)
return;
- if (part.ParentGroup == null)
+ SceneObjectGroup sog = part.ParentGroup;
+ if (sog == null || sog.IsDeleted || sog.inTransit)
return;
- if (part.CollisionSoundType < 0)
+ if(sog.CollisionSoundThrottled(part.CollisionSoundType))
return;
float volume = part.CollisionSoundVolume;
@@ -189,15 +193,23 @@ namespace OpenSim.Region.Framework.Scenes
continue;
}
- SceneObjectPart otherPart = part.ParentGroup.Scene.GetSceneObjectPart(id);
+ SceneObjectPart otherPart = sog.Scene.GetSceneObjectPart(id);
if (otherPart != null)
{
- if (otherPart.CollisionSoundType < 0 || otherPart.VolumeDetectActive)
+ SceneObjectGroup othersog = otherPart.ParentGroup;
+ if(othersog == null || othersog.IsDeleted || othersog.inTransit)
+ continue;
+
+ int otherType = otherPart.CollisionSoundType;
+ if (otherType < 0 || otherPart.VolumeDetectActive)
continue;
if (!HaveSound)
{
- if (otherPart.CollisionSoundType == 1)
+ if(othersog.CollisionSoundThrottled(otherType))
+ continue;
+
+ if (otherType == 1)
{
soundID = otherPart.CollisionSound;
volume = otherPart.CollisionSoundVolume;
@@ -206,7 +218,7 @@ namespace OpenSim.Region.Framework.Scenes
}
else
{
- if (otherPart.CollisionSoundType == 2)
+ if (otherType == 2)
{
volume = otherPart.CollisionSoundVolume;
if (volume == 0.0f)
diff --git a/OpenSim/Region/Framework/Scenes/EventManager.cs b/OpenSim/Region/Framework/Scenes/EventManager.cs
index 1e9711d0b4..f76f8828d0 100644
--- a/OpenSim/Region/Framework/Scenes/EventManager.cs
+++ b/OpenSim/Region/Framework/Scenes/EventManager.cs
@@ -855,7 +855,7 @@ namespace OpenSim.Region.Framework.Scenes
/// ,
/// ,
/// ,
- /// ,
+ /// ,
///
///
public event ParcelPrimCountTainted OnParcelPrimCountTainted;
@@ -3161,7 +3161,7 @@ namespace OpenSim.Region.Framework.Scenes
{
foreach (Action d in handler.GetInvocationList())
{
- m_log.InfoFormat("[EVENT MANAGER]: TriggerSceneShuttingDown invoque {0}", d.Method.Name.ToString());
+ m_log.InfoFormat("[EVENT MANAGER]: TriggerSceneShuttingDown invoke {0}", d.Method.Name.ToString());
try
{
d(s);
diff --git a/OpenSim/Region/Framework/Scenes/KeyframeMotion.cs b/OpenSim/Region/Framework/Scenes/KeyframeMotion.cs
index e4aa196497..80ee5101aa 100644
--- a/OpenSim/Region/Framework/Scenes/KeyframeMotion.cs
+++ b/OpenSim/Region/Framework/Scenes/KeyframeMotion.cs
@@ -295,6 +295,7 @@ namespace OpenSim.Region.Framework.Scenes
lock (m_frames)
{
KeyframeTimer.Add(this);
+ m_lasttickMS = Util.GetTimeStampMS();
m_timerStopped = false;
}
}
@@ -326,8 +327,8 @@ namespace OpenSim.Region.Framework.Scenes
newMotion.m_selected = true;
}
- newMotion.m_timerStopped = false;
- newMotion.m_running = true;
+// newMotion.m_timerStopped = false;
+// newMotion.m_running = true;
newMotion.m_isCrossing = false;
newMotion.m_waitingCrossing = false;
}
@@ -483,9 +484,10 @@ namespace OpenSim.Region.Framework.Scenes
m_group.RootPart.Velocity = Vector3.Zero;
m_group.RootPart.AngularVelocity = Vector3.Zero;
- m_group.SendGroupRootTerseUpdate();
-// m_group.RootPart.ScheduleTerseUpdate();
+// m_group.SendGroupRootTerseUpdate();
+ m_group.RootPart.ScheduleTerseUpdate();
m_frames.Clear();
+ m_group.Scene.EventManager.TriggerMovingEndEvent(m_group.RootPart.LocalId);
}
public void Pause()
@@ -495,8 +497,10 @@ namespace OpenSim.Region.Framework.Scenes
m_group.RootPart.Velocity = Vector3.Zero;
m_group.RootPart.AngularVelocity = Vector3.Zero;
- m_group.SendGroupRootTerseUpdate();
-// m_group.RootPart.ScheduleTerseUpdate();
+ m_skippedUpdates = 1000;
+// m_group.SendGroupRootTerseUpdate();
+ m_group.RootPart.ScheduleTerseUpdate();
+ m_group.Scene.EventManager.TriggerMovingEndEvent(m_group.RootPart.LocalId);
}
public void Suspend()
@@ -517,6 +521,7 @@ namespace OpenSim.Region.Framework.Scenes
return;
if (m_running && !m_waitingCrossing)
StartTimer();
+ m_skippedUpdates = 1000;
}
}
@@ -642,11 +647,17 @@ namespace OpenSim.Region.Framework.Scenes
m_group.RootPart.Velocity = Vector3.Zero;
m_group.RootPart.AngularVelocity = Vector3.Zero;
- m_group.SendGroupRootTerseUpdate();
- // m_group.RootPart.ScheduleTerseUpdate();
+// m_group.SendGroupRootTerseUpdate();
+ m_group.RootPart.ScheduleTerseUpdate();
m_frames.Clear();
}
+ [NonSerialized()] Vector3 m_lastPosUpdate;
+ [NonSerialized()] Quaternion m_lastRotationUpdate;
+ [NonSerialized()] Vector3 m_currentVel;
+ [NonSerialized()] int m_skippedUpdates;
+ [NonSerialized()] double m_lasttickMS;
+
private void DoOnTimer(double tickDuration)
{
if (m_skipLoops > 0)
@@ -665,7 +676,9 @@ namespace OpenSim.Region.Framework.Scenes
if (m_group.RootPart.Velocity != Vector3.Zero)
{
m_group.RootPart.Velocity = Vector3.Zero;
- m_group.SendGroupRootTerseUpdate();
+ m_skippedUpdates = 1000;
+// m_group.SendGroupRootTerseUpdate();
+ m_group.RootPart.ScheduleTerseUpdate();
}
return;
}
@@ -677,7 +690,9 @@ namespace OpenSim.Region.Framework.Scenes
// retry to set the position that evtually caused the outbound
// if still outside region this will call startCrossing below
m_isCrossing = false;
+ m_skippedUpdates = 1000;
m_group.AbsolutePosition = m_nextPosition;
+
if (!m_isCrossing)
{
StopTimer();
@@ -686,6 +701,8 @@ namespace OpenSim.Region.Framework.Scenes
return;
}
+ double nowMS = Util.GetTimeStampMS();
+
if (m_frames.Count == 0)
{
lock (m_frames)
@@ -700,19 +717,27 @@ namespace OpenSim.Region.Framework.Scenes
}
m_currentFrame = m_frames[0];
- m_currentFrame.TimeMS += (int)tickDuration;
}
- //force a update on a keyframe transition
m_nextPosition = m_group.AbsolutePosition;
+ m_currentVel = (Vector3)m_currentFrame.Position - m_nextPosition;
+ m_currentVel /= (m_currentFrame.TimeMS * 0.001f);
+
+ m_currentFrame.TimeMS += (int)tickDuration;
+ m_lasttickMS = nowMS - 50f;
update = true;
}
- m_currentFrame.TimeMS -= (int)tickDuration;
+ int elapsed = (int)(nowMS - m_lasttickMS);
+ if( elapsed > 3 * tickDuration)
+ elapsed = (int)tickDuration;
+
+ m_currentFrame.TimeMS -= elapsed;
+ m_lasttickMS = nowMS;
// Do the frame processing
double remainingSteps = (double)m_currentFrame.TimeMS / tickDuration;
- if (remainingSteps <= 0.0)
+ if (remainingSteps <= 1.0)
{
m_group.RootPart.Velocity = Vector3.Zero;
m_group.RootPart.AngularVelocity = Vector3.Zero;
@@ -720,94 +745,77 @@ namespace OpenSim.Region.Framework.Scenes
m_nextPosition = (Vector3)m_currentFrame.Position;
m_group.AbsolutePosition = m_nextPosition;
- // we are sending imediate updates, no doing force a extra terseUpdate
- // m_group.UpdateGroupRotationR((Quaternion)m_currentFrame.Rotation);
-
m_group.RootPart.RotationOffset = (Quaternion)m_currentFrame.Rotation;
lock (m_frames)
{
m_frames.RemoveAt(0);
if (m_frames.Count > 0)
+ {
m_currentFrame = m_frames[0];
+ m_currentVel = (Vector3)m_currentFrame.Position - m_nextPosition;
+ m_currentVel /= (m_currentFrame.TimeMS * 0.001f);
+ m_group.RootPart.Velocity = m_currentVel;
+ m_currentFrame.TimeMS += (int)tickDuration;
+ }
+ else
+ m_group.RootPart.Velocity = Vector3.Zero;
}
-
update = true;
}
else
{
- float completed = ((float)m_currentFrame.TimeTotal - (float)m_currentFrame.TimeMS) / (float)m_currentFrame.TimeTotal;
- bool lastStep = m_currentFrame.TimeMS <= tickDuration;
+// bool lastSteps = remainingSteps < 4;
+
+ Vector3 currentPosition = m_group.AbsolutePosition;
+ Vector3 motionThisFrame = (Vector3)m_currentFrame.Position - currentPosition;
+ motionThisFrame /= (float)remainingSteps;
+
+ m_nextPosition = currentPosition + motionThisFrame;
- Vector3 v = (Vector3)m_currentFrame.Position - m_group.AbsolutePosition;
- Vector3 motionThisFrame = v / (float)remainingSteps;
- v = v * 1000 / m_currentFrame.TimeMS;
-
- m_nextPosition = m_group.AbsolutePosition + motionThisFrame;
-
- if (Vector3.Mag(motionThisFrame) >= 0.05f)
- update = true;
-
- //int totalSteps = m_currentFrame.TimeTotal / (int)tickDuration;
- //m_log.DebugFormat("KeyframeMotion.OnTimer: step {0}/{1}, curPosition={2}, finalPosition={3}, motionThisStep={4} (scene {5})",
- // totalSteps - remainingSteps + 1, totalSteps, m_group.AbsolutePosition, m_currentFrame.Position, motionThisStep, m_scene.RegionInfo.RegionName);
-
- if ((Quaternion)m_currentFrame.Rotation != m_group.GroupRotation)
+ Quaternion currentRotation = m_group.GroupRotation;
+ if ((Quaternion)m_currentFrame.Rotation != currentRotation)
{
- Quaternion current = m_group.GroupRotation;
-
+ float completed = ((float)m_currentFrame.TimeTotal - (float)m_currentFrame.TimeMS) / (float)m_currentFrame.TimeTotal;
Quaternion step = Quaternion.Slerp(m_currentFrame.StartRotation, (Quaternion)m_currentFrame.Rotation, completed);
step.Normalize();
- /* use simpler change detection
- * float angle = 0;
-
- float aa = current.X * current.X + current.Y * current.Y + current.Z * current.Z + current.W * current.W;
- float bb = step.X * step.X + step.Y * step.Y + step.Z * step.Z + step.W * step.W;
- float aa_bb = aa * bb;
-
- if (aa_bb == 0)
- {
- angle = 0;
- }
- else
- {
- float ab = current.X * step.X +
- current.Y * step.Y +
- current.Z * step.Z +
- current.W * step.W;
- float q = (ab * ab) / aa_bb;
-
- if (q > 1.0f)
- {
- angle = 0;
- }
- else
- {
- angle = (float)Math.Acos(2 * q - 1);
- }
- }
-
- if (angle > 0.01f)
- */
- if (Math.Abs(step.X - current.X) > 0.001f
- || Math.Abs(step.Y - current.Y) > 0.001f
- || Math.Abs(step.Z - current.Z) > 0.001f)
- // assuming w is a dependente var
- {
-// m_group.UpdateGroupRotationR(step);
- m_group.RootPart.RotationOffset = step;
-
- //m_group.RootPart.UpdateAngularVelocity(m_currentFrame.AngularVelocity / 2);
+ m_group.RootPart.RotationOffset = step;
+/*
+ if (Math.Abs(step.X - m_lastRotationUpdate.X) > 0.001f
+ || Math.Abs(step.Y - m_lastRotationUpdate.Y) > 0.001f
+ || Math.Abs(step.Z - m_lastRotationUpdate.Z) > 0.001f)
update = true;
- }
+*/
}
- }
- if (update)
- {
m_group.AbsolutePosition = m_nextPosition;
- m_group.SendGroupRootTerseUpdate();
+// if(lastSteps)
+// m_group.RootPart.Velocity = Vector3.Zero;
+// else
+ m_group.RootPart.Velocity = m_currentVel;
+/*
+ if(!update && (
+// lastSteps ||
+ m_skippedUpdates * tickDuration > 0.5 ||
+ Math.Abs(m_nextPosition.X - currentPosition.X) > 5f ||
+ Math.Abs(m_nextPosition.Y - currentPosition.Y) > 5f ||
+ Math.Abs(m_nextPosition.Z - currentPosition.Z) > 5f
+ ))
+ {
+ update = true;
+ }
+ else
+ m_skippedUpdates++;
+*/
}
+// if(update)
+// {
+// m_lastPosUpdate = m_nextPosition;
+// m_lastRotationUpdate = m_group.GroupRotation;
+// m_skippedUpdates = 0;
+// m_group.SendGroupRootTerseUpdate();
+ m_group.RootPart.ScheduleTerseUpdate();
+// }
}
public Byte[] Serialize()
@@ -850,8 +858,9 @@ namespace OpenSim.Region.Framework.Scenes
if (m_group.RootPart.Velocity != Vector3.Zero)
{
m_group.RootPart.Velocity = Vector3.Zero;
- m_group.SendGroupRootTerseUpdate();
-// m_group.RootPart.ScheduleTerseUpdate();
+ m_skippedUpdates = 1000;
+// m_group.SendGroupRootTerseUpdate();
+ m_group.RootPart.ScheduleTerseUpdate();
}
}
@@ -862,8 +871,9 @@ namespace OpenSim.Region.Framework.Scenes
if (m_group != null)
{
m_group.RootPart.Velocity = Vector3.Zero;
- m_group.SendGroupRootTerseUpdate();
-// m_group.RootPart.ScheduleTerseUpdate();
+ m_skippedUpdates = 1000;
+// m_group.SendGroupRootTerseUpdate();
+ m_group.RootPart.ScheduleTerseUpdate();
if (m_running)
{
diff --git a/OpenSim/Region/Framework/Scenes/Prioritizer.cs b/OpenSim/Region/Framework/Scenes/Prioritizer.cs
index cbf40c80c5..53ca849fb1 100644
--- a/OpenSim/Region/Framework/Scenes/Prioritizer.cs
+++ b/OpenSim/Region/Framework/Scenes/Prioritizer.cs
@@ -172,14 +172,22 @@ namespace OpenSim.Region.Framework.Scenes
if (entity is SceneObjectPart)
{
+ SceneObjectGroup sog = ((SceneObjectPart)entity).ParentGroup;
// Attachments are high priority,
- if (((SceneObjectPart)entity).ParentGroup.IsAttachment)
+ if (sog.IsAttachment)
return 2;
+
+
+ if(presence.ParentPart != null)
+ {
+ if(presence.ParentPart.ParentGroup == sog)
+ return 2;
+ }
pqueue = ComputeDistancePriority(client, entity, false);
// Non physical prims are lower priority than physical prims
- PhysicsActor physActor = ((SceneObjectPart)entity).ParentGroup.RootPart.PhysActor;
+ PhysicsActor physActor = sog.RootPart.PhysActor;
if (physActor == null || !physActor.IsPhysical)
pqueue++;
}
@@ -302,6 +310,17 @@ namespace OpenSim.Region.Framework.Scenes
else
{
SceneObjectGroup group = (entity as SceneObjectPart).ParentGroup;
+ if(presence.ParentPart != null)
+ {
+ if(presence.ParentPart.ParentGroup == group)
+ return pqueue;
+ }
+ if(group.IsAttachment)
+ {
+ if(group.RootPart.LocalId == presence.LocalId)
+ return pqueue;
+ }
+
float bradius = group.GetBoundsRadius();
Vector3 grppos = group.AbsolutePosition + group.getBoundsCenter();
distance = Vector3.Distance(presencePos, grppos);
diff --git a/OpenSim/Region/Framework/Scenes/SOPMaterial.cs b/OpenSim/Region/Framework/Scenes/SOPMaterial.cs
index 651c52eee5..d38ef615ef 100644
--- a/OpenSim/Region/Framework/Scenes/SOPMaterial.cs
+++ b/OpenSim/Region/Framework/Scenes/SOPMaterial.cs
@@ -28,6 +28,7 @@
using System;
using System.Collections.Generic;
using OpenMetaverse;
+using OpenMetaverse.StructuredData;
using OpenSim.Framework;
namespace OpenSim.Region.Framework.Scenes
@@ -90,6 +91,87 @@ namespace OpenSim.Region.Framework.Scenes
else
return 0;
}
+ }
+ public class FaceMaterial
+ {
+ public UUID ID;
+ public UUID NormalMapID = UUID.Zero;
+ public float NormalOffsetX = 0.0f;
+ public float NormalOffsetY = 0.0f;
+ public float NormalRepeatX = 1.0f;
+ public float NormalRepeatY = 1.0f;
+ public float NormalRotation = 0.0f;
+
+ public UUID SpecularMapID = UUID.Zero;
+ public float SpecularOffsetX = 0.0f;
+ public float SpecularOffsetY = 0.0f;
+ public float SpecularRepeatX = 1.0f;
+ public float SpecularRepeatY = 1.0f;
+ public float SpecularRotation = 0.0f;
+
+ public Color4 SpecularLightColor = new Color4(255,255,255,255);
+ public Byte SpecularLightExponent = 51;
+ public Byte EnvironmentIntensity = 0;
+ public Byte DiffuseAlphaMode = 1;
+ public Byte AlphaMaskCutoff = 0;
+
+ public FaceMaterial()
+ { }
+
+ public FaceMaterial(UUID pID, OSDMap mat)
+ {
+ ID = pID;
+ if(mat == null)
+ return;
+ float scale = 0.0001f;
+ NormalMapID = mat["NormMap"].AsUUID();
+ NormalOffsetX = scale * (float)mat["NormOffsetX"].AsReal();
+ NormalOffsetY = scale * (float)mat["NormOffsetY"].AsReal();
+ NormalRepeatX = scale * (float)mat["NormRepeatX"].AsReal();
+ NormalRepeatY = scale * (float)mat["NormRepeatY"].AsReal();
+ NormalRotation = scale * (float)mat["NormRotation"].AsReal();
+
+ SpecularMapID = mat["SpecMap"].AsUUID();
+ SpecularOffsetX = scale * (float)mat["SpecOffsetX"].AsReal();
+ SpecularOffsetY = scale * (float)mat["SpecOffsetY"].AsReal();
+ SpecularRepeatX = scale * (float)mat["SpecRepeatX"].AsReal();
+ SpecularRepeatY = scale * (float)mat["SpecRepeatY"].AsReal();
+ SpecularRotation = scale * (float)mat["SpecRotation"].AsReal();
+
+ SpecularLightColor = mat["SpecColor"].AsColor4();
+ SpecularLightExponent = (Byte)mat["SpecExp"].AsUInteger();
+ EnvironmentIntensity = (Byte)mat["EnvIntensity"].AsUInteger();
+ DiffuseAlphaMode = (Byte)mat["DiffuseAlphaMode"].AsUInteger();
+ AlphaMaskCutoff = (Byte)mat["AlphaMaskCutoff"].AsUInteger();
+ }
+
+ public OSDMap toOSD()
+ {
+ OSDMap mat = new OSDMap();
+ float scale = 10000f;
+
+ mat["NormMap"] = NormalMapID;
+ mat["NormOffsetX"] = (int) (scale * NormalOffsetX);
+ mat["NormOffsetY"] = (int) (scale * NormalOffsetY);
+ mat["NormRepeatX"] = (int) (scale * NormalRepeatX);
+ mat["NormRepeatY"] = (int) (scale * NormalRepeatY);
+ mat["NormRotation"] = (int) (scale * NormalRotation);
+
+ mat["SpecMap"] = SpecularMapID;
+ mat["SpecOffsetX"] = (int) (scale * SpecularOffsetX);
+ mat["SpecOffsetY"] = (int) (scale * SpecularOffsetY);
+ mat["SpecRepeatX"] = (int) (scale * SpecularRepeatX);
+ mat["SpecRepeatY"] = (int) (scale * SpecularRepeatY);
+ mat["SpecRotation"] = (int) (scale * SpecularRotation);
+
+ mat["SpecColor"] = SpecularLightColor;
+ mat["SpecExp"] = SpecularLightExponent;
+ mat["EnvIntensity"] = EnvironmentIntensity;
+ mat["DiffuseAlphaMode"] = DiffuseAlphaMode;
+ mat["AlphaMaskCutoff"] = AlphaMaskCutoff;
+
+ return mat;
+ }
}
}
\ No newline at end of file
diff --git a/OpenSim/Region/Framework/Scenes/SOPVehicle.cs b/OpenSim/Region/Framework/Scenes/SOPVehicle.cs
index 8d11331740..351eda35ed 100644
--- a/OpenSim/Region/Framework/Scenes/SOPVehicle.cs
+++ b/OpenSim/Region/Framework/Scenes/SOPVehicle.cs
@@ -425,25 +425,25 @@ namespace OpenSim.Region.Framework.Scenes
private void XWfloat(string name, float f)
{
- writer.WriteElementString(name, f.ToString(Utils.EnUsCulture));
+ writer.WriteElementString(name, f.ToString(Culture.FormatProvider));
}
private void XWVector(string name, Vector3 vec)
{
writer.WriteStartElement(name);
- writer.WriteElementString("X", vec.X.ToString(Utils.EnUsCulture));
- writer.WriteElementString("Y", vec.Y.ToString(Utils.EnUsCulture));
- writer.WriteElementString("Z", vec.Z.ToString(Utils.EnUsCulture));
+ writer.WriteElementString("X", vec.X.ToString(Culture.FormatProvider));
+ writer.WriteElementString("Y", vec.Y.ToString(Culture.FormatProvider));
+ writer.WriteElementString("Z", vec.Z.ToString(Culture.FormatProvider));
writer.WriteEndElement();
}
private void XWQuat(string name, Quaternion quat)
{
writer.WriteStartElement(name);
- writer.WriteElementString("X", quat.X.ToString(Utils.EnUsCulture));
- writer.WriteElementString("Y", quat.Y.ToString(Utils.EnUsCulture));
- writer.WriteElementString("Z", quat.Z.ToString(Utils.EnUsCulture));
- writer.WriteElementString("W", quat.W.ToString(Utils.EnUsCulture));
+ writer.WriteElementString("X", quat.X.ToString(Culture.FormatProvider));
+ writer.WriteElementString("Y", quat.Y.ToString(Culture.FormatProvider));
+ writer.WriteElementString("Z", quat.Z.ToString(Culture.FormatProvider));
+ writer.WriteElementString("W", quat.W.ToString(Culture.FormatProvider));
writer.WriteEndElement();
}
diff --git a/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs b/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs
index cb06540de5..057ca17b0d 100644
--- a/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs
+++ b/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs
@@ -338,6 +338,7 @@ namespace OpenSim.Region.Framework.Scenes
// Update item with new asset
item.AssetID = asset.FullID;
group.UpdateInventoryItem(item);
+ group.InvalidateEffectivePerms();
part.SendPropertiesToClient(remoteClient);
@@ -647,7 +648,8 @@ namespace OpenSim.Region.Framework.Scenes
// Modify
uint permsMask = ~ ((uint)PermissionMask.Copy |
(uint)PermissionMask.Transfer |
- (uint)PermissionMask.Modify);
+ (uint)PermissionMask.Modify |
+ (uint)PermissionMask.Export);
// Now, reduce the next perms to the mask bits
// relevant to the operation
@@ -677,13 +679,29 @@ namespace OpenSim.Region.Framework.Scenes
(uint)PermissionMask.Move;
uint ownerPerms = item.CurrentPermissions;
+ // These will be applied to the root prim at next rez.
+ // The legacy slam bit (bit 3) and folded permission (bits 0-2)
+ // are preserved due to the above mangling
+// ownerPerms &= nextPerms;
+
+ // Mask the base permissions. This is a conservative
+ // approach altering only the three main perms
+// basePerms &= nextPerms;
+
+ // Mask out the folded portion of the base mask.
+ // While the owner mask carries the actual folded
+ // permissions, the base mask carries the original
+ // base mask, before masking with the folded perms.
+ // We need this later for rezzing.
+// basePerms &= ~(uint)PermissionMask.FoldedMask;
+// basePerms |= ((basePerms >> 13) & 7) | (((basePerms & (uint)PermissionMask.Export) != 0) ? (uint)PermissionMask.FoldedExport : 0);
+
// If this is an object, root prim perms may be more
// permissive than folded perms. Use folded perms as
// a mask
- if (item.InvType == (int)InventoryType.Object)
+ uint foldedPerms = (item.CurrentPermissions & (uint)PermissionMask.FoldedMask) << (int)PermissionMask.FoldingShift;
+ if (foldedPerms != 0 && item.InvType == (int)InventoryType.Object)
{
- // Create a safe mask for the current perms
- uint foldedPerms = (item.CurrentPermissions & 7) << 13;
foldedPerms |= permsMask;
bool isRootMod = (item.CurrentPermissions &
@@ -691,6 +709,8 @@ namespace OpenSim.Region.Framework.Scenes
true : false;
// Mask the owner perms to the folded perms
+ // Note that this is only to satisfy the viewer.
+ // The effect of this will be reversed on rez.
ownerPerms &= foldedPerms;
basePerms &= foldedPerms;
@@ -705,15 +725,11 @@ namespace OpenSim.Region.Framework.Scenes
}
}
- // These will be applied to the root prim at next rez.
- // The slam bit (bit 3) and folded permission (bits 0-2)
- // are preserved due to the above mangling
+ // move here so nextperms are mandatory
ownerPerms &= nextPerms;
-
- // Mask the base permissions. This is a conservative
- // approach altering only the three main perms
basePerms &= nextPerms;
-
+ basePerms &= ~(uint)PermissionMask.FoldedMask;
+ basePerms |= ((basePerms >> 13) & 7) | (((basePerms & (uint)PermissionMask.Export) != 0) ? (uint)PermissionMask.FoldedExport : 0);
// Assign to the actual item. Make sure the slam bit is
// set, if it wasn't set before.
itemCopy.BasePermissions = basePerms;
@@ -1200,6 +1216,7 @@ namespace OpenSim.Region.Framework.Scenes
}
group.RemoveInventoryItem(localID, itemID);
+ group.InvalidateEffectivePerms();
}
part.SendPropertiesToClient(remoteClient);
@@ -1244,22 +1261,32 @@ namespace OpenSim.Region.Framework.Scenes
agentItem.InvType = taskItem.InvType;
agentItem.Flags = taskItem.Flags;
+ // The code below isn't OK. It doesn't account for flags being changed
+ // in the object inventory, so it will break when you do it. That
+ // is the previous behaviour, so no matter at this moment. However, there is a lot
+ // TODO: Fix this after the inventory fixer exists and has beenr run
if ((part.OwnerID != destAgent) && Permissions.PropagatePermissions())
{
- agentItem.BasePermissions = taskItem.BasePermissions & (taskItem.NextPermissions | (uint)PermissionMask.Move);
+ uint perms = taskItem.BasePermissions & taskItem.NextPermissions;
if (taskItem.InvType == (int)InventoryType.Object)
- agentItem.CurrentPermissions = agentItem.BasePermissions & (((taskItem.CurrentPermissions & 7) << 13) | (taskItem.CurrentPermissions & (uint)PermissionMask.Move));
+ {
+ PermissionsUtil.ApplyFoldedPermissions(taskItem.CurrentPermissions, ref perms );
+ perms = PermissionsUtil.FixAndFoldPermissions(perms);
+ }
else
- agentItem.CurrentPermissions = agentItem.BasePermissions & taskItem.CurrentPermissions;
-
- agentItem.CurrentPermissions = agentItem.BasePermissions;
+ perms &= taskItem.CurrentPermissions;
+ // always unlock
+ perms |= (uint)PermissionMask.Move;
+
+ agentItem.BasePermissions = perms;
+ agentItem.CurrentPermissions = perms;
+ agentItem.NextPermissions = perms & taskItem.NextPermissions;
+ agentItem.EveryOnePermissions = perms & taskItem.EveryonePermissions;
+ agentItem.GroupPermissions = perms & taskItem.GroupPermissions;
+
agentItem.Flags |= (uint)InventoryItemFlags.ObjectSlamPerm;
agentItem.Flags &= ~(uint)(InventoryItemFlags.ObjectOverwriteBase | InventoryItemFlags.ObjectOverwriteOwner | InventoryItemFlags.ObjectOverwriteGroup | InventoryItemFlags.ObjectOverwriteEveryone | InventoryItemFlags.ObjectOverwriteNextOwner);
- agentItem.NextPermissions = taskItem.NextPermissions;
- agentItem.EveryOnePermissions = taskItem.EveryonePermissions & (taskItem.NextPermissions | (uint)PermissionMask.Move);
- // Group permissions make no sense here
- agentItem.GroupPermissions = 0;
}
else
{
@@ -1267,7 +1294,7 @@ namespace OpenSim.Region.Framework.Scenes
agentItem.CurrentPermissions = taskItem.CurrentPermissions;
agentItem.NextPermissions = taskItem.NextPermissions;
agentItem.EveryOnePermissions = taskItem.EveryonePermissions;
- agentItem.GroupPermissions = 0;
+ agentItem.GroupPermissions = taskItem.GroupPermissions;
}
message = null;
@@ -1360,20 +1387,8 @@ namespace OpenSim.Region.Framework.Scenes
return;
}
- if ((taskItem.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
- {
- // If the item to be moved is no copy, we need to be able to
- // edit the prim.
- if (!Permissions.CanEditObjectInventory(part.UUID, remoteClient.AgentId))
- return;
- }
- else
- {
- // If the item is copiable, then we just need to have perms
- // on it. The delete check is a pure rights check
- if (!Permissions.CanDeleteObject(part.UUID, remoteClient.AgentId))
- return;
- }
+ if (!Permissions.CanCopyObjectInventory(itemId, part.UUID, remoteClient.AgentId))
+ return;
string message;
InventoryItemBase item = MoveTaskInventoryItem(remoteClient, folderId, part, itemId, out message);
@@ -1449,29 +1464,9 @@ namespace OpenSim.Region.Framework.Scenes
return;
}
- // Can't transfer this
- //
- if (part.OwnerID != destPart.OwnerID && (srcTaskItem.CurrentPermissions & (uint)PermissionMask.Transfer) == 0)
+ if(!Permissions.CanDoObjectInvToObjectInv(srcTaskItem, part, destPart))
return;
- bool overrideNoMod = false;
- if ((part.GetEffectiveObjectFlags() & (uint)PrimFlags.AllowInventoryDrop) != 0)
- overrideNoMod = true;
-
- if (part.OwnerID != destPart.OwnerID && (destPart.GetEffectiveObjectFlags() & (uint)PrimFlags.AllowInventoryDrop) == 0)
- {
- // object cannot copy items to an object owned by a different owner
- // unless llAllowInventoryDrop has been called
-
- return;
- }
-
- // must have both move and modify permission to put an item in an object
- if (((part.OwnerMask & (uint)PermissionMask.Modify) == 0) && (!overrideNoMod))
- {
- return;
- }
-
TaskInventoryItem destTaskItem = new TaskInventoryItem();
destTaskItem.ItemID = UUID.Random();
@@ -1512,9 +1507,10 @@ namespace OpenSim.Region.Framework.Scenes
destTaskItem.Type = srcTaskItem.Type;
destPart.Inventory.AddInventoryItem(destTaskItem, part.OwnerID != destPart.OwnerID);
-
if ((srcTaskItem.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
+ {
part.Inventory.RemoveInventoryItem(itemId);
+ }
ScenePresence avatar;
@@ -1652,76 +1648,79 @@ namespace OpenSim.Region.Framework.Scenes
uint primLocalID)
{
UUID itemID = itemInfo.ItemID;
+ if (itemID == UUID.Zero)
+ {
+ m_log.ErrorFormat(
+ "[PRIM INVENTORY]: UpdateTaskInventory called with item ID Zero on update for {1}!",
+ remoteClient.Name);
+ return;
+ }
// Find the prim we're dealing with
SceneObjectPart part = GetSceneObjectPart(primLocalID);
-
- if (part != null)
+ if(part == null)
{
- TaskInventoryItem currentItem = part.Inventory.GetInventoryItem(itemID);
- bool allowInventoryDrop = (part.GetEffectiveObjectFlags()
- & (uint)PrimFlags.AllowInventoryDrop) != 0;
+ m_log.WarnFormat(
+ "[PRIM INVENTORY]: " +
+ "Update with item {0} requested of prim {1} for {2} but this prim does not exist",
+ itemID, primLocalID, remoteClient.Name);
+ return;
+ }
- // Explicity allow anyone to add to the inventory if the
- // AllowInventoryDrop flag has been set. Don't however let
- // them update an item unless they pass the external checks
- //
- if (!Permissions.CanEditObjectInventory(part.UUID, remoteClient.AgentId)
- && (currentItem != null || !allowInventoryDrop))
+ TaskInventoryItem currentItem = part.Inventory.GetInventoryItem(itemID);
+
+ if (currentItem == null)
+ {
+ InventoryItemBase item = InventoryService.GetItem(remoteClient.AgentId, itemID);
+
+ // if not found Try library
+ if (item == null && LibraryService != null && LibraryService.LibraryRootFolder != null)
+ item = LibraryService.LibraryRootFolder.FindItem(itemID);
+
+ if(item == null)
+ {
+ m_log.ErrorFormat(
+ "[PRIM INVENTORY]: Could not find inventory item {0} to update for {1}!",
+ itemID, remoteClient.Name);
+ return;
+ }
+
+ if (!Permissions.CanDropInObjectInv(item, remoteClient, part))
return;
- if (currentItem == null)
+ UUID copyID = UUID.Random();
+ bool modrights = Permissions.CanEditObject(part.ParentGroup, remoteClient);
+ part.ParentGroup.AddInventoryItem(remoteClient.AgentId, primLocalID, item, copyID, modrights);
+ m_log.InfoFormat(
+ "[PRIM INVENTORY]: Update with item {0} requested of prim {1} for {2}",
+ item.Name, primLocalID, remoteClient.Name);
+ part.SendPropertiesToClient(remoteClient);
+ if (!Permissions.BypassPermissions())
{
- UUID copyID = UUID.Random();
- if (itemID != UUID.Zero)
+ if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
{
- InventoryItemBase item = InventoryService.GetItem(remoteClient.AgentId, itemID);
-
- // Try library
- if (null == item && LibraryService != null && LibraryService.LibraryRootFolder != null)
- {
- item = LibraryService.LibraryRootFolder.FindItem(itemID);
- }
-
- // If we've found the item in the user's inventory or in the library
- if (item != null)
- {
- part.ParentGroup.AddInventoryItem(remoteClient.AgentId, primLocalID, item, copyID);
- m_log.InfoFormat(
- "[PRIM INVENTORY]: Update with item {0} requested of prim {1} for {2}",
- item.Name, primLocalID, remoteClient.Name);
- part.SendPropertiesToClient(remoteClient);
- if (!Permissions.BypassPermissions())
- {
- if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
- {
- List uuids = new List();
- uuids.Add(itemID);
- RemoveInventoryItem(remoteClient, uuids);
- }
- }
- }
- else
- {
- m_log.ErrorFormat(
- "[PRIM INVENTORY]: Could not find inventory item {0} to update for {1}!",
- itemID, remoteClient.Name);
- }
+ List uuids = new List();
+ uuids.Add(itemID);
+ RemoveInventoryItem(remoteClient, uuids);
}
}
- else // Updating existing item with new perms etc
- {
+ }
+ else // Updating existing item with new perms etc
+ {
// m_log.DebugFormat(
// "[PRIM INVENTORY]: Updating item {0} in {1} for UpdateTaskInventory()",
// currentItem.Name, part.Name);
- // Only look for an uploaded updated asset if we are passed a transaction ID. This is only the
- // case for updates uploded through UDP. Updates uploaded via a capability (e.g. a script update)
- // will not pass in a transaction ID in the update message.
- if (transactionID != UUID.Zero && AgentTransactionsModule != null)
- {
- AgentTransactionsModule.HandleTaskItemUpdateFromTransaction(
- remoteClient, part, transactionID, currentItem);
+ if (!Permissions.CanEditObjectInventory(part.UUID, remoteClient.AgentId))
+ return;
+
+ // Only look for an uploaded updated asset if we are passed a transaction ID. This is only the
+ // case for updates uploded through UDP. Updates uploaded via a capability (e.g. a script update)
+ // will not pass in a transaction ID in the update message.
+ if (transactionID != UUID.Zero && AgentTransactionsModule != null)
+ {
+ AgentTransactionsModule.HandleTaskItemUpdateFromTransaction(
+ remoteClient, part, transactionID, currentItem);
// if ((InventoryType)itemInfo.InvType == InventoryType.Notecard)
// remoteClient.SendAgentAlertMessage("Notecard saved", false);
@@ -1729,49 +1728,47 @@ namespace OpenSim.Region.Framework.Scenes
// remoteClient.SendAgentAlertMessage("Script saved", false);
// else
// remoteClient.SendAgentAlertMessage("Item saved", false);
- }
+ }
- // Base ALWAYS has move
- currentItem.BasePermissions |= (uint)PermissionMask.Move;
+ // Base ALWAYS has move
+ currentItem.BasePermissions |= (uint)PermissionMask.Move;
- itemInfo.Flags = currentItem.Flags;
+ itemInfo.Flags = currentItem.Flags;
- // Check if we're allowed to mess with permissions
- if (!Permissions.IsGod(remoteClient.AgentId)) // Not a god
+ // Check if we're allowed to mess with permissions
+ if (!Permissions.IsGod(remoteClient.AgentId)) // Not a god
+ {
+ bool noChange;
+ if (remoteClient.AgentId != part.OwnerID) // Not owner
{
- if (remoteClient.AgentId != part.OwnerID) // Not owner
+ noChange = true;
+ if(itemInfo.OwnerID == UUID.Zero && itemInfo.GroupID != UUID.Zero)
{
- // Friends and group members can't change any perms
- itemInfo.BasePermissions = currentItem.BasePermissions;
- itemInfo.EveryonePermissions = currentItem.EveryonePermissions;
- itemInfo.GroupPermissions = currentItem.GroupPermissions;
- itemInfo.NextPermissions = currentItem.NextPermissions;
- itemInfo.CurrentPermissions = currentItem.CurrentPermissions;
- }
- else
- {
- // Owner can't change base, and can change other
- // only up to base
- itemInfo.BasePermissions = currentItem.BasePermissions;
- if (itemInfo.EveryonePermissions != currentItem.EveryonePermissions)
- itemInfo.Flags |= (uint)InventoryItemFlags.ObjectOverwriteEveryone;
- if (itemInfo.GroupPermissions != currentItem.GroupPermissions)
- itemInfo.Flags |= (uint)InventoryItemFlags.ObjectOverwriteGroup;
- if (itemInfo.CurrentPermissions != currentItem.CurrentPermissions)
- itemInfo.Flags |= (uint)InventoryItemFlags.ObjectOverwriteOwner;
- if (itemInfo.NextPermissions != currentItem.NextPermissions)
- itemInfo.Flags |= (uint)InventoryItemFlags.ObjectOverwriteNextOwner;
- itemInfo.EveryonePermissions &= currentItem.BasePermissions;
- itemInfo.GroupPermissions &= currentItem.BasePermissions;
- itemInfo.CurrentPermissions &= currentItem.BasePermissions;
- itemInfo.NextPermissions &= currentItem.BasePermissions;
+ if(remoteClient.IsGroupMember(itemInfo.GroupID))
+ {
+ ulong powers = remoteClient.GetGroupPowers(itemInfo.GroupID);
+ if((powers & (ulong)GroupPowers.ObjectManipulate) != 0)
+ noChange = false;
+ }
}
+ }
+ else
+ noChange = false;
+ if(noChange)
+ {
+ // Friends and group members can't change any perms
+ itemInfo.BasePermissions = currentItem.BasePermissions;
+ itemInfo.EveryonePermissions = currentItem.EveryonePermissions;
+ itemInfo.GroupPermissions = currentItem.GroupPermissions;
+ itemInfo.NextPermissions = currentItem.NextPermissions;
+ itemInfo.CurrentPermissions = currentItem.CurrentPermissions;
}
else
{
- if (itemInfo.BasePermissions != currentItem.BasePermissions)
- itemInfo.Flags |= (uint)InventoryItemFlags.ObjectOverwriteBase;
+ // Owner can't change base, and can change other
+ // only up to base
+ itemInfo.BasePermissions = currentItem.BasePermissions;
if (itemInfo.EveryonePermissions != currentItem.EveryonePermissions)
itemInfo.Flags |= (uint)InventoryItemFlags.ObjectOverwriteEveryone;
if (itemInfo.GroupPermissions != currentItem.GroupPermissions)
@@ -1780,23 +1777,33 @@ namespace OpenSim.Region.Framework.Scenes
itemInfo.Flags |= (uint)InventoryItemFlags.ObjectOverwriteOwner;
if (itemInfo.NextPermissions != currentItem.NextPermissions)
itemInfo.Flags |= (uint)InventoryItemFlags.ObjectOverwriteNextOwner;
- }
-
- // Next ALWAYS has move
- itemInfo.NextPermissions |= (uint)PermissionMask.Move;
-
- if (part.Inventory.UpdateInventoryItem(itemInfo))
- {
- part.SendPropertiesToClient(remoteClient);
+ itemInfo.EveryonePermissions &= currentItem.BasePermissions;
+ itemInfo.GroupPermissions &= currentItem.BasePermissions;
+ itemInfo.CurrentPermissions &= currentItem.BasePermissions;
+ itemInfo.NextPermissions &= currentItem.BasePermissions;
}
}
- }
- else
- {
- m_log.WarnFormat(
- "[PRIM INVENTORY]: " +
- "Update with item {0} requested of prim {1} for {2} but this prim does not exist",
- itemID, primLocalID, remoteClient.Name);
+ else
+ {
+ if (itemInfo.BasePermissions != currentItem.BasePermissions)
+ itemInfo.Flags |= (uint)InventoryItemFlags.ObjectOverwriteBase;
+ if (itemInfo.EveryonePermissions != currentItem.EveryonePermissions)
+ itemInfo.Flags |= (uint)InventoryItemFlags.ObjectOverwriteEveryone;
+ if (itemInfo.GroupPermissions != currentItem.GroupPermissions)
+ itemInfo.Flags |= (uint)InventoryItemFlags.ObjectOverwriteGroup;
+ if (itemInfo.CurrentPermissions != currentItem.CurrentPermissions)
+ itemInfo.Flags |= (uint)InventoryItemFlags.ObjectOverwriteOwner;
+ if (itemInfo.NextPermissions != currentItem.NextPermissions)
+ itemInfo.Flags |= (uint)InventoryItemFlags.ObjectOverwriteNextOwner;
+ }
+
+ // Next ALWAYS has move
+ itemInfo.NextPermissions |= (uint)PermissionMask.Move;
+
+ if (part.Inventory.UpdateInventoryItem(itemInfo))
+ {
+ part.SendPropertiesToClient(remoteClient);
+ }
}
}
@@ -1960,6 +1967,8 @@ namespace OpenSim.Region.Framework.Scenes
part.Inventory.AddInventoryItem(taskItem, false);
part.Inventory.CreateScriptInstance(taskItem, 0, false, DefaultScriptEngine, 0);
+ part.ParentGroup.InvalidateEffectivePerms();
+
// tell anyone managing scripts that a new script exists
EventManager.TriggerNewScript(agentID, part, taskItem.ItemID);
@@ -2095,13 +2104,20 @@ namespace OpenSim.Region.Framework.Scenes
/// DeRezAction
/// User folder ID to place derezzed object
public virtual void DeRezObjects(
- IClientAPI remoteClient, List localIDs, UUID groupID, DeRezAction action, UUID destinationID)
+ IClientAPI remoteClient, List localIDs, UUID groupID, DeRezAction action, UUID destinationID, bool AddToReturns = true)
{
// First, see of we can perform the requested action and
// build a list of eligible objects
List deleteIDs = new List();
List deleteGroups = new List();
List takeGroups = new List();
+ List takeDeleteGroups = new List();
+
+ ScenePresence sp = null;
+ if(remoteClient != null)
+ sp = remoteClient.SceneAgent as ScenePresence;
+ else if(action != DeRezAction.Return)
+ return; // only Return can be called without a client
// Start with true for both, then remove the flags if objects
// that we can't derez are part of the selection
@@ -2157,17 +2173,17 @@ namespace OpenSim.Region.Framework.Scenes
{
if (action == DeRezAction.TakeCopy)
{
- if (!Permissions.CanTakeCopyObject(grp.UUID, remoteClient.AgentId))
+ if (!Permissions.CanTakeCopyObject(grp, sp))
permissionToTakeCopy = false;
}
else
{
permissionToTakeCopy = false;
}
- if (!Permissions.CanTakeObject(grp.UUID, remoteClient.AgentId))
+ if (!Permissions.CanTakeObject(grp, sp))
permissionToTake = false;
- if (!Permissions.CanDeleteObject(grp.UUID, remoteClient.AgentId))
+ if (!Permissions.CanDeleteObject(grp, remoteClient))
permissionToDelete = false;
}
@@ -2208,13 +2224,14 @@ namespace OpenSim.Region.Framework.Scenes
{
if (Permissions.CanReturnObjects(
null,
- remoteClient.AgentId,
+ remoteClient,
new List() {grp}))
{
permissionToTake = true;
permissionToDelete = true;
-
- AddReturn(grp.OwnerID == grp.GroupID ? grp.LastOwnerID : grp.OwnerID, grp.Name, grp.AbsolutePosition, "parcel owner return");
+ if(AddToReturns)
+ AddReturn(grp.OwnerID == grp.GroupID ? grp.LastOwnerID : grp.OwnerID, grp.Name, grp.AbsolutePosition,
+ "parcel owner return");
}
}
else // Auto return passes through here with null agent
@@ -2224,26 +2241,24 @@ namespace OpenSim.Region.Framework.Scenes
}
}
- if (permissionToTake && (!permissionToDelete))
- takeGroups.Add(grp);
-
if (permissionToDelete)
{
if (permissionToTake)
+ takeDeleteGroups.Add(grp);
+ else
deleteGroups.Add(grp);
deleteIDs.Add(grp.LocalId);
}
+ else if(permissionToTake)
+ takeGroups.Add(grp);
}
SendKillObject(deleteIDs);
- if (deleteGroups.Count > 0)
+ if (takeDeleteGroups.Count > 0)
{
- foreach (SceneObjectGroup g in deleteGroups)
- deleteIDs.Remove(g.LocalId);
-
m_asyncSceneObjectDeleter.DeleteToInventory(
- action, destinationID, deleteGroups, remoteClient,
+ action, destinationID, takeDeleteGroups, remoteClient,
true);
}
if (takeGroups.Count > 0)
@@ -2252,7 +2267,7 @@ namespace OpenSim.Region.Framework.Scenes
action, destinationID, takeGroups, remoteClient,
false);
}
- if (deleteIDs.Count > 0)
+ if (deleteGroups.Count > 0)
{
foreach (SceneObjectGroup g in deleteGroups)
DeleteSceneObject(g, true);
@@ -2640,6 +2655,7 @@ namespace OpenSim.Region.Framework.Scenes
// We can only call this after adding the scene object, since the scene object references the scene
// to find out if scripts should be activated at all.
+ group.InvalidateEffectivePerms();
group.CreateScriptInstances(param, true, DefaultScriptEngine, 3);
group.ScheduleGroupForFullUpdate();
@@ -2649,7 +2665,7 @@ namespace OpenSim.Region.Framework.Scenes
}
public virtual bool returnObjects(SceneObjectGroup[] returnobjects,
- UUID AgentId)
+ IClientAPI client)
{
List localIDs = new List();
@@ -2659,8 +2675,8 @@ namespace OpenSim.Region.Framework.Scenes
"parcel owner return");
localIDs.Add(grp.RootPart.LocalId);
}
- DeRezObjects(null, localIDs, UUID.Zero, DeRezAction.Return,
- UUID.Zero);
+ DeRezObjects(client, localIDs, UUID.Zero, DeRezAction.Return,
+ UUID.Zero, false);
return true;
}
@@ -2691,9 +2707,6 @@ namespace OpenSim.Region.Framework.Scenes
{
if (ownerID != UUID.Zero)
return;
-
- if (!Permissions.CanDeedObject(remoteClient.AgentId, groupID))
- return;
}
List groups = new List();
@@ -2724,21 +2737,22 @@ namespace OpenSim.Region.Framework.Scenes
child.TriggerScriptChangedEvent(Changed.OWNER);
}
}
- else // The object was deeded to the group
+ else // The object deeded to the group
{
- if (!Permissions.IsGod(remoteClient.AgentId) && sog.OwnerID != remoteClient.AgentId)
- continue;
-
- if (!Permissions.CanTransferObject(sog.UUID, groupID))
- continue;
-
- if (sog.GroupID != groupID)
+ if (!Permissions.CanDeedObject(remoteClient, sog, groupID))
continue;
sog.SetOwnerId(groupID);
- // Make the group mask be the previous owner mask
- sog.RootPart.GroupMask = sog.RootPart.OwnerMask;
+
+ // this is wrong, GroupMask is used for group sharing, still possible to set
+ // this whould give owner rights to users that are member of group but don't have role powers to edit
+// sog.RootPart.GroupMask = sog.RootPart.OwnerMask;
+
+ // we should keep all permissions on deed to group
+ // and with this comented code, if user does not set next permissions on the object
+ // and on ALL contents of ALL prims, he may loose rights, making the object useless
sog.ApplyNextOwnerPermissions();
+ sog.InvalidateEffectivePerms();
sog.ScheduleGroupForFullUpdate();
@@ -2748,8 +2762,6 @@ namespace OpenSim.Region.Framework.Scenes
child.Inventory.ChangeInventoryOwner(groupID);
child.TriggerScriptChangedEvent(Changed.OWNER);
}
-
-
}
}
@@ -2853,7 +2865,7 @@ namespace OpenSim.Region.Framework.Scenes
root.SendPropertiesToClient(sp.ControllingClient);
if (oldUsePhysics && (root.Flags & PrimFlags.Physics) == 0)
{
- sp.ControllingClient.SendAlertMessage("Object physics canceled");
+ sp.ControllingClient.SendAlertMessage("Object physics cancelled");
}
}
}
diff --git a/OpenSim/Region/Framework/Scenes/Scene.PacketHandlers.cs b/OpenSim/Region/Framework/Scenes/Scene.PacketHandlers.cs
index 2d62b50af4..4fef9c3012 100644
--- a/OpenSim/Region/Framework/Scenes/Scene.PacketHandlers.cs
+++ b/OpenSim/Region/Framework/Scenes/Scene.PacketHandlers.cs
@@ -183,11 +183,12 @@ namespace OpenSim.Region.Framework.Scenes
part.SendFullUpdate(remoteClient);
// A prim is only tainted if it's allowed to be edited by the person clicking it.
- if (Permissions.CanEditObject(sog.UUID, remoteClient.AgentId)
- || Permissions.CanMoveObject(sog.UUID, remoteClient.AgentId))
+ if (Permissions.CanChangeSelectedState(part, (ScenePresence)remoteClient.SceneAgent))
{
+ bool oldsel = part.IsSelected;
part.IsSelected = true;
- EventManager.TriggerParcelPrimCountTainted();
+ if(!oldsel)
+ EventManager.TriggerParcelPrimCountTainted();
}
part.SendPropertiesToClient(remoteClient);
@@ -229,6 +230,7 @@ namespace OpenSim.Region.Framework.Scenes
if (so.OwnerID == remoteClient.AgentId)
{
so.SetGroup(groupID, remoteClient);
+ EventManager.TriggerParcelPrimCountTainted();
}
}
}
@@ -250,8 +252,7 @@ namespace OpenSim.Region.Framework.Scenes
// handled by group, but by prim. Legacy cruft.
// TODO: Make selection flagging per prim!
//
- if (Permissions.CanEditObject(part.ParentGroup.UUID, remoteClient.AgentId)
- || Permissions.CanMoveObject(part.ParentGroup.UUID, remoteClient.AgentId))
+ if (Permissions.CanChangeSelectedState(part, (ScenePresence)remoteClient.SceneAgent))
{
part.IsSelected = false;
if (!part.ParentGroup.IsAttachment && oldgprSelect != part.ParentGroup.IsSelected)
@@ -327,7 +328,7 @@ namespace OpenSim.Region.Framework.Scenes
if(group == null || group.IsDeleted)
return;
- if (Permissions.CanMoveObject(group.UUID, remoteClient.AgentId))// && PermissionsMngr.)
+ if (Permissions.CanMoveObject(group, remoteClient))// && PermissionsMngr.)
{
group.GrabMovement(objectID, offset, pos, remoteClient);
}
@@ -388,7 +389,7 @@ namespace OpenSim.Region.Framework.Scenes
SceneObjectGroup group = GetGroupByPrim(objectID);
if (group != null)
{
- if (Permissions.CanMoveObject(group.UUID, remoteClient.AgentId))// && PermissionsMngr.)
+ if (Permissions.CanMoveObject(group, remoteClient))// && PermissionsMngr.)
{
group.SpinStart(remoteClient);
}
@@ -406,7 +407,7 @@ namespace OpenSim.Region.Framework.Scenes
SceneObjectGroup group = GetGroupByPrim(objectID);
if (group != null)
{
- if (Permissions.CanMoveObject(group.UUID, remoteClient.AgentId))// && PermissionsMngr.)
+ if (Permissions.CanMoveObject(group, remoteClient))// && PermissionsMngr.)
{
group.SpinMovement(rotation, remoteClient);
}
diff --git a/OpenSim/Region/Framework/Scenes/Scene.Permissions.cs b/OpenSim/Region/Framework/Scenes/Scene.Permissions.cs
index 893b38c152..a75671e6fd 100644
--- a/OpenSim/Region/Framework/Scenes/Scene.Permissions.cs
+++ b/OpenSim/Region/Framework/Scenes/Scene.Permissions.cs
@@ -37,52 +37,61 @@ using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Region.Framework.Scenes
{
#region Delegates
- public delegate uint GenerateClientFlagsHandler(UUID userID, UUID objectID);
+ public delegate uint GenerateClientFlagsHandler(SceneObjectPart part, ScenePresence sp, uint curEffectivePerms);
public delegate void SetBypassPermissionsHandler(bool value);
public delegate bool BypassPermissionsHandler();
public delegate bool PropagatePermissionsHandler();
- public delegate bool RezObjectHandler(int objectCount, UUID owner, Vector3 objectPosition, Scene scene);
- public delegate bool DeleteObjectHandler(UUID objectID, UUID deleter, Scene scene);
- public delegate bool TransferObjectHandler(UUID objectID, UUID recipient, Scene scene);
- public delegate bool TakeObjectHandler(UUID objectID, UUID stealer, Scene scene);
- public delegate bool SellGroupObjectHandler(UUID userID, UUID groupID, Scene scene);
- public delegate bool TakeCopyObjectHandler(UUID objectID, UUID userID, Scene inScene);
- public delegate bool DuplicateObjectHandler(int objectCount, UUID objectID, UUID owner, Scene scene, Vector3 objectPosition);
- public delegate bool EditObjectHandler(UUID objectID, UUID editorID, Scene scene);
- public delegate bool EditObjectInventoryHandler(UUID objectID, UUID editorID, Scene scene);
- public delegate bool MoveObjectHandler(UUID objectID, UUID moverID, Scene scene);
- public delegate bool ObjectEntryHandler(UUID objectID, bool enteringRegion, Vector3 newPoint, Scene scene);
- public delegate bool ReturnObjectsHandler(ILandObject land, UUID user, List objects, Scene scene);
- public delegate bool InstantMessageHandler(UUID user, UUID target, Scene startScene);
- public delegate bool InventoryTransferHandler(UUID user, UUID target, Scene startScene);
- public delegate bool ViewScriptHandler(UUID script, UUID objectID, UUID user, Scene scene);
- public delegate bool ViewNotecardHandler(UUID script, UUID objectID, UUID user, Scene scene);
- public delegate bool EditScriptHandler(UUID script, UUID objectID, UUID user, Scene scene);
- public delegate bool EditNotecardHandler(UUID notecard, UUID objectID, UUID user, Scene scene);
- public delegate bool RunScriptHandler(UUID script, UUID objectID, UUID user, Scene scene);
- public delegate bool CompileScriptHandler(UUID ownerUUID, int scriptType, Scene scene);
- public delegate bool StartScriptHandler(UUID script, UUID user, Scene scene);
- public delegate bool StopScriptHandler(UUID script, UUID user, Scene scene);
- public delegate bool ResetScriptHandler(UUID prim, UUID script, UUID user, Scene scene);
- public delegate bool TerraformLandHandler(UUID user, Vector3 position, Scene requestFromScene);
- public delegate bool RunConsoleCommandHandler(UUID user, Scene requestFromScene);
- public delegate bool IssueEstateCommandHandler(UUID user, Scene requestFromScene, bool ownerCommand);
- public delegate bool IsGodHandler(UUID user, Scene requestFromScene);
- public delegate bool IsGridGodHandler(UUID user, Scene requestFromScene);
+ public delegate bool RezObjectHandler(int objectCount, UUID owner, Vector3 objectPosition);
+ public delegate bool DeleteObjectHandlerByIDs(UUID objectID, UUID deleter);
+ public delegate bool DeleteObjectHandler(SceneObjectGroup sog, ScenePresence sp);
+ public delegate bool TransferObjectHandler(UUID objectID, UUID recipient);
+ public delegate bool TakeObjectHandler(SceneObjectGroup sog, ScenePresence sp);
+ public delegate bool SellGroupObjectHandler(UUID userID, UUID groupID);
+ public delegate bool SellObjectHandlerByUserID(SceneObjectGroup sog, UUID userID, byte saleType);
+ public delegate bool SellObjectHandler(SceneObjectGroup sog, ScenePresence sp, byte saleType);
+ public delegate bool TakeCopyObjectHandler(SceneObjectGroup sog, ScenePresence sp);
+ public delegate bool DuplicateObjectHandler(SceneObjectGroup sog, ScenePresence sp);
+ public delegate bool EditObjectByIDsHandler(UUID objectID, UUID editorID);
+ public delegate bool EditObjectHandler(SceneObjectGroup sog, ScenePresence sp);
+ public delegate bool EditObjectPermsHandler(SceneObjectGroup sog, UUID editorID);
+ public delegate bool EditObjectInventoryHandler(UUID objectID, UUID editorID);
+ public delegate bool MoveObjectHandler(SceneObjectGroup sog, ScenePresence sp);
+ public delegate bool ObjectEntryHandler(SceneObjectGroup sog, bool enteringRegion, Vector3 newPoint);
+ public delegate bool ObjectEnterWithScriptsHandler(SceneObjectGroup sog, ILandObject land);
+ public delegate bool ReturnObjectsHandler(ILandObject land, ScenePresence sp, List objects);
+ public delegate bool InstantMessageHandler(UUID user, UUID target);
+ public delegate bool InventoryTransferHandler(UUID user, UUID target);
+ public delegate bool ViewScriptHandler(UUID script, UUID objectID, UUID user);
+ public delegate bool ViewNotecardHandler(UUID script, UUID objectID, UUID user);
+ public delegate bool EditScriptHandler(UUID script, UUID objectID, UUID user);
+ public delegate bool EditNotecardHandler(UUID notecard, UUID objectID, UUID user);
+ public delegate bool RunScriptHandlerByIDs(UUID script, UUID objectID, UUID user);
+ public delegate bool RunScriptHandler(TaskInventoryItem item, SceneObjectPart part);
+ public delegate bool CompileScriptHandler(UUID ownerUUID, int scriptType);
+ public delegate bool StartScriptHandler(UUID script, UUID user);
+ public delegate bool StopScriptHandler(UUID script, UUID user);
+ public delegate bool ResetScriptHandler(UUID prim, UUID script, UUID user);
+ public delegate bool TerraformLandHandler(UUID user, Vector3 position);
+ public delegate bool RunConsoleCommandHandler(UUID user);
+ public delegate bool IssueEstateCommandHandler(UUID user, bool ownerCommand);
+ public delegate bool IsGodHandler(UUID user);
+ public delegate bool IsGridGodHandler(UUID user);
public delegate bool IsAdministratorHandler(UUID user);
public delegate bool IsEstateManagerHandler(UUID user);
- public delegate bool EditParcelHandler(UUID user, ILandObject parcel, Scene scene);
- public delegate bool EditParcelPropertiesHandler(UUID user, ILandObject parcel, GroupPowers p, Scene scene, bool allowManager);
- public delegate bool SellParcelHandler(UUID user, ILandObject parcel, Scene scene);
- public delegate bool AbandonParcelHandler(UUID user, ILandObject parcel, Scene scene);
- public delegate bool ReclaimParcelHandler(UUID user, ILandObject parcel, Scene scene);
- public delegate bool DeedParcelHandler(UUID user, ILandObject parcel, Scene scene);
- public delegate bool DeedObjectHandler(UUID user, UUID group, Scene scene);
- public delegate bool BuyLandHandler(UUID user, ILandObject parcel, Scene scene);
+ public delegate bool EditParcelHandler(UUID user, ILandObject parcel);
+ public delegate bool EditParcelPropertiesHandler(UUID user, ILandObject parcel, GroupPowers p, bool allowManager);
+ public delegate bool SellParcelHandler(UUID user, ILandObject parcel);
+ public delegate bool AbandonParcelHandler(UUID user, ILandObject parcel);
+ public delegate bool ReclaimParcelHandler(UUID user, ILandObject parcel);
+ public delegate bool DeedParcelHandler(UUID user, ILandObject parcel);
+ public delegate bool DeedObjectHandler(ScenePresence sp, SceneObjectGroup sog, UUID targetGroupID);
+ public delegate bool BuyLandHandler(UUID user, ILandObject parcel);
public delegate bool LinkObjectHandler(UUID user, UUID objectID);
public delegate bool DelinkObjectHandler(UUID user, UUID objectID);
public delegate bool CreateObjectInventoryHandler(int invType, UUID objectID, UUID userID);
public delegate bool CopyObjectInventoryHandler(UUID itemID, UUID objectID, UUID userID);
+ public delegate bool DoObjectInvToObjectInv(TaskInventoryItem item, SceneObjectPart sourcePart, SceneObjectPart destPart);
+ public delegate bool DoDropInObjectInv(InventoryItemBase item, ScenePresence sp, SceneObjectPart destPart);
public delegate bool DeleteObjectInventoryHandler(UUID itemID, UUID objectID, UUID userID);
public delegate bool TransferObjectInventoryHandler(UUID itemID, UUID objectID, UUID userID);
public delegate bool CreateUserInventoryHandler(int invType, UUID userID);
@@ -112,16 +121,24 @@ namespace OpenSim.Region.Framework.Scenes
public event BypassPermissionsHandler OnBypassPermissions;
public event PropagatePermissionsHandler OnPropagatePermissions;
public event RezObjectHandler OnRezObject;
+ public event DeleteObjectHandlerByIDs OnDeleteObjectByIDs;
public event DeleteObjectHandler OnDeleteObject;
public event TransferObjectHandler OnTransferObject;
public event TakeObjectHandler OnTakeObject;
+
public event SellGroupObjectHandler OnSellGroupObject;
+ public event SellObjectHandlerByUserID OnSellObjectByUserID;
+ public event SellObjectHandler OnSellObject;
+
public event TakeCopyObjectHandler OnTakeCopyObject;
public event DuplicateObjectHandler OnDuplicateObject;
+ public event EditObjectByIDsHandler OnEditObjectByIDs;
public event EditObjectHandler OnEditObject;
+ public event EditObjectPermsHandler OnEditObjectPerms;
public event EditObjectInventoryHandler OnEditObjectInventory;
public event MoveObjectHandler OnMoveObject;
public event ObjectEntryHandler OnObjectEntry;
+ public event ObjectEnterWithScriptsHandler OnObjectEnterWithScripts;
public event ReturnObjectsHandler OnReturnObjects;
public event InstantMessageHandler OnInstantMessage;
public event InventoryTransferHandler OnInventoryTransfer;
@@ -129,6 +146,7 @@ namespace OpenSim.Region.Framework.Scenes
public event ViewNotecardHandler OnViewNotecard;
public event EditScriptHandler OnEditScript;
public event EditNotecardHandler OnEditNotecard;
+ public event RunScriptHandlerByIDs OnRunScriptByIDs;
public event RunScriptHandler OnRunScript;
public event CompileScriptHandler OnCompileScript;
public event StartScriptHandler OnStartScript;
@@ -137,7 +155,6 @@ namespace OpenSim.Region.Framework.Scenes
public event TerraformLandHandler OnTerraformLand;
public event RunConsoleCommandHandler OnRunConsoleCommand;
public event IssueEstateCommandHandler OnIssueEstateCommand;
- public event IsGodHandler OnIsGod;
public event IsGridGodHandler OnIsGridGod;
public event IsAdministratorHandler OnIsAdministrator;
public event IsEstateManagerHandler OnIsEstateManager;
@@ -153,6 +170,8 @@ namespace OpenSim.Region.Framework.Scenes
public event DelinkObjectHandler OnDelinkObject;
public event CreateObjectInventoryHandler OnCreateObjectInventory;
public event CopyObjectInventoryHandler OnCopyObjectInventory;
+ public event DoObjectInvToObjectInv OnDoObjectInvToObjectInv;
+ public event DoDropInObjectInv OnDropInObjectInv;
public event DeleteObjectInventoryHandler OnDeleteObjectInventory;
public event TransferObjectInventoryHandler OnTransferObjectInventory;
public event CreateUserInventoryHandler OnCreateUserInventory;
@@ -167,7 +186,7 @@ namespace OpenSim.Region.Framework.Scenes
#region Object Permission Checks
- public uint GenerateClientFlags(UUID userID, UUID objectID)
+ public uint GenerateClientFlags( SceneObjectPart part, ScenePresence sp)
{
// libomv will moan about PrimFlags.ObjectYouOfficer being
// obsolete...
@@ -179,12 +198,9 @@ namespace OpenSim.Region.Framework.Scenes
PrimFlags.ObjectTransfer |
PrimFlags.ObjectYouOwner |
PrimFlags.ObjectAnyOwner |
- PrimFlags.ObjectOwnerModify |
- PrimFlags.ObjectYouOfficer;
+ PrimFlags.ObjectOwnerModify;
#pragma warning restore 0612
- SceneObjectPart part = m_scene.GetSceneObjectPart(objectID);
-
if (part == null)
return 0;
@@ -196,7 +212,7 @@ namespace OpenSim.Region.Framework.Scenes
Delegate[] list = handlerGenerateClientFlags.GetInvocationList();
foreach (GenerateClientFlagsHandler check in list)
{
- perms &= check(userID, objectID);
+ perms &= check(part, sp, perms);
}
}
return perms;
@@ -248,7 +264,7 @@ namespace OpenSim.Region.Framework.Scenes
Delegate[] list = handler.GetInvocationList();
foreach (RezObjectHandler h in list)
{
- if (h(objectCount, owner,objectPosition, m_scene) == false)
+ if (h(objectCount, owner,objectPosition) == false)
return false;
}
}
@@ -262,141 +278,183 @@ namespace OpenSim.Region.Framework.Scenes
{
bool result = true;
- DeleteObjectHandler handler = OnDeleteObject;
+ DeleteObjectHandlerByIDs handler = OnDeleteObjectByIDs;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
- foreach (DeleteObjectHandler h in list)
+ foreach (DeleteObjectHandlerByIDs h in list)
{
- if (h(objectID, deleter, m_scene) == false)
+ if (h(objectID, deleter) == false)
{
result = false;
break;
}
}
}
-
return result;
}
+ public bool CanDeleteObject(SceneObjectGroup sog, IClientAPI client)
+ {
+ DeleteObjectHandler handler = OnDeleteObject;
+ if (handler != null)
+ {
+ if(sog == null || client == null || client.SceneAgent == null)
+ return false;
+
+ ScenePresence sp = client.SceneAgent as ScenePresence;
+
+ Delegate[] list = handler.GetInvocationList();
+ foreach (DeleteObjectHandler h in list)
+ {
+ if (h(sog, sp) == false)
+ return false;
+ }
+ }
+
+ return true;
+ }
+
public bool CanTransferObject(UUID objectID, UUID recipient)
{
- bool result = true;
-
TransferObjectHandler handler = OnTransferObject;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (TransferObjectHandler h in list)
{
- if (h(objectID, recipient, m_scene) == false)
- {
- result = false;
- break;
- }
+ if (h(objectID, recipient) == false)
+ return false;
}
}
-
- return result;
+ return true;
}
#endregion
#region TAKE OBJECT
- public bool CanTakeObject(UUID objectID, UUID AvatarTakingUUID)
+ public bool CanTakeObject(SceneObjectGroup sog, ScenePresence sp)
{
- bool result = true;
-
TakeObjectHandler handler = OnTakeObject;
if (handler != null)
{
+ if(sog == null || sp == null)
+ return false;
+
Delegate[] list = handler.GetInvocationList();
foreach (TakeObjectHandler h in list)
{
- if (h(objectID, AvatarTakingUUID, m_scene) == false)
- {
- result = false;
- break;
- }
+ if (h(sog, sp) == false)
+ return false;
}
}
-
// m_log.DebugFormat(
// "[SCENE PERMISSIONS]: CanTakeObject() fired for object {0}, taker {1}, result {2}",
// objectID, AvatarTakingUUID, result);
-
- return result;
+ return true;
}
#endregion
#region SELL GROUP OBJECT
- public bool CanSellGroupObject(UUID userID, UUID groupID, Scene scene)
+ public bool CanSellGroupObject(UUID userID, UUID groupID)
{
- bool result = true;
-
SellGroupObjectHandler handler = OnSellGroupObject;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (SellGroupObjectHandler h in list)
{
- if (h(userID, groupID, scene) == false)
- {
- result = false;
- break;
- }
+ if (h(userID, groupID) == false)
+ return false;
}
}
-
//m_log.DebugFormat(
// "[SCENE PERMISSIONS]: CanSellGroupObject() fired for user {0}, group {1}, result {2}",
// userID, groupID, result);
+ return true;
+ }
- return result;
+ #endregion
+
+ #region SELL OBJECT
+ public bool CanSellObject(IClientAPI client, SceneObjectGroup sog, byte saleType)
+ {
+ SellObjectHandler handler = OnSellObject;
+ if (handler != null)
+ {
+ if(sog == null || client == null || client.SceneAgent == null)
+ return false;
+
+ ScenePresence sp = client.SceneAgent as ScenePresence;
+ Delegate[] list = handler.GetInvocationList();
+ foreach (SellObjectHandler h in list)
+ {
+ if (h(sog, sp, saleType) == false)
+ return false;
+ }
+ }
+ return true;
+ }
+
+ public bool CanSellObject(UUID userID, SceneObjectGroup sog, byte saleType)
+ {
+ SellObjectHandlerByUserID handler = OnSellObjectByUserID;
+ if (handler != null)
+ {
+ if(sog == null)
+ return false;
+ Delegate[] list = handler.GetInvocationList();
+ foreach (SellObjectHandlerByUserID h in list)
+ {
+ if (h(sog, userID, saleType) == false)
+ return false;
+ }
+ }
+ return true;
}
#endregion
#region TAKE COPY OBJECT
- public bool CanTakeCopyObject(UUID objectID, UUID userID)
+ public bool CanTakeCopyObject(SceneObjectGroup sog, ScenePresence sp)
{
- bool result = true;
-
TakeCopyObjectHandler handler = OnTakeCopyObject;
if (handler != null)
{
+ if(sog == null || sp == null)
+ return false;
Delegate[] list = handler.GetInvocationList();
foreach (TakeCopyObjectHandler h in list)
{
- if (h(objectID, userID, m_scene) == false)
- {
- result = false;
- break;
- }
+ if (h(sog, sp) == false)
+ return false;
}
}
-
// m_log.DebugFormat(
// "[SCENE PERMISSIONS]: CanTakeCopyObject() fired for object {0}, user {1}, result {2}",
// objectID, userID, result);
-
- return result;
+ return true;
}
#endregion
#region DUPLICATE OBJECT
- public bool CanDuplicateObject(int objectCount, UUID objectID, UUID owner, Vector3 objectPosition)
+ public bool CanDuplicateObject(SceneObjectGroup sog, UUID agentID)
{
DuplicateObjectHandler handler = OnDuplicateObject;
if (handler != null)
{
+ if(sog == null || sog.IsDeleted)
+ return false;
+ ScenePresence sp = m_scene.GetScenePresence(agentID);
+ if(sp == null || sp.IsDeleted)
+ return false;
Delegate[] list = handler.GetInvocationList();
foreach (DuplicateObjectHandler h in list)
{
- if (h(objectCount, objectID, owner, m_scene, objectPosition) == false)
+ if (h(sog, sp) == false)
return false;
}
}
@@ -405,22 +463,74 @@ namespace OpenSim.Region.Framework.Scenes
#endregion
+ #region persence EDIT or MOVE OBJECT
+ private const uint CANSELECTMASK = (uint)(
+ PrimFlags.ObjectMove |
+ PrimFlags.ObjectModify |
+ PrimFlags.ObjectOwnerModify
+ );
+
+ public bool CanChangeSelectedState(SceneObjectPart part, ScenePresence sp)
+ {
+ uint perms = GenerateClientFlags(part, sp);
+ return (perms & CANSELECTMASK) != 0;
+ }
+
+ #endregion
#region EDIT OBJECT
public bool CanEditObject(UUID objectID, UUID editorID)
{
- EditObjectHandler handler = OnEditObject;
+ EditObjectByIDsHandler handler = OnEditObjectByIDs;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
- foreach (EditObjectHandler h in list)
+ foreach (EditObjectByIDsHandler h in list)
{
- if (h(objectID, editorID, m_scene) == false)
+ if (h(objectID, editorID) == false)
return false;
}
}
return true;
}
+ public bool CanEditObject(SceneObjectGroup sog, IClientAPI client)
+ {
+ EditObjectHandler handler = OnEditObject;
+ if (handler != null)
+ {
+ if(sog == null || client == null || client.SceneAgent == null)
+ return false;
+
+ ScenePresence sp = client.SceneAgent as ScenePresence;
+
+ Delegate[] list = handler.GetInvocationList();
+ foreach (EditObjectHandler h in list)
+ {
+ if (h(sog, sp) == false)
+ return false;
+ }
+ }
+ return true;
+ }
+
+ public bool CanEditObjectPermissions(SceneObjectGroup sog, UUID editorID)
+ {
+ EditObjectPermsHandler handler = OnEditObjectPerms;
+ if (handler != null)
+ {
+ if(sog == null)
+ return false;
+ Delegate[] list = handler.GetInvocationList();
+ foreach (EditObjectPermsHandler h in list)
+ {
+ if (h(sog, editorID) == false)
+ return false;
+ }
+ }
+ return true;
+ }
+
+
public bool CanEditObjectInventory(UUID objectID, UUID editorID)
{
EditObjectInventoryHandler handler = OnEditObjectInventory;
@@ -429,7 +539,7 @@ namespace OpenSim.Region.Framework.Scenes
Delegate[] list = handler.GetInvocationList();
foreach (EditObjectInventoryHandler h in list)
{
- if (h(objectID, editorID, m_scene) == false)
+ if (h(objectID, editorID) == false)
return false;
}
}
@@ -439,15 +549,20 @@ namespace OpenSim.Region.Framework.Scenes
#endregion
#region MOVE OBJECT
- public bool CanMoveObject(UUID objectID, UUID moverID)
+ public bool CanMoveObject(SceneObjectGroup sog, IClientAPI client)
{
MoveObjectHandler handler = OnMoveObject;
if (handler != null)
{
+ if(sog == null || client == null || client.SceneAgent == null)
+ return false;
+
+ ScenePresence sp = client.SceneAgent as ScenePresence;
+
Delegate[] list = handler.GetInvocationList();
foreach (MoveObjectHandler h in list)
{
- if (h(objectID, moverID, m_scene) == false)
+ if (h(sog, sp) == false)
return false;
}
}
@@ -457,7 +572,7 @@ namespace OpenSim.Region.Framework.Scenes
#endregion
#region OBJECT ENTRY
- public bool CanObjectEntry(UUID objectID, bool enteringRegion, Vector3 newPoint)
+ public bool CanObjectEntry(SceneObjectGroup sog, bool enteringRegion, Vector3 newPoint)
{
ObjectEntryHandler handler = OnObjectEntry;
if (handler != null)
@@ -465,7 +580,22 @@ namespace OpenSim.Region.Framework.Scenes
Delegate[] list = handler.GetInvocationList();
foreach (ObjectEntryHandler h in list)
{
- if (h(objectID, enteringRegion, newPoint, m_scene) == false)
+ if (h(sog, enteringRegion, newPoint) == false)
+ return false;
+ }
+ }
+ return true;
+ }
+
+ public bool CanObjectEnterWithScripts(SceneObjectGroup sog, ILandObject land)
+ {
+ ObjectEnterWithScriptsHandler handler = OnObjectEnterWithScripts;
+ if (handler != null)
+ {
+ Delegate[] list = handler.GetInvocationList();
+ foreach (ObjectEnterWithScriptsHandler h in list)
+ {
+ if (h(sog, land) == false)
return false;
}
}
@@ -475,29 +605,30 @@ namespace OpenSim.Region.Framework.Scenes
#endregion
#region RETURN OBJECT
- public bool CanReturnObjects(ILandObject land, UUID user, List objects)
+ public bool CanReturnObjects(ILandObject land, IClientAPI client, List objects)
{
- bool result = true;
-
ReturnObjectsHandler handler = OnReturnObjects;
if (handler != null)
{
+ if(objects == null)
+ return false;
+
+ ScenePresence sp = null;
+ if(client != null && client.SceneAgent != null)
+ sp = client.SceneAgent as ScenePresence;
+
Delegate[] list = handler.GetInvocationList();
foreach (ReturnObjectsHandler h in list)
{
- if (h(land, user, objects, m_scene) == false)
- {
- result = false;
- break;
- }
+ if (h(land, sp, objects) == false)
+ return false;
}
}
-
// m_log.DebugFormat(
// "[SCENE PERMISSIONS]: CanReturnObjects() fired for user {0} for {1} objects on {2}, result {3}",
// user, objects.Count, land.LandData.Name, result);
- return result;
+ return true;
}
#endregion
@@ -511,7 +642,7 @@ namespace OpenSim.Region.Framework.Scenes
Delegate[] list = handler.GetInvocationList();
foreach (InstantMessageHandler h in list)
{
- if (h(user, target, m_scene) == false)
+ if (h(user, target) == false)
return false;
}
}
@@ -529,7 +660,7 @@ namespace OpenSim.Region.Framework.Scenes
Delegate[] list = handler.GetInvocationList();
foreach (InventoryTransferHandler h in list)
{
- if (h(user, target, m_scene) == false)
+ if (h(user, target) == false)
return false;
}
}
@@ -547,7 +678,7 @@ namespace OpenSim.Region.Framework.Scenes
Delegate[] list = handler.GetInvocationList();
foreach (ViewScriptHandler h in list)
{
- if (h(script, objectID, user, m_scene) == false)
+ if (h(script, objectID, user) == false)
return false;
}
}
@@ -562,7 +693,7 @@ namespace OpenSim.Region.Framework.Scenes
Delegate[] list = handler.GetInvocationList();
foreach (ViewNotecardHandler h in list)
{
- if (h(script, objectID, user, m_scene) == false)
+ if (h(script, objectID, user) == false)
return false;
}
}
@@ -580,7 +711,7 @@ namespace OpenSim.Region.Framework.Scenes
Delegate[] list = handler.GetInvocationList();
foreach (EditScriptHandler h in list)
{
- if (h(script, objectID, user, m_scene) == false)
+ if (h(script, objectID, user) == false)
return false;
}
}
@@ -595,7 +726,7 @@ namespace OpenSim.Region.Framework.Scenes
Delegate[] list = handler.GetInvocationList();
foreach (EditNotecardHandler h in list)
{
- if (h(script, objectID, user, m_scene) == false)
+ if (h(script, objectID, user) == false)
return false;
}
}
@@ -607,19 +738,37 @@ namespace OpenSim.Region.Framework.Scenes
#region RUN SCRIPT (When Script Placed in Object)
public bool CanRunScript(UUID script, UUID objectID, UUID user)
{
- RunScriptHandler handler = OnRunScript;
+ RunScriptHandlerByIDs handler = OnRunScriptByIDs;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
- foreach (RunScriptHandler h in list)
+ foreach (RunScriptHandlerByIDs h in list)
{
- if (h(script, objectID, user, m_scene) == false)
+ if (h(script, objectID, user) == false)
return false;
}
}
return true;
}
+ public bool CanRunScript(TaskInventoryItem item, SceneObjectPart part)
+ {
+ RunScriptHandler handler = OnRunScript;
+ if (handler != null)
+ {
+ if(item == null || part == null)
+ return false;
+ Delegate[] list = handler.GetInvocationList();
+ foreach (RunScriptHandler h in list)
+ {
+ if (h(item, part) == false)
+ return false;
+ }
+ }
+ return true;
+ }
+
+
#endregion
#region COMPILE SCRIPT (When Script needs to get (re)compiled)
@@ -631,7 +780,7 @@ namespace OpenSim.Region.Framework.Scenes
Delegate[] list = handler.GetInvocationList();
foreach (CompileScriptHandler h in list)
{
- if (h(ownerUUID, scriptType, m_scene) == false)
+ if (h(ownerUUID, scriptType) == false)
return false;
}
}
@@ -649,7 +798,7 @@ namespace OpenSim.Region.Framework.Scenes
Delegate[] list = handler.GetInvocationList();
foreach (StartScriptHandler h in list)
{
- if (h(script, user, m_scene) == false)
+ if (h(script, user) == false)
return false;
}
}
@@ -667,7 +816,7 @@ namespace OpenSim.Region.Framework.Scenes
Delegate[] list = handler.GetInvocationList();
foreach (StopScriptHandler h in list)
{
- if (h(script, user, m_scene) == false)
+ if (h(script, user) == false)
return false;
}
}
@@ -685,7 +834,7 @@ namespace OpenSim.Region.Framework.Scenes
Delegate[] list = handler.GetInvocationList();
foreach (ResetScriptHandler h in list)
{
- if (h(prim, script, user, m_scene) == false)
+ if (h(prim, script, user) == false)
return false;
}
}
@@ -703,7 +852,7 @@ namespace OpenSim.Region.Framework.Scenes
Delegate[] list = handler.GetInvocationList();
foreach (TerraformLandHandler h in list)
{
- if (h(user, pos, m_scene) == false)
+ if (h(user, pos) == false)
return false;
}
}
@@ -721,7 +870,7 @@ namespace OpenSim.Region.Framework.Scenes
Delegate[] list = handler.GetInvocationList();
foreach (RunConsoleCommandHandler h in list)
{
- if (h(user, m_scene) == false)
+ if (h(user) == false)
return false;
}
}
@@ -739,7 +888,7 @@ namespace OpenSim.Region.Framework.Scenes
Delegate[] list = handler.GetInvocationList();
foreach (IssueEstateCommandHandler h in list)
{
- if (h(user, m_scene, ownerCommand) == false)
+ if (h(user, ownerCommand) == false)
return false;
}
}
@@ -750,13 +899,13 @@ namespace OpenSim.Region.Framework.Scenes
#region CAN BE GODLIKE
public bool IsGod(UUID user)
{
- IsGodHandler handler = OnIsGod;
+ IsAdministratorHandler handler = OnIsAdministrator;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
- foreach (IsGodHandler h in list)
+ foreach (IsAdministratorHandler h in list)
{
- if (h(user, m_scene) == false)
+ if (h(user) == false)
return false;
}
}
@@ -771,7 +920,7 @@ namespace OpenSim.Region.Framework.Scenes
Delegate[] list = handler.GetInvocationList();
foreach (IsGridGodHandler h in list)
{
- if (h(user, m_scene) == false)
+ if (h(user) == false)
return false;
}
}
@@ -819,7 +968,7 @@ namespace OpenSim.Region.Framework.Scenes
Delegate[] list = handler.GetInvocationList();
foreach (EditParcelPropertiesHandler h in list)
{
- if (h(user, parcel, p, m_scene, allowManager) == false)
+ if (h(user, parcel, p, allowManager) == false)
return false;
}
}
@@ -836,7 +985,7 @@ namespace OpenSim.Region.Framework.Scenes
Delegate[] list = handler.GetInvocationList();
foreach (SellParcelHandler h in list)
{
- if (h(user, parcel, m_scene) == false)
+ if (h(user, parcel) == false)
return false;
}
}
@@ -853,7 +1002,7 @@ namespace OpenSim.Region.Framework.Scenes
Delegate[] list = handler.GetInvocationList();
foreach (AbandonParcelHandler h in list)
{
- if (h(user, parcel, m_scene) == false)
+ if (h(user, parcel) == false)
return false;
}
}
@@ -869,7 +1018,7 @@ namespace OpenSim.Region.Framework.Scenes
Delegate[] list = handler.GetInvocationList();
foreach (ReclaimParcelHandler h in list)
{
- if (h(user, parcel, m_scene) == false)
+ if (h(user, parcel) == false)
return false;
}
}
@@ -884,22 +1033,27 @@ namespace OpenSim.Region.Framework.Scenes
Delegate[] list = handler.GetInvocationList();
foreach (DeedParcelHandler h in list)
{
- if (h(user, parcel, m_scene) == false)
+ if (h(user, parcel) == false)
return false;
}
}
return true;
}
- public bool CanDeedObject(UUID user, UUID group)
+ public bool CanDeedObject(IClientAPI client, SceneObjectGroup sog, UUID targetGroupID)
{
DeedObjectHandler handler = OnDeedObject;
if (handler != null)
{
+ if(sog == null || client == null || client.SceneAgent == null || targetGroupID == UUID.Zero)
+ return false;
+
+ ScenePresence sp = client.SceneAgent as ScenePresence;
+
Delegate[] list = handler.GetInvocationList();
foreach (DeedObjectHandler h in list)
{
- if (h(user, group, m_scene) == false)
+ if (h(sp, sog, targetGroupID) == false)
return false;
}
}
@@ -914,7 +1068,7 @@ namespace OpenSim.Region.Framework.Scenes
Delegate[] list = handler.GetInvocationList();
foreach (BuyLandHandler h in list)
{
- if (h(user, parcel, m_scene) == false)
+ if (h(user, parcel) == false)
return false;
}
}
@@ -990,6 +1144,45 @@ namespace OpenSim.Region.Framework.Scenes
return true;
}
+ public bool CanDoObjectInvToObjectInv(TaskInventoryItem item, SceneObjectPart sourcePart, SceneObjectPart destPart)
+ {
+ DoObjectInvToObjectInv handler = OnDoObjectInvToObjectInv;
+ if (handler != null)
+ {
+ if (sourcePart == null || destPart == null || item == null)
+ return false;
+ Delegate[] list = handler.GetInvocationList();
+ foreach (DoObjectInvToObjectInv h in list)
+ {
+ if (h(item, sourcePart, destPart) == false)
+ return false;
+ }
+ }
+ return true;
+ }
+
+ public bool CanDropInObjectInv(InventoryItemBase item, IClientAPI client, SceneObjectPart destPart)
+ {
+ DoDropInObjectInv handler = OnDropInObjectInv;
+ if (handler != null)
+ {
+ if (client == null || client.SceneAgent == null|| destPart == null || item == null)
+ return false;
+
+ ScenePresence sp = client.SceneAgent as ScenePresence;
+ if(sp == null || sp.IsDeleted)
+ return false;
+
+ Delegate[] list = handler.GetInvocationList();
+ foreach (DoDropInObjectInv h in list)
+ {
+ if (h(item, sp, destPart) == false)
+ return false;
+ }
+ }
+ return true;
+ }
+
public bool CanDeleteObjectInventory(UUID itemID, UUID objectID, UUID userID)
{
DeleteObjectInventoryHandler handler = OnDeleteObjectInventory;
diff --git a/OpenSim/Region/Framework/Scenes/Scene.cs b/OpenSim/Region/Framework/Scenes/Scene.cs
index 2137b42417..c06b3dd401 100755
--- a/OpenSim/Region/Framework/Scenes/Scene.cs
+++ b/OpenSim/Region/Framework/Scenes/Scene.cs
@@ -257,37 +257,7 @@ namespace OpenSim.Region.Framework.Scenes
public bool m_useFlySlow;
public bool m_useTrashOnDelete = true;
- ///
- /// Temporarily setting to trigger appearance resends at 60 second intervals.
- ///
- public bool SendPeriodicAppearanceUpdates { get; set; }
-
- ///
- /// How much a root agent has to change position before updates are sent to viewers.
- ///
- public float RootPositionUpdateTolerance { get; set; }
-
- ///
- /// How much a root agent has to rotate before updates are sent to viewers.
- ///
- public float RootRotationUpdateTolerance { get; set; }
-
- ///
- /// How much a root agent has to change velocity before updates are sent to viewers.
- ///
- public float RootVelocityUpdateTolerance { get; set; }
-
- ///
- /// If greater than 1, we only send terse updates to other root agents on every n updates.
- ///
- public int RootTerseUpdatePeriod { get; set; }
-
- ///
- /// If greater than 1, we only send terse updates to child agents on every n updates.
- ///
- public int ChildTerseUpdatePeriod { get; set; }
-
- protected float m_defaultDrawDistance = 255f;
+ protected float m_defaultDrawDistance = 255f;
protected float m_defaultCullingDrawDistance = 16f;
public float DefaultDrawDistance
{
@@ -375,11 +345,6 @@ namespace OpenSim.Region.Framework.Scenes
protected set;
}
- ///
- /// Current maintenance run number
- ///
- public uint MaintenanceRun { get; private set; }
-
///
/// Frame time
///
@@ -391,14 +356,6 @@ namespace OpenSim.Region.Framework.Scenes
// see SimStatsReporter.cs
public bool Normalized55FPS { get; private set; }
- ///
- /// The minimum length of time in seconds that will be taken for a scene frame.
- ///
- ///
- /// Always derived from MinFrameTicks.
- ///
- public float MinMaintenanceTime { get; private set; }
-
private int m_update_physics = 1;
private int m_update_entitymovement = 1;
private int m_update_objects = 1;
@@ -407,9 +364,8 @@ namespace OpenSim.Region.Framework.Scenes
private int m_update_backup = 200;
private int m_update_terrain = 1000;
- private int m_update_land = 10;
- private int m_update_coarse_locations = 50;
+ private int m_update_coarse_locations = 5;
private int m_update_temp_cleaning = 180;
private float agentMS;
@@ -428,11 +384,6 @@ namespace OpenSim.Region.Framework.Scenes
///
private int m_lastFrameTick;
- ///
- /// Tick at which the last maintenance run occurred.
- ///
- private int m_lastMaintenanceTick;
-
///
/// Total script execution time (in Stopwatch Ticks) since the last frame
///
@@ -443,17 +394,13 @@ namespace OpenSim.Region.Framework.Scenes
/// asynchronously from the update loop.
///
private bool m_cleaningTemps = false;
+ private bool m_sendingCoarseLocations = false; // same for async course locations sending
///
/// Used to control main scene thread looping time when not updating via timer.
///
private ManualResetEvent m_updateWaitEvent = new ManualResetEvent(false);
- ///
- /// Used to control maintenance thread runs.
- ///
- private ManualResetEvent m_maintenanceWaitEvent = new ManualResetEvent(false);
-
// TODO: Possibly stop other classes being able to manipulate this directly.
private SceneGraph m_sceneGraph;
private readonly Timer m_restartTimer = new Timer(15000); // Wait before firing
@@ -497,7 +444,7 @@ namespace OpenSim.Region.Framework.Scenes
/// Is the scene active?
///
///
- /// If false, maintenance and update loops are not being run, though after setting to false update may still
+ /// If false, update loop is not being run, though after setting to false update may still
/// be active for a period (and IsRunning will still be true). Updates can still be triggered manually if
/// the scene is not active.
///
@@ -527,7 +474,6 @@ namespace OpenSim.Region.Framework.Scenes
public bool IsRunning { get { return m_isRunning; } }
private volatile bool m_isRunning;
-// private int m_lastUpdate;
private bool m_firstHeartbeat = true;
// private UpdatePrioritizationSchemes m_priorityScheme = UpdatePrioritizationSchemes.Time;
@@ -540,6 +486,9 @@ namespace OpenSim.Region.Framework.Scenes
private Timer m_mapGenerationTimer = new Timer();
private bool m_generateMaptiles;
+ protected int m_lastHealth = -1;
+ protected int m_lastUsers = -1;
+
#endregion Fields
#region Properties
@@ -805,6 +754,8 @@ namespace OpenSim.Region.Framework.Scenes
private float m_minReprioritizationDistance = 32f;
public bool ObjectsCullingByDistance = false;
+ private ExpiringCache TeleportTargetsCoolDown = new ExpiringCache();
+
public AgentCircuitManager AuthenticateHandler
{
get { return m_authenticateHandler; }
@@ -878,7 +829,6 @@ namespace OpenSim.Region.Framework.Scenes
FrameTimeWarnPercent = 60;
FrameTimeCritPercent = 40;
Normalized55FPS = true;
- MinMaintenanceTime = 1;
SeeIntoRegion = true;
Random random = new Random();
@@ -973,6 +923,7 @@ namespace OpenSim.Region.Framework.Scenes
m_maxDrawDistance = startupConfig.GetFloat("MaxDrawDistance", m_maxDrawDistance);
m_maxRegionViewDistance = startupConfig.GetFloat("MaxRegionsViewDistance", m_maxRegionViewDistance);
+ // old versions compatibility
LegacySitOffsets = startupConfig.GetBoolean("LegacySitOffsets", LegacySitOffsets);
if (m_defaultDrawDistance > m_maxDrawDistance)
@@ -1141,17 +1092,6 @@ namespace OpenSim.Region.Framework.Scenes
}
-
- // FIXME: Ultimately this should be in a module.
- SendPeriodicAppearanceUpdates = false;
-
- IConfig appearanceConfig = m_config.Configs["Appearance"];
- if (appearanceConfig != null)
- {
- SendPeriodicAppearanceUpdates
- = appearanceConfig.GetBoolean("ResendAppearanceUpdates", SendPeriodicAppearanceUpdates);
- }
-
#endregion Region Config
IConfig entityTransferConfig = m_config.Configs["EntityTransfer"];
@@ -1191,16 +1131,6 @@ namespace OpenSim.Region.Framework.Scenes
ObjectsCullingByDistance
= interestConfig.GetBoolean("ObjectsCullingByDistance", ObjectsCullingByDistance);
-
- RootTerseUpdatePeriod = interestConfig.GetInt("RootTerseUpdatePeriod", RootTerseUpdatePeriod);
- ChildTerseUpdatePeriod = interestConfig.GetInt("ChildTerseUpdatePeriod", ChildTerseUpdatePeriod);
-
- RootPositionUpdateTolerance
- = interestConfig.GetFloat("RootPositionUpdateTolerance", RootPositionUpdateTolerance);
- RootRotationUpdateTolerance
- = interestConfig.GetFloat("RootRotationUpdateTolerance", RootRotationUpdateTolerance);
- RootVelocityUpdateTolerance
- = interestConfig.GetFloat("RootVelocityUpdateTolerance", RootVelocityUpdateTolerance);
}
m_log.DebugFormat("[SCENE]: Using the {0} prioritization scheme", UpdatePrioritizationScheme);
@@ -1212,6 +1142,30 @@ namespace OpenSim.Region.Framework.Scenes
StatsReporter.OnSendStatsResult += SendSimStatsPackets;
StatsReporter.OnStatsIncorrect += m_sceneGraph.RecalculateStats;
+ IConfig restartConfig = config.Configs["RestartModule"];
+ if (restartConfig != null)
+ {
+ string markerPath = restartConfig.GetString("MarkerPath", String.Empty);
+
+ if (markerPath != String.Empty)
+ {
+ string path = Path.Combine(markerPath, RegionInfo.RegionID.ToString() + ".started");
+ try
+ {
+ string pidstring = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
+ FileStream fs = File.Create(path);
+ System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
+ Byte[] buf = enc.GetBytes(pidstring);
+ fs.Write(buf, 0, buf.Length);
+ fs.Close();
+ }
+ catch (Exception)
+ {
+ }
+ }
+ }
+
+ StartTimerWatchdog();
}
public Scene(RegionInfo regInfo)
@@ -1245,9 +1199,6 @@ namespace OpenSim.Region.Framework.Scenes
UpdatePrioritizationScheme = UpdatePrioritizationSchemes.Time;
ReprioritizationInterval = 5000;
- RootRotationUpdateTolerance = 0.1f;
- RootVelocityUpdateTolerance = 0.001f;
- RootPositionUpdateTolerance = 0.05f;
ReprioritizationDistance = m_minReprioritizationDistance;
m_eventManager = new EventManager();
@@ -1482,6 +1433,14 @@ namespace OpenSim.Region.Framework.Scenes
return;
}
+ IEtcdModule etcd = RequestModuleInterface();
+ if (etcd != null)
+ {
+ etcd.Delete("Health");
+ etcd.Delete("HealthFlags");
+ etcd.Delete("RootAgents");
+ }
+
m_log.InfoFormat("[SCENE]: Closing down the single simulator: {0}", RegionInfo.RegionName);
@@ -1520,6 +1479,8 @@ namespace OpenSim.Region.Framework.Scenes
m_log.Debug("[SCENE]: Persisting changed objects");
Backup(true);
+ m_log.Debug("[SCENE]: Closing scene");
+
m_sceneGraph.Close();
base.Close();
@@ -1628,100 +1589,12 @@ namespace OpenSim.Region.Framework.Scenes
// alarms for scenes with many objects.
Update(1);
- WorkManager.StartThread(
- Maintenance, string.Format("Maintenance ({0})", RegionInfo.RegionName), ThreadPriority.Normal, false, true);
-
Watchdog.GetCurrentThreadInfo().AlarmIfTimeout = true;
m_lastFrameTick = Util.EnvironmentTickCount();
Update(-1);
-
Watchdog.RemoveThread();
}
- private void Maintenance()
- {
- DoMaintenance(-1);
-
- Watchdog.RemoveThread();
- }
-
- public void DoMaintenance(int runs)
- {
- long? endRun = null;
- int runtc, tmpMS;
- int previousMaintenanceTick;
-
- if (runs >= 0)
- endRun = MaintenanceRun + runs;
-
- List coarseLocations;
- List avatarUUIDs;
-
- while (!m_shuttingDown && ((endRun == null && Active) || MaintenanceRun < endRun))
- {
- runtc = Util.EnvironmentTickCount();
- ++MaintenanceRun;
-
- // m_log.DebugFormat("[SCENE]: Maintenance run {0} in {1}", MaintenanceRun, Name);
-
- // Coarse locations relate to positions of green dots on the mini-map (on a SecondLife client)
- if (MaintenanceRun % (m_update_coarse_locations / 10) == 0)
- {
- SceneGraph.GetCoarseLocations(out coarseLocations, out avatarUUIDs, 60);
- // Send coarse locations to clients
- ForEachScenePresence(delegate(ScenePresence presence)
- {
- presence.SendCoarseLocations(coarseLocations, avatarUUIDs);
- });
- }
-
- if (SendPeriodicAppearanceUpdates && MaintenanceRun % 60 == 0)
- {
- // m_log.DebugFormat("[SCENE]: Sending periodic appearance updates");
-
- if (AvatarFactory != null)
- {
- ForEachRootScenePresence(sp => AvatarFactory.SendAppearance(sp.UUID));
- }
- }
-
- // Delete temp-on-rez stuff
- if (MaintenanceRun % m_update_temp_cleaning == 0 && !m_cleaningTemps)
- {
- // m_log.DebugFormat("[SCENE]: Running temp-on-rez cleaning in {0}", Name);
- tmpMS = Util.EnvironmentTickCount();
- m_cleaningTemps = true;
-
- WorkManager.RunInThread(
- delegate { CleanTempObjects(); m_cleaningTemps = false; },
- null,
- string.Format("CleanTempObjects ({0})", Name));
-
- tempOnRezMS = Util.EnvironmentTickCountSubtract(tmpMS);
- }
-
- Watchdog.UpdateThread();
-
- previousMaintenanceTick = m_lastMaintenanceTick;
- m_lastMaintenanceTick = Util.EnvironmentTickCount();
- runtc = Util.EnvironmentTickCountSubtract(m_lastMaintenanceTick, runtc);
- runtc = (int)(MinMaintenanceTime * 1000) - runtc;
-
- if (runtc > 0)
- m_maintenanceWaitEvent.WaitOne(runtc);
-
- // Optionally warn if a frame takes double the amount of time that it should.
- if (DebugUpdates
- && Util.EnvironmentTickCountSubtract(
- m_lastMaintenanceTick, previousMaintenanceTick) > (int)(MinMaintenanceTime * 1000 * 2))
- m_log.WarnFormat(
- "[SCENE]: Maintenance took {0} ms (desired max {1} ms) in {2}",
- Util.EnvironmentTickCountSubtract(m_lastMaintenanceTick, previousMaintenanceTick),
- MinMaintenanceTime * 1000,
- RegionInfo.RegionName);
- }
- }
-
public override void Update(int frames)
{
long? endFrame = null;
@@ -1778,9 +1651,28 @@ namespace OpenSim.Region.Framework.Scenes
physicsMS2 = (float)(tmpMS2 - tmpMS);
tmpMS = tmpMS2;
+/*
// Apply any pending avatar force input to the avatar's velocity
if (Frame % m_update_entitymovement == 0)
m_sceneGraph.UpdateScenePresenceMovement();
+*/
+ if (Frame % (m_update_coarse_locations) == 0 && !m_sendingCoarseLocations)
+ {
+ m_sendingCoarseLocations = true;
+ WorkManager.RunInThreadPool(
+ delegate
+ {
+ List coarseLocations;
+ List avatarUUIDs;
+ SceneGraph.GetCoarseLocations(out coarseLocations, out avatarUUIDs, 60);
+ // Send coarse locations to clients
+ ForEachScenePresence(delegate(ScenePresence presence)
+ {
+ presence.SendCoarseLocations(coarseLocations, avatarUUIDs);
+ });
+ m_sendingCoarseLocations = false;
+ }, null, string.Format("SendCoarseLocations ({0})", Name));
+ }
// Get the simulation frame time that the avatar force input
// took
@@ -1824,7 +1716,8 @@ namespace OpenSim.Region.Framework.Scenes
if (Frame % m_update_temp_cleaning == 0 && !m_cleaningTemps)
{
m_cleaningTemps = true;
- Util.FireAndForget(delegate { CleanTempObjects(); m_cleaningTemps = false; });
+ WorkManager.RunInThreadPool(
+ delegate { CleanTempObjects(); m_cleaningTemps = false; }, null, string.Format("CleanTempObjects ({0})", Name));
tmpMS2 = Util.GetTimeStampMS();
tempOnRezMS = (float)(tmpMS2 - tmpMS); // bad.. counts the FireAndForget, not CleanTempObjects
tmpMS = tmpMS2;
@@ -2050,8 +1943,7 @@ namespace OpenSim.Region.Framework.Scenes
{
if (!m_backingup)
{
- m_backingup = true;
- WorkManager.RunInThread(o => Backup(false), null, string.Format("BackupWaitCallback ({0})", Name));
+ WorkManager.RunInThreadPool(o => Backup(false), null, string.Format("BackupWorker ({0})", Name));
}
}
@@ -2079,38 +1971,58 @@ namespace OpenSim.Region.Framework.Scenes
{
lock (m_returns)
{
- EventManager.TriggerOnBackup(SimulationDataService, forced);
- m_backingup = false;
-
- foreach (KeyValuePair ret in m_returns)
+ if(m_backingup)
{
- UUID transaction = UUID.Random();
+ m_log.WarnFormat("[Scene] Backup of {0} already running. New call skipped", RegionInfo.RegionName);
+ return;
+ }
- GridInstantMessage msg = new GridInstantMessage();
- msg.fromAgentID = new Guid(UUID.Zero.ToString()); // From server
- msg.toAgentID = new Guid(ret.Key.ToString());
- msg.imSessionID = new Guid(transaction.ToString());
- msg.timestamp = (uint)Util.UnixTimeSinceEpoch();
- msg.fromAgentName = "Server";
- msg.dialog = (byte)19; // Object msg
- msg.fromGroup = false;
- msg.offline = (byte)1;
- msg.ParentEstateID = RegionInfo.EstateSettings.ParentEstateID;
- msg.Position = Vector3.Zero;
- msg.RegionID = RegionInfo.RegionID.Guid;
+ m_backingup = true;
+ try
+ {
+ EventManager.TriggerOnBackup(SimulationDataService, forced);
- // We must fill in a null-terminated 'empty' string here since bytes[0] will crash viewer 3.
- msg.binaryBucket = Util.StringToBytes256("\0");
- if (ret.Value.count > 1)
- msg.message = string.Format("Your {0} objects were returned from {1} in region {2} due to {3}", ret.Value.count, ret.Value.location.ToString(), RegionInfo.RegionName, ret.Value.reason);
- else
- msg.message = string.Format("Your object {0} was returned from {1} in region {2} due to {3}", ret.Value.objectName, ret.Value.location.ToString(), RegionInfo.RegionName, ret.Value.reason);
+ if(m_returns.Count == 0)
+ return;
IMessageTransferModule tr = RequestModuleInterface();
- if (tr != null)
+ if (tr == null)
+ return;
+
+ uint unixtime = (uint)Util.UnixTimeSinceEpoch();
+ uint estateid = RegionInfo.EstateSettings.ParentEstateID;
+ Guid regionguid = RegionInfo.RegionID.Guid;
+
+ foreach (KeyValuePair ret in m_returns)
+ {
+ GridInstantMessage msg = new GridInstantMessage();
+ msg.fromAgentID = Guid.Empty; // From server
+ msg.toAgentID = ret.Key.Guid;
+ msg.imSessionID = Guid.NewGuid();
+ msg.timestamp = unixtime;
+ msg.fromAgentName = "Server";
+ msg.dialog = 19; // Object msg
+ msg.fromGroup = false;
+ msg.offline = 1;
+ msg.ParentEstateID = estateid;
+ msg.Position = Vector3.Zero;
+ msg.RegionID = regionguid;
+
+ // We must fill in a null-terminated 'empty' string here since bytes[0] will crash viewer 3.
+ msg.binaryBucket = new Byte[1] {0};
+ if (ret.Value.count > 1)
+ msg.message = string.Format("Your {0} objects were returned from {1} in region {2} due to {3}", ret.Value.count, ret.Value.location.ToString(), RegionInfo.RegionName, ret.Value.reason);
+ else
+ msg.message = string.Format("Your object {0} was returned from {1} in region {2} due to {3}", ret.Value.objectName, ret.Value.location.ToString(), RegionInfo.RegionName, ret.Value.reason);
+
tr.SendInstantMessage(msg, delegate(bool success) { });
+ }
+ m_returns.Clear();
+ }
+ finally
+ {
+ m_backingup = false;
}
- m_returns.Clear();
}
}
@@ -2351,7 +2263,9 @@ namespace OpenSim.Region.Framework.Scenes
EventManager.TriggerOnSceneObjectLoaded(group);
SceneObjectPart rootPart = group.GetPart(group.UUID);
rootPart.Flags &= ~PrimFlags.Scripted;
+
rootPart.TrimPermissions();
+ group.InvalidateDeepEffectivePerms();
// Don't do this here - it will get done later on when sculpt data is loaded.
// group.CheckSculptAndLoad();
@@ -2603,8 +2517,8 @@ namespace OpenSim.Region.Framework.Scenes
{
// Otherwise, use this default creation code;
sceneObject = new SceneObjectGroup(ownerID, pos, rot, shape);
- AddNewSceneObject(sceneObject, true);
sceneObject.SetGroup(groupID, null);
+ AddNewSceneObject(sceneObject, true);
if (AgentPreferencesService != null) // This will override the brave new full perm world!
{
@@ -2622,6 +2536,7 @@ namespace OpenSim.Region.Framework.Scenes
if (UserManagementModule != null)
sceneObject.RootPart.CreatorIdentification = UserManagementModule.GetUserUUI(ownerID);
+ sceneObject.InvalidateDeepEffectivePerms();;
sceneObject.ScheduleGroupForFullUpdate();
return sceneObject;
@@ -2768,7 +2683,7 @@ namespace OpenSim.Region.Framework.Scenes
SceneObjectGroup sog = (SceneObjectGroup)e;
if (sog != null && !sog.IsAttachment)
{
- if (!exceptNoCopy || ((sog.GetEffectivePermissions() & (uint)PermissionMask.Copy) != 0))
+ if (!exceptNoCopy || ((sog.EffectiveOwnerPerms & (uint)PermissionMask.Copy) != 0))
{
DeleteSceneObject((SceneObjectGroup)e, false);
}
@@ -2782,7 +2697,7 @@ namespace OpenSim.Region.Framework.Scenes
}
if (toReturn.Count > 0)
{
- returnObjects(toReturn.ToArray(), UUID.Zero);
+ returnObjects(toReturn.ToArray(), null);
}
}
@@ -2944,15 +2859,15 @@ namespace OpenSim.Region.Framework.Scenes
// Return 'true' if position inside region.
public bool PositionIsInCurrentRegion(Vector3 pos)
{
- bool ret = false;
- int xx = (int)Math.Floor(pos.X);
- int yy = (int)Math.Floor(pos.Y);
- if (xx < 0 || yy < 0)
+ float t = pos.X;
+ if (t < 0 || t >= RegionInfo.RegionSizeX)
return false;
- if (xx < RegionInfo.RegionSizeX && yy < RegionInfo.RegionSizeY )
- ret = true;
- return ret;
+ t = pos.Y;
+ if (t < 0 || t >= RegionInfo.RegionSizeY)
+ return false;
+
+ return true;
}
///
@@ -3603,7 +3518,9 @@ namespace OpenSim.Region.Framework.Scenes
/// Group of new object
public void DuplicateObject(uint originalPrim, Vector3 offset, uint flags, UUID AgentID, UUID GroupID)
{
- SceneObjectGroup copy = SceneGraph.DuplicateObject(originalPrim, offset, flags, AgentID, GroupID, Quaternion.Identity);
+ bool createSelected = (flags & (uint)PrimFlags.CreateSelected) != 0;
+ SceneObjectGroup copy = SceneGraph.DuplicateObject(originalPrim, offset, AgentID,
+ GroupID, Quaternion.Identity, createSelected);
if (copy != null)
EventManager.TriggerObjectAddedToScene(copy);
}
@@ -3633,6 +3550,8 @@ namespace OpenSim.Region.Framework.Scenes
SceneObjectPart target = GetSceneObjectPart(localID);
SceneObjectPart target2 = GetSceneObjectPart(RayTargetObj);
+ bool createSelected = (dupeFlags & (uint)PrimFlags.CreateSelected) != 0;
+
if (target != null && target2 != null)
{
Vector3 direction = Vector3.Normalize(RayEnd - RayStart);
@@ -3674,13 +3593,13 @@ namespace OpenSim.Region.Framework.Scenes
Quaternion worldRot = target2.GetWorldRotation();
// SceneObjectGroup obj = m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID, worldRot);
- copy = m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID, worldRot);
+ copy = m_sceneGraph.DuplicateObject(localID, pos, AgentID, GroupID, worldRot, createSelected);
//obj.Rotation = worldRot;
//obj.UpdateGroupRotationR(worldRot);
}
else
{
- copy = m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID, Quaternion.Identity);
+ copy = m_sceneGraph.DuplicateObject(localID, pos, AgentID, GroupID, Quaternion.Identity, createSelected);
}
if (copy != null)
@@ -3983,7 +3902,7 @@ namespace OpenSim.Region.Framework.Scenes
if (!LoginsEnabled)
{
- reason = "Logins Disabled";
+ reason = "Logins to this region are disabled";
return false;
}
@@ -4906,16 +4825,34 @@ Label_GroupsDone:
public void RequestTeleportLocation(IClientAPI remoteClient, string regionName, Vector3 position,
Vector3 lookat, uint teleportFlags)
{
- GridRegion region = GridService.GetRegionByName(RegionInfo.ScopeID, regionName);
+ if (EntityTransferModule == null)
+ {
+ m_log.DebugFormat("[SCENE]: Unable to perform teleports: no AgentTransferModule is active");
+ return;
+ }
- if (region == null)
+ ScenePresence sp = GetScenePresence(remoteClient.AgentId);
+ if (sp == null || sp.IsDeleted || sp.IsInTransit)
+ return;
+
+ ulong regionHandle = 0;
+ if(regionName == RegionInfo.RegionName)
+ regionHandle = RegionInfo.RegionHandle;
+ else
+ {
+ GridRegion region = GridService.GetRegionByName(RegionInfo.ScopeID, regionName);
+ if (region != null)
+ regionHandle = region.RegionHandle;
+ }
+
+ if(regionHandle == 0)
{
// can't find the region: Tell viewer and abort
remoteClient.SendTeleportFailed("The region '" + regionName + "' could not be found.");
return;
}
- RequestTeleportLocation(remoteClient, region.RegionHandle, position, lookat, teleportFlags);
+ EntityTransferModule.Teleport(sp, regionHandle, position, lookat, teleportFlags);
}
///
@@ -4929,19 +4866,17 @@ Label_GroupsDone:
public void RequestTeleportLocation(IClientAPI remoteClient, ulong regionHandle, Vector3 position,
Vector3 lookAt, uint teleportFlags)
{
- ScenePresence sp = GetScenePresence(remoteClient.AgentId);
- if (sp != null)
+ if (EntityTransferModule == null)
{
- if (EntityTransferModule != null)
- {
- EntityTransferModule.Teleport(sp, regionHandle, position, lookAt, teleportFlags);
- }
- else
- {
- m_log.DebugFormat("[SCENE]: Unable to perform teleports: no AgentTransferModule is active");
- sp.ControllingClient.SendTeleportFailed("Unable to perform teleports on this simulator.");
- }
+ m_log.DebugFormat("[SCENE]: Unable to perform teleports: no AgentTransferModule is active");
+ return;
}
+
+ ScenePresence sp = GetScenePresence(remoteClient.AgentId);
+ if (sp == null || sp.IsDeleted || sp.IsInTransit)
+ return;
+
+ EntityTransferModule.Teleport(sp, regionHandle, position, lookAt, teleportFlags);
}
public bool CrossAgentToNewRegion(ScenePresence agent, bool isFlying)
@@ -5077,65 +5012,59 @@ Label_GroupsDone:
#endregion
#region Script Engine
+ public bool LSLScriptDanger(SceneObjectPart part, Vector3 pos)
+ {
+
+ ILandObject parcel = LandChannel.GetLandObject(pos.X, pos.Y);
+ if (parcel == null)
+ return true;
+
+ LandData ldata = parcel.LandData;
+ if (ldata == null)
+ return true;
+
+ uint landflags = ldata.Flags;
+
+ uint mask = (uint)(ParcelFlags.CreateObjects | ParcelFlags.AllowAPrimitiveEntry);
+ if((landflags & mask) != mask)
+ return true;
+
+ if((landflags & (uint)ParcelFlags.AllowOtherScripts) != 0)
+ return false;
+
+ if(part == null)
+ return true;
+ if(part.GroupID == ldata.GroupID && (landflags & (uint)ParcelFlags.AllowGroupScripts) != 0)
+ return false;
+
+ return true;
+ }
private bool ScriptDanger(SceneObjectPart part, Vector3 pos)
{
+ if (part == null)
+ return false;
+
ILandObject parcel = LandChannel.GetLandObject(pos.X, pos.Y);
- if (part != null)
+ if (parcel != null)
{
- if (parcel != null)
- {
- if ((parcel.LandData.Flags & (uint)ParcelFlags.AllowOtherScripts) != 0)
- {
- return true;
- }
- else if ((part.OwnerID == parcel.LandData.OwnerID) || Permissions.IsGod(part.OwnerID))
- {
- return true;
- }
- else if (((parcel.LandData.Flags & (uint)ParcelFlags.AllowGroupScripts) != 0)
- && (parcel.LandData.GroupID != UUID.Zero) && (parcel.LandData.GroupID == part.GroupID))
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- else
- {
+ if ((parcel.LandData.Flags & (uint)ParcelFlags.AllowOtherScripts) != 0)
+ return true;
- if (pos.X > 0f && pos.X < RegionInfo.RegionSizeX && pos.Y > 0f && pos.Y < RegionInfo.RegionSizeY)
- {
- // The only time parcel != null when an object is inside a region is when
- // there is nothing behind the landchannel. IE, no land plugin loaded.
- return true;
- }
- else
- {
- // The object is outside of this region. Stop piping events to it.
- return false;
- }
- }
+ if ((part.OwnerID == parcel.LandData.OwnerID) || Permissions.IsGod(part.OwnerID))
+ return true;
+
+ if (((parcel.LandData.Flags & (uint)ParcelFlags.AllowGroupScripts) != 0)
+ && (parcel.LandData.GroupID != UUID.Zero) && (parcel.LandData.GroupID == part.GroupID))
+ return true;
}
else
{
- return false;
+ if (pos.X > 0f && pos.X < RegionInfo.RegionSizeX && pos.Y > 0f && pos.Y < RegionInfo.RegionSizeY)
+ return true;
}
- }
- public bool ScriptDanger(uint localID, Vector3 pos)
- {
- SceneObjectPart part = GetSceneObjectPart(localID);
- if (part != null)
- {
- return ScriptDanger(part, pos);
- }
- else
- {
- return false;
- }
+ return false;
}
public bool PipeEventsForScript(uint localID)
@@ -5405,7 +5334,7 @@ Label_GroupsDone:
///
public void ForEachClient(Action action)
{
- m_clientManager.ForEachSync(action);
+ m_clientManager.ForEach(action);
}
public int GetNumberOfClients()
@@ -5512,23 +5441,24 @@ Label_GroupsDone:
return 0;
}
- if ((Util.EnvironmentTickCountSubtract(m_lastFrameTick)) < 1000)
+ if ((Util.EnvironmentTickCountSubtract(m_lastFrameTick)) < 2000)
{
health+=1;
flags |= 1;
}
- if (Util.EnvironmentTickCountSubtract(m_lastIncoming) < 1000)
+ if (Util.EnvironmentTickCountSubtract(m_lastIncoming) < 2000)
{
health+=1;
flags |= 2;
}
- if (Util.EnvironmentTickCountSubtract(m_lastOutgoing) < 1000)
+ if (Util.EnvironmentTickCountSubtract(m_lastOutgoing) < 2000)
{
health+=1;
flags |= 4;
}
+ /*
else
{
int pid = System.Diagnostics.Process.GetCurrentProcess().Id;
@@ -5541,6 +5471,7 @@ proc.WaitForExit();
Thread.Sleep(1000);
Environment.Exit(1);
}
+ */
if (flags != 7)
return health;
@@ -6305,6 +6236,32 @@ Environment.Exit(1);
public void TimerWatchdog(object sender, ElapsedEventArgs e)
{
CheckHeartbeat();
+
+ IEtcdModule etcd = RequestModuleInterface();
+ int flags;
+ string message;
+ if (etcd != null)
+ {
+ int health = GetHealth(out flags, out message);
+ if (health != m_lastHealth)
+ {
+ m_lastHealth = health;
+
+ etcd.Store("Health", health.ToString(), 300000);
+ etcd.Store("HealthFlags", flags.ToString(), 300000);
+ }
+
+ int roots = 0;
+ foreach (ScenePresence sp in GetScenePresences())
+ if (!sp.IsChildAgent && !sp.IsNPC)
+ roots++;
+
+ if (m_lastUsers != roots)
+ {
+ m_lastUsers = roots;
+ etcd.Store("RootAgents", roots.ToString(), 300000);
+ }
+ }
}
/// This method deals with movement when an avatar is automatically moving (but this is distinct from the
@@ -6461,5 +6418,21 @@ Environment.Exit(1);
m_eventManager.TriggerExtraSettingChanged(this, name, String.Empty);
}
+
+ public bool InTeleportTargetsCoolDown(UUID sourceID, UUID targetID, double timeout)
+ {
+ lock(TeleportTargetsCoolDown)
+ {
+ UUID lastSource = UUID.Zero;
+ TeleportTargetsCoolDown.TryGetValue(targetID, out lastSource);
+ if(lastSource == UUID.Zero)
+ {
+ TeleportTargetsCoolDown.Add(targetID, sourceID, timeout);
+ return false;
+ }
+ TeleportTargetsCoolDown.AddOrUpdate(targetID, sourceID, timeout);
+ return lastSource == sourceID;
+ }
+ }
}
}
diff --git a/OpenSim/Region/Framework/Scenes/SceneGraph.cs b/OpenSim/Region/Framework/Scenes/SceneGraph.cs
index 2f65ce2ae9..61a243dd20 100755
--- a/OpenSim/Region/Framework/Scenes/SceneGraph.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneGraph.cs
@@ -343,7 +343,7 @@ namespace OpenSim.Region.Framework.Scenes
sceneObject.ForceInventoryPersistence();
sceneObject.HasGroupChanged = true;
}
-
+ sceneObject.InvalidateDeepEffectivePerms();
return ret;
}
@@ -388,19 +388,19 @@ namespace OpenSim.Region.Framework.Scenes
public bool AddNewSceneObject(
SceneObjectGroup sceneObject, bool attachToBackup, Vector3? pos, Quaternion? rot, Vector3 vel)
{
- AddNewSceneObject(sceneObject, attachToBackup, false);
-
if (pos != null)
sceneObject.AbsolutePosition = (Vector3)pos;
+ if (rot != null)
+ sceneObject.UpdateGroupRotationR((Quaternion)rot);
+
+ AddNewSceneObject(sceneObject, attachToBackup, false);
+
if (sceneObject.RootPart.Shape.PCode == (byte)PCode.Prim)
{
sceneObject.ClearPartAttachmentData();
}
- if (rot != null)
- sceneObject.UpdateGroupRotationR((Quaternion)rot);
-
PhysicsActor pa = sceneObject.RootPart.PhysActor;
if (pa != null && pa.IsPhysical && vel != Vector3.Zero)
{
@@ -549,6 +549,8 @@ namespace OpenSim.Region.Framework.Scenes
// that are part of the Scene Object being removed
m_numTotalPrim -= grp.PrimCount;
+ bool isPh = (grp.RootPart.Flags & PrimFlags.Physics) == PrimFlags.Physics;
+ int nphysparts = 0;
// Go through all parts (primitives and meshes) of this Scene Object
foreach (SceneObjectPart part in grp.Parts)
{
@@ -559,10 +561,13 @@ namespace OpenSim.Region.Framework.Scenes
m_numMesh--;
else
m_numPrim--;
+
+ if(isPh && part.PhysicsShapeType != (byte)PhysShapeType.none)
+ nphysparts++;
}
- if ((grp.RootPart.Flags & PrimFlags.Physics) == PrimFlags.Physics)
- RemovePhysicalPrim(grp.PrimCount);
+ if (nphysparts > 0 )
+ RemovePhysicalPrim(nphysparts);
}
bool ret = Entities.Remove(uuid);
@@ -1358,7 +1363,7 @@ namespace OpenSim.Region.Framework.Scenes
SceneObjectGroup grp = part.ParentGroup;
if (grp != null)
{
- if (m_parentScene.Permissions.CanEditObject(grp.UUID, remoteClient.AgentId))
+ if (m_parentScene.Permissions.CanEditObject(grp, remoteClient))
{
// These two are exceptions SL makes in the interpretation
// of the change flags. Must check them here because otherwise
@@ -1379,7 +1384,7 @@ namespace OpenSim.Region.Framework.Scenes
if ((data.change & (ObjectChangeType.Position | ObjectChangeType.Rotation)) != 0)
{
// Are we allowed to move it?
- if (m_parentScene.Permissions.CanMoveObject(grp.UUID, remoteClient.AgentId))
+ if (m_parentScene.Permissions.CanMoveObject(grp, remoteClient))
{
// Strip all but move and rotation from request
data.change &= (ObjectChangeType.Group | ObjectChangeType.Position | ObjectChangeType.Rotation);
@@ -1406,7 +1411,7 @@ namespace OpenSim.Region.Framework.Scenes
if (part != null)
{
- if (m_parentScene.Permissions.CanEditObject(part.ParentGroup.UUID, remoteClient.AgentId))
+ if (m_parentScene.Permissions.CanEditObject(part.ParentGroup, remoteClient))
{
bool physbuild = false;
if (part.ParentGroup.RootPart.PhysActor != null)
@@ -1428,7 +1433,7 @@ namespace OpenSim.Region.Framework.Scenes
SceneObjectGroup group = GetGroupByPrim(localID);
if (group != null)
{
- if (m_parentScene.Permissions.CanEditObject(group.UUID, remoteClient.AgentId))
+ if (m_parentScene.Permissions.CanEditObject(group, remoteClient))
{
bool physbuild = false;
if (group.RootPart.PhysActor != null)
@@ -1474,7 +1479,7 @@ namespace OpenSim.Region.Framework.Scenes
SceneObjectGroup group = GetGroupByPrim(localID);
if (group != null)
{
- if (m_parentScene.Permissions.CanMoveObject(group.UUID, remoteClient.AgentId))
+ if (m_parentScene.Permissions.CanMoveObject(group, remoteClient))
{
group.UpdateSingleRotation(rot, localID);
}
@@ -1492,7 +1497,7 @@ namespace OpenSim.Region.Framework.Scenes
SceneObjectGroup group = GetGroupByPrim(localID);
if (group != null)
{
- if (m_parentScene.Permissions.CanMoveObject(group.UUID, remoteClient.AgentId))
+ if (m_parentScene.Permissions.CanMoveObject(group, remoteClient))
{
group.UpdateSingleRotation(rot, pos, localID);
}
@@ -1510,7 +1515,7 @@ namespace OpenSim.Region.Framework.Scenes
SceneObjectGroup group = GetGroupByPrim(localID);
if (group != null)
{
- if (m_parentScene.Permissions.CanMoveObject(group.UUID, remoteClient.AgentId))
+ if (m_parentScene.Permissions.CanMoveObject(group, remoteClient))
{
group.UpdateGroupRotationR(rot);
}
@@ -1529,7 +1534,7 @@ namespace OpenSim.Region.Framework.Scenes
SceneObjectGroup group = GetGroupByPrim(localID);
if (group != null)
{
- if (m_parentScene.Permissions.CanMoveObject(group.UUID, remoteClient.AgentId))
+ if (m_parentScene.Permissions.CanMoveObject(group, remoteClient))
{
group.UpdateGroupRotationPR(pos, rot);
}
@@ -1547,7 +1552,7 @@ namespace OpenSim.Region.Framework.Scenes
SceneObjectGroup group = GetGroupByPrim(localID);
if (group != null)
{
- if (m_parentScene.Permissions.CanMoveObject(group.UUID, remoteClient.AgentId) || group.IsAttachment)
+ if (m_parentScene.Permissions.CanMoveObject(group, remoteClient) || group.IsAttachment)
{
group.UpdateSinglePosition(pos, localID);
}
@@ -1561,17 +1566,6 @@ namespace OpenSim.Region.Framework.Scenes
///
///
public void UpdatePrimGroupPosition(uint localId, Vector3 pos, IClientAPI remoteClient)
- {
- UpdatePrimGroupPosition(localId, pos, remoteClient.AgentId);
- }
-
- ///
- /// Update the position of the given group.
- ///
- ///
- ///
- ///
- public void UpdatePrimGroupPosition(uint localId, Vector3 pos, UUID updatingAgentId)
{
SceneObjectGroup group = GetGroupByPrim(localId);
@@ -1580,7 +1574,7 @@ namespace OpenSim.Region.Framework.Scenes
if (group.IsAttachment || (group.RootPart.Shape.PCode == 9 && group.RootPart.Shape.State != 0))
{
// Set the new attachment point data in the object
- byte attachmentPoint = group.GetAttachmentPoint();
+ byte attachmentPoint = (byte)group.AttachmentPoint;
group.UpdateGroupPosition(pos);
group.IsAttachment = false;
group.AbsolutePosition = group.RootPart.AttachedPos;
@@ -1589,8 +1583,8 @@ namespace OpenSim.Region.Framework.Scenes
}
else
{
- if (m_parentScene.Permissions.CanMoveObject(group.UUID, updatingAgentId)
- && m_parentScene.Permissions.CanObjectEntry(group.UUID, false, pos))
+ if (m_parentScene.Permissions.CanMoveObject(group, remoteClient)
+ && m_parentScene.Permissions.CanObjectEntry(group, false, pos))
{
group.UpdateGroupPosition(pos);
}
@@ -1610,13 +1604,16 @@ namespace OpenSim.Region.Framework.Scenes
///
protected internal void UpdatePrimTexture(uint localID, byte[] texture, IClientAPI remoteClient)
{
- SceneObjectGroup group = GetGroupByPrim(localID);
+ SceneObjectPart part = GetSceneObjectPart(localID);
+ if(part == null)
+ return;
- if (group != null)
+ SceneObjectGroup group = part.ParentGroup;
+ if (group != null && !group.IsDeleted)
{
- if (m_parentScene.Permissions.CanEditObject(group.UUID,remoteClient.AgentId))
+ if (m_parentScene.Permissions.CanEditObject(group, remoteClient))
{
- group.UpdateTextureEntry(localID, texture);
+ part.UpdateTextureEntry(texture);
}
}
}
@@ -1638,7 +1635,7 @@ namespace OpenSim.Region.Framework.Scenes
SceneObjectGroup group = GetGroupByPrim(localID);
if (group != null)
{
- if (m_parentScene.Permissions.CanEditObject(group.UUID, remoteClient.AgentId))
+ if (m_parentScene.Permissions.CanEditObject(group, remoteClient))
{
// VolumeDetect can't be set via UI and will always be off when a change is made there
// now only change volume dtc if phantom off
@@ -1652,7 +1649,7 @@ namespace OpenSim.Region.Framework.Scenes
else // else turn it off
vdtc = false;
- group.UpdatePrimFlags(localID, UsePhysics, SetTemporary, SetPhantom, vdtc);
+ group.UpdateFlags(UsePhysics, SetTemporary, SetPhantom, vdtc);
}
else
{
@@ -1667,8 +1664,11 @@ namespace OpenSim.Region.Framework.Scenes
if (wantedPhys != group.UsesPhysics && remoteClient != null)
{
- remoteClient.SendAlertMessage("Object physics canceled because exceeds the limit of " +
- m_parentScene.m_linksetPhysCapacity + " physical prims with shape type not set to None");
+ if(m_parentScene.m_linksetPhysCapacity != 0)
+ remoteClient.SendAlertMessage("Object physics cancelled because it exceeds limits for physical prims, either size or number of primswith shape type not set to None");
+ else
+ remoteClient.SendAlertMessage("Object physics cancelled because it exceeds size limits for physical prims");
+
group.RootPart.ScheduleFullUpdate();
}
}
@@ -1685,7 +1685,7 @@ namespace OpenSim.Region.Framework.Scenes
SceneObjectGroup group = GetGroupByPrim(primLocalID);
if (group != null)
{
- if (m_parentScene.Permissions.CanEditObject(group.UUID, remoteClient.AgentId))
+ if (m_parentScene.Permissions.CanEditObject(group, remoteClient))
{
group.SetPartName(Util.CleanString(name), primLocalID);
group.HasGroupChanged = true;
@@ -1703,7 +1703,7 @@ namespace OpenSim.Region.Framework.Scenes
SceneObjectGroup group = GetGroupByPrim(primLocalID);
if (group != null)
{
- if (m_parentScene.Permissions.CanEditObject(group.UUID, remoteClient.AgentId))
+ if (m_parentScene.Permissions.CanEditObject(group, remoteClient))
{
group.SetPartDescription(Util.CleanString(description), primLocalID);
group.HasGroupChanged = true;
@@ -1725,7 +1725,7 @@ namespace OpenSim.Region.Framework.Scenes
SceneObjectGroup group = GetGroupByPrim(primLocalID);
if (group != null)
{
- if (m_parentScene.Permissions.CanEditObject(group.UUID, remoteClient.AgentId))
+ if (m_parentScene.Permissions.CanEditObject(group, remoteClient))
{
SceneObjectPart part = m_parentScene.GetSceneObjectPart(primLocalID);
if (part != null)
@@ -1742,7 +1742,7 @@ namespace OpenSim.Region.Framework.Scenes
SceneObjectGroup group = GetGroupByPrim(primLocalID);
if (group != null)
{
- if (m_parentScene.Permissions.CanEditObject(group.UUID, remoteClient.AgentId))
+ if (m_parentScene.Permissions.CanEditObject(group, remoteClient))
{
SceneObjectPart part = m_parentScene.GetSceneObjectPart(primLocalID);
if (part != null)
@@ -1996,6 +1996,7 @@ namespace OpenSim.Region.Framework.Scenes
{
newRoot.TriggerScriptChangedEvent(Changed.LINK);
newRoot.ParentGroup.HasGroupChanged = true;
+ newRoot.ParentGroup.InvalidatePartsLinkMaps();
newRoot.ParentGroup.ScheduleGroupForFullUpdate();
}
}
@@ -2012,6 +2013,7 @@ namespace OpenSim.Region.Framework.Scenes
// from the database. They will be rewritten immediately,
// minus the rows for the unlinked child prims.
m_parentScene.SimulationDataService.RemoveObject(g.UUID, m_parentScene.RegionInfo.RegionID);
+ g.InvalidatePartsLinkMaps();
g.TriggerScriptChangedEvent(Changed.LINK);
g.HasGroupChanged = true; // Persist
g.ScheduleGroupForFullUpdate();
@@ -2025,27 +2027,9 @@ namespace OpenSim.Region.Framework.Scenes
protected internal void MakeObjectSearchable(IClientAPI remoteClient, bool IncludeInSearch, uint localID)
{
- UUID user = remoteClient.AgentId;
- UUID objid = UUID.Zero;
- SceneObjectPart obj = null;
-
- EntityBase[] entityList = GetEntities();
- foreach (EntityBase ent in entityList)
- {
- if (ent is SceneObjectGroup)
- {
- SceneObjectGroup sog = ent as SceneObjectGroup;
-
- foreach (SceneObjectPart part in sog.Parts)
- {
- if (part.LocalId == localID)
- {
- objid = part.UUID;
- obj = part;
- }
- }
- }
- }
+ SceneObjectGroup sog = GetGroupByPrim(localID);
+ if(sog == null)
+ return;
//Protip: In my day, we didn't call them searchable objects, we called them limited point-to-point joints
//aka ObjectFlags.JointWheel = IncludeInSearch
@@ -2062,15 +2046,15 @@ namespace OpenSim.Region.Framework.Scenes
// libomv will complain about PrimFlags.JointWheel being
// deprecated, so we
#pragma warning disable 0612
- if (IncludeInSearch && m_parentScene.Permissions.CanEditObject(objid, user))
+ if (IncludeInSearch && m_parentScene.Permissions.CanEditObject(sog, remoteClient))
{
- obj.ParentGroup.RootPart.AddFlag(PrimFlags.JointWheel);
- obj.ParentGroup.HasGroupChanged = true;
+ sog.RootPart.AddFlag(PrimFlags.JointWheel);
+ sog.HasGroupChanged = true;
}
- else if (!IncludeInSearch && m_parentScene.Permissions.CanMoveObject(objid,user))
+ else if (!IncludeInSearch && m_parentScene.Permissions.CanMoveObject(sog, remoteClient))
{
- obj.ParentGroup.RootPart.RemFlag(PrimFlags.JointWheel);
- obj.ParentGroup.HasGroupChanged = true;
+ sog.RootPart.RemFlag(PrimFlags.JointWheel);
+ sog.HasGroupChanged = true;
}
#pragma warning restore 0612
}
@@ -2086,7 +2070,7 @@ namespace OpenSim.Region.Framework.Scenes
///
/// null if duplication fails, otherwise the duplicated object
///
- public SceneObjectGroup DuplicateObject(uint originalPrimID, Vector3 offset, uint flags, UUID AgentID, UUID GroupID, Quaternion rot)
+ public SceneObjectGroup DuplicateObject(uint originalPrimID, Vector3 offset, UUID AgentID, UUID GroupID, Quaternion rot, bool createSelected)
{
// m_log.DebugFormat(
// "[SCENE]: Duplication of object {0} at offset {1} requested by agent {2}",
@@ -2095,27 +2079,28 @@ namespace OpenSim.Region.Framework.Scenes
SceneObjectGroup original = GetGroupByPrim(originalPrimID);
if (original != null)
{
- if (m_parentScene.Permissions.CanDuplicateObject(
- original.PrimCount, original.UUID, AgentID, original.AbsolutePosition))
+ if (m_parentScene.Permissions.CanDuplicateObject(original, AgentID))
{
SceneObjectGroup copy = original.Copy(true);
copy.AbsolutePosition = copy.AbsolutePosition + offset;
+ SceneObjectPart[] parts = copy.Parts;
+
+ m_numTotalPrim += parts.Length;
+
if (original.OwnerID != AgentID)
{
- copy.SetOwnerId(AgentID);
- copy.SetRootPartOwner(copy.RootPart, AgentID, GroupID);
-
- SceneObjectPart[] partList = copy.Parts;
+ copy.SetOwner(AgentID, GroupID);
if (m_parentScene.Permissions.PropagatePermissions())
{
- foreach (SceneObjectPart child in partList)
+ foreach (SceneObjectPart child in parts)
{
child.Inventory.ChangeInventoryOwner(AgentID);
child.TriggerScriptChangedEvent(Changed.OWNER);
child.ApplyNextOwnerPermissions();
}
+ copy.InvalidateEffectivePerms();
}
}
@@ -2125,10 +2110,6 @@ namespace OpenSim.Region.Framework.Scenes
lock (SceneObjectGroupsByFullID)
SceneObjectGroupsByFullID[copy.UUID] = copy;
- SceneObjectPart[] parts = copy.Parts;
-
- m_numTotalPrim += parts.Length;
-
foreach (SceneObjectPart part in parts)
{
if (part.GetPrimType() == PrimType.SCULPT)
@@ -2144,28 +2125,19 @@ namespace OpenSim.Region.Framework.Scenes
// PROBABLE END OF FIXME
- // Since we copy from a source group that is in selected
- // state, but the copy is shown deselected in the viewer,
- // We need to clear the selection flag here, else that
- // prim never gets persisted at all. The client doesn't
- // think it's selected, so it will never send a deselect...
- copy.IsSelected = false;
-
- m_numPrim += copy.Parts.Length;
+ copy.IsSelected = createSelected;
if (rot != Quaternion.Identity)
- {
copy.UpdateGroupRotationR(rot);
- }
-
- copy.CreateScriptInstances(0, false, m_parentScene.DefaultScriptEngine, 1);
- copy.HasGroupChanged = true;
- copy.ScheduleGroupForFullUpdate();
- copy.ResumeScripts();
// required for physics to update it's position
- copy.AbsolutePosition = copy.AbsolutePosition;
+ copy.ResetChildPrimPhysicsPositions();
+ copy.CreateScriptInstances(0, false, m_parentScene.DefaultScriptEngine, 1);
+ copy.ResumeScripts();
+
+ copy.HasGroupChanged = true;
+ copy.ScheduleGroupForFullUpdate();
return copy;
}
}
diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectGroup.Inventory.cs b/OpenSim/Region/Framework/Scenes/SceneObjectGroup.Inventory.cs
index 9f98554ac0..f778367ce6 100644
--- a/OpenSim/Region/Framework/Scenes/SceneObjectGroup.Inventory.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneObjectGroup.Inventory.cs
@@ -111,7 +111,7 @@ namespace OpenSim.Region.Framework.Scenes
/// The user inventory item being added.
/// The item UUID that should be used by the new item.
///
- public bool AddInventoryItem(UUID agentID, uint localID, InventoryItemBase item, UUID copyItemID)
+ public bool AddInventoryItem(UUID agentID, uint localID, InventoryItemBase item, UUID copyItemID, bool withModRights = true)
{
// m_log.DebugFormat(
// "[PRIM INVENTORY]: Adding inventory item {0} from {1} to part with local ID {2}",
@@ -120,69 +120,72 @@ namespace OpenSim.Region.Framework.Scenes
UUID newItemId = (copyItemID != UUID.Zero) ? copyItemID : item.ID;
SceneObjectPart part = GetPart(localID);
- if (part != null)
- {
- TaskInventoryItem taskItem = new TaskInventoryItem();
-
- taskItem.ItemID = newItemId;
- taskItem.AssetID = item.AssetID;
- taskItem.Name = item.Name;
- taskItem.Description = item.Description;
- taskItem.OwnerID = part.OwnerID; // Transfer ownership
- taskItem.CreatorID = item.CreatorIdAsUuid;
- taskItem.Type = item.AssetType;
- taskItem.InvType = item.InvType;
-
- if (agentID != part.OwnerID && m_scene.Permissions.PropagatePermissions())
- {
- taskItem.BasePermissions = item.BasePermissions &
- item.NextPermissions;
- taskItem.CurrentPermissions = item.CurrentPermissions &
- item.NextPermissions;
- taskItem.EveryonePermissions = item.EveryOnePermissions &
- item.NextPermissions;
- taskItem.GroupPermissions = item.GroupPermissions &
- item.NextPermissions;
- taskItem.NextPermissions = item.NextPermissions;
- // We're adding this to a prim we don't own. Force
- // owner change
- taskItem.Flags |= (uint)InventoryItemFlags.ObjectSlamPerm;
- }
- else
- {
- taskItem.BasePermissions = item.BasePermissions;
- taskItem.CurrentPermissions = item.CurrentPermissions;
- taskItem.EveryonePermissions = item.EveryOnePermissions;
- taskItem.GroupPermissions = item.GroupPermissions;
- taskItem.NextPermissions = item.NextPermissions;
- }
-
- taskItem.Flags = item.Flags;
-
-// m_log.DebugFormat(
-// "[PRIM INVENTORY]: Flags are 0x{0:X} for item {1} added to part {2} by {3}",
-// taskItem.Flags, taskItem.Name, localID, remoteClient.Name);
-
- // TODO: These are pending addition of those fields to TaskInventoryItem
-// taskItem.SalePrice = item.SalePrice;
-// taskItem.SaleType = item.SaleType;
- taskItem.CreationDate = (uint)item.CreationDate;
-
- bool addFromAllowedDrop = agentID != part.OwnerID;
-
- part.Inventory.AddInventoryItem(taskItem, addFromAllowedDrop);
-
- return true;
- }
- else
+ if (part == null)
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Couldn't find prim local ID {0} in group {1}, {2} to add inventory item ID {3}",
localID, Name, UUID, newItemId);
+ return false;
}
- return false;
+ TaskInventoryItem taskItem = new TaskInventoryItem();
+
+ taskItem.ItemID = newItemId;
+ taskItem.AssetID = item.AssetID;
+ taskItem.Name = item.Name;
+ taskItem.Description = item.Description;
+ taskItem.OwnerID = part.OwnerID; // Transfer ownership
+ taskItem.CreatorID = item.CreatorIdAsUuid;
+ taskItem.Type = item.AssetType;
+ taskItem.InvType = item.InvType;
+
+ if (agentID != part.OwnerID && m_scene.Permissions.PropagatePermissions())
+ {
+ taskItem.BasePermissions = item.BasePermissions &
+ item.NextPermissions;
+ taskItem.CurrentPermissions = item.CurrentPermissions &
+ item.NextPermissions;
+ taskItem.EveryonePermissions = item.EveryOnePermissions &
+ item.NextPermissions;
+ taskItem.GroupPermissions = item.GroupPermissions &
+ item.NextPermissions;
+ taskItem.NextPermissions = item.NextPermissions;
+ // We're adding this to a prim we don't own. Force
+ // owner change
+ taskItem.Flags |= (uint)InventoryItemFlags.ObjectSlamPerm;
+
+ }
+ else
+ {
+ taskItem.BasePermissions = item.BasePermissions;
+ taskItem.CurrentPermissions = item.CurrentPermissions;
+ taskItem.EveryonePermissions = item.EveryOnePermissions;
+ taskItem.GroupPermissions = item.GroupPermissions;
+ taskItem.NextPermissions = item.NextPermissions;
+ }
+
+ taskItem.Flags = item.Flags;
+
+// m_log.DebugFormat(
+// "[PRIM INVENTORY]: Flags are 0x{0:X} for item {1} added to part {2} by {3}",
+// taskItem.Flags, taskItem.Name, localID, remoteClient.Name);
+
+ // TODO: These are pending addition of those fields to TaskInventoryItem
+// taskItem.SalePrice = item.SalePrice;
+// taskItem.SaleType = item.SaleType;
+ taskItem.CreationDate = (uint)item.CreationDate;
+
+ bool addFromAllowedDrop;
+ if(withModRights)
+ addFromAllowedDrop = false;
+ else
+ addFromAllowedDrop = (part.ParentGroup.RootPart.GetEffectiveObjectFlags() & (uint)PrimFlags.AllowInventoryDrop) != 0;
+
+ part.Inventory.AddInventoryItem(taskItem, addFromAllowedDrop);
+ part.ParentGroup.InvalidateEffectivePerms();
+ return true;
+
}
///
@@ -248,30 +251,201 @@ namespace OpenSim.Region.Framework.Scenes
return -1;
}
- public uint GetEffectivePermissions()
+ // new test code, to place in better place later
+ private object m_PermissionsLock = new object();
+ private bool m_EffectivePermsInvalid = true;
+ private bool m_DeepEffectivePermsInvalid = true;
+
+ // should called when parts chanced by their contents did not, so we know their cacche is valid
+ // in case of doubt call InvalidateDeepEffectivePerms(), it only costs a bit more cpu time
+ public void InvalidateEffectivePerms()
{
- return GetEffectivePermissions(false);
+ lock(m_PermissionsLock)
+ m_EffectivePermsInvalid = true;
}
- public uint GetEffectivePermissions(bool useBase)
+ // should called when parts chanced and their contents where accounted for
+ public void InvalidateDeepEffectivePerms()
+ {
+ lock(m_PermissionsLock)
+ {
+ m_DeepEffectivePermsInvalid = true;
+ m_EffectivePermsInvalid = true;
+ }
+ }
+
+ private uint m_EffectiveEveryOnePerms;
+ public uint EffectiveEveryOnePerms
+ {
+ get
+ {
+ lock(m_PermissionsLock)
+ {
+ if(m_EffectivePermsInvalid)
+ AggregatePerms();
+ return m_EffectiveEveryOnePerms;
+ }
+ }
+ }
+
+ private uint m_EffectiveGroupPerms;
+ public uint EffectiveGroupPerms
+ {
+ get
+ {
+ lock(m_PermissionsLock)
+ {
+ if(m_EffectivePermsInvalid)
+ AggregatePerms();
+ return m_EffectiveGroupPerms;
+ }
+ }
+ }
+
+ private uint m_EffectiveGroupOrEveryOnePerms;
+ public uint EffectiveGroupOrEveryOnePerms
+ {
+ get
+ {
+ lock(m_PermissionsLock)
+ {
+ if(m_EffectivePermsInvalid)
+ AggregatePerms();
+ return m_EffectiveGroupOrEveryOnePerms;
+ }
+ }
+ }
+
+ private uint m_EffectiveOwnerPerms;
+ public uint EffectiveOwnerPerms
+ {
+ get
+ {
+ lock(m_PermissionsLock)
+ {
+ if(m_EffectivePermsInvalid)
+ AggregatePerms();
+ return m_EffectiveOwnerPerms;
+ }
+ }
+ }
+
+ public void AggregatePerms()
+ {
+ lock(m_PermissionsLock)
+ {
+ // aux
+ const uint allmask = (uint)PermissionMask.AllEffective;
+ const uint movemodmask = (uint)(PermissionMask.Move | PermissionMask.Modify);
+ const uint copytransfermast = (uint)(PermissionMask.Copy | PermissionMask.Transfer);
+
+ uint basePerms = (RootPart.BaseMask & allmask) | (uint)PermissionMask.Move;
+ bool noBaseTransfer = (basePerms & (uint)PermissionMask.Transfer) == 0;
+
+ uint rootOwnerPerms = RootPart.OwnerMask;
+ uint owner = rootOwnerPerms;
+ uint rootGroupPerms = RootPart.GroupMask;
+ uint group = rootGroupPerms;
+ uint rootEveryonePerms = RootPart.EveryoneMask;
+ uint everyone = rootEveryonePerms;
+
+ bool needUpdate = false;
+ // date is time of writing april 30th 2017
+ bool newobj = (RootPart.CreationDate == 0 || RootPart.CreationDate > 1493574994);
+ SceneObjectPart[] parts = m_parts.GetArray();
+ for (int i = 0; i < parts.Length; i++)
+ {
+ SceneObjectPart part = parts[i];
+
+ if(m_DeepEffectivePermsInvalid)
+ part.AggregateInnerPerms();
+
+ owner &= part.AggregatedInnerOwnerPerms;
+ group &= part.AggregatedInnerGroupPerms;
+ if(newobj)
+ group &= part.AggregatedInnerGroupPerms;
+ if(newobj)
+ everyone &= part.AggregatedInnerEveryonePerms;
+ }
+ // recover modify and move
+ rootOwnerPerms &= movemodmask;
+ owner |= rootOwnerPerms;
+ if((owner & copytransfermast) == 0)
+ owner |= (uint)PermissionMask.Transfer;
+
+ owner &= basePerms;
+ if(owner != m_EffectiveOwnerPerms)
+ {
+ needUpdate = true;
+ m_EffectiveOwnerPerms = owner;
+ }
+
+ uint ownertransfermask = owner & (uint)PermissionMask.Transfer;
+
+ // recover modify and move
+ rootGroupPerms &= movemodmask;
+ group |= rootGroupPerms;
+ if(noBaseTransfer)
+ group &=~(uint)PermissionMask.Copy;
+ else
+ group |= ownertransfermask;
+
+ uint groupOrEveryone = group;
+ uint tmpPerms = group & owner;
+ if(tmpPerms != m_EffectiveGroupPerms)
+ {
+ needUpdate = true;
+ m_EffectiveGroupPerms = tmpPerms;
+ }
+
+ // recover move
+ rootEveryonePerms &= (uint)PermissionMask.Move;
+ everyone |= rootEveryonePerms;
+ everyone &= ~(uint)PermissionMask.Modify;
+ if(noBaseTransfer)
+ everyone &=~(uint)PermissionMask.Copy;
+ else
+ everyone |= ownertransfermask;
+
+ groupOrEveryone |= everyone;
+
+ tmpPerms = everyone & owner;
+ if(tmpPerms != m_EffectiveEveryOnePerms)
+ {
+ needUpdate = true;
+ m_EffectiveEveryOnePerms = tmpPerms;
+ }
+
+ tmpPerms = groupOrEveryone & owner;
+ if(tmpPerms != m_EffectiveGroupOrEveryOnePerms)
+ {
+ needUpdate = true;
+ m_EffectiveGroupOrEveryOnePerms = tmpPerms;
+ }
+
+ m_DeepEffectivePermsInvalid = false;
+ m_EffectivePermsInvalid = false;
+
+ if(needUpdate)
+ RootPart.ScheduleFullUpdate();
+ }
+ }
+
+ public uint CurrentAndFoldedNextPermissions()
{
uint perms=(uint)(PermissionMask.Modify |
PermissionMask.Copy |
PermissionMask.Move |
- PermissionMask.Transfer) | 7;
+ PermissionMask.Transfer |
+ PermissionMask.FoldedMask);
- uint ownerMask = 0x7fffffff;
+ uint ownerMask = RootPart.OwnerMask;
SceneObjectPart[] parts = m_parts.GetArray();
for (int i = 0; i < parts.Length; i++)
{
SceneObjectPart part = parts[i];
-
- if (useBase)
- ownerMask &= part.BaseMask;
- else
- ownerMask &= part.OwnerMask;
-
+ ownerMask &= part.BaseMask;
perms &= part.Inventory.MaskEffectivePermissions();
}
@@ -281,17 +455,8 @@ namespace OpenSim.Region.Framework.Scenes
perms &= ~(uint)PermissionMask.Copy;
if ((ownerMask & (uint)PermissionMask.Transfer) == 0)
perms &= ~(uint)PermissionMask.Transfer;
-
- // If root prim permissions are applied here, this would screw
- // with in-inventory manipulation of the next owner perms
- // in a major way. So, let's move this to the give itself.
- // Yes. I know. Evil.
-// if ((ownerMask & RootPart.NextOwnerMask & (uint)PermissionMask.Modify) == 0)
-// perms &= ~((uint)PermissionMask.Modify >> 13);
-// if ((ownerMask & RootPart.NextOwnerMask & (uint)PermissionMask.Copy) == 0)
-// perms &= ~((uint)PermissionMask.Copy >> 13);
-// if ((ownerMask & RootPart.NextOwnerMask & (uint)PermissionMask.Transfer) == 0)
-// perms &= ~((uint)PermissionMask.Transfer >> 13);
+ if ((ownerMask & (uint)PermissionMask.Export) == 0)
+ perms &= ~(uint)PermissionMask.Export;
return perms;
}
diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs b/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs
index 5928764a24..53b7ced25b 100644
--- a/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs
@@ -117,9 +117,6 @@ namespace OpenSim.Region.Framework.Scenes
NOT_STATUS_ROTATE_Z = 0xF7
}
- // This flag has the same purpose as InventoryItemFlags.ObjectSlamPerm
- public static readonly uint SLAM = 16;
-
// private PrimCountTaintedDelegate handlerPrimCountTainted = null;
///
@@ -156,7 +153,7 @@ namespace OpenSim.Region.Framework.Scenes
timeLastChanged = DateTime.UtcNow.Ticks;
if (!m_hasGroupChanged)
timeFirstChanged = DateTime.UtcNow.Ticks;
- if (m_rootPart != null && m_rootPart.UUID != null && m_scene != null)
+ if (m_rootPart != null && m_scene != null)
{
/*
if (m_rand == null)
@@ -379,6 +376,8 @@ namespace OpenSim.Region.Framework.Scenes
public bool m_dupeInProgress = false;
internal Dictionary m_savedScriptState;
+ public UUID MonitoringObject { get; set; }
+
#region Properties
///
@@ -539,7 +538,7 @@ namespace OpenSim.Region.Framework.Scenes
public bool inTransit = false;
- public delegate SceneObjectGroup SOGCrossDelegate(SceneObjectGroup sog,Vector3 pos);
+ private delegate SceneObjectGroup SOGCrossDelegate(SceneObjectGroup sog,Vector3 pos, TeleportObjectData tpData);
///
/// The absolute position of this scene object in the scene
@@ -561,7 +560,7 @@ namespace OpenSim.Region.Framework.Scenes
{
inTransit = true;
SOGCrossDelegate d = CrossAsync;
- d.BeginInvoke(this, val, CrossAsyncCompleted, d);
+ d.BeginInvoke(this, val, null, CrossAsyncCompleted, d);
}
return;
}
@@ -602,7 +601,6 @@ namespace OpenSim.Region.Framework.Scenes
av.sitSOGmoved();
}
-
// now that position is changed tell it to scripts
if (triggerScriptEvent)
{
@@ -618,64 +616,78 @@ namespace OpenSim.Region.Framework.Scenes
}
}
- public SceneObjectGroup CrossAsync(SceneObjectGroup sog, Vector3 val)
+ private SceneObjectGroup CrossAsync(SceneObjectGroup sog, Vector3 val, TeleportObjectData tpdata)
{
Scene sogScene = sog.m_scene;
+ SceneObjectPart root = sog.RootPart;
+
+ bool isTeleport = tpdata != null;
+
+ if(!isTeleport)
+ {
+ if (root.DIE_AT_EDGE)
+ {
+ try
+ {
+ sogScene.DeleteSceneObject(sog, false);
+ }
+ catch (Exception)
+ {
+ m_log.Warn("[SCENE]: exception when trying to remove the prim that crossed the border.");
+ }
+ return sog;
+ }
+
+ if (root.RETURN_AT_EDGE)
+ {
+ // We remove the object here
+ try
+ {
+ List localIDs = new List();
+ localIDs.Add(root.LocalId);
+ sogScene.AddReturn(sog.OwnerID, sog.Name, sog.AbsolutePosition,
+ "Returned at region cross");
+ sogScene.DeRezObjects(null, localIDs, UUID.Zero, DeRezAction.Return, UUID.Zero, false);
+ }
+ catch (Exception)
+ {
+ m_log.Warn("[SCENE]: exception when trying to return the prim that crossed the border.");
+ }
+ return sog;
+ }
+ }
+
+// if(!m_scene.IsRunning)
+// return sog;
+
+ if (root.KeyframeMotion != null)
+ root.KeyframeMotion.StartCrossingCheck();
+
+ if(root.PhysActor != null)
+ root.PhysActor.CrossingStart();
+
IEntityTransferModule entityTransfer = sogScene.RequestModuleInterface();
- Vector3 newpos = Vector3.Zero;
- OpenSim.Services.Interfaces.GridRegion destination = null;
-
- if (sog.RootPart.DIE_AT_EDGE)
- {
- try
- {
- sogScene.DeleteSceneObject(sog, false);
- }
- catch (Exception)
- {
- m_log.Warn("[SCENE]: exception when trying to remove the prim that crossed the border.");
- }
- return sog;
- }
-
- if (sog.RootPart.RETURN_AT_EDGE)
- {
- // We remove the object here
- try
- {
- List localIDs = new List();
- localIDs.Add(sog.RootPart.LocalId);
- sogScene.AddReturn(sog.OwnerID, sog.Name, sog.AbsolutePosition,
- "Returned at region cross");
- sogScene.DeRezObjects(null, localIDs, UUID.Zero, DeRezAction.Return, UUID.Zero);
- }
- catch (Exception)
- {
- m_log.Warn("[SCENE]: exception when trying to return the prim that crossed the border.");
- }
- return sog;
- }
-
- if (sog.m_rootPart.KeyframeMotion != null)
- sog.m_rootPart.KeyframeMotion.StartCrossingCheck();
-
if (entityTransfer == null)
return sog;
+ Vector3 newpos = Vector3.Zero;
+ OpenSim.Services.Interfaces.GridRegion destination = null;
+
destination = entityTransfer.GetObjectDestination(sog, val, out newpos);
if (destination == null)
return sog;
if (sog.m_sittingAvatars.Count == 0)
{
- entityTransfer.CrossPrimGroupIntoNewRegion(destination, newpos, sog, true, true);
+ entityTransfer.CrossPrimGroupIntoNewRegion(destination, newpos, sog, !isTeleport, true);
return sog;
}
string reason = String.Empty;
EntityTransferContext ctx = new EntityTransferContext();
+ Vector3 curPos = root.GroupPosition;
foreach (ScenePresence av in sog.m_sittingAvatars)
{
// We need to cross these agents. First, let's find
@@ -686,10 +698,15 @@ namespace OpenSim.Region.Framework.Scenes
// We set the avatar position as being the object
// position to get the region to send to
- if(!entityTransfer.checkAgentAccessToRegion(av, destination, newpos, ctx, out reason))
- {
+ if(av.IsNPC)
+ continue;
+
+ if(av.IsInTransit)
return sog;
- }
+
+ if(!entityTransfer.checkAgentAccessToRegion(av, destination, newpos, ctx, out reason))
+ return sog;
+
m_log.DebugFormat("[SCENE OBJECT]: Avatar {0} needs to be crossed to {1}", av.Name, destination.RegionName);
}
@@ -697,8 +714,10 @@ namespace OpenSim.Region.Framework.Scenes
// be made to stand up
List avsToCross = new List();
-
- foreach (ScenePresence av in sog.m_sittingAvatars)
+ List avsToCrossFar = new List();
+ ulong destHandle = destination.RegionHandle;
+ List sittingAvatars = GetSittingAvatars();
+ foreach (ScenePresence av in sittingAvatars)
{
byte cflags = 1;
@@ -712,68 +731,176 @@ namespace OpenSim.Region.Framework.Scenes
else
cflags = 3;
}
+ if(!av.knowsNeighbourRegion(destHandle))
+ cflags |= 8;
// 1 is crossing
// 2 is sitting
// 4 is sitting at sittarget
- av.crossingFlags = cflags;
+ // 8 far crossing
avinfo.av = av;
avinfo.ParentID = av.ParentID;
avsToCross.Add(avinfo);
+ if(!av.knowsNeighbourRegion(destHandle))
+ {
+ cflags |= 8;
+ avsToCrossFar.Add(av);
+ }
+
+ if(av.IsNPC)
+ av.crossingFlags = 0;
+ else
+ av.crossingFlags = cflags;
+
av.PrevSitOffset = av.OffsetPosition;
av.ParentID = 0;
}
+ Vector3 vel = root.Velocity;
+ Vector3 avel = root.AngularVelocity;
+ Vector3 acc = root.Acceleration;
+ Quaternion ori = root.RotationOffset;
+
+ if(isTeleport)
+ {
+ root.Stop();
+ sogScene.ForEachScenePresence(delegate(ScenePresence av)
+ {
+ av.ControllingClient.SendEntityUpdate(root,PrimUpdateFlags.SendInTransit);
+ av.ControllingClient.SendEntityTerseUpdateImmediate(root);
+ });
+
+ root.Velocity = tpdata.vel;
+ root.AngularVelocity = tpdata.avel;
+ root.Acceleration = tpdata.acc;
+ root.RotationOffset = tpdata.ori;
+ }
+
if (entityTransfer.CrossPrimGroupIntoNewRegion(destination, newpos, sog, true, false))
{
+ if(isTeleport)
+ {
+ sogScene.ForEachScenePresence(delegate(ScenePresence oav)
+ {
+ if(sittingAvatars.Contains(oav))
+ return;
+ if(oav.knowsNeighbourRegion(destHandle))
+ return;
+ oav.ControllingClient.SendEntityUpdate(root, PrimUpdateFlags.Kill);
+ foreach (ScenePresence sav in sittingAvatars)
+ {
+ sav.SendKillTo(oav);
+ }
+ });
+ }
+ bool crossedfar = false;
+ foreach (ScenePresence av in avsToCrossFar)
+ {
+ if(entityTransfer.CrossAgentCreateFarChild(av,destination, newpos, ctx))
+ crossedfar = true;
+ else
+ av.crossingFlags = 0;
+ }
+
+ if(crossedfar)
+ Thread.Sleep(1000);
+
foreach (avtocrossInfo avinfo in avsToCross)
{
ScenePresence av = avinfo.av;
- if (!av.IsInTransit) // just in case...
+ av.IsInLocalTransit = true;
+ av.IsInTransit = true;
+ m_log.DebugFormat("[SCENE OBJECT]: Crossing avatar {0} to {1}", av.Name, val);
+
+ if(av.crossingFlags > 0)
+ entityTransfer.CrossAgentToNewRegionAsync(av, newpos, destination, false, ctx);
+
+ if (av.IsChildAgent)
{
- m_log.DebugFormat("[SCENE OBJECT]: Crossing avatar {0} to {1}", av.Name, val);
-
- av.IsInTransit = true;
-
-// CrossAgentToNewRegionDelegate d = entityTransfer.CrossAgentToNewRegionAsync;
-// d.BeginInvoke(av, val, destination, av.Flying, version, CrossAgentToNewRegionCompleted, d);
- entityTransfer.CrossAgentToNewRegionAsync(av, newpos, destination, av.Flying, ctx);
- if (av.IsChildAgent)
+ // avatar crossed do some extra cleanup
+ if (av.ParentUUID != UUID.Zero)
{
- // avatar crossed do some extra cleanup
- if (av.ParentUUID != UUID.Zero)
- {
- av.ClearControls();
- av.ParentPart = null;
- }
+ av.ClearControls();
+ av.ParentPart = null;
}
- else
- {
- // avatar cross failed we need do dedicated standUp
- // part of it was done at CrossAgentToNewRegionAsync
- // so for now just remove the sog controls
- // this may need extra care
- av.UnRegisterSeatControls(sog.UUID);
- }
-
av.ParentUUID = UUID.Zero;
+ av.ParentPart = null;
// In any case
av.IsInTransit = false;
av.crossingFlags = 0;
m_log.DebugFormat("[SCENE OBJECT]: Crossing agent {0} {1} completed.", av.Firstname, av.Lastname);
}
else
- m_log.DebugFormat("[SCENE OBJECT]: Crossing avatar already in transit {0} to {1}", av.Name, val);
+ {
+ // avatar cross failed we need do dedicated standUp
+ // part of it was done at CrossAgentToNewRegionAsync
+ // so for now just remove the sog controls
+ // this may need extra care
+ av.UnRegisterSeatControls(sog.UUID);
+ av.ParentUUID = UUID.Zero;
+ av.ParentPart = null;
+ Vector3 oldp = curPos;
+ oldp.X = Util.Clamp(oldp.X, 0.5f, sog.m_scene.RegionInfo.RegionSizeX - 0.5f);
+ oldp.Y = Util.Clamp(oldp.Y, 0.5f, sog.m_scene.RegionInfo.RegionSizeY - 0.5f);
+ av.AbsolutePosition = oldp;
+ av.crossingFlags = 0;
+ av.sitAnimation = "SIT";
+ av.IsInTransit = false;
+ if(av.Animator!= null)
+ av.Animator.SetMovementAnimations("STAND");
+ av.AddToPhysicalScene(false);
+ sogScene.ForEachScenePresence(delegate(ScenePresence oav)
+ {
+ if(sittingAvatars.Contains(oav))
+ return;
+ if(oav.knowsNeighbourRegion(destHandle))
+ av.SendAvatarDataToAgent(oav);
+ else
+ {
+ av.SendAvatarDataToAgent(oav);
+ av.SendAppearanceToAgent(oav);
+ if (av.Animator != null)
+ av.Animator.SendAnimPackToClient(oav.ControllingClient);
+ av.SendAttachmentsToAgentNF(oav); // not ok
+ }
+ });
+ m_log.DebugFormat("[SCENE OBJECT]: Crossing agent {0} {1} failed.", av.Firstname, av.Lastname);
+ }
}
+
+ if(crossedfar)
+ {
+ Thread.Sleep(10000);
+ foreach (ScenePresence av in avsToCrossFar)
+ {
+ if(av.IsChildAgent)
+ {
+ av.Scene.CloseAgent(av.UUID, false);
+ }
+ else
+ av.RemoveNeighbourRegion(destHandle);
+ }
+ }
+ avsToCrossFar.Clear();
avsToCross.Clear();
sog.RemoveScriptInstances(true);
sog.Clear();
return sog;
}
- else // cross failed, put avas back ??
+ else
{
+ if(isTeleport)
+ {
+ if((tpdata.flags & OSTPOBJ_STOPONFAIL) == 0)
+ {
+ root.Velocity = vel;
+ root.AngularVelocity = avel;
+ root.Acceleration = acc;
+ }
+ root.RotationOffset = ori;
+ }
foreach (avtocrossInfo avinfo in avsToCross)
{
ScenePresence av = avinfo.av;
@@ -783,7 +910,6 @@ namespace OpenSim.Region.Framework.Scenes
}
}
avsToCross.Clear();
-
return sog;
}
@@ -795,11 +921,14 @@ namespace OpenSim.Region.Framework.Scenes
if (!sog.IsDeleted)
{
SceneObjectPart rootp = sog.m_rootPart;
+
Vector3 oldp = rootp.GroupPosition;
oldp.X = Util.Clamp(oldp.X, 0.5f, sog.m_scene.RegionInfo.RegionSizeX - 0.5f);
oldp.Y = Util.Clamp(oldp.Y, 0.5f, sog.m_scene.RegionInfo.RegionSizeY - 0.5f);
rootp.GroupPosition = oldp;
+ rootp.Stop();
+
SceneObjectPart[] parts = sog.m_parts.GetArray();
foreach (SceneObjectPart part in parts)
@@ -813,47 +942,150 @@ namespace OpenSim.Region.Framework.Scenes
av.sitSOGmoved();
}
- sog.Velocity = Vector3.Zero;
-
if (sog.m_rootPart.KeyframeMotion != null)
sog.m_rootPart.KeyframeMotion.CrossingFailure();
if (sog.RootPart.PhysActor != null)
- {
sog.RootPart.PhysActor.CrossingFailure();
- }
sog.inTransit = false;
+ AttachToBackup();
sog.ScheduleGroupForFullUpdate();
}
}
-/* outdated
- private void CrossAgentToNewRegionCompleted(ScenePresence agent)
+ private class TeleportObjectData
{
- //// If the cross was successful, this agent is a child agent
- if (agent.IsChildAgent)
+ public int flags;
+ public Vector3 vel;
+ public Vector3 avel;
+ public Vector3 acc;
+ public Quaternion ori;
+ public UUID sourceID;
+ }
+
+ // copy from LSL_constants.cs
+ const int OSTPOBJ_STOPATTARGET = 0x1; // stops at destination
+ const int OSTPOBJ_STOPONFAIL = 0x2; // stops at start if tp fails
+ const int OSTPOBJ_SETROT = 0x4; // the rotation is the final rotation, otherwise is a added rotation
+
+ public int TeleportObject(UUID sourceID, Vector3 targetPosition, Quaternion rotation, int flags)
+ {
+ if(inTransit || IsDeleted || IsAttachmentCheckFull() || IsSelected || Scene == null)
+ return -1;
+
+ inTransit = true;
+
+ PhysicsActor pa = RootPart.PhysActor;
+ if(pa == null || RootPart.KeyframeMotion != null /*|| m_sittingAvatars.Count == 0*/)
{
- if (agent.ParentUUID != UUID.Zero)
- {
- agent.HandleForceReleaseControls(agent.ControllingClient,agent.UUID);
- agent.ParentPart = null;
-// agent.ParentPosition = Vector3.Zero;
-// agent.ParentUUID = UUID.Zero;
- }
+ inTransit = false;
+ return -1;
}
- agent.ParentUUID = UUID.Zero;
-// agent.Reset();
-// else // Not successful
-// agent.RestoreInCurrentScene();
+ bool stop = (flags & OSTPOBJ_STOPATTARGET) != 0;
+ bool setrot = (flags & OSTPOBJ_SETROT) != 0;
- // In any case
- agent.IsInTransit = false;
+ rotation.Normalize();
+
+ Quaternion currentRot = RootPart.RotationOffset;
+ if(setrot)
+ rotation = Quaternion.Conjugate(currentRot) * rotation;
- m_log.DebugFormat("[SCENE OBJECT]: Crossing agent {0} {1} completed.", agent.Firstname, agent.Lastname);
+ bool dorot = setrot | (Math.Abs(rotation.W) < 0.99999);
+
+ Vector3 vel = Vector3.Zero;
+ Vector3 avel = Vector3.Zero;
+ Vector3 acc = Vector3.Zero;
+
+ if(!stop)
+ {
+ vel = RootPart.Velocity;
+ avel = RootPart.AngularVelocity;
+ acc = RootPart.Acceleration;
+ }
+ Quaternion ori = RootPart.RotationOffset;
+
+ if(dorot)
+ {
+ if(!stop)
+ {
+ vel *= rotation;
+ avel *= rotation;
+ acc *= rotation;
+ }
+ ori *= rotation;
+ }
+
+ if(Scene.PositionIsInCurrentRegion(targetPosition))
+ {
+ if(Scene.InTeleportTargetsCoolDown(UUID, sourceID, 1.0))
+ {
+ inTransit = false;
+ return -2;
+ }
+
+ Vector3 curPos = AbsolutePosition;
+ ILandObject curLand = Scene.LandChannel.GetLandObject(curPos.X, curPos.Y);
+ float posX = targetPosition.X;
+ float posY = targetPosition.Y;
+ ILandObject land = Scene.LandChannel.GetLandObject(posX, posY);
+ if(land != null && land != curLand)
+ {
+ if(!Scene.Permissions.CanObjectEnterWithScripts(this, land))
+ {
+ inTransit = false;
+ return -3;
+ }
+
+ UUID agentID;
+ foreach (ScenePresence av in m_sittingAvatars)
+ {
+ agentID = av.UUID;
+ if(land.IsRestrictedFromLand(agentID) || land.IsBannedFromLand(agentID))
+ {
+ inTransit = false;
+ return -4;
+ }
+ }
+ }
+
+ RootPart.Velocity = vel;
+ RootPart.AngularVelocity = avel;
+ RootPart.Acceleration = acc;
+ RootPart.RotationOffset = ori;
+
+ Vector3 s = RootPart.Scale * RootPart.RotationOffset;
+ float h = Scene.GetGroundHeight(posX, posY) + 0.5f * (float)Math.Abs(s.Z) + 0.01f;
+ if(targetPosition.Z < h)
+ targetPosition.Z = h;
+
+ inTransit = false;
+ AbsolutePosition = targetPosition;
+ RootPart.ScheduleTerseUpdate();
+ return 1;
+ }
+
+ if(Scene.InTeleportTargetsCoolDown(UUID, sourceID, 20.0))
+ {
+ inTransit = false;
+ return -1;
+ }
+
+ TeleportObjectData tdata = new TeleportObjectData();
+ tdata.flags = flags;
+ tdata.vel = vel;
+ tdata.avel = avel;
+ tdata.acc = acc;
+ tdata.ori = ori;
+ tdata.sourceID = sourceID;
+
+
+ SOGCrossDelegate d = CrossAsync;
+ d.BeginInvoke(this, targetPosition, tdata, CrossAsyncCompleted, d);
+ return 0;
}
-*/
+
public override Vector3 Velocity
{
get { return RootPart.Velocity; }
@@ -1030,6 +1262,8 @@ namespace OpenSim.Region.Framework.Scenes
set { m_LoopSoundSlavePrims = value; }
}
+ private double m_lastCollisionSoundMS;
+
///
/// The UUID for the region this object is in.
///
@@ -1107,7 +1341,7 @@ namespace OpenSim.Region.Framework.Scenes
///
public SceneObjectGroup()
{
-
+ m_lastCollisionSoundMS = Util.GetTimeStampMS() + 1000.0;
}
///
@@ -1786,63 +2020,6 @@ namespace OpenSim.Region.Framework.Scenes
}
}
- ///
- /// Attach this scene object to the given avatar.
- ///
- ///
- ///
- ///
- private void AttachToAgent(
- ScenePresence avatar, SceneObjectGroup so, uint attachmentpoint, Vector3 attachOffset, bool silent)
- {
- if (avatar != null)
- {
- // don't attach attachments to child agents
- if (avatar.IsChildAgent) return;
-
- // Remove from database and parcel prim count
- m_scene.DeleteFromStorage(so.UUID);
- m_scene.EventManager.TriggerParcelPrimCountTainted();
-
- so.AttachedAvatar = avatar.UUID;
-
- if (so.RootPart.PhysActor != null)
- {
- m_scene.PhysicsScene.RemovePrim(so.RootPart.PhysActor);
- so.RootPart.PhysActor = null;
- }
-
- so.AbsolutePosition = attachOffset;
- so.RootPart.AttachedPos = attachOffset;
- so.IsAttachment = true;
- so.RootPart.SetParentLocalId(avatar.LocalId);
- so.AttachmentPoint = attachmentpoint;
-
- avatar.AddAttachment(this);
-
- if (!silent)
- {
- // Killing it here will cause the client to deselect it
- // It then reappears on the avatar, deselected
- // through the full update below
- //
- if (IsSelected)
- {
- m_scene.SendKillObject(new List { m_rootPart.LocalId });
- }
-
- IsSelected = false; // fudge....
- ScheduleGroupForFullUpdate();
- }
- }
- else
- {
- m_log.WarnFormat(
- "[SOG]: Tried to add attachment {0} to avatar with UUID {1} in region {2} but the avatar is not present",
- UUID, avatar.ControllingClient.AgentId, Scene.RegionInfo.RegionName);
- }
- }
-
public byte GetAttachmentPoint()
{
return m_rootPart.Shape.State;
@@ -1957,6 +2134,7 @@ namespace OpenSim.Region.Framework.Scenes
if (part.LinkNum == 2)
RootPart.LinkNum = 1;
+ InvalidatePartsLinkMaps();
}
///
@@ -2233,7 +2411,8 @@ namespace OpenSim.Region.Framework.Scenes
{
if (part.OwnerID != userId)
{
- part.LastOwnerID = part.OwnerID;
+ if(part.GroupID != part.OwnerID)
+ part.LastOwnerID = part.OwnerID;
part.OwnerID = userId;
}
});
@@ -2313,7 +2492,7 @@ namespace OpenSim.Region.Framework.Scenes
RootPart.UUID);
m_scene.AddReturn(OwnerID == GroupID ? LastOwnerID : OwnerID, Name, AbsolutePosition, "parcel autoreturn");
m_scene.DeRezObjects(null, new List() { RootPart.LocalId }, UUID.Zero,
- DeRezAction.Return, UUID.Zero);
+ DeRezAction.Return, UUID.Zero, false);
return;
}
@@ -2443,17 +2622,16 @@ namespace OpenSim.Region.Framework.Scenes
dupe.CopyRootPart(m_rootPart, OwnerID, GroupID, userExposed);
dupe.m_rootPart.LinkNum = m_rootPart.LinkNum;
-
if (userExposed)
dupe.m_rootPart.TrimPermissions();
List partList = new List(m_parts.GetArray());
partList.Sort(delegate(SceneObjectPart p1, SceneObjectPart p2)
- {
- return p1.LinkNum.CompareTo(p2.LinkNum);
- }
- );
+ {
+ return p1.LinkNum.CompareTo(p2.LinkNum);
+ }
+ );
foreach (SceneObjectPart part in partList)
{
@@ -2505,12 +2683,15 @@ namespace OpenSim.Region.Framework.Scenes
if (dupe.m_rootPart.PhysActor != null)
dupe.m_rootPart.PhysActor.Building = false; // tell physics to finish building
+ dupe.InvalidateDeepEffectivePerms();
+
dupe.HasGroupChanged = true;
dupe.AttachToBackup();
- ScheduleGroupForFullUpdate();
+ dupe.ScheduleGroupForFullUpdate();
}
+ dupe.InvalidatePartsLinkMaps();
m_dupeInProgress = false;
return dupe;
}
@@ -2540,35 +2721,22 @@ namespace OpenSim.Region.Framework.Scenes
RootPart.KeyframeMotion.Stop();
RootPart.KeyframeMotion = null;
}
- UpdatePrimFlags(RootPart.LocalId, usePhysics, IsTemporary, IsPhantom, IsVolumeDetect);
+ UpdateFlags(usePhysics, IsTemporary, IsPhantom, IsVolumeDetect);
}
public void ScriptSetTemporaryStatus(bool makeTemporary)
{
- UpdatePrimFlags(RootPart.LocalId, UsesPhysics, makeTemporary, IsPhantom, IsVolumeDetect);
+ UpdateFlags(UsesPhysics, makeTemporary, IsPhantom, IsVolumeDetect);
}
public void ScriptSetPhantomStatus(bool makePhantom)
{
- UpdatePrimFlags(RootPart.LocalId, UsesPhysics, IsTemporary, makePhantom, IsVolumeDetect);
+ UpdateFlags(UsesPhysics, IsTemporary, makePhantom, IsVolumeDetect);
}
public void ScriptSetVolumeDetect(bool makeVolumeDetect)
{
- UpdatePrimFlags(RootPart.LocalId, UsesPhysics, IsTemporary, IsPhantom, makeVolumeDetect);
-
- /*
- ScriptSetPhantomStatus(false); // What ever it was before, now it's not phantom anymore
-
- if (PhysActor != null) // Should always be the case now
- {
- PhysActor.SetVolumeDetect(param);
- }
- if (param != 0)
- AddFlag(PrimFlags.Phantom);
-
- ScheduleFullUpdate();
- */
+ UpdateFlags(UsesPhysics, IsTemporary, IsPhantom, makeVolumeDetect);
}
public void applyImpulse(Vector3 impulse)
@@ -2746,25 +2914,33 @@ namespace OpenSim.Region.Framework.Scenes
}
///
- /// Set the owner of the root part.
+ /// Set the owner of all linkset.
///
- ///
///
///
- public void SetRootPartOwner(SceneObjectPart part, UUID cAgentID, UUID cGroupID)
+ public void SetOwner(UUID cAgentID, UUID cGroupID)
{
- part.LastOwnerID = part.OwnerID;
- part.OwnerID = cAgentID;
- part.GroupID = cGroupID;
+ SceneObjectPart rpart = RootPart;
+ UUID oldowner = rpart.OwnerID;
+ ForEachPart(delegate(SceneObjectPart part)
+ {
+ if(part.GroupID != part.OwnerID)
+ part.LastOwnerID = part.OwnerID;
+ part.OwnerID = cAgentID;
+ part.GroupID = cGroupID;
+ });
- if (part.OwnerID != cAgentID)
+ if (oldowner != cAgentID)
{
// Apply Next Owner Permissions if we're not bypassing permissions
if (!m_scene.Permissions.BypassPermissions())
+ {
ApplyNextOwnerPermissions();
+ InvalidateEffectivePerms();
+ }
}
- part.ScheduleFullUpdate();
+ rpart.ScheduleFullUpdate();
}
///
@@ -2845,12 +3021,13 @@ namespace OpenSim.Region.Framework.Scenes
// If we somehow got here to updating the SOG and its root part is not scheduled for update,
// check to see if the physical position or rotation warrant an update.
+/*
if (m_rootPart.UpdateFlag == UpdateRequired.NONE)
{
// rootpart SendScheduledUpdates will check if a update is needed
m_rootPart.UpdateFlag = UpdateRequired.TERSE;
}
-
+*/
if (IsAttachment)
{
ScenePresence sp = m_scene.GetScenePresence(AttachedAvatar);
@@ -3264,6 +3441,7 @@ namespace OpenSim.Region.Framework.Scenes
ResetChildPrimPhysicsPositions();
InvalidBoundsRadius();
+ InvalidatePartsLinkMaps();
if (m_rootPart.PhysActor != null)
m_rootPart.PhysActor.Building = false;
@@ -3420,6 +3598,8 @@ namespace OpenSim.Region.Framework.Scenes
objectGroup.HasGroupChangedDueToDelink = true;
InvalidBoundsRadius();
+ InvalidatePartsLinkMaps();
+ objectGroup.InvalidateEffectivePerms();
if (sendEvents)
linkPart.TriggerScriptChangedEvent(Changed.LINK);
@@ -3842,84 +4022,80 @@ namespace OpenSim.Region.Framework.Scenes
///
///
///
- public void UpdatePrimFlags(uint localID, bool UsePhysics, bool SetTemporary, bool SetPhantom, bool SetVolumeDetect)
+ public void UpdateFlags(bool UsePhysics, bool SetTemporary, bool SetPhantom, bool SetVolumeDetect)
{
+ if (m_scene == null || IsDeleted)
+ return;
+
HasGroupChanged = true;
- SceneObjectPart selectionPart = GetPart(localID);
-
- if (Scene != null)
+ if (SetTemporary)
{
- if (SetTemporary)
- {
- DetachFromBackup();
- // Remove from database and parcel prim count
- //
- m_scene.DeleteFromStorage(UUID);
- }
- else if (!Backup)
- {
- // Previously been temporary now switching back so make it
- // available for persisting again
- AttachToBackup();
- }
-
- m_scene.EventManager.TriggerParcelPrimCountTainted();
+ DetachFromBackup();
+ // Remove from database and parcel prim count
+ //
+ m_scene.DeleteFromStorage(UUID);
+ }
+ else if (!Backup)
+ {
+ // Previously been temporary now switching back so make it
+ // available for persisting again
+ AttachToBackup();
}
- if (selectionPart != null)
+
+ SceneObjectPart[] parts = m_parts.GetArray();
+
+ if (UsePhysics)
{
- SceneObjectPart[] parts = m_parts.GetArray();
+ int maxprims = m_scene.m_linksetPhysCapacity;
+ bool checkShape = (maxprims > 0 &&
+ parts.Length > maxprims);
- if (Scene != null && UsePhysics)
+ for (int i = 0; i < parts.Length; i++)
{
- int maxprims = m_scene.m_linksetPhysCapacity;
- bool checkShape = (maxprims > 0 &&
- parts.Length > maxprims);
+ SceneObjectPart part = parts[i];
- for (int i = 0; i < parts.Length; i++)
+ if(part.PhysicsShapeType == (byte)PhysicsShapeType.None)
+ continue; // assuming root type was checked elsewhere
+
+ if (checkShape)
{
- SceneObjectPart part = parts[i];
-
- if(part.PhysicsShapeType == (byte)PhysicsShapeType.None)
- continue; // assuming root type was checked elsewhere
-
- if (checkShape)
+ if (--maxprims < 0)
{
- if (--maxprims < 0)
- {
- UsePhysics = false;
- break;
- }
- }
-
- if (part.Scale.X > m_scene.m_maxPhys ||
- part.Scale.Y > m_scene.m_maxPhys ||
- part.Scale.Z > m_scene.m_maxPhys )
- {
- UsePhysics = false; // Reset physics
+ UsePhysics = false;
break;
}
}
- }
- if (parts.Length > 1)
- {
- m_rootPart.UpdatePrimFlags(UsePhysics, SetTemporary, SetPhantom, SetVolumeDetect, true);
-
- for (int i = 0; i < parts.Length; i++)
+ if (part.Scale.X > m_scene.m_maxPhys ||
+ part.Scale.Y > m_scene.m_maxPhys ||
+ part.Scale.Z > m_scene.m_maxPhys )
{
-
- if (parts[i].UUID != m_rootPart.UUID)
- parts[i].UpdatePrimFlags(UsePhysics, SetTemporary, SetPhantom, SetVolumeDetect, true);
+ UsePhysics = false; // Reset physics
+ break;
}
-
- if (m_rootPart.PhysActor != null)
- m_rootPart.PhysActor.Building = false;
}
- else
- m_rootPart.UpdatePrimFlags(UsePhysics, SetTemporary, SetPhantom, SetVolumeDetect, false);
}
+
+ if (parts.Length > 1)
+ {
+ m_rootPart.UpdatePrimFlags(UsePhysics, SetTemporary, SetPhantom, SetVolumeDetect, true);
+
+ for (int i = 0; i < parts.Length; i++)
+ {
+
+ if (parts[i].UUID != m_rootPart.UUID)
+ parts[i].UpdatePrimFlags(UsePhysics, SetTemporary, SetPhantom, SetVolumeDetect, true);
+ }
+
+ if (m_rootPart.PhysActor != null)
+ m_rootPart.PhysActor.Building = false;
+ }
+ else
+ m_rootPart.UpdatePrimFlags(UsePhysics, SetTemporary, SetPhantom, SetVolumeDetect, false);
+
+ m_scene.EventManager.TriggerParcelPrimCountTainted();
}
public void UpdateExtraParam(uint localID, ushort type, bool inUse, byte[] data)
@@ -3942,24 +4118,10 @@ namespace OpenSim.Region.Framework.Scenes
return Parts.Count();
}
- ///
- /// Update the texture entry for this part
- ///
- ///
- ///
- public void UpdateTextureEntry(uint localID, byte[] textureEntry)
- {
- SceneObjectPart part = GetPart(localID);
- if (part != null)
- {
- part.UpdateTextureEntry(textureEntry);
- }
- }
-
public void AdjustChildPrimPermissions(bool forceTaskInventoryPermissive)
{
- uint newOwnerMask = (uint)(PermissionMask.All | PermissionMask.Export) & 0xfffffff8; // Mask folded bits
- uint foldedPerms = RootPart.OwnerMask & 3;
+ uint newOwnerMask = (uint)(PermissionMask.All | PermissionMask.Export) & 0xfffffff0; // Mask folded bits
+ uint foldedPerms = RootPart.OwnerMask & (uint)PermissionMask.FoldedMask;
ForEachPart(part =>
{
@@ -3970,14 +4132,14 @@ namespace OpenSim.Region.Framework.Scenes
part.Inventory.ApplyGodPermissions(part.BaseMask);
});
- uint lockMask = ~(uint)(PermissionMask.Move | PermissionMask.Modify);
- uint lockBit = RootPart.OwnerMask & (uint)(PermissionMask.Move | PermissionMask.Modify);
+ uint lockMask = ~(uint)(PermissionMask.Move);
+ uint lockBit = RootPart.OwnerMask & (uint)(PermissionMask.Move);
RootPart.OwnerMask = (RootPart.OwnerMask & lockBit) | ((newOwnerMask | foldedPerms) & lockMask);
// m_log.DebugFormat(
// "[SCENE OBJECT GROUP]: RootPart.OwnerMask now {0} for {1} in {2}",
// (OpenMetaverse.PermissionMask)RootPart.OwnerMask, Name, Scene.Name);
-
+ InvalidateEffectivePerms();
RootPart.ScheduleFullUpdate();
}
@@ -4002,6 +4164,7 @@ namespace OpenSim.Region.Framework.Scenes
{
foreach (SceneObjectPart part in Parts)
part.Inventory.ApplyGodPermissions(RootPart.BaseMask);
+ InvalidateEffectivePerms();
}
HasGroupChanged = true;
@@ -4647,7 +4810,7 @@ namespace OpenSim.Region.Framework.Scenes
}
if ((change & ObjectChangeType.Position) != 0)
{
- if (IsAttachment || m_scene.Permissions.CanObjectEntry(group.UUID, false, data.position))
+ if (IsAttachment || m_scene.Permissions.CanObjectEntry(group, false, data.position))
UpdateGroupPosition(data.position);
updateType = updatetype.groupterse;
}
@@ -5056,6 +5219,49 @@ namespace OpenSim.Region.Framework.Scenes
return Ptot;
}
+ public void GetInertiaData(out float TotalMass, out Vector3 CenterOfMass, out Vector3 Inertia, out Vector4 aux )
+ {
+ PhysicsActor pa = RootPart.PhysActor;
+
+ if(((RootPart.Flags & PrimFlags.Physics) !=0) && pa !=null)
+ {
+ PhysicsInertiaData inertia;
+
+ inertia = pa.GetInertiaData();
+
+ TotalMass = inertia.TotalMass;
+ CenterOfMass = inertia.CenterOfMass;
+ Inertia = inertia.Inertia;
+ aux = inertia.InertiaRotation;
+
+ return;
+ }
+
+ TotalMass = GetMass();
+ CenterOfMass = GetCenterOfMass() - AbsolutePosition;
+ CenterOfMass *= Quaternion.Conjugate(RootPart.RotationOffset);
+ Inertia = Vector3.Zero;
+ aux = Vector4.Zero;
+ }
+
+ public void SetInertiaData(float TotalMass, Vector3 CenterOfMass, Vector3 Inertia, Vector4 aux )
+ {
+ PhysicsInertiaData inertia = new PhysicsInertiaData();
+ inertia.TotalMass = TotalMass;
+ inertia.CenterOfMass = CenterOfMass;
+ inertia.Inertia = Inertia;
+ inertia.InertiaRotation = aux;
+
+ if(TotalMass < 0)
+ RootPart.PhysicsInertia = null;
+ else
+ RootPart.PhysicsInertia = new PhysicsInertiaData(inertia);
+
+ PhysicsActor pa = RootPart.PhysActor;
+ if(pa !=null)
+ pa.SetInertiaData(inertia);
+ }
+
///
/// Set the user group to which this scene object belongs.
///
@@ -5217,6 +5423,7 @@ namespace OpenSim.Region.Framework.Scenes
{
part.ResetOwnerChangeFlag();
});
+ InvalidateEffectivePerms();
}
// clear some references to easy cg
@@ -5230,9 +5437,113 @@ namespace OpenSim.Region.Framework.Scenes
m_PlaySoundSlavePrims.Clear();
m_LoopSoundMasterPrim = null;
m_targets.Clear();
+ m_partsNameToLinkMap.Clear();
+ }
+
+ private Dictionary m_partsNameToLinkMap = new Dictionary();
+ private string GetLinkNumber_lastname;
+ private int GetLinkNumber_lastnumber;
+
+ // this scales bad but so does GetLinkNumPart
+ public int GetLinkNumber(string name)
+ {
+ if(String.IsNullOrEmpty(name) || name == "Object")
+ return -1;
+
+ lock(m_partsNameToLinkMap)
+ {
+ if(m_partsNameToLinkMap.Count == 0)
+ {
+ GetLinkNumber_lastname = String.Empty;
+ GetLinkNumber_lastnumber = -1;
+ SceneObjectPart[] parts = m_parts.GetArray();
+ for (int i = 0; i < parts.Length; i++)
+ {
+ string s = parts[i].Name;
+ if(String.IsNullOrEmpty(s) || s == "Object" || s == "Primitive")
+ continue;
+
+ if(m_partsNameToLinkMap.ContainsKey(s))
+ {
+ int ol = parts[i].LinkNum;
+ if(ol < m_partsNameToLinkMap[s])
+ m_partsNameToLinkMap[s] = ol;
+ }
+ else
+ m_partsNameToLinkMap[s] = parts[i].LinkNum;
+ }
+ }
+
+ if(name == GetLinkNumber_lastname)
+ return GetLinkNumber_lastnumber;
+
+ if(m_partsNameToLinkMap.ContainsKey(name))
+ {
+ lock(m_partsNameToLinkMap)
+ {
+ GetLinkNumber_lastname = name;
+ GetLinkNumber_lastnumber = m_partsNameToLinkMap[name];
+ return GetLinkNumber_lastnumber;
+ }
+ }
+ }
+
+ if(m_sittingAvatars.Count > 0)
+ {
+ int j = m_parts.Count + 1;
+
+ ScenePresence[] avs = m_sittingAvatars.ToArray();
+ for (int i = 0; i < avs.Length; i++, j++)
+ {
+ if (avs[i].Name == name)
+ {
+ GetLinkNumber_lastname = name;
+ GetLinkNumber_lastnumber = j;
+ return j;
+ }
+ }
+ }
+
+ return -1;
+ }
+
+ public void InvalidatePartsLinkMaps()
+ {
+ lock(m_partsNameToLinkMap)
+ {
+ m_partsNameToLinkMap.Clear();
+ GetLinkNumber_lastname = String.Empty;
+ GetLinkNumber_lastnumber = -1;
+ }
+ }
+
+ public bool CollisionSoundThrottled(int collisionSoundType)
+ {
+ double time = m_lastCollisionSoundMS;
+// m_lastCollisionSoundMS = Util.GetTimeStampMS();
+// time = m_lastCollisionSoundMS - time;
+ double now = Util.GetTimeStampMS();
+ time = now - time;
+ switch (collisionSoundType)
+ {
+ case 0: // default sounds
+ case 2: // default sounds with volume set by script
+ if(time < 300.0)
+ return true;
+ break;
+ case 1: // selected sound
+ if(time < 200.0)
+ return true;
+ break;
+ default:
+ break;
+ }
+ m_lastCollisionSoundMS = now;
+ return false;
}
#endregion
}
+
}
diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs b/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs
index b8ac089826..0370c41723 100644
--- a/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs
@@ -238,17 +238,6 @@ namespace OpenSim.Region.Framework.Scenes
///
public bool SoundQueueing { get; set; }
- public uint TimeStampFull;
-
- public uint TimeStampLastActivity; // Will be used for AutoReturn
-
- public uint TimeStampTerse;
-
- // The following two are to hold the attachment data
- // while an object is inworld
- [XmlIgnore]
- public byte AttachPoint = 0;
-
[XmlIgnore]
public Quaternion AttachRotation = Quaternion.Identity;
@@ -277,7 +266,11 @@ namespace OpenSim.Region.Framework.Scenes
public scriptEvents AggregateScriptEvents;
- public Vector3 AttachedPos;
+ public Vector3 AttachedPos
+ {
+ get;
+ set;
+ }
// rotation locks on local X,Y and or Z axis bit flags
// bits are as in llSetStatus defined in SceneObjectGroup.axisSelect enum
@@ -330,7 +323,8 @@ namespace OpenSim.Region.Framework.Scenes
private byte[] m_TextureAnimation;
private byte m_clickAction;
private Color m_color = Color.Black;
- private readonly List m_lastColliders = new List();
+ private List m_lastColliders = new List();
+ private bool m_lastLandCollide;
private int m_linkNum;
private int m_scriptAccessPin;
@@ -370,9 +364,9 @@ namespace OpenSim.Region.Framework.Scenes
protected Vector3 m_lastPosition;
protected Quaternion m_lastRotation;
protected Vector3 m_lastVelocity;
- protected Vector3 m_lastAcceleration;
+ protected Vector3 m_lastAcceleration; // acceleration is a derived var with high noise
protected Vector3 m_lastAngularVelocity;
- protected int m_lastUpdateSentTime;
+ protected double m_lastUpdateSentTime;
protected float m_buoyancy = 0.0f;
protected Vector3 m_force;
protected Vector3 m_torque;
@@ -407,6 +401,8 @@ namespace OpenSim.Region.Framework.Scenes
private SOPVehicle m_vehicleParams = null;
+ private PhysicsInertiaData m_physicsInertia;
+
public KeyframeMotion KeyframeMotion
{
get; set;
@@ -476,8 +472,8 @@ namespace OpenSim.Region.Framework.Scenes
APIDActive = false;
Flags = 0;
CreateSelected = true;
-
TrimPermissions();
+ AggregateInnerPerms();
}
#endregion Constructors
@@ -637,6 +633,8 @@ namespace OpenSim.Region.Framework.Scenes
set
{
m_name = value;
+ if(ParentGroup != null)
+ ParentGroup.InvalidatePartsLinkMaps();
PhysicsActor pa = PhysActor;
@@ -806,7 +804,7 @@ namespace OpenSim.Region.Framework.Scenes
{
// If this is a linkset, we don't want the physics engine mucking up our group position here.
PhysicsActor actor = PhysActor;
- if (ParentID == 0)
+ if (_parentID == 0)
{
if (actor != null)
m_groupPosition = actor.Position;
@@ -835,7 +833,7 @@ namespace OpenSim.Region.Framework.Scenes
try
{
// Root prim actually goes at Position
- if (ParentID == 0)
+ if (_parentID == 0)
{
actor.Position = value;
}
@@ -877,7 +875,7 @@ namespace OpenSim.Region.Framework.Scenes
ParentGroup.InvalidBoundsRadius();
PhysicsActor actor = PhysActor;
- if (ParentID != 0 && actor != null)
+ if (_parentID != 0 && actor != null)
{
actor.Position = GetWorldPosition();
actor.Orientation = GetWorldRotation();
@@ -937,21 +935,8 @@ namespace OpenSim.Region.Framework.Scenes
PhysicsActor actor = PhysActor;
// If this is a root of a linkset, the real rotation is what the physics engine thinks.
// If not a root prim, the offset rotation is computed by SOG and is relative to the root.
- if (ParentID == 0 && (Shape.PCode != 9 || Shape.State == 0) && actor != null)
- {
- if (actor.Orientation.X != 0f || actor.Orientation.Y != 0f
- || actor.Orientation.Z != 0f || actor.Orientation.W != 0f)
- {
- m_rotationOffset = actor.Orientation;
- }
- }
-
-// float roll, pitch, yaw = 0;
-// m_rotationOffset.GetEulerAngles(out roll, out pitch, out yaw);
-//
-// m_log.DebugFormat(
-// "[SCENE OBJECT PART]: Got euler {0} for RotationOffset on {1} {2}",
-// new Vector3(roll, pitch, yaw), Name, LocalId);
+ if (_parentID == 0 && (Shape.PCode != 9 || Shape.State == 0) && actor != null)
+ m_rotationOffset = actor.Orientation;
return m_rotationOffset;
}
@@ -967,7 +952,7 @@ namespace OpenSim.Region.Framework.Scenes
try
{
// Root prim gets value directly
- if (ParentID == 0)
+ if (_parentID == 0)
{
actor.Orientation = value;
//m_log.Info("[PART]: RO1:" + actor.Orientation.ToString());
@@ -1063,7 +1048,7 @@ namespace OpenSim.Region.Framework.Scenes
m_angularVelocity = value;
PhysicsActor actor = PhysActor;
- if ((actor != null) && actor.IsPhysical && ParentGroup.RootPart == this && VehicleType == (int)Vehicle.TYPE_NONE)
+ if ((actor != null) && actor.IsPhysical && ParentGroup.RootPart == this)
{
actor.RotationalVelocity = m_angularVelocity;
}
@@ -1089,6 +1074,12 @@ namespace OpenSim.Region.Framework.Scenes
m_acceleration = Vector3.Zero;
else
m_acceleration = value;
+
+ PhysicsActor actor = PhysActor;
+ if ((actor != null) && actor.IsPhysical && ParentGroup.RootPart == this)
+ {
+ actor.Acceleration = m_acceleration;
+ }
}
}
@@ -1107,8 +1098,8 @@ namespace OpenSim.Region.Framework.Scenes
{
get
{
- if (m_text.Length > 255)
- return m_text.Substring(0, 254);
+ if (m_text.Length > 256) // yes > 254
+ return m_text.Substring(0, 256);
return m_text;
}
set { m_text = value; }
@@ -1222,6 +1213,7 @@ namespace OpenSim.Region.Framework.Scenes
}
public UpdateRequired UpdateFlag { get; set; }
+ private object UpdateFlagLock = new object();
///
/// Used for media on a prim.
@@ -1262,6 +1254,9 @@ namespace OpenSim.Region.Framework.Scenes
{
get
{
+ if (_parentID == 0)
+ return GroupPosition;
+
return GroupPosition + (m_offsetPosition * ParentGroup.RootPart.RotationOffset);
}
}
@@ -1383,7 +1378,8 @@ namespace OpenSim.Region.Framework.Scenes
public UUID LastOwnerID
{
get { return _lastOwnerID; }
- set { _lastOwnerID = value; }
+ set {
+ _lastOwnerID = value; }
}
public UUID RezzerID
@@ -1640,8 +1636,10 @@ namespace OpenSim.Region.Framework.Scenes
PhysActor.SetMaterial((int)value);
}
if(ParentGroup != null)
+ {
ParentGroup.HasGroupChanged = true;
- ScheduleFullUpdateIfNone();
+ ScheduleFullUpdate();
+ }
}
}
}
@@ -1674,7 +1672,7 @@ namespace OpenSim.Region.Framework.Scenes
get
{
byte pst = PhysicsShapeType;
- if(pst == (byte) PhysShapeType.none || pst == (byte) PhysShapeType.convex || HasMesh())
+ if(pst == (byte) PhysShapeType.none || HasMesh())
return true;
return false;
}
@@ -1729,7 +1727,12 @@ namespace OpenSim.Region.Framework.Scenes
public byte PhysicsShapeType
{
- get { return m_physicsShapeType; }
+ get
+ {
+// if (PhysActor != null)
+// m_physicsShapeType = PhysActor.PhysicsShapeType;
+ return m_physicsShapeType;
+ }
set
{
byte oldv = m_physicsShapeType;
@@ -1780,10 +1783,12 @@ namespace OpenSim.Region.Framework.Scenes
{
m_density = value;
- ScheduleFullUpdateIfNone();
if (ParentGroup != null)
+ {
ParentGroup.HasGroupChanged = true;
+ ScheduleFullUpdate();
+ }
PhysicsActor pa = PhysActor;
if (pa != null)
@@ -1801,10 +1806,11 @@ namespace OpenSim.Region.Framework.Scenes
{
m_gravitymod = value;
- ScheduleFullUpdateIfNone();
-
if (ParentGroup != null)
+ {
ParentGroup.HasGroupChanged = true;
+ ScheduleFullUpdate();
+ }
PhysicsActor pa = PhysActor;
if (pa != null)
@@ -1822,10 +1828,11 @@ namespace OpenSim.Region.Framework.Scenes
{
m_friction = value;
- ScheduleFullUpdateIfNone();
-
if (ParentGroup != null)
+ {
ParentGroup.HasGroupChanged = true;
+ ScheduleFullUpdate();
+ }
PhysicsActor pa = PhysActor;
if (pa != null)
@@ -1843,10 +1850,11 @@ namespace OpenSim.Region.Framework.Scenes
{
m_bounce = value;
- ScheduleFullUpdateIfNone();
-
if (ParentGroup != null)
+ {
ParentGroup.HasGroupChanged = true;
+ ScheduleFullUpdate();
+ }
PhysicsActor pa = PhysActor;
if (pa != null)
@@ -1875,7 +1883,8 @@ namespace OpenSim.Region.Framework.Scenes
///
public void ClearUpdateSchedule()
{
- UpdateFlag = UpdateRequired.NONE;
+ lock(UpdateFlagLock)
+ UpdateFlag = UpdateRequired.NONE;
}
///
@@ -2013,7 +2022,7 @@ namespace OpenSim.Region.Framework.Scenes
// SetVelocity for LSL llSetVelocity.. may need revision if having other uses in future
public void SetVelocity(Vector3 pVel, bool localGlobalTF)
{
- if (ParentGroup == null || ParentGroup.IsDeleted)
+ if (ParentGroup == null || ParentGroup.IsDeleted || ParentGroup.inTransit)
return;
if (ParentGroup.IsAttachment)
@@ -2040,7 +2049,7 @@ namespace OpenSim.Region.Framework.Scenes
// SetAngularVelocity for LSL llSetAngularVelocity.. may need revision if having other uses in future
public void SetAngularVelocity(Vector3 pAngVel, bool localGlobalTF)
{
- if (ParentGroup == null || ParentGroup.IsDeleted)
+ if (ParentGroup == null || ParentGroup.IsDeleted || ParentGroup.inTransit)
return;
if (ParentGroup.IsAttachment)
@@ -2074,6 +2083,9 @@ namespace OpenSim.Region.Framework.Scenes
/// true for the local frame, false for the global frame
public void ApplyAngularImpulse(Vector3 impulsei, bool localGlobalTF)
{
+ if (ParentGroup == null || ParentGroup.IsDeleted || ParentGroup.inTransit)
+ return;
+
Vector3 impulse = impulsei;
if (localGlobalTF)
@@ -2228,7 +2240,11 @@ namespace OpenSim.Region.Framework.Scenes
dupe.LocalId = plocalID;
// This may be wrong... it might have to be applied in SceneObjectGroup to the object that's being duplicated.
- dupe.LastOwnerID = OwnerID;
+ if(OwnerID != GroupID)
+ dupe.LastOwnerID = OwnerID;
+ else
+ dupe.LastOwnerID = LastOwnerID; // redundant ?
+
dupe.RezzerID = RezzerID;
byte[] extraP = new byte[Shape.ExtraParams.Length];
@@ -2419,7 +2435,7 @@ namespace OpenSim.Region.Framework.Scenes
PhysActor.OnRequestTerseUpdate += PhysicsRequestingTerseUpdate;
PhysActor.OnOutOfBounds += PhysicsOutOfBounds;
- if (ParentID != 0 && ParentID != LocalId)
+ if (_parentID != 0 && _parentID != LocalId)
{
PhysicsActor parentPa = ParentGroup.RootPart.PhysActor;
@@ -2537,6 +2553,37 @@ namespace OpenSim.Region.Framework.Scenes
return (uint)Flags | (uint)LocalFlags;
}
+ // some of this lines need be moved to other place later
+
+ // effective permitions considering only this part inventory contents perms
+ public uint AggregatedInnerOwnerPerms {get; private set; }
+ public uint AggregatedInnerGroupPerms {get; private set; }
+ public uint AggregatedInnerEveryonePerms {get; private set; }
+ private object InnerPermsLock = new object();
+
+ public void AggregateInnerPerms()
+ {
+ // assuming child prims permissions masks are irrelevant on a linkset
+ // root part is handle at SOG since its masks are the sog masks
+ const uint mask = (uint)PermissionMask.AllEffective;
+
+ uint owner = mask;
+ uint group = mask;
+ uint everyone = mask;
+
+ lock(InnerPermsLock) // do we really need this?
+ {
+ if(Inventory != null)
+ Inventory.AggregateInnerPerms(ref owner, ref group, ref everyone);
+
+ AggregatedInnerOwnerPerms = owner & mask;
+ AggregatedInnerGroupPerms = group & mask;
+ AggregatedInnerEveryonePerms = everyone & mask;
+ if(ParentGroup != null)
+ ParentGroup.InvalidateEffectivePerms();
+ }
+ }
+
public Vector3 GetGeometricCenter()
{
// this is not real geometric center but a average of positions relative to root prim acording to
@@ -2754,12 +2801,13 @@ namespace OpenSim.Region.Framework.Scenes
{
ColliderArgs colliderArgs = new ColliderArgs();
List colliding = new List();
+ Scene parentScene = ParentGroup.Scene;
foreach (uint localId in colliders)
{
if (localId == 0)
continue;
- SceneObjectPart obj = ParentGroup.Scene.GetSceneObjectPart(localId);
+ SceneObjectPart obj = parentScene.GetSceneObjectPart(localId);
if (obj != null)
{
if (!dest.CollisionFilteredOut(obj.UUID, obj.Name))
@@ -2767,7 +2815,7 @@ namespace OpenSim.Region.Framework.Scenes
}
else
{
- ScenePresence av = ParentGroup.Scene.GetScenePresence(localId);
+ ScenePresence av = parentScene.GetScenePresence(localId);
if (av != null && (!av.IsChildAgent))
{
if (!dest.CollisionFilteredOut(av.UUID, av.Name))
@@ -2840,10 +2888,13 @@ namespace OpenSim.Region.Framework.Scenes
public void PhysicsCollision(EventArgs e)
{
- if (ParentGroup.Scene == null || ParentGroup.IsDeleted)
+ if (ParentGroup.Scene == null || ParentGroup.IsDeleted || ParentGroup.inTransit)
return;
// this a thread from physics ( heartbeat )
+ bool thisHitLand = false;
+ bool startLand = false;
+ bool endedLand = false;
CollisionEventUpdate a = (CollisionEventUpdate)e;
Dictionary collissionswith = a.m_objCollisionList;
@@ -2853,13 +2904,17 @@ namespace OpenSim.Region.Framework.Scenes
if (collissionswith.Count == 0)
{
- if (m_lastColliders.Count == 0)
+ if (m_lastColliders.Count == 0 && !m_lastLandCollide)
return; // nothing to do
+ endedLand = m_lastLandCollide;
+ m_lastLandCollide = false;
+
foreach (uint localID in m_lastColliders)
{
endedColliders.Add(localID);
}
+
m_lastColliders.Clear();
}
else
@@ -2875,19 +2930,39 @@ namespace OpenSim.Region.Framework.Scenes
foreach (uint id in collissionswith.Keys)
{
- thisHitColliders.Add(id);
- if (!m_lastColliders.Contains(id))
+ if(id == 0)
{
- startedColliders.Add(id);
-
- curcontact = collissionswith[id];
- if (Math.Abs(curcontact.RelativeSpeed) > 0.2)
+ thisHitLand = true;
+ if (!m_lastLandCollide)
{
- soundinfo = new CollisionForSoundInfo();
- soundinfo.colliderID = id;
- soundinfo.position = curcontact.Position;
- soundinfo.relativeVel = curcontact.RelativeSpeed;
- soundinfolist.Add(soundinfo);
+ startLand = true;
+ curcontact = collissionswith[id];
+ if (Math.Abs(curcontact.RelativeSpeed) > 0.2)
+ {
+ soundinfo = new CollisionForSoundInfo();
+ soundinfo.colliderID = id;
+ soundinfo.position = curcontact.Position;
+ soundinfo.relativeVel = curcontact.RelativeSpeed;
+ soundinfolist.Add(soundinfo);
+ }
+ }
+ }
+ else
+ {
+ thisHitColliders.Add(id);
+ if (!m_lastColliders.Contains(id))
+ {
+ startedColliders.Add(id);
+
+ curcontact = collissionswith[id];
+ if (Math.Abs(curcontact.RelativeSpeed) > 0.2)
+ {
+ soundinfo = new CollisionForSoundInfo();
+ soundinfo.colliderID = id;
+ soundinfo.position = curcontact.Position;
+ soundinfo.relativeVel = curcontact.RelativeSpeed;
+ soundinfolist.Add(soundinfo);
+ }
}
}
}
@@ -2896,9 +2971,18 @@ namespace OpenSim.Region.Framework.Scenes
{
foreach (uint id in collissionswith.Keys)
{
- thisHitColliders.Add(id);
- if (!m_lastColliders.Contains(id))
- startedColliders.Add(id);
+ if(id == 0)
+ {
+ thisHitLand = true;
+ if (!m_lastLandCollide)
+ startLand = true;
+ }
+ else
+ {
+ thisHitColliders.Add(id);
+ if (!m_lastColliders.Contains(id))
+ startedColliders.Add(id);
+ }
}
}
@@ -2917,22 +3001,32 @@ namespace OpenSim.Region.Framework.Scenes
foreach (uint localID in endedColliders)
m_lastColliders.Remove(localID);
+ if(m_lastLandCollide && !thisHitLand)
+ endedLand = true;
+
+ m_lastLandCollide = thisHitLand;
+
// play sounds.
if (soundinfolist.Count > 0)
CollisionSounds.PartCollisionSound(this, soundinfolist);
}
+
+ EventManager eventmanager = ParentGroup.Scene.EventManager;
- SendCollisionEvent(scriptEvents.collision_start, startedColliders, ParentGroup.Scene.EventManager.TriggerScriptCollidingStart);
+ SendCollisionEvent(scriptEvents.collision_start, startedColliders, eventmanager.TriggerScriptCollidingStart);
if (!VolumeDetectActive)
- SendCollisionEvent(scriptEvents.collision , m_lastColliders , ParentGroup.Scene.EventManager.TriggerScriptColliding);
- SendCollisionEvent(scriptEvents.collision_end , endedColliders , ParentGroup.Scene.EventManager.TriggerScriptCollidingEnd);
+ SendCollisionEvent(scriptEvents.collision , m_lastColliders , eventmanager.TriggerScriptColliding);
+ SendCollisionEvent(scriptEvents.collision_end , endedColliders , eventmanager.TriggerScriptCollidingEnd);
- if (startedColliders.Contains(0))
- SendLandCollisionEvent(scriptEvents.land_collision_start, ParentGroup.Scene.EventManager.TriggerScriptLandCollidingStart);
- if (m_lastColliders.Contains(0))
- SendLandCollisionEvent(scriptEvents.land_collision, ParentGroup.Scene.EventManager.TriggerScriptLandColliding);
- if (endedColliders.Contains(0))
- SendLandCollisionEvent(scriptEvents.land_collision_end, ParentGroup.Scene.EventManager.TriggerScriptLandCollidingEnd);
+ if (!VolumeDetectActive)
+ {
+ if (startLand)
+ SendLandCollisionEvent(scriptEvents.land_collision_start, eventmanager.TriggerScriptLandCollidingStart);
+ if (m_lastLandCollide)
+ SendLandCollisionEvent(scriptEvents.land_collision, eventmanager.TriggerScriptLandColliding);
+ if (endedLand)
+ SendLandCollisionEvent(scriptEvents.land_collision_end, eventmanager.TriggerScriptLandCollidingEnd);
+ }
}
// The Collision sounds code calls this
@@ -2951,7 +3045,7 @@ namespace OpenSim.Region.Framework.Scenes
volume = 0;
int now = Util.EnvironmentTickCount();
- if(Util.EnvironmentTickCountSubtract(now,LastColSoundSentTime) <200)
+ if(Util.EnvironmentTickCountSubtract(now, LastColSoundSentTime) < 200)
return;
LastColSoundSentTime = now;
@@ -2992,7 +3086,7 @@ namespace OpenSim.Region.Framework.Scenes
//ParentGroup.RootPart.m_groupPosition = newpos;
}
/*
- if (pa != null && ParentID != 0 && ParentGroup != null)
+ if (pa != null && _parentID != 0 && ParentGroup != null)
{
// Special case where a child object is requesting property updates.
// This happens when linksets are modified to use flexible links rather than
@@ -3153,17 +3247,6 @@ namespace OpenSim.Region.Framework.Scenes
APIDActive = false;
}
- public void ScheduleFullUpdateIfNone()
- {
- if (ParentGroup == null)
- return;
-
-// ??? ParentGroup.HasGroupChanged = true;
-
- if (UpdateFlag != UpdateRequired.FULL)
- ScheduleFullUpdate();
- }
-
///
/// Schedules this prim for a full update
///
@@ -3174,35 +3257,26 @@ namespace OpenSim.Region.Framework.Scenes
if (ParentGroup == null)
return;
- ParentGroup.QueueForUpdateCheck();
-
- int timeNow = Util.UnixTimeSinceEpoch();
-
- // If multiple updates are scheduled on the same second, we still need to perform all of them
- // So we'll force the issue by bumping up the timestamp so that later processing sees these need
- // to be performed.
- if (timeNow <= TimeStampFull)
+ lock(UpdateFlagLock)
{
- TimeStampFull += 1;
+ ParentGroup.QueueForUpdateCheck(); // just in case
+ if(UpdateFlag != UpdateRequired.FULL)
+ {
+ UpdateFlag = UpdateRequired.FULL;
+
+ // m_log.DebugFormat(
+ // "[SCENE OBJECT PART]: Scheduling full update for {0}, {1} at {2}",
+ // UUID, Name, TimeStampFull);
+
+ if (ParentGroup.Scene != null)
+ ParentGroup.Scene.EventManager.TriggerSceneObjectPartUpdated(this, true);
+ }
}
- else
- {
- TimeStampFull = (uint)timeNow;
- }
-
- UpdateFlag = UpdateRequired.FULL;
-
- // m_log.DebugFormat(
- // "[SCENE OBJECT PART]: Scheduling full update for {0}, {1} at {2}",
- // UUID, Name, TimeStampFull);
-
- if (ParentGroup.Scene != null)
- ParentGroup.Scene.EventManager.TriggerSceneObjectPartUpdated(this, true);
}
///
/// Schedule a terse update for this prim. Terse updates only send position,
- /// rotation, velocity and rotational velocity information.
+ /// rotation, velocity and rotational velocity information. WRONG!!!!
///
public void ScheduleTerseUpdate()
{
@@ -3218,21 +3292,23 @@ namespace OpenSim.Region.Framework.Scenes
return;
}
- if (UpdateFlag == UpdateRequired.NONE)
+ lock(UpdateFlagLock)
{
- ParentGroup.HasGroupChanged = true;
- ParentGroup.QueueForUpdateCheck();
+ if (UpdateFlag == UpdateRequired.NONE)
+ {
+ ParentGroup.HasGroupChanged = true;
+ ParentGroup.QueueForUpdateCheck();
- TimeStampTerse = (uint) Util.UnixTimeSinceEpoch();
- UpdateFlag = UpdateRequired.TERSE;
+ UpdateFlag = UpdateRequired.TERSE;
- // m_log.DebugFormat(
- // "[SCENE OBJECT PART]: Scheduling terse update for {0}, {1} at {2}",
- // UUID, Name, TimeStampTerse);
+ // m_log.DebugFormat(
+ // "[SCENE OBJECT PART]: Scheduling terse update for {0}, {1} at {2}",
+ // UUID, Name, TimeStampTerse);
+ }
+
+ if (ParentGroup.Scene != null)
+ ParentGroup.Scene.EventManager.TriggerSceneObjectPartUpdated(this, false);
}
-
- if (ParentGroup.Scene != null)
- ParentGroup.Scene.EventManager.TriggerSceneObjectPartUpdated(this, false);
}
public void ScriptSetPhysicsStatus(bool UsePhysics)
@@ -3261,21 +3337,6 @@ namespace OpenSim.Region.Framework.Scenes
sp.SendAttachmentUpdate(this, UpdateRequired.FULL);
}
}
-
-/* this does nothing
-SendFullUpdateToClient(remoteClient, Position) ignores position parameter
- if (IsRoot)
- {
- if (ParentGroup.IsAttachment)
- {
- SendFullUpdateToClient(remoteClient, AttachedPos);
- }
- else
- {
- SendFullUpdateToClient(remoteClient, AbsolutePosition);
- }
- }
-*/
else
{
SendFullUpdateToClient(remoteClient);
@@ -3291,12 +3352,15 @@ SendFullUpdateToClient(remoteClient, Position) ignores position parameter
return;
// Update the "last" values
- m_lastPosition = OffsetPosition;
- m_lastRotation = RotationOffset;
- m_lastVelocity = Velocity;
- m_lastAcceleration = Acceleration;
- m_lastAngularVelocity = AngularVelocity;
- m_lastUpdateSentTime = Environment.TickCount;
+ lock(UpdateFlagLock)
+ {
+ m_lastPosition = AbsolutePosition;
+ m_lastRotation = RotationOffset;
+ m_lastVelocity = Velocity;
+ m_lastAcceleration = Acceleration;
+ m_lastAngularVelocity = AngularVelocity;
+ m_lastUpdateSentTime = Util.GetTimeStampMS();
+ }
ParentGroup.Scene.ForEachScenePresence(delegate(ScenePresence avatar)
{
@@ -3310,12 +3374,15 @@ SendFullUpdateToClient(remoteClient, Position) ignores position parameter
return;
// Update the "last" values
- m_lastPosition = OffsetPosition;
- m_lastRotation = RotationOffset;
- m_lastVelocity = Velocity;
- m_lastAcceleration = Acceleration;
- m_lastAngularVelocity = AngularVelocity;
- m_lastUpdateSentTime = Environment.TickCount;
+ lock(UpdateFlagLock)
+ {
+ m_lastPosition = AbsolutePosition;
+ m_lastRotation = RotationOffset;
+ m_lastVelocity = Velocity;
+ m_lastAcceleration = Acceleration;
+ m_lastAngularVelocity = AngularVelocity;
+ m_lastUpdateSentTime = Util.GetTimeStampMS();
+ }
if (ParentGroup.IsAttachment)
{
@@ -3340,25 +3407,7 @@ SendFullUpdateToClient(remoteClient, Position) ignores position parameter
///
public void SendFullUpdateToClient(IClientAPI remoteClient)
{
- SendFullUpdateToClient(remoteClient, OffsetPosition);
- }
-
- ///
- /// Sends a full update to the client
- ///
- ///
- ///
- public void SendFullUpdateToClient(IClientAPI remoteClient, Vector3 lPos)
- {
- if (ParentGroup == null)
- return;
-
- // Suppress full updates during attachment editing
- // sl Does send them
- // if (ParentGroup.IsSelected && ParentGroup.IsAttachment)
- // return;
-
- if (ParentGroup.IsDeleted)
+ if (ParentGroup == null || ParentGroup.IsDeleted)
return;
if (ParentGroup.IsAttachment
@@ -3379,40 +3428,138 @@ SendFullUpdateToClient(remoteClient, Position) ignores position parameter
ParentGroup.Scene.StatsReporter.AddObjectUpdates(1);
}
+
+ private const float ROTATION_TOLERANCE = 0.01f;
+ private const float VELOCITY_TOLERANCE = 0.1f; // terse update vel has low resolution
+ private const float POSITION_TOLERANCE = 0.05f; // I don't like this, but I suppose it's necessary
+ private const double TIME_MS_TOLERANCE = 200f; //llSetPos has a 200ms delay. This should NOT be 3 seconds.
+
///
/// Tell all the prims which have had updates scheduled
///
public void SendScheduledUpdates()
- {
- const float ROTATION_TOLERANCE = 0.01f;
- const float VELOCITY_TOLERANCE = 0.001f;
- const float POSITION_TOLERANCE = 0.05f; // I don't like this, but I suppose it's necessary
- const int TIME_MS_TOLERANCE = 200; //llSetPos has a 200ms delay. This should NOT be 3 seconds.
-
- switch (UpdateFlag)
+ {
+ UpdateRequired currentUpdate;
+ lock(UpdateFlagLock)
{
+ currentUpdate = UpdateFlag;
+ ClearUpdateSchedule();
+ }
+
+ switch (currentUpdate)
+ {
+ case UpdateRequired.NONE:
+ break;
+
case UpdateRequired.TERSE:
- {
- ClearUpdateSchedule();
- // Throw away duplicate or insignificant updates
- if (!RotationOffset.ApproxEquals(m_lastRotation, ROTATION_TOLERANCE) ||
- !Acceleration.Equals(m_lastAcceleration) ||
- !Velocity.ApproxEquals(m_lastVelocity, VELOCITY_TOLERANCE) ||
- Velocity.ApproxEquals(Vector3.Zero, VELOCITY_TOLERANCE) ||
- !AngularVelocity.ApproxEquals(m_lastAngularVelocity, VELOCITY_TOLERANCE) ||
- !OffsetPosition.ApproxEquals(m_lastPosition, POSITION_TOLERANCE) ||
- Environment.TickCount - m_lastUpdateSentTime > TIME_MS_TOLERANCE)
+ bool needupdate = true;
+ lock(UpdateFlagLock)
{
- SendTerseUpdateToAllClientsInternal();
+ double now = Util.GetTimeStampMS();
+ Vector3 curvel = Velocity;
+ Vector3 curacc = Acceleration;
+ Vector3 angvel = AngularVelocity;
+
+ while(true) // just to avoid ugly goto
+ {
+ double elapsed = now - m_lastUpdateSentTime;
+ if (elapsed > TIME_MS_TOLERANCE)
+ break;
+
+ if( Math.Abs(curacc.X - m_lastAcceleration.X) > VELOCITY_TOLERANCE ||
+ Math.Abs(curacc.Y - m_lastAcceleration.Y) > VELOCITY_TOLERANCE ||
+ Math.Abs(curacc.Z - m_lastAcceleration.Z) > VELOCITY_TOLERANCE)
+ break;
+
+ // velocity change is also direction not only norm)
+ if( Math.Abs(curvel.X - m_lastVelocity.X) > VELOCITY_TOLERANCE ||
+ Math.Abs(curvel.Y - m_lastVelocity.Y) > VELOCITY_TOLERANCE ||
+ Math.Abs(curvel.Z - m_lastVelocity.Z) > VELOCITY_TOLERANCE)
+ break;
+
+ float vx = Math.Abs(curvel.X);
+ if(vx > 128.0)
+ break;
+ float vy = Math.Abs(curvel.Y);
+ if(vy > 128.0)
+ break;
+ float vz = Math.Abs(curvel.Z);
+ if(vz > 128.0)
+ break;
+
+ if (
+ vx < VELOCITY_TOLERANCE &&
+ vy < VELOCITY_TOLERANCE &&
+ vz < VELOCITY_TOLERANCE
+ )
+ {
+ if(!AbsolutePosition.ApproxEquals(m_lastPosition, POSITION_TOLERANCE))
+ break;
+
+ if (vx < 1e-4 &&
+ vy < 1e-4 &&
+ vz < 1e-4 &&
+ (
+ Math.Abs(m_lastVelocity.X) > 1e-4 ||
+ Math.Abs(m_lastVelocity.Y) > 1e-4 ||
+ Math.Abs(m_lastVelocity.Z) > 1e-4
+ ))
+ break;
+ }
+
+ if( Math.Abs(angvel.X - m_lastAngularVelocity.X) > VELOCITY_TOLERANCE ||
+ Math.Abs(angvel.Y - m_lastAngularVelocity.Y) > VELOCITY_TOLERANCE ||
+ Math.Abs(angvel.Z - m_lastAngularVelocity.Z) > VELOCITY_TOLERANCE)
+ break;
+
+ // viewer interpolators have a limit of 128m/s
+ float ax = Math.Abs(angvel.X);
+ if(ax > 64.0)
+ break;
+ float ay = Math.Abs(angvel.Y);
+ if(ay > 64.0)
+ break;
+ float az = Math.Abs(angvel.Z);
+ if(az > 64.0)
+ break;
+
+ if (
+ ax < VELOCITY_TOLERANCE &&
+ ay < VELOCITY_TOLERANCE &&
+ az < VELOCITY_TOLERANCE &&
+ !RotationOffset.ApproxEquals(m_lastRotation, ROTATION_TOLERANCE)
+ )
+ break;
+
+ needupdate = false;
+ break;
+ }
+
+ if(needupdate)
+ {
+
+ // Update the "last" values
+ m_lastPosition = AbsolutePosition;
+ m_lastRotation = RotationOffset;
+ m_lastVelocity = curvel;
+ m_lastAcceleration = curacc;
+ m_lastAngularVelocity = angvel;
+ m_lastUpdateSentTime = now;
+ }
+ }
+
+ if(needupdate)
+ {
+ ParentGroup.Scene.ForEachClient(delegate(IClientAPI client)
+ {
+ SendTerseUpdateToClient(client);
+ });
}
break;
- }
+
case UpdateRequired.FULL:
- {
- ClearUpdateSchedule();
SendFullUpdateToAllClientsInternal();
break;
- }
}
}
@@ -3425,13 +3572,19 @@ SendFullUpdateToClient(remoteClient, Position) ignores position parameter
if (ParentGroup == null || ParentGroup.Scene == null)
return;
- // Update the "last" values
- m_lastPosition = OffsetPosition;
- m_lastRotation = RotationOffset;
- m_lastVelocity = Velocity;
- m_lastAcceleration = Acceleration;
- m_lastAngularVelocity = AngularVelocity;
- m_lastUpdateSentTime = Environment.TickCount;
+ lock(UpdateFlagLock)
+ {
+ if(UpdateFlag != UpdateRequired.NONE)
+ return;
+
+ // Update the "last" values
+ m_lastPosition = AbsolutePosition;
+ m_lastRotation = RotationOffset;
+ m_lastVelocity = Velocity;
+ m_lastAcceleration = Acceleration;
+ m_lastAngularVelocity = AngularVelocity;
+ m_lastUpdateSentTime = Util.GetTimeStampMS();
+ }
ParentGroup.Scene.ForEachClient(delegate(IClientAPI client)
{
@@ -3444,13 +3597,19 @@ SendFullUpdateToClient(remoteClient, Position) ignores position parameter
if (ParentGroup == null || ParentGroup.Scene == null)
return;
- // Update the "last" values
- m_lastPosition = OffsetPosition;
- m_lastRotation = RotationOffset;
- m_lastVelocity = Velocity;
- m_lastAcceleration = Acceleration;
- m_lastAngularVelocity = AngularVelocity;
- m_lastUpdateSentTime = Environment.TickCount;
+ lock(UpdateFlagLock)
+ {
+ if(UpdateFlag != UpdateRequired.NONE)
+ return;
+
+ // Update the "last" values
+ m_lastPosition = AbsolutePosition;
+ m_lastRotation = RotationOffset;
+ m_lastVelocity = Velocity;
+ m_lastAcceleration = Acceleration;
+ m_lastAngularVelocity = AngularVelocity;
+ m_lastUpdateSentTime = Util.GetTimeStampMS();
+ }
if (ParentGroup.IsAttachment)
{
@@ -3516,6 +3675,18 @@ SendFullUpdateToClient(remoteClient, Position) ignores position parameter
Force = force;
}
+ public PhysicsInertiaData PhysicsInertia
+ {
+ get
+ {
+ return m_physicsInertia;
+ }
+ set
+ {
+ m_physicsInertia = value;
+ }
+ }
+
public SOPVehicle VehicleParams
{
get
@@ -3689,7 +3860,18 @@ SendFullUpdateToClient(remoteClient, Position) ignores position parameter
bool hasDimple;
bool hasProfileCut;
- PrimType primType = GetPrimType();
+ if(Shape.SculptEntry)
+ {
+ if (Shape.SculptType != (byte)SculptType.Mesh)
+ return 1; // sculp
+
+ //hack to detect new upload with faces data enconded on pbs
+ if ((Shape.ProfileCurve & 0xf0) != (byte)HollowShape.Triangle)
+ // old broken upload TODO
+ return 8;
+ }
+
+ PrimType primType = GetPrimType(true);
HasCutHollowDimpleProfileCut(primType, Shape, out hasCut, out hasHollow, out hasDimple, out hasProfileCut);
switch (primType)
@@ -3733,13 +3915,6 @@ SendFullUpdateToClient(remoteClient, Position) ignores position parameter
if (hasProfileCut) ret += 2;
if (hasHollow) ret += 1;
break;
- case PrimType.SCULPT:
- // Special mesh handling
- if (Shape.SculptType == (byte)SculptType.Mesh)
- ret = 8; // if it's a mesh then max 8 faces
- else
- ret = 1; // if it's a sculpt then max 1 face
- break;
}
return ret;
@@ -3750,9 +3925,9 @@ SendFullUpdateToClient(remoteClient, Position) ignores position parameter
///
///
///
- public PrimType GetPrimType()
+ public PrimType GetPrimType(bool ignoreSculpt = false)
{
- if (Shape.SculptEntry)
+ if (Shape.SculptEntry && !ignoreSculpt)
return PrimType.SCULPT;
if ((Shape.ProfileCurve & 0x07) == (byte)ProfileShape.Square)
@@ -4415,8 +4590,11 @@ SendFullUpdateToClient(remoteClient, Position) ignores position parameter
if (god)
baseMask = 0x7ffffff0;
- // Are we the owner?
- if ((AgentID == OwnerID) || god)
+ bool canChange = (AgentID == OwnerID) || god;
+ if(!canChange)
+ canChange = ParentGroup.Scene.Permissions.CanEditObjectPermissions(ParentGroup, AgentID);
+
+ if (canChange)
{
switch (field)
{
@@ -4464,7 +4642,7 @@ SendFullUpdateToClient(remoteClient, Position) ignores position parameter
break;
}
-
+ AggregateInnerPerms();
SendFullUpdateToAllClients();
}
}
@@ -4481,6 +4659,8 @@ SendFullUpdateToClient(remoteClient, Position) ignores position parameter
EveryoneMask = source.EveryoneMask & BaseMask;
NextOwnerMask = source.NextOwnerMask & BaseMask;
+ AggregateInnerPerms();
+
if (OwnerMask != prevOwnerMask ||
GroupMask != prevGroupMask ||
EveryoneMask != prevEveryoneMask ||
@@ -4714,8 +4894,13 @@ SendFullUpdateToClient(remoteClient, Position) ignores position parameter
if (VolumeDetectActive) // change if not the default only
pa.SetVolumeDetect(1);
+
+ bool isroot = (m_localId == ParentGroup.RootPart.LocalId);
- if (m_vehicleParams != null && m_localId == ParentGroup.RootPart.LocalId)
+ if(isroot && m_physicsInertia != null)
+ pa.SetInertiaData(m_physicsInertia);
+
+ if (isroot && m_vehicleParams != null )
{
m_vehicleParams.SetVehicle(pa);
if(isPhysical && !isPhantom && m_vehicleParams.CameraDecoupled)
@@ -4741,7 +4926,7 @@ SendFullUpdateToClient(remoteClient, Position) ignores position parameter
pa.OnRequestTerseUpdate += PhysicsRequestingTerseUpdate;
pa.OnOutOfBounds += PhysicsOutOfBounds;
- if (ParentID != 0 && ParentID != LocalId)
+ if (_parentID != 0 && _parentID != LocalId)
{
PhysicsActor parentPa = ParentGroup.RootPart.PhysActor;
@@ -4974,6 +5159,9 @@ SendFullUpdateToClient(remoteClient, Position) ignores position parameter
if (newTex.FaceTextures[i] != null)
newFace = newTex.FaceTextures[i];
+ if (oldFace.TextureID != newFace.TextureID)
+ changeFlags |= Changed.TEXTURE;
+
Color4 oldRGBA = oldFace.RGBA;
Color4 newRGBA = newFace.RGBA;
@@ -4983,9 +5171,6 @@ SendFullUpdateToClient(remoteClient, Position) ignores position parameter
oldRGBA.A != newRGBA.A)
changeFlags |= Changed.COLOR;
- if (oldFace.TextureID != newFace.TextureID)
- changeFlags |= Changed.TEXTURE;
-
// Max change, skip the rest of testing
if (changeFlags == (Changed.TEXTURE | Changed.COLOR))
break;
@@ -5011,17 +5196,11 @@ SendFullUpdateToClient(remoteClient, Position) ignores position parameter
m_shape.TextureEntry = newTex.GetBytes();
if (changeFlags != 0)
TriggerScriptChangedEvent(changeFlags);
- UpdateFlag = UpdateRequired.FULL;
ParentGroup.HasGroupChanged = true;
-
- //This is madness..
- //ParentGroup.ScheduleGroupForFullUpdate();
- //This is sparta
ScheduleFullUpdate();
}
}
-
internal void UpdatePhysicsSubscribedEvents()
{
PhysicsActor pa = PhysActor;
@@ -5181,7 +5360,7 @@ SendFullUpdateToClient(remoteClient, Position) ignores position parameter
/// The scene the prim is being rezzed into
public void ApplyPermissionsOnRez(InventoryItemBase item, bool userInventory, Scene scene)
{
- if ((OwnerID != item.Owner) || ((item.CurrentPermissions & SceneObjectGroup.SLAM) != 0) || ((item.Flags & (uint)InventoryItemFlags.ObjectSlamPerm) != 0))
+ if ((OwnerID != item.Owner) || ((item.CurrentPermissions & (uint)PermissionMask.Slam) != 0) || ((item.Flags & (uint)InventoryItemFlags.ObjectSlamPerm) != 0))
{
if (scene.Permissions.PropagatePermissions())
{
@@ -5212,16 +5391,13 @@ SendFullUpdateToClient(remoteClient, Position) ignores position parameter
if (OwnerID != item.Owner)
{
- //LogPermissions("Before ApplyNextOwnerPermissions");
+ if(OwnerID != GroupID)
+ LastOwnerID = OwnerID;
+ OwnerID = item.Owner;
+ Inventory.ChangeInventoryOwner(item.Owner);
if (scene.Permissions.PropagatePermissions())
ApplyNextOwnerPermissions();
-
- //LogPermissions("After ApplyNextOwnerPermissions");
-
- LastOwnerID = OwnerID;
- OwnerID = item.Owner;
- Inventory.ChangeInventoryOwner(item.Owner);
}
}
@@ -5239,12 +5415,13 @@ SendFullUpdateToClient(remoteClient, Position) ignores position parameter
// Export needs to be preserved in the base and everyone
// mask, but removed in the owner mask as a next owner
// can never change the export status
- BaseMask &= NextOwnerMask | (uint)PermissionMask.Export;
+ BaseMask &= (NextOwnerMask | (uint)PermissionMask.Export);
OwnerMask &= NextOwnerMask;
- EveryoneMask &= NextOwnerMask | (uint)PermissionMask.Export;
+ EveryoneMask &= (NextOwnerMask | (uint)PermissionMask.Export);
GroupMask = 0; // Giving an object zaps group permissions
Inventory.ApplyNextOwnerPermissions();
+ AggregateInnerPerms();
}
public void UpdateLookAt()
@@ -5306,6 +5483,7 @@ SendFullUpdateToClient(remoteClient, Position) ignores position parameter
item.OwnerChanged = false;
Inventory.UpdateInventoryItem(item, false, false);
}
+ AggregateInnerPerms();
}
///
diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs b/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs
index 6557003a12..3fd6e13c13 100644
--- a/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs
@@ -91,7 +91,8 @@ namespace OpenSim.Region.Framework.Scenes
///
protected internal TaskInventoryDictionary Items
{
- get {
+ get
+ {
return m_items;
}
set
@@ -141,45 +142,53 @@ namespace OpenSim.Region.Framework.Scenes
///
public void ResetInventoryIDs()
{
- if (null == m_part)
- m_items.LockItemsForWrite(true);
+ if (m_part == null)
+ return;
- if (Items.Count == 0)
+ m_items.LockItemsForWrite(true);
+ if (m_items.Count == 0)
{
m_items.LockItemsForWrite(false);
return;
}
- IList items = new List(Items.Values);
- Items.Clear();
+ UUID partID = m_part.UUID;
+ IList items = new List(m_items.Values);
+ m_items.Clear();
foreach (TaskInventoryItem item in items)
{
- item.ResetIDs(m_part.UUID);
- Items.Add(item.ItemID, item);
+ item.ResetIDs(partID);
+ m_items.Add(item.ItemID, item);
}
+ m_inventorySerial++;
m_items.LockItemsForWrite(false);
}
public void ResetObjectID()
{
+ if (m_part == null)
+ return;
+
m_items.LockItemsForWrite(true);
- if (Items.Count == 0)
+ if (m_items.Count == 0)
{
m_items.LockItemsForWrite(false);
return;
}
- IList items = new List(Items.Values);
- Items.Clear();
+ IList items = new List(m_items.Values);
+ m_items.Clear();
+ UUID partID = m_part.UUID;
foreach (TaskInventoryItem item in items)
{
- item.ParentPartID = m_part.UUID;
- item.ParentID = m_part.UUID;
- Items.Add(item.ItemID, item);
+ item.ParentPartID = partID;
+ item.ParentID = partID;
+ m_items.Add(item.ItemID, item);
}
+ m_inventorySerial++;
m_items.LockItemsForWrite(false);
}
@@ -189,15 +198,17 @@ namespace OpenSim.Region.Framework.Scenes
///
public void ChangeInventoryOwner(UUID ownerId)
{
- List items = GetInventoryItems();
-
- if (items.Count == 0)
+ if(m_part == null)
return;
m_items.LockItemsForWrite(true);
- HasInventoryChanged = true;
- m_part.ParentGroup.HasGroupChanged = true;
- foreach (TaskInventoryItem item in items)
+ if (m_items.Count == 0)
+ {
+ m_items.LockItemsForWrite(false);
+ return;
+ }
+
+ foreach (TaskInventoryItem item in m_items.Values)
{
if (ownerId != item.OwnerID)
item.LastOwnerID = item.OwnerID;
@@ -207,6 +218,9 @@ namespace OpenSim.Region.Framework.Scenes
item.PermsGranter = UUID.Zero;
item.OwnerChanged = true;
}
+ HasInventoryChanged = true;
+ m_part.ParentGroup.HasGroupChanged = true;
+ m_inventorySerial++;
m_items.LockItemsForWrite(false);
}
@@ -216,13 +230,16 @@ namespace OpenSim.Region.Framework.Scenes
///
public void ChangeInventoryGroup(UUID groupID)
{
+ if(m_part == null)
+ return;
+
m_items.LockItemsForWrite(true);
- if (0 == Items.Count)
+ if (m_items.Count == 0)
{
m_items.LockItemsForWrite(false);
return;
}
-
+ m_inventorySerial++;
// Don't let this set the HasGroupChanged flag for attachments
// as this happens during rez and we don't want a new asset
// for each attachment each time
@@ -232,14 +249,9 @@ namespace OpenSim.Region.Framework.Scenes
m_part.ParentGroup.HasGroupChanged = true;
}
- IList items = new List(Items.Values);
- foreach (TaskInventoryItem item in items)
- {
- if (groupID != item.GroupID)
- {
- item.GroupID = groupID;
- }
- }
+ foreach (TaskInventoryItem item in m_items.Values)
+ item.GroupID = groupID;
+
m_items.LockItemsForWrite(false);
}
@@ -248,8 +260,8 @@ namespace OpenSim.Region.Framework.Scenes
if (m_part == null || m_part.ParentGroup == null || m_part.ParentGroup.Scene == null)
return;
- Items.LockItemsForRead(true);
- foreach (TaskInventoryItem item in Items.Values)
+ m_items.LockItemsForRead(true);
+ foreach (TaskInventoryItem item in m_items.Values)
{
if (item.InvType == (int)InventoryType.LSL)
{
@@ -259,7 +271,7 @@ namespace OpenSim.Region.Framework.Scenes
}
}
- Items.LockItemsForRead(false);
+ m_items.LockItemsForRead(false);
}
public bool TryGetScriptInstanceRunning(UUID itemId, out bool running)
@@ -347,7 +359,9 @@ namespace OpenSim.Region.Framework.Scenes
///
public void StopScriptInstances()
{
- GetInventoryItems(InventoryType.LSL).ForEach(i => StopScriptInstance(i));
+ List scripts = GetInventoryItems(InventoryType.LSL);
+ foreach (TaskInventoryItem item in scripts)
+ StopScriptInstance(item);
}
///
@@ -360,7 +374,7 @@ namespace OpenSim.Region.Framework.Scenes
// m_log.DebugFormat("[PRIM INVENTORY]: Starting script {0} {1} in prim {2} {3} in {4}",
// item.Name, item.ItemID, m_part.Name, m_part.UUID, m_part.ParentGroup.Scene.RegionInfo.RegionName);
- if (!m_part.ParentGroup.Scene.Permissions.CanRunScript(item.ItemID, m_part.UUID, item.OwnerID))
+ if (!m_part.ParentGroup.Scene.Permissions.CanRunScript(item, m_part))
{
StoreScriptError(item.ItemID, "no permission");
return false;
@@ -807,8 +821,8 @@ namespace OpenSim.Region.Framework.Scenes
else
m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
+ m_part.AggregateInnerPerms();
m_inventorySerial++;
- //m_inventorySerial += 2;
HasInventoryChanged = true;
m_part.ParentGroup.HasGroupChanged = true;
}
@@ -829,7 +843,7 @@ namespace OpenSim.Region.Framework.Scenes
// m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
}
m_items.LockItemsForWrite(false);
-
+ m_part.AggregateInnerPerms();
m_inventorySerial++;
}
@@ -943,8 +957,7 @@ namespace OpenSim.Region.Framework.Scenes
group.SetGroup(m_part.GroupID, null);
- // TODO: Remove magic number badness
- if ((rootPart.OwnerID != item.OwnerID) || (item.CurrentPermissions & 16) != 0 || (item.Flags & (uint)InventoryItemFlags.ObjectSlamPerm) != 0) // Magic number
+ if ((rootPart.OwnerID != item.OwnerID) || (item.CurrentPermissions & (uint)PermissionMask.Slam) != 0 || (item.Flags & (uint)InventoryItemFlags.ObjectSlamPerm) != 0)
{
if (m_part.ParentGroup.Scene.Permissions.PropagatePermissions())
{
@@ -964,10 +977,10 @@ namespace OpenSim.Region.Framework.Scenes
foreach (SceneObjectPart part in partList)
{
- // TODO: Remove magic number badness
- if ((part.OwnerID != item.OwnerID) || (item.CurrentPermissions & 16) != 0 || (item.Flags & (uint)InventoryItemFlags.ObjectSlamPerm) != 0) // Magic number
+ if ((part.OwnerID != item.OwnerID) || (item.CurrentPermissions & (uint)PermissionMask.Slam) != 0 || (item.Flags & (uint)InventoryItemFlags.ObjectSlamPerm) != 0)
{
- part.LastOwnerID = part.OwnerID;
+ if(part.GroupID != part.OwnerID)
+ part.LastOwnerID = part.OwnerID;
part.OwnerID = item.OwnerID;
part.Inventory.ChangeInventoryOwner(item.OwnerID);
}
@@ -981,6 +994,7 @@ namespace OpenSim.Region.Framework.Scenes
}
// old code end
rootPart.TrimPermissions();
+ group.InvalidateDeepEffectivePerms();
}
return true;
@@ -1018,20 +1032,26 @@ namespace OpenSim.Region.Framework.Scenes
if (item.GroupPermissions != (uint)PermissionMask.None)
item.GroupID = m_part.GroupID;
+ if(item.OwnerID == UUID.Zero) // viewer to internal enconding of group owned
+ item.OwnerID = item.GroupID;
+
if (item.AssetID == UUID.Zero)
item.AssetID = m_items[item.ItemID].AssetID;
m_items[item.ItemID] = item;
+
m_inventorySerial++;
if (fireScriptEvents)
m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
if (considerChanged)
{
+ m_part.ParentGroup.InvalidateDeepEffectivePerms();
HasInventoryChanged = true;
m_part.ParentGroup.HasGroupChanged = true;
}
m_items.LockItemsForWrite(false);
+
return true;
}
else
@@ -1068,6 +1088,9 @@ namespace OpenSim.Region.Framework.Scenes
m_items.LockItemsForWrite(true);
m_items.Remove(itemID);
m_items.LockItemsForWrite(false);
+
+ m_part.ParentGroup.InvalidateDeepEffectivePerms();
+
m_inventorySerial++;
m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
@@ -1118,18 +1141,18 @@ namespace OpenSim.Region.Framework.Scenes
{
bool changed = false;
- Items.LockItemsForRead(true);
+ m_items.LockItemsForRead(true);
if (m_inventorySerial == 0) // No inventory
{
- Items.LockItemsForRead(false);
+ m_items.LockItemsForRead(false);
client.SendTaskInventory(m_part.UUID, 0, new byte[0]);
return;
}
if (m_items.Count == 0) // No inventory
{
- Items.LockItemsForRead(false);
+ m_items.LockItemsForRead(false);
client.SendTaskInventory(m_part.UUID, 0, new byte[0]);
return;
}
@@ -1140,7 +1163,7 @@ namespace OpenSim.Region.Framework.Scenes
changed = true;
}
- Items.LockItemsForRead(false);
+ m_items.LockItemsForRead(false);
if (m_inventoryFileData.Length < 2)
changed = true;
@@ -1165,12 +1188,13 @@ namespace OpenSim.Region.Framework.Scenes
InventoryStringBuilder invString = new InventoryStringBuilder(m_part.UUID, UUID.Zero);
- Items.LockItemsForRead(true);
+ m_items.LockItemsForRead(true);
foreach (TaskInventoryItem item in m_items.Values)
{
UUID ownerID = item.OwnerID;
- uint everyoneMask = 0;
+ UUID groupID = item.GroupID;
+ uint everyoneMask = item.EveryonePermissions;
uint baseMask = item.BasePermissions;
uint ownerMask = item.CurrentPermissions;
uint groupMask = item.GroupPermissions;
@@ -1188,11 +1212,21 @@ namespace OpenSim.Region.Framework.Scenes
invString.AddNameValueLine("next_owner_mask", Utils.UIntToHexString(item.NextPermissions));
invString.AddNameValueLine("creator_id", item.CreatorID.ToString());
- invString.AddNameValueLine("owner_id", ownerID.ToString());
invString.AddNameValueLine("last_owner_id", item.LastOwnerID.ToString());
- invString.AddNameValueLine("group_id", item.GroupID.ToString());
+ invString.AddNameValueLine("group_id",groupID.ToString());
+ if(groupID != UUID.Zero && ownerID == groupID)
+ {
+ invString.AddNameValueLine("owner_id", UUID.Zero.ToString());
+ invString.AddNameValueLine("group_owned","1");
+ }
+ else
+ {
+ invString.AddNameValueLine("owner_id", ownerID.ToString());
+ invString.AddNameValueLine("group_owned","0");
+ }
+
invString.AddSectionEnd();
if (includeAssets)
@@ -1215,7 +1249,7 @@ namespace OpenSim.Region.Framework.Scenes
invString.AddSectionEnd();
}
- Items.LockItemsForRead(false);
+ m_items.LockItemsForRead(false);
m_inventoryFileData = Utils.StringToBytes(invString.GetString());
@@ -1245,10 +1279,10 @@ namespace OpenSim.Region.Framework.Scenes
// of prim inventory loss.
// if (HasInventoryChanged)
// {
- Items.LockItemsForRead(true);
- ICollection itemsvalues = Items.Values;
+ m_items.LockItemsForRead(true);
+ ICollection itemsvalues = m_items.Values;
HasInventoryChanged = false;
- Items.LockItemsForRead(false);
+ m_items.LockItemsForRead(false);
try
{
datastore.StorePrimInventory(m_part.UUID, itemsvalues);
@@ -1319,35 +1353,49 @@ namespace OpenSim.Region.Framework.Scenes
}
}
- public uint MaskEffectivePermissions()
+ public void AggregateInnerPerms(ref uint owner, ref uint group, ref uint everyone)
{
- uint mask=0x7fffffff;
-
foreach (TaskInventoryItem item in m_items.Values)
{
- if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Copy) == 0)
- mask &= ~((uint)PermissionMask.Copy >> 13);
- if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Transfer) == 0)
- mask &= ~((uint)PermissionMask.Transfer >> 13);
- if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Modify) == 0)
- mask &= ~((uint)PermissionMask.Modify >> 13);
+ if(item.InvType == (sbyte)InventoryType.Landmark)
+ continue;
+ owner &= item.CurrentPermissions;
+ group &= item.GroupPermissions;
+ everyone &= item.EveryonePermissions;
+ }
+ }
- if (item.InvType == (int)InventoryType.Object)
- {
- if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0)
- mask &= ~((uint)PermissionMask.Copy >> 13);
- if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0)
- mask &= ~((uint)PermissionMask.Transfer >> 13);
- if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0)
- mask &= ~((uint)PermissionMask.Modify >> 13);
- }
+ public uint MaskEffectivePermissions()
+ {
+ // used to propagate permissions restrictions outwards
+ // Modify does not propagate outwards.
+ uint mask=0x7fffffff;
+
+ foreach (TaskInventoryItem item in m_items.Values)
+ {
+ if(item.InvType == (sbyte)InventoryType.Landmark)
+ continue;
- if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
+ // apply current to normal permission bits
+ uint newperms = item.CurrentPermissions;
+
+ if ((newperms & (uint)PermissionMask.Copy) == 0)
mask &= ~(uint)PermissionMask.Copy;
- if ((item.CurrentPermissions & (uint)PermissionMask.Transfer) == 0)
+ if ((newperms & (uint)PermissionMask.Transfer) == 0)
mask &= ~(uint)PermissionMask.Transfer;
- if ((item.CurrentPermissions & (uint)PermissionMask.Modify) == 0)
- mask &= ~(uint)PermissionMask.Modify;
+ if ((newperms & (uint)PermissionMask.Export) == 0)
+ mask &= ~((uint)PermissionMask.Export);
+
+ // apply next owner restricted by current to folded bits
+ newperms &= item.NextPermissions;
+
+ if ((newperms & (uint)PermissionMask.Copy) == 0)
+ mask &= ~((uint)PermissionMask.FoldedCopy);
+ if ((newperms & (uint)PermissionMask.Transfer) == 0)
+ mask &= ~((uint)PermissionMask.FoldedTransfer);
+ if ((newperms & (uint)PermissionMask.Export) == 0)
+ mask &= ~((uint)PermissionMask.FoldedExport);
+
}
return mask;
}
@@ -1356,19 +1404,6 @@ namespace OpenSim.Region.Framework.Scenes
{
foreach (TaskInventoryItem item in m_items.Values)
{
- if (item.InvType == (int)InventoryType.Object && (item.CurrentPermissions & 7) != 0)
- {
-// m_log.DebugFormat (
-// "[SCENE OBJECT PART INVENTORY]: Applying next permissions {0} to {1} in {2} with current {3}, base {4}, everyone {5}",
-// item.NextPermissions, item.Name, m_part.Name, item.CurrentPermissions, item.BasePermissions, item.EveryonePermissions);
-
- if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0)
- item.CurrentPermissions &= ~(uint)PermissionMask.Copy;
- if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0)
- item.CurrentPermissions &= ~(uint)PermissionMask.Transfer;
- if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0)
- item.CurrentPermissions &= ~(uint)PermissionMask.Modify;
- }
item.CurrentPermissions &= item.NextPermissions;
item.BasePermissions &= item.NextPermissions;
item.EveryonePermissions &= item.NextPermissions;
@@ -1414,15 +1449,13 @@ namespace OpenSim.Region.Framework.Scenes
public int ScriptCount()
{
int count = 0;
- Items.LockItemsForRead(true);
+ m_items.LockItemsForRead(true);
foreach (TaskInventoryItem item in m_items.Values)
{
if (item.InvType == (int)InventoryType.LSL)
- {
count++;
- }
}
- Items.LockItemsForRead(false);
+ m_items.LockItemsForRead(false);
return count;
}
///
@@ -1445,9 +1478,7 @@ namespace OpenSim.Region.Framework.Scenes
if (engine != null)
{
if (engine.GetScriptState(item.ItemID))
- {
count++;
- }
}
}
}
@@ -1456,37 +1487,35 @@ namespace OpenSim.Region.Framework.Scenes
public List GetInventoryList()
{
- List ret = new List();
+ m_items.LockItemsForRead(true);
+ List ret = new List(m_items.Count);
foreach (TaskInventoryItem item in m_items.Values)
ret.Add(item.ItemID);
+ m_items.LockItemsForRead(false);
return ret;
}
public List GetInventoryItems()
{
- List ret = new List();
-
- Items.LockItemsForRead(true);
- ret = new List(m_items.Values);
- Items.LockItemsForRead(false);
+ m_items.LockItemsForRead(true);
+ List ret = new List(m_items.Values);
+ m_items.LockItemsForRead(false);
return ret;
}
public List GetInventoryItems(InventoryType type)
{
- List ret = new List();
-
- Items.LockItemsForRead(true);
+ m_items.LockItemsForRead(true);
+ List ret = new List(m_items.Count);
foreach (TaskInventoryItem item in m_items.Values)
if (item.InvType == (int)type)
ret.Add(item);
- Items.LockItemsForRead(false);
-
+ m_items.LockItemsForRead(false);
return ret;
}
diff --git a/OpenSim/Region/Framework/Scenes/ScenePresence.cs b/OpenSim/Region/Framework/Scenes/ScenePresence.cs
index 9545c13d85..ba3aaaed61 100644
--- a/OpenSim/Region/Framework/Scenes/ScenePresence.cs
+++ b/OpenSim/Region/Framework/Scenes/ScenePresence.cs
@@ -170,6 +170,7 @@ namespace OpenSim.Region.Framework.Scenes
private bool m_previusParcelHide = false;
private bool m_currentParcelHide = false;
private object parcelLock = new Object();
+ public double ParcelDwellTickMS;
public UUID currentParcelUUID
{
@@ -182,6 +183,7 @@ namespace OpenSim.Region.Framework.Scenes
bool checksame = true;
if (value != m_currentParcelUUID)
{
+ ParcelDwellTickMS = Util.GetTimeStampMS();
m_previusParcelHide = m_currentParcelHide;
m_previusParcelUUID = m_currentParcelUUID;
checksame = false;
@@ -277,8 +279,11 @@ namespace OpenSim.Region.Framework.Scenes
private bool MouseDown = false;
public Vector3 lastKnownAllowedPosition;
public bool sentMessageAboutRestrictedParcelFlyingDown;
+
public Vector4 CollisionPlane = Vector4.UnitW;
+ public Vector4 m_lastCollisionPlane = Vector4.UnitW;
+ private byte m_lastState;
private Vector3 m_lastPosition;
private Quaternion m_lastRotation;
private Vector3 m_lastVelocity;
@@ -362,6 +367,7 @@ namespace OpenSim.Region.Framework.Scenes
//PauPaw:Proper PID Controler for autopilot************
public bool MovingToTarget { get; private set; }
public Vector3 MoveToPositionTarget { get; private set; }
+ private double m_delayedStop = -1.0;
///
/// Controls whether an avatar automatically moving to a target will land when it gets there (if flying).
@@ -968,6 +974,10 @@ namespace OpenSim.Region.Framework.Scenes
m_inTransit = value;
}
}
+ // this is is only valid if IsInTransit is true
+ // only false on HG tps
+ // used work arounf viewers asking source region about destination user
+ public bool IsInLocalTransit {get; set; }
///
@@ -1037,6 +1047,7 @@ namespace OpenSim.Region.Framework.Scenes
m_uuid = client.AgentId;
LocalId = m_scene.AllocateLocalId();
LegacySitOffsets = m_scene.LegacySitOffsets;
+ IsInLocalTransit = true;
UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, m_uuid);
if (account != null)
@@ -1778,6 +1789,20 @@ namespace OpenSim.Region.Framework.Scenes
private Dictionary m_knownChildRegionsSizeInfo = new Dictionary();
+ public void AddNeighbourRegion(GridRegion region, string capsPath)
+ {
+ lock (m_knownChildRegions)
+ {
+ ulong regionHandle = region.RegionHandle;
+ m_knownChildRegions.Add(regionHandle,capsPath);
+
+ spRegionSizeInfo sizeInfo = new spRegionSizeInfo();
+ sizeInfo.sizeX = region.RegionSizeX;
+ sizeInfo.sizeY = region.RegionSizeY;
+ m_knownChildRegionsSizeInfo[regionHandle] = sizeInfo;
+ }
+ }
+
public void AddNeighbourRegionSizeInfo(GridRegion region)
{
lock (m_knownChildRegions)
@@ -1802,6 +1827,7 @@ namespace OpenSim.Region.Framework.Scenes
lock (m_knownChildRegions)
{
m_knownChildRegionsSizeInfo.Clear();
+
foreach (GridRegion region in regionsList)
{
spRegionSizeInfo sizeInfo = new spRegionSizeInfo();
@@ -1826,6 +1852,12 @@ namespace OpenSim.Region.Framework.Scenes
}
}
+ public bool knowsNeighbourRegion(ulong regionHandle)
+ {
+ lock (m_knownChildRegions)
+ return m_knownChildRegions.ContainsKey(regionHandle);
+ }
+
public void DropOldNeighbours(List oldRegions)
{
foreach (ulong handle in oldRegions)
@@ -1862,7 +1894,8 @@ namespace OpenSim.Region.Framework.Scenes
{
get
{
- return new List(KnownRegions.Keys);
+ lock (m_knownChildRegions)
+ return new List(m_knownChildRegions.Keys);
}
}
@@ -2010,6 +2043,7 @@ namespace OpenSim.Region.Framework.Scenes
return;
}
+
m_log.DebugFormat("[CompleteMovement] MakeRootAgent: {0}ms", Util.EnvironmentTickCountSubtract(ts));
if(!haveGroupInformation && !IsChildAgent && !IsNPC)
@@ -2029,11 +2063,6 @@ namespace OpenSim.Region.Framework.Scenes
m_log.DebugFormat("[CompleteMovement]: Missing COF for {0} is {1}", client.AgentId, COF);
}
- // Tell the client that we're totally ready
- ControllingClient.MoveAgentIntoRegion(m_scene.RegionInfo, AbsolutePosition, look);
-
- m_log.DebugFormat("[CompleteMovement] MoveAgentIntoRegion: {0}ms", Util.EnvironmentTickCountSubtract(ts));
-
if (!string.IsNullOrEmpty(m_callbackURI))
{
// We cannot sleep here since this would hold up the inbound packet processing thread, as
@@ -2054,6 +2083,7 @@ namespace OpenSim.Region.Framework.Scenes
Scene.SimulationService.ReleaseAgent(originID, UUID, m_callbackURI);
m_callbackURI = null;
+ m_log.DebugFormat("[CompleteMovement] ReleaseAgent: {0}ms", Util.EnvironmentTickCountSubtract(ts));
}
// else
// {
@@ -2062,45 +2092,27 @@ namespace OpenSim.Region.Framework.Scenes
// client.Name, client.AgentId, m_scene.RegionInfo.RegionName);
// }
- m_log.DebugFormat("[CompleteMovement] ReleaseAgent: {0}ms", Util.EnvironmentTickCountSubtract(ts));
- if(m_teleportFlags > 0)
- {
- gotCrossUpdate = false; // sanity check
- Thread.Sleep(500); // let viewers catch us
- }
+ // Tell the client that we're totally ready
+ ControllingClient.MoveAgentIntoRegion(m_scene.RegionInfo, AbsolutePosition, look);
+ m_log.DebugFormat("[CompleteMovement] MoveAgentIntoRegion: {0}ms", Util.EnvironmentTickCountSubtract(ts));
- if(!gotCrossUpdate)
- RotateToLookAt(look);
-
- // HG
bool isHGTP = (m_teleportFlags & TeleportFlags.ViaHGLogin) != 0;
- if(isHGTP)
- {
-// ControllingClient.SendNameReply(m_uuid, Firstname, Lastname);
- m_log.DebugFormat("[CompleteMovement] HG");
- }
- m_previusParcelHide = false;
- m_previusParcelUUID = UUID.Zero;
- m_currentParcelHide = false;
- m_currentParcelUUID = UUID.Zero;
-
- if(!IsNPC)
- {
- GodController.SyncViewerState();
-
- // start sending terrain patchs
- if (!gotCrossUpdate)
- Scene.SendLayerData(ControllingClient);
- }
- // send initial land overlay and parcel
- ILandChannel landch = m_scene.LandChannel;
- if (landch != null)
- landch.sendClientInitialLandInfo(client);
+ int delayctnr = Util.EnvironmentTickCount();
if (!IsChildAgent)
{
+ if( ParentPart != null && !IsNPC && (crossingFlags & 0x08) != 0)
+ {
+
+// SceneObjectPart root = ParentPart.ParentGroup.RootPart;
+// if(root.LocalId != ParentPart.LocalId)
+// ControllingClient.SendEntityTerseUpdateImmediate(root);
+// ControllingClient.SendEntityTerseUpdateImmediate(ParentPart);
+ ParentPart.ParentGroup.SendFullUpdateToClient(ControllingClient);
+ }
+
// verify baked textures and cache
bool cachedbaked = false;
@@ -2118,11 +2130,52 @@ namespace OpenSim.Region.Framework.Scenes
m_scene.AvatarFactory.QueueAppearanceSave(UUID);
}
}
+ m_log.DebugFormat("[CompleteMovement] Baked check: {0}ms", Util.EnvironmentTickCountSubtract(ts));
+ }
+ if(m_teleportFlags > 0)
+ {
+ gotCrossUpdate = false; // sanity check
+ if(Util.EnvironmentTickCountSubtract(delayctnr)< 500)
+ Thread.Sleep(500); // let viewers catch us
+ }
+
+ if(!gotCrossUpdate)
+ RotateToLookAt(look);
+
+ // HG
+ if(isHGTP)
+ {
+// ControllingClient.SendNameReply(m_uuid, Firstname, Lastname);
+ m_log.DebugFormat("[CompleteMovement] HG");
+ }
+
+ m_previusParcelHide = false;
+ m_previusParcelUUID = UUID.Zero;
+ m_currentParcelHide = false;
+ m_currentParcelUUID = UUID.Zero;
+ ParcelDwellTickMS = Util.GetTimeStampMS();
+
+ if(!IsNPC)
+ {
+ GodController.SyncViewerState();
+
+ // start sending terrain patchs
+ if (!gotCrossUpdate)
+ Scene.SendLayerData(ControllingClient);
+ }
+ // send initial land overlay and parcel
+ ILandChannel landch = m_scene.LandChannel;
+ if (landch != null)
+ landch.sendClientInitialLandInfo(client);
+
+ if (!IsChildAgent)
+ {
List allpresences = m_scene.GetScenePresences();
// send avatar object to all presences including us, so they cross it into region
// then hide if necessary
+
SendInitialAvatarDataToAllAgents(allpresences);
// send this look
@@ -2409,7 +2462,9 @@ namespace OpenSim.Region.Framework.Scenes
// This is irritating. Really.
if (!AbsolutePosition.IsFinite())
{
- RemoveFromPhysicalScene();
+ bool isphysical = PhysicsActor != null;
+ if(isphysical)
+ RemoveFromPhysicalScene();
m_log.Error("[AVATAR]: NonFinite Avatar position detected... Reset Position. Mantis this please. Error #9999902");
m_pos = m_LastFinitePos;
@@ -2421,7 +2476,8 @@ namespace OpenSim.Region.Framework.Scenes
m_log.Error("[AVATAR]: NonFinite Avatar position detected... Reset Position. Mantis this please. Error #9999903");
}
- AddToPhysicalScene(false);
+ if(isphysical)
+ AddToPhysicalScene(false);
}
else
{
@@ -2681,7 +2737,6 @@ namespace OpenSim.Region.Framework.Scenes
agent_control_v3.Z = 0;
// else if(AgentControlStopActive %% Velocity.Z <0.01f)
-
// m_log.DebugFormat("[SCENE PRESENCE]: MovementFlag {0} for {1}", MovementFlag, Name);
// If the agent update does move the avatar, then calculate the force ready for the velocity update,
@@ -2690,6 +2745,7 @@ namespace OpenSim.Region.Framework.Scenes
// held down AGENT_CONTROL_STOP whilst normal walking/running). However, we do not want to update
// if the user rotated whilst holding down AGENT_CONTROL_STOP when already still (which locks the
// avatar location in place).
+
if (update_movementflag
|| (update_rotation && DCFlagKeyPressed && (!AgentControlStopActive || MovementFlag != 0)))
{
@@ -2706,17 +2762,27 @@ namespace OpenSim.Region.Framework.Scenes
}
else
{
- AddNewMovement(agent_control_v3);
+ if(MovingToTarget ||
+ (Animator.currentControlState != ScenePresenceAnimator.motionControlStates.flying &&
+ Animator.currentControlState != ScenePresenceAnimator.motionControlStates.onsurface)
+ )
+ AddNewMovement(agent_control_v3);
+ else
+ {
+ if (MovementFlag != 0)
+ AddNewMovement(agent_control_v3);
+ else
+ m_delayedStop = Util.GetTimeStampMS() + 200.0;
+ }
}
-
}
-
- if (update_movementflag && ParentID == 0)
+/*
+ if (update_movementflag && ParentID == 0 && m_delayedStop < 0)
{
// m_log.DebugFormat("[SCENE PRESENCE]: Updating movement animations for {0}", Name);
Animator.UpdateMovementAnimations();
}
-
+*/
SendControlsToScripts(flagsForScripts);
}
@@ -2755,16 +2821,13 @@ namespace OpenSim.Region.Framework.Scenes
CameraAtAxis = agentData.CameraAtAxis;
CameraLeftAxis = agentData.CameraLeftAxis;
CameraUpAxis = agentData.CameraUpAxis;
- Quaternion camRot = Util.Axes2Rot(CameraAtAxis, CameraLeftAxis, CameraUpAxis);
- CameraRotation = camRot;
-
- // The Agent's Draw distance setting
- // When we get to the point of re-computing neighbors everytime this
- // changes, then start using the agent's drawdistance rather than the
- // region's draw distance.
-
DrawDistance = agentData.Far;
+ CameraAtAxis.Normalize();
+ CameraLeftAxis.Normalize();
+ CameraUpAxis.Normalize();
+ Quaternion camRot = Util.Axes2Rot(CameraAtAxis, CameraLeftAxis, CameraUpAxis);
+ CameraRotation = camRot;
// Check if Client has camera in 'follow cam' or 'build' mode.
// Vector3 camdif = (Vector3.One * Rotation - Vector3.One * CameraRotation);
@@ -2890,31 +2953,32 @@ namespace OpenSim.Region.Framework.Scenes
Dir_ControlFlags.DIR_CONTROL_FLAG_DOWN));
MovementFlag &= noMovFlagsMask;
- AgentControlFlags &= noMovFlagsMask;
+ uint tmpAgentControlFlags = (uint)m_AgentControlFlags;
+ tmpAgentControlFlags &= noMovFlagsMask;
if (LocalVectorToTarget3D.X < 0) //MoveBack
{
MovementFlag |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_BACK;
- AgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_BACK;
+ tmpAgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_BACK;
updated = true;
}
else if (LocalVectorToTarget3D.X > 0) //Move Forward
{
MovementFlag |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD;
- AgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD;
+ tmpAgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD;
updated = true;
}
if (LocalVectorToTarget3D.Y > 0) //MoveLeft
{
MovementFlag |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_LEFT;
- AgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_LEFT;
+ tmpAgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_LEFT;
updated = true;
}
else if (LocalVectorToTarget3D.Y < 0) //MoveRight
{
MovementFlag |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_RIGHT;
- AgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_RIGHT;
+ tmpAgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_RIGHT;
updated = true;
}
@@ -2938,6 +3002,7 @@ namespace OpenSim.Region.Framework.Scenes
// "[SCENE PRESENCE]: HandleMoveToTargetUpdate adding {0} to move vector {1} for {2}",
// LocalVectorToTarget3D, agent_control_v3, Name);
+ m_AgentControlFlags = (AgentManager.ControlFlags) tmpAgentControlFlags;
agent_control_v3 += LocalVectorToTarget3D;
}
catch (Exception e)
@@ -2965,6 +3030,8 @@ namespace OpenSim.Region.Framework.Scenes
///
public void MoveToTarget(Vector3 pos, bool noFly, bool landAtTarget)
{
+ m_delayedStop = -1;
+
if (SitGround)
StandUp();
@@ -3110,6 +3177,7 @@ namespace OpenSim.Region.Framework.Scenes
Vector3 standPos = sitPartWorldPosition + adjustmentForSitPose;
m_pos = standPos;
+
}
// We need to wait until we have calculated proper stand positions before sitting up the physical
@@ -3124,6 +3192,7 @@ namespace OpenSim.Region.Framework.Scenes
part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK);
SendAvatarDataToAllAgents();
+ m_scene.EventManager.TriggerParcelPrimCountTainted(); // update select/ sat on
}
// reset to default sitAnimation
@@ -3256,6 +3325,7 @@ namespace OpenSim.Region.Framework.Scenes
// Moved here to avoid a race with default sit anim
// The script event needs to be raised after the default sit anim is set.
part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK);
+ m_scene.EventManager.TriggerParcelPrimCountTainted(); // update select/ sat on
}
}
@@ -3405,6 +3475,7 @@ namespace OpenSim.Region.Framework.Scenes
Animator.SetMovementAnimations("SIT");
part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK);
+ m_scene.EventManager.TriggerParcelPrimCountTainted(); // update select/ sat on
}
public void HandleAgentSit(IClientAPI remoteClient, UUID agentID)
@@ -3616,7 +3687,7 @@ namespace OpenSim.Region.Framework.Scenes
// m_log.DebugFormat(
// "[SCENE PRESENCE]: Adding new movement {0} with rotation {1}, thisAddSpeedModifier {2} for {3}",
// vec, Rotation, thisAddSpeedModifier, Name);
-
+ m_delayedStop = -1;
// rotate from avatar coord space to world
Quaternion rot = Rotation;
if (!Flying && PresenceType != PresenceType.Npc)
@@ -3634,7 +3705,7 @@ namespace OpenSim.Region.Framework.Scenes
direc.Z = 0f; // Prevent camera WASD up.
// odd rescalings
- direc *= 0.03f * 128f * SpeedModifier * thisAddSpeedModifier;
+ direc *= 0.032f * 128f * SpeedModifier * thisAddSpeedModifier;
// m_log.DebugFormat("[SCENE PRESENCE]: Force to apply before modification was {0} for {1}", direc, Name);
@@ -3699,39 +3770,40 @@ namespace OpenSim.Region.Framework.Scenes
if(MovingToTarget)
{
+ m_delayedStop = -1;
Vector3 control = Vector3.Zero;
if(HandleMoveToTargetUpdate(1f, ref control))
AddNewMovement(control);
}
+ else if(m_delayedStop > 0)
+ {
+ if(IsSatOnObject)
+ m_delayedStop = -1;
+ else
+ if(Util.GetTimeStampMS() > m_delayedStop)
+ AddNewMovement(Vector3.Zero);
+ }
if (Appearance.AvatarSize != m_lastSize)
SendAvatarDataToAllAgents();
// Send terse position update if not sitting and position, velocity, or rotation
// has changed significantly from last sent update
- if (!IsSatOnObject && (
- !Rotation.ApproxEquals(m_lastRotation, ROTATION_TOLERANCE)
- || !Velocity.ApproxEquals(m_lastVelocity, VELOCITY_TOLERANCE)
- || !m_pos.ApproxEquals(m_lastPosition, POSITION_LARGETOLERANCE)
- // if velocity is zero and it wasn't zero last time, send the update
- || (Velocity == Vector3.Zero && m_lastVelocity != Vector3.Zero)
- // if position has moved just a little and velocity is very low, send the update
- || (!m_pos.ApproxEquals(m_lastPosition, POSITION_SMALLTOLERANCE) && Velocity.LengthSquared() < LOWVELOCITYSQ )
- ) )
- {
-/*
if (!IsSatOnObject)
{
// this does need to be more complex later
Vector3 vel = Velocity;
Vector3 dpos = m_pos - m_lastPosition;
- if( Math.Abs(vel.X - m_lastVelocity.X) > VELOCITY_TOLERANCE ||
+ if( State != m_lastState ||
+ Math.Abs(vel.X - m_lastVelocity.X) > VELOCITY_TOLERANCE ||
Math.Abs(vel.Y - m_lastVelocity.Y) > VELOCITY_TOLERANCE ||
Math.Abs(vel.Z - m_lastVelocity.Z) > VELOCITY_TOLERANCE ||
Math.Abs(m_bodyRot.X - m_lastRotation.X) > ROTATION_TOLERANCE ||
Math.Abs(m_bodyRot.Y - m_lastRotation.Y) > ROTATION_TOLERANCE ||
Math.Abs(m_bodyRot.Z - m_lastRotation.Z) > ROTATION_TOLERANCE ||
+
+ (vel == Vector3.Zero && m_lastVelocity != Vector3.Zero) ||
Math.Abs(dpos.X) > POSITION_LARGETOLERANCE ||
Math.Abs(dpos.Y) > POSITION_LARGETOLERANCE ||
@@ -3741,11 +3813,15 @@ namespace OpenSim.Region.Framework.Scenes
Math.Abs(dpos.Y) > POSITION_SMALLTOLERANCE ||
Math.Abs(dpos.Z) > POSITION_SMALLTOLERANCE)
&& vel.LengthSquared() < LOWVELOCITYSQ
- ))
+ ) ||
+
+ Math.Abs(CollisionPlane.X - m_lastCollisionPlane.X) > POSITION_SMALLTOLERANCE ||
+ Math.Abs(CollisionPlane.Y - m_lastCollisionPlane.Y) > POSITION_SMALLTOLERANCE ||
+ Math.Abs(CollisionPlane.W - m_lastCollisionPlane.W) > POSITION_SMALLTOLERANCE
+ )
{
-*/
SendTerseUpdateToAllClients();
-// }
+ }
}
CheckForSignificantMovement();
}
@@ -3841,11 +3917,14 @@ namespace OpenSim.Region.Framework.Scenes
///
public void SendTerseUpdateToAllClients()
{
- m_scene.ForEachScenePresence(SendTerseUpdateToAgent);
- // Update the "last" values
+ m_lastState = State;
m_lastPosition = m_pos;
m_lastRotation = m_bodyRot;
m_lastVelocity = Velocity;
+ m_lastCollisionPlane = CollisionPlane;
+
+ m_scene.ForEachScenePresence(SendTerseUpdateToAgent);
+ // Update the "last" values
TriggerScenePresenceUpdated();
}
@@ -3968,7 +4047,7 @@ namespace OpenSim.Region.Framework.Scenes
int count = 0;
foreach (ScenePresence p in presences)
{
- p.ControllingClient.SendAvatarDataImmediate(this);
+ p.ControllingClient.SendEntityFullUpdateImmediate(this);
if (p != this && ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
// either just kill the object
// p.ControllingClient.SendKillObject(new List {LocalId});
@@ -3981,7 +4060,7 @@ namespace OpenSim.Region.Framework.Scenes
public void SendInitialAvatarDataToAgent(ScenePresence p)
{
- p.ControllingClient.SendAvatarDataImmediate(this);
+ p.ControllingClient.SendEntityFullUpdateImmediate(this);
if (p != this && ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
// either just kill the object
// p.ControllingClient.SendKillObject(new List {LocalId});
@@ -3998,12 +4077,12 @@ namespace OpenSim.Region.Framework.Scenes
//m_log.DebugFormat("[SCENE PRESENCE] SendAvatarDataToAgent from {0} ({1}) to {2} ({3})", Name, UUID, avatar.Name, avatar.UUID);
if (ParcelHideThisAvatar && currentParcelUUID != avatar.currentParcelUUID && !avatar.IsViewerUIGod)
return;
- avatar.ControllingClient.SendAvatarDataImmediate(this);
+ avatar.ControllingClient.SendEntityFullUpdateImmediate(this);
}
public void SendAvatarDataToAgentNF(ScenePresence avatar)
{
- avatar.ControllingClient.SendAvatarDataImmediate(this);
+ avatar.ControllingClient.SendEntityFullUpdateImmediate(this);
}
///
@@ -4353,72 +4432,75 @@ namespace OpenSim.Region.Framework.Scenes
}
- /* useless. Either use MakeChild or delete the presence
- public void Reset()
- {
- // m_log.DebugFormat("[SCENE PRESENCE]: Resetting {0} in {1}", Name, Scene.RegionInfo.RegionName);
-
- // Put the child agent back at the center
- AbsolutePosition
- = new Vector3(((float)m_scene.RegionInfo.RegionSizeX * 0.5f), ((float)m_scene.RegionInfo.RegionSizeY * 0.5f), 70);
-
- Animator.ResetAnimations();
- }
- */
///
/// Computes which child agents to close when the scene presence moves to another region.
/// Removes those regions from m_knownRegions.
///
- /// The new region's x on the map
- /// The new region's y on the map
+ /// The new region's handle
+ /// The new region's size x
+ /// The new region's size y
///
- public void CloseChildAgents(bool logout, ulong newRegionHandle, int newRegionSizeX, int newRegionSizeY)
+ public List GetChildAgentsToClose(ulong newRegionHandle, int newRegionSizeX, int newRegionSizeY)
{
- uint newRegionX, newRegionY;
+ ulong curRegionHandle = m_scene.RegionInfo.RegionHandle;
List byebyeRegions = new List();
+
+ if(newRegionHandle == curRegionHandle) //??
+ return byebyeRegions;
+
+ uint newRegionX, newRegionY;
List knownRegions = KnownRegionHandles;
m_log.DebugFormat(
"[SCENE PRESENCE]: Closing child agents. Checking {0} regions in {1}",
knownRegions.Count, Scene.RegionInfo.RegionName);
Util.RegionHandleToRegionLoc(newRegionHandle, out newRegionX, out newRegionY);
-
uint x, y;
spRegionSizeInfo regInfo;
foreach (ulong handle in knownRegions)
{
- // Don't close the agent on this region yet
- if (handle != Scene.RegionInfo.RegionHandle)
+ if(newRegionY == 0) // HG
+ byebyeRegions.Add(handle);
+ else if(handle == curRegionHandle)
{
- if (logout)
+ RegionInfo curreg = m_scene.RegionInfo;
+ if (Util.IsOutsideView(255, curreg.RegionLocX, newRegionX, curreg.RegionLocY, newRegionY,
+ (int)curreg.RegionSizeX, (int)curreg.RegionSizeX, newRegionSizeX, newRegionSizeY))
+ {
byebyeRegions.Add(handle);
+ }
+ }
+ else
+ {
+ Util.RegionHandleToRegionLoc(handle, out x, out y);
+ if (m_knownChildRegionsSizeInfo.TryGetValue(handle, out regInfo))
+ {
+// if (Util.IsOutsideView(RegionViewDistance, x, newRegionX, y, newRegionY,
+ // for now need to close all but first order bc RegionViewDistance it the target value not ours
+ if (Util.IsOutsideView(255, x, newRegionX, y, newRegionY,
+ regInfo.sizeX, regInfo.sizeY, newRegionSizeX, newRegionSizeY))
+ {
+ byebyeRegions.Add(handle);
+ }
+ }
else
{
- Util.RegionHandleToRegionLoc(handle, out x, out y);
- if (m_knownChildRegionsSizeInfo.TryGetValue(handle, out regInfo))
+// if (Util.IsOutsideView(RegionViewDistance, x, newRegionX, y, newRegionY,
+ if (Util.IsOutsideView(255, x, newRegionX, y, newRegionY,
+ (int)Constants.RegionSize, (int)Constants.RegionSize, newRegionSizeX, newRegionSizeY))
{
- if (Util.IsOutsideView(RegionViewDistance, x, newRegionX, y, newRegionY,
- regInfo.sizeX, regInfo.sizeY, newRegionSizeX, newRegionSizeY))
- {
- byebyeRegions.Add(handle);
- }
- }
- else
- {
- if (Util.IsOutsideView(RegionViewDistance, x, newRegionX, y, newRegionY,
- (int)Constants.RegionSize, (int)Constants.RegionSize, newRegionSizeX, newRegionSizeY))
- {
- byebyeRegions.Add(handle);
- // this should not be here
-// if(eventQueue != null)
-// eventQueue.DisableSimulator(handle,UUID);
- }
+ byebyeRegions.Add(handle);
}
}
}
}
+ return byebyeRegions;
+ }
+ public void CloseChildAgents(List byebyeRegions)
+ {
+ byebyeRegions.Remove(Scene.RegionInfo.RegionHandle);
if (byebyeRegions.Count > 0)
{
m_log.Debug("[SCENE PRESENCE]: Closing " + byebyeRegions.Count + " child agents");
@@ -4624,6 +4706,11 @@ namespace OpenSim.Region.Framework.Scenes
{
cAgent.CrossingFlags = crossingFlags;
cAgent.CrossingFlags |= 1;
+ cAgent.CrossExtraFlags = 0;
+ if((LastCommands & ScriptControlled.CONTROL_LBUTTON) != 0)
+ cAgent.CrossExtraFlags |= 1;
+ if((LastCommands & ScriptControlled.CONTROL_ML_LBUTTON) != 0)
+ cAgent.CrossExtraFlags |= 2;
}
else
cAgent.CrossingFlags = 0;
@@ -4633,7 +4720,10 @@ namespace OpenSim.Region.Framework.Scenes
cAgent.agentCOF = COF;
cAgent.ActiveGroupID = ControllingClient.ActiveGroupId;
cAgent.ActiveGroupName = ControllingClient.ActiveGroupName;
- cAgent.ActiveGroupTitle = Grouptitle;
+ if(Grouptitle == null)
+ cAgent.ActiveGroupTitle = String.Empty;
+ else
+ cAgent.ActiveGroupTitle = Grouptitle;
}
}
@@ -4735,6 +4825,15 @@ namespace OpenSim.Region.Framework.Scenes
crossingFlags = cAgent.CrossingFlags;
gotCrossUpdate = (crossingFlags != 0);
+ if(gotCrossUpdate)
+ {
+ LastCommands &= ~(ScriptControlled.CONTROL_LBUTTON | ScriptControlled.CONTROL_ML_LBUTTON);
+ if((cAgent.CrossExtraFlags & 1) != 0)
+ LastCommands |= ScriptControlled.CONTROL_LBUTTON;
+ if((cAgent.CrossExtraFlags & 2) != 0)
+ LastCommands |= ScriptControlled.CONTROL_ML_LBUTTON;
+ MouseDown = (cAgent.CrossExtraFlags & 3) != 0;
+ }
haveGroupInformation = false;
// using this as protocol detection don't want to mess with the numbers for now
@@ -4829,6 +4928,7 @@ namespace OpenSim.Region.Framework.Scenes
PhysicsActor.OnOutOfBounds += OutOfBoundsCall; // Called for PhysicsActors when there's something wrong
PhysicsActor.SubscribeEvents(100);
PhysicsActor.LocalID = LocalId;
+ PhysicsActor.SetAlwaysRun = m_setAlwaysRun;
}
private void OutOfBoundsCall(Vector3 pos)
@@ -4866,8 +4966,8 @@ namespace OpenSim.Region.Framework.Scenes
// if (m_updateCount > 0)
// {
- if (Animator != null && Animator.UpdateMovementAnimations())
- TriggerScenePresenceUpdated();
+// if (Animator != null && Animator.UpdateMovementAnimations())
+// TriggerScenePresenceUpdated();
// m_updateCount--;
// }
@@ -5703,29 +5803,21 @@ namespace OpenSim.Region.Framework.Scenes
if (scriptedcontrols.Count <= 0)
return;
- ScriptControlled allflags = ScriptControlled.CONTROL_ZERO;
-
- if (MouseDown)
+ ScriptControlled allflags;
+ // convert mouse from edge to level
+ if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_UP) != 0 ||
+ (flags & unchecked((uint)AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_UP)) != 0)
{
- allflags = LastCommands & (ScriptControlled.CONTROL_ML_LBUTTON | ScriptControlled.CONTROL_LBUTTON);
- if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_UP) != 0 || (flags & unchecked((uint)AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_UP)) != 0)
- {
- allflags = ScriptControlled.CONTROL_ZERO;
- MouseDown = true;
- }
+ allflags = ScriptControlled.CONTROL_ZERO;
}
+ else // recover last state of mouse
+ allflags = LastCommands & (ScriptControlled.CONTROL_ML_LBUTTON | ScriptControlled.CONTROL_LBUTTON);
if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_DOWN) != 0)
- {
allflags |= ScriptControlled.CONTROL_ML_LBUTTON;
- MouseDown = true;
- }
if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN) != 0)
- {
allflags |= ScriptControlled.CONTROL_LBUTTON;
- MouseDown = true;
- }
// find all activated controls, whether the scripts are interested in them or not
if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_AT_POS) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS) != 0)
@@ -5789,6 +5881,7 @@ namespace OpenSim.Region.Framework.Scenes
}
LastCommands = allflags;
+ MouseDown = (allflags & (ScriptControlled.CONTROL_ML_LBUTTON | ScriptControlled.CONTROL_LBUTTON)) != 0;
}
}
@@ -6440,7 +6533,7 @@ namespace OpenSim.Region.Framework.Scenes
if (check)
{
// check is relative to current parcel only
- if (currentParcelUUID == null || oldhide == currentParcelHide)
+ if (oldhide == currentParcelHide)
return;
allpresences = m_scene.GetScenePresences();
diff --git a/OpenSim/Region/Framework/Scenes/Serialization/CoalescedSceneObjectsSerializer.cs b/OpenSim/Region/Framework/Scenes/Serialization/CoalescedSceneObjectsSerializer.cs
index 7f7977ea25..41f3ef4020 100644
--- a/OpenSim/Region/Framework/Scenes/Serialization/CoalescedSceneObjectsSerializer.cs
+++ b/OpenSim/Region/Framework/Scenes/Serialization/CoalescedSceneObjectsSerializer.cs
@@ -86,9 +86,9 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
writer.WriteStartElement("CoalescedObject");
- writer.WriteAttributeString("x", size.X.ToString());
- writer.WriteAttributeString("y", size.Y.ToString());
- writer.WriteAttributeString("z", size.Z.ToString());
+ writer.WriteAttributeString("x", size.X.ToString(Culture.FormatProvider));
+ writer.WriteAttributeString("y", size.Y.ToString(Culture.FormatProvider));
+ writer.WriteAttributeString("z", size.Z.ToString(Culture.FormatProvider));
// Embed the offsets into the group XML
for (int i = 0; i < coaObjects.Count; i++)
@@ -100,9 +100,9 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
// i, obj.Name);
writer.WriteStartElement("SceneObjectGroup");
- writer.WriteAttributeString("offsetx", offsets[i].X.ToString());
- writer.WriteAttributeString("offsety", offsets[i].Y.ToString());
- writer.WriteAttributeString("offsetz", offsets[i].Z.ToString());
+ writer.WriteAttributeString("offsetx", offsets[i].X.ToString(Culture.FormatProvider));
+ writer.WriteAttributeString("offsety", offsets[i].Y.ToString(Culture.FormatProvider));
+ writer.WriteAttributeString("offsetz", offsets[i].Z.ToString(Culture.FormatProvider));
SceneObjectSerializer.ToOriginalXmlFormat(obj, writer, doScriptStates);
diff --git a/OpenSim/Region/Framework/Scenes/Serialization/SceneObjectSerializer.cs b/OpenSim/Region/Framework/Scenes/Serialization/SceneObjectSerializer.cs
index b8d210cac6..82bbe6f384 100644
--- a/OpenSim/Region/Framework/Scenes/Serialization/SceneObjectSerializer.cs
+++ b/OpenSim/Region/Framework/Scenes/Serialization/SceneObjectSerializer.cs
@@ -65,7 +65,8 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
{
using (XmlReader reader = XmlReader.Create(wrappedReader, new XmlReaderSettings() { IgnoreWhitespace = true, ConformanceLevel = ConformanceLevel.Fragment }))
{
- try {
+ try
+ {
return FromOriginalXmlFormat(reader);
}
catch (Exception e)
@@ -109,12 +110,24 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
}
}
while (reader.ReadToNextSibling("Part"));
+ reader.ReadEndElement();
}
+ if (reader.Name == "KeyframeMotion" && reader.NodeType == XmlNodeType.Element)
+ {
+
+ string innerkeytxt = reader.ReadElementContentAsString();
+ sceneObject.RootPart.KeyframeMotion =
+ KeyframeMotion.FromData(sceneObject, Convert.FromBase64String(innerkeytxt));
+ }
+ else
+ sceneObject.RootPart.KeyframeMotion = null;
+
// Script state may, or may not, exist. Not having any, is NOT
// ever a problem.
sceneObject.LoadScriptState(reader);
+ sceneObject.InvalidateDeepEffectivePerms();
return sceneObject;
}
@@ -210,9 +223,19 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
writer.WriteEndElement(); // OtherParts
+ if (sceneObject.RootPart.KeyframeMotion != null)
+ {
+ Byte[] data = sceneObject.RootPart.KeyframeMotion.Serialize();
+
+ writer.WriteStartElement(String.Empty, "KeyframeMotion", String.Empty);
+ writer.WriteBase64(data, 0, data.Length);
+ writer.WriteEndElement();
+ }
+
if (doScriptStates)
sceneObject.SaveScriptedState(writer);
+
if (!noRootElement)
writer.WriteEndElement(); // SceneObjectGroup
@@ -278,7 +301,7 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
// Script state may, or may not, exist. Not having any, is NOT
// ever a problem.
sceneObject.LoadScriptState(doc);
-
+// sceneObject.AggregatePerms();
return sceneObject;
}
catch (Exception e)
@@ -453,9 +476,10 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
m_SOPXmlProcessors.Add("Torque", ProcessTorque);
m_SOPXmlProcessors.Add("VolumeDetectActive", ProcessVolumeDetectActive);
-
m_SOPXmlProcessors.Add("Vehicle", ProcessVehicle);
+ m_SOPXmlProcessors.Add("PhysicsInertia", ProcessPhysicsInertia);
+
m_SOPXmlProcessors.Add("RotationAxisLocks", ProcessRotationAxisLocks);
m_SOPXmlProcessors.Add("PhysicsShapeType", ProcessPhysicsShapeType);
m_SOPXmlProcessors.Add("Density", ProcessDensity);
@@ -781,6 +805,23 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
}
}
+ private static void ProcessPhysicsInertia(SceneObjectPart obj, XmlReader reader)
+ {
+ PhysicsInertiaData pdata = PhysicsInertiaData.FromXml2(reader);
+
+ if (pdata == null)
+ {
+ obj.PhysicsInertia = null;
+ m_log.DebugFormat(
+ "[SceneObjectSerializer]: Parsing PhysicsInertiaData for object part {0} {1} encountered errors. Please see earlier log entries.",
+ obj.Name, obj.UUID);
+ }
+ else
+ {
+ obj.PhysicsInertia = pdata;
+ }
+ }
+
private static void ProcessShape(SceneObjectPart obj, XmlReader reader)
{
List errorNodeNames;
@@ -1343,8 +1384,27 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
private static void ProcessShpMedia(PrimitiveBaseShape shp, XmlReader reader)
{
- string value = reader.ReadElementContentAsString("Media", String.Empty);
- shp.Media = PrimitiveBaseShape.MediaList.FromXml(value);
+ string value = String.Empty;
+ try
+ {
+ // The STANDARD content of Media elemet is escaped XML string (with > etc).
+ value = reader.ReadElementContentAsString("Media", String.Empty);
+ shp.Media = PrimitiveBaseShape.MediaList.FromXml(value);
+ }
+ catch (XmlException e)
+ {
+ // There are versions of OAR files that contain unquoted XML.
+ // ie ONE comercial fork that never wanted their oars to be read by our code
+ try
+ {
+ value = reader.ReadInnerXml();
+ shp.Media = PrimitiveBaseShape.MediaList.FromXml(value);
+ }
+ catch
+ {
+ m_log.ErrorFormat("[SERIALIZER] Failed parsing halcyon MOAP information");
+ }
+ }
}
#endregion
@@ -1422,10 +1482,10 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
writer.WriteElementString("Description", sop.Description);
writer.WriteStartElement("Color");
- writer.WriteElementString("R", sop.Color.R.ToString(Utils.EnUsCulture));
- writer.WriteElementString("G", sop.Color.G.ToString(Utils.EnUsCulture));
- writer.WriteElementString("B", sop.Color.B.ToString(Utils.EnUsCulture));
- writer.WriteElementString("A", sop.Color.A.ToString(Utils.EnUsCulture));
+ writer.WriteElementString("R", sop.Color.R.ToString(Culture.FormatProvider));
+ writer.WriteElementString("G", sop.Color.G.ToString(Culture.FormatProvider));
+ writer.WriteElementString("B", sop.Color.B.ToString(Culture.FormatProvider));
+ writer.WriteElementString("A", sop.Color.A.ToString(Culture.FormatProvider));
writer.WriteEndElement();
writer.WriteElementString("Text", sop.Text);
@@ -1468,7 +1528,7 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
writer.WriteElementString("NextOwnerMask", sop.NextOwnerMask.ToString());
WriteFlags(writer, "Flags", sop.Flags.ToString(), options);
WriteUUID(writer, "CollisionSound", sop.CollisionSound, options);
- writer.WriteElementString("CollisionSoundVolume", sop.CollisionSoundVolume.ToString());
+ writer.WriteElementString("CollisionSoundVolume", sop.CollisionSoundVolume.ToString(Culture.FormatProvider));
if (sop.MediaUrl != null)
writer.WriteElementString("MediaUrl", sop.MediaUrl.ToString());
WriteVector(writer, "AttachedPos", sop.AttachedPos);
@@ -1488,7 +1548,7 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
writer.WriteElementString("PayPrice3", sop.PayPrice[3].ToString());
writer.WriteElementString("PayPrice4", sop.PayPrice[4].ToString());
- writer.WriteElementString("Buoyancy", sop.Buoyancy.ToString());
+ writer.WriteElementString("Buoyancy", sop.Buoyancy.ToString(Culture.FormatProvider));
WriteVector(writer, "Force", sop.Force);
WriteVector(writer, "Torque", sop.Torque);
@@ -1498,26 +1558,29 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
if (sop.VehicleParams != null)
sop.VehicleParams.ToXml2(writer);
+ if (sop.PhysicsInertia != null)
+ sop.PhysicsInertia.ToXml2(writer);
+
if(sop.RotationAxisLocks != 0)
writer.WriteElementString("RotationAxisLocks", sop.RotationAxisLocks.ToString().ToLower());
writer.WriteElementString("PhysicsShapeType", sop.PhysicsShapeType.ToString().ToLower());
if (sop.Density != 1000.0f)
- writer.WriteElementString("Density", sop.Density.ToString().ToLower());
+ writer.WriteElementString("Density", sop.Density.ToString(Culture.FormatProvider));
if (sop.Friction != 0.6f)
- writer.WriteElementString("Friction", sop.Friction.ToString().ToLower());
+ writer.WriteElementString("Friction", sop.Friction.ToString(Culture.FormatProvider));
if (sop.Restitution != 0.5f)
- writer.WriteElementString("Bounce", sop.Restitution.ToString().ToLower());
+ writer.WriteElementString("Bounce", sop.Restitution.ToString(Culture.FormatProvider));
if (sop.GravityModifier != 1.0f)
- writer.WriteElementString("GravityModifier", sop.GravityModifier.ToString().ToLower());
+ writer.WriteElementString("GravityModifier", sop.GravityModifier.ToString(Culture.FormatProvider));
WriteVector(writer, "CameraEyeOffset", sop.GetCameraEyeOffset());
WriteVector(writer, "CameraAtOffset", sop.GetCameraAtOffset());
// if (sop.Sound != UUID.Zero) force it till sop crossing does clear it on child prim
{
WriteUUID(writer, "SoundID", sop.Sound, options);
- writer.WriteElementString("SoundGain", sop.SoundGain.ToString().ToLower());
+ writer.WriteElementString("SoundGain", sop.SoundGain.ToString(Culture.FormatProvider));
writer.WriteElementString("SoundFlags", sop.SoundFlags.ToString().ToLower());
- writer.WriteElementString("SoundRadius", sop.SoundRadius.ToString().ToLower());
+ writer.WriteElementString("SoundRadius", sop.SoundRadius.ToString(Culture.FormatProvider));
}
writer.WriteElementString("SoundQueueing", sop.SoundQueueing.ToString().ToLower());
@@ -1537,19 +1600,19 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
static void WriteVector(XmlTextWriter writer, string name, Vector3 vec)
{
writer.WriteStartElement(name);
- writer.WriteElementString("X", vec.X.ToString(Utils.EnUsCulture));
- writer.WriteElementString("Y", vec.Y.ToString(Utils.EnUsCulture));
- writer.WriteElementString("Z", vec.Z.ToString(Utils.EnUsCulture));
+ writer.WriteElementString("X", vec.X.ToString(Culture.FormatProvider));
+ writer.WriteElementString("Y", vec.Y.ToString(Culture.FormatProvider));
+ writer.WriteElementString("Z", vec.Z.ToString(Culture.FormatProvider));
writer.WriteEndElement();
}
static void WriteQuaternion(XmlTextWriter writer, string name, Quaternion quat)
{
writer.WriteStartElement(name);
- writer.WriteElementString("X", quat.X.ToString(Utils.EnUsCulture));
- writer.WriteElementString("Y", quat.Y.ToString(Utils.EnUsCulture));
- writer.WriteElementString("Z", quat.Z.ToString(Utils.EnUsCulture));
- writer.WriteElementString("W", quat.W.ToString(Utils.EnUsCulture));
+ writer.WriteElementString("X", quat.X.ToString(Culture.FormatProvider));
+ writer.WriteElementString("Y", quat.Y.ToString(Culture.FormatProvider));
+ writer.WriteElementString("Z", quat.Z.ToString(Culture.FormatProvider));
+ writer.WriteElementString("W", quat.W.ToString(Culture.FormatProvider));
writer.WriteEndElement();
}
@@ -1691,22 +1754,22 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
// Don't serialize SculptData. It's just a copy of the asset, which can be loaded separately using 'SculptTexture'.
writer.WriteElementString("FlexiSoftness", shp.FlexiSoftness.ToString());
- writer.WriteElementString("FlexiTension", shp.FlexiTension.ToString());
- writer.WriteElementString("FlexiDrag", shp.FlexiDrag.ToString());
- writer.WriteElementString("FlexiGravity", shp.FlexiGravity.ToString());
- writer.WriteElementString("FlexiWind", shp.FlexiWind.ToString());
- writer.WriteElementString("FlexiForceX", shp.FlexiForceX.ToString());
- writer.WriteElementString("FlexiForceY", shp.FlexiForceY.ToString());
- writer.WriteElementString("FlexiForceZ", shp.FlexiForceZ.ToString());
+ writer.WriteElementString("FlexiTension", shp.FlexiTension.ToString(Culture.FormatProvider));
+ writer.WriteElementString("FlexiDrag", shp.FlexiDrag.ToString(Culture.FormatProvider));
+ writer.WriteElementString("FlexiGravity", shp.FlexiGravity.ToString(Culture.FormatProvider));
+ writer.WriteElementString("FlexiWind", shp.FlexiWind.ToString(Culture.FormatProvider));
+ writer.WriteElementString("FlexiForceX", shp.FlexiForceX.ToString(Culture.FormatProvider));
+ writer.WriteElementString("FlexiForceY", shp.FlexiForceY.ToString(Culture.FormatProvider));
+ writer.WriteElementString("FlexiForceZ", shp.FlexiForceZ.ToString(Culture.FormatProvider));
- writer.WriteElementString("LightColorR", shp.LightColorR.ToString());
- writer.WriteElementString("LightColorG", shp.LightColorG.ToString());
- writer.WriteElementString("LightColorB", shp.LightColorB.ToString());
- writer.WriteElementString("LightColorA", shp.LightColorA.ToString());
- writer.WriteElementString("LightRadius", shp.LightRadius.ToString());
- writer.WriteElementString("LightCutoff", shp.LightCutoff.ToString());
- writer.WriteElementString("LightFalloff", shp.LightFalloff.ToString());
- writer.WriteElementString("LightIntensity", shp.LightIntensity.ToString());
+ writer.WriteElementString("LightColorR", shp.LightColorR.ToString(Culture.FormatProvider));
+ writer.WriteElementString("LightColorG", shp.LightColorG.ToString(Culture.FormatProvider));
+ writer.WriteElementString("LightColorB", shp.LightColorB.ToString(Culture.FormatProvider));
+ writer.WriteElementString("LightColorA", shp.LightColorA.ToString(Culture.FormatProvider));
+ writer.WriteElementString("LightRadius", shp.LightRadius.ToString(Culture.FormatProvider));
+ writer.WriteElementString("LightCutoff", shp.LightCutoff.ToString(Culture.FormatProvider));
+ writer.WriteElementString("LightFalloff", shp.LightFalloff.ToString(Culture.FormatProvider));
+ writer.WriteElementString("LightIntensity", shp.LightIntensity.ToString(Culture.FormatProvider));
writer.WriteElementString("FlexiEntry", shp.FlexiEntry.ToString().ToLower());
writer.WriteElementString("LightEntry", shp.LightEntry.ToString().ToLower());
@@ -1739,6 +1802,7 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
reader.ReadEndElement(); // SceneObjectPart
+ obj.AggregateInnerPerms();
// m_log.DebugFormat("[SceneObjectSerializer]: parsed SOP {0} {1}", obj.Name, obj.UUID);
return obj;
}
diff --git a/OpenSim/Region/Framework/Scenes/Serialization/SceneXmlLoader.cs b/OpenSim/Region/Framework/Scenes/Serialization/SceneXmlLoader.cs
index 01bc491566..34fdb6df8f 100644
--- a/OpenSim/Region/Framework/Scenes/Serialization/SceneXmlLoader.cs
+++ b/OpenSim/Region/Framework/Scenes/Serialization/SceneXmlLoader.cs
@@ -70,6 +70,7 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
//obj.RegenerateFullIDs();
scene.AddNewSceneObject(obj, true);
+ obj.InvalidateDeepEffectivePerms();
}
}
else
diff --git a/OpenSim/Region/Framework/Scenes/Tests/SceneGraphTests.cs b/OpenSim/Region/Framework/Scenes/Tests/SceneGraphTests.cs
index 56723bfd95..4d2eb3fe89 100644
--- a/OpenSim/Region/Framework/Scenes/Tests/SceneGraphTests.cs
+++ b/OpenSim/Region/Framework/Scenes/Tests/SceneGraphTests.cs
@@ -67,7 +67,7 @@ namespace OpenSim.Region.Framework.Scenes.Tests
SceneObjectGroup dupeSo
= scene.SceneGraph.DuplicateObject(
- part1.LocalId, new Vector3(10, 0, 0), 0, ownerId, UUID.Zero, Quaternion.Identity);
+ part1.LocalId, new Vector3(10, 0, 0), ownerId, UUID.Zero, Quaternion.Identity, false);
Assert.That(dupeSo.Parts.Length, Is.EqualTo(2));
SceneObjectPart dupePart1 = dupeSo.GetLinkNumPart(1);
diff --git a/OpenSim/Region/Framework/Scenes/Tests/SceneObjectCrossingTests.cs b/OpenSim/Region/Framework/Scenes/Tests/SceneObjectCrossingTests.cs
index e1e973cdd3..abf8c488c5 100644
--- a/OpenSim/Region/Framework/Scenes/Tests/SceneObjectCrossingTests.cs
+++ b/OpenSim/Region/Framework/Scenes/Tests/SceneObjectCrossingTests.cs
@@ -157,29 +157,28 @@ namespace OpenSim.Region.Framework.Scenes.Tests
// Cross
sceneA.SceneGraph.UpdatePrimGroupPosition(
- so1.LocalId, new Vector3(so1StartPos.X, so1StartPos.Y - 20, so1StartPos.Z), userId);
+ so1.LocalId, new Vector3(so1StartPos.X, so1StartPos.Y - 20, so1StartPos.Z), sp1SceneA.ControllingClient);
// crossing is async
Thread.Sleep(500);
SceneObjectGroup so1PostCross;
- {
- ScenePresence sp1SceneAPostCross = sceneA.GetScenePresence(userId);
- Assert.IsTrue(sp1SceneAPostCross.IsChildAgent, "sp1SceneAPostCross.IsChildAgent unexpectedly false");
+ ScenePresence sp1SceneAPostCross = sceneA.GetScenePresence(userId);
+ Assert.IsTrue(sp1SceneAPostCross.IsChildAgent, "sp1SceneAPostCross.IsChildAgent unexpectedly false");
- ScenePresence sp1SceneBPostCross = sceneB.GetScenePresence(userId);
- TestClient sceneBTc = ((TestClient)sp1SceneBPostCross.ControllingClient);
- sceneBTc.CompleteMovement();
+ ScenePresence sp1SceneBPostCross = sceneB.GetScenePresence(userId);
+ TestClient sceneBTc = ((TestClient)sp1SceneBPostCross.ControllingClient);
+ sceneBTc.CompleteMovement();
- Assert.IsFalse(sp1SceneBPostCross.IsChildAgent, "sp1SceneAPostCross.IsChildAgent unexpectedly true");
- Assert.IsTrue(sp1SceneBPostCross.IsSatOnObject);
+ Assert.IsFalse(sp1SceneBPostCross.IsChildAgent, "sp1SceneAPostCross.IsChildAgent unexpectedly true");
+ Assert.IsTrue(sp1SceneBPostCross.IsSatOnObject);
+
+ Assert.IsNull(sceneA.GetSceneObjectGroup(so1Id), "uck");
+ so1PostCross = sceneB.GetSceneObjectGroup(so1Id);
+ Assert.NotNull(so1PostCross);
+ Assert.AreEqual(1, so1PostCross.GetSittingAvatarsCount());
- Assert.IsNull(sceneA.GetSceneObjectGroup(so1Id), "uck");
- so1PostCross = sceneB.GetSceneObjectGroup(so1Id);
- Assert.NotNull(so1PostCross);
- Assert.AreEqual(1, so1PostCross.GetSittingAvatarsCount());
- }
Vector3 so1PostCrossPos = so1PostCross.AbsolutePosition;
@@ -187,7 +186,7 @@ namespace OpenSim.Region.Framework.Scenes.Tests
// Recross
sceneB.SceneGraph.UpdatePrimGroupPosition(
- so1PostCross.LocalId, new Vector3(so1PostCrossPos.X, so1PostCrossPos.Y + 20, so1PostCrossPos.Z), userId);
+ so1PostCross.LocalId, new Vector3(so1PostCrossPos.X, so1PostCrossPos.Y + 20, so1PostCrossPos.Z), sp1SceneBPostCross.ControllingClient);
// crossing is async
Thread.Sleep(500);
@@ -255,13 +254,19 @@ namespace OpenSim.Region.Framework.Scenes.Tests
lmmA.EventManagerOnNoLandDataFromStorage();
lmmB.EventManagerOnNoLandDataFromStorage();
+ AgentCircuitData acd = SceneHelpers.GenerateAgentData(userId);
+ TestClient tc = new TestClient(acd, sceneA);
+ List destinationTestClients = new List();
+ EntityTransferHelpers.SetupInformClientOfNeighbourTriggersNeighbourClientCreate(tc, destinationTestClients);
+ ScenePresence sp1SceneA = SceneHelpers.AddScenePresence(sceneA, tc, acd);
+
SceneObjectGroup so1 = SceneHelpers.AddSceneObject(sceneA, 1, userId, "", sceneObjectIdTail);
UUID so1Id = so1.UUID;
so1.AbsolutePosition = new Vector3(128, 10, 20);
// Cross with a negative value. We must make this call rather than setting AbsolutePosition directly
// because only this will execute permission checks in the source region.
- sceneA.SceneGraph.UpdatePrimGroupPosition(so1.LocalId, new Vector3(128, -10, 20), userId);
+ sceneA.SceneGraph.UpdatePrimGroupPosition(so1.LocalId, new Vector3(128, -10, 20), sp1SceneA.ControllingClient);
// crossing is async
Thread.Sleep(500);
diff --git a/OpenSim/Region/Framework/Scenes/Tests/ScenePresenceAnimationTests.cs b/OpenSim/Region/Framework/Scenes/Tests/ScenePresenceAnimationTests.cs
index 42d91b954a..d650c4346d 100644
--- a/OpenSim/Region/Framework/Scenes/Tests/ScenePresenceAnimationTests.cs
+++ b/OpenSim/Region/Framework/Scenes/Tests/ScenePresenceAnimationTests.cs
@@ -60,7 +60,7 @@ namespace OpenSim.Region.Framework.Scenes.Tests
TestScene scene = new SceneHelpers().SetupScene();
ScenePresence sp = SceneHelpers.AddScenePresence(scene, TestHelpers.ParseTail(0x1));
sp.Flying = true;
- sp.PhysicsCollisionUpdate(new CollisionEventUpdate());
+ sp.Animator.UpdateMovementAnimations();
Assert.That(sp.Animator.CurrentMovementAnimation, Is.EqualTo("HOVER"));
}
diff --git a/OpenSim/Region/Framework/Scenes/Tests/SceneStatisticsTests.cs b/OpenSim/Region/Framework/Scenes/Tests/SceneStatisticsTests.cs
index 045fd3cec5..4ce6a95f36 100644
--- a/OpenSim/Region/Framework/Scenes/Tests/SceneStatisticsTests.cs
+++ b/OpenSim/Region/Framework/Scenes/Tests/SceneStatisticsTests.cs
@@ -54,8 +54,8 @@ namespace OpenSim.Region.Framework.Scenes.Tests
UUID ownerId = TestHelpers.ParseTail(0x1);
SceneObjectGroup so1 = SceneHelpers.CreateSceneObject(3, ownerId, "so1", 0x10);
- so1.ScriptSetPhysicsStatus(true);
m_scene.AddSceneObject(so1);
+ so1.ScriptSetPhysicsStatus(true);
Assert.That(m_scene.SceneGraph.GetTotalObjectsCount(), Is.EqualTo(3));
Assert.That(m_scene.SceneGraph.GetActiveObjectsCount(), Is.EqualTo(3));
diff --git a/OpenSim/Region/Framework/Scenes/UuidGatherer.cs b/OpenSim/Region/Framework/Scenes/UuidGatherer.cs
index 93406cbb79..80d3f62339 100644
--- a/OpenSim/Region/Framework/Scenes/UuidGatherer.cs
+++ b/OpenSim/Region/Framework/Scenes/UuidGatherer.cs
@@ -65,7 +65,10 @@ namespace OpenSim.Region.Framework.Scenes
///
/// The gathered uuids.
public IDictionary GatheredUuids { get; private set; }
-
+ public HashSet FailedUUIDs { get; private set; }
+ public HashSet UncertainAssetsUUIDs { get; private set; }
+ public int possibleNotAssetCount { get; set; }
+ public int ErrorCount { get; private set; }
///
/// Gets the next UUID to inspect.
///
@@ -92,7 +95,10 @@ namespace OpenSim.Region.Framework.Scenes
///
/// Asset service.
///
- public UuidGatherer(IAssetService assetService) : this(assetService, new Dictionary()) {}
+ public UuidGatherer(IAssetService assetService) : this(assetService, new Dictionary(),
+ new HashSet (),new HashSet ()) {}
+ public UuidGatherer(IAssetService assetService, IDictionary collector) : this(assetService, collector,
+ new HashSet (), new HashSet ()) {}
///
/// Initializes a new instance of the class.
@@ -101,16 +107,20 @@ namespace OpenSim.Region.Framework.Scenes
/// Asset service.
///
///
- /// Gathered UUIDs will be collected in this dictinaory.
+ /// Gathered UUIDs will be collected in this dictionary.
/// It can be pre-populated if you want to stop the gatherer from analyzing assets that have already been fetched and inspected.
///
- public UuidGatherer(IAssetService assetService, IDictionary collector)
+ public UuidGatherer(IAssetService assetService, IDictionary collector, HashSet failedIDs, HashSet uncertainAssetsUUIDs)
{
m_assetService = assetService;
GatheredUuids = collector;
// FIXME: Not efficient for searching, can improve.
m_assetUuidsToInspect = new Queue();
+ FailedUUIDs = failedIDs;
+ UncertainAssetsUUIDs = uncertainAssetsUUIDs;
+ ErrorCount = 0;
+ possibleNotAssetCount = 0;
}
///
@@ -120,6 +130,19 @@ namespace OpenSim.Region.Framework.Scenes
/// UUID.
public bool AddForInspection(UUID uuid)
{
+ if(uuid == UUID.Zero)
+ return false;
+
+ if(FailedUUIDs.Contains(uuid))
+ {
+ if(UncertainAssetsUUIDs.Contains(uuid))
+ possibleNotAssetCount++;
+ else
+ ErrorCount++;
+ return false;
+ }
+ if(GatheredUuids.ContainsKey(uuid))
+ return false;
if (m_assetUuidsToInspect.Contains(uuid))
return false;
@@ -141,7 +164,9 @@ namespace OpenSim.Region.Framework.Scenes
public void AddForInspection(SceneObjectGroup sceneObject)
{
// m_log.DebugFormat(
- // "[ASSET GATHERER]: Getting assets for object {0}, {1}", sceneObject.Name, sceneObject.UUID);
+ // "[UUID GATHERER]: Getting assets for object {0}, {1}", sceneObject.Name, sceneObject.UUID);
+ if(sceneObject.IsDeleted)
+ return;
SceneObjectPart[] parts = sceneObject.Parts;
for (int i = 0; i < parts.Length; i++)
@@ -149,7 +174,7 @@ namespace OpenSim.Region.Framework.Scenes
SceneObjectPart part = parts[i];
// m_log.DebugFormat(
- // "[ARCHIVER]: Getting part {0}, {1} for object {2}", part.Name, part.UUID, sceneObject.UUID);
+ // "[UUID GATHERER]: Getting part {0}, {1} for object {2}", part.Name, part.UUID, sceneObject.UUID);
try
{
@@ -207,9 +232,7 @@ namespace OpenSim.Region.Framework.Scenes
// m_log.DebugFormat(
// "[ARCHIVER]: Analysing item {0} asset type {1} in {2} {3}",
// tii.Name, tii.Type, part.Name, part.UUID);
-
- if (!GatheredUuids.ContainsKey(tii.AssetID))
- AddForInspection(tii.AssetID, (sbyte)tii.Type);
+ AddForInspection(tii.AssetID, (sbyte)tii.Type);
}
// FIXME: We need to make gathering modular but we cannot yet, since gatherers are not guaranteed
@@ -225,9 +248,6 @@ namespace OpenSim.Region.Framework.Scenes
catch (Exception e)
{
m_log.ErrorFormat("[UUID GATHERER]: Failed to get part - {0}", e);
- m_log.DebugFormat(
- "[UUID GATHERER]: Texture entry length for prim was {0} (min is 46)",
- part.Shape.TextureEntry.Length);
}
}
}
@@ -278,55 +298,112 @@ namespace OpenSim.Region.Framework.Scenes
/// The uuid of the asset for which to gather referenced assets
private void GetAssetUuids(UUID assetUuid)
{
+ if(assetUuid == UUID.Zero)
+ return;
+
+ if(FailedUUIDs.Contains(assetUuid))
+ {
+ if(UncertainAssetsUUIDs.Contains(assetUuid))
+ possibleNotAssetCount++;
+ else
+ ErrorCount++;
+ return;
+ }
+
// avoid infinite loops
if (GatheredUuids.ContainsKey(assetUuid))
return;
+ AssetBase assetBase;
try
{
- AssetBase assetBase = GetAsset(assetUuid);
+ assetBase = GetAsset(assetUuid);
+ }
+ catch (Exception e)
+ {
+ m_log.ErrorFormat("[UUID GATHERER]: Failed to get asset {0} : {1}", assetUuid, e.Message);
+ ErrorCount++;
+ FailedUUIDs.Add(assetUuid);
+ return;
+ }
- if (null != assetBase)
+ if(assetBase == null)
+ {
+// m_log.ErrorFormat("[UUID GATHERER]: asset {0} not found", assetUuid);
+ FailedUUIDs.Add(assetUuid);
+ if(UncertainAssetsUUIDs.Contains(assetUuid))
+ possibleNotAssetCount++;
+ else
+ ErrorCount++;
+ return;
+ }
+
+ if(UncertainAssetsUUIDs.Contains(assetUuid))
+ UncertainAssetsUUIDs.Remove(assetUuid);
+
+ sbyte assetType = assetBase.Type;
+
+ if(assetBase.Data == null || assetBase.Data.Length == 0)
+ {
+// m_log.ErrorFormat("[UUID GATHERER]: asset {0}, type {1} has no data", assetUuid, assetType);
+ ErrorCount++;
+ FailedUUIDs.Add(assetUuid);
+ return;
+ }
+
+ GatheredUuids[assetUuid] = assetType;
+ try
+ {
+ if ((sbyte)AssetType.Bodypart == assetType || (sbyte)AssetType.Clothing == assetType)
{
- sbyte assetType = assetBase.Type;
- GatheredUuids[assetUuid] = assetType;
-
- if ((sbyte)AssetType.Bodypart == assetType || (sbyte)AssetType.Clothing == assetType)
- {
- RecordWearableAssetUuids(assetBase);
- }
- else if ((sbyte)AssetType.Gesture == assetType)
- {
- RecordGestureAssetUuids(assetBase);
- }
- else if ((sbyte)AssetType.Notecard == assetType)
- {
- RecordTextEmbeddedAssetUuids(assetBase);
- }
- else if ((sbyte)AssetType.LSLText == assetType)
- {
- RecordTextEmbeddedAssetUuids(assetBase);
- }
- else if ((sbyte)OpenSimAssetType.Material == assetType)
- {
- RecordMaterialAssetUuids(assetBase);
- }
- else if ((sbyte)AssetType.Object == assetType)
- {
- RecordSceneObjectAssetUuids(assetBase);
- }
+ RecordWearableAssetUuids(assetBase);
+ }
+ else if ((sbyte)AssetType.Gesture == assetType)
+ {
+ RecordGestureAssetUuids(assetBase);
+ }
+ else if ((sbyte)AssetType.Notecard == assetType)
+ {
+ RecordTextEmbeddedAssetUuids(assetBase);
+ }
+ else if ((sbyte)AssetType.LSLText == assetType)
+ {
+ RecordTextEmbeddedAssetUuids(assetBase);
+ }
+ else if ((sbyte)OpenSimAssetType.Material == assetType)
+ {
+ RecordMaterialAssetUuids(assetBase);
+ }
+ else if ((sbyte)AssetType.Object == assetType)
+ {
+ RecordSceneObjectAssetUuids(assetBase);
}
}
- catch (Exception)
+ catch (Exception e)
{
- m_log.ErrorFormat("[UUID GATHERER]: Failed to gather uuids for asset id {0}", assetUuid);
- throw;
+ m_log.ErrorFormat("[UUID GATHERER]: Failed to gather uuids for asset with id {0} type {1}: {2}", assetUuid, assetType, e.Message);
+ GatheredUuids.Remove(assetUuid);
+ ErrorCount++;
+ FailedUUIDs.Add(assetUuid);
}
}
private void AddForInspection(UUID assetUuid, sbyte assetType)
{
+ if(assetUuid == UUID.Zero)
+ return;
+
// Here, we want to collect uuids which require further asset fetches but mark the others as gathered
+ if(FailedUUIDs.Contains(assetUuid))
+ {
+ if(UncertainAssetsUUIDs.Contains(assetUuid))
+ possibleNotAssetCount++;
+ else
+ ErrorCount++;
+ return;
+ }
+ if(GatheredUuids.ContainsKey(assetUuid))
+ return;
try
{
if ((sbyte)AssetType.Bodypart == assetType
@@ -458,8 +535,11 @@ namespace OpenSim.Region.Framework.Scenes
foreach (Match uuidMatch in uuidMatches)
{
UUID uuid = new UUID(uuidMatch.Value);
+ if(uuid == UUID.Zero)
+ continue;
// m_log.DebugFormat("[UUID GATHERER]: Recording {0} in text", uuid);
-
+ if(!UncertainAssetsUUIDs.Contains(uuid))
+ UncertainAssetsUUIDs.Add(uuid);
AddForInspection(uuid);
}
}
@@ -550,7 +630,16 @@ namespace OpenSim.Region.Framework.Scenes
///
private void RecordMaterialAssetUuids(AssetBase materialAsset)
{
- OSDMap mat = (OSDMap)OSDParser.DeserializeLLSDXml(materialAsset.Data);
+ OSDMap mat;
+ try
+ {
+ mat = (OSDMap)OSDParser.DeserializeLLSDXml(materialAsset.Data);
+ }
+ catch (Exception e)
+ {
+ m_log.WarnFormat("[Materials]: cannot decode material asset {0}: {1}", materialAsset.ID, e.Message);
+ return;
+ }
UUID normMap = mat["NormMap"].AsUUID();
if (normMap != UUID.Zero)
diff --git a/OpenSim/Region/OptionalModules/Agent/InternetRelayClientView/Server/IRCClientView.cs b/OpenSim/Region/OptionalModules/Agent/InternetRelayClientView/Server/IRCClientView.cs
index 83b534b0ca..d39c224129 100644
--- a/OpenSim/Region/OptionalModules/Agent/InternetRelayClientView/Server/IRCClientView.cs
+++ b/OpenSim/Region/OptionalModules/Agent/InternetRelayClientView/Server/IRCClientView.cs
@@ -1097,7 +1097,12 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server
}
- public void SendAvatarDataImmediate(ISceneEntity avatar)
+ public void SendEntityFullUpdateImmediate(ISceneEntity ent)
+ {
+
+ }
+
+ public void SendEntityTerseUpdateImmediate(ISceneEntity ent)
{
}
diff --git a/OpenSim/Region/OptionalModules/Agent/UDP/Linden/LindenUDPInfoModule.cs b/OpenSim/Region/OptionalModules/Agent/UDP/Linden/LindenUDPInfoModule.cs
index 3be5a07d27..490809eae1 100644
--- a/OpenSim/Region/OptionalModules/Agent/UDP/Linden/LindenUDPInfoModule.cs
+++ b/OpenSim/Region/OptionalModules/Agent/UDP/Linden/LindenUDPInfoModule.cs
@@ -124,15 +124,6 @@ namespace OpenSim.Region.OptionalModules.UDP.Linden
"Without the 'full' option, only root agents are shown."
+ " With the 'full' option child agents are also shown.",
(mod, cmd) => MainConsole.Instance.Output(GetThrottlesReport(cmd)));
-
- scene.AddCommand(
- "Comms", this, "show client stats",
- "show client stats [first_name last_name]",
- "Show client request stats",
- "Without the 'first_name last_name' option, all clients are shown."
- + " With the 'first_name last_name' option only a specific client is shown.",
- (mod, cmd) => MainConsole.Instance.Output(HandleClientStatsReport(cmd)));
-
}
public void RemoveRegion(Scene scene)
@@ -540,107 +531,6 @@ namespace OpenSim.Region.OptionalModules.UDP.Linden
return report.ToString();
}
- ///
- /// Show client stats data
- ///
- ///
- ///
- protected string HandleClientStatsReport(string[] showParams)
- {
- // NOTE: This writes to m_log on purpose. We want to store this information
- // in case we need to analyze it later.
- //
- if (showParams.Length <= 4)
- {
- m_log.InfoFormat("[INFO]: {0,-12} {1,-20} {2,-6} {3,-11} {4,-11} {5,-16}", "Region", "Name", "Root", "Time", "Reqs/min", "AgentUpdates");
- foreach (Scene scene in m_scenes.Values)
- {
- scene.ForEachClient(
- delegate(IClientAPI client)
- {
- if (client is LLClientView)
- {
- LLClientView llClient = client as LLClientView;
- ClientInfo cinfo = llClient.UDPClient.GetClientInfo();
- int avg_reqs = cinfo.AsyncRequests.Values.Sum() + cinfo.GenericRequests.Values.Sum() + cinfo.SyncRequests.Values.Sum();
- avg_reqs = avg_reqs / ((DateTime.Now - cinfo.StartedTime).Minutes + 1);
-
- string childAgentStatus;
-
- if (llClient.SceneAgent != null)
- childAgentStatus = llClient.SceneAgent.IsChildAgent ? "N" : "Y";
- else
- childAgentStatus = "Off!";
-
- m_log.InfoFormat("[INFO]: {0,-12} {1,-20} {2,-6} {3,-11} {4,-11} {5,-16}",
- scene.RegionInfo.RegionName, llClient.Name,
- childAgentStatus,
- (DateTime.Now - cinfo.StartedTime).Minutes,
- avg_reqs,
- string.Format(
- "{0} ({1:0.00}%)",
- llClient.TotalAgentUpdates,
- cinfo.SyncRequests.ContainsKey("AgentUpdate")
- ? (float)cinfo.SyncRequests["AgentUpdate"] / llClient.TotalAgentUpdates * 100
- : 0));
- }
- });
- }
- return string.Empty;
- }
-
- string fname = "", lname = "";
-
- if (showParams.Length > 3)
- fname = showParams[3];
- if (showParams.Length > 4)
- lname = showParams[4];
-
- foreach (Scene scene in m_scenes.Values)
- {
- scene.ForEachClient(
- delegate(IClientAPI client)
- {
- if (client is LLClientView)
- {
- LLClientView llClient = client as LLClientView;
-
- if (llClient.Name == fname + " " + lname)
- {
-
- ClientInfo cinfo = llClient.GetClientInfo();
- AgentCircuitData aCircuit = scene.AuthenticateHandler.GetAgentCircuitData(llClient.CircuitCode);
- if (aCircuit == null) // create a dummy one
- aCircuit = new AgentCircuitData();
-
- if (!llClient.SceneAgent.IsChildAgent)
- m_log.InfoFormat("[INFO]: {0} # {1} # {2}", llClient.Name, Util.GetViewerName(aCircuit), aCircuit.Id0);
-
- int avg_reqs = cinfo.AsyncRequests.Values.Sum() + cinfo.GenericRequests.Values.Sum() + cinfo.SyncRequests.Values.Sum();
- avg_reqs = avg_reqs / ((DateTime.Now - cinfo.StartedTime).Minutes + 1);
-
- m_log.InfoFormat("[INFO]:");
- m_log.InfoFormat("[INFO]: {0} # {1} # Time: {2}min # Avg Reqs/min: {3}", scene.RegionInfo.RegionName,
- (llClient.SceneAgent.IsChildAgent ? "Child" : "Root"), (DateTime.Now - cinfo.StartedTime).Minutes, avg_reqs);
-
- Dictionary sortedDict = (from entry in cinfo.AsyncRequests orderby entry.Value descending select entry)
- .ToDictionary(pair => pair.Key, pair => pair.Value);
- PrintRequests("TOP ASYNC", sortedDict, cinfo.AsyncRequests.Values.Sum());
-
- sortedDict = (from entry in cinfo.SyncRequests orderby entry.Value descending select entry)
- .ToDictionary(pair => pair.Key, pair => pair.Value);
- PrintRequests("TOP SYNC", sortedDict, cinfo.SyncRequests.Values.Sum());
-
- sortedDict = (from entry in cinfo.GenericRequests orderby entry.Value descending select entry)
- .ToDictionary(pair => pair.Key, pair => pair.Value);
- PrintRequests("TOP GENERIC", sortedDict, cinfo.GenericRequests.Values.Sum());
- }
- }
- });
- }
- return string.Empty;
- }
-
private void PrintRequests(string type, Dictionary sortedDict, int sum)
{
m_log.InfoFormat("[INFO]:");
diff --git a/OpenSim/Region/OptionalModules/Avatar/Attachments/TempAttachmentsModule.cs b/OpenSim/Region/OptionalModules/Avatar/Attachments/TempAttachmentsModule.cs
index ed27385efb..c3f38511dd 100644
--- a/OpenSim/Region/OptionalModules/Avatar/Attachments/TempAttachmentsModule.cs
+++ b/OpenSim/Region/OptionalModules/Avatar/Attachments/TempAttachmentsModule.cs
@@ -134,11 +134,12 @@ namespace OpenSim.Region.OptionalModules.Avatar.Attachments
private int llAttachToAvatarTemp(UUID host, UUID script, int attachmentPoint)
{
SceneObjectPart hostPart = m_scene.GetSceneObjectPart(host);
-
if (hostPart == null)
return 0;
- if (hostPart.ParentGroup.IsAttachment)
+ SceneObjectGroup hostgroup = hostPart.ParentGroup;
+
+ if (hostgroup== null || hostgroup.IsAttachment)
return 0;
IAttachmentsModule attachmentsModule = m_scene.RequestModuleInterface();
@@ -156,32 +157,32 @@ namespace OpenSim.Region.OptionalModules.Avatar.Attachments
if (!m_scene.TryGetScenePresence(item.PermsGranter, out target))
return 0;
- if (target.UUID != hostPart.ParentGroup.OwnerID)
+ if (target.UUID != hostgroup.OwnerID)
{
- uint effectivePerms = hostPart.ParentGroup.GetEffectivePermissions();
+ uint effectivePerms = hostgroup.EffectiveOwnerPerms;
if ((effectivePerms & (uint)PermissionMask.Transfer) == 0)
return 0;
- hostPart.ParentGroup.SetOwnerId(target.UUID);
- hostPart.ParentGroup.SetRootPartOwner(hostPart.ParentGroup.RootPart, target.UUID, target.ControllingClient.ActiveGroupId);
+ hostgroup.SetOwner(target.UUID, target.ControllingClient.ActiveGroupId);
if (m_scene.Permissions.PropagatePermissions())
{
- foreach (SceneObjectPart child in hostPart.ParentGroup.Parts)
+ foreach (SceneObjectPart child in hostgroup.Parts)
{
child.Inventory.ChangeInventoryOwner(target.UUID);
child.TriggerScriptChangedEvent(Changed.OWNER);
child.ApplyNextOwnerPermissions();
}
+ hostgroup.InvalidateEffectivePerms();
}
- hostPart.ParentGroup.RootPart.ObjectSaleType = 0;
- hostPart.ParentGroup.RootPart.SalePrice = 10;
+ hostgroup.RootPart.ObjectSaleType = 0;
+ hostgroup.RootPart.SalePrice = 10;
- hostPart.ParentGroup.HasGroupChanged = true;
- hostPart.ParentGroup.RootPart.SendPropertiesToClient(target.ControllingClient);
- hostPart.ParentGroup.RootPart.ScheduleFullUpdate();
+ hostgroup.HasGroupChanged = true;
+ hostgroup.RootPart.SendPropertiesToClient(target.ControllingClient);
+ hostgroup.RootPart.ScheduleFullUpdate();
}
return attachmentsModule.AttachObject(target, hostPart.ParentGroup, (uint)attachmentPoint, false, false, true) ? 1 : 0;
diff --git a/OpenSim/Region/OptionalModules/Avatar/Concierge/ConciergeModule.cs b/OpenSim/Region/OptionalModules/Avatar/Concierge/ConciergeModule.cs
index c0de3d95db..a5dc0ad0d0 100644
--- a/OpenSim/Region/OptionalModules/Avatar/Concierge/ConciergeModule.cs
+++ b/OpenSim/Region/OptionalModules/Avatar/Concierge/ConciergeModule.cs
@@ -460,9 +460,8 @@ namespace OpenSim.Region.OptionalModules.Avatar.Concierge
if (resp.ContentLength > 0)
{
- StreamReader content = new StreamReader(resp.GetResponseStream());
- m_log.ErrorFormat("[Concierge] response from {0} content: {1}", bs.Uri, content.ReadToEnd());
- content.Close();
+ using(StreamReader content = new StreamReader(resp.GetResponseStream()))
+ m_log.ErrorFormat("[Concierge] response from {0} content: {1}", bs.Uri, content.ReadToEnd());
}
}
}
diff --git a/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/GroupsModule.cs b/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/GroupsModule.cs
index d52a1d53db..65d50bb9a0 100644
--- a/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/GroupsModule.cs
+++ b/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/GroupsModule.cs
@@ -901,7 +901,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
remoteClient.SendCreateGroupReply(groupID, true, "Group created successfully");
// Update the founder with new group information.
- SendAgentGroupDataUpdate(remoteClient, false);
+ SendAgentGroupDataUpdate(remoteClient, true);
return groupID;
}
@@ -1520,6 +1520,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
lastname, activeGroupPowers, activeGroupName,
activeGroupTitle);
+
if (tellOthers)
SendScenePresenceUpdate(agentID, activeGroupTitle);
diff --git a/OpenSim/Region/OptionalModules/Framework/Monitoring/EtcdMonitoringModule.cs b/OpenSim/Region/OptionalModules/Framework/Monitoring/EtcdMonitoringModule.cs
new file mode 100644
index 0000000000..921bbfbbee
--- /dev/null
+++ b/OpenSim/Region/OptionalModules/Framework/Monitoring/EtcdMonitoringModule.cs
@@ -0,0 +1,195 @@
+/*
+ * 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.Reflection;
+using System.Text;
+using log4net;
+using Mono.Addins;
+using Nini.Config;
+using OpenMetaverse;
+using OpenSim.Framework;
+using OpenSim.Framework.Console;
+using OpenSim.Region.Framework.Interfaces;
+using OpenSim.Region.Framework.Scenes;
+using netcd;
+using netcd.Serialization;
+using netcd.Advanced;
+using netcd.Advanced.Requests;
+
+namespace OpenSim.Region.OptionalModules.Framework.Monitoring
+{
+ ///
+ /// Allows to store monitoring data in etcd, a high availability
+ /// name-value store.
+ ///
+ [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "EtcdMonitoringModule")]
+ public class EtcdMonitoringModule : INonSharedRegionModule, IEtcdModule
+ {
+ private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
+
+ protected Scene m_scene;
+ protected IEtcdClient m_client;
+ protected bool m_enabled = false;
+ protected string m_etcdBasePath = String.Empty;
+ protected bool m_appendRegionID = true;
+
+ public string Name
+ {
+ get { return "EtcdMonitoringModule"; }
+ }
+
+ public Type ReplaceableInterface
+ {
+ get { return null; }
+ }
+
+ public void Initialise(IConfigSource source)
+ {
+ if (source.Configs["Etcd"] == null)
+ return;
+
+ IConfig etcdConfig = source.Configs["Etcd"];
+
+ string etcdUrls = etcdConfig.GetString("EtcdUrls", String.Empty);
+ if (etcdUrls == String.Empty)
+ return;
+
+ m_etcdBasePath = etcdConfig.GetString("BasePath", m_etcdBasePath);
+ m_appendRegionID = etcdConfig.GetBoolean("AppendRegionID", m_appendRegionID);
+
+ if (!m_etcdBasePath.EndsWith("/"))
+ m_etcdBasePath += "/";
+
+ try
+ {
+ string[] endpoints = etcdUrls.Split(new char[] {','});
+ List uris = new List();
+ foreach (string endpoint in endpoints)
+ uris.Add(new Uri(endpoint.Trim()));
+
+ m_client = new EtcdClient(uris.ToArray(), new DefaultSerializer(), new DefaultSerializer());
+ }
+ catch (Exception e)
+ {
+ m_log.DebugFormat("[ETCD]: Error initializing connection: " + e.ToString());
+ return;
+ }
+
+ m_log.DebugFormat("[ETCD]: Etcd module configured");
+ m_enabled = true;
+ }
+
+ public void Close()
+ {
+ //m_client = null;
+ m_scene = null;
+ }
+
+ public void AddRegion(Scene scene)
+ {
+ m_scene = scene;
+
+ if (m_enabled)
+ {
+ if (m_appendRegionID)
+ m_etcdBasePath += m_scene.RegionInfo.RegionID.ToString() + "/";
+
+ m_log.DebugFormat("[ETCD]: Using base path {0} for all keys", m_etcdBasePath);
+
+ try
+ {
+ m_client.Advanced.CreateDirectory(new CreateDirectoryRequest() {Key = m_etcdBasePath});
+ }
+ catch (Exception e)
+ {
+ m_log.ErrorFormat("Exception trying to create base path {0}: " + e.ToString(), m_etcdBasePath);
+ }
+
+ scene.RegisterModuleInterface(this);
+ }
+ }
+
+ public void RemoveRegion(Scene scene)
+ {
+ }
+
+ public void RegionLoaded(Scene scene)
+ {
+ }
+
+ public bool Store(string k, string v)
+ {
+ return Store(k, v, 0);
+ }
+
+ public bool Store(string k, string v, int ttl)
+ {
+ Response resp = m_client.Advanced.SetKey(new SetKeyRequest() { Key = m_etcdBasePath + k, Value = v, TimeToLive = ttl });
+
+ if (resp == null)
+ return false;
+
+ if (resp.ErrorCode.HasValue)
+ {
+ m_log.DebugFormat("[ETCD]: Error {0} ({1}) storing {2} => {3}", resp.Cause, (int)resp.ErrorCode, m_etcdBasePath + k, v);
+
+ return false;
+ }
+
+ return true;
+ }
+
+ public string Get(string k)
+ {
+ Response resp = m_client.Advanced.GetKey(new GetKeyRequest() { Key = m_etcdBasePath + k });
+
+ if (resp == null)
+ return String.Empty;
+
+ if (resp.ErrorCode.HasValue)
+ {
+ m_log.DebugFormat("[ETCD]: Error {0} ({1}) getting {2}", resp.Cause, (int)resp.ErrorCode, m_etcdBasePath + k);
+
+ return String.Empty;
+ }
+
+ return resp.Node.Value;
+ }
+
+ public void Delete(string k)
+ {
+ m_client.Advanced.DeleteKey(new DeleteKeyRequest() { Key = m_etcdBasePath + k });
+ }
+
+ public void Watch(string k, Action callback)
+ {
+ m_client.Advanced.WatchKey(new WatchKeyRequest() { Key = m_etcdBasePath + k, Callback = (x) => { callback(x.Node.Value); } });
+ }
+ }
+}
diff --git a/OpenSim/Region/OptionalModules/Materials/MaterialsModule.cs b/OpenSim/Region/OptionalModules/Materials/MaterialsModule.cs
index 52fa908d4a..e8cb052263 100644
--- a/OpenSim/Region/OptionalModules/Materials/MaterialsModule.cs
+++ b/OpenSim/Region/OptionalModules/Materials/MaterialsModule.cs
@@ -329,7 +329,7 @@ namespace OpenSim.Region.OptionalModules.Materials
AssetBase matAsset = m_scene.AssetService.Get(id.ToString());
if (matAsset == null || matAsset.Data == null || matAsset.Data.Length == 0 )
{
- m_log.WarnFormat("[Materials]: Prim \"{0}\" ({1}) contains unknown material ID {2}", part.Name, part.UUID, id);
+ //m_log.WarnFormat("[Materials]: Prim \"{0}\" ({1}) contains unknown material ID {2}", part.Name, part.UUID, id);
return;
}
diff --git a/OpenSim/Region/OptionalModules/PrimLimitsModule/PrimLimitsModule.cs b/OpenSim/Region/OptionalModules/PrimLimitsModule/PrimLimitsModule.cs
index 9c0fa7577d..61b6d682e6 100644
--- a/OpenSim/Region/OptionalModules/PrimLimitsModule/PrimLimitsModule.cs
+++ b/OpenSim/Region/OptionalModules/PrimLimitsModule/PrimLimitsModule.cs
@@ -52,6 +52,7 @@ namespace OpenSim.Region.OptionalModules
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool m_enabled;
+ private Scene m_scene;
public string Name { get { return "PrimLimitsModule"; } }
public Type ReplaceableInterface { get { return null; } }
@@ -77,11 +78,12 @@ namespace OpenSim.Region.OptionalModules
public void AddRegion(Scene scene)
{
if (!m_enabled)
- {
return;
- }
+
+ m_scene = scene;
scene.Permissions.OnRezObject += CanRezObject;
scene.Permissions.OnObjectEntry += CanObjectEnter;
+ scene.Permissions.OnObjectEnterWithScripts += CanObjectEnterWithScripts;
scene.Permissions.OnDuplicateObject += CanDuplicateObject;
m_log.DebugFormat("[PRIM LIMITS]: Region {0} added", scene.RegionInfo.RegionName);
@@ -89,14 +91,13 @@ namespace OpenSim.Region.OptionalModules
public void RemoveRegion(Scene scene)
{
- if (m_enabled)
- {
+ if (!m_enabled)
return;
- }
- scene.Permissions.OnRezObject -= CanRezObject;
- scene.Permissions.OnObjectEntry -= CanObjectEnter;
- scene.Permissions.OnDuplicateObject -= CanDuplicateObject;
+ m_scene.Permissions.OnRezObject -= CanRezObject;
+ m_scene.Permissions.OnObjectEntry -= CanObjectEnter;
+ scene.Permissions.OnObjectEnterWithScripts -= CanObjectEnterWithScripts;
+ m_scene.Permissions.OnDuplicateObject -= CanDuplicateObject;
}
public void RegionLoaded(Scene scene)
@@ -104,11 +105,12 @@ namespace OpenSim.Region.OptionalModules
m_dialogModule = scene.RequestModuleInterface();
}
- private bool CanRezObject(int objectCount, UUID ownerID, Vector3 objectPosition, Scene scene)
+ private bool CanRezObject(int objectCount, UUID ownerID, Vector3 objectPosition)
{
- ILandObject lo = scene.LandChannel.GetLandObject(objectPosition.X, objectPosition.Y);
+
+ ILandObject lo = m_scene.LandChannel.GetLandObject(objectPosition.X, objectPosition.Y);
- string response = DoCommonChecks(objectCount, ownerID, lo, scene);
+ string response = DoCommonChecks(objectCount, ownerID, lo);
if (response != null)
{
@@ -119,88 +121,99 @@ namespace OpenSim.Region.OptionalModules
}
//OnDuplicateObject
- private bool CanDuplicateObject(int objectCount, UUID objectID, UUID ownerID, Scene scene, Vector3 objectPosition)
+ private bool CanDuplicateObject(SceneObjectGroup sog, ScenePresence sp)
{
- ILandObject lo = scene.LandChannel.GetLandObject(objectPosition.X, objectPosition.Y);
+ Vector3 objectPosition = sog.AbsolutePosition;
+ ILandObject lo = m_scene.LandChannel.GetLandObject(objectPosition.X, objectPosition.Y);
- string response = DoCommonChecks(objectCount, ownerID, lo, scene);
+ string response = DoCommonChecks(sog.PrimCount, sp.UUID, lo);
if (response != null)
{
- m_dialogModule.SendAlertToUser(ownerID, response);
+ m_dialogModule.SendAlertToUser(sp.UUID, response);
return false;
}
return true;
}
- private bool CanObjectEnter(UUID objectID, bool enteringRegion, Vector3 newPoint, Scene scene)
+ private bool CanObjectEnter(SceneObjectGroup sog, bool enteringRegion, Vector3 newPoint)
{
- if (newPoint.X < -1f || newPoint.X > (scene.RegionInfo.RegionSizeX + 1) ||
- newPoint.Y < -1f || newPoint.Y > (scene.RegionInfo.RegionSizeY) )
+ float newX = newPoint.X;
+ float newY = newPoint.Y;
+ if (newX < -1.0f || newX > (m_scene.RegionInfo.RegionSizeX + 1.0f) ||
+ newY < -1.0f || newY > (m_scene.RegionInfo.RegionSizeY + 1.0f) )
return true;
- SceneObjectPart obj = scene.GetSceneObjectPart(objectID);
-
- if (obj == null)
+ if (sog == null)
return false;
- // Prim counts are determined by the location of the root prim. if we're
- // moving a child prim, just let it pass
- if (!obj.IsRoot)
- {
- return true;
- }
-
- ILandObject newParcel = scene.LandChannel.GetLandObject(newPoint.X, newPoint.Y);
+ ILandObject newParcel = m_scene.LandChannel.GetLandObject(newX, newY);
if (newParcel == null)
return true;
- Vector3 oldPoint = obj.GroupPosition;
- ILandObject oldParcel = scene.LandChannel.GetLandObject(oldPoint.X, oldPoint.Y);
-
- // The prim hasn't crossed a region boundry so we don't need to worry
- // about prim counts here
- if(oldParcel != null && oldParcel.Equals(newParcel))
+ if(!enteringRegion)
{
- return true;
+ Vector3 oldPoint = sog.AbsolutePosition;
+ ILandObject oldParcel = m_scene.LandChannel.GetLandObject(oldPoint.X, oldPoint.Y);
+ if(oldParcel != null && oldParcel.Equals(newParcel))
+ return true;
}
- int objectCount = obj.ParentGroup.PrimCount;
- int usedPrims = newParcel.PrimCounts.Total;
- int simulatorCapacity = newParcel.GetSimulatorMaxPrimCount();
+ int objectCount = sog.PrimCount;
// TODO: Add Special Case here for temporary prims
- string response = DoCommonChecks(objectCount, obj.OwnerID, newParcel, scene);
+ string response = DoCommonChecks(objectCount, sog.OwnerID, newParcel);
if (response != null)
{
- m_dialogModule.SendAlertToUser(obj.OwnerID, response);
+ if(m_dialogModule != null)
+ m_dialogModule.SendAlertToUser(sog.OwnerID, response);
return false;
}
return true;
}
- private string DoCommonChecks(int objectCount, UUID ownerID, ILandObject lo, Scene scene)
+ private bool CanObjectEnterWithScripts(SceneObjectGroup sog, ILandObject newParcel)
+ {
+ if (sog == null)
+ return false;
+
+ if (newParcel == null)
+ return true;
+
+ int objectCount = sog.PrimCount;
+
+ // TODO: Add Special Case here for temporary prims
+
+ string response = DoCommonChecks(objectCount, sog.OwnerID, newParcel);
+
+ if (response != null)
+ return false;
+
+ return true;
+ }
+
+ private string DoCommonChecks(int objectCount, UUID ownerID, ILandObject lo)
{
string response = null;
int OwnedParcelsCapacity = lo.GetSimulatorMaxPrimCount();
if ((objectCount + lo.PrimCounts.Total) > OwnedParcelsCapacity)
{
- response = "Unable to rez object because the parcel is too full";
+ response = "Unable to rez object because the parcel is full";
}
else
{
- int maxPrimsPerUser = scene.RegionInfo.MaxPrimsPerUser;
+ int maxPrimsPerUser = m_scene.RegionInfo.MaxPrimsPerUser;
if (maxPrimsPerUser >= 0)
{
// per-user prim limit is set
if (ownerID != lo.LandData.OwnerID || lo.LandData.IsGroupOwned)
{
// caller is not the sole Parcel owner
- EstateSettings estateSettings = scene.RegionInfo.EstateSettings;
+ EstateSettings estateSettings = m_scene.RegionInfo.EstateSettings;
if (ownerID != estateSettings.EstateOwner)
{
// caller is NOT the Estate owner
diff --git a/OpenSim/Region/OptionalModules/Scripting/JsonStore/JsonStoreScriptModule.cs b/OpenSim/Region/OptionalModules/Scripting/JsonStore/JsonStoreScriptModule.cs
index a9fdb667c4..fe8d9621e1 100644
--- a/OpenSim/Region/OptionalModules/Scripting/JsonStore/JsonStoreScriptModule.cs
+++ b/OpenSim/Region/OptionalModules/Scripting/JsonStore/JsonStoreScriptModule.cs
@@ -665,7 +665,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore
taskItem.AssetID = asset.FullID;
host.Inventory.AddInventoryItem(taskItem, false);
-
+ host.ParentGroup.InvalidateEffectivePerms();
m_comms.DispatchReply(scriptID,1,assetID.ToString(),reqID.ToString());
}
diff --git a/OpenSim/Region/OptionalModules/World/AutoBackup/AutoBackupModule.cs b/OpenSim/Region/OptionalModules/World/AutoBackup/AutoBackupModule.cs
index 79b80f88f4..a14d8194ad 100644
--- a/OpenSim/Region/OptionalModules/World/AutoBackup/AutoBackupModule.cs
+++ b/OpenSim/Region/OptionalModules/World/AutoBackup/AutoBackupModule.cs
@@ -59,23 +59,23 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
///
///
/// Config Settings Documentation.
- /// Each configuration setting can be specified in two places: OpenSim.ini or Regions.ini.
- /// If specified in Regions.ini, the settings should be within the region's section name.
- /// If specified in OpenSim.ini, the settings should be within the [AutoBackupModule] section.
- /// Region-specific settings take precedence.
+ /// Configuration setting can be specified in two places: OpenSim.ini and/or Regions.ini.
///
- /// AutoBackupModuleEnabled: True/False. Default: False. If True, use the auto backup module. This setting does not support per-region basis.
- /// All other settings under [AutoBackupModule] are ignored if AutoBackupModuleEnabled is false, even per-region settings!
- /// AutoBackup: True/False. Default: False. If True, activate auto backup functionality.
- /// This is the only required option for enabling auto-backup; the other options have sane defaults.
- /// If False for a particular region, the auto-backup module becomes a no-op for the region, and all other AutoBackup* settings are ignored.
- /// If False globally (the default), only regions that specifically override it in Regions.ini will get AutoBackup functionality.
+ /// OpenSim.ini only settings section [AutoBackupModule]
+ /// AutoBackupModuleEnabled: True/False. Default: False. If True, use the auto backup module.
+ /// if false module is disable and all rest is ignored
/// AutoBackupInterval: Double, non-negative value. Default: 720 (12 hours).
/// The number of minutes between each backup attempt.
- /// If a negative or zero value is given, it is equivalent to setting AutoBackup = False.
- /// AutoBackupBusyCheck: True/False. Default: True.
- /// If True, we will only take an auto-backup if a set of conditions are met.
- /// These conditions are heuristics to try and avoid taking a backup when the sim is busy.
+ /// AutoBackupDir: String. Default: "." (the current directory).
+ /// A directory (absolute or relative) where backups should be saved.
+ /// AutoBackupKeepFilesForDays remove files older than this number of days. 0 disables
+ ///
+ /// Next can be set on OpenSim.ini, as default, and or per region in Regions.ini
+ /// Region-specific settings take precedence.
+ ///
+ /// AutoBackup: True/False. Default: False. If True, activate auto backup functionality.
+ /// controls backup per region, with default optionaly set on OpenSim.ini
+
/// AutoBackupSkipAssets
/// If true, assets are not saved to the oar file. Considerably reduces impact on simulator when backing up. Intended for when assets db is backed up separately
/// AutoBackupKeepFilesForDays
@@ -89,40 +89,28 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
/// AutoBackupNaming: string. Default: Time.
/// One of three strings (case insensitive):
/// "Time": Current timestamp is appended to file name. An existing file will never be overwritten.
- /// "Sequential": A number is appended to the file name. So if RegionName_x.oar exists, we'll save to RegionName_{x+1}.oar next. An existing file will never be overwritten.
- /// "Overwrite": Always save to file named "${AutoBackupDir}/RegionName.oar", even if we have to overwrite an existing file.
- /// AutoBackupDir: String. Default: "." (the current directory).
- /// A directory (absolute or relative) where backups should be saved.
- /// AutoBackupDilationThreshold: float. Default: 0.5. Lower bound on time dilation required for BusyCheck heuristics to pass.
- /// If the time dilation is below this value, don't take a backup right now.
- /// AutoBackupAgentThreshold: int. Default: 10. Upper bound on # of agents in region required for BusyCheck heuristics to pass.
- /// If the number of agents is greater than this value, don't take a backup right now
- /// Save memory by setting low initial capacities. Minimizes impact in common cases of all regions using same interval, and instances hosting 1 ~ 4 regions.
- /// Also helps if you don't want AutoBackup at all.
+ /// "Sequential": A number is appended to the file name. So if RegionName_x.oar exists, we'll save to RegionName_{x+1}.oar next. An existing file will never be overwritten.
+ /// "Overwrite": Always save to file named "${AutoBackupDir}/RegionName.oar", even if we have to overwrite an existing file.
///
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "AutoBackupModule")]
public class AutoBackupModule : ISharedRegionModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
- private readonly Dictionary m_pendingSaves = new Dictionary(1);
private readonly AutoBackupModuleState m_defaultState = new AutoBackupModuleState();
private readonly Dictionary m_states =
new Dictionary(1);
- private readonly Dictionary> m_timerMap =
- new Dictionary>(1);
- private readonly Dictionary m_timers = new Dictionary(1);
private delegate T DefaultGetter(string settingName, T defaultValue);
private bool m_enabled;
private ICommandConsole m_console;
private List m_Scenes = new List ();
-
-
- ///
- /// Whether the shared module should be enabled at all. NOT the same as m_Enabled in AutoBackupModuleState!
- ///
- private bool m_closed;
+ private Timer m_masterTimer;
+ private bool m_busy;
+ private int m_KeepFilesForDays = -1;
+ private string m_backupDir;
+ private bool m_doneFirst;
+ private double m_baseInterval;
private IConfigSource m_configSource;
@@ -159,36 +147,38 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
void IRegionModuleBase.Initialise(IConfigSource source)
{
// Determine if we have been enabled at all in OpenSim.ini -- this is part and parcel of being an optional module
- this.m_configSource = source;
+ m_configSource = source;
IConfig moduleConfig = source.Configs["AutoBackupModule"];
if (moduleConfig == null)
{
- this.m_enabled = false;
+ m_enabled = false;
return;
}
- else
- {
- this.m_enabled = moduleConfig.GetBoolean("AutoBackupModuleEnabled", false);
- if (this.m_enabled)
- {
- m_log.Info("[AUTO BACKUP]: AutoBackupModule enabled");
- }
- else
- {
- return;
- }
- }
- Timer defTimer = new Timer(43200000);
- this.m_defaultState.Timer = defTimer;
- this.m_timers.Add(43200000, defTimer);
- defTimer.Elapsed += this.HandleElapsed;
- defTimer.AutoReset = true;
- defTimer.Start();
+ m_enabled = moduleConfig.GetBoolean("AutoBackupModuleEnabled", false);
+ if(!m_enabled)
+ return;
- AutoBackupModuleState abms = this.ParseConfig(null, true);
- m_log.Debug("[AUTO BACKUP]: Here is the default config:");
- m_log.Debug(abms.ToString());
+ ParseDefaultConfig(moduleConfig);
+ if(!m_enabled)
+ return;
+
+ m_log.Debug("[AUTO BACKUP]: Default config:");
+ m_log.Debug(m_defaultState.ToString());
+
+ m_log.Info("[AUTO BACKUP]: AutoBackupModule enabled");
+ m_masterTimer = new Timer();
+ m_masterTimer.Interval = m_baseInterval;
+ m_masterTimer.Elapsed += HandleElapsed;
+ m_masterTimer.AutoReset = false;
+
+ m_console = MainConsole.Instance;
+
+ m_console.Commands.AddCommand (
+ "AutoBackup", true, "dooarbackup",
+ "dooarbackup | ALL",
+ "saves the single region to a oar or ALL regions in instance to oars, using same settings as AutoBackup. Note it restarts time interval", DoBackup);
+ m_busy = true;
}
///
@@ -196,13 +186,11 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
///
void IRegionModuleBase.Close()
{
- if (!this.m_enabled)
- {
+ if (!m_enabled)
return;
- }
// We don't want any timers firing while the sim's coming down; strange things may happen.
- this.StopAllTimers();
+ m_masterTimer.Dispose();
}
///
@@ -211,18 +199,11 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
///
void IRegionModuleBase.AddRegion (Scene scene)
{
- if (!this.m_enabled) {
+ if (!m_enabled)
return;
- }
- lock (m_Scenes) {
- m_Scenes.Add (scene);
- }
- m_console = MainConsole.Instance;
- m_console.Commands.AddCommand (
- "AutoBackup", false, "dobackup",
- "dobackup",
- "do backup.", DoBackup);
+ lock (m_Scenes)
+ m_Scenes.Add (scene);
}
///
@@ -231,28 +212,14 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
/// The scene (region) to stop performing AutoBackup on.
void IRegionModuleBase.RemoveRegion(Scene scene)
{
- if (!this.m_enabled)
- {
+ if (m_enabled)
return;
- }
- m_Scenes.Remove (scene);
- if (this.m_states.ContainsKey(scene))
+
+ lock(m_Scenes)
{
- AutoBackupModuleState abms = this.m_states[scene];
-
- // Remove this scene out of the timer map list
- Timer timer = abms.Timer;
- List list = this.m_timerMap[timer];
- list.Remove(scene);
-
- // Shut down the timer if this was the last scene for the timer
- if (list.Count == 0)
- {
- this.m_timerMap.Remove(timer);
- this.m_timers.Remove(timer.Interval);
- timer.Close();
- }
- this.m_states.Remove(scene);
+ if (m_states.ContainsKey(scene))
+ m_states.Remove(scene);
+ m_Scenes.Remove(scene);
}
}
@@ -263,22 +230,29 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
/// The scene to (possibly) perform AutoBackup on.
void IRegionModuleBase.RegionLoaded(Scene scene)
{
- if (!this.m_enabled)
- {
+ if (!m_enabled)
return;
- }
// This really ought not to happen, but just in case, let's pretend it didn't...
if (scene == null)
- {
return;
+
+ AutoBackupModuleState abms = ParseConfig(scene);
+ if(abms == null)
+ {
+ m_log.Debug("[AUTO BACKUP]: Config for " + scene.RegionInfo.RegionName);
+ m_log.Debug("DEFAULT");
+ abms = new AutoBackupModuleState(m_defaultState);
+ }
+ else
+ {
+ m_log.Debug("[AUTO BACKUP]: Config for " + scene.RegionInfo.RegionName);
+ m_log.Debug(abms.ToString());
}
- AutoBackupModuleState abms = this.ParseConfig(scene, false);
- m_log.Debug("[AUTO BACKUP]: Config for " + scene.RegionInfo.RegionName);
- m_log.Debug((abms == null ? "DEFAULT" : abms.ToString()));
-
m_states.Add(scene, abms);
+ m_busy = false;
+ m_masterTimer.Start();
}
///
@@ -292,24 +266,122 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
private void DoBackup (string module, string[] args)
{
- if (args.Length != 2) {
- MainConsole.Instance.OutputFormat ("Usage: dobackup ");
+ if (!m_enabled)
+ return;
+
+ if (args.Length != 2)
+ {
+ MainConsole.Instance.OutputFormat ("Usage: dooarbackup ");
return;
}
+
+ if(m_busy)
+ {
+ MainConsole.Instance.OutputFormat ("Already doing a backup, please try later");
+ return;
+ }
+
+ m_masterTimer.Stop();
+ m_busy = true;
+
bool found = false;
string name = args [1];
- lock (m_Scenes) {
- foreach (Scene s in m_Scenes) {
- string test = s.Name.ToString ();
- if (test == name) {
+ Scene[] scenes;
+ lock (m_Scenes)
+ scenes = m_Scenes.ToArray();
+
+ if(scenes == null)
+ return;
+
+ Scene s;
+ try
+ {
+ if(name == "ALL")
+ {
+ for(int i = 0; i < scenes.Length; i++)
+ {
+ s = scenes[i];
+ DoRegionBackup(s);
+ if (!m_enabled)
+ return;
+ }
+ return;
+ }
+
+ for(int i = 0; i < scenes.Length; i++)
+ {
+ s = scenes[i];
+ if (s.Name == name)
+ {
found = true;
- DoRegionBackup (s);
+ DoRegionBackup(s);
+ break;
}
}
- if (!found) {
+ }
+ catch { }
+ finally
+ {
+ if (m_enabled)
+ m_masterTimer.Start();
+ m_busy = false;
+ }
+ if (!found)
MainConsole.Instance.OutputFormat ("No such region {0}. Nothing to backup", name);
+ }
+
+ private void ParseDefaultConfig(IConfig config)
+ {
+
+ m_backupDir = ".";
+ string backupDir = config.GetString("AutoBackupDir", ".");
+ if (backupDir != ".")
+ {
+ try
+ {
+ DirectoryInfo dirinfo = new DirectoryInfo(backupDir);
+ if (!dirinfo.Exists)
+ dirinfo.Create();
+ }
+ catch (Exception e)
+ {
+ m_enabled = false;
+ m_log.WarnFormat("[AUTO BACKUP]: Error accessing backup folder {0}. Module disabled. {1}",
+ backupDir, e);
+ return;
}
}
+ m_backupDir = backupDir;
+
+ double interval = config.GetDouble("AutoBackupInterval", 720);
+ interval *= 60000.0;
+ m_baseInterval = interval;
+
+ // How long to keep backup files in days, 0 Disables this feature
+ m_KeepFilesForDays = config.GetInt("AutoBackupKeepFilesForDays",m_KeepFilesForDays);
+
+ m_defaultState.Enabled = config.GetBoolean("AutoBackup", m_defaultState.Enabled);
+
+ m_defaultState.SkipAssets = config.GetBoolean("AutoBackupSkipAssets",m_defaultState.SkipAssets);
+
+ // Set file naming algorithm
+ string stmpNamingType = config.GetString("AutoBackupNaming", m_defaultState.NamingType.ToString());
+ NamingType tmpNamingType;
+ if (stmpNamingType.Equals("Time", StringComparison.CurrentCultureIgnoreCase))
+ tmpNamingType = NamingType.Time;
+ else if (stmpNamingType.Equals("Sequential", StringComparison.CurrentCultureIgnoreCase))
+ tmpNamingType = NamingType.Sequential;
+ else if (stmpNamingType.Equals("Overwrite", StringComparison.CurrentCultureIgnoreCase))
+ tmpNamingType = NamingType.Overwrite;
+ else
+ {
+ m_log.Warn("Unknown naming type specified for Default");
+ tmpNamingType = NamingType.Time;
+ }
+ m_defaultState.NamingType = tmpNamingType;
+
+ m_defaultState.Script = config.GetString("AutoBackupScript", m_defaultState.Script);
+
}
///
@@ -319,329 +391,49 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
/// The scene to look at.
/// Whether this call is intended to figure out what we consider the "default" config (applied to all regions unless overridden by per-region settings).
/// An AutoBackupModuleState contains most information you should need to know relevant to auto-backup, as applicable to a single region.
- private AutoBackupModuleState ParseConfig(IScene scene, bool parseDefault)
+ private AutoBackupModuleState ParseConfig(IScene scene)
{
- string sRegionName;
- string sRegionLabel;
-// string prepend;
- AutoBackupModuleState state;
+ if(scene == null)
+ return null;
- if (parseDefault)
- {
- sRegionName = null;
- sRegionLabel = "DEFAULT";
-// prepend = "";
- state = this.m_defaultState;
- }
- else
- {
- sRegionName = scene.RegionInfo.RegionName;
- sRegionLabel = sRegionName;
-// prepend = sRegionName + ".";
- state = null;
- }
+ string sRegionName;
+ AutoBackupModuleState state = null;
+
+ sRegionName = scene.RegionInfo.RegionName;
// Read the config settings and set variables.
- IConfig regionConfig = (scene != null ? scene.Config.Configs[sRegionName] : null);
- IConfig config = this.m_configSource.Configs["AutoBackupModule"];
- if (config == null)
- {
- // defaultState would be disabled too if the section doesn't exist.
- state = this.m_defaultState;
- return state;
- }
+ IConfig regionConfig = scene.Config.Configs[sRegionName];
+ if (regionConfig == null)
+ return null;
- bool tmpEnabled = ResolveBoolean("AutoBackup", this.m_defaultState.Enabled, config, regionConfig);
- if (state == null && tmpEnabled != this.m_defaultState.Enabled)
- //Varies from default state
- {
- state = new AutoBackupModuleState();
- }
+ state = new AutoBackupModuleState();
- if (state != null)
- {
- state.Enabled = tmpEnabled;
- }
-
- // If you don't want AutoBackup, we stop.
- if ((state == null && !this.m_defaultState.Enabled) || (state != null && !state.Enabled))
- {
- return state;
- }
- else
- {
- m_log.Info("[AUTO BACKUP]: Region " + sRegionLabel + " is AutoBackup ENABLED.");
- }
-
- // Borrow an existing timer if one exists for the same interval; otherwise, make a new one.
- double interval =
- this.ResolveDouble("AutoBackupInterval", this.m_defaultState.IntervalMinutes,
- config, regionConfig) * 60000.0;
- if (state == null && interval != this.m_defaultState.IntervalMinutes * 60000.0)
- {
- state = new AutoBackupModuleState();
- }
-
- if (this.m_timers.ContainsKey(interval))
- {
- if (state != null)
- {
- state.Timer = this.m_timers[interval];
- }
- m_log.Debug("[AUTO BACKUP]: Reusing timer for " + interval + " msec for region " +
- sRegionLabel);
- }
- else
- {
- // 0 or negative interval == do nothing.
- if (interval <= 0.0 && state != null)
- {
- state.Enabled = false;
- return state;
- }
- if (state == null)
- {
- state = new AutoBackupModuleState();
- }
- Timer tim = new Timer(interval);
- state.Timer = tim;
- //Milliseconds -> minutes
- this.m_timers.Add(interval, tim);
- tim.Elapsed += this.HandleElapsed;
- tim.AutoReset = true;
- tim.Start();
- }
-
- // Add the current region to the list of regions tied to this timer.
- if (scene != null)
- {
- if (state != null)
- {
- if (this.m_timerMap.ContainsKey(state.Timer))
- {
- this.m_timerMap[state.Timer].Add(scene);
- }
- else
- {
- List scns = new List(1);
- scns.Add(scene);
- this.m_timerMap.Add(state.Timer, scns);
- }
- }
- else
- {
- if (this.m_timerMap.ContainsKey(this.m_defaultState.Timer))
- {
- this.m_timerMap[this.m_defaultState.Timer].Add(scene);
- }
- else
- {
- List scns = new List(1);
- scns.Add(scene);
- this.m_timerMap.Add(this.m_defaultState.Timer, scns);
- }
- }
- }
-
- bool tmpBusyCheck = ResolveBoolean("AutoBackupBusyCheck",
- this.m_defaultState.BusyCheck, config, regionConfig);
- if (state == null && tmpBusyCheck != this.m_defaultState.BusyCheck)
- {
- state = new AutoBackupModuleState();
- }
-
- if (state != null)
- {
- state.BusyCheck = tmpBusyCheck;
- }
+ state.Enabled = regionConfig.GetBoolean("AutoBackup", m_defaultState.Enabled);
// Included Option To Skip Assets
- bool tmpSkipAssets = ResolveBoolean("AutoBackupSkipAssets",
- this.m_defaultState.SkipAssets, config, regionConfig);
- if (state == null && tmpSkipAssets != this.m_defaultState.SkipAssets)
- {
- state = new AutoBackupModuleState();
- }
-
- if (state != null)
- {
- state.SkipAssets = tmpSkipAssets;
- }
-
- // How long to keep backup files in days, 0 Disables this feature
- int tmpKeepFilesForDays = ResolveInt("AutoBackupKeepFilesForDays",
- this.m_defaultState.KeepFilesForDays, config, regionConfig);
- if (state == null && tmpKeepFilesForDays != this.m_defaultState.KeepFilesForDays)
- {
- state = new AutoBackupModuleState();
- }
-
- if (state != null)
- {
- state.KeepFilesForDays = tmpKeepFilesForDays;
- }
+ state.SkipAssets = regionConfig.GetBoolean("AutoBackupSkipAssets", m_defaultState.SkipAssets);
// Set file naming algorithm
- string stmpNamingType = ResolveString("AutoBackupNaming",
- this.m_defaultState.NamingType.ToString(), config, regionConfig);
+ string stmpNamingType = regionConfig.GetString("AutoBackupNaming", m_defaultState.NamingType.ToString());
NamingType tmpNamingType;
if (stmpNamingType.Equals("Time", StringComparison.CurrentCultureIgnoreCase))
- {
tmpNamingType = NamingType.Time;
- }
else if (stmpNamingType.Equals("Sequential", StringComparison.CurrentCultureIgnoreCase))
- {
tmpNamingType = NamingType.Sequential;
- }
else if (stmpNamingType.Equals("Overwrite", StringComparison.CurrentCultureIgnoreCase))
- {
tmpNamingType = NamingType.Overwrite;
- }
else
{
- m_log.Warn("Unknown naming type specified for region " + sRegionLabel + ": " +
+ m_log.Warn("Unknown naming type specified for region " + sRegionName + ": " +
stmpNamingType);
tmpNamingType = NamingType.Time;
}
+ m_defaultState.NamingType = tmpNamingType;
- if (state == null && tmpNamingType != this.m_defaultState.NamingType)
- {
- state = new AutoBackupModuleState();
- }
-
- if (state != null)
- {
- state.NamingType = tmpNamingType;
- }
-
- string tmpScript = ResolveString("AutoBackupScript",
- this.m_defaultState.Script, config, regionConfig);
- if (state == null && tmpScript != this.m_defaultState.Script)
- {
- state = new AutoBackupModuleState();
- }
-
- if (state != null)
- {
- state.Script = tmpScript;
- }
-
- string tmpBackupDir = ResolveString("AutoBackupDir", ".", config, regionConfig);
- if (state == null && tmpBackupDir != this.m_defaultState.BackupDir)
- {
- state = new AutoBackupModuleState();
- }
-
- if (state != null)
- {
- state.BackupDir = tmpBackupDir;
- // Let's give the user some convenience and auto-mkdir
- if (state.BackupDir != ".")
- {
- try
- {
- DirectoryInfo dirinfo = new DirectoryInfo(state.BackupDir);
- if (!dirinfo.Exists)
- {
- dirinfo.Create();
- }
- }
- catch (Exception e)
- {
- m_log.Warn(
- "[AUTO BACKUP]: BAD NEWS. You won't be able to save backups to directory " +
- state.BackupDir +
- " because it doesn't exist or there's a permissions issue with it. Here's the exception.",
- e);
- }
- }
- }
-
- if(state == null)
- return m_defaultState;
-
+ state.Script = regionConfig.GetString("AutoBackupScript", m_defaultState.Script);
return state;
}
- ///
- /// Helper function for ParseConfig.
- ///
- ///
- ///
- ///
- ///
- ///
- private bool ResolveBoolean(string settingName, bool defaultValue, IConfig global, IConfig local)
- {
- if(local != null)
- {
- return local.GetBoolean(settingName, global.GetBoolean(settingName, defaultValue));
- }
- else
- {
- return global.GetBoolean(settingName, defaultValue);
- }
- }
-
- ///
- /// Helper function for ParseConfig.
- ///
- ///
- ///
- ///
- ///
- ///
- private double ResolveDouble(string settingName, double defaultValue, IConfig global, IConfig local)
- {
- if (local != null)
- {
- return local.GetDouble(settingName, global.GetDouble(settingName, defaultValue));
- }
- else
- {
- return global.GetDouble(settingName, defaultValue);
- }
- }
-
- ///
- /// Helper function for ParseConfig.
- ///
- ///
- ///
- ///
- ///
- ///
- private int ResolveInt(string settingName, int defaultValue, IConfig global, IConfig local)
- {
- if (local != null)
- {
- return local.GetInt(settingName, global.GetInt(settingName, defaultValue));
- }
- else
- {
- return global.GetInt(settingName, defaultValue);
- }
- }
-
- ///
- /// Helper function for ParseConfig.
- ///
- ///
- ///
- ///
- ///
- ///
- private string ResolveString(string settingName, string defaultValue, IConfig global, IConfig local)
- {
- if (local != null)
- {
- return local.GetString(settingName, global.GetString(settingName, defaultValue));
- }
- else
- {
- return global.GetString(settingName, defaultValue);
- }
- }
///
/// Called when any auto-backup timer expires. This starts the code path for actually performing a backup.
@@ -650,63 +442,27 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
///
private void HandleElapsed(object sender, ElapsedEventArgs e)
{
- // TODO: heuristic thresholds are per-region, so we should probably run heuristics once per region
- // XXX: Running heuristics once per region could add undue performance penalty for something that's supposed to
- // check whether the region is too busy! Especially on sims with LOTS of regions.
- // Alternative: make heuristics thresholds global to the module rather than per-region. Less flexible,
- // but would allow us to be semantically correct while being easier on perf.
- // Alternative 2: Run heuristics once per unique set of heuristics threshold parameters! Ay yi yi...
- // Alternative 3: Don't support per-region heuristics at all; just accept them as a global only parameter.
- // Since this is pretty experimental, I haven't decided which alternative makes the most sense.
- if (this.m_closed)
- {
+ if (!m_enabled || m_busy)
return;
- }
- bool heuristicsRun = false;
- bool heuristicsPassed = false;
- if (!this.m_timerMap.ContainsKey((Timer) sender))
+
+ m_busy = true;
+ if(m_doneFirst && m_KeepFilesForDays > 0)
+ RemoveOldFiles();
+
+ foreach (IScene scene in m_Scenes)
{
- m_log.Debug("[AUTO BACKUP]: Code-up error: timerMap doesn't contain timer " + sender);
+ if (!m_enabled)
+ return;
+ DoRegionBackup(scene);
}
- List tmap = this.m_timerMap[(Timer) sender];
- if (tmap != null && tmap.Count > 0)
+ if (m_enabled)
{
- foreach (IScene scene in tmap)
- {
- AutoBackupModuleState state = this.m_states[scene];
- bool heuristics = state.BusyCheck;
-
- // Fast path: heuristics are on; already ran em; and sim is fine; OR, no heuristics for the region.
- if ((heuristics && heuristicsRun && heuristicsPassed) || !heuristics)
- {
- this.DoRegionBackup(scene);
- // Heuristics are on; ran but we're too busy -- keep going. Maybe another region will have heuristics off!
- }
- else if (heuristicsRun)
- {
- m_log.Info("[AUTO BACKUP]: Heuristics: too busy to backup " +
- scene.RegionInfo.RegionName + " right now.");
- continue;
- // Logical Deduction: heuristics are on but haven't been run
- }
- else
- {
- heuristicsPassed = this.RunHeuristics(scene);
- heuristicsRun = true;
- if (!heuristicsPassed)
- {
- m_log.Info("[AUTO BACKUP]: Heuristics: too busy to backup " +
- scene.RegionInfo.RegionName + " right now.");
- continue;
- }
- this.DoRegionBackup(scene);
- }
-
- // Remove Old Backups
- this.RemoveOldFiles(state);
- }
+ m_masterTimer.Start();
+ m_busy = false;
}
+
+ m_doneFirst = true;
}
///
@@ -723,21 +479,29 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
return;
}
- AutoBackupModuleState state = this.m_states[scene];
+ m_busy = true;
+
+ AutoBackupModuleState state;
+ if(!m_states.TryGetValue(scene, out state))
+ return;
+
+ if(state == null || !state.Enabled)
+ return;
+
IRegionArchiverModule iram = scene.RequestModuleInterface();
+ if(iram == null)
+ return;
+
string savePath = BuildOarPath(scene.RegionInfo.RegionName,
- state.BackupDir,
+ m_backupDir,
state.NamingType);
if (savePath == null)
{
m_log.Warn("[AUTO BACKUP]: savePath is null in HandleElapsed");
return;
}
- Guid guid = Guid.NewGuid();
- m_pendingSaves.Add(guid, scene);
- state.LiveRequests.Add(guid, savePath);
- ((Scene) scene).EventManager.OnOarFileSaved += new EventManager.OarFileSaved(EventManager_OnOarFileSaved);
+ Guid guid = Guid.NewGuid();
m_log.Info("[AUTO BACKUP]: Backing up region " + scene.RegionInfo.RegionName);
// Must pass options, even if dictionary is empty!
@@ -747,47 +511,37 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
options["noassets"] = true;
iram.ArchiveRegion(savePath, guid, options);
+ ExecuteScript(state.Script, savePath);
}
// For the given state, remove backup files older than the states KeepFilesForDays property
- private void RemoveOldFiles(AutoBackupModuleState state)
+ private void RemoveOldFiles()
{
- // 0 Means Disabled, Keep Files Indefinitely
- if (state.KeepFilesForDays > 0)
+ string[] files;
+ try
{
- string[] files = Directory.GetFiles(state.BackupDir, "*.oar");
- DateTime CuttOffDate = DateTime.Now.AddDays(0 - state.KeepFilesForDays);
-
- foreach (string file in files)
- {
- try
- {
- FileInfo fi = new FileInfo(file);
- if (fi.CreationTime < CuttOffDate)
- fi.Delete();
- }
- catch (Exception Ex)
- {
- m_log.Error("[AUTO BACKUP]: Error deleting old backup file '" + file + "': " + Ex.Message);
- }
- }
+ files = Directory.GetFiles(m_backupDir, "*.oar");
}
- }
-
- ///
- /// Called by the Event Manager when the OnOarFileSaved event is fired.
- ///
- ///
- ///
- void EventManager_OnOarFileSaved(Guid guid, string message)
- {
- // Ignore if the OAR save is being done by some other part of the system
- if (m_pendingSaves.ContainsKey(guid))
+ catch (Exception Ex)
{
- AutoBackupModuleState abms = m_states[(m_pendingSaves[guid])];
- ExecuteScript(abms.Script, abms.LiveRequests[guid]);
- m_pendingSaves.Remove(guid);
- abms.LiveRequests.Remove(guid);
+ m_log.Error("[AUTO BACKUP]: Error reading backup folder " + m_backupDir + ": " + Ex.Message);
+ return;
+ }
+
+ DateTime CuttOffDate = DateTime.Now.AddDays(-m_KeepFilesForDays);
+
+ foreach (string file in files)
+ {
+ try
+ {
+ FileInfo fi = new FileInfo(file);
+ if (fi.CreationTime < CuttOffDate)
+ fi.Delete();
+ }
+ catch (Exception Ex)
+ {
+ m_log.Error("[AUTO BACKUP]: Error deleting old backup file '" + file + "': " + Ex.Message);
+ }
}
}
@@ -817,63 +571,6 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
return output;
}
- /// Return value of true ==> not too busy; false ==> too busy to backup an OAR right now, or error.
- private bool RunHeuristics(IScene region)
- {
- try
- {
- return this.RunTimeDilationHeuristic(region) && this.RunAgentLimitHeuristic(region);
- }
- catch (Exception e)
- {
- m_log.Warn("[AUTO BACKUP]: Exception in RunHeuristics", e);
- return false;
- }
- }
-
- ///
- /// If the time dilation right at this instant is less than the threshold specified in AutoBackupDilationThreshold (default 0.5),
- /// then we return false and trip the busy heuristic's "too busy" path (i.e. don't save an OAR).
- /// AutoBackupDilationThreshold is a _LOWER BOUND_. Lower Time Dilation is bad, so if you go lower than our threshold, it's "too busy".
- ///
- ///
- /// Returns true if we're not too busy; false means we've got worse time dilation than the threshold.
- private bool RunTimeDilationHeuristic(IScene region)
- {
- string regionName = region.RegionInfo.RegionName;
- return region.TimeDilation >=
- this.m_configSource.Configs["AutoBackupModule"].GetFloat(
- regionName + ".AutoBackupDilationThreshold", 0.5f);
- }
-
- ///
- /// If the root agent count right at this instant is less than the threshold specified in AutoBackupAgentThreshold (default 10),
- /// then we return false and trip the busy heuristic's "too busy" path (i.e., don't save an OAR).
- /// AutoBackupAgentThreshold is an _UPPER BOUND_. Higher Agent Count is bad, so if you go higher than our threshold, it's "too busy".
- ///
- ///
- /// Returns true if we're not too busy; false means we've got more agents on the sim than the threshold.
- private bool RunAgentLimitHeuristic(IScene region)
- {
- string regionName = region.RegionInfo.RegionName;
- try
- {
- Scene scene = (Scene) region;
- // TODO: Why isn't GetRootAgentCount() a method in the IScene interface? Seems generally useful...
- return scene.GetRootAgentCount() <=
- this.m_configSource.Configs["AutoBackupModule"].GetInt(
- regionName + ".AutoBackupAgentThreshold", 10);
- }
- catch (InvalidCastException ice)
- {
- m_log.Debug(
- "[AUTO BACKUP]: I NEED MAINTENANCE: IScene is not a Scene; can't get root agent count!",
- ice);
- return true;
- // Non-obstructionist safest answer...
- }
- }
-
///
/// Run the script or executable specified by the "AutoBackupScript" config setting.
/// Of course this is a security risk if you let anyone modify OpenSim.ini and they want to run some nasty bash script.
@@ -919,18 +616,6 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
" is yacking on stderr: " + e.Data);
}
- ///
- /// Quickly stop all timers from firing.
- ///
- private void StopAllTimers()
- {
- foreach (Timer t in this.m_timerMap.Keys)
- {
- t.Close();
- }
- this.m_closed = true;
- }
-
///
/// Determine the next unique filename by number, for "Sequential" AutoBackupNamingType.
///
@@ -1033,5 +718,3 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
}
}
}
-
-
diff --git a/OpenSim/Region/OptionalModules/World/AutoBackup/AutoBackupModuleState.cs b/OpenSim/Region/OptionalModules/World/AutoBackup/AutoBackupModuleState.cs
index b90f0c4740..fb87677d62 100644
--- a/OpenSim/Region/OptionalModules/World/AutoBackup/AutoBackupModuleState.cs
+++ b/OpenSim/Region/OptionalModules/World/AutoBackup/AutoBackupModuleState.cs
@@ -38,26 +38,20 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
///
public class AutoBackupModuleState
{
- private Dictionary m_liveRequests = null;
-
public AutoBackupModuleState()
{
- this.Enabled = false;
- this.BackupDir = ".";
- this.BusyCheck = true;
- this.SkipAssets = false;
- this.Timer = null;
- this.NamingType = NamingType.Time;
- this.Script = null;
- this.KeepFilesForDays = 0;
+ Enabled = false;
+ SkipAssets = false;
+ NamingType = NamingType.Time;
+ Script = null;
}
- public Dictionary LiveRequests
+ public AutoBackupModuleState(AutoBackupModuleState copyFrom)
{
- get {
- return this.m_liveRequests ??
- (this.m_liveRequests = new Dictionary(1));
- }
+ Enabled = copyFrom.Enabled;
+ SkipAssets = copyFrom.SkipAssets;
+ NamingType = copyFrom.NamingType;
+ Script = copyFrom.Script;
}
public bool Enabled
@@ -66,33 +60,6 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
set;
}
- public System.Timers.Timer Timer
- {
- get;
- set;
- }
-
- public double IntervalMinutes
- {
- get
- {
- if (this.Timer == null)
- {
- return -1.0;
- }
- else
- {
- return this.Timer.Interval / 60000.0;
- }
- }
- }
-
- public bool BusyCheck
- {
- get;
- set;
- }
-
public bool SkipAssets
{
get;
@@ -105,36 +72,19 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
set;
}
- public string BackupDir
- {
- get;
- set;
- }
-
public NamingType NamingType
{
get;
set;
}
- public int KeepFilesForDays
- {
- get;
- set;
- }
-
public new string ToString()
{
string retval = "";
-
retval += "[AUTO BACKUP]: AutoBackup: " + (Enabled ? "ENABLED" : "DISABLED") + "\n";
- retval += "[AUTO BACKUP]: Interval: " + IntervalMinutes + " minutes" + "\n";
- retval += "[AUTO BACKUP]: Do Busy Check: " + (BusyCheck ? "Yes" : "No") + "\n";
retval += "[AUTO BACKUP]: Naming Type: " + NamingType.ToString() + "\n";
- retval += "[AUTO BACKUP]: Backup Dir: " + BackupDir + "\n";
retval += "[AUTO BACKUP]: Script: " + Script + "\n";
return retval;
}
}
}
-
diff --git a/OpenSim/Region/OptionalModules/World/MoneyModule/SampleMoneyModule.cs b/OpenSim/Region/OptionalModules/World/MoneyModule/SampleMoneyModule.cs
index 47edeb9221..3666c3f2fc 100644
--- a/OpenSim/Region/OptionalModules/World/MoneyModule/SampleMoneyModule.cs
+++ b/OpenSim/Region/OptionalModules/World/MoneyModule/SampleMoneyModule.cs
@@ -844,9 +844,14 @@ namespace OpenSim.Region.OptionalModules.World.MoneyModule
module.BuyObject(remoteClient, categoryID, localID, saleType, salePrice);
}
- public void MoveMoney(UUID fromAgentID, UUID toAgentID, int amount, string text)
+ public void MoveMoney(UUID fromUser, UUID toUser, int amount, string text)
{
}
+
+ public bool MoveMoney(UUID fromUser, UUID toUser, int amount, MoneyTransactionType type, string text)
+ {
+ return true;
+ }
}
public enum TransactionType : int
diff --git a/OpenSim/Region/OptionalModules/World/NPC/NPCAvatar.cs b/OpenSim/Region/OptionalModules/World/NPC/NPCAvatar.cs
index 6a7c735fd6..151a202e49 100644
--- a/OpenSim/Region/OptionalModules/World/NPC/NPCAvatar.cs
+++ b/OpenSim/Region/OptionalModules/World/NPC/NPCAvatar.cs
@@ -813,7 +813,11 @@ namespace OpenSim.Region.OptionalModules.World.NPC
{
}
- public void SendAvatarDataImmediate(ISceneEntity avatar)
+ public void SendEntityFullUpdateImmediate(ISceneEntity avatar)
+ {
+ }
+
+ public void SendEntityTerseUpdateImmediate(ISceneEntity ent)
{
}
diff --git a/OpenSim/Region/OptionalModules/World/SceneCommands/SceneCommandsModule.cs b/OpenSim/Region/OptionalModules/World/SceneCommands/SceneCommandsModule.cs
index d0d726c96b..7e3bd7f235 100644
--- a/OpenSim/Region/OptionalModules/World/SceneCommands/SceneCommandsModule.cs
+++ b/OpenSim/Region/OptionalModules/World/SceneCommands/SceneCommandsModule.cs
@@ -96,18 +96,11 @@ namespace OpenSim.Region.OptionalModules.Avatar.Attachments
"List current scene options.",
"active - if false then main scene update and maintenance loops are suspended.\n"
+ "animations - if true then extra animations debug information is logged.\n"
- + "appear-refresh - if true then appearance is resent to other avatars every 60 seconds.\n"
- + "client-pos-upd - the tolerance before clients are updated with new rotation information for an avatar.\n"
- + "client-rot-upd - the tolerance before clients are updated with new rotation information for an avatar.\n"
- + "client-vel-upd - the tolerance before clients are updated with new velocity information for an avatar.\n"
- + "root-upd-per - if greater than 1, terse updates are only sent to root agents other than the originator on every n updates.\n"
- + "child-upd-per - if greater than 1, terse updates are only sent to child agents on every n updates.\n"
+ "collisions - if false then collisions with other objects are turned off.\n"
+ "pbackup - if false then periodic scene backup is turned off.\n"
+ "physics - if false then all physics objects are non-physical.\n"
+ "scripting - if false then no scripting operations happen.\n"
+ "teleport - if true then some extra teleport debug information is logged.\n"
- + "update-on-timer - If true then the scene is updated via a timer. If false then a thread with sleep is used.\n"
+ "updates - if true then any frame which exceeds double the maximum desired frame time is logged.",
HandleDebugSceneGetCommand);
@@ -117,18 +110,11 @@ namespace OpenSim.Region.OptionalModules.Avatar.Attachments
"Turn on scene debugging options.",
"active - if false then main scene update and maintenance loops are suspended.\n"
+ "animations - if true then extra animations debug information is logged.\n"
- + "appear-refresh - if true then appearance is resent to other avatars every 60 seconds.\n"
- + "client-pos-upd - the tolerance before clients are updated with new rotation information for an avatar.\n"
- + "client-rot-upd - the tolerance before clients are updated with new rotation information for an avatar.\n"
- + "client-vel-upd - the tolerance before clients are updated with new velocity information for an avatar.\n"
- + "root-upd-per - if greater than 1, terse updates are only sent to root agents other than the originator on every n updates.\n"
- + "child-upd-per - if greater than 1, terse updates are only sent to child agents on every n updates.\n"
+ "collisions - if false then collisions with other objects are turned off.\n"
+ "pbackup - if false then periodic scene backup is turned off.\n"
+ "physics - if false then all physics objects are non-physical.\n"
+ "scripting - if false then no scripting operations happen.\n"
+ "teleport - if true then some extra teleport debug information is logged.\n"
- + "update-on-timer - If true then the scene is updated via a timer. If false then a thread with sleep is used.\n"
+ "updates - if true then any frame which exceeds double the maximum desired frame time is logged.",
HandleDebugSceneSetCommand);
}
@@ -153,17 +139,10 @@ namespace OpenSim.Region.OptionalModules.Avatar.Attachments
ConsoleDisplayList cdl = new ConsoleDisplayList();
cdl.AddRow("active", m_scene.Active);
cdl.AddRow("animations", m_scene.DebugAnimations);
- cdl.AddRow("appear-refresh", m_scene.SendPeriodicAppearanceUpdates);
- cdl.AddRow("client-pos-upd", m_scene.RootPositionUpdateTolerance);
- cdl.AddRow("client-rot-upd", m_scene.RootRotationUpdateTolerance);
- cdl.AddRow("client-vel-upd", m_scene.RootVelocityUpdateTolerance);
- cdl.AddRow("root-upd-per", m_scene.RootTerseUpdatePeriod);
- cdl.AddRow("child-upd-per", m_scene.ChildTerseUpdatePeriod);
cdl.AddRow("pbackup", m_scene.PeriodicBackup);
cdl.AddRow("physics", m_scene.PhysicsEnabled);
cdl.AddRow("scripting", m_scene.ScriptsEnabled);
cdl.AddRow("teleport", m_scene.DebugTeleporting);
-// cdl.AddRow("update-on-timer", m_scene.UpdateOnTimer);
cdl.AddRow("updates", m_scene.DebugUpdates);
MainConsole.Instance.OutputFormat("Scene {0} options:", m_scene.Name);
@@ -207,60 +186,6 @@ namespace OpenSim.Region.OptionalModules.Avatar.Attachments
m_scene.DebugAnimations = active;
}
- if (options.ContainsKey("appear-refresh"))
- {
- bool newValue;
-
- // FIXME: This can only come from the console at the moment but might not always be true.
- if (ConsoleUtil.TryParseConsoleBool(MainConsole.Instance, options["appear-refresh"], out newValue))
- m_scene.SendPeriodicAppearanceUpdates = newValue;
- }
-
- if (options.ContainsKey("client-pos-upd"))
- {
- float newValue;
-
- // FIXME: This can only come from the console at the moment but might not always be true.
- if (ConsoleUtil.TryParseConsoleFloat(MainConsole.Instance, options["client-pos-upd"], out newValue))
- m_scene.RootPositionUpdateTolerance = newValue;
- }
-
- if (options.ContainsKey("client-rot-upd"))
- {
- float newValue;
-
- // FIXME: This can only come from the console at the moment but might not always be true.
- if (ConsoleUtil.TryParseConsoleFloat(MainConsole.Instance, options["client-rot-upd"], out newValue))
- m_scene.RootRotationUpdateTolerance = newValue;
- }
-
- if (options.ContainsKey("client-vel-upd"))
- {
- float newValue;
-
- // FIXME: This can only come from the console at the moment but might not always be true.
- if (ConsoleUtil.TryParseConsoleFloat(MainConsole.Instance, options["client-vel-upd"], out newValue))
- m_scene.RootVelocityUpdateTolerance = newValue;
- }
-
- if (options.ContainsKey("root-upd-per"))
- {
- int newValue;
-
- // FIXME: This can only come from the console at the moment but might not always be true.
- if (ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, options["root-upd-per"], out newValue))
- m_scene.RootTerseUpdatePeriod = newValue;
- }
-
- if (options.ContainsKey("child-upd-per"))
- {
- int newValue;
-
- // FIXME: This can only come from the console at the moment but might not always be true.
- if (ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, options["child-upd-per"], out newValue))
- m_scene.ChildTerseUpdatePeriod = newValue;
- }
-
if (options.ContainsKey("pbackup"))
{
bool active;
@@ -296,21 +221,6 @@ namespace OpenSim.Region.OptionalModules.Avatar.Attachments
m_scene.DebugTeleporting = enableTeleportDebugging;
}
- if (options.ContainsKey("update-on-timer"))
- {
- bool enableUpdateOnTimer;
- if (bool.TryParse(options["update-on-timer"], out enableUpdateOnTimer))
- {
-// m_scene.UpdateOnTimer = enableUpdateOnTimer;
- m_scene.Active = false;
-
- while (m_scene.IsRunning)
- Thread.Sleep(20);
-
- m_scene.Active = true;
- }
- }
-
if (options.ContainsKey("updates"))
{
bool enableUpdateDebugging;
diff --git a/OpenSim/Region/OptionalModules/World/TreePopulator/TreePopulatorModule.cs b/OpenSim/Region/OptionalModules/World/TreePopulator/TreePopulatorModule.cs
index e22c6eae9a..6e1f8bb654 100644
--- a/OpenSim/Region/OptionalModules/World/TreePopulator/TreePopulatorModule.cs
+++ b/OpenSim/Region/OptionalModules/World/TreePopulator/TreePopulatorModule.cs
@@ -27,8 +27,13 @@
using System;
using System.Collections.Generic;
+using System.IO;
using System.Reflection;
using System.Timers;
+using System.Threading;
+using System.Xml;
+using System.Xml.Serialization;
+
using OpenMetaverse;
using log4net;
using Mono.Addins;
@@ -38,9 +43,7 @@ using OpenSim.Region.CoreModules.Framework.InterfaceCommander;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
-using System.Xml;
-using System.Xml.Serialization;
-using System.IO;
+using Timer= System.Timers.Timer;
namespace OpenSim.Region.OptionalModules.World.TreePopulator
{
@@ -48,7 +51,7 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
/// Version 2.02 - Still hacky
///
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "TreePopulatorModule")]
- public class TreePopulatorModule : INonSharedRegionModule, ICommandableModule, IVegetationModule
+ public class TreePopulatorModule : INonSharedRegionModule, ICommandableModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private readonly Commander m_commander = new Commander("tree");
@@ -82,20 +85,20 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
{
Copse cp = (Copse)DeserializeObject(fileName);
- this.m_name = cp.m_name;
- this.m_frozen = cp.m_frozen;
- this.m_tree_quantity = cp.m_tree_quantity;
- this.m_treeline_high = cp.m_treeline_high;
- this.m_treeline_low = cp.m_treeline_low;
- this.m_range = cp.m_range;
- this.m_tree_type = cp.m_tree_type;
- this.m_seed_point = cp.m_seed_point;
- this.m_initial_scale = cp.m_initial_scale;
- this.m_maximum_scale = cp.m_maximum_scale;
- this.m_initial_scale = cp.m_initial_scale;
- this.m_rate = cp.m_rate;
- this.m_planted = planted;
- this.m_trees = new List();
+ m_name = cp.m_name;
+ m_frozen = cp.m_frozen;
+ m_tree_quantity = cp.m_tree_quantity;
+ m_treeline_high = cp.m_treeline_high;
+ m_treeline_low = cp.m_treeline_low;
+ m_range = cp.m_range;
+ m_tree_type = cp.m_tree_type;
+ m_seed_point = cp.m_seed_point;
+ m_initial_scale = cp.m_initial_scale;
+ m_maximum_scale = cp.m_maximum_scale;
+ m_initial_scale = cp.m_initial_scale;
+ m_rate = cp.m_rate;
+ m_planted = planted;
+ m_trees = new List();
}
public Copse(string copsedef)
@@ -103,61 +106,63 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
char[] delimiterChars = {':', ';'};
string[] field = copsedef.Split(delimiterChars);
- this.m_name = field[1].Trim();
- this.m_frozen = (copsedef[0] == 'F');
- this.m_tree_quantity = int.Parse(field[2]);
- this.m_treeline_high = float.Parse(field[3], Culture.NumberFormatInfo);
- this.m_treeline_low = float.Parse(field[4], Culture.NumberFormatInfo);
- this.m_range = double.Parse(field[5], Culture.NumberFormatInfo);
- this.m_tree_type = (Tree) Enum.Parse(typeof(Tree),field[6]);
- this.m_seed_point = Vector3.Parse(field[7]);
- this.m_initial_scale = Vector3.Parse(field[8]);
- this.m_maximum_scale = Vector3.Parse(field[9]);
- this.m_rate = Vector3.Parse(field[10]);
- this.m_planted = true;
- this.m_trees = new List();
+ m_name = field[1].Trim();
+ m_frozen = (copsedef[0] == 'F');
+ m_tree_quantity = int.Parse(field[2]);
+ m_treeline_high = float.Parse(field[3], Culture.NumberFormatInfo);
+ m_treeline_low = float.Parse(field[4], Culture.NumberFormatInfo);
+ m_range = double.Parse(field[5], Culture.NumberFormatInfo);
+ m_tree_type = (Tree) Enum.Parse(typeof(Tree),field[6]);
+ m_seed_point = Vector3.Parse(field[7]);
+ m_initial_scale = Vector3.Parse(field[8]);
+ m_maximum_scale = Vector3.Parse(field[9]);
+ m_rate = Vector3.Parse(field[10]);
+ m_planted = true;
+ m_trees = new List();
}
public Copse(string name, int quantity, float high, float low, double range, Vector3 point, Tree type, Vector3 scale, Vector3 max_scale, Vector3 rate, List trees)
{
- this.m_name = name;
- this.m_frozen = false;
- this.m_tree_quantity = quantity;
- this.m_treeline_high = high;
- this.m_treeline_low = low;
- this.m_range = range;
- this.m_tree_type = type;
- this.m_seed_point = point;
- this.m_initial_scale = scale;
- this.m_maximum_scale = max_scale;
- this.m_rate = rate;
- this.m_planted = false;
- this.m_trees = trees;
+ m_name = name;
+ m_frozen = false;
+ m_tree_quantity = quantity;
+ m_treeline_high = high;
+ m_treeline_low = low;
+ m_range = range;
+ m_tree_type = type;
+ m_seed_point = point;
+ m_initial_scale = scale;
+ m_maximum_scale = max_scale;
+ m_rate = rate;
+ m_planted = false;
+ m_trees = trees;
}
public override string ToString()
{
- string frozen = (this.m_frozen ? "F" : "A");
+ string frozen = (m_frozen ? "F" : "A");
return string.Format("{0}TPM: {1}; {2}; {3:0.0}; {4:0.0}; {5:0.0}; {6}; {7:0.0}; {8:0.0}; {9:0.0}; {10:0.00};",
frozen,
- this.m_name,
- this.m_tree_quantity,
- this.m_treeline_high,
- this.m_treeline_low,
- this.m_range,
- this.m_tree_type,
- this.m_seed_point.ToString(),
- this.m_initial_scale.ToString(),
- this.m_maximum_scale.ToString(),
- this.m_rate.ToString());
+ m_name,
+ m_tree_quantity,
+ m_treeline_high,
+ m_treeline_low,
+ m_range,
+ m_tree_type,
+ m_seed_point.ToString(),
+ m_initial_scale.ToString(),
+ m_maximum_scale.ToString(),
+ m_rate.ToString());
}
}
- private List m_copse;
-
+ private List m_copses = new List();
+ private object mylock;
private double m_update_ms = 1000.0; // msec between updates
private bool m_active_trees = false;
+ private bool m_enabled = true; // original default
+ private bool m_allowGrow = true; // original default
Timer CalculateTrees;
@@ -174,51 +179,51 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
public void Initialise(IConfigSource config)
{
-
- // ini file settings
- try
+ IConfig moduleConfig = config.Configs["Trees"];
+ if (moduleConfig != null)
{
- m_active_trees = config.Configs["Trees"].GetBoolean("active_trees", m_active_trees);
- }
- catch (Exception)
- {
- m_log.Debug("[TREES]: ini failure for active_trees - using default");
+ m_enabled = moduleConfig.GetBoolean("enabled", m_enabled);
+ m_active_trees = moduleConfig.GetBoolean("active_trees", m_active_trees);
+ m_allowGrow = moduleConfig.GetBoolean("allowGrow", m_allowGrow);
+ m_update_ms = moduleConfig.GetDouble("update_rate", m_update_ms);
}
- try
- {
- m_update_ms = config.Configs["Trees"].GetDouble("update_rate", m_update_ms);
- }
- catch (Exception)
- {
- m_log.Debug("[TREES]: ini failure for update_rate - using default");
- }
+ if(!m_enabled)
+ return;
+
+ m_copses = new List();
+ mylock = new object();
InstallCommands();
- m_log.Debug("[TREES]: Initialised tree module");
+ m_log.Debug("[TREES]: Initialised tree populator module");
}
public void AddRegion(Scene scene)
{
+ if(!m_enabled)
+ return;
m_scene = scene;
m_scene.RegisterModuleCommander(m_commander);
m_scene.EventManager.OnPluginConsole += EventManager_OnPluginConsole;
-
+ m_scene.EventManager.OnPrimsLoaded += EventManager_OnPrimsLoaded;
}
public void RemoveRegion(Scene scene)
{
- }
+ if(!m_enabled)
+ return;
+ if(m_active_trees && CalculateTrees != null)
+ {
+ CalculateTrees.Dispose();
+ CalculateTrees = null;
+ }
+ m_scene.EventManager.OnPluginConsole -= EventManager_OnPluginConsole;
+ m_scene.EventManager.OnPrimsLoaded -= EventManager_OnPrimsLoaded;
+ }
public void RegionLoaded(Scene scene)
{
- ReloadCopse();
- if (m_copse.Count > 0)
- m_log.Info("[TREES]: Copse load complete");
-
- if (m_active_trees)
- activeizeTreeze(true);
}
public void Close()
@@ -240,6 +245,16 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
//--------------------------------------------------------------
+ private void EventManager_OnPrimsLoaded(Scene s)
+ {
+ ReloadCopse();
+ if (m_copses.Count > 0)
+ m_log.Info("[TREES]: Copses loaded" );
+
+ if (m_active_trees)
+ activeizeTreeze(true);
+ }
+
#region ICommandableModule Members
private void HandleTreeActive(Object[] args)
@@ -267,25 +282,57 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
string copsename = ((string)args[0]).Trim();
Boolean freezeState = (Boolean) args[1];
- foreach (Copse cp in m_copse)
+ lock(mylock)
{
- if (cp.m_name == copsename && (!cp.m_frozen && freezeState || cp.m_frozen && !freezeState))
+ foreach (Copse cp in m_copses)
{
- cp.m_frozen = freezeState;
- foreach (UUID tree in cp.m_trees)
- {
- SceneObjectPart sop = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
- sop.Name = (freezeState ? sop.Name.Replace("ATPM", "FTPM") : sop.Name.Replace("FTPM", "ATPM"));
- sop.ParentGroup.HasGroupChanged = true;
- }
+ if (cp.m_name != copsename)
+ continue;
- m_log.InfoFormat("[TREES]: Activity for copse {0} is frozen {1}", copsename, freezeState);
- return;
- }
- else if (cp.m_name == copsename && (cp.m_frozen && freezeState || !cp.m_frozen && !freezeState))
- {
- m_log.InfoFormat("[TREES]: Copse {0} is already in the requested freeze state", copsename);
- return;
+ if(!cp.m_frozen && freezeState || cp.m_frozen && !freezeState)
+ {
+ cp.m_frozen = freezeState;
+ List losttrees = new List();
+ foreach (UUID tree in cp.m_trees)
+ {
+ SceneObjectGroup sog = m_scene.GetSceneObjectGroup(tree);
+ if(sog != null && !sog.IsDeleted)
+ {
+ SceneObjectPart sop = sog.RootPart;
+ string name = sop.Name;
+ if(freezeState)
+ {
+ if(name.StartsWith("FTPM"))
+ continue;
+ if(!name.StartsWith("ATPM"))
+ continue;
+ sop.Name = sop.Name.Replace("ATPM", "FTPM");
+ }
+ else
+ {
+ if(name.StartsWith("ATPM"))
+ continue;
+ if(!name.StartsWith("FTPM"))
+ continue;
+ sop.Name = sop.Name.Replace("FTPM", "ATPM");
+ }
+ sop.ParentGroup.HasGroupChanged = true;
+ sog.ScheduleGroupForFullUpdate();
+ }
+ else
+ losttrees.Add(tree);
+ }
+ foreach (UUID tree in losttrees)
+ cp.m_trees.Remove(tree);
+
+ m_log.InfoFormat("[TREES]: Activity for copse {0} is frozen {1}", copsename, freezeState);
+ return;
+ }
+ else
+ {
+ m_log.InfoFormat("[TREES]: Copse {0} is already in the requested freeze state", copsename);
+ return;
+ }
}
}
m_log.InfoFormat("[TREES]: Copse {0} was not found - command failed", copsename);
@@ -297,17 +344,21 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
m_log.InfoFormat("[TREES]: Loading copse definition....");
- copse = new Copse(((string)args[0]), false);
- foreach (Copse cp in m_copse)
+ lock(mylock)
{
- if (cp.m_name == copse.m_name)
+ copse = new Copse(((string)args[0]), false);
{
- m_log.InfoFormat("[TREES]: Copse: {0} is already defined - command failed", copse.m_name);
- return;
+ foreach (Copse cp in m_copses)
+ {
+ if (cp.m_name == copse.m_name)
+ {
+ m_log.InfoFormat("[TREES]: Copse: {0} is already defined - command failed", copse.m_name);
+ return;
+ }
+ }
}
+ m_copses.Add(copse);
}
-
- m_copse.Add(copse);
m_log.InfoFormat("[TREES]: Loaded copse: {0}", copse.ToString());
}
@@ -318,20 +369,24 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
m_log.InfoFormat("[TREES]: New tree planting for copse {0}", copsename);
UUID uuid = m_scene.RegionInfo.EstateSettings.EstateOwner;
- foreach (Copse copse in m_copse)
+ lock(mylock)
{
- if (copse.m_name == copsename)
+ foreach (Copse copse in m_copses)
{
- if (!copse.m_planted)
+ if (copse.m_name == copsename)
{
- // The first tree for a copse is created here
- CreateTree(uuid, copse, copse.m_seed_point);
- copse.m_planted = true;
- return;
- }
- else
- {
- m_log.InfoFormat("[TREES]: Copse {0} has already been planted", copsename);
+ if (!copse.m_planted)
+ {
+ // The first tree for a copse is created here
+ CreateTree(uuid, copse, copse.m_seed_point, true);
+ copse.m_planted = true;
+ return;
+ }
+ else
+ {
+ m_log.InfoFormat("[TREES]: Copse {0} has already been planted", copsename);
+ return;
+ }
}
}
}
@@ -376,45 +431,49 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
string copsename = ((string)args[0]).Trim();
Copse copseIdentity = null;
- foreach (Copse cp in m_copse)
+ lock(mylock)
{
- if (cp.m_name == copsename)
+ foreach (Copse cp in m_copses)
{
- copseIdentity = cp;
+ if (cp.m_name == copsename)
+ {
+ copseIdentity = cp;
+ }
}
- }
- if (copseIdentity != null)
- {
- foreach (UUID tree in copseIdentity.m_trees)
+ if (copseIdentity != null)
{
- if (m_scene.Entities.ContainsKey(tree))
+ foreach (UUID tree in copseIdentity.m_trees)
{
- SceneObjectPart selectedTree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
- // Delete tree and alert clients (not silent)
- m_scene.DeleteSceneObject(selectedTree.ParentGroup, false);
- }
- else
- {
- m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
+ if (m_scene.Entities.ContainsKey(tree))
+ {
+ SceneObjectPart selectedTree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
+ // Delete tree and alert clients (not silent)
+ m_scene.DeleteSceneObject(selectedTree.ParentGroup, false);
+ }
+ else
+ {
+ m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
+ }
}
+ copseIdentity.m_trees = null;
+ m_copses.Remove(copseIdentity);
+ m_log.InfoFormat("[TREES]: Copse {0} has been removed", copsename);
+ }
+ else
+ {
+ m_log.InfoFormat("[TREES]: Copse {0} was not found - command failed", copsename);
}
- copseIdentity.m_trees = new List();
- m_copse.Remove(copseIdentity);
- m_log.InfoFormat("[TREES]: Copse {0} has been removed", copsename);
- }
- else
- {
- m_log.InfoFormat("[TREES]: Copse {0} was not found - command failed", copsename);
}
}
private void HandleTreeStatistics(Object[] args)
{
- m_log.InfoFormat("[TREES]: Activity State: {0}; Update Rate: {1}", m_active_trees, m_update_ms);
- foreach (Copse cp in m_copse)
+ m_log.InfoFormat("[TREES]: region {0}:", m_scene.Name);
+ m_log.InfoFormat("[TREES]: Activity State: {0}; Update Rate: {1}", m_active_trees, m_update_ms);
+ foreach (Copse cp in m_copses)
{
- m_log.InfoFormat("[TREES]: Copse {0}; {1} trees; frozen {2}", cp.m_name, cp.m_trees.Count, cp.m_frozen);
+ m_log.InfoFormat("[TREES]: Copse {0}; {1} trees; frozen {2}", cp.m_name, cp.m_trees.Count, cp.m_frozen);
}
}
@@ -442,7 +501,7 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
treeRateCommand.AddArgument("updateRate", "The required update rate (minimum 1000.0)", "Double");
Command treeReloadCommand =
- new Command("reload", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeReload, "Reload copse definitions from the in-scene trees");
+ new Command("reload", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeReload, "Reload copses from the in-scene trees");
Command treeRemoveCommand =
new Command("remove", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeRemove, "Remove a copse definition and all its in-scene trees");
@@ -499,34 +558,17 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
treeShape.Scale = scale;
treeShape.State = (byte)treeType;
- return m_scene.AddNewPrim(uuid, groupID, position, rotation, treeShape);
- }
-
- #endregion
-
- #region IEntityCreator Members
-
- protected static readonly PCode[] creationCapabilities = new PCode[] { PCode.NewTree, PCode.Tree };
- public PCode[] CreationCapabilities { get { return creationCapabilities; } }
-
- public SceneObjectGroup CreateEntity(
- UUID ownerID, UUID groupID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape)
- {
- if (Array.IndexOf(creationCapabilities, (PCode)shape.PCode) < 0)
- {
- m_log.DebugFormat("[VEGETATION]: PCode {0} not handled by {1}", shape.PCode, Name);
- return null;
- }
-
- SceneObjectGroup sceneObject = new SceneObjectGroup(ownerID, pos, rot, shape);
- SceneObjectPart rootPart = sceneObject.GetPart(sceneObject.UUID);
+ SceneObjectGroup sog = new SceneObjectGroup(uuid, position, rotation, treeShape);
+ SceneObjectPart rootPart = sog.RootPart;
rootPart.AddFlag(PrimFlags.Phantom);
- m_scene.AddNewSceneObject(sceneObject, true);
- sceneObject.SetGroup(groupID, null);
-
- return sceneObject;
+ sog.SetGroup(groupID, null);
+ m_scene.AddNewSceneObject(sog, true, false);
+ sog.IsSelected = false;
+ rootPart.IsSelected = false;
+ sog.InvalidateEffectivePerms();
+ return sog;
}
#endregion
@@ -569,26 +611,27 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
private void ReloadCopse()
{
- m_copse = new List();
+ m_copses = new List();
- EntityBase[] objs = m_scene.GetEntities();
- foreach (EntityBase obj in objs)
+ List grps = m_scene.GetSceneObjectGroups();
+ foreach (SceneObjectGroup grp in grps)
{
- if (obj is SceneObjectGroup)
+ if(grp.RootPart.Shape.PCode != (byte)PCode.NewTree && grp.RootPart.Shape.PCode != (byte)PCode.Tree)
+ continue;
+
+ if (grp.Name.Length > 5 && (grp.Name.Substring(0, 5) == "ATPM:" || grp.Name.Substring(0, 5) == "FTPM:"))
{
- SceneObjectGroup grp = (SceneObjectGroup)obj;
-
- if (grp.Name.Length > 5 && (grp.Name.Substring(0, 5) == "ATPM:" || grp.Name.Substring(0, 5) == "FTPM:"))
+ // Create a new copse definition or add uuid to an existing definition
+ try
{
- // Create a new copse definition or add uuid to an existing definition
- try
- {
- Boolean copsefound = false;
- Copse copse = new Copse(grp.Name);
+ Boolean copsefound = false;
+ Copse grpcopse = new Copse(grp.Name);
- foreach (Copse cp in m_copse)
+ lock(mylock)
+ {
+ foreach (Copse cp in m_copses)
{
- if (cp.m_name == copse.m_name)
+ if (cp.m_name == grpcopse.m_name)
{
copsefound = true;
cp.m_trees.Add(grp.UUID);
@@ -598,15 +641,15 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
if (!copsefound)
{
- m_log.InfoFormat("[TREES]: Found copse {0}", grp.Name);
- m_copse.Add(copse);
- copse.m_trees.Add(grp.UUID);
+ m_log.InfoFormat("[TREES]: adding copse {0}", grpcopse.m_name);
+ grpcopse.m_trees.Add(grp.UUID);
+ m_copses.Add(grpcopse);
}
}
- catch
- {
- m_log.InfoFormat("[TREES]: Ill formed copse definition {0} - ignoring", grp.Name);
- }
+ }
+ catch
+ {
+ m_log.InfoFormat("[TREES]: Ill formed copse definition {0} - ignoring", grp.Name);
}
}
}
@@ -617,8 +660,10 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
{
if (activeYN)
{
- CalculateTrees = new Timer(m_update_ms);
+ if(CalculateTrees == null)
+ CalculateTrees = new Timer(m_update_ms);
CalculateTrees.Elapsed += CalculateTrees_Elapsed;
+ CalculateTrees.AutoReset = false;
CalculateTrees.Start();
}
else
@@ -629,154 +674,251 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
private void growTrees()
{
- foreach (Copse copse in m_copse)
- {
- if (!copse.m_frozen)
- {
- foreach (UUID tree in copse.m_trees)
- {
- if (m_scene.Entities.ContainsKey(tree))
- {
- SceneObjectPart s_tree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
+ if(!m_allowGrow)
+ return;
- if (s_tree.Scale.X < copse.m_maximum_scale.X && s_tree.Scale.Y < copse.m_maximum_scale.Y && s_tree.Scale.Z < copse.m_maximum_scale.Z)
- {
- s_tree.Scale += copse.m_rate;
- s_tree.ParentGroup.HasGroupChanged = true;
- s_tree.ScheduleFullUpdate();
- }
- }
- else
+ foreach (Copse copse in m_copses)
+ {
+ if (copse.m_frozen)
+ continue;
+
+ if(copse.m_trees.Count == 0)
+ continue;
+
+ float maxscale = copse.m_maximum_scale.Z;
+ float ratescale = 1.0f;
+ List losttrees = new List();
+ foreach (UUID tree in copse.m_trees)
+ {
+ SceneObjectGroup sog = m_scene.GetSceneObjectGroup(tree);
+
+ if (sog != null && !sog.IsDeleted)
+ {
+ SceneObjectPart s_tree = sog.RootPart;
+ if (s_tree.Scale.Z < maxscale)
{
- m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
+ ratescale = (float)Util.RandomClass.NextDouble();
+ if(ratescale < 0.2f)
+ ratescale = 0.2f;
+ s_tree.Scale += copse.m_rate * ratescale;
+ sog.HasGroupChanged = true;
+ s_tree.ScheduleFullUpdate();
}
}
+ else
+ losttrees.Add(tree);
}
+
+ foreach (UUID tree in losttrees)
+ copse.m_trees.Remove(tree);
}
}
private void seedTrees()
{
- foreach (Copse copse in m_copse)
+ foreach (Copse copse in m_copses)
{
- if (!copse.m_frozen)
- {
- foreach (UUID tree in copse.m_trees)
- {
- if (m_scene.Entities.ContainsKey(tree))
- {
- SceneObjectPart s_tree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
+ if (copse.m_frozen)
+ continue;
- if (copse.m_trees.Count < copse.m_tree_quantity)
- {
- // Tree has grown enough to seed if it has grown by at least 25% of seeded to full grown height
- if (s_tree.Scale.Z > copse.m_initial_scale.Z + (copse.m_maximum_scale.Z - copse.m_initial_scale.Z) / 4.0)
- {
- if (Util.RandomClass.NextDouble() > 0.75)
- {
- SpawnChild(copse, s_tree);
- }
- }
- }
- }
- else
- {
- m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
- }
+ if(copse.m_trees.Count == 0)
+ return;
+
+ bool low = copse.m_trees.Count < (int)(copse.m_tree_quantity * 0.8f);
+
+ if (!low && Util.RandomClass.NextDouble() < 0.75)
+ return;
+
+ int maxbirths = (int)(copse.m_tree_quantity) - copse.m_trees.Count;
+ if(maxbirths <= 1)
+ return;
+
+ if(maxbirths > 20)
+ maxbirths = 20;
+
+ float minscale = 0;
+ if(!low && m_allowGrow)
+ minscale = copse.m_maximum_scale.Z * 0.75f;;
+
+ int i = 0;
+ UUID[] current = copse.m_trees.ToArray();
+ while(--maxbirths > 0)
+ {
+ if(current.Length > 1)
+ i = Util.RandomClass.Next(current.Length -1);
+
+ UUID tree = current[i];
+ SceneObjectGroup sog = m_scene.GetSceneObjectGroup(tree);
+
+ if (sog != null && !sog.IsDeleted)
+ {
+ SceneObjectPart s_tree = sog.RootPart;
+
+ // Tree has grown enough to seed if it has grown by at least 25% of seeded to full grown height
+ if (s_tree.Scale.Z > minscale)
+ SpawnChild(copse, s_tree, true);
}
- }
+ else if(copse.m_trees.Contains(tree))
+ copse.m_trees.Remove(tree);
+ }
}
}
private void killTrees()
{
- foreach (Copse copse in m_copse)
+ foreach (Copse copse in m_copses)
{
- if (!copse.m_frozen && copse.m_trees.Count >= copse.m_tree_quantity)
+ if (copse.m_frozen)
+ continue;
+
+ if (Util.RandomClass.NextDouble() < 0.25)
+ return;
+
+ int maxbdeaths = copse.m_trees.Count - (int)(copse.m_tree_quantity * .98f) ;
+ if(maxbdeaths < 1)
+ return;
+
+ float odds;
+ float scale = 1.0f / copse.m_maximum_scale.Z;
+
+ int ntries = maxbdeaths * 4;
+ while(ntries-- > 0 )
{
- foreach (UUID tree in copse.m_trees)
+ int next = 0;
+ if (copse.m_trees.Count > 1)
+ next = Util.RandomClass.Next(copse.m_trees.Count - 1);
+ UUID tree = copse.m_trees[next];
+ SceneObjectGroup sog = m_scene.GetSceneObjectGroup(tree);
+ if (sog != null && !sog.IsDeleted)
{
- double killLikelyhood = 0.0;
-
- if (m_scene.Entities.ContainsKey(tree))
+ if(m_allowGrow)
{
- SceneObjectPart selectedTree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
- double selectedTreeScale = Math.Sqrt(Math.Pow(selectedTree.Scale.X, 2) +
- Math.Pow(selectedTree.Scale.Y, 2) +
- Math.Pow(selectedTree.Scale.Z, 2));
-
- foreach (UUID picktree in copse.m_trees)
- {
- if (picktree != tree)
- {
- SceneObjectPart pickedTree = ((SceneObjectGroup)m_scene.Entities[picktree]).RootPart;
-
- double pickedTreeScale = Math.Sqrt(Math.Pow(pickedTree.Scale.X, 2) +
- Math.Pow(pickedTree.Scale.Y, 2) +
- Math.Pow(pickedTree.Scale.Z, 2));
-
- double pickedTreeDistance = Vector3.Distance(pickedTree.AbsolutePosition, selectedTree.AbsolutePosition);
-
- killLikelyhood += (selectedTreeScale / (pickedTreeScale * pickedTreeDistance)) * 0.1;
- }
- }
-
- if (Util.RandomClass.NextDouble() < killLikelyhood)
- {
- // Delete tree and alert clients (not silent)
- m_scene.DeleteSceneObject(selectedTree.ParentGroup, false);
- copse.m_trees.Remove(selectedTree.ParentGroup.UUID);
- break;
- }
+ odds = sog.RootPart.Scale.Z * scale;
+ odds = odds * odds * odds;
+ odds *= (float)Util.RandomClass.NextDouble();
}
else
{
- m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
+ odds = (float)Util.RandomClass.NextDouble();
+ odds = odds * odds * odds;
}
+
+ if(odds > 0.9f)
+ {
+ m_scene.DeleteSceneObject(sog, false);
+ if(maxbdeaths <= 0)
+ break;
+ }
+ }
+ else
+ {
+ copse.m_trees.Remove(tree);
+ if(copse.m_trees.Count - (int)(copse.m_tree_quantity * .98f) <= 0 )
+ break;
}
}
}
}
- private void SpawnChild(Copse copse, SceneObjectPart s_tree)
+ private void SpawnChild(Copse copse, SceneObjectPart s_tree, bool low)
{
Vector3 position = new Vector3();
-
- double randX = ((Util.RandomClass.NextDouble() * 2.0) - 1.0) * (s_tree.Scale.X * 3);
- double randY = ((Util.RandomClass.NextDouble() * 2.0) - 1.0) * (s_tree.Scale.X * 3);
-
+
+ float randX = copse.m_maximum_scale.X * 1.25f;
+ float randY = copse.m_maximum_scale.Y * 1.25f;
+
+ float r = (float)Util.RandomClass.NextDouble();
+ randX *= 2.0f * r - 1.0f;
position.X = s_tree.AbsolutePosition.X + (float)randX;
+
+ r = (float)Util.RandomClass.NextDouble();
+ randY *= 2.0f * r - 1.0f;
position.Y = s_tree.AbsolutePosition.Y + (float)randY;
- if (position.X <= (m_scene.RegionInfo.RegionSizeX - 1) && position.X >= 0 &&
- position.Y <= (m_scene.RegionInfo.RegionSizeY - 1) && position.Y >= 0 &&
- Util.GetDistanceTo(position, copse.m_seed_point) <= copse.m_range)
- {
- UUID uuid = m_scene.RegionInfo.EstateSettings.EstateOwner;
+ if (position.X > (m_scene.RegionInfo.RegionSizeX - 1) || position.X <= 0 ||
+ position.Y > (m_scene.RegionInfo.RegionSizeY - 1) || position.Y <= 0)
+ return;
- CreateTree(uuid, copse, position);
- }
+ randX = position.X - copse.m_seed_point.X;
+ randX *= randX;
+ randY = position.Y - copse.m_seed_point.Y;
+ randY *= randY;
+ randX += randY;
+
+ if(randX > copse.m_range * copse.m_range)
+ return;
+
+ UUID uuid = m_scene.RegionInfo.EstateSettings.EstateOwner;
+ CreateTree(uuid, copse, position, low);
}
- private void CreateTree(UUID uuid, Copse copse, Vector3 position)
+ private void CreateTree(UUID uuid, Copse copse, Vector3 position, bool randomScale)
{
-
position.Z = (float)m_scene.Heightmap[(int)position.X, (int)position.Y];
- if (position.Z >= copse.m_treeline_low && position.Z <= copse.m_treeline_high)
- {
- SceneObjectGroup tree = AddTree(uuid, UUID.Zero, copse.m_initial_scale, Quaternion.Identity, position, copse.m_tree_type, false);
+ if (position.Z < copse.m_treeline_low || position.Z > copse.m_treeline_high)
+ return;
- tree.Name = copse.ToString();
- copse.m_trees.Add(tree.UUID);
- tree.SendGroupFullUpdate();
+ Vector3 scale = copse.m_initial_scale;
+ if(randomScale)
+ {
+ try
+ {
+ float t;
+ float r = (float)Util.RandomClass.NextDouble();
+ r *= (float)Util.RandomClass.NextDouble();
+ r *= (float)Util.RandomClass.NextDouble();
+
+ t = copse.m_maximum_scale.X / copse.m_initial_scale.X;
+ if(t < 1.0)
+ t = 1 / t;
+ t = t * r + 1.0f;
+ scale.X *= t;
+
+ t = copse.m_maximum_scale.Y / copse.m_initial_scale.Y;
+ if(t < 1.0)
+ t = 1 / t;
+ t = t * r + 1.0f;
+ scale.Y *= t;
+
+ t = copse.m_maximum_scale.Z / copse.m_initial_scale.Z;
+ if(t < 1.0)
+ t = 1 / t;
+ t = t * r + 1.0f;
+ scale.Z *= t;
+ }
+ catch
+ {
+ scale = copse.m_initial_scale;
+ }
}
+
+ SceneObjectGroup tree = AddTree(uuid, UUID.Zero, scale, Quaternion.Identity, position, copse.m_tree_type, false);
+ tree.Name = copse.ToString();
+ copse.m_trees.Add(tree.UUID);
+ tree.RootPart.ScheduleFullUpdate();
}
private void CalculateTrees_Elapsed(object sender, ElapsedEventArgs e)
{
- growTrees();
- seedTrees();
- killTrees();
+ if(!m_scene.IsRunning)
+ return;
+
+ if(Monitor.TryEnter(mylock))
+ {
+ try
+ {
+ if(m_scene.LoginsEnabled )
+ {
+ growTrees();
+ seedTrees();
+ killTrees();
+ }
+ }
+ catch { }
+ if(CalculateTrees != null)
+ CalculateTrees.Start();
+ Monitor.Exit(mylock);
+ }
}
}
}
diff --git a/OpenSim/Region/PhysicsModules/BulletS/BSTerrainHeightmap.cs b/OpenSim/Region/PhysicsModules/BulletS/BSTerrainHeightmap.cs
index 42fc11bcd5..f72ad28600 100755
--- a/OpenSim/Region/PhysicsModules/BulletS/BSTerrainHeightmap.cs
+++ b/OpenSim/Region/PhysicsModules/BulletS/BSTerrainHeightmap.cs
@@ -141,14 +141,30 @@ public sealed class BSTerrainHeightmap : BSTerrainPhys
}
// The passed position is relative to the base of the region.
+ // There are many assumptions herein that the heightmap increment is 1.
public override float GetTerrainHeightAtXYZ(Vector3 pos)
{
float ret = BSTerrainManager.HEIGHT_GETHEIGHT_RET;
- int mapIndex = (int)pos.Y * (int)m_mapInfo.sizeY + (int)pos.X;
- try
- {
- ret = m_mapInfo.heightMap[mapIndex];
+ try {
+ int baseX = (int)pos.X;
+ int baseY = (int)pos.Y;
+ int maxX = (int)m_mapInfo.sizeX;
+ int maxY = (int)m_mapInfo.sizeY;
+ float diffX = pos.X - (float)baseX;
+ float diffY = pos.Y - (float)baseY;
+
+ float mapHeight1 = m_mapInfo.heightMap[baseY * maxY + baseX];
+ float mapHeight2 = m_mapInfo.heightMap[Math.Min(baseY + 1, maxY - 1) * maxY + baseX];
+ float mapHeight3 = m_mapInfo.heightMap[baseY * maxY + Math.Min(baseX + 1, maxX - 1)];
+ float mapHeight4 = m_mapInfo.heightMap[Math.Min(baseY + 1, maxY - 1) * maxY + Math.Min(baseX + 1, maxX - 1)];
+
+ float Xrise = (mapHeight4 - mapHeight3) * diffX;
+ float Yrise = (mapHeight2 - mapHeight1) * diffY;
+
+ ret = mapHeight1 + ((Xrise + Yrise) / 2f);
+ // m_physicsScene.DetailLog("{0},BSTerrainHeightMap,GetTerrainHeightAtXYZ,pos={1},{2}/{3}/{4}/{5},ret={6}",
+ // BSScene.DetailLogZero, pos, mapHeight1, mapHeight2, mapHeight3, mapHeight4, ret);
}
catch
{
diff --git a/OpenSim/Region/PhysicsModules/Meshing/Meshmerizer/Meshmerizer.cs b/OpenSim/Region/PhysicsModules/Meshing/Meshmerizer/Meshmerizer.cs
index 4f95554863..0d4b6b96f2 100644
--- a/OpenSim/Region/PhysicsModules/Meshing/Meshmerizer/Meshmerizer.cs
+++ b/OpenSim/Region/PhysicsModules/Meshing/Meshmerizer/Meshmerizer.cs
@@ -66,7 +66,7 @@ namespace OpenSim.Region.PhysicsModule.Meshing
private bool cacheSculptMaps = true;
private string decodedSculptMapPath = null;
- private bool useMeshiesPhysicsMesh = false;
+ private bool useMeshiesPhysicsMesh = true;
private float minSizeForComplexMesh = 0.2f; // prims with all dimensions smaller than this will have a bounding box mesh
diff --git a/OpenSim/Region/PhysicsModules/SharedBase/PhysicsActor.cs b/OpenSim/Region/PhysicsModules/SharedBase/PhysicsActor.cs
index 33f033759b..2fa98b579e 100644
--- a/OpenSim/Region/PhysicsModules/SharedBase/PhysicsActor.cs
+++ b/OpenSim/Region/PhysicsModules/SharedBase/PhysicsActor.cs
@@ -256,6 +256,7 @@ namespace OpenSim.Region.PhysicsModules.SharedBase
///
public string SOPName;
+ public virtual void CrossingStart() { }
public abstract void CrossingFailure();
public abstract void link(PhysicsActor obj);
@@ -462,6 +463,23 @@ namespace OpenSim.Region.PhysicsModules.SharedBase
public abstract bool SubscribedEvents();
public virtual void AddCollisionEvent(uint CollidedWith, ContactPoint contact) { }
+ public virtual void AddVDTCCollisionEvent(uint CollidedWith, ContactPoint contact) { }
+
+ public virtual PhysicsInertiaData GetInertiaData()
+ {
+ PhysicsInertiaData data = new PhysicsInertiaData();
+ data.TotalMass = this.Mass;
+ data.CenterOfMass = CenterOfMass - Position;
+ data.Inertia = Vector3.Zero;
+ data.InertiaRotation = Vector4.Zero;
+ return data;
+ }
+
+ public virtual void SetInertiaData(PhysicsInertiaData inertia)
+ {
+ }
+
+ public virtual float SimulationSuspended { get; set; }
// Warning in a parent part it returns itself, not null
public virtual PhysicsActor ParentActor { get { return this; } }
diff --git a/OpenSim/Region/PhysicsModules/ubOde/ODECharacter.cs b/OpenSim/Region/PhysicsModules/ubOde/ODECharacter.cs
index 9cef3d5496..0e46471879 100644
--- a/OpenSim/Region/PhysicsModules/ubOde/ODECharacter.cs
+++ b/OpenSim/Region/PhysicsModules/ubOde/ODECharacter.cs
@@ -103,7 +103,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
public float walkDivisor = 1.3f;
public float runDivisor = 0.8f;
- private bool flying = false;
+ private bool m_flying = false;
private bool m_iscolliding = false;
private bool m_iscollidingGround = false;
private bool m_iscollidingObj = false;
@@ -138,7 +138,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
);
// we do land collisions not ode | CollisionCategories.Land);
public IntPtr Body = IntPtr.Zero;
- private ODEScene _parent_scene;
+ private ODEScene m_parent_scene;
private IntPtr capsule = IntPtr.Zero;
public IntPtr collider = IntPtr.Zero;
@@ -169,6 +169,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
{
m_uuid = UUID.Random();
m_localID = localID;
+ m_parent_scene = parent_scene;
timeStep = parent_scene.ODE_STEPSIZE;
invtimeStep = 1 / timeStep;
@@ -187,13 +188,10 @@ namespace OpenSim.Region.PhysicsModule.ubOde
}
else
{
- _position = new Vector3(((float)_parent_scene.WorldExtents.X * 0.5f), ((float)_parent_scene.WorldExtents.Y * 0.5f), parent_scene.GetTerrainHeightAtXY(128f, 128f) + 10f);
+ _position = new Vector3(((float)m_parent_scene.WorldExtents.X * 0.5f), ((float)m_parent_scene.WorldExtents.Y * 0.5f), parent_scene.GetTerrainHeightAtXY(128f, 128f) + 10f);
m_log.Warn("[PHYSICS]: Got NaN Position on Character Create");
}
- _parent_scene = parent_scene;
-
-
m_size.X = pSize.X;
m_size.Y = pSize.Y;
m_size.Z = pSize.Z;
@@ -213,7 +211,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
// force lower density for testing
m_density = 3.0f;
- mu = parent_scene.AvatarFriction;
+ mu = m_parent_scene.AvatarFriction;
walkDivisor = walk_divisor;
runDivisor = rundivisor;
@@ -300,10 +298,10 @@ namespace OpenSim.Region.PhysicsModule.ubOde
public override bool Flying
{
- get { return flying; }
+ get { return m_flying; }
set
{
- flying = value;
+ m_flying = value;
// m_log.DebugFormat("[PHYSICS]: Set OdeCharacter Flying to {0}", flying);
}
}
@@ -437,11 +435,11 @@ namespace OpenSim.Region.PhysicsModule.ubOde
{
if (value.Z > 9999999f)
{
- value.Z = _parent_scene.GetTerrainHeightAtXY(127, 127) + 5;
+ value.Z = m_parent_scene.GetTerrainHeightAtXY(127, 127) + 5;
}
if (value.Z < -100f)
{
- value.Z = _parent_scene.GetTerrainHeightAtXY(127, 127) + 5;
+ value.Z = m_parent_scene.GetTerrainHeightAtXY(127, 127) + 5;
}
AddChange(changes.Position, value);
}
@@ -704,7 +702,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
{
if (pushforce)
{
- AddChange(changes.Force, force * m_density / (_parent_scene.ODE_STEPSIZE * 28f));
+ AddChange(changes.Force, force * m_density / (m_parent_scene.ODE_STEPSIZE * 28f));
}
else
{
@@ -751,9 +749,9 @@ namespace OpenSim.Region.PhysicsModule.ubOde
AvaAvaSizeYsq = 0.5f * sy;
AvaAvaSizeYsq *= AvaAvaSizeYsq;
- _parent_scene.waitForSpaceUnlock(_parent_scene.CharsSpace);
+ m_parent_scene.waitForSpaceUnlock(m_parent_scene.CharsSpace);
- collider = d.HashSpaceCreate(_parent_scene.CharsSpace);
+ collider = d.HashSpaceCreate(m_parent_scene.CharsSpace);
d.HashSpaceSetLevels(collider, -4, 3);
d.SpaceSetSublevel(collider, 3);
d.SpaceSetCleanup(collider, false);
@@ -772,10 +770,10 @@ namespace OpenSim.Region.PhysicsModule.ubOde
d.MassSetBoxTotal(out ShellMass, m_mass, m_size.X, m_size.Y, m_size.Z);
- PID_D = basePID_D * m_mass / _parent_scene.ODE_STEPSIZE;
- PID_P = basePID_P * m_mass / _parent_scene.ODE_STEPSIZE;
+ PID_D = basePID_D * m_mass / m_parent_scene.ODE_STEPSIZE;
+ PID_P = basePID_P * m_mass / m_parent_scene.ODE_STEPSIZE;
- Body = d.BodyCreate(_parent_scene.world);
+ Body = d.BodyCreate(m_parent_scene.world);
_zeroFlag = false;
m_pidControllerActive = true;
@@ -795,7 +793,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
// The purpose of the AMotor here is to keep the avatar's physical
// surrogate from rotating while moving
- Amotor = d.JointCreateAMotor(_parent_scene.world, IntPtr.Zero);
+ Amotor = d.JointCreateAMotor(m_parent_scene.world, IntPtr.Zero);
d.JointAttach(Amotor, Body, IntPtr.Zero);
d.JointSetAMotorMode(Amotor, 0);
@@ -854,8 +852,8 @@ namespace OpenSim.Region.PhysicsModule.ubOde
//kill the Geoms
if (capsule != IntPtr.Zero)
{
- _parent_scene.actor_name_map.Remove(capsule);
- _parent_scene.waitForSpaceUnlock(collider);
+ m_parent_scene.actor_name_map.Remove(capsule);
+ m_parent_scene.waitForSpaceUnlock(collider);
d.GeomDestroy(capsule);
capsule = IntPtr.Zero;
}
@@ -901,9 +899,9 @@ namespace OpenSim.Region.PhysicsModule.ubOde
y = tx * sin + y * cos;
}
- public bool Collide(IntPtr me, IntPtr other, bool reverse, ref d.ContactGeom contact,
+ public bool Collide(IntPtr me, IntPtr other, bool reverse, ref d.ContactGeom contact,
ref d.ContactGeom altContact , ref bool useAltcontact, ref bool feetcollision)
- {
+ {
feetcollision = false;
useAltcontact = false;
@@ -945,12 +943,13 @@ namespace OpenSim.Region.PhysicsModule.ubOde
}
return true;
}
-/*
- d.AABB aabb;
- d.GeomGetAABB(other,out aabb);
- float othertop = aabb.MaxZ - _position.Z;
-*/
-// if (offset.Z > 0 || othertop > -feetOff || contact.normal.Z > 0.35f)
+
+ if (gtype == d.GeomClassID.SphereClass && d.GeomGetBody(other) != IntPtr.Zero)
+ {
+ if(d.GeomSphereGetRadius(other) < 0.5)
+ return true;
+ }
+
if (offset.Z > 0 || contact.normal.Z > 0.35f)
{
if (offset.Z <= 0)
@@ -967,6 +966,18 @@ namespace OpenSim.Region.PhysicsModule.ubOde
return true;
}
+ if(m_flying)
+ return true;
+
+ feetcollision = true;
+ if (h < boneOff)
+ {
+ m_collideNormal.X = contact.normal.X;
+ m_collideNormal.Y = contact.normal.Y;
+ m_collideNormal.Z = contact.normal.Z;
+ IsColliding = true;
+ }
+
altContact = contact;
useAltcontact = true;
@@ -974,8 +985,21 @@ namespace OpenSim.Region.PhysicsModule.ubOde
offset.Normalize();
- if (contact.depth > 0.1f)
- contact.depth = 0.1f;
+ float tdp = contact.depth;
+ float t = offset.X;
+ t = Math.Abs(t);
+ if(t > 1e-6)
+ {
+ tdp /= t;
+ tdp *= contact.normal.X;
+ }
+ else
+ tdp *= 10;
+
+ if (tdp > 0.25f)
+ tdp = 0.25f;
+
+ altContact.depth = tdp;
if (reverse)
{
@@ -989,15 +1013,6 @@ namespace OpenSim.Region.PhysicsModule.ubOde
altContact.normal.Y = -offset.Y;
altContact.normal.Z = -offset.Z;
}
-
- feetcollision = true;
- if (h < boneOff)
- {
- m_collideNormal.X = contact.normal.X;
- m_collideNormal.Y = contact.normal.Y;
- m_collideNormal.Z = contact.normal.Z;
- IsColliding = true;
- }
return true;
}
return false;
@@ -1049,20 +1064,20 @@ namespace OpenSim.Region.PhysicsModule.ubOde
fixbody = true;
localpos.X = 0.1f;
}
- else if (localpos.X > _parent_scene.WorldExtents.X - 0.1f)
+ else if (localpos.X > m_parent_scene.WorldExtents.X - 0.1f)
{
fixbody = true;
- localpos.X = _parent_scene.WorldExtents.X - 0.1f;
+ localpos.X = m_parent_scene.WorldExtents.X - 0.1f;
}
if (localpos.Y < 0.0f)
{
fixbody = true;
localpos.Y = 0.1f;
}
- else if (localpos.Y > _parent_scene.WorldExtents.Y - 0.1)
+ else if (localpos.Y > m_parent_scene.WorldExtents.Y - 0.1)
{
fixbody = true;
- localpos.Y = _parent_scene.WorldExtents.Y - 0.1f;
+ localpos.Y = m_parent_scene.WorldExtents.Y - 0.1f;
}
if (fixbody)
{
@@ -1100,14 +1115,14 @@ namespace OpenSim.Region.PhysicsModule.ubOde
float ftmp;
- if (flying)
+ if (m_flying)
{
ftmp = timeStep;
posch.X += vel.X * ftmp;
posch.Y += vel.Y * ftmp;
}
- float terrainheight = _parent_scene.GetTerrainHeightAtXY(posch.X, posch.Y);
+ float terrainheight = m_parent_scene.GetTerrainHeightAtXY(posch.X, posch.Y);
if (chrminZ < terrainheight)
{
if (ctz.Z < 0)
@@ -1119,12 +1134,12 @@ namespace OpenSim.Region.PhysicsModule.ubOde
m_haveLastFallVel = true;
}
- Vector3 n = _parent_scene.GetTerrainNormalAtXY(posch.X, posch.Y);
+ Vector3 n = m_parent_scene.GetTerrainNormalAtXY(posch.X, posch.Y);
float depth = terrainheight - chrminZ;
vec.Z = depth * PID_P * 50;
- if (!flying)
+ if (!m_flying)
{
vec.Z += -vel.Z * PID_D;
if(n.Z < 0.4f)
@@ -1215,7 +1230,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
break;
case PIDHoverType.GroundAndWater:
- float waterHeight = _parent_scene.GetWaterLevel();
+ float waterHeight = m_parent_scene.GetWaterLevel();
if (terrainheight > waterHeight)
m_targetHoverHeight = terrainheight + m_PIDHoverHeight;
else
@@ -1261,7 +1276,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
// movement relative to surface if moving on it
// dont disturbe vertical movement, ie jumps
- if (m_iscolliding && !flying && ctz.Z == 0 && m_collideNormal.Z > 0.2f && m_collideNormal.Z < 0.94f)
+ if (m_iscolliding && !m_flying && ctz.Z == 0 && m_collideNormal.Z > 0.2f && m_collideNormal.Z < 0.94f)
{
float p = ctz.X * m_collideNormal.X + ctz.Y * m_collideNormal.Y;
ctz.X *= (float)Math.Sqrt(1 - m_collideNormal.X * m_collideNormal.X);
@@ -1278,7 +1293,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
{
// if velocity is zero, use position control; otherwise, velocity control
- if (tviszero && m_iscolliding && !flying)
+ if (tviszero && m_iscolliding && !m_flying)
{
// keep track of where we stopped. No more slippin' & slidin'
if (!_zeroFlag)
@@ -1315,7 +1330,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
if (m_iscolliding)
{
- if (!flying)
+ if (!m_flying)
{
// we are on a surface
if (ctz.Z > 0f)
@@ -1363,7 +1378,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
}
else // ie not colliding
{
- if (flying || hoverPIDActive) //(!m_iscolliding && flying)
+ if (m_flying || hoverPIDActive) //(!m_iscolliding && flying)
{
// we're in mid air suspended
vec.X += (ctz.X - vel.X) * (PID_D);
@@ -1381,7 +1396,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
vec.Y += (ctz.Y - vel.Y) * PID_D * 0.833f;
// hack for breaking on fall
if (ctz.Z == -9999f)
- vec.Z += -vel.Z * PID_D - _parent_scene.gravityz * m_mass;
+ vec.Z += -vel.Z * PID_D - m_parent_scene.gravityz * m_mass;
}
}
}
@@ -1399,15 +1414,15 @@ namespace OpenSim.Region.PhysicsModule.ubOde
breakfactor = m_mass;
vec.X -= breakfactor * vel.X;
vec.Y -= breakfactor * vel.Y;
- if (flying)
+ if (m_flying)
vec.Z -= 0.5f * breakfactor * vel.Z;
else
vec.Z -= .16f* m_mass * vel.Z;
}
- if (flying || hoverPIDActive)
+ if (m_flying || hoverPIDActive)
{
- vec.Z -= _parent_scene.gravityz * m_mass;
+ vec.Z -= m_parent_scene.gravityz * m_mass;
if(!hoverPIDActive)
{
@@ -1585,7 +1600,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
public override void UnSubscribeEvents()
{
m_eventsubscription = 0;
- _parent_scene.RemoveCollisionEventReporting(this);
+ m_parent_scene.RemoveCollisionEventReporting(this);
lock(CollisionEventsThisFrame)
CollisionEventsThisFrame.Clear();
}
@@ -1594,7 +1609,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
{
lock(CollisionEventsThisFrame)
CollisionEventsThisFrame.AddCollider(CollidedWith, contact);
- _parent_scene.AddCollisionEventReporting(this);
+ m_parent_scene.AddCollisionEventReporting(this);
}
public void SendCollisions(int timestep)
@@ -1645,14 +1660,14 @@ namespace OpenSim.Region.PhysicsModule.ubOde
AvatarGeomAndBodyCreation(_position.X, _position.Y, _position.Z);
- _parent_scene.actor_name_map[collider] = (PhysicsActor)this;
- _parent_scene.actor_name_map[capsule] = (PhysicsActor)this;
- _parent_scene.AddCharacter(this);
+ m_parent_scene.actor_name_map[collider] = (PhysicsActor)this;
+ m_parent_scene.actor_name_map[capsule] = (PhysicsActor)this;
+ m_parent_scene.AddCharacter(this);
}
else
{
- _parent_scene.RemoveCollisionEventReporting(this);
- _parent_scene.RemoveCharacter(this);
+ m_parent_scene.RemoveCollisionEventReporting(this);
+ m_parent_scene.RemoveCharacter(this);
// destroy avatar capsule and related ODE data
AvatarGeomAndBodyDestroy();
}
@@ -1699,8 +1714,8 @@ namespace OpenSim.Region.PhysicsModule.ubOde
// Velocity = Vector3.Zero;
m_targetVelocity = Vector3.Zero;
- _parent_scene.actor_name_map[collider] = (PhysicsActor)this;
- _parent_scene.actor_name_map[capsule] = (PhysicsActor)this;
+ m_parent_scene.actor_name_map[collider] = (PhysicsActor)this;
+ m_parent_scene.actor_name_map[capsule] = (PhysicsActor)this;
}
m_freemove = false;
m_pidControllerActive = true;
@@ -2008,7 +2023,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
public void AddChange(changes what, object arg)
{
- _parent_scene.AddChange((PhysicsActor)this, what, arg);
+ m_parent_scene.AddChange((PhysicsActor)this, what, arg);
}
private struct strAvatarSize
diff --git a/OpenSim/Region/PhysicsModules/ubOde/ODEDynamics.cs b/OpenSim/Region/PhysicsModules/ubOde/ODEDynamics.cs
index 63bef7cdc6..ce10065af9 100644
--- a/OpenSim/Region/PhysicsModules/ubOde/ODEDynamics.cs
+++ b/OpenSim/Region/PhysicsModules/ubOde/ODEDynamics.cs
@@ -243,6 +243,8 @@ namespace OpenSim.Region.PhysicsModule.ubOde
internal void ProcessFloatVehicleParam(Vehicle pParam, float pValue)
{
float len;
+ if(float.IsNaN(pValue) || float.IsInfinity(pValue))
+ return;
switch (pParam)
{
@@ -343,6 +345,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
if (rootPrim.Body != IntPtr.Zero && !d.BodyIsEnabled(rootPrim.Body)
&& !rootPrim.m_isSelected && !rootPrim.m_disabled)
d.BodyEnable(rootPrim.Body);
+
break;
case Vehicle.LINEAR_FRICTION_TIMESCALE:
if (pValue < m_timestep) pValue = m_timestep;
@@ -374,6 +377,8 @@ namespace OpenSim.Region.PhysicsModule.ubOde
internal void ProcessVectorVehicleParam(Vehicle pParam, Vector3 pValue)
{
float len;
+ if(!pValue.IsFinite())
+ return;
switch (pParam)
{
diff --git a/OpenSim/Region/PhysicsModules/ubOde/ODEMeshWorker.cs b/OpenSim/Region/PhysicsModules/ubOde/ODEMeshWorker.cs
index 923e2ff8ba..5465035c58 100644
--- a/OpenSim/Region/PhysicsModules/ubOde/ODEMeshWorker.cs
+++ b/OpenSim/Region/PhysicsModules/ubOde/ODEMeshWorker.cs
@@ -62,6 +62,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
public byte shapetype;
public bool hasOBB;
public bool hasMeshVolume;
+ public bool isTooSmall;
public MeshState meshState;
public UUID? assetID;
public meshWorkerCmnds comand;
@@ -69,18 +70,16 @@ namespace OpenSim.Region.PhysicsModule.ubOde
public class ODEMeshWorker
{
-
private ILog m_log;
private ODEScene m_scene;
private IMesher m_mesher;
public bool meshSculptedPrim = true;
- public bool forceSimplePrimMeshing = false;
public float meshSculptLOD = 32;
public float MeshSculptphysicalLOD = 32;
+ public float MinSizeToMeshmerize = 0.1f;
-
- private OpenSim.Framework.BlockingQueue createqueue = new OpenSim.Framework.BlockingQueue();
+ private OpenSim.Framework.BlockingQueue workQueue = new OpenSim.Framework.BlockingQueue();
private bool m_running;
private Thread m_thread;
@@ -93,9 +92,9 @@ namespace OpenSim.Region.PhysicsModule.ubOde
if (pConfig != null)
{
- forceSimplePrimMeshing = pConfig.GetBoolean("force_simple_prim_meshing", forceSimplePrimMeshing);
meshSculptedPrim = pConfig.GetBoolean("mesh_sculpted_prim", meshSculptedPrim);
meshSculptLOD = pConfig.GetFloat("mesh_lod", meshSculptLOD);
+ MinSizeToMeshmerize = pConfig.GetFloat("mesh_min_size", MinSizeToMeshmerize);
MeshSculptphysicalLOD = pConfig.GetFloat("mesh_physical_lod", MeshSculptphysicalLOD);
}
m_running = true;
@@ -110,7 +109,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
while(m_running)
{
- ODEPhysRepData nextRep = createqueue.Dequeue();
+ ODEPhysRepData nextRep = workQueue.Dequeue();
if(!m_running)
return;
if (nextRep == null)
@@ -139,7 +138,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
try
{
m_thread.Abort();
- createqueue.Clear();
+ workQueue.Clear();
}
catch
{
@@ -196,7 +195,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
repData.meshState = MeshState.loadingAsset;
repData.comand = meshWorkerCmnds.getmesh;
- createqueue.Enqueue(repData);
+ workQueue.Enqueue(repData);
}
}
@@ -242,7 +241,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
if (needsMeshing(repData)) // no need for pbs now?
{
repData.comand = meshWorkerCmnds.changefull;
- createqueue.Enqueue(repData);
+ workQueue.Enqueue(repData);
}
}
else
@@ -288,6 +287,16 @@ namespace OpenSim.Region.PhysicsModule.ubOde
{
PrimitiveBaseShape pbs = repData.pbs;
// check sculpts or meshs
+
+ Vector3 scale = pbs.Scale;
+ if(scale.X <= MinSizeToMeshmerize &&
+ scale.Y <= MinSizeToMeshmerize &&
+ scale.Z <= MinSizeToMeshmerize)
+ {
+ repData.isTooSmall = true;
+ return false;
+ }
+
if (pbs.SculptEntry)
{
if (meshSculptedPrim)
@@ -299,9 +308,6 @@ namespace OpenSim.Region.PhysicsModule.ubOde
return false;
}
- if (forceSimplePrimMeshing)
- return true;
-
// convex shapes have no holes
ushort profilehollow = pbs.ProfileHollow;
if(repData.shapetype == 2)
@@ -425,17 +431,8 @@ namespace OpenSim.Region.PhysicsModule.ubOde
Vector3 size = repData.size;
int clod = (int)LevelOfDetail.High;
- bool convex;
byte shapetype = repData.shapetype;
- if (shapetype == 0)
- convex = false;
- else
- {
- convex = true;
- // sculpts pseudo convex
- if (pbs.SculptEntry && pbs.SculptType != (byte)SculptType.Mesh)
- clod = (int)LevelOfDetail.Low;
- }
+ bool convex = shapetype == 2;
mesh = m_mesher.GetMesh(actor.Name, pbs, size, clod, true, convex);
@@ -563,10 +560,16 @@ namespace OpenSim.Region.PhysicsModule.ubOde
private void CalculateBasicPrimVolume(ODEPhysRepData repData)
{
- PrimitiveBaseShape _pbs = repData.pbs;
Vector3 _size = repData.size;
float volume = _size.X * _size.Y * _size.Z; // default
+ if(repData.isTooSmall)
+ {
+ repData.volume = volume;
+ return;
+ }
+
+ PrimitiveBaseShape _pbs = repData.pbs;
float tmp;
float hollowAmount = (float)_pbs.ProfileHollow * 2.0e-5f;
@@ -936,7 +939,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
repData.actor.Name, asset.ID.ToString());
}
else
- m_log.WarnFormat("[PHYSICS]: asset provider returned null asset fo mesh of prim {0}.",
+ m_log.WarnFormat("[PHYSICS]: asset provider returned null asset for mesh of prim {0}.",
repData.actor.Name);
}
}
diff --git a/OpenSim/Region/PhysicsModules/ubOde/ODEPrim.cs b/OpenSim/Region/PhysicsModules/ubOde/ODEPrim.cs
index a2fbf41ec6..aa208e2370 100644
--- a/OpenSim/Region/PhysicsModules/ubOde/ODEPrim.cs
+++ b/OpenSim/Region/PhysicsModules/ubOde/ODEPrim.cs
@@ -85,7 +85,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
private Vector3 m_lastposition;
private Vector3 m_rotationalVelocity;
private Vector3 _size;
- private Vector3 _acceleration;
+ private Vector3 m_acceleration;
private IntPtr Amotor;
internal Vector3 m_force;
@@ -109,8 +109,8 @@ namespace OpenSim.Region.PhysicsModule.ubOde
private float m_waterHeight;
private float m_buoyancy; //KF: m_buoyancy should be set by llSetBuoyancy() for non-vehicle.
- private int body_autodisable_frames;
- public int bodydisablecontrol = 0;
+ private int m_body_autodisable_frames;
+ public int m_bodydisablecontrol = 0;
private float m_gravmod = 1.0f;
// Default we're a Geometry
@@ -165,6 +165,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
private float m_density;
private byte m_shapetype;
+ private byte m_fakeShapetype;
public bool _zeroFlag;
private bool m_lastUpdateSent;
@@ -182,18 +183,21 @@ namespace OpenSim.Region.PhysicsModule.ubOde
private float m_streamCost;
public d.Mass primdMass; // prim inertia information on it's own referencial
+ private PhysicsInertiaData m_InertiaOverride;
float primMass; // prim own mass
float primVolume; // prim own volume;
- float _mass; // object mass acording to case
+ float m_mass; // object mass acording to case
public int givefakepos;
private Vector3 fakepos;
public int givefakeori;
private Quaternion fakeori;
+ private PhysicsInertiaData m_fakeInertiaOverride;
private int m_eventsubscription;
private int m_cureventsubscription;
private CollisionEventUpdate CollisionEventsThisFrame = null;
+ private CollisionEventUpdate CollisionVDTCEventsThisFrame = null;
private bool SentEmptyCollisionsEvent;
public volatile bool childPrim;
@@ -417,7 +421,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
{
if (value.IsFinite())
{
- _parent_scene.m_meshWorker.ChangeActorPhysRep(this, _pbs, value, m_shapetype);
+ _parent_scene.m_meshWorker.ChangeActorPhysRep(this, _pbs, value, m_fakeShapetype);
}
else
{
@@ -465,6 +469,103 @@ namespace OpenSim.Region.PhysicsModule.ubOde
}
}
+ public override PhysicsInertiaData GetInertiaData()
+ {
+ PhysicsInertiaData inertia;
+ if(childPrim)
+ {
+ if(_parent != null)
+ return _parent.GetInertiaData();
+ else
+ {
+ inertia = new PhysicsInertiaData();
+ inertia.TotalMass = -1;
+ return inertia;
+ }
+ }
+
+ inertia = new PhysicsInertiaData();
+
+ // double buffering
+ if(m_fakeInertiaOverride != null)
+ {
+ d.Mass objdmass = new d.Mass();
+ objdmass.I.M00 = m_fakeInertiaOverride.Inertia.X;
+ objdmass.I.M11 = m_fakeInertiaOverride.Inertia.Y;
+ objdmass.I.M22 = m_fakeInertiaOverride.Inertia.Z;
+
+ objdmass.mass = m_fakeInertiaOverride.TotalMass;
+
+ if(Math.Abs(m_fakeInertiaOverride.InertiaRotation.W) < 0.999)
+ {
+ d.Matrix3 inertiarotmat = new d.Matrix3();
+ d.Quaternion inertiarot = new d.Quaternion();
+
+ inertiarot.X = m_fakeInertiaOverride.InertiaRotation.X;
+ inertiarot.Y = m_fakeInertiaOverride.InertiaRotation.Y;
+ inertiarot.Z = m_fakeInertiaOverride.InertiaRotation.Z;
+ inertiarot.W = m_fakeInertiaOverride.InertiaRotation.W;
+ d.RfromQ(out inertiarotmat, ref inertiarot);
+ d.MassRotate(ref objdmass, ref inertiarotmat);
+ }
+
+ inertia.TotalMass = m_fakeInertiaOverride.TotalMass;
+ inertia.CenterOfMass = m_fakeInertiaOverride.CenterOfMass;
+ inertia.Inertia.X = objdmass.I.M00;
+ inertia.Inertia.Y = objdmass.I.M11;
+ inertia.Inertia.Z = objdmass.I.M22;
+ inertia.InertiaRotation.X = objdmass.I.M01;
+ inertia.InertiaRotation.Y = objdmass.I.M02;
+ inertia.InertiaRotation.Z = objdmass.I.M12;
+ return inertia;
+ }
+
+ inertia.TotalMass = m_mass;
+
+ if(Body == IntPtr.Zero || prim_geom == IntPtr.Zero)
+ {
+ inertia.CenterOfMass = Vector3.Zero;
+ inertia.Inertia = Vector3.Zero;
+ inertia.InertiaRotation = Vector4.Zero;
+ return inertia;
+ }
+
+ d.Vector3 dtmp;
+ d.Mass m = new d.Mass();
+ lock(_parent_scene.OdeLock)
+ {
+ d.AllocateODEDataForThread(0);
+ dtmp = d.GeomGetOffsetPosition(prim_geom);
+ d.BodyGetMass(Body, out m);
+ }
+
+ Vector3 cm = new Vector3(-dtmp.X, -dtmp.Y, -dtmp.Z);
+ inertia.CenterOfMass = cm;
+ inertia.Inertia = new Vector3(m.I.M00, m.I.M11, m.I.M22);
+ inertia.InertiaRotation = new Vector4(m.I.M01, m.I.M02 , m.I.M12, 0);
+
+ return inertia;
+ }
+
+ public override void SetInertiaData(PhysicsInertiaData inertia)
+ {
+ if(childPrim)
+ {
+ if(_parent != null)
+ _parent.SetInertiaData(inertia);
+ return;
+ }
+
+ if(inertia.TotalMass > 0)
+ m_fakeInertiaOverride = new PhysicsInertiaData(inertia);
+ else
+ m_fakeInertiaOverride = null;
+
+ if (inertia.TotalMass > _parent_scene.maximumMassObject)
+ inertia.TotalMass = _parent_scene.maximumMassObject;
+ AddChange(changes.SetInertia,(object)m_fakeInertiaOverride);
+ }
+
public override Vector3 CenterOfMass
{
get
@@ -530,7 +631,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
set
{
// AddChange(changes.Shape, value);
- _parent_scene.m_meshWorker.ChangeActorPhysRep(this, value, _size, m_shapetype);
+ _parent_scene.m_meshWorker.ChangeActorPhysRep(this, value, _size, m_fakeShapetype);
}
}
@@ -538,11 +639,11 @@ namespace OpenSim.Region.PhysicsModule.ubOde
{
get
{
- return m_shapetype;
+ return m_fakeShapetype;
}
set
{
- m_shapetype = value;
+ m_fakeShapetype = value;
_parent_scene.m_meshWorker.ChangeActorPhysRep(this, _pbs, _size, value);
}
}
@@ -569,7 +670,10 @@ namespace OpenSim.Region.PhysicsModule.ubOde
{
if (value.IsFinite())
{
- AddChange(changes.Velocity, value);
+ if(m_outbounds)
+ _velocity = value;
+ else
+ AddChange(changes.Velocity, value);
}
else
{
@@ -642,8 +746,12 @@ namespace OpenSim.Region.PhysicsModule.ubOde
public override Vector3 Acceleration
{
- get { return _acceleration; }
- set { }
+ get { return m_acceleration; }
+ set
+ {
+ if(m_outbounds)
+ m_acceleration = value;
+ }
}
public override Vector3 RotationalVelocity
@@ -663,7 +771,10 @@ namespace OpenSim.Region.PhysicsModule.ubOde
{
if (value.IsFinite())
{
- AddChange(changes.AngVelocity, value);
+ if(m_outbounds)
+ m_rotationalVelocity = value;
+ else
+ AddChange(changes.AngVelocity, value);
}
else
{
@@ -837,7 +948,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
}
public void SetAcceleration(Vector3 accel)
{
- _acceleration = accel;
+ m_acceleration = accel;
}
public override void AddForce(Vector3 force, bool pushforce)
@@ -873,31 +984,69 @@ namespace OpenSim.Region.PhysicsModule.ubOde
public override void CrossingFailure()
{
- if (m_outbounds)
+ lock(_parent_scene.OdeLock)
{
- _position.X = Util.Clip(_position.X, 0.5f, _parent_scene.WorldExtents.X - 0.5f);
- _position.Y = Util.Clip(_position.Y, 0.5f, _parent_scene.WorldExtents.Y - 0.5f);
- _position.Z = Util.Clip(_position.Z + 0.2f, -100f, 50000f);
+ if (m_outbounds)
+ {
+ _position.X = Util.Clip(_position.X, 0.5f, _parent_scene.WorldExtents.X - 0.5f);
+ _position.Y = Util.Clip(_position.Y, 0.5f, _parent_scene.WorldExtents.Y - 0.5f);
+ _position.Z = Util.Clip(_position.Z + 0.2f, -100f, 50000f);
+
+ m_lastposition = _position;
+ _velocity.X = 0;
+ _velocity.Y = 0;
+ _velocity.Z = 0;
+
+ d.AllocateODEDataForThread(0);
+
+ m_lastVelocity = _velocity;
+ if (m_vehicle != null && m_vehicle.Type != Vehicle.TYPE_NONE)
+ m_vehicle.Stop();
+
+ if(Body != IntPtr.Zero)
+ d.BodySetLinearVel(Body, 0, 0, 0); // stop it
+ if (prim_geom != IntPtr.Zero)
+ d.GeomSetPosition(prim_geom, _position.X, _position.Y, _position.Z);
+
+ m_outbounds = false;
+ changeDisable(false);
+ base.RequestPhysicsterseUpdate();
+ }
+ }
+ }
+
+ public override void CrossingStart()
+ {
+ lock(_parent_scene.OdeLock)
+ {
+ if (m_outbounds || childPrim)
+ return;
+
+ m_outbounds = true;
m_lastposition = _position;
- _velocity.X = 0;
- _velocity.Y = 0;
- _velocity.Z = 0;
+ m_lastorientation = _orientation;
d.AllocateODEDataForThread(0);
-
- m_lastVelocity = _velocity;
- if (m_vehicle != null && m_vehicle.Type != Vehicle.TYPE_NONE)
- m_vehicle.Stop();
-
if(Body != IntPtr.Zero)
- d.BodySetLinearVel(Body, 0, 0, 0); // stop it
- if (prim_geom != IntPtr.Zero)
- d.GeomSetPosition(prim_geom, _position.X, _position.Y, _position.Z);
+ {
+ d.Vector3 dtmp = d.BodyGetAngularVel(Body);
+ m_rotationalVelocity.X = dtmp.X;
+ m_rotationalVelocity.Y = dtmp.Y;
+ m_rotationalVelocity.Z = dtmp.Z;
- m_outbounds = false;
- changeDisable(false);
- base.RequestPhysicsterseUpdate();
+ dtmp = d.BodyGetLinearVel(Body);
+ _velocity.X = dtmp.X;
+ _velocity.Y = dtmp.Y;
+ _velocity.Z = dtmp.Z;
+
+ d.BodySetLinearVel(Body, 0, 0, 0); // stop it
+ d.BodySetAngularVel(Body, 0, 0, 0);
+ }
+ if(prim_geom != IntPtr.Zero)
+ d.GeomSetPosition(prim_geom, _position.X, _position.Y, _position.Z);
+ disableBodySoft(); // stop collisions
+ UnSubscribeEvents();
}
}
@@ -920,8 +1069,10 @@ namespace OpenSim.Region.PhysicsModule.ubOde
}
set
{
+ float old = m_density;
m_density = value / 100f;
- // for not prim mass is not updated since this implies full rebuild of body inertia TODO
+ // if(m_density != old)
+ // UpdatePrimBodyData();
}
}
public override float GravModifier
@@ -989,11 +1140,18 @@ namespace OpenSim.Region.PhysicsModule.ubOde
m_cureventsubscription = 0;
if (CollisionEventsThisFrame == null)
CollisionEventsThisFrame = new CollisionEventUpdate();
+ if (CollisionVDTCEventsThisFrame == null)
+ CollisionVDTCEventsThisFrame = new CollisionEventUpdate();
SentEmptyCollisionsEvent = false;
}
public override void UnSubscribeEvents()
{
+ if (CollisionVDTCEventsThisFrame != null)
+ {
+ CollisionVDTCEventsThisFrame.Clear();
+ CollisionVDTCEventsThisFrame = null;
+ }
if (CollisionEventsThisFrame != null)
{
CollisionEventsThisFrame.Clear();
@@ -1012,22 +1170,51 @@ namespace OpenSim.Region.PhysicsModule.ubOde
_parent_scene.AddCollisionEventReporting(this);
}
+ public override void AddVDTCCollisionEvent(uint CollidedWith, ContactPoint contact)
+ {
+ if (CollisionVDTCEventsThisFrame == null)
+ CollisionVDTCEventsThisFrame = new CollisionEventUpdate();
+
+ CollisionVDTCEventsThisFrame.AddCollider(CollidedWith, contact);
+ _parent_scene.AddCollisionEventReporting(this);
+ }
+
internal void SleeperAddCollisionEvents()
{
- if (CollisionEventsThisFrame == null)
- return;
- if(CollisionEventsThisFrame.m_objCollisionList.Count == 0)
- return;
- foreach(KeyValuePair kvp in CollisionEventsThisFrame.m_objCollisionList)
+ if(CollisionEventsThisFrame != null && CollisionEventsThisFrame.m_objCollisionList.Count != 0)
{
- OdePrim other = _parent_scene.getPrim(kvp.Key);
- if(other == null)
- continue;
- ContactPoint cp = kvp.Value;
- cp.SurfaceNormal = - cp.SurfaceNormal;
- cp.RelativeSpeed = -cp.RelativeSpeed;
- other.AddCollisionEvent(ParentActor.LocalID,cp);
+ foreach(KeyValuePair kvp in CollisionEventsThisFrame.m_objCollisionList)
+ {
+ if(kvp.Key == 0)
+ continue;
+ OdePrim other = _parent_scene.getPrim(kvp.Key);
+ if(other == null)
+ continue;
+ ContactPoint cp = kvp.Value;
+ cp.SurfaceNormal = - cp.SurfaceNormal;
+ cp.RelativeSpeed = -cp.RelativeSpeed;
+ other.AddCollisionEvent(ParentActor.LocalID,cp);
+ }
}
+ if(CollisionVDTCEventsThisFrame != null && CollisionVDTCEventsThisFrame.m_objCollisionList.Count != 0)
+ {
+ foreach(KeyValuePair kvp in CollisionVDTCEventsThisFrame.m_objCollisionList)
+ {
+ OdePrim other = _parent_scene.getPrim(kvp.Key);
+ if(other == null)
+ continue;
+ ContactPoint cp = kvp.Value;
+ cp.SurfaceNormal = - cp.SurfaceNormal;
+ cp.RelativeSpeed = -cp.RelativeSpeed;
+ other.AddCollisionEvent(ParentActor.LocalID,cp);
+ }
+ }
+ }
+
+ internal void clearSleeperCollisions()
+ {
+ if(CollisionVDTCEventsThisFrame != null && CollisionVDTCEventsThisFrame.Count >0 )
+ CollisionVDTCEventsThisFrame.Clear();
}
public void SendCollisions(int timestep)
@@ -1035,14 +1222,15 @@ namespace OpenSim.Region.PhysicsModule.ubOde
if (m_cureventsubscription < 50000)
m_cureventsubscription += timestep;
+
+ if (m_cureventsubscription < m_eventsubscription)
+ return;
+
if (CollisionEventsThisFrame == null)
return;
int ncolisions = CollisionEventsThisFrame.m_objCollisionList.Count;
- if (m_cureventsubscription < m_eventsubscription)
- return;
-
if (!SentEmptyCollisionsEvent || ncolisions > 0)
{
base.SendCollisionUpdate(CollisionEventsThisFrame);
@@ -1053,7 +1241,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
SentEmptyCollisionsEvent = true;
// _parent_scene.RemoveCollisionEventReporting(this);
}
- else if(Body == IntPtr.Zero || d.BodyIsEnabled(Body))
+ else if(Body == IntPtr.Zero || (d.BodyIsEnabled(Body) && m_bodydisablecontrol >= 0 ))
{
SentEmptyCollisionsEvent = false;
CollisionEventsThisFrame.Clear();
@@ -1091,7 +1279,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
m_invTimeStep = 1f / m_timeStep;
m_density = parent_scene.geomDefaultDensity;
- body_autodisable_frames = parent_scene.bodyFramesAutoDisable;
+ m_body_autodisable_frames = parent_scene.bodyFramesAutoDisable;
prim_geom = IntPtr.Zero;
collide_geom = IntPtr.Zero;
@@ -1143,7 +1331,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
_triMeshData = IntPtr.Zero;
- m_shapetype = _shapeType;
+ m_fakeShapetype = _shapeType;
m_lastdoneSelected = false;
m_isSelected = false;
@@ -1160,7 +1348,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
AddChange(changes.Add, null);
// get basic mass parameters
- ODEPhysRepData repData = _parent_scene.m_meshWorker.NewActorPhysRep(this, _pbs, _size, m_shapetype);
+ ODEPhysRepData repData = _parent_scene.m_meshWorker.NewActorPhysRep(this, _pbs, _size, _shapeType);
primVolume = repData.volume;
m_OBB = repData.OBB;
@@ -1545,7 +1733,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
return true;
}
- private void CreateGeom()
+ private void CreateGeom(bool OverrideToBox)
{
bool hasMesh = false;
@@ -1554,7 +1742,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
if ((m_meshState & MeshState.MeshNoColide) != 0)
m_NoColide = true;
- else if(m_mesh != null)
+ else if(!OverrideToBox && m_mesh != null)
{
if (GetMeshGeom())
hasMesh = true;
@@ -1660,8 +1848,8 @@ namespace OpenSim.Region.PhysicsModule.ubOde
ApplyCollisionCatFlags();
_zeroFlag = true;
+ d.BodySetAutoDisableSteps(Body, m_body_autodisable_frames);
d.BodyEnable(Body);
-
}
}
resetCollisionAccounting();
@@ -1714,26 +1902,29 @@ namespace OpenSim.Region.PhysicsModule.ubOde
m_log.Warn("[PHYSICS]: MakeBody root geom already had a body");
}
+ bool noInertiaOverride = (m_InertiaOverride == null);
+
+ Body = d.BodyCreate(_parent_scene.world);
+
d.Matrix3 mymat = new d.Matrix3();
d.Quaternion myrot = new d.Quaternion();
d.Mass objdmass = new d.Mass { };
- Body = d.BodyCreate(_parent_scene.world);
-
- objdmass = primdMass;
-
- // rotate inertia
myrot.X = _orientation.X;
myrot.Y = _orientation.Y;
myrot.Z = _orientation.Z;
myrot.W = _orientation.W;
-
d.RfromQ(out mymat, ref myrot);
- d.MassRotate(ref objdmass, ref mymat);
// set the body rotation
d.BodySetRotation(Body, ref mymat);
+ if(noInertiaOverride)
+ {
+ objdmass = primdMass;
+ d.MassRotate(ref objdmass, ref mymat);
+ }
+
// recompute full object inertia if needed
if (childrenPrim.Count > 0)
{
@@ -1756,27 +1947,12 @@ namespace OpenSim.Region.PhysicsModule.ubOde
continue;
}
- tmpdmass = prm.primdMass;
-
- // apply prim current rotation to inertia
quat.X = prm._orientation.X;
quat.Y = prm._orientation.Y;
quat.Z = prm._orientation.Z;
quat.W = prm._orientation.W;
d.RfromQ(out mat, ref quat);
- d.MassRotate(ref tmpdmass, ref mat);
- Vector3 ppos = prm._position;
- ppos.X -= rcm.X;
- ppos.Y -= rcm.Y;
- ppos.Z -= rcm.Z;
- // refer inertia to root prim center of mass position
- d.MassTranslate(ref tmpdmass,
- ppos.X,
- ppos.Y,
- ppos.Z);
-
- d.MassAdd(ref objdmass, ref tmpdmass); // add to total object inertia
// fix prim colision cats
if (d.GeomGetBody(prm.prim_geom) != IntPtr.Zero)
@@ -1789,6 +1965,24 @@ namespace OpenSim.Region.PhysicsModule.ubOde
d.GeomSetBody(prm.prim_geom, Body);
prm.Body = Body;
d.GeomSetOffsetWorldRotation(prm.prim_geom, ref mat); // set relative rotation
+
+ if(noInertiaOverride)
+ {
+ tmpdmass = prm.primdMass;
+
+ d.MassRotate(ref tmpdmass, ref mat);
+ Vector3 ppos = prm._position;
+ ppos.X -= rcm.X;
+ ppos.Y -= rcm.Y;
+ ppos.Z -= rcm.Z;
+ // refer inertia to root prim center of mass position
+ d.MassTranslate(ref tmpdmass,
+ ppos.X,
+ ppos.Y,
+ ppos.Z);
+
+ d.MassAdd(ref objdmass, ref tmpdmass); // add to total object inertia
+ }
}
}
}
@@ -1797,25 +1991,66 @@ namespace OpenSim.Region.PhysicsModule.ubOde
// associate root geom with body
d.GeomSetBody(prim_geom, Body);
- d.BodySetPosition(Body, _position.X + objdmass.c.X, _position.Y + objdmass.c.Y, _position.Z + objdmass.c.Z);
+ if(noInertiaOverride)
+ d.BodySetPosition(Body, _position.X + objdmass.c.X, _position.Y + objdmass.c.Y, _position.Z + objdmass.c.Z);
+ else
+ {
+ Vector3 ncm = m_InertiaOverride.CenterOfMass * _orientation;
+ d.BodySetPosition(Body,
+ _position.X + ncm.X,
+ _position.Y + ncm.Y,
+ _position.Z + ncm.Z);
+ }
+
d.GeomSetOffsetWorldPosition(prim_geom, _position.X, _position.Y, _position.Z);
- d.MassTranslate(ref objdmass, -objdmass.c.X, -objdmass.c.Y, -objdmass.c.Z); // ode wants inertia at center of body
- myrot.X = -myrot.X;
- myrot.Y = -myrot.Y;
- myrot.Z = -myrot.Z;
+ if(noInertiaOverride)
+ {
+ d.MassTranslate(ref objdmass, -objdmass.c.X, -objdmass.c.Y, -objdmass.c.Z); // ode wants inertia at center of body
+ myrot.X = -myrot.X;
+ myrot.Y = -myrot.Y;
+ myrot.Z = -myrot.Z;
- d.RfromQ(out mymat, ref myrot);
- d.MassRotate(ref objdmass, ref mymat);
+ d.RfromQ(out mymat, ref myrot);
+ d.MassRotate(ref objdmass, ref mymat);
- d.BodySetMass(Body, ref objdmass);
- _mass = objdmass.mass;
+ d.BodySetMass(Body, ref objdmass);
+ m_mass = objdmass.mass;
+ }
+ else
+ {
+ objdmass.c.X = 0;
+ objdmass.c.Y = 0;
+ objdmass.c.Z = 0;
+
+ objdmass.I.M00 = m_InertiaOverride.Inertia.X;
+ objdmass.I.M11 = m_InertiaOverride.Inertia.Y;
+ objdmass.I.M22 = m_InertiaOverride.Inertia.Z;
+
+ objdmass.mass = m_InertiaOverride.TotalMass;
+
+ if(Math.Abs(m_InertiaOverride.InertiaRotation.W) < 0.999)
+ {
+ d.Matrix3 inertiarotmat = new d.Matrix3();
+ d.Quaternion inertiarot = new d.Quaternion();
+
+ inertiarot.X = m_InertiaOverride.InertiaRotation.X;
+ inertiarot.Y = m_InertiaOverride.InertiaRotation.Y;
+ inertiarot.Z = m_InertiaOverride.InertiaRotation.Z;
+ inertiarot.W = m_InertiaOverride.InertiaRotation.W;
+ d.RfromQ(out inertiarotmat, ref inertiarot);
+ d.MassRotate(ref objdmass, ref inertiarotmat);
+ }
+ d.BodySetMass(Body, ref objdmass);
+
+ m_mass = objdmass.mass;
+ }
// disconnect from world gravity so we can apply buoyancy
d.BodySetGravityMode(Body, false);
d.BodySetAutoDisableFlag(Body, true);
- d.BodySetAutoDisableSteps(Body, body_autodisable_frames);
+ d.BodySetAutoDisableSteps(Body, m_body_autodisable_frames);
d.BodySetAutoDisableAngularThreshold(Body, 0.05f);
d.BodySetAutoDisableLinearThreshold(Body, 0.05f);
d.BodySetDamping(Body, .004f, .001f);
@@ -1909,8 +2144,9 @@ namespace OpenSim.Region.PhysicsModule.ubOde
{
d.BodySetAngularVel(Body, m_rotationalVelocity.X, m_rotationalVelocity.Y, m_rotationalVelocity.Z);
d.BodySetLinearVel(Body, _velocity.X, _velocity.Y, _velocity.Z);
+
_zeroFlag = false;
- bodydisablecontrol = 0;
+ m_bodydisablecontrol = 0;
}
_parent_scene.addActiveGroups(this);
}
@@ -1988,7 +2224,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
SetInStaticSpace(prm);
}
prm.Body = IntPtr.Zero;
- prm._mass = prm.primMass;
+ prm.m_mass = prm.primMass;
prm.m_collisionscore = 0;
}
}
@@ -2002,7 +2238,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
}
Body = IntPtr.Zero;
}
- _mass = primMass;
+ m_mass = primMass;
m_collisionscore = 0;
}
@@ -2079,7 +2315,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
d.BodySetPosition(Body, dobjpos.X + thispos.X, dobjpos.Y + thispos.Y, dobjpos.Z + thispos.Z);
d.MassTranslate(ref objdmass, -objdmass.c.X, -objdmass.c.Y, -objdmass.c.Z); // ode wants inertia at center of body
d.BodySetMass(Body, ref objdmass);
- _mass = objdmass.mass;
+ m_mass = objdmass.mass;
}
private void FixInertia(Vector3 NewPos)
@@ -2143,7 +2379,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
d.BodySetPosition(Body, dobjpos.X + thispos.X, dobjpos.Y + thispos.Y, dobjpos.Z + thispos.Z);
d.MassTranslate(ref objdmass, -objdmass.c.X, -objdmass.c.Y, -objdmass.c.Z); // ode wants inertia at center of body
d.BodySetMass(Body, ref objdmass);
- _mass = objdmass.mass;
+ m_mass = objdmass.mass;
}
private void FixInertia(Quaternion newrot)
@@ -2209,7 +2445,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
d.BodySetPosition(Body, dobjpos.X + thispos.X, dobjpos.Y + thispos.Y, dobjpos.Z + thispos.Z);
d.MassTranslate(ref objdmass, -objdmass.c.X, -objdmass.c.Y, -objdmass.c.Z); // ode wants inertia at center of body
d.BodySetMass(Body, ref objdmass);
- _mass = objdmass.mass;
+ m_mass = objdmass.mass;
}
@@ -2224,7 +2460,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
if (primMass > _parent_scene.maximumMassObject)
primMass = _parent_scene.maximumMassObject;
- _mass = primMass; // just in case
+ m_mass = primMass; // just in case
d.MassSetBoxTotal(out primdMass, primMass, 2.0f * m_OBB.X, 2.0f * m_OBB.Y, 2.0f * m_OBB.Z);
@@ -2514,7 +2750,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
m_angularForceacc = Vector3.Zero;
// m_torque = Vector3.Zero;
_velocity = Vector3.Zero;
- _acceleration = Vector3.Zero;
+ m_acceleration = Vector3.Zero;
m_rotationalVelocity = Vector3.Zero;
_target_velocity = Vector3.Zero;
if (m_vehicle != null && m_vehicle.Type != Vehicle.TYPE_NONE)
@@ -2665,6 +2901,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
if (Body != IntPtr.Zero && !m_disabled)
{
_zeroFlag = true;
+ d.BodySetAutoDisableSteps(Body, m_body_autodisable_frames);
d.BodyEnable(Body);
}
}
@@ -2698,6 +2935,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
if (!d.BodyIsEnabled(Body))
{
_zeroFlag = true;
+ d.BodySetAutoDisableSteps(Body, m_body_autodisable_frames);
d.BodyEnable(Body);
}
}
@@ -2712,6 +2950,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
if (Body != IntPtr.Zero && !d.BodyIsEnabled(Body))
{
_zeroFlag = true;
+ d.BodySetAutoDisableSteps(Body, m_body_autodisable_frames);
d.BodyEnable(Body);
}
}
@@ -2767,12 +3006,17 @@ namespace OpenSim.Region.PhysicsModule.ubOde
myrot.W = newOri.W;
d.GeomSetQuaternion(prim_geom, ref myrot);
_orientation = newOri;
- if (Body != IntPtr.Zero && m_angularlocks != 0)
- createAMotor(m_angularlocks);
+
+ if (Body != IntPtr.Zero)
+ {
+ if(m_angularlocks != 0)
+ createAMotor(m_angularlocks);
+ }
}
if (Body != IntPtr.Zero && !d.BodyIsEnabled(Body))
{
_zeroFlag = true;
+ d.BodySetAutoDisableSteps(Body, m_body_autodisable_frames);
d.BodyEnable(Body);
}
}
@@ -2831,6 +3075,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
if (Body != IntPtr.Zero && !d.BodyIsEnabled(Body))
{
_zeroFlag = true;
+ d.BodySetAutoDisableSteps(Body, m_body_autodisable_frames);
d.BodyEnable(Body);
}
}
@@ -2923,7 +3168,6 @@ namespace OpenSim.Region.PhysicsModule.ubOde
{
_size = repData.size; //??
_pbs = repData.pbs;
- m_shapetype = repData.shapetype;
m_mesh = repData.mesh;
@@ -2936,7 +3180,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
primVolume = repData.volume;
- CreateGeom();
+ CreateGeom(repData.isTooSmall);
if (prim_geom != IntPtr.Zero)
{
@@ -2962,9 +3206,11 @@ namespace OpenSim.Region.PhysicsModule.ubOde
{
repData.size = _size;
repData.pbs = _pbs;
- repData.shapetype = m_shapetype;
+ repData.shapetype = m_fakeShapetype;
_parent_scene.m_meshWorker.RequestMesh(repData);
}
+ else
+ m_shapetype = repData.shapetype;
}
private void changePhysRepData(ODEPhysRepData repData)
@@ -2998,7 +3244,6 @@ namespace OpenSim.Region.PhysicsModule.ubOde
_size = repData.size;
_pbs = repData.pbs;
- m_shapetype = repData.shapetype;
m_mesh = repData.mesh;
@@ -3011,7 +3256,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
primVolume = repData.volume;
- CreateGeom();
+ CreateGeom(repData.isTooSmall);
if (prim_geom != IntPtr.Zero)
{
@@ -3049,9 +3294,11 @@ namespace OpenSim.Region.PhysicsModule.ubOde
{
repData.size = _size;
repData.pbs = _pbs;
- repData.shapetype = m_shapetype;
+ repData.shapetype = m_fakeShapetype;
_parent_scene.m_meshWorker.RequestMesh(repData);
}
+ else
+ m_shapetype = repData.shapetype;
}
private void changeFloatOnWater(bool newval)
@@ -3064,15 +3311,17 @@ namespace OpenSim.Region.PhysicsModule.ubOde
private void changeSetTorque(Vector3 newtorque)
{
- if (!m_isSelected)
+ if (!m_isSelected && !m_outbounds)
{
if (m_isphysical && Body != IntPtr.Zero)
{
if (m_disabled)
enableBodySoft();
else if (!d.BodyIsEnabled(Body))
+ {
+ d.BodySetAutoDisableSteps(Body, m_body_autodisable_frames);
d.BodyEnable(Body);
-
+ }
}
m_torque = newtorque;
}
@@ -3081,14 +3330,17 @@ namespace OpenSim.Region.PhysicsModule.ubOde
private void changeForce(Vector3 force)
{
m_force = force;
- if (Body != IntPtr.Zero && !d.BodyIsEnabled(Body))
+ if (!m_isSelected && !m_outbounds && Body != IntPtr.Zero && !d.BodyIsEnabled(Body))
+ {
+ d.BodySetAutoDisableSteps(Body, m_body_autodisable_frames);
d.BodyEnable(Body);
+ }
}
private void changeAddForce(Vector3 theforce)
{
m_forceacc += theforce;
- if (!m_isSelected)
+ if (!m_isSelected && !m_outbounds)
{
lock (this)
{
@@ -3098,7 +3350,10 @@ namespace OpenSim.Region.PhysicsModule.ubOde
if (m_disabled)
enableBodySoft();
else if (!d.BodyIsEnabled(Body))
+ {
+ d.BodySetAutoDisableSteps(Body, m_body_autodisable_frames);
d.BodyEnable(Body);
+ }
}
}
m_collisionscore = 0;
@@ -3109,7 +3364,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
private void changeAddAngularImpulse(Vector3 aimpulse)
{
m_angularForceacc += aimpulse * m_invTimeStep;
- if (!m_isSelected)
+ if (!m_isSelected && !m_outbounds)
{
lock (this)
{
@@ -3118,7 +3373,10 @@ namespace OpenSim.Region.PhysicsModule.ubOde
if (m_disabled)
enableBodySoft();
else if (!d.BodyIsEnabled(Body))
+ {
+ d.BodySetAutoDisableSteps(Body, m_body_autodisable_frames);
d.BodyEnable(Body);
+ }
}
}
m_collisionscore = 0;
@@ -3134,15 +3392,17 @@ namespace OpenSim.Region.PhysicsModule.ubOde
newVel *= len;
}
- if (!m_isSelected)
+ if (!m_isSelected && !m_outbounds)
{
if (Body != IntPtr.Zero)
{
if (m_disabled)
enableBodySoft();
else if (!d.BodyIsEnabled(Body))
+ {
+ d.BodySetAutoDisableSteps(Body, m_body_autodisable_frames);
d.BodyEnable(Body);
-
+ }
d.BodySetLinearVel(Body, newVel.X, newVel.Y, newVel.Z);
}
//resetCollisionAccounting();
@@ -3159,16 +3419,17 @@ namespace OpenSim.Region.PhysicsModule.ubOde
newAngVel *= len;
}
- if (!m_isSelected)
+ if (!m_isSelected && !m_outbounds)
{
if (Body != IntPtr.Zero)
{
if (m_disabled)
enableBodySoft();
else if (!d.BodyIsEnabled(Body))
+ {
+ d.BodySetAutoDisableSteps(Body, m_body_autodisable_frames);
d.BodyEnable(Body);
-
-
+ }
d.BodySetAngularVel(Body, newAngVel.X, newAngVel.Y, newAngVel.Z);
}
//resetCollisionAccounting();
@@ -3304,6 +3565,15 @@ namespace OpenSim.Region.PhysicsModule.ubOde
m_useHoverPID = active;
}
+ private void changeInertia(PhysicsInertiaData inertia)
+ {
+ m_InertiaOverride = inertia;
+
+ if (Body != IntPtr.Zero)
+ DestroyBody();
+ MakeBody();
+ }
+
#endregion
public void Move()
@@ -3317,19 +3587,20 @@ namespace OpenSim.Region.PhysicsModule.ubOde
if (m_vehicle != null && m_vehicle.Type != Vehicle.TYPE_NONE)
return;
- if (++bodydisablecontrol < 50)
+ if (++m_bodydisablecontrol < 50)
return;
// clear residuals
d.BodySetAngularVel(Body,0f,0f,0f);
d.BodySetLinearVel(Body,0f,0f,0f);
_zeroFlag = true;
+ d.BodySetAutoDisableSteps(Body, 1);
d.BodyEnable(Body);
- bodydisablecontrol = -4;
+ m_bodydisablecontrol = -3;
}
- if(bodydisablecontrol < 0)
- bodydisablecontrol ++;
+ if(m_bodydisablecontrol < 0)
+ m_bodydisablecontrol++;
d.Vector3 lpos = d.GeomGetPosition(prim_geom); // root position that is seem by rest of simulator
@@ -3344,7 +3615,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
float fy = 0;
float fz = 0;
- float m_mass = _mass;
+ float mass = m_mass;
if (m_usePID && m_PIDTau > 0)
{
@@ -3451,9 +3722,9 @@ namespace OpenSim.Region.PhysicsModule.ubOde
fz = _parent_scene.gravityz * b;
}
- fx *= m_mass;
- fy *= m_mass;
- fz *= m_mass;
+ fx *= mass;
+ fy *= mass;
+ fz *= mass;
// constant force
fx += m_force.X;
@@ -3494,13 +3765,12 @@ namespace OpenSim.Region.PhysicsModule.ubOde
public void UpdatePositionAndVelocity(int frame)
{
- if (_parent == null && !m_disabled && !m_building && !m_outbounds && Body != IntPtr.Zero)
+ if (_parent == null && !m_isSelected && !m_disabled && !m_building && !m_outbounds && Body != IntPtr.Zero)
{
- bool bodyenabled = d.BodyIsEnabled(Body);
-
- if(bodydisablecontrol < 0)
+ if(m_bodydisablecontrol < 0)
return;
+ bool bodyenabled = d.BodyIsEnabled(Body);
if (bodyenabled || !_zeroFlag)
{
bool lastZeroFlag = _zeroFlag;
@@ -3513,9 +3783,9 @@ namespace OpenSim.Region.PhysicsModule.ubOde
m_outbounds = true;
lpos.Z = Util.Clip(lpos.Z, -100f, 100000f);
- _acceleration.X = 0;
- _acceleration.Y = 0;
- _acceleration.Z = 0;
+ m_acceleration.X = 0;
+ m_acceleration.Y = 0;
+ m_acceleration.Z = 0;
_velocity.X = 0;
_velocity.Y = 0;
@@ -3638,19 +3908,19 @@ namespace OpenSim.Region.PhysicsModule.ubOde
_orientation.W = ori.W;
}
- // update velocities and aceleration
+ // update velocities and acceleration
if (_zeroFlag || lastZeroFlag)
{
// disable interpolators
_velocity = Vector3.Zero;
- _acceleration = Vector3.Zero;
- m_rotationalVelocity = Vector3.Zero;
+ m_acceleration = Vector3.Zero;
+ m_rotationalVelocity = Vector3.Zero;
}
else
{
d.Vector3 vel = d.BodyGetLinearVel(Body);
- _acceleration = _velocity;
+ m_acceleration = _velocity;
if ((Math.Abs(vel.X) < 0.005f) &&
(Math.Abs(vel.Y) < 0.005f) &&
@@ -3658,28 +3928,28 @@ namespace OpenSim.Region.PhysicsModule.ubOde
{
_velocity = Vector3.Zero;
float t = -m_invTimeStep;
- _acceleration = _acceleration * t;
+ m_acceleration = m_acceleration * t;
}
else
{
_velocity.X = vel.X;
_velocity.Y = vel.Y;
_velocity.Z = vel.Z;
- _acceleration = (_velocity - _acceleration) * m_invTimeStep;
+ m_acceleration = (_velocity - m_acceleration) * m_invTimeStep;
}
- if ((Math.Abs(_acceleration.X) < 0.01f) &&
- (Math.Abs(_acceleration.Y) < 0.01f) &&
- (Math.Abs(_acceleration.Z) < 0.01f))
+ if ((Math.Abs(m_acceleration.X) < 0.01f) &&
+ (Math.Abs(m_acceleration.Y) < 0.01f) &&
+ (Math.Abs(m_acceleration.Z) < 0.01f))
{
- _acceleration = Vector3.Zero;
+ m_acceleration = Vector3.Zero;
}
vel = d.BodyGetAngularVel(Body);
if ((Math.Abs(vel.X) < 0.0001) &&
- (Math.Abs(vel.Y) < 0.0001) &&
- (Math.Abs(vel.Z) < 0.0001)
- )
+ (Math.Abs(vel.Y) < 0.0001) &&
+ (Math.Abs(vel.Z) < 0.0001)
+ )
{
m_rotationalVelocity = Vector3.Zero;
}
@@ -3939,6 +4209,10 @@ namespace OpenSim.Region.PhysicsModule.ubOde
changePIDHoverActive((bool)arg);
break;
+ case changes.SetInertia:
+ changeInertia((PhysicsInertiaData) arg);
+ break;
+
case changes.Null:
donullchange();
break;
@@ -3955,7 +4229,6 @@ namespace OpenSim.Region.PhysicsModule.ubOde
_parent_scene.AddChange((PhysicsActor) this, what, arg);
}
-
private struct strVehicleBoolParam
{
public int param;
diff --git a/OpenSim/Region/PhysicsModules/ubOde/ODEScene.cs b/OpenSim/Region/PhysicsModules/ubOde/ODEScene.cs
index bed66ccad3..004ee7f31d 100644
--- a/OpenSim/Region/PhysicsModules/ubOde/ODEScene.cs
+++ b/OpenSim/Region/PhysicsModules/ubOde/ODEScene.cs
@@ -155,6 +155,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
VehicleRotationParam,
VehicleFlags,
SetVehicle,
+ SetInertia,
Null //keep this last used do dim the methods array. does nothing but pulsing the prim
}
@@ -185,7 +186,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
float frictionMovementMult = 0.8f;
- float TerrainBounce = 0.1f;
+ float TerrainBounce = 0.001f;
float TerrainFriction = 0.3f;
public float AvatarFriction = 0;// 0.9f * 0.5f;
@@ -202,8 +203,8 @@ namespace OpenSim.Region.PhysicsModule.ubOde
private float metersInSpace = 25.6f;
private float m_timeDilation = 1.0f;
- private DateTime m_lastframe;
- private DateTime m_lastMeshExpire;
+ private double m_lastframe;
+ private double m_lastMeshExpire;
public float gravityx = 0f;
public float gravityy = 0f;
@@ -480,7 +481,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
contactsPerCollision = physicsconfig.GetInt("contacts_per_collision", contactsPerCollision);
geomDefaultDensity = physicsconfig.GetFloat("geometry_default_density", geomDefaultDensity);
- bodyFramesAutoDisable = physicsconfig.GetInt("body_frames_auto_disable", bodyFramesAutoDisable);
+// bodyFramesAutoDisable = physicsconfig.GetInt("body_frames_auto_disable", bodyFramesAutoDisable);
physics_logging = physicsconfig.GetBoolean("physics_logging", false);
physics_logging_interval = physicsconfig.GetInt("physics_logging_interval", 0);
@@ -502,7 +503,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
d.WorldSetGravity(world, gravityx, gravityy, gravityz);
- d.WorldSetLinearDamping(world, 0.002f);
+ d.WorldSetLinearDamping(world, 0.001f);
d.WorldSetAngularDamping(world, 0.002f);
d.WorldSetAngularDampingThreshold(world, 0f);
d.WorldSetLinearDampingThreshold(world, 0f);
@@ -528,6 +529,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
SharedTmpcontact.surface.mode = comumContactFlags;
SharedTmpcontact.surface.mu = 0;
SharedTmpcontact.surface.bounce = 0;
+ SharedTmpcontact.surface.bounce_vel = 1.5f;
SharedTmpcontact.surface.soft_cfm = comumContactCFM;
SharedTmpcontact.surface.soft_erp = comumContactERP;
SharedTmpcontact.surface.slip1 = comumContactSLIP;
@@ -627,8 +629,9 @@ namespace OpenSim.Region.PhysicsModule.ubOde
staticPrimspaceOffRegion[i] = newspace;
}
- m_lastframe = DateTime.UtcNow;
+ m_lastframe = Util.GetTimeStamp();
m_lastMeshExpire = m_lastframe;
+ step_time = -1;
}
internal void waitForSpaceUnlock(IntPtr space)
@@ -726,8 +729,8 @@ namespace OpenSim.Region.PhysicsModule.ubOde
if (g1 == g2)
return; // Can't collide with yourself
- if (b1 != IntPtr.Zero && b2 != IntPtr.Zero && d.AreConnectedExcluding(b1, b2, d.JointType.Contact))
- return;
+// if (b1 != IntPtr.Zero && b2 != IntPtr.Zero && d.AreConnectedExcluding(b1, b2, d.JointType.Contact))
+// return;
/*
// debug
PhysicsActor dp2;
@@ -950,8 +953,8 @@ namespace OpenSim.Region.PhysicsModule.ubOde
SharedTmpcontact.surface.bounce = bounce;
d.ContactGeom altContact = new d.ContactGeom();
- bool useAltcontact = false;
- bool noskip = true;
+ bool useAltcontact;
+ bool noskip;
if(dop1ava || dop2ava)
smoothMesh = false;
@@ -998,7 +1001,6 @@ namespace OpenSim.Region.PhysicsModule.ubOde
Joint = CreateContacJoint(ref altContact,smoothMesh);
else
Joint = CreateContacJoint(ref curContact,smoothMesh);
-
if (Joint == IntPtr.Zero)
break;
@@ -1082,9 +1084,12 @@ namespace OpenSim.Region.PhysicsModule.ubOde
case ActorTypes.Prim:
if (p2events)
{
- AddCollisionEventReporting(p2);
+ //AddCollisionEventReporting(p2);
p2.AddCollisionEvent(p1.ParentActor.LocalID, contact);
}
+ else if(p1.IsVolumeDtc)
+ p2.AddVDTCCollisionEvent(p1.ParentActor.LocalID, contact);
+
obj2LocalID = p2.ParentActor.LocalID;
break;
@@ -1098,9 +1103,16 @@ namespace OpenSim.Region.PhysicsModule.ubOde
{
contact.SurfaceNormal = -contact.SurfaceNormal;
contact.RelativeSpeed = -contact.RelativeSpeed;
- AddCollisionEventReporting(p1);
+ //AddCollisionEventReporting(p1);
p1.AddCollisionEvent(obj2LocalID, contact);
}
+ else if(p2.IsVolumeDtc)
+ {
+ contact.SurfaceNormal = -contact.SurfaceNormal;
+ contact.RelativeSpeed = -contact.RelativeSpeed;
+ //AddCollisionEventReporting(p1);
+ p1.AddVDTCCollisionEvent(obj2LocalID, contact);
+ }
break;
}
case ActorTypes.Ground:
@@ -1109,7 +1121,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
{
if (p2events && !p2.IsVolumeDtc)
{
- AddCollisionEventReporting(p2);
+ //AddCollisionEventReporting(p2);
p2.AddCollisionEvent(0, contact);
}
break;
@@ -1161,8 +1173,11 @@ namespace OpenSim.Region.PhysicsModule.ubOde
{
aprim.CollisionScore = 0;
aprim.IsColliding = false;
+ if(!aprim.m_outbounds && d.BodyIsEnabled(aprim.Body))
+ aprim.clearSleeperCollisions();
}
}
+
lock (_activegroups)
{
try
@@ -1611,6 +1626,8 @@ namespace OpenSim.Region.PhysicsModule.ubOde
}
m_log.InfoFormat("[ubOde] {0} prim actors loaded",_prims.Count);
}
+ m_lastframe = Util.GetTimeStamp() + 0.5;
+ step_time = -0.5f;
}
///
@@ -1624,13 +1641,12 @@ namespace OpenSim.Region.PhysicsModule.ubOde
///
public override float Simulate(float reqTimeStep)
{
- DateTime now = DateTime.UtcNow;
- TimeSpan timedif = now - m_lastframe;
- float timeStep = (float)timedif.TotalSeconds;
+ double now = Util.GetTimeStamp();
+ double timeStep = now - m_lastframe;
m_lastframe = now;
// acumulate time so we can reduce error
- step_time += timeStep;
+ step_time += (float)timeStep;
if (step_time < HalfOdeStep)
return 0;
@@ -1657,11 +1673,15 @@ namespace OpenSim.Region.PhysicsModule.ubOde
// d.WorldSetQuickStepNumIterations(world, curphysiteractions);
- int loopstartMS = Util.EnvironmentTickCount();
- int looptimeMS = 0;
- int changestimeMS = 0;
- int maxChangestime = (int)(reqTimeStep * 500f); // half the time
- int maxLoopTime = (int)(reqTimeStep * 1200f); // 1.2 the time
+ double loopstartMS = Util.GetTimeStampMS();
+ double looptimeMS = 0;
+ double changestimeMS = 0;
+ double maxChangestime = (int)(reqTimeStep * 500f); // half the time
+ double maxLoopTime = (int)(reqTimeStep * 1200f); // 1.2 the time
+
+// double collisionTime = 0;
+// double qstepTIme = 0;
+// double tmpTime = 0;
d.AllocateODEDataForThread(~0U);
@@ -1684,7 +1704,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
item.actor.Name, item.what.ToString());
}
}
- changestimeMS = Util.EnvironmentTickCountSubtract(loopstartMS);
+ changestimeMS = Util.GetTimeStampMS() - loopstartMS;
if (changestimeMS > maxChangestime)
break;
}
@@ -1729,9 +1749,19 @@ namespace OpenSim.Region.PhysicsModule.ubOde
m_rayCastManager.ProcessQueuedRequests();
+// tmpTime = Util.GetTimeStampMS();
collision_optimized();
- List sleepers = new List();
+// collisionTime += Util.GetTimeStampMS() - tmpTime;
+ lock(_collisionEventPrimRemove)
+ {
+ foreach (PhysicsActor obj in _collisionEventPrimRemove)
+ _collisionEventPrim.Remove(obj);
+
+ _collisionEventPrimRemove.Clear();
+ }
+
+ List sleepers = new List();
foreach (PhysicsActor obj in _collisionEventPrim)
{
if (obj == null)
@@ -1761,18 +1791,12 @@ namespace OpenSim.Region.PhysicsModule.ubOde
foreach(OdePrim prm in sleepers)
prm.SleeperAddCollisionEvents();
sleepers.Clear();
-
- lock(_collisionEventPrimRemove)
- {
- foreach (PhysicsActor obj in _collisionEventPrimRemove)
- _collisionEventPrim.Remove(obj);
-
- _collisionEventPrimRemove.Clear();
- }
-
+
// do a ode simulation step
+// tmpTime = Util.GetTimeStampMS();
d.WorldQuickStep(world, ODE_STEPSIZE);
d.JointGroupEmpty(contactgroup);
+// qstepTIme += Util.GetTimeStampMS() - tmpTime;
// update managed ideia of physical data and do updates to core
/*
@@ -1813,7 +1837,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
step_time -= ODE_STEPSIZE;
nodeframes++;
- looptimeMS = Util.EnvironmentTickCountSubtract(loopstartMS);
+ looptimeMS = Util.GetTimeStampMS() - loopstartMS;
if (looptimeMS > maxLoopTime)
break;
}
@@ -1831,14 +1855,6 @@ namespace OpenSim.Region.PhysicsModule.ubOde
}
}
- timedif = now - m_lastMeshExpire;
-
- if (timedif.Seconds > 10)
- {
- mesher.ExpireReleaseMeshs();
- m_lastMeshExpire = now;
- }
-
// information block for in debug breakpoint only
/*
int ntopactivegeoms = d.SpaceGetNumGeoms(ActiveSpace);
@@ -1881,6 +1897,14 @@ namespace OpenSim.Region.PhysicsModule.ubOde
int totgeoms = nstaticgeoms + nactivegeoms + ngroundgeoms + 1; // one ray
int nbodies = d.NTotalBodies;
int ngeoms = d.NTotalGeoms;
+*/
+/*
+ looptimeMS /= nodeframes;
+ if(looptimeMS > 0.080)
+ {
+ collisionTime /= nodeframes;
+ qstepTIme /= nodeframes;
+ }
*/
// Finished with all sim stepping. If requested, dump world state to file for debugging.
// TODO: This call to the export function is already inside lock (OdeLock) - but is an extra lock needed?
@@ -1910,7 +1934,7 @@ namespace OpenSim.Region.PhysicsModule.ubOde
// if we lag too much skip frames
m_timeDilation = 0.0f;
step_time = 0;
- m_lastframe = DateTime.UtcNow; // skip also the time lost
+ m_lastframe = Util.GetTimeStamp(); // skip also the time lost
}
else
{
@@ -1918,6 +1942,14 @@ namespace OpenSim.Region.PhysicsModule.ubOde
if (m_timeDilation > 1)
m_timeDilation = 1;
}
+
+ if (m_timeDilation == 1 && now - m_lastMeshExpire > 30)
+ {
+ mesher.ExpireReleaseMeshs();
+ m_lastMeshExpire = now;
+ }
+
+
}
return fps;
diff --git a/OpenSim/Region/PhysicsModules/ubOdeMeshing/Meshmerizer.cs b/OpenSim/Region/PhysicsModules/ubOdeMeshing/Meshmerizer.cs
index 163f43928a..a2a3f79276 100644
--- a/OpenSim/Region/PhysicsModules/ubOdeMeshing/Meshmerizer.cs
+++ b/OpenSim/Region/PhysicsModules/ubOdeMeshing/Meshmerizer.cs
@@ -36,15 +36,13 @@ using OpenSim.Region.PhysicsModules.ConvexDecompositionDotNet;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using System.Drawing;
-using System.Drawing.Imaging;
+using System.Threading;
using System.IO.Compression;
using PrimMesher;
using log4net;
using Nini.Config;
using System.Reflection;
using System.IO;
-using System.Runtime.Serialization;
-using System.Runtime.Serialization.Formatters.Binary;
using Mono.Addins;
@@ -58,22 +56,22 @@ namespace OpenSim.Region.PhysicsModule.ubODEMeshing
// Setting baseDir to a path will enable the dumping of raw files
// raw files can be imported by blender so a visual inspection of the results can be done
+ private static string cacheControlFilename = "cntr";
private bool m_Enabled = false;
public static object diskLock = new object();
public bool doMeshFileCache = true;
-
+ public bool doCacheExpire = true;
public string cachePath = "MeshCache";
public TimeSpan CacheExpire;
- public bool doCacheExpire = true;
// const string baseDir = "rawFiles";
private const string baseDir = null; //"rawFiles";
- private bool useMeshiesPhysicsMesh = false;
-
- private float minSizeForComplexMesh = 0.2f; // prims with all dimensions smaller than this will have a bounding box mesh
+ private bool useMeshiesPhysicsMesh = true;
+ private bool doConvexPrims = true;
+ private bool doConvexSculpts = true;
private Dictionary m_uniqueMeshes = new Dictionary();
private Dictionary m_uniqueReleasedMeshes = new Dictionary();
@@ -103,40 +101,31 @@ namespace OpenSim.Region.PhysicsModule.ubODEMeshing
if (mesh_config != null)
{
useMeshiesPhysicsMesh = mesh_config.GetBoolean("UseMeshiesPhysicsMesh", useMeshiesPhysicsMesh);
- if (useMeshiesPhysicsMesh)
- {
- doMeshFileCache = mesh_config.GetBoolean("MeshFileCache", doMeshFileCache);
- cachePath = mesh_config.GetString("MeshFileCachePath", cachePath);
- fcache = mesh_config.GetFloat("MeshFileCacheExpireHours", fcache);
- doCacheExpire = mesh_config.GetBoolean("MeshFileCacheDoExpire", doCacheExpire);
- }
- else
- {
- doMeshFileCache = false;
- doCacheExpire = false;
- }
+ doConvexPrims = mesh_config.GetBoolean("ConvexPrims",doConvexPrims);
+ doConvexSculpts = mesh_config.GetBoolean("ConvexSculpts",doConvexPrims);
+ doMeshFileCache = mesh_config.GetBoolean("MeshFileCache", doMeshFileCache);
+ cachePath = mesh_config.GetString("MeshFileCachePath", cachePath);
+ fcache = mesh_config.GetFloat("MeshFileCacheExpireHours", fcache);
+ doCacheExpire = mesh_config.GetBoolean("MeshFileCacheDoExpire", doCacheExpire);
m_Enabled = true;
}
CacheExpire = TimeSpan.FromHours(fcache);
- lock (diskLock)
+ if(String.IsNullOrEmpty(cachePath))
+ doMeshFileCache = false;
+
+ if(doMeshFileCache)
{
- if(doMeshFileCache && cachePath != "")
+ if(!checkCache())
{
- try
- {
- if (!Directory.Exists(cachePath))
- Directory.CreateDirectory(cachePath);
- }
- catch
- {
- doMeshFileCache = false;
- doCacheExpire = false;
- }
+ doMeshFileCache = false;
+ doCacheExpire = false;
}
}
+ else
+ doCacheExpire = false;
}
}
@@ -168,87 +157,6 @@ namespace OpenSim.Region.PhysicsModule.ubODEMeshing
#endregion
- ///
- /// creates a simple box mesh of the specified size. This mesh is of very low vertex count and may
- /// be useful as a backup proxy when level of detail is not needed or when more complex meshes fail
- /// for some reason
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- private static Mesh CreateSimpleBoxMesh(float minX, float maxX, float minY, float maxY, float minZ, float maxZ)
- {
- Mesh box = new Mesh(true);
- List vertices = new List();
- // bottom
-
- vertices.Add(new Vertex(minX, maxY, minZ));
- vertices.Add(new Vertex(maxX, maxY, minZ));
- vertices.Add(new Vertex(maxX, minY, minZ));
- vertices.Add(new Vertex(minX, minY, minZ));
-
- box.Add(new Triangle(vertices[0], vertices[1], vertices[2]));
- box.Add(new Triangle(vertices[0], vertices[2], vertices[3]));
-
- // top
-
- vertices.Add(new Vertex(maxX, maxY, maxZ));
- vertices.Add(new Vertex(minX, maxY, maxZ));
- vertices.Add(new Vertex(minX, minY, maxZ));
- vertices.Add(new Vertex(maxX, minY, maxZ));
-
- box.Add(new Triangle(vertices[4], vertices[5], vertices[6]));
- box.Add(new Triangle(vertices[4], vertices[6], vertices[7]));
-
- // sides
-
- box.Add(new Triangle(vertices[5], vertices[0], vertices[3]));
- box.Add(new Triangle(vertices[5], vertices[3], vertices[6]));
-
- box.Add(new Triangle(vertices[1], vertices[0], vertices[5]));
- box.Add(new Triangle(vertices[1], vertices[5], vertices[4]));
-
- box.Add(new Triangle(vertices[7], vertices[1], vertices[4]));
- box.Add(new Triangle(vertices[7], vertices[2], vertices[1]));
-
- box.Add(new Triangle(vertices[3], vertices[2], vertices[7]));
- box.Add(new Triangle(vertices[3], vertices[7], vertices[6]));
-
- return box;
- }
-
- ///
- /// Creates a simple bounding box mesh for a complex input mesh
- ///
- ///
- ///
- private static Mesh CreateBoundingBoxMesh(Mesh meshIn)
- {
- float minX = float.MaxValue;
- float maxX = float.MinValue;
- float minY = float.MaxValue;
- float maxY = float.MinValue;
- float minZ = float.MaxValue;
- float maxZ = float.MinValue;
-
- foreach (Vector3 v in meshIn.getVertexList())
- {
- if (v.X < minX) minX = v.X;
- if (v.Y < minY) minY = v.Y;
- if (v.Z < minZ) minZ = v.Z;
-
- if (v.X > maxX) maxX = v.X;
- if (v.Y > maxY) maxY = v.Y;
- if (v.Z > maxZ) maxZ = v.Z;
- }
-
- return CreateSimpleBoxMesh(minX, maxX, minY, maxY, minZ, maxZ);
- }
-
private void ReportPrimError(string message, string primName, PrimMesh primMesh)
{
m_log.Error(message);
@@ -265,7 +173,7 @@ namespace OpenSim.Region.PhysicsModule.ubODEMeshing
///
private void AddSubMesh(OSDMap subMeshData, List coords, List faces)
{
- // Console.WriteLine("subMeshMap for {0} - {1}", primName, Util.GetFormattedXml((OSD)subMeshMap));
+ // Console.WriteLine("subMeshMap for {0} - {1}", primName, Util.GetFormattedXml((OSD)subMeshMap));
// As per http://wiki.secondlife.com/wiki/Mesh/Mesh_Asset_Format, some Mesh Level
// of Detail Blocks (maps) contain just a NoGeometry key to signal there is no
@@ -330,6 +238,7 @@ namespace OpenSim.Region.PhysicsModule.ubODEMeshing
List coords;
List faces;
+ bool needsConvexProcessing = convex;
if (primShape.SculptEntry)
{
@@ -340,23 +249,49 @@ namespace OpenSim.Region.PhysicsModule.ubODEMeshing
if (!GenerateCoordsAndFacesFromPrimMeshData(primName, primShape, out coords, out faces, convex))
return null;
+ needsConvexProcessing = false;
}
else
{
if (!GenerateCoordsAndFacesFromPrimSculptData(primName, primShape, lod, out coords, out faces))
return null;
+ needsConvexProcessing &= doConvexSculpts;
}
}
else
{
if (!GenerateCoordsAndFacesFromPrimShapeData(primName, primShape, lod, convex, out coords, out faces))
return null;
+ needsConvexProcessing &= doConvexPrims;
}
-
int numCoords = coords.Count;
int numFaces = faces.Count;
+ if(numCoords < 3 || (!needsConvexProcessing && numFaces < 1))
+ {
+ m_log.ErrorFormat("[MESH]: invalid degenerated mesh for prim {0} ignored", primName);
+ return null;
+ }
+
+ if(needsConvexProcessing)
+ {
+ List convexcoords;
+ List convexfaces;
+ if(CreateBoundingHull(coords, out convexcoords, out convexfaces) && convexcoords != null && convexfaces != null)
+ {
+ coords.Clear();
+ coords = convexcoords;
+ numCoords = coords.Count;
+
+ faces.Clear();
+ faces = convexfaces;
+ numFaces = faces.Count;
+ }
+ else
+ m_log.ErrorFormat("[ubMESH]: failed to create convex for {0} using normal mesh", primName);
+ }
+
Mesh mesh = new Mesh(true);
// Add the corresponding triangles to the mesh
for (int i = 0; i < numFaces; i++)
@@ -371,10 +306,10 @@ namespace OpenSim.Region.PhysicsModule.ubODEMeshing
faces.Clear();
if(mesh.numberVertices() < 3 || mesh.numberTriangles() < 1)
- {
- m_log.ErrorFormat("[MESH]: invalid degenerated mesh for prim " + primName + " ignored");
+ {
+ m_log.ErrorFormat("[MESH]: invalid degenerated mesh for prim {0} ignored", primName);
return null;
- }
+ }
primShape.SculptData = Utils.EmptyBytes;
@@ -454,7 +389,7 @@ namespace OpenSim.Region.PhysicsModule.ubODEMeshing
if (physicsParms == null)
{
- m_log.WarnFormat("[MESH]: unknown mesh type for prim {0}",primName);
+ //m_log.WarnFormat("[MESH]: unknown mesh type for prim {0}",primName);
return false;
}
@@ -625,45 +560,7 @@ namespace OpenSim.Region.PhysicsModule.ubODEMeshing
vs.Clear();
continue;
}
- /*
- if (!HullUtils.ComputeHull(vs, ref hullr, 0, 0.0f))
- {
- vs.Clear();
- continue;
- }
- nverts = hullr.Vertices.Count;
- nindexs = hullr.Indices.Count;
-
- if (nindexs % 3 != 0)
- {
- vs.Clear();
- continue;
- }
-
- for (i = 0; i < nverts; i++)
- {
- c.X = hullr.Vertices[i].x;
- c.Y = hullr.Vertices[i].y;
- c.Z = hullr.Vertices[i].z;
- coords.Add(c);
- }
-
- for (i = 0; i < nindexs; i += 3)
- {
- t1 = hullr.Indices[i];
- if (t1 > nverts)
- break;
- t2 = hullr.Indices[i + 1];
- if (t2 > nverts)
- break;
- t3 = hullr.Indices[i + 2];
- if (t3 > nverts)
- break;
- f = new Face(vertsoffset + t1, vertsoffset + t2, vertsoffset + t3);
- faces.Add(f);
- }
- */
List indices;
if (!HullUtils.ComputeHull(vs, out indices))
{
@@ -712,7 +609,7 @@ namespace OpenSim.Region.PhysicsModule.ubODEMeshing
else
{
// if neither mesh or decomposition present, warn and use convex
- m_log.WarnFormat("[MESH]: Data for PRIM shape type ( mesh or decomposition) not found for prim {0}",primName);
+ //m_log.WarnFormat("[MESH]: Data for PRIM shape type ( mesh or decomposition) not found for prim {0}",primName);
}
}
vs.Clear();
@@ -769,38 +666,7 @@ namespace OpenSim.Region.PhysicsModule.ubODEMeshing
vs.Clear();
return true;
}
-/*
- if (!HullUtils.ComputeHull(vs, ref hullr, 0, 0.0f))
- return false;
- nverts = hullr.Vertices.Count;
- nindexs = hullr.Indices.Count;
-
- if (nindexs % 3 != 0)
- return false;
-
- for (i = 0; i < nverts; i++)
- {
- c.X = hullr.Vertices[i].x;
- c.Y = hullr.Vertices[i].y;
- c.Z = hullr.Vertices[i].z;
- coords.Add(c);
- }
- for (i = 0; i < nindexs; i += 3)
- {
- t1 = hullr.Indices[i];
- if (t1 > nverts)
- break;
- t2 = hullr.Indices[i + 1];
- if (t2 > nverts)
- break;
- t3 = hullr.Indices[i + 2];
- if (t3 > nverts)
- break;
- f = new Face(t1, t2, t3);
- faces.Add(f);
- }
-*/
List indices;
if (!HullUtils.ComputeHull(vs, out indices))
return false;
@@ -1413,7 +1279,7 @@ namespace OpenSim.Region.PhysicsModule.ubODEMeshing
}
}
- public void FileNames(AMeshKey key, out string dir,out string fullFileName)
+ public void FileNames(AMeshKey key, out string dir, out string fullFileName)
{
string id = key.ToString();
string init = id.Substring(0, 1);
@@ -1530,7 +1396,7 @@ namespace OpenSim.Region.PhysicsModule.ubODEMeshing
if (!doCacheExpire)
return;
- string controlfile = System.IO.Path.Combine(cachePath, "cntr");
+ string controlfile = System.IO.Path.Combine(cachePath, cacheControlFilename);
lock (diskLock)
{
@@ -1583,5 +1449,153 @@ namespace OpenSim.Region.PhysicsModule.ubODEMeshing
catch { }
}
}
+
+ public bool checkCache()
+ {
+ string controlfile = System.IO.Path.Combine(cachePath, cacheControlFilename);
+ lock (diskLock)
+ {
+ try
+ {
+ if (!Directory.Exists(cachePath))
+ {
+ Directory.CreateDirectory(cachePath);
+ Thread.Sleep(100);
+ FileStream fs = File.Create(controlfile, 4096, FileOptions.WriteThrough);
+ fs.Close();
+ return true;
+ }
+ }
+ catch
+ {
+ doMeshFileCache = false;
+ doCacheExpire = false;
+ return false;
+ }
+ finally {}
+
+ if (File.Exists(controlfile))
+ return true;
+
+ try
+ {
+ Directory.Delete(cachePath, true);
+ while(Directory.Exists(cachePath))
+ Thread.Sleep(100);
+ }
+ catch(Exception e)
+ {
+ m_log.Error("[MESH CACHE]: failed to delete old version of the cache: " + e.Message);
+ doMeshFileCache = false;
+ doCacheExpire = false;
+ return false;
+ }
+ finally {}
+ try
+ {
+ Directory.CreateDirectory(cachePath);
+ while(!Directory.Exists(cachePath))
+ Thread.Sleep(100);
+ }
+ catch(Exception e)
+ {
+ m_log.Error("[MESH CACHE]: failed to create new cache folder: " + e.Message);
+ doMeshFileCache = false;
+ doCacheExpire = false;
+ return false;
+ }
+ finally {}
+
+ try
+ {
+ FileStream fs = File.Create(controlfile, 4096, FileOptions.WriteThrough);
+ fs.Close();
+ }
+ catch(Exception e)
+ {
+ m_log.Error("[MESH CACHE]: failed to create new control file: " + e.Message);
+ doMeshFileCache = false;
+ doCacheExpire = false;
+ return false;
+ }
+ finally {}
+
+ return true;
+ }
+ }
+
+ public bool CreateBoundingHull(List inputVertices, out List convexcoords, out List newfaces)
+ {
+ convexcoords = null;
+ newfaces = null;
+ HullDesc desc = new HullDesc();
+ HullResult result = new HullResult();
+
+ int nInputVerts = inputVertices.Count;
+ int i;
+
+ List vs = new List(nInputVerts);
+ float3 f3;
+
+ //useless copy
+ for(i = 0 ; i < nInputVerts; i++)
+ {
+ f3 = new float3(inputVertices[i].X, inputVertices[i].Y, inputVertices[i].Z);
+ vs.Add(f3);
+ }
+
+ desc.Vertices = vs;
+ desc.Flags = HullFlag.QF_TRIANGLES;
+ desc.MaxVertices = 256;
+
+ try
+ {
+ HullError ret = HullUtils.CreateConvexHull(desc, ref result);
+ if (ret != HullError.QE_OK)
+ return false;
+ int nverts = result.OutputVertices.Count;
+ int nindx = result.Indices.Count;
+ if(nverts < 3 || nindx< 3)
+ return false;
+ if(nindx % 3 != 0)
+ return false;
+
+ convexcoords = new List(nverts);
+ Coord c;
+ vs = result.OutputVertices;
+
+ for(i = 0 ; i < nverts; i++)
+ {
+ c = new Coord(vs[i].x, vs[i].y, vs[i].z);
+ convexcoords.Add(c);
+ }
+
+ newfaces = new List(nindx / 3);
+ List indxs = result.Indices;
+ int k, l, m;
+ Face f;
+ for(i = 0 ; i < nindx;)
+ {
+ k = indxs[i++];
+ l = indxs[i++];
+ m = indxs[i++];
+ if(k > nInputVerts)
+ continue;
+ if(l > nInputVerts)
+ continue;
+ if(m > nInputVerts)
+ continue;
+ f = new Face(k,l,m);
+ newfaces.Add(f);
+ }
+ return true;
+ }
+ catch
+ {
+
+ return false;
+ }
+ return false;
+ }
}
}
diff --git a/OpenSim/Region/PhysicsModules/ubOdeMeshing/PrimMesher.cs b/OpenSim/Region/PhysicsModules/ubOdeMeshing/PrimMesher.cs
index 10facf2713..e93175f081 100644
--- a/OpenSim/Region/PhysicsModules/ubOdeMeshing/PrimMesher.cs
+++ b/OpenSim/Region/PhysicsModules/ubOdeMeshing/PrimMesher.cs
@@ -755,8 +755,8 @@ namespace PrimMesher
if (hollowAngles.angles[0].angle - angles.angles[i].angle < angles.angles[i].angle - hollowAngles.angles[maxJ].angle + 0.000001f)
{
newFace.v1 = 0;
- newFace.v2 = numTotalVerts - maxJ - 1;
- newFace.v3 = numTotalVerts - 1;
+ newFace.v2 = numTotalVerts - 1;
+ newFace.v3 = numTotalVerts - maxJ - 1;
faces.Add(newFace);
}
diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/AsyncCommandManager.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/AsyncCommandManager.cs
index 6a39bb95e0..e01d2e44ea 100644
--- a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/AsyncCommandManager.cs
+++ b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/AsyncCommandManager.cs
@@ -51,7 +51,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
private static Thread cmdHandlerThread;
private static int cmdHandlerThreadCycleSleepms;
-
+ private static int numInstances;
///
/// Lock for reading/writing static components of AsyncCommandManager.
///
@@ -172,18 +172,12 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
if (!m_XmlRequest.ContainsKey(m_ScriptEngine))
m_XmlRequest[m_ScriptEngine] = new XmlRequest(this);
- StartThread();
- }
- }
-
- private static void StartThread()
- {
- if (cmdHandlerThread == null)
- {
- // Start the thread that will be doing the work
- cmdHandlerThread
- = WorkManager.StartThread(
+ numInstances++;
+ if (cmdHandlerThread == null)
+ {
+ cmdHandlerThread = WorkManager.StartThread(
CmdHandlerThreadLoop, "AsyncLSLCmdHandlerThread", ThreadPriority.Normal, true, true);
+ }
}
}
@@ -194,25 +188,34 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
cmdHandlerThreadCycleSleepms = 100;
}
+/*
~AsyncCommandManager()
{
// Shut down thread
-// try
-// {
-// if (cmdHandlerThread != null)
-// {
-// if (cmdHandlerThread.IsAlive == true)
-// {
-// cmdHandlerThread.Abort();
-// //cmdHandlerThread.Join();
-// }
-// }
-// }
-// catch
-// {
-// }
- }
+ try
+ {
+ lock (staticLock)
+ {
+ numInstances--;
+ if(numInstances > 0)
+ return;
+ if (cmdHandlerThread != null)
+ {
+ if (cmdHandlerThread.IsAlive == true)
+ {
+ cmdHandlerThread.Abort();
+ //cmdHandlerThread.Join();
+ cmdHandlerThread = null;
+ }
+ }
+ }
+ }
+ catch
+ {
+ }
+ }
+*/
///
/// Main loop for the manager thread
///
@@ -223,11 +226,11 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
try
{
Thread.Sleep(cmdHandlerThreadCycleSleepms);
-
+ Watchdog.UpdateThread();
DoOneCmdHandlerPass();
-
Watchdog.UpdateThread();
}
+ catch ( System.Threading.ThreadAbortException) { }
catch (Exception e)
{
m_log.Error("[ASYNC COMMAND MANAGER]: Exception in command handler pass: ", e);
@@ -240,24 +243,25 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
lock (staticLock)
{
// Check HttpRequests
- m_HttpRequest[m_ScriptEngines[0]].CheckHttpRequests();
+ try { m_HttpRequest[m_ScriptEngines[0]].CheckHttpRequests(); } catch {}
// Check XMLRPCRequests
- m_XmlRequest[m_ScriptEngines[0]].CheckXMLRPCRequests();
+ try { m_XmlRequest[m_ScriptEngines[0]].CheckXMLRPCRequests(); } catch {}
foreach (IScriptEngine s in m_ScriptEngines)
{
// Check Listeners
- m_Listener[s].CheckListeners();
+ try { m_Listener[s].CheckListeners(); } catch {}
+
// Check timers
- m_Timer[s].CheckTimerEvents();
+ try { m_Timer[s].CheckTimerEvents(); } catch {}
// Check Sensors
- m_SensorRepeat[s].CheckSenseRepeaterEvents();
+ try { m_SensorRepeat[s].CheckSenseRepeaterEvents(); } catch {}
// Check dataserver
- m_Dataserver[s].ExpireRequests();
+ try { m_Dataserver[s].ExpireRequests(); } catch {}
}
}
}
@@ -387,8 +391,6 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
}
}
-
-
public static Object[] GetSerializationData(IScriptEngine engine, UUID itemID)
{
List