diff --git a/OpenSim/ApplicationPlugins/RemoteController/RemoteAdminPlugin.cs b/OpenSim/ApplicationPlugins/RemoteController/RemoteAdminPlugin.cs index 1b4d1ea9f9..5a011cecb3 100644 --- a/OpenSim/ApplicationPlugins/RemoteController/RemoteAdminPlugin.cs +++ b/OpenSim/ApplicationPlugins/RemoteController/RemoteAdminPlugin.cs @@ -94,7 +94,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController public void Initialise() { - m_log.Info("[RADMIN]: " + Name + " cannot be default-initialized!"); + m_log.Error("[RADMIN]: " + Name + " cannot be default-initialized!"); throw new PluginNotInitialisedException(Name); } @@ -111,7 +111,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController else { m_config = m_configSource.Configs["RemoteAdmin"]; - m_log.Info("[RADMIN]: Remote Admin Plugin Enabled"); + m_log.Debug("[RADMIN]: Remote Admin Plugin Enabled"); m_requiredPassword = m_config.GetString("access_password", String.Empty); int port = m_config.GetInt("port", 0); @@ -130,6 +130,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController availableMethods["admin_broadcast"] = XmlRpcAlertMethod; availableMethods["admin_restart"] = XmlRpcRestartMethod; availableMethods["admin_load_heightmap"] = XmlRpcLoadHeightmapMethod; + availableMethods["admin_save_heightmap"] = XmlRpcSaveHeightmapMethod; // User management availableMethods["admin_create_user"] = XmlRpcCreateUserMethod; availableMethods["admin_create_user_email"] = XmlRpcCreateUserMethod; @@ -230,8 +231,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController } catch (Exception e) { - m_log.ErrorFormat("[RADMIN]: Restart region: failed: {0}", e.Message); - m_log.DebugFormat("[RADMIN]: Restart region: failed: {0}", e.ToString()); + m_log.ErrorFormat("[RADMIN]: Restart region: failed: {0} {1}", e.Message, e.StackTrace); responseData["accepted"] = false; responseData["success"] = false; responseData["rebooting"] = false; @@ -277,8 +277,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController } catch (Exception e) { - m_log.ErrorFormat("[RADMIN]: Broadcasting: failed: {0}", e.Message); - m_log.DebugFormat("[RADMIN]: Broadcasting: failed: {0}", e.ToString()); + m_log.ErrorFormat("[RADMIN]: Broadcasting: failed: {0}", e.Message, e.StackTrace); responseData["accepted"] = false; responseData["success"] = false; @@ -301,7 +300,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController { Hashtable requestData = (Hashtable) request.Params[0]; - m_log.DebugFormat("[RADMIN]: Load Terrain: XmlRpc {0}", request.ToString()); + m_log.DebugFormat("[RADMIN]: Load Terrain: XmlRpc {0}", request); // foreach (string k in requestData.Keys) // { // m_log.DebugFormat("[RADMIN]: Load Terrain: XmlRpc {0}: >{1}< {2}", @@ -348,8 +347,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController } catch (Exception e) { - m_log.ErrorFormat("[RADMIN]: Terrain Loading: failed: {0}", e.Message); - m_log.DebugFormat("[RADMIN]: Terrain Loading: failed: {0}", e.ToString()); + m_log.ErrorFormat("[RADMIN]: Terrain Loading: failed: {0} {1}", e.Message, e.StackTrace); responseData["success"] = false; responseData["error"] = e.Message; @@ -360,6 +358,61 @@ namespace OpenSim.ApplicationPlugins.RemoteController return response; } + public XmlRpcResponse XmlRpcSaveHeightmapMethod(XmlRpcRequest request, IPEndPoint remoteClient) + + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable responseData = new Hashtable(); + + m_log.Info("[RADMIN]: Save height maps request started"); + + try + { + Hashtable requestData = (Hashtable)request.Params[0]; + + m_log.DebugFormat("[RADMIN]: Save Terrain: XmlRpc {0}", request.ToString()); + + CheckStringParameters(request, new string[] { "password", "filename", "regionid" }); + + if (m_requiredPassword != String.Empty && + (!requestData.Contains("password") || (string)requestData["password"] != m_requiredPassword)) + throw new Exception("wrong password"); + + string file = (string)requestData["filename"]; + UUID regionID = (UUID)(string)requestData["regionid"]; + m_log.InfoFormat("[RADMIN]: Terrain Saving: {0}", file); + + responseData["accepted"] = true; + + Scene region = null; + + if (!m_application.SceneManager.TryGetScene(regionID, out region)) + throw new Exception("1: unable to get a scene with that name"); + + ITerrainModule terrainModule = region.RequestModuleInterface(); + if (null == terrainModule) throw new Exception("terrain module not available"); + + terrainModule.SaveToFile(file); + + responseData["success"] = false; + + response.Value = responseData; + } + catch (Exception e) + { + m_log.ErrorFormat("[RADMIN]: Terrain Saving: failed: {0}", e.Message); + m_log.DebugFormat("[RADMIN]: Terrain Saving: failed: {0}", e.ToString()); + + responseData["success"] = false; + responseData["error"] = e.Message; + + } + + m_log.Info("[RADMIN]: Save height maps request complete"); + + return response; + } + public XmlRpcResponse XmlRpcShutdownMethod(XmlRpcRequest request, IPEndPoint remoteClient) { m_log.Info("[RADMIN]: Received Shutdown Administrator Request"); @@ -417,14 +470,14 @@ namespace OpenSim.ApplicationPlugins.RemoteController } catch (Exception e) { - m_log.ErrorFormat("[RADMIN] Shutdown: failed: {0}", e.Message); - m_log.DebugFormat("[RADMIN] Shutdown: failed: {0}", e.ToString()); + m_log.ErrorFormat("[RADMIN]: Shutdown: failed: {0} {1}", e.Message, e.StackTrace); responseData["accepted"] = false; responseData["error"] = e.Message; response.Value = responseData; } + m_log.Info("[RADMIN]: Shutdown Administrator Request complete"); return response; } @@ -725,8 +778,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController } catch (Exception e) { - m_log.ErrorFormat("[RADMIN] CreateRegion: failed {0}", e.Message); - m_log.DebugFormat("[RADMIN] CreateRegion: failed {0}", e.ToString()); + m_log.ErrorFormat("[RADMIN] CreateRegion: failed {0} {1}", e.Message, e.StackTrace); responseData["success"] = false; responseData["error"] = e.Message; @@ -792,8 +844,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController } catch (Exception e) { - m_log.ErrorFormat("[RADMIN] DeleteRegion: failed {0}", e.Message); - m_log.DebugFormat("[RADMIN] DeleteRegion: failed {0}", e.ToString()); + m_log.ErrorFormat("[RADMIN] DeleteRegion: failed {0} {1}", e.Message, e.StackTrace); responseData["success"] = false; responseData["error"] = e.Message; @@ -884,8 +935,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController } catch (Exception e) { - m_log.ErrorFormat("[RADMIN] CloseRegion: failed {0}", e.Message); - m_log.DebugFormat("[RADMIN] CloseRegion: failed {0}", e.ToString()); + m_log.ErrorFormat("[RADMIN]: CloseRegion: failed {0} {1}", e.Message, e.StackTrace); responseData["success"] = false; responseData["error"] = e.Message; @@ -982,8 +1032,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController } catch (Exception e) { - m_log.ErrorFormat("[RADMIN] ModifyRegion: failed {0}", e.Message); - m_log.DebugFormat("[RADMIN] ModifyRegion: failed {0}", e.ToString()); + m_log.ErrorFormat("[RADMIN] ModifyRegion: failed {0} {1}", e.Message, e.StackTrace); responseData["success"] = false; responseData["error"] = e.Message; @@ -1106,8 +1155,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController } catch (Exception e) { - m_log.ErrorFormat("[RADMIN] CreateUser: failed: {0}", e.Message); - m_log.DebugFormat("[RADMIN] CreateUser: failed: {0}", e.ToString()); + m_log.ErrorFormat("[RADMIN]: CreateUser: failed: {0} {1}", e.Message, e.StackTrace); responseData["success"] = false; responseData["avatar_uuid"] = UUID.Zero.ToString(); @@ -1198,8 +1246,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController } catch (Exception e) { - m_log.ErrorFormat("[RADMIN] UserExists: failed: {0}", e.Message); - m_log.DebugFormat("[RADMIN] UserExists: failed: {0}", e.ToString()); + m_log.ErrorFormat("[RADMIN]: UserExists: failed: {0} {1}", e.Message, e.StackTrace); responseData["success"] = false; responseData["error"] = e.Message; @@ -1372,9 +1419,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController } catch (Exception e) { - - m_log.ErrorFormat("[RADMIN] UpdateUserAccount: failed: {0}", e.Message); - m_log.DebugFormat("[RADMIN] UpdateUserAccount: failed: {0}", e.ToString()); + m_log.ErrorFormat("[RADMIN] UpdateUserAccount: failed: {0} {1}", e.Message, e.StackTrace); responseData["success"] = false; responseData["avatar_uuid"] = UUID.Zero.ToString(); @@ -1382,6 +1427,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController response.Value = responseData; } + m_log.Info("[RADMIN]: UpdateUserAccount: request complete"); return response; } @@ -1397,7 +1443,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController private void UpdateUserAppearance(Hashtable responseData, Hashtable requestData, UUID userid) { - m_log.DebugFormat("[RADMIN] updateUserAppearance"); + m_log.DebugFormat("[RADMIN]: updateUserAppearance"); string defaultMale = m_config.GetString("default_male", "Default Male"); string defaultFemale = m_config.GetString("default_female", "Default Female"); @@ -1437,16 +1483,16 @@ namespace OpenSim.ApplicationPlugins.RemoteController if (String.IsNullOrEmpty(model)) { - m_log.DebugFormat("[RADMIN] Appearance update not requested"); + m_log.DebugFormat("[RADMIN]: Appearance update not requested"); return; } - m_log.DebugFormat("[RADMIN] Setting appearance for avatar {0}, using model <{1}>", userid, model); + m_log.DebugFormat("[RADMIN]: Setting appearance for avatar {0}, using model <{1}>", userid, model); string[] modelSpecifiers = model.Split(); if (modelSpecifiers.Length != 2) { - m_log.WarnFormat("[RADMIN] User appearance not set for {0}. Invalid model name : <{1}>", userid, model); + m_log.WarnFormat("[RADMIN]: User appearance not set for {0}. Invalid model name : <{1}>", userid, model); // modelSpecifiers = dmodel.Split(); return; } @@ -1457,7 +1503,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController if (modelProfile == null) { - m_log.WarnFormat("[RADMIN] Requested model ({0}) not found. Appearance unchanged", model); + m_log.WarnFormat("[RADMIN]: Requested model ({0}) not found. Appearance unchanged", model); return; } @@ -1467,7 +1513,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController EstablishAppearance(userid, modelProfile.PrincipalID); - m_log.DebugFormat("[RADMIN] Finished setting appearance for avatar {0}, using model {1}", + m_log.DebugFormat("[RADMIN]: Finished setting appearance for avatar {0}, using model {1}", userid, model); } @@ -1479,7 +1525,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController private void EstablishAppearance(UUID destination, UUID source) { - m_log.DebugFormat("[RADMIN] Initializing inventory for {0} from {1}", destination, source); + m_log.DebugFormat("[RADMIN]: Initializing inventory for {0} from {1}", destination, source); Scene scene = m_application.SceneManager.CurrentOrFirstScene; // If the model has no associated appearance we're done. @@ -1501,7 +1547,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController } catch (Exception e) { - m_log.WarnFormat("[RADMIN] Error transferring appearance for {0} : {1}", + m_log.WarnFormat("[RADMIN]: Error transferring appearance for {0} : {1}", destination, e.Message); } @@ -1532,7 +1578,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController } catch (Exception e) { - m_log.WarnFormat("[RADMIN] Error transferring appearance for {0} : {1}", + m_log.WarnFormat("[RADMIN]: Error transferring appearance for {0} : {1}", destination, e.Message); } @@ -1567,7 +1613,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController destinationFolder.ParentID = inventoryService.GetRootFolder(destination).ID; destinationFolder.Version = 1; inventoryService.AddFolder(destinationFolder); // store base record - m_log.ErrorFormat("[RADMIN] Created folder for destination {0}", source); + m_log.ErrorFormat("[RADMIN]: Created folder for destination {0}", source); } // Wearables @@ -1587,6 +1633,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController { InventoryItemBase destinationItem = new InventoryItemBase(UUID.Random(), destination); destinationItem.Name = item.Name; + destinationItem.Owner = destination; destinationItem.Description = item.Description; destinationItem.InvType = item.InvType; destinationItem.CreatorId = item.CreatorId; @@ -1606,6 +1653,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController destinationItem.Flags = item.Flags; destinationItem.CreationDate = item.CreationDate; destinationItem.Folder = destinationFolder.ID; + ApplyNextOwnerPermissions(destinationItem); m_application.SceneManager.CurrentOrFirstScene.AddInventoryItem(destinationItem); m_log.DebugFormat("[RADMIN]: Added item {0} to folder {1}", destinationItem.ID, destinationFolder.ID); @@ -1640,6 +1688,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController { InventoryItemBase destinationItem = new InventoryItemBase(UUID.Random(), destination); destinationItem.Name = item.Name; + destinationItem.Owner = destination; destinationItem.Description = item.Description; destinationItem.InvType = item.InvType; destinationItem.CreatorId = item.CreatorId; @@ -1659,6 +1708,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController destinationItem.Flags = item.Flags; destinationItem.CreationDate = item.CreationDate; destinationItem.Folder = destinationFolder.ID; + ApplyNextOwnerPermissions(destinationItem); m_application.SceneManager.CurrentOrFirstScene.AddInventoryItem(destinationItem); m_log.DebugFormat("[RADMIN]: Added item {0} to folder {1}", destinationItem.ID, destinationFolder.ID); @@ -1716,13 +1766,17 @@ namespace OpenSim.ApplicationPlugins.RemoteController { destinationFolder = new InventoryFolderBase(); destinationFolder.ID = UUID.Random(); - destinationFolder.Name = assetType.ToString(); + if (assetType == AssetType.Clothing) { + destinationFolder.Name = "Clothing"; + } else { + destinationFolder.Name = "Body Parts"; + } destinationFolder.Owner = destination; destinationFolder.Type = (short)assetType; destinationFolder.ParentID = inventoryService.GetRootFolder(destination).ID; destinationFolder.Version = 1; inventoryService.AddFolder(destinationFolder); // store base record - m_log.ErrorFormat("[RADMIN] Created folder for destination {0}", source); + m_log.ErrorFormat("[RADMIN]: Created folder for destination {0}", source); } InventoryFolderBase extraFolder; @@ -1740,7 +1794,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController extraFolder.ParentID = destinationFolder.ID; inventoryService.AddFolder(extraFolder); - m_log.DebugFormat("[RADMIN] Added folder {0} to folder {1}", extraFolder.ID, sourceFolder.ID); + m_log.DebugFormat("[RADMIN]: Added folder {0} to folder {1}", extraFolder.ID, sourceFolder.ID); List items = inventoryService.GetFolderContent(source, folder.ID).Items; @@ -1748,6 +1802,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController { InventoryItemBase destinationItem = new InventoryItemBase(UUID.Random(), destination); destinationItem.Name = item.Name; + destinationItem.Owner = destination; destinationItem.Description = item.Description; destinationItem.InvType = item.InvType; destinationItem.CreatorId = item.CreatorId; @@ -1767,6 +1822,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController destinationItem.Flags = item.Flags; destinationItem.CreationDate = item.CreationDate; destinationItem.Folder = extraFolder.ID; + ApplyNextOwnerPermissions(destinationItem); m_application.SceneManager.CurrentOrFirstScene.AddInventoryItem(destinationItem); inventoryMap.Add(item.ID, destinationItem.ID); @@ -1783,6 +1839,29 @@ namespace OpenSim.ApplicationPlugins.RemoteController } } + /// + /// Apply next owner permissions. + /// + + private void ApplyNextOwnerPermissions(InventoryItemBase item) + { + if (item.InvType == (int)InventoryType.Object && (item.CurrentPermissions & 7) != 0) + { + 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; + // item.OwnerChanged = true; + // item.PermsMask = 0; + // item.PermsGranter = UUID.Zero; + } + /// /// This method is called if a given model avatar name can not be found. If the external /// file has already been loaded once, then control returns immediately. If not, then it @@ -1792,7 +1871,6 @@ namespace OpenSim.ApplicationPlugins.RemoteController /// indicate which outfit is the default, and this outfit will be automatically worn. The /// other outfits are provided to allow "real" avatars a way to easily change their outfits. /// - private bool CreateDefaultAvatars() { // Only load once @@ -1801,7 +1879,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController return false; } - m_log.DebugFormat("[RADMIN] Creating default avatar entries"); + m_log.DebugFormat("[RADMIN]: Creating default avatar entries"); m_defaultAvatarsLoaded = true; @@ -1857,7 +1935,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController foreach (XmlElement avatar in avatars) { - m_log.DebugFormat("[RADMIN] Loading appearance for {0}, gender = {1}", + m_log.DebugFormat("[RADMIN]: Loading appearance for {0}, gender = {1}", GetStringAttribute(avatar,"name","?"), GetStringAttribute(avatar,"gender","?")); // Create the user identified by the avatar entry @@ -1879,7 +1957,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController account = CreateUser(scopeID, names[0], names[1], password, email); if (null == account) { - m_log.ErrorFormat("[RADMIN] Avatar {0} {1} was not created", names[0], names[1]); + m_log.ErrorFormat("[RADMIN]: Avatar {0} {1} was not created", names[0], names[1]); return false; } } @@ -1897,12 +1975,12 @@ namespace OpenSim.ApplicationPlugins.RemoteController ID = account.PrincipalID; - m_log.DebugFormat("[RADMIN] User {0}[{1}] created or retrieved", name, ID); + m_log.DebugFormat("[RADMIN]: User {0}[{1}] created or retrieved", name, ID); include = true; } catch (Exception e) { - m_log.DebugFormat("[RADMIN] Error creating user {0} : {1}", name, e.Message); + m_log.DebugFormat("[RADMIN]: Error creating user {0} : {1}", name, e.Message); include = false; } @@ -1942,7 +2020,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController clothingFolder.ParentID = inventoryService.GetRootFolder(ID).ID; clothingFolder.Version = 1; inventoryService.AddFolder(clothingFolder); // store base record - m_log.ErrorFormat("[RADMIN] Created clothing folder for {0}/{1}", name, ID); + m_log.ErrorFormat("[RADMIN]: Created clothing folder for {0}/{1}", name, ID); } // OK, now we have an inventory for the user, read in the outfits from the @@ -1955,7 +2033,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController foreach (XmlElement outfit in outfits) { - m_log.DebugFormat("[RADMIN] Loading outfit {0} for {1}", + m_log.DebugFormat("[RADMIN]: Loading outfit {0} for {1}", GetStringAttribute(outfit,"name","?"), GetStringAttribute(avatar,"name","?")); outfitName = GetStringAttribute(outfit,"name",""); @@ -1979,7 +2057,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController // Otherwise, we must create the folder. if (extraFolder == null) { - m_log.DebugFormat("[RADMIN] Creating outfit folder {0} for {1}", outfitName, name); + m_log.DebugFormat("[RADMIN]: Creating outfit folder {0} for {1}", outfitName, name); extraFolder = new InventoryFolderBase(); extraFolder.ID = UUID.Random(); extraFolder.Name = outfitName; @@ -1988,7 +2066,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController extraFolder.Version = 1; extraFolder.ParentID = clothingFolder.ID; inventoryService.AddFolder(extraFolder); - m_log.DebugFormat("[RADMIN] Adding outfile folder {0} to folder {1}", extraFolder.ID, clothingFolder.ID); + m_log.DebugFormat("[RADMIN]: Adding outfile folder {0} to folder {1}", extraFolder.ID, clothingFolder.ID); } // Now get the pieces that make up the outfit @@ -2003,7 +2081,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController switch (child.Name) { case "Permissions" : - m_log.DebugFormat("[RADMIN] Permissions specified"); + m_log.DebugFormat("[RADMIN]: Permissions specified"); perms = child; break; case "Asset" : @@ -2053,7 +2131,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController inventoryItem.Folder = extraFolder.ID; // Parent folder m_application.SceneManager.CurrentOrFirstScene.AddInventoryItem(inventoryItem); - m_log.DebugFormat("[RADMIN] Added item {0} to folder {1}", inventoryItem.ID, extraFolder.ID); + m_log.DebugFormat("[RADMIN]: Added item {0} to folder {1}", inventoryItem.ID, extraFolder.ID); } // Attach item, if attachpoint is specified @@ -2061,7 +2139,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController if (attachpoint != 0) { avatarAppearance.SetAttachment(attachpoint, inventoryItem.ID, inventoryItem.AssetID); - m_log.DebugFormat("[RADMIN] Attached {0}", inventoryItem.ID); + m_log.DebugFormat("[RADMIN]: Attached {0}", inventoryItem.ID); } // Record whether or not the item is to be initially worn @@ -2074,32 +2152,32 @@ namespace OpenSim.ApplicationPlugins.RemoteController } catch (Exception e) { - m_log.WarnFormat("[RADMIN] Error wearing item {0} : {1}", inventoryItem.ID, e.Message); + m_log.WarnFormat("[RADMIN]: Error wearing item {0} : {1}", inventoryItem.ID, e.Message); } } // foreach item in outfit - m_log.DebugFormat("[RADMIN] Outfit {0} load completed", outfitName); + m_log.DebugFormat("[RADMIN]: Outfit {0} load completed", outfitName); } // foreach outfit - m_log.DebugFormat("[RADMIN] Inventory update complete for {0}", name); + m_log.DebugFormat("[RADMIN]: Inventory update complete for {0}", name); scene.AvatarService.SetAppearance(ID, avatarAppearance); } catch (Exception e) { - m_log.WarnFormat("[RADMIN] Inventory processing incomplete for user {0} : {1}", + m_log.WarnFormat("[RADMIN]: Inventory processing incomplete for user {0} : {1}", name, e.Message); } } // End of include } - m_log.DebugFormat("[RADMIN] Default avatar loading complete"); + m_log.DebugFormat("[RADMIN]: Default avatar loading complete"); } else { - m_log.DebugFormat("[RADMIN] No default avatar information available"); + m_log.DebugFormat("[RADMIN]: No default avatar information available"); return false; } } catch (Exception e) { - m_log.WarnFormat("[RADMIN] Exception whilst loading default avatars ; {0}", e.Message); + m_log.WarnFormat("[RADMIN]: Exception whilst loading default avatars ; {0}", e.Message); return false; } @@ -2194,8 +2272,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController } catch (Exception e) { - m_log.InfoFormat("[RADMIN] LoadOAR: {0}", e.Message); - m_log.DebugFormat("[RADMIN] LoadOAR: {0}", e.ToString()); + m_log.ErrorFormat("[RADMIN]: LoadOAR: {0} {1}", e.Message, e.StackTrace); responseData["loaded"] = false; responseData["error"] = e.Message; @@ -2300,8 +2377,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController } catch (Exception e) { - m_log.InfoFormat("[RADMIN] SaveOAR: {0}", e.Message); - m_log.DebugFormat("[RADMIN] SaveOAR: {0}", e.ToString()); + m_log.ErrorFormat("[RADMIN]: SaveOAR: {0} {1}", e.Message, e.StackTrace); responseData["saved"] = false; responseData["error"] = e.Message; @@ -2315,7 +2391,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController private void RemoteAdminOarSaveCompleted(Guid uuid, string name) { - m_log.DebugFormat("[RADMIN] File processing complete for {0}", name); + m_log.DebugFormat("[RADMIN]: File processing complete for {0}", name); lock (m_saveOarLock) Monitor.Pulse(m_saveOarLock); } @@ -2353,14 +2429,14 @@ namespace OpenSim.ApplicationPlugins.RemoteController UUID region_uuid = (UUID) (string) requestData["region_uuid"]; if (!m_application.SceneManager.TrySetCurrentScene(region_uuid)) throw new Exception(String.Format("failed to switch to region {0}", region_uuid.ToString())); - m_log.InfoFormat("[RADMIN] Switched to region {0}", region_uuid.ToString()); + m_log.InfoFormat("[RADMIN]: Switched to region {0}", region_uuid.ToString()); } else if (requestData.Contains("region_name")) { string region_name = (string) requestData["region_name"]; if (!m_application.SceneManager.TrySetCurrentScene(region_name)) throw new Exception(String.Format("failed to switch to region {0}", region_name)); - m_log.InfoFormat("[RADMIN] Switched to region {0}", region_name); + m_log.InfoFormat("[RADMIN]: Switched to region {0}", region_name); } else throw new Exception("neither region_name nor region_uuid given"); @@ -2391,8 +2467,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController } catch (Exception e) { - m_log.InfoFormat("[RADMIN] LoadXml: {0}", e.Message); - m_log.DebugFormat("[RADMIN] LoadXml: {0}", e.ToString()); + m_log.ErrorFormat("[RADMIN] LoadXml: {0} {1}", e.Message, e.StackTrace); responseData["loaded"] = false; responseData["switched"] = false; @@ -2438,14 +2513,14 @@ namespace OpenSim.ApplicationPlugins.RemoteController UUID region_uuid = (UUID) (string) requestData["region_uuid"]; if (!m_application.SceneManager.TrySetCurrentScene(region_uuid)) throw new Exception(String.Format("failed to switch to region {0}", region_uuid.ToString())); - m_log.InfoFormat("[RADMIN] Switched to region {0}", region_uuid.ToString()); + m_log.InfoFormat("[RADMIN]: Switched to region {0}", region_uuid.ToString()); } else if (requestData.Contains("region_name")) { string region_name = (string) requestData["region_name"]; if (!m_application.SceneManager.TrySetCurrentScene(region_name)) throw new Exception(String.Format("failed to switch to region {0}", region_name)); - m_log.InfoFormat("[RADMIN] Switched to region {0}", region_name); + m_log.InfoFormat("[RADMIN]: Switched to region {0}", region_name); } else throw new Exception("neither region_name nor region_uuid given"); @@ -2477,8 +2552,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController } catch (Exception e) { - m_log.InfoFormat("[RADMIN] SaveXml: {0}", e.Message); - m_log.DebugFormat("[RADMIN] SaveXml: {0}", e.ToString()); + m_log.ErrorFormat("[RADMIN]: SaveXml: {0} {1}", e.Message, e.StackTrace); responseData["saved"] = false; responseData["switched"] = false; @@ -2517,14 +2591,14 @@ namespace OpenSim.ApplicationPlugins.RemoteController UUID region_uuid = (UUID) (string) requestData["region_uuid"]; if (!m_application.SceneManager.TrySetCurrentScene(region_uuid)) throw new Exception(String.Format("failed to switch to region {0}", region_uuid.ToString())); - m_log.InfoFormat("[RADMIN] Switched to region {0}", region_uuid.ToString()); + m_log.InfoFormat("[RADMIN]: Switched to region {0}", region_uuid.ToString()); } else if (requestData.Contains("region_name")) { string region_name = (string) requestData["region_name"]; if (!m_application.SceneManager.TrySetCurrentScene(region_name)) throw new Exception(String.Format("failed to switch to region {0}", region_name)); - m_log.InfoFormat("[RADMIN] Switched to region {0}", region_name); + m_log.InfoFormat("[RADMIN]: Switched to region {0}", region_name); } else throw new Exception("neither region_name nor region_uuid given"); @@ -2536,7 +2610,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController } catch (Exception e) { - m_log.InfoFormat("[RADMIN] RegionQuery: {0}", e.Message); + m_log.InfoFormat("[RADMIN]: RegionQuery: {0}", e.Message); responseData["success"] = false; responseData["error"] = e.Message; @@ -2577,7 +2651,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController } catch (Exception e) { - m_log.InfoFormat("[RADMIN] ConsoleCommand: {0}", e.Message); + m_log.InfoFormat("[RADMIN]: ConsoleCommand: {0}", e.Message); responseData["success"] = false; responseData["error"] = e.Message; @@ -2614,14 +2688,14 @@ namespace OpenSim.ApplicationPlugins.RemoteController UUID region_uuid = (UUID) (string) requestData["region_uuid"]; if (!m_application.SceneManager.TrySetCurrentScene(region_uuid)) throw new Exception(String.Format("failed to switch to region {0}", region_uuid.ToString())); - m_log.InfoFormat("[RADMIN] Switched to region {0}", region_uuid.ToString()); + m_log.InfoFormat("[RADMIN]: Switched to region {0}", region_uuid.ToString()); } else if (requestData.Contains("region_name")) { string region_name = (string) requestData["region_name"]; if (!m_application.SceneManager.TrySetCurrentScene(region_name)) throw new Exception(String.Format("failed to switch to region {0}", region_name)); - m_log.InfoFormat("[RADMIN] Switched to region {0}", region_name); + m_log.InfoFormat("[RADMIN]: Switched to region {0}", region_name); } else throw new Exception("neither region_name nor region_uuid given"); @@ -2632,7 +2706,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController } catch (Exception e) { - m_log.InfoFormat("[RADMIN] Access List Clear Request: {0}", e.Message); + m_log.ErrorFormat("[RADMIN]: Access List Clear Request: {0} {1}", e.Message, e.StackTrace); responseData["success"] = false; responseData["error"] = e.Message; @@ -2671,14 +2745,14 @@ namespace OpenSim.ApplicationPlugins.RemoteController UUID region_uuid = (UUID) (string) requestData["region_uuid"]; if (!m_application.SceneManager.TrySetCurrentScene(region_uuid)) throw new Exception(String.Format("failed to switch to region {0}", region_uuid.ToString())); - m_log.InfoFormat("[RADMIN] Switched to region {0}", region_uuid.ToString()); + m_log.InfoFormat("[RADMIN]: Switched to region {0}", region_uuid.ToString()); } else if (requestData.Contains("region_name")) { string region_name = (string) requestData["region_name"]; if (!m_application.SceneManager.TrySetCurrentScene(region_name)) throw new Exception(String.Format("failed to switch to region {0}", region_name)); - m_log.InfoFormat("[RADMIN] Switched to region {0}", region_name); + m_log.InfoFormat("[RADMIN]: Switched to region {0}", region_name); } else throw new Exception("neither region_name nor region_uuid given"); @@ -2698,7 +2772,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController if (account != null) { uuids.Add(account.PrincipalID); - m_log.DebugFormat("[RADMIN] adding \"{0}\" to ACL for \"{1}\"", name, scene.RegionInfo.RegionName); + m_log.DebugFormat("[RADMIN]: adding \"{0}\" to ACL for \"{1}\"", name, scene.RegionInfo.RegionName); } } List accessControlList = new List(scene.RegionInfo.EstateSettings.EstateAccess); @@ -2719,7 +2793,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController } catch (Exception e) { - m_log.InfoFormat("[RADMIN] Access List Add Request: {0}", e.Message); + m_log.ErrorFormat("[RADMIN]: Access List Add Request: {0} {1}", e.Message, e.StackTrace); responseData["success"] = false; responseData["error"] = e.Message; @@ -2758,14 +2832,14 @@ namespace OpenSim.ApplicationPlugins.RemoteController UUID region_uuid = (UUID) (string) requestData["region_uuid"]; if (!m_application.SceneManager.TrySetCurrentScene(region_uuid)) throw new Exception(String.Format("failed to switch to region {0}", region_uuid.ToString())); - m_log.InfoFormat("[RADMIN] Switched to region {0}", region_uuid.ToString()); + m_log.InfoFormat("[RADMIN]: Switched to region {0}", region_uuid.ToString()); } else if (requestData.Contains("region_name")) { string region_name = (string) requestData["region_name"]; if (!m_application.SceneManager.TrySetCurrentScene(region_name)) throw new Exception(String.Format("failed to switch to region {0}", region_name)); - m_log.InfoFormat("[RADMIN] Switched to region {0}", region_name); + m_log.InfoFormat("[RADMIN]: Switched to region {0}", region_name); } else throw new Exception("neither region_name nor region_uuid given"); @@ -2806,7 +2880,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController } catch (Exception e) { - m_log.InfoFormat("[RADMIN] Access List Remove Request: {0}", e.Message); + m_log.ErrorFormat("[RADMIN]: Access List Remove Request: {0} {1}", e.Message, e.StackTrace); responseData["success"] = false; responseData["error"] = e.Message; @@ -2845,14 +2919,14 @@ namespace OpenSim.ApplicationPlugins.RemoteController UUID region_uuid = (UUID) (string) requestData["region_uuid"]; if (!m_application.SceneManager.TrySetCurrentScene(region_uuid)) throw new Exception(String.Format("failed to switch to region {0}", region_uuid.ToString())); - m_log.InfoFormat("[RADMIN] Switched to region {0}", region_uuid.ToString()); + m_log.InfoFormat("[RADMIN]: Switched to region {0}", region_uuid.ToString()); } else if (requestData.Contains("region_name")) { string region_name = (string) requestData["region_name"]; if (!m_application.SceneManager.TrySetCurrentScene(region_name)) throw new Exception(String.Format("failed to switch to region {0}", region_name)); - m_log.InfoFormat("[RADMIN] Switched to region {0}", region_name); + m_log.InfoFormat("[RADMIN]: Switched to region {0}", region_name); } else throw new Exception("neither region_name nor region_uuid given"); @@ -2874,7 +2948,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController } catch (Exception e) { - m_log.InfoFormat("[RADMIN] Acces List List: {0}", e.Message); + m_log.ErrorFormat("[RADMIN]: Access List List: {0} {1}", e.Message, e.StackTrace); responseData["success"] = false; responseData["error"] = e.Message; diff --git a/OpenSim/Client/MXP/ClientStack/MXPClientView.cs b/OpenSim/Client/MXP/ClientStack/MXPClientView.cs index 93c6c98469..a604a2ee63 100644 --- a/OpenSim/Client/MXP/ClientStack/MXPClientView.cs +++ b/OpenSim/Client/MXP/ClientStack/MXPClientView.cs @@ -66,8 +66,8 @@ namespace OpenSim.Client.MXP.ClientStack private readonly IScene m_scene; private readonly string m_firstName; private readonly string m_lastName; - private int m_objectsToSynchronize = 0; - private int m_objectsSynchronized = -1; +// private int m_objectsToSynchronize = 0; +// private int m_objectsSynchronized = -1; private Vector3 m_startPosition=new Vector3(128f, 128f, 128f); #endregion @@ -462,8 +462,8 @@ namespace OpenSim.Client.MXP.ClientStack public void MXPSendSynchronizationBegin(int objectCount) { - m_objectsToSynchronize = objectCount; - m_objectsSynchronized = 0; +// m_objectsToSynchronize = objectCount; +// m_objectsSynchronized = 0; SynchronizationBeginEventMessage synchronizationBeginEventMessage = new SynchronizationBeginEventMessage(); synchronizationBeginEventMessage.ObjectCount = (uint)objectCount; Session.Send(synchronizationBeginEventMessage); @@ -1337,12 +1337,12 @@ namespace OpenSim.Client.MXP.ClientStack // Need to translate to MXP somehow } - public void SendObjectPropertiesFamilyData(uint RequestFlags, UUID ObjectUUID, UUID OwnerID, UUID GroupID, uint BaseMask, uint OwnerMask, uint GroupMask, uint EveryoneMask, uint NextOwnerMask, int OwnershipCost, byte SaleType, int SalePrice, uint Category, UUID LastOwnerID, string ObjectName, string Description) + public void SendObjectPropertiesFamilyData(ISceneEntity Entity, uint RequestFlags) { //throw new System.NotImplementedException(); } - public void SendObjectPropertiesReply(UUID ItemID, ulong CreationDate, UUID CreatorUUID, UUID FolderUUID, UUID FromTaskUUID, UUID GroupUUID, short InventorySerial, UUID LastOwnerUUID, UUID ObjectUUID, UUID OwnerUUID, string TouchTitle, byte[] TextureID, string SitTitle, string ItemName, string ItemDescription, uint OwnerMask, uint NextOwnerMask, uint GroupMask, uint EveryoneMask, uint BaseMask, byte saleType, int salePrice) + public void SendObjectPropertiesReply(ISceneEntity entity) { //throw new System.NotImplementedException(); } diff --git a/OpenSim/Client/VWoHTTP/ClientStack/VWHClientView.cs b/OpenSim/Client/VWoHTTP/ClientStack/VWHClientView.cs index fc27f0198b..d8cd0acbd9 100644 --- a/OpenSim/Client/VWoHTTP/ClientStack/VWHClientView.cs +++ b/OpenSim/Client/VWoHTTP/ClientStack/VWHClientView.cs @@ -884,12 +884,12 @@ namespace OpenSim.Client.VWoHTTP.ClientStack throw new System.NotImplementedException(); } - public void SendObjectPropertiesFamilyData(uint RequestFlags, UUID ObjectUUID, UUID OwnerID, UUID GroupID, uint BaseMask, uint OwnerMask, uint GroupMask, uint EveryoneMask, uint NextOwnerMask, int OwnershipCost, byte SaleType, int SalePrice, uint Category, UUID LastOwnerID, string ObjectName, string Description) + public void SendObjectPropertiesFamilyData(ISceneEntity Entity, uint RequestFlags) { throw new System.NotImplementedException(); } - public void SendObjectPropertiesReply(UUID ItemID, ulong CreationDate, UUID CreatorUUID, UUID FolderUUID, UUID FromTaskUUID, UUID GroupUUID, short InventorySerial, UUID LastOwnerUUID, UUID ObjectUUID, UUID OwnerUUID, string TouchTitle, byte[] TextureID, string SitTitle, string ItemName, string ItemDescription, uint OwnerMask, uint NextOwnerMask, uint GroupMask, uint EveryoneMask, uint BaseMask, byte saleType, int salePrice) + public void SendObjectPropertiesReply(ISceneEntity entity) { throw new System.NotImplementedException(); } diff --git a/OpenSim/Data/MSSQL/MSSQLAvatarData.cs b/OpenSim/Data/MSSQL/MSSQLAvatarData.cs index 49a6b09f76..301b42490a 100644 --- a/OpenSim/Data/MSSQL/MSSQLAvatarData.cs +++ b/OpenSim/Data/MSSQL/MSSQLAvatarData.cs @@ -43,7 +43,7 @@ namespace OpenSim.Data.MSSQL public class MSSQLAvatarData : MSSQLGenericTableHandler, IAvatarData { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); +// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public MSSQLAvatarData(string connectionString, string realm) : base(connectionString, realm, "Avatar") diff --git a/OpenSim/Data/MSSQL/MSSQLEstateData.cs b/OpenSim/Data/MSSQL/MSSQLEstateData.cs index 92a8d80b9a..d10ebe4f48 100644 --- a/OpenSim/Data/MSSQL/MSSQLEstateData.cs +++ b/OpenSim/Data/MSSQL/MSSQLEstateData.cs @@ -372,6 +372,11 @@ namespace OpenSim.Data.MSSQL return new List(); } + public List GetEstatesByOwner(UUID ownerID) + { + return new List(); + } + public bool LinkRegion(UUID regionID, int estateID) { // TODO: Implementation! diff --git a/OpenSim/Data/MSSQL/MSSQLGenericTableHandler.cs b/OpenSim/Data/MSSQL/MSSQLGenericTableHandler.cs index 904366e995..6a5d6eb58a 100644 --- a/OpenSim/Data/MSSQL/MSSQLGenericTableHandler.cs +++ b/OpenSim/Data/MSSQL/MSSQLGenericTableHandler.cs @@ -40,8 +40,8 @@ namespace OpenSim.Data.MSSQL { public class MSSQLGenericTableHandler where T : class, new() { - private static readonly ILog m_log = - LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); +// private static readonly ILog m_log = +// LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected string m_ConnectionString; protected MSSQLManager m_database; //used for parameter type translation diff --git a/OpenSim/Data/MSSQL/MSSQLGridUserData.cs b/OpenSim/Data/MSSQL/MSSQLGridUserData.cs index 1870273616..9e215f9fb2 100644 --- a/OpenSim/Data/MSSQL/MSSQLGridUserData.cs +++ b/OpenSim/Data/MSSQL/MSSQLGridUserData.cs @@ -43,7 +43,7 @@ namespace OpenSim.Data.MSSQL public class MSSQLGridUserData : MSSQLGenericTableHandler, IGridUserData { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); +// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public MSSQLGridUserData(string connectionString, string realm) : base(connectionString, realm, "GridUserStore") diff --git a/OpenSim/Data/MSSQL/MSSQLManager.cs b/OpenSim/Data/MSSQL/MSSQLManager.cs index 575fd210c1..cf963e3f07 100644 --- a/OpenSim/Data/MSSQL/MSSQLManager.cs +++ b/OpenSim/Data/MSSQL/MSSQLManager.cs @@ -41,7 +41,7 @@ namespace OpenSim.Data.MSSQL /// public class MSSQLManager { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); +// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// /// Connection string for ADO.net @@ -180,8 +180,6 @@ namespace OpenSim.Data.MSSQL return parameter; } - private static readonly Dictionary emptyDictionary = new Dictionary(); - /// /// Checks if we need to do some migrations to the database /// diff --git a/OpenSim/Data/MSSQL/MSSQLPresenceData.cs b/OpenSim/Data/MSSQL/MSSQLPresenceData.cs index e7b3d9c367..8068d23bb1 100644 --- a/OpenSim/Data/MSSQL/MSSQLPresenceData.cs +++ b/OpenSim/Data/MSSQL/MSSQLPresenceData.cs @@ -43,7 +43,7 @@ namespace OpenSim.Data.MSSQL public class MSSQLPresenceData : MSSQLGenericTableHandler, IPresenceData { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); +// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public MSSQLPresenceData(string connectionString, string realm) : base(connectionString, realm, "Presence") diff --git a/OpenSim/Data/MSSQL/MSSQLXInventoryData.cs b/OpenSim/Data/MSSQL/MSSQLXInventoryData.cs index 739eb55ad4..5bc4fe41e5 100644 --- a/OpenSim/Data/MSSQL/MSSQLXInventoryData.cs +++ b/OpenSim/Data/MSSQL/MSSQLXInventoryData.cs @@ -40,8 +40,8 @@ namespace OpenSim.Data.MSSQL { public class MSSQLXInventoryData : IXInventoryData { - private static readonly ILog m_log = LogManager.GetLogger( - MethodBase.GetCurrentMethod().DeclaringType); +// private static readonly ILog m_log = LogManager.GetLogger( +// MethodBase.GetCurrentMethod().DeclaringType); private MSSQLGenericTableHandler m_Folders; private MSSQLItemHandler m_Items; diff --git a/OpenSim/Data/MySQL/MySQLEstateData.cs b/OpenSim/Data/MySQL/MySQLEstateData.cs index 6d72e82e2b..86416d1775 100644 --- a/OpenSim/Data/MySQL/MySQLEstateData.cs +++ b/OpenSim/Data/MySQL/MySQLEstateData.cs @@ -484,6 +484,36 @@ namespace OpenSim.Data.MySQL return result; } + public List GetEstatesByOwner(UUID ownerID) + { + List result = new List(); + + using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) + { + dbcon.Open(); + + using (MySqlCommand cmd = dbcon.CreateCommand()) + { + cmd.CommandText = "select estateID from estate_settings where EstateOwner = ?EstateOwner"; + cmd.Parameters.AddWithValue("?EstateOwner", ownerID); + + using (IDataReader reader = cmd.ExecuteReader()) + { + while (reader.Read()) + { + result.Add(Convert.ToInt32(reader["EstateID"])); + } + reader.Close(); + } + } + + + dbcon.Close(); + } + + return result; + } + public bool LinkRegion(UUID regionID, int estateID) { using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) diff --git a/OpenSim/Data/MySQL/MySQLGenericTableHandler.cs b/OpenSim/Data/MySQL/MySQLGenericTableHandler.cs index 8efe4e9bd6..50b6dbef42 100644 --- a/OpenSim/Data/MySQL/MySQLGenericTableHandler.cs +++ b/OpenSim/Data/MySQL/MySQLGenericTableHandler.cs @@ -39,6 +39,8 @@ namespace OpenSim.Data.MySQL { public class MySQLGenericTableHandler : MySqlFramework where T: class, new() { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + protected Dictionary m_Fields = new Dictionary(); @@ -217,7 +219,6 @@ namespace OpenSim.Data.MySQL { using (MySqlCommand cmd = new MySqlCommand()) { - string query = ""; List names = new List(); List values = new List(); @@ -226,6 +227,16 @@ namespace OpenSim.Data.MySQL { names.Add(fi.Name); values.Add("?" + fi.Name); + + // Temporarily return more information about what field is unexpectedly null for + // http://opensimulator.org/mantis/view.php?id=5403. This might be due to a bug in the + // InventoryTransferModule or we may be required to substitute a DBNull here. + if (fi.GetValue(row) == null) + throw new NullReferenceException( + string.Format( + "[MYSQL GENERIC TABLE HANDLER]: Trying to store field {0} for {1} which is unexpectedly null", + fi.Name, row)); + cmd.Parameters.AddWithValue(fi.Name, fi.GetValue(row).ToString()); } @@ -268,4 +279,4 @@ namespace OpenSim.Data.MySQL } } } -} +} \ No newline at end of file diff --git a/OpenSim/Data/Null/NullEstateData.cs b/OpenSim/Data/Null/NullEstateData.cs new file mode 100755 index 0000000000..8db8064cbe --- /dev/null +++ b/OpenSim/Data/Null/NullEstateData.cs @@ -0,0 +1,133 @@ +/* + * 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 log4net; +using OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Region.Framework; +using OpenSim.Region.Framework.Interfaces; + +namespace OpenSim.Data.Null +{ + public class NullEstateStore : IEstateDataStore + { +// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + +// private string m_connectionString; + + protected virtual Assembly Assembly + { + get { return GetType().Assembly; } + } + + public NullEstateStore() + { + } + + public NullEstateStore(string connectionString) + { + Initialise(connectionString); + } + + public void Initialise(string connectionString) + { +// m_connectionString = connectionString; + } + + private string[] FieldList + { + get { return new string[0]; } + } + + public EstateSettings LoadEstateSettings(UUID regionID, bool create) + { + // This fools the initialization caller into thinking an estate was fetched (a check in OpenSimBase). + // The estate info is pretty empty so don't try banning anyone. + EstateSettings oneEstate = new EstateSettings(); + oneEstate.EstateID = 1; + return oneEstate; + } + + public void StoreEstateSettings(EstateSettings es) + { + return; + } + + public EstateSettings LoadEstateSettings(int estateID) + { + return new EstateSettings(); + } + + public List LoadEstateSettingsAll() + { + List allEstateSettings = new List(); + allEstateSettings.Add(new EstateSettings()); + return allEstateSettings; + } + + public List GetEstatesAll() + { + List result = new List(); + return result; + } + + public List GetEstates(string search) + { + List result = new List(); + return result; + } + + public bool LinkRegion(UUID regionID, int estateID) + { + return false; + } + + public List GetRegions(int estateID) + { + List result = new List(); + return result; + } + + public bool DeleteEstate(int estateID) + { + return false; + } + + #region IEstateDataStore Members + + + public List GetEstatesByOwner(UUID ownerID) + { + return new List(); + } + + #endregion + } +} diff --git a/OpenSim/Data/Null/NullSimulationData.cs b/OpenSim/Data/Null/NullSimulationData.cs index eb4e313f84..e8d733b582 100644 --- a/OpenSim/Data/Null/NullSimulationData.cs +++ b/OpenSim/Data/Null/NullSimulationData.cs @@ -38,6 +38,15 @@ namespace OpenSim.Data.Null /// public class NullSimulationData : ISimulationDataStore { + public NullSimulationData() + { + } + + public NullSimulationData(string connectionString) + { + Initialise(connectionString); + } + public void Initialise(string dbfile) { return; @@ -85,12 +94,20 @@ namespace OpenSim.Data.Null return new List(); } + Dictionary m_terrains = new Dictionary(); public void StoreTerrain(double[,] ter, UUID regionID) { + if (m_terrains.ContainsKey(regionID)) + m_terrains.Remove(regionID); + m_terrains.Add(regionID, ter); } public double[,] LoadTerrain(UUID regionID) { + if (m_terrains.ContainsKey(regionID)) + { + return m_terrains[regionID]; + } return null; } diff --git a/OpenSim/Data/SQLite/SQLiteEstateData.cs b/OpenSim/Data/SQLite/SQLiteEstateData.cs index 6afc5401d8..2f05a6e9f4 100644 --- a/OpenSim/Data/SQLite/SQLiteEstateData.cs +++ b/OpenSim/Data/SQLite/SQLiteEstateData.cs @@ -412,6 +412,28 @@ namespace OpenSim.Data.SQLite return result; } + public List GetEstatesByOwner(UUID ownerID) + { + List result = new List(); + + string sql = "select EstateID from estate_settings where estate_settings.EstateOwner = :EstateOwner"; + + SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand(); + + cmd.CommandText = sql; + cmd.Parameters.AddWithValue(":EstateOwner", ownerID); + + IDataReader r = cmd.ExecuteReader(); + + while (r.Read()) + { + result.Add(Convert.ToInt32(r["EstateID"])); + } + r.Close(); + + return result; + } + public bool LinkRegion(UUID regionID, int estateID) { SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand(); diff --git a/OpenSim/Data/SQLiteLegacy/Properties/AssemblyInfo.cs b/OpenSim/Data/SQLiteLegacy/Properties/AssemblyInfo.cs deleted file mode 100644 index 609a024b73..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System.Reflection; -using System.Runtime.InteropServices; - -// General information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. - -[assembly : AssemblyTitle("OpenSim.Data.SQLiteLegacy")] -[assembly : AssemblyDescription("")] -[assembly : AssemblyConfiguration("")] -[assembly : AssemblyCompany("http://opensimulator.org")] -[assembly : AssemblyProduct("OpenSim.Data.SQLiteLegacy")] -[assembly : AssemblyCopyright("Copyright (c) OpenSimulator.org Developers 2007-2009")] -[assembly : AssemblyTrademark("")] -[assembly : AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. - -[assembly : ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM - -[assembly : Guid("6113d5ce-4547-49f4-9236-0dcc503457b1")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Revision and Build Numbers -// by using the '*' as shown below: - -[assembly : AssemblyVersion("0.6.5.*")] -[assembly : AssemblyFileVersion("0.6.5.0")] diff --git a/OpenSim/Data/SQLiteLegacy/Resources/001_AssetStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/001_AssetStore.sql deleted file mode 100644 index 2e026cad19..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/001_AssetStore.sql +++ /dev/null @@ -1,12 +0,0 @@ -BEGIN TRANSACTION; -CREATE TABLE assets( - UUID varchar(255) primary key, - Name varchar(255), - Description varchar(255), - Type integer, - InvType integer, - Local integer, - Temporary integer, - Data blob); - -COMMIT; diff --git a/OpenSim/Data/SQLiteLegacy/Resources/001_AuthStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/001_AuthStore.sql deleted file mode 100644 index 468567dcc2..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/001_AuthStore.sql +++ /dev/null @@ -1,18 +0,0 @@ -BEGIN TRANSACTION; - -CREATE TABLE auth ( - UUID char(36) NOT NULL, - passwordHash char(32) NOT NULL default '', - passwordSalt char(32) NOT NULL default '', - webLoginKey varchar(255) NOT NULL default '', - accountType VARCHAR(32) NOT NULL DEFAULT 'UserAccount', - PRIMARY KEY (`UUID`) -); - -CREATE TABLE tokens ( - UUID char(36) NOT NULL, - token varchar(255) NOT NULL, - validity datetime NOT NULL -); - -COMMIT; diff --git a/OpenSim/Data/SQLiteLegacy/Resources/001_Avatar.sql b/OpenSim/Data/SQLiteLegacy/Resources/001_Avatar.sql deleted file mode 100644 index 7ec906b48a..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/001_Avatar.sql +++ /dev/null @@ -1,9 +0,0 @@ -BEGIN TRANSACTION; - -CREATE TABLE Avatars ( - PrincipalID CHAR(36) NOT NULL, - Name VARCHAR(32) NOT NULL, - Value VARCHAR(255) NOT NULL DEFAULT '', - PRIMARY KEY(PrincipalID, Name)); - -COMMIT; diff --git a/OpenSim/Data/SQLiteLegacy/Resources/001_FriendsStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/001_FriendsStore.sql deleted file mode 100644 index f1b9ab9902..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/001_FriendsStore.sql +++ /dev/null @@ -1,10 +0,0 @@ -BEGIN TRANSACTION; - -CREATE TABLE `Friends` ( - `PrincipalID` CHAR(36) NOT NULL, - `Friend` VARCHAR(255) NOT NULL, - `Flags` VARCHAR(16) NOT NULL DEFAULT 0, - `Offered` VARCHAR(32) NOT NULL DEFAULT 0, - PRIMARY KEY(`PrincipalID`, `Friend`)); - -COMMIT; diff --git a/OpenSim/Data/SQLiteLegacy/Resources/001_InventoryStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/001_InventoryStore.sql deleted file mode 100644 index 554d5c2ec8..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/001_InventoryStore.sql +++ /dev/null @@ -1,32 +0,0 @@ -BEGIN TRANSACTION; - -CREATE TABLE inventoryfolders( - UUID varchar(255) primary key, - name varchar(255), - agentID varchar(255), - parentID varchar(255), - type integer, - version integer); - -CREATE TABLE inventoryitems( - UUID varchar(255) primary key, - assetID varchar(255), - assetType integer, - invType integer, - parentFolderID varchar(255), - avatarID varchar(255), - creatorsID varchar(255), - inventoryName varchar(255), - inventoryDescription varchar(255), - inventoryNextPermissions integer, - inventoryCurrentPermissions integer, - inventoryBasePermissions integer, - inventoryEveryOnePermissions integer, - salePrice integer default 99, - saleType integer default 0, - creationDate integer default 2000, - groupID varchar(255) default '00000000-0000-0000-0000-000000000000', - groupOwned integer default 0, - flags integer default 0); - -COMMIT; diff --git a/OpenSim/Data/SQLiteLegacy/Resources/001_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/001_RegionStore.sql deleted file mode 100644 index 39e8180cdc..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/001_RegionStore.sql +++ /dev/null @@ -1,144 +0,0 @@ -BEGIN TRANSACTION; - -CREATE TABLE prims( - UUID varchar(255) primary key, - RegionUUID varchar(255), - ParentID integer, - CreationDate integer, - Name varchar(255), - SceneGroupID varchar(255), - Text varchar(255), - Description varchar(255), - SitName varchar(255), - TouchName varchar(255), - CreatorID varchar(255), - OwnerID varchar(255), - GroupID varchar(255), - LastOwnerID varchar(255), - OwnerMask integer, - NextOwnerMask integer, - GroupMask integer, - EveryoneMask integer, - BaseMask integer, - PositionX float, - PositionY float, - PositionZ float, - GroupPositionX float, - GroupPositionY float, - GroupPositionZ float, - VelocityX float, - VelocityY float, - VelocityZ float, - AngularVelocityX float, - AngularVelocityY float, - AngularVelocityZ float, - AccelerationX float, - AccelerationY float, - AccelerationZ float, - RotationX float, - RotationY float, - RotationZ float, - RotationW float, - ObjectFlags integer, - SitTargetOffsetX float NOT NULL default 0, - SitTargetOffsetY float NOT NULL default 0, - SitTargetOffsetZ float NOT NULL default 0, - SitTargetOrientW float NOT NULL default 0, - SitTargetOrientX float NOT NULL default 0, - SitTargetOrientY float NOT NULL default 0, - SitTargetOrientZ float NOT NULL default 0); - -CREATE TABLE primshapes( - UUID varchar(255) primary key, - Shape integer, - ScaleX float, - ScaleY float, - ScaleZ float, - PCode integer, - PathBegin integer, - PathEnd integer, - PathScaleX integer, - PathScaleY integer, - PathShearX integer, - PathShearY integer, - PathSkew integer, - PathCurve integer, - PathRadiusOffset integer, - PathRevolutions integer, - PathTaperX integer, - PathTaperY integer, - PathTwist integer, - PathTwistBegin integer, - ProfileBegin integer, - ProfileEnd integer, - ProfileCurve integer, - ProfileHollow integer, - Texture blob, - ExtraParams blob, - State Integer NOT NULL default 0); - -CREATE TABLE primitems( - itemID varchar(255) primary key, - primID varchar(255), - assetID varchar(255), - parentFolderID varchar(255), - invType integer, - assetType integer, - name varchar(255), - description varchar(255), - creationDate integer, - creatorID varchar(255), - ownerID varchar(255), - lastOwnerID varchar(255), - groupID varchar(255), - nextPermissions string, - currentPermissions string, - basePermissions string, - everyonePermissions string, - groupPermissions string); - -CREATE TABLE terrain( - RegionUUID varchar(255), - Revision integer, - Heightfield blob); - -CREATE TABLE land( - UUID varchar(255) primary key, - RegionUUID varchar(255), - LocalLandID string, - Bitmap blob, - Name varchar(255), - Desc varchar(255), - OwnerUUID varchar(255), - IsGroupOwned string, - Area integer, - AuctionID integer, - Category integer, - ClaimDate integer, - ClaimPrice integer, - GroupUUID varchar(255), - SalePrice integer, - LandStatus integer, - LandFlags string, - LandingType string, - MediaAutoScale string, - MediaTextureUUID varchar(255), - MediaURL varchar(255), - MusicURL varchar(255), - PassHours float, - PassPrice string, - SnapshotUUID varchar(255), - UserLocationX float, - UserLocationY float, - UserLocationZ float, - UserLookAtX float, - UserLookAtY float, - UserLookAtZ float, - AuthbuyerID varchar(36) NOT NULL default '00000000-0000-0000-0000-000000000000'); - -CREATE TABLE landaccesslist( - LandUUID varchar(255), - AccessUUID varchar(255), - Flags string); - -COMMIT; diff --git a/OpenSim/Data/SQLiteLegacy/Resources/001_UserAccount.sql b/OpenSim/Data/SQLiteLegacy/Resources/001_UserAccount.sql deleted file mode 100644 index c38d9a762f..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/001_UserAccount.sql +++ /dev/null @@ -1,17 +0,0 @@ -BEGIN TRANSACTION; - --- useraccounts table -CREATE TABLE UserAccounts ( - PrincipalID CHAR(36) primary key, - ScopeID CHAR(36) NOT NULL, - FirstName VARCHAR(64) NOT NULL, - LastName VARCHAR(64) NOT NULL, - Email VARCHAR(64), - ServiceURLs TEXT, - Created INT(11), - UserLevel integer NOT NULL DEFAULT 0, - UserFlags integer NOT NULL DEFAULT 0, - UserTitle varchar(64) NOT NULL DEFAULT '' -); - -COMMIT; \ No newline at end of file diff --git a/OpenSim/Data/SQLiteLegacy/Resources/001_UserStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/001_UserStore.sql deleted file mode 100644 index b584594ced..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/001_UserStore.sql +++ /dev/null @@ -1,39 +0,0 @@ -BEGIN TRANSACTION; - --- users table -CREATE TABLE users( - UUID varchar(255) primary key, - username varchar(255), - surname varchar(255), - passwordHash varchar(255), - passwordSalt varchar(255), - homeRegionX integer, - homeRegionY integer, - homeLocationX float, - homeLocationY float, - homeLocationZ float, - homeLookAtX float, - homeLookAtY float, - homeLookAtZ float, - created integer, - lastLogin integer, - rootInventoryFolderID varchar(255), - userInventoryURI varchar(255), - userAssetURI varchar(255), - profileCanDoMask integer, - profileWantDoMask integer, - profileAboutText varchar(255), - profileFirstText varchar(255), - profileImage varchar(255), - profileFirstImage varchar(255), - webLoginKey text default '00000000-0000-0000-0000-000000000000'); --- friends table -CREATE TABLE userfriends( - ownerID varchar(255), - friendID varchar(255), - friendPerms integer, - ownerPerms integer, - datetimestamp integer); - -COMMIT; - diff --git a/OpenSim/Data/SQLiteLegacy/Resources/002_AssetStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/002_AssetStore.sql deleted file mode 100644 index 5339b84dfd..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/002_AssetStore.sql +++ /dev/null @@ -1,10 +0,0 @@ -BEGIN TRANSACTION; - -CREATE TEMPORARY TABLE assets_backup(UUID,Name,Description,Type,Local,Temporary,Data); -INSERT INTO assets_backup SELECT UUID,Name,Description,Type,Local,Temporary,Data FROM assets; -DROP TABLE assets; -CREATE TABLE assets(UUID,Name,Description,Type,Local,Temporary,Data); -INSERT INTO assets SELECT UUID,Name,Description,Type,Local,Temporary,Data FROM assets_backup; -DROP TABLE assets_backup; - -COMMIT; diff --git a/OpenSim/Data/SQLiteLegacy/Resources/002_AuthStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/002_AuthStore.sql deleted file mode 100644 index 3237b68fd6..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/002_AuthStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN TRANSACTION; - -INSERT INTO auth (UUID, passwordHash, passwordSalt, webLoginKey) SELECT `UUID` AS UUID, `passwordHash` AS passwordHash, `passwordSalt` AS passwordSalt, `webLoginKey` AS webLoginKey FROM users; - -COMMIT; diff --git a/OpenSim/Data/SQLiteLegacy/Resources/002_FriendsStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/002_FriendsStore.sql deleted file mode 100644 index 6733502224..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/002_FriendsStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN TRANSACTION; - -INSERT INTO `Friends` SELECT `ownerID`, `friendID`, `friendPerms`, 0 FROM `userfriends`; - -COMMIT; diff --git a/OpenSim/Data/SQLiteLegacy/Resources/002_InventoryStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/002_InventoryStore.sql deleted file mode 100644 index 01951d6582..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/002_InventoryStore.sql +++ /dev/null @@ -1,8 +0,0 @@ -BEGIN TRANSACTION; - -create index inventoryfolders_agentid on inventoryfolders(agentid); -create index inventoryfolders_parentid on inventoryfolders(parentid); -create index inventoryitems_parentfolderid on inventoryitems(parentfolderid); -create index inventoryitems_avatarid on inventoryitems(avatarid); - -COMMIT; \ No newline at end of file diff --git a/OpenSim/Data/SQLiteLegacy/Resources/002_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/002_RegionStore.sql deleted file mode 100644 index c5c7c99455..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/002_RegionStore.sql +++ /dev/null @@ -1,10 +0,0 @@ -BEGIN TRANSACTION; - -CREATE TABLE regionban( - regionUUID varchar (255), - bannedUUID varchar (255), - bannedIp varchar (255), - bannedIpHostMask varchar (255) - ); - -COMMIT; \ No newline at end of file diff --git a/OpenSim/Data/SQLiteLegacy/Resources/002_UserAccount.sql b/OpenSim/Data/SQLiteLegacy/Resources/002_UserAccount.sql deleted file mode 100644 index c7a62932ac..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/002_UserAccount.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN TRANSACTION; - -INSERT INTO UserAccounts (PrincipalID, ScopeID, FirstName, LastName, Email, ServiceURLs, Created) SELECT `UUID` AS PrincipalID, '00000000-0000-0000-0000-000000000000' AS ScopeID, username AS FirstName, surname AS LastName, '' as Email, '' AS ServiceURLs, created as Created FROM users; - -COMMIT; diff --git a/OpenSim/Data/SQLiteLegacy/Resources/002_UserStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/002_UserStore.sql deleted file mode 100644 index 48fc680b33..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/002_UserStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN; - -ALTER TABLE users add homeRegionID varchar(36) NOT NULL default '00000000-0000-0000-0000-000000000000'; - -COMMIT; diff --git a/OpenSim/Data/SQLiteLegacy/Resources/003_AssetStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/003_AssetStore.sql deleted file mode 100644 index f54f8d98a2..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/003_AssetStore.sql +++ /dev/null @@ -1 +0,0 @@ -DELETE FROM assets WHERE UUID = 'dc4b9f0bd00845c696a401dd947ac621' diff --git a/OpenSim/Data/SQLiteLegacy/Resources/003_InventoryStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/003_InventoryStore.sql deleted file mode 100644 index 4c6da91aab..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/003_InventoryStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN; - -alter table inventoryitems add column inventoryGroupPermissions integer unsigned not null default 0; - -COMMIT; diff --git a/OpenSim/Data/SQLiteLegacy/Resources/003_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/003_RegionStore.sql deleted file mode 100644 index 4db2f7587d..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/003_RegionStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN; - -ALTER TABLE primitems add flags integer not null default 0; - -COMMIT; \ No newline at end of file diff --git a/OpenSim/Data/SQLiteLegacy/Resources/003_UserStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/003_UserStore.sql deleted file mode 100644 index 6f890eeec1..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/003_UserStore.sql +++ /dev/null @@ -1,6 +0,0 @@ -BEGIN; - -ALTER TABLE users add userFlags integer NOT NULL default 0; -ALTER TABLE users add godLevel integer NOT NULL default 0; - -COMMIT; diff --git a/OpenSim/Data/SQLiteLegacy/Resources/004_AssetStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/004_AssetStore.sql deleted file mode 100644 index 39421c4434..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/004_AssetStore.sql +++ /dev/null @@ -1,7 +0,0 @@ -BEGIN; - -update assets - set UUID = substr(UUID, 1, 8) || "-" || substr(UUID, 9, 4) || "-" || substr(UUID, 13, 4) || "-" || substr(UUID, 17, 4) || "-" || substr(UUID, 21, 12) - where UUID not like '%-%'; - -COMMIT; diff --git a/OpenSim/Data/SQLiteLegacy/Resources/004_InventoryStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/004_InventoryStore.sql deleted file mode 100644 index e8f4d46333..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/004_InventoryStore.sql +++ /dev/null @@ -1,36 +0,0 @@ -BEGIN; - -update inventoryitems - set UUID = substr(UUID, 1, 8) || "-" || substr(UUID, 9, 4) || "-" || substr(UUID, 13, 4) || "-" || substr(UUID, 17, 4) || "-" || substr(UUID, 21, 12) - where UUID not like '%-%'; - -update inventoryitems - set assetID = substr(assetID, 1, 8) || "-" || substr(assetID, 9, 4) || "-" || substr(assetID, 13, 4) || "-" || substr(assetID, 17, 4) || "-" || substr(assetID, 21, 12) - where assetID not like '%-%'; - -update inventoryitems - set parentFolderID = substr(parentFolderID, 1, 8) || "-" || substr(parentFolderID, 9, 4) || "-" || substr(parentFolderID, 13, 4) || "-" || substr(parentFolderID, 17, 4) || "-" || substr(parentFolderID, 21, 12) - where parentFolderID not like '%-%'; - -update inventoryitems - set avatarID = substr(avatarID, 1, 8) || "-" || substr(avatarID, 9, 4) || "-" || substr(avatarID, 13, 4) || "-" || substr(avatarID, 17, 4) || "-" || substr(avatarID, 21, 12) - where avatarID not like '%-%'; - -update inventoryitems - set creatorsID = substr(creatorsID, 1, 8) || "-" || substr(creatorsID, 9, 4) || "-" || substr(creatorsID, 13, 4) || "-" || substr(creatorsID, 17, 4) || "-" || substr(creatorsID, 21, 12) - where creatorsID not like '%-%'; - - -update inventoryfolders - set UUID = substr(UUID, 1, 8) || "-" || substr(UUID, 9, 4) || "-" || substr(UUID, 13, 4) || "-" || substr(UUID, 17, 4) || "-" || substr(UUID, 21, 12) - where UUID not like '%-%'; - -update inventoryfolders - set agentID = substr(agentID, 1, 8) || "-" || substr(agentID, 9, 4) || "-" || substr(agentID, 13, 4) || "-" || substr(agentID, 17, 4) || "-" || substr(agentID, 21, 12) - where agentID not like '%-%'; - -update inventoryfolders - set parentID = substr(parentID, 1, 8) || "-" || substr(parentID, 9, 4) || "-" || substr(parentID, 13, 4) || "-" || substr(parentID, 17, 4) || "-" || substr(parentID, 21, 12) - where parentID not like '%-%'; - -COMMIT; diff --git a/OpenSim/Data/SQLiteLegacy/Resources/004_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/004_RegionStore.sql deleted file mode 100644 index de328cb47a..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/004_RegionStore.sql +++ /dev/null @@ -1,38 +0,0 @@ -BEGIN; - -create table regionsettings ( - regionUUID char(36) not null, - block_terraform integer not null, - block_fly integer not null, - allow_damage integer not null, - restrict_pushing integer not null, - allow_land_resell integer not null, - allow_land_join_divide integer not null, - block_show_in_search integer not null, - agent_limit integer not null, - object_bonus float not null, - maturity integer not null, - disable_scripts integer not null, - disable_collisions integer not null, - disable_physics integer not null, - terrain_texture_1 char(36) not null, - terrain_texture_2 char(36) not null, - terrain_texture_3 char(36) not null, - terrain_texture_4 char(36) not null, - elevation_1_nw float not null, - elevation_2_nw float not null, - elevation_1_ne float not null, - elevation_2_ne float not null, - elevation_1_se float not null, - elevation_2_se float not null, - elevation_1_sw float not null, - elevation_2_sw float not null, - water_height float not null, - terrain_raise_limit float not null, - terrain_lower_limit float not null, - use_estate_sun integer not null, - fixed_sun integer not null, - sun_position float not null, - covenant char(36)); - -COMMIT; diff --git a/OpenSim/Data/SQLiteLegacy/Resources/004_UserStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/004_UserStore.sql deleted file mode 100644 index 03142afa37..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/004_UserStore.sql +++ /dev/null @@ -1,6 +0,0 @@ -BEGIN; - -ALTER TABLE users add customType varchar(32) not null default ''; -ALTER TABLE users add partner char(36) not null default '00000000-0000-0000-0000-000000000000'; - -COMMIT; diff --git a/OpenSim/Data/SQLiteLegacy/Resources/005_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/005_RegionStore.sql deleted file mode 100644 index 1f6d1bd271..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/005_RegionStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN; - -delete from regionsettings; - -COMMIT; diff --git a/OpenSim/Data/SQLiteLegacy/Resources/005_UserStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/005_UserStore.sql deleted file mode 100644 index e45c09a493..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/005_UserStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN; - -CREATE TABLE `avatarattachments` (`UUID` char(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000', `attachpoint` int(11) NOT NULL DEFAULT 0, `item` char(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000', `asset` char(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000'); - -COMMIT; diff --git a/OpenSim/Data/SQLiteLegacy/Resources/006_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/006_RegionStore.sql deleted file mode 100644 index 94ed8181cd..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/006_RegionStore.sql +++ /dev/null @@ -1,102 +0,0 @@ -BEGIN TRANSACTION; - -CREATE TABLE estate_groups ( - EstateID int(10) NOT NULL, - uuid char(36) NOT NULL -); - -CREATE TABLE estate_managers ( - EstateID int(10) NOT NULL, - uuid char(36) NOT NULL -); - -CREATE TABLE estate_map ( - RegionID char(36) NOT NULL default '00000000-0000-0000-0000-000000000000', - EstateID int(11) NOT NULL -); - -CREATE TABLE estate_settings ( - EstateID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, - EstateName varchar(64) default NULL, - AbuseEmailToEstateOwner tinyint(4) NOT NULL, - DenyAnonymous tinyint(4) NOT NULL, - ResetHomeOnTeleport tinyint(4) NOT NULL, - FixedSun tinyint(4) NOT NULL, - DenyTransacted tinyint(4) NOT NULL, - BlockDwell tinyint(4) NOT NULL, - DenyIdentified tinyint(4) NOT NULL, - AllowVoice tinyint(4) NOT NULL, - UseGlobalTime tinyint(4) NOT NULL, - PricePerMeter int(11) NOT NULL, - TaxFree tinyint(4) NOT NULL, - AllowDirectTeleport tinyint(4) NOT NULL, - RedirectGridX int(11) NOT NULL, - RedirectGridY int(11) NOT NULL, - ParentEstateID int(10) NOT NULL, - SunPosition double NOT NULL, - EstateSkipScripts tinyint(4) NOT NULL, - BillableFactor float NOT NULL, - PublicAccess tinyint(4) NOT NULL -); -insert into estate_settings (EstateID,EstateName,AbuseEmailToEstateOwner,DenyAnonymous,ResetHomeOnTeleport,FixedSun,DenyTransacted,BlockDwell,DenyIdentified,AllowVoice,UseGlobalTime,PricePerMeter,TaxFree,AllowDirectTeleport,RedirectGridX,RedirectGridY,ParentEstateID,SunPosition,PublicAccess,EstateSkipScripts,BillableFactor) values ( 99, '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''); -delete from estate_settings; -CREATE TABLE estate_users ( - EstateID int(10) NOT NULL, - uuid char(36) NOT NULL -); - -CREATE TABLE estateban ( - EstateID int(10) NOT NULL, - bannedUUID varchar(36) NOT NULL, - bannedIp varchar(16) NOT NULL, - bannedIpHostMask varchar(16) NOT NULL, - bannedNameMask varchar(64) default NULL -); - -drop table regionsettings; -CREATE TABLE regionsettings ( - regionUUID char(36) NOT NULL, - block_terraform int(11) NOT NULL, - block_fly int(11) NOT NULL, - allow_damage int(11) NOT NULL, - restrict_pushing int(11) NOT NULL, - allow_land_resell int(11) NOT NULL, - allow_land_join_divide int(11) NOT NULL, - block_show_in_search int(11) NOT NULL, - agent_limit int(11) NOT NULL, - object_bonus float NOT NULL, - maturity int(11) NOT NULL, - disable_scripts int(11) NOT NULL, - disable_collisions int(11) NOT NULL, - disable_physics int(11) NOT NULL, - terrain_texture_1 char(36) NOT NULL, - terrain_texture_2 char(36) NOT NULL, - terrain_texture_3 char(36) NOT NULL, - terrain_texture_4 char(36) NOT NULL, - elevation_1_nw float NOT NULL, - elevation_2_nw float NOT NULL, - elevation_1_ne float NOT NULL, - elevation_2_ne float NOT NULL, - elevation_1_se float NOT NULL, - elevation_2_se float NOT NULL, - elevation_1_sw float NOT NULL, - elevation_2_sw float NOT NULL, - water_height float NOT NULL, - terrain_raise_limit float NOT NULL, - terrain_lower_limit float NOT NULL, - use_estate_sun int(11) NOT NULL, - fixed_sun int(11) NOT NULL, - sun_position float NOT NULL, - covenant char(36) default NULL, - Sandbox tinyint(4) NOT NULL, - PRIMARY KEY (regionUUID) -); - -CREATE INDEX estate_ban_estate_id on estateban(EstateID); -CREATE INDEX estate_groups_estate_id on estate_groups(EstateID); -CREATE INDEX estate_managers_estate_id on estate_managers(EstateID); -CREATE INDEX estate_map_estate_id on estate_map(EstateID); -CREATE UNIQUE INDEX estate_map_region_id on estate_map(RegionID); -CREATE INDEX estate_users_estate_id on estate_users(EstateID); - -COMMIT; \ No newline at end of file diff --git a/OpenSim/Data/SQLiteLegacy/Resources/006_UserStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/006_UserStore.sql deleted file mode 100644 index f9454c55cf..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/006_UserStore.sql +++ /dev/null @@ -1,20 +0,0 @@ -BEGIN TRANSACTION; - --- usersagents table -CREATE TABLE IF NOT EXISTS useragents( - UUID varchar(255) primary key, - agentIP varchar(255), - agentPort integer, - agentOnline boolean, - sessionID varchar(255), - secureSessionID varchar(255), - regionID varchar(255), - loginTime integer, - logoutTime integer, - currentRegion varchar(255), - currentHandle varchar(255), - currentPosX float, - currentPosY float, - currentPosZ float); - -COMMIT; diff --git a/OpenSim/Data/SQLiteLegacy/Resources/007_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/007_RegionStore.sql deleted file mode 100644 index 1c813a0d40..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/007_RegionStore.sql +++ /dev/null @@ -1,8 +0,0 @@ -begin; - -alter table estate_settings add column AbuseEmail varchar(255) not null default ''; - -alter table estate_settings add column EstateOwner varchar(36) not null default ''; - -commit; - diff --git a/OpenSim/Data/SQLiteLegacy/Resources/007_UserStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/007_UserStore.sql deleted file mode 100644 index 8b0cd285c7..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/007_UserStore.sql +++ /dev/null @@ -1,7 +0,0 @@ -BEGIN TRANSACTION; - -ALTER TABLE useragents add currentLookAtX float not null default 128; -ALTER TABLE useragents add currentLookAtY float not null default 128; -ALTER TABLE useragents add currentLookAtZ float not null default 70; - -COMMIT; diff --git a/OpenSim/Data/SQLiteLegacy/Resources/008_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/008_RegionStore.sql deleted file mode 100644 index 28bfbf59c3..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/008_RegionStore.sql +++ /dev/null @@ -1,6 +0,0 @@ -begin; - -alter table estate_settings add column DenyMinors tinyint not null default 0; - -commit; - diff --git a/OpenSim/Data/SQLiteLegacy/Resources/008_UserStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/008_UserStore.sql deleted file mode 100644 index 97da81848c..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/008_UserStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN TRANSACTION; - -ALTER TABLE users add email varchar(250); - -COMMIT; diff --git a/OpenSim/Data/SQLiteLegacy/Resources/009_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/009_RegionStore.sql deleted file mode 100644 index 1f40548f36..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/009_RegionStore.sql +++ /dev/null @@ -1,8 +0,0 @@ -BEGIN; - -ALTER TABLE prims ADD COLUMN ColorR integer not null default 0; -ALTER TABLE prims ADD COLUMN ColorG integer not null default 0; -ALTER TABLE prims ADD COLUMN ColorB integer not null default 0; -ALTER TABLE prims ADD COLUMN ColorA integer not null default 0; - -COMMIT; diff --git a/OpenSim/Data/SQLiteLegacy/Resources/009_UserStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/009_UserStore.sql deleted file mode 100644 index 8ab03ef897..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/009_UserStore.sql +++ /dev/null @@ -1,11 +0,0 @@ -BEGIN; - -update users - set UUID = substr(UUID, 1, 8) || "-" || substr(UUID, 9, 4) || "-" || substr(UUID, 13, 4) || "-" || substr(UUID, 17, 4) || "-" || substr(UUID, 21, 12) - where UUID not like '%-%'; - -update useragents - set UUID = substr(UUID, 1, 8) || "-" || substr(UUID, 9, 4) || "-" || substr(UUID, 13, 4) || "-" || substr(UUID, 17, 4) || "-" || substr(UUID, 21, 12) - where UUID not like '%-%'; - -COMMIT; diff --git a/OpenSim/Data/SQLiteLegacy/Resources/010_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/010_RegionStore.sql deleted file mode 100644 index b91ccf0a8d..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/010_RegionStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN; - -ALTER TABLE prims ADD COLUMN ClickAction INTEGER NOT NULL default 0; - -COMMIT; diff --git a/OpenSim/Data/SQLiteLegacy/Resources/010_UserStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/010_UserStore.sql deleted file mode 100644 index 5f956dadfd..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/010_UserStore.sql +++ /dev/null @@ -1,37 +0,0 @@ -BEGIN TRANSACTION; - -CREATE TABLE IF NOT EXISTS avatarappearance( - Owner varchar(36) NOT NULL primary key, - BodyItem varchar(36) DEFAULT NULL, - BodyAsset varchar(36) DEFAULT NULL, - SkinItem varchar(36) DEFAULT NULL, - SkinAsset varchar(36) DEFAULT NULL, - HairItem varchar(36) DEFAULT NULL, - HairAsset varchar(36) DEFAULT NULL, - EyesItem varchar(36) DEFAULT NULL, - EyesAsset varchar(36) DEFAULT NULL, - ShirtItem varchar(36) DEFAULT NULL, - ShirtAsset varchar(36) DEFAULT NULL, - PantsItem varchar(36) DEFAULT NULL, - PantsAsset varchar(36) DEFAULT NULL, - ShoesItem varchar(36) DEFAULT NULL, - ShoesAsset varchar(36) DEFAULT NULL, - SocksItem varchar(36) DEFAULT NULL, - SocksAsset varchar(36) DEFAULT NULL, - JacketItem varchar(36) DEFAULT NULL, - JacketAsset varchar(36) DEFAULT NULL, - GlovesItem varchar(36) DEFAULT NULL, - GlovesAsset varchar(36) DEFAULT NULL, - UnderShirtItem varchar(36) DEFAULT NULL, - UnderShirtAsset varchar(36) DEFAULT NULL, - UnderPantsItem varchar(36) DEFAULT NULL, - UnderPantsAsset varchar(36) DEFAULT NULL, - SkirtItem varchar(36) DEFAULT NULL, - SkirtAsset varchar(36) DEFAULT NULL, - Texture blob, - VisualParams blob, - Serial int DEFAULT NULL, - AvatarHeight float DEFAULT NULL -); - -COMMIT; diff --git a/OpenSim/Data/SQLiteLegacy/Resources/011_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/011_RegionStore.sql deleted file mode 100644 index 42bef89616..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/011_RegionStore.sql +++ /dev/null @@ -1,28 +0,0 @@ -BEGIN; - -ALTER TABLE prims ADD COLUMN PayPrice INTEGER NOT NULL default 0; -ALTER TABLE prims ADD COLUMN PayButton1 INTEGER NOT NULL default 0; -ALTER TABLE prims ADD COLUMN PayButton2 INTEGER NOT NULL default 0; -ALTER TABLE prims ADD COLUMN PayButton3 INTEGER NOT NULL default 0; -ALTER TABLE prims ADD COLUMN PayButton4 INTEGER NOT NULL default 0; -ALTER TABLE prims ADD COLUMN LoopedSound varchar(36) NOT NULL default '00000000-0000-0000-0000-000000000000'; -ALTER TABLE prims ADD COLUMN LoopedSoundGain float NOT NULL default 0; -ALTER TABLE prims ADD COLUMN TextureAnimation string; -ALTER TABLE prims ADD COLUMN ParticleSystem string; -ALTER TABLE prims ADD COLUMN OmegaX float NOT NULL default 0; -ALTER TABLE prims ADD COLUMN OmegaY float NOT NULL default 0; -ALTER TABLE prims ADD COLUMN OmegaZ float NOT NULL default 0; -ALTER TABLE prims ADD COLUMN CameraEyeOffsetX float NOT NULL default 0; -ALTER TABLE prims ADD COLUMN CameraEyeOffsetY float NOT NULL default 0; -ALTER TABLE prims ADD COLUMN CameraEyeOffsetZ float NOT NULL default 0; -ALTER TABLE prims ADD COLUMN CameraAtOffsetX float NOT NULL default 0; -ALTER TABLE prims ADD COLUMN CameraAtOffsetY float NOT NULL default 0; -ALTER TABLE prims ADD COLUMN CameraAtOffsetZ float NOT NULL default 0; -ALTER TABLE prims ADD COLUMN ForceMouselook string NOT NULL default 0; -ALTER TABLE prims ADD COLUMN ScriptAccessPin INTEGER NOT NULL default 0; -ALTER TABLE prims ADD COLUMN AllowedDrop INTEGER NOT NULL default 0; -ALTER TABLE prims ADD COLUMN DieAtEdge string NOT NULL default 0; -ALTER TABLE prims ADD COLUMN SalePrice INTEGER NOT NULL default 0; -ALTER TABLE prims ADD COLUMN SaleType string NOT NULL default 0; - -COMMIT; \ No newline at end of file diff --git a/OpenSim/Data/SQLiteLegacy/Resources/012_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/012_RegionStore.sql deleted file mode 100644 index d952b78bd2..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/012_RegionStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN; - -ALTER TABLE prims ADD COLUMN Material INTEGER NOT NULL default 3; - -COMMIT; diff --git a/OpenSim/Data/SQLiteLegacy/Resources/013_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/013_RegionStore.sql deleted file mode 100644 index 11529cd3f1..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/013_RegionStore.sql +++ /dev/null @@ -1,6 +0,0 @@ -BEGIN; - -ALTER TABLE land ADD COLUMN OtherCleanTime INTEGER NOT NULL default 0; -ALTER TABLE land ADD COLUMN Dwell INTEGER NOT NULL default 0; - -COMMIT; diff --git a/OpenSim/Data/SQLiteLegacy/Resources/014_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/014_RegionStore.sql deleted file mode 100644 index c59b27e745..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/014_RegionStore.sql +++ /dev/null @@ -1,8 +0,0 @@ -begin; - -ALTER TABLE regionsettings ADD COLUMN sunvectorx double NOT NULL default 0; -ALTER TABLE regionsettings ADD COLUMN sunvectory double NOT NULL default 0; -ALTER TABLE regionsettings ADD COLUMN sunvectorz double NOT NULL default 0; - -commit; - diff --git a/OpenSim/Data/SQLiteLegacy/Resources/015_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/015_RegionStore.sql deleted file mode 100644 index c43f356be3..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/015_RegionStore.sql +++ /dev/null @@ -1,6 +0,0 @@ -BEGIN; - -ALTER TABLE prims ADD COLUMN CollisionSound varchar(36) NOT NULL default '00000000-0000-0000-0000-000000000000'; -ALTER TABLE prims ADD COLUMN CollisionSoundVolume float NOT NULL default 0; - -COMMIT; diff --git a/OpenSim/Data/SQLiteLegacy/Resources/016_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/016_RegionStore.sql deleted file mode 100644 index 52f160cdbc..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/016_RegionStore.sql +++ /dev/null @@ -1,5 +0,0 @@ -BEGIN; - -ALTER TABLE prims ADD COLUMN VolumeDetect INTEGER NOT NULL DEFAULT 0; - -COMMIT; diff --git a/OpenSim/Data/SQLiteLegacy/Resources/017_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/017_RegionStore.sql deleted file mode 100644 index 6c6b7b5d40..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/017_RegionStore.sql +++ /dev/null @@ -1,8 +0,0 @@ -BEGIN; -CREATE TEMPORARY TABLE prims_backup(UUID,RegionUUID,CreationDate,Name,SceneGroupID,Text,Description,SitName,TouchName,CreatorID,OwnerID,GroupID,LastOwnerID,OwnerMask,NextOwnerMask,GroupMask,EveryoneMask,BaseMask,PositionX,PositionY,PositionZ,GroupPositionX,GroupPositionY,GroupPositionZ,VelocityX,VelocityY,VelocityZ,AngularVelocityX,AngularVelocityY,AngularVelocityZ,AccelerationX,AccelerationY,AccelerationZ,RotationX,RotationY,RotationZ,RotationW,ObjectFlags,SitTargetOffsetX,SitTargetOffsetY,SitTargetOffsetZ,SitTargetOrientW,SitTargetOrientX,SitTargetOrientY,SitTargetOrientZ,ColorR,ColorG,ColorB,ColorA,ClickAction,PayPrice,PayButton1,PayButton2,PayButton3,PayButton4,LoopedSound,LoopedSoundGain,TextureAnimation,ParticleSystem,OmegaX,OmegaY,OmegaZ,CameraEyeOffsetX,CameraEyeOffsetY,CameraEyeOffsetZ,CameraAtOffsetX,CameraAtOffsetY,CameraAtOffsetZ,ForceMouselook,ScriptAccessPin,AllowedDrop,DieAtEdge,SalePrice,SaleType,Material,CollisionSound,CollisionSoundVolume,VolumeDetect); -INSERT INTO prims_backup SELECT UUID,RegionUUID,CreationDate,Name,SceneGroupID,Text,Description,SitName,TouchName,CreatorID,OwnerID,GroupID,LastOwnerID,OwnerMask,NextOwnerMask,GroupMask,EveryoneMask,BaseMask,PositionX,PositionY,PositionZ,GroupPositionX,GroupPositionY,GroupPositionZ,VelocityX,VelocityY,VelocityZ,AngularVelocityX,AngularVelocityY,AngularVelocityZ,AccelerationX,AccelerationY,AccelerationZ,RotationX,RotationY,RotationZ,RotationW,ObjectFlags,SitTargetOffsetX,SitTargetOffsetY,SitTargetOffsetZ,SitTargetOrientW,SitTargetOrientX,SitTargetOrientY,SitTargetOrientZ,ColorR,ColorG,ColorB,ColorA,ClickAction,PayPrice,PayButton1,PayButton2,PayButton3,PayButton4,LoopedSound,LoopedSoundGain,TextureAnimation,ParticleSystem,OmegaX,OmegaY,OmegaZ,CameraEyeOffsetX,CameraEyeOffsetY,CameraEyeOffsetZ,CameraAtOffsetX,CameraAtOffsetY,CameraAtOffsetZ,ForceMouselook,ScriptAccessPin,AllowedDrop,DieAtEdge,SalePrice,SaleType,Material,CollisionSound,CollisionSoundVolume,VolumeDetect FROM prims; -DROP TABLE prims; -CREATE TABLE prims(UUID,RegionUUID,CreationDate,Name,SceneGroupID,Text,Description,SitName,TouchName,CreatorID,OwnerID,GroupID,LastOwnerID,OwnerMask,NextOwnerMask,GroupMask,EveryoneMask,BaseMask,PositionX,PositionY,PositionZ,GroupPositionX,GroupPositionY,GroupPositionZ,VelocityX,VelocityY,VelocityZ,AngularVelocityX,AngularVelocityY,AngularVelocityZ,AccelerationX,AccelerationY,AccelerationZ,RotationX,RotationY,RotationZ,RotationW,ObjectFlags,SitTargetOffsetX,SitTargetOffsetY,SitTargetOffsetZ,SitTargetOrientW,SitTargetOrientX,SitTargetOrientY,SitTargetOrientZ,ColorR,ColorG,ColorB,ColorA,ClickAction,PayPrice,PayButton1,PayButton2,PayButton3,PayButton4,LoopedSound,LoopedSoundGain,TextureAnimation,ParticleSystem,OmegaX,OmegaY,OmegaZ,CameraEyeOffsetX,CameraEyeOffsetY,CameraEyeOffsetZ,CameraAtOffsetX,CameraAtOffsetY,CameraAtOffsetZ,ForceMouselook,ScriptAccessPin,AllowedDrop,DieAtEdge,SalePrice,SaleType,Material,CollisionSound,CollisionSoundVolume,VolumeDetect); -INSERT INTO prims SELECT UUID,RegionUUID,CreationDate,Name,SceneGroupID,Text,Description,SitName,TouchName,CreatorID,OwnerID,GroupID,LastOwnerID,OwnerMask,NextOwnerMask,GroupMask,EveryoneMask,BaseMask,PositionX,PositionY,PositionZ,GroupPositionX,GroupPositionY,GroupPositionZ,VelocityX,VelocityY,VelocityZ,AngularVelocityX,AngularVelocityY,AngularVelocityZ,AccelerationX,AccelerationY,AccelerationZ,RotationX,RotationY,RotationZ,RotationW,ObjectFlags,SitTargetOffsetX,SitTargetOffsetY,SitTargetOffsetZ,SitTargetOrientW,SitTargetOrientX,SitTargetOrientY,SitTargetOrientZ,ColorR,ColorG,ColorB,ColorA,ClickAction,PayPrice,PayButton1,PayButton2,PayButton3,PayButton4,LoopedSound,LoopedSoundGain,TextureAnimation,ParticleSystem,OmegaX,OmegaY,OmegaZ,CameraEyeOffsetX,CameraEyeOffsetY,CameraEyeOffsetZ,CameraAtOffsetX,CameraAtOffsetY,CameraAtOffsetZ,ForceMouselook,ScriptAccessPin,AllowedDrop,DieAtEdge,SalePrice,SaleType,Material,CollisionSound,CollisionSoundVolume,VolumeDetect FROM prims_backup; -DROP TABLE prims_backup; -COMMIT; \ No newline at end of file diff --git a/OpenSim/Data/SQLiteLegacy/Resources/018_RegionStore.sql b/OpenSim/Data/SQLiteLegacy/Resources/018_RegionStore.sql deleted file mode 100644 index 6a390c2161..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/018_RegionStore.sql +++ /dev/null @@ -1,79 +0,0 @@ -BEGIN; - -update terrain - set RegionUUID = substr(RegionUUID, 1, 8) || "-" || substr(RegionUUID, 9, 4) || "-" || substr(RegionUUID, 13, 4) || "-" || substr(RegionUUID, 17, 4) || "-" || substr(RegionUUID, 21, 12) - where RegionUUID not like '%-%'; - - -update landaccesslist - set LandUUID = substr(LandUUID, 1, 8) || "-" || substr(LandUUID, 9, 4) || "-" || substr(LandUUID, 13, 4) || "-" || substr(LandUUID, 17, 4) || "-" || substr(LandUUID, 21, 12) - where LandUUID not like '%-%'; - -update landaccesslist - set AccessUUID = substr(AccessUUID, 1, 8) || "-" || substr(AccessUUID, 9, 4) || "-" || substr(AccessUUID, 13, 4) || "-" || substr(AccessUUID, 17, 4) || "-" || substr(AccessUUID, 21, 12) - where AccessUUID not like '%-%'; - - -update prims - set UUID = substr(UUID, 1, 8) || "-" || substr(UUID, 9, 4) || "-" || substr(UUID, 13, 4) || "-" || substr(UUID, 17, 4) || "-" || substr(UUID, 21, 12) - where UUID not like '%-%'; - -update prims - set RegionUUID = substr(RegionUUID, 1, 8) || "-" || substr(RegionUUID, 9, 4) || "-" || substr(RegionUUID, 13, 4) || "-" || substr(RegionUUID, 17, 4) || "-" || substr(RegionUUID, 21, 12) - where RegionUUID not like '%-%'; - -update prims - set SceneGroupID = substr(SceneGroupID, 1, 8) || "-" || substr(SceneGroupID, 9, 4) || "-" || substr(SceneGroupID, 13, 4) || "-" || substr(SceneGroupID, 17, 4) || "-" || substr(SceneGroupID, 21, 12) - where SceneGroupID not like '%-%'; - -update prims - set CreatorID = substr(CreatorID, 1, 8) || "-" || substr(CreatorID, 9, 4) || "-" || substr(CreatorID, 13, 4) || "-" || substr(CreatorID, 17, 4) || "-" || substr(CreatorID, 21, 12) - where CreatorID not like '%-%'; - -update prims - set OwnerID = substr(OwnerID, 1, 8) || "-" || substr(OwnerID, 9, 4) || "-" || substr(OwnerID, 13, 4) || "-" || substr(OwnerID, 17, 4) || "-" || substr(OwnerID, 21, 12) - where OwnerID not like '%-%'; - -update prims - set GroupID = substr(GroupID, 1, 8) || "-" || substr(GroupID, 9, 4) || "-" || substr(GroupID, 13, 4) || "-" || substr(GroupID, 17, 4) || "-" || substr(GroupID, 21, 12) - where GroupID not like '%-%'; - -update prims - set LastOwnerID = substr(LastOwnerID, 1, 8) || "-" || substr(LastOwnerID, 9, 4) || "-" || substr(LastOwnerID, 13, 4) || "-" || substr(LastOwnerID, 17, 4) || "-" || substr(LastOwnerID, 21, 12) - where LastOwnerID not like '%-%'; - - -update primshapes - set UUID = substr(UUID, 1, 8) || "-" || substr(UUID, 9, 4) || "-" || substr(UUID, 13, 4) || "-" || substr(UUID, 17, 4) || "-" || substr(UUID, 21, 12) - where UUID not like '%-%'; - - -update land - set UUID = substr(UUID, 1, 8) || "-" || substr(UUID, 9, 4) || "-" || substr(UUID, 13, 4) || "-" || substr(UUID, 17, 4) || "-" || substr(UUID, 21, 12) - where UUID not like '%-%'; - -update land - set RegionUUID = substr(RegionUUID, 1, 8) || "-" || substr(RegionUUID, 9, 4) || "-" || substr(RegionUUID, 13, 4) || "-" || substr(RegionUUID, 17, 4) || "-" || substr(RegionUUID, 21, 12) - where RegionUUID not like '%-%'; - -update land - set OwnerUUID = substr(OwnerUUID, 1, 8) || "-" || substr(OwnerUUID, 9, 4) || "-" || substr(OwnerUUID, 13, 4) || "-" || substr(OwnerUUID, 17, 4) || "-" || substr(OwnerUUID, 21, 12) - where OwnerUUID not like '%-%'; - -update land - set GroupUUID = substr(GroupUUID, 1, 8) || "-" || substr(GroupUUID, 9, 4) || "-" || substr(GroupUUID, 13, 4) || "-" || substr(GroupUUID, 17, 4) || "-" || substr(GroupUUID, 21, 12) - where GroupUUID not like '%-%'; - -update land - set MediaTextureUUID = substr(MediaTextureUUID, 1, 8) || "-" || substr(MediaTextureUUID, 9, 4) || "-" || substr(MediaTextureUUID, 13, 4) || "-" || substr(MediaTextureUUID, 17, 4) || "-" || substr(MediaTextureUUID, 21, 12) - where MediaTextureUUID not like '%-%'; - -update land - set SnapshotUUID = substr(SnapshotUUID, 1, 8) || "-" || substr(SnapshotUUID, 9, 4) || "-" || substr(SnapshotUUID, 13, 4) || "-" || substr(SnapshotUUID, 17, 4) || "-" || substr(SnapshotUUID, 21, 12) - where SnapshotUUID not like '%-%'; - -update land - set AuthbuyerID = substr(AuthbuyerID, 1, 8) || "-" || substr(AuthbuyerID, 9, 4) || "-" || substr(AuthbuyerID, 13, 4) || "-" || substr(AuthbuyerID, 17, 4) || "-" || substr(AuthbuyerID, 21, 12) - where AuthbuyerID not like '%-%'; - -COMMIT; \ No newline at end of file diff --git a/OpenSim/Data/SQLiteLegacy/Resources/OpenSim.Data.SQLite.addin.xml b/OpenSim/Data/SQLiteLegacy/Resources/OpenSim.Data.SQLite.addin.xml deleted file mode 100644 index e6764facbd..0000000000 --- a/OpenSim/Data/SQLiteLegacy/Resources/OpenSim.Data.SQLite.addin.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/OpenSim/Data/SQLiteLegacy/SQLiteAssetData.cs b/OpenSim/Data/SQLiteLegacy/SQLiteAssetData.cs deleted file mode 100644 index df509023eb..0000000000 --- a/OpenSim/Data/SQLiteLegacy/SQLiteAssetData.cs +++ /dev/null @@ -1,347 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Data; -using System.Reflection; -using System.Collections.Generic; -using log4net; -using Mono.Data.SqliteClient; -using OpenMetaverse; -using OpenSim.Framework; - -namespace OpenSim.Data.SQLiteLegacy -{ - /// - /// An asset storage interface for the SQLite database system - /// - public class SQLiteAssetData : AssetDataBase - { -// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private const string SelectAssetSQL = "select * from assets where UUID=:UUID"; - private const string SelectAssetMetadataSQL = "select Name, Description, Type, Temporary, UUID from assets limit :start, :count"; - private const string DeleteAssetSQL = "delete from assets where UUID=:UUID"; - private const string InsertAssetSQL = "insert into assets(UUID, Name, Description, Type, Local, Temporary, Data) values(:UUID, :Name, :Description, :Type, :Local, :Temporary, :Data)"; - private const string UpdateAssetSQL = "update assets set Name=:Name, Description=:Description, Type=:Type, Local=:Local, Temporary=:Temporary, Data=:Data where UUID=:UUID"; - private const string assetSelect = "select * from assets"; - - private SqliteConnection m_conn; - - override public void Dispose() - { - if (m_conn != null) - { - m_conn.Close(); - m_conn = null; - } - } - - /// - /// - /// Initialises AssetData interface - /// Loads and initialises a new SQLite connection and maintains it. - /// use default URI if connect string is empty. - /// - /// - /// connect string - override public void Initialise(string dbconnect) - { - if (dbconnect == string.Empty) - { - dbconnect = "URI=file:Asset.db,version=3"; - } - m_conn = new SqliteConnection(dbconnect); - m_conn.Open(); - - Assembly assem = GetType().Assembly; - Migration m = new Migration(m_conn, assem, "AssetStore"); - m.Update(); - - return; - } - - /// - /// Fetch Asset - /// - /// UUID of ... ? - /// Asset base - override public AssetBase GetAsset(UUID uuid) - { - lock (this) - { - using (SqliteCommand cmd = new SqliteCommand(SelectAssetSQL, m_conn)) - { - cmd.Parameters.Add(new SqliteParameter(":UUID", uuid.ToString())); - using (IDataReader reader = cmd.ExecuteReader()) - { - if (reader.Read()) - { - AssetBase asset = buildAsset(reader); - reader.Close(); - return asset; - } - else - { - reader.Close(); - return null; - } - } - } - } - } - - /// - /// Create an asset - /// - /// Asset Base - override public void StoreAsset(AssetBase asset) - { - //m_log.Info("[ASSET DB]: Creating Asset " + asset.FullID.ToString()); - if (ExistsAsset(asset.FullID)) - { - //LogAssetLoad(asset); - - lock (this) - { - using (SqliteCommand cmd = new SqliteCommand(UpdateAssetSQL, m_conn)) - { - cmd.Parameters.Add(new SqliteParameter(":UUID", asset.FullID.ToString())); - cmd.Parameters.Add(new SqliteParameter(":Name", asset.Name)); - cmd.Parameters.Add(new SqliteParameter(":Description", asset.Description)); - cmd.Parameters.Add(new SqliteParameter(":Type", asset.Type)); - cmd.Parameters.Add(new SqliteParameter(":Local", asset.Local)); - cmd.Parameters.Add(new SqliteParameter(":Temporary", asset.Temporary)); - cmd.Parameters.Add(new SqliteParameter(":Data", asset.Data)); - - cmd.ExecuteNonQuery(); - } - } - } - else - { - lock (this) - { - using (SqliteCommand cmd = new SqliteCommand(InsertAssetSQL, m_conn)) - { - cmd.Parameters.Add(new SqliteParameter(":UUID", asset.FullID.ToString())); - cmd.Parameters.Add(new SqliteParameter(":Name", asset.Name)); - cmd.Parameters.Add(new SqliteParameter(":Description", asset.Description)); - cmd.Parameters.Add(new SqliteParameter(":Type", asset.Type)); - cmd.Parameters.Add(new SqliteParameter(":Local", asset.Local)); - cmd.Parameters.Add(new SqliteParameter(":Temporary", asset.Temporary)); - cmd.Parameters.Add(new SqliteParameter(":Data", asset.Data)); - - cmd.ExecuteNonQuery(); - } - } - } - } - -// /// -// /// Some... logging functionnality -// /// -// /// -// private static void LogAssetLoad(AssetBase asset) -// { -// string temporary = asset.Temporary ? "Temporary" : "Stored"; -// string local = asset.Local ? "Local" : "Remote"; -// -// int assetLength = (asset.Data != null) ? asset.Data.Length : 0; -// -// m_log.Debug("[ASSET DB]: " + -// string.Format("Loaded {5} {4} Asset: [{0}][{3}] \"{1}\":{2} ({6} bytes)", -// asset.FullID, asset.Name, asset.Description, asset.Type, -// temporary, local, assetLength)); -// } - - /// - /// Check if an asset exist in database - /// - /// The asset UUID - /// True if exist, or false. - override public bool ExistsAsset(UUID uuid) - { - lock (this) { - using (SqliteCommand cmd = new SqliteCommand(SelectAssetSQL, m_conn)) - { - cmd.Parameters.Add(new SqliteParameter(":UUID", uuid.ToString())); - using (IDataReader reader = cmd.ExecuteReader()) - { - if (reader.Read()) - { - reader.Close(); - return true; - } - else - { - reader.Close(); - return false; - } - } - } - } - } - - /// - /// Delete an asset from database - /// - /// - public void DeleteAsset(UUID uuid) - { - using (SqliteCommand cmd = new SqliteCommand(DeleteAssetSQL, m_conn)) - { - cmd.Parameters.Add(new SqliteParameter(":UUID", uuid.ToString())); - - cmd.ExecuteNonQuery(); - } - } - - /// - /// - /// - /// - /// - private static AssetBase buildAsset(IDataReader row) - { - // TODO: this doesn't work yet because something more - // interesting has to be done to actually get these values - // back out. Not enough time to figure it out yet. - AssetBase asset = new AssetBase( - new UUID((String)row["UUID"]), - (String)row["Name"], - Convert.ToSByte(row["Type"]), - UUID.Zero.ToString() - ); - - asset.Description = (String) row["Description"]; - asset.Local = Convert.ToBoolean(row["Local"]); - asset.Temporary = Convert.ToBoolean(row["Temporary"]); - asset.Data = (byte[]) row["Data"]; - return asset; - } - - private static AssetMetadata buildAssetMetadata(IDataReader row) - { - AssetMetadata metadata = new AssetMetadata(); - - metadata.FullID = new UUID((string) row["UUID"]); - metadata.Name = (string) row["Name"]; - metadata.Description = (string) row["Description"]; - metadata.Type = Convert.ToSByte(row["Type"]); - metadata.Temporary = Convert.ToBoolean(row["Temporary"]); // Not sure if this is correct. - - // Current SHA1s are not stored/computed. - metadata.SHA1 = new byte[] {}; - - return metadata; - } - - /// - /// Returns a list of AssetMetadata objects. The list is a subset of - /// the entire data set offset by containing - /// elements. - /// - /// The number of results to discard from the total data set. - /// The number of rows the returned list should contain. - /// A list of AssetMetadata objects. - public override List FetchAssetMetadataSet(int start, int count) - { - List retList = new List(count); - - lock (this) - { - using (SqliteCommand cmd = new SqliteCommand(SelectAssetMetadataSQL, m_conn)) - { - cmd.Parameters.Add(new SqliteParameter(":start", start)); - cmd.Parameters.Add(new SqliteParameter(":count", count)); - - using (IDataReader reader = cmd.ExecuteReader()) - { - while (reader.Read()) - { - AssetMetadata metadata = buildAssetMetadata(reader); - retList.Add(metadata); - } - } - } - } - - return retList; - } - - /*********************************************************************** - * - * Database Binding functions - * - * These will be db specific due to typing, and minor differences - * in databases. - * - **********************************************************************/ - - #region IPlugin interface - - /// - /// - /// - override public string Version - { - get - { - Module module = GetType().Module; - // string dllName = module.Assembly.ManifestModule.Name; - Version dllVersion = module.Assembly.GetName().Version; - - return - string.Format("{0}.{1}.{2}.{3}", dllVersion.Major, dllVersion.Minor, dllVersion.Build, - dllVersion.Revision); - } - } - - /// - /// Initialise the AssetData interface using default URI - /// - override public void Initialise() - { - Initialise("URI=file:Asset.db,version=3"); - } - - /// - /// Name of this DB provider - /// - override public string Name - { - get { return "SQLite Asset storage engine"; } - } - - public override bool Delete(string id) - { - return false; - } - #endregion - } -} diff --git a/OpenSim/Data/SQLiteLegacy/SQLiteAuthenticationData.cs b/OpenSim/Data/SQLiteLegacy/SQLiteAuthenticationData.cs deleted file mode 100644 index 760221d9fe..0000000000 --- a/OpenSim/Data/SQLiteLegacy/SQLiteAuthenticationData.cs +++ /dev/null @@ -1,266 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data; -using System.Reflection; -using log4net; -using OpenMetaverse; -using OpenSim.Framework; -using Mono.Data.SqliteClient; - -namespace OpenSim.Data.SQLiteLegacy -{ - public class SQLiteAuthenticationData : SQLiteFramework, IAuthenticationData - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private string m_Realm; - private List m_ColumnNames; - private int m_LastExpire; - private string m_connectionString; - - protected static SqliteConnection m_Connection; - private static bool m_initialized = false; - - public SQLiteAuthenticationData(string connectionString, string realm) - : base(connectionString) - { - m_Realm = realm; - m_connectionString = connectionString; - - if (!m_initialized) - { - m_Connection = new SqliteConnection(connectionString); - m_Connection.Open(); - - using (SqliteConnection dbcon = (SqliteConnection)((ICloneable)m_Connection).Clone()) - { - dbcon.Open(); - Migration m = new Migration(dbcon, GetType().Assembly, "AuthStore"); - m.Update(); - dbcon.Close(); - } - - m_initialized = true; - } - } - - public AuthenticationData Get(UUID principalID) - { - AuthenticationData ret = new AuthenticationData(); - ret.Data = new Dictionary(); - - SqliteCommand cmd = new SqliteCommand("select * from `" + m_Realm + "` where UUID = :PrincipalID"); - cmd.Parameters.Add(new SqliteParameter(":PrincipalID", principalID.ToString())); - - IDataReader result = ExecuteReader(cmd, m_Connection); - - try - { - if (result.Read()) - { - ret.PrincipalID = principalID; - - if (m_ColumnNames == null) - { - m_ColumnNames = new List(); - - DataTable schemaTable = result.GetSchemaTable(); - foreach (DataRow row in schemaTable.Rows) - m_ColumnNames.Add(row["ColumnName"].ToString()); - } - - foreach (string s in m_ColumnNames) - { - if (s == "UUID") - continue; - - ret.Data[s] = result[s].ToString(); - } - - return ret; - } - else - { - return null; - } - } - catch - { - } - finally - { - CloseCommand(cmd); - } - - return null; - } - - public bool Store(AuthenticationData data) - { - if (data.Data.ContainsKey("UUID")) - data.Data.Remove("UUID"); - - string[] fields = new List(data.Data.Keys).ToArray(); - string[] values = new string[data.Data.Count]; - int i = 0; - foreach (object o in data.Data.Values) - values[i++] = o.ToString(); - - SqliteCommand cmd = new SqliteCommand(); - - if (Get(data.PrincipalID) != null) - { - - - string update = "update `" + m_Realm + "` set "; - bool first = true; - foreach (string field in fields) - { - if (!first) - update += ", "; - update += "`" + field + "` = :" + field; - cmd.Parameters.Add(new SqliteParameter(":" + field, data.Data[field])); - - first = false; - } - - update += " where UUID = :UUID"; - cmd.Parameters.Add(new SqliteParameter(":UUID", data.PrincipalID.ToString())); - - cmd.CommandText = update; - try - { - if (ExecuteNonQuery(cmd, m_Connection) < 1) - { - CloseCommand(cmd); - return false; - } - } - catch (Exception e) - { - m_log.Error("[SQLITE]: Exception storing authentication data", e); - CloseCommand(cmd); - return false; - } - } - - else - { - string insert = "insert into `" + m_Realm + "` (`UUID`, `" + - String.Join("`, `", fields) + - "`) values (:UUID, :" + String.Join(", :", fields) + ")"; - - cmd.Parameters.Add(new SqliteParameter(":UUID", data.PrincipalID.ToString())); - foreach (string field in fields) - cmd.Parameters.Add(new SqliteParameter(":" + field, data.Data[field])); - - cmd.CommandText = insert; - - try - { - if (ExecuteNonQuery(cmd, m_Connection) < 1) - { - CloseCommand(cmd); - return false; - } - } - catch (Exception e) - { - Console.WriteLine(e.ToString()); - CloseCommand(cmd); - return false; - } - } - - CloseCommand(cmd); - - return true; - } - - public bool SetDataItem(UUID principalID, string item, string value) - { - SqliteCommand cmd = new SqliteCommand("update `" + m_Realm + - "` set `" + item + "` = " + value + " where UUID = '" + principalID.ToString() + "'"); - - if (ExecuteNonQuery(cmd, m_Connection) > 0) - return true; - - return false; - } - - public bool SetToken(UUID principalID, string token, int lifetime) - { - if (System.Environment.TickCount - m_LastExpire > 30000) - DoExpire(); - - SqliteCommand cmd = new SqliteCommand("insert into tokens (UUID, token, validity) values ('" + principalID.ToString() + - "', '" + token + "', datetime('now', 'localtime', '+" + lifetime.ToString() + " minutes'))"); - - if (ExecuteNonQuery(cmd, m_Connection) > 0) - { - cmd.Dispose(); - return true; - } - - cmd.Dispose(); - return false; - } - - public bool CheckToken(UUID principalID, string token, int lifetime) - { - if (System.Environment.TickCount - m_LastExpire > 30000) - DoExpire(); - - SqliteCommand cmd = new SqliteCommand("update tokens set validity = datetime('now', 'localtime', '+" + lifetime.ToString() + - " minutes') where UUID = '" + principalID.ToString() + "' and token = '" + token + "' and validity > datetime('now', 'localtime')"); - - if (ExecuteNonQuery(cmd, m_Connection) > 0) - { - cmd.Dispose(); - return true; - } - - cmd.Dispose(); - - return false; - } - - private void DoExpire() - { - SqliteCommand cmd = new SqliteCommand("delete from tokens where validity < datetime('now', 'localtime')"); - ExecuteNonQuery(cmd, m_Connection); - - cmd.Dispose(); - - m_LastExpire = System.Environment.TickCount; - } - } -} diff --git a/OpenSim/Data/SQLiteLegacy/SQLiteAvatarData.cs b/OpenSim/Data/SQLiteLegacy/SQLiteAvatarData.cs deleted file mode 100644 index 660632ca07..0000000000 --- a/OpenSim/Data/SQLiteLegacy/SQLiteAvatarData.cs +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using System.Data; -using System.Reflection; -using System.Threading; -using log4net; -using OpenMetaverse; -using OpenSim.Framework; -using Mono.Data.SqliteClient; - -namespace OpenSim.Data.SQLiteLegacy -{ - /// - /// A SQLite Interface for Avatar Data - /// - public class SQLiteAvatarData : SQLiteGenericTableHandler, - IAvatarData - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - public SQLiteAvatarData(string connectionString, string realm) : - base(connectionString, realm, "Avatar") - { - } - - public bool Delete(UUID principalID, string name) - { - SqliteCommand cmd = new SqliteCommand(); - - cmd.CommandText = String.Format("delete from {0} where `PrincipalID` = :PrincipalID and `Name` = :Name", m_Realm); - cmd.Parameters.Add(":PrincipalID", principalID.ToString()); - cmd.Parameters.Add(":Name", name); - - try - { - if (ExecuteNonQuery(cmd, m_Connection) > 0) - return true; - - return false; - } - finally - { - CloseCommand(cmd); - } - } - } -} diff --git a/OpenSim/Data/SQLiteLegacy/SQLiteEstateData.cs b/OpenSim/Data/SQLiteLegacy/SQLiteEstateData.cs deleted file mode 100644 index ad28c000c6..0000000000 --- a/OpenSim/Data/SQLiteLegacy/SQLiteEstateData.cs +++ /dev/null @@ -1,429 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using System.Data; -using System.Reflection; -using log4net; -using Mono.Data.SqliteClient; -using OpenMetaverse; -using OpenSim.Framework; -using OpenSim.Region.Framework.Interfaces; - -namespace OpenSim.Data.SQLiteLegacy -{ - public class SQLiteEstateStore : IEstateDataStore - { - private static readonly ILog m_log = - LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private SqliteConnection m_connection; - private string m_connectionString; - - private FieldInfo[] m_Fields; - private Dictionary m_FieldMap = - new Dictionary(); - - public SQLiteEstateStore() - { - } - - public SQLiteEstateStore(string connectionString) - { - Initialise(connectionString); - } - - public void Initialise(string connectionString) - { - m_connectionString = connectionString; - - m_log.Info("[ESTATE DB]: Sqlite - connecting: "+m_connectionString); - - m_connection = new SqliteConnection(m_connectionString); - m_connection.Open(); - - Assembly assem = GetType().Assembly; - Migration m = new Migration(m_connection, assem, "EstateStore"); - m.Update(); - - m_connection.Close(); - m_connection.Open(); - - Type t = typeof(EstateSettings); - m_Fields = t.GetFields(BindingFlags.NonPublic | - BindingFlags.Instance | - BindingFlags.DeclaredOnly); - - foreach (FieldInfo f in m_Fields) - if (f.Name.Substring(0, 2) == "m_") - m_FieldMap[f.Name.Substring(2)] = f; - } - - private string[] FieldList - { - get { return new List(m_FieldMap.Keys).ToArray(); } - } - - public EstateSettings LoadEstateSettings(UUID regionID, bool create) - { - string sql = "select estate_settings."+String.Join(",estate_settings.", FieldList)+" from estate_map left join estate_settings on estate_map.EstateID = estate_settings.EstateID where estate_settings.EstateID is not null and RegionID = :RegionID"; - - SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand(); - - cmd.CommandText = sql; - cmd.Parameters.Add(":RegionID", regionID.ToString()); - - return DoLoad(cmd, regionID, create); - } - - public List LoadEstateSettingsAll() - { - List estateSettings = new List(); - - List estateIds = GetEstatesAll(); - foreach (int estateId in estateIds) - estateSettings.Add(LoadEstateSettings(estateId)); - - return estateSettings; - } - - private EstateSettings DoLoad(SqliteCommand cmd, UUID regionID, bool create) - { - EstateSettings es = new EstateSettings(); - es.OnSave += StoreEstateSettings; - - IDataReader r = cmd.ExecuteReader(); - - if (r.Read()) - { - foreach (string name in FieldList) - { - if (m_FieldMap[name].GetValue(es) is bool) - { - int v = Convert.ToInt32(r[name]); - if (v != 0) - m_FieldMap[name].SetValue(es, true); - else - m_FieldMap[name].SetValue(es, false); - } - else if (m_FieldMap[name].GetValue(es) is UUID) - { - UUID uuid = UUID.Zero; - - UUID.TryParse(r[name].ToString(), out uuid); - m_FieldMap[name].SetValue(es, uuid); - } - else - { - m_FieldMap[name].SetValue(es, Convert.ChangeType(r[name], m_FieldMap[name].FieldType)); - } - } - r.Close(); - } - else if (create) - { - r.Close(); - - List names = new List(FieldList); - - names.Remove("EstateID"); - - string sql = "insert into estate_settings ("+String.Join(",", names.ToArray())+") values ( :"+String.Join(", :", names.ToArray())+")"; - - cmd.CommandText = sql; - cmd.Parameters.Clear(); - - foreach (string name in FieldList) - { - if (m_FieldMap[name].GetValue(es) is bool) - { - if ((bool)m_FieldMap[name].GetValue(es)) - cmd.Parameters.Add(":"+name, "1"); - else - cmd.Parameters.Add(":"+name, "0"); - } - else - { - cmd.Parameters.Add(":"+name, m_FieldMap[name].GetValue(es).ToString()); - } - } - - cmd.ExecuteNonQuery(); - - cmd.CommandText = "select LAST_INSERT_ROWID() as id"; - cmd.Parameters.Clear(); - - r = cmd.ExecuteReader(); - - r.Read(); - - es.EstateID = Convert.ToUInt32(r["id"]); - - r.Close(); - - cmd.CommandText = "insert into estate_map values (:RegionID, :EstateID)"; - cmd.Parameters.Add(":RegionID", regionID.ToString()); - cmd.Parameters.Add(":EstateID", es.EstateID.ToString()); - - // This will throw on dupe key - try - { - cmd.ExecuteNonQuery(); - } - catch (Exception) - { - } - - es.Save(); - } - - LoadBanList(es); - - es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers"); - es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users"); - es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups"); - return es; - } - - public void StoreEstateSettings(EstateSettings es) - { - List fields = new List(FieldList); - fields.Remove("EstateID"); - - List terms = new List(); - - foreach (string f in fields) - terms.Add(f+" = :"+f); - - string sql = "update estate_settings set "+String.Join(", ", terms.ToArray())+" where EstateID = :EstateID"; - - SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand(); - - cmd.CommandText = sql; - - foreach (string name in FieldList) - { - if (m_FieldMap[name].GetValue(es) is bool) - { - if ((bool)m_FieldMap[name].GetValue(es)) - cmd.Parameters.Add(":"+name, "1"); - else - cmd.Parameters.Add(":"+name, "0"); - } - else - { - cmd.Parameters.Add(":"+name, m_FieldMap[name].GetValue(es).ToString()); - } - } - - cmd.ExecuteNonQuery(); - - SaveBanList(es); - SaveUUIDList(es.EstateID, "estate_managers", es.EstateManagers); - SaveUUIDList(es.EstateID, "estate_users", es.EstateAccess); - SaveUUIDList(es.EstateID, "estate_groups", es.EstateGroups); - } - - private void LoadBanList(EstateSettings es) - { - es.ClearBans(); - - SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand(); - - cmd.CommandText = "select bannedUUID from estateban where EstateID = :EstateID"; - cmd.Parameters.Add(":EstateID", es.EstateID); - - IDataReader r = cmd.ExecuteReader(); - - while (r.Read()) - { - EstateBan eb = new EstateBan(); - - UUID uuid = new UUID(); - UUID.TryParse(r["bannedUUID"].ToString(), out uuid); - - eb.BannedUserID = uuid; - eb.BannedHostAddress = "0.0.0.0"; - eb.BannedHostIPMask = "0.0.0.0"; - es.AddBan(eb); - } - r.Close(); - } - - private void SaveBanList(EstateSettings es) - { - SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand(); - - cmd.CommandText = "delete from estateban where EstateID = :EstateID"; - cmd.Parameters.Add(":EstateID", es.EstateID.ToString()); - - cmd.ExecuteNonQuery(); - - cmd.Parameters.Clear(); - - cmd.CommandText = "insert into estateban (EstateID, bannedUUID, bannedIp, bannedIpHostMask, bannedNameMask) values ( :EstateID, :bannedUUID, '', '', '' )"; - - foreach (EstateBan b in es.EstateBans) - { - cmd.Parameters.Add(":EstateID", es.EstateID.ToString()); - cmd.Parameters.Add(":bannedUUID", b.BannedUserID.ToString()); - - cmd.ExecuteNonQuery(); - cmd.Parameters.Clear(); - } - } - - void SaveUUIDList(uint EstateID, string table, UUID[] data) - { - SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand(); - - cmd.CommandText = "delete from "+table+" where EstateID = :EstateID"; - cmd.Parameters.Add(":EstateID", EstateID.ToString()); - - cmd.ExecuteNonQuery(); - - cmd.Parameters.Clear(); - - cmd.CommandText = "insert into "+table+" (EstateID, uuid) values ( :EstateID, :uuid )"; - - foreach (UUID uuid in data) - { - cmd.Parameters.Add(":EstateID", EstateID.ToString()); - cmd.Parameters.Add(":uuid", uuid.ToString()); - - cmd.ExecuteNonQuery(); - cmd.Parameters.Clear(); - } - } - - UUID[] LoadUUIDList(uint EstateID, string table) - { - List uuids = new List(); - - SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand(); - - cmd.CommandText = "select uuid from "+table+" where EstateID = :EstateID"; - cmd.Parameters.Add(":EstateID", EstateID); - - IDataReader r = cmd.ExecuteReader(); - - while (r.Read()) - { - // EstateBan eb = new EstateBan(); - - UUID uuid = new UUID(); - UUID.TryParse(r["uuid"].ToString(), out uuid); - - uuids.Add(uuid); - } - r.Close(); - - return uuids.ToArray(); - } - - public EstateSettings LoadEstateSettings(int estateID) - { - string sql = "select estate_settings."+String.Join(",estate_settings.", FieldList)+" from estate_settings where estate_settings.EstateID = :EstateID"; - - SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand(); - - cmd.CommandText = sql; - cmd.Parameters.Add(":EstateID", estateID.ToString()); - - return DoLoad(cmd, UUID.Zero, false); - } - - public List GetEstates(string search) - { - List result = new List(); - - string sql = "select EstateID from estate_settings where estate_settings.EstateName = :EstateName"; - - SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand(); - - cmd.CommandText = sql; - cmd.Parameters.Add(":EstateName", search); - - IDataReader r = cmd.ExecuteReader(); - - while (r.Read()) - { - result.Add(Convert.ToInt32(r["EstateID"])); - } - r.Close(); - - return result; - } - - - public List GetEstatesAll() - { - List result = new List(); - - string sql = "select EstateID from estate_settings"; - - SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand(); - - cmd.CommandText = sql; - - IDataReader r = cmd.ExecuteReader(); - - while (r.Read()) - { - result.Add(Convert.ToInt32(r["EstateID"])); - } - r.Close(); - - return result; - } - - public bool LinkRegion(UUID regionID, int estateID) - { - SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand(); - - cmd.CommandText = "insert into estate_map values (:RegionID, :EstateID)"; - cmd.Parameters.Add(":RegionID", regionID.ToString()); - cmd.Parameters.Add(":EstateID", estateID.ToString()); - - if (cmd.ExecuteNonQuery() == 0) - return false; - - return true; - } - - public List GetRegions(int estateID) - { - return new List(); - } - - public bool DeleteEstate(int estateID) - { - return false; - } - } -} diff --git a/OpenSim/Data/SQLiteLegacy/SQLiteFramework.cs b/OpenSim/Data/SQLiteLegacy/SQLiteFramework.cs deleted file mode 100644 index 606478ea7e..0000000000 --- a/OpenSim/Data/SQLiteLegacy/SQLiteFramework.cs +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data; -using OpenMetaverse; -using OpenSim.Framework; -using Mono.Data.SqliteClient; - -namespace OpenSim.Data.SQLiteLegacy -{ - /// - /// A database interface class to a user profile storage system - /// - public class SQLiteFramework - { - protected Object m_lockObject = new Object(); - - protected SQLiteFramework(string connectionString) - { - } - - ////////////////////////////////////////////////////////////// - // - // All non queries are funneled through one connection - // to increase performance a little - // - protected int ExecuteNonQuery(SqliteCommand cmd, SqliteConnection connection) - { - lock (connection) - { - SqliteConnection newConnection = - (SqliteConnection)((ICloneable)connection).Clone(); - newConnection.Open(); - - cmd.Connection = newConnection; - //Console.WriteLine("XXX " + cmd.CommandText); - - return cmd.ExecuteNonQuery(); - } - } - - protected IDataReader ExecuteReader(SqliteCommand cmd, SqliteConnection connection) - { - lock (connection) - { - SqliteConnection newConnection = - (SqliteConnection)((ICloneable)connection).Clone(); - newConnection.Open(); - - cmd.Connection = newConnection; - //Console.WriteLine("XXX " + cmd.CommandText); - - return cmd.ExecuteReader(); - } - } - - protected void CloseCommand(SqliteCommand cmd) - { - cmd.Connection.Close(); - cmd.Connection.Dispose(); - cmd.Dispose(); - } - } -} diff --git a/OpenSim/Data/SQLiteLegacy/SQLiteFriendsData.cs b/OpenSim/Data/SQLiteLegacy/SQLiteFriendsData.cs deleted file mode 100644 index d529d4d8ab..0000000000 --- a/OpenSim/Data/SQLiteLegacy/SQLiteFriendsData.cs +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data; -using OpenMetaverse; -using OpenSim.Framework; -using Mono.Data.SqliteClient; - -namespace OpenSim.Data.SQLiteLegacy -{ - public class SQLiteFriendsData : SQLiteGenericTableHandler, IFriendsData - { - public SQLiteFriendsData(string connectionString, string realm) - : base(connectionString, realm, "FriendsStore") - { - } - - public FriendsData[] GetFriends(UUID userID) - { - SqliteCommand cmd = new SqliteCommand(); - - cmd.CommandText = String.Format("select a.*,case when b.Flags is null then -1 else b.Flags end as TheirFlags from {0} as a left join {0} as b on a.PrincipalID = b.Friend and a.Friend = b.PrincipalID where a.PrincipalID = :PrincipalID", m_Realm); - cmd.Parameters.Add(":PrincipalID", userID.ToString()); - - return DoQuery(cmd); - - } - - public bool Delete(UUID principalID, string friend) - { - SqliteCommand cmd = new SqliteCommand(); - - cmd.CommandText = String.Format("delete from {0} where PrincipalID = :PrincipalID and Friend = :Friend", m_Realm); - cmd.Parameters.Add(":PrincipalID", principalID.ToString()); - cmd.Parameters.Add(":Friend", friend); - - ExecuteNonQuery(cmd, cmd.Connection); - - return true; - } - - } -} diff --git a/OpenSim/Data/SQLiteLegacy/SQLiteGenericTableHandler.cs b/OpenSim/Data/SQLiteLegacy/SQLiteGenericTableHandler.cs deleted file mode 100644 index 1c1fe8cc0f..0000000000 --- a/OpenSim/Data/SQLiteLegacy/SQLiteGenericTableHandler.cs +++ /dev/null @@ -1,268 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using System.Data; -using System.Reflection; -using log4net; -using Mono.Data.SqliteClient; -using OpenMetaverse; -using OpenSim.Framework; -using OpenSim.Region.Framework.Interfaces; - -namespace OpenSim.Data.SQLiteLegacy -{ - public class SQLiteGenericTableHandler : SQLiteFramework where T: class, new() - { -// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - protected Dictionary m_Fields = - new Dictionary(); - - protected List m_ColumnNames = null; - protected string m_Realm; - protected FieldInfo m_DataField = null; - - protected static SqliteConnection m_Connection; - private static bool m_initialized; - - public SQLiteGenericTableHandler(string connectionString, - string realm, string storeName) : base(connectionString) - { - m_Realm = realm; - - if (!m_initialized) - { - m_Connection = new SqliteConnection(connectionString); - m_Connection.Open(); - - if (storeName != String.Empty) - { - Assembly assem = GetType().Assembly; - SqliteConnection newConnection = - (SqliteConnection)((ICloneable)m_Connection).Clone(); - newConnection.Open(); - - Migration m = new Migration(newConnection, assem, storeName); - m.Update(); - newConnection.Close(); - newConnection.Dispose(); - } - - m_initialized = true; - } - - Type t = typeof(T); - FieldInfo[] fields = t.GetFields(BindingFlags.Public | - BindingFlags.Instance | - BindingFlags.DeclaredOnly); - - if (fields.Length == 0) - return; - - foreach (FieldInfo f in fields) - { - if (f.Name != "Data") - m_Fields[f.Name] = f; - else - m_DataField = f; - } - } - - private void CheckColumnNames(IDataReader reader) - { - if (m_ColumnNames != null) - return; - - m_ColumnNames = new List(); - - DataTable schemaTable = reader.GetSchemaTable(); - foreach (DataRow row in schemaTable.Rows) - { - if (row["ColumnName"] != null && - (!m_Fields.ContainsKey(row["ColumnName"].ToString()))) - m_ColumnNames.Add(row["ColumnName"].ToString()); - } - } - - public T[] Get(string field, string key) - { - return Get(new string[] { field }, new string[] { key }); - } - - public T[] Get(string[] fields, string[] keys) - { - if (fields.Length != keys.Length) - return new T[0]; - - List terms = new List(); - - SqliteCommand cmd = new SqliteCommand(); - - for (int i = 0 ; i < fields.Length ; i++) - { - cmd.Parameters.Add(new SqliteParameter(":" + fields[i], keys[i])); - terms.Add("`" + fields[i] + "` = :" + fields[i]); - } - - string where = String.Join(" and ", terms.ToArray()); - - string query = String.Format("select * from {0} where {1}", - m_Realm, where); - - cmd.CommandText = query; - - return DoQuery(cmd); - } - - protected T[] DoQuery(SqliteCommand cmd) - { - IDataReader reader = ExecuteReader(cmd, m_Connection); - if (reader == null) - return new T[0]; - - CheckColumnNames(reader); - - List result = new List(); - - while (reader.Read()) - { - T row = new T(); - - foreach (string name in m_Fields.Keys) - { - if (m_Fields[name].GetValue(row) is bool) - { - int v = Convert.ToInt32(reader[name]); - m_Fields[name].SetValue(row, v != 0 ? true : false); - } - else if (m_Fields[name].GetValue(row) is UUID) - { - UUID uuid = UUID.Zero; - - UUID.TryParse(reader[name].ToString(), out uuid); - m_Fields[name].SetValue(row, uuid); - } - else if (m_Fields[name].GetValue(row) is int) - { - int v = Convert.ToInt32(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); - } - - CloseCommand(cmd); - - return result.ToArray(); - } - - public T[] Get(string where) - { - SqliteCommand cmd = new SqliteCommand(); - - string query = String.Format("select * from {0} where {1}", - m_Realm, where); - - cmd.CommandText = query; - - return DoQuery(cmd); - } - - public bool Store(T row) - { - SqliteCommand cmd = new SqliteCommand(); - - string query = ""; - List names = new List(); - List values = new List(); - - foreach (FieldInfo fi in m_Fields.Values) - { - names.Add(fi.Name); - values.Add(":" + fi.Name); - cmd.Parameters.Add(new SqliteParameter(":" + fi.Name, fi.GetValue(row).ToString())); - } - - if (m_DataField != null) - { - Dictionary data = - (Dictionary)m_DataField.GetValue(row); - - foreach (KeyValuePair kvp in data) - { - names.Add(kvp.Key); - values.Add(":" + kvp.Key); - cmd.Parameters.Add(new SqliteParameter(":" + kvp.Key, kvp.Value)); - } - } - - query = String.Format("replace into {0} (`", m_Realm) + String.Join("`,`", names.ToArray()) + "`) values (" + String.Join(",", values.ToArray()) + ")"; - - cmd.CommandText = query; - - if (ExecuteNonQuery(cmd, m_Connection) > 0) - return true; - - return false; - } - - public bool Delete(string field, string val) - { - SqliteCommand cmd = new SqliteCommand(); - - cmd.CommandText = String.Format("delete from {0} where `{1}` = :{1}", m_Realm, field); - cmd.Parameters.Add(new SqliteParameter(field, val)); - - if (ExecuteNonQuery(cmd, m_Connection) > 0) - return true; - - return false; - } - } -} diff --git a/OpenSim/Data/SQLiteLegacy/SQLiteInventoryStore.cs b/OpenSim/Data/SQLiteLegacy/SQLiteInventoryStore.cs deleted file mode 100644 index 8ca48f94b1..0000000000 --- a/OpenSim/Data/SQLiteLegacy/SQLiteInventoryStore.cs +++ /dev/null @@ -1,898 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using System.Data; -using System.Reflection; -using log4net; -using Mono.Data.SqliteClient; -using OpenMetaverse; -using OpenSim.Framework; - -namespace OpenSim.Data.SQLiteLegacy -{ - /// - /// An Inventory Interface to the SQLite database - /// - public class SQLiteInventoryStore : SQLiteUtil, IInventoryDataPlugin - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private const string invItemsSelect = "select * from inventoryitems"; - private const string invFoldersSelect = "select * from inventoryfolders"; - - private static SqliteConnection conn; - private static DataSet ds; - private static SqliteDataAdapter invItemsDa; - private static SqliteDataAdapter invFoldersDa; - - private static bool m_Initialized = false; - - public void Initialise() - { - m_log.Info("[SQLiteInventoryData]: " + Name + " cannot be default-initialized!"); - throw new PluginNotInitialisedException(Name); - } - - /// - /// - /// Initialises Inventory interface - /// Loads and initialises a new SQLite connection and maintains it. - /// use default URI if connect string string is empty. - /// - /// - /// connect string - public void Initialise(string dbconnect) - { - if (!m_Initialized) - { - m_Initialized = true; - - if (dbconnect == string.Empty) - { - dbconnect = "URI=file:inventoryStore.db,version=3"; - } - m_log.Info("[INVENTORY DB]: Sqlite - connecting: " + dbconnect); - conn = new SqliteConnection(dbconnect); - - conn.Open(); - - Assembly assem = GetType().Assembly; - Migration m = new Migration(conn, assem, "InventoryStore"); - m.Update(); - - SqliteCommand itemsSelectCmd = new SqliteCommand(invItemsSelect, conn); - invItemsDa = new SqliteDataAdapter(itemsSelectCmd); - // SqliteCommandBuilder primCb = new SqliteCommandBuilder(primDa); - - SqliteCommand foldersSelectCmd = new SqliteCommand(invFoldersSelect, conn); - invFoldersDa = new SqliteDataAdapter(foldersSelectCmd); - - ds = new DataSet(); - - ds.Tables.Add(createInventoryFoldersTable()); - invFoldersDa.Fill(ds.Tables["inventoryfolders"]); - setupFoldersCommands(invFoldersDa, conn); - m_log.Info("[INVENTORY DB]: Populated Inventory Folders Definitions"); - - ds.Tables.Add(createInventoryItemsTable()); - invItemsDa.Fill(ds.Tables["inventoryitems"]); - setupItemsCommands(invItemsDa, conn); - m_log.Info("[INVENTORY DB]: Populated Inventory Items Definitions"); - - ds.AcceptChanges(); - } - } - - /// - /// Closes the inventory interface - /// - public void Dispose() - { - if (conn != null) - { - conn.Close(); - conn = null; - } - if (invItemsDa != null) - { - invItemsDa.Dispose(); - invItemsDa = null; - } - if (invFoldersDa != null) - { - invFoldersDa.Dispose(); - invFoldersDa = null; - } - if (ds != null) - { - ds.Dispose(); - ds = null; - } - } - - /// - /// - /// - /// - /// - public InventoryItemBase buildItem(DataRow row) - { - InventoryItemBase item = new InventoryItemBase(); - item.ID = new UUID((string) row["UUID"]); - item.AssetID = new UUID((string) row["assetID"]); - item.AssetType = Convert.ToInt32(row["assetType"]); - item.InvType = Convert.ToInt32(row["invType"]); - item.Folder = new UUID((string) row["parentFolderID"]); - item.Owner = new UUID((string) row["avatarID"]); - item.CreatorIdentification = (string)row["creatorsID"]; - item.Name = (string) row["inventoryName"]; - item.Description = (string) row["inventoryDescription"]; - - item.NextPermissions = Convert.ToUInt32(row["inventoryNextPermissions"]); - item.CurrentPermissions = Convert.ToUInt32(row["inventoryCurrentPermissions"]); - item.BasePermissions = Convert.ToUInt32(row["inventoryBasePermissions"]); - item.EveryOnePermissions = Convert.ToUInt32(row["inventoryEveryOnePermissions"]); - item.GroupPermissions = Convert.ToUInt32(row["inventoryGroupPermissions"]); - - // new fields - if (!Convert.IsDBNull(row["salePrice"])) - item.SalePrice = Convert.ToInt32(row["salePrice"]); - - if (!Convert.IsDBNull(row["saleType"])) - item.SaleType = Convert.ToByte(row["saleType"]); - - if (!Convert.IsDBNull(row["creationDate"])) - item.CreationDate = Convert.ToInt32(row["creationDate"]); - - if (!Convert.IsDBNull(row["groupID"])) - item.GroupID = new UUID((string)row["groupID"]); - - if (!Convert.IsDBNull(row["groupOwned"])) - item.GroupOwned = Convert.ToBoolean(row["groupOwned"]); - - if (!Convert.IsDBNull(row["Flags"])) - item.Flags = Convert.ToUInt32(row["Flags"]); - - return item; - } - - /// - /// Fill a database row with item data - /// - /// - /// - private static void fillItemRow(DataRow row, InventoryItemBase item) - { - row["UUID"] = item.ID.ToString(); - row["assetID"] = item.AssetID.ToString(); - row["assetType"] = item.AssetType; - row["invType"] = item.InvType; - row["parentFolderID"] = item.Folder.ToString(); - row["avatarID"] = item.Owner.ToString(); - row["creatorsID"] = item.CreatorIdentification.ToString(); - row["inventoryName"] = item.Name; - row["inventoryDescription"] = item.Description; - - row["inventoryNextPermissions"] = item.NextPermissions; - row["inventoryCurrentPermissions"] = item.CurrentPermissions; - row["inventoryBasePermissions"] = item.BasePermissions; - row["inventoryEveryOnePermissions"] = item.EveryOnePermissions; - row["inventoryGroupPermissions"] = item.GroupPermissions; - - // new fields - row["salePrice"] = item.SalePrice; - row["saleType"] = item.SaleType; - row["creationDate"] = item.CreationDate; - row["groupID"] = item.GroupID.ToString(); - row["groupOwned"] = item.GroupOwned; - row["flags"] = item.Flags; - } - - /// - /// Add inventory folder - /// - /// Folder base - /// true=create folder. false=update existing folder - /// nasty - private void addFolder(InventoryFolderBase folder, bool add) - { - lock (ds) - { - DataTable inventoryFolderTable = ds.Tables["inventoryfolders"]; - - DataRow inventoryRow = inventoryFolderTable.Rows.Find(folder.ID.ToString()); - if (inventoryRow == null) - { - if (! add) - m_log.ErrorFormat("Interface Misuse: Attempting to Update non-existant inventory folder: {0}", folder.ID); - - inventoryRow = inventoryFolderTable.NewRow(); - fillFolderRow(inventoryRow, folder); - inventoryFolderTable.Rows.Add(inventoryRow); - } - else - { - if (add) - m_log.ErrorFormat("Interface Misuse: Attempting to Add inventory folder that already exists: {0}", folder.ID); - - fillFolderRow(inventoryRow, folder); - } - - invFoldersDa.Update(ds, "inventoryfolders"); - } - } - - /// - /// Move an inventory folder - /// - /// folder base - private void moveFolder(InventoryFolderBase folder) - { - lock (ds) - { - DataTable inventoryFolderTable = ds.Tables["inventoryfolders"]; - - DataRow inventoryRow = inventoryFolderTable.Rows.Find(folder.ID.ToString()); - if (inventoryRow == null) - { - inventoryRow = inventoryFolderTable.NewRow(); - fillFolderRow(inventoryRow, folder); - inventoryFolderTable.Rows.Add(inventoryRow); - } - else - { - moveFolderRow(inventoryRow, folder); - } - - invFoldersDa.Update(ds, "inventoryfolders"); - } - } - - /// - /// add an item in inventory - /// - /// the item - /// true=add item ; false=update existing item - private void addItem(InventoryItemBase item, bool add) - { - lock (ds) - { - DataTable inventoryItemTable = ds.Tables["inventoryitems"]; - - DataRow inventoryRow = inventoryItemTable.Rows.Find(item.ID.ToString()); - if (inventoryRow == null) - { - if (!add) - m_log.ErrorFormat("[INVENTORY DB]: Interface Misuse: Attempting to Update non-existant inventory item: {0}", item.ID); - - inventoryRow = inventoryItemTable.NewRow(); - fillItemRow(inventoryRow, item); - inventoryItemTable.Rows.Add(inventoryRow); - } - else - { - if (add) - m_log.ErrorFormat("[INVENTORY DB]: Interface Misuse: Attempting to Add inventory item that already exists: {0}", item.ID); - - fillItemRow(inventoryRow, item); - } - - invItemsDa.Update(ds, "inventoryitems"); - - DataTable inventoryFolderTable = ds.Tables["inventoryfolders"]; - - inventoryRow = inventoryFolderTable.Rows.Find(item.Folder.ToString()); - if (inventoryRow != null) //MySQL doesn't throw an exception here, so sqlite shouldn't either. - inventoryRow["version"] = (int)inventoryRow["version"] + 1; - - invFoldersDa.Update(ds, "inventoryfolders"); - } - } - - /// - /// TODO : DataSet commit - /// - public void Shutdown() - { - // TODO: DataSet commit - } - - /// - /// The name of this DB provider - /// - /// Name of DB provider - public string Name - { - get { return "SQLite Inventory Data Interface"; } - } - - /// - /// Returns the version of this DB provider - /// - /// A string containing the DB provider version - public string Version - { - get - { - Module module = GetType().Module; - // string dllName = module.Assembly.ManifestModule.Name; - Version dllVersion = module.Assembly.GetName().Version; - - - return - string.Format("{0}.{1}.{2}.{3}", dllVersion.Major, dllVersion.Minor, dllVersion.Build, - dllVersion.Revision); - } - } - - /// - /// Returns a list of inventory items contained within the specified folder - /// - /// The UUID of the target folder - /// A List of InventoryItemBase items - public List getInventoryInFolder(UUID folderID) - { - lock (ds) - { - List retval = new List(); - DataTable inventoryItemTable = ds.Tables["inventoryitems"]; - string selectExp = "parentFolderID = '" + folderID + "'"; - DataRow[] rows = inventoryItemTable.Select(selectExp); - foreach (DataRow row in rows) - { - retval.Add(buildItem(row)); - } - - return retval; - } - } - - /// - /// Returns a list of the root folders within a users inventory - /// - /// The user whos inventory is to be searched - /// A list of folder objects - public List getUserRootFolders(UUID user) - { - return new List(); - } - - // see InventoryItemBase.getUserRootFolder - public InventoryFolderBase getUserRootFolder(UUID user) - { - lock (ds) - { - List folders = new List(); - DataTable inventoryFolderTable = ds.Tables["inventoryfolders"]; - string selectExp = "agentID = '" + user + "' AND parentID = '" + UUID.Zero + "'"; - DataRow[] rows = inventoryFolderTable.Select(selectExp); - foreach (DataRow row in rows) - { - folders.Add(buildFolder(row)); - } - - // There should only ever be one root folder for a user. However, if there's more - // than one we'll simply use the first one rather than failing. It would be even - // nicer to print some message to this effect, but this feels like it's too low a - // to put such a message out, and it's too minor right now to spare the time to - // suitably refactor. - if (folders.Count > 0) - { - return folders[0]; - } - - return null; - } - } - - /// - /// Append a list of all the child folders of a parent folder - /// - /// list where folders will be appended - /// ID of parent - protected void getInventoryFolders(ref List folders, UUID parentID) - { - lock (ds) - { - DataTable inventoryFolderTable = ds.Tables["inventoryfolders"]; - string selectExp = "parentID = '" + parentID + "'"; - DataRow[] rows = inventoryFolderTable.Select(selectExp); - foreach (DataRow row in rows) - { - folders.Add(buildFolder(row)); - } - - } - } - - /// - /// Returns a list of inventory folders contained in the folder 'parentID' - /// - /// The folder to get subfolders for - /// A list of inventory folders - public List getInventoryFolders(UUID parentID) - { - List folders = new List(); - getInventoryFolders(ref folders, parentID); - return folders; - } - - /// - /// See IInventoryDataPlugin - /// - /// - /// - public List getFolderHierarchy(UUID parentID) - { - /* Note: There are subtle changes between this implementation of getFolderHierarchy and the previous one - * - We will only need to hit the database twice instead of n times. - * - We assume the database is well-formed - no stranded/dangling folders, all folders in heirarchy owned - * by the same person, each user only has 1 inventory heirarchy - * - The returned list is not ordered, instead of breadth-first ordered - There are basically 2 usage cases for getFolderHeirarchy: - 1) Getting the user's entire inventory heirarchy when they log in - 2) Finding a subfolder heirarchy to delete when emptying the trash. - This implementation will pull all inventory folders from the database, and then prune away any folder that - is not part of the requested sub-heirarchy. The theory is that it is cheaper to make 1 request from the - database than to make n requests. This pays off only if requested heirarchy is large. - By making this choice, we are making the worst case better at the cost of making the best case worse - - Francis - */ - - List folders = new List(); - DataRow[] folderRows = null, parentRow; - InventoryFolderBase parentFolder = null; - lock (ds) - { - /* Fetch the parent folder from the database to determine the agent ID. - * Then fetch all inventory folders for that agent from the agent ID. - */ - DataTable inventoryFolderTable = ds.Tables["inventoryfolders"]; - string selectExp = "UUID = '" + parentID + "'"; - parentRow = inventoryFolderTable.Select(selectExp); // Assume at most 1 result - if (parentRow.GetLength(0) >= 1) // No result means parent folder does not exist - { - parentFolder = buildFolder(parentRow[0]); - UUID agentID = parentFolder.Owner; - selectExp = "agentID = '" + agentID + "'"; - folderRows = inventoryFolderTable.Select(selectExp); - } - - if (folderRows != null && folderRows.GetLength(0) >= 1) // No result means parent folder does not exist - { // or has no children - /* if we're querying the root folder, just return an unordered list of all folders in the user's - * inventory - */ - if (parentFolder.ParentID == UUID.Zero) - { - foreach (DataRow row in folderRows) - { - InventoryFolderBase curFolder = buildFolder(row); - if (curFolder.ID != parentID) // Return all folders except the parent folder of heirarchy - folders.Add(buildFolder(row)); - } - } // If requesting root folder - /* else we are querying a non-root folder. We currently have a list of all of the user's folders, - * we must construct a list of all folders in the heirarchy below parentID. - * Our first step will be to construct a hash table of all folders, indexed by parent ID. - * Once we have constructed the hash table, we will do a breadth-first traversal on the tree using the - * hash table to find child folders. - */ - else - { // Querying a non-root folder - - // Build a hash table of all user's inventory folders, indexed by each folder's parent ID - Dictionary> hashtable = - new Dictionary>(folderRows.GetLength(0)); - - foreach (DataRow row in folderRows) - { - InventoryFolderBase curFolder = buildFolder(row); - if (curFolder.ParentID != UUID.Zero) // Discard root of tree - not needed - { - if (hashtable.ContainsKey(curFolder.ParentID)) - { - // Current folder already has a sibling - append to sibling list - hashtable[curFolder.ParentID].Add(curFolder); - } - else - { - List siblingList = new List(); - siblingList.Add(curFolder); - // Current folder has no known (yet) siblings - hashtable.Add(curFolder.ParentID, siblingList); - } - } - } // For all inventory folders - - // Note: Could release the ds lock here - we don't access folderRows or the database anymore. - // This is somewhat of a moot point as the callers of this function usually lock db anyways. - - if (hashtable.ContainsKey(parentID)) // if requested folder does have children - folders.AddRange(hashtable[parentID]); - - // BreadthFirstSearch build inventory tree **Note: folders.Count is *not* static - for (int i = 0; i < folders.Count; i++) - if (hashtable.ContainsKey(folders[i].ID)) - folders.AddRange(hashtable[folders[i].ID]); - - } // if requesting a subfolder heirarchy - } // if folder parentID exists and has children - } // lock ds - return folders; - } - - /// - /// Returns an inventory item by its UUID - /// - /// The UUID of the item to be returned - /// A class containing item information - public InventoryItemBase getInventoryItem(UUID item) - { - lock (ds) - { - DataRow row = ds.Tables["inventoryitems"].Rows.Find(item.ToString()); - if (row != null) - { - return buildItem(row); - } - else - { - return null; - } - } - } - - /// - /// Returns a specified inventory folder by its UUID - /// - /// The UUID of the folder to be returned - /// A class containing folder information - public InventoryFolderBase getInventoryFolder(UUID folder) - { - // TODO: Deep voodoo here. If you enable this code then - // multi region breaks. No idea why, but I figured it was - // better to leave multi region at this point. It does mean - // that you don't get to see system textures why creating - // clothes and the like. :( - lock (ds) - { - DataRow row = ds.Tables["inventoryfolders"].Rows.Find(folder.ToString()); - if (row != null) - { - return buildFolder(row); - } - else - { - return null; - } - } - } - - /// - /// Creates a new inventory item based on item - /// - /// The item to be created - public void addInventoryItem(InventoryItemBase item) - { - addItem(item, true); - } - - /// - /// Updates an inventory item with item (updates based on ID) - /// - /// The updated item - public void updateInventoryItem(InventoryItemBase item) - { - addItem(item, false); - } - - /// - /// Delete an inventory item - /// - /// The item UUID - public void deleteInventoryItem(UUID itemID) - { - lock (ds) - { - DataTable inventoryItemTable = ds.Tables["inventoryitems"]; - - DataRow inventoryRow = inventoryItemTable.Rows.Find(itemID.ToString()); - if (inventoryRow != null) - { - inventoryRow.Delete(); - } - - invItemsDa.Update(ds, "inventoryitems"); - } - } - - public InventoryItemBase queryInventoryItem(UUID itemID) - { - return getInventoryItem(itemID); - } - - public InventoryFolderBase queryInventoryFolder(UUID folderID) - { - return getInventoryFolder(folderID); - } - - /// - /// Delete all items in the specified folder - /// - /// id of the folder, whose item content should be deleted - /// this is horribly inefficient, but I don't want to ruin the overall structure of this implementation - private void deleteItemsInFolder(UUID folderId) - { - List items = getInventoryInFolder(folderId); - - foreach (InventoryItemBase i in items) - deleteInventoryItem(i.ID); - } - - /// - /// Adds a new folder specified by folder - /// - /// The inventory folder - public void addInventoryFolder(InventoryFolderBase folder) - { - addFolder(folder, true); - } - - /// - /// Updates a folder based on its ID with folder - /// - /// The inventory folder - public void updateInventoryFolder(InventoryFolderBase folder) - { - addFolder(folder, false); - } - - /// - /// Moves a folder based on its ID with folder - /// - /// The inventory folder - public void moveInventoryFolder(InventoryFolderBase folder) - { - moveFolder(folder); - } - - /// - /// Delete a folder - /// - /// - /// This will clean-up any child folders and child items as well - /// - /// the folder UUID - public void deleteInventoryFolder(UUID folderID) - { - lock (ds) - { - List subFolders = getFolderHierarchy(folderID); - - DataTable inventoryFolderTable = ds.Tables["inventoryfolders"]; - DataRow inventoryRow; - - //Delete all sub-folders - foreach (InventoryFolderBase f in subFolders) - { - inventoryRow = inventoryFolderTable.Rows.Find(f.ID.ToString()); - if (inventoryRow != null) - { - deleteItemsInFolder(f.ID); - inventoryRow.Delete(); - } - } - - //Delete the actual row - inventoryRow = inventoryFolderTable.Rows.Find(folderID.ToString()); - if (inventoryRow != null) - { - deleteItemsInFolder(folderID); - inventoryRow.Delete(); - } - - invFoldersDa.Update(ds, "inventoryfolders"); - } - } - - /*********************************************************************** - * - * Data Table definitions - * - **********************************************************************/ - - /// - /// Create the "inventoryitems" table - /// - private static DataTable createInventoryItemsTable() - { - DataTable inv = new DataTable("inventoryitems"); - - createCol(inv, "UUID", typeof (String)); //inventoryID - createCol(inv, "assetID", typeof (String)); - createCol(inv, "assetType", typeof (Int32)); - createCol(inv, "invType", typeof (Int32)); - createCol(inv, "parentFolderID", typeof (String)); - createCol(inv, "avatarID", typeof (String)); - createCol(inv, "creatorsID", typeof (String)); - - createCol(inv, "inventoryName", typeof (String)); - createCol(inv, "inventoryDescription", typeof (String)); - // permissions - createCol(inv, "inventoryNextPermissions", typeof (Int32)); - createCol(inv, "inventoryCurrentPermissions", typeof (Int32)); - createCol(inv, "inventoryBasePermissions", typeof (Int32)); - createCol(inv, "inventoryEveryOnePermissions", typeof (Int32)); - createCol(inv, "inventoryGroupPermissions", typeof (Int32)); - - // sale info - createCol(inv, "salePrice", typeof(Int32)); - createCol(inv, "saleType", typeof(Byte)); - - // creation date - createCol(inv, "creationDate", typeof(Int32)); - - // group info - createCol(inv, "groupID", typeof(String)); - createCol(inv, "groupOwned", typeof(Boolean)); - - // Flags - createCol(inv, "flags", typeof(UInt32)); - - inv.PrimaryKey = new DataColumn[] { inv.Columns["UUID"] }; - return inv; - } - - /// - /// Creates the "inventoryfolders" table - /// - /// - private static DataTable createInventoryFoldersTable() - { - DataTable fol = new DataTable("inventoryfolders"); - - createCol(fol, "UUID", typeof (String)); //folderID - createCol(fol, "name", typeof (String)); - createCol(fol, "agentID", typeof (String)); - createCol(fol, "parentID", typeof (String)); - createCol(fol, "type", typeof (Int32)); - createCol(fol, "version", typeof (Int32)); - - fol.PrimaryKey = new DataColumn[] {fol.Columns["UUID"]}; - return fol; - } - - /// - /// - /// - /// - /// - private void setupItemsCommands(SqliteDataAdapter da, SqliteConnection conn) - { - lock (ds) - { - da.InsertCommand = createInsertCommand("inventoryitems", ds.Tables["inventoryitems"]); - da.InsertCommand.Connection = conn; - - da.UpdateCommand = createUpdateCommand("inventoryitems", "UUID=:UUID", ds.Tables["inventoryitems"]); - da.UpdateCommand.Connection = conn; - - SqliteCommand delete = new SqliteCommand("delete from inventoryitems where UUID = :UUID"); - delete.Parameters.Add(createSqliteParameter("UUID", typeof(String))); - delete.Connection = conn; - da.DeleteCommand = delete; - } - } - - /// - /// - /// - /// - /// - private void setupFoldersCommands(SqliteDataAdapter da, SqliteConnection conn) - { - lock (ds) - { - da.InsertCommand = createInsertCommand("inventoryfolders", ds.Tables["inventoryfolders"]); - da.InsertCommand.Connection = conn; - - da.UpdateCommand = createUpdateCommand("inventoryfolders", "UUID=:UUID", ds.Tables["inventoryfolders"]); - da.UpdateCommand.Connection = conn; - - SqliteCommand delete = new SqliteCommand("delete from inventoryfolders where UUID = :UUID"); - delete.Parameters.Add(createSqliteParameter("UUID", typeof(String))); - delete.Connection = conn; - da.DeleteCommand = delete; - } - } - - /// - /// - /// - /// - /// - private static InventoryFolderBase buildFolder(DataRow row) - { - InventoryFolderBase folder = new InventoryFolderBase(); - folder.ID = new UUID((string) row["UUID"]); - folder.Name = (string) row["name"]; - folder.Owner = new UUID((string) row["agentID"]); - folder.ParentID = new UUID((string) row["parentID"]); - folder.Type = Convert.ToInt16(row["type"]); - folder.Version = Convert.ToUInt16(row["version"]); - return folder; - } - - /// - /// - /// - /// - /// - private static void fillFolderRow(DataRow row, InventoryFolderBase folder) - { - row["UUID"] = folder.ID.ToString(); - row["name"] = folder.Name; - row["agentID"] = folder.Owner.ToString(); - row["parentID"] = folder.ParentID.ToString(); - row["type"] = folder.Type; - row["version"] = folder.Version; - } - - /// - /// - /// - /// - /// - private static void moveFolderRow(DataRow row, InventoryFolderBase folder) - { - row["UUID"] = folder.ID.ToString(); - row["parentID"] = folder.ParentID.ToString(); - } - - public List fetchActiveGestures (UUID avatarID) - { - lock (ds) - { - List items = new List(); - - DataTable inventoryItemTable = ds.Tables["inventoryitems"]; - string selectExp - = "avatarID = '" + avatarID + "' AND assetType = " + (int)AssetType.Gesture + " AND flags = 1"; - //m_log.DebugFormat("[SQL]: sql = " + selectExp); - DataRow[] rows = inventoryItemTable.Select(selectExp); - foreach (DataRow row in rows) - { - items.Add(buildItem(row)); - } - return items; - } - } - } -} diff --git a/OpenSim/Data/SQLiteLegacy/SQLiteSimulationData.cs b/OpenSim/Data/SQLiteLegacy/SQLiteSimulationData.cs deleted file mode 100644 index 644864af28..0000000000 --- a/OpenSim/Data/SQLiteLegacy/SQLiteSimulationData.cs +++ /dev/null @@ -1,2274 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using System.Data; -using System.Drawing; -using System.IO; -using System.Reflection; -using log4net; -using Mono.Data.SqliteClient; -using OpenMetaverse; -using OpenSim.Framework; -using OpenSim.Region.Framework.Interfaces; -using OpenSim.Region.Framework.Scenes; - -namespace OpenSim.Data.SQLiteLegacy -{ - /// - /// A RegionData Interface to the SQLite database - /// - public class SQLiteSimulationData : ISimulationDataStore - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private const string primSelect = "select * from prims"; - private const string shapeSelect = "select * from primshapes"; - private const string itemsSelect = "select * from primitems"; - private const string terrainSelect = "select * from terrain limit 1"; - private const string landSelect = "select * from land"; - private const string landAccessListSelect = "select distinct * from landaccesslist"; - private const string regionbanListSelect = "select * from regionban"; - private const string regionSettingsSelect = "select * from regionsettings"; - - private DataSet ds; - private SqliteDataAdapter primDa; - private SqliteDataAdapter shapeDa; - private SqliteDataAdapter itemsDa; - private SqliteDataAdapter terrainDa; - private SqliteDataAdapter landDa; - private SqliteDataAdapter landAccessListDa; - private SqliteDataAdapter regionSettingsDa; - - private SqliteConnection m_conn; - - private String m_connectionString; - - public SQLiteSimulationData() - { - } - - public SQLiteSimulationData(string connectionString) - { - Initialise(connectionString); - } - - // Temporary attribute while this is experimental - - /*********************************************************************** - * - * Public Interface Functions - * - **********************************************************************/ - - /// - /// - /// Initialises RegionData Interface - /// Loads and initialises a new SQLite connection and maintains it. - /// - /// - /// the connection string - public void Initialise(string connectionString) - { - m_connectionString = connectionString; - - ds = new DataSet(); - - m_log.Info("[REGION DB]: Sqlite - connecting: " + connectionString); - m_conn = new SqliteConnection(m_connectionString); - m_conn.Open(); - - - - SqliteCommand primSelectCmd = new SqliteCommand(primSelect, m_conn); - primDa = new SqliteDataAdapter(primSelectCmd); - // SqliteCommandBuilder primCb = new SqliteCommandBuilder(primDa); - - SqliteCommand shapeSelectCmd = new SqliteCommand(shapeSelect, m_conn); - shapeDa = new SqliteDataAdapter(shapeSelectCmd); - // SqliteCommandBuilder shapeCb = new SqliteCommandBuilder(shapeDa); - - SqliteCommand itemsSelectCmd = new SqliteCommand(itemsSelect, m_conn); - itemsDa = new SqliteDataAdapter(itemsSelectCmd); - - SqliteCommand terrainSelectCmd = new SqliteCommand(terrainSelect, m_conn); - terrainDa = new SqliteDataAdapter(terrainSelectCmd); - - SqliteCommand landSelectCmd = new SqliteCommand(landSelect, m_conn); - landDa = new SqliteDataAdapter(landSelectCmd); - - SqliteCommand landAccessListSelectCmd = new SqliteCommand(landAccessListSelect, m_conn); - landAccessListDa = new SqliteDataAdapter(landAccessListSelectCmd); - - SqliteCommand regionSettingsSelectCmd = new SqliteCommand(regionSettingsSelect, m_conn); - regionSettingsDa = new SqliteDataAdapter(regionSettingsSelectCmd); - // This actually does the roll forward assembly stuff - Assembly assem = GetType().Assembly; - Migration m = new Migration(m_conn, assem, "RegionStore"); - m.Update(); - - lock (ds) - { - ds.Tables.Add(createPrimTable()); - setupPrimCommands(primDa, m_conn); - primDa.Fill(ds.Tables["prims"]); - - ds.Tables.Add(createShapeTable()); - setupShapeCommands(shapeDa, m_conn); - - ds.Tables.Add(createItemsTable()); - setupItemsCommands(itemsDa, m_conn); - itemsDa.Fill(ds.Tables["primitems"]); - - ds.Tables.Add(createTerrainTable()); - setupTerrainCommands(terrainDa, m_conn); - - ds.Tables.Add(createLandTable()); - setupLandCommands(landDa, m_conn); - - ds.Tables.Add(createLandAccessListTable()); - setupLandAccessCommands(landAccessListDa, m_conn); - - ds.Tables.Add(createRegionSettingsTable()); - - setupRegionSettingsCommands(regionSettingsDa, m_conn); - - // WORKAROUND: This is a work around for sqlite on - // windows, which gets really unhappy with blob columns - // that have no sample data in them. At some point we - // need to actually find a proper way to handle this. - try - { - shapeDa.Fill(ds.Tables["primshapes"]); - } - catch (Exception) - { - m_log.Info("[REGION DB]: Caught fill error on primshapes table"); - } - - try - { - terrainDa.Fill(ds.Tables["terrain"]); - } - catch (Exception) - { - m_log.Info("[REGION DB]: Caught fill error on terrain table"); - } - - try - { - landDa.Fill(ds.Tables["land"]); - } - catch (Exception) - { - m_log.Info("[REGION DB]: Caught fill error on land table"); - } - - try - { - landAccessListDa.Fill(ds.Tables["landaccesslist"]); - } - catch (Exception) - { - m_log.Info("[REGION DB]: Caught fill error on landaccesslist table"); - } - - try - { - regionSettingsDa.Fill(ds.Tables["regionsettings"]); - } - catch (Exception) - { - m_log.Info("[REGION DB]: Caught fill error on regionsettings table"); - } - return; - } - } - - public void Dispose() - { - if (m_conn != null) - { - m_conn.Close(); - m_conn = null; - } - if (ds != null) - { - ds.Dispose(); - ds = null; - } - if (primDa != null) - { - primDa.Dispose(); - primDa = null; - } - if (shapeDa != null) - { - shapeDa.Dispose(); - shapeDa = null; - } - if (itemsDa != null) - { - itemsDa.Dispose(); - itemsDa = null; - } - if (terrainDa != null) - { - terrainDa.Dispose(); - terrainDa = null; - } - if (landDa != null) - { - landDa.Dispose(); - landDa = null; - } - if (landAccessListDa != null) - { - landAccessListDa.Dispose(); - landAccessListDa = null; - } - if (regionSettingsDa != null) - { - regionSettingsDa.Dispose(); - regionSettingsDa = null; - } - } - - public void StoreRegionSettings(RegionSettings rs) - { - lock (ds) - { - DataTable regionsettings = ds.Tables["regionsettings"]; - - DataRow settingsRow = regionsettings.Rows.Find(rs.RegionUUID.ToString()); - if (settingsRow == null) - { - settingsRow = regionsettings.NewRow(); - fillRegionSettingsRow(settingsRow, rs); - regionsettings.Rows.Add(settingsRow); - } - else - { - fillRegionSettingsRow(settingsRow, rs); - } - - Commit(); - } - } - public RegionLightShareData LoadRegionWindlightSettings(UUID regionUUID) - { - //This connector doesn't support the windlight module yet - //Return default LL windlight settings - return new RegionLightShareData(); - } - public void RemoveRegionWindlightSettings(UUID regionID) - { - } - public void StoreRegionWindlightSettings(RegionLightShareData wl) - { - //This connector doesn't support the windlight module yet - } - public RegionSettings LoadRegionSettings(UUID regionUUID) - { - lock (ds) - { - DataTable regionsettings = ds.Tables["regionsettings"]; - - string searchExp = "regionUUID = '" + regionUUID.ToString() + "'"; - DataRow[] rawsettings = regionsettings.Select(searchExp); - if (rawsettings.Length == 0) - { - RegionSettings rs = new RegionSettings(); - rs.RegionUUID = regionUUID; - rs.OnSave += StoreRegionSettings; - - StoreRegionSettings(rs); - - return rs; - } - DataRow row = rawsettings[0]; - - RegionSettings newSettings = buildRegionSettings(row); - newSettings.OnSave += StoreRegionSettings; - - return newSettings; - } - } - - /// - /// Adds an object into region storage - /// - /// the object - /// the region UUID - public void StoreObject(SceneObjectGroup obj, UUID regionUUID) - { - uint flags = obj.RootPart.GetEffectiveObjectFlags(); - - // Eligibility check - // - if ((flags & (uint)PrimFlags.Temporary) != 0) - return; - if ((flags & (uint)PrimFlags.TemporaryOnRez) != 0) - return; - - lock (ds) - { - foreach (SceneObjectPart prim in obj.Parts) - { -// m_log.Info("[REGION DB]: Adding obj: " + obj.UUID + " to region: " + regionUUID); - addPrim(prim, obj.UUID, regionUUID); - } - } - - Commit(); - // m_log.Info("[Dump of prims]: " + ds.GetXml()); - } - - /// - /// Removes an object from region storage - /// - /// the object - /// the region UUID - public void RemoveObject(UUID obj, UUID regionUUID) - { - // m_log.InfoFormat("[REGION DB]: Removing obj: {0} from region: {1}", obj.Guid, regionUUID); - - DataTable prims = ds.Tables["prims"]; - DataTable shapes = ds.Tables["primshapes"]; - - string selectExp = "SceneGroupID = '" + obj + "' and RegionUUID = '" + regionUUID + "'"; - lock (ds) - { - DataRow[] primRows = prims.Select(selectExp); - foreach (DataRow row in primRows) - { - // Remove shape rows - UUID uuid = new UUID((string) row["UUID"]); - DataRow shapeRow = shapes.Rows.Find(uuid.ToString()); - if (shapeRow != null) - { - shapeRow.Delete(); - } - - RemoveItems(uuid); - - // Remove prim row - row.Delete(); - } - } - - Commit(); - } - - /// - /// Remove all persisted items of the given prim. - /// The caller must acquire the necessrary synchronization locks and commit or rollback changes. - /// - /// The item UUID - private void RemoveItems(UUID uuid) - { - DataTable items = ds.Tables["primitems"]; - - String sql = String.Format("primID = '{0}'", uuid); - DataRow[] itemRows = items.Select(sql); - - foreach (DataRow itemRow in itemRows) - { - itemRow.Delete(); - } - } - - /// - /// Load persisted objects from region storage. - /// - /// The region UUID - /// List of loaded groups - public List LoadObjects(UUID regionUUID) - { - Dictionary createdObjects = new Dictionary(); - - List retvals = new List(); - - DataTable prims = ds.Tables["prims"]; - DataTable shapes = ds.Tables["primshapes"]; - - string byRegion = "RegionUUID = '" + regionUUID + "'"; - - lock (ds) - { - DataRow[] primsForRegion = prims.Select(byRegion); - m_log.Info("[REGION DB]: Loaded " + primsForRegion.Length + " prims for region: " + regionUUID); - - // First, create all groups - foreach (DataRow primRow in primsForRegion) - { - try - { - SceneObjectPart prim = null; - - string uuid = (string) primRow["UUID"]; - string objID = (string) primRow["SceneGroupID"]; - - if (uuid == objID) //is new SceneObjectGroup ? - { - prim = buildPrim(primRow); - DataRow shapeRow = shapes.Rows.Find(prim.UUID.ToString()); - if (shapeRow != null) - { - prim.Shape = buildShape(shapeRow); - } - else - { - m_log.Info( - "[REGION DB]: No shape found for prim in storage, so setting default box shape"); - prim.Shape = PrimitiveBaseShape.Default; - } - - SceneObjectGroup group = new SceneObjectGroup(prim); - createdObjects.Add(group.UUID, group); - retvals.Add(group); - LoadItems(prim); - } - } - catch (Exception e) - { - m_log.Error("[REGION DB]: Failed create prim object in new group, exception and data follows"); - m_log.Info("[REGION DB]: " + e.ToString()); - foreach (DataColumn col in prims.Columns) - { - m_log.Info("[REGION DB]: Col: " + col.ColumnName + " => " + primRow[col]); - } - } - } - - // Now fill the groups with part data - foreach (DataRow primRow in primsForRegion) - { - try - { - SceneObjectPart prim = null; - - string uuid = (string) primRow["UUID"]; - string objID = (string) primRow["SceneGroupID"]; - if (uuid != objID) //is new SceneObjectGroup ? - { - prim = buildPrim(primRow); - DataRow shapeRow = shapes.Rows.Find(prim.UUID.ToString()); - if (shapeRow != null) - { - prim.Shape = buildShape(shapeRow); - } - else - { - m_log.Warn( - "[REGION DB]: No shape found for prim in storage, so setting default box shape"); - prim.Shape = PrimitiveBaseShape.Default; - } - - createdObjects[new UUID(objID)].AddPart(prim); - LoadItems(prim); - } - } - catch (Exception e) - { - m_log.Error("[REGION DB]: Failed create prim object in group, exception and data follows"); - m_log.Info("[REGION DB]: " + e.ToString()); - foreach (DataColumn col in prims.Columns) - { - m_log.Info("[REGION DB]: Col: " + col.ColumnName + " => " + primRow[col]); - } - } - } - } - return retvals; - } - - /// - /// Load in a prim's persisted inventory. - /// - /// the prim - private void LoadItems(SceneObjectPart prim) - { - //m_log.DebugFormat("[DATASTORE]: Loading inventory for {0}, {1}", prim.Name, prim.UUID); - - DataTable dbItems = ds.Tables["primitems"]; - String sql = String.Format("primID = '{0}'", prim.UUID.ToString()); - DataRow[] dbItemRows = dbItems.Select(sql); - IList inventory = new List(); - - foreach (DataRow row in dbItemRows) - { - TaskInventoryItem item = buildItem(row); - inventory.Add(item); - - //m_log.DebugFormat("[DATASTORE]: Restored item {0}, {1}", item.Name, item.ItemID); - } - - prim.Inventory.RestoreInventoryItems(inventory); - } - - /// - /// Store a terrain revision in region storage - /// - /// terrain heightfield - /// region UUID - public void StoreTerrain(double[,] ter, UUID regionID) - { - lock (ds) - { - int revision = Util.UnixTimeSinceEpoch(); - - // This is added to get rid of the infinitely growing - // terrain databases which negatively impact on SQLite - // over time. Before reenabling this feature there - // needs to be a limitter put on the number of - // revisions in the database, as this old - // implementation is a DOS attack waiting to happen. - - using ( - SqliteCommand cmd = - new SqliteCommand("delete from terrain where RegionUUID=:RegionUUID and Revision <= :Revision", - m_conn)) - { - cmd.Parameters.Add(new SqliteParameter(":RegionUUID", regionID.ToString())); - cmd.Parameters.Add(new SqliteParameter(":Revision", revision)); - cmd.ExecuteNonQuery(); - } - - // the following is an work around for .NET. The perf - // issues associated with it aren't as bad as you think. - m_log.Info("[REGION DB]: Storing terrain revision r" + revision.ToString()); - String sql = "insert into terrain(RegionUUID, Revision, Heightfield)" + - " values(:RegionUUID, :Revision, :Heightfield)"; - - using (SqliteCommand cmd = new SqliteCommand(sql, m_conn)) - { - cmd.Parameters.Add(new SqliteParameter(":RegionUUID", regionID.ToString())); - cmd.Parameters.Add(new SqliteParameter(":Revision", revision)); - cmd.Parameters.Add(new SqliteParameter(":Heightfield", serializeTerrain(ter))); - cmd.ExecuteNonQuery(); - } - } - } - - /// - /// Load the latest terrain revision from region storage - /// - /// the region UUID - /// Heightfield data - public double[,] LoadTerrain(UUID regionID) - { - lock (ds) - { - double[,] terret = new double[(int)Constants.RegionSize, (int)Constants.RegionSize]; - terret.Initialize(); - - String sql = "select RegionUUID, Revision, Heightfield from terrain" + - " where RegionUUID=:RegionUUID order by Revision desc"; - - using (SqliteCommand cmd = new SqliteCommand(sql, m_conn)) - { - cmd.Parameters.Add(new SqliteParameter(":RegionUUID", regionID.ToString())); - - using (IDataReader row = cmd.ExecuteReader()) - { - int rev = 0; - if (row.Read()) - { - // TODO: put this into a function - using (MemoryStream str = new MemoryStream((byte[])row["Heightfield"])) - { - using (BinaryReader br = new BinaryReader(str)) - { - for (int x = 0; x < (int)Constants.RegionSize; x++) - { - for (int y = 0; y < (int)Constants.RegionSize; y++) - { - terret[x, y] = br.ReadDouble(); - } - } - } - } - rev = (int) row["Revision"]; - } - else - { - m_log.Info("[REGION DB]: No terrain found for region"); - return null; - } - - m_log.Info("[REGION DB]: Loaded terrain revision r" + rev.ToString()); - } - } - return terret; - } - } - - /// - /// - /// - /// - public void RemoveLandObject(UUID globalID) - { - lock (ds) - { - // Can't use blanket SQL statements when using SqlAdapters unless you re-read the data into the adapter - // after you're done. - // replaced below code with the SqliteAdapter version. - //using (SqliteCommand cmd = new SqliteCommand("delete from land where UUID=:UUID", m_conn)) - //{ - // cmd.Parameters.Add(new SqliteParameter(":UUID", globalID.ToString())); - // cmd.ExecuteNonQuery(); - //} - - //using (SqliteCommand cmd = new SqliteCommand("delete from landaccesslist where LandUUID=:UUID", m_conn)) - //{ - // cmd.Parameters.Add(new SqliteParameter(":UUID", globalID.ToString())); - // cmd.ExecuteNonQuery(); - //} - - DataTable land = ds.Tables["land"]; - DataTable landaccesslist = ds.Tables["landaccesslist"]; - DataRow landRow = land.Rows.Find(globalID.ToString()); - if (landRow != null) - { - landRow.Delete(); - land.Rows.Remove(landRow); - } - List rowsToDelete = new List(); - foreach (DataRow rowToCheck in landaccesslist.Rows) - { - if (rowToCheck["LandUUID"].ToString() == globalID.ToString()) - rowsToDelete.Add(rowToCheck); - } - for (int iter = 0; iter < rowsToDelete.Count; iter++) - { - rowsToDelete[iter].Delete(); - landaccesslist.Rows.Remove(rowsToDelete[iter]); - } - - - } - Commit(); - } - - /// - /// - /// - /// - public void StoreLandObject(ILandObject parcel) - { - lock (ds) - { - DataTable land = ds.Tables["land"]; - DataTable landaccesslist = ds.Tables["landaccesslist"]; - - DataRow landRow = land.Rows.Find(parcel.LandData.GlobalID.ToString()); - if (landRow == null) - { - landRow = land.NewRow(); - fillLandRow(landRow, parcel.LandData, parcel.RegionUUID); - land.Rows.Add(landRow); - } - else - { - fillLandRow(landRow, parcel.LandData, parcel.RegionUUID); - } - - // I know this caused someone issues before, but OpenSim is unusable if we leave this stuff around - //using (SqliteCommand cmd = new SqliteCommand("delete from landaccesslist where LandUUID=:LandUUID", m_conn)) - //{ - // cmd.Parameters.Add(new SqliteParameter(":LandUUID", parcel.LandData.GlobalID.ToString())); - // cmd.ExecuteNonQuery(); - -// } - - // This is the slower.. but more appropriate thing to do - - // We can't modify the table with direct queries before calling Commit() and re-filling them. - List rowsToDelete = new List(); - foreach (DataRow rowToCheck in landaccesslist.Rows) - { - if (rowToCheck["LandUUID"].ToString() == parcel.LandData.GlobalID.ToString()) - rowsToDelete.Add(rowToCheck); - } - for (int iter = 0; iter < rowsToDelete.Count; iter++) - { - rowsToDelete[iter].Delete(); - landaccesslist.Rows.Remove(rowsToDelete[iter]); - } - rowsToDelete.Clear(); - foreach (ParcelManager.ParcelAccessEntry entry in parcel.LandData.ParcelAccessList) - { - DataRow newAccessRow = landaccesslist.NewRow(); - fillLandAccessRow(newAccessRow, entry, parcel.LandData.GlobalID); - landaccesslist.Rows.Add(newAccessRow); - } - } - - Commit(); - } - - /// - /// - /// - /// - /// - public List LoadLandObjects(UUID regionUUID) - { - List landDataForRegion = new List(); - lock (ds) - { - DataTable land = ds.Tables["land"]; - DataTable landaccesslist = ds.Tables["landaccesslist"]; - string searchExp = "RegionUUID = '" + regionUUID + "'"; - DataRow[] rawDataForRegion = land.Select(searchExp); - foreach (DataRow rawDataLand in rawDataForRegion) - { - LandData newLand = buildLandData(rawDataLand); - string accessListSearchExp = "LandUUID = '" + newLand.GlobalID + "'"; - DataRow[] rawDataForLandAccessList = landaccesslist.Select(accessListSearchExp); - foreach (DataRow rawDataLandAccess in rawDataForLandAccessList) - { - newLand.ParcelAccessList.Add(buildLandAccessData(rawDataLandAccess)); - } - - landDataForRegion.Add(newLand); - } - } - return landDataForRegion; - } - - /// - /// - /// - public void Commit() - { - lock (ds) - { - primDa.Update(ds, "prims"); - shapeDa.Update(ds, "primshapes"); - - itemsDa.Update(ds, "primitems"); - - terrainDa.Update(ds, "terrain"); - landDa.Update(ds, "land"); - landAccessListDa.Update(ds, "landaccesslist"); - try - { - regionSettingsDa.Update(ds, "regionsettings"); - } - catch (SqliteExecutionException SqlEx) - { - if (SqlEx.Message.Contains("logic error")) - { - throw new Exception( - "There was a SQL error or connection string configuration error when saving the region settings. This could be a bug, it could also happen if ConnectionString is defined in the [DatabaseService] section of StandaloneCommon.ini in the config_include folder. This could also happen if the config_include folder doesn't exist or if the OpenSim.ini [Architecture] section isn't set. If this is your first time running OpenSimulator, please restart the simulator and bug a developer to fix this!", - SqlEx); - } - else - { - throw SqlEx; - } - } - ds.AcceptChanges(); - } - } - - /// - /// See - /// - public void Shutdown() - { - Commit(); - } - - /*********************************************************************** - * - * Database Definition Functions - * - * This should be db agnostic as we define them in ADO.NET terms - * - **********************************************************************/ - - /// - /// - /// - /// - /// - /// - private static void createCol(DataTable dt, string name, Type type) - { - DataColumn col = new DataColumn(name, type); - dt.Columns.Add(col); - } - - /// - /// Creates the "terrain" table - /// - /// terrain table DataTable - private static DataTable createTerrainTable() - { - DataTable terrain = new DataTable("terrain"); - - createCol(terrain, "RegionUUID", typeof (String)); - createCol(terrain, "Revision", typeof (Int32)); - createCol(terrain, "Heightfield", typeof (Byte[])); - - return terrain; - } - - /// - /// Creates the "prims" table - /// - /// prim table DataTable - private static DataTable createPrimTable() - { - DataTable prims = new DataTable("prims"); - - createCol(prims, "UUID", typeof (String)); - createCol(prims, "RegionUUID", typeof (String)); - createCol(prims, "CreationDate", typeof (Int32)); - createCol(prims, "Name", typeof (String)); - createCol(prims, "SceneGroupID", typeof (String)); - // various text fields - createCol(prims, "Text", typeof (String)); - createCol(prims, "ColorR", typeof (Int32)); - createCol(prims, "ColorG", typeof (Int32)); - createCol(prims, "ColorB", typeof (Int32)); - createCol(prims, "ColorA", typeof (Int32)); - createCol(prims, "Description", typeof (String)); - createCol(prims, "SitName", typeof (String)); - createCol(prims, "TouchName", typeof (String)); - // permissions - createCol(prims, "ObjectFlags", typeof (Int32)); - createCol(prims, "CreatorID", typeof (String)); - createCol(prims, "OwnerID", typeof (String)); - createCol(prims, "GroupID", typeof (String)); - createCol(prims, "LastOwnerID", typeof (String)); - createCol(prims, "OwnerMask", typeof (Int32)); - createCol(prims, "NextOwnerMask", typeof (Int32)); - createCol(prims, "GroupMask", typeof (Int32)); - createCol(prims, "EveryoneMask", typeof (Int32)); - createCol(prims, "BaseMask", typeof (Int32)); - // vectors - createCol(prims, "PositionX", typeof (Double)); - createCol(prims, "PositionY", typeof (Double)); - createCol(prims, "PositionZ", typeof (Double)); - createCol(prims, "GroupPositionX", typeof (Double)); - createCol(prims, "GroupPositionY", typeof (Double)); - createCol(prims, "GroupPositionZ", typeof (Double)); - createCol(prims, "VelocityX", typeof (Double)); - createCol(prims, "VelocityY", typeof (Double)); - createCol(prims, "VelocityZ", typeof (Double)); - createCol(prims, "AngularVelocityX", typeof (Double)); - createCol(prims, "AngularVelocityY", typeof (Double)); - createCol(prims, "AngularVelocityZ", typeof (Double)); - createCol(prims, "AccelerationX", typeof (Double)); - createCol(prims, "AccelerationY", typeof (Double)); - createCol(prims, "AccelerationZ", typeof (Double)); - // quaternions - createCol(prims, "RotationX", typeof (Double)); - createCol(prims, "RotationY", typeof (Double)); - createCol(prims, "RotationZ", typeof (Double)); - createCol(prims, "RotationW", typeof (Double)); - - // sit target - createCol(prims, "SitTargetOffsetX", typeof (Double)); - createCol(prims, "SitTargetOffsetY", typeof (Double)); - createCol(prims, "SitTargetOffsetZ", typeof (Double)); - - createCol(prims, "SitTargetOrientW", typeof (Double)); - createCol(prims, "SitTargetOrientX", typeof (Double)); - createCol(prims, "SitTargetOrientY", typeof (Double)); - createCol(prims, "SitTargetOrientZ", typeof (Double)); - - createCol(prims, "PayPrice", typeof(Int32)); - createCol(prims, "PayButton1", typeof(Int32)); - createCol(prims, "PayButton2", typeof(Int32)); - createCol(prims, "PayButton3", typeof(Int32)); - createCol(prims, "PayButton4", typeof(Int32)); - - createCol(prims, "LoopedSound", typeof(String)); - createCol(prims, "LoopedSoundGain", typeof(Double)); - createCol(prims, "TextureAnimation", typeof(String)); - createCol(prims, "ParticleSystem", typeof(String)); - - createCol(prims, "OmegaX", typeof(Double)); - createCol(prims, "OmegaY", typeof(Double)); - createCol(prims, "OmegaZ", typeof(Double)); - - createCol(prims, "CameraEyeOffsetX", typeof(Double)); - createCol(prims, "CameraEyeOffsetY", typeof(Double)); - createCol(prims, "CameraEyeOffsetZ", typeof(Double)); - - createCol(prims, "CameraAtOffsetX", typeof(Double)); - createCol(prims, "CameraAtOffsetY", typeof(Double)); - createCol(prims, "CameraAtOffsetZ", typeof(Double)); - - createCol(prims, "ForceMouselook", typeof(Int16)); - - createCol(prims, "ScriptAccessPin", typeof(Int32)); - - createCol(prims, "AllowedDrop", typeof(Int16)); - createCol(prims, "DieAtEdge", typeof(Int16)); - - createCol(prims, "SalePrice", typeof(Int32)); - createCol(prims, "SaleType", typeof(Int16)); - - // click action - createCol(prims, "ClickAction", typeof (Byte)); - - createCol(prims, "Material", typeof(Byte)); - - createCol(prims, "CollisionSound", typeof(String)); - createCol(prims, "CollisionSoundVolume", typeof(Double)); - - createCol(prims, "VolumeDetect", typeof(Int16)); - - // Add in contraints - prims.PrimaryKey = new DataColumn[] {prims.Columns["UUID"]}; - - return prims; - } - - /// - /// Creates "primshapes" table - /// - /// shape table DataTable - private static DataTable createShapeTable() - { - DataTable shapes = new DataTable("primshapes"); - createCol(shapes, "UUID", typeof (String)); - // shape is an enum - createCol(shapes, "Shape", typeof (Int32)); - // vectors - createCol(shapes, "ScaleX", typeof (Double)); - createCol(shapes, "ScaleY", typeof (Double)); - createCol(shapes, "ScaleZ", typeof (Double)); - // paths - createCol(shapes, "PCode", typeof (Int32)); - createCol(shapes, "PathBegin", typeof (Int32)); - createCol(shapes, "PathEnd", typeof (Int32)); - createCol(shapes, "PathScaleX", typeof (Int32)); - createCol(shapes, "PathScaleY", typeof (Int32)); - createCol(shapes, "PathShearX", typeof (Int32)); - createCol(shapes, "PathShearY", typeof (Int32)); - createCol(shapes, "PathSkew", typeof (Int32)); - createCol(shapes, "PathCurve", typeof (Int32)); - createCol(shapes, "PathRadiusOffset", typeof (Int32)); - createCol(shapes, "PathRevolutions", typeof (Int32)); - createCol(shapes, "PathTaperX", typeof (Int32)); - createCol(shapes, "PathTaperY", typeof (Int32)); - createCol(shapes, "PathTwist", typeof (Int32)); - createCol(shapes, "PathTwistBegin", typeof (Int32)); - // profile - createCol(shapes, "ProfileBegin", typeof (Int32)); - createCol(shapes, "ProfileEnd", typeof (Int32)); - createCol(shapes, "ProfileCurve", typeof (Int32)); - createCol(shapes, "ProfileHollow", typeof (Int32)); - createCol(shapes, "State", typeof(Int32)); - // text TODO: this isn't right, but I'm not sure the right - // way to specify this as a blob atm - createCol(shapes, "Texture", typeof (Byte[])); - createCol(shapes, "ExtraParams", typeof (Byte[])); - - shapes.PrimaryKey = new DataColumn[] {shapes.Columns["UUID"]}; - - return shapes; - } - - /// - /// creates "primitems" table - /// - /// item table DataTable - private static DataTable createItemsTable() - { - DataTable items = new DataTable("primitems"); - - createCol(items, "itemID", typeof (String)); - createCol(items, "primID", typeof (String)); - createCol(items, "assetID", typeof (String)); - createCol(items, "parentFolderID", typeof (String)); - - createCol(items, "invType", typeof (Int32)); - createCol(items, "assetType", typeof (Int32)); - - createCol(items, "name", typeof (String)); - createCol(items, "description", typeof (String)); - - createCol(items, "creationDate", typeof (Int64)); - createCol(items, "creatorID", typeof (String)); - createCol(items, "ownerID", typeof (String)); - createCol(items, "lastOwnerID", typeof (String)); - createCol(items, "groupID", typeof (String)); - - createCol(items, "nextPermissions", typeof (UInt32)); - createCol(items, "currentPermissions", typeof (UInt32)); - createCol(items, "basePermissions", typeof (UInt32)); - createCol(items, "everyonePermissions", typeof (UInt32)); - createCol(items, "groupPermissions", typeof (UInt32)); - createCol(items, "flags", typeof (UInt32)); - - items.PrimaryKey = new DataColumn[] { items.Columns["itemID"] }; - - return items; - } - - /// - /// Creates "land" table - /// - /// land table DataTable - private static DataTable createLandTable() - { - DataTable land = new DataTable("land"); - createCol(land, "UUID", typeof (String)); - createCol(land, "RegionUUID", typeof (String)); - createCol(land, "LocalLandID", typeof (UInt32)); - - // Bitmap is a byte[512] - createCol(land, "Bitmap", typeof (Byte[])); - - createCol(land, "Name", typeof (String)); - createCol(land, "Desc", typeof (String)); - createCol(land, "OwnerUUID", typeof (String)); - createCol(land, "IsGroupOwned", typeof (Boolean)); - createCol(land, "Area", typeof (Int32)); - createCol(land, "AuctionID", typeof (Int32)); //Unemplemented - createCol(land, "Category", typeof (Int32)); //Enum OpenMetaverse.Parcel.ParcelCategory - createCol(land, "ClaimDate", typeof (Int32)); - createCol(land, "ClaimPrice", typeof (Int32)); - createCol(land, "GroupUUID", typeof (string)); - createCol(land, "SalePrice", typeof (Int32)); - createCol(land, "LandStatus", typeof (Int32)); //Enum. OpenMetaverse.Parcel.ParcelStatus - createCol(land, "LandFlags", typeof (UInt32)); - createCol(land, "LandingType", typeof (Byte)); - createCol(land, "MediaAutoScale", typeof (Byte)); - createCol(land, "MediaTextureUUID", typeof (String)); - createCol(land, "MediaURL", typeof (String)); - createCol(land, "MusicURL", typeof (String)); - createCol(land, "PassHours", typeof (Double)); - createCol(land, "PassPrice", typeof (UInt32)); - createCol(land, "SnapshotUUID", typeof (String)); - createCol(land, "UserLocationX", typeof (Double)); - createCol(land, "UserLocationY", typeof (Double)); - createCol(land, "UserLocationZ", typeof (Double)); - createCol(land, "UserLookAtX", typeof (Double)); - createCol(land, "UserLookAtY", typeof (Double)); - createCol(land, "UserLookAtZ", typeof (Double)); - createCol(land, "AuthbuyerID", typeof(String)); - createCol(land, "OtherCleanTime", typeof(Int32)); - - land.PrimaryKey = new DataColumn[] {land.Columns["UUID"]}; - - return land; - } - - /// - /// create "landaccesslist" table - /// - /// Landacceslist DataTable - private static DataTable createLandAccessListTable() - { - DataTable landaccess = new DataTable("landaccesslist"); - createCol(landaccess, "LandUUID", typeof (String)); - createCol(landaccess, "AccessUUID", typeof (String)); - createCol(landaccess, "Flags", typeof (UInt32)); - - return landaccess; - } - - private static DataTable createRegionSettingsTable() - { - DataTable regionsettings = new DataTable("regionsettings"); - createCol(regionsettings, "regionUUID", typeof(String)); - createCol(regionsettings, "block_terraform", typeof (Int32)); - createCol(regionsettings, "block_fly", typeof (Int32)); - createCol(regionsettings, "allow_damage", typeof (Int32)); - createCol(regionsettings, "restrict_pushing", typeof (Int32)); - createCol(regionsettings, "allow_land_resell", typeof (Int32)); - createCol(regionsettings, "allow_land_join_divide", typeof (Int32)); - createCol(regionsettings, "block_show_in_search", typeof (Int32)); - createCol(regionsettings, "agent_limit", typeof (Int32)); - createCol(regionsettings, "object_bonus", typeof (Double)); - createCol(regionsettings, "maturity", typeof (Int32)); - createCol(regionsettings, "disable_scripts", typeof (Int32)); - createCol(regionsettings, "disable_collisions", typeof (Int32)); - createCol(regionsettings, "disable_physics", typeof (Int32)); - createCol(regionsettings, "terrain_texture_1", typeof(String)); - createCol(regionsettings, "terrain_texture_2", typeof(String)); - createCol(regionsettings, "terrain_texture_3", typeof(String)); - createCol(regionsettings, "terrain_texture_4", typeof(String)); - createCol(regionsettings, "elevation_1_nw", typeof (Double)); - createCol(regionsettings, "elevation_2_nw", typeof (Double)); - createCol(regionsettings, "elevation_1_ne", typeof (Double)); - createCol(regionsettings, "elevation_2_ne", typeof (Double)); - createCol(regionsettings, "elevation_1_se", typeof (Double)); - createCol(regionsettings, "elevation_2_se", typeof (Double)); - createCol(regionsettings, "elevation_1_sw", typeof (Double)); - createCol(regionsettings, "elevation_2_sw", typeof (Double)); - createCol(regionsettings, "water_height", typeof (Double)); - createCol(regionsettings, "terrain_raise_limit", typeof (Double)); - createCol(regionsettings, "terrain_lower_limit", typeof (Double)); - createCol(regionsettings, "use_estate_sun", typeof (Int32)); - createCol(regionsettings, "sandbox", typeof (Int32)); - createCol(regionsettings, "sunvectorx",typeof (Double)); - createCol(regionsettings, "sunvectory",typeof (Double)); - createCol(regionsettings, "sunvectorz",typeof (Double)); - createCol(regionsettings, "fixed_sun", typeof (Int32)); - createCol(regionsettings, "sun_position", typeof (Double)); - createCol(regionsettings, "covenant", typeof(String)); - regionsettings.PrimaryKey = new DataColumn[] { regionsettings.Columns["regionUUID"] }; - return regionsettings; - } - - /*********************************************************************** - * - * Convert between ADO.NET <=> OpenSim Objects - * - * These should be database independant - * - **********************************************************************/ - - /// - /// - /// - /// - /// - private SceneObjectPart buildPrim(DataRow row) - { - // Code commented. Uncomment to test the unit test inline. - - // The unit test mentions this commented code for the purposes - // of debugging a unit test failure - - // SceneObjectGroup sog = new SceneObjectGroup(); - // SceneObjectPart sop = new SceneObjectPart(); - // sop.LocalId = 1; - // sop.Name = "object1"; - // sop.Description = "object1"; - // sop.Text = ""; - // sop.SitName = ""; - // sop.TouchName = ""; - // sop.UUID = UUID.Random(); - // sop.Shape = PrimitiveBaseShape.Default; - // sog.SetRootPart(sop); - // Add breakpoint in above line. Check sop fields. - - // TODO: this doesn't work yet because something more - // interesting has to be done to actually get these values - // back out. Not enough time to figure it out yet. - - SceneObjectPart prim = new SceneObjectPart(); - prim.UUID = new UUID((String) row["UUID"]); - // explicit conversion of integers is required, which sort - // of sucks. No idea if there is a shortcut here or not. - prim.CreationDate = Convert.ToInt32(row["CreationDate"]); - prim.Name = row["Name"] == DBNull.Value ? string.Empty : (string)row["Name"]; - // various text fields - prim.Text = (String) row["Text"]; - prim.Color = Color.FromArgb(Convert.ToInt32(row["ColorA"]), - Convert.ToInt32(row["ColorR"]), - Convert.ToInt32(row["ColorG"]), - Convert.ToInt32(row["ColorB"])); - prim.Description = (String) row["Description"]; - prim.SitName = (String) row["SitName"]; - prim.TouchName = (String) row["TouchName"]; - // permissions - prim.Flags = (PrimFlags)Convert.ToUInt32(row["ObjectFlags"]); - prim.CreatorIdentification = (String) row["CreatorID"]; - prim.OwnerID = new UUID((String) row["OwnerID"]); - prim.GroupID = new UUID((String) row["GroupID"]); - prim.LastOwnerID = new UUID((String) row["LastOwnerID"]); - prim.OwnerMask = Convert.ToUInt32(row["OwnerMask"]); - prim.NextOwnerMask = Convert.ToUInt32(row["NextOwnerMask"]); - prim.GroupMask = Convert.ToUInt32(row["GroupMask"]); - prim.EveryoneMask = Convert.ToUInt32(row["EveryoneMask"]); - prim.BaseMask = Convert.ToUInt32(row["BaseMask"]); - // vectors - prim.OffsetPosition = new Vector3( - Convert.ToSingle(row["PositionX"]), - Convert.ToSingle(row["PositionY"]), - Convert.ToSingle(row["PositionZ"]) - ); - prim.GroupPosition = new Vector3( - Convert.ToSingle(row["GroupPositionX"]), - Convert.ToSingle(row["GroupPositionY"]), - Convert.ToSingle(row["GroupPositionZ"]) - ); - prim.Velocity = new Vector3( - Convert.ToSingle(row["VelocityX"]), - Convert.ToSingle(row["VelocityY"]), - Convert.ToSingle(row["VelocityZ"]) - ); - prim.AngularVelocity = new Vector3( - Convert.ToSingle(row["AngularVelocityX"]), - Convert.ToSingle(row["AngularVelocityY"]), - Convert.ToSingle(row["AngularVelocityZ"]) - ); - prim.Acceleration = new Vector3( - Convert.ToSingle(row["AccelerationX"]), - Convert.ToSingle(row["AccelerationY"]), - Convert.ToSingle(row["AccelerationZ"]) - ); - // quaternions - prim.RotationOffset = new Quaternion( - Convert.ToSingle(row["RotationX"]), - Convert.ToSingle(row["RotationY"]), - Convert.ToSingle(row["RotationZ"]), - Convert.ToSingle(row["RotationW"]) - ); - - prim.SitTargetPositionLL = new Vector3( - Convert.ToSingle(row["SitTargetOffsetX"]), - Convert.ToSingle(row["SitTargetOffsetY"]), - Convert.ToSingle(row["SitTargetOffsetZ"])); - prim.SitTargetOrientationLL = new Quaternion( - Convert.ToSingle( - row["SitTargetOrientX"]), - Convert.ToSingle( - row["SitTargetOrientY"]), - Convert.ToSingle( - row["SitTargetOrientZ"]), - Convert.ToSingle( - row["SitTargetOrientW"])); - - prim.ClickAction = Convert.ToByte(row["ClickAction"]); - prim.PayPrice[0] = Convert.ToInt32(row["PayPrice"]); - prim.PayPrice[1] = Convert.ToInt32(row["PayButton1"]); - prim.PayPrice[2] = Convert.ToInt32(row["PayButton2"]); - prim.PayPrice[3] = Convert.ToInt32(row["PayButton3"]); - prim.PayPrice[4] = Convert.ToInt32(row["PayButton4"]); - - prim.Sound = new UUID(row["LoopedSound"].ToString()); - prim.SoundGain = Convert.ToSingle(row["LoopedSoundGain"]); - prim.SoundFlags = 1; // If it's persisted at all, it's looped - - if (!row.IsNull("TextureAnimation")) - prim.TextureAnimation = Convert.FromBase64String(row["TextureAnimation"].ToString()); - if (!row.IsNull("ParticleSystem")) - prim.ParticleSystem = Convert.FromBase64String(row["ParticleSystem"].ToString()); - - prim.AngularVelocity = new Vector3( - Convert.ToSingle(row["OmegaX"]), - Convert.ToSingle(row["OmegaY"]), - Convert.ToSingle(row["OmegaZ"]) - ); - - prim.SetCameraEyeOffset(new Vector3( - Convert.ToSingle(row["CameraEyeOffsetX"]), - Convert.ToSingle(row["CameraEyeOffsetY"]), - Convert.ToSingle(row["CameraEyeOffsetZ"]) - )); - - prim.SetCameraAtOffset(new Vector3( - Convert.ToSingle(row["CameraAtOffsetX"]), - Convert.ToSingle(row["CameraAtOffsetY"]), - Convert.ToSingle(row["CameraAtOffsetZ"]) - )); - - if (Convert.ToInt16(row["ForceMouselook"]) != 0) - prim.SetForceMouselook(true); - - prim.ScriptAccessPin = Convert.ToInt32(row["ScriptAccessPin"]); - - if (Convert.ToInt16(row["AllowedDrop"]) != 0) - prim.AllowedDrop = true; - - if (Convert.ToInt16(row["DieAtEdge"]) != 0) - prim.DIE_AT_EDGE = true; - - prim.SalePrice = Convert.ToInt32(row["SalePrice"]); - prim.ObjectSaleType = Convert.ToByte(row["SaleType"]); - - prim.Material = Convert.ToByte(row["Material"]); - - prim.CollisionSound = new UUID(row["CollisionSound"].ToString()); - prim.CollisionSoundVolume = Convert.ToSingle(row["CollisionSoundVolume"]); - - if (Convert.ToInt16(row["VolumeDetect"]) != 0) - prim.VolumeDetectActive = true; - - return prim; - } - - /// - /// Build a prim inventory item from the persisted data. - /// - /// - /// - private static TaskInventoryItem buildItem(DataRow row) - { - TaskInventoryItem taskItem = new TaskInventoryItem(); - - taskItem.ItemID = new UUID((String)row["itemID"]); - taskItem.ParentPartID = new UUID((String)row["primID"]); - taskItem.AssetID = new UUID((String)row["assetID"]); - taskItem.ParentID = new UUID((String)row["parentFolderID"]); - - taskItem.InvType = Convert.ToInt32(row["invType"]); - taskItem.Type = Convert.ToInt32(row["assetType"]); - - taskItem.Name = (String)row["name"]; - taskItem.Description = (String)row["description"]; - taskItem.CreationDate = Convert.ToUInt32(row["creationDate"]); - taskItem.CreatorIdentification = (String)row["creatorID"]; - taskItem.OwnerID = new UUID((String)row["ownerID"]); - taskItem.LastOwnerID = new UUID((String)row["lastOwnerID"]); - taskItem.GroupID = new UUID((String)row["groupID"]); - - taskItem.NextPermissions = Convert.ToUInt32(row["nextPermissions"]); - taskItem.CurrentPermissions = Convert.ToUInt32(row["currentPermissions"]); - taskItem.BasePermissions = Convert.ToUInt32(row["basePermissions"]); - taskItem.EveryonePermissions = Convert.ToUInt32(row["everyonePermissions"]); - taskItem.GroupPermissions = Convert.ToUInt32(row["groupPermissions"]); - taskItem.Flags = Convert.ToUInt32(row["flags"]); - - return taskItem; - } - - /// - /// Build a Land Data from the persisted data. - /// - /// - /// - private LandData buildLandData(DataRow row) - { - LandData newData = new LandData(); - - newData.GlobalID = new UUID((String) row["UUID"]); - newData.LocalID = Convert.ToInt32(row["LocalLandID"]); - - // Bitmap is a byte[512] - newData.Bitmap = (Byte[]) row["Bitmap"]; - - newData.Name = (String) row["Name"]; - newData.Description = (String) row["Desc"]; - newData.OwnerID = (UUID)(String) row["OwnerUUID"]; - newData.IsGroupOwned = (Boolean) row["IsGroupOwned"]; - newData.Area = Convert.ToInt32(row["Area"]); - newData.AuctionID = Convert.ToUInt32(row["AuctionID"]); //Unemplemented - newData.Category = (ParcelCategory) Convert.ToInt32(row["Category"]); - //Enum OpenMetaverse.Parcel.ParcelCategory - newData.ClaimDate = Convert.ToInt32(row["ClaimDate"]); - newData.ClaimPrice = Convert.ToInt32(row["ClaimPrice"]); - newData.GroupID = new UUID((String) row["GroupUUID"]); - newData.SalePrice = Convert.ToInt32(row["SalePrice"]); - newData.Status = (ParcelStatus) Convert.ToInt32(row["LandStatus"]); - //Enum. OpenMetaverse.Parcel.ParcelStatus - newData.Flags = Convert.ToUInt32(row["LandFlags"]); - newData.LandingType = (Byte) row["LandingType"]; - newData.MediaAutoScale = (Byte) row["MediaAutoScale"]; - newData.MediaID = new UUID((String) row["MediaTextureUUID"]); - newData.MediaURL = (String) row["MediaURL"]; - newData.MusicURL = (String) row["MusicURL"]; - newData.PassHours = Convert.ToSingle(row["PassHours"]); - newData.PassPrice = Convert.ToInt32(row["PassPrice"]); - newData.SnapshotID = (UUID)(String) row["SnapshotUUID"]; - try - { - - newData.UserLocation = - new Vector3(Convert.ToSingle(row["UserLocationX"]), Convert.ToSingle(row["UserLocationY"]), - Convert.ToSingle(row["UserLocationZ"])); - newData.UserLookAt = - new Vector3(Convert.ToSingle(row["UserLookAtX"]), Convert.ToSingle(row["UserLookAtY"]), - Convert.ToSingle(row["UserLookAtZ"])); - - } - catch (InvalidCastException) - { - m_log.ErrorFormat("[PARCEL]: unable to get parcel telehub settings for {1}", newData.Name); - newData.UserLocation = Vector3.Zero; - newData.UserLookAt = Vector3.Zero; - } - newData.ParcelAccessList = new List(); - UUID authBuyerID = UUID.Zero; - - UUID.TryParse((string)row["AuthbuyerID"], out authBuyerID); - - newData.OtherCleanTime = Convert.ToInt32(row["OtherCleanTime"]); - - return newData; - } - - private RegionSettings buildRegionSettings(DataRow row) - { - RegionSettings newSettings = new RegionSettings(); - - newSettings.RegionUUID = new UUID((string) row["regionUUID"]); - newSettings.BlockTerraform = Convert.ToBoolean(row["block_terraform"]); - newSettings.AllowDamage = Convert.ToBoolean(row["allow_damage"]); - newSettings.BlockFly = Convert.ToBoolean(row["block_fly"]); - newSettings.RestrictPushing = Convert.ToBoolean(row["restrict_pushing"]); - newSettings.AllowLandResell = Convert.ToBoolean(row["allow_land_resell"]); - newSettings.AllowLandJoinDivide = Convert.ToBoolean(row["allow_land_join_divide"]); - newSettings.BlockShowInSearch = Convert.ToBoolean(row["block_show_in_search"]); - newSettings.AgentLimit = Convert.ToInt32(row["agent_limit"]); - newSettings.ObjectBonus = Convert.ToDouble(row["object_bonus"]); - newSettings.Maturity = Convert.ToInt32(row["maturity"]); - newSettings.DisableScripts = Convert.ToBoolean(row["disable_scripts"]); - newSettings.DisableCollisions = Convert.ToBoolean(row["disable_collisions"]); - newSettings.DisablePhysics = Convert.ToBoolean(row["disable_physics"]); - newSettings.TerrainTexture1 = new UUID((String) row["terrain_texture_1"]); - newSettings.TerrainTexture2 = new UUID((String) row["terrain_texture_2"]); - newSettings.TerrainTexture3 = new UUID((String) row["terrain_texture_3"]); - newSettings.TerrainTexture4 = new UUID((String) row["terrain_texture_4"]); - newSettings.Elevation1NW = Convert.ToDouble(row["elevation_1_nw"]); - newSettings.Elevation2NW = Convert.ToDouble(row["elevation_2_nw"]); - newSettings.Elevation1NE = Convert.ToDouble(row["elevation_1_ne"]); - newSettings.Elevation2NE = Convert.ToDouble(row["elevation_2_ne"]); - newSettings.Elevation1SE = Convert.ToDouble(row["elevation_1_se"]); - newSettings.Elevation2SE = Convert.ToDouble(row["elevation_2_se"]); - newSettings.Elevation1SW = Convert.ToDouble(row["elevation_1_sw"]); - newSettings.Elevation2SW = Convert.ToDouble(row["elevation_2_sw"]); - newSettings.WaterHeight = Convert.ToDouble(row["water_height"]); - newSettings.TerrainRaiseLimit = Convert.ToDouble(row["terrain_raise_limit"]); - newSettings.TerrainLowerLimit = Convert.ToDouble(row["terrain_lower_limit"]); - newSettings.UseEstateSun = Convert.ToBoolean(row["use_estate_sun"]); - newSettings.Sandbox = Convert.ToBoolean(row["sandbox"]); - newSettings.SunVector = new Vector3 ( - Convert.ToSingle(row["sunvectorx"]), - Convert.ToSingle(row["sunvectory"]), - Convert.ToSingle(row["sunvectorz"]) - ); - newSettings.FixedSun = Convert.ToBoolean(row["fixed_sun"]); - newSettings.SunPosition = Convert.ToDouble(row["sun_position"]); - newSettings.Covenant = new UUID((String) row["covenant"]); - - return newSettings; - } - - /// - /// Build a land access entry from the persisted data. - /// - /// - /// - private static ParcelManager.ParcelAccessEntry buildLandAccessData(DataRow row) - { - ParcelManager.ParcelAccessEntry entry = new ParcelManager.ParcelAccessEntry(); - entry.AgentID = new UUID((string) row["AccessUUID"]); - entry.Flags = (AccessList) row["Flags"]; - entry.Time = new DateTime(); - return entry; - } - - /// - /// - /// - /// - /// - private static Array serializeTerrain(double[,] val) - { - MemoryStream str = new MemoryStream(((int)Constants.RegionSize * (int)Constants.RegionSize) *sizeof (double)); - BinaryWriter bw = new BinaryWriter(str); - - // TODO: COMPATIBILITY - Add byte-order conversions - for (int x = 0; x < (int)Constants.RegionSize; x++) - for (int y = 0; y < (int)Constants.RegionSize; y++) - bw.Write(val[x, y]); - - return str.ToArray(); - } - -// private void fillTerrainRow(DataRow row, UUID regionUUID, int rev, double[,] val) -// { -// row["RegionUUID"] = regionUUID; -// row["Revision"] = rev; - - // MemoryStream str = new MemoryStream(((int)Constants.RegionSize * (int)Constants.RegionSize)*sizeof (double)); -// BinaryWriter bw = new BinaryWriter(str); - -// // TODO: COMPATIBILITY - Add byte-order conversions - // for (int x = 0; x < (int)Constants.RegionSize; x++) - // for (int y = 0; y < (int)Constants.RegionSize; y++) -// bw.Write(val[x, y]); - -// row["Heightfield"] = str.ToArray(); -// } - - /// - /// - /// - /// - /// - /// - /// - private static void fillPrimRow(DataRow row, SceneObjectPart prim, UUID sceneGroupID, UUID regionUUID) - { - row["UUID"] = prim.UUID.ToString(); - row["RegionUUID"] = regionUUID.ToString(); - row["CreationDate"] = prim.CreationDate; - row["Name"] = prim.Name; - row["SceneGroupID"] = sceneGroupID.ToString(); - // the UUID of the root part for this SceneObjectGroup - // various text fields - row["Text"] = prim.Text; - row["Description"] = prim.Description; - row["SitName"] = prim.SitName; - row["TouchName"] = prim.TouchName; - // permissions - row["ObjectFlags"] = (uint)prim.Flags; - row["CreatorID"] = prim.CreatorIdentification.ToString(); - row["OwnerID"] = prim.OwnerID.ToString(); - row["GroupID"] = prim.GroupID.ToString(); - row["LastOwnerID"] = prim.LastOwnerID.ToString(); - row["OwnerMask"] = prim.OwnerMask; - row["NextOwnerMask"] = prim.NextOwnerMask; - row["GroupMask"] = prim.GroupMask; - row["EveryoneMask"] = prim.EveryoneMask; - row["BaseMask"] = prim.BaseMask; - // vectors - row["PositionX"] = prim.OffsetPosition.X; - row["PositionY"] = prim.OffsetPosition.Y; - row["PositionZ"] = prim.OffsetPosition.Z; - row["GroupPositionX"] = prim.GroupPosition.X; - row["GroupPositionY"] = prim.GroupPosition.Y; - row["GroupPositionZ"] = prim.GroupPosition.Z; - row["VelocityX"] = prim.Velocity.X; - row["VelocityY"] = prim.Velocity.Y; - row["VelocityZ"] = prim.Velocity.Z; - row["AngularVelocityX"] = prim.AngularVelocity.X; - row["AngularVelocityY"] = prim.AngularVelocity.Y; - row["AngularVelocityZ"] = prim.AngularVelocity.Z; - row["AccelerationX"] = prim.Acceleration.X; - row["AccelerationY"] = prim.Acceleration.Y; - row["AccelerationZ"] = prim.Acceleration.Z; - // quaternions - row["RotationX"] = prim.RotationOffset.X; - row["RotationY"] = prim.RotationOffset.Y; - row["RotationZ"] = prim.RotationOffset.Z; - row["RotationW"] = prim.RotationOffset.W; - - // Sit target - Vector3 sitTargetPos = prim.SitTargetPositionLL; - row["SitTargetOffsetX"] = sitTargetPos.X; - row["SitTargetOffsetY"] = sitTargetPos.Y; - row["SitTargetOffsetZ"] = sitTargetPos.Z; - - Quaternion sitTargetOrient = prim.SitTargetOrientationLL; - row["SitTargetOrientW"] = sitTargetOrient.W; - row["SitTargetOrientX"] = sitTargetOrient.X; - row["SitTargetOrientY"] = sitTargetOrient.Y; - row["SitTargetOrientZ"] = sitTargetOrient.Z; - row["ColorR"] = Convert.ToInt32(prim.Color.R); - row["ColorG"] = Convert.ToInt32(prim.Color.G); - row["ColorB"] = Convert.ToInt32(prim.Color.B); - row["ColorA"] = Convert.ToInt32(prim.Color.A); - row["PayPrice"] = prim.PayPrice[0]; - row["PayButton1"] = prim.PayPrice[1]; - row["PayButton2"] = prim.PayPrice[2]; - row["PayButton3"] = prim.PayPrice[3]; - row["PayButton4"] = prim.PayPrice[4]; - - - row["TextureAnimation"] = Convert.ToBase64String(prim.TextureAnimation); - row["ParticleSystem"] = Convert.ToBase64String(prim.ParticleSystem); - - row["OmegaX"] = prim.AngularVelocity.X; - row["OmegaY"] = prim.AngularVelocity.Y; - row["OmegaZ"] = prim.AngularVelocity.Z; - - row["CameraEyeOffsetX"] = prim.GetCameraEyeOffset().X; - row["CameraEyeOffsetY"] = prim.GetCameraEyeOffset().Y; - row["CameraEyeOffsetZ"] = prim.GetCameraEyeOffset().Z; - - row["CameraAtOffsetX"] = prim.GetCameraAtOffset().X; - row["CameraAtOffsetY"] = prim.GetCameraAtOffset().Y; - row["CameraAtOffsetZ"] = prim.GetCameraAtOffset().Z; - - - if ((prim.SoundFlags & 1) != 0) // Looped - { - row["LoopedSound"] = prim.Sound.ToString(); - row["LoopedSoundGain"] = prim.SoundGain; - } - else - { - row["LoopedSound"] = UUID.Zero.ToString(); - row["LoopedSoundGain"] = 0.0f; - } - - if (prim.GetForceMouselook()) - row["ForceMouselook"] = 1; - else - row["ForceMouselook"] = 0; - - row["ScriptAccessPin"] = prim.ScriptAccessPin; - - if (prim.AllowedDrop) - row["AllowedDrop"] = 1; - else - row["AllowedDrop"] = 0; - - if (prim.DIE_AT_EDGE) - row["DieAtEdge"] = 1; - else - row["DieAtEdge"] = 0; - - row["SalePrice"] = prim.SalePrice; - row["SaleType"] = Convert.ToInt16(prim.ObjectSaleType); - - // click action - row["ClickAction"] = prim.ClickAction; - - row["SalePrice"] = prim.SalePrice; - row["Material"] = prim.Material; - - row["CollisionSound"] = prim.CollisionSound.ToString(); - row["CollisionSoundVolume"] = prim.CollisionSoundVolume; - if (prim.VolumeDetectActive) - row["VolumeDetect"] = 1; - else - row["VolumeDetect"] = 0; - - } - - /// - /// - /// - /// - /// - private static void fillItemRow(DataRow row, TaskInventoryItem taskItem) - { - row["itemID"] = taskItem.ItemID.ToString(); - row["primID"] = taskItem.ParentPartID.ToString(); - row["assetID"] = taskItem.AssetID.ToString(); - row["parentFolderID"] = taskItem.ParentID.ToString(); - - row["invType"] = taskItem.InvType; - row["assetType"] = taskItem.Type; - - row["name"] = taskItem.Name; - row["description"] = taskItem.Description; - row["creationDate"] = taskItem.CreationDate; - row["creatorID"] = taskItem.CreatorIdentification.ToString(); - row["ownerID"] = taskItem.OwnerID.ToString(); - row["lastOwnerID"] = taskItem.LastOwnerID.ToString(); - row["groupID"] = taskItem.GroupID.ToString(); - row["nextPermissions"] = taskItem.NextPermissions; - row["currentPermissions"] = taskItem.CurrentPermissions; - row["basePermissions"] = taskItem.BasePermissions; - row["everyonePermissions"] = taskItem.EveryonePermissions; - row["groupPermissions"] = taskItem.GroupPermissions; - row["flags"] = taskItem.Flags; - } - - /// - /// - /// - /// - /// - /// - private static void fillLandRow(DataRow row, LandData land, UUID regionUUID) - { - row["UUID"] = land.GlobalID.ToString(); - row["RegionUUID"] = regionUUID.ToString(); - row["LocalLandID"] = land.LocalID; - - // Bitmap is a byte[512] - row["Bitmap"] = land.Bitmap; - - row["Name"] = land.Name; - row["Desc"] = land.Description; - row["OwnerUUID"] = land.OwnerID.ToString(); - row["IsGroupOwned"] = land.IsGroupOwned; - row["Area"] = land.Area; - row["AuctionID"] = land.AuctionID; //Unemplemented - row["Category"] = land.Category; //Enum OpenMetaverse.Parcel.ParcelCategory - row["ClaimDate"] = land.ClaimDate; - row["ClaimPrice"] = land.ClaimPrice; - row["GroupUUID"] = land.GroupID.ToString(); - row["SalePrice"] = land.SalePrice; - row["LandStatus"] = land.Status; //Enum. OpenMetaverse.Parcel.ParcelStatus - row["LandFlags"] = land.Flags; - row["LandingType"] = land.LandingType; - row["MediaAutoScale"] = land.MediaAutoScale; - row["MediaTextureUUID"] = land.MediaID.ToString(); - row["MediaURL"] = land.MediaURL; - row["MusicURL"] = land.MusicURL; - row["PassHours"] = land.PassHours; - row["PassPrice"] = land.PassPrice; - row["SnapshotUUID"] = land.SnapshotID.ToString(); - row["UserLocationX"] = land.UserLocation.X; - row["UserLocationY"] = land.UserLocation.Y; - row["UserLocationZ"] = land.UserLocation.Z; - row["UserLookAtX"] = land.UserLookAt.X; - row["UserLookAtY"] = land.UserLookAt.Y; - row["UserLookAtZ"] = land.UserLookAt.Z; - row["AuthbuyerID"] = land.AuthBuyerID.ToString(); - row["OtherCleanTime"] = land.OtherCleanTime; - } - - /// - /// - /// - /// - /// - /// - private static void fillLandAccessRow(DataRow row, ParcelManager.ParcelAccessEntry entry, UUID parcelID) - { - row["LandUUID"] = parcelID.ToString(); - row["AccessUUID"] = entry.AgentID.ToString(); - row["Flags"] = entry.Flags; - } - - private static void fillRegionSettingsRow(DataRow row, RegionSettings settings) - { - row["regionUUID"] = settings.RegionUUID.ToString(); - row["block_terraform"] = settings.BlockTerraform; - row["block_fly"] = settings.BlockFly; - row["allow_damage"] = settings.AllowDamage; - row["restrict_pushing"] = settings.RestrictPushing; - row["allow_land_resell"] = settings.AllowLandResell; - row["allow_land_join_divide"] = settings.AllowLandJoinDivide; - row["block_show_in_search"] = settings.BlockShowInSearch; - row["agent_limit"] = settings.AgentLimit; - row["object_bonus"] = settings.ObjectBonus; - row["maturity"] = settings.Maturity; - row["disable_scripts"] = settings.DisableScripts; - row["disable_collisions"] = settings.DisableCollisions; - row["disable_physics"] = settings.DisablePhysics; - row["terrain_texture_1"] = settings.TerrainTexture1.ToString(); - row["terrain_texture_2"] = settings.TerrainTexture2.ToString(); - row["terrain_texture_3"] = settings.TerrainTexture3.ToString(); - row["terrain_texture_4"] = settings.TerrainTexture4.ToString(); - row["elevation_1_nw"] = settings.Elevation1NW; - row["elevation_2_nw"] = settings.Elevation2NW; - row["elevation_1_ne"] = settings.Elevation1NE; - row["elevation_2_ne"] = settings.Elevation2NE; - row["elevation_1_se"] = settings.Elevation1SE; - row["elevation_2_se"] = settings.Elevation2SE; - row["elevation_1_sw"] = settings.Elevation1SW; - row["elevation_2_sw"] = settings.Elevation2SW; - row["water_height"] = settings.WaterHeight; - row["terrain_raise_limit"] = settings.TerrainRaiseLimit; - row["terrain_lower_limit"] = settings.TerrainLowerLimit; - row["use_estate_sun"] = settings.UseEstateSun; - row["Sandbox"] = settings.Sandbox; // database uses upper case S for sandbox - row["sunvectorx"] = settings.SunVector.X; - row["sunvectory"] = settings.SunVector.Y; - row["sunvectorz"] = settings.SunVector.Z; - row["fixed_sun"] = settings.FixedSun; - row["sun_position"] = settings.SunPosition; - row["covenant"] = settings.Covenant.ToString(); - } - - /// - /// - /// - /// - /// - private PrimitiveBaseShape buildShape(DataRow row) - { - PrimitiveBaseShape s = new PrimitiveBaseShape(); - s.Scale = new Vector3( - Convert.ToSingle(row["ScaleX"]), - Convert.ToSingle(row["ScaleY"]), - Convert.ToSingle(row["ScaleZ"]) - ); - // paths - s.PCode = Convert.ToByte(row["PCode"]); - s.PathBegin = Convert.ToUInt16(row["PathBegin"]); - s.PathEnd = Convert.ToUInt16(row["PathEnd"]); - s.PathScaleX = Convert.ToByte(row["PathScaleX"]); - s.PathScaleY = Convert.ToByte(row["PathScaleY"]); - s.PathShearX = Convert.ToByte(row["PathShearX"]); - s.PathShearY = Convert.ToByte(row["PathShearY"]); - s.PathSkew = Convert.ToSByte(row["PathSkew"]); - s.PathCurve = Convert.ToByte(row["PathCurve"]); - s.PathRadiusOffset = Convert.ToSByte(row["PathRadiusOffset"]); - s.PathRevolutions = Convert.ToByte(row["PathRevolutions"]); - s.PathTaperX = Convert.ToSByte(row["PathTaperX"]); - s.PathTaperY = Convert.ToSByte(row["PathTaperY"]); - s.PathTwist = Convert.ToSByte(row["PathTwist"]); - s.PathTwistBegin = Convert.ToSByte(row["PathTwistBegin"]); - // profile - s.ProfileBegin = Convert.ToUInt16(row["ProfileBegin"]); - s.ProfileEnd = Convert.ToUInt16(row["ProfileEnd"]); - s.ProfileCurve = Convert.ToByte(row["ProfileCurve"]); - s.ProfileHollow = Convert.ToUInt16(row["ProfileHollow"]); - s.State = Convert.ToByte(row["State"]); - - byte[] textureEntry = (byte[])row["Texture"]; - s.TextureEntry = textureEntry; - - s.ExtraParams = (byte[]) row["ExtraParams"]; - return s; - } - - /// - /// - /// - /// - /// - private static void fillShapeRow(DataRow row, SceneObjectPart prim) - { - PrimitiveBaseShape s = prim.Shape; - row["UUID"] = prim.UUID.ToString(); - // shape is an enum - row["Shape"] = 0; - // vectors - row["ScaleX"] = s.Scale.X; - row["ScaleY"] = s.Scale.Y; - row["ScaleZ"] = s.Scale.Z; - // paths - row["PCode"] = s.PCode; - row["PathBegin"] = s.PathBegin; - row["PathEnd"] = s.PathEnd; - row["PathScaleX"] = s.PathScaleX; - row["PathScaleY"] = s.PathScaleY; - row["PathShearX"] = s.PathShearX; - row["PathShearY"] = s.PathShearY; - row["PathSkew"] = s.PathSkew; - row["PathCurve"] = s.PathCurve; - row["PathRadiusOffset"] = s.PathRadiusOffset; - row["PathRevolutions"] = s.PathRevolutions; - row["PathTaperX"] = s.PathTaperX; - row["PathTaperY"] = s.PathTaperY; - row["PathTwist"] = s.PathTwist; - row["PathTwistBegin"] = s.PathTwistBegin; - // profile - row["ProfileBegin"] = s.ProfileBegin; - row["ProfileEnd"] = s.ProfileEnd; - row["ProfileCurve"] = s.ProfileCurve; - row["ProfileHollow"] = s.ProfileHollow; - row["State"] = s.State; - - row["Texture"] = s.TextureEntry; - row["ExtraParams"] = s.ExtraParams; - } - - /// - /// - /// - /// - /// - /// - private void addPrim(SceneObjectPart prim, UUID sceneGroupID, UUID regionUUID) - { - - DataTable prims = ds.Tables["prims"]; - DataTable shapes = ds.Tables["primshapes"]; - - DataRow primRow = prims.Rows.Find(prim.UUID.ToString()); - if (primRow == null) - { - primRow = prims.NewRow(); - fillPrimRow(primRow, prim, sceneGroupID, regionUUID); - prims.Rows.Add(primRow); - } - else - { - fillPrimRow(primRow, prim, sceneGroupID, regionUUID); - } - - DataRow shapeRow = shapes.Rows.Find(prim.UUID.ToString()); - if (shapeRow == null) - { - shapeRow = shapes.NewRow(); - fillShapeRow(shapeRow, prim); - shapes.Rows.Add(shapeRow); - } - else - { - fillShapeRow(shapeRow, prim); - } - } - - /// - /// - /// - /// - public void StorePrimInventory(UUID primID, ICollection items) - { - m_log.InfoFormat("[REGION DB]: Entered StorePrimInventory with prim ID {0}", primID); - - DataTable dbItems = ds.Tables["primitems"]; - - // For now, we're just going to crudely remove all the previous inventory items - // no matter whether they have changed or not, and replace them with the current set. - lock (ds) - { - RemoveItems(primID); - - // repalce with current inventory details - foreach (TaskInventoryItem newItem in items) - { -// m_log.InfoFormat( -// "[DATASTORE]: ", -// "Adding item {0}, {1} to prim ID {2}", -// newItem.Name, newItem.ItemID, newItem.ParentPartID); - - DataRow newItemRow = dbItems.NewRow(); - fillItemRow(newItemRow, newItem); - dbItems.Rows.Add(newItemRow); - } - } - - Commit(); - } - - /*********************************************************************** - * - * SQL Statement Creation Functions - * - * These functions create SQL statements for update, insert, and create. - * They can probably be factored later to have a db independant - * portion and a db specific portion - * - **********************************************************************/ - - /// - /// Create an insert command - /// - /// table name - /// data table - /// the created command - /// - /// This is subtle enough to deserve some commentary. - /// Instead of doing *lots* and *lots of hardcoded strings - /// for database definitions we'll use the fact that - /// realistically all insert statements look like "insert - /// into A(b, c) values(:b, :c) on the parameterized query - /// front. If we just have a list of b, c, etc... we can - /// generate these strings instead of typing them out. - /// - private static SqliteCommand createInsertCommand(string table, DataTable dt) - { - string[] cols = new string[dt.Columns.Count]; - for (int i = 0; i < dt.Columns.Count; i++) - { - DataColumn col = dt.Columns[i]; - cols[i] = col.ColumnName; - } - - string sql = "insert into " + table + "("; - sql += String.Join(", ", cols); - // important, the first ':' needs to be here, the rest get added in the join - sql += ") values (:"; - sql += String.Join(", :", cols); - sql += ")"; - SqliteCommand cmd = new SqliteCommand(sql); - - // this provides the binding for all our parameters, so - // much less code than it used to be - foreach (DataColumn col in dt.Columns) - { - cmd.Parameters.Add(createSqliteParameter(col.ColumnName, col.DataType)); - } - return cmd; - } - - - /// - /// create an update command - /// - /// table name - /// - /// - /// the created command - private static SqliteCommand createUpdateCommand(string table, string pk, DataTable dt) - { - string sql = "update " + table + " set "; - string subsql = String.Empty; - foreach (DataColumn col in dt.Columns) - { - if (subsql.Length > 0) - { - // a map function would rock so much here - subsql += ", "; - } - subsql += col.ColumnName + "= :" + col.ColumnName; - } - sql += subsql; - sql += " where " + pk; - SqliteCommand cmd = new SqliteCommand(sql); - - // this provides the binding for all our parameters, so - // much less code than it used to be - - foreach (DataColumn col in dt.Columns) - { - cmd.Parameters.Add(createSqliteParameter(col.ColumnName, col.DataType)); - } - return cmd; - } - - /// - /// create an update command - /// - /// table name - /// - /// - /// the created command - private static SqliteCommand createUpdateCommand(string table, string pk1, string pk2, DataTable dt) - { - string sql = "update " + table + " set "; - string subsql = String.Empty; - foreach (DataColumn col in dt.Columns) - { - if (subsql.Length > 0) - { - // a map function would rock so much here - subsql += ", "; - } - subsql += col.ColumnName + "= :" + col.ColumnName; - } - sql += subsql; - sql += " where " + pk1 + " and " + pk2; - SqliteCommand cmd = new SqliteCommand(sql); - - // this provides the binding for all our parameters, so - // much less code than it used to be - - foreach (DataColumn col in dt.Columns) - { - cmd.Parameters.Add(createSqliteParameter(col.ColumnName, col.DataType)); - } - return cmd; - } - - /// - /// - /// - /// Data Table - /// - // private static string defineTable(DataTable dt) - // { - // string sql = "create table " + dt.TableName + "("; - // string subsql = String.Empty; - // foreach (DataColumn col in dt.Columns) - // { - // if (subsql.Length > 0) - // { - // // a map function would rock so much here - // subsql += ",\n"; - // } - // subsql += col.ColumnName + " " + sqliteType(col.DataType); - // if (dt.PrimaryKey.Length > 0 && col == dt.PrimaryKey[0]) - // { - // subsql += " primary key"; - // } - // } - // sql += subsql; - // sql += ")"; - // return sql; - // } - - /*********************************************************************** - * - * Database Binding functions - * - * These will be db specific due to typing, and minor differences - * in databases. - * - **********************************************************************/ - - /// - /// This is a convenience function that collapses 5 repetitive - /// lines for defining SqliteParameters to 2 parameters: - /// column name and database type. - /// - /// It assumes certain conventions like :param as the param - /// name to replace in parametrized queries, and that source - /// version is always current version, both of which are fine - /// for us. - /// - ///a built sqlite parameter - private static SqliteParameter createSqliteParameter(string name, Type type) - { - SqliteParameter param = new SqliteParameter(); - param.ParameterName = ":" + name; - param.DbType = dbtypeFromType(type); - param.SourceColumn = name; - param.SourceVersion = DataRowVersion.Current; - return param; - } - - /// - /// - /// - /// - /// - private void setupPrimCommands(SqliteDataAdapter da, SqliteConnection conn) - { - da.InsertCommand = createInsertCommand("prims", ds.Tables["prims"]); - da.InsertCommand.Connection = conn; - - da.UpdateCommand = createUpdateCommand("prims", "UUID=:UUID", ds.Tables["prims"]); - da.UpdateCommand.Connection = conn; - - SqliteCommand delete = new SqliteCommand("delete from prims where UUID = :UUID"); - delete.Parameters.Add(createSqliteParameter("UUID", typeof (String))); - delete.Connection = conn; - da.DeleteCommand = delete; - } - - /// - /// - /// - /// - /// - private void setupItemsCommands(SqliteDataAdapter da, SqliteConnection conn) - { - da.InsertCommand = createInsertCommand("primitems", ds.Tables["primitems"]); - da.InsertCommand.Connection = conn; - - da.UpdateCommand = createUpdateCommand("primitems", "itemID = :itemID", ds.Tables["primitems"]); - da.UpdateCommand.Connection = conn; - - SqliteCommand delete = new SqliteCommand("delete from primitems where itemID = :itemID"); - delete.Parameters.Add(createSqliteParameter("itemID", typeof (String))); - delete.Connection = conn; - da.DeleteCommand = delete; - } - - /// - /// - /// - /// - /// - private void setupTerrainCommands(SqliteDataAdapter da, SqliteConnection conn) - { - da.InsertCommand = createInsertCommand("terrain", ds.Tables["terrain"]); - da.InsertCommand.Connection = conn; - } - - /// - /// - /// - /// - /// - private void setupLandCommands(SqliteDataAdapter da, SqliteConnection conn) - { - da.InsertCommand = createInsertCommand("land", ds.Tables["land"]); - da.InsertCommand.Connection = conn; - - da.UpdateCommand = createUpdateCommand("land", "UUID=:UUID", ds.Tables["land"]); - da.UpdateCommand.Connection = conn; - - SqliteCommand delete = new SqliteCommand("delete from land where UUID=:UUID"); - delete.Parameters.Add(createSqliteParameter("UUID", typeof(String))); - da.DeleteCommand = delete; - da.DeleteCommand.Connection = conn; - } - - /// - /// - /// - /// - /// - private void setupLandAccessCommands(SqliteDataAdapter da, SqliteConnection conn) - { - da.InsertCommand = createInsertCommand("landaccesslist", ds.Tables["landaccesslist"]); - da.InsertCommand.Connection = conn; - - da.UpdateCommand = createUpdateCommand("landaccesslist", "LandUUID=:landUUID", "AccessUUID=:AccessUUID", ds.Tables["landaccesslist"]); - da.UpdateCommand.Connection = conn; - - SqliteCommand delete = new SqliteCommand("delete from landaccesslist where LandUUID= :LandUUID and AccessUUID= :AccessUUID"); - delete.Parameters.Add(createSqliteParameter("LandUUID", typeof(String))); - delete.Parameters.Add(createSqliteParameter("AccessUUID", typeof(String))); - da.DeleteCommand = delete; - da.DeleteCommand.Connection = conn; - - } - - private void setupRegionSettingsCommands(SqliteDataAdapter da, SqliteConnection conn) - { - da.InsertCommand = createInsertCommand("regionsettings", ds.Tables["regionsettings"]); - da.InsertCommand.Connection = conn; - da.UpdateCommand = createUpdateCommand("regionsettings", "regionUUID=:regionUUID", ds.Tables["regionsettings"]); - da.UpdateCommand.Connection = conn; - } - - /// - /// - /// - /// - /// - private void setupShapeCommands(SqliteDataAdapter da, SqliteConnection conn) - { - da.InsertCommand = createInsertCommand("primshapes", ds.Tables["primshapes"]); - da.InsertCommand.Connection = conn; - - da.UpdateCommand = createUpdateCommand("primshapes", "UUID=:UUID", ds.Tables["primshapes"]); - da.UpdateCommand.Connection = conn; - - SqliteCommand delete = new SqliteCommand("delete from primshapes where UUID = :UUID"); - delete.Parameters.Add(createSqliteParameter("UUID", typeof (String))); - delete.Connection = conn; - da.DeleteCommand = delete; - } - - /*********************************************************************** - * - * Type conversion functions - * - **********************************************************************/ - - /// - /// Type conversion function - /// - /// - /// - private static DbType dbtypeFromType(Type type) - { - if (type == typeof (String)) - { - return DbType.String; - } - else if (type == typeof (Int32)) - { - return DbType.Int32; - } - else if (type == typeof (Double)) - { - return DbType.Double; - } - else if (type == typeof (Byte)) - { - return DbType.Byte; - } - else if (type == typeof (Double)) - { - return DbType.Double; - } - else if (type == typeof (Byte[])) - { - return DbType.Binary; - } - else - { - return DbType.String; - } - } - - } -} diff --git a/OpenSim/Data/SQLiteLegacy/SQLiteUserAccountData.cs b/OpenSim/Data/SQLiteLegacy/SQLiteUserAccountData.cs deleted file mode 100644 index 27553c61eb..0000000000 --- a/OpenSim/Data/SQLiteLegacy/SQLiteUserAccountData.cs +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data; -using OpenMetaverse; -using OpenSim.Framework; -using Mono.Data.SqliteClient; - -namespace OpenSim.Data.SQLiteLegacy -{ - public class SQLiteUserAccountData : SQLiteGenericTableHandler, IUserAccountData - { - public SQLiteUserAccountData(string connectionString, string realm) - : base(connectionString, realm, "UserAccount") - { - } - - public UserAccountData[] GetUsers(UUID scopeID, string query) - { - string[] words = query.Split(new char[] {' '}); - - for (int i = 0 ; i < words.Length ; i++) - { - if (words[i].Length < 3) - { - if (i != words.Length - 1) - Array.Copy(words, i + 1, words, i, words.Length - i - 1); - Array.Resize(ref words, words.Length - 1); - } - } - - if (words.Length == 0) - return new UserAccountData[0]; - - if (words.Length > 2) - return new UserAccountData[0]; - - SqliteCommand cmd = new SqliteCommand(); - - if (words.Length == 1) - { - cmd.CommandText = String.Format("select * from {0} where (ScopeID='{1}' or ScopeID='00000000-0000-0000-0000-000000000000') and (FirstName like '{2}%' or LastName like '{2}%')", - m_Realm, scopeID.ToString(), words[0]); - } - else - { - cmd.CommandText = String.Format("select * from {0} where (ScopeID='{1}' or ScopeID='00000000-0000-0000-0000-000000000000') and (FirstName like '{2}%' or LastName like '{3}%')", - m_Realm, scopeID.ToString(), words[0], words[1]); - } - - return DoQuery(cmd); - } - } -} diff --git a/OpenSim/Data/SQLiteLegacy/SQLiteUtils.cs b/OpenSim/Data/SQLiteLegacy/SQLiteUtils.cs deleted file mode 100644 index 095a26251f..0000000000 --- a/OpenSim/Data/SQLiteLegacy/SQLiteUtils.cs +++ /dev/null @@ -1,307 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Data; -using Mono.Data.SqliteClient; - -namespace OpenSim.Data.SQLiteLegacy -{ - /// - /// A base class for methods needed by all SQLite database classes - /// - public class SQLiteUtil - { - /*********************************************************************** - * - * Database Definition Helper Functions - * - * This should be db agnostic as we define them in ADO.NET terms - * - **********************************************************************/ - - /// - /// - /// - /// - /// - /// - public static void createCol(DataTable dt, string name, Type type) - { - DataColumn col = new DataColumn(name, type); - dt.Columns.Add(col); - } - - /*********************************************************************** - * - * SQL Statement Creation Functions - * - * These functions create SQL statements for update, insert, and create. - * They can probably be factored later to have a db independant - * portion and a db specific portion - * - **********************************************************************/ - - /// - /// Create an insert command - /// - /// table name - /// data table - /// the created command - /// - /// This is subtle enough to deserve some commentary. - /// Instead of doing *lots* and *lots of hardcoded strings - /// for database definitions we'll use the fact that - /// realistically all insert statements look like "insert - /// into A(b, c) values(:b, :c) on the parameterized query - /// front. If we just have a list of b, c, etc... we can - /// generate these strings instead of typing them out. - /// - public static SqliteCommand createInsertCommand(string table, DataTable dt) - { - - string[] cols = new string[dt.Columns.Count]; - for (int i = 0; i < dt.Columns.Count; i++) - { - DataColumn col = dt.Columns[i]; - cols[i] = col.ColumnName; - } - - string sql = "insert into " + table + "("; - sql += String.Join(", ", cols); - // important, the first ':' needs to be here, the rest get added in the join - sql += ") values (:"; - sql += String.Join(", :", cols); - sql += ")"; - SqliteCommand cmd = new SqliteCommand(sql); - - // this provides the binding for all our parameters, so - // much less code than it used to be - foreach (DataColumn col in dt.Columns) - { - cmd.Parameters.Add(createSqliteParameter(col.ColumnName, col.DataType)); - } - return cmd; - } - - /// - /// create an update command - /// - /// table name - /// - /// - /// the created command - public static SqliteCommand createUpdateCommand(string table, string pk, DataTable dt) - { - string sql = "update " + table + " set "; - string subsql = String.Empty; - foreach (DataColumn col in dt.Columns) - { - if (subsql.Length > 0) - { - // a map function would rock so much here - subsql += ", "; - } - subsql += col.ColumnName + "= :" + col.ColumnName; - } - sql += subsql; - sql += " where " + pk; - SqliteCommand cmd = new SqliteCommand(sql); - - // this provides the binding for all our parameters, so - // much less code than it used to be - - foreach (DataColumn col in dt.Columns) - { - cmd.Parameters.Add(createSqliteParameter(col.ColumnName, col.DataType)); - } - return cmd; - } - - /// - /// - /// - /// Data Table - /// - public static string defineTable(DataTable dt) - { - string sql = "create table " + dt.TableName + "("; - string subsql = String.Empty; - foreach (DataColumn col in dt.Columns) - { - if (subsql.Length > 0) - { - // a map function would rock so much here - subsql += ",\n"; - } - subsql += col.ColumnName + " " + sqliteType(col.DataType); - if (dt.PrimaryKey.Length > 0) - { - if (col == dt.PrimaryKey[0]) - { - subsql += " primary key"; - } - } - } - sql += subsql; - sql += ")"; - return sql; - } - - /*********************************************************************** - * - * Database Binding functions - * - * These will be db specific due to typing, and minor differences - * in databases. - * - **********************************************************************/ - - /// - /// - /// This is a convenience function that collapses 5 repetitive - /// lines for defining SqliteParameters to 2 parameters: - /// column name and database type. - /// - /// - /// - /// It assumes certain conventions like :param as the param - /// name to replace in parametrized queries, and that source - /// version is always current version, both of which are fine - /// for us. - /// - /// - /// - /// - ///a built sqlite parameter - public static SqliteParameter createSqliteParameter(string name, Type type) - { - SqliteParameter param = new SqliteParameter(); - param.ParameterName = ":" + name; - param.DbType = dbtypeFromType(type); - param.SourceColumn = name; - param.SourceVersion = DataRowVersion.Current; - return param; - } - - /*********************************************************************** - * - * Type conversion functions - * - **********************************************************************/ - - /// - /// Type conversion function - /// - /// a type - /// a DbType - public static DbType dbtypeFromType(Type type) - { - if (type == typeof (String)) - { - return DbType.String; - } - else if (type == typeof (Int32)) - { - return DbType.Int32; - } - else if (type == typeof (UInt32)) - { - return DbType.UInt32; - } - else if (type == typeof (Int64)) - { - return DbType.Int64; - } - else if (type == typeof (UInt64)) - { - return DbType.UInt64; - } - else if (type == typeof (Double)) - { - return DbType.Double; - } - else if (type == typeof (Boolean)) - { - return DbType.Boolean; - } - else if (type == typeof (Byte[])) - { - return DbType.Binary; - } - else - { - return DbType.String; - } - } - - /// - /// - /// a Type - /// a string - /// this is something we'll need to implement for each db slightly differently. - public static string sqliteType(Type type) - { - if (type == typeof (String)) - { - return "varchar(255)"; - } - else if (type == typeof (Int32)) - { - return "integer"; - } - else if (type == typeof (UInt32)) - { - return "integer"; - } - else if (type == typeof (Int64)) - { - return "varchar(255)"; - } - else if (type == typeof (UInt64)) - { - return "varchar(255)"; - } - else if (type == typeof (Double)) - { - return "float"; - } - else if (type == typeof (Boolean)) - { - return "integer"; - } - else if (type == typeof (Byte[])) - { - return "blob"; - } - else - { - return "string"; - } - } - } -} diff --git a/OpenSim/Data/SQLiteLegacy/SQLiteXInventoryData.cs b/OpenSim/Data/SQLiteLegacy/SQLiteXInventoryData.cs deleted file mode 100644 index 5422cbf6ad..0000000000 --- a/OpenSim/Data/SQLiteLegacy/SQLiteXInventoryData.cs +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Data; -using System.Reflection; -using System.Collections.Generic; -using Mono.Data.SqliteClient; -using log4net; -using OpenMetaverse; -using OpenSim.Framework; - -namespace OpenSim.Data.SQLiteLegacy -{ - /// - /// A MySQL Interface for the Asset Server - /// - public class SQLiteXInventoryData : IXInventoryData - { -// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private SQLiteGenericTableHandler m_Folders; - private SqliteItemHandler m_Items; - - public SQLiteXInventoryData(string conn, string realm) - { - m_Folders = new SQLiteGenericTableHandler( - conn, "inventoryfolders", "InventoryStore"); - m_Items = new SqliteItemHandler( - conn, "inventoryitems", String.Empty); - } - - public XInventoryFolder[] GetFolders(string[] fields, string[] vals) - { - return m_Folders.Get(fields, vals); - } - - public XInventoryItem[] GetItems(string[] fields, string[] vals) - { - return m_Items.Get(fields, vals); - } - - public bool StoreFolder(XInventoryFolder folder) - { - return m_Folders.Store(folder); - } - - public bool StoreItem(XInventoryItem item) - { - return m_Items.Store(item); - } - - public bool DeleteFolders(string field, string val) - { - return m_Folders.Delete(field, val); - } - - public bool DeleteItems(string field, string val) - { - return m_Items.Delete(field, val); - } - - public bool MoveItem(string id, string newParent) - { - return m_Items.MoveItem(id, newParent); - } - - public XInventoryItem[] GetActiveGestures(UUID principalID) - { - return m_Items.GetActiveGestures(principalID); - } - - public int GetAssetPermissions(UUID principalID, UUID assetID) - { - return m_Items.GetAssetPermissions(principalID, assetID); - } - } - - public class SqliteItemHandler : SQLiteGenericTableHandler - { - public SqliteItemHandler(string c, string t, string m) : - base(c, t, m) - { - } - - public bool MoveItem(string id, string newParent) - { - SqliteCommand cmd = new SqliteCommand(); - - cmd.CommandText = String.Format("update {0} set parentFolderID = :ParentFolderID where inventoryID = :InventoryID", m_Realm); - cmd.Parameters.Add(new SqliteParameter(":ParentFolderID", newParent)); - cmd.Parameters.Add(new SqliteParameter(":InventoryID", id)); - - return ExecuteNonQuery(cmd, m_Connection) == 0 ? false : true; - } - - public XInventoryItem[] GetActiveGestures(UUID principalID) - { - SqliteCommand cmd = new SqliteCommand(); - cmd.CommandText = String.Format("select * from inventoryitems where avatarId = :uuid and assetType = :type and flags = 1", m_Realm); - - cmd.Parameters.Add(new SqliteParameter(":uuid", principalID.ToString())); - cmd.Parameters.Add(new SqliteParameter(":type", (int)AssetType.Gesture)); - - return DoQuery(cmd); - } - - public int GetAssetPermissions(UUID principalID, UUID assetID) - { - SqliteCommand cmd = new SqliteCommand(); - - cmd.CommandText = String.Format("select inventoryCurrentPermissions from inventoryitems where avatarID = :PrincipalID and assetID = :AssetID", m_Realm); - cmd.Parameters.Add(new SqliteParameter(":PrincipalID", principalID.ToString())); - cmd.Parameters.Add(new SqliteParameter(":AssetID", assetID.ToString())); - - IDataReader reader = ExecuteReader(cmd, m_Connection); - - int perms = 0; - - while (reader.Read()) - { - perms |= Convert.ToInt32(reader["inventoryCurrentPermissions"]); - } - - reader.Close(); - CloseCommand(cmd); - - return perms; - } - } -} diff --git a/OpenSim/Framework/IClientAPI.cs b/OpenSim/Framework/IClientAPI.cs index 5bf0b7b0a9..f573c32d07 100644 --- a/OpenSim/Framework/IClientAPI.cs +++ b/OpenSim/Framework/IClientAPI.cs @@ -570,16 +570,35 @@ namespace OpenSim.Framework public float dwell; } - public class EntityUpdate + public class IEntityUpdate { public ISceneEntity Entity; - public PrimUpdateFlags Flags; - public float TimeDilation; + public uint Flags; - public EntityUpdate(ISceneEntity entity, PrimUpdateFlags flags, float timedilation) + public virtual void Update(IEntityUpdate update) + { + this.Flags |= update.Flags; + } + + public IEntityUpdate(ISceneEntity entity, uint flags) { Entity = entity; Flags = flags; + } + } + + + public class EntityUpdate : IEntityUpdate + { + // public ISceneEntity Entity; + // public PrimUpdateFlags Flags; + public float TimeDilation; + + public EntityUpdate(ISceneEntity entity, PrimUpdateFlags flags, float timedilation) + : base(entity,(uint)flags) + { + //Entity = entity; + // Flags = flags; TimeDilation = timedilation; } } @@ -1211,20 +1230,9 @@ namespace OpenSim.Framework /// void SendSimStats(SimStats stats); - void SendObjectPropertiesFamilyData(uint RequestFlags, UUID ObjectUUID, UUID OwnerID, UUID GroupID, - uint BaseMask, uint OwnerMask, uint GroupMask, uint EveryoneMask, - uint NextOwnerMask, int OwnershipCost, byte SaleType, int SalePrice, - uint Category, - UUID LastOwnerID, string ObjectName, string Description); + void SendObjectPropertiesFamilyData(ISceneEntity Entity, uint RequestFlags); - void SendObjectPropertiesReply(UUID ItemID, ulong CreationDate, UUID CreatorUUID, UUID FolderUUID, - UUID FromTaskUUID, - UUID GroupUUID, short InventorySerial, UUID LastOwnerUUID, UUID ObjectUUID, - UUID OwnerUUID, string TouchTitle, byte[] TextureID, string SitTitle, - string ItemName, - string ItemDescription, uint OwnerMask, uint NextOwnerMask, uint GroupMask, - uint EveryoneMask, - uint BaseMask, byte saleType, int salePrice); + void SendObjectPropertiesReply(ISceneEntity Entity); void SendAgentOffline(UUID[] agentIDs); diff --git a/OpenSim/Framework/ILandChannel.cs b/OpenSim/Framework/ILandChannel.cs index 30bae16d81..869d4c8184 100644 --- a/OpenSim/Framework/ILandChannel.cs +++ b/OpenSim/Framework/ILandChannel.cs @@ -77,7 +77,6 @@ namespace OpenSim.Region.Framework.Interfaces /// void Clear(bool setupDefaultParcel); - bool IsLandPrimCountTainted(); bool IsForcefulBansAllowed(); void UpdateLandObject(int localID, LandData data); void ReturnObjectsInParcel(int localID, uint returnType, UUID[] agentIDs, UUID[] taskIDs, IClientAPI remoteClient); diff --git a/OpenSim/Framework/ILandObject.cs b/OpenSim/Framework/ILandObject.cs index 931e24aebb..5a55b02f8e 100644 --- a/OpenSim/Framework/ILandObject.cs +++ b/OpenSim/Framework/ILandObject.cs @@ -82,14 +82,36 @@ namespace OpenSim.Framework void ForceUpdateLandInfo(); void SetLandBitmap(bool[,] bitmap); + /// + /// Get a land bitmap that would cover an entire region. + /// + /// The bitmap created. bool[,] BasicFullRegionLandBitmap(); + + /// + /// Create a square land bitmap. + /// + /// + /// Land co-ordinates are zero indexed. The inputs are treated as points. So if you want to create a bitmap + /// that covers an entire 256 x 256m region apart from a strip of land on the east, then you would need to + /// specify start_x = 0, start_y = 0, end_x = 252 (or anything up to 255), end_y = 256. + /// + /// At the moment, the smallest parcel of land is 4m x 4m, so if the + /// region is 256 x 256m (the SL size), the bitmap returned will start at (0,0) and end at (63,63). + /// + /// + /// + /// + /// + /// The bitmap created. bool[,] GetSquareLandBitmap(int start_x, int start_y, int end_x, int end_y); + bool[,] ModifyLandBitmapSquare(bool[,] land_bitmap, int start_x, int start_y, int end_x, int end_y, bool set_value); bool[,] MergeLandBitmaps(bool[,] bitmap_base, bool[,] bitmap_add); void SendForceObjectSelect(int local_id, int request_type, List returnIDs, IClientAPI remote_client); void SendLandObjectOwners(IClientAPI remote_client); void ReturnLandObjects(uint type, UUID[] owners, UUID[] tasks, IClientAPI remote_client); - void ResetLandPrimCounts(); + void ResetOverMeRecord(); void UpdateLandSold(UUID avatarID, UUID groupID, bool groupOwned, uint AuctionID, int claimprice, int area); void DeedToGroup(UUID groupID); diff --git a/OpenSim/Framework/LandData.cs b/OpenSim/Framework/LandData.cs index a9a493d876..c107143a6c 100644 --- a/OpenSim/Framework/LandData.cs +++ b/OpenSim/Framework/LandData.cs @@ -54,12 +54,10 @@ namespace OpenSim.Framework private int _claimPrice = 0; //Unemplemented private UUID _globalID = UUID.Zero; private UUID _groupID = UUID.Zero; - private int _groupPrims = 0; private bool _isGroupOwned = false; private byte[] _bitmap = new byte[512]; private string _description = String.Empty; - private uint _flags = (uint) ParcelFlags.AllowFly | (uint) ParcelFlags.AllowLandmark | (uint) ParcelFlags.AllowAPrimitiveEntry | (uint) ParcelFlags.AllowDeedToGroup | (uint) ParcelFlags.AllowTerraform | @@ -72,17 +70,13 @@ namespace OpenSim.Framework private int _localID = 0; private byte _mediaAutoScale = 0; private UUID _mediaID = UUID.Zero; - private string _mediaURL = String.Empty; private string _musicURL = String.Empty; - private int _otherPrims = 0; private UUID _ownerID = UUID.Zero; - private int _ownerPrims = 0; private List _parcelAccessList = new List(); private float _passHours = 0; private int _passPrice = 0; private int _salePrice = 0; //Unemeplemented. Parcels price. - private int _selectedPrims = 0; private int _simwideArea = 0; private int _simwidePrims = 0; private UUID _snapshotID = UUID.Zero; @@ -283,19 +277,6 @@ namespace OpenSim.Framework } } - /// - /// Number of SceneObjectPart that are owned by a Group - /// - [XmlIgnore] - public int GroupPrims { - get { - return _groupPrims; - } - set { - _groupPrims = value; - } - } - /// /// Returns true if the Land Parcel is owned by a group /// @@ -453,20 +434,6 @@ namespace OpenSim.Framework } } - /// - /// Number of SceneObjectPart that are owned by users who do not own the parcel - /// and don't have the 'group. These are elegable for AutoReturn collection - /// - [XmlIgnore] - public int OtherPrims { - get { - return _otherPrims; - } - set { - _otherPrims = value; - } - } - /// /// Owner Avatar or Group of the parcel. Naturally, all land masses must be /// owned by someone @@ -480,19 +447,6 @@ namespace OpenSim.Framework } } - /// - /// Number of SceneObjectPart that are owned by the owner of the parcel - /// - [XmlIgnore] - public int OwnerPrims { - get { - return _ownerPrims; - } - set { - _ownerPrims = value; - } - } - /// /// List of access data for the parcel. User data, some bitflags, and a time /// @@ -541,19 +495,6 @@ namespace OpenSim.Framework } } - /// - /// Number of SceneObjectPart that are currently selected by avatar - /// - [XmlIgnore] - public int SelectedPrims { - get { - return _selectedPrims; - } - set { - _selectedPrims = value; - } - } - /// /// Number of meters^2 in the Simulator /// @@ -619,7 +560,7 @@ namespace OpenSim.Framework } /// - /// Number of minutes to return SceneObjectGroup that are owned by someone who doesn't own + /// Autoreturn number of minutes to return SceneObjectGroup that are owned by someone who doesn't own /// the parcel and isn't set to the same 'group' as the parcel. /// public int OtherCleanTime { @@ -666,10 +607,6 @@ namespace OpenSim.Framework landData._claimPrice = _claimPrice; landData._globalID = _globalID; landData._groupID = _groupID; - landData._groupPrims = _groupPrims; - landData._otherPrims = _otherPrims; - landData._ownerPrims = _ownerPrims; - landData._selectedPrims = _selectedPrims; landData._isGroupOwned = _isGroupOwned; landData._localID = _localID; landData._landingType = _landingType; @@ -731,4 +668,4 @@ namespace OpenSim.Framework return land; } } -} +} \ No newline at end of file diff --git a/OpenSim/Framework/RegionInfo.cs b/OpenSim/Framework/RegionInfo.cs index 680e702a11..daf0a256d6 100644 --- a/OpenSim/Framework/RegionInfo.cs +++ b/OpenSim/Framework/RegionInfo.cs @@ -347,7 +347,6 @@ namespace OpenSim.Framework public bool commFailTF = false; public ConfigurationMember configMember; - public string DataStore = String.Empty; public string RegionFile = String.Empty; public bool isSandbox = false; public bool Persistent = true; @@ -746,10 +745,6 @@ namespace OpenSim.Framework m_regionLocX = Convert.ToUInt32(locationElements[0]); m_regionLocY = Convert.ToUInt32(locationElements[1]); - - // Datastore (is this implemented? Omitted from example!) - DataStore = config.GetString("Datastore", String.Empty); - // Internal IP IPAddress address; @@ -846,9 +841,6 @@ namespace OpenSim.Framework string location = String.Format("{0},{1}", m_regionLocX, m_regionLocY); config.Set("Location", location); - if (DataStore != String.Empty) - config.Set("Datastore", DataStore); - config.Set("InternalAddress", m_internalEndPoint.Address.ToString()); config.Set("InternalPort", m_internalEndPoint.Port); @@ -1025,9 +1017,6 @@ namespace OpenSim.Framework case "sim_location_y": m_regionLocY = (uint) configuration_result; break; - case "datastore": - DataStore = (string) configuration_result; - break; case "internal_ip_address": IPAddress address = (IPAddress) configuration_result; m_internalEndPoint = new IPEndPoint(address, 0); @@ -1175,11 +1164,6 @@ namespace OpenSim.Framework return regionInfo; } - public int getInternalEndPointPort() - { - return m_internalEndPoint.Port; - } - public Dictionary ToKeyValuePairs() { Dictionary kvp = new Dictionary(); @@ -1198,4 +1182,4 @@ namespace OpenSim.Framework return kvp; } } -} +} \ No newline at end of file diff --git a/OpenSim/Framework/Serialization/Tests/LandDataSerializerTests.cs b/OpenSim/Framework/Serialization/Tests/LandDataSerializerTests.cs index 70e87b3c08..c69c89dc0a 100644 --- a/OpenSim/Framework/Serialization/Tests/LandDataSerializerTests.cs +++ b/OpenSim/Framework/Serialization/Tests/LandDataSerializerTests.cs @@ -42,10 +42,7 @@ namespace OpenSim.Framework.Serialization.Tests private LandData landWithParcelAccessList; private static string preSerialized = "\n\n 128\n 0\n 00000000-0000-0000-0000-000000000000\n 10\n 0\n 0\n 54ff9641-dd40-4a2c-b1f1-47dd3af24e50\n d740204e-bbbf-44aa-949d-02c7d739f6a5\n False\n AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\n land data to test LandDataSerializer\n 536870944\n 2\n LandDataSerializerTest Land\n 0\n 0\n 1\n d4452578-2f25-4b97-a81b-819af559cfd7\n http://videos.opensimulator.org/bumblebee.mp4\n \n 1b8eedf9-6d15-448b-8015-24286f1756bf\n \n 0\n 0\n 0\n 00000000-0000-0000-0000-000000000000\n <0, 0, 0>\n <0, 0, 0>\n 0\n 0\n"; - private static string preSerializedWithParcelAccessList = "\n\n 128\n 0\n 00000000-0000-0000-0000-000000000000\n 10\n 0\n 0\n 54ff9641-dd40-4a2c-b1f1-47dd3af24e50\n d740204e-bbbf-44aa-949d-02c7d739f6a5\n False\n AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\n land data to test LandDataSerializer\n 536870944\n 2\n LandDataSerializerTest Land\n 0\n 0\n 1\n d4452578-2f25-4b97-a81b-819af559cfd7\n http://videos.opensimulator.org/bumblebee.mp4\n \n 1b8eedf9-6d15-448b-8015-24286f1756bf\n \n \n 62d65d45-c91a-4f77-862c-46557d978b6c\n \n 2\n \n \n ec2a8d18-2378-4fe0-8b68-2a31b57c481e\n \n 1\n \n \n 0\n 0\n 0\n 00000000-0000-0000-0000-000000000000\n <0, 0, 0>\n <0, 0, 0>\n 0\n 0\n"; - - - + private static string preSerializedWithParcelAccessList = "\n\n 128\n 0\n 00000000-0000-0000-0000-000000000000\n 10\n 0\n 0\n 54ff9641-dd40-4a2c-b1f1-47dd3af24e50\n d740204e-bbbf-44aa-949d-02c7d739f6a5\n False\n AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\n land data to test LandDataSerializer\n 536870944\n 2\n LandDataSerializerTest Land\n 0\n 0\n 1\n d4452578-2f25-4b97-a81b-819af559cfd7\n http://videos.opensimulator.org/bumblebee.mp4\n \n 1b8eedf9-6d15-448b-8015-24286f1756bf\n \n \n 62d65d45-c91a-4f77-862c-46557d978b6c\n \n 2\n \n \n ec2a8d18-2378-4fe0-8b68-2a31b57c481e\n \n 1\n \n \n 0\n 0\n 0\n 00000000-0000-0000-0000-000000000000\n <0, 0, 0>\n <0, 0, 0>\n 0\n 0\n"; [SetUp] public void setup() @@ -62,7 +59,6 @@ namespace OpenSim.Framework.Serialization.Tests this.land.ClaimPrice = 0; this.land.GlobalID = new UUID("54ff9641-dd40-4a2c-b1f1-47dd3af24e50"); this.land.GroupID = new UUID("d740204e-bbbf-44aa-949d-02c7d739f6a5"); - this.land.GroupPrims = 0; this.land.Description = "land data to test LandDataSerializer"; this.land.Flags = (uint)(ParcelFlags.AllowDamage | ParcelFlags.AllowVoiceChat); this.land.LandingType = (byte)LandingType.Direct; @@ -132,4 +128,4 @@ namespace OpenSim.Framework.Serialization.Tests "Reified LandData.Name != original LandData.Name (pre-serialized with parcel access list)"); } } -} +} \ No newline at end of file diff --git a/OpenSim/Framework/Servers/HttpServer/AsynchronousRestObjectRequester.cs b/OpenSim/Framework/Servers/HttpServer/AsynchronousRestObjectRequester.cs deleted file mode 100644 index 03c12dd560..0000000000 --- a/OpenSim/Framework/Servers/HttpServer/AsynchronousRestObjectRequester.cs +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.IO; -using System.Net; -using System.Reflection; -using System.Text; -using System.Xml; -using System.Xml.Serialization; -using log4net; - -namespace OpenSim.Framework.Servers.HttpServer -{ - public class AsynchronousRestObjectRequester - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - /// - /// Perform an asynchronous REST request. - /// - /// GET or POST - /// - /// - /// - /// - /// - /// Thrown if we encounter a - /// network issue while posting the request. You'll want to make - /// sure you deal with this as they're not uncommon - // - public static void MakeRequest(string verb, - string requestUrl, TRequest obj, Action action) - { -// m_log.DebugFormat("[ASYNC REQUEST]: Starting {0} {1}", verb, requestUrl); - - Type type = typeof (TRequest); - - WebRequest request = WebRequest.Create(requestUrl); - WebResponse response = null; - TResponse deserial = default(TResponse); - XmlSerializer deserializer = new XmlSerializer(typeof (TResponse)); - - request.Method = verb; - - if (verb == "POST") - { - request.ContentType = "text/xml"; - - MemoryStream buffer = new MemoryStream(); - - XmlWriterSettings settings = new XmlWriterSettings(); - settings.Encoding = Encoding.UTF8; - - using (XmlWriter writer = XmlWriter.Create(buffer, settings)) - { - XmlSerializer serializer = new XmlSerializer(type); - serializer.Serialize(writer, obj); - writer.Flush(); - } - - int length = (int) buffer.Length; - request.ContentLength = length; - - request.BeginGetRequestStream(delegate(IAsyncResult res) - { - Stream requestStream = request.EndGetRequestStream(res); - - requestStream.Write(buffer.ToArray(), 0, length); - requestStream.Close(); - - request.BeginGetResponse(delegate(IAsyncResult ar) - { - response = request.EndGetResponse(ar); - Stream respStream = null; - try - { - respStream = response.GetResponseStream(); - deserial = (TResponse)deserializer.Deserialize( - respStream); - } - catch (System.InvalidOperationException) - { - } - finally - { - // Let's not close this - //buffer.Close(); - respStream.Close(); - response.Close(); - } - - action(deserial); - - }, null); - }, null); - - - return; - } - - request.BeginGetResponse(delegate(IAsyncResult res2) - { - try - { - // If the server returns a 404, this appears to trigger a System.Net.WebException even though that isn't - // documented in MSDN - response = request.EndGetResponse(res2); - - Stream respStream = null; - try - { - respStream = response.GetResponseStream(); - deserial = (TResponse)deserializer.Deserialize(respStream); - } - catch (System.InvalidOperationException) - { - } - finally - { - respStream.Close(); - response.Close(); - } - } - catch (WebException e) - { - if (e.Status == WebExceptionStatus.ProtocolError) - { - if (e.Response is HttpWebResponse) - { - HttpWebResponse httpResponse = (HttpWebResponse)e.Response; - - if (httpResponse.StatusCode != HttpStatusCode.NotFound) - { - // We don't appear to be handling any other status codes, so log these feailures to that - // people don't spend unnecessary hours hunting phantom bugs. - m_log.DebugFormat( - "[ASYNC REQUEST]: Request {0} {1} failed with unexpected status code {2}", - verb, requestUrl, httpResponse.StatusCode); - } - } - } - else - { - m_log.ErrorFormat("[ASYNC REQUEST]: Request {0} {1} failed with status {2} and message {3}", verb, requestUrl, e.Status, e.Message); - } - } - catch (Exception e) - { - m_log.ErrorFormat("[ASYNC REQUEST]: Request {0} {1} failed with exception {2}", verb, requestUrl, e); - } - - // m_log.DebugFormat("[ASYNC REQUEST]: Received {0}", deserial.ToString()); - - try - { - action(deserial); - } - catch (Exception e) - { - m_log.ErrorFormat( - "[ASYNC REQUEST]: Request {0} {1} callback failed with exception {2}", verb, requestUrl, e); - } - - }, null); - } - } -} diff --git a/OpenSim/Framework/Servers/HttpServer/SynchronousRestFormsRequester.cs b/OpenSim/Framework/Servers/HttpServer/SynchronousRestFormsRequester.cs deleted file mode 100644 index 41ece86047..0000000000 --- a/OpenSim/Framework/Servers/HttpServer/SynchronousRestFormsRequester.cs +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.IO; -using System.Net; -using System.Reflection; -using System.Text; -using System.Xml; -using System.Xml.Serialization; - -using log4net; - -namespace OpenSim.Framework.Servers.HttpServer -{ - public class SynchronousRestFormsRequester - { - private static readonly ILog m_log = - LogManager.GetLogger( - MethodBase.GetCurrentMethod().DeclaringType); - - /// - /// Perform a synchronous REST request. - /// - /// - /// - /// - /// - /// - /// Thrown if we encounter a network issue while posting - /// the request. You'll want to make sure you deal with this as they're not uncommon - public static string MakeRequest(string verb, string requestUrl, string obj) - { - WebRequest request = WebRequest.Create(requestUrl); - request.Method = verb; - string respstring = String.Empty; - - using (MemoryStream buffer = new MemoryStream()) - { - if ((verb == "POST") || (verb == "PUT")) - { - request.ContentType = "text/www-form-urlencoded"; - - int length = 0; - using (StreamWriter writer = new StreamWriter(buffer)) - { - writer.Write(obj); - writer.Flush(); - } - - length = (int)obj.Length; - request.ContentLength = length; - - Stream requestStream = null; - try - { - requestStream = request.GetRequestStream(); - requestStream.Write(buffer.ToArray(), 0, length); - } - catch (Exception e) - { - m_log.DebugFormat("[FORMS]: exception occured on sending request to {0}: " + e.ToString(), requestUrl); - } - finally - { - if (requestStream != null) - requestStream.Close(); - } - } - - try - { - using (WebResponse resp = request.GetResponse()) - { - if (resp.ContentLength != 0) - { - Stream respStream = null; - try - { - respStream = resp.GetResponseStream(); - using (StreamReader reader = new StreamReader(respStream)) - { - respstring = reader.ReadToEnd(); - } - } - catch (Exception e) - { - m_log.DebugFormat("[FORMS]: exception occured on receiving reply " + e.ToString()); - } - finally - { - if (respStream != null) - respStream.Close(); - } - } - } - } - catch (System.InvalidOperationException) - { - // This is what happens when there is invalid XML - m_log.DebugFormat("[FORMS]: InvalidOperationException on receiving request"); - } - } - return respstring; - } - } -} diff --git a/OpenSim/Framework/Servers/HttpServer/SynchronousRestObjectRequester.cs b/OpenSim/Framework/Servers/HttpServer/SynchronousRestObjectRequester.cs deleted file mode 100644 index eab463cbd8..0000000000 --- a/OpenSim/Framework/Servers/HttpServer/SynchronousRestObjectRequester.cs +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.IO; -using System.Net; -using System.Text; -using System.Xml; -using System.Xml.Serialization; - -namespace OpenSim.Framework.Servers.HttpServer -{ - public class SynchronousRestObjectPoster - { - [Obsolete] - public static TResponse BeginPostObject(string verb, string requestUrl, TRequest obj) - { - return SynchronousRestObjectRequester.MakeRequest(verb, requestUrl, obj); - } - } - - public class SynchronousRestObjectRequester - { - /// - /// Perform a synchronous REST request. - /// - /// - /// - /// - /// - /// - /// Thrown if we encounter a network issue while posting - /// the request. You'll want to make sure you deal with this as they're not uncommon - public static TResponse MakeRequest(string verb, string requestUrl, TRequest obj) - { - Type type = typeof (TRequest); - TResponse deserial = default(TResponse); - - WebRequest request = WebRequest.Create(requestUrl); - request.Method = verb; - - if ((verb == "POST") || (verb == "PUT")) - { - request.ContentType = "text/xml"; - - MemoryStream buffer = new MemoryStream(); - - XmlWriterSettings settings = new XmlWriterSettings(); - settings.Encoding = Encoding.UTF8; - - using (XmlWriter writer = XmlWriter.Create(buffer, settings)) - { - XmlSerializer serializer = new XmlSerializer(type); - serializer.Serialize(writer, obj); - writer.Flush(); - } - - int length = (int) buffer.Length; - request.ContentLength = length; - - Stream requestStream = null; - try - { - requestStream = request.GetRequestStream(); - requestStream.Write(buffer.ToArray(), 0, length); - } - catch (Exception) - { - return deserial; - } - finally - { - if (requestStream != null) - requestStream.Close(); - } - } - - try - { - using (WebResponse resp = request.GetResponse()) - { - if (resp.ContentLength > 0) - { - Stream respStream = resp.GetResponseStream(); - XmlSerializer deserializer = new XmlSerializer(typeof(TResponse)); - deserial = (TResponse)deserializer.Deserialize(respStream); - respStream.Close(); - } - } - } - catch (System.InvalidOperationException) - { - // This is what happens when there is invalid XML - } - return deserial; - } - } -} diff --git a/OpenSim/Framework/WebUtil.cs b/OpenSim/Framework/WebUtil.cs index 1feeeb31e5..9d70f63189 100644 --- a/OpenSim/Framework/WebUtil.cs +++ b/OpenSim/Framework/WebUtil.cs @@ -36,6 +36,9 @@ using System.Net.Security; using System.Reflection; using System.Text; using System.Web; +using System.Xml; +using System.Xml.Serialization; + using log4net; using OpenSim.Framework.Servers.HttpServer; using OpenMetaverse.StructuredData; @@ -219,8 +222,8 @@ namespace OpenSim.Framework m_log.InfoFormat("[WEB UTIL]: osd request <{0}> (URI:{1}, METHOD:{2}) took {3}ms overall, {4}ms writing", reqnum,url,method,tickdiff,tickdata); } - - m_log.WarnFormat("[WEB UTIL] <{0}> osd request failed: {1}",reqnum,errorMessage); + + m_log.WarnFormat("[WEB UTIL]: <{0}> osd request for {1}, method {2} FAILED: {3}", reqnum, url, method, errorMessage); return ErrorResponseMap(errorMessage); } @@ -625,4 +628,336 @@ namespace OpenSim.Framework } + + public static class AsynchronousRestObjectRequester + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + /// + /// Perform an asynchronous REST request. + /// + /// GET or POST + /// + /// + /// + /// + /// + /// Thrown if we encounter a + /// network issue while posting the request. You'll want to make + /// sure you deal with this as they're not uncommon + // + public static void MakeRequest(string verb, + string requestUrl, TRequest obj, Action action) + { + // m_log.DebugFormat("[ASYNC REQUEST]: Starting {0} {1}", verb, requestUrl); + + Type type = typeof(TRequest); + + WebRequest request = WebRequest.Create(requestUrl); + WebResponse response = null; + TResponse deserial = default(TResponse); + XmlSerializer deserializer = new XmlSerializer(typeof(TResponse)); + + request.Method = verb; + + if (verb == "POST") + { + request.ContentType = "text/xml"; + + MemoryStream buffer = new MemoryStream(); + + XmlWriterSettings settings = new XmlWriterSettings(); + settings.Encoding = Encoding.UTF8; + + using (XmlWriter writer = XmlWriter.Create(buffer, settings)) + { + XmlSerializer serializer = new XmlSerializer(type); + serializer.Serialize(writer, obj); + writer.Flush(); + } + + int length = (int)buffer.Length; + request.ContentLength = length; + + request.BeginGetRequestStream(delegate(IAsyncResult res) + { + Stream requestStream = request.EndGetRequestStream(res); + + requestStream.Write(buffer.ToArray(), 0, length); + requestStream.Close(); + + request.BeginGetResponse(delegate(IAsyncResult ar) + { + response = request.EndGetResponse(ar); + Stream respStream = null; + try + { + respStream = response.GetResponseStream(); + deserial = (TResponse)deserializer.Deserialize( + respStream); + } + catch (System.InvalidOperationException) + { + } + finally + { + // Let's not close this + //buffer.Close(); + respStream.Close(); + response.Close(); + } + + action(deserial); + + }, null); + }, null); + + + return; + } + + request.BeginGetResponse(delegate(IAsyncResult res2) + { + try + { + // If the server returns a 404, this appears to trigger a System.Net.WebException even though that isn't + // documented in MSDN + response = request.EndGetResponse(res2); + + Stream respStream = null; + try + { + respStream = response.GetResponseStream(); + deserial = (TResponse)deserializer.Deserialize(respStream); + } + catch (System.InvalidOperationException) + { + } + finally + { + respStream.Close(); + response.Close(); + } + } + catch (WebException e) + { + if (e.Status == WebExceptionStatus.ProtocolError) + { + if (e.Response is HttpWebResponse) + { + HttpWebResponse httpResponse = (HttpWebResponse)e.Response; + + if (httpResponse.StatusCode != HttpStatusCode.NotFound) + { + // We don't appear to be handling any other status codes, so log these feailures to that + // people don't spend unnecessary hours hunting phantom bugs. + m_log.DebugFormat( + "[ASYNC REQUEST]: Request {0} {1} failed with unexpected status code {2}", + verb, requestUrl, httpResponse.StatusCode); + } + } + } + else + { + m_log.ErrorFormat("[ASYNC REQUEST]: Request {0} {1} failed with status {2} and message {3}", verb, requestUrl, e.Status, e.Message); + } + } + catch (Exception e) + { + m_log.ErrorFormat("[ASYNC REQUEST]: Request {0} {1} failed with exception {2}", verb, requestUrl, e); + } + + // m_log.DebugFormat("[ASYNC REQUEST]: Received {0}", deserial.ToString()); + + try + { + action(deserial); + } + catch (Exception e) + { + m_log.ErrorFormat( + "[ASYNC REQUEST]: Request {0} {1} callback failed with exception {2}", verb, requestUrl, e); + } + + }, null); + } + } + + public static class SynchronousRestFormsRequester + { + private static readonly ILog m_log = + LogManager.GetLogger( + MethodBase.GetCurrentMethod().DeclaringType); + + /// + /// Perform a synchronous REST request. + /// + /// + /// + /// + /// + /// + /// Thrown if we encounter a network issue while posting + /// the request. You'll want to make sure you deal with this as they're not uncommon + public static string MakeRequest(string verb, string requestUrl, string obj) + { + WebRequest request = WebRequest.Create(requestUrl); + request.Method = verb; + string respstring = String.Empty; + + using (MemoryStream buffer = new MemoryStream()) + { + if ((verb == "POST") || (verb == "PUT")) + { + request.ContentType = "text/www-form-urlencoded"; + + int length = 0; + using (StreamWriter writer = new StreamWriter(buffer)) + { + writer.Write(obj); + writer.Flush(); + } + + length = (int)obj.Length; + request.ContentLength = length; + + Stream requestStream = null; + try + { + requestStream = request.GetRequestStream(); + requestStream.Write(buffer.ToArray(), 0, length); + } + catch (Exception e) + { + m_log.DebugFormat("[FORMS]: exception occured on sending request to {0}: " + e.ToString(), requestUrl); + } + finally + { + if (requestStream != null) + requestStream.Close(); + } + } + + try + { + using (WebResponse resp = request.GetResponse()) + { + if (resp.ContentLength != 0) + { + Stream respStream = null; + try + { + respStream = resp.GetResponseStream(); + using (StreamReader reader = new StreamReader(respStream)) + { + respstring = reader.ReadToEnd(); + } + } + catch (Exception e) + { + m_log.DebugFormat("[FORMS]: exception occured on receiving reply " + e.ToString()); + } + finally + { + if (respStream != null) + respStream.Close(); + } + } + } + } + catch (System.InvalidOperationException) + { + // This is what happens when there is invalid XML + m_log.DebugFormat("[FORMS]: InvalidOperationException on receiving request"); + } + } + return respstring; + } + } + + public class SynchronousRestObjectPoster + { + [Obsolete] + public static TResponse BeginPostObject(string verb, string requestUrl, TRequest obj) + { + return SynchronousRestObjectRequester.MakeRequest(verb, requestUrl, obj); + } + } + + public class SynchronousRestObjectRequester + { + /// + /// Perform a synchronous REST request. + /// + /// + /// + /// + /// + /// + /// Thrown if we encounter a network issue while posting + /// the request. You'll want to make sure you deal with this as they're not uncommon + public static TResponse MakeRequest(string verb, string requestUrl, TRequest obj) + { + Type type = typeof(TRequest); + TResponse deserial = default(TResponse); + + WebRequest request = WebRequest.Create(requestUrl); + request.Method = verb; + + if ((verb == "POST") || (verb == "PUT")) + { + request.ContentType = "text/xml"; + + MemoryStream buffer = new MemoryStream(); + + XmlWriterSettings settings = new XmlWriterSettings(); + settings.Encoding = Encoding.UTF8; + + using (XmlWriter writer = XmlWriter.Create(buffer, settings)) + { + XmlSerializer serializer = new XmlSerializer(type); + serializer.Serialize(writer, obj); + writer.Flush(); + } + + int length = (int)buffer.Length; + request.ContentLength = length; + + Stream requestStream = null; + try + { + requestStream = request.GetRequestStream(); + requestStream.Write(buffer.ToArray(), 0, length); + } + catch (Exception) + { + return deserial; + } + finally + { + if (requestStream != null) + requestStream.Close(); + } + } + + try + { + using (WebResponse resp = request.GetResponse()) + { + if (resp.ContentLength > 0) + { + Stream respStream = resp.GetResponseStream(); + XmlSerializer deserializer = new XmlSerializer(typeof(TResponse)); + deserial = (TResponse)deserializer.Deserialize(respStream); + respStream.Close(); + } + } + } + catch (System.InvalidOperationException) + { + // This is what happens when there is invalid XML + } + return deserial; + } + } } diff --git a/OpenSim/Region/Application/Application.cs b/OpenSim/Region/Application/Application.cs index d120f03dc9..7e320e6798 100644 --- a/OpenSim/Region/Application/Application.cs +++ b/OpenSim/Region/Application/Application.cs @@ -250,9 +250,7 @@ namespace OpenSim m_saveCrashDumps = configSource.Configs["Startup"].GetBoolean("save_crashes", false); // load Crash directory config - m_crashDir = configSource.Configs["Startup"].GetString("crash_dir", m_crashDir); - - + m_crashDir = configSource.Configs["Startup"].GetString("crash_dir", m_crashDir); if (background) { @@ -260,15 +258,9 @@ namespace OpenSim m_sim.Startup(); } else - { - - - - + { m_sim = new OpenSim(configSource); - - - + m_sim.Startup(); while (true) diff --git a/OpenSim/Region/Application/OpenSim.cs b/OpenSim/Region/Application/OpenSim.cs index 408188824d..39004d4028 100644 --- a/OpenSim/Region/Application/OpenSim.cs +++ b/OpenSim/Region/Application/OpenSim.cs @@ -123,7 +123,7 @@ namespace OpenSim m_log.Info("===================================================================="); m_log.Info("========================= STARTING OPENSIM ========================="); m_log.Info("===================================================================="); - m_log.InfoFormat("[OPENSIM MAIN]: Running "); + //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; @@ -341,10 +341,15 @@ namespace OpenSim m_console.Commands.AddCommand("region", false, "config get", "config get [
] []", - "Show a config option", + "Synonym for config show", + HandleConfig); + + m_console.Commands.AddCommand("region", false, "config show", + "config show [
] []", + "Show config information", "If neither section nor field are specified, then the whole current configuration is printed." + Environment.NewLine + "If a section is given but not a field, then all fields in that section are printed.", - HandleConfig); + HandleConfig); m_console.Commands.AddCommand("region", false, "config save", "config save ", @@ -593,7 +598,9 @@ namespace OpenSim if (cmdparams.Length > 0) { - switch (cmdparams[0].ToLower()) + string firstParam = cmdparams[0].ToLower(); + + switch (firstParam) { case "set": if (cmdparams.Length < 4) @@ -618,6 +625,7 @@ namespace OpenSim break; case "get": + case "show": if (cmdparams.Length == 1) { foreach (IConfig config in m_config.Source.Configs) @@ -654,8 +662,8 @@ namespace OpenSim } else { - Notice("Syntax: config get [
] []"); - Notice("Example: config get ScriptEngine.DotNetEngine NumberOfScriptThreads"); + Notice("Syntax: config {0} [
] []", firstParam); + Notice("Example: config {0} ScriptEngine.DotNetEngine NumberOfScriptThreads", firstParam); } break; diff --git a/OpenSim/Region/Application/OpenSimBase.cs b/OpenSim/Region/Application/OpenSimBase.cs index 640581181c..ea9edf686b 100644 --- a/OpenSim/Region/Application/OpenSimBase.cs +++ b/OpenSim/Region/Application/OpenSimBase.cs @@ -860,7 +860,7 @@ namespace OpenSim = MainConsole.Instance.CmdPrompt( string.Format( "Do you wish to join region {0} to an existing estate (yes/no)?", regInfo.RegionName), - "no", + "yes", new List() { "yes", "no" }); if (response == "no") @@ -876,15 +876,12 @@ namespace OpenSim = MainConsole.Instance.CmdPrompt( string.Format( "Name of estate to join. Existing estate names are ({0})", string.Join(", ", estateNames.ToArray())), - "None"); - - if (response == "None") - continue; + estateNames[0]); List estateIDs = EstateDataService.GetEstates(response); if (estateIDs.Count < 1) { - MainConsole.Instance.Output("The name you have entered matches no known estate. Please try again."); + MainConsole.Instance.Output("The name you have entered matches no known estate. Please try again."); continue; } diff --git a/OpenSim/Region/ClientStack/LindenUDP/LLClientView.cs b/OpenSim/Region/ClientStack/LindenUDP/LLClientView.cs index 2faffae58e..1f7e66dabb 100644 --- a/OpenSim/Region/ClientStack/LindenUDP/LLClientView.cs +++ b/OpenSim/Region/ClientStack/LindenUDP/LLClientView.cs @@ -49,6 +49,8 @@ using Timer = System.Timers.Timer; using AssetLandmark = OpenSim.Framework.AssetLandmark; using Nini.Config; +using System.IO; + namespace OpenSim.Region.ClientStack.LindenUDP { public delegate bool PacketMethod(IClientAPI simClient, Packet packet); @@ -313,6 +315,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP private int m_cachedTextureSerial; private PriorityQueue m_entityUpdates; + private PriorityQueue m_entityProps; private Prioritizer m_prioritizer; private bool m_disableFacelights = false; @@ -360,9 +363,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP protected IAssetService m_assetService; private const bool m_checkPackets = true; - private Timer m_propertiesPacketTimer; - private List m_propertiesBlocks = new List(); - #endregion Class Members #region Properties @@ -438,6 +438,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP m_scene = scene; m_entityUpdates = new PriorityQueue(m_scene.Entities.Count); + m_entityProps = new PriorityQueue(m_scene.Entities.Count); m_fullUpdateDataBlocksBuilder = new List(); m_killRecord = new HashSet(); // m_attachmentsSent = new HashSet(); @@ -461,9 +462,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP m_udpClient.OnQueueEmpty += HandleQueueEmpty; m_udpClient.OnPacketStats += PopulateStats; - m_propertiesPacketTimer = new Timer(100); - m_propertiesPacketTimer.Elapsed += ProcessObjectPropertiesPacket; - m_prioritizer = new Prioritizer(m_scene); RegisterLocalPacketHandlers(); @@ -1537,7 +1535,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP } else { - OutPacket(kill, ThrottleOutPacketType.State); + // OutPacket(kill, ThrottleOutPacketType.State); + OutPacket(kill, ThrottleOutPacketType.Task); } } @@ -2367,7 +2366,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP packet.Effect = effectBlocks; - OutPacket(packet, ThrottleOutPacketType.State); + // OutPacket(packet, ThrottleOutPacketType.State); + OutPacket(packet, ThrottleOutPacketType.Task); } public void SendAvatarProperties(UUID avatarID, string aboutText, string bornOn, Byte[] charterMember, @@ -3547,16 +3547,18 @@ 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 /// public void SendPrimUpdate(ISceneEntity entity, PrimUpdateFlags updateFlags) { - double priority = m_prioritizer.GetUpdatePriority(this, entity); + //double priority = m_prioritizer.GetUpdatePriority(this, entity); + uint priority = m_prioritizer.GetUpdatePriority(this, entity); lock (m_entityUpdates.SyncRoot) - m_entityUpdates.Enqueue(priority, new EntityUpdate(entity, updateFlags, m_scene.TimeDilation), entity.LocalId); + m_entityUpdates.Enqueue(priority, new EntityUpdate(entity, updateFlags, m_scene.TimeDilation)); } private void ProcessEntityUpdates(int maxUpdates) @@ -3566,7 +3568,12 @@ namespace OpenSim.Region.ClientStack.LindenUDP OpenSim.Framework.Lazy> terseUpdateBlocks = new OpenSim.Framework.Lazy>(); OpenSim.Framework.Lazy> terseAgentUpdateBlocks = new OpenSim.Framework.Lazy>(); - if (maxUpdates <= 0) maxUpdates = Int32.MaxValue; + // Check to see if this is a flush + if (maxUpdates <= 0) + { + maxUpdates = Int32.MaxValue; + } + int updatesThisCall = 0; // We must lock for both manipulating the kill record and sending the packet, in order to avoid a race @@ -3574,12 +3581,17 @@ namespace OpenSim.Region.ClientStack.LindenUDP lock (m_killRecord) { float avgTimeDilation = 1.0f; - EntityUpdate update; + IEntityUpdate iupdate; + Int32 timeinqueue; // this is just debugging code & can be dropped later + while (updatesThisCall < maxUpdates) { lock (m_entityUpdates.SyncRoot) - if (!m_entityUpdates.TryDequeue(out update)) + if (!m_entityUpdates.TryDequeue(out iupdate, out timeinqueue)) break; + + EntityUpdate update = (EntityUpdate)iupdate; + avgTimeDilation += update.TimeDilation; avgTimeDilation *= 0.5f; @@ -3619,7 +3631,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP #region UpdateFlags to packet type conversion - PrimUpdateFlags updateFlags = update.Flags; + PrimUpdateFlags updateFlags = (PrimUpdateFlags)update.Flags; bool canUseCompressed = true; bool canUseImproved = true; @@ -3679,36 +3691,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP } else { - // if (update.Entity is SceneObjectPart && ((SceneObjectPart)update.Entity).IsAttachment) - // { - // SceneObjectPart sop = (SceneObjectPart)update.Entity; - // string text = sop.Text; - // if (text.IndexOf("\n") >= 0) - // text = text.Remove(text.IndexOf("\n")); - // - // if (m_attachmentsSent.Contains(sop.ParentID)) - // { - //// m_log.DebugFormat( - //// "[CLIENT]: Sending full info about attached prim {0} text {1}", - //// sop.LocalId, text); - // - // objectUpdateBlocks.Value.Add(CreatePrimUpdateBlock(sop, this.m_agentId)); - // - // m_attachmentsSent.Add(sop.LocalId); - // } - // else - // { - // m_log.DebugFormat( - // "[CLIENT]: Requeueing full update of prim {0} text {1} since we haven't sent its parent {2} yet", - // sop.LocalId, text, sop.ParentID); - // - // m_entityUpdates.Enqueue(double.MaxValue, update, sop.LocalId); - // } - // } - // else - // { - objectUpdateBlocks.Value.Add(CreatePrimUpdateBlock((SceneObjectPart)update.Entity, this.m_agentId)); - // } + objectUpdateBlocks.Value.Add(CreatePrimUpdateBlock((SceneObjectPart)update.Entity, this.m_agentId)); } } else if (!canUseImproved) @@ -3727,6 +3710,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP #endregion Block Construction } + #region Packet Sending @@ -3802,26 +3786,24 @@ namespace OpenSim.Region.ClientStack.LindenUDP public void ReprioritizeUpdates() { - //m_log.Debug("[CLIENT]: Reprioritizing prim updates for " + m_firstName + " " + m_lastName); - lock (m_entityUpdates.SyncRoot) m_entityUpdates.Reprioritize(UpdatePriorityHandler); } - private bool UpdatePriorityHandler(ref double priority, uint localID) + private bool UpdatePriorityHandler(ref uint priority, ISceneEntity entity) { - EntityBase entity; - if (m_scene.Entities.TryGetValue(localID, out entity)) + if (entity != null) { priority = m_prioritizer.GetUpdatePriority(this, entity); + return true; } - return priority != double.NaN; + return false; } public void FlushPrimUpdates() { - m_log.Debug("[CLIENT]: Flushing prim updates to " + m_firstName + " " + m_lastName); + m_log.WarnFormat("[CLIENT]: Flushing prim updates to " + m_firstName + " " + m_lastName); while (m_entityUpdates.Count > 0) ProcessEntityUpdates(-1); @@ -3829,12 +3811,36 @@ namespace OpenSim.Region.ClientStack.LindenUDP #endregion Primitive Packet/Data Sending Methods + // These are used to implement an adaptive backoff in the number + // of updates converted to packets. Since we don't want packets + // to sit in the queue with old data, only convert enough updates + // to packets that can be sent in 200ms. + private Int32 m_LastQueueFill = 0; + private Int32 m_maxUpdates = 0; + void HandleQueueEmpty(ThrottleOutPacketTypeFlags categories) { if ((categories & ThrottleOutPacketTypeFlags.Task) != 0) { + if (m_maxUpdates == 0 || m_LastQueueFill == 0) + { + m_maxUpdates = m_udpServer.PrimUpdatesPerCallback; + } + else + { + if (Util.EnvironmentTickCountSubtract(m_LastQueueFill) < 200) + m_maxUpdates += 5; + else + m_maxUpdates = m_maxUpdates >> 1; + } + m_maxUpdates = Util.Clamp(m_maxUpdates,10,500); + m_LastQueueFill = Util.EnvironmentTickCount(); + if (m_entityUpdates.Count > 0) - ProcessEntityUpdates(m_udpServer.PrimUpdatesPerCallback); + ProcessEntityUpdates(m_maxUpdates); + + if (m_entityProps.Count > 0) + ProcessEntityPropertyRequests(m_maxUpdates); } if ((categories & ThrottleOutPacketTypeFlags.Texture) != 0) @@ -3948,47 +3954,167 @@ namespace OpenSim.Region.ClientStack.LindenUDP OutPacket(pack, ThrottleOutPacketType.Task); } - public void SendObjectPropertiesFamilyData(uint RequestFlags, UUID ObjectUUID, UUID OwnerID, UUID GroupID, - uint BaseMask, uint OwnerMask, uint GroupMask, uint EveryoneMask, - uint NextOwnerMask, int OwnershipCost, byte SaleType, int SalePrice, uint Category, - UUID LastOwnerID, string ObjectName, string Description) + private class ObjectPropertyUpdate : IEntityUpdate { - ObjectPropertiesFamilyPacket objPropFamilyPack = (ObjectPropertiesFamilyPacket)PacketPool.Instance.GetPacket(PacketType.ObjectPropertiesFamily); - // TODO: don't create new blocks if recycling an old packet - - ObjectPropertiesFamilyPacket.ObjectDataBlock objPropDB = new ObjectPropertiesFamilyPacket.ObjectDataBlock(); - objPropDB.RequestFlags = RequestFlags; - objPropDB.ObjectID = ObjectUUID; - if (OwnerID == GroupID) - objPropDB.OwnerID = UUID.Zero; - else - objPropDB.OwnerID = OwnerID; - objPropDB.GroupID = GroupID; - objPropDB.BaseMask = BaseMask; - objPropDB.OwnerMask = OwnerMask; - objPropDB.GroupMask = GroupMask; - objPropDB.EveryoneMask = EveryoneMask; - objPropDB.NextOwnerMask = NextOwnerMask; - - // TODO: More properties are needed in SceneObjectPart! - objPropDB.OwnershipCost = OwnershipCost; - objPropDB.SaleType = SaleType; - objPropDB.SalePrice = SalePrice; - objPropDB.Category = Category; - objPropDB.LastOwnerID = LastOwnerID; - objPropDB.Name = Util.StringToBytes256(ObjectName); - objPropDB.Description = Util.StringToBytes256(Description); - objPropFamilyPack.ObjectData = objPropDB; - objPropFamilyPack.Header.Zerocoded = true; - OutPacket(objPropFamilyPack, ThrottleOutPacketType.Task); + internal bool SendFamilyProps; + internal bool SendObjectProps; + + public ObjectPropertyUpdate(ISceneEntity entity, uint flags, bool sendfam, bool sendobj) + : base(entity,flags) + { + SendFamilyProps = sendfam; + SendObjectProps = sendobj; + } + public void Update(ObjectPropertyUpdate update) + { + SendFamilyProps = SendFamilyProps || update.SendFamilyProps; + SendObjectProps = SendObjectProps || update.SendObjectProps; + Flags |= update.Flags; + } + } + + public void SendObjectPropertiesFamilyData(ISceneEntity entity, uint requestFlags) + { + uint priority = 0; // time based ordering only + lock (m_entityProps.SyncRoot) + m_entityProps.Enqueue(priority, new ObjectPropertyUpdate(entity,requestFlags,true,false)); } - public void SendObjectPropertiesReply( - UUID ItemID, ulong CreationDate, UUID CreatorUUID, UUID FolderUUID, UUID FromTaskUUID, - UUID GroupUUID, short InventorySerial, UUID LastOwnerUUID, UUID ObjectUUID, - UUID OwnerUUID, string TouchTitle, byte[] TextureID, string SitTitle, string ItemName, - string ItemDescription, uint OwnerMask, uint NextOwnerMask, uint GroupMask, uint EveryoneMask, - uint BaseMask, byte saleType, int salePrice) + public void SendObjectPropertiesReply(ISceneEntity entity) + { + uint priority = 0; // time based ordering only + lock (m_entityProps.SyncRoot) + m_entityProps.Enqueue(priority, new ObjectPropertyUpdate(entity,0,false,true)); + } + + private void ProcessEntityPropertyRequests(int maxUpdates) + { + OpenSim.Framework.Lazy> objectFamilyBlocks = + new OpenSim.Framework.Lazy>(); + + OpenSim.Framework.Lazy> objectPropertiesBlocks = + new OpenSim.Framework.Lazy>(); + + IEntityUpdate iupdate; + Int32 timeinqueue; // this is just debugging code & can be dropped later + + int updatesThisCall = 0; + while (updatesThisCall < m_maxUpdates) + { + lock (m_entityProps.SyncRoot) + if (!m_entityProps.TryDequeue(out iupdate, out timeinqueue)) + break; + + ObjectPropertyUpdate update = (ObjectPropertyUpdate)iupdate; + if (update.SendFamilyProps) + { + if (update.Entity is SceneObjectPart) + { + SceneObjectPart sop = (SceneObjectPart)update.Entity; + ObjectPropertiesFamilyPacket.ObjectDataBlock objPropDB = CreateObjectPropertiesFamilyBlock(sop,update.Flags); + objectFamilyBlocks.Value.Add(objPropDB); + } + } + + if (update.SendObjectProps) + { + if (update.Entity is SceneObjectPart) + { + SceneObjectPart sop = (SceneObjectPart)update.Entity; + ObjectPropertiesPacket.ObjectDataBlock objPropDB = CreateObjectPropertiesBlock(sop); + objectPropertiesBlocks.Value.Add(objPropDB); + } + } + + updatesThisCall++; + } + + + Int32 ppcnt = 0; + Int32 pbcnt = 0; + + if (objectPropertiesBlocks.IsValueCreated) + { + List blocks = objectPropertiesBlocks.Value; + + ObjectPropertiesPacket packet = (ObjectPropertiesPacket)PacketPool.Instance.GetPacket(PacketType.ObjectProperties); + packet.ObjectData = new ObjectPropertiesPacket.ObjectDataBlock[blocks.Count]; + for (int i = 0; i < blocks.Count; i++) + packet.ObjectData[i] = blocks[i]; + + packet.Header.Zerocoded = true; + OutPacket(packet, ThrottleOutPacketType.Task, true); + + pbcnt += blocks.Count; + ppcnt++; + } + + Int32 fpcnt = 0; + Int32 fbcnt = 0; + + if (objectFamilyBlocks.IsValueCreated) + { + List blocks = objectFamilyBlocks.Value; + + // ObjectPropertiesFamilyPacket objPropFamilyPack = + // (ObjectPropertiesFamilyPacket)PacketPool.Instance.GetPacket(PacketType.ObjectPropertiesFamily); + // + // objPropFamilyPack.ObjectData = new ObjectPropertiesFamilyPacket.ObjectDataBlock[blocks.Count]; + // for (int i = 0; i < blocks.Count; i++) + // objPropFamilyPack.ObjectData[i] = blocks[i]; + // + // OutPacket(objPropFamilyPack, ThrottleOutPacketType.Task, true); + + // one packet per object block... uggh... + for (int i = 0; i < blocks.Count; i++) + { + ObjectPropertiesFamilyPacket packet = + (ObjectPropertiesFamilyPacket)PacketPool.Instance.GetPacket(PacketType.ObjectPropertiesFamily); + + packet.ObjectData = blocks[i]; + packet.Header.Zerocoded = true; + OutPacket(packet, ThrottleOutPacketType.Task); + + fpcnt++; + fbcnt++; + } + + } + + // m_log.WarnFormat("[PACKETCOUNTS] queued {0} property packets with {1} blocks",ppcnt,pbcnt); + // m_log.WarnFormat("[PACKETCOUNTS] queued {0} family property packets with {1} blocks",fpcnt,fbcnt); + } + + private ObjectPropertiesFamilyPacket.ObjectDataBlock CreateObjectPropertiesFamilyBlock(SceneObjectPart sop, uint requestFlags) + { + ObjectPropertiesFamilyPacket.ObjectDataBlock block = new ObjectPropertiesFamilyPacket.ObjectDataBlock(); + + block.RequestFlags = requestFlags; + block.ObjectID = sop.UUID; + if (sop.OwnerID == sop.GroupID) + block.OwnerID = UUID.Zero; + else + block.OwnerID = sop.OwnerID; + block.GroupID = sop.GroupID; + block.BaseMask = sop.BaseMask; + block.OwnerMask = sop.OwnerMask; + block.GroupMask = sop.GroupMask; + block.EveryoneMask = sop.EveryoneMask; + block.NextOwnerMask = sop.NextOwnerMask; + + // TODO: More properties are needed in SceneObjectPart! + block.OwnershipCost = sop.OwnershipCost; + block.SaleType = sop.ObjectSaleType; + block.SalePrice = sop.SalePrice; + block.Category = sop.Category; + block.LastOwnerID = sop.CreatorID; // copied from old SOG call... is this right? + block.Name = Util.StringToBytes256(sop.Name); + block.Description = Util.StringToBytes256(sop.Description); + + return block; + } + + private ObjectPropertiesPacket.ObjectDataBlock CreateObjectPropertiesBlock(SceneObjectPart sop) { //ObjectPropertiesPacket proper = (ObjectPropertiesPacket)PacketPool.Instance.GetPacket(PacketType.ObjectProperties); // TODO: don't create new blocks if recycling an old packet @@ -3996,84 +4122,38 @@ namespace OpenSim.Region.ClientStack.LindenUDP ObjectPropertiesPacket.ObjectDataBlock block = new ObjectPropertiesPacket.ObjectDataBlock(); - block.ItemID = ItemID; - block.CreationDate = CreationDate; - block.CreatorID = CreatorUUID; - block.FolderID = FolderUUID; - block.FromTaskID = FromTaskUUID; - block.GroupID = GroupUUID; - block.InventorySerial = InventorySerial; + block.ObjectID = sop.UUID; + block.Name = Util.StringToBytes256(sop.Name); + block.Description = Util.StringToBytes256(sop.Description); - block.LastOwnerID = LastOwnerUUID; - // proper.ObjectData[0].LastOwnerID = UUID.Zero; - - block.ObjectID = ObjectUUID; - if (OwnerUUID == GroupUUID) + block.CreationDate = (ulong)sop.CreationDate * 1000000; // viewer wants date in microseconds + block.CreatorID = sop.CreatorID; + block.GroupID = sop.GroupID; + block.LastOwnerID = sop.LastOwnerID; + if (sop.OwnerID == sop.GroupID) block.OwnerID = UUID.Zero; else - block.OwnerID = OwnerUUID; - block.TouchName = Util.StringToBytes256(TouchTitle); - block.TextureID = TextureID; - block.SitName = Util.StringToBytes256(SitTitle); - block.Name = Util.StringToBytes256(ItemName); - block.Description = Util.StringToBytes256(ItemDescription); - block.OwnerMask = OwnerMask; - block.NextOwnerMask = NextOwnerMask; - block.GroupMask = GroupMask; - block.EveryoneMask = EveryoneMask; - block.BaseMask = BaseMask; - // proper.ObjectData[0].AggregatePerms = 53; - // proper.ObjectData[0].AggregatePermTextures = 0; - // proper.ObjectData[0].AggregatePermTexturesOwner = 0; - block.SaleType = saleType; - block.SalePrice = salePrice; + block.OwnerID = sop.OwnerID; - lock (m_propertiesPacketTimer) - { - m_propertiesBlocks.Add(block); + block.ItemID = sop.FromUserInventoryItemID; + block.FolderID = UUID.Zero; // sop.FromFolderID ?? + block.FromTaskID = UUID.Zero; // ??? + block.InventorySerial = (short)sop.InventorySerial; + + SceneObjectPart root = sop.ParentGroup.RootPart; - int length = 0; - foreach (ObjectPropertiesPacket.ObjectDataBlock b in m_propertiesBlocks) - { - length += b.Length; - } - if (length > 1100) // FIXME: use real MTU - { - ProcessObjectPropertiesPacket(null, null); - m_propertiesPacketTimer.Stop(); - return; - } + block.TouchName = Util.StringToBytes256(root.TouchName); + block.TextureID = new byte[0]; // TextureID ??? + block.SitName = Util.StringToBytes256(root.SitName); + block.OwnerMask = root.OwnerMask; + block.NextOwnerMask = root.NextOwnerMask; + block.GroupMask = root.GroupMask; + block.EveryoneMask = root.EveryoneMask; + block.BaseMask = root.BaseMask; + block.SaleType = root.ObjectSaleType; + block.SalePrice = root.SalePrice; - m_propertiesPacketTimer.Stop(); - m_propertiesPacketTimer.Start(); - } - - //proper.Header.Zerocoded = true; - //OutPacket(proper, ThrottleOutPacketType.Task); - } - - private void ProcessObjectPropertiesPacket(Object sender, ElapsedEventArgs e) - { - ObjectPropertiesPacket proper = (ObjectPropertiesPacket)PacketPool.Instance.GetPacket(PacketType.ObjectProperties); - - lock (m_propertiesPacketTimer) - { - m_propertiesPacketTimer.Stop(); - - proper.ObjectData = new ObjectPropertiesPacket.ObjectDataBlock[m_propertiesBlocks.Count]; - - int index = 0; - - foreach (ObjectPropertiesPacket.ObjectDataBlock b in m_propertiesBlocks) - { - proper.ObjectData[index++] = b; - } - - m_propertiesBlocks.Clear(); - } - - proper.Header.Zerocoded = true; - OutPacket(proper, ThrottleOutPacketType.Task); + return block; } #region Estate Data Sending Methods @@ -4217,6 +4297,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP public void SendEstateCovenantInformation(UUID covenant) { +// m_log.DebugFormat("[LLCLIENTVIEW]: Sending estate covenant asset id of {0} to {1}", covenant, Name); + EstateCovenantReplyPacket einfopack = new EstateCovenantReplyPacket(); EstateCovenantReplyPacket.DataBlock edata = new EstateCovenantReplyPacket.DataBlock(); edata.CovenantID = covenant; @@ -4227,8 +4309,13 @@ namespace OpenSim.Region.ClientStack.LindenUDP OutPacket(einfopack, ThrottleOutPacketType.Task); } - public void SendDetailedEstateData(UUID invoice, string estateName, uint estateID, uint parentEstate, uint estateFlags, uint sunPosition, UUID covenant, string abuseEmail, UUID estateOwner) + public void SendDetailedEstateData( + UUID invoice, string estateName, uint estateID, uint parentEstate, uint estateFlags, uint sunPosition, + UUID covenant, string abuseEmail, UUID estateOwner) { +// m_log.DebugFormat( +// "[LLCLIENTVIEW]: Sending detailed estate data to {0} with covenant asset id {1}", Name, covenant); + EstateOwnerMessagePacket packet = new EstateOwnerMessagePacket(); packet.MethodData.Invoice = invoice; packet.AgentData.TransactionID = UUID.Random(); @@ -4407,6 +4494,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP public void SendForceClientSelectObjects(List ObjectIDs) { + m_log.WarnFormat("[LLCLIENTVIEW] sending select with {0} objects", ObjectIDs.Count); + bool firstCall = true; const int MAX_OBJECTS_PER_PACKET = 251; ForceObjectSelectPacket pack = (ForceObjectSelectPacket)PacketPool.Instance.GetPacket(PacketType.ForceObjectSelect); @@ -4938,7 +5027,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP AddLocalPacketHandler(PacketType.TeleportLocationRequest, HandleTeleportLocationRequest); AddLocalPacketHandler(PacketType.UUIDNameRequest, HandleUUIDNameRequest, false); AddLocalPacketHandler(PacketType.RegionHandleRequest, HandleRegionHandleRequest); - AddLocalPacketHandler(PacketType.ParcelInfoRequest, HandleParcelInfoRequest, false); + AddLocalPacketHandler(PacketType.ParcelInfoRequest, HandleParcelInfoRequest); AddLocalPacketHandler(PacketType.ParcelAccessListRequest, HandleParcelAccessListRequest, false); AddLocalPacketHandler(PacketType.ParcelAccessListUpdate, HandleParcelAccessListUpdate, false); AddLocalPacketHandler(PacketType.ParcelPropertiesRequest, HandleParcelPropertiesRequest, false); @@ -8809,13 +8898,29 @@ namespace OpenSim.Region.ClientStack.LindenUDP case "instantmessage": if (((Scene)m_scene).Permissions.CanIssueEstateCommand(AgentId, false)) { - if (messagePacket.ParamList.Length < 5) + if (messagePacket.ParamList.Length < 2) return true; + UUID invoice = messagePacket.MethodData.Invoice; - UUID SenderID = new UUID(Utils.BytesToString(messagePacket.ParamList[2].Parameter)); - string SenderName = Utils.BytesToString(messagePacket.ParamList[3].Parameter); - string Message = Utils.BytesToString(messagePacket.ParamList[4].Parameter); UUID sessionID = messagePacket.AgentData.SessionID; + + UUID SenderID; + string SenderName; + string Message; + + if (messagePacket.ParamList.Length < 5) + { + SenderID = AgentId; + SenderName = Utils.BytesToString(messagePacket.ParamList[0].Parameter); + Message = Utils.BytesToString(messagePacket.ParamList[1].Parameter); + } + else + { + SenderID = new UUID(Utils.BytesToString(messagePacket.ParamList[2].Parameter)); + SenderName = Utils.BytesToString(messagePacket.ParamList[3].Parameter); + Message = Utils.BytesToString(messagePacket.ParamList[4].Parameter); + } + OnEstateBlueBoxMessageRequest(this, invoice, SenderID, sessionID, SenderName, Message); } return true; @@ -11282,7 +11387,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP if (logPacket) m_log.DebugFormat("[CLIENT]: Packet OUT {0}", packet.Type); } - + m_udpServer.SendPacket(m_udpClient, packet, throttlePacketType, doAutomaticSplitting); } @@ -11710,171 +11815,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP OutPacket(pack, ThrottleOutPacketType.Task); } - #region PriorityQueue - public class PriorityQueue - { - internal delegate bool UpdatePriorityHandler(ref double priority, uint local_id); - - private MinHeap[] m_heaps = new MinHeap[1]; - private Dictionary m_lookupTable; - private Comparison m_comparison; - private object m_syncRoot = new object(); - - internal PriorityQueue() : - this(MinHeap.DEFAULT_CAPACITY, Comparer.Default) { } - internal PriorityQueue(int capacity) : - this(capacity, Comparer.Default) { } - internal PriorityQueue(IComparer comparer) : - this(new Comparison(comparer.Compare)) { } - internal PriorityQueue(Comparison comparison) : - this(MinHeap.DEFAULT_CAPACITY, comparison) { } - internal PriorityQueue(int capacity, IComparer comparer) : - this(capacity, new Comparison(comparer.Compare)) { } - internal PriorityQueue(int capacity, Comparison comparison) - { - m_lookupTable = new Dictionary(capacity); - - for (int i = 0; i < m_heaps.Length; ++i) - m_heaps[i] = new MinHeap(capacity); - this.m_comparison = comparison; - } - - public object SyncRoot { get { return this.m_syncRoot; } } - internal int Count - { - get - { - int count = 0; - for (int i = 0; i < m_heaps.Length; ++i) - count = m_heaps[i].Count; - return count; - } - } - - public bool Enqueue(double priority, EntityUpdate value, uint local_id) - { - LookupItem item; - - if (m_lookupTable.TryGetValue(local_id, out item)) - { - // Combine flags - value.Flags |= item.Heap[item.Handle].Value.Flags; - - item.Heap[item.Handle] = new MinHeapItem(priority, value, local_id, this.m_comparison); - return false; - } - else - { - item.Heap = m_heaps[0]; - item.Heap.Add(new MinHeapItem(priority, value, local_id, this.m_comparison), ref item.Handle); - m_lookupTable.Add(local_id, item); - return true; - } - } - - internal EntityUpdate Peek() - { - for (int i = 0; i < m_heaps.Length; ++i) - if (m_heaps[i].Count > 0) - return m_heaps[i].Min().Value; - throw new InvalidOperationException(string.Format("The {0} is empty", this.GetType().ToString())); - } - - internal bool TryDequeue(out EntityUpdate value) - { - for (int i = 0; i < m_heaps.Length; ++i) - { - if (m_heaps[i].Count > 0) - { - MinHeapItem item = m_heaps[i].RemoveMin(); - m_lookupTable.Remove(item.LocalID); - value = item.Value; - return true; - } - } - - value = default(EntityUpdate); - return false; - } - - internal void Reprioritize(UpdatePriorityHandler handler) - { - MinHeapItem item; - double priority; - - foreach (LookupItem lookup in new List(this.m_lookupTable.Values)) - { - if (lookup.Heap.TryGetValue(lookup.Handle, out item)) - { - priority = item.Priority; - if (handler(ref priority, item.LocalID)) - { - if (lookup.Heap.ContainsHandle(lookup.Handle)) - lookup.Heap[lookup.Handle] = - new MinHeapItem(priority, item.Value, item.LocalID, this.m_comparison); - } - else - { - m_log.Warn("[LLCLIENTVIEW]: UpdatePriorityHandler returned false, dropping update"); - lookup.Heap.Remove(lookup.Handle); - this.m_lookupTable.Remove(item.LocalID); - } - } - } - } - - #region MinHeapItem - private struct MinHeapItem : IComparable - { - private double priority; - private EntityUpdate value; - private uint local_id; - private Comparison comparison; - - internal MinHeapItem(double priority, EntityUpdate value, uint local_id) : - this(priority, value, local_id, Comparer.Default) { } - internal MinHeapItem(double priority, EntityUpdate value, uint local_id, IComparer comparer) : - this(priority, value, local_id, new Comparison(comparer.Compare)) { } - internal MinHeapItem(double priority, EntityUpdate value, uint local_id, Comparison comparison) - { - this.priority = priority; - this.value = value; - this.local_id = local_id; - this.comparison = comparison; - } - - internal double Priority { get { return this.priority; } } - internal EntityUpdate Value { get { return this.value; } } - internal uint LocalID { get { return this.local_id; } } - - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - sb.Append("["); - sb.Append(this.priority.ToString()); - sb.Append(","); - if (this.value != null) - sb.Append(this.value.ToString()); - sb.Append("]"); - return sb.ToString(); - } - - public int CompareTo(MinHeapItem other) - { - return this.comparison(this.priority, other.priority); - } - } - #endregion - - #region LookupItem - private struct LookupItem - { - internal MinHeap Heap; - internal IHandle Handle; - } - #endregion - } - public struct PacketProcessor { public PacketMethod method; @@ -11895,8 +11835,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP } } - #endregion - public static OSD BuildEvent(string eventName, OSD eventBody) { OSDMap osdEvent = new OSDMap(2); diff --git a/OpenSim/Region/ClientStack/LindenUDP/LLUDPClient.cs b/OpenSim/Region/ClientStack/LindenUDP/LLUDPClient.cs index 65a8fe3ca8..7be8a0ae59 100644 --- a/OpenSim/Region/ClientStack/LindenUDP/LLUDPClient.cs +++ b/OpenSim/Region/ClientStack/LindenUDP/LLUDPClient.cs @@ -135,7 +135,9 @@ namespace OpenSim.Region.ClientStack.LindenUDP private int m_nextOnQueueEmpty = 1; /// Throttle bucket for this agent's connection - private readonly TokenBucket m_throttle; + private readonly TokenBucket m_throttleClient; + /// Throttle bucket for this agent's connection + private readonly TokenBucket m_throttleCategory; /// Throttle buckets for each packet category private readonly TokenBucket[] m_throttleCategories; /// Outgoing queues for throttled packets @@ -149,7 +151,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP /// Caches packed throttle information private byte[] m_packedThrottles; - private int m_defaultRTO = 3000; + private int m_defaultRTO = 1000; // 1sec is the recommendation in the RFC private int m_maxRTO = 60000; /// @@ -174,7 +176,9 @@ namespace OpenSim.Region.ClientStack.LindenUDP m_maxRTO = maxRTO; // Create a token bucket throttle for this client that has the scene token bucket as a parent - m_throttle = new TokenBucket(parentThrottle, rates.TotalLimit, rates.Total); + m_throttleClient = new TokenBucket(parentThrottle, rates.TotalLimit); + // Create a token bucket throttle for the total categary with the client bucket as a throttle + m_throttleCategory = new TokenBucket(m_throttleClient, rates.TotalLimit); // Create an array of token buckets for this clients different throttle categories m_throttleCategories = new TokenBucket[THROTTLE_CATEGORY_COUNT]; @@ -185,7 +189,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP // Initialize the packet outboxes, where packets sit while they are waiting for tokens m_packetOutboxes[i] = new OpenSim.Framework.LocklessQueue(); // Initialize the token buckets that control the throttling for each category - m_throttleCategories[i] = new TokenBucket(m_throttle, rates.GetLimit(type), rates.GetRate(type)); + m_throttleCategories[i] = new TokenBucket(m_throttleCategory, rates.GetLimit(type)); } // Default the retransmission timeout to three seconds @@ -206,6 +210,9 @@ namespace OpenSim.Region.ClientStack.LindenUDP m_packetOutboxes[i].Clear(); m_nextPackets[i] = null; } + + // pull the throttle out of the scene throttle + m_throttleClient.Parent.UnregisterRequest(m_throttleClient); OnPacketStats = null; OnQueueEmpty = null; } @@ -216,6 +223,26 @@ namespace OpenSim.Region.ClientStack.LindenUDP /// Information about the client connection public ClientInfo GetClientInfo() { +/// + TokenBucket tb; + + tb = m_throttleClient.Parent; + m_log.WarnFormat("[TOKENS] {3}: Actual={0},Request={1},TotalRequest={2}",tb.DripRate,tb.RequestedDripRate,tb.TotalDripRequest,"ROOT"); + + tb = m_throttleClient; + m_log.WarnFormat("[TOKENS] {3}: Actual={0},Request={1},TotalRequest={2}",tb.DripRate,tb.RequestedDripRate,tb.TotalDripRequest," CLIENT"); + + tb = m_throttleCategory; + m_log.WarnFormat("[TOKENS] {3}: Actual={0},Request={1},TotalRequest={2}",tb.DripRate,tb.RequestedDripRate,tb.TotalDripRequest," CATEGORY"); + + for (int i = 0; i < THROTTLE_CATEGORY_COUNT; i++) + { + tb = m_throttleCategories[i]; + m_log.WarnFormat("[TOKENS] {4} <{0}:{1}>: Actual={2},Requested={3}",AgentID,i,tb.DripRate,tb.RequestedDripRate," BUCKET"); + } + +/// + // TODO: This data structure is wrong in so many ways. Locking and copying the entire lists // of pending and needed ACKs for every client every time some method wants information about // this connection is a recipe for poor performance @@ -223,13 +250,14 @@ namespace OpenSim.Region.ClientStack.LindenUDP info.pendingAcks = new Dictionary(); info.needAck = new Dictionary(); - info.resendThrottle = m_throttleCategories[(int)ThrottleOutPacketType.Resend].DripRate; - info.landThrottle = m_throttleCategories[(int)ThrottleOutPacketType.Land].DripRate; - info.windThrottle = m_throttleCategories[(int)ThrottleOutPacketType.Wind].DripRate; - info.cloudThrottle = m_throttleCategories[(int)ThrottleOutPacketType.Cloud].DripRate; - info.taskThrottle = m_throttleCategories[(int)ThrottleOutPacketType.State].DripRate + m_throttleCategories[(int)ThrottleOutPacketType.Task].DripRate; - info.assetThrottle = m_throttleCategories[(int)ThrottleOutPacketType.Asset].DripRate; - info.textureThrottle = m_throttleCategories[(int)ThrottleOutPacketType.Texture].DripRate; + info.resendThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Resend].DripRate; + info.landThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Land].DripRate; + info.windThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Wind].DripRate; + info.cloudThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Cloud].DripRate; + // info.taskThrottle = m_throttleCategories[(int)ThrottleOutPacketType.State].DripRate + m_throttleCategories[(int)ThrottleOutPacketType.Task].DripRate; + info.taskThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Task].DripRate; + info.assetThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Asset].DripRate; + info.textureThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Texture].DripRate; info.totalThrottle = info.resendThrottle + info.landThrottle + info.windThrottle + info.cloudThrottle + info.taskThrottle + info.assetThrottle + info.textureThrottle; @@ -317,8 +345,9 @@ namespace OpenSim.Region.ClientStack.LindenUDP int texture = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); pos += 4; int asset = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); // State is a subcategory of task that we allocate a percentage to - int state = (int)((float)task * STATE_TASK_PERCENTAGE); - task -= state; + int state = 0; + // int state = (int)((float)task * STATE_TASK_PERCENTAGE); + // task -= state; // Make sure none of the throttles are set below our packet MTU, // otherwise a throttle could become permanently clogged @@ -339,40 +368,32 @@ namespace OpenSim.Region.ClientStack.LindenUDP // Update the token buckets with new throttle values TokenBucket bucket; - bucket = m_throttle; - bucket.MaxBurst = total; + bucket = m_throttleCategory; + bucket.RequestedDripRate = total; bucket = m_throttleCategories[(int)ThrottleOutPacketType.Resend]; - bucket.DripRate = resend; - bucket.MaxBurst = resend; + bucket.RequestedDripRate = resend; bucket = m_throttleCategories[(int)ThrottleOutPacketType.Land]; - bucket.DripRate = land; - bucket.MaxBurst = land; + bucket.RequestedDripRate = land; bucket = m_throttleCategories[(int)ThrottleOutPacketType.Wind]; - bucket.DripRate = wind; - bucket.MaxBurst = wind; + bucket.RequestedDripRate = wind; bucket = m_throttleCategories[(int)ThrottleOutPacketType.Cloud]; - bucket.DripRate = cloud; - bucket.MaxBurst = cloud; + bucket.RequestedDripRate = cloud; bucket = m_throttleCategories[(int)ThrottleOutPacketType.Asset]; - bucket.DripRate = asset; - bucket.MaxBurst = asset; + bucket.RequestedDripRate = asset; bucket = m_throttleCategories[(int)ThrottleOutPacketType.Task]; - bucket.DripRate = task + state; - bucket.MaxBurst = task + state; + bucket.RequestedDripRate = task; bucket = m_throttleCategories[(int)ThrottleOutPacketType.State]; - bucket.DripRate = state; - bucket.MaxBurst = state; + bucket.RequestedDripRate = state; bucket = m_throttleCategories[(int)ThrottleOutPacketType.Texture]; - bucket.DripRate = texture; - bucket.MaxBurst = texture; + bucket.RequestedDripRate = texture; // Reset the packed throttles cached data m_packedThrottles = null; @@ -387,14 +408,13 @@ namespace OpenSim.Region.ClientStack.LindenUDP data = new byte[7 * 4]; int i = 0; - Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Resend].DripRate), 0, data, i, 4); i += 4; - Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Land].DripRate), 0, data, i, 4); i += 4; - Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Wind].DripRate), 0, data, i, 4); i += 4; - Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Cloud].DripRate), 0, data, i, 4); i += 4; - Buffer.BlockCopy(Utils.FloatToBytes((float)(m_throttleCategories[(int)ThrottleOutPacketType.Task].DripRate) + - m_throttleCategories[(int)ThrottleOutPacketType.State].DripRate), 0, data, i, 4); i += 4; - Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Texture].DripRate), 0, data, i, 4); i += 4; - Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Asset].DripRate), 0, data, i, 4); i += 4; + Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Resend].RequestedDripRate), 0, data, i, 4); i += 4; + Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Land].RequestedDripRate), 0, data, i, 4); i += 4; + Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Wind].RequestedDripRate), 0, data, i, 4); i += 4; + Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Cloud].RequestedDripRate), 0, data, i, 4); i += 4; + Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Task].RequestedDripRate), 0, data, i, 4); i += 4; + Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Texture].RequestedDripRate), 0, data, i, 4); i += 4; + Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Asset].RequestedDripRate), 0, data, i, 4); i += 4; m_packedThrottles = data; } @@ -420,6 +440,16 @@ namespace OpenSim.Region.ClientStack.LindenUDP OpenSim.Framework.LocklessQueue queue = m_packetOutboxes[category]; TokenBucket bucket = m_throttleCategories[category]; + // Don't send this packet if there is already a packet waiting in the queue + // even if we have the tokens to send it, tokens should go to the already + // queued packets + if (queue.Count > 0) + { + queue.Enqueue(packet); + return true; + } + + if (!forceQueue && bucket.RemoveTokens(packet.Buffer.DataLength)) { // Enough tokens were removed from the bucket, the packet will not be queued @@ -557,7 +587,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP int rto = (int)(SRTT + Math.Max(m_udpServer.TickCountResolution, K * RTTVAR)); // Clamp the retransmission timeout to manageable values - rto = Utils.Clamp(RTO, m_defaultRTO, m_maxRTO); + rto = Utils.Clamp(rto, m_defaultRTO, m_maxRTO); RTO = rto; diff --git a/OpenSim/Region/ClientStack/LindenUDP/LLUDPServer.cs b/OpenSim/Region/ClientStack/LindenUDP/LLUDPServer.cs index 583214ca0b..d08b25f79d 100644 --- a/OpenSim/Region/ClientStack/LindenUDP/LLUDPServer.cs +++ b/OpenSim/Region/ClientStack/LindenUDP/LLUDPServer.cs @@ -228,7 +228,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP } #endregion BinaryStats - m_throttle = new TokenBucket(null, sceneThrottleBps, sceneThrottleBps); + m_throttle = new TokenBucket(null, sceneThrottleBps); ThrottleRates = new ThrottleRates(configSource); } diff --git a/OpenSim/Region/ClientStack/LindenUDP/OpenSimUDPBase.cs b/OpenSim/Region/ClientStack/LindenUDP/OpenSimUDPBase.cs index d2779ba302..6eebd9df3a 100644 --- a/OpenSim/Region/ClientStack/LindenUDP/OpenSimUDPBase.cs +++ b/OpenSim/Region/ClientStack/LindenUDP/OpenSimUDPBase.cs @@ -100,6 +100,10 @@ namespace OpenMetaverse const int SIO_UDP_CONNRESET = -1744830452; IPEndPoint ipep = new IPEndPoint(m_localBindAddress, m_udpPort); + + m_log.DebugFormat( + "[UDPBASE]: Binding UDP listener using internal IP address config {0}:{1}", + ipep.Address, ipep.Port); m_udpSocket = new Socket( AddressFamily.InterNetwork, diff --git a/OpenSim/Region/ClientStack/LindenUDP/PriorityQueue.cs b/OpenSim/Region/ClientStack/LindenUDP/PriorityQueue.cs new file mode 100644 index 0000000000..b62ec07ed9 --- /dev/null +++ b/OpenSim/Region/ClientStack/LindenUDP/PriorityQueue.cs @@ -0,0 +1,245 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; + +using OpenSim.Framework; +using OpenSim.Framework.Client; +using log4net; + +namespace OpenSim.Region.ClientStack.LindenUDP +{ + public class PriorityQueue + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + internal delegate bool UpdatePriorityHandler(ref uint priority, ISceneEntity entity); + + // Heap[0] for self updates + // Heap[1..12] for entity updates + + internal const uint m_numberOfQueues = 12; + + private MinHeap[] m_heaps = new MinHeap[m_numberOfQueues]; + private Dictionary m_lookupTable; + private uint m_nextQueue = 0; + private UInt64 m_nextRequest = 0; + + private object m_syncRoot = new object(); + public object SyncRoot { + get { return this.m_syncRoot; } + } + + internal PriorityQueue() : this(MinHeap.DEFAULT_CAPACITY) { } + + internal PriorityQueue(int capacity) + { + m_lookupTable = new Dictionary(capacity); + + for (int i = 0; i < m_heaps.Length; ++i) + m_heaps[i] = new MinHeap(capacity); + } + + internal int Count + { + get + { + int count = 0; + for (int i = 0; i < m_heaps.Length; ++i) + count += m_heaps[i].Count; + return count; + } + } + + public bool Enqueue(uint pqueue, IEntityUpdate value) + { + LookupItem lookup; + + uint localid = value.Entity.LocalId; + UInt64 entry = m_nextRequest++; + if (m_lookupTable.TryGetValue(localid, out lookup)) + { + entry = lookup.Heap[lookup.Handle].EntryOrder; + value.Update(lookup.Heap[lookup.Handle].Value); + lookup.Heap.Remove(lookup.Handle); + } + + pqueue = Util.Clamp(pqueue, 0, m_numberOfQueues - 1); + lookup.Heap = m_heaps[pqueue]; + lookup.Heap.Add(new MinHeapItem(pqueue, entry, value), ref lookup.Handle); + m_lookupTable[localid] = lookup; + + return true; + } + + internal bool TryDequeue(out IEntityUpdate value, out Int32 timeinqueue) + { + for (int i = 0; i < m_numberOfQueues; ++i) + { + // To get the fair queing, we cycle through each of the + // queues when finding an element to dequeue, this code + // assumes that the distribution of updates in the queues + // is polynomial, probably quadractic (eg distance of PI * R^2) + uint h = (uint)((m_nextQueue + i) % m_numberOfQueues); + if (m_heaps[h].Count > 0) + { + m_nextQueue = (uint)((h + 1) % m_numberOfQueues); + + MinHeapItem item = m_heaps[h].RemoveMin(); + m_lookupTable.Remove(item.Value.Entity.LocalId); + timeinqueue = Util.EnvironmentTickCountSubtract(item.EntryTime); + value = item.Value; + + return true; + } + } + + timeinqueue = 0; + value = default(IEntityUpdate); + return false; + } + + internal void Reprioritize(UpdatePriorityHandler handler) + { + MinHeapItem item; + foreach (LookupItem lookup in new List(this.m_lookupTable.Values)) + { + if (lookup.Heap.TryGetValue(lookup.Handle, out item)) + { + uint pqueue = item.PriorityQueue; + uint localid = item.Value.Entity.LocalId; + + if (handler(ref pqueue, item.Value.Entity)) + { + // unless the priority queue has changed, there is no need to modify + // the entry + pqueue = Util.Clamp(pqueue, 0, m_numberOfQueues - 1); + if (pqueue != item.PriorityQueue) + { + lookup.Heap.Remove(lookup.Handle); + + LookupItem litem = lookup; + litem.Heap = m_heaps[pqueue]; + litem.Heap.Add(new MinHeapItem(pqueue, item), ref litem.Handle); + m_lookupTable[localid] = litem; + } + } + else + { + // m_log.WarnFormat("[PQUEUE]: UpdatePriorityHandler returned false for {0}",item.Value.Entity.UUID); + lookup.Heap.Remove(lookup.Handle); + this.m_lookupTable.Remove(localid); + } + } + } + } + + public override string ToString() + { + string s = ""; + for (int i = 0; i < m_numberOfQueues; i++) + { + if (s != "") s += ","; + s += m_heaps[i].Count.ToString(); + } + return s; + } + +#region MinHeapItem + private struct MinHeapItem : IComparable + { + private IEntityUpdate value; + internal IEntityUpdate Value { + get { + return this.value; + } + } + + private uint pqueue; + internal uint PriorityQueue { + get { + return this.pqueue; + } + } + + private Int32 entrytime; + internal Int32 EntryTime { + get { + return this.entrytime; + } + } + + private UInt64 entryorder; + internal UInt64 EntryOrder + { + get { + return this.entryorder; + } + } + + internal MinHeapItem(uint pqueue, MinHeapItem other) + { + this.entrytime = other.entrytime; + this.entryorder = other.entryorder; + this.value = other.value; + this.pqueue = pqueue; + } + + internal MinHeapItem(uint pqueue, UInt64 entryorder, IEntityUpdate value) + { + this.entrytime = Util.EnvironmentTickCount(); + this.entryorder = entryorder; + this.value = value; + this.pqueue = pqueue; + } + + public override string ToString() + { + return String.Format("[{0},{1},{2}]",pqueue,entryorder,value.Entity.LocalId); + } + + public int CompareTo(MinHeapItem other) + { + // I'm assuming that the root part of an SOG is added to the update queue + // before the component parts + return Comparer.Default.Compare(this.EntryOrder, other.EntryOrder); + } + } +#endregion + +#region LookupItem + private struct LookupItem + { + internal MinHeap Heap; + internal IHandle Handle; + } +#endregion + } +} diff --git a/OpenSim/Region/ClientStack/LindenUDP/TokenBucket.cs b/OpenSim/Region/ClientStack/LindenUDP/TokenBucket.cs index 0a8331f32a..07b0a1df7a 100644 --- a/OpenSim/Region/ClientStack/LindenUDP/TokenBucket.cs +++ b/OpenSim/Region/ClientStack/LindenUDP/TokenBucket.cs @@ -26,6 +26,10 @@ */ using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using log4net; namespace OpenSim.Region.ClientStack.LindenUDP { @@ -35,89 +39,126 @@ namespace OpenSim.Region.ClientStack.LindenUDP /// public class TokenBucket { - /// Parent bucket to this bucket, or null if this is a root - /// bucket - TokenBucket parent; - /// Size of the bucket in bytes. If zero, the bucket has - /// infinite capacity - int maxBurst; - /// Rate that the bucket fills, in bytes per millisecond. If - /// zero, the bucket always remains full - int tokensPerMS; - /// Number of tokens currently in the bucket - int content; - /// Time of the last drip, in system ticks - int lastDrip; + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + private static Int32 m_counter = 0; + + private Int32 m_identifier; + + /// + /// Number of ticks (ms) per quantum, drip rate and max burst + /// are defined over this interval. + /// + private const Int32 m_ticksPerQuantum = 1000; - #region Properties + /// + /// This is the number of quantums worth of packets that can + /// be accommodated during a burst + /// + private const Double m_quantumsPerBurst = 1.5; + + /// + /// + private const Int32 m_minimumDripRate = 1400; + + /// Time of the last drip, in system ticks + private Int32 m_lastDrip; + + /// + /// The number of bytes that can be sent at this moment. This is the + /// current number of tokens in the bucket + /// + private Int64 m_tokenCount; + + /// + /// Map of children buckets and their requested maximum burst rate + /// + private Dictionary m_children = new Dictionary(); + +#region Properties /// /// The parent bucket of this bucket, or null if this bucket has no /// parent. The parent bucket will limit the aggregate bandwidth of all /// of its children buckets /// + private TokenBucket m_parent; public TokenBucket Parent { - get { return parent; } + get { return m_parent; } + set { m_parent = value; } } /// /// Maximum burst rate in bytes per second. This is the maximum number - /// of tokens that can accumulate in the bucket at any one time + /// of tokens that can accumulate in the bucket at any one time. This + /// also sets the total request for leaf nodes /// - public int MaxBurst + private Int64 m_burstRate; + public Int64 RequestedBurstRate { - get { return maxBurst; } - set { maxBurst = (value >= 0 ? value : 0); } + get { return m_burstRate; } + set { m_burstRate = (value < 0 ? 0 : value); } } + public Int64 BurstRate + { + get { + double rate = RequestedBurstRate * BurstRateModifier(); + if (rate < m_minimumDripRate * m_quantumsPerBurst) + rate = m_minimumDripRate * m_quantumsPerBurst; + + return (Int64) rate; + } + } + /// /// The speed limit of this bucket in bytes per second. This is the - /// number of tokens that are added to the bucket per second + /// number of tokens that are added to the bucket per quantum /// /// Tokens are added to the bucket any time /// is called, at the granularity of /// the system tick interval (typically around 15-22ms) - public int DripRate + private Int64 m_dripRate; + public Int64 RequestedDripRate { - get { return tokensPerMS * 1000; } - set - { - if (value == 0) - tokensPerMS = 0; - else - { - int bpms = (int)((float)value / 1000.0f); + get { return (m_dripRate == 0 ? m_totalDripRequest : m_dripRate); } + set { + m_dripRate = (value < 0 ? 0 : value); + m_burstRate = (Int64)((double)m_dripRate * m_quantumsPerBurst); + m_totalDripRequest = m_dripRate; + if (m_parent != null) + m_parent.RegisterRequest(this,m_dripRate); + } + } - if (bpms <= 0) - tokensPerMS = 1; // 1 byte/ms is the minimum granularity - else - tokensPerMS = bpms; - } + public Int64 DripRate + { + get { + if (m_parent == null) + return Math.Min(RequestedDripRate,TotalDripRequest); + + double rate = (double)RequestedDripRate * m_parent.DripRateModifier(); + if (rate < m_minimumDripRate) + rate = m_minimumDripRate; + + return (Int64)rate; } } /// - /// The speed limit of this bucket in bytes per millisecond + /// The current total of the requested maximum burst rates of + /// this bucket's children buckets. /// - public int DripPerMS - { - get { return tokensPerMS; } - } + private Int64 m_totalDripRequest; + public Int64 TotalDripRequest + { + get { return m_totalDripRequest; } + set { m_totalDripRequest = value; } + } + +#endregion Properties - /// - /// The number of bytes that can be sent at this moment. This is the - /// current number of tokens in the bucket - /// If this bucket has a parent bucket that does not have - /// enough tokens for a request, will - /// return false regardless of the content of this bucket - /// - public int Content - { - get { return content; } - } - - #endregion Properties +#region Constructor /// /// Default constructor @@ -128,56 +169,114 @@ namespace OpenSim.Region.ClientStack.LindenUDP /// zero if this bucket has no maximum capacity /// Rate that the bucket fills, in bytes per /// second. If zero, the bucket always remains full - public TokenBucket(TokenBucket parent, int maxBurst, int dripRate) + public TokenBucket(TokenBucket parent, Int64 dripRate) { - this.parent = parent; - MaxBurst = maxBurst; - DripRate = dripRate; - lastDrip = Environment.TickCount & Int32.MaxValue; + m_identifier = m_counter++; + + Parent = parent; + RequestedDripRate = dripRate; + // TotalDripRequest = dripRate; // this will be overwritten when a child node registers + // MaxBurst = (Int64)((double)dripRate * m_quantumsPerBurst); + m_lastDrip = Environment.TickCount & Int32.MaxValue; } +#endregion Constructor + + /// + /// Compute a modifier for the MaxBurst rate. This is 1.0, meaning + /// no modification if the requested bandwidth is less than the + /// max burst bandwidth all the way to the root of the throttle + /// hierarchy. However, if any of the parents is over-booked, then + /// the modifier will be less than 1. + /// + private double DripRateModifier() + { + Int64 driprate = DripRate; + return driprate >= TotalDripRequest ? 1.0 : (double)driprate / (double)TotalDripRequest; + } + + /// + /// + private double BurstRateModifier() + { + // for now... burst rate is always m_quantumsPerBurst (constant) + // larger than drip rate so the ratio of burst requests is the + // same as the drip ratio + return DripRateModifier(); + } + + /// + /// Register drip rate requested by a child of this throttle. Pass the + /// changes up the hierarchy. + /// + public void RegisterRequest(TokenBucket child, Int64 request) + { + m_children[child] = request; + // m_totalDripRequest = m_children.Values.Sum(); + + m_totalDripRequest = 0; + foreach (KeyValuePair cref in m_children) + m_totalDripRequest += cref.Value; + + // Pass the new values up to the parent + if (m_parent != null) + m_parent.RegisterRequest(this,Math.Min(RequestedDripRate, TotalDripRequest)); + } + + /// + /// Remove the rate requested by a child of this throttle. Pass the + /// changes up the hierarchy. + /// + public void UnregisterRequest(TokenBucket child) + { + m_children.Remove(child); + // m_totalDripRequest = m_children.Values.Sum(); + + m_totalDripRequest = 0; + foreach (KeyValuePair cref in m_children) + m_totalDripRequest += cref.Value; + + // Pass the new values up to the parent + if (m_parent != null) + m_parent.RegisterRequest(this,Math.Min(RequestedDripRate, TotalDripRequest)); + } + /// /// Remove a given number of tokens from the bucket /// /// Number of tokens to remove from the bucket /// True if the requested number of tokens were removed from /// the bucket, otherwise false - public bool RemoveTokens(int amount) + public bool RemoveTokens(Int64 amount) { - bool dummy; - return RemoveTokens(amount, out dummy); + // Deposit tokens for this interval + Drip(); + + // If we have enough tokens then remove them and return + if (m_tokenCount - amount >= 0) + { + // we don't have to remove from the parent, the drip rate is already + // reflective of the drip rate limits in the parent + m_tokenCount -= amount; + return true; + } + + return false; } /// - /// Remove a given number of tokens from the bucket + /// Deposit tokens into the bucket from a child bucket that did + /// not use all of its available tokens /// - /// Number of tokens to remove from the bucket - /// True if tokens were added to the bucket - /// during this call, otherwise false - /// True if the requested number of tokens were removed from - /// the bucket, otherwise false - public bool RemoveTokens(int amount, out bool dripSucceeded) + private void Deposit(Int64 count) { - if (maxBurst == 0) - { - dripSucceeded = true; - return true; - } + m_tokenCount += count; - dripSucceeded = Drip(); - - if (content - amount >= 0) - { - if (parent != null && !parent.RemoveTokens(amount)) - return false; - - content -= amount; - return true; - } - else - { - return false; - } + // Deposit the overflow in the parent bucket, this is how we share + // unused bandwidth + Int64 burstrate = BurstRate; + if (m_tokenCount > burstrate) + m_tokenCount = burstrate; } /// @@ -186,37 +285,29 @@ namespace OpenSim.Region.ClientStack.LindenUDP /// call to Drip /// /// True if tokens were added to the bucket, otherwise false - public bool Drip() + private void Drip() { - if (tokensPerMS == 0) + // This should never happen... means we are a leaf node and were created + // with no drip rate... + if (DripRate == 0) { - content = maxBurst; - return true; + m_log.WarnFormat("[TOKENBUCKET] something odd is happening and drip rate is 0"); + return; } - else - { - int now = Environment.TickCount & Int32.MaxValue; - int deltaMS = now - lastDrip; + + // Determine the interval over which we are adding tokens, never add + // more than a single quantum of tokens + Int32 now = Environment.TickCount & Int32.MaxValue; + Int32 deltaMS = Math.Min(now - m_lastDrip, m_ticksPerQuantum); - if (deltaMS <= 0) - { - if (deltaMS < 0) - lastDrip = now; - return false; - } + m_lastDrip = now; - int dripAmount = deltaMS * tokensPerMS; + // This can be 0 in the very unusual case that the timer wrapped + // It can be 0 if we try add tokens at a sub-tick rate + if (deltaMS <= 0) + return; - content = Math.Min(content + dripAmount, maxBurst); - lastDrip = now; - - if (dripAmount < 0 || content < 0) - // sim has been idle for too long, integer has overflown - // previous calculation is meaningless, let's put it at correct max - content = maxBurst; - - return true; - } + Deposit(deltaMS * DripRate / m_ticksPerQuantum); } } } diff --git a/OpenSim/Region/CoreModules/Avatar/Assets/GetMeshModule.cs b/OpenSim/Region/CoreModules/Avatar/Assets/GetMeshModule.cs index 878242a447..deec444e8b 100644 --- a/OpenSim/Region/CoreModules/Avatar/Assets/GetMeshModule.cs +++ b/OpenSim/Region/CoreModules/Avatar/Assets/GetMeshModule.cs @@ -54,6 +54,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Assets private Scene m_scene; private IAssetService m_assetService; + private bool m_enabled = true; #region IRegionModuleBase Members @@ -65,7 +66,11 @@ namespace OpenSim.Region.CoreModules.Avatar.Assets public void Initialise(IConfigSource source) { - + IConfig meshConfig = source.Configs["Mesh"]; + if (meshConfig == null) + return; + + m_enabled = meshConfig.GetBoolean("ColladaMesh", true); } public void AddRegion(Scene pScene) @@ -101,16 +106,19 @@ namespace OpenSim.Region.CoreModules.Avatar.Assets public void RegisterCaps(UUID agentID, Caps caps) { + if(!m_enabled) + return; + UUID capID = UUID.Random(); // m_log.Info("[GETMESH]: /CAPS/" + capID); + caps.RegisterHandler("GetMesh", new RestHTTPHandler("GET", "/CAPS/" + capID, delegate(Hashtable m_dhttpMethod) { return ProcessGetMesh(m_dhttpMethod, agentID, caps); })); - } #endregion diff --git a/OpenSim/Region/CoreModules/Avatar/Assets/NewFileAgentInventoryVariablePriceModule.cs b/OpenSim/Region/CoreModules/Avatar/Assets/NewFileAgentInventoryVariablePriceModule.cs index 4a42c938d5..d651cb26f8 100644 --- a/OpenSim/Region/CoreModules/Avatar/Assets/NewFileAgentInventoryVariablePriceModule.cs +++ b/OpenSim/Region/CoreModules/Avatar/Assets/NewFileAgentInventoryVariablePriceModule.cs @@ -56,6 +56,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Assets private Scene m_scene; // private IAssetService m_assetService; private bool m_dumpAssetsToFile = false; + private bool m_enabled = true; #region IRegionModuleBase Members @@ -67,7 +68,11 @@ namespace OpenSim.Region.CoreModules.Avatar.Assets public void Initialise(IConfigSource source) { - + IConfig meshConfig = source.Configs["Mesh"]; + if (meshConfig == null) + return; + + m_enabled = meshConfig.GetBoolean("ColladaMesh", true); } public void AddRegion(Scene pScene) @@ -103,6 +108,9 @@ namespace OpenSim.Region.CoreModules.Avatar.Assets public void RegisterCaps(UUID agentID, Caps caps) { + if(!m_enabled) + return; + UUID capID = UUID.Random(); // m_log.Debug("[NEW FILE AGENT INVENTORY VARIABLE PRICE]: /CAPS/" + capID); diff --git a/OpenSim/Region/CoreModules/Avatar/Friends/FriendsModule.cs b/OpenSim/Region/CoreModules/Avatar/Friends/FriendsModule.cs index 4d74b2a0a0..5baf0785f4 100644 --- a/OpenSim/Region/CoreModules/Avatar/Friends/FriendsModule.cs +++ b/OpenSim/Region/CoreModules/Avatar/Friends/FriendsModule.cs @@ -34,13 +34,13 @@ using Nini.Config; using Nwc.XmlRpc; using OpenMetaverse; using OpenSim.Framework; +using OpenSim.Framework.Servers.HttpServer; using OpenSim.Framework.Communications; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using OpenSim.Services.Connectors.Friends; using OpenSim.Server.Base; -using OpenSim.Framework.Servers.HttpServer; using FriendInfo = OpenSim.Services.Interfaces.FriendInfo; using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo; using GridRegion = OpenSim.Services.Interfaces.GridRegion; diff --git a/OpenSim/Region/CoreModules/Avatar/InstantMessage/OfflineMessageModule.cs b/OpenSim/Region/CoreModules/Avatar/InstantMessage/OfflineMessageModule.cs index fdfcd104c0..919ea338f4 100644 --- a/OpenSim/Region/CoreModules/Avatar/InstantMessage/OfflineMessageModule.cs +++ b/OpenSim/Region/CoreModules/Avatar/InstantMessage/OfflineMessageModule.cs @@ -33,7 +33,6 @@ using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Framework.Servers; -using OpenSim.Framework.Servers.HttpServer; using OpenSim.Framework.Client; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; diff --git a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveReadRequest.cs b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveReadRequest.cs index 9b98de3b67..6b247180d8 100644 --- a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveReadRequest.cs +++ b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveReadRequest.cs @@ -77,7 +77,17 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver /// private Stream m_loadStream; - protected bool m_controlFileLoaded; + /// + /// Has the control file been loaded for this archive? + /// + public bool ControlFileLoaded { get; private set; } + + /// + /// Do we want to enforce the check. IAR versions before 0.2 and 1.1 do not guarantee this order, so we can't + /// enforce. + /// + public bool EnforceControlFileCheck { get; private set; } + protected bool m_assetsLoaded; protected bool m_inventoryNodesLoaded; @@ -126,6 +136,11 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver m_userInfo = userInfo; m_invPath = invPath; m_loadStream = loadStream; + + // FIXME: Do not perform this check since older versions of OpenSim do save the control file after other things + // (I thought they weren't). We will need to bump the version number and perform this check on all + // subsequent IAR versions only + ControlFileLoaded = true; } /// @@ -466,16 +481,30 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver if (m_creatorIdForAssetId.ContainsKey(assetId)) { string xmlData = Utils.BytesToString(data); - SceneObjectGroup sog = SceneObjectSerializer.FromOriginalXmlFormat(xmlData); - foreach (SceneObjectPart sop in sog.Parts) + List sceneObjects = new List(); + + CoalescedSceneObjects coa = null; + if (CoalescedSceneObjectsSerializer.TryFromXml(xmlData, out coa)) { - if (sop.CreatorData == null || sop.CreatorData == "") - { - sop.CreatorID = m_creatorIdForAssetId[assetId]; - } +// m_log.DebugFormat( +// "[INVENTORY ARCHIVER]: Loaded coalescence {0} has {1} objects", assetId, coa.Count); + + sceneObjects.AddRange(coa.Objects); + } + else + { + sceneObjects.Add(SceneObjectSerializer.FromOriginalXmlFormat(xmlData)); } - data = Utils.StringToBytes(SceneObjectSerializer.ToOriginalXmlFormat(sog)); + foreach (SceneObjectGroup sog in sceneObjects) + foreach (SceneObjectPart sop in sog.Parts) + if (sop.CreatorData == null || sop.CreatorData == "") + sop.CreatorID = m_creatorIdForAssetId[assetId]; + + if (coa != null) + data = Utils.StringToBytes(CoalescedSceneObjectsSerializer.ToXml(coa)); + else + data = Utils.StringToBytes(SceneObjectSerializer.ToOriginalXmlFormat(sceneObjects[0])); } } @@ -503,7 +532,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver /// /// /// - protected void LoadControlFile(string path, byte[] data) + public void LoadControlFile(string path, byte[] data) { XDocument doc = XDocument.Parse(Encoding.ASCII.GetString(data)); XElement archiveElement = doc.Element("archive"); @@ -519,7 +548,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver majorVersion, MAX_MAJOR_VERSION)); } - m_controlFileLoaded = true; + ControlFileLoaded = true; m_log.InfoFormat("[INVENTORY ARCHIVER]: Loading IAR with version {0}", version); } @@ -531,7 +560,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver /// protected void LoadInventoryFile(string path, TarArchiveReader.TarEntryType entryType, byte[] data) { - if (!m_controlFileLoaded) + if (!ControlFileLoaded) throw new Exception( string.Format( "The IAR you are trying to load does not list {0} before {1}. Aborting load", @@ -578,7 +607,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver /// protected void LoadAssetFile(string path, byte[] data) { - if (!m_controlFileLoaded) + if (!ControlFileLoaded) throw new Exception( string.Format( "The IAR you are trying to load does not list {0} before {1}. Aborting load", diff --git a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveWriteRequest.cs b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveWriteRequest.cs index dc4900f5a7..c039b5a387 100644 --- a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveWriteRequest.cs +++ b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveWriteRequest.cs @@ -394,12 +394,12 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver if (options.ContainsKey("profile")) { majorVersion = 1; - minorVersion = 0; + minorVersion = 1; } else { majorVersion = 0; - minorVersion = 1; + minorVersion = 2; } m_log.InfoFormat("[INVENTORY ARCHIVER]: Creating version {0}.{1} IAR", majorVersion, minorVersion); diff --git a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/Tests/InventoryArchiveTestCase.cs b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/Tests/InventoryArchiveTestCase.cs index e5127a0118..5ba08ee094 100644 --- a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/Tests/InventoryArchiveTestCase.cs +++ b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/Tests/InventoryArchiveTestCase.cs @@ -68,17 +68,21 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests PrincipalID = UUID.Parse("00000000-0000-0000-0000-000000000555"), FirstName = "Mr", LastName = "Tiddles" }; + protected UserAccount m_uaLL1 = new UserAccount { PrincipalID = UUID.Parse("00000000-0000-0000-0000-000000000666"), FirstName = "Lord", LastName = "Lucan" }; + protected UserAccount m_uaLL2 = new UserAccount { PrincipalID = UUID.Parse("00000000-0000-0000-0000-000000000777"), FirstName = "Lord", - LastName = "Lucan" }; + LastName = "Lucan" }; + protected string m_item1Name = "Ray Gun Item"; + protected string m_coaItemName = "Coalesced Item"; [SetUp] public virtual void SetUp() @@ -97,38 +101,22 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests // log4net.Config.XmlConfigurator.Configure(); InventoryArchiverModule archiverModule = new InventoryArchiverModule(); - Scene scene = SceneSetupHelpers.SetupScene("Inventory"); + Scene scene = SceneSetupHelpers.SetupScene(); SceneSetupHelpers.SetupSceneModules(scene, archiverModule); UserProfileTestUtils.CreateUserWithInventory(scene, m_uaLL1, "hampshire"); MemoryStream archiveWriteStream = new MemoryStream(); - // Create asset - SceneObjectGroup object1; - SceneObjectPart part1; - { - string partName = "Ray Gun Object"; - UUID ownerId = UUID.Parse("00000000-0000-0000-0000-000000000040"); - PrimitiveBaseShape shape = PrimitiveBaseShape.CreateSphere(); - Vector3 groupPosition = new Vector3(10, 20, 30); - Quaternion rotationOffset = new Quaternion(20, 30, 40, 50); - Vector3 offsetPosition = new Vector3(5, 10, 15); - - part1 - = new SceneObjectPart( - ownerId, shape, groupPosition, rotationOffset, offsetPosition); - part1.Name = partName; - - object1 = new SceneObjectGroup(part1); - scene.AddNewSceneObject(object1, false); - } + // Create scene object asset + UUID ownerId = UUID.Parse("00000000-0000-0000-0000-000000000040"); + SceneObjectGroup object1 = SceneSetupHelpers.CreateSceneObject(1, ownerId, "Ray Gun Object", 0x50); UUID asset1Id = UUID.Parse("00000000-0000-0000-0000-000000000060"); AssetBase asset1 = AssetHelpers.CreateAsset(asset1Id, object1); scene.AssetService.Store(asset1); - // Create item + // Create scene object item InventoryItemBase item1 = new InventoryItemBase(); item1.Name = m_item1Name; item1.ID = UUID.Parse("00000000-0000-0000-0000-000000000020"); @@ -139,8 +127,31 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests item1.Folder = scene.InventoryService.GetRootFolder(m_uaLL1.PrincipalID).ID; scene.AddInventoryItem(item1); + // Create coalesced objects asset + SceneObjectGroup cobj1 = SceneSetupHelpers.CreateSceneObject(1, m_uaLL1.PrincipalID, "Object1", 0x120); + cobj1.AbsolutePosition = new Vector3(15, 30, 45); + + SceneObjectGroup cobj2 = SceneSetupHelpers.CreateSceneObject(1, m_uaLL1.PrincipalID, "Object2", 0x140); + cobj2.AbsolutePosition = new Vector3(25, 50, 75); + + CoalescedSceneObjects coa = new CoalescedSceneObjects(m_uaLL1.PrincipalID, cobj1, cobj2); + + AssetBase coaAsset = AssetHelpers.CreateAsset(0x160, coa); + scene.AssetService.Store(coaAsset); + + // Create coalesced objects inventory item + InventoryItemBase coaItem = new InventoryItemBase(); + coaItem.Name = m_coaItemName; + coaItem.ID = UUID.Parse("00000000-0000-0000-0000-000000000180"); + coaItem.AssetID = coaAsset.FullID; + coaItem.GroupID = UUID.Random(); + coaItem.CreatorIdAsUuid = m_uaLL1.PrincipalID; + coaItem.Owner = m_uaLL1.PrincipalID; + coaItem.Folder = scene.InventoryService.GetRootFolder(m_uaLL1.PrincipalID).ID; + scene.AddInventoryItem(coaItem); + archiverModule.ArchiveInventory( - Guid.NewGuid(), m_uaLL1.FirstName, m_uaLL1.LastName, m_item1Name, "hampshire", archiveWriteStream); + Guid.NewGuid(), m_uaLL1.FirstName, m_uaLL1.LastName, "/*", "hampshire", archiveWriteStream); m_iarStreamBytes = archiveWriteStream.ToArray(); } diff --git a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/Tests/InventoryArchiverTests.cs b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/Tests/InventoryArchiverTests.cs index 7f156f8904..52232a0c9e 100644 --- a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/Tests/InventoryArchiverTests.cs +++ b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/Tests/InventoryArchiverTests.cs @@ -62,9 +62,66 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests SerialiserModule serialiserModule = new SerialiserModule(); m_archiverModule = new InventoryArchiverModule(); - m_scene = SceneSetupHelpers.SetupScene("Inventory"); + m_scene = SceneSetupHelpers.SetupScene(); SceneSetupHelpers.SetupSceneModules(m_scene, serialiserModule, m_archiverModule); } + + [Test] + public void TestLoadCoalesecedItem() + { + TestHelper.InMethod(); +// log4net.Config.XmlConfigurator.Configure(); + + UserProfileTestUtils.CreateUserWithInventory(m_scene, m_uaLL1, "password"); + m_archiverModule.DearchiveInventory(m_uaLL1.FirstName, m_uaLL1.LastName, "/", "password", m_iarStream); + + InventoryItemBase coaItem + = InventoryArchiveUtils.FindItemByPath(m_scene.InventoryService, m_uaLL1.PrincipalID, m_coaItemName); + + Assert.That(coaItem, Is.Not.Null, "Didn't find loaded item 1"); + + string assetXml = AssetHelpers.ReadAssetAsString(m_scene.AssetService, coaItem.AssetID); + + CoalescedSceneObjects coa; + bool readResult = CoalescedSceneObjectsSerializer.TryFromXml(assetXml, out coa); + + Assert.That(readResult, Is.True); + Assert.That(coa.Count, Is.EqualTo(2)); + + List coaObjects = coa.Objects; + Assert.That(coaObjects[0].UUID, Is.EqualTo(UUID.Parse("00000000-0000-0000-0000-000000000120"))); + Assert.That(coaObjects[0].AbsolutePosition, Is.EqualTo(new Vector3(15, 30, 45))); + + Assert.That(coaObjects[1].UUID, Is.EqualTo(UUID.Parse("00000000-0000-0000-0000-000000000140"))); + Assert.That(coaObjects[1].AbsolutePosition, Is.EqualTo(new Vector3(25, 50, 75))); + } + + /// + /// Test that the IAR has the required files in the right order. + /// + /// + /// At the moment, the only thing that matters is that the control file is the very first one. + /// + [Test] + public void TestOrder() + { + TestHelper.InMethod(); +// log4net.Config.XmlConfigurator.Configure(); + + MemoryStream archiveReadStream = new MemoryStream(m_iarStreamBytes); + TarArchiveReader tar = new TarArchiveReader(archiveReadStream); + string filePath; + TarArchiveReader.TarEntryType tarEntryType; + + byte[] data = tar.ReadEntry(out filePath, out tarEntryType); + Assert.That(filePath, Is.EqualTo(ArchiveConstants.CONTROL_FILE_PATH)); + + InventoryArchiveReadRequest iarr + = new InventoryArchiveReadRequest(null, null, null, (Stream)null, false); + iarr.LoadControlFile(filePath, data); + + Assert.That(iarr.ControlFileLoaded, Is.True); + } /// /// Test saving a single inventory item to a V0.1 OpenSim Inventory Archive @@ -84,24 +141,8 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests UserProfileTestUtils.CreateUserWithInventory(m_scene, userFirstName, userLastName, userId, userPassword); // Create asset - SceneObjectGroup object1; - SceneObjectPart part1; - { - string partName = "My Little Dog Object"; - UUID ownerId = UUID.Parse("00000000-0000-0000-0000-000000000040"); - PrimitiveBaseShape shape = PrimitiveBaseShape.CreateSphere(); - Vector3 groupPosition = new Vector3(10, 20, 30); - Quaternion rotationOffset = new Quaternion(20, 30, 40, 50); - Vector3 offsetPosition = new Vector3(5, 10, 15); - - part1 - = new SceneObjectPart( - ownerId, shape, groupPosition, rotationOffset, offsetPosition); - part1.Name = partName; - - object1 = new SceneObjectGroup(part1); - m_scene.AddNewSceneObject(object1, false); - } + UUID ownerId = UUID.Parse("00000000-0000-0000-0000-000000000040"); + SceneObjectGroup object1 = SceneSetupHelpers.CreateSceneObject(1, ownerId, "My Little Dog Object", 0x50); UUID asset1Id = UUID.Parse("00000000-0000-0000-0000-000000000060"); AssetBase asset1 = AssetHelpers.CreateAsset(asset1Id, object1); diff --git a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/Tests/PathTests.cs b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/Tests/PathTests.cs index 0e8f647dbc..c7dae5276b 100644 --- a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/Tests/PathTests.cs +++ b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/Tests/PathTests.cs @@ -63,7 +63,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests InventoryArchiverModule archiverModule = new InventoryArchiverModule(); - Scene scene = SceneSetupHelpers.SetupScene("Inventory"); + Scene scene = SceneSetupHelpers.SetupScene(); SceneSetupHelpers.SetupSceneModules(scene, archiverModule); // Create user @@ -180,7 +180,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests InventoryArchiverModule archiverModule = new InventoryArchiverModule(); // Annoyingly, we have to set up a scene even though inventory loading has nothing to do with a scene - Scene scene = SceneSetupHelpers.SetupScene("inventory"); + Scene scene = SceneSetupHelpers.SetupScene(); SceneSetupHelpers.SetupSceneModules(scene, serialiserModule, archiverModule); @@ -223,7 +223,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests SerialiserModule serialiserModule = new SerialiserModule(); InventoryArchiverModule archiverModule = new InventoryArchiverModule(); - Scene scene = SceneSetupHelpers.SetupScene("inventory"); + Scene scene = SceneSetupHelpers.SetupScene(); SceneSetupHelpers.SetupSceneModules(scene, serialiserModule, archiverModule); UserProfileTestUtils.CreateUserWithInventory(scene, m_uaMT, "password"); @@ -248,7 +248,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests InventoryArchiverModule archiverModule = new InventoryArchiverModule(); - Scene scene = SceneSetupHelpers.SetupScene("Inventory"); + Scene scene = SceneSetupHelpers.SetupScene(); SceneSetupHelpers.SetupSceneModules(scene, archiverModule); // Create user @@ -327,7 +327,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests TestHelper.InMethod(); // log4net.Config.XmlConfigurator.Configure(); - Scene scene = SceneSetupHelpers.SetupScene("inventory"); + Scene scene = SceneSetupHelpers.SetupScene(); UserAccount ua1 = UserProfileTestUtils.CreateUserWithInventory(scene); Dictionary foldersCreated = new Dictionary(); @@ -394,7 +394,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests TestHelper.InMethod(); //log4net.Config.XmlConfigurator.Configure(); - Scene scene = SceneSetupHelpers.SetupScene("inventory"); + Scene scene = SceneSetupHelpers.SetupScene(); UserAccount ua1 = UserProfileTestUtils.CreateUserWithInventory(scene); string folder1ExistingName = "a"; @@ -445,7 +445,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests TestHelper.InMethod(); // log4net.Config.XmlConfigurator.Configure(); - Scene scene = SceneSetupHelpers.SetupScene("inventory"); + Scene scene = SceneSetupHelpers.SetupScene(); UserAccount ua1 = UserProfileTestUtils.CreateUserWithInventory(scene); string folder1ExistingName = "a"; diff --git a/OpenSim/Region/CoreModules/Framework/InventoryAccess/HGInventoryAccessModule.cs b/OpenSim/Region/CoreModules/Framework/InventoryAccess/HGInventoryAccessModule.cs index 4565d103ff..52791cb046 100644 --- a/OpenSim/Region/CoreModules/Framework/InventoryAccess/HGInventoryAccessModule.cs +++ b/OpenSim/Region/CoreModules/Framework/InventoryAccess/HGInventoryAccessModule.cs @@ -75,6 +75,9 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess if (name == Name) { m_Enabled = true; + + InitialiseCommon(source); + m_log.InfoFormat("[HG INVENTORY ACCESS MODULE]: {0} enabled.", Name); IConfig thisModuleConfig = source.Configs["HGInventoryAccessModule"]; @@ -129,35 +132,14 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess } /// - /// DeleteToInventory + /// Used in DeleteToInventory /// - public override UUID DeleteToInventory(DeRezAction action, UUID folderID, List objectGroups, IClientAPI remoteClient) + protected override void ExportAsset(UUID agentID, UUID assetID) { - UUID ret = UUID.Zero; - - // HACK: Only works for lists of length one. - // Intermediate version, just to make things compile - foreach (SceneObjectGroup g in objectGroups) - ret = DeleteToInventory(action, folderID, g, remoteClient); - - return ret; - } - - // DO NOT OVERRIDE THE BASE METHOD - public new virtual UUID DeleteToInventory(DeRezAction action, UUID folderID, - SceneObjectGroup objectGroup, IClientAPI remoteClient) - { - UUID assetID = base.DeleteToInventory(action, folderID, new List() {objectGroup}, remoteClient); - if (!assetID.Equals(UUID.Zero)) - { - if (remoteClient != null) - UploadInventoryItem(remoteClient.AgentId, assetID, "", 0); - } + UploadInventoryItem(agentID, assetID, "", 0); else m_log.Debug("[HGScene]: Scene.Inventory did not create asset"); - - return assetID; } /// diff --git a/OpenSim/Region/CoreModules/Framework/InventoryAccess/InventoryAccessModule.cs b/OpenSim/Region/CoreModules/Framework/InventoryAccess/InventoryAccessModule.cs index 798547a82d..6b3df9ddd6 100644 --- a/OpenSim/Region/CoreModules/Framework/InventoryAccess/InventoryAccessModule.cs +++ b/OpenSim/Region/CoreModules/Framework/InventoryAccess/InventoryAccessModule.cs @@ -28,6 +28,7 @@ using System; using System.Collections.Generic; using System.Net; +using System.Xml; using System.Reflection; using System.Threading; @@ -63,7 +64,8 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess return m_UserManagement; } } - + + public bool CoalesceMultipleObjectsToInventory { get; set; } #region INonSharedRegionModule @@ -86,10 +88,28 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess if (name == Name) { m_Enabled = true; - m_log.InfoFormat("[INVENTORY ACCESS MODULE]: {0} enabled.", Name); + + InitialiseCommon(source); + + m_log.InfoFormat("[INVENTORY ACCESS MODULE]: {0} enabled.", Name); } } } + + /// + /// Common module config for both this and descendant classes. + /// + /// + protected virtual void InitialiseCommon(IConfigSource source) + { + IConfig inventoryConfig = source.Configs["Inventory"]; + + if (inventoryConfig != null) + CoalesceMultipleObjectsToInventory + = inventoryConfig.GetBoolean("CoalesceMultipleObjectsToInventory", true); + else + CoalesceMultipleObjectsToInventory = true; + } public virtual void PostInitialise() { @@ -193,269 +213,142 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess return UUID.Zero; } + + public virtual UUID CopyToInventory(DeRezAction action, UUID folderID, + List objectGroups, IClientAPI remoteClient) + { + Dictionary> bundlesToCopy = new Dictionary>(); + + if (CoalesceMultipleObjectsToInventory) + { + // The following code groups the SOG's by owner. No objects + // belonging to different people can be coalesced, for obvious + // reasons. + foreach (SceneObjectGroup g in objectGroups) + { + if (!bundlesToCopy.ContainsKey(g.OwnerID)) + bundlesToCopy[g.OwnerID] = new List(); + + bundlesToCopy[g.OwnerID].Add(g); + } + } + else + { + // If we don't want to coalesce then put every object in its own bundle. + foreach (SceneObjectGroup g in objectGroups) + { + List bundle = new List(); + bundle.Add(g); + bundlesToCopy[g.UUID] = bundle; + } + } + // This is method scoped and will be returned. It will be the + // last created asset id + UUID assetID = UUID.Zero; + + // Each iteration is really a separate asset being created, + // with distinct destinations as well. + foreach (List bundle in bundlesToCopy.Values) + assetID = CopyBundleToInventory(action, folderID, bundle, remoteClient); + + return assetID; + } + /// - /// Delete a scene object from a scene and place in the given avatar's inventory. - /// Returns the UUID of the newly created asset. + /// Copy a bundle of objects to inventory. If there is only one object, then this will create an object + /// item. If there are multiple objects then these will be saved as a single coalesced item. /// /// /// - /// - /// - public virtual UUID DeleteToInventory(DeRezAction action, UUID folderID, - List objectGroups, IClientAPI remoteClient) - { - // HACK: This is only working for lists containing a single item! - // It's just a hack to make this WIP compile and run. Nothing - // currently calls this with multiple items. - UUID ret = UUID.Zero; - - Dictionary> deletes = - new Dictionary>(); - - foreach (SceneObjectGroup g in objectGroups) - { - if (!deletes.ContainsKey(g.OwnerID)) - deletes[g.OwnerID] = new List(); - - deletes[g.OwnerID].Add(g); - } - - foreach (List objlist in deletes.Values) - { - foreach (SceneObjectGroup g in objlist) - ret = DeleteToInventory(action, folderID, g, remoteClient); - } - - return ret; - } - - private UUID DeleteToInventory(DeRezAction action, UUID folderID, - SceneObjectGroup objectGroup, IClientAPI remoteClient) + /// + /// + /// + protected UUID CopyBundleToInventory( + DeRezAction action, UUID folderID, List objlist, IClientAPI remoteClient) { UUID assetID = UUID.Zero; + + CoalescedSceneObjects coa = new CoalescedSceneObjects(UUID.Zero); + Dictionary originalPositions = new Dictionary(); - Vector3 inventoryStoredPosition = new Vector3 - (((objectGroup.AbsolutePosition.X > (int)Constants.RegionSize) - ? 250 - : objectGroup.AbsolutePosition.X) - , - (objectGroup.AbsolutePosition.X > (int)Constants.RegionSize) - ? 250 - : objectGroup.AbsolutePosition.X, - objectGroup.AbsolutePosition.Z); - - Vector3 originalPosition = objectGroup.AbsolutePosition; - - objectGroup.AbsolutePosition = inventoryStoredPosition; - - string sceneObjectXml = SceneObjectSerializer.ToOriginalXmlFormat(objectGroup); - - objectGroup.AbsolutePosition = originalPosition; - - // Get the user info of the item destination - // - UUID userID = UUID.Zero; - - if (action == DeRezAction.Take || action == DeRezAction.TakeCopy || - action == DeRezAction.SaveToExistingUserInventoryItem) + foreach (SceneObjectGroup objectGroup in objlist) { - // Take or take copy require a taker - // Saving changes requires a local user - // - if (remoteClient == null) - return UUID.Zero; + Vector3 inventoryStoredPosition = new Vector3 + (((objectGroup.AbsolutePosition.X > (int)Constants.RegionSize) + ? 250 + : objectGroup.AbsolutePosition.X) + , + (objectGroup.AbsolutePosition.Y > (int)Constants.RegionSize) + ? 250 + : objectGroup.AbsolutePosition.Y, + objectGroup.AbsolutePosition.Z); - userID = remoteClient.AgentId; + originalPositions[objectGroup.UUID] = objectGroup.AbsolutePosition; + + objectGroup.AbsolutePosition = inventoryStoredPosition; + + // Make sure all bits but the ones we want are clear + // on take. + // This will be applied to the current perms, so + // it will do what we want. + objectGroup.RootPart.NextOwnerMask &= + ((uint)PermissionMask.Copy | + (uint)PermissionMask.Transfer | + (uint)PermissionMask.Modify); + objectGroup.RootPart.NextOwnerMask |= + (uint)PermissionMask.Move; + + coa.Add(objectGroup); } + + string itemXml; + + if (objlist.Count > 1) + itemXml = CoalescedSceneObjectsSerializer.ToXml(coa); else - { - // All returns / deletes go to the object owner - // + itemXml = SceneObjectSerializer.ToOriginalXmlFormat(objlist[0]); + + // Restore the position of each group now that it has been stored to inventory. + foreach (SceneObjectGroup objectGroup in objlist) + objectGroup.AbsolutePosition = originalPositions[objectGroup.UUID]; - userID = objectGroup.RootPart.OwnerID; - } - - if (userID == UUID.Zero) // Can't proceed - { + InventoryItemBase item = CreateItemForObject(action, remoteClient, objlist[0], folderID); + if (item == null) return UUID.Zero; - } - - // If we're returning someone's item, it goes back to the - // owner's Lost And Found folder. - // Delete is treated like return in this case - // Deleting your own items makes them go to trash - // - - InventoryFolderBase folder = null; - InventoryItemBase item = null; - - if (DeRezAction.SaveToExistingUserInventoryItem == action) + + // Can't know creator is the same, so null it in inventory + if (objlist.Count > 1) { - item = new InventoryItemBase(objectGroup.RootPart.FromUserInventoryItemID, userID); - item = m_Scene.InventoryService.GetItem(item); - - //item = userInfo.RootFolder.FindItem( - // objectGroup.RootPart.FromUserInventoryItemID); - - if (null == item) - { - m_log.DebugFormat( - "[AGENT INVENTORY]: Object {0} {1} scheduled for save to inventory has already been deleted.", - objectGroup.Name, objectGroup.UUID); - return UUID.Zero; - } + item.CreatorId = UUID.Zero.ToString(); + item.Flags = (uint)InventoryItemFlags.ObjectHasMultipleItems; } else { - // Folder magic - // - if (action == DeRezAction.Delete) - { - // Deleting someone else's item - // - if (remoteClient == null || - objectGroup.OwnerID != remoteClient.AgentId) - { - - folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.LostAndFoundFolder); - } - else - { - folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.TrashFolder); - } - } - else if (action == DeRezAction.Return) - { - - // Dump to lost + found unconditionally - // - folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.LostAndFoundFolder); - } - - if (folderID == UUID.Zero && folder == null) - { - if (action == DeRezAction.Delete) - { - // Deletes go to trash by default - // - folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.TrashFolder); - } - else - { - if (remoteClient == null || - objectGroup.OwnerID != remoteClient.AgentId) - { - // Taking copy of another person's item. Take to - // Objects folder. - folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.Object); - } - else - { - // Catch all. Use lost & found - // - - folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.LostAndFoundFolder); - } - } - } - - // Override and put into where it came from, if it came - // from anywhere in inventory - // - if (action == DeRezAction.Take || action == DeRezAction.TakeCopy) - { - if (objectGroup.RootPart.FromFolderID != UUID.Zero) - { - InventoryFolderBase f = new InventoryFolderBase(objectGroup.RootPart.FromFolderID, userID); - folder = m_Scene.InventoryService.GetFolder(f); - } - } - - if (folder == null) // None of the above - { - folder = new InventoryFolderBase(folderID); - - if (folder == null) // Nowhere to put it - { - return UUID.Zero; - } - } - - item = new InventoryItemBase(); - item.CreatorId = objectGroup.RootPart.CreatorID.ToString(); - item.CreatorData = objectGroup.RootPart.CreatorData; - item.ID = UUID.Random(); - item.InvType = (int)InventoryType.Object; - item.Folder = folder.ID; - item.Owner = userID; - } + item.CreatorId = objlist[0].RootPart.CreatorID.ToString(); + item.SaleType = objlist[0].RootPart.ObjectSaleType; + item.SalePrice = objlist[0].RootPart.SalePrice; + } AssetBase asset = CreateAsset( - objectGroup.GetPartName(objectGroup.RootPart.LocalId), - objectGroup.GetPartDescription(objectGroup.RootPart.LocalId), + objlist[0].GetPartName(objlist[0].RootPart.LocalId), + objlist[0].GetPartDescription(objlist[0].RootPart.LocalId), (sbyte)AssetType.Object, - Utils.StringToBytes(sceneObjectXml), - objectGroup.OwnerID.ToString()); + Utils.StringToBytes(itemXml), + objlist[0].OwnerID.ToString()); m_Scene.AssetService.Store(asset); - assetID = asset.FullID; + + item.AssetID = asset.FullID; + assetID = asset.FullID; if (DeRezAction.SaveToExistingUserInventoryItem == action) { - item.AssetID = asset.FullID; m_Scene.InventoryService.UpdateItem(item); } else { - item.AssetID = asset.FullID; + AddPermissions(item, objlist[0], objlist, remoteClient); - if (remoteClient != null && (remoteClient.AgentId != objectGroup.RootPart.OwnerID) && m_Scene.Permissions.PropagatePermissions()) - { - uint perms = objectGroup.GetEffectivePermissions(); - 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; - - // Make sure all bits but the ones we want are clear - // on take. - // This will be applied to the current perms, so - // it will do what we want. - objectGroup.RootPart.NextOwnerMask &= - ((uint)PermissionMask.Copy | - (uint)PermissionMask.Transfer | - (uint)PermissionMask.Modify); - objectGroup.RootPart.NextOwnerMask |= - (uint)PermissionMask.Move; - - item.BasePermissions = perms & objectGroup.RootPart.NextOwnerMask; - item.CurrentPermissions = item.BasePermissions; - item.NextPermissions = objectGroup.RootPart.NextOwnerMask; - item.EveryOnePermissions = objectGroup.RootPart.EveryoneMask & objectGroup.RootPart.NextOwnerMask; - item.GroupPermissions = objectGroup.RootPart.GroupMask & objectGroup.RootPart.NextOwnerMask; - - item.Flags |= (uint)InventoryItemFlags.ObjectSlamPerm; - } - else - { - item.BasePermissions = objectGroup.GetEffectivePermissions(); - item.CurrentPermissions = objectGroup.GetEffectivePermissions(); - item.NextPermissions = objectGroup.RootPart.NextOwnerMask; - item.EveryOnePermissions = objectGroup.RootPart.EveryoneMask; - item.GroupPermissions = objectGroup.RootPart.GroupMask; - - item.CurrentPermissions &= - ((uint)PermissionMask.Copy | - (uint)PermissionMask.Transfer | - (uint)PermissionMask.Modify | - (uint)PermissionMask.Move | - 7); // Preserve folded permissions - } - - // TODO: add the new fields (Flags, Sale info, etc) item.CreationDate = Util.UnixTimeSinceEpoch(); item.Description = asset.Description; item.Name = asset.Name; @@ -477,15 +370,229 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess } } + // This is a hook to do some per-asset post-processing for subclasses that need that + ExportAsset(remoteClient.AgentId, assetID); + return assetID; } + protected virtual void ExportAsset(UUID agentID, UUID assetID) + { + // nothing to do here + } + + /// + /// Add relevant permissions for an object to the item. + /// + /// + /// + /// + /// + /// + protected InventoryItemBase AddPermissions( + InventoryItemBase item, SceneObjectGroup so, List objsForEffectivePermissions, + IClientAPI remoteClient) + { + uint effectivePerms = (uint)(PermissionMask.Copy | PermissionMask.Transfer | PermissionMask.Modify | PermissionMask.Move) | 7; + foreach (SceneObjectGroup grp in objsForEffectivePermissions) + effectivePerms &= grp.GetEffectivePermissions(); + 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; + + // Magic number badness. Maybe this deserves an enum. + // bit 4 (16) is the "Slam" bit, it means treat as passed + // and apply next owner perms on rez + item.CurrentPermissions |= 16; // Slam! + } + else + { + item.BasePermissions = effectivePerms; + item.CurrentPermissions = effectivePerms; + item.NextPermissions = so.RootPart.NextOwnerMask & effectivePerms; + item.EveryOnePermissions = so.RootPart.EveryoneMask & effectivePerms; + item.GroupPermissions = so.RootPart.GroupMask & effectivePerms; + + item.CurrentPermissions &= + ((uint)PermissionMask.Copy | + (uint)PermissionMask.Transfer | + (uint)PermissionMask.Modify | + (uint)PermissionMask.Move | + 7); // Preserve folded permissions + } + + return item; + } + + /// + /// Create an item using details for the given scene object. + /// + /// + /// + /// + /// + /// + protected InventoryItemBase CreateItemForObject( + DeRezAction action, IClientAPI remoteClient, SceneObjectGroup so, UUID folderID) + { + // Get the user info of the item destination + // + UUID userID = UUID.Zero; + + if (action == DeRezAction.Take || action == DeRezAction.TakeCopy || + action == DeRezAction.SaveToExistingUserInventoryItem) + { + // Take or take copy require a taker + // Saving changes requires a local user + // + if (remoteClient == null) + return null; + + userID = remoteClient.AgentId; + } + else + { + // All returns / deletes go to the object owner + // + userID = so.RootPart.OwnerID; + } + + if (userID == UUID.Zero) // Can't proceed + { + return null; + } + + // If we're returning someone's item, it goes back to the + // owner's Lost And Found folder. + // Delete is treated like return in this case + // Deleting your own items makes them go to trash + // + + InventoryFolderBase folder = null; + InventoryItemBase item = null; + + if (DeRezAction.SaveToExistingUserInventoryItem == action) + { + item = new InventoryItemBase(so.RootPart.FromUserInventoryItemID, userID); + item = m_Scene.InventoryService.GetItem(item); + + //item = userInfo.RootFolder.FindItem( + // objectGroup.RootPart.FromUserInventoryItemID); + + if (null == item) + { + m_log.DebugFormat( + "[AGENT INVENTORY]: Object {0} {1} scheduled for save to inventory has already been deleted.", + so.Name, so.UUID); + + return null; + } + } + else + { + // Folder magic + // + if (action == DeRezAction.Delete) + { + // Deleting someone else's item + // + if (remoteClient == null || + so.OwnerID != remoteClient.AgentId) + { + folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.LostAndFoundFolder); + } + else + { + folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.TrashFolder); + } + } + else if (action == DeRezAction.Return) + { + // Dump to lost + found unconditionally + // + folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.LostAndFoundFolder); + } + + if (folderID == UUID.Zero && folder == null) + { + if (action == DeRezAction.Delete) + { + // Deletes go to trash by default + // + folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.TrashFolder); + } + else + { + if (remoteClient == null || so.OwnerID != remoteClient.AgentId) + { + // Taking copy of another person's item. Take to + // Objects folder. + folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.Object); + } + else + { + // Catch all. Use lost & found + // + + folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.LostAndFoundFolder); + } + } + } + + // Override and put into where it came from, if it came + // from anywhere in inventory + // + if (action == DeRezAction.Take || action == DeRezAction.TakeCopy) + { + if (so.RootPart.FromFolderID != UUID.Zero) + { + InventoryFolderBase f = new InventoryFolderBase(so.RootPart.FromFolderID, userID); + folder = m_Scene.InventoryService.GetFolder(f); + } + } + + if (folder == null) // None of the above + { + folder = new InventoryFolderBase(folderID); + + if (folder == null) // Nowhere to put it + { + return null; + } + } + + item = new InventoryItemBase(); + item.ID = UUID.Random(); + item.InvType = (int)InventoryType.Object; + item.Folder = folder.ID; + item.Owner = userID; + } + + return item; + } /// /// Rez an object into the scene from the user's inventory /// + /// /// FIXME: It would be really nice if inventory access modules didn't also actually do the work of rezzing /// things to the scene. The caller should be doing that, I think. + /// /// /// /// @@ -502,21 +609,10 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection, bool RezSelected, bool RemoveItem, UUID fromTaskID, bool attachment) { - // Work out position details - byte bRayEndIsIntersection = (byte)0; - - if (RayEndIsIntersection) - { - bRayEndIsIntersection = (byte)1; - } - else - { - bRayEndIsIntersection = (byte)0; - } - +// m_log.DebugFormat("[INVENTORY ACCESS MODULE]: RezObject for {0}, item {1}", remoteClient.Name, itemID); + + byte bRayEndIsIntersection = (byte)(RayEndIsIntersection ? 1 : 0); Vector3 scale = new Vector3(0.5f, 0.5f, 0.5f); - - Vector3 pos = m_Scene.GetNewRezLocation( RayStart, RayEnd, RayTargetID, Quaternion.Identity, BypassRayCast, bRayEndIsIntersection, true, scale, false); @@ -531,6 +627,8 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess AssetBase rezAsset = m_Scene.AssetService.Get(item.AssetID.ToString()); + SceneObjectGroup group = null; + if (rezAsset != null) { UUID itemId = UUID.Zero; @@ -539,34 +637,87 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess // item that it came from. This allows us to enable 'save object to inventory' if (!m_Scene.Permissions.BypassPermissions()) { - if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == (uint)PermissionMask.Copy) + if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == (uint)PermissionMask.Copy && (item.Flags & (uint)InventoryItemFlags.ObjectHasMultipleItems) == 0) { itemId = item.ID; } } else { - // Brave new fullperm world - // - itemId = item.ID; + if ((item.Flags & (uint)InventoryItemFlags.ObjectHasMultipleItems) == 0) + { + // Brave new fullperm world + itemId = item.ID; + } } string xmlData = Utils.BytesToString(rezAsset.Data); - SceneObjectGroup group - = SceneObjectSerializer.FromOriginalXmlFormat(itemId, xmlData); + List objlist = + new List(); + List veclist = new List(); - Util.FireAndForget(delegate { AddUserData(group); }); - - group.RootPart.FromFolderID = item.Folder; + XmlDocument doc = new XmlDocument(); + doc.LoadXml(xmlData); + XmlElement e = (XmlElement)doc.SelectSingleNode("/CoalescedObject"); + if (e == null || attachment) // Single + { + SceneObjectGroup g = + SceneObjectSerializer.FromOriginalXmlFormat( + itemId, xmlData); + objlist.Add(g); + veclist.Add(new Vector3(0, 0, 0)); - // If it's rezzed in world, select it. Much easier to - // find small items. - // - if (!attachment) - group.RootPart.CreateSelected = true; + float offsetHeight = 0; + pos = m_Scene.GetNewRezLocation( + RayStart, RayEnd, RayTargetID, Quaternion.Identity, + BypassRayCast, bRayEndIsIntersection, true, g.GetAxisAlignedBoundingBox(out offsetHeight), false); + pos.Z += offsetHeight; + } + else + { + XmlElement coll = (XmlElement)e; + float bx = Convert.ToSingle(coll.GetAttribute("x")); + float by = Convert.ToSingle(coll.GetAttribute("y")); + float bz = Convert.ToSingle(coll.GetAttribute("z")); + Vector3 bbox = new Vector3(bx, by, bz); + + pos = m_Scene.GetNewRezLocation(RayStart, RayEnd, + RayTargetID, Quaternion.Identity, + BypassRayCast, bRayEndIsIntersection, true, + bbox, false); + + pos -= bbox / 2; + + XmlNodeList groups = e.SelectNodes("SceneObjectGroup"); + foreach (XmlNode n in groups) + { + SceneObjectGroup g = + SceneObjectSerializer.FromOriginalXmlFormat( + itemId, n.OuterXml); + objlist.Add(g); + XmlElement el = (XmlElement)n; + + string rawX = el.GetAttribute("offsetx"); + string rawY = el.GetAttribute("offsety"); + string rawZ = el.GetAttribute("offsetz"); +// +// m_log.DebugFormat( +// "[INVENTORY ACCESS MODULE]: Converting coalesced object {0} offset <{1}, {2}, {3}>", +// g.Name, rawX, rawY, rawZ); + + float x = Convert.ToSingle(rawX); + float y = Convert.ToSingle(rawY); + float z = Convert.ToSingle(rawZ); + veclist.Add(new Vector3(x, y, z)); + } + } + + int primcount = 0; + foreach (SceneObjectGroup g in objlist) + primcount += g.PrimCount; if (!m_Scene.Permissions.CanRezObject( - group.PrimCount, remoteClient.AgentId, pos) + primcount, remoteClient.AgentId, pos) && !attachment) { // The client operates in no fail mode. It will @@ -579,131 +730,136 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess return null; } - group.ResetIDs(); - - if (attachment) + for (int i = 0 ; i < objlist.Count ; i++ ) { - group.RootPart.Flags |= PrimFlags.Phantom; - group.RootPart.IsAttachment = true; + group = objlist[i]; + + Vector3 storedPosition = group.AbsolutePosition; + if (group.UUID == UUID.Zero) + { + m_log.Debug("[InventoryAccessModule]: Inventory object has UUID.Zero! Position 3"); + } + group.RootPart.FromFolderID = item.Folder; + + // If it's rezzed in world, select it. Much easier to + // find small items. + // + if (!attachment) + { + group.RootPart.CreateSelected = true; + foreach (SceneObjectPart child in group.Parts) + child.CreateSelected = true; + } + group.ResetIDs(); + + if (attachment) + { + group.RootPart.Flags |= PrimFlags.Phantom; + group.RootPart.IsAttachment = true; + } // If we're rezzing an attachment then don't ask // AddNewSceneObject() to update the client since - // we'll be doing that later on. Scheduling more - // than one full update during the attachment - // process causes some clients to fail to display - // the attachment properly. - // Also, don't persist attachments. - m_Scene.AddNewSceneObject(group, false, false); - } - else - { + // we'll be doing that later on. Scheduling more than + // one full update during the attachment + // process causes some clients to fail to display the + // attachment properly. m_Scene.AddNewSceneObject(group, true, false); - } - // m_log.InfoFormat("ray end point for inventory rezz is {0} {1} {2} ", RayEnd.X, RayEnd.Y, RayEnd.Z); - // if attachment we set it's asset id so object updates can reflect that - // if not, we set it's position in world. - if (!attachment) - { - group.ScheduleGroupForFullUpdate(); - - float offsetHeight = 0; - pos = m_Scene.GetNewRezLocation( - RayStart, RayEnd, RayTargetID, Quaternion.Identity, - BypassRayCast, bRayEndIsIntersection, true, group.GetAxisAlignedBoundingBox(out offsetHeight), false); - pos.Z += offsetHeight; - group.AbsolutePosition = pos; - // m_log.InfoFormat("rezx point for inventory rezz is {0} {1} {2} and offsetheight was {3}", pos.X, pos.Y, pos.Z, offsetHeight); - - } - else - { - group.SetFromItemID(itemID); - } - - SceneObjectPart rootPart = null; - try - { - rootPart = group.GetChildPart(group.UUID); - } - catch (NullReferenceException) - { - string isAttachment = ""; - - if (attachment) - isAttachment = " Object was an attachment"; - - m_log.Error("[AGENT INVENTORY]: Error rezzing ItemID: " + itemID + " object has no rootpart." + isAttachment); - } - - // Since renaming the item in the inventory does not affect the name stored - // in the serialization, transfer the correct name from the inventory to the - // object itself before we rez. - rootPart.Name = item.Name; - rootPart.Description = item.Description; - - if ((item.Flags & (uint)InventoryItemFlags.ObjectSlamSale) != 0) - { - rootPart.ObjectSaleType = item.SaleType; - rootPart.SalePrice = item.SalePrice; - } - - group.SetGroup(remoteClient.ActiveGroupId, remoteClient); - if ((rootPart.OwnerID != item.Owner) || - (item.CurrentPermissions & 16) != 0 || // Magic number - (item.Flags & (uint)InventoryItemFlags.ObjectSlamPerm) != 0) - { - //Need to kill the for sale here - rootPart.ObjectSaleType = 0; - rootPart.SalePrice = 10; - - if (m_Scene.Permissions.PropagatePermissions()) + // if attachment we set it's asset id so object updates + // can reflect that, if not, we set it's position in world. + if (!attachment) { - foreach (SceneObjectPart part in group.Parts) - { - if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteEveryone) != 0) - part.EveryoneMask = item.EveryOnePermissions; - if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteNextOwner) != 0) - part.NextOwnerMask = item.NextPermissions; - if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteGroup) != 0) - part.GroupMask = item.GroupPermissions; - } + group.ScheduleGroupForFullUpdate(); - group.ApplyNextOwnerPermissions(); + group.AbsolutePosition = pos + veclist[i]; } - } - - foreach (SceneObjectPart part in group.Parts) - { - if ((part.OwnerID != item.Owner) || (item.CurrentPermissions & 16) != 0) + else { - part.LastOwnerID = part.OwnerID; - part.OwnerID = item.Owner; - part.Inventory.ChangeInventoryOwner(item.Owner); - part.GroupMask = 0; // DO NOT propagate here + group.SetFromItemID(itemID); } - if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteEveryone) != 0) + + SceneObjectPart rootPart = null; + + try + { + rootPart = group.GetChildPart(group.UUID); + } + catch (NullReferenceException) + { + string isAttachment = ""; + + if (attachment) + isAttachment = " Object was an attachment"; + + m_log.Error("[AGENT INVENTORY]: Error rezzing ItemID: " + itemID + " object has no rootpart." + isAttachment); + } + + // Since renaming the item in the inventory does not + // affect the name stored in the serialization, transfer + // the correct name from the inventory to the + // object itself before we rez. + // + // Only do these for the first object if we are rezzing a coalescence. + if (i == 0) + { + rootPart.Name = item.Name; + rootPart.Description = item.Description; + rootPart.ObjectSaleType = item.SaleType; + rootPart.SalePrice = item.SalePrice; + } + + group.SetGroup(remoteClient.ActiveGroupId, remoteClient); + if ((rootPart.OwnerID != item.Owner) || + (item.CurrentPermissions & 16) != 0) + { + //Need to kill the for sale here + rootPart.ObjectSaleType = 0; + rootPart.SalePrice = 10; + + if (m_Scene.Permissions.PropagatePermissions()) + { + foreach (SceneObjectPart part in group.Parts) + { + if ((item.Flags & (uint)InventoryItemFlags.ObjectHasMultipleItems) == 0) + { + part.EveryoneMask = item.EveryOnePermissions; + part.NextOwnerMask = item.NextPermissions; + } + part.GroupMask = 0; // DO NOT propagate here + } + + group.ApplyNextOwnerPermissions(); + } + } + + foreach (SceneObjectPart part in group.Parts) + { + if ((part.OwnerID != item.Owner) || + (item.CurrentPermissions & 16) != 0) + { + part.LastOwnerID = part.OwnerID; + part.OwnerID = item.Owner; + part.Inventory.ChangeInventoryOwner(item.Owner); + part.GroupMask = 0; // DO NOT propagate here + } part.EveryoneMask = item.EveryOnePermissions; - if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteNextOwner) != 0) part.NextOwnerMask = item.NextPermissions; - if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteGroup) != 0) - part.GroupMask = item.GroupPermissions; - } - - rootPart.TrimPermissions(); - - if (!attachment) - { - if (group.RootPart.Shape.PCode == (byte)PCode.Prim) - { - group.ClearPartAttachmentData(); } - - // Fire on_rez - group.CreateScriptInstances(0, true, m_Scene.DefaultScriptEngine, 1); - rootPart.ParentGroup.ResumeScripts(); - rootPart.ScheduleFullUpdate(); + rootPart.TrimPermissions(); + + if (!attachment) + { + if (group.RootPart.Shape.PCode == (byte)PCode.Prim) + group.ClearPartAttachmentData(); + + // Fire on_rez + group.CreateScriptInstances(0, true, m_Scene.DefaultScriptEngine, 1); + rootPart.ParentGroup.ResumeScripts(); + + rootPart.ScheduleFullUpdate(); + } } if (!m_Scene.Permissions.BypassPermissions()) @@ -721,9 +877,8 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess } } } - - return rootPart.ParentGroup; } + return group; } return null; diff --git a/OpenSim/Region/CoreModules/Framework/InventoryAccess/Tests/InventoryAccessModuleTests.cs b/OpenSim/Region/CoreModules/Framework/InventoryAccess/Tests/InventoryAccessModuleTests.cs new file mode 100644 index 0000000000..8d53cf1542 --- /dev/null +++ b/OpenSim/Region/CoreModules/Framework/InventoryAccess/Tests/InventoryAccessModuleTests.cs @@ -0,0 +1,174 @@ +/* + * 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.IO; +using System.Reflection; +using System.Threading; +using Nini.Config; +using NUnit.Framework; +using OpenMetaverse; +using OpenSim.Data; +using OpenSim.Framework; +using OpenSim.Framework.Serialization; +using OpenSim.Framework.Serialization.External; +using OpenSim.Framework.Communications; +using OpenSim.Region.CoreModules.Avatar.Inventory.Archiver; +using OpenSim.Region.CoreModules.Framework.InventoryAccess; +using OpenSim.Region.Framework.Scenes; +using OpenSim.Region.Framework.Scenes.Serialization; +using OpenSim.Services.Interfaces; +using OpenSim.Tests.Common; +using OpenSim.Tests.Common.Mock; +using OpenSim.Tests.Common.Setup; + +namespace OpenSim.Region.CoreModules.Framework.InventoryAccess.Tests +{ + [TestFixture] + public class InventoryAccessModuleTests + { + protected TestScene m_scene; + protected BasicInventoryAccessModule m_iam; + protected UUID m_userId = UUID.Parse("00000000-0000-0000-0000-000000000020"); + protected TestClient m_tc; + + [SetUp] + public void SetUp() + { + m_iam = new BasicInventoryAccessModule(); + + IConfigSource config = new IniConfigSource(); + config.AddConfig("Modules"); + config.Configs["Modules"].Set("InventoryAccessModule", "BasicInventoryAccessModule"); + + m_scene = SceneSetupHelpers.SetupScene(); + SceneSetupHelpers.SetupSceneModules(m_scene, config, m_iam); + + // Create user + string userFirstName = "Jock"; + string userLastName = "Stirrup"; + string userPassword = "troll"; + UserProfileTestUtils.CreateUserWithInventory(m_scene, userFirstName, userLastName, m_userId, userPassword); + + AgentCircuitData acd = new AgentCircuitData(); + acd.AgentID = m_userId; + m_tc = new TestClient(acd, m_scene); + } + + [Test] + public void TestRezCoalescedObject() + { + TestHelper.InMethod(); +// log4net.Config.XmlConfigurator.Configure(); + + // Create asset + SceneObjectGroup object1 = SceneSetupHelpers.CreateSceneObject(1, m_userId, "Object1", 0x20); + object1.AbsolutePosition = new Vector3(15, 30, 45); + + SceneObjectGroup object2 = SceneSetupHelpers.CreateSceneObject(1, m_userId, "Object2", 0x40); + object2.AbsolutePosition = new Vector3(25, 50, 75); + + CoalescedSceneObjects coa = new CoalescedSceneObjects(m_userId, object1, object2); + + UUID asset1Id = UUID.Parse("00000000-0000-0000-0000-000000000060"); + AssetBase asset1 = AssetHelpers.CreateAsset(asset1Id, coa); + m_scene.AssetService.Store(asset1); + + // Create item + UUID item1Id = UUID.Parse("00000000-0000-0000-0000-000000000080"); + string item1Name = "My Little Dog"; + InventoryItemBase item1 = new InventoryItemBase(); + item1.Name = item1Name; + item1.AssetID = asset1.FullID; + item1.ID = item1Id; + InventoryFolderBase objsFolder + = InventoryArchiveUtils.FindFolderByPath(m_scene.InventoryService, m_userId, "Objects")[0]; + item1.Folder = objsFolder.ID; + m_scene.AddInventoryItem(item1); + + SceneObjectGroup so + = m_iam.RezObject( + m_tc, item1Id, new Vector3(100, 100, 100), Vector3.Zero, UUID.Zero, 1, false, false, false, UUID.Zero, false); + + Assert.That(so, Is.Not.Null); + + Assert.That(m_scene.SceneGraph.GetTotalObjectsCount(), Is.EqualTo(2)); + + SceneObjectPart retrievedObj1Part = m_scene.GetSceneObjectPart(object1.Name); + Assert.That(retrievedObj1Part, Is.Null); + + retrievedObj1Part = m_scene.GetSceneObjectPart(item1.Name); + Assert.That(retrievedObj1Part, Is.Not.Null); + Assert.That(retrievedObj1Part.Name, Is.EqualTo(item1.Name)); + + // Bottom of coalescence is placed on ground, hence we end up with 100.5 rather than 85 since the bottom + // object is unit square. + Assert.That(retrievedObj1Part.AbsolutePosition, Is.EqualTo(new Vector3(95, 90, 100.5f))); + + SceneObjectPart retrievedObj2Part = m_scene.GetSceneObjectPart(object2.Name); + Assert.That(retrievedObj2Part, Is.Not.Null); + Assert.That(retrievedObj2Part.Name, Is.EqualTo(object2.Name)); + Assert.That(retrievedObj2Part.AbsolutePosition, Is.EqualTo(new Vector3(105, 110, 130.5f))); + } + + [Test] + public void TestRezObject() + { + TestHelper.InMethod(); +// log4net.Config.XmlConfigurator.Configure(); + + // Create asset + SceneObjectGroup object1 = SceneSetupHelpers.CreateSceneObject(1, m_userId, "My Little Dog Object", 0x40); + + UUID asset1Id = UUID.Parse("00000000-0000-0000-0000-000000000060"); + AssetBase asset1 = AssetHelpers.CreateAsset(asset1Id, object1); + m_scene.AssetService.Store(asset1); + + // Create item + UUID item1Id = UUID.Parse("00000000-0000-0000-0000-000000000080"); + string item1Name = "My Little Dog"; + InventoryItemBase item1 = new InventoryItemBase(); + item1.Name = item1Name; + item1.AssetID = asset1.FullID; + item1.ID = item1Id; + InventoryFolderBase objsFolder + = InventoryArchiveUtils.FindFolderByPath(m_scene.InventoryService, m_userId, "Objects")[0]; + item1.Folder = objsFolder.ID; + m_scene.AddInventoryItem(item1); + + SceneObjectGroup so + = m_iam.RezObject( + m_tc, item1Id, Vector3.Zero, Vector3.Zero, UUID.Zero, 1, false, false, false, UUID.Zero, false); + + Assert.That(so, Is.Not.Null); + + SceneObjectPart retrievedPart = m_scene.GetSceneObjectPart(so.UUID); + Assert.That(retrievedPart, Is.Not.Null); + } + } +} \ No newline at end of file diff --git a/OpenSim/Region/CoreModules/Scripting/EMailModules/EmailModule.cs b/OpenSim/Region/CoreModules/Scripting/EMailModules/EmailModule.cs index c0975eaaa0..9255791c76 100644 --- a/OpenSim/Region/CoreModules/Scripting/EMailModules/EmailModule.cs +++ b/OpenSim/Region/CoreModules/Scripting/EMailModules/EmailModule.cs @@ -111,14 +111,12 @@ namespace OpenSim.Region.CoreModules.Scripting.EmailModules { if ((SMTPConfig = m_Config.Configs["SMTP"]) == null) { - m_log.InfoFormat("[SMTP] SMTP server not configured"); m_Enabled = false; return; } if (!SMTPConfig.GetBoolean("enabled", false)) { - m_log.InfoFormat("[SMTP] module disabled in configuration"); m_Enabled = false; return; } diff --git a/OpenSim/Region/CoreModules/Scripting/HttpRequest/ScriptsHttpRequests.cs b/OpenSim/Region/CoreModules/Scripting/HttpRequest/ScriptsHttpRequests.cs index d78931a524..4c8424d7cc 100644 --- a/OpenSim/Region/CoreModules/Scripting/HttpRequest/ScriptsHttpRequests.cs +++ b/OpenSim/Region/CoreModules/Scripting/HttpRequest/ScriptsHttpRequests.cs @@ -29,8 +29,10 @@ using System; using System.Collections.Generic; using System.IO; using System.Net; +using System.Net.Security; using System.Text; using System.Threading; +using System.Security.Cryptography.X509Certificates; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; @@ -100,8 +102,24 @@ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest public HttpRequestModule() { + ServicePointManager.ServerCertificateValidationCallback +=ValidateServerCertificate; } + public static bool ValidateServerCertificate( + object sender, + X509Certificate certificate, + X509Chain chain, + SslPolicyErrors sslPolicyErrors) + { + HttpWebRequest Request = (HttpWebRequest)sender; + + if (Request.Headers.Get("NoVerifyCert") != null) + { + return true; + } + + return chain.Build(new X509Certificate2(certificate)); + } #region IHttpRequestModule Members public UUID MakeHttpRequest(string url, string parameters, string body) @@ -141,8 +159,7 @@ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest break; case (int)HttpRequestConstants.HTTP_VERIFY_CERT: - - // TODO implement me + htc.HttpVerifyCert = (int.Parse(parms[i + 1]) != 0); break; } } @@ -189,7 +206,7 @@ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest * Not sure how important ordering is is here - the next first * one completed in the list is returned, based soley on its list * position, not the order in which the request was started or - * finsihed. I thought about setting up a queue for this, but + * finished. I thought about setting up a queue for this, but * it will need some refactoring and this works 'enough' right now */ @@ -237,8 +254,8 @@ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest m_scene.RegisterModuleInterface(this); - m_proxyurl = config.Configs["Startup"].GetString("HttpProxy"); - m_proxyexcepts = config.Configs["Startup"].GetString("HttpProxyExceptions"); + m_proxyurl = config.Configs["Startup"].GetString("HttpProxy"); + m_proxyexcepts = config.Configs["Startup"].GetString("HttpProxyExceptions"); m_pendingRequests = new Dictionary(); } @@ -282,7 +299,7 @@ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest public string HttpMethod = "GET"; public string HttpMIMEType = "text/plain;charset=utf-8"; public int HttpTimeout; - // public bool HttpVerifyCert = true; // not implemented + public bool HttpVerifyCert = true; private Thread httpThread; // Request info @@ -344,6 +361,17 @@ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest Request.Method = HttpMethod; Request.ContentType = HttpMIMEType; + if(!HttpVerifyCert) + { + // We could hijack Connection Group Name to identify + // a desired security exception. But at the moment we'll use a dummy header instead. +// Request.ConnectionGroupName = "NoVerify"; + Request.Headers.Add("NoVerifyCert", "true"); + } +// else +// { +// Request.ConnectionGroupName="Verify"; +// } if (proxyurl != null && proxyurl.Length > 0) { if (proxyexcepts != null && proxyexcepts.Length > 0) @@ -436,4 +464,4 @@ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest } } } -} +} \ No newline at end of file diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Asset/AssetServiceInConnectorModule.cs b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Asset/AssetServiceInConnectorModule.cs index e25700d1f7..422f394d7a 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Asset/AssetServiceInConnectorModule.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Asset/AssetServiceInConnectorModule.cs @@ -31,7 +31,6 @@ using System.Collections.Generic; using log4net; using Nini.Config; using OpenSim.Framework; -using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Interfaces; using OpenSim.Server.Base; diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Authentication/AuthenticationServiceInConnectorModule.cs b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Authentication/AuthenticationServiceInConnectorModule.cs index 02acddc37e..2b5beba374 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Authentication/AuthenticationServiceInConnectorModule.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Authentication/AuthenticationServiceInConnectorModule.cs @@ -31,7 +31,6 @@ using System.Collections.Generic; using log4net; using Nini.Config; using OpenSim.Framework; -using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Interfaces; using OpenSim.Server.Base; diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Grid/GridInfoServiceInConnectorModule.cs b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Grid/GridInfoServiceInConnectorModule.cs index 6d975afb14..f29c074206 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Grid/GridInfoServiceInConnectorModule.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Grid/GridInfoServiceInConnectorModule.cs @@ -31,7 +31,6 @@ using System.Collections.Generic; using log4net; using Nini.Config; using OpenSim.Framework; -using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Interfaces; using OpenSim.Server.Base; diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Hypergrid/HypergridServiceInConnectorModule.cs b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Hypergrid/HypergridServiceInConnectorModule.cs index 2f96bcb1ab..d2343c994e 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Hypergrid/HypergridServiceInConnectorModule.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Hypergrid/HypergridServiceInConnectorModule.cs @@ -31,7 +31,6 @@ using System.Collections.Generic; using log4net; using Nini.Config; using OpenSim.Framework; -using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Interfaces; using OpenSim.Server.Base; diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Inventory/InventoryServiceInConnectorModule.cs b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Inventory/InventoryServiceInConnectorModule.cs index 209cf0d3c2..53a8ace14c 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Inventory/InventoryServiceInConnectorModule.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Inventory/InventoryServiceInConnectorModule.cs @@ -31,9 +31,8 @@ using System.Collections.Generic; using log4net; using Nini.Config; using OpenSim.Framework; -using OpenSim.Framework.Servers.HttpServer; -using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Interfaces; +using OpenSim.Region.Framework.Scenes; using OpenSim.Server.Base; using OpenSim.Server.Handlers.Base; diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Land/LandServiceInConnectorModule.cs b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Land/LandServiceInConnectorModule.cs index fcc69e949f..fc642032b5 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Land/LandServiceInConnectorModule.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Land/LandServiceInConnectorModule.cs @@ -31,7 +31,6 @@ using System.Collections.Generic; using log4net; using Nini.Config; using OpenSim.Framework; -using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Interfaces; using OpenSim.Server.Base; diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Login/LLLoginServiceInConnectorModule.cs b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Login/LLLoginServiceInConnectorModule.cs index 2a9366c44e..f759470b28 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Login/LLLoginServiceInConnectorModule.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Login/LLLoginServiceInConnectorModule.cs @@ -31,7 +31,6 @@ using System.Collections.Generic; using log4net; using Nini.Config; using OpenSim.Framework; -using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Interfaces; using OpenSim.Server.Base; diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Neighbour/NeighbourServiceInConnectorModule.cs b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Neighbour/NeighbourServiceInConnectorModule.cs index 35518d59f8..5c3263260e 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Neighbour/NeighbourServiceInConnectorModule.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Neighbour/NeighbourServiceInConnectorModule.cs @@ -31,7 +31,6 @@ using System.Collections.Generic; using log4net; using Nini.Config; using OpenSim.Framework; -using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Interfaces; using OpenSim.Server.Base; diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Simulation/SimulationServiceInConnectorModule.cs b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Simulation/SimulationServiceInConnectorModule.cs index 5ee1c97e5f..86b4926ac5 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Simulation/SimulationServiceInConnectorModule.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Simulation/SimulationServiceInConnectorModule.cs @@ -31,7 +31,6 @@ using System.Collections.Generic; using log4net; using Nini.Config; using OpenSim.Framework; -using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Interfaces; using OpenSim.Server.Base; diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Asset/LocalAssetServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Asset/LocalAssetServiceConnector.cs index 1b3419d12f..51d1d599c5 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Asset/LocalAssetServiceConnector.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Asset/LocalAssetServiceConnector.cs @@ -195,6 +195,8 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset public byte[] GetData(string id) { +// m_log.DebugFormat("[LOCAL ASSET SERVICES CONNECTOR]: Requesting data for asset {0}", id); + AssetBase asset = m_Cache.Get(id); if (asset != null) diff --git a/OpenSim/Region/CoreModules/World/Archiver/ArchiveReadRequest.cs b/OpenSim/Region/CoreModules/World/Archiver/ArchiveReadRequest.cs index fd8f546737..82bef48c8c 100644 --- a/OpenSim/Region/CoreModules/World/Archiver/ArchiveReadRequest.cs +++ b/OpenSim/Region/CoreModules/World/Archiver/ArchiveReadRequest.cs @@ -57,6 +57,11 @@ namespace OpenSim.Region.CoreModules.World.Archiver /// bumps here should be compatible. /// public static int MAX_MAJOR_VERSION = 1; + + /// + /// Has the control file been loaded for this archive? + /// + public bool ControlFileLoaded { get; private set; } protected Scene m_scene; protected Stream m_loadStream; @@ -527,7 +532,7 @@ namespace OpenSim.Region.CoreModules.World.Archiver /// /// /// - protected void LoadControlFile(string path, byte[] data) + public void LoadControlFile(string path, byte[] data) { XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable()); XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None); @@ -573,6 +578,8 @@ namespace OpenSim.Region.CoreModules.World.Archiver } currentRegionSettings.Save(); + + ControlFileLoaded = true; } } } \ No newline at end of file diff --git a/OpenSim/Region/CoreModules/World/Archiver/ArchiveWriteRequestPreparation.cs b/OpenSim/Region/CoreModules/World/Archiver/ArchiveWriteRequestPreparation.cs index f2d487ef94..597b7809e5 100644 --- a/OpenSim/Region/CoreModules/World/Archiver/ArchiveWriteRequestPreparation.cs +++ b/OpenSim/Region/CoreModules/World/Archiver/ArchiveWriteRequestPreparation.cs @@ -206,7 +206,7 @@ namespace OpenSim.Region.CoreModules.World.Archiver /// public static string CreateControlFile(Dictionary options) { - int majorVersion = MAX_MAJOR_VERSION, minorVersion = 5; + int majorVersion = MAX_MAJOR_VERSION, minorVersion = 6; // // if (options.ContainsKey("version")) // { diff --git a/OpenSim/Region/CoreModules/World/Archiver/Tests/ArchiverTests.cs b/OpenSim/Region/CoreModules/World/Archiver/Tests/ArchiverTests.cs index e2760a2065..2307c8e585 100644 --- a/OpenSim/Region/CoreModules/World/Archiver/Tests/ArchiverTests.cs +++ b/OpenSim/Region/CoreModules/World/Archiver/Tests/ArchiverTests.cs @@ -171,7 +171,6 @@ namespace OpenSim.Region.CoreModules.World.Archiver.Tests MemoryStream archiveReadStream = new MemoryStream(archive); TarArchiveReader tar = new TarArchiveReader(archiveReadStream); - bool gotControlFile = false; bool gotNcAssetFile = false; string expectedNcAssetFileName = string.Format("{0}_{1}", ncAssetUuid, "notecard.txt"); @@ -182,15 +181,19 @@ namespace OpenSim.Region.CoreModules.World.Archiver.Tests expectedPaths.Add(ArchiveHelpers.CreateObjectPath(sog2)); string filePath; - TarArchiveReader.TarEntryType tarEntryType; + TarArchiveReader.TarEntryType tarEntryType; + byte[] data = tar.ReadEntry(out filePath, out tarEntryType); + Assert.That(filePath, Is.EqualTo(ArchiveConstants.CONTROL_FILE_PATH)); + + ArchiveReadRequest arr = new ArchiveReadRequest(m_scene, (Stream)null, false, false, Guid.Empty); + arr.LoadControlFile(filePath, data); + + Assert.That(arr.ControlFileLoaded, Is.True); + while (tar.ReadEntry(out filePath, out tarEntryType) != null) { - if (ArchiveConstants.CONTROL_FILE_PATH == filePath) - { - gotControlFile = true; - } - else if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH)) + if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH)) { string fileName = filePath.Remove(0, ArchiveConstants.ASSETS_PATH.Length); @@ -203,7 +206,6 @@ namespace OpenSim.Region.CoreModules.World.Archiver.Tests } } - Assert.That(gotControlFile, Is.True, "No control file in archive"); Assert.That(gotNcAssetFile, Is.True, "No notecard asset file in archive"); Assert.That(foundPaths, Is.EquivalentTo(expectedPaths)); diff --git a/OpenSim/Region/CoreModules/World/Estate/EstateManagementModule.cs b/OpenSim/Region/CoreModules/World/Estate/EstateManagementModule.cs index 57ab13550a..ab90e90b78 100644 --- a/OpenSim/Region/CoreModules/World/Estate/EstateManagementModule.cs +++ b/OpenSim/Region/CoreModules/World/Estate/EstateManagementModule.cs @@ -200,12 +200,13 @@ namespace OpenSim.Region.CoreModules.World.Estate } Scene.RegionInfo.RegionSettings.Save(); TriggerRegionInfoChange(); + sendRegionHandshakeToAll(); sendRegionInfoPacketToAll(); } private void handleCommitEstateTerrainTextureRequest(IClientAPI remoteClient) { - sendRegionHandshakeToAll(); + // sendRegionHandshakeToAll(); } public void setRegionTerrainSettings(float WaterHeight, @@ -258,6 +259,10 @@ namespace OpenSim.Region.CoreModules.World.Estate private void handleChangeEstateCovenantRequest(IClientAPI remoteClient, UUID estateCovenantID) { +// m_log.DebugFormat( +// "[ESTATE MANAGEMENT MODULE]: Handling request from {0} to change estate covenant to {1}", +// remoteClient.Name, estateCovenantID); + Scene.RegionInfo.RegionSettings.Covenant = estateCovenantID; Scene.RegionInfo.RegionSettings.Save(); TriggerRegionInfoChange(); @@ -274,8 +279,25 @@ namespace OpenSim.Region.CoreModules.World.Estate { if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true) || Scene.Permissions.BypassPermissions()) { + if ((estateAccessType & 1) != 0) // All estates + { + List estateIDs = Scene.EstateDataService.GetEstatesByOwner(Scene.RegionInfo.EstateSettings.EstateOwner); + EstateSettings estateSettings; + + foreach (int estateID in estateIDs) + { + if (estateID != Scene.RegionInfo.EstateSettings.EstateID) + { + estateSettings = Scene.EstateDataService.LoadEstateSettings(estateID); + estateSettings.AddEstateUser(user); + estateSettings.Save(); + } + } + } + Scene.RegionInfo.EstateSettings.AddEstateUser(user); Scene.RegionInfo.EstateSettings.Save(); + TriggerEstateInfoChange(); remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AccessOptions, Scene.RegionInfo.EstateSettings.EstateAccess, Scene.RegionInfo.EstateSettings.EstateID); } @@ -289,10 +311,26 @@ namespace OpenSim.Region.CoreModules.World.Estate { if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true) || Scene.Permissions.BypassPermissions()) { + if ((estateAccessType & 1) != 0) // All estates + { + List estateIDs = Scene.EstateDataService.GetEstatesByOwner(Scene.RegionInfo.EstateSettings.EstateOwner); + EstateSettings estateSettings; + + foreach (int estateID in estateIDs) + { + if (estateID != Scene.RegionInfo.EstateSettings.EstateID) + { + estateSettings = Scene.EstateDataService.LoadEstateSettings(estateID); + estateSettings.RemoveEstateUser(user); + estateSettings.Save(); + } + } + } + Scene.RegionInfo.EstateSettings.RemoveEstateUser(user); Scene.RegionInfo.EstateSettings.Save(); - TriggerEstateInfoChange(); + TriggerEstateInfoChange(); remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AccessOptions, Scene.RegionInfo.EstateSettings.EstateAccess, Scene.RegionInfo.EstateSettings.EstateID); } else @@ -304,8 +342,25 @@ namespace OpenSim.Region.CoreModules.World.Estate { if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true) || Scene.Permissions.BypassPermissions()) { + if ((estateAccessType & 1) != 0) // All estates + { + List estateIDs = Scene.EstateDataService.GetEstatesByOwner(Scene.RegionInfo.EstateSettings.EstateOwner); + EstateSettings estateSettings; + + foreach (int estateID in estateIDs) + { + if (estateID != Scene.RegionInfo.EstateSettings.EstateID) + { + estateSettings = Scene.EstateDataService.LoadEstateSettings(estateID); + estateSettings.AddEstateGroup(user); + estateSettings.Save(); + } + } + } + Scene.RegionInfo.EstateSettings.AddEstateGroup(user); Scene.RegionInfo.EstateSettings.Save(); + TriggerEstateInfoChange(); remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AllowedGroups, Scene.RegionInfo.EstateSettings.EstateGroups, Scene.RegionInfo.EstateSettings.EstateID); } @@ -318,10 +373,26 @@ namespace OpenSim.Region.CoreModules.World.Estate { if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true) || Scene.Permissions.BypassPermissions()) { + if ((estateAccessType & 1) != 0) // All estates + { + List estateIDs = Scene.EstateDataService.GetEstatesByOwner(Scene.RegionInfo.EstateSettings.EstateOwner); + EstateSettings estateSettings; + + foreach (int estateID in estateIDs) + { + if (estateID != Scene.RegionInfo.EstateSettings.EstateID) + { + estateSettings = Scene.EstateDataService.LoadEstateSettings(estateID); + estateSettings.RemoveEstateGroup(user); + estateSettings.Save(); + } + } + } + Scene.RegionInfo.EstateSettings.RemoveEstateGroup(user); Scene.RegionInfo.EstateSettings.Save(); - TriggerEstateInfoChange(); + TriggerEstateInfoChange(); remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AllowedGroups, Scene.RegionInfo.EstateSettings.EstateGroups, Scene.RegionInfo.EstateSettings.EstateID); } else @@ -349,6 +420,29 @@ namespace OpenSim.Region.CoreModules.World.Estate if (!alreadyInList) { + if ((estateAccessType & 1) != 0) // All estates + { + List estateIDs = Scene.EstateDataService.GetEstatesByOwner(Scene.RegionInfo.EstateSettings.EstateOwner); + EstateSettings estateSettings; + + foreach (int estateID in estateIDs) + { + if (estateID != Scene.RegionInfo.EstateSettings.EstateID) + { + EstateBan bitem = new EstateBan(); + + bitem.BannedUserID = user; + bitem.EstateID = (uint)estateID; + bitem.BannedHostAddress = "0.0.0.0"; + bitem.BannedHostIPMask = "0.0.0.0"; + + estateSettings = Scene.EstateDataService.LoadEstateSettings(estateID); + estateSettings.AddBan(bitem); + estateSettings.Save(); + } + } + } + EstateBan item = new EstateBan(); item.BannedUserID = user; @@ -358,6 +452,7 @@ namespace OpenSim.Region.CoreModules.World.Estate Scene.RegionInfo.EstateSettings.AddBan(item); Scene.RegionInfo.EstateSettings.Save(); + TriggerEstateInfoChange(); ScenePresence s = Scene.GetScenePresence(user); @@ -403,8 +498,25 @@ namespace OpenSim.Region.CoreModules.World.Estate if (alreadyInList && listitem != null) { + if ((estateAccessType & 1) != 0) // All estates + { + List estateIDs = Scene.EstateDataService.GetEstatesByOwner(Scene.RegionInfo.EstateSettings.EstateOwner); + EstateSettings estateSettings; + + foreach (int estateID in estateIDs) + { + if (estateID != Scene.RegionInfo.EstateSettings.EstateID) + { + estateSettings = Scene.EstateDataService.LoadEstateSettings(estateID); + estateSettings.RemoveBan(user); + estateSettings.Save(); + } + } + } + Scene.RegionInfo.EstateSettings.RemoveBan(listitem.BannedUserID); Scene.RegionInfo.EstateSettings.Save(); + TriggerEstateInfoChange(); } else @@ -424,8 +536,25 @@ namespace OpenSim.Region.CoreModules.World.Estate { if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true) || Scene.Permissions.BypassPermissions()) { + if ((estateAccessType & 1) != 0) // All estates + { + List estateIDs = Scene.EstateDataService.GetEstatesByOwner(Scene.RegionInfo.EstateSettings.EstateOwner); + EstateSettings estateSettings; + + foreach (int estateID in estateIDs) + { + if (estateID != Scene.RegionInfo.EstateSettings.EstateID) + { + estateSettings = Scene.EstateDataService.LoadEstateSettings(estateID); + estateSettings.AddEstateManager(user); + estateSettings.Save(); + } + } + } + Scene.RegionInfo.EstateSettings.AddEstateManager(user); Scene.RegionInfo.EstateSettings.Save(); + TriggerEstateInfoChange(); remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.EstateManagers, Scene.RegionInfo.EstateSettings.EstateManagers, Scene.RegionInfo.EstateSettings.EstateID); } @@ -438,10 +567,26 @@ namespace OpenSim.Region.CoreModules.World.Estate { if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true) || Scene.Permissions.BypassPermissions()) { + if ((estateAccessType & 1) != 0) // All estates + { + List estateIDs = Scene.EstateDataService.GetEstatesByOwner(Scene.RegionInfo.EstateSettings.EstateOwner); + EstateSettings estateSettings; + + foreach (int estateID in estateIDs) + { + if (estateID != Scene.RegionInfo.EstateSettings.EstateID) + { + estateSettings = Scene.EstateDataService.LoadEstateSettings(estateID); + estateSettings.RemoveEstateManager(user); + estateSettings.Save(); + } + } + } + Scene.RegionInfo.EstateSettings.RemoveEstateManager(user); Scene.RegionInfo.EstateSettings.Save(); - TriggerEstateInfoChange(); + TriggerEstateInfoChange(); remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.EstateManagers, Scene.RegionInfo.EstateSettings.EstateManagers, Scene.RegionInfo.EstateSettings.EstateID); } else diff --git a/OpenSim/Region/CoreModules/World/Land/LandChannel.cs b/OpenSim/Region/CoreModules/World/Land/LandChannel.cs index 7d990c265c..7fc358dc54 100644 --- a/OpenSim/Region/CoreModules/World/Land/LandChannel.cs +++ b/OpenSim/Region/CoreModules/World/Land/LandChannel.cs @@ -133,16 +133,6 @@ namespace OpenSim.Region.CoreModules.World.Land return new List(); } - public bool IsLandPrimCountTainted() - { - if (m_landManagementModule != null) - { - return m_landManagementModule.IsLandPrimCountTainted(); - } - - return false; - } - public bool IsForcefulBansAllowed() { if (m_landManagementModule != null) diff --git a/OpenSim/Region/CoreModules/World/Land/LandManagementModule.cs b/OpenSim/Region/CoreModules/World/Land/LandManagementModule.cs index 52e3718bc7..bfab7b88e4 100644 --- a/OpenSim/Region/CoreModules/World/Land/LandManagementModule.cs +++ b/OpenSim/Region/CoreModules/World/Land/LandManagementModule.cs @@ -62,8 +62,7 @@ namespace OpenSim.Region.CoreModules.World.Land public class LandManagementModule : INonSharedRegionModule { - private static readonly ILog m_log = - LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly string remoteParcelRequestPath = "0009/"; @@ -89,7 +88,6 @@ namespace OpenSim.Region.CoreModules.World.Land /// private readonly Dictionary m_landList = new Dictionary(); - private bool m_landPrimCountTainted; private int m_lastLandLocalID = LandChannel.START_LAND_LOCAL_ID - 1; private bool m_allowedForcefulBans = true; @@ -122,18 +120,18 @@ namespace OpenSim.Region.CoreModules.World.Land m_scene.EventManager.OnParcelPrimCountAdd += EventManagerOnParcelPrimCountAdd; m_scene.EventManager.OnParcelPrimCountUpdate += EventManagerOnParcelPrimCountUpdate; + m_scene.EventManager.OnObjectBeingRemovedFromScene += EventManagerOnObjectBeingRemovedFromScene; + m_scene.EventManager.OnRequestParcelPrimCountUpdate += EventManagerOnRequestParcelPrimCountUpdate; + m_scene.EventManager.OnAvatarEnteringNewParcel += EventManagerOnAvatarEnteringNewParcel; m_scene.EventManager.OnClientMovement += EventManagerOnClientMovement; m_scene.EventManager.OnValidateLandBuy += EventManagerOnValidateLandBuy; m_scene.EventManager.OnLandBuy += EventManagerOnLandBuy; m_scene.EventManager.OnNewClient += EventManagerOnNewClient; m_scene.EventManager.OnSignificantClientMovement += EventManagerOnSignificantClientMovement; - m_scene.EventManager.OnObjectBeingRemovedFromScene += EventManagerOnObjectBeingRemovedFromScene; m_scene.EventManager.OnNoticeNoLandDataFromStorage += EventManagerOnNoLandDataFromStorage; m_scene.EventManager.OnIncomingLandDataFromStorage += EventManagerOnIncomingLandDataFromStorage; - m_scene.EventManager.OnSetAllowForcefulBan += EventManagerOnSetAllowedForcefulBan; - m_scene.EventManager.OnRequestParcelPrimCountUpdate += EventManagerOnRequestParcelPrimCountUpdate; - m_scene.EventManager.OnParcelPrimCountTainted += EventManagerOnParcelPrimCountTainted; + m_scene.EventManager.OnSetAllowForcefulBan += EventManagerOnSetAllowedForcefulBan; m_scene.EventManager.OnRegisterCaps += EventManagerOnRegisterCaps; m_scene.EventManager.OnPluginConsole += EventManagerOnPluginConsole; @@ -308,8 +306,8 @@ namespace OpenSim.Region.CoreModules.World.Land /// The parcel created. protected ILandObject CreateDefaultParcel() { -// m_log.DebugFormat( -// "[LAND MANAGEMENT MODULE]: Creating default parcel for region {0}", m_scene.RegionInfo.RegionName); + m_log.DebugFormat( + "[LAND MANAGEMENT MODULE]: Creating default parcel for region {0}", m_scene.RegionInfo.RegionName); ILandObject fullSimParcel = new LandObject(UUID.Zero, false, m_scene); fullSimParcel.SetLandBitmap(fullSimParcel.GetSquareLandBitmap(0, 0, (int)Constants.RegionSize, (int)Constants.RegionSize)); @@ -614,6 +612,10 @@ namespace OpenSim.Region.CoreModules.World.Land { if (landBitmap[x, y]) { +// m_log.DebugFormat( +// "[LAND MANAGEMENT MODULE]: Registering parcel {0} for land co-ord ({1}, {2}) on {3}", +// new_land.LandData.Name, x, y, m_scene.RegionInfo.RegionName); + m_landIDList[x, y] = newLandLocalID; } } @@ -743,8 +745,16 @@ namespace OpenSim.Region.CoreModules.World.Land // Corner case. If an autoreturn happens during sim startup // we will come here with the list uninitialized // + int landId = m_landIDList[x, y]; + +// if (landId == 0) +// m_log.DebugFormat( +// "[LAND MANAGEMENT MODULE]: No land object found at ({0}, {1}) on {2}", +// x, y, m_scene.RegionInfo.RegionName); + if (m_landList.ContainsKey(m_landIDList[x, y])) return m_landList[m_landIDList[x, y]]; + return null; } } @@ -762,13 +772,14 @@ namespace OpenSim.Region.CoreModules.World.Land { try { - //if (m_landList.ContainsKey(m_landIDList[x / 4, y / 4])) - return m_landList[m_landIDList[x / 4, y / 4]]; - //else - // return null; + return m_landList[m_landIDList[x / 4, y / 4]]; } catch (IndexOutOfRangeException) { +// m_log.WarnFormat( +// "[LAND MANAGEMENT MODULE]: Tried to retrieve land object from out of bounds co-ordinate ({0},{1}) in {2}", +// x, y, m_scene.RegionInfo.RegionName); + return null; } } @@ -778,34 +789,24 @@ namespace OpenSim.Region.CoreModules.World.Land #region Parcel Modification - public void ResetAllLandPrimCounts() + public void ResetOverMeRecords() { lock (m_landList) { foreach (LandObject p in m_landList.Values) { - p.ResetLandPrimCounts(); + p.ResetOverMeRecord(); } } } - public void EventManagerOnParcelPrimCountTainted() - { - m_landPrimCountTainted = true; - } - - public bool IsLandPrimCountTainted() - { - return m_landPrimCountTainted; - } - public void EventManagerOnParcelPrimCountAdd(SceneObjectGroup obj) { Vector3 position = obj.AbsolutePosition; ILandObject landUnderPrim = GetLandObject(position.X, position.Y); if (landUnderPrim != null) { - ((LandObject)landUnderPrim).AddPrimToCount(obj); + ((LandObject)landUnderPrim).AddPrimOverMe(obj); } } @@ -815,7 +816,7 @@ namespace OpenSim.Region.CoreModules.World.Land { foreach (LandObject p in m_landList.Values) { - p.RemovePrimFromCount(obj); + p.RemovePrimFromOverMe(obj); } } } @@ -848,8 +849,7 @@ namespace OpenSim.Region.CoreModules.World.Land foreach (LandObject p in landOwnersAndParcels[owner]) { simArea += p.LandData.Area; - simPrims += p.LandData.OwnerPrims + p.LandData.OtherPrims + p.LandData.GroupPrims + - p.LandData.SelectedPrims; + simPrims += p.PrimCounts.Total; } foreach (LandObject p in landOwnersAndParcels[owner]) @@ -866,7 +866,7 @@ namespace OpenSim.Region.CoreModules.World.Land // "[LAND MANAGEMENT MODULE]: Triggered EventManagerOnParcelPrimCountUpdate() for {0}", // m_scene.RegionInfo.RegionName); - ResetAllLandPrimCounts(); + ResetOverMeRecords(); EntityBase[] entities = m_scene.Entities.GetEntities(); foreach (EntityBase obj in entities) { @@ -879,15 +879,13 @@ namespace OpenSim.Region.CoreModules.World.Land } } FinalizeLandPrimCountUpdate(); - m_landPrimCountTainted = false; } public void EventManagerOnRequestParcelPrimCountUpdate() { - ResetAllLandPrimCounts(); + ResetOverMeRecords(); m_scene.EventManager.TriggerParcelPrimCountUpdate(); FinalizeLandPrimCountUpdate(); - m_landPrimCountTainted = false; } /// @@ -951,8 +949,6 @@ namespace OpenSim.Region.CoreModules.World.Land m_landList[startLandObjectIndex].ForceUpdateLandInfo(); } - EventManagerOnParcelPrimCountTainted(); - //Now add the new land object ILandObject result = AddLandObject(newLand); UpdateLandObject(startLandObject.LandData.LocalID, startLandObject.LandData); @@ -1019,7 +1015,6 @@ namespace OpenSim.Region.CoreModules.World.Land performFinalLandJoin(masterLandObject, slaveLandObject); } } - EventManagerOnParcelPrimCountTainted(); masterLandObject.SendLandUpdateToAvatarsOverMe(); } @@ -1209,6 +1204,7 @@ namespace OpenSim.Region.CoreModules.World.Land if (land != null) { + m_scene.EventManager.TriggerParcelPrimCountUpdate(); m_landList[local_id].SendLandObjectOwners(remote_client); } else @@ -1440,7 +1436,8 @@ namespace OpenSim.Region.CoreModules.World.Land private string ProcessPropertiesUpdate(string request, string path, string param, UUID agentID, Caps caps) { IClientAPI client; - if (! m_scene.TryGetClient(agentID, out client)) { + if (!m_scene.TryGetClient(agentID, out client)) + { m_log.WarnFormat("[LAND MANAGEMENT MODULE]: Unable to retrieve IClientAPI for {0}", agentID); return LLSDHelpers.SerialiseLLSDReply(new LLSDEmpty()); } diff --git a/OpenSim/Region/CoreModules/World/Land/LandObject.cs b/OpenSim/Region/CoreModules/World/Land/LandObject.cs index e7bdb19e56..c2f104e370 100644 --- a/OpenSim/Region/CoreModules/World/Land/LandObject.cs +++ b/OpenSim/Region/CoreModules/World/Land/LandObject.cs @@ -64,8 +64,6 @@ namespace OpenSim.Region.CoreModules.World.Land #endregion - #region ILandObject Members - public int GetPrimsFree() { m_scene.EventManager.TriggerParcelPrimCountUpdate(); @@ -213,6 +211,7 @@ namespace OpenSim.Region.CoreModules.World.Land return simMax; } } + #endregion #region Packet Request Handling @@ -702,23 +701,11 @@ namespace OpenSim.Region.CoreModules.World.Land return LandBitmap; } - /// - /// Full sim land object creation - /// - /// public bool[,] BasicFullRegionLandBitmap() { return GetSquareLandBitmap(0, 0, (int) Constants.RegionSize, (int) Constants.RegionSize); } - - /// - /// Used to modify the bitmap between the x and y points. Points use 64 scale - /// - /// - /// - /// - /// - /// + public bool[,] GetSquareLandBitmap(int start_x, int start_y, int end_x, int end_y) { bool[,] tempBitmap = new bool[64,64]; @@ -909,9 +896,12 @@ namespace OpenSim.Region.CoreModules.World.Land lock (primsOverMe) { +// m_log.DebugFormat( +// "[LAND OBJECT]: Request for SendLandObjectOwners() from {0} with {1} known prims on region", +// remote_client.Name, primsOverMe.Count); + try { - foreach (SceneObjectGroup obj in primsOverMe) { try @@ -923,7 +913,7 @@ namespace OpenSim.Region.CoreModules.World.Land } catch (NullReferenceException) { - m_log.Info("[LAND]: " + "Got Null Reference when searching land owners from the parcel panel"); + m_log.Error("[LAND]: " + "Got Null Reference when searching land owners from the parcel panel"); } try { @@ -950,6 +940,7 @@ namespace OpenSim.Region.CoreModules.World.Land public Dictionary GetLandObjectOwners() { Dictionary ownersAndCount = new Dictionary(); + lock (primsOverMe) { try @@ -986,8 +977,10 @@ namespace OpenSim.Region.CoreModules.World.Land public void ReturnLandObjects(uint type, UUID[] owners, UUID[] tasks, IClientAPI remote_client) { - Dictionary> returns = - new Dictionary>(); +// m_log.DebugFormat( +// "[LAND OBJECT]: Request to return objects in {0} from {1}", LandData.Name, remote_client.Name); + + Dictionary> returns = new Dictionary>(); lock (primsOverMe) { @@ -1060,82 +1053,28 @@ namespace OpenSim.Region.CoreModules.World.Land #region Object Adding/Removing from Parcel - public void ResetLandPrimCounts() + public void ResetOverMeRecord() { - LandData.GroupPrims = 0; - LandData.OwnerPrims = 0; - LandData.OtherPrims = 0; - LandData.SelectedPrims = 0; - - lock (primsOverMe) primsOverMe.Clear(); } - public void AddPrimToCount(SceneObjectGroup obj) + public void AddPrimOverMe(SceneObjectGroup obj) { - - UUID prim_owner = obj.OwnerID; - int prim_count = obj.PrimCount; - - if (obj.IsSelected) - { - LandData.SelectedPrims += prim_count; - } - else - { - if (prim_owner == LandData.OwnerID) - { - LandData.OwnerPrims += prim_count; - } - else if ((obj.GroupID == LandData.GroupID || - prim_owner == LandData.GroupID) && - LandData.GroupID != UUID.Zero) - { - LandData.GroupPrims += prim_count; - } - else - { - LandData.OtherPrims += prim_count; - } - } - +// m_log.DebugFormat("[LAND OBJECT]: Adding scene object {0} {1} over {2}", obj.Name, obj.LocalId, LandData.Name); + lock (primsOverMe) primsOverMe.Add(obj); } - public void RemovePrimFromCount(SceneObjectGroup obj) + public void RemovePrimFromOverMe(SceneObjectGroup obj) { +// m_log.DebugFormat("[LAND OBJECT]: Removing scene object {0} {1} from over {2}", obj.Name, obj.LocalId, LandData.Name); + lock (primsOverMe) - { - if (primsOverMe.Contains(obj)) - { - UUID prim_owner = obj.OwnerID; - int prim_count = obj.PrimCount; - - if (prim_owner == LandData.OwnerID) - { - LandData.OwnerPrims -= prim_count; - } - else if (obj.GroupID == LandData.GroupID || - prim_owner == LandData.GroupID) - { - LandData.GroupPrims -= prim_count; - } - else - { - LandData.OtherPrims -= prim_count; - } - - primsOverMe.Remove(obj); - } - } + primsOverMe.Remove(obj); } - #endregion - - #endregion - #endregion /// @@ -1157,5 +1096,7 @@ namespace OpenSim.Region.CoreModules.World.Land LandData.MusicURL = url; SendLandUpdateToAvatarsOverMe(); } + + #endregion } } diff --git a/OpenSim/Region/CoreModules/World/Land/PrimCountModule.cs b/OpenSim/Region/CoreModules/World/Land/PrimCountModule.cs index d1e2328728..dca842ab91 100644 --- a/OpenSim/Region/CoreModules/World/Land/PrimCountModule.cs +++ b/OpenSim/Region/CoreModules/World/Land/PrimCountModule.cs @@ -173,18 +173,31 @@ namespace OpenSim.Region.CoreModules.World.Land // NOTE: Call under Taint Lock private void AddObject(SceneObjectGroup obj) - { -// m_log.DebugFormat("[PRIM COUNT MODULE]: Adding object {0} {1} to prim count", obj.Name, obj.UUID); - + { if (obj.IsAttachment) return; if (((obj.RootPart.Flags & PrimFlags.TemporaryOnRez) != 0)) - return; + return; Vector3 pos = obj.AbsolutePosition; ILandObject landObject = m_Scene.LandChannel.GetLandObject(pos.X, pos.Y); + + // If for some reason there is no land object (perhaps the object is out of bounds) then we can't count it + if (landObject == null) + { +// m_log.WarnFormat( +// "[PRIM COUNT MODULE]: Found no land object for {0} at position ({1}, {2}) on {3}", +// obj.Name, pos.X, pos.Y, m_Scene.RegionInfo.RegionName); + + return; + } + LandData landData = landObject.LandData; +// m_log.DebugFormat( +// "[PRIM COUNT MODULE]: Adding object {0} with {1} parts to prim count for parcel {2} on {3}", +// obj.Name, obj.Parts.Length, landData.Name, m_Scene.RegionInfo.RegionName); + // m_log.DebugFormat( // "[PRIM COUNT MODULE]: Object {0} is owned by {1} over land owned by {2}", // obj.Name, obj.OwnerID, landData.OwnerID); @@ -201,27 +214,29 @@ namespace OpenSim.Region.CoreModules.World.Land else parcelCounts.Users[obj.OwnerID] = partCount; - if (landData.IsGroupOwned) + if (obj.IsSelected) { - if (obj.OwnerID == landData.GroupID) - parcelCounts.Owner += partCount; - else if (obj.GroupID == landData.GroupID) - parcelCounts.Group += partCount; - else - parcelCounts.Others += partCount; + parcelCounts.Selected += partCount; } else { - if (obj.OwnerID == landData.OwnerID) - parcelCounts.Owner += partCount; - else if (obj.GroupID == landData.GroupID) - parcelCounts.Group += partCount; + 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 - parcelCounts.Others += partCount; + { + if (obj.OwnerID == landData.OwnerID) + parcelCounts.Owner += partCount; + else + parcelCounts.Others += partCount; + } } - - if (obj.IsSelected) - parcelCounts.Selected += partCount; } } @@ -377,6 +392,7 @@ namespace OpenSim.Region.CoreModules.World.Land count = counts.Owner; count += counts.Group; count += counts.Others; + count += counts.Selected; } } @@ -465,7 +481,9 @@ namespace OpenSim.Region.CoreModules.World.Land m_OwnerMap[landData.GlobalID] = landData.OwnerID; m_SimwideCounts[landData.OwnerID] = 0; -// m_log.DebugFormat("[PRIM COUNT MODULE]: Adding parcel count for {0}", landData.GlobalID); +// m_log.DebugFormat( +// "[PRIM COUNT MODULE]: Initializing parcel count for {0} on {1}", +// landData.Name, m_Scene.RegionInfo.RegionName); m_ParcelCounts[landData.GlobalID] = new ParcelCounts(); } @@ -575,4 +593,4 @@ namespace OpenSim.Region.CoreModules.World.Land } } } -} +} \ No newline at end of file diff --git a/OpenSim/Region/CoreModules/World/Land/Tests/PrimCountModuleTests.cs b/OpenSim/Region/CoreModules/World/Land/Tests/PrimCountModuleTests.cs index 5a60f22a48..67b00ac759 100644 --- a/OpenSim/Region/CoreModules/World/Land/Tests/PrimCountModuleTests.cs +++ b/OpenSim/Region/CoreModules/World/Land/Tests/PrimCountModuleTests.cs @@ -45,10 +45,20 @@ namespace OpenSim.Region.CoreModules.World.Land.Tests public class PrimCountModuleTests { protected UUID m_userId = new UUID("00000000-0000-0000-0000-100000000000"); - protected UUID m_dummyUserId = new UUID("99999999-9999-9999-9999-999999999999"); + protected UUID m_groupId = new UUID("00000000-0000-0000-8888-000000000000"); + protected UUID m_otherUserId = new UUID("99999999-9999-9999-9999-999999999999"); protected TestScene m_scene; protected PrimCountModule m_pcm; + + /// + /// A parcel that covers the entire sim except for a 1 unit wide strip on the eastern side. + /// protected ILandObject m_lo; + + /// + /// A parcel that covers just the eastern strip of the sim. + /// + protected ILandObject m_lo2; [SetUp] public void SetUp() @@ -58,12 +68,39 @@ namespace OpenSim.Region.CoreModules.World.Land.Tests m_scene = SceneSetupHelpers.SetupScene(); SceneSetupHelpers.SetupSceneModules(m_scene, lmm, m_pcm); + int xParcelDivider = (int)Constants.RegionSize - 1; + ILandObject lo = new LandObject(m_userId, false, m_scene); - lo.SetLandBitmap(lo.GetSquareLandBitmap(0, 0, (int)Constants.RegionSize, (int)Constants.RegionSize)); - m_lo = lmm.AddLandObject(lo); - //scene.loadAllLandObjectsFromStorage(scene.RegionInfo.originRegionID); + lo.LandData.Name = "m_lo"; + lo.SetLandBitmap( + lo.GetSquareLandBitmap(0, 0, xParcelDivider, (int)Constants.RegionSize)); + m_lo = lmm.AddLandObject(lo); + + ILandObject lo2 = new LandObject(m_userId, false, m_scene); + lo2.SetLandBitmap( + lo2.GetSquareLandBitmap(xParcelDivider, 0, (int)Constants.RegionSize, (int)Constants.RegionSize)); + lo2.LandData.Name = "m_lo2"; + m_lo2 = lmm.AddLandObject(lo2); } + /// + /// Test that counts before we do anything are correct. + /// + [Test] + public void TestInitialCounts() + { + IPrimCounts pc = m_lo.PrimCounts; + + Assert.That(pc.Owner, Is.EqualTo(0)); + Assert.That(pc.Group, Is.EqualTo(0)); + Assert.That(pc.Others, Is.EqualTo(0)); + Assert.That(pc.Total, Is.EqualTo(0)); + Assert.That(pc.Selected, Is.EqualTo(0)); + Assert.That(pc.Users[m_userId], Is.EqualTo(0)); + Assert.That(pc.Users[m_otherUserId], Is.EqualTo(0)); + Assert.That(pc.Simulator, Is.EqualTo(0)); + } + /// /// Test count after a parcel owner owned object is added. /// @@ -73,18 +110,9 @@ namespace OpenSim.Region.CoreModules.World.Land.Tests TestHelper.InMethod(); // log4net.Config.XmlConfigurator.Configure(); - IPrimCounts pc = m_lo.PrimCounts; + IPrimCounts pc = m_lo.PrimCounts; - Assert.That(pc.Owner, Is.EqualTo(0)); - Assert.That(pc.Group, Is.EqualTo(0)); - Assert.That(pc.Others, Is.EqualTo(0)); - Assert.That(pc.Total, Is.EqualTo(0)); - Assert.That(pc.Selected, Is.EqualTo(0)); - Assert.That(pc.Users[m_userId], Is.EqualTo(0)); - Assert.That(pc.Users[m_dummyUserId], Is.EqualTo(0)); - Assert.That(pc.Simulator, Is.EqualTo(0)); - - SceneObjectGroup sog = SceneSetupHelpers.CreateSceneObject(3, m_userId, 0x01); + SceneObjectGroup sog = SceneSetupHelpers.CreateSceneObject(3, m_userId, "a", 0x01); m_scene.AddNewSceneObject(sog, false); Assert.That(pc.Owner, Is.EqualTo(3)); @@ -93,11 +121,11 @@ namespace OpenSim.Region.CoreModules.World.Land.Tests Assert.That(pc.Total, Is.EqualTo(3)); Assert.That(pc.Selected, Is.EqualTo(0)); Assert.That(pc.Users[m_userId], Is.EqualTo(3)); - Assert.That(pc.Users[m_dummyUserId], Is.EqualTo(0)); + Assert.That(pc.Users[m_otherUserId], Is.EqualTo(0)); Assert.That(pc.Simulator, Is.EqualTo(3)); // Add a second object and retest - SceneObjectGroup sog2 = SceneSetupHelpers.CreateSceneObject(2, m_userId, 0x10); + SceneObjectGroup sog2 = SceneSetupHelpers.CreateSceneObject(2, m_userId, "b", 0x10); m_scene.AddNewSceneObject(sog2, false); Assert.That(pc.Owner, Is.EqualTo(5)); @@ -106,7 +134,7 @@ namespace OpenSim.Region.CoreModules.World.Land.Tests Assert.That(pc.Total, Is.EqualTo(5)); Assert.That(pc.Selected, Is.EqualTo(0)); Assert.That(pc.Users[m_userId], Is.EqualTo(5)); - Assert.That(pc.Users[m_dummyUserId], Is.EqualTo(0)); + Assert.That(pc.Users[m_otherUserId], Is.EqualTo(0)); Assert.That(pc.Simulator, Is.EqualTo(5)); } @@ -114,14 +142,14 @@ namespace OpenSim.Region.CoreModules.World.Land.Tests /// Test count after a parcel owner owned copied object is added. /// [Test] - public void TestCopiedOwnerObject() + public void TestCopyOwnerObject() { TestHelper.InMethod(); // log4net.Config.XmlConfigurator.Configure(); IPrimCounts pc = m_lo.PrimCounts; - SceneObjectGroup sog = SceneSetupHelpers.CreateSceneObject(3, m_userId, 0x01); + SceneObjectGroup sog = SceneSetupHelpers.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); @@ -131,9 +159,71 @@ namespace OpenSim.Region.CoreModules.World.Land.Tests Assert.That(pc.Total, Is.EqualTo(6)); Assert.That(pc.Selected, Is.EqualTo(0)); Assert.That(pc.Users[m_userId], Is.EqualTo(6)); - Assert.That(pc.Users[m_dummyUserId], Is.EqualTo(0)); + Assert.That(pc.Users[m_otherUserId], Is.EqualTo(0)); Assert.That(pc.Simulator, Is.EqualTo(6)); - } + } + + /// + /// Test that parcel counts update correctly when an object is moved between parcels, where that movement + /// is not done directly by the user/ + /// + [Test] + public void TestMoveOwnerObject() + { + TestHelper.InMethod(); +// log4net.Config.XmlConfigurator.Configure(); + + SceneObjectGroup sog = SceneSetupHelpers.CreateSceneObject(3, m_userId, "a", 0x01); + m_scene.AddNewSceneObject(sog, false); + SceneObjectGroup sog2 = SceneSetupHelpers.CreateSceneObject(2, m_userId, "b", 0x10); + m_scene.AddNewSceneObject(sog2, false); + + // Move the first scene object to the eastern strip parcel + sog.AbsolutePosition = new Vector3(254, 2, 2); + + IPrimCounts pclo1 = m_lo.PrimCounts; + + Assert.That(pclo1.Owner, Is.EqualTo(2)); + Assert.That(pclo1.Group, Is.EqualTo(0)); + Assert.That(pclo1.Others, Is.EqualTo(0)); + Assert.That(pclo1.Total, Is.EqualTo(2)); + Assert.That(pclo1.Selected, Is.EqualTo(0)); + Assert.That(pclo1.Users[m_userId], Is.EqualTo(2)); + Assert.That(pclo1.Users[m_otherUserId], Is.EqualTo(0)); + Assert.That(pclo1.Simulator, Is.EqualTo(5)); + + IPrimCounts pclo2 = m_lo2.PrimCounts; + + Assert.That(pclo2.Owner, Is.EqualTo(3)); + Assert.That(pclo2.Group, Is.EqualTo(0)); + Assert.That(pclo2.Others, Is.EqualTo(0)); + Assert.That(pclo2.Total, Is.EqualTo(3)); + Assert.That(pclo2.Selected, Is.EqualTo(0)); + Assert.That(pclo2.Users[m_userId], Is.EqualTo(3)); + Assert.That(pclo2.Users[m_otherUserId], Is.EqualTo(0)); + Assert.That(pclo2.Simulator, Is.EqualTo(5)); + + // Now move it back again + sog.AbsolutePosition = new Vector3(2, 2, 2); + + Assert.That(pclo1.Owner, Is.EqualTo(5)); + Assert.That(pclo1.Group, Is.EqualTo(0)); + Assert.That(pclo1.Others, Is.EqualTo(0)); + Assert.That(pclo1.Total, Is.EqualTo(5)); + Assert.That(pclo1.Selected, Is.EqualTo(0)); + Assert.That(pclo1.Users[m_userId], Is.EqualTo(5)); + Assert.That(pclo1.Users[m_otherUserId], Is.EqualTo(0)); + Assert.That(pclo1.Simulator, Is.EqualTo(5)); + + Assert.That(pclo2.Owner, Is.EqualTo(0)); + Assert.That(pclo2.Group, Is.EqualTo(0)); + Assert.That(pclo2.Others, Is.EqualTo(0)); + Assert.That(pclo2.Total, Is.EqualTo(0)); + Assert.That(pclo2.Selected, Is.EqualTo(0)); + Assert.That(pclo2.Users[m_userId], Is.EqualTo(0)); + Assert.That(pclo2.Users[m_otherUserId], Is.EqualTo(0)); + Assert.That(pclo2.Simulator, Is.EqualTo(5)); + } /// /// Test count after a parcel owner owned object is removed. @@ -146,8 +236,8 @@ namespace OpenSim.Region.CoreModules.World.Land.Tests IPrimCounts pc = m_lo.PrimCounts; - m_scene.AddNewSceneObject(SceneSetupHelpers.CreateSceneObject(1, m_userId, 0x1), false); - SceneObjectGroup sogToDelete = SceneSetupHelpers.CreateSceneObject(3, m_userId, 0x10); + m_scene.AddNewSceneObject(SceneSetupHelpers.CreateSceneObject(1, m_userId, "a", 0x1), false); + SceneObjectGroup sogToDelete = SceneSetupHelpers.CreateSceneObject(3, m_userId, "b", 0x10); m_scene.AddNewSceneObject(sogToDelete, false); m_scene.DeleteSceneObject(sogToDelete, false); @@ -157,9 +247,113 @@ namespace OpenSim.Region.CoreModules.World.Land.Tests Assert.That(pc.Total, Is.EqualTo(1)); Assert.That(pc.Selected, Is.EqualTo(0)); Assert.That(pc.Users[m_userId], Is.EqualTo(1)); - Assert.That(pc.Users[m_dummyUserId], Is.EqualTo(0)); + Assert.That(pc.Users[m_otherUserId], Is.EqualTo(0)); Assert.That(pc.Simulator, Is.EqualTo(1)); - } + } + + [Test] + public void TestAddGroupObject() + { + TestHelper.InMethod(); +// log4net.Config.XmlConfigurator.Configure(); + + m_lo.DeedToGroup(m_groupId); + + IPrimCounts pc = m_lo.PrimCounts; + + SceneObjectGroup sog = SceneSetupHelpers.CreateSceneObject(3, m_otherUserId, "a", 0x01); + sog.GroupID = m_groupId; + m_scene.AddNewSceneObject(sog, false); + + Assert.That(pc.Owner, Is.EqualTo(0)); + Assert.That(pc.Group, Is.EqualTo(3)); + Assert.That(pc.Others, Is.EqualTo(0)); + Assert.That(pc.Total, Is.EqualTo(3)); + Assert.That(pc.Selected, Is.EqualTo(0)); + + // Is this desired behaviour? Not totally sure. + Assert.That(pc.Users[m_userId], Is.EqualTo(0)); + Assert.That(pc.Users[m_groupId], Is.EqualTo(0)); + Assert.That(pc.Users[m_otherUserId], Is.EqualTo(3)); + + Assert.That(pc.Simulator, Is.EqualTo(3)); + } + + /// + /// Test count after a parcel owner owned object is removed. + /// + [Test] + public void TestRemoveGroupObject() + { + TestHelper.InMethod(); +// log4net.Config.XmlConfigurator.Configure(); + + m_lo.DeedToGroup(m_groupId); + + IPrimCounts pc = m_lo.PrimCounts; + + SceneObjectGroup sogToKeep = SceneSetupHelpers.CreateSceneObject(1, m_userId, "a", 0x1); + sogToKeep.GroupID = m_groupId; + m_scene.AddNewSceneObject(sogToKeep, false); + + SceneObjectGroup sogToDelete = SceneSetupHelpers.CreateSceneObject(3, m_userId, "b", 0x10); + m_scene.AddNewSceneObject(sogToDelete, false); + m_scene.DeleteSceneObject(sogToDelete, false); + + Assert.That(pc.Owner, Is.EqualTo(0)); + Assert.That(pc.Group, Is.EqualTo(1)); + Assert.That(pc.Others, Is.EqualTo(0)); + Assert.That(pc.Total, Is.EqualTo(1)); + Assert.That(pc.Selected, Is.EqualTo(0)); + Assert.That(pc.Users[m_userId], Is.EqualTo(1)); + Assert.That(pc.Users[m_groupId], Is.EqualTo(0)); + Assert.That(pc.Users[m_otherUserId], Is.EqualTo(0)); + Assert.That(pc.Simulator, Is.EqualTo(1)); + } + + [Test] + public void TestAddOthersObject() + { + TestHelper.InMethod(); +// log4net.Config.XmlConfigurator.Configure(); + + IPrimCounts pc = m_lo.PrimCounts; + + SceneObjectGroup sog = SceneSetupHelpers.CreateSceneObject(3, m_otherUserId, "a", 0x01); + m_scene.AddNewSceneObject(sog, false); + + Assert.That(pc.Owner, Is.EqualTo(0)); + Assert.That(pc.Group, Is.EqualTo(0)); + Assert.That(pc.Others, Is.EqualTo(3)); + Assert.That(pc.Total, Is.EqualTo(3)); + Assert.That(pc.Selected, Is.EqualTo(0)); + Assert.That(pc.Users[m_userId], Is.EqualTo(0)); + Assert.That(pc.Users[m_otherUserId], Is.EqualTo(3)); + Assert.That(pc.Simulator, Is.EqualTo(3)); + } + + [Test] + public void TestRemoveOthersObject() + { + TestHelper.InMethod(); +// log4net.Config.XmlConfigurator.Configure(); + + IPrimCounts pc = m_lo.PrimCounts; + + m_scene.AddNewSceneObject(SceneSetupHelpers.CreateSceneObject(1, m_otherUserId, "a", 0x1), false); + SceneObjectGroup sogToDelete = SceneSetupHelpers.CreateSceneObject(3, m_otherUserId, "b", 0x10); + m_scene.AddNewSceneObject(sogToDelete, false); + m_scene.DeleteSceneObject(sogToDelete, false); + + Assert.That(pc.Owner, Is.EqualTo(0)); + Assert.That(pc.Group, Is.EqualTo(0)); + Assert.That(pc.Others, Is.EqualTo(1)); + Assert.That(pc.Total, Is.EqualTo(1)); + Assert.That(pc.Selected, Is.EqualTo(0)); + Assert.That(pc.Users[m_userId], Is.EqualTo(0)); + Assert.That(pc.Users[m_otherUserId], Is.EqualTo(1)); + Assert.That(pc.Simulator, Is.EqualTo(1)); + } /// /// Test the count is correct after is has been tainted. @@ -170,7 +364,7 @@ namespace OpenSim.Region.CoreModules.World.Land.Tests TestHelper.InMethod(); IPrimCounts pc = m_lo.PrimCounts; - SceneObjectGroup sog = SceneSetupHelpers.CreateSceneObject(3, m_userId, 0x01); + SceneObjectGroup sog = SceneSetupHelpers.CreateSceneObject(3, m_userId, "a", 0x01); m_scene.AddNewSceneObject(sog, false); m_pcm.TaintPrimCount(); @@ -181,7 +375,7 @@ namespace OpenSim.Region.CoreModules.World.Land.Tests Assert.That(pc.Total, Is.EqualTo(3)); Assert.That(pc.Selected, Is.EqualTo(0)); Assert.That(pc.Users[m_userId], Is.EqualTo(3)); - Assert.That(pc.Users[m_dummyUserId], Is.EqualTo(0)); + Assert.That(pc.Users[m_otherUserId], Is.EqualTo(0)); Assert.That(pc.Simulator, Is.EqualTo(3)); } } diff --git a/OpenSim/Region/CoreModules/World/Serialiser/Tests/SerialiserTests.cs b/OpenSim/Region/CoreModules/World/Serialiser/Tests/SerialiserTests.cs index dafaa0c107..a866fd938c 100644 --- a/OpenSim/Region/CoreModules/World/Serialiser/Tests/SerialiserTests.cs +++ b/OpenSim/Region/CoreModules/World/Serialiser/Tests/SerialiserTests.cs @@ -237,7 +237,7 @@ namespace OpenSim.Region.CoreModules.World.Serialiser.Tests public void Init() { m_serialiserModule = new SerialiserModule(); - m_scene = SceneSetupHelpers.SetupScene(""); + m_scene = SceneSetupHelpers.SetupScene(); SceneSetupHelpers.SetupSceneModules(m_scene, m_serialiserModule); } diff --git a/OpenSim/Region/CoreModules/World/Sun/SunModule.cs b/OpenSim/Region/CoreModules/World/Sun/SunModule.cs index cea7c78ce8..4e14c73a25 100644 --- a/OpenSim/Region/CoreModules/World/Sun/SunModule.cs +++ b/OpenSim/Region/CoreModules/World/Sun/SunModule.cs @@ -469,8 +469,8 @@ namespace OpenSim.Region.CoreModules m_SunFixedHour = FixedSunHour; m_SunFixed = FixedSun; - m_log.DebugFormat("[SUN]: Sun Settings Update: Fixed Sun? : {0}", m_SunFixed.ToString()); - m_log.DebugFormat("[SUN]: Sun Settings Update: Sun Hour : {0}", m_SunFixedHour.ToString()); + // m_log.DebugFormat("[SUN]: Sun Settings Update: Fixed Sun? : {0}", m_SunFixed.ToString()); + // m_log.DebugFormat("[SUN]: Sun Settings Update: Sun Hour : {0}", m_SunFixedHour.ToString()); receivedEstateToolsSunUpdate = true; @@ -480,7 +480,7 @@ namespace OpenSim.Region.CoreModules // When sun settings are updated, we should update all clients with new settings. SunUpdateToAllClients(); - m_log.DebugFormat("[SUN]: PosTime : {0}", PosTime.ToString()); + // m_log.DebugFormat("[SUN]: PosTime : {0}", PosTime.ToString()); } } diff --git a/OpenSim/Region/CoreModules/World/Terrain/FileLoaders/GenericSystemDrawing.cs b/OpenSim/Region/CoreModules/World/Terrain/FileLoaders/GenericSystemDrawing.cs index d6fa0937e5..21a9999ba0 100644 --- a/OpenSim/Region/CoreModules/World/Terrain/FileLoaders/GenericSystemDrawing.cs +++ b/OpenSim/Region/CoreModules/World/Terrain/FileLoaders/GenericSystemDrawing.cs @@ -124,6 +124,52 @@ namespace OpenSim.Region.CoreModules.World.Terrain.FileLoaders colours.Save(stream, ImageFormat.Png); } + public virtual void SaveFile(ITerrainChannel m_channel, string filename, + int offsetX, int offsetY, + int fileWidth, int fileHeight, + int regionSizeX, int regionSizeY) + + { + // We need to do this because: + // "Saving the image to the same file it was constructed from is not allowed and throws an exception." + string tempName = offsetX + "_ " + offsetY + "_" + filename; + + Bitmap entireBitmap = null; + Bitmap thisBitmap = null; + if (File.Exists(filename)) + { + File.Copy(filename, tempName); + entireBitmap = new Bitmap(tempName); + if (entireBitmap.Width != fileWidth * regionSizeX || entireBitmap.Height != fileHeight * regionSizeY) + { + // old file, let's overwrite it + entireBitmap = new Bitmap(fileWidth * regionSizeX, fileHeight * regionSizeY); + } + } + else + { + entireBitmap = new Bitmap(fileWidth * regionSizeX, fileHeight * regionSizeY); + } + + thisBitmap = CreateGrayscaleBitmapFromMap(m_channel); + Console.WriteLine("offsetX=" + offsetX + " offsetY=" + offsetY); + for (int x = 0; x < regionSizeX; x++) + for (int y = 0; y < regionSizeY; y++) + entireBitmap.SetPixel(x + offsetX * regionSizeX, y + (fileHeight - 1 - offsetY) * regionSizeY, thisBitmap.GetPixel(x, y)); + + Save(entireBitmap, filename); + thisBitmap.Dispose(); + entireBitmap.Dispose(); + + if (File.Exists(tempName)) + File.Delete(tempName); + } + + protected virtual void Save(Bitmap bmp, string filename) + { + bmp.Save(filename, ImageFormat.Png); + } + #endregion public override string ToString() diff --git a/OpenSim/Region/CoreModules/World/Terrain/FileLoaders/JPEG.cs b/OpenSim/Region/CoreModules/World/Terrain/FileLoaders/JPEG.cs index 8667607d0b..1a0d8ecf60 100644 --- a/OpenSim/Region/CoreModules/World/Terrain/FileLoaders/JPEG.cs +++ b/OpenSim/Region/CoreModules/World/Terrain/FileLoaders/JPEG.cs @@ -76,6 +76,14 @@ namespace OpenSim.Region.CoreModules.World.Terrain.FileLoaders colours.Save(stream, ImageFormat.Jpeg); } + public virtual void SaveFile(ITerrainChannel m_channel, string filename, + int offsetX, int offsetY, + int fileWidth, int fileHeight, + int regionSizeX, int regionSizeY) + { + throw new System.Exception("Not Implemented"); + } + #endregion public override string ToString() diff --git a/OpenSim/Region/CoreModules/World/Terrain/FileLoaders/LLRAW.cs b/OpenSim/Region/CoreModules/World/Terrain/FileLoaders/LLRAW.cs index a70ef13ed0..fad7641e42 100644 --- a/OpenSim/Region/CoreModules/World/Terrain/FileLoaders/LLRAW.cs +++ b/OpenSim/Region/CoreModules/World/Terrain/FileLoaders/LLRAW.cs @@ -240,6 +240,14 @@ namespace OpenSim.Region.CoreModules.World.Terrain.FileLoaders get { return ".raw"; } } + public virtual void SaveFile(ITerrainChannel m_channel, string filename, + int offsetX, int offsetY, + int fileWidth, int fileHeight, + int regionSizeX, int regionSizeY) + { + throw new System.Exception("Not Implemented"); + } + #endregion public override string ToString() diff --git a/OpenSim/Region/CoreModules/World/Terrain/FileLoaders/RAW32.cs b/OpenSim/Region/CoreModules/World/Terrain/FileLoaders/RAW32.cs index 3c76665d5e..ba073cae5a 100644 --- a/OpenSim/Region/CoreModules/World/Terrain/FileLoaders/RAW32.cs +++ b/OpenSim/Region/CoreModules/World/Terrain/FileLoaders/RAW32.cs @@ -160,6 +160,13 @@ namespace OpenSim.Region.CoreModules.World.Terrain.FileLoaders bs.Close(); } + public virtual void SaveFile(ITerrainChannel m_channel, string filename, + int offsetX, int offsetY, + int fileWidth, int fileHeight, + int regionSizeX, int regionSizeY) + { + throw new System.Exception("Not Implemented"); + } #endregion public override string ToString() diff --git a/OpenSim/Region/CoreModules/World/Terrain/FileLoaders/Terragen.cs b/OpenSim/Region/CoreModules/World/Terrain/FileLoaders/Terragen.cs index 2919897153..2f37d9d7e9 100644 --- a/OpenSim/Region/CoreModules/World/Terrain/FileLoaders/Terragen.cs +++ b/OpenSim/Region/CoreModules/World/Terrain/FileLoaders/Terragen.cs @@ -308,6 +308,14 @@ namespace OpenSim.Region.CoreModules.World.Terrain.FileLoaders get { return ".ter"; } } + public virtual void SaveFile(ITerrainChannel m_channel, string filename, + int offsetX, int offsetY, + int fileWidth, int fileHeight, + int regionSizeX, int regionSizeY) + { + throw new System.Exception("Not Implemented"); + } + #endregion public override string ToString() diff --git a/OpenSim/Region/CoreModules/World/Terrain/ITerrainLoader.cs b/OpenSim/Region/CoreModules/World/Terrain/ITerrainLoader.cs index 7403281621..7237f90a38 100644 --- a/OpenSim/Region/CoreModules/World/Terrain/ITerrainLoader.cs +++ b/OpenSim/Region/CoreModules/World/Terrain/ITerrainLoader.cs @@ -38,5 +38,6 @@ namespace OpenSim.Region.CoreModules.World.Terrain ITerrainChannel LoadStream(Stream stream); void SaveFile(string filename, ITerrainChannel map); void SaveStream(Stream stream, ITerrainChannel map); + void SaveFile(ITerrainChannel map, string filename, int offsetX, int offsetY, int fileWidth, int fileHeight, int regionSizeX, int regionSizeY); } } \ No newline at end of file diff --git a/OpenSim/Region/CoreModules/World/Terrain/TerrainModule.cs b/OpenSim/Region/CoreModules/World/Terrain/TerrainModule.cs index 8a79d78b22..9c7b2fab9c 100644 --- a/OpenSim/Region/CoreModules/World/Terrain/TerrainModule.cs +++ b/OpenSim/Region/CoreModules/World/Terrain/TerrainModule.cs @@ -540,6 +540,39 @@ namespace OpenSim.Region.CoreModules.World.Terrain } } + /// + /// Saves the terrain to a larger terrain file. + /// + /// The terrain file to save + /// The width of the file in units + /// The height of the file in units + /// Where to begin our slice + /// Where to begin our slice + public void SaveToFile(string filename, int fileWidth, int fileHeight, int fileStartX, int fileStartY) + { + int offsetX = (int)m_scene.RegionInfo.RegionLocX - fileStartX; + int offsetY = (int)m_scene.RegionInfo.RegionLocY - fileStartY; + + if (offsetX >= 0 && offsetX < fileWidth && offsetY >= 0 && offsetY < fileHeight) + { + // this region is included in the tile request + foreach (KeyValuePair loader in m_loaders) + { + if (filename.EndsWith(loader.Key)) + { + lock (m_scene) + { + loader.Value.SaveFile(m_channel, filename, offsetX, offsetY, + fileWidth, fileHeight, + (int)Constants.RegionSize, + (int)Constants.RegionSize); + } + return; + } + } + } + } + /// /// Performs updates to the region periodically, synchronising physics and other heightmap aware sections /// @@ -860,6 +893,15 @@ namespace OpenSim.Region.CoreModules.World.Terrain SaveToFile((string) args[0]); } + private void InterfaceSaveTileFile(Object[] args) + { + SaveToFile((string)args[0], + (int)args[1], + (int)args[2], + (int)args[3], + (int)args[4]); + } + private void InterfaceBakeTerrain(Object[] args) { UpdateRevertMap(); @@ -1115,6 +1157,17 @@ namespace OpenSim.Region.CoreModules.World.Terrain loadFromTileCommand.AddArgument("minimum Y tile", "The Y region coordinate of the first section on the file", "Integer"); + Command saveToTileCommand = + new Command("save-tile", CommandIntentions.COMMAND_HAZARDOUS, InterfaceSaveTileFile, "Saves the current heightmap to the larger file."); + saveToTileCommand.AddArgument("filename", + "The file you wish to save to, the file extension determines the loader to be used. Supported extensions include: " + + supportedFileExtensions, "String"); + saveToTileCommand.AddArgument("file width", "The width of the file in tiles", "Integer"); + saveToTileCommand.AddArgument("file height", "The height of the file in tiles", "Integer"); + saveToTileCommand.AddArgument("minimum X tile", "The X region coordinate of the first section on the file", + "Integer"); + saveToTileCommand.AddArgument("minimum Y tile", "The Y region coordinate of the first section on the file", + "Integer"); // Terrain adjustments Command fillRegionCommand = new Command("fill", CommandIntentions.COMMAND_HAZARDOUS, InterfaceFillTerrain, "Fills the current heightmap with a specified value."); @@ -1166,6 +1219,7 @@ namespace OpenSim.Region.CoreModules.World.Terrain m_commander.RegisterCommand("load", loadFromFileCommand); m_commander.RegisterCommand("load-tile", loadFromTileCommand); m_commander.RegisterCommand("save", saveToFileCommand); + m_commander.RegisterCommand("save-tile", saveToTileCommand); m_commander.RegisterCommand("fill", fillRegionCommand); m_commander.RegisterCommand("elevate", elevateCommand); m_commander.RegisterCommand("lower", lowerCommand); diff --git a/OpenSim/Region/Examples/SimpleModule/MyNpcCharacter.cs b/OpenSim/Region/Examples/SimpleModule/MyNpcCharacter.cs index d939329814..89e9e204bb 100644 --- a/OpenSim/Region/Examples/SimpleModule/MyNpcCharacter.cs +++ b/OpenSim/Region/Examples/SimpleModule/MyNpcCharacter.cs @@ -702,18 +702,12 @@ namespace OpenSim.Region.Examples.SimpleModule { } - public void SendObjectPropertiesFamilyData(uint RequestFlags, UUID ObjectUUID, UUID OwnerID, UUID GroupID, - uint BaseMask, uint OwnerMask, uint GroupMask, uint EveryoneMask, - uint NextOwnerMask, int OwnershipCost, byte SaleType,int SalePrice, uint Category, - UUID LastOwnerID, string ObjectName, string Description) + public void SendObjectPropertiesFamilyData(ISceneEntity Entity, uint RequestFlags) { + } - public void SendObjectPropertiesReply(UUID ItemID, ulong CreationDate, UUID CreatorUUID, UUID FolderUUID, UUID FromTaskUUID, - UUID GroupUUID, short InventorySerial, UUID LastOwnerUUID, UUID ObjectUUID, - UUID OwnerUUID, string TouchTitle, byte[] TextureID, string SitTitle, string ItemName, - string ItemDescription, uint OwnerMask, uint NextOwnerMask, uint GroupMask, uint EveryoneMask, - uint BaseMask, byte saleType, int salePrice) + public void SendObjectPropertiesReply(ISceneEntity entity) { } diff --git a/OpenSim/Region/Framework/Interfaces/IEstateDataService.cs b/OpenSim/Region/Framework/Interfaces/IEstateDataService.cs index 38c10a6d1b..7066cf21e0 100644 --- a/OpenSim/Region/Framework/Interfaces/IEstateDataService.cs +++ b/OpenSim/Region/Framework/Interfaces/IEstateDataService.cs @@ -70,6 +70,12 @@ namespace OpenSim.Region.Framework.Interfaces /// List GetEstates(string search); + /// + /// Get the IDs of all estates owned by the given user. + /// + /// An empty list if no estates were found. + List GetEstatesByOwner(UUID ownerID); + /// /// Get the IDs of all estates. /// diff --git a/OpenSim/Region/Framework/Interfaces/IEstateDataStore.cs b/OpenSim/Region/Framework/Interfaces/IEstateDataStore.cs index c82661db74..d790a30b8a 100644 --- a/OpenSim/Region/Framework/Interfaces/IEstateDataStore.cs +++ b/OpenSim/Region/Framework/Interfaces/IEstateDataStore.cs @@ -74,6 +74,12 @@ namespace OpenSim.Region.Framework.Interfaces /// Name of estate to search for. This is the exact name, no parttern matching is done. /// List GetEstates(string search); + + /// + /// Get the IDs of all estates owned by the given user. + /// + /// An empty list if no estates were found. + List GetEstatesByOwner(UUID ownerID); /// /// Get the IDs of all estates. diff --git a/OpenSim/Region/Framework/Interfaces/IInventoryAccessModule.cs b/OpenSim/Region/Framework/Interfaces/IInventoryAccessModule.cs index 05fc2add3e..305975e855 100644 --- a/OpenSim/Region/Framework/Interfaces/IInventoryAccessModule.cs +++ b/OpenSim/Region/Framework/Interfaces/IInventoryAccessModule.cs @@ -38,7 +38,23 @@ namespace OpenSim.Region.Framework.Interfaces public interface IInventoryAccessModule { UUID CapsUpdateInventoryItemAsset(IClientAPI remoteClient, UUID itemID, byte[] data); - UUID DeleteToInventory(DeRezAction action, UUID folderID, List objectGroups, IClientAPI remoteClient); + + /// + /// Copy objects to a user's inventory. + /// + /// + /// Is it left to the caller to delete them from the scene if required. + /// + /// + /// + /// + /// + /// + /// Returns the UUID of the newly created item asset (not the item itself). + /// FIXME: This is not very useful. It would be far more useful to return a list of items instead. + /// + UUID CopyToInventory(DeRezAction action, UUID folderID, List objectGroups, IClientAPI remoteClient); + SceneObjectGroup RezObject(IClientAPI remoteClient, UUID itemID, Vector3 RayEnd, Vector3 RayStart, UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection, bool RezSelected, bool RemoveItem, UUID fromTaskID, bool attachment); diff --git a/OpenSim/Region/Framework/ModuleLoader.cs b/OpenSim/Region/Framework/ModuleLoader.cs index 23be9c252c..14ecd4430a 100644 --- a/OpenSim/Region/Framework/ModuleLoader.cs +++ b/OpenSim/Region/Framework/ModuleLoader.cs @@ -223,7 +223,8 @@ namespace OpenSim.Region.Framework catch (Exception e) { m_log.ErrorFormat( - "[MODULES]: Could not load types for [{0}]. Exception {1}", pluginAssembly.FullName, e); + "[MODULES]: Could not load types for plugin DLL {0}. Exception {1} {2}", + pluginAssembly.FullName, e.Message, e.StackTrace); // justincc: Right now this is fatal to really get the user's attention throw e; diff --git a/OpenSim/Region/Framework/Scenes/AsyncSceneObjectGroupDeleter.cs b/OpenSim/Region/Framework/Scenes/AsyncSceneObjectGroupDeleter.cs index 64567db9d8..342354257d 100644 --- a/OpenSim/Region/Framework/Scenes/AsyncSceneObjectGroupDeleter.cs +++ b/OpenSim/Region/Framework/Scenes/AsyncSceneObjectGroupDeleter.cs @@ -137,13 +137,14 @@ namespace OpenSim.Region.Framework.Scenes x = m_inventoryDeletes.Dequeue(); m_log.DebugFormat( - "[ASYNC DELETER]: Sending object to user's inventory, {0} item(s) remaining.", left); + "[ASYNC DELETER]: Sending object to user's inventory, action {1}, count {2}, {0} item(s) remaining.", left, x.action, x.objectGroups.Count); try { IInventoryAccessModule invAccess = m_scene.RequestModuleInterface(); if (invAccess != null) - invAccess.DeleteToInventory(x.action, x.folderID, x.objectGroups, x.remoteClient); + invAccess.CopyToInventory(x.action, x.folderID, x.objectGroups, x.remoteClient); + if (x.permissionToDelete) { foreach (SceneObjectGroup g in x.objectGroups) @@ -177,4 +178,4 @@ namespace OpenSim.Region.Framework.Scenes return false; } } -} \ No newline at end of file +} diff --git a/OpenSim/Region/Framework/Scenes/CoalescedSceneObjects.cs b/OpenSim/Region/Framework/Scenes/CoalescedSceneObjects.cs new file mode 100644 index 0000000000..af8ccda6c2 --- /dev/null +++ b/OpenSim/Region/Framework/Scenes/CoalescedSceneObjects.cs @@ -0,0 +1,154 @@ +/* + * 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.Linq; +using OpenMetaverse; + +namespace OpenSim.Region.Framework.Scenes +{ + /// + /// Represents a coalescene of scene objects. A coalescence occurs when objects that are not in the same linkset + /// are grouped together. + /// + public class CoalescedSceneObjects + { + /// + /// The creator of this coalesence, though not necessarily the objects within it. + /// + public UUID CreatorId { get; set; } + + /// + /// The number of objects in this coalesence + /// + public int Count + { + get + { + lock (m_memberObjects) + return m_memberObjects.Count; + } + } + + /// + /// Does this coalesence have any member objects? + /// + public bool HasObjects { get { return Count > 0; } } + + /// + /// Get the objects currently in this coalescence + /// + public List Objects + { + get + { + lock (m_memberObjects) + return new List(m_memberObjects); + } + } + + /// + /// Get the scene that contains the objects in this coalescence. If there are no objects then null is returned. + /// + public Scene Scene + { + get + { + if (!HasObjects) + return null; + else + return Objects[0].Scene; + } + } + + /// + /// At this point, we need to preserve the order of objects added to the coalescence, since the first + /// one will end up matching the item name when rerezzed. + /// + protected List m_memberObjects = new List(); + + public CoalescedSceneObjects(UUID creatorId) + { + CreatorId = creatorId; + } + + public CoalescedSceneObjects(UUID creatorId, params SceneObjectGroup[] objs) : this(creatorId) + { + foreach (SceneObjectGroup obj in objs) + Add(obj); + } + + /// + /// Add an object to the coalescence. + /// + /// + /// The offset of the object within the group + public void Add(SceneObjectGroup obj) + { + lock (m_memberObjects) + m_memberObjects.Add(obj); + } + + /// + /// Removes a scene object from the coalescene + /// + /// + /// true if the object was there to be removed, false if not. + public bool Remove(SceneObjectGroup obj) + { + lock (m_memberObjects) + return m_memberObjects.Remove(obj); + } + + /// + /// Get the total size of the coalescence (the size required to cover all the objects within it) and the + /// offsets of each of those objects. + /// + /// + /// + /// An array of offsets. The order of objects is the same as returned from the Objects property + /// + public Vector3[] GetSizeAndOffsets(out Vector3 size) + { + float minX, minY, minZ; + float maxX, maxY, maxZ; + + Vector3[] offsets + = Scene.GetCombinedBoundingBox( + Objects, out minX, out maxX, out minY, out maxY, out minZ, out maxZ); + + float sizeX = maxX - minX; + float sizeY = maxY - minY; + float sizeZ = maxZ - minZ; + + size = new Vector3(sizeX, sizeY, sizeZ); + + return offsets; + } + } +} \ No newline at end of file diff --git a/OpenSim/Region/Framework/Scenes/Prioritizer.cs b/OpenSim/Region/Framework/Scenes/Prioritizer.cs index f9599f5a96..e3ed905c2f 100644 --- a/OpenSim/Region/Framework/Scenes/Prioritizer.cs +++ b/OpenSim/Region/Framework/Scenes/Prioritizer.cs @@ -58,17 +58,8 @@ namespace OpenSim.Region.Framework.Scenes public class Prioritizer { -// private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - /// - /// This is added to the priority of all child prims, to make sure that the root prim update is sent to the - /// viewer before child prim updates. - /// The adjustment is added to child prims and subtracted from root prims, so the gap ends up - /// being double. We do it both ways so that there is a still a priority delta even if the priority is already - /// double.MinValue or double.MaxValue. - /// - private double m_childPrimAdjustmentFactor = 0.05; - private Scene m_scene; public Prioritizer(Scene scene) @@ -76,17 +67,35 @@ namespace OpenSim.Region.Framework.Scenes m_scene = scene; } - public double GetUpdatePriority(IClientAPI client, ISceneEntity entity) + /// + /// Returns the priority queue into which the update should be placed. Updates within a + /// queue will be processed in arrival order. There are currently 12 priority queues + /// implemented in PriorityQueue class in LLClientView. Queue 0 is generally retained + /// for avatar updates. The fair queuing discipline for processing the priority queues + /// assumes that the number of entities in each priority queues increases exponentially. + /// So for example... if queue 1 contains all updates within 10m of the avatar or camera + /// then queue 2 at 20m is about 3X bigger in space & about 3X bigger in total number + /// of updates. + /// + public uint GetUpdatePriority(IClientAPI client, ISceneEntity entity) { - double priority = 0; - + // If entity is null we have a serious problem if (entity == null) - return 100000; + { + m_log.WarnFormat("[PRIORITIZER] attempt to prioritize null entity"); + throw new InvalidOperationException("Prioritization entity not defined"); + } + + // If this is an update for our own avatar give it the highest priority + if (client.AgentId == entity.UUID) + return 0; + + uint priority; switch (m_scene.UpdatePrioritizationScheme) { case UpdatePrioritizationSchemes.Time: - priority = GetPriorityByTime(); + priority = GetPriorityByTime(client, entity); break; case UpdatePrioritizationSchemes.Distance: priority = GetPriorityByDistance(client, entity); @@ -104,180 +113,115 @@ namespace OpenSim.Region.Framework.Scenes throw new InvalidOperationException("UpdatePrioritizationScheme not defined."); } - // Adjust priority so that root prims are sent to the viewer first. This is especially important for - // attachments acting as huds, since current viewers fail to display hud child prims if their updates - // arrive before the root one. - if (entity is SceneObjectPart) - { - SceneObjectPart sop = ((SceneObjectPart)entity); - - if (sop.IsRoot) - { - if (priority >= double.MinValue + m_childPrimAdjustmentFactor) - priority -= m_childPrimAdjustmentFactor; - } - else - { - if (priority <= double.MaxValue - m_childPrimAdjustmentFactor) - priority += m_childPrimAdjustmentFactor; - } - } - return priority; } - private double GetPriorityByTime() + + private uint GetPriorityByTime(IClientAPI client, ISceneEntity entity) { - return DateTime.UtcNow.ToOADate(); + return 1; } - private double GetPriorityByDistance(IClientAPI client, ISceneEntity entity) + private uint GetPriorityByDistance(IClientAPI client, ISceneEntity entity) { + return ComputeDistancePriority(client,entity,false); + } + + private uint GetPriorityByFrontBack(IClientAPI client, ISceneEntity entity) + { + return ComputeDistancePriority(client,entity,true); + } + + private uint GetPriorityByBestAvatarResponsiveness(IClientAPI client, ISceneEntity entity) + { + uint pqueue = ComputeDistancePriority(client,entity,true); + ScenePresence presence = m_scene.GetScenePresence(client.AgentId); if (presence != null) { - // If this is an update for our own avatar give it the highest priority - if (presence == entity) - return 0.0; - - // Use the camera position for local agents and avatar position for remote agents - Vector3 presencePos = (presence.IsChildAgent) ? - presence.AbsolutePosition : - presence.CameraPosition; - - // Use group position for child prims - Vector3 entityPos; - if (entity is SceneObjectPart) - { - // Can't use Scene.GetGroupByPrim() here, since the entity may have been delete from the scene - // before its scheduled update was triggered - //entityPos = m_scene.GetGroupByPrim(entity.LocalId).AbsolutePosition; - entityPos = ((SceneObjectPart)entity).ParentGroup.AbsolutePosition; - } - else - { - entityPos = entity.AbsolutePosition; - } - - return Vector3.DistanceSquared(presencePos, entityPos); - } - - return double.NaN; - } - - private double GetPriorityByFrontBack(IClientAPI client, ISceneEntity entity) - { - ScenePresence presence = m_scene.GetScenePresence(client.AgentId); - if (presence != null) - { - // If this is an update for our own avatar give it the highest priority - if (presence == entity) - return 0.0; - - // Use group position for child prims - Vector3 entityPos = entity.AbsolutePosition; - if (entity is SceneObjectPart) - { - // Can't use Scene.GetGroupByPrim() here, since the entity may have been delete from the scene - // before its scheduled update was triggered - //entityPos = m_scene.GetGroupByPrim(entity.LocalId).AbsolutePosition; - entityPos = ((SceneObjectPart)entity).ParentGroup.AbsolutePosition; - } - else - { - entityPos = entity.AbsolutePosition; - } - if (!presence.IsChildAgent) { - // Root agent. Use distance from camera and a priority decrease for objects behind us - Vector3 camPosition = presence.CameraPosition; - Vector3 camAtAxis = presence.CameraAtAxis; + if (entity is SceneObjectPart) + { + // Non physical prims are lower priority than physical prims + PhysicsActor physActor = ((SceneObjectPart)entity).ParentGroup.RootPart.PhysActor; + if (physActor == null || !physActor.IsPhysical) + pqueue++; - // Distance - double priority = Vector3.DistanceSquared(camPosition, entityPos); - - // Plane equation - float d = -Vector3.Dot(camPosition, camAtAxis); - float p = Vector3.Dot(camAtAxis, entityPos) + d; - if (p < 0.0f) priority *= 2.0; - - return priority; - } - else - { - // Child agent. Use the normal distance method - Vector3 presencePos = presence.AbsolutePosition; - - return Vector3.DistanceSquared(presencePos, entityPos); + // Attachments are high priority, + // MIC: shouldn't these already be in the highest priority queue already + // since their root position is same as the avatars? + if (((SceneObjectPart)entity).ParentGroup.RootPart.IsAttachment) + pqueue = 1; + } } } - return double.NaN; + return pqueue; } - private double GetPriorityByBestAvatarResponsiveness(IClientAPI client, ISceneEntity entity) + private uint ComputeDistancePriority(IClientAPI client, ISceneEntity entity, bool useFrontBack) { - // If this is an update for our own avatar give it the highest priority - if (client.AgentId == entity.UUID) - return 0.0; - if (entity == null) - return double.NaN; + // Get this agent's position + ScenePresence presence = m_scene.GetScenePresence(client.AgentId); + if (presence == null) + { + // this shouldn't happen, it basically means that we are prioritizing + // updates to send to a client that doesn't have a presence in the scene + // seems like there's race condition here... - // Use group position for child prims + // m_log.WarnFormat("[PRIORITIZER] attempt to use agent {0} not in the scene",client.AgentId); + // throw new InvalidOperationException("Prioritization agent not defined"); + return Int32.MaxValue; + } + + // Use group position for child prims, since we are putting child prims in + // the same queue with the root of the group, the root prim (which goes into + // the queue first) should always be sent first, no need to adjust child prim + // priorities Vector3 entityPos = entity.AbsolutePosition; if (entity is SceneObjectPart) { SceneObjectGroup group = (entity as SceneObjectPart).ParentGroup; if (group != null) entityPos = group.AbsolutePosition; - else - entityPos = entity.AbsolutePosition; } - else - entityPos = entity.AbsolutePosition; - ScenePresence presence = m_scene.GetScenePresence(client.AgentId); - if (presence != null) + // Use the camera position for local agents and avatar position for remote agents + Vector3 presencePos = (presence.IsChildAgent) ? + presence.AbsolutePosition : + presence.CameraPosition; + + // Compute the distance... + double distance = Vector3.Distance(presencePos, entityPos); + + // And convert the distance to a priority queue, this computation gives queues + // at 10, 20, 40, 80, 160, 320, 640, and 1280m + uint pqueue = 1; + for (int i = 0; i < 8; i++) { - if (!presence.IsChildAgent) - { - if (entity is ScenePresence) - return 1.0; + if (distance < 10 * Math.Pow(2.0,i)) + break; + pqueue++; + } + + // If this is a root agent, then determine front & back + // Bump up the priority queue (drop the priority) for any objects behind the avatar + if (useFrontBack && ! presence.IsChildAgent) + { + // Root agent, decrease priority for objects behind us + Vector3 camPosition = presence.CameraPosition; + Vector3 camAtAxis = presence.CameraAtAxis; - // Root agent. Use distance from camera and a priority decrease for objects behind us - Vector3 camPosition = presence.CameraPosition; - Vector3 camAtAxis = presence.CameraAtAxis; - - // Distance - double priority = Vector3.DistanceSquared(camPosition, entityPos); - - // Plane equation - float d = -Vector3.Dot(camPosition, camAtAxis); - float p = Vector3.Dot(camAtAxis, entityPos) + d; - if (p < 0.0f) priority *= 2.0; - - if (entity is SceneObjectPart) - { - PhysicsActor physActor = ((SceneObjectPart)entity).ParentGroup.RootPart.PhysActor; - if (physActor == null || !physActor.IsPhysical) - priority += 100; - - if (((SceneObjectPart)entity).ParentGroup.RootPart.IsAttachment) - priority = 1.0; - } - return priority; - } - else - { - // Child agent. Use the normal distance method - Vector3 presencePos = presence.AbsolutePosition; - - return Vector3.DistanceSquared(presencePos, entityPos); - } + // Plane equation + float d = -Vector3.Dot(camPosition, camAtAxis); + float p = Vector3.Dot(camAtAxis, entityPos) + d; + if (p < 0.0f) + pqueue++; } - return double.NaN; + return pqueue; } + } } diff --git a/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs b/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs index fcbcf593ba..0f85925c78 100644 --- a/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs +++ b/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs @@ -1955,11 +1955,49 @@ namespace OpenSim.Region.Framework.Scenes UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection, bool RezSelected, bool RemoveItem, UUID fromTaskID) { - IInventoryAccessModule invAccess = RequestModuleInterface(); - if (invAccess != null) - invAccess.RezObject( - remoteClient, itemID, RayEnd, RayStart, RayTargetID, BypassRayCast, RayEndIsIntersection, - RezSelected, RemoveItem, fromTaskID, false); +// m_log.DebugFormat( +// "[PRIM INVENTORY]: RezObject from {0} for item {1} from task id {2}", +// remoteClient.Name, itemID, fromTaskID); + + if (fromTaskID == UUID.Zero) + { + IInventoryAccessModule invAccess = RequestModuleInterface(); + if (invAccess != null) + invAccess.RezObject( + remoteClient, itemID, RayEnd, RayStart, RayTargetID, BypassRayCast, RayEndIsIntersection, + RezSelected, RemoveItem, fromTaskID, false); + } + else + { + SceneObjectPart part = GetSceneObjectPart(fromTaskID); + if (part == null) + { + m_log.ErrorFormat( + "[TASK INVENTORY]: {0} tried to rez item id {1} from object id {2} but there is no such scene object", + remoteClient.Name, itemID, fromTaskID); + + return; + } + + TaskInventoryItem item = part.Inventory.GetInventoryItem(itemID); + if (item == null) + { + m_log.ErrorFormat( + "[TASK INVENTORY]: {0} tried to rez item id {1} from object id {2} but there is no such item", + remoteClient.Name, itemID, fromTaskID); + + return; + } + + byte bRayEndIsIntersection = (byte)(RayEndIsIntersection ? 1 : 0); + Vector3 scale = new Vector3(0.5f, 0.5f, 0.5f); + Vector3 pos + = GetNewRezLocation( + RayStart, RayEnd, RayTargetID, Quaternion.Identity, + BypassRayCast, bRayEndIsIntersection, true, scale, false); + + RezObject(part, item, pos, null, Vector3.Zero, 0); + } } /// @@ -1967,14 +2005,14 @@ namespace OpenSim.Region.Framework.Scenes /// /// /// - /// - /// - /// + /// The position of the rezzed object. + /// The rotation of the rezzed object. If null, then the rotation stored with the object + /// will be used if it exists. + /// The velocity of the rezzed object. /// /// The SceneObjectGroup rezzed or null if rez was unsuccessful public virtual SceneObjectGroup RezObject( - SceneObjectPart sourcePart, TaskInventoryItem item, - Vector3 pos, Quaternion rot, Vector3 vel, int param) + SceneObjectPart sourcePart, TaskInventoryItem item, Vector3 pos, Quaternion? rot, Vector3 vel, int param) { if (null == item) return null; @@ -1992,8 +2030,14 @@ namespace OpenSim.Region.Framework.Scenes if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0) sourcePart.Inventory.RemoveInventoryItem(item.ItemID); } - - AddNewSceneObject(group, true, pos, rot, vel); + + AddNewSceneObject(group, true); + + group.AbsolutePosition = pos; + group.Velocity = vel; + + if (rot != null) + group.UpdateGroupRotationR((Quaternion)rot); // 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. @@ -2069,7 +2113,10 @@ namespace OpenSim.Region.Framework.Scenes SceneObjectPart[] partList = sog.Parts; foreach (SceneObjectPart child in partList) + { child.Inventory.ChangeInventoryOwner(ownerID); + child.TriggerScriptChangedEvent(Changed.OWNER); + } } else { @@ -2085,6 +2132,7 @@ namespace OpenSim.Region.Framework.Scenes { child.LastOwnerID = child.OwnerID; child.Inventory.ChangeInventoryOwner(groupID); + child.TriggerScriptChangedEvent(Changed.OWNER); } sog.SetOwnerId(groupID); diff --git a/OpenSim/Region/Framework/Scenes/Scene.cs b/OpenSim/Region/Framework/Scenes/Scene.cs index d407a6f033..fdd5205de8 100644 --- a/OpenSim/Region/Framework/Scenes/Scene.cs +++ b/OpenSim/Region/Framework/Scenes/Scene.cs @@ -563,7 +563,6 @@ namespace OpenSim.Region.Framework.Scenes m_regInfo = regInfo; m_regionHandle = m_regInfo.RegionHandle; m_regionName = m_regInfo.RegionName; - m_datastore = m_regInfo.DataStore; m_lastUpdate = Util.EnvironmentTickCount(); m_physicalPrim = physicalPrim; @@ -1428,20 +1427,6 @@ namespace OpenSim.Region.Framework.Scenes ); } - /// - /// Recount SceneObjectPart in parcel aabb - /// - private void UpdateLand() - { - if (LandChannel != null) - { - if (LandChannel.IsLandPrimCountTainted()) - { - EventManager.TriggerParcelPrimCountUpdate(); - } - } - } - /// /// Update the terrain if it needs to be updated. /// @@ -1536,8 +1521,11 @@ namespace OpenSim.Region.Framework.Scenes } /// - /// Return object to avatar Message + /// Tell an agent that their object has been returned. /// + /// + /// The actual return is handled by the caller. + /// /// Avatar Unique Id /// Name of object returned /// Location of object returned @@ -4851,7 +4839,20 @@ namespace OpenSim.Region.Framework.Scenes } } - public Vector3[] GetCombinedBoundingBox(List objects, out float minX, out float maxX, out float minY, out float maxY, out float minZ, out float maxZ) + /// + /// Get the volume of space that will encompass all the given objects. + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static Vector3[] GetCombinedBoundingBox( + List objects, + out float minX, out float maxX, out float minY, out float maxY, out float minZ, out float maxZ) { minX = 256; maxX = -256; @@ -4866,7 +4867,20 @@ namespace OpenSim.Region.Framework.Scenes { float ominX, ominY, ominZ, omaxX, omaxY, omaxZ; + Vector3 vec = g.AbsolutePosition; + g.GetAxisAlignedBoundingBoxRaw(out ominX, out omaxX, out ominY, out omaxY, out ominZ, out omaxZ); + +// m_log.DebugFormat( +// "[SCENE]: For {0} found AxisAlignedBoundingBoxRaw {1}, {2}", +// g.Name, new Vector3(ominX, ominY, ominZ), new Vector3(omaxX, omaxY, omaxZ)); + + ominX += vec.X; + omaxX += vec.X; + ominY += vec.Y; + omaxY += vec.Y; + ominZ += vec.Z; + omaxZ += vec.Z; if (minX > ominX) minX = ominX; diff --git a/OpenSim/Region/Framework/Scenes/SceneBase.cs b/OpenSim/Region/Framework/Scenes/SceneBase.cs index f343bc861e..c4547f2b46 100644 --- a/OpenSim/Region/Framework/Scenes/SceneBase.cs +++ b/OpenSim/Region/Framework/Scenes/SceneBase.cs @@ -136,8 +136,6 @@ namespace OpenSim.Region.Framework.Scenes get { return m_permissions; } } - protected string m_datastore; - /* Used by the loadbalancer plugin on GForge */ protected RegionStatus m_regStatus; public RegionStatus RegionStatus diff --git a/OpenSim/Region/Framework/Scenes/SceneGraph.cs b/OpenSim/Region/Framework/Scenes/SceneGraph.cs index 60855b2c36..72f040252f 100644 --- a/OpenSim/Region/Framework/Scenes/SceneGraph.cs +++ b/OpenSim/Region/Framework/Scenes/SceneGraph.cs @@ -997,6 +997,8 @@ namespace OpenSim.Region.Framework.Scenes { foreach (SceneObjectPart p in ((SceneObjectGroup)entity).Parts) { +// m_log.DebugFormat("[SCENE GRAPH]: Part {0} has name {1}", p.UUID, p.Name); + if (p.Name == name) { sop = p; @@ -1855,7 +1857,7 @@ namespace OpenSim.Region.Framework.Scenes { SceneObjectGroupsByLocalPartID[copy.LocalId] = copy; foreach (SceneObjectPart part in children) - SceneObjectGroupsByLocalPartID[copy.LocalId] = copy; + SceneObjectGroupsByLocalPartID[part.LocalId] = copy; } // PROBABLE END OF FIXME diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs b/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs index f17fb28f8d..19a95062b4 100644 --- a/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs +++ b/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs @@ -296,11 +296,14 @@ namespace OpenSim.Region.Framework.Scenes { Vector3 val = value; - if ((m_scene.TestBorderCross(val - Vector3.UnitX, Cardinals.E) || m_scene.TestBorderCross(val + Vector3.UnitX, Cardinals.W) - || m_scene.TestBorderCross(val - Vector3.UnitY, Cardinals.N) || m_scene.TestBorderCross(val + Vector3.UnitY, Cardinals.S)) - && !IsAttachmentCheckFull() && (!m_scene.LoadingPrims)) + if (Scene != null) { - m_scene.CrossPrimGroupIntoNewRegion(val, this, true); + if ((Scene.TestBorderCross(val - Vector3.UnitX, Cardinals.E) || Scene.TestBorderCross(val + Vector3.UnitX, Cardinals.W) + || Scene.TestBorderCross(val - Vector3.UnitY, Cardinals.N) || Scene.TestBorderCross(val + Vector3.UnitY, Cardinals.S)) + && !IsAttachmentCheckFull() && (!Scene.LoadingPrims)) + { + m_scene.CrossPrimGroupIntoNewRegion(val, this, true); + } } if (RootPart.GetStatusSandbox()) @@ -308,8 +311,11 @@ namespace OpenSim.Region.Framework.Scenes if (Util.GetDistanceTo(RootPart.StatusSandboxPos, value) > 10) { RootPart.ScriptSetPhysicsStatus(false); - Scene.SimChat(Utils.StringToBytes("Hit Sandbox Limit"), - ChatTypeEnum.DebugChannel, 0x7FFFFFFF, RootPart.AbsolutePosition, Name, UUID, false); + + if (Scene != null) + Scene.SimChat(Utils.StringToBytes("Hit Sandbox Limit"), + ChatTypeEnum.DebugChannel, 0x7FFFFFFF, RootPart.AbsolutePosition, Name, UUID, false); + return; } } @@ -325,6 +331,9 @@ namespace OpenSim.Region.Framework.Scenes //m_rootPart.GroupPosition.Z); //m_scene.PhysicsScene.AddPhysicsActorTaint(m_rootPart.PhysActor); //} + + if (Scene != null) + Scene.EventManager.TriggerParcelPrimCountTainted(); } } @@ -1313,8 +1322,10 @@ namespace OpenSim.Region.Framework.Scenes parcel.LandData.OtherCleanTime) { DetachFromBackup(); - m_log.InfoFormat("[SCENE]: Returning object {0} due to parcel auto return", RootPart.UUID.ToString()); - m_scene.AddReturn(OwnerID, Name, AbsolutePosition, "parcel auto return"); + m_log.DebugFormat( + "[SCENE OBJECT GROUP]: Returning object {0} due to parcel autoreturn", + RootPart.UUID); + m_scene.AddReturn(OwnerID, Name, AbsolutePosition, "parcel autoreturn"); m_scene.DeRezObjects(null, new List() { RootPart.LocalId }, UUID.Zero, DeRezAction.Return, UUID.Zero); @@ -1761,10 +1772,12 @@ namespace OpenSim.Region.Framework.Scenes /// public void ServiceObjectPropertiesFamilyRequest(IClientAPI remoteClient, UUID AgentID, uint RequestFlags) { - remoteClient.SendObjectPropertiesFamilyData(RequestFlags, RootPart.UUID, RootPart.OwnerID, RootPart.GroupID, RootPart.BaseMask, - RootPart.OwnerMask, RootPart.GroupMask, RootPart.EveryoneMask, RootPart.NextOwnerMask, - RootPart.OwnershipCost, RootPart.ObjectSaleType, RootPart.SalePrice, RootPart.Category, - RootPart.CreatorID, RootPart.Name, RootPart.Description); + remoteClient.SendObjectPropertiesFamilyData(RootPart, RequestFlags); + +// remoteClient.SendObjectPropertiesFamilyData(RequestFlags, RootPart.UUID, RootPart.OwnerID, RootPart.GroupID, RootPart.BaseMask, +// RootPart.OwnerMask, RootPart.GroupMask, RootPart.EveryoneMask, RootPart.NextOwnerMask, +// RootPart.OwnershipCost, RootPart.ObjectSaleType, RootPart.SalePrice, RootPart.Category, +// RootPart.CreatorID, RootPart.Name, RootPart.Description); } public void SetPartOwner(SceneObjectPart part, UUID cAgentID, UUID cGroupID) diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs b/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs index 4d5eedfc95..8a8a6993cc 100644 --- a/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs +++ b/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs @@ -2055,15 +2055,7 @@ namespace OpenSim.Region.Framework.Scenes public void GetProperties(IClientAPI client) { - //Viewer wants date in microseconds so multiply it by 1,000,000. - client.SendObjectPropertiesReply( - m_fromUserInventoryItemID, (ulong)_creationDate*(ulong)1e6, _creatorID, UUID.Zero, UUID.Zero, - _groupID, (short)InventorySerial, _lastOwnerID, UUID, _ownerID, - ParentGroup.RootPart.TouchName, new byte[0], ParentGroup.RootPart.SitName, Name, Description, - ParentGroup.RootPart._ownerMask, ParentGroup.RootPart._nextOwnerMask, ParentGroup.RootPart._groupMask, ParentGroup.RootPart._everyoneMask, - ParentGroup.RootPart._baseMask, - ParentGroup.RootPart.ObjectSaleType, - ParentGroup.RootPart.SalePrice); + client.SendObjectPropertiesReply(this); } public UUID GetRootPartUUID() @@ -2088,7 +2080,14 @@ namespace OpenSim.Region.Framework.Scenes axPos *= parentRot; Vector3 translationOffsetPosition = axPos; - return GroupPosition + translationOffsetPosition; + +// m_log.DebugFormat("[SCENE OBJECT PART]: Found group pos {0} for part {1}", GroupPosition, Name); + + Vector3 worldPos = GroupPosition + translationOffsetPosition; + +// m_log.DebugFormat("[SCENE OBJECT PART]: Found world pos {0} for part {1}", worldPos, Name); + + return worldPos; } /// diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs b/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs index fa404c01bd..3281eabd33 100644 --- a/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs +++ b/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs @@ -175,12 +175,12 @@ namespace OpenSim.Region.Framework.Scenes foreach (TaskInventoryItem item in items) { if (ownerId != item.OwnerID) - { item.LastOwnerID = item.OwnerID; - item.OwnerID = ownerId; - item.PermsMask = 0; - item.PermsGranter = UUID.Zero; - } + + item.OwnerID = ownerId; + item.PermsMask = 0; + item.PermsGranter = UUID.Zero; + item.OwnerChanged = true; } } diff --git a/OpenSim/Region/Framework/Scenes/Serialization/CoalescedSceneObjectsSerializer.cs b/OpenSim/Region/Framework/Scenes/Serialization/CoalescedSceneObjectsSerializer.cs new file mode 100644 index 0000000000..babcb54ae9 --- /dev/null +++ b/OpenSim/Region/Framework/Scenes/Serialization/CoalescedSceneObjectsSerializer.cs @@ -0,0 +1,149 @@ +/* + * 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.Drawing; +using System.IO; +using System.Reflection; +using System.Xml; +using log4net; +using OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Region.Framework.Interfaces; +using OpenSim.Region.Framework.Scenes; + +namespace OpenSim.Region.Framework.Scenes.Serialization +{ + /// + /// Serialize and deserialize coalesced scene objects. + /// + /// + /// Deserialization not yet here. + /// + public class CoalescedSceneObjectsSerializer + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + /// + /// Serialize coalesced objects to Xml + /// + /// + /// + public static string ToXml(CoalescedSceneObjects coa) + { + using (StringWriter sw = new StringWriter()) + { + using (XmlTextWriter writer = new XmlTextWriter(sw)) + { + Vector3 size; + + List coaObjects = coa.Objects; + +// m_log.DebugFormat( +// "[COALESCED SCENE OBJECTS SERIALIZER]: Writing {0} objects for coalesced object", +// coaObjects.Count); + + // This is weak - we're relying on the set of coalesced objects still being identical + Vector3[] offsets = coa.GetSizeAndOffsets(out size); + + writer.WriteStartElement("CoalescedObject"); + + writer.WriteAttributeString("x", size.X.ToString()); + writer.WriteAttributeString("y", size.Y.ToString()); + writer.WriteAttributeString("z", size.Z.ToString()); + + // Embed the offsets into the group XML + for (int i = 0; i < coaObjects.Count; i++) + { + SceneObjectGroup obj = coaObjects[i]; + +// m_log.DebugFormat( +// "[COALESCED SCENE OBJECTS SERIALIZER]: Writing offset for object {0}, {1}", +// 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()); + + SceneObjectSerializer.ToOriginalXmlFormat(obj, writer, true); + + writer.WriteEndElement(); // SceneObjectGroup + } + + writer.WriteEndElement(); // CoalescedObject + } + + string output = sw.ToString(); + +// Console.WriteLine(output); + + return output; + } + } + + public static bool TryFromXml(string xml, out CoalescedSceneObjects coa) + { +// m_log.DebugFormat("[COALESCED SCENE OBJECTS SERIALIZER]: TryFromXml() deserializing {0}", xml); + + coa = null; + + using (StringReader sr = new StringReader(xml)) + { + using (XmlTextReader reader = new XmlTextReader(sr)) + { + reader.Read(); + if (reader.Name != "CoalescedObject") + { +// m_log.DebugFormat( +// "[COALESCED SCENE OBJECTS SERIALIZER]: TryFromXml() root element was {0} so returning false", +// reader.Name); + + return false; + } + + coa = new CoalescedSceneObjects(UUID.Zero); + reader.Read(); + + while (reader.NodeType != XmlNodeType.EndElement && reader.Name != "CoalescedObject") + { + if (reader.Name == "SceneObjectGroup") + { + string soXml = reader.ReadOuterXml(); + coa.Add(SceneObjectSerializer.FromOriginalXmlFormat(soXml)); + } + } + + reader.ReadEndElement(); // CoalescedObject + } + } + + return true; + } + } +} \ No newline at end of file diff --git a/OpenSim/Region/Framework/Scenes/Serialization/SceneObjectSerializer.cs b/OpenSim/Region/Framework/Scenes/Serialization/SceneObjectSerializer.cs index 57ae4fd24f..bb8a83a1af 100644 --- a/OpenSim/Region/Framework/Scenes/Serialization/SceneObjectSerializer.cs +++ b/OpenSim/Region/Framework/Scenes/Serialization/SceneObjectSerializer.cs @@ -139,6 +139,7 @@ namespace OpenSim.Region.Framework.Scenes.Serialization return sw.ToString(); } } + /// /// Serialize a scene object to the original xml format @@ -146,11 +147,25 @@ namespace OpenSim.Region.Framework.Scenes.Serialization /// /// public static void ToOriginalXmlFormat(SceneObjectGroup sceneObject, XmlTextWriter writer) + { + ToOriginalXmlFormat(sceneObject, writer, false); + } + + /// + /// Serialize a scene object to the original xml format + /// + /// + /// + /// If false, don't write the enclosing SceneObjectGroup element + /// + public static void ToOriginalXmlFormat(SceneObjectGroup sceneObject, XmlTextWriter writer, bool noRootElement) { //m_log.DebugFormat("[SERIALIZER]: Starting serialization of {0}", Name); //int time = System.Environment.TickCount; - writer.WriteStartElement(String.Empty, "SceneObjectGroup", String.Empty); + if (!noRootElement) + writer.WriteStartElement(String.Empty, "SceneObjectGroup", String.Empty); + writer.WriteStartElement(String.Empty, "RootPart", String.Empty); ToXmlFormat(sceneObject.RootPart, writer); writer.WriteEndElement(); @@ -170,10 +185,12 @@ namespace OpenSim.Region.Framework.Scenes.Serialization writer.WriteEndElement(); // OtherParts sceneObject.SaveScriptedState(writer); - writer.WriteEndElement(); // SceneObjectGroup + + if (!noRootElement) + writer.WriteEndElement(); // SceneObjectGroup //m_log.DebugFormat("[SERIALIZER]: Finished serialization of SOG {0}, {1}ms", Name, System.Environment.TickCount - time); - } + } protected static void ToXmlFormat(SceneObjectPart part, XmlTextWriter writer) { @@ -1318,7 +1335,7 @@ namespace OpenSim.Region.Framework.Scenes.Serialization writer.WriteStartElement("SculptData"); byte[] sd; if (shp.SculptData != null) - sd = shp.ExtraParams; + sd = shp.SculptData; else sd = Utils.EmptyBytes; writer.WriteBase64(sd, 0, sd.Length); diff --git a/OpenSim/Region/Framework/Scenes/Tests/StandaloneTeleportTests.cs b/OpenSim/Region/Framework/Scenes/Tests/StandaloneTeleportTests.cs index 8588f7f599..dd28416788 100644 --- a/OpenSim/Region/Framework/Scenes/Tests/StandaloneTeleportTests.cs +++ b/OpenSim/Region/Framework/Scenes/Tests/StandaloneTeleportTests.cs @@ -117,11 +117,11 @@ namespace OpenSim.Region.Framework.Scenes.Tests ISharedRegionModule interregionComms = new LocalSimulationConnectorModule(); - Scene sceneB = SceneSetupHelpers.SetupScene("sceneB", sceneBId, 1010, 1010, "grid"); + Scene sceneB = SceneSetupHelpers.SetupScene("sceneB", sceneBId, 1010, 1010); SceneSetupHelpers.SetupSceneModules(sceneB, new IniConfigSource(), interregionComms); sceneB.RegisterRegionWithGrid(); - Scene sceneA = SceneSetupHelpers.SetupScene("sceneA", sceneAId, 1000, 1000, "grid"); + Scene sceneA = SceneSetupHelpers.SetupScene("sceneA", sceneAId, 1000, 1000); SceneSetupHelpers.SetupSceneModules(sceneA, new IniConfigSource(), interregionComms); sceneA.RegisterRegionWithGrid(); diff --git a/OpenSim/Region/Framework/Scenes/Tests/TaskInventoryTests.cs b/OpenSim/Region/Framework/Scenes/Tests/TaskInventoryTests.cs index 8138bcc19a..2aef4b0d19 100644 --- a/OpenSim/Region/Framework/Scenes/Tests/TaskInventoryTests.cs +++ b/OpenSim/Region/Framework/Scenes/Tests/TaskInventoryTests.cs @@ -101,7 +101,7 @@ namespace OpenSim.Region.Framework.Tests TestHelper.InMethod(); // log4net.Config.XmlConfigurator.Configure(); - Scene scene = SceneSetupHelpers.SetupScene("inventory"); + Scene scene = SceneSetupHelpers.SetupScene(); UserAccount user1 = CreateUser(scene); SceneObjectGroup sog1 = CreateSO1(scene, user1.PrincipalID); SceneObjectPart sop1 = sog1.RootPart; @@ -127,7 +127,7 @@ namespace OpenSim.Region.Framework.Tests TestHelper.InMethod(); // log4net.Config.XmlConfigurator.Configure(); - Scene scene = SceneSetupHelpers.SetupScene("inventory"); + Scene scene = SceneSetupHelpers.SetupScene(); UserAccount user1 = CreateUser(scene); SceneObjectGroup sog1 = CreateSO1(scene, user1.PrincipalID); SceneObjectPart sop1 = sog1.RootPart; diff --git a/OpenSim/Region/Framework/Scenes/Tests/UuidGathererTests.cs b/OpenSim/Region/Framework/Scenes/Tests/UuidGathererTests.cs index 6b70865533..dbf9e0f550 100644 --- a/OpenSim/Region/Framework/Scenes/Tests/UuidGathererTests.cs +++ b/OpenSim/Region/Framework/Scenes/Tests/UuidGathererTests.cs @@ -47,7 +47,9 @@ namespace OpenSim.Region.Framework.Scenes.Tests [SetUp] public void Init() { - m_assetService = new MockAssetService(); + // FIXME: We don't need a full scene here - it would be enough to set up the asset service. + Scene scene = SceneSetupHelpers.SetupScene(); + m_assetService = scene.AssetService; m_uuidGatherer = new UuidGatherer(m_assetService); } diff --git a/OpenSim/Region/OptionalModules/Agent/InternetRelayClientView/Server/IRCClientView.cs b/OpenSim/Region/OptionalModules/Agent/InternetRelayClientView/Server/IRCClientView.cs index 821cd4bd33..4b6e52e757 100644 --- a/OpenSim/Region/OptionalModules/Agent/InternetRelayClientView/Server/IRCClientView.cs +++ b/OpenSim/Region/OptionalModules/Agent/InternetRelayClientView/Server/IRCClientView.cs @@ -1332,14 +1332,13 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server } - public void SendObjectPropertiesFamilyData(uint RequestFlags, UUID ObjectUUID, UUID OwnerID, UUID GroupID, uint BaseMask, uint OwnerMask, uint GroupMask, uint EveryoneMask, uint NextOwnerMask, int OwnershipCost, byte SaleType, int SalePrice, uint Category, UUID LastOwnerID, string ObjectName, string Description) + public void SendObjectPropertiesFamilyData(ISceneEntity Entity, uint RequestFlags) { } - public void SendObjectPropertiesReply(UUID ItemID, ulong CreationDate, UUID CreatorUUID, UUID FolderUUID, UUID FromTaskUUID, UUID GroupUUID, short InventorySerial, UUID LastOwnerUUID, UUID ObjectUUID, UUID OwnerUUID, string TouchTitle, byte[] TextureID, string SitTitle, string ItemName, string ItemDescription, uint OwnerMask, uint NextOwnerMask, uint GroupMask, uint EveryoneMask, uint BaseMask, byte saleType, int salePrice) + public void SendObjectPropertiesReply(ISceneEntity entity) { - } public void SendAgentOffline(UUID[] agentIDs) diff --git a/OpenSim/Region/OptionalModules/Avatar/Concierge/ConciergeModule.cs b/OpenSim/Region/OptionalModules/Avatar/Concierge/ConciergeModule.cs index 2fcc477dc2..0d6313acb4 100644 --- a/OpenSim/Region/OptionalModules/Avatar/Concierge/ConciergeModule.cs +++ b/OpenSim/Region/OptionalModules/Avatar/Concierge/ConciergeModule.cs @@ -80,16 +80,11 @@ namespace OpenSim.Region.OptionalModules.Avatar.Concierge m_config = config.Configs["Concierge"]; if (null == m_config) - { - m_log.Info("[Concierge]: no config found, plugin disabled"); return; - } if (!m_config.GetBoolean("enabled", false)) - { - m_log.Info("[Concierge]: plugin disabled by configuration"); return; - } + m_enabled = true; @@ -113,9 +108,9 @@ namespace OpenSim.Region.OptionalModules.Avatar.Concierge { m_replacingChatModule = false; } + m_log.InfoFormat("[Concierge] {0} ChatModule", m_replacingChatModule ? "replacing" : "not replacing"); - // take note of concierge channel and of identity m_conciergeChannel = config.Configs["Concierge"].GetInt("concierge_channel", m_conciergeChannel); m_whoami = m_config.GetString("whoami", "conferencier"); diff --git a/OpenSim/Region/OptionalModules/Avatar/Voice/FreeSwitchVoice/FreeSwitchVoiceModule.cs b/OpenSim/Region/OptionalModules/Avatar/Voice/FreeSwitchVoice/FreeSwitchVoiceModule.cs index 05a1c3b427..7909d8a8ec 100644 --- a/OpenSim/Region/OptionalModules/Avatar/Voice/FreeSwitchVoice/FreeSwitchVoiceModule.cs +++ b/OpenSim/Region/OptionalModules/Avatar/Voice/FreeSwitchVoice/FreeSwitchVoiceModule.cs @@ -106,16 +106,10 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice m_Config = config.Configs["FreeSwitchVoice"]; if (m_Config == null) - { - m_log.Info("[FreeSwitchVoice] no config found, plugin disabled"); return; - } if (!m_Config.GetBoolean("Enabled", false)) - { - m_log.Info("[FreeSwitchVoice] plugin disabled by configuration"); return; - } try { diff --git a/OpenSim/Region/OptionalModules/Avatar/Voice/VivoxVoice/VivoxVoiceModule.cs b/OpenSim/Region/OptionalModules/Avatar/Voice/VivoxVoice/VivoxVoiceModule.cs index 34d0e248c6..534bf929a4 100644 --- a/OpenSim/Region/OptionalModules/Avatar/Voice/VivoxVoice/VivoxVoiceModule.cs +++ b/OpenSim/Region/OptionalModules/Avatar/Voice/VivoxVoice/VivoxVoiceModule.cs @@ -121,16 +121,10 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice m_config = config.Configs["VivoxVoice"]; if (null == m_config) - { - m_log.Info("[VivoxVoice] no config found, plugin disabled"); return; - } if (!m_config.GetBoolean("enabled", false)) - { - m_log.Info("[VivoxVoice] plugin disabled by configuration"); return; - } try { @@ -218,7 +212,6 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice m_pluginEnabled = true; m_log.Info("[VivoxVoice] plugin enabled"); - } catch (Exception e) { @@ -228,7 +221,6 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice } } - // Called to indicate that the module has been added to the region public void AddRegion(Scene scene) { diff --git a/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/GroupsMessagingModule.cs b/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/GroupsMessagingModule.cs index 3d34441a90..8c01d75b8f 100644 --- a/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/GroupsMessagingModule.cs +++ b/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/GroupsMessagingModule.cs @@ -86,13 +86,10 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups return; } - m_log.Info("[GROUPS-MESSAGING]: Initializing GroupsMessagingModule"); - m_debugEnabled = groupsConfig.GetBoolean("DebugEnabled", true); } m_log.Info("[GROUPS-MESSAGING]: GroupsMessagingModule starting up"); - } public void AddRegion(Scene scene) diff --git a/OpenSim/Region/OptionalModules/Example/BareBonesShared/BareBonesSharedModule.cs b/OpenSim/Region/OptionalModules/Example/BareBonesShared/BareBonesSharedModule.cs index 781fe952d2..dddea3e1d8 100644 --- a/OpenSim/Region/OptionalModules/Example/BareBonesShared/BareBonesSharedModule.cs +++ b/OpenSim/Region/OptionalModules/Example/BareBonesShared/BareBonesSharedModule.cs @@ -33,6 +33,9 @@ using Nini.Config; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; +[assembly: Addin("BareBonesSharedModule", "0.1")] +[assembly: AddinDependency("OpenSim", "0.5")] + namespace OpenSim.Region.OptionalModules.Example.BareBonesShared { /// diff --git a/OpenSim/Region/OptionalModules/Scripting/Minimodule/MRMModule.cs b/OpenSim/Region/OptionalModules/Scripting/Minimodule/MRMModule.cs index df60709535..74f52087fe 100644 --- a/OpenSim/Region/OptionalModules/Scripting/Minimodule/MRMModule.cs +++ b/OpenSim/Region/OptionalModules/Scripting/Minimodule/MRMModule.cs @@ -75,7 +75,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule if (source.Configs["MRM"].GetBoolean("Enabled", false)) { - m_log.Info("[MRM] Enabling MRM Module"); + m_log.Info("[MRM]: Enabling MRM Module"); m_scene = scene; // when hidden, we don't listen for client initiated script events @@ -90,14 +90,6 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule scene.RegisterModuleInterface(this); } - else - { - m_log.Info("[MRM] Disabled MRM Module (Disabled in ini)"); - } - } - else - { - m_log.Info("[MRM] Disabled MRM Module (Default disabled)"); } } diff --git a/OpenSim/Region/OptionalModules/World/NPC/NPCAvatar.cs b/OpenSim/Region/OptionalModules/World/NPC/NPCAvatar.cs index 96760a2721..2504e3019c 100644 --- a/OpenSim/Region/OptionalModules/World/NPC/NPCAvatar.cs +++ b/OpenSim/Region/OptionalModules/World/NPC/NPCAvatar.cs @@ -786,18 +786,12 @@ namespace OpenSim.Region.OptionalModules.World.NPC { } - public void SendObjectPropertiesFamilyData(uint RequestFlags, UUID ObjectUUID, UUID OwnerID, UUID GroupID, - uint BaseMask, uint OwnerMask, uint GroupMask, uint EveryoneMask, - uint NextOwnerMask, int OwnershipCost, byte SaleType, int SalePrice, uint Category, - UUID LastOwnerID, string ObjectName, string Description) + public void SendObjectPropertiesFamilyData(ISceneEntity Entity, uint RequestFlags) { + } - public void SendObjectPropertiesReply(UUID ItemID, ulong CreationDate, UUID CreatorUUID, UUID FolderUUID, UUID FromTaskUUID, - UUID GroupUUID, short InventorySerial, UUID LastOwnerUUID, UUID ObjectUUID, - UUID OwnerUUID, string TouchTitle, byte[] TextureID, string SitTitle, string ItemName, - string ItemDescription, uint OwnerMask, uint NextOwnerMask, uint GroupMask, uint EveryoneMask, - uint BaseMask, byte saleType, int salePrice) + public void SendObjectPropertiesReply(ISceneEntity entity) { } diff --git a/OpenSim/Region/Physics/BulletDotNETPlugin/BulletDotNETScene.cs b/OpenSim/Region/Physics/BulletDotNETPlugin/BulletDotNETScene.cs index 85e34c1e3d..6df213d851 100644 --- a/OpenSim/Region/Physics/BulletDotNETPlugin/BulletDotNETScene.cs +++ b/OpenSim/Region/Physics/BulletDotNETPlugin/BulletDotNETScene.cs @@ -648,6 +648,9 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin if (pbs.ProfileHollow != 0) iPropertiesNotSupportedDefault++; + if ((pbs.PathBegin != 0) || pbs.PathEnd != 0) + iPropertiesNotSupportedDefault++; + if ((pbs.PathTwistBegin != 0) || (pbs.PathTwist != 0)) iPropertiesNotSupportedDefault++; diff --git a/OpenSim/Region/Physics/OdePlugin/OdePlugin.cs b/OpenSim/Region/Physics/OdePlugin/OdePlugin.cs index eb97f41e3c..a0101af2bb 100644 --- a/OpenSim/Region/Physics/OdePlugin/OdePlugin.cs +++ b/OpenSim/Region/Physics/OdePlugin/OdePlugin.cs @@ -2528,6 +2528,9 @@ namespace OpenSim.Region.Physics.OdePlugin if (pbs.ProfileHollow != 0) iPropertiesNotSupportedDefault++; + if ((pbs.PathBegin != 0) || pbs.PathEnd != 0) + iPropertiesNotSupportedDefault++; + if ((pbs.PathTwistBegin != 0) || (pbs.PathTwist != 0)) iPropertiesNotSupportedDefault++; diff --git a/OpenSim/Region/RegionCombinerModule/RegionCombinerLargeLandChannel.cs b/OpenSim/Region/RegionCombinerModule/RegionCombinerLargeLandChannel.cs index 98e5453d1e..a133e51da6 100644 --- a/OpenSim/Region/RegionCombinerModule/RegionCombinerLargeLandChannel.cs +++ b/OpenSim/Region/RegionCombinerModule/RegionCombinerLargeLandChannel.cs @@ -130,11 +130,6 @@ public class RegionCombinerLargeLandChannel : ILandChannel } } - public bool IsLandPrimCountTainted() - { - return RootRegionLandChannel.IsLandPrimCountTainted(); - } - public bool IsForcefulBansAllowed() { return RootRegionLandChannel.IsForcefulBansAllowed(); diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs index 72ee495906..aa28fa0ca2 100644 --- a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs +++ b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs @@ -81,7 +81,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api /// public class LSL_Api : MarshalByRefObject, ILSL_Api, IScriptApi { - //private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected IScriptEngine m_ScriptEngine; protected SceneObjectPart m_host; protected uint m_localID; @@ -9835,63 +9835,42 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api public LSL_Integer llGetParcelPrimCount(LSL_Vector pos, int category, int sim_wide) { m_host.AddScriptLPS(1); + + ILandObject lo = World.LandChannel.GetLandObject((float)pos.x, (float)pos.y); - LandData land = World.GetLandData((float)pos.x, (float)pos.y); - - if (land == null) - { + if (lo == null) return 0; - } + + IPrimCounts pc = lo.PrimCounts; - else + if (sim_wide != ScriptBaseClass.FALSE) { - if (sim_wide != 0) + if (category == ScriptBaseClass.PARCEL_COUNT_TOTAL) { - if (category == 0) - { - return land.SimwidePrims; - } - - else - { - //public int simwideArea = 0; - return 0; - } + return pc.Simulator; } - else { - if (category == 0)//Total Prims - { - return 0;//land. - } - - else if (category == 1)//Owner Prims - { - return land.OwnerPrims; - } - - else if (category == 2)//Group Prims - { - return land.GroupPrims; - } - - else if (category == 3)//Other Prims - { - return land.OtherPrims; - } - - else if (category == 4)//Selected - { - return land.SelectedPrims; - } - - else if (category == 5)//Temp - { - return 0;//land. - } + // counts not implemented yet + return 0; } } + else + { + if (category == ScriptBaseClass.PARCEL_COUNT_TOTAL) + return pc.Total; + else if (category == ScriptBaseClass.PARCEL_COUNT_OWNER) + return pc.Owner; + else if (category == ScriptBaseClass.PARCEL_COUNT_GROUP) + return pc.Group; + else if (category == ScriptBaseClass.PARCEL_COUNT_OTHER) + return pc.Others; + else if (category == ScriptBaseClass.PARCEL_COUNT_SELECTED) + return pc.Selected; + else if (category == ScriptBaseClass.PARCEL_COUNT_TEMP) + return 0; // counts not implemented yet + } + return 0; } @@ -10278,6 +10257,60 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api return GetLinkPrimitiveParams(obj, rules); } + + public void print(string str) + { + // yes, this is a real LSL function. See: http://wiki.secondlife.com/wiki/Print + IOSSL_Api ossl = (IOSSL_Api)m_ScriptEngine.GetApi(m_itemID, "OSSL"); + if (ossl != null) + { + ossl.CheckThreatLevel(ThreatLevel.High, "print"); + m_log.Info("LSL print():" + str); + } + } + + private string Name2Username(string name) + { + string[] parts = name.Split(new char[] {' '}); + if (parts.Length < 2) + return name.ToLower(); + if (parts[1] == "Resident") + return parts[0].ToLower(); + + return name.Replace(" ", ".").ToLower(); + } + + public LSL_String llGetUsername(string id) + { + return Name2Username(llKey2Name(id)); + } + + public LSL_String llRequestUsername(string id) + { + UUID rq = UUID.Random(); + + AsyncCommands.DataserverPlugin.RegisterRequest(m_localID, m_itemID, rq.ToString()); + + AsyncCommands.DataserverPlugin.DataserverReply(rq.ToString(), Name2Username(llKey2Name(id))); + + return rq.ToString(); + } + + public LSL_String llGetDisplayName(string id) + { + return llKey2Name(id); + } + + public LSL_String llRequestDisplayName(string id) + { + UUID rq = UUID.Random(); + + AsyncCommands.DataserverPlugin.RegisterRequest(m_localID, m_itemID, rq.ToString()); + + AsyncCommands.DataserverPlugin.DataserverReply(rq.ToString(), llKey2Name(id)); + + return rq.ToString(); + } } public class NotecardCache diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/Plugins/SensorRepeat.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/Plugins/SensorRepeat.cs index fefbb35760..47c7915a3e 100644 --- a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/Plugins/SensorRepeat.cs +++ b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/Plugins/SensorRepeat.cs @@ -50,6 +50,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api.Plugins private Object SenseLock = new Object(); private const int AGENT = 1; + private const int AGENT_BY_USERNAME = 0x10; private const int ACTIVE = 2; private const int PASSIVE = 4; private const int SCRIPTED = 8; @@ -202,7 +203,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api.Plugins List sensedEntities = new List(); // Is the sensor type is AGENT and not SCRIPTED then include agents - if ((ts.type & AGENT) != 0 && (ts.type & SCRIPTED) == 0) + if ((ts.type & (AGENT | AGENT_BY_USERNAME)) != 0 && (ts.type & SCRIPTED) == 0) { sensedEntities.AddRange(doAgentSensor(ts)); } @@ -493,9 +494,26 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api.Plugins { ScenePresence sp; // Try lookup by name will return if/when found - if (!m_CmdManager.m_ScriptEngine.World.TryGetAvatarByName(ts.name, out sp)) - return sensedEntities; - senseEntity(sp); + if (((ts.type & AGENT) != 0) && m_CmdManager.m_ScriptEngine.World.TryGetAvatarByName(ts.name, out sp)) + senseEntity(sp); + if ((ts.type & AGENT_BY_USERNAME) != 0) + { + m_CmdManager.m_ScriptEngine.World.ForEachScenePresence( + delegate (ScenePresence ssp) + { + if (ssp.Lastname == "Resident") + { + if (ssp.Firstname.ToLower() == ts.name) + senseEntity(ssp); + return; + } + if (ssp.Name.Replace(" ", ".").ToLower() == ts.name) + senseEntity(ssp); + } + ); + } + + return sensedEntities; } else { diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Interface/ILSL_Api.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Interface/ILSL_Api.cs index 561e3b3213..654ea8129a 100644 --- a/OpenSim/Region/ScriptEngine/Shared/Api/Interface/ILSL_Api.cs +++ b/OpenSim/Region/ScriptEngine/Shared/Api/Interface/ILSL_Api.cs @@ -209,6 +209,10 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api.Interfaces void llInstantMessage(string user, string message); LSL_String llIntegerToBase64(int number); LSL_String llKey2Name(string id); + LSL_String llGetUsername(string id); + LSL_String llRequestUsername(string id); + LSL_String llGetDisplayName(string id); + LSL_String llRequestDisplayName(string id); void llLinkParticleSystem(int linknum, LSL_List rules); LSL_String llList2CSV(LSL_List src); LSL_Float llList2Float(LSL_List src, int index); @@ -398,6 +402,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api.Interfaces LSL_Vector llWind(LSL_Vector offset); LSL_String llXorBase64Strings(string str1, string str2); LSL_String llXorBase64StringsCorrect(string str1, string str2); + void print(string str); void SetPrimitiveParamsEx(LSL_Key prim, LSL_List rules); LSL_List GetLinkPrimitiveParamsEx(LSL_Key prim, LSL_List rules); diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/LSL_Constants.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/LSL_Constants.cs index b3c4d95c48..9377cdafd8 100644 --- a/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/LSL_Constants.cs +++ b/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/LSL_Constants.cs @@ -50,6 +50,8 @@ namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase public const int STATUS_CAST_SHADOWS = 512; public const int AGENT = 1; + public const int AGENT_BY_LEGACY_NAME = 1; + public const int AGENT_BY_USERNAME = 0x10; public const int ACTIVE = 2; public const int PASSIVE = 4; public const int SCRIPTED = 8; diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/LSL_Stub.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/LSL_Stub.cs index 451163fe99..303d75e36d 100644 --- a/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/LSL_Stub.cs +++ b/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/LSL_Stub.cs @@ -894,6 +894,26 @@ namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase return m_LSL_Functions.llKey2Name(id); } + public LSL_String llGetUsername(string id) + { + return m_LSL_Functions.llGetUsername(id); + } + + public LSL_String llRequestUsername(string id) + { + return m_LSL_Functions.llRequestUsername(id); + } + + public LSL_String llGetDisplayName(string id) + { + return m_LSL_Functions.llGetDisplayName(id); + } + + public LSL_String llRequestDisplayName(string id) + { + return m_LSL_Functions.llRequestDisplayName(id); + } + public void llLinkParticleSystem(int linknum, LSL_List rules) { m_LSL_Functions.llLinkParticleSystem(linknum, rules); @@ -1847,5 +1867,10 @@ namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase { return m_LSL_Functions.llClearPrimMedia(face); } + + public void print(string str) + { + m_LSL_Functions.print(str); + } } } diff --git a/OpenSim/Services/AssetService/AssetService.cs b/OpenSim/Services/AssetService/AssetService.cs index a81af4355a..e1f90b6e18 100644 --- a/OpenSim/Services/AssetService/AssetService.cs +++ b/OpenSim/Services/AssetService/AssetService.cs @@ -89,6 +89,8 @@ namespace OpenSim.Services.AssetService public virtual AssetBase Get(string id) { +// m_log.DebugFormat("[ASSET SERVICE]: Get asset for {0}", id); + UUID assetID; if (!UUID.TryParse(id, out assetID)) @@ -107,6 +109,8 @@ namespace OpenSim.Services.AssetService public virtual AssetMetadata GetMetadata(string id) { +// m_log.DebugFormat("[ASSET SERVICE]: Get asset metadata for {0}", id); + UUID assetID; if (!UUID.TryParse(id, out assetID)) @@ -121,6 +125,8 @@ namespace OpenSim.Services.AssetService public virtual byte[] GetData(string id) { +// m_log.DebugFormat("[ASSET SERVICE]: Get asset data for {0}", id); + UUID assetID; if (!UUID.TryParse(id, out assetID)) @@ -150,7 +156,9 @@ namespace OpenSim.Services.AssetService public virtual string Store(AssetBase asset) { - //m_log.DebugFormat("[ASSET SERVICE]: Store asset {0} {1}", asset.Name, asset.ID); +// m_log.DebugFormat( +// "[ASSET SERVICE]: Storing asset {0} {1}, bytes {2}", asset.Name, asset.ID, asset.Data.Length); + m_Database.StoreAsset(asset); return asset.ID; diff --git a/OpenSim/Services/Connectors/Asset/AssetServiceConnector.cs b/OpenSim/Services/Connectors/Asset/AssetServiceConnector.cs index 65b3537041..f1da4fa777 100644 --- a/OpenSim/Services/Connectors/Asset/AssetServiceConnector.cs +++ b/OpenSim/Services/Connectors/Asset/AssetServiceConnector.cs @@ -34,7 +34,6 @@ using Nini.Config; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.Communications; -using OpenSim.Framework.Servers.HttpServer; using OpenSim.Services.Interfaces; using OpenMetaverse; diff --git a/OpenSim/Services/Connectors/Authentication/AuthenticationServiceConnector.cs b/OpenSim/Services/Connectors/Authentication/AuthenticationServiceConnector.cs index 6f77a2d8b3..c04e7a4971 100644 --- a/OpenSim/Services/Connectors/Authentication/AuthenticationServiceConnector.cs +++ b/OpenSim/Services/Connectors/Authentication/AuthenticationServiceConnector.cs @@ -33,7 +33,6 @@ using System.Reflection; using Nini.Config; using OpenSim.Framework; using OpenSim.Framework.Communications; -using OpenSim.Framework.Servers.HttpServer; using OpenSim.Services.Interfaces; using OpenSim.Server.Base; using OpenMetaverse; diff --git a/OpenSim/Services/Connectors/Authorization/AuthorizationServiceConnector.cs b/OpenSim/Services/Connectors/Authorization/AuthorizationServiceConnector.cs index 4eb4bd2470..35b7109496 100644 --- a/OpenSim/Services/Connectors/Authorization/AuthorizationServiceConnector.cs +++ b/OpenSim/Services/Connectors/Authorization/AuthorizationServiceConnector.cs @@ -33,7 +33,6 @@ using System.Reflection; using Nini.Config; using OpenSim.Framework; using OpenSim.Framework.Communications; -using OpenSim.Framework.Servers.HttpServer; using OpenSim.Services.Interfaces; using OpenMetaverse; diff --git a/OpenSim/Services/Connectors/Avatar/AvatarServiceConnector.cs b/OpenSim/Services/Connectors/Avatar/AvatarServiceConnector.cs index 1cd6bf8e1a..1a93ae71c6 100644 --- a/OpenSim/Services/Connectors/Avatar/AvatarServiceConnector.cs +++ b/OpenSim/Services/Connectors/Avatar/AvatarServiceConnector.cs @@ -33,7 +33,6 @@ using System.Reflection; using Nini.Config; using OpenSim.Framework; using OpenSim.Framework.Communications; -using OpenSim.Framework.Servers.HttpServer; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using IAvatarService = OpenSim.Services.Interfaces.IAvatarService; diff --git a/OpenSim/Services/Connectors/Freeswitch/RemoteFreeswitchConnector.cs b/OpenSim/Services/Connectors/Freeswitch/RemoteFreeswitchConnector.cs index c9bba0b730..d68829996d 100644 --- a/OpenSim/Services/Connectors/Freeswitch/RemoteFreeswitchConnector.cs +++ b/OpenSim/Services/Connectors/Freeswitch/RemoteFreeswitchConnector.cs @@ -33,7 +33,6 @@ using System.Reflection; using Nini.Config; using OpenSim.Framework; using OpenSim.Framework.Communications; -using OpenSim.Framework.Servers.HttpServer; using OpenSim.Services.Interfaces; using OpenSim.Server.Base; using OpenMetaverse; diff --git a/OpenSim/Services/Connectors/Friends/FriendsServiceConnector.cs b/OpenSim/Services/Connectors/Friends/FriendsServiceConnector.cs index 36b5083860..861c4759a3 100644 --- a/OpenSim/Services/Connectors/Friends/FriendsServiceConnector.cs +++ b/OpenSim/Services/Connectors/Friends/FriendsServiceConnector.cs @@ -33,7 +33,6 @@ using System.Reflection; using Nini.Config; using OpenSim.Framework; using OpenSim.Framework.Communications; -using OpenSim.Framework.Servers.HttpServer; using OpenSim.Services.Interfaces; using FriendInfo = OpenSim.Services.Interfaces.FriendInfo; using OpenSim.Server.Base; diff --git a/OpenSim/Services/Connectors/Friends/FriendsSimConnector.cs b/OpenSim/Services/Connectors/Friends/FriendsSimConnector.cs index 0a7b277e4c..4ffa68c381 100644 --- a/OpenSim/Services/Connectors/Friends/FriendsSimConnector.cs +++ b/OpenSim/Services/Connectors/Friends/FriendsSimConnector.cs @@ -32,7 +32,7 @@ using System.Reflection; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenSim.Server.Base; -using OpenSim.Framework.Servers.HttpServer; +using OpenSim.Framework; using OpenMetaverse; using log4net; diff --git a/OpenSim/Services/Connectors/Grid/GridServiceConnector.cs b/OpenSim/Services/Connectors/Grid/GridServiceConnector.cs index 5092d741e6..e57f28b44e 100644 --- a/OpenSim/Services/Connectors/Grid/GridServiceConnector.cs +++ b/OpenSim/Services/Connectors/Grid/GridServiceConnector.cs @@ -33,7 +33,6 @@ using System.Reflection; using Nini.Config; using OpenSim.Framework; using OpenSim.Framework.Communications; -using OpenSim.Framework.Servers.HttpServer; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenSim.Server.Base; diff --git a/OpenSim/Services/Connectors/GridUser/GridUserServiceConnector.cs b/OpenSim/Services/Connectors/GridUser/GridUserServiceConnector.cs index b3ea865996..738cc06949 100644 --- a/OpenSim/Services/Connectors/GridUser/GridUserServiceConnector.cs +++ b/OpenSim/Services/Connectors/GridUser/GridUserServiceConnector.cs @@ -33,7 +33,6 @@ using System.Reflection; using Nini.Config; using OpenSim.Framework; using OpenSim.Framework.Communications; -using OpenSim.Framework.Servers.HttpServer; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenSim.Server.Base; diff --git a/OpenSim/Services/Connectors/Inventory/XInventoryConnector.cs b/OpenSim/Services/Connectors/Inventory/XInventoryConnector.cs index b3bfcc27df..cd9f2bfcff 100644 --- a/OpenSim/Services/Connectors/Inventory/XInventoryConnector.cs +++ b/OpenSim/Services/Connectors/Inventory/XInventoryConnector.cs @@ -34,7 +34,6 @@ using Nini.Config; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.Communications; -using OpenSim.Framework.Servers.HttpServer; using OpenSim.Services.Interfaces; using OpenSim.Server.Base; using OpenMetaverse; diff --git a/OpenSim/Services/Connectors/Land/LandServiceConnector.cs b/OpenSim/Services/Connectors/Land/LandServiceConnector.cs index 252f7a1d16..30a73a471c 100644 --- a/OpenSim/Services/Connectors/Land/LandServiceConnector.cs +++ b/OpenSim/Services/Connectors/Land/LandServiceConnector.cs @@ -34,7 +34,6 @@ using System.Reflection; using Nini.Config; using OpenSim.Framework; using OpenSim.Framework.Communications; -using OpenSim.Framework.Servers.HttpServer; using OpenSim.Services.Interfaces; using OpenMetaverse; using Nwc.XmlRpc; diff --git a/OpenSim/Services/Connectors/Neighbour/NeighbourServiceConnector.cs b/OpenSim/Services/Connectors/Neighbour/NeighbourServiceConnector.cs index 9e444c49bc..2cae02d42a 100644 --- a/OpenSim/Services/Connectors/Neighbour/NeighbourServiceConnector.cs +++ b/OpenSim/Services/Connectors/Neighbour/NeighbourServiceConnector.cs @@ -36,7 +36,6 @@ using System.Text; using Nini.Config; using OpenSim.Framework; using OpenSim.Framework.Communications; -using OpenSim.Framework.Servers.HttpServer; using OpenSim.Services.Interfaces; using OpenMetaverse; using OpenMetaverse.StructuredData; diff --git a/OpenSim/Services/Connectors/Presence/PresenceServiceConnector.cs b/OpenSim/Services/Connectors/Presence/PresenceServiceConnector.cs index 41ebeaf05e..7238afc613 100644 --- a/OpenSim/Services/Connectors/Presence/PresenceServiceConnector.cs +++ b/OpenSim/Services/Connectors/Presence/PresenceServiceConnector.cs @@ -33,7 +33,6 @@ using System.Reflection; using Nini.Config; using OpenSim.Framework; using OpenSim.Framework.Communications; -using OpenSim.Framework.Servers.HttpServer; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenSim.Server.Base; diff --git a/OpenSim/Services/Connectors/Simulation/EstateDataService.cs b/OpenSim/Services/Connectors/Simulation/EstateDataService.cs index d0588bff09..7184ba188e 100644 --- a/OpenSim/Services/Connectors/Simulation/EstateDataService.cs +++ b/OpenSim/Services/Connectors/Simulation/EstateDataService.cs @@ -111,6 +111,11 @@ namespace OpenSim.Services.Connectors return m_database.GetEstatesAll(); } + public List GetEstatesByOwner(UUID ownerID) + { + return m_database.GetEstatesByOwner(ownerID); + } + public bool LinkRegion(UUID regionID, int estateID) { return m_database.LinkRegion(regionID, estateID); diff --git a/OpenSim/Services/Connectors/UserAccounts/UserAccountServiceConnector.cs b/OpenSim/Services/Connectors/UserAccounts/UserAccountServiceConnector.cs index 2a5df83193..f6835b9f2f 100644 --- a/OpenSim/Services/Connectors/UserAccounts/UserAccountServiceConnector.cs +++ b/OpenSim/Services/Connectors/UserAccounts/UserAccountServiceConnector.cs @@ -33,7 +33,6 @@ using System.Reflection; using Nini.Config; using OpenSim.Framework; using OpenSim.Framework.Communications; -using OpenSim.Framework.Servers.HttpServer; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenMetaverse; diff --git a/OpenSim/Services/Interfaces/IAssetService.cs b/OpenSim/Services/Interfaces/IAssetService.cs index 3be6815728..1ac1cec358 100644 --- a/OpenSim/Services/Interfaces/IAssetService.cs +++ b/OpenSim/Services/Interfaces/IAssetService.cs @@ -48,6 +48,11 @@ namespace OpenSim.Services.Interfaces /// AssetMetadata GetMetadata(string id); + /// + /// Get an asset's data, ignoring the metadata. + /// + /// + /// null if there is no such asset byte[] GetData(string id); /// diff --git a/OpenSim/Services/Interfaces/IInventoryService.cs b/OpenSim/Services/Interfaces/IInventoryService.cs index d19faeddf7..a8bfe479a7 100644 --- a/OpenSim/Services/Interfaces/IInventoryService.cs +++ b/OpenSim/Services/Interfaces/IInventoryService.cs @@ -169,7 +169,7 @@ namespace OpenSim.Services.Interfaces /// Get an item, given by its UUID /// /// - /// + /// null if no item was found, otherwise the found item InventoryItemBase GetItem(InventoryItemBase item); /// diff --git a/OpenSim/Tests/Common/Mock/MockAssetService.cs b/OpenSim/Tests/Common/Mock/MockAssetService.cs deleted file mode 100644 index 4118308bed..0000000000 --- a/OpenSim/Tests/Common/Mock/MockAssetService.cs +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using System.Reflection; -using log4net; -using OpenMetaverse; -using OpenSim.Framework; -using OpenSim.Data; -using OpenSim.Services.Interfaces; -using Nini.Config; - -namespace OpenSim.Tests.Common.Mock -{ - public class MockAssetService : IAssetService - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private readonly Dictionary Assets = new Dictionary(); - - public MockAssetService() {} - - /// - /// This constructor is required if the asset service is being created reflectively (which is the case in some - /// tests). - /// - /// - public MockAssetService(IConfigSource config) {} - - public AssetBase Get(string id) - { - m_log.DebugFormat("[MOCK ASSET SERVICE]: Getting asset with id {0}", id); - - AssetBase asset; - if (Assets.ContainsKey(id)) - asset = Assets[id]; - else - asset = null; - - return asset; - } - - public AssetBase GetCached(string id) - { - return Get(id); - } - - public AssetMetadata GetMetadata(string id) - { - throw new System.NotImplementedException(); - } - - public byte[] GetData(string id) - { - throw new System.NotImplementedException(); - } - - public bool Get(string id, object sender, AssetRetrieved handler) - { - handler(id, sender, Get(id)); - - return true; - } - - public string Store(AssetBase asset) - { - m_log.DebugFormat("[MOCK ASSET SERVICE]: Storing asset {0}", asset.ID); - - Assets[asset.ID] = asset; - - return asset.ID; - } - - public bool UpdateContent(string id, byte[] data) - { - throw new System.NotImplementedException(); - } - - public bool Delete(string id) - { - throw new System.NotImplementedException(); - } - } -} \ No newline at end of file diff --git a/OpenSim/Tests/Common/Mock/MockInventoryService.cs b/OpenSim/Tests/Common/Mock/MockInventoryService.cs deleted file mode 100644 index 4ac1078795..0000000000 --- a/OpenSim/Tests/Common/Mock/MockInventoryService.cs +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using System.Text; -using OpenSim.Framework; -using OpenMetaverse; -using OpenSim.Services.Interfaces; -using Nini.Config; - -namespace OpenSim.Tests.Common.Mock -{ - public class MockInventoryService : IInventoryService - { - public MockInventoryService() {} - - public MockInventoryService(IConfigSource config) {} - - /// - /// - /// - /// - /// - public bool CreateUserInventory(UUID userId) - { - return false; - } - - /// - /// - /// - /// - /// - public List GetInventorySkeleton(UUID userId) - { - List folders = new List(); - InventoryFolderBase folder = new InventoryFolderBase(); - folder.ID = UUID.Random(); - folder.Owner = userId; - folders.Add(folder); - return folders; - } - - public InventoryFolderBase GetRootFolder(UUID userID) - { - return new InventoryFolderBase(); - } - - public InventoryCollection GetFolderContent(UUID userID, UUID folderID) - { - return null; - } - - public InventoryFolderBase GetFolderForType(UUID userID, AssetType type) - { - return null; - } - - /// - /// Returns a list of all the active gestures in a user's inventory. - /// - /// - /// The of the user - /// - /// - /// A flat list of the gesture items. - /// - public List GetActiveGestures(UUID userId) - { - return null; - } - - public InventoryCollection GetUserInventory(UUID userID) - { - return null; - } - - public void GetUserInventory(UUID userID, OpenSim.Services.Interfaces.InventoryReceiptCallback callback) - { - } - - public List GetFolderItems(UUID userID, UUID folderID) - { - return null; - } - - public bool AddFolder(InventoryFolderBase folder) - { - return false; - } - - public bool UpdateFolder(InventoryFolderBase folder) - { - return false; - } - - public bool MoveFolder(InventoryFolderBase folder) - { - return false; - } - - public bool DeleteFolders(UUID ownerID, List ids) - { - return false; - } - - public bool PurgeFolder(InventoryFolderBase folder) - { - return false; - } - - public bool AddItem(InventoryItemBase item) - { - return true; - } - - public bool UpdateItem(InventoryItemBase item) - { - return false; - } - - public bool MoveItems(UUID ownerID, List items) - { - return false; - } - - public bool DeleteItems(UUID ownerID, List itemIDs) - { - return false; - } - - public InventoryItemBase GetItem(InventoryItemBase item) - { - return null; - } - - public InventoryFolderBase GetFolder(InventoryFolderBase folder) - { - return null; - } - - public bool HasInventoryForUser(UUID userID) - { - return false; - } - - public InventoryFolderBase RequestRootFolder(UUID userID) - { - InventoryFolderBase root = new InventoryFolderBase(); - root.ID = UUID.Random(); - root.Owner = userID; - root.ParentID = UUID.Zero; - return root; - } - - public int GetAssetPermissions(UUID userID, UUID assetID) - { - return 1; - } - } -} \ No newline at end of file diff --git a/OpenSim/Tests/Common/Mock/TestClient.cs b/OpenSim/Tests/Common/Mock/TestClient.cs index d1dc17fc9b..dca562674b 100644 --- a/OpenSim/Tests/Common/Mock/TestClient.cs +++ b/OpenSim/Tests/Common/Mock/TestClient.cs @@ -816,18 +816,11 @@ namespace OpenSim.Tests.Common.Mock { } - public void SendObjectPropertiesFamilyData(uint RequestFlags, UUID ObjectUUID, UUID OwnerID, UUID GroupID, - uint BaseMask, uint OwnerMask, uint GroupMask, uint EveryoneMask, - uint NextOwnerMask, int OwnershipCost, byte SaleType,int SalePrice, uint Category, - UUID LastOwnerID, string ObjectName, string Description) + public void SendObjectPropertiesFamilyData(ISceneEntity Entity, uint RequestFlags) { } - public void SendObjectPropertiesReply(UUID ItemID, ulong CreationDate, UUID CreatorUUID, UUID FolderUUID, UUID FromTaskUUID, - UUID GroupUUID, short InventorySerial, UUID LastOwnerUUID, UUID ObjectUUID, - UUID OwnerUUID, string TouchTitle, byte[] TextureID, string SitTitle, string ItemName, - string ItemDescription, uint OwnerMask, uint NextOwnerMask, uint GroupMask, uint EveryoneMask, - uint BaseMask, byte saleType, int salePrice) + public void SendObjectPropertiesReply(ISceneEntity entity) { } diff --git a/OpenSim/Tests/Common/Setup/AssetHelpers.cs b/OpenSim/Tests/Common/Setup/AssetHelpers.cs index ff4423f7ab..d572249997 100644 --- a/OpenSim/Tests/Common/Setup/AssetHelpers.cs +++ b/OpenSim/Tests/Common/Setup/AssetHelpers.cs @@ -30,6 +30,7 @@ using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes.Serialization; +using OpenSim.Services.Interfaces; namespace OpenSim.Tests.Common { @@ -55,7 +56,7 @@ namespace OpenSim.Tests.Common AssetBase asset = CreateAsset(UUID.Random(), AssetType.Notecard, "hello", creatorId); scene.AssetService.Store(asset); return asset; - } + } /// /// Create an asset from the given scene object. @@ -71,6 +72,35 @@ namespace OpenSim.Tests.Common Encoding.ASCII.GetBytes(SceneObjectSerializer.ToOriginalXmlFormat(sog)), sog.OwnerID); } + + /// + /// Create an asset from the given scene object. + /// + /// + /// The hexadecimal last part of the UUID for the asset created. A UUID of the form "00000000-0000-0000-0000-{0:XD12}" + /// will be used. + /// + /// + /// + public static AssetBase CreateAsset(int assetUuidTail, CoalescedSceneObjects coa) + { + return CreateAsset(new UUID(string.Format("00000000-0000-0000-0000-{0:X12}", assetUuidTail)), coa); + } + + /// + /// Create an asset from the given scene object. + /// + /// + /// + /// + public static AssetBase CreateAsset(UUID assetUuid, CoalescedSceneObjects coa) + { + return CreateAsset( + assetUuid, + AssetType.Object, + Encoding.ASCII.GetBytes(CoalescedSceneObjectsSerializer.ToXml(coa)), + coa.CreatorId); + } /// /// Create an asset from the given data. @@ -89,5 +119,11 @@ namespace OpenSim.Tests.Common asset.Data = data; return asset; } + + public static string ReadAssetAsString(IAssetService assetService, UUID uuid) + { + byte[] assetData = assetService.GetData(uuid.ToString()); + return Encoding.ASCII.GetString(assetData); + } } } diff --git a/OpenSim/Tests/Common/Setup/SceneSetupHelpers.cs b/OpenSim/Tests/Common/Setup/SceneSetupHelpers.cs index 57850c1cc7..99517d2b19 100644 --- a/OpenSim/Tests/Common/Setup/SceneSetupHelpers.cs +++ b/OpenSim/Tests/Common/Setup/SceneSetupHelpers.cs @@ -66,32 +66,7 @@ namespace OpenSim.Tests.Common.Setup /// public static TestScene SetupScene() { - return SetupScene(""); - } - - /// - /// Set up a test scene - /// - /// - /// Starts real inventory and asset services, as opposed to mock ones, if true - /// - public static TestScene SetupScene(String realServices) - { - return SetupScene("Unit test region", UUID.Random(), 1000, 1000, realServices); - } - - /// - /// Set up a test scene - /// - /// Name of the region - /// ID of the region - /// X co-ordinate of the region - /// Y co-ordinate of the region - /// This should be the same if simulating two scenes within a standalone - /// - public static TestScene SetupScene(string name, UUID id, uint x, uint y) - { - return SetupScene(name, id, x, y, ""); + return SetupScene("Unit test region", UUID.Random(), 1000, 1000); } /// @@ -103,10 +78,8 @@ namespace OpenSim.Tests.Common.Setup /// X co-ordinate of the region /// Y co-ordinate of the region /// This should be the same if simulating two scenes within a standalone - /// Starts real inventory and asset services, as opposed to mock ones, if true /// - public static TestScene SetupScene( - string name, UUID id, uint x, uint y, String realServices) + public static TestScene SetupScene(string name, UUID id, uint x, uint y) { Console.WriteLine("Setting up test scene {0}", name); @@ -130,15 +103,11 @@ namespace OpenSim.Tests.Common.Setup IRegionModule godsModule = new GodsModule(); godsModule.Initialise(testScene, new IniConfigSource()); testScene.AddModule(godsModule.Name, godsModule); - realServices = realServices.ToLower(); - LocalAssetServicesConnector assetService = StartAssetService(testScene, realServices.Contains("asset")); - - // For now, always started a 'real' authentication service - StartAuthenticationService(testScene, true); - - LocalInventoryServicesConnector inventoryService = StartInventoryService(testScene, realServices.Contains("inventory")); - StartGridService(testScene, true); + LocalAssetServicesConnector assetService = StartAssetService(testScene); + StartAuthenticationService(testScene); + LocalInventoryServicesConnector inventoryService = StartInventoryService(testScene); + StartGridService(testScene); LocalUserAccountServicesConnector userAccountService = StartUserAccountService(testScene); LocalPresenceServicesConnector presenceService = StartPresenceService(testScene); @@ -164,18 +133,17 @@ namespace OpenSim.Tests.Common.Setup return testScene; } - private static LocalAssetServicesConnector StartAssetService(Scene testScene, bool real) + private static LocalAssetServicesConnector StartAssetService(Scene testScene) { LocalAssetServicesConnector assetService = new LocalAssetServicesConnector(); IConfigSource config = new IniConfigSource(); - config.AddConfig("Modules"); + + config.AddConfig("Modules"); + config.Configs["Modules"].Set("AssetServices", "LocalAssetServicesConnector"); config.AddConfig("AssetService"); - config.Configs["Modules"].Set("AssetServices", "LocalAssetServicesConnector"); - if (real) - config.Configs["AssetService"].Set("LocalServiceModule", "OpenSim.Services.AssetService.dll:AssetService"); - else - config.Configs["AssetService"].Set("LocalServiceModule", "OpenSim.Tests.Common.dll:MockAssetService"); + config.Configs["AssetService"].Set("LocalServiceModule", "OpenSim.Services.AssetService.dll:AssetService"); config.Configs["AssetService"].Set("StorageProvider", "OpenSim.Tests.Common.dll"); + assetService.Initialise(config); assetService.AddRegion(testScene); assetService.RegionLoaded(testScene); @@ -184,20 +152,18 @@ namespace OpenSim.Tests.Common.Setup return assetService; } - private static void StartAuthenticationService(Scene testScene, bool real) + private static void StartAuthenticationService(Scene testScene) { ISharedRegionModule service = new LocalAuthenticationServicesConnector(); IConfigSource config = new IniConfigSource(); + config.AddConfig("Modules"); config.AddConfig("AuthenticationService"); config.Configs["Modules"].Set("AuthenticationServices", "LocalAuthenticationServicesConnector"); - if (real) - config.Configs["AuthenticationService"].Set( - "LocalServiceModule", "OpenSim.Services.AuthenticationService.dll:PasswordAuthenticationService"); - else - config.Configs["AuthenticationService"].Set( - "LocalServiceModule", "OpenSim.Tests.Common.dll:MockAuthenticationService"); + config.Configs["AuthenticationService"].Set( + "LocalServiceModule", "OpenSim.Services.AuthenticationService.dll:PasswordAuthenticationService"); config.Configs["AuthenticationService"].Set("StorageProvider", "OpenSim.Data.Null.dll"); + service.Initialise(config); service.AddRegion(testScene); service.RegionLoaded(testScene); @@ -205,24 +171,17 @@ namespace OpenSim.Tests.Common.Setup //m_authenticationService = service; } - private static LocalInventoryServicesConnector StartInventoryService(Scene testScene, bool real) + private static LocalInventoryServicesConnector StartInventoryService(Scene testScene) { LocalInventoryServicesConnector inventoryService = new LocalInventoryServicesConnector(); - IConfigSource config = new IniConfigSource(); + + IConfigSource config = new IniConfigSource(); config.AddConfig("Modules"); config.AddConfig("InventoryService"); config.Configs["Modules"].Set("InventoryServices", "LocalInventoryServicesConnector"); - - if (real) - { - config.Configs["InventoryService"].Set("LocalServiceModule", "OpenSim.Services.InventoryService.dll:InventoryService"); - } - else - { - config.Configs["InventoryService"].Set("LocalServiceModule", "OpenSim.Tests.Common.dll:MockInventoryService"); - } - + config.Configs["InventoryService"].Set("LocalServiceModule", "OpenSim.Services.InventoryService.dll:InventoryService"); config.Configs["InventoryService"].Set("StorageProvider", "OpenSim.Tests.Common.dll"); + inventoryService.Initialise(config); inventoryService.AddRegion(testScene); inventoryService.RegionLoaded(testScene); @@ -231,24 +190,19 @@ namespace OpenSim.Tests.Common.Setup return inventoryService; } - private static LocalGridServicesConnector StartGridService(Scene testScene, bool real) + private static LocalGridServicesConnector StartGridService(Scene testScene) { IConfigSource config = new IniConfigSource(); config.AddConfig("Modules"); config.AddConfig("GridService"); config.Configs["Modules"].Set("GridServices", "LocalGridServicesConnector"); config.Configs["GridService"].Set("StorageProvider", "OpenSim.Data.Null.dll:NullRegionData"); - if (real) - config.Configs["GridService"].Set("LocalServiceModule", "OpenSim.Services.GridService.dll:GridService"); + config.Configs["GridService"].Set("LocalServiceModule", "OpenSim.Services.GridService.dll:GridService"); LocalGridServicesConnector gridService = new LocalGridServicesConnector(); gridService.Initialise(config); - - //else - // config.Configs["GridService"].Set("LocalServiceModule", "OpenSim.Tests.Common.dll:TestGridService"); gridService.AddRegion(testScene); gridService.RegionLoaded(testScene); - //testScene.AddRegionModule(m_gridService.Name, m_gridService); return gridService; } @@ -472,10 +426,10 @@ namespace OpenSim.Tests.Common.Setup /// /// public static SceneObjectPart CreateSceneObjectPart(string name, UUID id, UUID ownerId) - { + { return new SceneObjectPart( ownerId, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero) - { Name = name, UUID = id }; + { Name = name, UUID = id, Scale = new Vector3(1, 1, 1) }; } /// @@ -489,32 +443,38 @@ namespace OpenSim.Tests.Common.Setup /// public static SceneObjectGroup CreateSceneObject(int parts, UUID ownerId) { - return CreateSceneObject(parts, ownerId, 0x1); + return CreateSceneObject(parts, ownerId, "", 0x1); } /// /// Create a scene object but do not add it to the scene. /// - /// The number of parts that should be in the scene object + /// + /// The number of parts that should be in the scene object + /// /// + /// + /// The prefix to be given to part names. This will be suffixed with "Part" + /// (e.g. mynamePart0 for the root part) + /// /// /// The hexadecimal last part of the UUID for parts created. A UUID of the form "00000000-0000-0000-0000-{0:XD12}" /// will be given to the root part, and incremented for each part thereafter. /// /// - public static SceneObjectGroup CreateSceneObject(int parts, UUID ownerId, int uuidTail) + public static SceneObjectGroup CreateSceneObject(int parts, UUID ownerId, string partNamePrefix, int uuidTail) { string rawSogId = string.Format("00000000-0000-0000-0000-{0:X12}", uuidTail); SceneObjectGroup sog = new SceneObjectGroup( - CreateSceneObjectPart("part0", new UUID(rawSogId), ownerId)); + CreateSceneObjectPart(string.Format("{0}Part0", partNamePrefix), new UUID(rawSogId), ownerId)); if (parts > 1) for (int i = 1; i < parts; i++) sog.AddPart( CreateSceneObjectPart( - string.Format("obj{0}", i), + string.Format("{0}Part{1}", partNamePrefix, i), new UUID(string.Format("00000000-0000-0000-0000-{0:X12}", uuidTail + i)), ownerId)); diff --git a/bin/Mono.Data.Sqlite.dll.config b/bin/Mono.Data.Sqlite.dll.config index 6a95476537..ccc0cf59d8 100644 --- a/bin/Mono.Data.Sqlite.dll.config +++ b/bin/Mono.Data.Sqlite.dll.config @@ -1,4 +1,5 @@ + diff --git a/bin/OpenSim.ini.example b/bin/OpenSim.ini.example index 5bac56e66a..c05c3de2c4 100644 --- a/bin/OpenSim.ini.example +++ b/bin/OpenSim.ini.example @@ -1,4 +1,22 @@ -;; A note on the format of this file +;; This is the main configuration file for OpenSimulator. If it's named OpenSim.ini +;; then it will be loaded by OpenSimulator. If it's named OpenSim.ini.example then +;; you will need to copy it to OpenSim.ini first (if that file does not already exist) +;; +;; If you are copying, then once you have copied OpenSim.ini.example to OpenSim.ini you will +;; need to pick an architecture in the [Architecture] section at the end of this file. +;; +;; The settings in this file are in the form " = ". For example, save_crashes = false +;; in the [Startup] section below. +;; +;; All settings are initially commented out and the default value used, as found in +;; OpenSimDefaults.ini. To change a setting, first uncomment it by deleting the initial semicolon (;) +;; and then change the value. This will override the value in OpenSimDefaults.ini +;; +;; If you want to find out what configuration OpenSimulator has finished with once all the configuration +;; files are loaded then type "config show" on the region console command line. +;; +;; +;; NOTES FOR DEVELOPERS REGARDING THE FORMAT OF THIS FILE ;; ;; All leading white space is ignored, but preserved. ;; @@ -8,15 +26,14 @@ ;; formatted as: ;; {option} {depends on} {question to ask} {choices} default value ;; Any text comments following the declaration, up to the next blank line. -;; will be copied to the generated file. -;; A * in the choices list will allow an empty entry.\ +;; will be copied to the generated file (NOTE: generation is not yet implemented) +;; A * in the choices list will allow an empty entry. ;; An empty question will set the default if the dependencies are ;; satisfied. ;; -;; ; denotes a commented out option. Uncomment it to actvate it -;; and change it to the desired value -;; Any options added to OpenSim.ini.exmaple must be commented out, -;; and their value must represent the default. +;; ; denotes a commented out option. +;; Any options added to OpenSim.ini.example should be initially commented out. + [Startup] ;# {save_crashes} {} {Save crashes to disk?} {true false} false @@ -35,7 +52,7 @@ ;; Determine where OpenSimulator looks for the files which tell it ;; which regions to server - ;; Defaults to "filesystem" if this setting isn't present + ;; Default is "filesystem" ; region_info_source = "filesystem" ; region_info_source = "web" @@ -131,6 +148,7 @@ ;; ZeroMesher is faster but leaves the physics engine to model the mesh ;; using the basic shapes that it supports. ;; Usually this is only a box. + ;; Default is Meshmerizer ; meshing = Meshmerizer ; meshing = ZeroMesher @@ -138,6 +156,7 @@ ;; OpenDynamicsEngine is by some distance the most developed physics engine ;; basicphysics effectively does not model physics at all, making all ;; objects phantom + ;; Default is OpenDynamicsEngine ; physics = OpenDynamicsEngine ; physics = basicphysics ; physics = POS @@ -154,7 +173,6 @@ ;; permission checks (allowing anybody to copy ;; any item, etc. This may not yet be implemented uniformally. ;; If set to true, then all permissions checks are carried out - ;; Default is false ; serverside_object_permissions = false ;; This allows users with a UserLevel of 200 or more to assume god @@ -183,11 +201,20 @@ ;; If not generating maptiles, use this static texture asset ID ; MaptileStaticUUID = "00000000-0000-0000-0000-000000000000" + ;; Http proxy setting for llHTTPRequest and dynamic texture loading, if required + ; HttpProxy = "http://proxy.com:8080" + + ;; If you're using HttpProxy, then you can set HttpProxyExceptions to a list of regular expressions for URLs that you don't want to go through the proxy + ;; For example, servers inside your firewall. + ;; Separate patterns with a ';' + ; HttpProxyExceptions = ".mydomain.com;localhost" + ;# {emailmodule} {} {Provide llEmail and llGetNextEmail functionality? (requires SMTP server)} {true false} false ;; The email module requires some configuration. It needs an SMTP ;; server to send mail through. ; emailmodule = DefaultEmailModule + [SMTP] ;; The SMTP server enabled the email module to send email to external ;; destinations. @@ -214,6 +241,7 @@ ;# {SMTP_SERVER_PASSWORD} {[Startup]emailmodule:DefaultEmailModule enabled:true} {SMTP server password} {} ; SMTP_SERVER_PASSWORD = "" + [Network] ;; Configure the remote console user here. This will not actually be used ;; unless you use -console=rest at startup. @@ -247,6 +275,7 @@ ;; " (Mozilla Compatible)" to the text where there are problems with a web server ; user_agent = "OpenSim LSL (Mozilla Compatible)" + [ClientStack.LindenUDP] ;; See OpensSimDefaults.ini for the throttle options. You can copy the ;; relevant sections and override them here. @@ -263,17 +292,18 @@ ;; building's lights to possibly not be rendered. ; DisableFacelights = "false" + [Chat] ;# {whisper_distance} {} {Distance at which a whisper is heard, in meters?} {} 10 - ;; Distance in meters that whispers should travel. Default is 10m + ;; Distance in meters that whispers should travel. ; whisper_distance = 10 ;# {say_distance} {} {Distance at which normal chat is heard, in meters? (SL uses 20 here)} {} 30 - ;; Distance in meters that ordinary chat should travel. Default is 30m + ;; Distance in meters that ordinary chat should travel. ; say_distance = 30 ;# {shout_distance} {Distance at which a shout is heard, in meters?} {} 100 - ;; Distance in meters that shouts should travel. Default is 100m + ;; Distance in meters that shouts should travel. ; shout_distance = 100 @@ -337,13 +367,13 @@ ;# {create_region_enable_voice} {enabled:true} {Enable voice for newly created regions?} {true false} false ;; set this variable to true if you want the create_region XmlRpc ;; call to unconditionally enable voice on all parcels for a newly - ;; created region [default: false] + ;; created region ; create_region_enable_voice = false ;# {create_region_public} {enabled:true} {Make newly created regions public?} {true false} false ;; set this variable to false if you want the create_region XmlRpc ;; call to create all regions as private per default (can be - ;; overridden in the XmlRpc call) [default: true] + ;; overridden in the XmlRpc call) ; create_region_public = false ;# {enabled_methods} {enabled:true} {List of methods to allow, separated by |} {} all @@ -372,15 +402,16 @@ ;; default avatars ; default_appearance = default_appearance.xml + [Wind] ;# {enabled} {} {Enable wind module?} {true false} true - ;; Enables the wind module. Default is true - ;enabled = true + ;; Enables the wind module. + ; enabled = true ;# {wind_update_rate} {enabled:true} {Wind update rate in frames?} {} 150 ;; How often should wind be updated, as a function of world frames. ;; Approximately 50 frames a second - wind_update_rate = 150 + ; wind_update_rate = 150 ;; The Default Wind Plugin to load ; wind_plugin = SimpleRandomWind @@ -396,9 +427,10 @@ ;# {strength} {enabled:true wind_plugin:SimpleRandomWind} {Wind strength?} {} 1.0 ;; This setting is specific to the SimpleRandomWind plugin - ;; Adjusts wind strength. 0.0 = no wind, 1.0 = normal wind. Default is 1.0 + ;; Adjusts wind strength. 0.0 = no wind, 1.0 = normal wind. ; strength = 1.0 + [LightShare] ;# {enable_windlight} {} {Enable LightShare technology?} {true false} false ;; This enables the transmission of Windlight scenes to supporting clients, @@ -406,7 +438,8 @@ ;; It has no ill effect on viewers which do not support server-side ;; windlight settings. ;; Currently we only have support for MySQL databases. - ; enable_windlight = false; + ; enable_windlight = false + [DataSnapshot] ;# {index_sims} {} {Enable data snapshotting (search)?} {true false} false @@ -417,7 +450,6 @@ ;; and you can ignore the rest of these search-related configs. ; index_sims = false - ;# {data_exposure} {index_sims:true} {How much data should be exposed?} {minimum all} minimum ;; The variable data_exposure controls what the regions expose: ;; minimum: exposes only things explicitly marked for search @@ -462,6 +494,7 @@ ;; Money Unit fee to create groups ; PriceGroupCreate = 0 + [XEngine] ;# {Enabled} {} {Enable the XEngine scripting engine?} {true false} true ;; Enable this engine in this OpenSim instance @@ -556,9 +589,9 @@ ;; Default is ./bin/ScriptEngines ; ScriptEnginesPath = "ScriptEngines" + [MRM] ;; Enables the Mini Region Modules Script Engine. - ;; default is false ; Enabled = false ;; Runs MRM in a Security Sandbox @@ -580,6 +613,7 @@ ;; May represent a security risk if you disable this. ; OwnerOnly = true + [FreeSwitchVoice] ;; In order for this to work you need a functioning FreeSWITCH PBX set up. ;; Configuration details at http://opensimulator.org/wiki/Freeswitch_Module @@ -593,6 +627,7 @@ ;; If using a remote module, specify the server URL ; FreeswitchServiceURL = http://my.grid.server:8003/fsapi + [FreeswitchService] ;; !!!!!!!!!!!!!!!!!!!!!!!!!!! ;; !!!!!!STANDALONE ONLY!!!!!! @@ -611,6 +646,7 @@ ; UserName = "freeswitch" ; Password = "password" + [Groups] ;# {Enabled} {} {Enable groups?} {true false} false ;; Enables the groups module @@ -634,7 +670,7 @@ ;# {ServicesConnectorModule} {Module:GroupsModule} {Service connector to use for groups} {XmlRpcGroupsServicesConnector SimianGroupsServicesConnector} XmlRpcGroupsServicesConnector ;; Service connectors to the Groups Service as used in the GroupsModule. Select one depending on ;; whether you're using a Flotsam XmlRpc backend or a SimianGrid backend - ; ServicesConnectorModule = SimianGroupsServicesConnector + ; ServicesConnectorModule = XmlRpcGroupsServicesConnector ;# {GroupsServerURI} {Module:GroupsModule} {Groups Server URI} {} ;; URI for the groups services @@ -654,6 +690,7 @@ ; XmlRpcServiceReadKey = 1234 ; XmlRpcServiceWriteKey = 1234 + [InterestManagement] ;# {UpdatePrioritizationScheme} {} {Update prioritization scheme?} {BestAvatarResponsiveness Time Distance SimpleAngularDistance FrontBack} BestAvatarResponsiveness ;; This section controls how state updates are prioritized for each client @@ -661,24 +698,28 @@ ;; SimpleAngularDistance, FrontBack ; UpdatePrioritizationScheme = BestAvatarResponsiveness + [MediaOnAPrim] ;# {Enabled} {} {Enable Media-on-a-Prim (MOAP)} {true false} true ;; Enable media on a prim facilities ; Enabled = true; + [Architecture] ;# {Include-Architecture} {} {Choose one of the following architectures} {config-include/Standalone.ini config-include/StandaloneHypergrid.ini config-include/Grid.ini config-include/GridHypergrid.ini config-include/SimianGrid.ini config-include/HyperSimianGrid.ini} config-include/Standalone.ini - ;; Choose one of these architecture includes: - ;; Include-Architecture = "config-include/Standalone.ini" - ;; Include-Architecture = "config-include/StandaloneHypergrid.ini" - ;; Include-Architecture = "config-include/Grid.ini" - ;; Include-Architecture = "config-include/GridHypergrid.ini" - ;; Include-Architecture = "config-include/SimianGrid.ini" - ;; Include-Architecture = "config-include/HyperSimianGrid.ini" + ;; Uncomment one of the following includes as required. For instance, to create a standalone OpenSim, + ;; uncomment Include-Architecture = "config-include/Standalone.ini" + ;; + ;; Then you will need to copy and edit the corresponding *Common.example file in config-include/ + ;; that the referenced .ini file goes on to include. + ;; + ;; For instance, if you chose "config-include/Standalone.ini" then you will need to copy + ;; "config-include/StandaloneCommon.ini.example" to "config-include/StandaloneCommon.ini" before + ;; editing it to set the database and backend services that OpenSim will use. + ;; ; Include-Architecture = "config-include/Standalone.ini" - - ;; Then choose - ;; config-include/StandaloneCommon.ini.example (if you're in standlone) OR - ;; config-include/GridCommon.ini.example (if you're connected to a grid) - ;; Copy to your own .ini there (without .example extension) and edit it - ;; to customize your data + ; Include-Architecture = "config-include/StandaloneHypergrid.ini" + ; Include-Architecture = "config-include/Grid.ini" + ; Include-Architecture = "config-include/GridHypergrid.ini" + ; Include-Architecture = "config-include/SimianGrid.ini" + ; Include-Architecture = "config-include/HyperSimianGrid.ini" diff --git a/bin/OpenSimDefaults.ini b/bin/OpenSimDefaults.ini index 96ffb7ea6b..e72e85103f 100644 --- a/bin/OpenSimDefaults.ini +++ b/bin/OpenSimDefaults.ini @@ -1,3 +1,7 @@ +; This file contains defaults for various settings in OpenSimulator. These can be overriden +; by changing the same setting in OpenSim.ini (once OpenSim.ini.example has been copied to OpenSim.ini). + + [Startup] ; Set this to true if you want to log crashes to disk ; this can be useful when submitting bug reports. @@ -10,15 +14,6 @@ ; Place to create a PID file ; PIDFile = "/tmp/my.pid" - ; Http proxy support for llHTTPRequest and dynamic texture loading - ; Set HttpProxy to the URL for your proxy server if you would like - ; to proxy llHTTPRequests through a firewall - ; HttpProxy = "http://proxy.com" - ; Set HttpProxyExceptions to a list of regular expressions for - ; URLs that you don't want going through the proxy such as servers - ; inside your firewall, separate patterns with a ';' - ; HttpProxyExceptions = ".mydomain.com;localhost" - startup_console_commands_file = "startup_commands.txt" shutdown_console_commands_file = "shutdown_commands.txt" @@ -159,7 +154,7 @@ ; mesh, and use it for collisions. This is currently experimental code and enabling ; it may cause unexpected physics problems. ;UseMeshiesPhysicsMesh = false - + ; Choose one of the physics engines below ; OpenDynamicsEngine is by some distance the most developed physics engine ; basicphysics effectively does not model physics at all, making all objects phantom @@ -287,6 +282,7 @@ ;SMTP_SERVER_LOGIN=foo ;SMTP_SERVER_PASSWORD=bar + [Network] ConsoleUser = "Test" ConsolePass = "secret" @@ -317,6 +313,7 @@ ; " (Mozilla Compatible)" to the text where there are problems with a web server ;user_agent = "OpenSim LSL (Mozilla Compatible)" + [XMLRPC] ; ## ; ## Scripting XMLRPC mapper @@ -330,6 +327,7 @@ ;XmlRpcRouterModule = "XmlRpcRouterModule" ;XmlRpcPort = 20800 + [ClientStack.LindenUDP] ; Set this to true to process incoming packets asynchronously. Networking is ; already separated from packet handling with a queue, so this will only @@ -422,6 +420,7 @@ ; ;DisableFacelights = "false" + [Chat] ; Controls whether the chat module is enabled. Default is true. enabled = true; @@ -450,6 +449,19 @@ ; ForwardOfflineGroupMessages = true +[Inventory] + ; Control whether multiple objects sent to inventory should be coaleseced into a single item + ; There are still some issues with coalescence, including the fact that rotation is not restored + ; and some assets may be missing from archive files. + CoalesceMultipleObjectsToInventory = true + + +[Mesh] + ; enable / disable Collada mesh support + ; default is true + ; ColladaMesh = true + + [ODEPhysicsSettings] ;## ;## World Settings @@ -680,6 +692,7 @@ ; path to default appearance XML file that specifies the look of the default avatars ;default_appearance = default_appearance.xml + [RestPlugins] ; Change this to true to enable REST Plugins. This must be true if you wish to use ; REST Region or REST Asset and Inventory Plugins @@ -706,11 +719,10 @@ flush-on-error = true -; Uncomment the following for IRC bridge -; experimental, so if it breaks... keep both parts... yada yada +; IRC bridge is experimental, so if it breaks... keep both parts... yada yada ; also, not good error detection when it fails -;[IRC] - ;enabled = true ; you need to set this otherwise it won't connect +[IRC] + enabled = false; you need to set this to true otherwise it won't connect ;server = name.of.irc.server.on.the.net ;; user password - only use this if the server requires one ;password = mypass @@ -767,14 +779,14 @@ ;exclude_list=User 1,User 2,User 3 -;[CMS] - ;enabled = true +[CMS] + enabled = false ;channel = 345 -; Uncomment the following to control the progression of daytime -; in the Sim. The defaults are what is shown below -;[Sun] +; The following settings control the progression of daytime +; in the Sim. The defaults are the same as the commented out settings +[Sun] ; number of wall clock hours for an opensim day. 24.0 would mean realtime ;day_length = 4 ; Year length in days @@ -821,12 +833,13 @@ ; default is 1000 cloud_update_rate = 1000 -[LightShare] +[LightShare] ; This enables the transmission of Windlight scenes to supporting clients, such as the Meta7 viewer. ; It has no ill effect on viewers which do not support server-side windlight settings. ; Currently we only have support for MySQL databases. - enable_windlight = false; + enable_windlight = false + [Trees] ; Enable this to allow the tree module to manage your sim trees, including growing, reproducing and dying @@ -838,7 +851,6 @@ [VectorRender] - ; the font to use for rendering text (default: Arial) ; font_name = "Arial" @@ -1032,6 +1044,7 @@ ;; Path to script assemblies ; ScriptEnginesPath = "ScriptEngines" + [OpenGridProtocol] ;These are the settings for the Open Grid Protocol.. the Agent Domain, Region Domain, you know.. ;On/true or Off/false @@ -1240,11 +1253,11 @@ ChildReprioritizationDistance = 20.0 -[WebStats] ; View region statistics via a web page ; See http://opensimulator.org/wiki/FAQ#Region_Statistics_on_a_Web_Page ; Use a web browser and type in the "Login URI" + "/SStats/" ; For example- http://127.0.0.1:9000/SStats/ +[WebStats] ; enabled=false diff --git a/bin/System.Data.SQLite.dll b/bin/System.Data.SQLite.dll deleted file mode 100644 index 66f38e7235..0000000000 Binary files a/bin/System.Data.SQLite.dll and /dev/null differ diff --git a/bin/config-include/GridCommon.ini.example b/bin/config-include/GridCommon.ini.example index a6fe4b1092..bc8bc0fdab 100644 --- a/bin/config-include/GridCommon.ini.example +++ b/bin/config-include/GridCommon.ini.example @@ -6,11 +6,6 @@ ; SQLite Include-Storage = "config-include/storage/SQLiteStandalone.ini"; - ; Unfortunately the current SQLite database plugin is not compatible with Mac OSX. You can still use the older - ; legacy sqlite library if you are using Mono 2.4. Please see the notes in OpenSim.ini (search for sqlite) - ; for more details - ;Include-Storage = "config-include/storage/SQLiteLegacyStandalone.ini"; - ; MySql ; Uncomment these lines if you want to use mysql storage ; Change the connection string to your db details diff --git a/bin/config-include/StandaloneCommon.ini.example b/bin/config-include/StandaloneCommon.ini.example index 995a33e8e1..d6f15bbf3b 100644 --- a/bin/config-include/StandaloneCommon.ini.example +++ b/bin/config-include/StandaloneCommon.ini.example @@ -8,11 +8,6 @@ ; SQLite Include-Storage = "config-include/storage/SQLiteStandalone.ini"; - ; Unfortunately the current SQLite database plugin is not compatible with Mac OSX. You can still use the older - ; legacy sqlite library if you are using Mono 2.4. Please see the notes in OpenSim.ini (search for sqlite) - ; for more details - ;Include-Storage = "config-include/storage/SQLiteLegacyStandalone.ini"; - ; MySql ; Uncomment these lines if you want to use mysql storage ; Change the connection string to your db details diff --git a/bin/config-include/storage/SQLiteLegacyStandalone.ini b/bin/config-include/storage/SQLiteLegacyStandalone.ini deleted file mode 100644 index ffe9a70ca8..0000000000 --- a/bin/config-include/storage/SQLiteLegacyStandalone.ini +++ /dev/null @@ -1,20 +0,0 @@ -; These are the initialization settings for running OpenSim Standalone with an SQLite database - -[DatabaseService] - StorageProvider = "OpenSim.Data.SQLiteLegacy.dll" - ConnectionString = "URI=file:OpenSim.db,version=3,UseUTF16Encoding=True" - -[AssetService] - ConnectionString = "URI=file:Asset.db,version=3" - -[AvatarService] - ConnectionString = "URI=file:avatars.db,version=3" - -[AuthenticationService] - ConnectionString = "URI=file:auth.db,version=3" - -[UserAccountService] - ConnectionString = "URI=file:userprofiles.db,version=3" - -[FriendsService] - ConnectionString = "URI=file:friends.db,version=3" diff --git a/bin/libode.dylib b/bin/libode.dylib index e81f9e4b0b..958d2021fb 100644 Binary files a/bin/libode.dylib and b/bin/libode.dylib differ diff --git a/bin/libsqlite3.dylib b/bin/libsqlite3.dylib new file mode 100755 index 0000000000..94dcca8e10 Binary files /dev/null and b/bin/libsqlite3.dylib differ diff --git a/prebuild.xml b/prebuild.xml index c818908d80..49063daa57 100644 --- a/prebuild.xml +++ b/prebuild.xml @@ -931,7 +931,6 @@ - @@ -2096,44 +2095,6 @@ - - - - ../../../bin/ - - - - - ../../../bin/ - - - - ../../../bin/ - - - - - - - - - - - - - - - - - - - - - - - - - @@ -2927,6 +2888,7 @@ +