From be20f41637b6c06ce3ab16bc25851b6e43468e12 Mon Sep 17 00:00:00 2001 From: Adam Frisby Date: Wed, 30 Apr 2008 21:43:47 +0000 Subject: * Cruft removal step #1. Cleaning Modules directory. --- .../Agent/AssetDownload/AssetDownloadModule.cs | 37 +- .../AssetTransaction/AgentAssetsTransactions.cs | 83 +- .../AssetTransaction/AssetTransactionModule.cs | 55 +- .../Agent/TextureDownload/TextureDownloadModule.cs | 66 +- .../Agent/TextureDownload/TextureNotFoundSender.cs | 51 +- .../TextureDownload/UserTextureDownloadService.cs | 85 +- .../Modules/Agent/TextureSender/TextureSender.cs | 91 +- .../Environment/Modules/Agent/Xfer/XferModule.cs | 68 +- .../Environment/Modules/Avatar/Chat/ChatModule.cs | 349 ++-- .../Currency/SampleMoney/SampleMoneyModule.cs | 1847 ++++++++++---------- .../Modules/Avatar/Friends/FriendsModule.cs | 165 +- .../Modules/Avatar/Groups/GroupsModule.cs | 111 +- .../Avatar/InstantMessage/InstantMessageModule.cs | 75 +- .../Modules/Avatar/Inventory/InventoryModule.cs | 104 +- .../Avatar/Profiles/AvatarProfilesModule.cs | 6 +- .../Voice/AsterixVoice/AsteriskVoiceModule.cs | 81 +- .../Avatar/Voice/SIPVoice/SIPVoiceModule.cs | 47 +- .../Modules/Framework/CommanderTestModule.cs | 27 +- .../Modules/Grid/Interregion/InterregionModule.cs | 137 +- .../DynamicTexture/DynamicTextureModule.cs | 82 +- .../Scripting/HttpRequest/ScriptsHttpRequests.cs | 94 +- .../Scripting/LoadImageURL/LoadImageURLModule.cs | 82 +- .../Scripting/VectorRender/VectorRenderModule.cs | 132 +- .../Modules/Scripting/WorldComm/WorldCommModule.cs | 79 +- .../Modules/Scripting/XMLRPC/XMLRPCModule.cs | 214 +-- .../Environment/Modules/World/Land/LandChannel.cs | 364 ++-- .../Modules/World/Land/LandManagementModule.cs | 11 +- .../Environment/Modules/World/Land/LandObject.cs | 227 ++- .../Modules/World/Serialiser/SerialiseObjects.cs | 2 + .../Environment/Modules/World/Sun/SunModule.cs | 20 +- .../Modules/World/Terrain/FileLoaders/GIF.cs | 1 - .../Modules/World/Terrain/FileLoaders/PNG.cs | 1 - .../Modules/World/Terrain/FileLoaders/TIFF.cs | 1 - .../Modules/World/Terrain/TerrainModule.cs | 7 +- .../World/TreePopulator/TreePopulatorModule.cs | 83 +- 35 files changed, 2487 insertions(+), 2398 deletions(-) (limited to 'OpenSim/Region') diff --git a/OpenSim/Region/Environment/Modules/Agent/AssetDownload/AssetDownloadModule.cs b/OpenSim/Region/Environment/Modules/Agent/AssetDownload/AssetDownloadModule.cs index 47c1479..33e917a 100644 --- a/OpenSim/Region/Environment/Modules/Agent/AssetDownload/AssetDownloadModule.cs +++ b/OpenSim/Region/Environment/Modules/Agent/AssetDownload/AssetDownloadModule.cs @@ -37,17 +37,18 @@ namespace OpenSim.Region.Environment.Modules.Agent.AssetDownload { public class AssetDownloadModule : IRegionModule { + /// + /// Asset requests with data which are ready to be sent back to requesters. This includes textures. + /// + private List AssetRequests; + private Scene m_scene; private Dictionary RegisteredScenes = new Dictionary(); + /// /// Assets requests (for each user) which are waiting for asset server data. This includes texture requests /// - private Dictionary> RequestedAssets; - - /// - /// Asset requests with data which are ready to be sent back to requesters. This includes textures. - /// - private List AssetRequests; + private Dictionary> RequestedAssets; public AssetDownloadModule() { @@ -55,6 +56,8 @@ namespace OpenSim.Region.Environment.Modules.Agent.AssetDownload AssetRequests = new List(); } + #region IRegionModule Members + public void Initialise(Scene scene, IConfigSource config) { if (!RegisteredScenes.ContainsKey(scene.RegionInfo.RegionID)) @@ -92,6 +95,8 @@ namespace OpenSim.Region.Environment.Modules.Agent.AssetDownload get { return true; } } + #endregion + public void NewClient(IClientAPI client) { // client.OnRequestAsset += AddAssetRequest; @@ -301,33 +306,37 @@ namespace OpenSim.Region.Environment.Modules.Agent.AssetDownload { // over max number of bytes so split up file long restData = data.LongLength - m_maxPacketSize; - int restPackets = (int)((restData + m_maxPacketSize - 1) / m_maxPacketSize); + int restPackets = (int) ((restData + m_maxPacketSize - 1) / m_maxPacketSize); numPackets += restPackets; } return numPackets; } + #region Nested type: AssetRequest + public class AssetRequest { - public IClientAPI RequestUser; - public LLUUID RequestAssetID; public AssetBase AssetInf; - public AssetBase ImageInfo; - public LLUUID TransferRequestID; + public byte AssetRequestSource = 2; public long DataPointer = 0; + public int DiscardLevel = -1; + public AssetBase ImageInfo; + public bool IsTextureRequest; public int NumPackets = 0; public int PacketCounter = 0; - public bool IsTextureRequest; - public byte AssetRequestSource = 2; public byte[] Params = null; + public LLUUID RequestAssetID; + public IClientAPI RequestUser; + public LLUUID TransferRequestID; //public bool AssetInCache; //public int TimeRequested; - public int DiscardLevel = -1; public AssetRequest() { } } + + #endregion } } \ No newline at end of file diff --git a/OpenSim/Region/Environment/Modules/Agent/AssetTransaction/AgentAssetsTransactions.cs b/OpenSim/Region/Environment/Modules/Agent/AssetTransaction/AgentAssetsTransactions.cs index 74bb247..8192be4 100644 --- a/OpenSim/Region/Environment/Modules/Agent/AssetTransaction/AgentAssetsTransactions.cs +++ b/OpenSim/Region/Environment/Modules/Agent/AssetTransaction/AgentAssetsTransactions.cs @@ -42,12 +42,12 @@ namespace OpenSim.Region.Environment.Modules.Agent.AssetTransaction { //private static readonly log4net.ILog m_log // = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - + // Fields + private bool m_dumpAssetsToFile; + public AgentAssetTransactionsManager Manager; public LLUUID UserID; public Dictionary XferUploaders = new Dictionary(); - public AgentAssetTransactionsManager Manager; - private bool m_dumpAssetsToFile; // Methods public AgentAssetTransactions(LLUUID agentID, AgentAssetTransactionsManager manager, bool dumpAssetsToFile) @@ -67,7 +67,7 @@ namespace OpenSim.Region.Environment.Modules.Agent.AssetTransaction { XferUploaders.Add(transactionID, uploader); } - + return uploader; } return null; @@ -76,7 +76,7 @@ namespace OpenSim.Region.Environment.Modules.Agent.AssetTransaction public void HandleXfer(ulong xferID, uint packetID, byte[] data) { // AssetXferUploader uploaderFound = null; - + lock (XferUploaders) { foreach (AssetXferUploader uploader in XferUploaders.Values) @@ -86,7 +86,7 @@ namespace OpenSim.Region.Environment.Modules.Agent.AssetTransaction uploader.HandleXferPacket(xferID, packetID, data); break; } - } + } } } @@ -101,15 +101,15 @@ namespace OpenSim.Region.Environment.Modules.Agent.AssetTransaction wearableType, nextOwnerMask); } } - - public void RequestUpdateInventoryItem(IClientAPI remoteClient, LLUUID transactionID, + + public void RequestUpdateInventoryItem(IClientAPI remoteClient, LLUUID transactionID, InventoryItemBase item) { if (XferUploaders.ContainsKey(transactionID)) { XferUploaders[transactionID].RequestUpdateInventoryItem(remoteClient, transactionID, item); } - } + } /// /// Get an uploaded asset. If the data is successfully retrieved, the transaction will be removed. @@ -122,40 +122,43 @@ namespace OpenSim.Region.Environment.Modules.Agent.AssetTransaction { AssetXferUploader uploader = XferUploaders[transactionID]; AssetBase asset = uploader.GetAssetData(); - + lock (XferUploaders) { XferUploaders.Remove(transactionID); } - + return asset; } - + return null; } // Nested Types + + #region Nested type: AssetXferUploader + public class AssetXferUploader { // Fields public bool AddToInventory; public AssetBase Asset; public LLUUID InventFolder = LLUUID.Zero; + private sbyte invType = 0; + private bool m_createItem = false; + private string m_description = String.Empty; + private bool m_dumpAssetToFile; + private bool m_finished = false; + private string m_name = String.Empty; + private bool m_storeLocal; + private AgentAssetTransactions m_userTransactions; + private uint nextPerm = 0; private IClientAPI ourClient; public LLUUID TransactionID = LLUUID.Zero; - public bool UploadComplete; - public ulong XferID; - private string m_name = String.Empty; - private string m_description = String.Empty; private sbyte type = 0; - private sbyte invType = 0; + public bool UploadComplete; private byte wearableType = 0; - private uint nextPerm = 0; - private bool m_finished = false; - private bool m_createItem = false; - private AgentAssetTransactions m_userTransactions; - private bool m_storeLocal; - private bool m_dumpAssetToFile; + public ulong XferID; public AssetXferUploader(AgentAssetTransactions transactions, bool dumpAssetToFile) { @@ -197,7 +200,7 @@ namespace OpenSim.Region.Environment.Modules.Agent.AssetTransaction return true; } } - + return false; } @@ -233,7 +236,7 @@ namespace OpenSim.Region.Environment.Modules.Agent.AssetTransaction { RequestStartXfer(); } - + return false; } @@ -279,7 +282,7 @@ namespace OpenSim.Region.Environment.Modules.Agent.AssetTransaction SaveAssetToFile(filename, Asset.Data); } } - + ///Left this in and commented in case there are unforseen issues //private void SaveAssetToFile(string filename, byte[] data) //{ @@ -327,28 +330,28 @@ namespace OpenSim.Region.Environment.Modules.Agent.AssetTransaction } } } - - public void RequestUpdateInventoryItem(IClientAPI remoteClient, LLUUID transactionID, + + public void RequestUpdateInventoryItem(IClientAPI remoteClient, LLUUID transactionID, InventoryItemBase item) { if (TransactionID == transactionID) - { + { CachedUserInfo userInfo = m_userTransactions.Manager.MyScene.CommsManager.UserProfileCacheService.GetUserDetails( remoteClient.AgentId); - + if (userInfo != null) - { + { LLUUID assetID = LLUUID.Combine(transactionID, remoteClient.SecureSessionId); - + AssetBase asset = m_userTransactions.Manager.MyScene.CommsManager.AssetCache.GetAsset( assetID, (item.AssetType == (int) AssetType.Texture ? true : false)); - + if (asset == null) { asset = m_userTransactions.GetTransactionAsset(transactionID); - } + } if (asset != null && asset.FullID == assetID) { @@ -359,10 +362,10 @@ namespace OpenSim.Region.Environment.Modules.Agent.AssetTransaction item.AssetID = asset.FullID; m_userTransactions.Manager.MyScene.CommsManager.AssetCache.AddAsset(Asset); - } - - userInfo.UpdateItem(remoteClient.AgentId, item); - } + } + + userInfo.UpdateItem(remoteClient.AgentId, item); + } } } @@ -387,7 +390,7 @@ namespace OpenSim.Region.Environment.Modules.Agent.AssetTransaction item.BasePermissions = 2147483647; item.CurrentPermissions = 2147483647; item.NextPermissions = nextPerm; - item.Flags = (uint)wearableType; + item.Flags = (uint) wearableType; userInfo.AddItem(ourClient.AgentId, item); ourClient.SendInventoryItemCreateUpdate(item); @@ -403,5 +406,7 @@ namespace OpenSim.Region.Environment.Modules.Agent.AssetTransaction return null; } } + + #endregion } } \ No newline at end of file diff --git a/OpenSim/Region/Environment/Modules/Agent/AssetTransaction/AssetTransactionModule.cs b/OpenSim/Region/Environment/Modules/Agent/AssetTransaction/AssetTransactionModule.cs index ef81625..b264c8a 100644 --- a/OpenSim/Region/Environment/Modules/Agent/AssetTransaction/AssetTransactionModule.cs +++ b/OpenSim/Region/Environment/Modules/Agent/AssetTransaction/AssetTransactionModule.cs @@ -33,7 +33,6 @@ using log4net; using Nini.Config; using OpenSim.Framework; using OpenSim.Region.Environment.Interfaces; -using OpenSim.Region.Environment.Modules.Agent.AssetTransaction; using OpenSim.Region.Environment.Scenes; namespace OpenSim.Region.Environment.Modules.Agent.AssetTransaction @@ -41,8 +40,8 @@ namespace OpenSim.Region.Environment.Modules.Agent.AssetTransaction public class AssetTransactionModule : IRegionModule, IAgentAssetTransactions { private readonly Dictionary RegisteredScenes = new Dictionary(); - private Scene m_scene = null; private bool m_dumpAssetsToFile = false; + private Scene m_scene = null; private AgentAssetTransactionsManager m_transactionManager; @@ -51,6 +50,31 @@ namespace OpenSim.Region.Environment.Modules.Agent.AssetTransaction // System.Console.WriteLine("creating AgentAssetTransactionModule"); } + #region IAgentAssetTransactions Members + + public void HandleItemCreationFromTransaction(IClientAPI remoteClient, LLUUID transactionID, LLUUID folderID, + uint callbackID, string description, string name, sbyte invType, + sbyte type, byte wearableType, uint nextOwnerMask) + { + m_transactionManager.HandleItemCreationFromTransaction(remoteClient, transactionID, folderID, callbackID, description, name, invType, type, + wearableType, nextOwnerMask); + } + + public void HandleItemUpdateFromTransaction(IClientAPI remoteClient, LLUUID transactionID, + InventoryItemBase item) + { + m_transactionManager.HandleItemUpdateFromTransaction(remoteClient, transactionID, item); + } + + public void RemoveAgentAssetTransactions(LLUUID userID) + { + m_transactionManager.RemoveAgentAssetTransactions(userID); + } + + #endregion + + #region IRegionModule Members + public void Initialise(Scene scene, IConfigSource config) { if (!RegisteredScenes.ContainsKey(scene.RegionInfo.RegionID)) @@ -81,13 +105,11 @@ namespace OpenSim.Region.Environment.Modules.Agent.AssetTransaction { m_transactionManager = new AgentAssetTransactionsManager(m_scene, false); } - } } public void PostInitialise() { - } public void Close() @@ -104,29 +126,13 @@ namespace OpenSim.Region.Environment.Modules.Agent.AssetTransaction get { return true; } } + #endregion + public void NewClient(IClientAPI client) { client.OnAssetUploadRequest += m_transactionManager.HandleUDPUploadRequest; client.OnXferReceive += m_transactionManager.HandleXfer; } - - public void HandleItemCreationFromTransaction(IClientAPI remoteClient, LLUUID transactionID, LLUUID folderID, - uint callbackID, string description, string name, sbyte invType, - sbyte type, byte wearableType, uint nextOwnerMask) - { - m_transactionManager.HandleItemCreationFromTransaction(remoteClient, transactionID, folderID, callbackID, description, name, invType, type, wearableType, nextOwnerMask); - } - - public void HandleItemUpdateFromTransaction(IClientAPI remoteClient, LLUUID transactionID, - InventoryItemBase item) - { - m_transactionManager.HandleItemUpdateFromTransaction(remoteClient, transactionID, item); - } - - public void RemoveAgentAssetTransactions(LLUUID userID) - { - m_transactionManager.RemoveAgentAssetTransactions(userID); - } } public class AgentAssetTransactionsManager @@ -135,7 +141,6 @@ namespace OpenSim.Region.Environment.Modules.Agent.AssetTransaction = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // Fields - public Scene MyScene; /// /// Each agent has its own singleton collection of transactions @@ -148,6 +153,8 @@ namespace OpenSim.Region.Environment.Modules.Agent.AssetTransaction /// private bool m_dumpAssetsToFile; + public Scene MyScene; + public AgentAssetTransactionsManager(Scene scene, bool dumpAssetsToFile) { MyScene = scene; @@ -260,10 +267,8 @@ namespace OpenSim.Region.Environment.Modules.Agent.AssetTransaction AgentAssetTransactions.AssetXferUploader uploader = transactions.RequestXferUploader(transaction); if (uploader != null) { - if (uploader.Initialise(remoteClient, assetID, transaction, type, data, storeLocal, tempFile)) { - } } } diff --git a/OpenSim/Region/Environment/Modules/Agent/TextureDownload/TextureDownloadModule.cs b/OpenSim/Region/Environment/Modules/Agent/TextureDownload/TextureDownloadModule.cs index b8899d2..ae2df69 100644 --- a/OpenSim/Region/Environment/Modules/Agent/TextureDownload/TextureDownloadModule.cs +++ b/OpenSim/Region/Environment/Modules/Agent/TextureDownload/TextureDownloadModule.cs @@ -40,14 +40,11 @@ namespace OpenSim.Region.Environment.Modules.Agent.TextureDownload { //private static readonly log4net.ILog m_log // = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - - private Scene m_scene; - private List m_scenes = new List(); /// /// There is one queue for all textures waiting to be sent, regardless of the requesting user. /// - private readonly BlockingQueue m_queueSenders + private readonly BlockingQueue m_queueSenders = new BlockingQueue(); /// @@ -56,12 +53,17 @@ namespace OpenSim.Region.Environment.Modules.Agent.TextureDownload private readonly Dictionary m_userTextureServices = new Dictionary(); + private Scene m_scene; + private List m_scenes = new List(); + private Thread m_thread; public TextureDownloadModule() { } + #region IRegionModule Members + public void Initialise(Scene scene, IConfigSource config) { if (m_scene == null) @@ -83,6 +85,26 @@ namespace OpenSim.Region.Environment.Modules.Agent.TextureDownload } } + public void PostInitialise() + { + } + + public void Close() + { + } + + public string Name + { + get { return "TextureDownloadModule"; } + } + + public bool IsSharedModule + { + get { return false; } + } + + #endregion + /// /// Cleanup the texture service related objects for the removed presence. /// @@ -102,24 +124,6 @@ namespace OpenSim.Region.Environment.Modules.Agent.TextureDownload } } - public void PostInitialise() - { - } - - public void Close() - { - } - - public string Name - { - get { return "TextureDownloadModule"; } - } - - public bool IsSharedModule - { - get { return false; } - } - public void NewClient(IClientAPI client) { client.OnRequestTexture += TextureRequest; @@ -143,7 +147,7 @@ namespace OpenSim.Region.Environment.Modules.Agent.TextureDownload textureService = new UserTextureDownloadService(client, m_scene, m_queueSenders); m_userTextureServices.Add(client.AgentId, textureService); - + return true; } } @@ -157,11 +161,11 @@ namespace OpenSim.Region.Environment.Modules.Agent.TextureDownload { IClientAPI client = (IClientAPI) sender; UserTextureDownloadService textureService; - + if (TryGetUserTextureService(client, out textureService)) { textureService.HandleTextureRequest(e); - } + } } /// @@ -170,11 +174,11 @@ namespace OpenSim.Region.Environment.Modules.Agent.TextureDownload public void ProcessTextureSenders() { ITextureSender sender = null; - + while (true) { sender = m_queueSenders.Dequeue(); - + if (sender.Cancel) { TextureSent(sender); @@ -193,10 +197,10 @@ namespace OpenSim.Region.Environment.Modules.Agent.TextureDownload m_queueSenders.Enqueue(sender); } } - + // Make sure that any sender we currently have can get garbage collected sender = null; - + //m_log.InfoFormat("[TEXTURE DOWNLOAD] Texture sender queue size: {0}", m_queueSenders.Count()); } } @@ -207,9 +211,9 @@ namespace OpenSim.Region.Environment.Modules.Agent.TextureDownload /// private void TextureSent(ITextureSender sender) { - sender.Sending = false; + sender.Sending = false; //m_log.DebugFormat("[TEXTURE DOWNLOAD]: Removing download stat for {0}", sender.assetID); - m_scene.AddPendingDownloads(-1); + m_scene.AddPendingDownloads(-1); } } } \ No newline at end of file diff --git a/OpenSim/Region/Environment/Modules/Agent/TextureDownload/TextureNotFoundSender.cs b/OpenSim/Region/Environment/Modules/Agent/TextureDownload/TextureNotFoundSender.cs index 6f11f73..b181d20 100644 --- a/OpenSim/Region/Environment/Modules/Agent/TextureDownload/TextureNotFoundSender.cs +++ b/OpenSim/Region/Environment/Modules/Agent/TextureDownload/TextureNotFoundSender.cs @@ -39,55 +39,60 @@ namespace OpenSim.Region.Environment.Modules.Agent.TextureDownload { //private static readonly log4net.ILog m_log // = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - - private LLUUID m_textureId; + + private bool m_cancel = false; private IClientAPI m_client; - + // See ITextureSender - public bool Sending - { - get { return false; } - set { m_sending = value; } - } - - private bool m_sending = false; + + private bool m_sending = false; + private LLUUID m_textureId; // See ITextureSender - public bool Cancel - { - get { return false; } - set { m_cancel = value; } - } - - private bool m_cancel = false; - + public TextureNotFoundSender(IClientAPI client, LLUUID textureID) { m_client = client; m_textureId = textureID; } - + + #region ITextureSender Members + + public bool Sending + { + get { return false; } + set { m_sending = value; } + } + + public bool Cancel + { + get { return false; } + set { m_cancel = value; } + } + // See ITextureSender public void UpdateRequest(int discardLevel, uint packetNumber) { // Not need to implement since priority changes don't affect this operation } - + // See ITextureSender public bool SendTexturePacket() { //m_log.InfoFormat( // "[TEXTURE NOT FOUND SENDER]: Informing the client that texture {0} cannot be found", // m_textureId); - + ImageNotInDatabasePacket notFound = new ImageNotInDatabasePacket(); notFound.ImageID.ID = m_textureId; - + // XXX Temporarily disabling as this appears to be causing client crashes on at least // 1.19.0(5) of the Linden Second Life client. // m_client.OutPacket(notFound, ThrottleOutPacketType.Texture); - + return true; } + + #endregion } } \ No newline at end of file diff --git a/OpenSim/Region/Environment/Modules/Agent/TextureDownload/UserTextureDownloadService.cs b/OpenSim/Region/Environment/Modules/Agent/TextureDownload/UserTextureDownloadService.cs index 08a22d6..4f63fd0 100644 --- a/OpenSim/Region/Environment/Modules/Agent/TextureDownload/UserTextureDownloadService.cs +++ b/OpenSim/Region/Environment/Modules/Agent/TextureDownload/UserTextureDownloadService.cs @@ -32,8 +32,6 @@ using log4net; using OpenSim.Framework; using OpenSim.Framework.Communications.Limit; using OpenSim.Region.Environment.Interfaces; -using OpenSim.Region.Environment.Modules.Agent.TextureDownload; -using OpenSim.Region.Environment.Modules.Agent.TextureSender; using OpenSim.Region.Environment.Scenes; namespace OpenSim.Region.Environment.Modules.Agent.TextureDownload @@ -45,7 +43,7 @@ namespace OpenSim.Region.Environment.Modules.Agent.TextureDownload /// public class UserTextureDownloadService { - private static readonly ILog m_log + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// @@ -56,35 +54,34 @@ namespace OpenSim.Region.Environment.Modules.Agent.TextureDownload /// sophisticated way. /// private static readonly int MAX_ALLOWED_TEXTURE_REQUESTS = 5; - - /// - /// We're going to limit requests for the same missing texture. - /// XXX This is really a temporary solution to deal with the situation where a client continually requests - /// the same missing textures - /// - private readonly IRequestLimitStrategy missingTextureLimitStrategy - = new RepeatLimitStrategy(MAX_ALLOWED_TEXTURE_REQUESTS); - + /// /// XXX Also going to limit requests for found textures. /// - private readonly IRequestLimitStrategy foundTextureLimitStrategy - = new RepeatLimitStrategy(MAX_ALLOWED_TEXTURE_REQUESTS); - - /// - /// Holds texture senders before they have received the appropriate texture from the asset cache. - /// - private readonly Dictionary m_textureSenders = new Dictionary(); - + private readonly IRequestLimitStrategy foundTextureLimitStrategy + = new RepeatLimitStrategy(MAX_ALLOWED_TEXTURE_REQUESTS); + + private readonly IClientAPI m_client; + private readonly Scene m_scene; + /// /// Texture Senders are placed in this queue once they have received their texture from the asset /// cache. Another module actually invokes the send. /// private readonly BlockingQueue m_sharedSendersQueue; - - private readonly Scene m_scene; - - private readonly IClientAPI m_client; + + /// + /// Holds texture senders before they have received the appropriate texture from the asset cache. + /// + private readonly Dictionary m_textureSenders = new Dictionary(); + + /// + /// We're going to limit requests for the same missing texture. + /// XXX This is really a temporary solution to deal with the situation where a client continually requests + /// the same missing textures + /// + private readonly IRequestLimitStrategy missingTextureLimitStrategy + = new RepeatLimitStrategy(MAX_ALLOWED_TEXTURE_REQUESTS); public UserTextureDownloadService( IClientAPI client, Scene scene, BlockingQueue sharedQueue) @@ -112,19 +109,19 @@ namespace OpenSim.Region.Environment.Modules.Agent.TextureDownload { // If we've received new non UUID information for this request and it hasn't dispatched // yet, then update the request accordingly. - textureSender.UpdateRequest(e.DiscardLevel, e.PacketNumber); + textureSender.UpdateRequest(e.DiscardLevel, e.PacketNumber); } else - { + { if (!foundTextureLimitStrategy.AllowRequest(e.RequestedAssetID)) { // m_log.DebugFormat( // "[USER TEXTURE DOWNLOAD SERVICE]: Refusing request for {0} from client {1}", // e.RequestedAssetID, m_client.AgentId); - + return; } - else if (!missingTextureLimitStrategy.AllowRequest(e.RequestedAssetID)) + else if (!missingTextureLimitStrategy.AllowRequest(e.RequestedAssetID)) { if (missingTextureLimitStrategy.IsFirstRefusal(e.RequestedAssetID)) { @@ -135,17 +132,17 @@ namespace OpenSim.Region.Environment.Modules.Agent.TextureDownload // m_log.DebugFormat( // "[USER TEXTURE DOWNLOAD SERVICE]: Dropping requests for notified missing texture {0} for client {1} since we have received more than {2} requests", // e.RequestedAssetID, m_client.AgentId, MAX_ALLOWED_TEXTURE_REQUESTS); - } - - return; + } + + return; } - + m_scene.AddPendingDownloads(1); - - TextureSender.TextureSender requestHandler = new TextureSender.TextureSender(m_client, e.DiscardLevel, e.PacketNumber); + + TextureSender.TextureSender requestHandler = new TextureSender.TextureSender(m_client, e.DiscardLevel, e.PacketNumber); m_textureSenders.Add(e.RequestedAssetID, requestHandler); - - m_scene.AssetCache.GetAsset(e.RequestedAssetID, TextureCallback, true); + + m_scene.AssetCache.GetAsset(e.RequestedAssetID, TextureCallback, true); } } } @@ -170,7 +167,7 @@ namespace OpenSim.Region.Environment.Modules.Agent.TextureDownload public void TextureCallback(LLUUID textureID, AssetBase texture) { //m_log.DebugFormat("[USER TEXTURE DOWNLOAD SERVICE]: Calling TextureCallback with {0}, texture == null is {1}", textureID, (texture == null ? true : false)); - + lock (m_textureSenders) { TextureSender.TextureSender textureSender; @@ -181,18 +178,18 @@ namespace OpenSim.Region.Environment.Modules.Agent.TextureDownload // this on to the TextureSender it will blow up, so just discard for now. // Needs investigation. if (texture == null || texture.Data == null) - { + { if (!missingTextureLimitStrategy.IsMonitoringRequests(textureID)) { missingTextureLimitStrategy.MonitorRequests(textureID); m_log.DebugFormat( - "[USER TEXTURE DOWNLOAD SERVICE]: Queueing first TextureNotFoundSender for {0}, client {1}", + "[USER TEXTURE DOWNLOAD SERVICE]: Queueing first TextureNotFoundSender for {0}, client {1}", textureID, m_client.AgentId); } - + ITextureSender textureNotFoundSender = new TextureNotFoundSender(m_client, textureID); - EnqueueTextureSender(textureNotFoundSender); + EnqueueTextureSender(textureNotFoundSender); } else { @@ -200,13 +197,13 @@ namespace OpenSim.Region.Environment.Modules.Agent.TextureDownload { textureSender.TextureReceived(texture); EnqueueTextureSender(textureSender); - + foundTextureLimitStrategy.MonitorRequests(textureID); } } //m_log.InfoFormat("[TEXTURE SENDER] Removing texture sender with uuid {0}", textureID); - m_textureSenders.Remove(textureID); + m_textureSenders.Remove(textureID); //m_log.InfoFormat("[TEXTURE SENDER] Current texture senders in dictionary: {0}", m_textureSenders.Count); } else @@ -240,7 +237,7 @@ namespace OpenSim.Region.Environment.Modules.Agent.TextureDownload { lock (m_textureSenders) { - foreach( TextureSender.TextureSender textureSender in m_textureSenders.Values ) + foreach (TextureSender.TextureSender textureSender in m_textureSenders.Values) { textureSender.Cancel = true; } diff --git a/OpenSim/Region/Environment/Modules/Agent/TextureSender/TextureSender.cs b/OpenSim/Region/Environment/Modules/Agent/TextureSender/TextureSender.cs index 37b0652..b6f7095 100644 --- a/OpenSim/Region/Environment/Modules/Agent/TextureSender/TextureSender.cs +++ b/OpenSim/Region/Environment/Modules/Agent/TextureSender/TextureSender.cs @@ -40,56 +40,43 @@ namespace OpenSim.Region.Environment.Modules.Agent.TextureSender /// public class TextureSender : ITextureSender { - private static readonly ILog m_log + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// /// Records the number of times texture send has been called. /// public int counter = 0; - + + public bool ImageLoaded = false; + /// /// Holds the texture asset to send. /// private AssetBase m_asset; - + //public LLUUID assetID { get { return m_asset.FullID; } } - + + private bool m_cancel = false; + + // See ITextureSender + + private bool m_sending = false; + /// /// This is actually the number of extra packets required to send the texture data! We always assume /// at least one is required. /// private int NumPackets = 0; - + /// /// Holds the packet number to send next. In this case, each packet is 1000 bytes long and starts /// at the 600th byte (0th indexed). /// private int PacketCounter = 0; - - // See ITextureSender - public bool Cancel - { - get { return false; } - set { m_cancel = value; } - } - - private bool m_cancel = false; - - // See ITextureSender - public bool Sending - { - get { return false; } - set { m_sending = value; } - } - - private bool m_sending = false; - - public bool ImageLoaded = false; - - private IClientAPI RequestUser; private int RequestedDiscardLevel = -1; + private IClientAPI RequestUser; private uint StartPacketNumber = 0; public TextureSender(IClientAPI client, int discardLevel, uint packetNumber) @@ -99,18 +86,18 @@ namespace OpenSim.Region.Environment.Modules.Agent.TextureSender StartPacketNumber = packetNumber; } - /// - /// Load up the texture data to send. - /// - /// - /// A - /// - public void TextureReceived(AssetBase asset) + #region ITextureSender Members + + public bool Cancel { - m_asset = asset; - NumPackets = CalculateNumPackets(asset.Data.Length); - PacketCounter = (int) StartPacketNumber; - ImageLoaded = true; + get { return false; } + set { m_cancel = value; } + } + + public bool Sending + { + get { return false; } + set { m_sending = value; } } // See ITextureSender @@ -125,17 +112,33 @@ namespace OpenSim.Region.Environment.Modules.Agent.TextureSender public bool SendTexturePacket() { //m_log.DebugFormat("[TEXTURE SENDER]: Sending packet for {0}", m_asset.FullID); - + SendPacket(); counter++; if ((NumPackets == 0) || (RequestedDiscardLevel == -1) || (PacketCounter > NumPackets) || - ((RequestedDiscardLevel > 0) && (counter > 50 + (NumPackets/(RequestedDiscardLevel + 1))))) + ((RequestedDiscardLevel > 0) && (counter > 50 + (NumPackets / (RequestedDiscardLevel + 1))))) { return true; } return false; } + #endregion + + /// + /// Load up the texture data to send. + /// + /// + /// A + /// + public void TextureReceived(AssetBase asset) + { + m_asset = asset; + NumPackets = CalculateNumPackets(asset.Data.Length); + PacketCounter = (int) StartPacketNumber; + ImageLoaded = true; + } + /// /// Sends a texture packet to the client. /// @@ -177,17 +180,17 @@ namespace OpenSim.Region.Environment.Modules.Agent.TextureSender im.Header.Reliable = false; im.ImageID.Packet = (ushort) (PacketCounter); im.ImageID.ID = m_asset.FullID; - int size = m_asset.Data.Length - 600 - (1000*(PacketCounter - 1)); + int size = m_asset.Data.Length - 600 - (1000 * (PacketCounter - 1)); if (size > 1000) size = 1000; im.ImageData.Data = new byte[size]; try { - Array.Copy(m_asset.Data, 600 + (1000*(PacketCounter - 1)), im.ImageData.Data, 0, size); + Array.Copy(m_asset.Data, 600 + (1000 * (PacketCounter - 1)), im.ImageData.Data, 0, size); } catch (ArgumentOutOfRangeException) { m_log.Error("[TEXTURE SENDER]: Unable to separate texture into multiple packets: Array bounds failure on asset:" + - m_asset.FullID.ToString() ); + m_asset.FullID.ToString()); return; } RequestUser.OutPacket(im, ThrottleOutPacketType.Texture); @@ -210,7 +213,7 @@ namespace OpenSim.Region.Environment.Modules.Agent.TextureSender { //over 600 bytes so split up file int restData = (length - 600); - int restPackets = ((restData + 999)/1000); + int restPackets = ((restData + 999) / 1000); numPackets = restPackets; } diff --git a/OpenSim/Region/Environment/Modules/Agent/Xfer/XferModule.cs b/OpenSim/Region/Environment/Modules/Agent/Xfer/XferModule.cs index b609f93..e35b6f5 100644 --- a/OpenSim/Region/Environment/Modules/Agent/Xfer/XferModule.cs +++ b/OpenSim/Region/Environment/Modules/Agent/Xfer/XferModule.cs @@ -37,15 +37,16 @@ namespace OpenSim.Region.Environment.Modules.Agent.Xfer { public class XferModule : IRegionModule, IXfer { + private Scene m_scene; public Dictionary NewFiles = new Dictionary(); public Dictionary Transfers = new Dictionary(); - private Scene m_scene; - public XferModule() { } + #region IRegionModule Members + public void Initialise(Scene scene, IConfigSource config) { m_scene = scene; @@ -72,6 +73,28 @@ namespace OpenSim.Region.Environment.Modules.Agent.Xfer get { return false; } } + #endregion + + #region IXfer Members + + public bool AddNewFile(string fileName, byte[] data) + { + lock (NewFiles) + { + if (NewFiles.ContainsKey(fileName)) + { + NewFiles[fileName] = data; + } + else + { + NewFiles.Add(fileName, data); + } + } + return true; + } + + #endregion + public void NewClient(IClientAPI client) { client.OnRequestXfer += RequestXfer; @@ -96,7 +119,7 @@ namespace OpenSim.Region.Environment.Modules.Agent.Xfer XferDownLoad transaction = new XferDownLoad(fileName, fileData, xferID, remoteClient); Transfers.Add(xferID, transaction); NewFiles.Remove(fileName); - + if (transaction.StartSend()) { Transfers.Remove(xferID); @@ -119,33 +142,18 @@ namespace OpenSim.Region.Environment.Modules.Agent.Xfer } } - public bool AddNewFile(string fileName, byte[] data) - { - lock (NewFiles) - { - if (NewFiles.ContainsKey(fileName)) - { - NewFiles[fileName] = data; - } - else - { - NewFiles.Add(fileName, data); - } - } - return true; - } - + #region Nested type: XferDownLoad public class XferDownLoad { + public IClientAPI Client; + private bool complete; public byte[] Data = new byte[0]; - public string FileName = String.Empty; - public ulong XferID = 0; public int DataPointer = 0; + public string FileName = String.Empty; public uint Packet = 0; - public IClientAPI Client; public uint Serial = 1; - private bool complete; + public ulong XferID = 0; public XferDownLoad(string fileName, byte[] data, ulong xferID, IClientAPI client) { @@ -172,7 +180,7 @@ namespace OpenSim.Region.Environment.Modules.Agent.Xfer Array.Copy(Helpers.IntToBytes(Data.Length), 0, transferData, 0, 4); Array.Copy(Data, 0, transferData, 4, Data.Length); Client.SendXferPacket(XferID, 0 + 0x80000000, transferData); - + complete = true; } else @@ -182,10 +190,10 @@ namespace OpenSim.Region.Environment.Modules.Agent.Xfer Array.Copy(Data, 0, transferData, 4, 1000); Client.SendXferPacket(XferID, 0, transferData); Packet++; - DataPointer = 1000; + DataPointer = 1000; } - - return complete; + + return complete; } /// @@ -213,13 +221,15 @@ namespace OpenSim.Region.Environment.Modules.Agent.Xfer Client.SendXferPacket(XferID, endPacket, transferData); Packet++; DataPointer += (Data.Length - DataPointer); - + complete = true; } } - + return complete; } } + + #endregion } } \ No newline at end of file diff --git a/OpenSim/Region/Environment/Modules/Avatar/Chat/ChatModule.cs b/OpenSim/Region/Environment/Modules/Avatar/Chat/ChatModule.cs index 1281873..966f5f3 100644 --- a/OpenSim/Region/Environment/Modules/Avatar/Chat/ChatModule.cs +++ b/OpenSim/Region/Environment/Modules/Avatar/Chat/ChatModule.cs @@ -44,21 +44,21 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat public class ChatModule : IRegionModule, ISimChat { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private List m_scenes = new List(); - - private int m_whisperdistance = 10; - private int m_saydistance = 30; - private int m_shoutdistance = 100; + private string m_defaultzone = null; private IRCChatModule m_irc = null; + private Thread m_irc_connector = null; - private string m_last_new_user = null; private string m_last_leaving_user = null; - private string m_defaultzone = null; + private string m_last_new_user = null; + private int m_saydistance = 30; + private List m_scenes = new List(); + private int m_shoutdistance = 100; internal object m_syncInit = new object(); internal object m_syncLogout = new object(); - private Thread m_irc_connector=null; + private int m_whisperdistance = 10; + + #region IRegionModule Members public void Initialise(Scene scene, IConfigSource config) { @@ -85,14 +85,17 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat try { - m_defaultzone = config.Configs["IRC"].GetString("nick","Sim"); + m_defaultzone = config.Configs["IRC"].GetString("nick", "Sim"); } catch (Exception) { } // setup IRC Relay - if (m_irc == null) { m_irc = new IRCChatModule(config); } + if (m_irc == null) + { + m_irc = new IRCChatModule(config); + } if (m_irc_connector == null) { m_irc_connector = new Thread(IRCConnectRun); @@ -142,83 +145,9 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat get { return true; } } - public void NewClient(IClientAPI client) - { - try - { - client.OnChatFromViewer += SimChat; + #endregion - if ((m_irc.Enabled) && (m_irc.Connected)) - { - string clientName = client.FirstName + " " + client.LastName; - // handles simple case. May not work for hundred connecting in per second. - // and the NewClients calles getting interleved - // but filters out multiple reports - if (clientName != m_last_new_user) - { - m_last_new_user = clientName; - string clientRegion = FindClientRegion(client.FirstName, client.LastName); - m_irc.PrivMsg(m_irc.Nick, "Sim", "notices " + clientName + " in "+clientRegion); - } - } - client.OnLogout += ClientLoggedOut; - client.OnConnectionClosed += ClientLoggedOut; - client.OnLogout += ClientLoggedOut; - } - catch (Exception ex) - { - m_log.Error("[IRC]: NewClient exception trap:" + ex.ToString()); - } - } - - public void ClientLoggedOut(IClientAPI client) - { - lock (m_syncLogout) - { - try - { - if ((m_irc.Enabled) && (m_irc.Connected)) - { - string clientName = client.FirstName + " " + client.LastName; - string clientRegion = FindClientRegion(client.FirstName, client.LastName); - // handles simple case. May not work for hundred connecting in per second. - // and the NewClients calles getting interleved - // but filters out multiple reports - if (clientName != m_last_leaving_user) - { - m_last_leaving_user = clientName; - m_irc.PrivMsg(m_irc.Nick, "Sim", "notices " + clientName + " left " + clientRegion); - m_log.Info("[IRC]: IRC watcher notices " + clientName + " left " + clientRegion); - } - } - } - catch (Exception ex) - { - m_log.Error("[IRC]: ClientLoggedOut exception trap:" + ex.ToString()); - } - } - } - - private void TrySendChatMessage(ScenePresence presence, LLVector3 fromPos, LLVector3 regionPos, - LLUUID fromAgentID, string fromName, ChatTypeEnum type, string message) - { - if (!presence.IsChildAgent) - { - LLVector3 fromRegionPos = fromPos + regionPos; - LLVector3 toRegionPos = presence.AbsolutePosition + regionPos; - int dis = Math.Abs((int) Util.GetDistanceTo(toRegionPos, fromRegionPos)); - - if (type == ChatTypeEnum.Whisper && dis > m_whisperdistance || - type == ChatTypeEnum.Say && dis > m_saydistance || - type == ChatTypeEnum.Shout && dis > m_shoutdistance) - { - return; - } - - // TODO: should change so the message is sent through the avatar rather than direct to the ClientView - presence.ControllingClient.SendChatMessage(message, (byte) type, fromPos, fromName, fromAgentID); - } - } + #region ISimChat Members public void SimChat(Object sender, ChatFromViewerArgs e) { @@ -289,7 +218,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat m_irc.PrivMsg(fromName, scene.RegionInfo.RegionName, e.Message); } } - + foreach (Scene s in m_scenes) { s.ForEachScenePresence(delegate(ScenePresence presence) @@ -301,12 +230,92 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat } } + #endregion + + public void NewClient(IClientAPI client) + { + try + { + client.OnChatFromViewer += SimChat; + + if ((m_irc.Enabled) && (m_irc.Connected)) + { + string clientName = client.FirstName + " " + client.LastName; + // handles simple case. May not work for hundred connecting in per second. + // and the NewClients calles getting interleved + // but filters out multiple reports + if (clientName != m_last_new_user) + { + m_last_new_user = clientName; + string clientRegion = FindClientRegion(client.FirstName, client.LastName); + m_irc.PrivMsg(m_irc.Nick, "Sim", "notices " + clientName + " in " + clientRegion); + } + } + client.OnLogout += ClientLoggedOut; + client.OnConnectionClosed += ClientLoggedOut; + client.OnLogout += ClientLoggedOut; + } + catch (Exception ex) + { + m_log.Error("[IRC]: NewClient exception trap:" + ex.ToString()); + } + } + + public void ClientLoggedOut(IClientAPI client) + { + lock (m_syncLogout) + { + try + { + if ((m_irc.Enabled) && (m_irc.Connected)) + { + string clientName = client.FirstName + " " + client.LastName; + string clientRegion = FindClientRegion(client.FirstName, client.LastName); + // handles simple case. May not work for hundred connecting in per second. + // and the NewClients calles getting interleved + // but filters out multiple reports + if (clientName != m_last_leaving_user) + { + m_last_leaving_user = clientName; + m_irc.PrivMsg(m_irc.Nick, "Sim", "notices " + clientName + " left " + clientRegion); + m_log.Info("[IRC]: IRC watcher notices " + clientName + " left " + clientRegion); + } + } + } + catch (Exception ex) + { + m_log.Error("[IRC]: ClientLoggedOut exception trap:" + ex.ToString()); + } + } + } + + private void TrySendChatMessage(ScenePresence presence, LLVector3 fromPos, LLVector3 regionPos, + LLUUID fromAgentID, string fromName, ChatTypeEnum type, string message) + { + if (!presence.IsChildAgent) + { + LLVector3 fromRegionPos = fromPos + regionPos; + LLVector3 toRegionPos = presence.AbsolutePosition + regionPos; + int dis = Math.Abs((int) Util.GetDistanceTo(toRegionPos, fromRegionPos)); + + if (type == ChatTypeEnum.Whisper && dis > m_whisperdistance || + type == ChatTypeEnum.Say && dis > m_saydistance || + type == ChatTypeEnum.Shout && dis > m_shoutdistance) + { + return; + } + + // TODO: should change so the message is sent through the avatar rather than direct to the ClientView + presence.ControllingClient.SendChatMessage(message, (byte) type, fromPos, fromName, fromAgentID); + } + } + // if IRC is enabled then just keep trying using a monitor thread public void IRCConnectRun() { - while(true) + while (true) { - if ((m_irc.Enabled)&&(!m_irc.Connected)) + if ((m_irc.Enabled) && (!m_irc.Connected)) { m_irc.Connect(m_scenes); } @@ -314,54 +323,76 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat } } - public string FindClientRegion(string client_FirstName,string client_LastName) + public string FindClientRegion(string client_FirstName, string client_LastName) { string sourceRegion = null; foreach (Scene s in m_scenes) { s.ForEachScenePresence(delegate(ScenePresence presence) { - if ((presence.IsChildAgent==false) - &&(presence.Firstname==client_FirstName) - &&(presence.Lastname==client_LastName)) + if ((presence.IsChildAgent == false) + && (presence.Firstname == client_FirstName) + && (presence.Lastname == client_LastName)) { sourceRegion = presence.Scene.RegionInfo.RegionName; //sourceRegion= s.RegionInfo.RegionName; } }); - if (sourceRegion != null) return sourceRegion; + if (sourceRegion != null) return sourceRegion; + } + if (m_defaultzone == null) + { + m_defaultzone = "Sim"; } - if (m_defaultzone == null) { m_defaultzone = "Sim"; } return m_defaultzone; } } internal class IRCChatModule { + #region ErrorReplies enum + + public enum ErrorReplies + { + NotRegistered = 451, // ":You have not registered" + NicknameInUse = 433 // " :Nickname is already in use" + } + + #endregion + + #region Replies enum + + public enum Replies + { + MotdStart = 375, // ":- Message of the day - " + Motd = 372, // ":- " + EndOfMotd = 376 // ":End of /MOTD command" + } + + #endregion + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + private Thread listener; - private string m_server = null; - private uint m_port = 6668; - private string m_user = "USER OpenSimBot 8 * :I'm a OpenSim to irc bot"; - private string m_nick = null; private string m_basenick = null; private string m_channel = null; + private bool m_connected = false; + private bool m_enabled = false; + private List m_last_scenes = null; + private string m_nick = null; + private uint m_port = 6668; private string m_privmsgformat = "PRIVMSG {0} :<{1} in {2}>: {3}"; + private StreamReader m_reader; + private List m_scenes = null; + private string m_server = null; private NetworkStream m_stream; + internal object m_syncConnect = new object(); private TcpClient m_tcp; + private string m_user = "USER OpenSimBot 8 * :I'm a OpenSim to irc bot"; private StreamWriter m_writer; - private StreamReader m_reader; private Thread pingSender; - private Thread listener; - internal object m_syncConnect = new object(); - - private bool m_enabled = false; - private bool m_connected = false; - - private List m_scenes = null; - private List m_last_scenes = null; public IRCChatModule(IConfigSource config) { @@ -412,6 +443,21 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat } } + public bool Enabled + { + get { return m_enabled; } + } + + public bool Connected + { + get { return m_connected; } + } + + public string Nick + { + get { return m_nick; } + } + public bool Connect(List scenes) { lock (m_syncConnect) @@ -420,9 +466,12 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat { if (m_connected) return true; m_scenes = scenes; - if (m_last_scenes == null) { m_last_scenes = scenes; } + if (m_last_scenes == null) + { + m_last_scenes = scenes; + } - m_tcp = new TcpClient(m_server, (int)m_port); + m_tcp = new TcpClient(m_server, (int) m_port); m_log.Info("[IRC]: Connecting..."); m_stream = m_tcp.GetStream(); m_log.Info("[IRC]: Connected to " + m_server); @@ -458,21 +507,6 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat } } - public bool Enabled - { - get { return m_enabled; } - } - - public bool Connected - { - get { return m_connected; } - } - - public string Nick - { - get { return m_nick; } - } - public void Reconnect() { m_connected = false; @@ -481,7 +515,10 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat m_writer.Close(); m_reader.Close(); m_tcp.Close(); - if (m_enabled) { Connect(m_last_scenes); } + if (m_enabled) + { + Connect(m_last_scenes); + } } public void PrivMsg(string from, string region, string msg) @@ -627,7 +664,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat } } - public void BroadcastSim(string message,string sender) + public void BroadcastSim(string message, string sender) { LLVector3 pos = new LLVector3(128, 128, 20); try @@ -652,23 +689,10 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat } } - public enum ErrorReplies - { - NotRegistered = 451, // ":You have not registered" - NicknameInUse = 433 // " :Nickname is already in use" - } - - public enum Replies - { - MotdStart = 375, // ":- Message of the day - " - Motd = 372, // ":- " - EndOfMotd = 376 // ":End of /MOTD command" - } - public void ProcessIRCCommand(string command) { //m_log.Info("[IRC]: ProcessIRCCommand:" + command); - + string[] commArgs = new string[command.Split(' ').Length]; string c_server = m_server; @@ -690,7 +714,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat if (commArgs[0] == "ERROR") { - m_log.Error("[IRC]: IRC SERVER ERROR:" + command); + m_log.Error("[IRC]: IRC SERVER ERROR:" + command); } if (commArgs[0] == "PING") @@ -713,7 +737,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat Int32 commandCode = Int32.Parse(commArgs[1]); switch (commandCode) { - case (int)ErrorReplies.NicknameInUse: + case (int) ErrorReplies.NicknameInUse: // Gen a new name m_nick = m_basenick + Util.RandomClass.Next(1, 99); m_log.Error("[IRC]: IRC SERVER reports NicknameInUse, trying " + m_nick); @@ -723,9 +747,9 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat m_writer.WriteLine("JOIN " + m_channel); m_writer.Flush(); break; - case (int)ErrorReplies.NotRegistered: + case (int) ErrorReplies.NotRegistered: break; - case (int)Replies.EndOfMotd: + case (int) Replies.EndOfMotd: break; } } @@ -733,19 +757,32 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat { } } - else - { + else + { // Normal message string commAct = commArgs[1]; switch (commAct) { - case "JOIN": eventIrcJoin(commArgs); break; - case "PART": eventIrcPart(commArgs); break; - case "MODE": eventIrcMode(commArgs); break; - case "NICK": eventIrcNickChange(commArgs); break; - case "KICK": eventIrcKick(commArgs); break; - case "QUIT": eventIrcQuit(commArgs); break; - case "PONG": break; // that's nice + case "JOIN": + eventIrcJoin(commArgs); + break; + case "PART": + eventIrcPart(commArgs); + break; + case "MODE": + eventIrcMode(commArgs); + break; + case "NICK": + eventIrcNickChange(commArgs); + break; + case "KICK": + eventIrcKick(commArgs); + break; + case "QUIT": + eventIrcQuit(commArgs); + break; + case "PONG": + break; // that's nice } } } @@ -797,7 +834,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Chat { KickMessage += commArgs[i] + " "; } - BroadcastSim(UserKicker + " kicked " + UserKicked +" on "+IrcChannel+" saying "+KickMessage, m_nick); + BroadcastSim(UserKicker + " kicked " + UserKicked + " on " + IrcChannel + " saying " + KickMessage, m_nick); if (UserKicked == m_nick) { BroadcastSim("Hey, that was me!!!", m_nick); diff --git a/OpenSim/Region/Environment/Modules/Avatar/Currency/SampleMoney/SampleMoneyModule.cs b/OpenSim/Region/Environment/Modules/Avatar/Currency/SampleMoney/SampleMoneyModule.cs index 0e058ec..181984e 100644 --- a/OpenSim/Region/Environment/Modules/Avatar/Currency/SampleMoney/SampleMoneyModule.cs +++ b/OpenSim/Region/Environment/Modules/Avatar/Currency/SampleMoney/SampleMoneyModule.cs @@ -53,7 +53,6 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Currency.SampleMoney /// Centralized grid structure example using OpenSimWi Redux revision 9+ /// svn co https://opensimwiredux.svn.sourceforge.net/svnroot/opensimwiredux /// - public delegate void ObjectPaid(LLUUID objectID, LLUUID agentID, int amount); public interface IMoneyModule : IRegionModule @@ -65,37 +64,39 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Currency.SampleMoney public class SampleMoneyModule : IMoneyModule { - public event ObjectPaid OnObjectPaid; - - private ObjectPaid handerOnObjectPaid; - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - /// - /// Region UUIDS indexed by AgentID - /// - Dictionary m_rootAgents = new Dictionary(); - + /// - /// Scenes by Region Handle + /// Where Stipends come from and Fees go to. /// - private Dictionary m_scenel = new Dictionary(); + private LLUUID EconomyBaseAccount = LLUUID.Zero; + + private float EnergyEfficiency = 0f; + private bool gridmode = false; + private ObjectPaid handerOnObjectPaid; + private bool m_enabled = true; private IConfigSource m_gConfig; private bool m_keepMoneyAcrossLogins = true; + private Dictionary m_KnownClientFunds = new Dictionary(); + private string m_LandAddress = String.Empty; private int m_minFundsBeforeRefresh = 100; + private string m_MoneyAddress = String.Empty; - private int m_stipend = 1000; + /// + /// Region UUIDS indexed by AgentID + /// + private Dictionary m_rootAgents = new Dictionary(); - private bool m_enabled = true; + /// + /// Scenes by Region Handle + /// + private Dictionary m_scenel = new Dictionary(); - private Dictionary m_KnownClientFunds = new Dictionary(); + private int m_stipend = 1000; - private bool gridmode = false; - private Scene XMLRPCHandler; - private float EnergyEfficiency = 0f; private int ObjectCapacity = 45000; private int ObjectCount = 0; private int PriceEnergyUnit = 0; @@ -111,16 +112,14 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Currency.SampleMoney private int PriceRentLight = 0; private int PriceUpload = 0; private int TeleportMinPrice = 0; + + private float TeleportPriceExponent = 0f; private int UserLevelPaysFees = 2; - private string m_MoneyAddress = String.Empty; - private string m_LandAddress = String.Empty; + private Scene XMLRPCHandler; - float TeleportPriceExponent = 0f; + #region IMoneyModule Members - /// - /// Where Stipends come from and Fees go to. - /// - LLUUID EconomyBaseAccount = LLUUID.Zero; + public event ObjectPaid OnObjectPaid; /// /// Startup @@ -130,12 +129,12 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Currency.SampleMoney public void Initialise(Scene scene, IConfigSource config) { m_gConfig = config; - + IConfig startupConfig = m_gConfig.Configs["Startup"]; IConfig economyConfig = m_gConfig.Configs["Economy"]; - + scene.RegisterModuleInterface(this); - + ReadConfigAndPopulate(scene, startupConfig, "Startup"); ReadConfigAndPopulate(scene, economyConfig, "Economy"); @@ -167,8 +166,6 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Currency.SampleMoney scene.AddXmlRPCHandler("preflightBuyLandPrep", preflightBuyLandPrep_func); scene.AddXmlRPCHandler("buyLandPrep", landBuy_func); } - - } if (m_scenel.ContainsKey(scene.RegionInfo.RegionHandle)) @@ -180,7 +177,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Currency.SampleMoney m_scenel.Add(scene.RegionInfo.RegionHandle, scene); } } - + scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnMoneyTransfer += MoneyTransferAction; scene.EventManager.OnClientClosed += ClientClosed; @@ -189,9 +186,41 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Currency.SampleMoney scene.EventManager.OnClientClosed += ClientLoggedOut; scene.EventManager.OnValidateLandBuy += ValidateLandBuy; scene.EventManager.OnLandBuy += processLandBuy; - } } + + public bool ObjectGiveMoney(LLUUID objectID, LLUUID fromID, LLUUID toID, int amount) + { + string description = String.Format("Object {0} pays {1}", resolveObjectName(objectID), resolveAgentName(toID)); + + bool give_result = doMoneyTransfer(fromID, toID, amount, 2, description); + + if (m_MoneyAddress.Length == 0) + BalanceUpdate(fromID, toID, give_result, description); + + return give_result; + } + + public void PostInitialise() + { + } + + public void Close() + { + } + + public string Name + { + get { return "BetaGridLikeMoneyModule"; } + } + + public bool IsSharedModule + { + get { return true; } + } + + #endregion + /// /// Parse Configuration /// @@ -207,7 +236,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Currency.SampleMoney } if (config == "Economy" && startupConfig != null) - { + { ObjectCapacity = startupConfig.GetInt("ObjectCapacity", 45000); PriceEnergyUnit = startupConfig.GetInt("PriceEnergyUnit", 100); PriceObjectClaim = startupConfig.GetInt("PriceObjectClaim", 10); @@ -225,7 +254,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Currency.SampleMoney PriceParcelRent = startupConfig.GetInt("PriceParcelRent", 1); PriceGroupCreate = startupConfig.GetInt("PriceGroupCreate", -1); string EBA = startupConfig.GetString("EconomyBaseAccount", LLUUID.Zero.ToString()); - Helpers.TryParse(EBA,out EconomyBaseAccount); + Helpers.TryParse(EBA, out EconomyBaseAccount); UserLevelPaysFees = startupConfig.GetInt("UserLevelPaysFees", -1); m_stipend = startupConfig.GetInt("UserStipend", 500); @@ -234,7 +263,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Currency.SampleMoney m_MoneyAddress = startupConfig.GetString("CurrencyServer", String.Empty); m_LandAddress = startupConfig.GetString("LandServer", String.Empty); } - + // Send ObjectCapacity to Scene.. Which sends it to the SimStatsReporter. scene.SetObjectCapacity(ObjectCapacity); } @@ -253,7 +282,6 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Currency.SampleMoney { if (m_MoneyAddress.Length == 0) { - CheckExistAndRefreshFunds(client.AgentId); } else @@ -273,15 +301,16 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Currency.SampleMoney //s.RegionInfo.RegionHandle; LLUUID agentID = LLUUID.Zero; int funds = 0; - - Hashtable hbinfo = GetBalanceForUserFromMoneyServer(client.AgentId, client.SecureSessionId, s.RegionInfo.originRegionID.ToString(), s.RegionInfo.regionSecret); - if ((bool)hbinfo["success"] == true) - { - Helpers.TryParse((string)hbinfo["agentId"], out agentID); + Hashtable hbinfo = + GetBalanceForUserFromMoneyServer(client.AgentId, client.SecureSessionId, s.RegionInfo.originRegionID.ToString(), + s.RegionInfo.regionSecret); + if ((bool) hbinfo["success"] == true) + { + Helpers.TryParse((string) hbinfo["agentId"], out agentID); try { - funds = (Int32)hbinfo["funds"]; + funds = (Int32) hbinfo["funds"]; } catch (ArgumentException) { @@ -303,1189 +332,1139 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Currency.SampleMoney } else { - m_log.WarnFormat("[MONEY]: Getting Money for user {0} failed with the following message:{1}", agentID, (string)hbinfo["errorMessage"]); - client.SendAlertMessage((string)hbinfo["errorMessage"]); + m_log.WarnFormat("[MONEY]: Getting Money for user {0} failed with the following message:{1}", agentID, + (string) hbinfo["errorMessage"]); + client.SendAlertMessage((string) hbinfo["errorMessage"]); } SendMoneyBalance(client, agentID, client.SessionId, LLUUID.Zero); - } } - } else { CheckExistAndRefreshFunds(client.AgentId); } - + // Subscribe to Money messages client.OnEconomyDataRequest += EconomyDataRequestHandler; client.OnMoneyBalanceRequest += SendMoneyBalance; client.OnRequestPayPrice += requestPayPrice; client.OnLogout += ClientClosed; - - - } - - #region event Handlers - - public void requestPayPrice(IClientAPI client, LLUUID objectID) - { - Scene scene=LocateSceneClientIn(client.AgentId); - if(scene == null) - return; - - SceneObjectPart task=scene.GetSceneObjectPart(objectID); - if(task == null) - return; - SceneObjectGroup group=task.ParentGroup; - SceneObjectPart root=group.RootPart; - - client.SendPayPrice(objectID, root.PayPrice); - } - - /// - /// When the client closes the connection we remove their accounting info from memory to free up resources. - /// - /// - public void ClientClosed(LLUUID AgentID) - { - lock (m_KnownClientFunds) - { - if (m_keepMoneyAcrossLogins && m_MoneyAddress.Length == 0) - { - } - else - { - m_KnownClientFunds.Remove(AgentID); - } - } } /// - /// Event called Economy Data Request handler. + /// Transfer money /// - /// - public void EconomyDataRequestHandler(LLUUID agentId) - { - IClientAPI user = LocateClientObject(agentId); - - if (user != null) - { - user.SendEconomyData(EnergyEfficiency, ObjectCapacity, ObjectCount, PriceEnergyUnit, PriceGroupCreate, - PriceObjectClaim, PriceObjectRent, PriceObjectScaleFactor, PriceParcelClaim, PriceParcelClaimFactor, - PriceParcelRent, PricePublicObjectDecay, PricePublicObjectDelete, PriceRentLight, PriceUpload, - TeleportMinPrice, TeleportPriceExponent); - } - } - - private void ValidateLandBuy (Object osender, EventManager.LandBuyArgs e) + /// + /// + /// + /// + private bool doMoneyTransfer(LLUUID Sender, LLUUID Receiver, int amount, int transactiontype, string description) { - if (m_MoneyAddress.Length == 0) + bool result = false; + if (amount >= 0) { lock (m_KnownClientFunds) { - if (m_KnownClientFunds.ContainsKey(e.agentId)) + // If we don't know about the sender, then the sender can't + // actually be here and therefore this is likely fraud or outdated. + if (m_MoneyAddress.Length == 0) { - // Does the sender have enough funds to give? - if (m_KnownClientFunds[e.agentId] >= e.parcelPrice) + if (m_KnownClientFunds.ContainsKey(Sender)) { - lock(e) + // Does the sender have enough funds to give? + if (m_KnownClientFunds[Sender] >= amount) + { + // Subtract the funds from the senders account + m_KnownClientFunds[Sender] -= amount; + + // do we know about the receiver? + if (!m_KnownClientFunds.ContainsKey(Receiver)) + { + // Make a record for them so they get the updated balance when they login + CheckExistAndRefreshFunds(Receiver); + } + if (m_enabled) + { + //Add the amount to the Receiver's funds + m_KnownClientFunds[Receiver] += amount; + result = true; + } + } + else { - e.economyValidated=true; + // These below are redundant to make this clearer to read + result = false; } } + else + { + result = false; + } } - } - } - else - { - if(GetRemoteBalance(e.agentId) >= e.parcelPrice) - { - lock(e) + else { - e.economyValidated=true; + result = TransferMoneyonMoneyServer(Sender, Receiver, amount, transactiontype, description); } } } + return result; } - private void processLandBuy(Object osender, EventManager.LandBuyArgs e) + + /// + /// Sends the the stored money balance to the client + /// + /// + /// + /// + /// + public void SendMoneyBalance(IClientAPI client, LLUUID agentID, LLUUID SessionID, LLUUID TransactionID) { - lock(e) + if (client.AgentId == agentID && client.SessionId == SessionID) { - if(e.economyValidated == true && e.transactionID == 0) - { - e.transactionID=Util.UnixTimeSinceEpoch(); + int returnfunds = 0; - if(doMoneyTransfer(e.agentId, e.parcelOwnerID, e.parcelPrice, 0, "Land purchase")) - { - lock (e) - { - e.amountDebited = e.parcelPrice; - } - } + try + { + returnfunds = GetFundsForAgentID(agentID); + } + catch (Exception e) + { + client.SendAlertMessage(e.Message + " "); } + + client.SendMoneyBalance(TransactionID, true, new byte[0], returnfunds); + } + else + { + client.SendAlertMessage("Unable to send your money balance to you!"); } } /// - /// THis method gets called when someone pays someone else as a gift. + /// Gets the current balance for the user from the Grid Money Server /// - /// - /// - private void MoneyTransferAction (Object osender, EventManager.MoneyTransferArgs e) + /// + /// + /// + /// + /// + public Hashtable GetBalanceForUserFromMoneyServer(LLUUID agentId, LLUUID secureSessionID, LLUUID regionId, string regionSecret) { - IClientAPI sender = null; - IClientAPI receiver = null; - - if(m_MoneyAddress.Length > 0) // Handled on server - e.description=String.Empty; - - if(e.transactiontype == 5008) // Object gets paid - { - sender = LocateClientObject(e.sender); - if (sender != null) - { - SceneObjectPart part=findPrim(e.receiver); - if(part == null) - return; - - string name=resolveAgentName(part.OwnerID); - if(name == String.Empty) - name="(hippos)"; + Hashtable MoneyBalanceRequestParams = new Hashtable(); + MoneyBalanceRequestParams["agentId"] = agentId.ToString(); + MoneyBalanceRequestParams["secureSessionId"] = secureSessionID.ToString(); + MoneyBalanceRequestParams["regionId"] = regionId.ToString(); + MoneyBalanceRequestParams["secret"] = regionSecret; + MoneyBalanceRequestParams["currencySecret"] = ""; // per - region/user currency secret gotten from the money system - receiver = LocateClientObject(part.OwnerID); + Hashtable MoneyRespData = genericCurrencyXMLRPCRequest(MoneyBalanceRequestParams, "simulatorUserBalanceRequest"); - string description=String.Format("Paid {0} via object {1}", name, e.description); - bool transactionresult = doMoneyTransfer(e.sender, part.OwnerID, e.amount, e.transactiontype, description); + return MoneyRespData; + } - if(transactionresult) - { - ObjectPaid handlerOnObjectPaid = OnObjectPaid; - if(handlerOnObjectPaid != null) - { - handlerOnObjectPaid(e.receiver, e.sender, e.amount); - } - } - if (e.sender != e.receiver) - { - sender.SendMoneyBalance(LLUUID.Random(), transactionresult, Helpers.StringToField(e.description), GetFundsForAgentID(e.sender)); - } - if(receiver != null) - { - receiver.SendMoneyBalance(LLUUID.Random(), transactionresult, Helpers.StringToField(e.description), GetFundsForAgentID(part.OwnerID)); - } - } - return; + /// + /// Generic XMLRPC client abstraction + /// + /// Hashtable containing parameters to the method + /// Method to invoke + /// Hashtable with success=>bool and other values + public Hashtable genericCurrencyXMLRPCRequest(Hashtable ReqParams, string method) + { + ArrayList SendParams = new ArrayList(); + SendParams.Add(ReqParams); + // Send Request + XmlRpcResponse MoneyResp; + try + { + XmlRpcRequest BalanceRequestReq = new XmlRpcRequest(method, SendParams); + MoneyResp = BalanceRequestReq.Send(m_MoneyAddress, 30000); } + catch (WebException ex) + { + m_log.ErrorFormat( + "[MONEY]: Unable to connect to Money Server {0}. Exception {1}", + m_MoneyAddress, ex); - sender = LocateClientObject(e.sender); - if (sender != null) + Hashtable ErrorHash = new Hashtable(); + ErrorHash["success"] = false; + ErrorHash["errorMessage"] = "Unable to manage your money at this time. Purchases may be unavailable"; + ErrorHash["errorURI"] = ""; + + return ErrorHash; + //throw (ex); + } + catch (SocketException ex) { - receiver = LocateClientObject(e.receiver); + m_log.ErrorFormat( + "[MONEY]: Unable to connect to Money Server {0}. Exception {1}", + m_MoneyAddress, ex); - bool transactionresult = doMoneyTransfer(e.sender, e.receiver, e.amount, e.transactiontype, e.description); + Hashtable ErrorHash = new Hashtable(); + ErrorHash["success"] = false; + ErrorHash["errorMessage"] = "Unable to manage your money at this time. Purchases may be unavailable"; + ErrorHash["errorURI"] = ""; - if (e.sender != e.receiver) - { - if (sender != null) - { - sender.SendMoneyBalance(LLUUID.Random(), transactionresult, Helpers.StringToField(e.description), GetFundsForAgentID(e.sender)); - } - } + return ErrorHash; + //throw (ex); + } + catch (XmlException ex) + { + m_log.ErrorFormat( + "[MONEY]: Unable to connect to Money Server {0}. Exception {1}", + m_MoneyAddress, ex); - if (receiver != null) - { - receiver.SendMoneyBalance(LLUUID.Random(), transactionresult, Helpers.StringToField(e.description), GetFundsForAgentID(e.receiver)); - } + Hashtable ErrorHash = new Hashtable(); + ErrorHash["success"] = false; + ErrorHash["errorMessage"] = "Unable to manage your money at this time. Purchases may be unavailable"; + ErrorHash["errorURI"] = ""; + + return ErrorHash; } - else + if (MoneyResp.IsFault) { - m_log.Warn("[MONEY]: Potential Fraud Warning, got money transfer request for avatar that isn't in this simulator - Details; Sender:" + e.sender.ToString() + " Receiver: " + e.receiver.ToString() + " Amount: " + e.amount.ToString()); + Hashtable ErrorHash = new Hashtable(); + ErrorHash["success"] = false; + ErrorHash["errorMessage"] = "Unable to manage your money at this time. Purchases may be unavailable"; + ErrorHash["errorURI"] = ""; + + return ErrorHash; } + Hashtable MoneyRespData = (Hashtable) MoneyResp.Value; + + return MoneyRespData; } /// - /// Event Handler for when a root agent becomes a child agent + /// This informs the Money Grid Server that the avatar is in this simulator /// - /// - private void MakeChildAgent(ScenePresence avatar) + /// + /// + /// + /// + /// + public Hashtable claim_user(LLUUID agentId, LLUUID secureSessionID, LLUUID regionId, string regionSecret) { - lock (m_rootAgents) + Hashtable MoneyBalanceRequestParams = new Hashtable(); + MoneyBalanceRequestParams["agentId"] = agentId.ToString(); + MoneyBalanceRequestParams["secureSessionId"] = secureSessionID.ToString(); + MoneyBalanceRequestParams["regionId"] = regionId.ToString(); + MoneyBalanceRequestParams["secret"] = regionSecret; + + Hashtable MoneyRespData = genericCurrencyXMLRPCRequest(MoneyBalanceRequestParams, "simulatorClaimUserRequest"); + IClientAPI sendMoneyBal = LocateClientObject(agentId); + if (sendMoneyBal != null) { - if (m_rootAgents.ContainsKey(avatar.UUID)) + SendMoneyBalance(sendMoneyBal, agentId, sendMoneyBal.SessionId, LLUUID.Zero); + } + return MoneyRespData; + } + + private SceneObjectPart findPrim(LLUUID objectID) + { + lock (m_scenel) + { + foreach (Scene s in m_scenel.Values) { - if (m_rootAgents[avatar.UUID] == avatar.Scene.RegionInfo.originRegionID) + SceneObjectPart part = s.GetSceneObjectPart(objectID); + if (part != null) { - m_rootAgents.Remove(avatar.UUID); - m_log.Info("[MONEY]: Removing " + avatar.Firstname + " " + avatar.Lastname + " as a root agent"); + return part; } - } } - + return null; } - /// - /// Event Handler for when the client logs out. - /// - /// - private void ClientLoggedOut(LLUUID AgentId) + private string resolveObjectName(LLUUID objectID) { - lock (m_rootAgents) + SceneObjectPart part = findPrim(objectID); + if (part != null) { - if (m_rootAgents.ContainsKey(AgentId)) - { - m_rootAgents.Remove(AgentId); - //m_log.Info("[MONEY]: Removing " + AgentId + ". Agent logged out."); - } + return part.Name; } + return String.Empty; } - /// - /// Call this when the client disconnects. - /// - /// - public void ClientClosed(IClientAPI client) + private string resolveAgentName(LLUUID agentID) { - ClientClosed(client.AgentId); + // try avatar username surname + Scene scene = GetRandomScene(); + UserProfileData profile = scene.CommsManager.UserService.GetUserProfile(agentID); + if (profile != null) + { + string avatarname = profile.FirstName + " " + profile.SurName; + return avatarname; + } + return String.Empty; } - /// - /// Event Handler for when an Avatar enters one of the parcels in the simulator. - /// - /// - /// - /// - private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, LLUUID regionID) + private void BalanceUpdate(LLUUID senderID, LLUUID receiverID, bool transactionresult, string description) { - lock (m_rootAgents) + IClientAPI sender = LocateClientObject(senderID); + IClientAPI receiver = LocateClientObject(receiverID); + + if (senderID != receiverID) { - if (m_rootAgents.ContainsKey(avatar.UUID)) + if (sender != null) { - if (avatar.Scene.RegionInfo.originRegionID != m_rootAgents[avatar.UUID]) - { - m_rootAgents[avatar.UUID] = avatar.Scene.RegionInfo.originRegionID; - //m_log.Info("[MONEY]: Claiming " + avatar.Firstname + " " + avatar.Lastname + " in region:" + avatar.RegionHandle + "."); - // Claim User! my user! Mine mine mine! - if (m_MoneyAddress.Length > 0) - { - Scene RegionItem = GetSceneByUUID(regionID); - if (RegionItem != null) - { - Hashtable hresult = claim_user(avatar.UUID, avatar.ControllingClient.SecureSessionId, regionID, RegionItem.RegionInfo.regionSecret); - if ((bool)hresult["success"] == true) - { - int funds = 0; - try - { - funds = (Int32)hresult["funds"]; - } - catch (InvalidCastException) - { - - } - SetLocalFundsForAgentID(avatar.UUID, funds); - } - else - { - avatar.ControllingClient.SendAgentAlertMessage((string)hresult["errorMessage"], true); - } - } - } - } + sender.SendMoneyBalance(LLUUID.Random(), transactionresult, Helpers.StringToField(description), GetFundsForAgentID(senderID)); } - else - { - lock (m_rootAgents) - { - m_rootAgents.Add(avatar.UUID, avatar.Scene.RegionInfo.originRegionID); - } - if (m_MoneyAddress.Length > 0) - { - Scene RegionItem = GetSceneByUUID(regionID); - if (RegionItem != null) - { - Hashtable hresult = claim_user(avatar.UUID, avatar.ControllingClient.SecureSessionId, regionID, RegionItem.RegionInfo.regionSecret); - if ((bool)hresult["success"] == true) - { - int funds = 0; - try - { - funds = (Int32)hresult["funds"]; - } - catch (InvalidCastException) - { - } - SetLocalFundsForAgentID(avatar.UUID, funds); - } - else - { - avatar.ControllingClient.SendAgentAlertMessage((string)hresult["errorMessage"], true); - } - } - } - - //m_log.Info("[MONEY]: Claiming " + avatar.Firstname + " " + avatar.Lastname + " in region:" + avatar.RegionHandle + "."); + if (receiver != null) + { + receiver.SendMoneyBalance(LLUUID.Random(), transactionresult, Helpers.StringToField(description), GetFundsForAgentID(receiverID)); } } - //m_log.Info("[FRIEND]: " + avatar.Name + " status:" + (!avatar.IsChildAgent).ToString()); } - #endregion - /// - /// Transfer money + /// Informs the Money Grid Server of a transfer. /// - /// - /// + /// + /// /// /// - private bool doMoneyTransfer(LLUUID Sender, LLUUID Receiver, int amount, int transactiontype, string description) + public bool TransferMoneyonMoneyServer(LLUUID sourceId, LLUUID destId, int amount, int transactiontype, string description) { - bool result = false; - if (amount >= 0) + int aggregatePermInventory = 0; + int aggregatePermNextOwner = 0; + int flags = 0; + bool rvalue = false; + + IClientAPI cli = LocateClientObject(sourceId); + if (cli != null) { - lock (m_KnownClientFunds) + Scene userScene = null; + lock (m_rootAgents) { - // If we don't know about the sender, then the sender can't - // actually be here and therefore this is likely fraud or outdated. - if (m_MoneyAddress.Length == 0) - { - if (m_KnownClientFunds.ContainsKey(Sender)) - { - // Does the sender have enough funds to give? - if (m_KnownClientFunds[Sender] >= amount) - { - // Subtract the funds from the senders account - m_KnownClientFunds[Sender] -= amount; - - // do we know about the receiver? - if (!m_KnownClientFunds.ContainsKey(Receiver)) - { - // Make a record for them so they get the updated balance when they login - CheckExistAndRefreshFunds(Receiver); - } - if (m_enabled) - { - //Add the amount to the Receiver's funds - m_KnownClientFunds[Receiver] += amount; - result = true; - } + userScene = GetSceneByUUID(m_rootAgents[sourceId]); + } + if (userScene != null) + { + Hashtable ht = new Hashtable(); + ht["agentId"] = sourceId.ToString(); + ht["secureSessionId"] = cli.SecureSessionId.ToString(); + ht["regionId"] = userScene.RegionInfo.originRegionID.ToString(); + ht["secret"] = userScene.RegionInfo.regionSecret; + ht["currencySecret"] = " "; + ht["destId"] = destId.ToString(); + ht["cash"] = amount; + ht["aggregatePermInventory"] = aggregatePermInventory; + ht["aggregatePermNextOwner"] = aggregatePermNextOwner; + ht["flags"] = flags; + ht["transactionType"] = transactiontype; + ht["description"] = description; + + Hashtable hresult = genericCurrencyXMLRPCRequest(ht, "regionMoveMoney"); + + if ((bool) hresult["success"] == true) + { + int funds1 = 0; + int funds2 = 0; + try + { + funds1 = (Int32) hresult["funds"]; + } + catch (InvalidCastException) + { + funds1 = 0; + } + SetLocalFundsForAgentID(sourceId, funds1); + if (m_KnownClientFunds.ContainsKey(destId)) + { + try + { + funds2 = (Int32) hresult["funds2"]; } - else + catch (InvalidCastException) { - // These below are redundant to make this clearer to read - result = false; + funds2 = 0; } + SetLocalFundsForAgentID(destId, funds2); } - else - { - result = false; - } + + + rvalue = true; } else { - result = TransferMoneyonMoneyServer(Sender, Receiver, amount, transactiontype, description); + cli.SendAgentAlertMessage((string) hresult["errorMessage"], true); } } } - return result; + else + { + m_log.ErrorFormat("[MONEY]: Client {0} not found", sourceId.ToString()); + } + + return rvalue; } - #region Utility Helpers - /// - /// Locates a IClientAPI for the client specified - /// - /// - /// - private IClientAPI LocateClientObject(LLUUID AgentID) + public int GetRemoteBalance(LLUUID agentId) { - ScenePresence tPresence = null; - IClientAPI rclient = null; + int funds = 0; - lock (m_scenel) + IClientAPI aClient = LocateClientObject(agentId); + if (aClient != null) { - foreach (Scene _scene in m_scenel.Values) + Scene s = LocateSceneClientIn(agentId); + if (s != null) { - tPresence = _scene.GetScenePresence(AgentID); - if (tPresence != null) + if (m_MoneyAddress.Length > 0) { - if (!tPresence.IsChildAgent) + Hashtable hbinfo = + GetBalanceForUserFromMoneyServer(aClient.AgentId, aClient.SecureSessionId, s.RegionInfo.originRegionID.ToString(), + s.RegionInfo.regionSecret); + if ((bool) hbinfo["success"] == true) { - rclient = tPresence.ControllingClient; + try + { + funds = (Int32) hbinfo["funds"]; + } + catch (ArgumentException) + { + } + catch (FormatException) + { + } + catch (OverflowException) + { + m_log.ErrorFormat("[MONEY]: While getting the Currency for user {0}, the return funds overflowed.", agentId); + aClient.SendAlertMessage("Unable to get your money balance, money operations will be unavailable"); + } + catch (InvalidCastException) + { + funds = 0; + } + } + else + { + m_log.WarnFormat("[MONEY]: Getting Money for user {0} failed with the following message:{1}", agentId, + (string) hbinfo["errorMessage"]); + aClient.SendAlertMessage((string) hbinfo["errorMessage"]); } } - if (rclient != null) - { - return rclient; - } - } + SetLocalFundsForAgentID(agentId, funds); + SendMoneyBalance(aClient, agentId, aClient.SessionId, LLUUID.Zero); + } + else + { + m_log.Debug("[MONEY]: Got balance request update for agent that is here, but couldn't find which scene."); + } } - return null; + else + { + m_log.Debug("[MONEY]: Got balance request update for agent that isn't here."); + } + return funds; } - private Scene LocateSceneClientIn(LLUUID AgentId) + public XmlRpcResponse GridMoneyUpdate(XmlRpcRequest request) { - lock (m_scenel) + m_log.Debug("[MONEY]: Dynamic balance update called."); + Hashtable requestData = (Hashtable) request.Params[0]; + + if (requestData.ContainsKey("agentId")) { - foreach (Scene _scene in m_scenel.Values) - { - ScenePresence tPresence = _scene.GetScenePresence(AgentId); - if (tPresence != null) - { - if (!tPresence.IsChildAgent) - { - return _scene; - } - } + LLUUID agentId = LLUUID.Zero; + Helpers.TryParse((string) requestData["agentId"], out agentId); + if (agentId != LLUUID.Zero) + { + GetRemoteBalance(agentId); + } + else + { + m_log.Debug("[MONEY]: invalid agentId specified, dropping."); } - } - return null; - } - - /// - /// Utility function Gets a Random scene in the instance. For when which scene exactly you're doing something with doesn't matter - /// - /// - public Scene GetRandomScene() - { - lock (m_scenel) + else { - foreach (Scene rs in m_scenel.Values) - return rs; + m_log.Debug("[MONEY]: no agentId specified, dropping."); } - return null; + XmlRpcResponse r = new XmlRpcResponse(); + Hashtable rparms = new Hashtable(); + rparms["success"] = true; + r.Value = rparms; + return r; } + /// - /// Utility function to get a Scene by RegionID in a module + /// XMLRPC handler to send alert message and sound to client /// - /// - /// - public Scene GetSceneByUUID(LLUUID RegionID) + public XmlRpcResponse UserAlert(XmlRpcRequest request) { - lock (m_scenel) - { - foreach (Scene rs in m_scenel.Values) - { - if (rs.RegionInfo.originRegionID == RegionID) - { - return rs; - } - } - } - return null; - } - #endregion + XmlRpcResponse ret = new XmlRpcResponse(); + Hashtable retparam = new Hashtable(); + Hashtable requestData = (Hashtable) request.Params[0]; + LLUUID agentId = LLUUID.Zero; + LLUUID soundId = LLUUID.Zero; + Helpers.TryParse((string) requestData["agentId"], out agentId); + Helpers.TryParse((string) requestData["soundId"], out soundId); + string text = (string) requestData["text"]; + string secret = (string) requestData["secret"]; - /// - /// Sends the the stored money balance to the client - /// - /// - /// - /// - /// - public void SendMoneyBalance(IClientAPI client, LLUUID agentID, LLUUID SessionID, LLUUID TransactionID) - { - if (client.AgentId == agentID && client.SessionId == SessionID) + Scene userScene = GetRandomScene(); + if (userScene.RegionInfo.regionSecret.ToString() == secret) { - int returnfunds = 0; - - try + IClientAPI client = LocateClientObject(agentId); + + if (client != null) { - returnfunds = GetFundsForAgentID(agentID); + if (soundId != LLUUID.Zero) + client.SendPlayAttachedSound(soundId, LLUUID.Zero, LLUUID.Zero, 1.0f, 0); + client.SendBlueBoxMessage(LLUUID.Zero, LLUUID.Zero, "", text); + retparam.Add("success", true); } - catch (Exception e) + else { - client.SendAlertMessage(e.Message + " "); + retparam.Add("success", false); } - - client.SendMoneyBalance(TransactionID, true, new byte[0], returnfunds); } else { - client.SendAlertMessage("Unable to send your money balance to you!"); + retparam.Add("success", false); } + ret.Value = retparam; + + return ret; } - #region local Fund Management - /// - /// Ensures that the agent accounting data is set up in this instance. - /// - /// - private void CheckExistAndRefreshFunds(LLUUID agentID) + # region Standalone box enablers only + + public XmlRpcResponse quote_func(XmlRpcRequest request) { - lock (m_KnownClientFunds) + Hashtable requestData = (Hashtable) request.Params[0]; + LLUUID agentId = LLUUID.Zero; + int amount = 0; + Hashtable quoteResponse = new Hashtable(); + XmlRpcResponse returnval = new XmlRpcResponse(); + + if (requestData.ContainsKey("agentId") && requestData.ContainsKey("currencyBuy")) { - if (!m_KnownClientFunds.ContainsKey(agentID)) + Helpers.TryParse((string) requestData["agentId"], out agentId); + try { - m_KnownClientFunds.Add(agentID, m_stipend); + amount = (Int32) requestData["currencyBuy"]; } - else + catch (InvalidCastException) { - if (m_KnownClientFunds[agentID] <= m_minFundsBeforeRefresh) - { - m_KnownClientFunds[agentID] = m_stipend; - } } - } - } - /// - /// Gets the amount of Funds for an agent - /// - /// - /// - private int GetFundsForAgentID(LLUUID AgentID) - { - int returnfunds = 0; - lock (m_KnownClientFunds) - { - if (m_KnownClientFunds.ContainsKey(AgentID)) - { - returnfunds = m_KnownClientFunds[AgentID]; - } - else - { - //throw new Exception("Unable to get funds."); - } - } - return returnfunds; - } - private void SetLocalFundsForAgentID(LLUUID AgentID, int amount) - { - lock (m_KnownClientFunds) - { - if (m_KnownClientFunds.ContainsKey(AgentID)) - { - m_KnownClientFunds[AgentID] = amount; - } - else - { - m_KnownClientFunds.Add(AgentID, amount); - } - } - - } - - #endregion - - /// - /// Gets the current balance for the user from the Grid Money Server - /// - /// - /// - /// - /// - /// - public Hashtable GetBalanceForUserFromMoneyServer(LLUUID agentId, LLUUID secureSessionID, LLUUID regionId, string regionSecret) - { - - Hashtable MoneyBalanceRequestParams = new Hashtable(); - MoneyBalanceRequestParams["agentId"] = agentId.ToString(); - MoneyBalanceRequestParams["secureSessionId"] = secureSessionID.ToString(); - MoneyBalanceRequestParams["regionId"] = regionId.ToString(); - MoneyBalanceRequestParams["secret"] = regionSecret; - MoneyBalanceRequestParams["currencySecret"] = ""; // per - region/user currency secret gotten from the money system - - Hashtable MoneyRespData = genericCurrencyXMLRPCRequest(MoneyBalanceRequestParams, "simulatorUserBalanceRequest"); - - return MoneyRespData; - } - - - - /// - /// Generic XMLRPC client abstraction - /// - /// Hashtable containing parameters to the method - /// Method to invoke - /// Hashtable with success=>bool and other values - public Hashtable genericCurrencyXMLRPCRequest(Hashtable ReqParams, string method) - { - ArrayList SendParams = new ArrayList(); - SendParams.Add(ReqParams); - // Send Request - XmlRpcResponse MoneyResp; - try - { - XmlRpcRequest BalanceRequestReq = new XmlRpcRequest(method, SendParams); - MoneyResp = BalanceRequestReq.Send(m_MoneyAddress, 30000); - } - catch (WebException ex) - { - - m_log.ErrorFormat( - "[MONEY]: Unable to connect to Money Server {0}. Exception {1}", - m_MoneyAddress, ex); - - Hashtable ErrorHash = new Hashtable(); - ErrorHash["success"] = false; - ErrorHash["errorMessage"] = "Unable to manage your money at this time. Purchases may be unavailable"; - ErrorHash["errorURI"] = ""; - - return ErrorHash; - //throw (ex); - } - catch (SocketException ex) - { - - m_log.ErrorFormat( - "[MONEY]: Unable to connect to Money Server {0}. Exception {1}", - m_MoneyAddress, ex); - - Hashtable ErrorHash = new Hashtable(); - ErrorHash["success"] = false; - ErrorHash["errorMessage"] = "Unable to manage your money at this time. Purchases may be unavailable"; - ErrorHash["errorURI"] = ""; - - return ErrorHash; - //throw (ex); - } - catch (XmlException ex) - { - m_log.ErrorFormat( - "[MONEY]: Unable to connect to Money Server {0}. Exception {1}", - m_MoneyAddress, ex); - - Hashtable ErrorHash = new Hashtable(); - ErrorHash["success"] = false; - ErrorHash["errorMessage"] = "Unable to manage your money at this time. Purchases may be unavailable"; - ErrorHash["errorURI"] = ""; - - return ErrorHash; - - } - if (MoneyResp.IsFault) - { - Hashtable ErrorHash = new Hashtable(); - ErrorHash["success"] = false; - ErrorHash["errorMessage"] = "Unable to manage your money at this time. Purchases may be unavailable"; - ErrorHash["errorURI"] = ""; + Hashtable currencyResponse = new Hashtable(); + currencyResponse.Add("estimatedCost", 0); + currencyResponse.Add("currencyBuy", amount); - return ErrorHash; + quoteResponse.Add("success", true); + quoteResponse.Add("currency", currencyResponse); + quoteResponse.Add("confirm", "asdfad9fj39ma9fj"); + returnval.Value = quoteResponse; + return returnval; } - Hashtable MoneyRespData = (Hashtable)MoneyResp.Value; - - return MoneyRespData; - } - /// - /// This informs the Money Grid Server that the avatar is in this simulator - /// - /// - /// - /// - /// - /// - public Hashtable claim_user(LLUUID agentId, LLUUID secureSessionID, LLUUID regionId, string regionSecret) - { - Hashtable MoneyBalanceRequestParams = new Hashtable(); - MoneyBalanceRequestParams["agentId"] = agentId.ToString(); - MoneyBalanceRequestParams["secureSessionId"] = secureSessionID.ToString(); - MoneyBalanceRequestParams["regionId"] = regionId.ToString(); - MoneyBalanceRequestParams["secret"] = regionSecret; - Hashtable MoneyRespData = genericCurrencyXMLRPCRequest(MoneyBalanceRequestParams, "simulatorClaimUserRequest"); - IClientAPI sendMoneyBal = LocateClientObject(agentId); - if (sendMoneyBal != null) - { - SendMoneyBalance(sendMoneyBal, agentId, sendMoneyBal.SessionId, LLUUID.Zero); - } - return MoneyRespData; + quoteResponse.Add("success", false); + quoteResponse.Add("errorMessage", "Invalid parameters passed to the quote box"); + quoteResponse.Add("errorURI", "http://www.opensimulator.org/wiki"); + returnval.Value = quoteResponse; + return returnval; } - private SceneObjectPart findPrim(LLUUID objectID) + public XmlRpcResponse buy_func(XmlRpcRequest request) { - lock (m_scenel) + Hashtable requestData = (Hashtable) request.Params[0]; + LLUUID agentId = LLUUID.Zero; + int amount = 0; + if (requestData.ContainsKey("agentId") && requestData.ContainsKey("currencyBuy")) { - foreach (Scene s in m_scenel.Values) + Helpers.TryParse((string) requestData["agentId"], out agentId); + try + { + amount = (Int32) requestData["currencyBuy"]; + } + catch (InvalidCastException) { - SceneObjectPart part=s.GetSceneObjectPart(objectID); - if(part != null) + } + if (agentId != LLUUID.Zero) + { + lock (m_KnownClientFunds) { - return part; + if (m_KnownClientFunds.ContainsKey(agentId)) + { + m_KnownClientFunds[agentId] += amount; + } + else + { + m_KnownClientFunds.Add(agentId, amount); + } + } + IClientAPI client = LocateClientObject(agentId); + if (client != null) + { + SendMoneyBalance(client, agentId, client.SessionId, LLUUID.Zero); } } } - return null; - } - - private string resolveObjectName(LLUUID objectID) - { - SceneObjectPart part=findPrim(objectID); - if(part != null) - { - return part.Name; - } - return String.Empty; + XmlRpcResponse returnval = new XmlRpcResponse(); + Hashtable returnresp = new Hashtable(); + returnresp.Add("success", true); + returnval.Value = returnresp; + return returnval; } - private string resolveAgentName(LLUUID agentID) + public XmlRpcResponse preflightBuyLandPrep_func(XmlRpcRequest request) { - // try avatar username surname - Scene scene=GetRandomScene(); - UserProfileData profile = scene.CommsManager.UserService.GetUserProfile(agentID); - if (profile != null) - { - string avatarname = profile.FirstName + " " + profile.SurName; - return avatarname; - } - return String.Empty; - } + XmlRpcResponse ret = new XmlRpcResponse(); + Hashtable retparam = new Hashtable(); + Hashtable membershiplevels = new Hashtable(); + ArrayList levels = new ArrayList(); + Hashtable level = new Hashtable(); + level.Add("id", "00000000-0000-0000-0000-000000000000"); + level.Add("description", "some level"); + levels.Add(level); + //membershiplevels.Add("levels",levels); - public bool ObjectGiveMoney(LLUUID objectID, LLUUID fromID, LLUUID toID, int amount) - { - string description=String.Format("Object {0} pays {1}", resolveObjectName(objectID), resolveAgentName(toID)); + Hashtable landuse = new Hashtable(); + landuse.Add("upgrade", false); + landuse.Add("action", "http://invaliddomaininvalid.com/"); - bool give_result = doMoneyTransfer(fromID, toID, amount, 2, description); + Hashtable currency = new Hashtable(); + currency.Add("estimatedCost", 0); - if (m_MoneyAddress.Length == 0) - BalanceUpdate(fromID, toID, give_result, description); + Hashtable membership = new Hashtable(); + membershiplevels.Add("upgrade", false); + membershiplevels.Add("action", "http://invaliddomaininvalid.com/"); + membershiplevels.Add("levels", membershiplevels); - return give_result; + retparam.Add("success", true); + retparam.Add("currency", currency); + retparam.Add("membership", membership); + retparam.Add("landuse", landuse); + retparam.Add("confirm", "asdfajsdkfjasdkfjalsdfjasdf"); + ret.Value = retparam; + return ret; } - private void BalanceUpdate(LLUUID senderID, LLUUID receiverID, bool transactionresult, string description) + + public XmlRpcResponse landBuy_func(XmlRpcRequest request) { - IClientAPI sender = LocateClientObject(senderID); - IClientAPI receiver = LocateClientObject(receiverID); + XmlRpcResponse ret = new XmlRpcResponse(); + Hashtable retparam = new Hashtable(); + Hashtable requestData = (Hashtable) request.Params[0]; - if (senderID != receiverID) + LLUUID agentId = LLUUID.Zero; + int amount = 0; + if (requestData.ContainsKey("agentId") && requestData.ContainsKey("currencyBuy")) { - if (sender != null) + Helpers.TryParse((string) requestData["agentId"], out agentId); + try { - sender.SendMoneyBalance(LLUUID.Random(), transactionresult, Helpers.StringToField(description), GetFundsForAgentID(senderID)); + amount = (Int32) requestData["currencyBuy"]; } - - if (receiver != null) + catch (InvalidCastException) { - receiver.SendMoneyBalance(LLUUID.Random(), transactionresult, Helpers.StringToField(description), GetFundsForAgentID(receiverID)); + } + if (agentId != LLUUID.Zero) + { + lock (m_KnownClientFunds) + { + if (m_KnownClientFunds.ContainsKey(agentId)) + { + m_KnownClientFunds[agentId] += amount; + } + else + { + m_KnownClientFunds.Add(agentId, amount); + } + } + IClientAPI client = LocateClientObject(agentId); + if (client != null) + { + SendMoneyBalance(client, agentId, client.SessionId, LLUUID.Zero); + } } } + retparam.Add("success", true); + ret.Value = retparam; + + return ret; } + #endregion + + #region local Fund Management + /// - /// Informs the Money Grid Server of a transfer. + /// Ensures that the agent accounting data is set up in this instance. /// - /// - /// - /// - /// - public bool TransferMoneyonMoneyServer(LLUUID sourceId, LLUUID destId, int amount, int transactiontype, string description) + /// + private void CheckExistAndRefreshFunds(LLUUID agentID) { - int aggregatePermInventory = 0; - int aggregatePermNextOwner = 0; - int flags = 0; - bool rvalue = false; - - IClientAPI cli = LocateClientObject(sourceId); - if (cli != null) + lock (m_KnownClientFunds) { - - Scene userScene = null; - lock (m_rootAgents) + if (!m_KnownClientFunds.ContainsKey(agentID)) { - userScene = GetSceneByUUID(m_rootAgents[sourceId]); + m_KnownClientFunds.Add(agentID, m_stipend); } - if (userScene != null) - { - Hashtable ht = new Hashtable(); - ht["agentId"] = sourceId.ToString(); - ht["secureSessionId"] = cli.SecureSessionId.ToString(); - ht["regionId"] = userScene.RegionInfo.originRegionID.ToString(); - ht["secret"] = userScene.RegionInfo.regionSecret; - ht["currencySecret"] = " "; - ht["destId"] = destId.ToString(); - ht["cash"] = amount; - ht["aggregatePermInventory"] = aggregatePermInventory; - ht["aggregatePermNextOwner"] = aggregatePermNextOwner; - ht["flags"] = flags; - ht["transactionType"] = transactiontype; - ht["description"] = description; - - Hashtable hresult = genericCurrencyXMLRPCRequest(ht, "regionMoveMoney"); - - if ((bool)hresult["success"] == true) - { - int funds1 = 0; - int funds2 = 0; - try - { - funds1 = (Int32)hresult["funds"]; - } - catch(InvalidCastException) - { - funds1 = 0; - } - SetLocalFundsForAgentID(sourceId, funds1); - if (m_KnownClientFunds.ContainsKey(destId)) - { - try - { - funds2 = (Int32)hresult["funds2"]; - } - catch (InvalidCastException) - { - funds2 = 0; - } - SetLocalFundsForAgentID(destId, funds2); - } - - - rvalue = true; - } - else + else + { + if (m_KnownClientFunds[agentID] <= m_minFundsBeforeRefresh) { - cli.SendAgentAlertMessage((string)hresult["errorMessage"], true); + m_KnownClientFunds[agentID] = m_stipend; } - } } - else - { - m_log.ErrorFormat("[MONEY]: Client {0} not found", sourceId.ToString()); - } - - return rvalue; - } - public int GetRemoteBalance(LLUUID agentId) + /// + /// Gets the amount of Funds for an agent + /// + /// + /// + private int GetFundsForAgentID(LLUUID AgentID) { - int funds = 0; - - IClientAPI aClient = LocateClientObject(agentId); - if (aClient != null) + int returnfunds = 0; + lock (m_KnownClientFunds) { - Scene s = LocateSceneClientIn(agentId); - if (s != null) + if (m_KnownClientFunds.ContainsKey(AgentID)) { - if (m_MoneyAddress.Length > 0) - { - Hashtable hbinfo = GetBalanceForUserFromMoneyServer(aClient.AgentId, aClient.SecureSessionId, s.RegionInfo.originRegionID.ToString(), s.RegionInfo.regionSecret); - if ((bool)hbinfo["success"] == true) - { - try - { - funds = (Int32)hbinfo["funds"]; - } - catch (ArgumentException) - { - } - catch (FormatException) - { - } - catch (OverflowException) - { - m_log.ErrorFormat("[MONEY]: While getting the Currency for user {0}, the return funds overflowed.", agentId); - aClient.SendAlertMessage("Unable to get your money balance, money operations will be unavailable"); - } - catch (InvalidCastException) - { - funds = 0; - } - - } - else - { - m_log.WarnFormat("[MONEY]: Getting Money for user {0} failed with the following message:{1}", agentId, (string)hbinfo["errorMessage"]); - aClient.SendAlertMessage((string)hbinfo["errorMessage"]); - } - } - - SetLocalFundsForAgentID(agentId, funds); - SendMoneyBalance(aClient, agentId, aClient.SessionId, LLUUID.Zero); + returnfunds = m_KnownClientFunds[AgentID]; } else { - m_log.Debug("[MONEY]: Got balance request update for agent that is here, but couldn't find which scene."); + //throw new Exception("Unable to get funds."); } } - else - { - m_log.Debug("[MONEY]: Got balance request update for agent that isn't here."); - } - return funds; + return returnfunds; } - public XmlRpcResponse GridMoneyUpdate(XmlRpcRequest request) + private void SetLocalFundsForAgentID(LLUUID AgentID, int amount) { - m_log.Debug("[MONEY]: Dynamic balance update called."); - Hashtable requestData = (Hashtable)request.Params[0]; - - if (requestData.ContainsKey("agentId")) + lock (m_KnownClientFunds) { - LLUUID agentId = LLUUID.Zero; - - Helpers.TryParse((string)requestData["agentId"], out agentId); - if (agentId != LLUUID.Zero) + if (m_KnownClientFunds.ContainsKey(AgentID)) { - GetRemoteBalance(agentId); - + m_KnownClientFunds[AgentID] = amount; } else { - m_log.Debug("[MONEY]: invalid agentId specified, dropping."); + m_KnownClientFunds.Add(AgentID, amount); } } - else - { - m_log.Debug("[MONEY]: no agentId specified, dropping."); - } - XmlRpcResponse r = new XmlRpcResponse(); - Hashtable rparms = new Hashtable(); - rparms["success"] = true; - - r.Value = rparms; - return r; } + #endregion + + #region Utility Helpers + /// - /// XMLRPC handler to send alert message and sound to client + /// Locates a IClientAPI for the client specified /// - public XmlRpcResponse UserAlert(XmlRpcRequest request) + /// + /// + private IClientAPI LocateClientObject(LLUUID AgentID) { - XmlRpcResponse ret = new XmlRpcResponse(); - Hashtable retparam = new Hashtable(); - Hashtable requestData = (Hashtable)request.Params[0]; - - LLUUID agentId = LLUUID.Zero; - LLUUID soundId = LLUUID.Zero; - - Helpers.TryParse((string)requestData["agentId"], out agentId); - Helpers.TryParse((string)requestData["soundId"], out soundId); - string text=(string)requestData["text"]; - string secret=(string)requestData["secret"]; + ScenePresence tPresence = null; + IClientAPI rclient = null; - Scene userScene = GetRandomScene(); - if(userScene.RegionInfo.regionSecret.ToString() == secret) + lock (m_scenel) { - IClientAPI client = LocateClientObject(agentId); - - if (client != null) + foreach (Scene _scene in m_scenel.Values) { - if(soundId != LLUUID.Zero) - client.SendPlayAttachedSound(soundId, LLUUID.Zero, LLUUID.Zero, 1.0f, 0); - client.SendBlueBoxMessage(LLUUID.Zero, LLUUID.Zero, "", text); - retparam.Add("success", true); + tPresence = _scene.GetScenePresence(AgentID); + if (tPresence != null) + { + if (!tPresence.IsChildAgent) + { + rclient = tPresence.ControllingClient; + } + } + if (rclient != null) + { + return rclient; + } } - else + } + return null; + } + + private Scene LocateSceneClientIn(LLUUID AgentId) + { + lock (m_scenel) + { + foreach (Scene _scene in m_scenel.Values) { - retparam.Add("success", false); + ScenePresence tPresence = _scene.GetScenePresence(AgentId); + if (tPresence != null) + { + if (!tPresence.IsChildAgent) + { + return _scene; + } + } } } - else + return null; + } + + /// + /// Utility function Gets a Random scene in the instance. For when which scene exactly you're doing something with doesn't matter + /// + /// + public Scene GetRandomScene() + { + lock (m_scenel) { - retparam.Add("success", false); + foreach (Scene rs in m_scenel.Values) + return rs; } - ret.Value = retparam; + return null; + } - return ret; + /// + /// Utility function to get a Scene by RegionID in a module + /// + /// + /// + public Scene GetSceneByUUID(LLUUID RegionID) + { + lock (m_scenel) + { + foreach (Scene rs in m_scenel.Values) + { + if (rs.RegionInfo.originRegionID == RegionID) + { + return rs; + } + } + } + return null; } + #endregion - # region Standalone box enablers only + #region event Handlers - public XmlRpcResponse quote_func(XmlRpcRequest request) + public void requestPayPrice(IClientAPI client, LLUUID objectID) { - Hashtable requestData = (Hashtable)request.Params[0]; - LLUUID agentId = LLUUID.Zero; - int amount = 0; - Hashtable quoteResponse = new Hashtable(); - XmlRpcResponse returnval = new XmlRpcResponse(); + Scene scene = LocateSceneClientIn(client.AgentId); + if (scene == null) + return; - if (requestData.ContainsKey("agentId") && requestData.ContainsKey("currencyBuy")) + SceneObjectPart task = scene.GetSceneObjectPart(objectID); + if (task == null) + return; + SceneObjectGroup group = task.ParentGroup; + SceneObjectPart root = group.RootPart; + + client.SendPayPrice(objectID, root.PayPrice); + } + + /// + /// When the client closes the connection we remove their accounting info from memory to free up resources. + /// + /// + public void ClientClosed(LLUUID AgentID) + { + lock (m_KnownClientFunds) { - Helpers.TryParse((string)requestData["agentId"], out agentId); - try + if (m_keepMoneyAcrossLogins && m_MoneyAddress.Length == 0) { - amount = (Int32)requestData["currencyBuy"]; } - catch (InvalidCastException) + else { - + m_KnownClientFunds.Remove(AgentID); } - Hashtable currencyResponse = new Hashtable(); - currencyResponse.Add("estimatedCost", 0); - currencyResponse.Add("currencyBuy", amount); - - quoteResponse.Add("success", true); - quoteResponse.Add("currency", currencyResponse); - quoteResponse.Add("confirm", "asdfad9fj39ma9fj"); - - returnval.Value = quoteResponse; - return returnval; } - - - - quoteResponse.Add("success", false); - quoteResponse.Add("errorMessage", "Invalid parameters passed to the quote box"); - quoteResponse.Add("errorURI", "http://www.opensimulator.org/wiki"); - returnval.Value = quoteResponse; - return returnval; } - public XmlRpcResponse buy_func(XmlRpcRequest request) + + /// + /// Event called Economy Data Request handler. + /// + /// + public void EconomyDataRequestHandler(LLUUID agentId) { + IClientAPI user = LocateClientObject(agentId); - Hashtable requestData = (Hashtable)request.Params[0]; - LLUUID agentId = LLUUID.Zero; - int amount = 0; - if (requestData.ContainsKey("agentId") && requestData.ContainsKey("currencyBuy")) + if (user != null) { - Helpers.TryParse((string)requestData["agentId"], out agentId); - try - { - amount = (Int32)requestData["currencyBuy"]; - } - catch (InvalidCastException) - { + user.SendEconomyData(EnergyEfficiency, ObjectCapacity, ObjectCount, PriceEnergyUnit, PriceGroupCreate, + PriceObjectClaim, PriceObjectRent, PriceObjectScaleFactor, PriceParcelClaim, PriceParcelClaimFactor, + PriceParcelRent, PricePublicObjectDecay, PricePublicObjectDelete, PriceRentLight, PriceUpload, + TeleportMinPrice, TeleportPriceExponent); + } + } - } - if (agentId != LLUUID.Zero) + private void ValidateLandBuy(Object osender, EventManager.LandBuyArgs e) + { + if (m_MoneyAddress.Length == 0) + { + lock (m_KnownClientFunds) { - lock (m_KnownClientFunds) + if (m_KnownClientFunds.ContainsKey(e.agentId)) { - if (m_KnownClientFunds.ContainsKey(agentId)) - { - m_KnownClientFunds[agentId] += amount; - } - else + // Does the sender have enough funds to give? + if (m_KnownClientFunds[e.agentId] >= e.parcelPrice) { - m_KnownClientFunds.Add(agentId, amount); + lock (e) + { + e.economyValidated = true; + } } } - IClientAPI client = LocateClientObject(agentId); - if (client != null) + } + } + else + { + if (GetRemoteBalance(e.agentId) >= e.parcelPrice) + { + lock (e) { - SendMoneyBalance(client, agentId, client.SessionId, LLUUID.Zero); + e.economyValidated = true; } } } - XmlRpcResponse returnval = new XmlRpcResponse(); - Hashtable returnresp = new Hashtable(); - returnresp.Add("success", true); - returnval.Value = returnresp; - return returnval; } - public XmlRpcResponse preflightBuyLandPrep_func(XmlRpcRequest request) + private void processLandBuy(Object osender, EventManager.LandBuyArgs e) { - XmlRpcResponse ret = new XmlRpcResponse(); - Hashtable retparam = new Hashtable(); - Hashtable membershiplevels = new Hashtable(); - ArrayList levels = new ArrayList(); - Hashtable level = new Hashtable(); - level.Add("id", "00000000-0000-0000-0000-000000000000"); - level.Add("description", "some level"); - levels.Add(level); - //membershiplevels.Add("levels",levels); - - Hashtable landuse = new Hashtable(); - landuse.Add("upgrade", false); - landuse.Add("action", "http://invaliddomaininvalid.com/"); + lock (e) + { + if (e.economyValidated == true && e.transactionID == 0) + { + e.transactionID = Util.UnixTimeSinceEpoch(); - Hashtable currency = new Hashtable(); - currency.Add("estimatedCost", 0); + if (doMoneyTransfer(e.agentId, e.parcelOwnerID, e.parcelPrice, 0, "Land purchase")) + { + lock (e) + { + e.amountDebited = e.parcelPrice; + } + } + } + } + } - Hashtable membership = new Hashtable(); - membershiplevels.Add("upgrade", false); - membershiplevels.Add("action", "http://invaliddomaininvalid.com/"); - membershiplevels.Add("levels", membershiplevels); + /// + /// THis method gets called when someone pays someone else as a gift. + /// + /// + /// + private void MoneyTransferAction(Object osender, EventManager.MoneyTransferArgs e) + { + IClientAPI sender = null; + IClientAPI receiver = null; - retparam.Add("success", true); - retparam.Add("currency", currency); - retparam.Add("membership", membership); - retparam.Add("landuse", landuse); - retparam.Add("confirm", "asdfajsdkfjasdkfjalsdfjasdf"); + if (m_MoneyAddress.Length > 0) // Handled on server + e.description = String.Empty; - ret.Value = retparam; + if (e.transactiontype == 5008) // Object gets paid + { + sender = LocateClientObject(e.sender); + if (sender != null) + { + SceneObjectPart part = findPrim(e.receiver); + if (part == null) + return; - return ret; + string name = resolveAgentName(part.OwnerID); + if (name == String.Empty) + name = "(hippos)"; - } - public XmlRpcResponse landBuy_func(XmlRpcRequest request) - { - XmlRpcResponse ret = new XmlRpcResponse(); - Hashtable retparam = new Hashtable(); - Hashtable requestData = (Hashtable)request.Params[0]; + receiver = LocateClientObject(part.OwnerID); - LLUUID agentId = LLUUID.Zero; - int amount = 0; - if (requestData.ContainsKey("agentId") && requestData.ContainsKey("currencyBuy")) - { - Helpers.TryParse((string)requestData["agentId"], out agentId); - try - { - amount = (Int32)requestData["currencyBuy"]; - } - catch (InvalidCastException) - { + string description = String.Format("Paid {0} via object {1}", name, e.description); + bool transactionresult = doMoneyTransfer(e.sender, part.OwnerID, e.amount, e.transactiontype, description); - } - if (agentId != LLUUID.Zero) - { - lock (m_KnownClientFunds) + if (transactionresult) { - if (m_KnownClientFunds.ContainsKey(agentId)) - { - m_KnownClientFunds[agentId] += amount; - } - else + ObjectPaid handlerOnObjectPaid = OnObjectPaid; + if (handlerOnObjectPaid != null) { - m_KnownClientFunds.Add(agentId, amount); + handlerOnObjectPaid(e.receiver, e.sender, e.amount); } } - IClientAPI client = LocateClientObject(agentId); - if (client != null) + + if (e.sender != e.receiver) { - SendMoneyBalance(client, agentId, client.SessionId, LLUUID.Zero); + sender.SendMoneyBalance(LLUUID.Random(), transactionresult, Helpers.StringToField(e.description), GetFundsForAgentID(e.sender)); + } + if (receiver != null) + { + receiver.SendMoneyBalance(LLUUID.Random(), transactionresult, Helpers.StringToField(e.description), GetFundsForAgentID(part.OwnerID)); } } + return; } - retparam.Add("success", true); - ret.Value = retparam; - return ret; + sender = LocateClientObject(e.sender); + if (sender != null) + { + receiver = LocateClientObject(e.receiver); + + bool transactionresult = doMoneyTransfer(e.sender, e.receiver, e.amount, e.transactiontype, e.description); + + if (e.sender != e.receiver) + { + if (sender != null) + { + sender.SendMoneyBalance(LLUUID.Random(), transactionresult, Helpers.StringToField(e.description), GetFundsForAgentID(e.sender)); + } + } + if (receiver != null) + { + receiver.SendMoneyBalance(LLUUID.Random(), transactionresult, Helpers.StringToField(e.description), GetFundsForAgentID(e.receiver)); + } + } + else + { + m_log.Warn("[MONEY]: Potential Fraud Warning, got money transfer request for avatar that isn't in this simulator - Details; Sender:" + + e.sender.ToString() + " Receiver: " + e.receiver.ToString() + " Amount: " + e.amount.ToString()); + } } - #endregion - public void PostInitialise() + /// + /// Event Handler for when a root agent becomes a child agent + /// + /// + private void MakeChildAgent(ScenePresence avatar) { + lock (m_rootAgents) + { + if (m_rootAgents.ContainsKey(avatar.UUID)) + { + if (m_rootAgents[avatar.UUID] == avatar.Scene.RegionInfo.originRegionID) + { + m_rootAgents.Remove(avatar.UUID); + m_log.Info("[MONEY]: Removing " + avatar.Firstname + " " + avatar.Lastname + " as a root agent"); + } + } + } } - public void Close() + /// + /// Event Handler for when the client logs out. + /// + /// + private void ClientLoggedOut(LLUUID AgentId) { + lock (m_rootAgents) + { + if (m_rootAgents.ContainsKey(AgentId)) + { + m_rootAgents.Remove(AgentId); + //m_log.Info("[MONEY]: Removing " + AgentId + ". Agent logged out."); + } + } } - public string Name + /// + /// Call this when the client disconnects. + /// + /// + public void ClientClosed(IClientAPI client) { - get { return "BetaGridLikeMoneyModule"; } + ClientClosed(client.AgentId); } - public bool IsSharedModule + /// + /// Event Handler for when an Avatar enters one of the parcels in the simulator. + /// + /// + /// + /// + private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, LLUUID regionID) { - get { return true; } + lock (m_rootAgents) + { + if (m_rootAgents.ContainsKey(avatar.UUID)) + { + if (avatar.Scene.RegionInfo.originRegionID != m_rootAgents[avatar.UUID]) + { + m_rootAgents[avatar.UUID] = avatar.Scene.RegionInfo.originRegionID; + //m_log.Info("[MONEY]: Claiming " + avatar.Firstname + " " + avatar.Lastname + " in region:" + avatar.RegionHandle + "."); + // Claim User! my user! Mine mine mine! + if (m_MoneyAddress.Length > 0) + { + Scene RegionItem = GetSceneByUUID(regionID); + if (RegionItem != null) + { + Hashtable hresult = + claim_user(avatar.UUID, avatar.ControllingClient.SecureSessionId, regionID, RegionItem.RegionInfo.regionSecret); + if ((bool) hresult["success"] == true) + { + int funds = 0; + try + { + funds = (Int32) hresult["funds"]; + } + catch (InvalidCastException) + { + } + SetLocalFundsForAgentID(avatar.UUID, funds); + } + else + { + avatar.ControllingClient.SendAgentAlertMessage((string) hresult["errorMessage"], true); + } + } + } + } + } + else + { + lock (m_rootAgents) + { + m_rootAgents.Add(avatar.UUID, avatar.Scene.RegionInfo.originRegionID); + } + if (m_MoneyAddress.Length > 0) + { + Scene RegionItem = GetSceneByUUID(regionID); + if (RegionItem != null) + { + Hashtable hresult = claim_user(avatar.UUID, avatar.ControllingClient.SecureSessionId, regionID, RegionItem.RegionInfo.regionSecret); + if ((bool) hresult["success"] == true) + { + int funds = 0; + try + { + funds = (Int32) hresult["funds"]; + } + catch (InvalidCastException) + { + } + SetLocalFundsForAgentID(avatar.UUID, funds); + } + else + { + avatar.ControllingClient.SendAgentAlertMessage((string) hresult["errorMessage"], true); + } + } + } + + //m_log.Info("[MONEY]: Claiming " + avatar.Firstname + " " + avatar.Lastname + " in region:" + avatar.RegionHandle + "."); + } + } + //m_log.Info("[FRIEND]: " + avatar.Name + " status:" + (!avatar.IsChildAgent).ToString()); } + + #endregion } public enum TransactionType : int { - SystemGenerated=0, - RegionMoneyRequest=1, - Gift=2, - Purchase=3 - + SystemGenerated = 0, + RegionMoneyRequest = 1, + Gift = 2, + Purchase = 3 } } \ No newline at end of file diff --git a/OpenSim/Region/Environment/Modules/Avatar/Friends/FriendsModule.cs b/OpenSim/Region/Environment/Modules/Avatar/Friends/FriendsModule.cs index 3b0cc4c..db38d87 100644 --- a/OpenSim/Region/Environment/Modules/Avatar/Friends/FriendsModule.cs +++ b/OpenSim/Region/Environment/Modules/Avatar/Friends/FriendsModule.cs @@ -42,13 +42,12 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + private Dictionary> FriendLists = new Dictionary>(); + private Dictionary m_pendingFriendRequests = new Dictionary(); + private Dictionary m_rootAgents = new Dictionary(); private List m_scene = new List(); - Dictionary m_rootAgents = new Dictionary(); - - Dictionary m_pendingFriendRequests = new Dictionary(); - - Dictionary> FriendLists = new Dictionary>(); + #region IRegionModule Members public void Initialise(Scene scene, IConfigSource config) { @@ -68,11 +67,33 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends scene.EventManager.OnMakeChildAgent += MakeChildAgent; scene.EventManager.OnClientClosed += ClientLoggedOut; } + + public void PostInitialise() + { + } + + public void Close() + { + } + + public string Name + { + get { return "FriendsModule"; } + } + + public bool IsSharedModule + { + get { return true; } + } + + #endregion + public XmlRpcResponse processPresenceUpdate(XmlRpcRequest req) { m_log.Info("[FRIENDS]: Got Notification about a user! OMG"); return new XmlRpcResponse(); } + private void OnNewClient(IClientAPI client) { // All friends establishment protocol goes over instant message @@ -83,7 +104,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends // Generated by LoginService. The friends are retreived from the database by the UserManager // Subscribe to instant messages - + client.OnInstantMessage += OnInstantMessage; client.OnApproveFriendRequest += OnApprovedFriendRequest; client.OnDenyFriendRequest += OnDenyFriendRequest; @@ -99,10 +120,10 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends { fl = FriendLists[client.AgentId]; } - else + else { fl = m_scene[0].GetFriendList(client.AgentId); - + //lock (FriendLists) //{ if (!FriendLists.ContainsKey(client.AgentId)) @@ -110,11 +131,11 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends //} } } - + List UpdateUsers = new List(); foreach (FriendListItem f in fl) - { + { if (m_rootAgents.ContainsKey(f.Friend)) { if (f.onlinestatus == false) @@ -169,10 +190,6 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends onp.AgentBlock = onpb; client.OutPacket(onp, ThrottleOutPacketType.Task); } - - - - } private void ClientLoggedOut(LLUUID AgentId) @@ -182,7 +199,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends if (m_rootAgents.ContainsKey(AgentId)) { m_rootAgents.Remove(AgentId); - m_log.Info("[FRIEND]: Removing " + AgentId + ". Agent logged out."); + m_log.Info("[FRIEND]: Removing " + AgentId + ". Agent logged out."); } } List lfli = new List(); @@ -208,7 +225,6 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends List flfli = new List(); try { - lock (FriendLists) { if (FriendLists.ContainsKey(updateUsers[i])) @@ -231,9 +247,8 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends { flfli[i].onlinestatus = false; } - } - + catch (IndexOutOfRangeException) { // Ignore the index out of range exception. @@ -242,15 +257,13 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends m_log.Info("[FRIEND]: Unable to enumerate last friendlist user. User logged off"); } } - } - + for (int i = 0; i < updateUsers.Count; i++) { ScenePresence av = GetPresenceFromAgentID(updateUsers[i]); if (av != null) { - OfflineNotificationPacket onp = new OfflineNotificationPacket(); OfflineNotificationPacket.AgentBlockBlock[] onpb = new OfflineNotificationPacket.AgentBlockBlock[1]; OfflineNotificationPacket.AgentBlockBlock onpbl = new OfflineNotificationPacket.AgentBlockBlock(); @@ -265,7 +278,6 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends { FriendLists.Remove(AgentId); } - } private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, LLUUID regionID) @@ -282,7 +294,6 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends { JId avatarID = new JId(avatar.JID); // REST Post XMPP Stanzas! - } // Claim User! my user! Mine mine mine! } @@ -295,9 +306,9 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends } //m_log.Info("[FRIEND]: " + avatar.Name + " status:" + (!avatar.IsChildAgent).ToString()); } + private void MakeChildAgent(ScenePresence avatar) { - lock (m_rootAgents) { if (m_rootAgents.ContainsKey(avatar.UUID)) @@ -307,30 +318,53 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends m_rootAgents.Remove(avatar.UUID); m_log.Info("[FRIEND]: Removing " + avatar.Firstname + " " + avatar.Lastname + " as a root agent"); } - } } + } + private ScenePresence GetPresenceFromAgentID(LLUUID AgentID) + { + ScenePresence returnAgent = null; + lock (m_scene) + { + ScenePresence queryagent = null; + for (int i = 0; i < m_scene.Count; i++) + { + queryagent = m_scene[i].GetScenePresence(AgentID); + if (queryagent != null) + { + if (!queryagent.IsChildAgent) + { + returnAgent = queryagent; + break; + } + } + } + } + return returnAgent; } + #region FriendRequestHandling - private void OnInstantMessage(IClientAPI client,LLUUID fromAgentID, + + private void OnInstantMessage(IClientAPI client, LLUUID fromAgentID, LLUUID fromAgentSession, LLUUID toAgentID, LLUUID imSessionID, uint timestamp, string fromAgentName, - string message, byte dialog, bool fromGroup, byte offline, - uint ParentEstateID, LLVector3 Position, LLUUID RegionID, + string message, byte dialog, bool fromGroup, byte offline, + uint ParentEstateID, LLVector3 Position, LLUUID RegionID, byte[] binaryBucket) { // Friend Requests go by Instant Message.. using the dialog param // https://wiki.secondlife.com/wiki/ImprovedInstantMessage // 38 == Offer friendship - if (dialog == (byte)38) + if (dialog == (byte) 38) { LLUUID friendTransactionID = LLUUID.Random(); m_pendingFriendRequests.Add(friendTransactionID, fromAgentID); - m_log.Info("[FRIEND]: 38 - From:" + fromAgentID.ToString() + " To: " + toAgentID.ToString() + " Session:" + imSessionID.ToString() + " Message:" + message); + m_log.Info("[FRIEND]: 38 - From:" + fromAgentID.ToString() + " To: " + toAgentID.ToString() + " Session:" + imSessionID.ToString() + " Message:" + + message); GridInstantMessage msg = new GridInstantMessage(); msg.fromAgentID = fromAgentID.UUID; msg.fromAgentSession = fromAgentSession.UUID; @@ -340,11 +374,11 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends msg.timestamp = timestamp; if (client != null) { - msg.fromAgentName = client.FirstName + " " + client.LastName;// fromAgentName; + msg.fromAgentName = client.FirstName + " " + client.LastName; // fromAgentName; } else { - msg.fromAgentName = "(hippos)";// Added for posterity. This means that we can't figure out who sent it + msg.fromAgentName = "(hippos)"; // Added for posterity. This means that we can't figure out who sent it } msg.message = message; msg.dialog = dialog; @@ -359,15 +393,17 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends } // 39 == Accept Friendship - if (dialog == (byte)39) + if (dialog == (byte) 39) { - m_log.Info("[FRIEND]: 39 - From:" + fromAgentID.ToString() + " To: " + toAgentID.ToString() + " Session:" + imSessionID.ToString() + " Message:" + message); + m_log.Info("[FRIEND]: 39 - From:" + fromAgentID.ToString() + " To: " + toAgentID.ToString() + " Session:" + imSessionID.ToString() + " Message:" + + message); } // 40 == Decline Friendship - if (dialog == (byte)40) + if (dialog == (byte) 40) { - m_log.Info("[FRIEND]: 40 - From:" + fromAgentID.ToString() + " To: " + toAgentID.ToString() + " Session:" + imSessionID.ToString() + " Message:" + message); + m_log.Info("[FRIEND]: 40 - From:" + fromAgentID.ToString() + " To: " + toAgentID.ToString() + " Session:" + imSessionID.ToString() + " Message:" + + message); } } @@ -395,16 +431,16 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends msg.imSessionID = transactionID.UUID; msg.message = agentID.UUID.ToString(); msg.ParentEstateID = 0; - msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); + msg.timestamp = (uint) Util.UnixTimeSinceEpoch(); msg.RegionID = SceneAgentIn.RegionInfo.RegionID.UUID; - msg.dialog = (byte)39;// Approved friend request + msg.dialog = (byte) 39; // Approved friend request msg.Position = new sLLVector3(); - msg.offline = (byte)0; + msg.offline = (byte) 0; msg.binaryBucket = new byte[0]; // We don't really care which scene we pipe it through, it goes to the shared IM Module and/or the database SceneAgentIn.TriggerGridInstantMessage(msg, InstantMessageReceiver.IMModule); - SceneAgentIn.StoreAddFriendship(m_pendingFriendRequests[transactionID], agentID, (uint)1); + SceneAgentIn.StoreAddFriendship(m_pendingFriendRequests[transactionID], agentID, (uint) 1); m_pendingFriendRequests.Remove(transactionID); // TODO: Inform agent that the friend is online @@ -433,11 +469,11 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends msg.imSessionID = transactionID.UUID; msg.message = agentID.UUID.ToString(); msg.ParentEstateID = 0; - msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); + msg.timestamp = (uint) Util.UnixTimeSinceEpoch(); msg.RegionID = SceneAgentIn.RegionInfo.RegionID.UUID; - msg.dialog = (byte)40;// Deny friend request + msg.dialog = (byte) 40; // Deny friend request msg.Position = new sLLVector3(); - msg.offline = (byte)0; + msg.offline = (byte) 0; msg.binaryBucket = new byte[0]; SceneAgentIn.TriggerGridInstantMessage(msg, InstantMessageReceiver.IMModule); m_pendingFriendRequests.Remove(transactionID); @@ -453,52 +489,13 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Friends private void OnGridInstantMessage(GridInstantMessage msg) { // Trigger the above event handler - OnInstantMessage(null,new LLUUID(msg.fromAgentID), new LLUUID(msg.fromAgentSession), + OnInstantMessage(null, new LLUUID(msg.fromAgentID), new LLUUID(msg.fromAgentSession), new LLUUID(msg.toAgentID), new LLUUID(msg.imSessionID), msg.timestamp, msg.fromAgentName, msg.message, msg.dialog, msg.fromGroup, msg.offline, msg.ParentEstateID, new LLVector3(msg.Position.x, msg.Position.y, msg.Position.z), new LLUUID(msg.RegionID), msg.binaryBucket); } - #endregion - private ScenePresence GetPresenceFromAgentID(LLUUID AgentID) - { - ScenePresence returnAgent = null; - lock (m_scene) - { - ScenePresence queryagent = null; - for (int i = 0; i < m_scene.Count; i++) - { - queryagent = m_scene[i].GetScenePresence(AgentID); - if (queryagent != null) - { - if (!queryagent.IsChildAgent) - { - returnAgent = queryagent; - break; - } - } - } - } - return returnAgent; - - } - - public void PostInitialise() - { - } - - public void Close() - { - } - public string Name - { - get { return "FriendsModule"; } - } - - public bool IsSharedModule - { - get { return true; } - } + #endregion } } \ No newline at end of file diff --git a/OpenSim/Region/Environment/Modules/Avatar/Groups/GroupsModule.cs b/OpenSim/Region/Environment/Modules/Avatar/Groups/GroupsModule.cs index 4b28ad7..c4906d2 100644 --- a/OpenSim/Region/Environment/Modules/Avatar/Groups/GroupsModule.cs +++ b/OpenSim/Region/Environment/Modules/Avatar/Groups/GroupsModule.cs @@ -41,10 +41,12 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Groups { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - private List m_scene = new List(); - private Dictionary m_iclientmap = new Dictionary(); - private Dictionary m_groupmap = new Dictionary(); private Dictionary m_grouplistmap = new Dictionary(); + private Dictionary m_groupmap = new Dictionary(); + private Dictionary m_iclientmap = new Dictionary(); + private List m_scene = new List(); + + #region IRegionModule Members public void Initialise(Scene scene, IConfigSource config) { @@ -58,6 +60,42 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Groups //scene.EventManager. } + public void PostInitialise() + { + } + + public void Close() + { + m_log.Info("[GROUP]: Shutting down group module."); + lock (m_iclientmap) + { + m_iclientmap.Clear(); + } + + lock (m_groupmap) + { + m_groupmap.Clear(); + } + + lock (m_grouplistmap) + { + m_grouplistmap.Clear(); + } + GC.Collect(); + } + + public string Name + { + get { return "GroupsModule"; } + } + + public bool IsSharedModule + { + get { return true; } + } + + #endregion + private void OnNewClient(IClientAPI client) { // All friends establishment protocol goes over instant message @@ -115,7 +153,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Groups string ActiveGroupTitle = ""; bool foundUser = false; - + lock (m_iclientmap) { if (m_iclientmap.ContainsKey(remoteClient.AgentId)) @@ -139,11 +177,9 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Groups } //remoteClient.SendAgentDataUpdate(AgentID, ActiveGroupID, firstname, lastname, ActiveGroupPowers, ActiveGroupName, ActiveGroupTitle); - } } } - } private void OnInstantMessage(IClientAPI client, LLUUID fromAgentID, @@ -183,7 +219,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Groups m_iclientmap.Remove(agentID); } } - + lock (m_groupmap) { if (m_groupmap.ContainsKey(agentID)) @@ -191,7 +227,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Groups m_groupmap.Remove(agentID); } } - + lock (m_grouplistmap) { if (m_grouplistmap.ContainsKey(agentID)) @@ -201,63 +237,16 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Groups } GC.Collect(); } - - public void PostInitialise() - { - } - - public void Close() - { - m_log.Info("[GROUP]: Shutting down group module."); - lock (m_iclientmap) - { - m_iclientmap.Clear(); - } - - lock (m_groupmap) - { - m_groupmap.Clear(); - } - - lock (m_grouplistmap) - { - m_grouplistmap.Clear(); - } - GC.Collect(); - } - - public string Name - { - get { return "GroupsModule"; } - } - - public bool IsSharedModule - { - get { return true; } - } - } public class GroupData { + public string ActiveGroupTitle; public LLUUID GroupID; + public List GroupMembers; public string groupName; - public string ActiveGroupTitle; + public uint groupPowers = (uint) (GroupPowers.LandAllowLandmark | GroupPowers.LandAllowSetHome); public List GroupTitles; - public List GroupMembers; - public uint groupPowers = (uint)(GroupPowers.LandAllowLandmark | GroupPowers.LandAllowSetHome); - - public GroupPowers ActiveGroupPowers - { - set - { - groupPowers = (uint) value; - } - get - { - return (GroupPowers)groupPowers; - } - } public GroupData() { @@ -265,11 +254,17 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Groups GroupMembers = new List(); } + public GroupPowers ActiveGroupPowers + { + set { groupPowers = (uint) value; } + get { return (GroupPowers) groupPowers; } + } } public class GroupList { public List m_GroupList; + public GroupList() { m_GroupList = new List(); diff --git a/OpenSim/Region/Environment/Modules/Avatar/InstantMessage/InstantMessageModule.cs b/OpenSim/Region/Environment/Modules/Avatar/InstantMessage/InstantMessageModule.cs index 1b82837..cb58b4c 100644 --- a/OpenSim/Region/Environment/Modules/Avatar/InstantMessage/InstantMessageModule.cs +++ b/OpenSim/Region/Environment/Modules/Avatar/InstantMessage/InstantMessageModule.cs @@ -38,6 +38,8 @@ namespace OpenSim.Region.Environment.Modules.Avatar.InstantMessage { private readonly List m_scenes = new List(); + #region IRegionModule Members + public void Initialise(Scene scene, IConfigSource config) { lock (m_scenes) @@ -56,27 +58,47 @@ namespace OpenSim.Region.Environment.Modules.Avatar.InstantMessage } } + public void PostInitialise() + { + } + + public void Close() + { + } + + public string Name + { + get { return "InstantMessageModule"; } + } + + public bool IsSharedModule + { + get { return true; } + } + + #endregion + private void OnNewClient(IClientAPI client) { client.OnInstantMessage += OnInstantMessage; } - private void OnInstantMessage(IClientAPI client,LLUUID fromAgentID, + private void OnInstantMessage(IClientAPI client, LLUUID fromAgentID, LLUUID fromAgentSession, LLUUID toAgentID, LLUUID imSessionID, uint timestamp, string fromAgentName, - string message, byte dialog, bool fromGroup, byte offline, - uint ParentEstateID, LLVector3 Position, LLUUID RegionID, + string message, byte dialog, bool fromGroup, byte offline, + uint ParentEstateID, LLVector3 Position, LLUUID RegionID, byte[] binaryBucket) { - bool dialogHandledElsewhere + bool dialogHandledElsewhere = ((dialog == 38) || (dialog == 39) || (dialog == 40) - || dialog == (byte)InstantMessageDialog.InventoryOffered - || dialog == (byte)InstantMessageDialog.InventoryAccepted - || dialog == (byte)InstantMessageDialog.InventoryDeclined); + || dialog == (byte) InstantMessageDialog.InventoryOffered + || dialog == (byte) InstantMessageDialog.InventoryAccepted + || dialog == (byte) InstantMessageDialog.InventoryDeclined); // IM dialogs need to be pre-processed and have their sessionID filled by the server // so the sim can match the transaction on the return packet. - + // Don't send a Friend Dialog IM with a LLUUID.Zero session. if (!(dialogHandledElsewhere && imSessionID == LLUUID.Zero)) { @@ -86,7 +108,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.InstantMessage if (scene.Entities.ContainsKey(toAgentID) && scene.Entities[toAgentID] is ScenePresence) { // Local message - ScenePresence user = (ScenePresence)scene.Entities[toAgentID]; + ScenePresence user = (ScenePresence) scene.Entities[toAgentID]; if (!user.IsChildAgent) { user.ControllingClient.SendInstantMessage(fromAgentID, fromAgentSession, message, @@ -104,54 +126,33 @@ namespace OpenSim.Region.Environment.Modules.Avatar.InstantMessage if (scene.Entities.ContainsKey(toAgentID) && scene.Entities[toAgentID] is ScenePresence) { // Local message - ScenePresence user = (ScenePresence)scene.Entities[toAgentID]; - + ScenePresence user = (ScenePresence) scene.Entities[toAgentID]; + user.ControllingClient.SendInstantMessage(fromAgentID, fromAgentSession, message, toAgentID, imSessionID, fromAgentName, dialog, timestamp); // Message sent return; - } } - } // Still here, try send via Grid // TODO } - + // Trusty OSG1 called method. This method also gets called from the FriendsModule // Turns out the sim has to send an instant message to the user to get it to show an accepted friend. private void OnGridInstantMessage(GridInstantMessage msg) { // Trigger the above event handler - OnInstantMessage(null,new LLUUID(msg.fromAgentID), new LLUUID(msg.fromAgentSession), - new LLUUID(msg.toAgentID), new LLUUID(msg.imSessionID), msg.timestamp, msg.fromAgentName, - msg.message, msg.dialog, msg.fromGroup, msg.offline, msg.ParentEstateID, - new LLVector3(msg.Position.x,msg.Position.y,msg.Position.z), new LLUUID(msg.RegionID), + OnInstantMessage(null, new LLUUID(msg.fromAgentID), new LLUUID(msg.fromAgentSession), + new LLUUID(msg.toAgentID), new LLUUID(msg.imSessionID), msg.timestamp, msg.fromAgentName, + msg.message, msg.dialog, msg.fromGroup, msg.offline, msg.ParentEstateID, + new LLVector3(msg.Position.x, msg.Position.y, msg.Position.z), new LLUUID(msg.RegionID), msg.binaryBucket); - - } - - public void PostInitialise() - { - } - - public void Close() - { - } - - public string Name - { - get { return "InstantMessageModule"; } - } - - public bool IsSharedModule - { - get { return true; } } } } \ No newline at end of file diff --git a/OpenSim/Region/Environment/Modules/Avatar/Inventory/InventoryModule.cs b/OpenSim/Region/Environment/Modules/Avatar/Inventory/InventoryModule.cs index 42c6238..2844450 100644 --- a/OpenSim/Region/Environment/Modules/Avatar/Inventory/InventoryModule.cs +++ b/OpenSim/Region/Environment/Modules/Avatar/Inventory/InventoryModule.cs @@ -38,11 +38,9 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Inventory { public class InventoryModule : IRegionModule { - private static readonly ILog m_log - = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private Scene m_scene; - + private static readonly ILog m_log + = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + /// /// We need to keep track of the pending item offers between clients since the itemId offered only /// occurs in the initial offer message, not the accept message. So this dictionary links @@ -50,10 +48,14 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Inventory /// private IDictionary m_pendingOffers = new Dictionary(); + private Scene m_scene; + + #region IRegionModule Members + public void Initialise(Scene scene, IConfigSource config) - { + { m_scene = scene; - scene.EventManager.OnNewClient += OnNewClient; + scene.EventManager.OnNewClient += OnNewClient; } public void PostInitialise() @@ -73,59 +75,61 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Inventory { get { return false; } } - + + #endregion + private void OnNewClient(IClientAPI client) { // Inventory giving is conducted via instant message client.OnInstantMessage += OnInstantMessage; } - + private void OnInstantMessage(IClientAPI client, LLUUID fromAgentID, LLUUID fromAgentSession, LLUUID toAgentID, LLUUID imSessionID, uint timestamp, string fromAgentName, - string message, byte dialog, bool fromGroup, byte offline, - uint ParentEstateID, LLVector3 Position, LLUUID RegionID, + string message, byte dialog, bool fromGroup, byte offline, + uint ParentEstateID, LLVector3 Position, LLUUID RegionID, byte[] binaryBucket) { - if (dialog == (byte)InstantMessageDialog.InventoryOffered) + if (dialog == (byte) InstantMessageDialog.InventoryOffered) { m_log.DebugFormat( - "[AGENT INVENTORY]: Routing inventory offering message from {0}, {1} to {2}", + "[AGENT INVENTORY]: Routing inventory offering message from {0}, {1} to {2}", client.AgentId, client.Name, toAgentID); - + if (m_scene.Entities.ContainsKey(toAgentID) && m_scene.Entities[toAgentID] is ScenePresence) { - ScenePresence user = (ScenePresence)m_scene.Entities[toAgentID]; - + ScenePresence user = (ScenePresence) m_scene.Entities[toAgentID]; + if (!user.IsChildAgent) { //byte[] rawId = new byte[16]; - + // First byte of the array is probably the item type // Next 16 bytes are the UUID //Array.Copy(binaryBucket, 1, rawId, 0, 16); - + //LLUUID itemId = new LLUUID(new Guid(rawId)); LLUUID itemId = new LLUUID(binaryBucket, 1); - + m_log.DebugFormat( "[AGENT INVENTORY]: ItemId for giving is {0}", itemId); - + m_pendingOffers[imSessionID] = itemId; - + user.ControllingClient.SendInstantMessage( - fromAgentID, fromAgentSession, message, toAgentID, imSessionID, fromAgentName, + fromAgentID, fromAgentSession, message, toAgentID, imSessionID, fromAgentName, dialog, timestamp, binaryBucket); - + return; } else { m_log.WarnFormat( - "[AGENT INVENTORY]: Agent {0} targeted for inventory give by {1}, {2} of {3} was a child agent!", + "[AGENT INVENTORY]: Agent {0} targeted for inventory give by {1}, {2} of {3} was a child agent!", toAgentID, client.AgentId, client.Name, message); } - } + } else { m_log.WarnFormat( @@ -133,84 +137,84 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Inventory toAgentID, client.AgentId, client.Name, message); } } - else if (dialog == (byte)InstantMessageDialog.InventoryAccepted) + else if (dialog == (byte) InstantMessageDialog.InventoryAccepted) { m_log.DebugFormat( - "[AGENT INVENTORY]: Routing inventory accepted message from {0}, {1} to {2}", + "[AGENT INVENTORY]: Routing inventory accepted message from {0}, {1} to {2}", client.AgentId, client.Name, toAgentID); - + if (m_scene.Entities.ContainsKey(toAgentID) && m_scene.Entities[toAgentID] is ScenePresence) { - ScenePresence user = (ScenePresence)m_scene.Entities[toAgentID]; - + ScenePresence user = (ScenePresence) m_scene.Entities[toAgentID]; + if (!user.IsChildAgent) { user.ControllingClient.SendInstantMessage( - fromAgentID, fromAgentSession, message, toAgentID, imSessionID, fromAgentName, + fromAgentID, fromAgentSession, message, toAgentID, imSessionID, fromAgentName, dialog, timestamp, binaryBucket); - + if (m_pendingOffers.ContainsKey(imSessionID)) - { + { m_log.DebugFormat( "[AGENT INVENTORY]: Accepted item id {0}", m_pendingOffers[imSessionID]); - + // Since the message originates from the accepting client, the toAgentID is // the agent giving the item. m_scene.GiveInventoryItem(client, toAgentID, m_pendingOffers[imSessionID]); - + m_pendingOffers.Remove(imSessionID); } else { m_log.ErrorFormat( - "[AGENT INVENTORY]: Could not find an item associated with session id {0} to accept", + "[AGENT INVENTORY]: Could not find an item associated with session id {0} to accept", imSessionID); } - + return; } else { m_log.WarnFormat( - "[AGENT INVENTORY]: Agent {0} targeted for inventory give by {1}, {2} of {3} was a child agent!", + "[AGENT INVENTORY]: Agent {0} targeted for inventory give by {1}, {2} of {3} was a child agent!", toAgentID, client.AgentId, client.Name, message); } - } + } else { m_log.WarnFormat( "[AGENT INVENTORY]: Could not find agent {0} for user {1}, {2} to give {3}", toAgentID, client.AgentId, client.Name, message); - } + } } - else if (dialog == (byte)InstantMessageDialog.InventoryDeclined) + else if (dialog == (byte) InstantMessageDialog.InventoryDeclined) { if (m_scene.Entities.ContainsKey(toAgentID) && m_scene.Entities[toAgentID] is ScenePresence) { - ScenePresence user = (ScenePresence)m_scene.Entities[toAgentID]; - + ScenePresence user = (ScenePresence) m_scene.Entities[toAgentID]; + if (!user.IsChildAgent) { user.ControllingClient.SendInstantMessage( - fromAgentID, fromAgentSession, message, toAgentID, imSessionID, fromAgentName, + fromAgentID, fromAgentSession, message, toAgentID, imSessionID, fromAgentName, dialog, timestamp, binaryBucket); - + if (m_pendingOffers.ContainsKey(imSessionID)) - { + { m_log.DebugFormat( "[AGENT INVENTORY]: Declined item id {0}", m_pendingOffers[imSessionID]); - + m_pendingOffers.Remove(imSessionID); } else { m_log.ErrorFormat( - "[AGENT INVENTORY]: Could not find an item associated with session id {0} to decline", + "[AGENT INVENTORY]: Could not find an item associated with session id {0} to decline", imSessionID); - } + } } } - } + } } } } \ No newline at end of file diff --git a/OpenSim/Region/Environment/Modules/Avatar/Profiles/AvatarProfilesModule.cs b/OpenSim/Region/Environment/Modules/Avatar/Profiles/AvatarProfilesModule.cs index f8b14d3..1955d2a 100644 --- a/OpenSim/Region/Environment/Modules/Avatar/Profiles/AvatarProfilesModule.cs +++ b/OpenSim/Region/Environment/Modules/Avatar/Profiles/AvatarProfilesModule.cs @@ -45,6 +45,8 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Profiles { } + #region IRegionModule Members + public void Initialise(Scene scene, IConfigSource config) { m_scene = scene; @@ -69,6 +71,8 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Profiles get { return false; } } + #endregion + public void NewClient(IClientAPI client) { client.OnRequestAvatarProperties += RequestAvatarProperty; @@ -107,7 +111,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Profiles public void UpdateAvatarProperties(IClientAPI remoteClient, UserProfileData newProfile) { UserProfileData Profile = m_scene.CommsManager.UserService.GetUserProfile(newProfile.ID); - + // if it's the profile of the user requesting the update, then we change only a few things. if (remoteClient.AgentId.CompareTo(Profile.ID) == 0) { diff --git a/OpenSim/Region/Environment/Modules/Avatar/Voice/AsterixVoice/AsteriskVoiceModule.cs b/OpenSim/Region/Environment/Modules/Avatar/Voice/AsterixVoice/AsteriskVoiceModule.cs index 0d7de78..44d67e6 100644 --- a/OpenSim/Region/Environment/Modules/Avatar/Voice/AsterixVoice/AsteriskVoiceModule.cs +++ b/OpenSim/Region/Environment/Modules/Avatar/Voice/AsterixVoice/AsteriskVoiceModule.cs @@ -44,40 +44,43 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.AsterixVoice { public class AsteriskVoiceModule : IRegionModule { - private static readonly ILog m_log = + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - private Scene m_scene; - private IConfig m_config; + private static readonly string m_parcelVoiceInfoRequestPath = "0007/"; + private static readonly string m_provisionVoiceAccountRequestPath = "0008/"; + private string m_asterisk; private string m_asterisk_password; private string m_asterisk_salt; private int m_asterisk_timeout; - private string m_sipDomain; private string m_confDomain; + private IConfig m_config; + private Scene m_scene; + private string m_sipDomain; - private static readonly string m_parcelVoiceInfoRequestPath = "0007/"; - private static readonly string m_provisionVoiceAccountRequestPath = "0008/"; + #region IRegionModule Members public void Initialise(Scene scene, IConfigSource config) { m_scene = scene; m_config = config.Configs["AsteriskVoice"]; - if (null == m_config) + if (null == m_config) { m_log.Info("[ASTERISKVOICE] no config found, plugin disabled"); return; } - if (!m_config.GetBoolean("enabled", false)) + if (!m_config.GetBoolean("enabled", false)) { m_log.Info("[ASTERISKVOICE] plugin disabled by configuration"); return; } m_log.Info("[ASTERISKVOICE] plugin enabled"); - try { + try + { m_sipDomain = m_config.GetString("sip_domain", String.Empty); m_log.InfoFormat("[ASTERISKVOICE] using SIP domain {0}", m_sipDomain); @@ -91,17 +94,17 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.AsterixVoice if (String.IsNullOrEmpty(m_asterisk)) throw new Exception("missing asterisk_frontend config parameter"); if (String.IsNullOrEmpty(m_asterisk_password)) throw new Exception("missing asterisk_password config parameter"); m_log.InfoFormat("[ASTERISKVOICE] using asterisk front end {0}", m_asterisk); - + scene.EventManager.OnRegisterCaps += OnRegisterCaps; } - catch (Exception e) + catch (Exception e) { m_log.ErrorFormat("[ASTERISKVOICE] plugin initialization failed: {0}", e.Message); m_log.DebugFormat("[ASTERISKVOICE] plugin initialization failed: {0}", e.ToString()); return; } } - + public void PostInitialise() { } @@ -120,15 +123,17 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.AsterixVoice get { return false; } } - public void OnRegisterCaps(LLUUID agentID, Caps caps) + #endregion + + public void OnRegisterCaps(LLUUID agentID, Caps caps) { m_log.DebugFormat("[ASTERISKVOICE] OnRegisterCaps: agentID {0} caps {1}", agentID, caps); - string capsBase = "/CAPS/" + caps.CapsObjectPath; + string capsBase = "/CAPS/" + caps.CapsObjectPath; caps.RegisterHandler("ParcelVoiceInfoRequest", - new RestStreamHandler("POST", capsBase + m_parcelVoiceInfoRequestPath, - delegate(string request, string path, string param) + new RestStreamHandler("POST", capsBase + m_parcelVoiceInfoRequestPath, + delegate(string request, string path, string param) { - return ParcelVoiceInfoRequest(request, path, param, + return ParcelVoiceInfoRequest(request, path, param, agentID, caps); })); caps.RegisterHandler("ProvisionVoiceAccountRequest", @@ -139,7 +144,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.AsterixVoice agentID, caps); })); } - + /// /// Callback for a client request for ParcelVoiceInfo /// @@ -149,30 +154,30 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.AsterixVoice /// /// /// - public string ParcelVoiceInfoRequest(string request, string path, string param, - LLUUID agentID, Caps caps) + public string ParcelVoiceInfoRequest(string request, string path, string param, + LLUUID agentID, Caps caps) { // we need to do: // - send channel_uri: as "sip:regionID@m_sipDomain" try { - m_log.DebugFormat("[ASTERISKVOICE][PARCELVOICE]: request: {0}, path: {1}, param: {2}", + m_log.DebugFormat("[ASTERISKVOICE][PARCELVOICE]: request: {0}, path: {1}, param: {2}", request, path, param); // setup response to client Hashtable creds = new Hashtable(); - creds["channel_uri"] = String.Format("sip:{0}@{1}", + creds["channel_uri"] = String.Format("sip:{0}@{1}", m_scene.RegionInfo.RegionID, m_sipDomain); - + string regionName = m_scene.RegionInfo.RegionName; ScenePresence avatar = m_scene.GetScenePresence(agentID); if (null == m_scene.LandChannel) throw new Exception("land data not yet available"); LandData land = m_scene.GetLandData(avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y); - - LLSDParcelVoiceInfoResponse parcelVoiceInfo = + + LLSDParcelVoiceInfoResponse parcelVoiceInfo = new LLSDParcelVoiceInfoResponse(regionName, land.localID, creds); - + string r = LLSDHelpers.SerialiseLLSDReply(parcelVoiceInfo); @@ -183,17 +188,17 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.AsterixVoice if (!String.IsNullOrEmpty(m_confDomain)) { requestData["region"] += String.Format("@{0}", m_confDomain); - } + } ArrayList SendParams = new ArrayList(); SendParams.Add(requestData); XmlRpcRequest updateAccountRequest = new XmlRpcRequest("region_update", SendParams); XmlRpcResponse updateAccountResponse = updateAccountRequest.Send(m_asterisk, m_asterisk_timeout); - Hashtable responseData = (Hashtable)updateAccountResponse.Value; - + Hashtable responseData = (Hashtable) updateAccountResponse.Value; + if (!responseData.ContainsKey("success")) throw new Exception("region_update call failed"); - bool success = Convert.ToBoolean((string)responseData["success"]); + bool success = Convert.ToBoolean((string) responseData["success"]); if (!success) throw new Exception("region_update failed"); @@ -218,8 +223,8 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.AsterixVoice /// /// /// - public string ProvisionVoiceAccountRequest(string request, string path, string param, - LLUUID agentID, Caps caps) + public string ProvisionVoiceAccountRequest(string request, string path, string param, + LLUUID agentID, Caps caps) { // we need to // - get user data from UserProfileCacheService @@ -232,7 +237,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.AsterixVoice // send account details back to client try { - m_log.DebugFormat("[ASTERISKVOICE][PROVISIONVOICE]: request: {0}, path: {1}, param: {2}", + m_log.DebugFormat("[ASTERISKVOICE][PROVISIONVOICE]: request: {0}, path: {1}, param: {2}", request, path, param); // get user data & prepare voice account response @@ -244,7 +249,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.AsterixVoice // we generate a nonce everytime string voicePassword = "$1$" + Util.Md5Hash(DateTime.UtcNow.ToLongTimeString() + m_asterisk_salt); - LLSDVoiceAccountResponse voiceAccountResponse = + LLSDVoiceAccountResponse voiceAccountResponse = new LLSDVoiceAccountResponse(voiceUser, voicePassword); string r = LLSDHelpers.SerialiseLLSDReply(voiceAccountResponse); m_log.DebugFormat("[CAPS][PROVISIONVOICE]: {0}", r); @@ -257,18 +262,18 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.AsterixVoice if (!String.IsNullOrEmpty(m_sipDomain)) { requestData["username"] += String.Format("@{0}", m_sipDomain); - } + } requestData["password"] = voicePassword; ArrayList SendParams = new ArrayList(); SendParams.Add(requestData); XmlRpcRequest updateAccountRequest = new XmlRpcRequest("account_update", SendParams); XmlRpcResponse updateAccountResponse = updateAccountRequest.Send(m_asterisk, m_asterisk_timeout); - Hashtable responseData = (Hashtable)updateAccountResponse.Value; - + Hashtable responseData = (Hashtable) updateAccountResponse.Value; + if (!responseData.ContainsKey("success")) throw new Exception("account_update call failed"); - bool success = Convert.ToBoolean((string)responseData["success"]); + bool success = Convert.ToBoolean((string) responseData["success"]); if (!success) throw new Exception("account_update failed"); return r; diff --git a/OpenSim/Region/Environment/Modules/Avatar/Voice/SIPVoice/SIPVoiceModule.cs b/OpenSim/Region/Environment/Modules/Avatar/Voice/SIPVoice/SIPVoiceModule.cs index 8b7c3d0..8d9ba6f 100644 --- a/OpenSim/Region/Environment/Modules/Avatar/Voice/SIPVoice/SIPVoiceModule.cs +++ b/OpenSim/Region/Environment/Modules/Avatar/Voice/SIPVoice/SIPVoiceModule.cs @@ -43,22 +43,23 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.SIPVoice { public class SIPVoiceModule : IRegionModule { - private static readonly ILog m_log = + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - private Scene m_scene; + private static readonly string m_parcelVoiceInfoRequestPath = "0007/"; + private static readonly string m_provisionVoiceAccountRequestPath = "0008/"; private IConfig m_config; + private Scene m_scene; private string m_sipDomain; - private static readonly string m_parcelVoiceInfoRequestPath = "0007/"; - private static readonly string m_provisionVoiceAccountRequestPath = "0008/"; + #region IRegionModule Members public void Initialise(Scene scene, IConfigSource config) { m_scene = scene; m_config = config.Configs["Voice"]; - if (null == m_config || !m_config.GetBoolean("enabled", false)) + if (null == m_config || !m_config.GetBoolean("enabled", false)) { m_log.Info("[VOICE] plugin disabled"); return; @@ -95,15 +96,17 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.SIPVoice get { return false; } } - public void OnRegisterCaps(LLUUID agentID, Caps caps) + #endregion + + public void OnRegisterCaps(LLUUID agentID, Caps caps) { m_log.DebugFormat("[VOICE] OnRegisterCaps: agentID {0} caps {1}", agentID, caps); - string capsBase = "/CAPS/" + caps.CapsObjectPath; + string capsBase = "/CAPS/" + caps.CapsObjectPath; caps.RegisterHandler("ParcelVoiceInfoRequest", - new RestStreamHandler("POST", capsBase + m_parcelVoiceInfoRequestPath, - delegate(string request, string path, string param) + new RestStreamHandler("POST", capsBase + m_parcelVoiceInfoRequestPath, + delegate(string request, string path, string param) { - return ParcelVoiceInfoRequest(request, path, param, + return ParcelVoiceInfoRequest(request, path, param, agentID, caps); })); caps.RegisterHandler("ProvisionVoiceAccountRequest", @@ -114,7 +117,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.SIPVoice agentID, caps); })); } - + /// /// Callback for a client request for ParcelVoiceInfo /// @@ -124,8 +127,8 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.SIPVoice /// /// /// - public string ParcelVoiceInfoRequest(string request, string path, string param, - LLUUID agentID, Caps caps) + public string ParcelVoiceInfoRequest(string request, string path, string param, + LLUUID agentID, Caps caps) { try { @@ -135,15 +138,15 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.SIPVoice Hashtable creds = new Hashtable(); creds["channel_uri"] = String.Format("sip:{0}@{1}", agentID, m_sipDomain); - + string regionName = m_scene.RegionInfo.RegionName; ScenePresence avatar = m_scene.GetScenePresence(agentID); if (null == m_scene.LandChannel) throw new Exception("land data not yet available"); LandData land = m_scene.GetLandData(avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y); - - LLSDParcelVoiceInfoResponse parcelVoiceInfo = + + LLSDParcelVoiceInfoResponse parcelVoiceInfo = new LLSDParcelVoiceInfoResponse(regionName, land.localID, creds); - + string r = LLSDHelpers.SerialiseLLSDReply(parcelVoiceInfo); m_log.DebugFormat("[VOICE][PARCELVOICE]: {0}", r); @@ -153,7 +156,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.SIPVoice { m_log.ErrorFormat("[CAPS]: {0}, try again later", e.ToString()); } - + return null; } @@ -166,12 +169,12 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.SIPVoice /// /// /// - public string ProvisionVoiceAccountRequest(string request, string path, string param, - LLUUID agentID, Caps caps) + public string ProvisionVoiceAccountRequest(string request, string path, string param, + LLUUID agentID, Caps caps) { try { - m_log.DebugFormat("[VOICE][PROVISIONVOICE]: request: {0}, path: {1}, param: {2}", + m_log.DebugFormat("[VOICE][PROVISIONVOICE]: request: {0}, path: {1}, param: {2}", request, path, param); string voiceUser = "x" + Convert.ToBase64String(agentID.GetBytes()); @@ -180,7 +183,7 @@ namespace OpenSim.Region.Environment.Modules.Avatar.Voice.SIPVoice CachedUserInfo userInfo = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(agentID); if (null == userInfo) throw new Exception("cannot get user details"); - LLSDVoiceAccountResponse voiceAccountResponse = + LLSDVoiceAccountResponse voiceAccountResponse = new LLSDVoiceAccountResponse(voiceUser, "$1$" + userInfo.UserProfile.PasswordHash); string r = LLSDHelpers.SerialiseLLSDReply(voiceAccountResponse); m_log.DebugFormat("[CAPS][PROVISIONVOICE]: {0}", r); diff --git a/OpenSim/Region/Environment/Modules/Framework/CommanderTestModule.cs b/OpenSim/Region/Environment/Modules/Framework/CommanderTestModule.cs index 76bdae3..cf87021 100644 --- a/OpenSim/Region/Environment/Modules/Framework/CommanderTestModule.cs +++ b/OpenSim/Region/Environment/Modules/Framework/CommanderTestModule.cs @@ -28,26 +28,29 @@ using System; using Nini.Config; using OpenSim.Region.Environment.Interfaces; -using OpenSim.Region.Environment.Modules.Framework; using OpenSim.Region.Environment.Scenes; namespace OpenSim.Region.Environment.Modules.Framework { public class CommanderTestModule : IRegionModule, ICommandableModule { - Commander m_commander = new Commander("CommanderTest"); - Scene m_scene; + private Commander m_commander = new Commander("CommanderTest"); + private Scene m_scene; - #region IRegionModule Members + #region ICommandableModule Members - public void Initialise(Scene scene, IConfigSource source) + public ICommander CommandInterface { - m_scene = scene; + get { throw new NotImplementedException(); } } - private void InterfaceHelloWorld(Object[] args) + #endregion + + #region IRegionModule Members + + public void Initialise(Scene scene, IConfigSource source) { - Console.WriteLine("Hello World"); + m_scene = scene; } public void PostInitialise() @@ -77,13 +80,9 @@ namespace OpenSim.Region.Environment.Modules.Framework #endregion - #region ICommandableModule Members - - public ICommander CommandInterface + private void InterfaceHelloWorld(Object[] args) { - get { throw new NotImplementedException(); } + Console.WriteLine("Hello World"); } - - #endregion } } \ No newline at end of file diff --git a/OpenSim/Region/Environment/Modules/Grid/Interregion/InterregionModule.cs b/OpenSim/Region/Environment/Modules/Grid/Interregion/InterregionModule.cs index 1a77ac8..8307e50 100644 --- a/OpenSim/Region/Environment/Modules/Grid/Interregion/InterregionModule.cs +++ b/OpenSim/Region/Environment/Modules/Grid/Interregion/InterregionModule.cs @@ -35,61 +35,14 @@ namespace OpenSim.Region.Environment.Modules.Communications.Interregion private readonly Dictionary m_neighbourInterfaces = new Dictionary(); private readonly Dictionary m_neighbourRemote = new Dictionary(); private IConfigSource m_config; - private RemotingObject m_myRemote; + private bool m_enabled = false; private Object m_lockObject = new object(); + private RemotingObject m_myRemote; private TcpChannel m_tcpChannel; private int m_tcpPort = 10101; - private bool m_enabled = false; - - #region IRegionModule Members - - //TODO: This prevents us from registering new scenes after PostInitialise if we want comms updated. - public void Initialise(Scene scene, IConfigSource source) - { - if (m_enabled) - { - m_myLocations.Add(new Location((int) scene.RegionInfo.RegionLocX, - (int) scene.RegionInfo.RegionLocY)); - m_config = source; - - scene.RegisterModuleInterface(this); - } - } - - //TODO: This prevents us from registering new scenes after PostInitialise if we want comms updated. - public void PostInitialise() - { - if (m_enabled) - { - try - { - m_tcpPort = m_config.Configs["Comms"].GetInt("remoting_port", m_tcpPort); - } - catch - { - } - - internal_CreateRemotingObjects(); - } - } - - public void Close() - { - ChannelServices.UnregisterChannel(m_tcpChannel); - } - - public string Name - { - get { return "InterregionModule"; } - } - - public bool IsSharedModule - { - get { return true; } - } - #endregion + #region IInterregionModule Members public void internal_CreateRemotingObjects() { @@ -106,22 +59,6 @@ namespace OpenSim.Region.Environment.Modules.Communications.Interregion } } - public void RegisterRemoteRegion(string uri) - { - RegisterRemotingInterface((RemotingObject) Activator.GetObject(typeof (RemotingObject), uri)); - } - - private void RegisterRemotingInterface(RemotingObject remote) - { - Location[] locs = remote.GetLocations(); - string[] interfaces = remote.GetInterfaces(); - foreach (Location loc in locs) - { - m_neighbourInterfaces[loc] = interfaces; - m_neighbourRemote[loc] = remote; - } - } - public void RegisterMethod(T e) { m_interfaces[typeof (T)] = e; @@ -171,5 +108,73 @@ namespace OpenSim.Region.Environment.Modules.Communications.Interregion { return new Location(0, 0); } + + #endregion + + //TODO: This prevents us from registering new scenes after PostInitialise if we want comms updated. + + #region IRegionModule Members + + public void Initialise(Scene scene, IConfigSource source) + { + if (m_enabled) + { + m_myLocations.Add(new Location((int) scene.RegionInfo.RegionLocX, + (int) scene.RegionInfo.RegionLocY)); + m_config = source; + + scene.RegisterModuleInterface(this); + } + } + + //TODO: This prevents us from registering new scenes after PostInitialise if we want comms updated. + public void PostInitialise() + { + if (m_enabled) + { + try + { + m_tcpPort = m_config.Configs["Comms"].GetInt("remoting_port", m_tcpPort); + } + catch + { + } + + internal_CreateRemotingObjects(); + } + } + + public void Close() + { + ChannelServices.UnregisterChannel(m_tcpChannel); + } + + public string Name + { + get { return "InterregionModule"; } + } + + public bool IsSharedModule + { + get { return true; } + } + + #endregion + + public void RegisterRemoteRegion(string uri) + { + RegisterRemotingInterface((RemotingObject) Activator.GetObject(typeof (RemotingObject), uri)); + } + + private void RegisterRemotingInterface(RemotingObject remote) + { + Location[] locs = remote.GetLocations(); + string[] interfaces = remote.GetInterfaces(); + foreach (Location loc in locs) + { + m_neighbourInterfaces[loc] = interfaces; + m_neighbourRemote[loc] = remote; + } + } } } \ No newline at end of file diff --git a/OpenSim/Region/Environment/Modules/Scripting/DynamicTexture/DynamicTextureModule.cs b/OpenSim/Region/Environment/Modules/Scripting/DynamicTexture/DynamicTextureModule.cs index 63eee97..735a3cf 100644 --- a/OpenSim/Region/Environment/Modules/Scripting/DynamicTexture/DynamicTextureModule.cs +++ b/OpenSim/Region/Environment/Modules/Scripting/DynamicTexture/DynamicTextureModule.cs @@ -47,32 +47,7 @@ namespace OpenSim.Region.Environment.Modules.Scripting.DynamicTexture private Dictionary Updaters = new Dictionary(); - public void Initialise(Scene scene, IConfigSource config) - { - if (!RegisteredScenes.ContainsKey(scene.RegionInfo.RegionID)) - { - RegisteredScenes.Add(scene.RegionInfo.RegionID, scene); - scene.RegisterModuleInterface(this); - } - } - - public void PostInitialise() - { - } - - public void Close() - { - } - - public string Name - { - get { return "DynamicTextureModule"; } - } - - public bool IsSharedModule - { - get { return true; } - } + #region IDynamicTextureManager Members public void RegisterRender(string handleType, IDynamicTextureRender render) { @@ -164,20 +139,55 @@ namespace OpenSim.Region.Environment.Modules.Scripting.DynamicTexture return LLUUID.Zero; } + #endregion + + #region IRegionModule Members + + public void Initialise(Scene scene, IConfigSource config) + { + if (!RegisteredScenes.ContainsKey(scene.RegionInfo.RegionID)) + { + RegisteredScenes.Add(scene.RegionInfo.RegionID, scene); + scene.RegisterModuleInterface(this); + } + } + + public void PostInitialise() + { + } + + public void Close() + { + } + + public string Name + { + get { return "DynamicTextureModule"; } + } + + public bool IsSharedModule + { + get { return true; } + } + + #endregion + + #region Nested type: DynamicTextureUpdater + public class DynamicTextureUpdater { - public LLUUID SimUUID; - public LLUUID UpdaterID; - public string ContentType; - public string Url; + public bool BlendWithOldTexture = false; public string BodyData; - public LLUUID PrimID; - public int UpdateTimer; + public string ContentType; + public byte FrontAlpha = 255; public LLUUID LastAssetID; public string Params; - public bool BlendWithOldTexture = false; + public LLUUID PrimID; public bool SetNewFrontAlpha = false; - public byte FrontAlpha = 255; + public LLUUID SimUUID; + public LLUUID UpdaterID; + public int UpdateTimer; + public string Url; public DynamicTextureUpdater() { @@ -224,7 +234,7 @@ namespace OpenSim.Region.Environment.Modules.Scripting.DynamicTexture LastAssetID = asset.FullID; - + part.Shape.Textures = new LLObject.TextureEntry(asset.FullID); part.ScheduleFullUpdate(); } @@ -273,5 +283,7 @@ namespace OpenSim.Region.Environment.Modules.Scripting.DynamicTexture } } } + + #endregion } } \ No newline at end of file diff --git a/OpenSim/Region/Environment/Modules/Scripting/HttpRequest/ScriptsHttpRequests.cs b/OpenSim/Region/Environment/Modules/Scripting/HttpRequest/ScriptsHttpRequests.cs index 4977a86..184e026 100644 --- a/OpenSim/Region/Environment/Modules/Scripting/HttpRequest/ScriptsHttpRequests.cs +++ b/OpenSim/Region/Environment/Modules/Scripting/HttpRequest/ScriptsHttpRequests.cs @@ -84,45 +84,20 @@ namespace OpenSim.Region.Environment.Modules.Scripting.HttpRequest { public class HttpRequestModule : IRegionModule, IHttpRequests { - private Scene m_scene; - private Queue rpcQueue = new Queue(); private object HttpListLock = new object(); - private string m_name = "HttpScriptRequests"; private int httpTimeout = 30000; + private string m_name = "HttpScriptRequests"; // private Dictionary m_pendingRequests; + private Scene m_scene; + private Queue rpcQueue = new Queue(); public HttpRequestModule() { } - public void Initialise(Scene scene, IConfigSource config) - { - m_scene = scene; - - m_scene.RegisterModuleInterface(this); - - m_pendingRequests = new Dictionary(); - } - - public void PostInitialise() - { - } - - public void Close() - { - } - - public string Name - { - get { return m_name; } - } - - public bool IsSharedModule - { - get { return true; } - } + #region IHttpRequests Members public LLUUID MakeHttpRequest(string url, string parameters, string body) { @@ -141,7 +116,7 @@ namespace OpenSim.Region.Environment.Modules.Scripting.HttpRequest if (parameters != null) { string[] parms = parameters.ToArray(); - for (int i = 0; i < parms.Length/2; i += 2) + for (int i = 0; i < parms.Length / 2; i += 2) { switch (Int32.Parse(parms[i])) { @@ -187,7 +162,8 @@ namespace OpenSim.Region.Environment.Modules.Scripting.HttpRequest public void StopHttpRequest(uint m_localID, LLUUID m_itemID) { - if(m_pendingRequests != null) { + if (m_pendingRequests != null) + { lock (HttpListLock) { HttpRequestClass tmpReq; @@ -243,36 +219,68 @@ namespace OpenSim.Region.Environment.Modules.Scripting.HttpRequest } } + #endregion + + #region IRegionModule Members + + public void Initialise(Scene scene, IConfigSource config) + { + m_scene = scene; + + m_scene.RegisterModuleInterface(this); + + m_pendingRequests = new Dictionary(); + } + + public void PostInitialise() + { + } + + public void Close() + { + } + + public string Name + { + get { return m_name; } + } + + public bool IsSharedModule + { + get { return true; } + } + + #endregion } public class HttpRequestClass { // Constants for parameters + public const int HTTP_BODY_MAXLENGTH = 2; public const int HTTP_METHOD = 0; public const int HTTP_MIMETYPE = 1; - public const int HTTP_BODY_MAXLENGTH = 2; public const int HTTP_VERIFY_CERT = 3; + public bool finished; + public int httpBodyMaxLen = 2048; // not implemented // Parameter members and default values public string httpMethod = "GET"; public string httpMIMEType = "text/plain;charset=utf-8"; - public int httpBodyMaxLen = 2048; // not implemented + private Thread httpThread; + public int httpTimeout; public bool httpVerifyCert = true; // not implemented // Request info - public uint localID; public LLUUID itemID; - public LLUUID reqID; - public int httpTimeout; - public string url; - public string outbound_body; + public uint localID; public DateTime next; - public int status; - public bool finished; - public List response_metadata; - public string response_body; + public string outbound_body; + public LLUUID reqID; public HttpWebRequest request; - private Thread httpThread; + public string response_body; + public List response_metadata; + public int status; + public string url; public void process() { diff --git a/OpenSim/Region/Environment/Modules/Scripting/LoadImageURL/LoadImageURLModule.cs b/OpenSim/Region/Environment/Modules/Scripting/LoadImageURL/LoadImageURLModule.cs index eaf9d36..a0408cd 100644 --- a/OpenSim/Region/Environment/Modules/Scripting/LoadImageURL/LoadImageURLModule.cs +++ b/OpenSim/Region/Environment/Modules/Scripting/LoadImageURL/LoadImageURLModule.cs @@ -40,39 +40,10 @@ namespace OpenSim.Region.Environment.Modules.Scripting.LoadImageURL public class LoadImageURLModule : IRegionModule, IDynamicTextureRender { private string m_name = "LoadImageURL"; - private IDynamicTextureManager m_textureManager; private Scene m_scene; + private IDynamicTextureManager m_textureManager; - public void Initialise(Scene scene, IConfigSource config) - { - if (m_scene == null) - { - m_scene = scene; - } - } - - public void PostInitialise() - { - m_textureManager = m_scene.RequestModuleInterface(); - if (m_textureManager != null) - { - m_textureManager.RegisterRender(GetContentType(), this); - } - } - - public void Close() - { - } - - public string Name - { - get { return m_name; } - } - - public bool IsSharedModule - { - get { return true; } - } + #region IDynamicTextureRender Members public string GetName() { @@ -110,6 +81,43 @@ namespace OpenSim.Region.Environment.Modules.Scripting.LoadImageURL return false; } + #endregion + + #region IRegionModule Members + + public void Initialise(Scene scene, IConfigSource config) + { + if (m_scene == null) + { + m_scene = scene; + } + } + + public void PostInitialise() + { + m_textureManager = m_scene.RequestModuleInterface(); + if (m_textureManager != null) + { + m_textureManager.RegisterRender(GetContentType(), this); + } + } + + public void Close() + { + } + + public string Name + { + get { return m_name; } + } + + public bool IsSharedModule + { + get { return true; } + } + + #endregion + private void MakeHttpRequest(string url, LLUUID requestID) { WebRequest request = HttpWebRequest.Create(url); @@ -138,8 +146,8 @@ namespace OpenSim.Region.Environment.Modules.Scripting.LoadImageURL else if ((image.Height < 128) && (image.Width < 128)) { newsize = new Size(64, 64); - } - else if ((image.Height <256) && (image.Width < 256)) + } + else if ((image.Height < 256) && (image.Width < 256)) { newsize = new Size(128, 128); } @@ -153,8 +161,8 @@ namespace OpenSim.Region.Environment.Modules.Scripting.LoadImageURL } else { - newsize = new Size(1024,1024); - } + newsize = new Size(1024, 1024); + } Bitmap resize = new Bitmap(image, newsize); byte[] imageJ2000 = OpenJPEG.EncodeFromImage(resize, true); @@ -163,6 +171,8 @@ namespace OpenSim.Region.Environment.Modules.Scripting.LoadImageURL } } + #region Nested type: RequestState + public class RequestState { public HttpWebRequest Request = null; @@ -175,5 +185,7 @@ namespace OpenSim.Region.Environment.Modules.Scripting.LoadImageURL RequestID = requestID; } } + + #endregion } } \ No newline at end of file diff --git a/OpenSim/Region/Environment/Modules/Scripting/VectorRender/VectorRenderModule.cs b/OpenSim/Region/Environment/Modules/Scripting/VectorRender/VectorRenderModule.cs index 4fba5b9..386c2b5 100644 --- a/OpenSim/Region/Environment/Modules/Scripting/VectorRender/VectorRenderModule.cs +++ b/OpenSim/Region/Environment/Modules/Scripting/VectorRender/VectorRenderModule.cs @@ -44,14 +44,56 @@ namespace OpenSim.Region.Environment.Modules.Scripting.VectorRender { public class VectorRenderModule : IRegionModule, IDynamicTextureRender { - private Scene m_scene; private string m_name = "VectorRenderModule"; + private Scene m_scene; private IDynamicTextureManager m_textureManager; public VectorRenderModule() { } + #region IDynamicTextureRender Members + + public string GetContentType() + { + return ("vector"); + } + + public string GetName() + { + return m_name; + } + + public bool SupportsAsynchronous() + { + return true; + } + + public byte[] ConvertUrl(string url, string extraParams) + { + return null; + } + + public byte[] ConvertStream(Stream data, string extraParams) + { + return null; + } + + public bool AsyncConvertUrl(LLUUID id, string url, string extraParams) + { + return false; + } + + public bool AsyncConvertData(LLUUID id, string bodyData, string extraParams) + { + Draw(bodyData, id, extraParams); + return true; + } + + #endregion + + #region IRegionModule Members + public void Initialise(Scene scene, IConfigSource config) { if (m_scene == null) @@ -83,21 +125,25 @@ namespace OpenSim.Region.Environment.Modules.Scripting.VectorRender get { return true; } } + #endregion + private void Draw(string data, LLUUID id, string extraParams) { // TODO: this is a brutal hack. extraParams should actually be parsed reasonably. int size = 256; - try { + try + { size = Convert.ToInt32(extraParams); - } catch (Exception e) { - + } + catch (Exception e) + { //Ckrinke: Add a WriteLine to remove the warning about 'e' defined but not used Console.WriteLine("Problem with Draw. Please verify parameters." + e.ToString()); } - + if ((size < 128) || (size > 1024)) size = 256; - + Bitmap bitmap = new Bitmap(size, size, PixelFormat.Format32bppArgb); Graphics graph = Graphics.FromImage(bitmap); @@ -121,13 +167,11 @@ namespace OpenSim.Region.Environment.Modules.Scripting.VectorRender } } - GDIDraw(data, graph); byte[] imageJ2000 = OpenJPEG.EncodeFromImage(bitmap, true); m_textureManager.ReturnData(id, imageJ2000); - } /* @@ -175,10 +219,10 @@ namespace OpenSim.Region.Environment.Modules.Scripting.VectorRender Pen drawPen = new Pen(Color.Black, 7); Font myFont = new Font("Times New Roman", 14); SolidBrush myBrush = new SolidBrush(Color.Black); - char[] lineDelimiter = { ';' }; - char[] partsDelimiter = { ',' }; + char[] lineDelimiter = {';'}; + char[] partsDelimiter = {','}; string[] lines = data.Split(lineDelimiter); - + foreach (string line in lines) { string nextLine = line.Trim(); @@ -188,16 +232,16 @@ namespace OpenSim.Region.Environment.Modules.Scripting.VectorRender float x = 0; float y = 0; GetParams(partsDelimiter, ref nextLine, 6, ref x, ref y); - startPoint.X = (int)x; - startPoint.Y = (int)y; + startPoint.X = (int) x; + startPoint.Y = (int) y; } else if (nextLine.StartsWith("LineTo")) { float x = 0; float y = 0; GetParams(partsDelimiter, ref nextLine, 6, ref x, ref y); - endPoint.X = (int)x; - endPoint.Y = (int)y; + endPoint.X = (int) x; + endPoint.Y = (int) y; graph.DrawLine(drawPen, startPoint, endPoint); startPoint.X = endPoint.X; startPoint.Y = endPoint.Y; @@ -213,10 +257,10 @@ namespace OpenSim.Region.Environment.Modules.Scripting.VectorRender float x = 0; float y = 0; GetParams(partsDelimiter, ref nextLine, 5, ref x, ref y); - endPoint.X = (int)x; - endPoint.Y = (int)y; + endPoint.X = (int) x; + endPoint.Y = (int) y; Image image = ImageHttpRequest(nextLine); - graph.DrawImage(image, (float)startPoint.X, (float)startPoint.Y, x, y); + graph.DrawImage(image, (float) startPoint.X, (float) startPoint.Y, x, y); startPoint.X += endPoint.X; startPoint.Y += endPoint.Y; } @@ -225,8 +269,8 @@ namespace OpenSim.Region.Environment.Modules.Scripting.VectorRender float x = 0; float y = 0; GetParams(partsDelimiter, ref nextLine, 9, ref x, ref y); - endPoint.X = (int)x; - endPoint.Y = (int)y; + endPoint.X = (int) x; + endPoint.Y = (int) y; graph.DrawRectangle(drawPen, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y); startPoint.X += endPoint.X; startPoint.Y += endPoint.Y; @@ -236,8 +280,8 @@ namespace OpenSim.Region.Environment.Modules.Scripting.VectorRender float x = 0; float y = 0; GetParams(partsDelimiter, ref nextLine, 13, ref x, ref y); - endPoint.X = (int)x; - endPoint.Y = (int)y; + endPoint.X = (int) x; + endPoint.Y = (int) y; graph.FillRectangle(myBrush, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y); startPoint.X += endPoint.X; startPoint.Y += endPoint.Y; @@ -247,8 +291,8 @@ namespace OpenSim.Region.Environment.Modules.Scripting.VectorRender float x = 0; float y = 0; GetParams(partsDelimiter, ref nextLine, 7, ref x, ref y); - endPoint.X = (int)x; - endPoint.Y = (int)y; + endPoint.X = (int) x; + endPoint.Y = (int) y; graph.DrawEllipse(drawPen, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y); startPoint.X += endPoint.X; startPoint.Y += endPoint.Y; @@ -271,7 +315,7 @@ namespace OpenSim.Region.Environment.Modules.Scripting.VectorRender { nextLine = nextLine.Remove(0, 9); nextLine = nextLine.Trim(); - + Color newColour = Color.FromName(nextLine); myBrush.Color = newColour; @@ -312,7 +356,7 @@ namespace OpenSim.Region.Environment.Modules.Scripting.VectorRender WebRequest request = HttpWebRequest.Create(url); //Ckrinke: Comment out for now as 'str' is unused. Bring it back into play later when it is used. //Ckrinke Stream str = null; - HttpWebResponse response = (HttpWebResponse)(request).GetResponse(); + HttpWebResponse response = (HttpWebResponse) (request).GetResponse(); if (response.StatusCode == HttpStatusCode.OK) { Bitmap image = new Bitmap(response.GetResponseStream()); @@ -321,41 +365,5 @@ namespace OpenSim.Region.Environment.Modules.Scripting.VectorRender return null; } - - public string GetContentType() - { - return ("vector"); - } - - public string GetName() - { - return m_name; - } - - public bool SupportsAsynchronous() - { - return true; - } - - public byte[] ConvertUrl(string url, string extraParams) - { - return null; - } - - public byte[] ConvertStream(Stream data, string extraParams) - { - return null; - } - - public bool AsyncConvertUrl(LLUUID id, string url, string extraParams) - { - return false; - } - - public bool AsyncConvertData(LLUUID id, string bodyData, string extraParams) - { - Draw(bodyData, id, extraParams); - return true; - } } } \ No newline at end of file diff --git a/OpenSim/Region/Environment/Modules/Scripting/WorldComm/WorldCommModule.cs b/OpenSim/Region/Environment/Modules/Scripting/WorldComm/WorldCommModule.cs index a949fb6..ff3b31e 100644 --- a/OpenSim/Region/Environment/Modules/Scripting/WorldComm/WorldCommModule.cs +++ b/OpenSim/Region/Environment/Modules/Scripting/WorldComm/WorldCommModule.cs @@ -67,18 +67,20 @@ namespace OpenSim.Region.Environment.Modules.Scripting.WorldComm { public class WorldCommModule : IRegionModule, IWorldComm { - private Scene m_scene; private object CommListLock = new object(); private object ListLock = new object(); - private string m_name = "WorldCommModule"; private ListenerManager m_listenerManager; - private Queue m_pendingQ; + private string m_name = "WorldCommModule"; private Queue m_pending; + private Queue m_pendingQ; + private Scene m_scene; public WorldCommModule() { } + #region IRegionModule Members + public void Initialise(Scene scene, IConfigSource config) { m_scene = scene; @@ -107,23 +109,9 @@ namespace OpenSim.Region.Environment.Modules.Scripting.WorldComm get { return false; } } - public void NewClient(IClientAPI client) - { - client.OnChatFromViewer += DeliverClientMessage; - } + #endregion - /******************************************************************** - * - * Listener Stuff - * - * *****************************************************************/ - private void DeliverClientMessage(Object sender, ChatFromViewerArgs e) - { - DeliverMessage(e.Sender.AgentId.ToString(), - e.Type, e.Channel, - e.Sender.FirstName + " " + e.Sender.LastName, - e.Message); - } + #region IWorldComm Members public int Listen(uint localID, LLUUID itemID, LLUUID hostID, int channel, string name, string id, string msg) { @@ -295,7 +283,7 @@ namespace OpenSim.Region.Environment.Modules.Scripting.WorldComm lock (m_pending.SyncRoot) { - li = (ListenerInfo)m_pending.Dequeue(); + li = (ListenerInfo) m_pending.Dequeue(); } return li; @@ -303,20 +291,41 @@ namespace OpenSim.Region.Environment.Modules.Scripting.WorldComm public uint PeekNextMessageLocalID() { - return ((ListenerInfo)m_pending.Peek()).GetLocalID(); + return ((ListenerInfo) m_pending.Peek()).GetLocalID(); } public LLUUID PeekNextMessageItemID() { - return ((ListenerInfo)m_pending.Peek()).GetItemID(); + return ((ListenerInfo) m_pending.Peek()).GetItemID(); + } + + #endregion + + public void NewClient(IClientAPI client) + { + client.OnChatFromViewer += DeliverClientMessage; + } + + /******************************************************************** + * + * Listener Stuff + * + * *****************************************************************/ + + private void DeliverClientMessage(Object sender, ChatFromViewerArgs e) + { + DeliverMessage(e.Sender.AgentId.ToString(), + e.Type, e.Channel, + e.Sender.FirstName + " " + e.Sender.LastName, + e.Message); } } public class ListenerManager { //private Dictionary m_listeners; - private Hashtable m_listeners = Hashtable.Synchronized(new Hashtable()); private object ListenersLock = new object(); + private Hashtable m_listeners = Hashtable.Synchronized(new Hashtable()); private int m_MaxListeners = 100; public int AddListener(uint localID, LLUUID itemID, LLUUID hostID, int channel, string name, string id, string msg) @@ -363,7 +372,7 @@ namespace OpenSim.Region.Environment.Modules.Scripting.WorldComm IDictionaryEnumerator en = m_listeners.GetEnumerator(); while (en.MoveNext()) { - ListenerInfo li = (ListenerInfo)en.Value; + ListenerInfo li = (ListenerInfo) en.Value; if (li.GetItemID().Equals(itemID)) { removedListeners.Add(li.GetHandle()); @@ -400,12 +409,11 @@ namespace OpenSim.Region.Environment.Modules.Scripting.WorldComm public void Activate(int handle) { - if (m_listeners.ContainsKey(handle)) { lock (m_listeners.SyncRoot) { - ListenerInfo li = (ListenerInfo)m_listeners[handle]; + ListenerInfo li = (ListenerInfo) m_listeners[handle]; li.Activate(); } } @@ -413,10 +421,9 @@ namespace OpenSim.Region.Environment.Modules.Scripting.WorldComm public void Dectivate(int handle) { - if (m_listeners.ContainsKey(handle)) { - ListenerInfo li = (ListenerInfo)m_listeners[handle]; + ListenerInfo li = (ListenerInfo) m_listeners[handle]; li.Deactivate(); } } @@ -432,9 +439,9 @@ namespace OpenSim.Region.Environment.Modules.Scripting.WorldComm IDictionaryEnumerator en = m_listeners.GetEnumerator(); while (en.MoveNext()) { - ListenerInfo li = (ListenerInfo)en.Value; + ListenerInfo li = (ListenerInfo) en.Value; - if (li.IsActive()) + if (li.IsActive()) { if (li.GetHostID().Equals(listenerKey)) { @@ -478,16 +485,16 @@ namespace OpenSim.Region.Environment.Modules.Scripting.WorldComm public class ListenerInfo { - private LLUUID m_itemID; // ID of the host script engine - private LLUUID m_hostID; // ID of the host/scene part - private LLUUID m_sourceItemID; // ID of the scenePart or avatar source of the message + private bool m_active; // Listener is active or not private int m_channel; // Channel private int m_handle; // Assigned handle of this listener - private uint m_localID; // Local ID from script engine - private string m_name; // Object name to filter messages from + private LLUUID m_hostID; // ID of the host/scene part private LLUUID m_id; // ID to filter messages from + private LLUUID m_itemID; // ID of the host script engine + private uint m_localID; // Local ID from script engine private string m_message; // The message - private bool m_active; // Listener is active or not + private string m_name; // Object name to filter messages from + private LLUUID m_sourceItemID; // ID of the scenePart or avatar source of the message public ListenerInfo(uint localID, int handle, LLUUID ItemID, LLUUID hostID, int channel, string name, LLUUID id, string message) { diff --git a/OpenSim/Region/Environment/Modules/Scripting/XMLRPC/XMLRPCModule.cs b/OpenSim/Region/Environment/Modules/Scripting/XMLRPC/XMLRPCModule.cs index 1139b4b..6ca8136 100644 --- a/OpenSim/Region/Environment/Modules/Scripting/XMLRPC/XMLRPCModule.cs +++ b/OpenSim/Region/Environment/Modules/Scripting/XMLRPC/XMLRPCModule.cs @@ -79,20 +79,21 @@ namespace OpenSim.Region.Environment.Modules.Scripting.XMLRPC { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - private object XMLRPCListLock = new object(); private string m_name = "XMLRPCModule"; - private int RemoteReplyScriptWait = 300; - private int RemoteReplyScriptTimeout = 9000; - private int m_remoteDataPort = 0; - private List m_scenes = new List(); // private Dictionary m_openChannels; + private Dictionary m_pendingSRDResponses; + private int m_remoteDataPort = 0; private Dictionary m_rpcPending; private Dictionary m_rpcPendingResponses; + private List m_scenes = new List(); + private int RemoteReplyScriptTimeout = 9000; + private int RemoteReplyScriptWait = 300; + private object XMLRPCListLock = new object(); - private Dictionary m_pendingSRDResponses; + #region IRegionModule Members public void Initialise(Scene scene, IConfigSource config) { @@ -125,7 +126,7 @@ namespace OpenSim.Region.Environment.Modules.Scripting.XMLRPC // Attach xmlrpc handlers m_log.Info("[REMOTE_DATA]: " + "Starting XMLRPC Server on port " + m_remoteDataPort + " for llRemoteData commands."); - BaseHttpServer httpServer = new BaseHttpServer((uint)m_remoteDataPort); + BaseHttpServer httpServer = new BaseHttpServer((uint) m_remoteDataPort); httpServer.AddXmlRPCHandler("llRemoteData", XmlRpcRemoteData); httpServer.Start(); } @@ -145,6 +146,10 @@ namespace OpenSim.Region.Environment.Modules.Scripting.XMLRPC get { return true; } } + #endregion + + #region IXMLRPC Members + public bool IsEnabled() { return (m_remoteDataPort > 0); @@ -196,7 +201,6 @@ namespace OpenSim.Region.Environment.Modules.Scripting.XMLRPC // for when a script is deleted public void DeleteChannels(LLUUID itemID) { - if (m_openChannels != null) { ArrayList tmp = new ArrayList(); @@ -212,12 +216,10 @@ namespace OpenSim.Region.Environment.Modules.Scripting.XMLRPC } IEnumerator tmpEnumerator = tmp.GetEnumerator(); - while ( tmpEnumerator.MoveNext() ) - m_openChannels.Remove((LLUUID)tmpEnumerator.Current); + while (tmpEnumerator.MoveNext()) + m_openChannels.Remove((LLUUID) tmpEnumerator.Current); } - } - } /********************************************** @@ -255,67 +257,6 @@ namespace OpenSim.Region.Environment.Modules.Scripting.XMLRPC } - public XmlRpcResponse XmlRpcRemoteData(XmlRpcRequest request) - { - XmlRpcResponse response = new XmlRpcResponse(); - - Hashtable requestData = (Hashtable)request.Params[0]; - bool GoodXML = (requestData.Contains("Channel") && requestData.Contains("IntValue") && - requestData.Contains("StringValue")); - - if (GoodXML) - { - LLUUID channel = new LLUUID((string)requestData["Channel"]); - RPCChannelInfo rpcChanInfo; - if (m_openChannels.TryGetValue(channel, out rpcChanInfo)) - { - string intVal = (string)requestData["IntValue"]; - string strVal = (string)requestData["StringValue"]; - - RPCRequestInfo rpcInfo; - - lock (XMLRPCListLock) - { - rpcInfo = - new RPCRequestInfo(rpcChanInfo.GetLocalID(), rpcChanInfo.GetItemID(), channel, strVal, - intVal); - m_rpcPending.Add(rpcInfo.GetMessageID(), rpcInfo); - } - - int timeoutCtr = 0; - - while (!rpcInfo.IsProcessed() && (timeoutCtr < RemoteReplyScriptTimeout)) - { - Thread.Sleep(RemoteReplyScriptWait); - timeoutCtr += RemoteReplyScriptWait; - } - if (rpcInfo.IsProcessed()) - { - Hashtable param = new Hashtable(); - param["StringValue"] = rpcInfo.GetStrRetval(); - param["IntValue"] = Convert.ToString(rpcInfo.GetIntRetval()); - - ArrayList parameters = new ArrayList(); - parameters.Add(param); - - response.Value = parameters; - rpcInfo = null; - } - else - { - response.SetFault(-1, "Script timeout"); - rpcInfo = null; - } - } - else - { - response.SetFault(-1, "Invalid channel"); - } - } - - return response; - } - public bool hasRequests() { lock (XMLRPCListLock) @@ -339,7 +280,6 @@ namespace OpenSim.Region.Environment.Modules.Scripting.XMLRPC if (m_rpcPending.TryGetValue(luid, out tmpReq)) { - if (!tmpReq.IsProcessed()) return tmpReq; } } @@ -367,13 +307,11 @@ namespace OpenSim.Region.Environment.Modules.Scripting.XMLRPC public LLUUID SendRemoteData(uint localID, LLUUID itemID, string channel, string dest, int idata, string sdata) { - SendRemoteDataRequest req = new SendRemoteDataRequest( localID, itemID, channel, dest, idata, sdata ); m_pendingSRDResponses.Add(req.GetReqID(), req); return req.process(); - } public SendRemoteDataRequest GetNextCompletedSRDRequest() @@ -423,19 +361,82 @@ namespace OpenSim.Region.Environment.Modules.Scripting.XMLRPC } } } + + #endregion + + public XmlRpcResponse XmlRpcRemoteData(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + + Hashtable requestData = (Hashtable) request.Params[0]; + bool GoodXML = (requestData.Contains("Channel") && requestData.Contains("IntValue") && + requestData.Contains("StringValue")); + + if (GoodXML) + { + LLUUID channel = new LLUUID((string) requestData["Channel"]); + RPCChannelInfo rpcChanInfo; + if (m_openChannels.TryGetValue(channel, out rpcChanInfo)) + { + string intVal = (string) requestData["IntValue"]; + string strVal = (string) requestData["StringValue"]; + + RPCRequestInfo rpcInfo; + + lock (XMLRPCListLock) + { + rpcInfo = + new RPCRequestInfo(rpcChanInfo.GetLocalID(), rpcChanInfo.GetItemID(), channel, strVal, + intVal); + m_rpcPending.Add(rpcInfo.GetMessageID(), rpcInfo); + } + + int timeoutCtr = 0; + + while (!rpcInfo.IsProcessed() && (timeoutCtr < RemoteReplyScriptTimeout)) + { + Thread.Sleep(RemoteReplyScriptWait); + timeoutCtr += RemoteReplyScriptWait; + } + if (rpcInfo.IsProcessed()) + { + Hashtable param = new Hashtable(); + param["StringValue"] = rpcInfo.GetStrRetval(); + param["IntValue"] = Convert.ToString(rpcInfo.GetIntRetval()); + + ArrayList parameters = new ArrayList(); + parameters.Add(param); + + response.Value = parameters; + rpcInfo = null; + } + else + { + response.SetFault(-1, "Script timeout"); + rpcInfo = null; + } + } + else + { + response.SetFault(-1, "Invalid channel"); + } + } + + return response; + } } public class RPCRequestInfo { - private string m_StrVal; + private LLUUID m_ChannelKey; private string m_IntVal; - private bool m_processed; - private string m_respStr; - private int m_respInt; - private uint m_localID; private LLUUID m_ItemID; + private uint m_localID; private LLUUID m_MessageID; - private LLUUID m_ChannelKey; + private bool m_processed; + private int m_respInt; + private string m_respStr; + private string m_StrVal; public RPCRequestInfo(uint localID, LLUUID itemID, LLUUID channelKey, string strVal, string intVal) { @@ -474,6 +475,7 @@ namespace OpenSim.Region.Environment.Modules.Scripting.XMLRPC { return m_respStr; } + public void SetIntRetval(int resp) { m_respInt = resp; @@ -483,6 +485,7 @@ namespace OpenSim.Region.Environment.Modules.Scripting.XMLRPC { return m_respInt; } + public uint GetLocalID() { return m_localID; @@ -511,9 +514,9 @@ namespace OpenSim.Region.Environment.Modules.Scripting.XMLRPC public class RPCChannelInfo { + private LLUUID m_ChannelKey; private LLUUID m_itemID; private uint m_localID; - private LLUUID m_ChannelKey; public RPCChannelInfo(uint localID, LLUUID itemID, LLUUID channelID) { @@ -536,38 +539,34 @@ namespace OpenSim.Region.Environment.Modules.Scripting.XMLRPC { return m_localID; } - } public class SendRemoteDataRequest { - - public LLUUID reqID; - public string destURL; + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public string channel; - public string sdata; - public int idata; + public string destURL; public bool finished; - public string response_sdata; - public int response_idata; - public XmlRpcRequest request; private Thread httpThread; + public int idata; public LLUUID m_itemID; public uint m_localID; - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + public LLUUID reqID; + public XmlRpcRequest request; + public int response_idata; + public string response_sdata; + public string sdata; public SendRemoteDataRequest(uint localID, LLUUID itemID, string channel, string dest, int idata, string sdata) { - this.channel = channel; - this.destURL = dest; + destURL = dest; this.idata = idata; this.sdata = sdata; m_itemID = itemID; m_localID = localID; reqID = LLUUID.Random(); - } public LLUUID process() @@ -581,7 +580,6 @@ namespace OpenSim.Region.Environment.Modules.Scripting.XMLRPC ThreadTracker.Add(httpThread); return reqID; - } /* @@ -597,8 +595,8 @@ namespace OpenSim.Region.Environment.Modules.Scripting.XMLRPC // if not, use as method name LLUUID parseUID; string mName = "llRemoteData"; - if( (channel != null) && (channel != "") ) - if( !LLUUID.TryParse(channel, out parseUID) ) + if ((channel != null) && (channel != "")) + if (!LLUUID.TryParse(channel, out parseUID)) mName = channel; else param["Channel"] = channel; @@ -615,26 +613,28 @@ namespace OpenSim.Region.Environment.Modules.Scripting.XMLRPC if (resp != null) { Hashtable respParms; - if(resp.Value.GetType().Equals(Type.GetType("System.Collections.Hashtable"))) { - respParms = (Hashtable)resp.Value; + if (resp.Value.GetType().Equals(Type.GetType("System.Collections.Hashtable"))) + { + respParms = (Hashtable) resp.Value; } - else { - ArrayList respData = (ArrayList)resp.Value; - respParms = (Hashtable)respData[0]; + else + { + ArrayList respData = (ArrayList) resp.Value; + respParms = (Hashtable) respData[0]; } if (respParms != null) { if (respParms.Contains("StringValue")) { - sdata = (string)respParms["StringValue"]; + sdata = (string) respParms["StringValue"]; } if (respParms.Contains("IntValue")) { - idata = Convert.ToInt32((string)respParms["IntValue"]); + idata = Convert.ToInt32((string) respParms["IntValue"]); } if (respParms.Contains("faultString")) { - sdata = (string)respParms["faultString"]; + sdata = (string) respParms["faultString"]; } if (respParms.Contains("faultCode")) { diff --git a/OpenSim/Region/Environment/Modules/World/Land/LandChannel.cs b/OpenSim/Region/Environment/Modules/World/Land/LandChannel.cs index cbea07a..efc5234 100644 --- a/OpenSim/Region/Environment/Modules/World/Land/LandChannel.cs +++ b/OpenSim/Region/Environment/Modules/World/Land/LandChannel.cs @@ -43,61 +43,45 @@ namespace OpenSim.Region.Environment.Modules.World.Land //Land types set with flags in ParcelOverlay. //Only one of these can be used. - public const byte LAND_TYPE_PUBLIC = (byte)0; //Equals 00000000 - public const byte LAND_TYPE_OWNED_BY_OTHER = (byte)1; //Equals 00000001 - public const byte LAND_TYPE_OWNED_BY_GROUP = (byte)2; //Equals 00000010 - public const byte LAND_TYPE_OWNED_BY_REQUESTER = (byte)3; //Equals 00000011 - public const byte LAND_TYPE_IS_FOR_SALE = (byte)4; //Equals 00000100 - public const byte LAND_TYPE_IS_BEING_AUCTIONED = (byte)5; //Equals 00000101 - - //Flags that when set, a border on the given side will be placed - //NOTE: North and East is assumable by the west and south sides (if land to east has a west border, then I have an east border; etc) - //This took forever to figure out -- jeesh. /blame LL for even having to send these - public const byte LAND_FLAG_PROPERTY_BORDER_WEST = (byte)64; //Equals 01000000 - public const byte LAND_FLAG_PROPERTY_BORDER_SOUTH = (byte)128; //Equals 10000000 + public const float BAN_LINE_SAFETY_HIEGHT = 100; + public const byte LAND_FLAG_PROPERTY_BORDER_SOUTH = (byte) 128; //Equals 10000000 + public const byte LAND_FLAG_PROPERTY_BORDER_WEST = (byte) 64; //Equals 01000000 //RequestResults (I think these are right, they seem to work): - public const int LAND_RESULT_SINGLE = 0; // The request they made contained only a single piece of land public const int LAND_RESULT_MULTIPLE = 1; // The request they made contained more than a single peice of land + public const int LAND_RESULT_SINGLE = 0; // The request they made contained only a single piece of land //ParcelSelectObjects - public const int LAND_SELECT_OBJECTS_OWNER = 2; public const int LAND_SELECT_OBJECTS_GROUP = 4; public const int LAND_SELECT_OBJECTS_OTHER = 8; + public const int LAND_SELECT_OBJECTS_OWNER = 2; + public const byte LAND_TYPE_IS_BEING_AUCTIONED = (byte) 5; //Equals 00000101 + public const byte LAND_TYPE_IS_FOR_SALE = (byte) 4; //Equals 00000100 + public const byte LAND_TYPE_OWNED_BY_GROUP = (byte) 2; //Equals 00000010 + public const byte LAND_TYPE_OWNED_BY_OTHER = (byte) 1; //Equals 00000001 + public const byte LAND_TYPE_OWNED_BY_REQUESTER = (byte) 3; //Equals 00000011 + public const byte LAND_TYPE_PUBLIC = (byte) 0; //Equals 00000000 //These are other constants. Yay! public const int START_LAND_LOCAL_ID = 1; - public const float BAN_LINE_SAFETY_HIEGHT = 100; - #endregion - private Scene m_scene; - + private int[,] landIDList = new int[64,64]; private Dictionary landList = new Dictionary(); - private int lastLandLocalID = START_LAND_LOCAL_ID - 1; - private int[,] landIDList = new int[64, 64]; private bool landPrimCountTainted = false; + private int lastLandLocalID = START_LAND_LOCAL_ID - 1; private bool m_allowedForcefulBans = true; - public bool allowedForcefulBans - { - get - { - return m_allowedForcefulBans; - } - set - { - m_allowedForcefulBans = value; - } - } + private Scene m_scene; public LandChannel(Scene scene) { m_scene = scene; landIDList.Initialize(); } + #region Land Object From Storage Functions public void IncomingLandObjectsFromStorage(List data) @@ -133,10 +117,64 @@ namespace OpenSim.Region.Environment.Modules.World.Land resetSimLandObjects(); } - #endregion + #endregion #region Parcel Add/Remove/Get/Create + public void updateLandObject(int local_id, LandData newData) + { + if (landList.ContainsKey(local_id)) + { + landList[local_id].landData = newData.Copy(); + m_scene.EventManager.TriggerLandObjectUpdated((uint) local_id, landList[local_id]); + } + } + + /// + /// Get the land object at the specified point + /// + /// Value between 0 - 256 on the x axis of the point + /// Value between 0 - 256 on the y axis of the point + /// Land object at the point supplied + public ILandObject getLandObject(float x_float, float y_float) + { + int x; + int y; + + try + { + x = Convert.ToInt32(Math.Floor(Convert.ToDouble(x_float) / Convert.ToDouble(4.0))); + y = Convert.ToInt32(Math.Floor(Convert.ToDouble(y_float) / Convert.ToDouble(4.0))); + } + catch (OverflowException) + { + return null; + } + + if (x >= 64 || y >= 64 || x < 0 || y < 0) + { + return null; + } + else + { + return landList[landIDList[x, y]]; + } + } + + public ILandObject getLandObject(int x, int y) + { + if (x >= Convert.ToInt32(Constants.RegionSize) || y >= Convert.ToInt32(Constants.RegionSize) || x < 0 || y < 0) + { + // These exceptions here will cause a lot of complaints from the users specifically because + // they happen every time at border crossings + throw new Exception("Error: Parcel not found at point " + x + ", " + y); + } + else + { + return landList[landIDList[x / 4, y / 4]]; + } + } + /// /// Creates a basic Parcel object without an owner (a zeroed key) /// @@ -154,7 +192,7 @@ namespace OpenSim.Region.Environment.Modules.World.Land { lastLandLocalID++; new_land.landData.localID = lastLandLocalID; - landList.Add(lastLandLocalID, (LandObject)new_land.Copy()); + landList.Add(lastLandLocalID, (LandObject) new_land.Copy()); bool[,] landBitmap = new_land.getLandBitmap(); @@ -197,15 +235,6 @@ namespace OpenSim.Region.Environment.Modules.World.Land landList.Remove(local_id); } - public void updateLandObject(int local_id, LandData newData) - { - if (landList.ContainsKey(local_id)) - { - landList[local_id].landData = newData.Copy(); - m_scene.EventManager.TriggerLandObjectUpdated((uint)local_id, landList[local_id]); - } - } - private void performFinalLandJoin(ILandObject master, ILandObject slave) { int x, y; @@ -225,66 +254,113 @@ namespace OpenSim.Region.Environment.Modules.World.Land updateLandObject(master.landData.localID, master.landData); } - /// - /// Get the land object at the specified point - /// - /// Value between 0 - 256 on the x axis of the point - /// Value between 0 - 256 on the y axis of the point - /// Land object at the point supplied - public ILandObject getLandObject(float x_float, float y_float) + public ILandObject getLandObject(int parcelLocalID) { - int x; - int y; - - try + lock (landList) { - x = Convert.ToInt32(Math.Floor(Convert.ToDouble(x_float) / Convert.ToDouble(4.0))); - y = Convert.ToInt32(Math.Floor(Convert.ToDouble(y_float) / Convert.ToDouble(4.0))); + if (landList.ContainsKey(parcelLocalID)) + { + return landList[parcelLocalID]; + } } - catch (OverflowException) + return null; + } + + #endregion + + #region Parcel Modification + + public void resetAllLandPrimCounts() + { + foreach (LandObject p in landList.Values) { - return null; + p.resetLandPrimCounts(); } + } - if (x >= 64 || y >= 64 || x < 0 || y < 0) + public void setPrimsTainted() + { + landPrimCountTainted = true; + } + + public bool isLandPrimCountTainted() + { + return landPrimCountTainted; + } + + public void addPrimToLandPrimCounts(SceneObjectGroup obj) + { + LLVector3 position = obj.AbsolutePosition; + ILandObject landUnderPrim = getLandObject(position.X, position.Y); + if (landUnderPrim != null) { - return null; + landUnderPrim.addPrimToCount(obj); } - else + } + + public void removePrimFromLandPrimCounts(SceneObjectGroup obj) + { + foreach (LandObject p in landList.Values) { - return landList[landIDList[x, y]]; + p.removePrimFromCount(obj); } } - public ILandObject getLandObject(int parcelLocalID) + public void finalizeLandPrimCountUpdate() { - lock (landList) + //Get Simwide prim count for owner + Dictionary> landOwnersAndParcels = new Dictionary>(); + foreach (LandObject p in landList.Values) { - if (landList.ContainsKey(parcelLocalID)) + if (!landOwnersAndParcels.ContainsKey(p.landData.ownerID)) { - return landList[parcelLocalID]; + List tempList = new List(); + tempList.Add(p); + landOwnersAndParcels.Add(p.landData.ownerID, tempList); + } + else + { + landOwnersAndParcels[p.landData.ownerID].Add(p); } } - return null; - } - public ILandObject getLandObject(int x, int y) - { - if (x >= Convert.ToInt32(Constants.RegionSize) || y >= Convert.ToInt32(Constants.RegionSize) || x < 0 || y < 0) + foreach (LLUUID owner in landOwnersAndParcels.Keys) { - // These exceptions here will cause a lot of complaints from the users specifically because - // they happen every time at border crossings - throw new Exception("Error: Parcel not found at point " + x + ", " + y); + int simArea = 0; + int simPrims = 0; + foreach (LandObject p in landOwnersAndParcels[owner]) + { + simArea += p.landData.area; + simPrims += p.landData.ownerPrims + p.landData.otherPrims + p.landData.groupPrims + + p.landData.selectedPrims; + } + + foreach (LandObject p in landOwnersAndParcels[owner]) + { + p.landData.simwideArea = simArea; + p.landData.simwidePrims = simPrims; + } } - else + } + + public void updateLandPrimCounts() + { + foreach (EntityBase obj in m_scene.Entities.Values) { - return landList[landIDList[x / 4, y / 4]]; + if (obj is SceneObjectGroup) + { + m_scene.EventManager.TriggerParcelPrimCountAdd((SceneObjectGroup) obj); + } } } - #endregion - - #region Parcel Modification + public void performParcelPrimCountUpdate() + { + resetAllLandPrimCounts(); + m_scene.EventManager.TriggerParcelPrimCountUpdate(); + finalizeLandPrimCountUpdate(); + landPrimCountTainted = false; + } /// /// Subdivides a piece of land @@ -435,97 +511,6 @@ namespace OpenSim.Region.Environment.Modules.World.Land return true; } - public void resetAllLandPrimCounts() - { - foreach (LandObject p in landList.Values) - { - p.resetLandPrimCounts(); - } - } - - public void setPrimsTainted() - { - landPrimCountTainted = true; - } - - public bool isLandPrimCountTainted() - { - return landPrimCountTainted; - } - - public void addPrimToLandPrimCounts(SceneObjectGroup obj) - { - LLVector3 position = obj.AbsolutePosition; - ILandObject landUnderPrim = getLandObject(position.X, position.Y); - if (landUnderPrim != null) - { - landUnderPrim.addPrimToCount(obj); - } - } - - public void removePrimFromLandPrimCounts(SceneObjectGroup obj) - { - foreach (LandObject p in landList.Values) - { - p.removePrimFromCount(obj); - } - } - - public void finalizeLandPrimCountUpdate() - { - //Get Simwide prim count for owner - Dictionary> landOwnersAndParcels = new Dictionary>(); - foreach (LandObject p in landList.Values) - { - if (!landOwnersAndParcels.ContainsKey(p.landData.ownerID)) - { - List tempList = new List(); - tempList.Add(p); - landOwnersAndParcels.Add(p.landData.ownerID, tempList); - } - else - { - landOwnersAndParcels[p.landData.ownerID].Add(p); - } - } - - foreach (LLUUID owner in landOwnersAndParcels.Keys) - { - int simArea = 0; - int simPrims = 0; - foreach (LandObject p in landOwnersAndParcels[owner]) - { - simArea += p.landData.area; - simPrims += p.landData.ownerPrims + p.landData.otherPrims + p.landData.groupPrims + - p.landData.selectedPrims; - } - - foreach (LandObject p in landOwnersAndParcels[owner]) - { - p.landData.simwideArea = simArea; - p.landData.simwidePrims = simPrims; - } - } - } - - public void updateLandPrimCounts() - { - foreach (EntityBase obj in m_scene.Entities.Values) - { - if (obj is SceneObjectGroup) - { - m_scene.EventManager.TriggerParcelPrimCountAdd((SceneObjectGroup)obj); - } - } - } - - public void performParcelPrimCountUpdate() - { - resetAllLandPrimCounts(); - m_scene.EventManager.TriggerParcelPrimCountUpdate(); - finalizeLandPrimCountUpdate(); - landPrimCountTainted = false; - } #endregion #region Parcel Updating @@ -547,7 +532,7 @@ namespace OpenSim.Region.Environment.Modules.World.Land { for (x = 0; x < 64; x++) { - byte tempByte = (byte)0; //This represents the byte for the current 4x4 + byte tempByte = (byte) 0; //This represents the byte for the current 4x4 ILandObject currentParcelBlock = null; try @@ -623,10 +608,10 @@ namespace OpenSim.Region.Environment.Modules.World.Land if (byteArrayCount >= LAND_BLOCKS_PER_PACKET) { byteArrayCount = 0; - packet = (ParcelOverlayPacket)PacketPool.Instance.GetPacket(PacketType.ParcelOverlay); + packet = (ParcelOverlayPacket) PacketPool.Instance.GetPacket(PacketType.ParcelOverlay); packet.ParcelData.Data = byteArray; packet.ParcelData.SequenceID = sequenceID; - remote_client.OutPacket((Packet)packet, ThrottleOutPacketType.Task); + remote_client.OutPacket((Packet) packet, ThrottleOutPacketType.Task); sequenceID++; byteArray = new byte[LAND_BLOCKS_PER_PACKET]; } @@ -652,7 +637,6 @@ namespace OpenSim.Region.Environment.Modules.World.Land { for (y = 0; y < inc_y; y++) { - ILandObject currentParcel = null; try { @@ -693,7 +677,6 @@ namespace OpenSim.Region.Environment.Modules.World.Land if (landList.ContainsKey(packet.ParcelData.LocalID)) { landList[packet.ParcelData.LocalID].updateLandProperties(packet, remote_client); - } } @@ -719,6 +702,14 @@ namespace OpenSim.Region.Environment.Modules.World.Land #endregion + #region ILandChannel Members + + public bool allowedForcefulBans + { + get { return m_allowedForcefulBans; } + set { m_allowedForcefulBans = value; } + } + /// /// Resets the sim to the default land object (full sim piece of land owned by the default user) /// @@ -731,7 +722,7 @@ namespace OpenSim.Region.Environment.Modules.World.Land ILandObject fullSimParcel = new LandObject(LLUUID.Zero, false, m_scene); - fullSimParcel.setLandBitmap(fullSimParcel.getSquareLandBitmap(0, 0, (int)Constants.RegionSize, (int)Constants.RegionSize)); + fullSimParcel.setLandBitmap(fullSimParcel.getSquareLandBitmap(0, 0, (int) Constants.RegionSize, (int) Constants.RegionSize)); fullSimParcel.landData.ownerID = m_scene.RegionInfo.MasterAvatarAssignedUUID; addLandObject(fullSimParcel); @@ -816,18 +807,17 @@ namespace OpenSim.Region.Environment.Modules.World.Land { if (presence.UUID == avatar.AgentId) { - List checkLandParcels = parcelsNearPoint(presence.AbsolutePosition); foreach (ILandObject checkBan in checkLandParcels) { if (checkBan.isBannedFromLand(avatar.AgentId)) { - checkBan.sendLandProperties(-30000, false, (int)ParcelManager.ParcelResult.Single, avatar); + checkBan.sendLandProperties(-30000, false, (int) ParcelManager.ParcelResult.Single, avatar); return; //Only send one } else if (checkBan.isRestrictedFromLand(avatar.AgentId)) { - checkBan.sendLandProperties(-40000, false, (int)ParcelManager.ParcelResult.Single, avatar); + checkBan.sendLandProperties(-40000, false, (int) ParcelManager.ParcelResult.Single, avatar); return; //Only send one } } @@ -841,8 +831,8 @@ namespace OpenSim.Region.Environment.Modules.World.Land ILandObject over = null; try { - over = getLandObject((int)Math.Min(255, Math.Max(0, Math.Round(avatar.AbsolutePosition.X))), - (int)Math.Min(255, Math.Max(0, Math.Round(avatar.AbsolutePosition.Y)))); + over = getLandObject((int) Math.Min(255, Math.Max(0, Math.Round(avatar.AbsolutePosition.X))), + (int) Math.Min(255, Math.Max(0, Math.Round(avatar.AbsolutePosition.Y)))); } catch (Exception) { @@ -873,11 +863,12 @@ namespace OpenSim.Region.Environment.Modules.World.Land } } } + public void sendLandUpdate(ScenePresence avatar) { sendLandUpdate(avatar, false); - } + public void handleSignificantClientMovement(IClientAPI remote_client) { ScenePresence clientAvatar = m_scene.GetScenePresence(remote_client.AgentId); @@ -949,6 +940,8 @@ namespace OpenSim.Region.Environment.Modules.World.Land } } + #endregion + // If the economy has been validated by the economy module, // and land has been validated as well, this method transfers // the land ownership @@ -961,7 +954,7 @@ namespace OpenSim.Region.Environment.Modules.World.Land { if (landList.ContainsKey(e.parcelLocalID)) { - landList[e.parcelLocalID].updateLandSold(e.agentId, e.groupId, e.groupOwned, (uint)e.transactionID, e.parcelPrice, e.parcelArea); + landList[e.parcelLocalID].updateLandSold(e.agentId, e.groupId, e.groupOwned, (uint) e.transactionID, e.parcelPrice, e.parcelArea); return; } } @@ -989,17 +982,16 @@ namespace OpenSim.Region.Environment.Modules.World.Land LLUUID AuthorizedID = lob.landData.authBuyerID; int saleprice = lob.landData.salePrice; LLUUID pOwnerID = lob.landData.ownerID; - - bool landforsale = ((lob.landData.landFlags & (uint)(Parcel.ParcelFlags.ForSale | Parcel.ParcelFlags.ForSaleObjects | Parcel.ParcelFlags.SellParcelObjects)) != 0); + + bool landforsale = ((lob.landData.landFlags & + (uint) (Parcel.ParcelFlags.ForSale | Parcel.ParcelFlags.ForSaleObjects | Parcel.ParcelFlags.SellParcelObjects)) != 0); if ((AuthorizedID == LLUUID.Zero || AuthorizedID == e.agentId) && e.parcelPrice >= saleprice && landforsale) { lock (e) { e.parcelOwnerID = pOwnerID; e.landValidated = true; - } - } } } diff --git a/OpenSim/Region/Environment/Modules/World/Land/LandManagementModule.cs b/OpenSim/Region/Environment/Modules/World/Land/LandManagementModule.cs index c5ffdca..3f09bd5 100644 --- a/OpenSim/Region/Environment/Modules/World/Land/LandManagementModule.cs +++ b/OpenSim/Region/Environment/Modules/World/Land/LandManagementModule.cs @@ -27,7 +27,6 @@ using Nini.Config; using OpenSim.Region.Environment.Interfaces; -using OpenSim.Region.Environment.Modules.World.Land; using OpenSim.Region.Environment.Scenes; namespace OpenSim.Region.Environment.Modules.World.Land @@ -43,7 +42,7 @@ namespace OpenSim.Region.Environment.Modules.World.Land { m_scene = scene; landChannel = new LandChannel(scene); - + m_scene.EventManager.OnParcelPrimCountAdd += landChannel.addPrimToLandPrimCounts; m_scene.EventManager.OnParcelPrimCountUpdate += landChannel.updateLandPrimCounts; m_scene.EventManager.OnAvatarEnteringNewParcel += new EventManager.AvatarEnteringNewParcel(landChannel.handleAvatarChangingParcel); @@ -53,18 +52,16 @@ namespace OpenSim.Region.Environment.Modules.World.Land lock (m_scene) { - m_scene.LandChannel = (ILandChannel)landChannel; + m_scene.LandChannel = (ILandChannel) landChannel; } } public void PostInitialise() { - } public void Close() { - } public string Name @@ -77,10 +74,6 @@ namespace OpenSim.Region.Environment.Modules.World.Land get { return false; } } - - - - #endregion } } \ No newline at end of file diff --git a/OpenSim/Region/Environment/Modules/World/Land/LandObject.cs b/OpenSim/Region/Environment/Modules/World/Land/LandObject.cs index 693c55d..368e113 100644 --- a/OpenSim/Region/Environment/Modules/World/Land/LandObject.cs +++ b/OpenSim/Region/Environment/Modules/World/Land/LandObject.cs @@ -33,7 +33,6 @@ using libsecondlife.Packets; using log4net; using OpenSim.Framework; using OpenSim.Region.Environment.Interfaces; -using OpenSim.Region.Environment.Modules.World.Land; using OpenSim.Region.Environment.Scenes; namespace OpenSim.Region.Environment.Modules.World.Land @@ -46,23 +45,16 @@ namespace OpenSim.Region.Environment.Modules.World.Land #region Member Variables private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + private bool[,] m_landBitmap = new bool[64,64]; protected LandData m_landData = new LandData(); - protected List primsOverMe = new List(); protected Scene m_scene; - - private bool[,] m_landBitmap = new bool[64,64]; + protected List primsOverMe = new List(); public bool[,] landBitmap { - get - { - return m_landBitmap; - } - set - { - m_landBitmap = value; - } + get { return m_landBitmap; } + set { m_landBitmap = value; } } #endregion @@ -71,25 +63,16 @@ namespace OpenSim.Region.Environment.Modules.World.Land public LandData landData { - get - { - return m_landData; - } + get { return m_landData; } - set - { - m_landData = value; - } + set { m_landData = value; } } - public LLUUID regionUUID + public LLUUID regionUUID { get { return m_scene.RegionInfo.RegionID; } } - #endregion - - #region Constructors public LandObject(LLUUID owner_id, bool is_group_owned, Scene scene) @@ -115,7 +98,7 @@ namespace OpenSim.Region.Environment.Modules.World.Land { if (x >= 0 && y >= 0 && x <= Constants.RegionSize && x <= Constants.RegionSize) { - return (landBitmap[x/4, y/4] == true); + return (landBitmap[x / 4, y / 4] == true); } else { @@ -149,7 +132,7 @@ namespace OpenSim.Region.Environment.Modules.World.Land { ParcelPropertiesPacket updatePacket = (ParcelPropertiesPacket) PacketPool.Instance.GetPacket(PacketType.ParcelProperties); // TODO: don't create new blocks if recycling an old packet - + updatePacket.ParcelData.AABBMax = landData.AABBMax; updatePacket.ParcelData.AABBMin = landData.AABBMin; updatePacket.ParcelData.Area = landData.area; @@ -171,7 +154,7 @@ namespace OpenSim.Region.Environment.Modules.World.Land { updatePacket.ParcelData.MaxPrims = Convert.ToInt32( - Math.Round((Convert.ToDecimal(landData.area)/Convert.ToDecimal(65536))*m_scene.objectCapacity* + Math.Round((Convert.ToDecimal(landData.area) / Convert.ToDecimal(65536)) * m_scene.objectCapacity * Convert.ToDecimal(m_scene.RegionInfo.EstateSettings.objectBonusFactor))); } else @@ -193,7 +176,7 @@ namespace OpenSim.Region.Environment.Modules.World.Land updatePacket.ParcelData.PassHours = landData.passHours; updatePacket.ParcelData.PassPrice = landData.passPrice; updatePacket.ParcelData.PublicCount = 0; //unemplemented - + uint regionFlags = (uint) m_scene.RegionInfo.EstateSettings.regionFlags; updatePacket.ParcelData.RegionDenyAnonymous = ((regionFlags & (uint) Simulator.RegionFlags.DenyAnonymous) > 0); @@ -255,12 +238,13 @@ namespace OpenSim.Region.Environment.Modules.World.Land newData.snapshotID = packet.ParcelData.SnapshotID; newData.userLocation = packet.ParcelData.UserLocation; newData.userLookAt = packet.ParcelData.UserLookAt; - + m_scene.LandChannel.updateLandObject(landData.localID, newData); sendLandUpdateToAvatarsOverMe(); } } + public void updateLandSold(LLUUID avatarID, LLUUID groupID, bool groupOwned, uint AuctionID, int claimprice, int area) { LandData newData = landData.Copy(); @@ -272,7 +256,7 @@ namespace OpenSim.Region.Environment.Modules.World.Land newData.claimPrice = claimprice; newData.salePrice = 0; newData.authBuyerID = LLUUID.Zero; - newData.landFlags &= ~(uint)(Parcel.ParcelFlags.ForSale | Parcel.ParcelFlags.ForSaleObjects | Parcel.ParcelFlags.SellParcelObjects); + newData.landFlags &= ~(uint) (Parcel.ParcelFlags.ForSale | Parcel.ParcelFlags.ForSaleObjects | Parcel.ParcelFlags.SellParcelObjects); m_scene.LandChannel.updateLandObject(landData.localID, newData); sendLandUpdateToAvatarsOverMe(); @@ -339,12 +323,13 @@ namespace OpenSim.Region.Environment.Modules.World.Land try { over = - m_scene.LandChannel.getLandObject((int)Math.Max(255,Math.Min(0,Math.Round(avatars[i].AbsolutePosition.X))), - (int)Math.Max(255,Math.Min(0,Math.Round(avatars[i].AbsolutePosition.Y)))); + m_scene.LandChannel.getLandObject((int) Math.Max(255, Math.Min(0, Math.Round(avatars[i].AbsolutePosition.X))), + (int) Math.Max(255, Math.Min(0, Math.Round(avatars[i].AbsolutePosition.Y)))); } catch (Exception) { - m_log.Warn("[LAND]: " + "unable to get land at x: " + Math.Round(avatars[i].AbsolutePosition.X) + " y: " + Math.Round(avatars[i].AbsolutePosition.Y)); + m_log.Warn("[LAND]: " + "unable to get land at x: " + Math.Round(avatars[i].AbsolutePosition.X) + " y: " + + Math.Round(avatars[i].AbsolutePosition.Y)); } if (over != null) @@ -463,6 +448,25 @@ namespace OpenSim.Region.Environment.Modules.World.Land #region Update Functions + public void updateLandBitmapByteArray() + { + landData.landBitmapByteArray = convertLandBitmapToBytes(); + } + + /// + /// Update all settings in land such as area, bitmap byte array, etc + /// + public void forceUpdateLandInfo() + { + updateAABBAndAreaValues(); + updateLandBitmapByteArray(); + } + + public void setLandBitmapFromByteArray() + { + landBitmap = convertBytesToLandBitmap(); + } + /// /// Updates the AABBMin and AABBMax values after area/shape modification of the land object /// @@ -495,8 +499,8 @@ namespace OpenSim.Region.Environment.Modules.World.Land if (ty > 255) ty = 255; landData.AABBMin = - new LLVector3((float)(min_x * 4), (float)(min_y * 4), - (float)m_scene.Heightmap[tx, ty]); + new LLVector3((float) (min_x * 4), (float) (min_y * 4), + (float) m_scene.Heightmap[tx, ty]); tx = max_x * 4; if (tx > 255) @@ -505,30 +509,11 @@ namespace OpenSim.Region.Environment.Modules.World.Land if (ty > 255) ty = 255; landData.AABBMax = - new LLVector3((float)(max_x * 4), (float)(max_y * 4), - (float)m_scene.Heightmap[tx, ty]); + new LLVector3((float) (max_x * 4), (float) (max_y * 4), + (float) m_scene.Heightmap[tx, ty]); landData.area = tempArea; } - public void updateLandBitmapByteArray() - { - landData.landBitmapByteArray = convertLandBitmapToBytes(); - } - - /// - /// Update all settings in land such as area, bitmap byte array, etc - /// - public void forceUpdateLandInfo() - { - updateAABBAndAreaValues(); - updateLandBitmapByteArray(); - } - - public void setLandBitmapFromByteArray() - { - landBitmap = convertBytesToLandBitmap(); - } - #endregion #region Land Bitmap Functions @@ -562,63 +547,12 @@ namespace OpenSim.Region.Environment.Modules.World.Land } /// - /// Converts the land bitmap to a packet friendly byte array - /// - /// - private byte[] convertLandBitmapToBytes() - { - byte[] tempConvertArr = new byte[512]; - byte tempByte = 0; - int x, y, i, byteNum = 0; - i = 0; - for (y = 0; y < 64; y++) - { - for (x = 0; x < 64; x++) - { - tempByte = Convert.ToByte(tempByte | Convert.ToByte(landBitmap[x, y]) << (i++%8)); - if (i%8 == 0) - { - tempConvertArr[byteNum] = tempByte; - tempByte = (byte) 0; - i = 0; - byteNum++; - } - } - } - return tempConvertArr; - } - - private bool[,] convertBytesToLandBitmap() - { - bool[,] tempConvertMap = new bool[64,64]; - tempConvertMap.Initialize(); - byte tempByte = 0; - int x = 0, y = 0, i = 0, bitNum = 0; - for (i = 0; i < 512; i++) - { - tempByte = landData.landBitmapByteArray[i]; - for (bitNum = 0; bitNum < 8; bitNum++) - { - bool bit = Convert.ToBoolean(Convert.ToByte(tempByte >> bitNum) & (byte) 1); - tempConvertMap[x, y] = bit; - x++; - if (x > 63) - { - x = 0; - y++; - } - } - } - return tempConvertMap; - } - - /// /// Full sim land object creation /// /// public bool[,] basicFullRegionLandBitmap() { - return getSquareLandBitmap(0, 0, (int)Constants.RegionSize, (int)Constants.RegionSize); + return getSquareLandBitmap(0, 0, (int) Constants.RegionSize, (int) Constants.RegionSize); } /// @@ -662,8 +596,8 @@ namespace OpenSim.Region.Environment.Modules.World.Land { for (x = 0; x < 64; x++) { - if (x >= start_x/4 && x < end_x/4 - && y >= start_y/4 && y < end_y/4) + if (x >= start_x / 4 && x < end_x / 4 + && y >= start_y / 4 && y < end_y / 4) { land_bitmap[x, y] = set_value; } @@ -705,6 +639,57 @@ namespace OpenSim.Region.Environment.Modules.World.Land return bitmap_base; } + /// + /// Converts the land bitmap to a packet friendly byte array + /// + /// + private byte[] convertLandBitmapToBytes() + { + byte[] tempConvertArr = new byte[512]; + byte tempByte = 0; + int x, y, i, byteNum = 0; + i = 0; + for (y = 0; y < 64; y++) + { + for (x = 0; x < 64; x++) + { + tempByte = Convert.ToByte(tempByte | Convert.ToByte(landBitmap[x, y]) << (i++ % 8)); + if (i % 8 == 0) + { + tempConvertArr[byteNum] = tempByte; + tempByte = (byte) 0; + i = 0; + byteNum++; + } + } + } + return tempConvertArr; + } + + private bool[,] convertBytesToLandBitmap() + { + bool[,] tempConvertMap = new bool[64,64]; + tempConvertMap.Initialize(); + byte tempByte = 0; + int x = 0, y = 0, i = 0, bitNum = 0; + for (i = 0; i < 512; i++) + { + tempByte = landData.landBitmapByteArray[i]; + for (bitNum = 0; bitNum < 8; bitNum++) + { + bool bit = Convert.ToBoolean(Convert.ToByte(tempByte >> bitNum) & (byte) 1); + tempConvertMap[x, y] = bit; + x++; + if (x > 63) + { + x = 0; + y++; + } + } + } + return tempConvertMap; + } + #endregion #region Object Select and Object Owner Listing @@ -781,7 +766,7 @@ namespace OpenSim.Region.Environment.Modules.World.Land public void sendLandObjectOwners(IClientAPI remote_client) { Dictionary primCount = new Dictionary(); - ParcelObjectOwnersReplyPacket pack + ParcelObjectOwnersReplyPacket pack = (ParcelObjectOwnersReplyPacket) PacketPool.Instance.GetPacket(PacketType.ParcelObjectOwnersReply); // TODO: don't create new blocks if recycling an old packet @@ -807,21 +792,21 @@ namespace OpenSim.Region.Environment.Modules.World.Land m_log.Error("[LAND]: Unable to match a prim with it's owner."); } } - + int notifyCount = primCount.Count; - + if (notifyCount > 0) { if (notifyCount > 32) { m_log.InfoFormat( "[LAND]: More than {0} avatars own prims on this parcel. Only sending back details of first {0}" - + " - a developer might want to investigate whether this is a hard limit", 32); - + + " - a developer might want to investigate whether this is a hard limit", 32); + notifyCount = 32; } - - ParcelObjectOwnersReplyPacket.DataBlock[] dataBlock + + ParcelObjectOwnersReplyPacket.DataBlock[] dataBlock = new ParcelObjectOwnersReplyPacket.DataBlock[notifyCount]; int num = 0; @@ -834,16 +819,16 @@ namespace OpenSim.Region.Environment.Modules.World.Land dataBlock[num].OwnerID = owner; num++; - + if (num >= notifyCount) { break; } } - + pack.Data = dataBlock; } - + remote_client.OutPacket(pack, ThrottleOutPacketType.Task); } @@ -937,7 +922,7 @@ namespace OpenSim.Region.Environment.Modules.World.Land #endregion #endregion - + #endregion } } \ No newline at end of file diff --git a/OpenSim/Region/Environment/Modules/World/Serialiser/SerialiseObjects.cs b/OpenSim/Region/Environment/Modules/World/Serialiser/SerialiseObjects.cs index c14ae57..ef90fd4 100644 --- a/OpenSim/Region/Environment/Modules/World/Serialiser/SerialiseObjects.cs +++ b/OpenSim/Region/Environment/Modules/World/Serialiser/SerialiseObjects.cs @@ -110,6 +110,7 @@ namespace OpenSim.Region.Environment.Modules.ExportSerialiser private static void CreateCompressedXmlFile(MemoryStream xmlStream, string fileName) { #region GZip Compressed Version + FileStream objectsFileCompressed = new FileStream(fileName + ".gzs", FileMode.Create); MemoryStream gzipMSStream = new MemoryStream(); GZipStream gzipStream = new GZipStream(gzipMSStream, CompressionMode.Compress); @@ -117,6 +118,7 @@ namespace OpenSim.Region.Environment.Modules.ExportSerialiser gzipMSStream.WriteTo(objectsFileCompressed); objectsFileCompressed.Flush(); objectsFileCompressed.Close(); + #endregion } } diff --git a/OpenSim/Region/Environment/Modules/World/Sun/SunModule.cs b/OpenSim/Region/Environment/Modules/World/Sun/SunModule.cs index a465a60..a12118e 100644 --- a/OpenSim/Region/Environment/Modules/World/Sun/SunModule.cs +++ b/OpenSim/Region/Environment/Modules/World/Sun/SunModule.cs @@ -39,15 +39,17 @@ namespace OpenSim.Region.Environment.Modules { //private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - private const double m_real_day = 24.0; private const int m_default_frame = 100; - private int m_frame_mod; + private const double m_real_day = 24.0; private double m_day_length; private int m_dilation; private int m_frame; - private long m_start; + private int m_frame_mod; private Scene m_scene; + private long m_start; + + #region IRegionModule Members public void Initialise(Scene scene, IConfigSource config) { @@ -66,7 +68,7 @@ namespace OpenSim.Region.Environment.Modules m_frame_mod = m_default_frame; } - m_dilation = (int) (m_real_day/m_day_length); + m_dilation = (int) (m_real_day / m_day_length); m_scene = scene; scene.EventManager.OnFrame += SunUpdate; scene.EventManager.OnNewClient += SunToClient; @@ -90,6 +92,8 @@ namespace OpenSim.Region.Environment.Modules get { return false; } } + #endregion + public void SunToClient(IClientAPI client) { client.SendSunPos(SunPos(HourOfTheDay()), new LLVector3(0, 0.0f, 10.0f)); @@ -121,15 +125,15 @@ namespace OpenSim.Region.Environment.Modules // ticks don't get out of hand private double HourOfTheDay() { - long m_addticks = (DateTime.Now.Ticks - m_start)*m_dilation; + long m_addticks = (DateTime.Now.Ticks - m_start) * m_dilation; DateTime dt = new DateTime(m_start + m_addticks); - return (double) dt.Hour + ((double) dt.Minute/60.0); + return (double) dt.Hour + ((double) dt.Minute / 60.0); } private LLVector3 SunPos(double hour) { // now we have our radian position - double rad = (hour/m_real_day)*2*Math.PI - (Math.PI/2.0); + double rad = (hour / m_real_day) * 2 * Math.PI - (Math.PI / 2.0); double z = Math.Sin(rad); double x = Math.Cos(rad); return new LLVector3((float) x, 0f, (float) z); @@ -192,4 +196,4 @@ namespace OpenSim.Region.Environment.Modules // // OutPacket(viewertime); // } } -} +} \ No newline at end of file diff --git a/OpenSim/Region/Environment/Modules/World/Terrain/FileLoaders/GIF.cs b/OpenSim/Region/Environment/Modules/World/Terrain/FileLoaders/GIF.cs index 1dd923a..9c2fedc 100644 --- a/OpenSim/Region/Environment/Modules/World/Terrain/FileLoaders/GIF.cs +++ b/OpenSim/Region/Environment/Modules/World/Terrain/FileLoaders/GIF.cs @@ -27,7 +27,6 @@ using System.Drawing; using System.Drawing.Imaging; using OpenSim.Region.Environment.Interfaces; -using OpenSim.Region.Environment.Modules.World.Terrain.FileLoaders; namespace OpenSim.Region.Environment.Modules.World.Terrain.FileLoaders { diff --git a/OpenSim/Region/Environment/Modules/World/Terrain/FileLoaders/PNG.cs b/OpenSim/Region/Environment/Modules/World/Terrain/FileLoaders/PNG.cs index 07072be..2925c7d 100644 --- a/OpenSim/Region/Environment/Modules/World/Terrain/FileLoaders/PNG.cs +++ b/OpenSim/Region/Environment/Modules/World/Terrain/FileLoaders/PNG.cs @@ -27,7 +27,6 @@ using System.Drawing; using System.Drawing.Imaging; using OpenSim.Region.Environment.Interfaces; -using OpenSim.Region.Environment.Modules.World.Terrain.FileLoaders; namespace OpenSim.Region.Environment.Modules.World.Terrain.FileLoaders { diff --git a/OpenSim/Region/Environment/Modules/World/Terrain/FileLoaders/TIFF.cs b/OpenSim/Region/Environment/Modules/World/Terrain/FileLoaders/TIFF.cs index d206763..3a137ae 100644 --- a/OpenSim/Region/Environment/Modules/World/Terrain/FileLoaders/TIFF.cs +++ b/OpenSim/Region/Environment/Modules/World/Terrain/FileLoaders/TIFF.cs @@ -27,7 +27,6 @@ using System.Drawing; using System.Drawing.Imaging; using OpenSim.Region.Environment.Interfaces; -using OpenSim.Region.Environment.Modules.World.Terrain.FileLoaders; namespace OpenSim.Region.Environment.Modules.World.Terrain.FileLoaders { diff --git a/OpenSim/Region/Environment/Modules/World/Terrain/TerrainModule.cs b/OpenSim/Region/Environment/Modules/World/Terrain/TerrainModule.cs index cf85aa4..09c3117 100644 --- a/OpenSim/Region/Environment/Modules/World/Terrain/TerrainModule.cs +++ b/OpenSim/Region/Environment/Modules/World/Terrain/TerrainModule.cs @@ -35,7 +35,6 @@ using Nini.Config; using OpenSim.Framework; using OpenSim.Region.Environment.Interfaces; using OpenSim.Region.Environment.Modules.Framework; -using OpenSim.Region.Environment.Modules.World.Terrain; using OpenSim.Region.Environment.Modules.World.Terrain.FileLoaders; using OpenSim.Region.Environment.Modules.World.Terrain.FloodBrushes; using OpenSim.Region.Environment.Modules.World.Terrain.PaintBrushes; @@ -79,9 +78,8 @@ namespace OpenSim.Region.Environment.Modules.World.Terrain private readonly Dictionary m_painteffects = new Dictionary(); - private Dictionary m_channels; - private ITerrainChannel m_channel; + private Dictionary m_channels; private Dictionary m_plugineffects; private ITerrainChannel m_revert; private Scene m_scene; @@ -252,7 +250,8 @@ namespace OpenSim.Region.Environment.Modules.World.Terrain { m_plugineffects.Add(pluginType.Name, terEffect); m_log.Info("E ... " + pluginType.Name); - } else + } + else { m_log.Warn("E ... " + pluginType.Name + " (Already added)"); } diff --git a/OpenSim/Region/Environment/Modules/World/TreePopulator/TreePopulatorModule.cs b/OpenSim/Region/Environment/Modules/World/TreePopulator/TreePopulatorModule.cs index ce93060..f144444 100644 --- a/OpenSim/Region/Environment/Modules/World/TreePopulator/TreePopulatorModule.cs +++ b/OpenSim/Region/Environment/Modules/World/TreePopulator/TreePopulatorModule.cs @@ -44,13 +44,14 @@ namespace OpenSim.Region.Environment.Modules /// public class TreePopulatorModule : IRegionModule { - private Scene m_scene; private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private List m_trees; + private Scene m_scene; public double m_tree_density = 50.0; // Aim for this many per region public double m_tree_updates = 1000.0; // MS between updates + private List m_trees; + + #region IRegionModule Members public void Initialise(Scene scene, IConfigSource config) { @@ -59,7 +60,8 @@ namespace OpenSim.Region.Environment.Modules m_tree_density = config.Configs["Trees"].GetDouble("tree_density", m_tree_density); } catch (Exception) - { } + { + } m_trees = new List(); m_scene = scene; @@ -72,7 +74,27 @@ namespace OpenSim.Region.Environment.Modules m_log.Debug("[TREES]: Initialised tree module"); } - void EventManager_OnPluginConsole(string[] args) + public void PostInitialise() + { + } + + public void Close() + { + } + + public string Name + { + get { return "TreePopulatorModule"; } + } + + public bool IsSharedModule + { + get { return false; } + } + + #endregion + + private void EventManager_OnPluginConsole(string[] args) { if (args[0] == "tree") { @@ -81,13 +103,13 @@ namespace OpenSim.Region.Environment.Modules } } - void growTrees() + private void growTrees() { foreach (LLUUID tree in m_trees) { if (m_scene.Entities.ContainsKey(tree)) { - SceneObjectPart s_tree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart; + SceneObjectPart s_tree = ((SceneObjectGroup) m_scene.Entities[tree]).RootPart; // 100 seconds to grow 1m s_tree.Scale += new LLVector3(0.1f, 0.1f, 0.1f); @@ -101,13 +123,13 @@ namespace OpenSim.Region.Environment.Modules } } - void seedTrees() + private void seedTrees() { foreach (LLUUID tree in m_trees) { if (m_scene.Entities.ContainsKey(tree)) { - SceneObjectPart s_tree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart; + SceneObjectPart s_tree = ((SceneObjectGroup) m_scene.Entities[tree]).RootPart; if (s_tree.Scale.X > 0.5) { @@ -116,7 +138,6 @@ namespace OpenSim.Region.Environment.Modules SpawnChild(s_tree); } } - } else { @@ -125,7 +146,7 @@ namespace OpenSim.Region.Environment.Modules } } - void killTrees() + private void killTrees() { foreach (LLUUID tree in m_trees) { @@ -133,7 +154,7 @@ namespace OpenSim.Region.Environment.Modules if (m_scene.Entities.ContainsKey(tree)) { - SceneObjectPart selectedTree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart; + SceneObjectPart selectedTree = ((SceneObjectGroup) m_scene.Entities[tree]).RootPart; double selectedTreeScale = Math.Sqrt(Math.Pow(selectedTree.Scale.X, 2) + Math.Pow(selectedTree.Scale.Y, 2) + Math.Pow(selectedTree.Scale.Z, 2)); @@ -142,7 +163,7 @@ namespace OpenSim.Region.Environment.Modules { if (picktree != tree) { - SceneObjectPart pickedTree = ((SceneObjectGroup)m_scene.Entities[picktree]).RootPart; + SceneObjectPart pickedTree = ((SceneObjectGroup) m_scene.Entities[picktree]).RootPart; double pickedTreeScale = Math.Sqrt(Math.Pow(pickedTree.Scale.X, 2) + Math.Pow(pickedTree.Scale.Y, 2) + @@ -162,10 +183,10 @@ namespace OpenSim.Region.Environment.Modules m_trees.Remove(selectedTree.ParentGroup.UUID); m_scene.ForEachClient(delegate(IClientAPI controller) - { - controller.SendKillObject(m_scene.RegionInfo.RegionHandle, - selectedTree.LocalId); - }); + { + controller.SendKillObject(m_scene.RegionInfo.RegionHandle, + selectedTree.LocalId); + }); break; } @@ -199,15 +220,15 @@ namespace OpenSim.Region.Environment.Modules double randX = ((Util.RandomClass.NextDouble() * 2.0) - 1.0) * (s_tree.Scale.X * 3); double randY = ((Util.RandomClass.NextDouble() * 2.0) - 1.0) * (s_tree.Scale.X * 3); - position.X += (float)randX; - position.Y += (float)randY; + position.X += (float) randX; + position.Y += (float) randY; CreateTree(position); } private void CreateTree(LLVector3 position) { - position.Z = (float)m_scene.Heightmap[(int)position.X, (int)position.Y]; + position.Z = (float) m_scene.Heightmap[(int) position.X, (int) position.Y]; SceneObjectGroup tree = m_scene.AddTree(new LLVector3(0.1f, 0.1f, 0.1f), @@ -220,29 +241,11 @@ namespace OpenSim.Region.Environment.Modules tree.SendGroupFullUpdate(); } - void CalculateTrees_Elapsed(object sender, ElapsedEventArgs e) + private void CalculateTrees_Elapsed(object sender, ElapsedEventArgs e) { growTrees(); seedTrees(); killTrees(); } - - public void PostInitialise() - { - } - - public void Close() - { - } - - public string Name - { - get { return "TreePopulatorModule"; } - } - - public bool IsSharedModule - { - get { return false; } - } } -} +} \ No newline at end of file -- cgit v1.1