From 5e4d6cab00cb29cd088ab7b62ab13aff103b64cb Mon Sep 17 00:00:00 2001 From: onefang Date: Sun, 19 May 2019 21:24:15 +1000 Subject: Dump OpenSim 0.9.0.1 into it's own branch. --- .../Server/IRCClientView.cs | 352 ++++++--- .../Agent/TextureSender/J2KDecoderCommandModule.cs | 20 +- .../Agent/UDP/Linden/LindenUDPInfoModule.cs | 299 ++----- .../OptionalModules/Asset/AssetInfoModule.cs | 32 +- .../Avatar/Animations/AnimationsCommandModule.cs | 31 +- .../Avatar/Appearance/AppearanceInfoModule.cs | 42 +- .../Avatar/Attachments/AttachmentsCommandModule.cs | 43 +- .../Avatar/Attachments/TempAttachmentsModule.cs | 29 +- .../OptionalModules/Avatar/Chat/ChannelState.cs | 27 +- .../OptionalModules/Avatar/Chat/IRCBridgeModule.cs | 4 +- .../OptionalModules/Avatar/Chat/IRCConnector.cs | 58 +- .../OptionalModules/Avatar/Chat/RegionState.cs | 43 +- .../Avatar/Concierge/ConciergeModule.cs | 87 +- .../Avatar/Friends/FriendsCommandsModule.cs | 20 +- .../Avatar/SitStand/SitStandCommandsModule.cs | 22 +- .../Voice/FreeSwitchVoice/FreeSwitchVoiceModule.cs | 64 +- .../Avatar/Voice/VivoxVoice/VivoxVoiceModule.cs | 183 +++-- .../Avatar/XmlRpcGroups/GroupsMessagingModule.cs | 237 +++--- .../Avatar/XmlRpcGroups/GroupsModule.cs | 517 ++++++------ .../XmlRpcGroups/IGroupsServicesConnector.cs | 7 +- .../SimianGroupsServicesConnectorModule.cs | 95 ++- .../Avatar/XmlRpcGroups/Tests/GroupsModuleTests.cs | 23 +- .../XmlRpcGroupsServicesConnectorModule.cs | 86 +- .../DataSnapshot/DataSnapshotManager.cs | 5 +- .../OptionalModules/DataSnapshot/LandSnapshot.cs | 13 +- .../OptionalModules/DataSnapshot/ObjectSnapshot.cs | 3 +- .../BareBonesNonShared/BareBonesNonSharedModule.cs | 28 +- .../BareBonesShared/BareBonesSharedModule.cs | 32 +- .../WebSocketEchoTest/WebSocketEchoModule.cs | 10 +- .../Framework/Monitoring/EtcdMonitoringModule.cs | 195 +++++ .../Framework/Monitoring/MonitorServicesModule.cs | 8 +- .../OptionalModules/Materials/MaterialsModule.cs | 453 +++++++---- .../PhysicsParameters/PhysicsParameters.cs | 18 +- .../PrimLimitsModule/PrimLimitsModule.cs | 125 +-- .../OptionalModules/Properties/AssemblyInfo.cs | 10 +- .../RegionCombinerClientEventForwarder.cs | 94 --- .../RegionCombinerIndividualEventForwarder.cs | 139 ---- .../RegionCombinerLargeLandChannel.cs | 201 ----- .../RegionCombinerModule/RegionCombinerModule.cs | 880 --------------------- .../RegionCombinerPermissionModule.cs | 270 ------- .../RegionCombinerModule/RegionConnections.cs | 94 --- .../RegionCombinerModule/RegionCourseLocation.cs | 43 - .../RegionCombinerModule/RegionData.cs | 40 - .../Scripting/JsonStore/JsonStore.cs | 130 +-- .../Scripting/JsonStore/JsonStoreCommands.cs | 8 +- .../Scripting/JsonStore/JsonStoreModule.cs | 78 +- .../Scripting/JsonStore/JsonStoreScriptModule.cs | 114 +-- .../JsonStore/Tests/JsonStoreScriptModuleTests.cs | 80 +- .../Minimodule/Interfaces/IAvatarAttachment.cs | 2 +- .../Minimodule/Interfaces/IInventoryItem.cs | 2 +- .../Scripting/Minimodule/Interfaces/IObject.cs | 16 +- .../Scripting/Minimodule/InventoryItem.cs | 8 +- .../Scripting/Minimodule/MicroScheduler.cs | 2 +- .../Scripting/Minimodule/SOPObject.cs | 28 +- .../Scripting/Minimodule/SOPObjectInventory.cs | 36 +- .../Scripting/Minimodule/SPAvatar.cs | 8 +- .../Scripting/Minimodule/SPAvatarAttachment.cs | 6 +- .../Scripting/Minimodule/Test/TestModule.cs | 4 +- .../OptionalModules/Scripting/Minimodule/World.cs | 6 +- .../RegionReadyModule/RegionReadyModule.cs | 38 +- .../XmlRpcRouterModule/XmlRpcGridRouterModule.cs | 8 +- .../XmlRpcRouterModule/XmlRpcRouterModule.cs | 5 +- .../FreeswitchServiceInConnectorModule.cs | 4 +- .../UserStatistics/Clients_report.cs | 23 +- .../UserStatistics/Default_Report.cs | 19 +- .../OptionalModules/UserStatistics/HTMLUtil.cs | 4 +- .../OptionalModules/UserStatistics/LogLinesAJAX.cs | 12 +- .../UserStatistics/Prototype_distributor.cs | 2 +- .../UserStatistics/Sessions_Report.cs | 11 +- .../OptionalModules/UserStatistics/SimStatsAJAX.cs | 8 +- .../UserStatistics/WebStatsModule.cs | 40 +- .../ViewerSupport/CameraOnlyModeModule.cs | 7 +- .../ViewerSupport/DynamicFloaterModule.cs | 2 +- .../ViewerSupport/DynamicMenuModule.cs | 11 +- .../ViewerSupport/GodNamesModule.cs | 4 +- .../ViewerSupport/SimulatorFeaturesHelper.cs | 102 +-- .../ViewerSupport/SpecialUIModule.cs | 5 +- .../World/AutoBackup/AutoBackupModule.cs | 791 ++++++------------ .../World/AutoBackup/AutoBackupModuleState.cs | 70 +- .../World/MoneyModule/SampleMoneyModule.cs | 156 ++-- .../Region/OptionalModules/World/NPC/NPCAvatar.cs | 181 ++++- .../Region/OptionalModules/World/NPC/NPCModule.cs | 99 ++- .../World/NPC/Tests/NPCModuleTests.cs | 8 +- .../World/SceneCommands/SceneCommandsModule.cs | 122 +-- .../World/TreePopulator/TreePopulatorModule.cs | 724 ++++++++++------- 85 files changed, 3198 insertions(+), 4768 deletions(-) create mode 100644 OpenSim/Region/OptionalModules/Framework/Monitoring/EtcdMonitoringModule.cs mode change 100644 => 100755 OpenSim/Region/OptionalModules/PhysicsParameters/PhysicsParameters.cs delete mode 100644 OpenSim/Region/OptionalModules/RegionCombinerModule/RegionCombinerClientEventForwarder.cs delete mode 100644 OpenSim/Region/OptionalModules/RegionCombinerModule/RegionCombinerIndividualEventForwarder.cs delete mode 100644 OpenSim/Region/OptionalModules/RegionCombinerModule/RegionCombinerLargeLandChannel.cs delete mode 100644 OpenSim/Region/OptionalModules/RegionCombinerModule/RegionCombinerModule.cs delete mode 100644 OpenSim/Region/OptionalModules/RegionCombinerModule/RegionCombinerPermissionModule.cs delete mode 100644 OpenSim/Region/OptionalModules/RegionCombinerModule/RegionConnections.cs delete mode 100644 OpenSim/Region/OptionalModules/RegionCombinerModule/RegionCourseLocation.cs delete mode 100644 OpenSim/Region/OptionalModules/RegionCombinerModule/RegionData.cs (limited to 'OpenSim/Region/OptionalModules') diff --git a/OpenSim/Region/OptionalModules/Agent/InternetRelayClientView/Server/IRCClientView.cs b/OpenSim/Region/OptionalModules/Agent/InternetRelayClientView/Server/IRCClientView.cs index 6fe86b2..469dd67 100644 --- a/OpenSim/Region/OptionalModules/Agent/InternetRelayClientView/Server/IRCClientView.cs +++ b/OpenSim/Region/OptionalModules/Agent/InternetRelayClientView/Server/IRCClientView.cs @@ -58,6 +58,8 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server public ISceneAgent SceneAgent { get; set; } + public int PingTimeMS { get { return 0; } } + private string m_username; private string m_nick; @@ -66,6 +68,8 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server private bool m_connected = true; + public List SelectedObjects {get; private set;} + public IRCClientView(TcpClient client, Scene scene) { m_client = client; @@ -566,18 +570,28 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server public UUID ActiveGroupId { get { return UUID.Zero; } + set {} } public string ActiveGroupName { get { return "IRCd User"; } + set {} } public ulong ActiveGroupPowers { get { return 0; } + set {} + } + + public Dictionary GetGroupPowers() + { + return new Dictionary(); } + public void SetGroupPowers(Dictionary powers) { } + public ulong GetGroupPowers(UUID groupID) { return 0; @@ -671,6 +685,7 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server public event ObjectDrop OnObjectDrop; public event StartAnim OnStartAnim; public event StopAnim OnStopAnim; + public event ChangeAnim OnChangeAnim; public event LinkObjects OnLinkObjects; public event DelinkObjects OnDelinkObjects; public event RequestMapBlocks OnRequestMapBlocks; @@ -682,6 +697,7 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server public event TeleportLandmarkRequest OnTeleportLandmarkRequest; public event TeleportCancel OnTeleportCancel; public event DeRezObject OnDeRezObject; + public event RezRestoreToWorld OnRezRestoreToWorld; public event Action OnRegionHandShakeReply; public event GenericCall1 OnRequestWearables; public event Action OnCompleteMovementToRegion; @@ -717,6 +733,7 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server public event RequestObjectPropertiesFamily OnRequestObjectPropertiesFamily; public event UpdatePrimFlags OnUpdatePrimFlags; public event UpdatePrimTexture OnUpdatePrimTexture; + public event ClientChangeObject onClientChangeObject; public event UpdateVector OnUpdatePrimGroupPosition; public event UpdateVector OnUpdatePrimSinglePosition; public event UpdatePrimRotation OnUpdatePrimGroupRotation; @@ -821,6 +838,7 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server public event ObjectOwner OnObjectOwner; public event DirPlacesQuery OnDirPlacesQuery; public event DirFindQuery OnDirFindQuery; + public event MoveItemsAndLeaveCopy OnMoveItemsAndLeaveCopy; public event DirLandQuery OnDirLandQuery; public event DirPopularQuery OnDirPopularQuery; public event DirClassifiedQuery OnDirClassifiedQuery; @@ -837,7 +855,7 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server public event ClassifiedInfoRequest OnClassifiedInfoRequest; public event ClassifiedInfoUpdate OnClassifiedInfoUpdate; public event ClassifiedDelete OnClassifiedDelete; - public event ClassifiedDelete OnClassifiedGodDelete; + public event ClassifiedGodDelete OnClassifiedGodDelete; public event EventNotificationAddRequest OnEventNotificationAddRequest; public event EventNotificationRemoveRequest OnEventNotificationRemoveRequest; public event EventGodDelete OnEventGodDelete; @@ -867,10 +885,12 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server public event GroupVoteHistoryRequest OnGroupVoteHistoryRequest; public event SimWideDeletesDelegate OnSimWideDeletes; public event SendPostcard OnSendPostcard; + public event ChangeInventoryItemFlags OnChangeInventoryItemFlags; public event MuteListEntryUpdate OnUpdateMuteListEntry; public event MuteListEntryRemove OnRemoveMuteListEntry; public event GodlikeMessage onGodlikeMessage; public event GodUpdateRegionInfoUpdate OnGodUpdateRegionInfoUpdate; + public event GenericCall2 OnUpdateThrottles; #pragma warning restore 67 @@ -878,20 +898,20 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server public void InPacket(object NewPack) { - + } public void ProcessInPacket(Packet NewPack) { - + } public void Close() { - Close(false); + Close(true, false); } - public void Close(bool force) + public void Close(bool sendStop, bool force) { Disconnect(); } @@ -933,32 +953,32 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server public void SendWearables(AvatarWearable[] wearables, int serial) { - + } public void SendAppearance(UUID agentID, byte[] visualParams, byte[] textureEntry) { - + } - + public void SendCachedTextureResponse(ISceneEntity avatar, int serial, List cachedTextures) { } - + public void SendStartPingCheck(byte seq) { - + } public void SendKillObject(List localID) { - + } public void SendAnimations(UUID[] animID, int[] seqs, UUID sourceAgentId, UUID[] objectIDs) { - + } public void SendChatMessage( @@ -985,37 +1005,42 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server public void SendGenericMessage(string method, UUID invoice, List message) { - + + } + + public virtual bool CanSendLayerData() + { + return false; } public void SendLayerData(float[] map) { - + } public void SendLayerData(int px, int py, float[] map) { - + } - public void SendWindData(Vector2[] windSpeeds) + public void SendWindData(int version, Vector2[] windSpeeds) { - + } - public void SendCloudData(float[] cloudCover) + public void SendCloudData(int version, float[] cloudCover) { - + } public void MoveAgentIntoRegion(RegionInfo regInfo, Vector3 pos, Vector3 look) { - + } public void InformClientOfNeighbour(ulong neighbourHandle, IPEndPoint neighbourExternalEndPoint) { - + } public AgentCircuitData RequestClientInfo() @@ -1025,32 +1050,32 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server public void CrossRegion(ulong newRegionHandle, Vector3 pos, Vector3 lookAt, IPEndPoint newRegionExternalEndPoint, string capsURL) { - + } public void SendMapBlock(List mapBlocks, uint flag) { - + } public void SendLocalTeleport(Vector3 position, Vector3 lookAt, uint flags) { - + } public void SendRegionTeleport(ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint, uint locationID, uint flags, string capsURL) { - + } public void SendTeleportFailed(string reason) { - + } public void SendTeleportStart(uint flags) { - + } public void SendTeleportProgress(uint flags, string message) @@ -1059,20 +1084,25 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server public void SendMoneyBalance(UUID transaction, bool success, byte[] description, int balance, int transactionType, UUID sourceID, bool sourceIsGroup, UUID destID, bool destIsGroup, int amount, string item) { - + } public void SendPayPrice(UUID objectID, int[] payPrice) { - + } public void SendCoarseLocationUpdate(List users, List CoarseLocations) { - + } - public void SendAvatarDataImmediate(ISceneEntity avatar) + public void SendEntityFullUpdateImmediate(ISceneEntity ent) + { + + } + + public void SendEntityTerseUpdateImmediate(ISceneEntity ent) { } @@ -1094,87 +1124,92 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server public void SendInventoryFolderDetails(UUID ownerID, UUID folderID, List items, List folders, int version, bool fetchFolders, bool fetchItems) { - + } public void SendInventoryItemDetails(UUID ownerID, InventoryItemBase item) { - + } public void SendInventoryItemCreateUpdate(InventoryItemBase Item, uint callbackId) { - + + } + + public void SendInventoryItemCreateUpdate(InventoryItemBase Item, UUID transactionID, uint callbackId) + { + } public void SendRemoveInventoryItem(UUID itemID) { - + } public void SendTakeControls(int controls, bool passToAgent, bool TakeControls) { - + } public void SendTaskInventory(UUID taskID, short serial, byte[] fileName) { - + } public void SendBulkUpdateInventory(InventoryNodeBase node) { - + } - public void SendXferPacket(ulong xferID, uint packet, byte[] data) + public void SendXferPacket(ulong xferID, uint packet, byte[] data, bool isTaskInventory) { - + } public void SendAbortXferPacket(ulong xferID) { - + } public void SendEconomyData(float EnergyEfficiency, int ObjectCapacity, int ObjectCount, int PriceEnergyUnit, int PriceGroupCreate, int PriceObjectClaim, float PriceObjectRent, float PriceObjectScaleFactor, int PriceParcelClaim, float PriceParcelClaimFactor, int PriceParcelRent, int PricePublicObjectDecay, int PricePublicObjectDelete, int PriceRentLight, int PriceUpload, int TeleportMinPrice, float TeleportPriceExponent) { - + } public void SendAvatarPickerReply(AvatarPickerReplyAgentDataArgs AgentData, List Data) { - + } public void SendAgentDataUpdate(UUID agentid, UUID activegroupid, string firstname, string lastname, ulong grouppowers, string groupname, string grouptitle) { - + } public void SendPreLoadSound(UUID objectID, UUID ownerID, UUID soundID) { - + } public void SendPlayAttachedSound(UUID soundID, UUID objectID, UUID ownerID, float gain, byte flags) { - + } public void SendTriggeredSound(UUID soundID, UUID ownerID, UUID objectID, UUID parentID, ulong handle, Vector3 position, float gain) { - + } public void SendAttachedSoundGainChange(UUID objectID, float gain) { - + } public void SendNameReply(UUID profileId, string firstname, string lastname) { - + } public void SendAlertMessage(string message) @@ -1184,7 +1219,12 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server public void SendAgentAlertMessage(string message, bool modal) { - + + } + + public void SendAlertMessage(string message, string info) + { + } public void SendLoadURL(string objectname, UUID objectID, UUID ownerID, bool groupOwned, string message, string url) @@ -1194,77 +1234,77 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server public void SendDialog(string objectname, UUID objectID, UUID ownerID, string ownerFirstName, string ownerLastName, string msg, UUID textureID, int ch, string[] buttonlabels) { - + } public void SendSunPos(Vector3 sunPos, Vector3 sunVel, ulong CurrentTime, uint SecondsPerSunCycle, uint SecondsPerYear, float OrbitalPosition) { - + } public void SendViewerEffect(ViewerEffectPacket.EffectBlock[] effectBlocks) { - + } public void SendViewerTime(int phase) { - + } - public void SendAvatarProperties(UUID avatarID, string aboutText, string bornOn, byte[] charterMember, string flAbout, uint flags, UUID flImageID, UUID imageID, string profileURL, UUID partnerID) + public void SendAvatarProperties(UUID avatarID, string aboutText, string bornOn, byte[] membershipType, string flAbout, uint flags, UUID flImageID, UUID imageID, string profileURL, UUID partnerID) { - + } public void SendScriptQuestion(UUID taskID, string taskName, string ownerName, UUID itemID, int question) { - + } public void SendHealth(float health) { - + } public void SendEstateList(UUID invoice, int code, UUID[] Data, uint estateID) { - + } public void SendBannedUserList(UUID invoice, EstateBan[] banlist, uint estateID) { - + } public void SendRegionInfoToEstateMenu(RegionInfoForEstateMenuArgs args) { - + } public void SendEstateCovenantInformation(UUID covenant) { - + } public void SendDetailedEstateData(UUID invoice, string estateName, uint estateID, uint parentEstate, uint estateFlags, uint sunPosition, UUID covenant, uint covenantChanged, string abuseEmail, UUID estateOwner) { - + } public void SendLandProperties(int sequence_id, bool snap_selection, int request_result, ILandObject lo, float simObjectBonusFactor, int parcelObjectCapacity, int simObjectCapacity, uint regionFlags) { - + } public void SendLandAccessListData(List accessList, uint accessFlag, int localLandID) { - + } public void SendForceClientSelectObjects(List objectIDs) { - + } public void SendCameraConstraint(Vector4 ConstraintPlane) @@ -1274,57 +1314,57 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server public void SendLandObjectOwners(LandData land, List groups, Dictionary ownersAndCount) { - + } public void SendLandParcelOverlay(byte[] data, int sequence_id) { - + } public void SendParcelMediaCommand(uint flags, ParcelMediaCommandEnum command, float time) { - + } public void SendParcelMediaUpdate(string mediaUrl, UUID mediaTextureID, byte autoScale, string mediaType, string mediaDesc, int mediaWidth, int mediaHeight, byte mediaLoop) { - + } public void SendAssetUploadCompleteMessage(sbyte AssetType, bool Success, UUID AssetFullID) { - + } public void SendConfirmXfer(ulong xferID, uint PacketID) { - + } public void SendXferRequest(ulong XferID, short AssetType, UUID vFileID, byte FilePath, byte[] FileName) { - + } public void SendInitiateDownload(string simFileName, string clientFileName) { - + } public void SendImageFirstPart(ushort numParts, UUID ImageUUID, uint ImageSize, byte[] ImageData, byte imageCodec) { - + } public void SendImageNextPart(ushort partNumber, UUID imageUuid, byte[] imageData) { - + } public void SendImageNotFound(UUID imageid) { - + } public void SendShutdownConnectionNotice() @@ -1334,12 +1374,12 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server public void SendSimStats(SimStats stats) { - + } public void SendObjectPropertiesFamilyData(ISceneEntity Entity, uint RequestFlags) { - + } public void SendObjectPropertiesReply(ISceneEntity entity) @@ -1348,72 +1388,76 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server public void SendAgentOffline(UUID[] agentIDs) { - + } public void SendAgentOnline(UUID[] agentIDs) { - + + } + + public void SendFindAgent(UUID HunterID, UUID PreyID, double GlobalX, double GlobalY) + { } public void SendSitResponse(UUID TargetID, Vector3 OffsetPos, Quaternion SitOrientation, bool autopilot, Vector3 CameraAtOffset, Vector3 CameraEyeOffset, bool ForceMouseLook) { - + } public void SendAdminResponse(UUID Token, uint AdminLevel) { - + } public void SendGroupMembership(GroupMembershipData[] GroupMembership) { - + } public void SendGroupNameReply(UUID groupLLUID, string GroupName) { - + } public void SendJoinGroupReply(UUID groupID, bool success) { - + } public void SendEjectGroupMemberReply(UUID agentID, UUID groupID, bool success) { - + } public void SendLeaveGroupReply(UUID groupID, bool success) { - + } public void SendCreateGroupReply(UUID groupID, bool success, string message) { - + } public void SendLandStatReply(uint reportType, uint requestFlags, uint resultCount, LandStatReportItem[] lsrpia) { - + } public void SendScriptRunningReply(UUID objectID, UUID itemID, bool running) { - + } public void SendAsset(AssetRequestToClient req) { - + } public void SendTexture(AssetBase TextureAsset) { - + } public virtual void SetChildAgentThrottle(byte[] throttle) @@ -1421,6 +1465,16 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server } + public virtual void SetChildAgentThrottle(byte[] throttle,float factor) + { + + } + + public void SetAgentThrottleSilent(int throttle, int setting) + { + + + } public byte[] GetThrottlesPacked(float multiplier) { return new byte[0]; @@ -1449,12 +1503,12 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server public void SetClientInfo(ClientInfo info) { - + } public void SetClientOption(string option, string value) { - + } public string GetClientOption(string option) @@ -1469,67 +1523,67 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server public void SendSetFollowCamProperties(UUID objectID, SortedDictionary parameters) { - + } public void SendClearFollowCamProperties(UUID objectID) { - + } public void SendRegionHandle(UUID regoinID, ulong handle) { - + } public void SendParcelInfo(RegionInfo info, LandData land, UUID parcelID, uint x, uint y) { - + } public void SendScriptTeleportRequest(string objName, string simName, Vector3 pos, Vector3 lookAt) { - + } public void SendDirPlacesReply(UUID queryID, DirPlacesReplyData[] data) { - + } public void SendDirPeopleReply(UUID queryID, DirPeopleReplyData[] data) { - + } public void SendDirEventsReply(UUID queryID, DirEventsReplyData[] data) { - + } public void SendDirGroupsReply(UUID queryID, DirGroupsReplyData[] data) { - + } public void SendDirClassifiedReply(UUID queryID, DirClassifiedReplyData[] data) { - + } public void SendDirLandReply(UUID queryID, DirLandReplyData[] data) { - + } public void SendDirPopularReply(UUID queryID, DirPopularReplyData[] data) { - + } public void SendEventInfoReply(EventData info) { - + } public void SendTelehubInfo(UUID ObjectID, string ObjectName, Vector3 ObjectPos, Quaternion ObjectRot, List SpawnPoint) @@ -1539,72 +1593,93 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server public void SendMapItemReply(mapItemReply[] replies, uint mapitemtype, uint flags) { - + } public void SendAvatarGroupsReply(UUID avatarID, GroupMembershipData[] data) { - + + } + + public void SendAgentGroupDataUpdate(UUID avatarID, GroupMembershipData[] data) + { + } public void SendOfferCallingCard(UUID srcID, UUID transactionID) { - + } public void SendAcceptCallingCard(UUID transactionID) { - + } public void SendDeclineCallingCard(UUID transactionID) { - + } public void SendTerminateFriend(UUID exFriendID) { - + } public void SendAvatarClassifiedReply(UUID targetID, UUID[] classifiedID, string[] name) { - + } public void SendClassifiedInfoReply(UUID classifiedID, UUID creatorID, uint creationDate, uint expirationDate, uint category, string name, string description, UUID parcelID, uint parentEstate, UUID snapshotID, string simName, Vector3 globalPos, string parcelName, byte classifiedFlags, int price) { - + } public void SendAgentDropGroup(UUID groupID) { - + } public void RefreshGroupMembership() { - + + } + + public void UpdateGroupMembership(GroupMembershipData[] data) + { + } + public void GroupMembershipRemove(UUID GroupID) + { + + } + + public void GroupMembershipAddReplace(UUID GroupID,ulong GroupPowers) + { + + } + + public void SendAvatarNotesReply(UUID targetID, string text) { - + } public void SendAvatarPicksReply(UUID targetID, Dictionary picks) { - + } public void SendPickInfoReply(UUID pickID, UUID creatorID, bool topPick, UUID parcelID, string name, string desc, UUID snapshotID, string user, string originalName, string simName, Vector3 posGlobal, int sortOrder, bool enabled) { - + } public void SendAvatarClassifiedReply(UUID targetID, Dictionary classifieds) { - + } public void SendAvatarInterestUpdate(IClientAPI client, uint wantmask, string wanttext, uint skillsmask, string skillstext, string languages) @@ -1614,22 +1689,27 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server public void SendParcelDwellReply(int localID, UUID parcelID, float dwell) { - + } public void SendUserInfoReply(bool imViaEmail, bool visible, string email) { - + } public void SendUseCachedMuteList() { - + + } + + public void SendEmpytMuteList() + { + } public void SendMuteListUpdate(string filename) { - + } public bool AddGenericPacketHandler(string MethodName, GenericMessage handler) @@ -1646,15 +1726,15 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server public void SendAvatarInterestsReply(UUID avatarID, uint wantMask, string wantText, uint skillsMask, string skillsText, string languages) { } - + public void SendGroupAccountingDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID, int amt) { } - + public void SendGroupAccountingSummary(IClientAPI sender,UUID groupID, uint moneyAmt, int totalTier, int usedTier) { } - + public void SendGroupTransactionsSummaryDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID,int amt) { } @@ -1678,14 +1758,26 @@ namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server public void SendAgentTerseUpdate(ISceneEntity presence) { } - + public void SendPlacesReply(UUID queryID, UUID transactionID, PlacesReplyData[] data) { } + public void SendSelectedPartsProprieties(List parts) + { + } + public void SendPartPhysicsProprieties(ISceneEntity entity) { } + public void SendPartFullUpdate(ISceneEntity ent, uint? parentID) + { + } + + public int GetAgentThrottleSilent(int throttle) + { + return 0; + } } } diff --git a/OpenSim/Region/OptionalModules/Agent/TextureSender/J2KDecoderCommandModule.cs b/OpenSim/Region/OptionalModules/Agent/TextureSender/J2KDecoderCommandModule.cs index c897aa5..e93fcdc 100644 --- a/OpenSim/Region/OptionalModules/Agent/TextureSender/J2KDecoderCommandModule.cs +++ b/OpenSim/Region/OptionalModules/Agent/TextureSender/J2KDecoderCommandModule.cs @@ -54,36 +54,36 @@ namespace OpenSim.Region.OptionalModules.Agent.TextureSender // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Scene m_scene; - + public string Name { get { return "Asset Information Module"; } } - + public Type ReplaceableInterface { get { return null; } } - + public void Initialise(IConfigSource source) { // m_log.DebugFormat("[J2K DECODER COMMAND MODULE]: INITIALIZED MODULE"); } - + public void PostInitialise() { // m_log.DebugFormat("[J2K DECODER COMMAND MODULE]: POST INITIALIZED MODULE"); } - + public void Close() { // m_log.DebugFormat("[J2K DECODER COMMAND MODULE]: CLOSED MODULE"); } - + public void AddRegion(Scene scene) { // m_log.DebugFormat("[J2K DECODER COMMAND MODULE]: REGION {0} ADDED", scene.RegionInfo.RegionName); } - + public void RemoveRegion(Scene scene) { // m_log.DebugFormat("[J2K DECODER COMMAND MODULE]: REGION {0} REMOVED", scene.RegionInfo.RegionName); } - + public void RegionLoaded(Scene scene) { // m_log.DebugFormat("[J2K DECODER COMMAND MODULE]: REGION {0} LOADED", scene.RegionInfo.RegionName); @@ -117,10 +117,10 @@ namespace OpenSim.Region.OptionalModules.Agent.TextureSender MainConsole.Instance.OutputFormat("ERROR: {0} is not a valid ID format", rawAssetId); return; } - + AssetBase asset = m_scene.AssetService.Get(assetId.ToString()); if (asset == null) - { + { MainConsole.Instance.OutputFormat("ERROR: No asset found with ID {0}", assetId); return; } diff --git a/OpenSim/Region/OptionalModules/Agent/UDP/Linden/LindenUDPInfoModule.cs b/OpenSim/Region/OptionalModules/Agent/UDP/Linden/LindenUDPInfoModule.cs index 08d0fbf..490809e 100644 --- a/OpenSim/Region/OptionalModules/Agent/UDP/Linden/LindenUDPInfoModule.cs +++ b/OpenSim/Region/OptionalModules/Agent/UDP/Linden/LindenUDPInfoModule.cs @@ -52,48 +52,48 @@ namespace OpenSim.Region.OptionalModules.UDP.Linden [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "LindenUDPInfoModule")] public class LindenUDPInfoModule : ISharedRegionModule { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + protected Dictionary m_scenes = new Dictionary(); - - public string Name { get { return "Linden UDP Module"; } } - + + public string Name { get { return "Linden UDP Module"; } } + public Type ReplaceableInterface { get { return null; } } - + public void Initialise(IConfigSource source) { // m_log.DebugFormat("[LINDEN UDP INFO MODULE]: INITIALIZED MODULE"); } - + public void PostInitialise() { // m_log.DebugFormat("[LINDEN UDP INFO MODULE]: POST INITIALIZED MODULE"); } - + public void Close() { // m_log.DebugFormat("[LINDEN UDP INFO MODULE]: CLOSED MODULE"); } - + public void AddRegion(Scene scene) { // m_log.DebugFormat("[LINDEN UDP INFO MODULE]: REGION {0} ADDED", scene.RegionInfo.RegionName); - + lock (m_scenes) m_scenes[scene.RegionInfo.RegionID] = scene; scene.AddCommand( "Comms", this, "show pqueues", "show pqueues [full]", - "Show priority queue data for each client", + "Show priority queue data for each client", "Without the 'full' option, only root agents are shown." - + " With the 'full' option child agents are also shown.", + + " With the 'full' option child agents are also shown.", (mod, cmd) => MainConsole.Instance.Output(GetPQueuesReport(cmd))); - + scene.AddCommand( "Comms", this, "show queues", "show queues [full]", - "Show queue data for each client", + "Show queue data for each client", "Without the 'full' option, only root agents are shown.\n" + "With the 'full' option child agents are also shown.\n\n" + "Type - Rt is a root (avatar) client whilst cd is a child (neighbour interacting) client.\n" @@ -116,40 +116,24 @@ namespace OpenSim.Region.OptionalModules.UDP.Linden "clear image queues ", "Clear the image queues (textures downloaded via UDP) for a particular client.", (mod, cmd) => MainConsole.Instance.Output(HandleImageQueuesClear(cmd))); - + scene.AddCommand( "Comms", this, "show throttles", "show throttles [full]", - "Show throttle settings for each client and for the server overall", + "Show throttle settings for each client and for the server overall", "Without the 'full' option, only root agents are shown." - + " With the 'full' option child agents are also shown.", + + " With the 'full' option child agents are also shown.", (mod, cmd) => MainConsole.Instance.Output(GetThrottlesReport(cmd))); - - scene.AddCommand( - "Comms", this, "emergency-monitoring", - "emergency-monitoring", - "Go on/off emergency monitoring mode", - "Go on/off emergency monitoring mode", - HandleEmergencyMonitoring); - - scene.AddCommand( - "Comms", this, "show client stats", - "show client stats [first_name last_name]", - "Show client request stats", - "Without the 'first_name last_name' option, all clients are shown." - + " With the 'first_name last_name' option only a specific client is shown.", - (mod, cmd) => MainConsole.Instance.Output(HandleClientStatsReport(cmd))); - } - + public void RemoveRegion(Scene scene) { // m_log.DebugFormat("[LINDEN UDP INFO MODULE]: REGION {0} REMOVED", scene.RegionInfo.RegionName); - + lock (m_scenes) m_scenes.Remove(scene.RegionInfo.RegionID); - } - + } + public void RegionLoaded(Scene scene) { // m_log.DebugFormat("[LINDEN UDP INFO MODULE]: REGION {0} LOADED", scene.RegionInfo.RegionName); @@ -183,7 +167,7 @@ namespace OpenSim.Region.OptionalModules.UDP.Linden foreach (ScenePresence agent in foundAgents) { LLClientView client = agent.ControllingClient as LLClientView; - + if (client == null) return "This command is only supported for LLClientView"; @@ -197,29 +181,11 @@ namespace OpenSim.Region.OptionalModules.UDP.Linden return report.ToString(); } - protected void HandleEmergencyMonitoring(string module, string[] cmd) - { - bool mode = true; - if (cmd.Length == 1 || (cmd.Length > 1 && cmd[1] == "on")) - { - mode = true; - MainConsole.Instance.Output("Emergency Monitoring ON"); - } - else - { - mode = false; - MainConsole.Instance.Output("Emergency Monitoring OFF"); - } - - foreach (Scene s in m_scenes.Values) - s.EmergencyMonitoring = mode; - } - protected string GetColumnEntry(string entry, int maxLength, int columnPadding) - { + { return string.Format( - "{0,-" + maxLength + "}{1,-" + columnPadding + "}", - entry.Length > maxLength ? entry.Substring(0, maxLength) : entry, + "{0,-" + maxLength + "}{1,-" + columnPadding + "}", + entry.Length > maxLength ? entry.Substring(0, maxLength) : entry, ""); } @@ -232,29 +198,29 @@ namespace OpenSim.Region.OptionalModules.UDP.Linden { bool showChildren = false; string pname = ""; - + if (showParams.Length > 2 && showParams[2] == "full") - showChildren = true; + showChildren = true; else if (showParams.Length > 3) pname = showParams[2] + " " + showParams[3]; - - StringBuilder report = new StringBuilder(); + + StringBuilder report = new StringBuilder(); int columnPadding = 2; - int maxNameLength = 18; + int maxNameLength = 18; int maxRegionNameLength = 14; int maxTypeLength = 4; -// int totalInfoFieldsLength = maxNameLength + columnPadding + maxRegionNameLength + columnPadding + maxTypeLength + columnPadding; - +// int totalInfoFieldsLength = maxNameLength + columnPadding + maxRegionNameLength + columnPadding + maxTypeLength + columnPadding; + report.Append(GetColumnEntry("User", maxNameLength, columnPadding)); report.Append(GetColumnEntry("Region", maxRegionNameLength, columnPadding)); report.Append(GetColumnEntry("Type", maxTypeLength, columnPadding)); - + report.AppendFormat( "{0,7} {1,7} {2,7} {3,7} {4,7} {5,7} {6,7} {7,7} {8,7} {9,7} {10,7} {11,7}\n", "Pri 0", "Pri 1", - "Pri 2", + "Pri 2", "Pri 3", "Pri 4", "Pri 5", @@ -277,16 +243,16 @@ namespace OpenSim.Region.OptionalModules.UDP.Linden bool isChild = client.SceneAgent.IsChildAgent; if (isChild && !showChildren) return; - + string name = client.Name; if (pname != "" && name != pname) return; - + string regionName = scene.RegionInfo.RegionName; - + report.Append(GetColumnEntry(name, maxNameLength, columnPadding)); report.Append(GetColumnEntry(regionName, maxRegionNameLength, columnPadding)); - report.Append(GetColumnEntry(isChild ? "Cd" : "Rt", maxTypeLength, columnPadding)); + report.Append(GetColumnEntry(isChild ? "Cd" : "Rt", maxTypeLength, columnPadding)); report.AppendLine(((LLClientView)client).EntityUpdateQueue.ToString()); } }); @@ -331,17 +297,17 @@ namespace OpenSim.Region.OptionalModules.UDP.Linden foreach (ScenePresence agent in foundAgents) { LLClientView client = agent.ControllingClient as LLClientView; - + if (client == null) return "This command is only supported for LLClientView"; - + J2KImage[] images = client.ImageManager.GetImages(); report.AppendFormat( "In region {0} ({1} agent)\n", agent.Scene.RegionInfo.RegionName, agent.IsChildAgent ? "child" : "root"); report.AppendFormat("Images in queue: {0}\n", images.Length); - + if (images.Length > 0) { report.AppendFormat( @@ -352,7 +318,7 @@ namespace OpenSim.Region.OptionalModules.UDP.Linden "Start Pkt", "Has Asset", "Decoded"); - + foreach (J2KImage image in images) report.AppendFormat( "{0,36} {1,8} {2,10} {3,10} {4,9} {5,7}\n", @@ -362,7 +328,7 @@ namespace OpenSim.Region.OptionalModules.UDP.Linden return report.ToString(); } - + /// /// Generate UDP Queue data report for each client /// @@ -372,16 +338,16 @@ namespace OpenSim.Region.OptionalModules.UDP.Linden { bool showChildren = false; string pname = ""; - + if (showParams.Length > 2 && showParams[2] == "full") - showChildren = true; + showChildren = true; else if (showParams.Length > 3) pname = showParams[2] + " " + showParams[3]; - - StringBuilder report = new StringBuilder(); - + + StringBuilder report = new StringBuilder(); + int columnPadding = 2; - int maxNameLength = 18; + int maxNameLength = 18; int maxRegionNameLength = 14; int maxTypeLength = 4; @@ -389,11 +355,11 @@ namespace OpenSim.Region.OptionalModules.UDP.Linden = maxNameLength + columnPadding + maxRegionNameLength + columnPadding + maxTypeLength + columnPadding; - + report.Append(GetColumnEntry("User", maxNameLength, columnPadding)); report.Append(GetColumnEntry("Region", maxRegionNameLength, columnPadding)); report.Append(GetColumnEntry("Type", maxTypeLength, columnPadding)); - + report.AppendFormat( "{0,7} {1,7} {2,7} {3,7} {4,9} {5,7} {6,7} {7,7} {8,7} {9,7} {10,8} {11,7}\n", "Since", @@ -408,7 +374,7 @@ namespace OpenSim.Region.OptionalModules.UDP.Linden "Q Pkts", "Q Pkts", "Q Pkts"); - + report.AppendFormat("{0,-" + totalInfoFieldsLength + "}", ""); report.AppendFormat( "{0,7} {1,7} {2,7} {3,7} {4,9} {5,7} {6,7} {7,7} {8,7} {9,7} {10,8} {11,7}\n", @@ -423,8 +389,8 @@ namespace OpenSim.Region.OptionalModules.UDP.Linden "Cloud", "Task", "Texture", - "Asset"); - + "Asset"); + lock (m_scenes) { foreach (Scene scene in m_scenes.Values) @@ -438,7 +404,7 @@ namespace OpenSim.Region.OptionalModules.UDP.Linden bool isChild = client.SceneAgent.IsChildAgent; if (isChild && !showChildren) return; - + string name = client.Name; if (pname != "" && name != pname) return; @@ -449,7 +415,7 @@ namespace OpenSim.Region.OptionalModules.UDP.Linden report.Append(GetColumnEntry(regionName, maxRegionNameLength, columnPadding)); report.Append(GetColumnEntry(isChild ? "Cd" : "Rt", maxTypeLength, columnPadding)); - IStatsCollector stats = (IStatsCollector)client; + IStatsCollector stats = (IStatsCollector)client; report.AppendLine(stats.Report()); } }); @@ -457,8 +423,8 @@ namespace OpenSim.Region.OptionalModules.UDP.Linden } return report.ToString(); - } - + } + /// /// Show throttle data /// @@ -468,28 +434,28 @@ namespace OpenSim.Region.OptionalModules.UDP.Linden { bool showChildren = false; string pname = ""; - + if (showParams.Length > 2 && showParams[2] == "full") - showChildren = true; + showChildren = true; else if (showParams.Length > 3) pname = showParams[2] + " " + showParams[3]; - - StringBuilder report = new StringBuilder(); - + + StringBuilder report = new StringBuilder(); + int columnPadding = 2; - int maxNameLength = 18; + int maxNameLength = 18; int maxRegionNameLength = 14; - int maxTypeLength = 4; - int totalInfoFieldsLength = maxNameLength + columnPadding + maxRegionNameLength + columnPadding + maxTypeLength + columnPadding; - + int maxTypeLength = 4; + int totalInfoFieldsLength = maxNameLength + columnPadding + maxRegionNameLength + columnPadding + maxTypeLength + columnPadding; + report.Append(GetColumnEntry("User", maxNameLength, columnPadding)); report.Append(GetColumnEntry("Region", maxRegionNameLength, columnPadding)); - report.Append(GetColumnEntry("Type", maxTypeLength, columnPadding)); - + report.Append(GetColumnEntry("Type", maxTypeLength, columnPadding)); + report.AppendFormat( "{0,8} {1,8} {2,7} {3,8} {4,7} {5,7} {6,7} {7,7} {8,9} {9,7}\n", "Max", - "Target", + "Target", "Actual", "Resend", "Land", @@ -497,8 +463,8 @@ namespace OpenSim.Region.OptionalModules.UDP.Linden "Cloud", "Task", "Texture", - "Asset"); - + "Asset"); + report.AppendFormat("{0,-" + totalInfoFieldsLength + "}", ""); report.AppendFormat( "{0,8} {1,8} {2,7} {3,8} {4,7} {5,7} {6,7} {7,7} {8,9} {9,7}\n", @@ -511,10 +477,10 @@ namespace OpenSim.Region.OptionalModules.UDP.Linden "kb/s", "kb/s", "kb/s", - "kb/s"); - + "kb/s"); + report.AppendLine(); - + lock (m_scenes) { foreach (Scene scene in m_scenes.Values) @@ -529,25 +495,25 @@ namespace OpenSim.Region.OptionalModules.UDP.Linden bool isChild = client.SceneAgent.IsChildAgent; if (isChild && !showChildren) return; - + string name = client.Name; if (pname != "" && name != pname) return; string regionName = scene.RegionInfo.RegionName; - + LLUDPClient llUdpClient = llClient.UDPClient; ClientInfo ci = llUdpClient.GetClientInfo(); - + report.Append(GetColumnEntry(name, maxNameLength, columnPadding)); report.Append(GetColumnEntry(regionName, maxRegionNameLength, columnPadding)); - report.Append(GetColumnEntry(isChild ? "Cd" : "Rt", maxTypeLength, columnPadding)); - + report.Append(GetColumnEntry(isChild ? "Cd" : "Rt", maxTypeLength, columnPadding)); + report.AppendFormat( "{0,8} {1,8} {2,7} {3,8} {4,7} {5,7} {6,7} {7,7} {8,9} {9,7}\n", ci.maxThrottle > 0 ? ((ci.maxThrottle * 8) / 1000).ToString() : "-", - llUdpClient.FlowThrottle.AdaptiveEnabled - ? ((ci.targetThrottle * 8) / 1000).ToString() + llUdpClient.FlowThrottle.AdaptiveEnabled + ? ((ci.targetThrottle * 8) / 1000).ToString() : (llUdpClient.FlowThrottle.TotalDripRequest * 8 / 1000).ToString(), (ci.totalThrottle * 8) / 1000, (ci.resendThrottle * 8) / 1000, @@ -563,107 +529,6 @@ namespace OpenSim.Region.OptionalModules.UDP.Linden } return report.ToString(); - } - - /// - /// Show client stats data - /// - /// - /// - protected string HandleClientStatsReport(string[] showParams) - { - // NOTE: This writes to m_log on purpose. We want to store this information - // in case we need to analyze it later. - // - if (showParams.Length <= 4) - { - m_log.InfoFormat("[INFO]: {0,-12} {1,-20} {2,-6} {3,-11} {4,-11} {5,-16}", "Region", "Name", "Root", "Time", "Reqs/min", "AgentUpdates"); - foreach (Scene scene in m_scenes.Values) - { - scene.ForEachClient( - delegate(IClientAPI client) - { - if (client is LLClientView) - { - LLClientView llClient = client as LLClientView; - ClientInfo cinfo = llClient.UDPClient.GetClientInfo(); - int avg_reqs = cinfo.AsyncRequests.Values.Sum() + cinfo.GenericRequests.Values.Sum() + cinfo.SyncRequests.Values.Sum(); - avg_reqs = avg_reqs / ((DateTime.Now - cinfo.StartedTime).Minutes + 1); - - string childAgentStatus; - - if (llClient.SceneAgent != null) - childAgentStatus = llClient.SceneAgent.IsChildAgent ? "N" : "Y"; - else - childAgentStatus = "Off!"; - - m_log.InfoFormat("[INFO]: {0,-12} {1,-20} {2,-6} {3,-11} {4,-11} {5,-16}", - scene.RegionInfo.RegionName, llClient.Name, - childAgentStatus, - (DateTime.Now - cinfo.StartedTime).Minutes, - avg_reqs, - string.Format( - "{0} ({1:0.00}%)", - llClient.TotalAgentUpdates, - cinfo.SyncRequests.ContainsKey("AgentUpdate") - ? (float)cinfo.SyncRequests["AgentUpdate"] / llClient.TotalAgentUpdates * 100 - : 0)); - } - }); - } - return string.Empty; - } - - string fname = "", lname = ""; - - if (showParams.Length > 3) - fname = showParams[3]; - if (showParams.Length > 4) - lname = showParams[4]; - - foreach (Scene scene in m_scenes.Values) - { - scene.ForEachClient( - delegate(IClientAPI client) - { - if (client is LLClientView) - { - LLClientView llClient = client as LLClientView; - - if (llClient.Name == fname + " " + lname) - { - - ClientInfo cinfo = llClient.GetClientInfo(); - AgentCircuitData aCircuit = scene.AuthenticateHandler.GetAgentCircuitData(llClient.CircuitCode); - if (aCircuit == null) // create a dummy one - aCircuit = new AgentCircuitData(); - - if (!llClient.SceneAgent.IsChildAgent) - m_log.InfoFormat("[INFO]: {0} # {1} # {2}", llClient.Name, Util.GetViewerName(aCircuit), aCircuit.Id0); - - int avg_reqs = cinfo.AsyncRequests.Values.Sum() + cinfo.GenericRequests.Values.Sum() + cinfo.SyncRequests.Values.Sum(); - avg_reqs = avg_reqs / ((DateTime.Now - cinfo.StartedTime).Minutes + 1); - - m_log.InfoFormat("[INFO]:"); - m_log.InfoFormat("[INFO]: {0} # {1} # Time: {2}min # Avg Reqs/min: {3}", scene.RegionInfo.RegionName, - (llClient.SceneAgent.IsChildAgent ? "Child" : "Root"), (DateTime.Now - cinfo.StartedTime).Minutes, avg_reqs); - - Dictionary sortedDict = (from entry in cinfo.AsyncRequests orderby entry.Value descending select entry) - .ToDictionary(pair => pair.Key, pair => pair.Value); - PrintRequests("TOP ASYNC", sortedDict, cinfo.AsyncRequests.Values.Sum()); - - sortedDict = (from entry in cinfo.SyncRequests orderby entry.Value descending select entry) - .ToDictionary(pair => pair.Key, pair => pair.Value); - PrintRequests("TOP SYNC", sortedDict, cinfo.SyncRequests.Values.Sum()); - - sortedDict = (from entry in cinfo.GenericRequests orderby entry.Value descending select entry) - .ToDictionary(pair => pair.Key, pair => pair.Value); - PrintRequests("TOP GENERIC", sortedDict, cinfo.GenericRequests.Values.Sum()); - } - } - }); - } - return string.Empty; } private void PrintRequests(string type, Dictionary sortedDict, int sum) diff --git a/OpenSim/Region/OptionalModules/Asset/AssetInfoModule.cs b/OpenSim/Region/OptionalModules/Asset/AssetInfoModule.cs index 7639c6c..906e1ee 100644 --- a/OpenSim/Region/OptionalModules/Asset/AssetInfoModule.cs +++ b/OpenSim/Region/OptionalModules/Asset/AssetInfoModule.cs @@ -50,36 +50,36 @@ namespace OpenSim.Region.OptionalModules.Asset // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Scene m_scene; - + public string Name { get { return "Asset Information Module"; } } - + public Type ReplaceableInterface { get { return null; } } - + public void Initialise(IConfigSource source) { // m_log.DebugFormat("[ASSET INFO MODULE]: INITIALIZED MODULE"); } - + public void PostInitialise() { // m_log.DebugFormat("[ASSET INFO MODULE]: POST INITIALIZED MODULE"); } - + public void Close() { // m_log.DebugFormat("[ASSET INFO MODULE]: CLOSED MODULE"); } - + public void AddRegion(Scene scene) { // m_log.DebugFormat("[ASSET INFO MODULE]: REGION {0} ADDED", scene.RegionInfo.RegionName); } - + public void RemoveRegion(Scene scene) { // m_log.DebugFormat("[ASSET INFO MODULE]: REGION {0} REMOVED", scene.RegionInfo.RegionName); - } - + } + public void RegionLoaded(Scene scene) { // m_log.DebugFormat("[ASSET INFO MODULE]: REGION {0} LOADED", scene.RegionInfo.RegionName); @@ -118,27 +118,27 @@ namespace OpenSim.Region.OptionalModules.Asset MainConsole.Instance.OutputFormat("ERROR: {0} is not a valid ID format", rawAssetId); return; } - + AssetBase asset = m_scene.AssetService.Get(assetId.ToString()); if (asset == null) - { + { MainConsole.Instance.OutputFormat("ERROR: No asset found with ID {0}", assetId); - return; + return; } - + string fileName = rawAssetId; if (!ConsoleUtil.CheckFileDoesNotExist(MainConsole.Instance, fileName)) return; - + using (FileStream fs = new FileStream(fileName, FileMode.CreateNew)) { using (BinaryWriter bw = new BinaryWriter(fs)) { bw.Write(asset.Data); } - } - + } + MainConsole.Instance.OutputFormat("Asset dumped to file {0}", fileName); } diff --git a/OpenSim/Region/OptionalModules/Avatar/Animations/AnimationsCommandModule.cs b/OpenSim/Region/OptionalModules/Avatar/Animations/AnimationsCommandModule.cs index 84211a9..0698cec 100644 --- a/OpenSim/Region/OptionalModules/Avatar/Animations/AnimationsCommandModule.cs +++ b/OpenSim/Region/OptionalModules/Avatar/Animations/AnimationsCommandModule.cs @@ -42,6 +42,7 @@ using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes.Animation; using OpenSim.Services.Interfaces; +using AnimationSet = OpenSim.Region.Framework.Scenes.Animation.AnimationSet; namespace OpenSim.Region.OptionalModules.Avatar.Animations { @@ -56,41 +57,41 @@ namespace OpenSim.Region.OptionalModules.Avatar.Animations private List m_scenes = new List(); public string Name { get { return "Animations Command Module"; } } - + public Type ReplaceableInterface { get { return null; } } - + public void Initialise(IConfigSource source) { // m_log.DebugFormat("[ANIMATIONS COMMAND MODULE]: INITIALIZED MODULE"); } - + public void PostInitialise() { // m_log.DebugFormat("[ANIMATIONS COMMAND MODULE]: POST INITIALIZED MODULE"); } - + public void Close() { // m_log.DebugFormat("[ANIMATIONS COMMAND MODULE]: CLOSED MODULE"); } - + public void AddRegion(Scene scene) { // m_log.DebugFormat("[ANIMATIONS COMMAND MODULE]: REGION {0} ADDED", scene.RegionInfo.RegionName); } - + public void RemoveRegion(Scene scene) { // m_log.DebugFormat("[ATTACHMENTS COMMAND MODULE]: REGION {0} REMOVED", scene.RegionInfo.RegionName); - + lock (m_scenes) m_scenes.Remove(scene); - } - + } + public void RegionLoaded(Scene scene) { // m_log.DebugFormat("[ANIMATIONS COMMAND MODULE]: REGION {0} LOADED", scene.RegionInfo.RegionName); - + lock (m_scenes) m_scenes.Add(scene); @@ -155,18 +156,18 @@ namespace OpenSim.Region.OptionalModules.Avatar.Animations string cma = spa.CurrentMovementAnimation; cdl.AddRow( - "Current movement anim", + "Current movement anim", string.Format("{0}, {1}", DefaultAvatarAnimations.GetDefaultAnimation(cma), cma)); UUID defaultAnimId = anims.DefaultAnimation.AnimID; cdl.AddRow( - "Default anim", + "Default anim", string.Format("{0}, {1}", defaultAnimId, sp.Animator.GetAnimName(defaultAnimId))); UUID implicitDefaultAnimId = anims.ImplicitDefaultAnimation.AnimID; cdl.AddRow( - "Implicit default anim", - string.Format("{0}, {1}", + "Implicit default anim", + string.Format("{0}, {1}", implicitDefaultAnimId, sp.Animator.GetAnimName(implicitDefaultAnimId))); cdl.AddToStringBuilder(sb); @@ -197,4 +198,4 @@ namespace OpenSim.Region.OptionalModules.Avatar.Animations sb.Append("\n"); } } -} \ No newline at end of file +} diff --git a/OpenSim/Region/OptionalModules/Avatar/Appearance/AppearanceInfoModule.cs b/OpenSim/Region/OptionalModules/Avatar/Appearance/AppearanceInfoModule.cs index 2f9bb1e..60ae0cb 100644 --- a/OpenSim/Region/OptionalModules/Avatar/Appearance/AppearanceInfoModule.cs +++ b/OpenSim/Region/OptionalModules/Avatar/Appearance/AppearanceInfoModule.cs @@ -54,43 +54,43 @@ namespace OpenSim.Region.OptionalModules.Avatar.Appearance private List m_scenes = new List(); // private IAvatarFactoryModule m_avatarFactory; - - public string Name { get { return "Appearance Information Module"; } } - + + public string Name { get { return "Appearance Information Module"; } } + public Type ReplaceableInterface { get { return null; } } - + public void Initialise(IConfigSource source) { // m_log.DebugFormat("[APPEARANCE INFO MODULE]: INITIALIZED MODULE"); } - + public void PostInitialise() { // m_log.DebugFormat("[APPEARANCE INFO MODULE]: POST INITIALIZED MODULE"); } - + public void Close() { // m_log.DebugFormat("[APPEARANCE INFO MODULE]: CLOSED MODULE"); } - + public void AddRegion(Scene scene) { -// m_log.DebugFormat("[APPEARANCE INFO MODULE]: REGION {0} ADDED", scene.RegionInfo.RegionName); +// m_log.DebugFormat("[APPEARANCE INFO MODULE]: REGION {0} ADDED", scene.RegionInfo.RegionName); } - + public void RemoveRegion(Scene scene) { // m_log.DebugFormat("[APPEARANCE INFO MODULE]: REGION {0} REMOVED", scene.RegionInfo.RegionName); - + lock (m_scenes) m_scenes.Remove(scene); - } - + } + public void RegionLoaded(Scene scene) { // m_log.DebugFormat("[APPEARANCE INFO MODULE]: REGION {0} LOADED", scene.RegionInfo.RegionName); - + lock (m_scenes) m_scenes.Add(scene); @@ -99,7 +99,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Appearance "show appearance [ ]", "Synonym for 'appearance show'", HandleShowAppearanceCommand); - + scene.AddCommand( "Users", this, "appearance show", "appearance show [ ]", @@ -222,7 +222,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Appearance } lock (m_scenes) - { + { foreach (Scene scene in m_scenes) { if (targetNameSupplied) @@ -344,7 +344,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Appearance if (targetNameSupplied) { - lock (m_scenes) + lock (m_scenes) { foreach (Scene scene in m_scenes) { @@ -360,12 +360,12 @@ namespace OpenSim.Region.OptionalModules.Avatar.Appearance cdt.AddColumn("Name", ConsoleDisplayUtil.UserNameSize); cdt.AddColumn("Wearables", 2); - lock (m_scenes) + lock (m_scenes) { foreach (Scene scene in m_scenes) { scene.ForEachRootScenePresence( - sp => + sp => { int count = 0; @@ -428,7 +428,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Appearance uuidGatherer.AddForInspection(wi.AssetID); uuidGatherer.GatherAll(); - string[] assetStrings + string[] assetStrings = Array.ConvertAll(uuidGatherer.GatheredUuids.Keys.ToArray(), u => u.ToString()); bool[] existChecks = scene.AssetService.AssetsExist(assetStrings); @@ -438,10 +438,10 @@ namespace OpenSim.Region.OptionalModules.Avatar.Appearance cdt.AddColumn("Type", 10); cdt.AddColumn("UUID", ConsoleDisplayUtil.UuidSize); cdt.AddColumn("Found", 5); - + for (int k = 0; k < existChecks.Length; k++) cdt.AddRow( - (AssetType)uuidGatherer.GatheredUuids[new UUID(assetStrings[k])], + (AssetType)uuidGatherer.GatheredUuids[new UUID(assetStrings[k])], assetStrings[k], existChecks[k] ? "yes" : "no"); sb.Append(cdt.ToString()); diff --git a/OpenSim/Region/OptionalModules/Avatar/Attachments/AttachmentsCommandModule.cs b/OpenSim/Region/OptionalModules/Avatar/Attachments/AttachmentsCommandModule.cs index 0333747..3685041 100644 --- a/OpenSim/Region/OptionalModules/Avatar/Attachments/AttachmentsCommandModule.cs +++ b/OpenSim/Region/OptionalModules/Avatar/Attachments/AttachmentsCommandModule.cs @@ -55,41 +55,41 @@ namespace OpenSim.Region.OptionalModules.Avatar.Attachments // private IAvatarFactoryModule m_avatarFactory; public string Name { get { return "Attachments Command Module"; } } - + public Type ReplaceableInterface { get { return null; } } - + public void Initialise(IConfigSource source) { // m_log.DebugFormat("[ATTACHMENTS COMMAND MODULE]: INITIALIZED MODULE"); } - + public void PostInitialise() { // m_log.DebugFormat("[ATTACHMENTS COMMAND MODULE]: POST INITIALIZED MODULE"); } - + public void Close() { // m_log.DebugFormat("[ATTACHMENTS COMMAND MODULE]: CLOSED MODULE"); } - + public void AddRegion(Scene scene) { // m_log.DebugFormat("[ATTACHMENTS COMMAND MODULE]: REGION {0} ADDED", scene.RegionInfo.RegionName); } - + public void RemoveRegion(Scene scene) { // m_log.DebugFormat("[ATTACHMENTS COMMAND MODULE]: REGION {0} REMOVED", scene.RegionInfo.RegionName); - + lock (m_scenes) m_scenes.Remove(scene); - } - + } + public void RegionLoaded(Scene scene) { // m_log.DebugFormat("[ATTACHMENTS COMMAND MODULE]: REGION {0} LOADED", scene.RegionInfo.RegionName); - + lock (m_scenes) m_scenes.Add(scene); @@ -144,14 +144,9 @@ namespace OpenSim.Region.OptionalModules.Avatar.Attachments private void GetAttachmentsReport(ScenePresence sp, StringBuilder sb) { - sb.AppendFormat("Attachments for {0}\n", sp.Name); + sb.AppendFormat("Attachments for {0}\n\n", sp.Name); - ConsoleDisplayTable ct = new ConsoleDisplayTable() { Indent = 2 }; - ct.Columns.Add(new ConsoleDisplayTableColumn("Attachment Name", 50)); - ct.Columns.Add(new ConsoleDisplayTableColumn("Local ID", 10)); - ct.Columns.Add(new ConsoleDisplayTableColumn("Item ID", 36)); - ct.Columns.Add(new ConsoleDisplayTableColumn("Attach Point", 14)); - ct.Columns.Add(new ConsoleDisplayTableColumn("Position", 15)); + ConsoleDisplayList ct = new ConsoleDisplayList(); // sb.AppendFormat( // " {0,-36} {1,-10} {2,-36} {3,-14} {4,-15}\n", @@ -177,17 +172,17 @@ namespace OpenSim.Region.OptionalModules.Avatar.Attachments // attachmentObject.Name, attachmentObject.LocalId, attachmentObject.FromItemID, // (AttachmentPoint)attachmentObject.AttachmentPoint, attachmentObject.RootPart.AttachedPos); - ct.AddRow( - attachmentObject.Name, - attachmentObject.LocalId, - attachmentObject.FromItemID, - ((AttachmentPoint)attachmentObject.AttachmentPoint), - attachmentObject.RootPart.AttachedPos); + ct.Indent = 2; + ct.AddRow("Attachment Name", attachmentObject.Name); + ct.AddRow("Local ID", attachmentObject.LocalId); + ct.AddRow("Item ID", attachmentObject.UUID); + ct.AddRow("From Item ID", attachmentObject.FromItemID); + ct.AddRow("Attach Point", ((AttachmentPoint)attachmentObject.AttachmentPoint)); + ct.AddRow("Position", attachmentObject.RootPart.AttachedPos + "\n\n"); // } } ct.AddToStringBuilder(sb); - sb.Append("\n"); } } } \ No newline at end of file diff --git a/OpenSim/Region/OptionalModules/Avatar/Attachments/TempAttachmentsModule.cs b/OpenSim/Region/OptionalModules/Avatar/Attachments/TempAttachmentsModule.cs index 535bf67..c3f3851 100644 --- a/OpenSim/Region/OptionalModules/Avatar/Attachments/TempAttachmentsModule.cs +++ b/OpenSim/Region/OptionalModules/Avatar/Attachments/TempAttachmentsModule.cs @@ -125,7 +125,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Attachments SendConsoleOutput(agentID, "Command parameter error"); return; } - + m_scene.StoreExtraSetting("auto_grant_attach_perms", val); SendConsoleOutput(agentID, String.Format("auto_grant_attach_perms set to {0}", val)); @@ -134,11 +134,12 @@ namespace OpenSim.Region.OptionalModules.Avatar.Attachments private int llAttachToAvatarTemp(UUID host, UUID script, int attachmentPoint) { SceneObjectPart hostPart = m_scene.GetSceneObjectPart(host); - if (hostPart == null) return 0; - if (hostPart.ParentGroup.IsAttachment) + SceneObjectGroup hostgroup = hostPart.ParentGroup; + + if (hostgroup== null || hostgroup.IsAttachment) return 0; IAttachmentsModule attachmentsModule = m_scene.RequestModuleInterface(); @@ -155,33 +156,33 @@ namespace OpenSim.Region.OptionalModules.Avatar.Attachments ScenePresence target; if (!m_scene.TryGetScenePresence(item.PermsGranter, out target)) return 0; - - if (target.UUID != hostPart.ParentGroup.OwnerID) + + if (target.UUID != hostgroup.OwnerID) { - uint effectivePerms = hostPart.ParentGroup.GetEffectivePermissions(); + uint effectivePerms = hostgroup.EffectiveOwnerPerms; if ((effectivePerms & (uint)PermissionMask.Transfer) == 0) return 0; - hostPart.ParentGroup.SetOwnerId(target.UUID); - hostPart.ParentGroup.SetRootPartOwner(hostPart.ParentGroup.RootPart, target.UUID, target.ControllingClient.ActiveGroupId); + hostgroup.SetOwner(target.UUID, target.ControllingClient.ActiveGroupId); if (m_scene.Permissions.PropagatePermissions()) { - foreach (SceneObjectPart child in hostPart.ParentGroup.Parts) + foreach (SceneObjectPart child in hostgroup.Parts) { child.Inventory.ChangeInventoryOwner(target.UUID); child.TriggerScriptChangedEvent(Changed.OWNER); child.ApplyNextOwnerPermissions(); } + hostgroup.InvalidateEffectivePerms(); } - hostPart.ParentGroup.RootPart.ObjectSaleType = 0; - hostPart.ParentGroup.RootPart.SalePrice = 10; + hostgroup.RootPart.ObjectSaleType = 0; + hostgroup.RootPart.SalePrice = 10; - hostPart.ParentGroup.HasGroupChanged = true; - hostPart.ParentGroup.RootPart.SendPropertiesToClient(target.ControllingClient); - hostPart.ParentGroup.RootPart.ScheduleFullUpdate(); + hostgroup.HasGroupChanged = true; + hostgroup.RootPart.SendPropertiesToClient(target.ControllingClient); + hostgroup.RootPart.ScheduleFullUpdate(); } return attachmentsModule.AttachObject(target, hostPart.ParentGroup, (uint)attachmentPoint, false, false, true) ? 1 : 0; diff --git a/OpenSim/Region/OptionalModules/Avatar/Chat/ChannelState.cs b/OpenSim/Region/OptionalModules/Avatar/Chat/ChannelState.cs index b5d9fda..27ab32f 100644 --- a/OpenSim/Region/OptionalModules/Avatar/Chat/ChannelState.cs +++ b/OpenSim/Region/OptionalModules/Avatar/Chat/ChannelState.cs @@ -38,7 +38,7 @@ using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.OptionalModules.Avatar.Chat { - // An instance of this class exists for each unique combination of + // An instance of this class exists for each unique combination of // IRC chat interface characteristics, as determined by the supplied // configuration file. @@ -48,7 +48,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Chat private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - private static Regex arg = new Regex(@"\[[^\[\]]*\]"); + private static Regex arg = new Regex(@"(?", idn, from, + // m_log.DebugFormat("[IRC-Connector-{0}] PrivMsg to IRC from {1}: <{2}>", idn, from, // String.Format(pattern, m_ircChannel, from, region, msg)); // One message to the IRC server @@ -521,11 +506,11 @@ namespace OpenSim.Region.OptionalModules.Avatar.Chat c.Message = data["msg"]; c.Type = ChatTypeEnum.Region; c.Position = CenterOfRegion; - c.From = data["nick"]; + c.From = data["nick"] + "@IRC"; c.Sender = null; c.SenderUUID = UUID.Zero; - // Is message "\001ACTION foo bar\001"? + // Is message "\001ACTION foo bar\001"? // Then change to: "/me foo bar" if ((1 == c.Message[0]) && c.Message.Substring(1).StartsWith("ACTION")) @@ -623,8 +608,8 @@ namespace OpenSim.Region.OptionalModules.Avatar.Chat string parms = String.Empty; // ":" indicates that a prefix is present - // There are NEVER more than 17 real - // fields. A parameter that starts with + // There are NEVER more than 17 real + // fields. A parameter that starts with // ":" indicates that the remainder of the // line is a single parameter value. @@ -659,6 +644,11 @@ namespace OpenSim.Region.OptionalModules.Avatar.Chat version = commArgs[2]; usermod = commArgs[3]; chanmod = commArgs[4]; + + m_writer.WriteLine(String.Format("JOIN {0}", m_ircChannel)); + m_writer.Flush(); + m_log.InfoFormat("[IRC-Connector-{0}]: sent request to join {1} ", idn, m_ircChannel); + break; case "005": // Server information break; @@ -721,11 +711,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Chat case "PONG": break; case "JOIN": - if (m_pending) - { - m_log.InfoFormat("[IRC-Connector-{0}] [{1}] Connected", idn, cmd); - m_pending = false; - } + m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms); eventIrcJoin(pfx, cmd, parms); break; @@ -767,7 +753,13 @@ namespace OpenSim.Region.OptionalModules.Avatar.Chat if (IrcChannel.StartsWith(":")) IrcChannel = IrcChannel.Substring(1); - m_log.DebugFormat("[IRC-Connector-{0}] Event: IRCJoin {1}:{2}", idn, m_server, m_ircChannel); + if(IrcChannel == m_ircChannel) + { + m_log.InfoFormat("[IRC-Connector-{0}] Joined requested channel {1} at {2}", idn, IrcChannel,m_server); + m_pending = false; + } + else + m_log.InfoFormat("[IRC-Connector-{0}] Joined unknown channel {1} at {2}", idn, IrcChannel,m_server); BroadcastSim(IrcUser, "/me joins {0}", IrcChannel); } @@ -881,7 +873,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Chat } // Being marked connected is not enough to ping. Socket establishment can sometimes take a long - // time, in which case the watch dog might try to ping the server before the socket has been + // time, in which case the watch dog might try to ping the server before the socket has been // set up, with nasty side-effects. else if (_pdk_ == 0) diff --git a/OpenSim/Region/OptionalModules/Avatar/Chat/RegionState.cs b/OpenSim/Region/OptionalModules/Avatar/Chat/RegionState.cs index 6ea542c..a3ef83b 100644 --- a/OpenSim/Region/OptionalModules/Avatar/Chat/RegionState.cs +++ b/OpenSim/Region/OptionalModules/Avatar/Chat/RegionState.cs @@ -389,39 +389,32 @@ namespace OpenSim.Region.OptionalModules.Avatar.Chat } m_log.DebugFormat("[IRC-Region {0}] heard on channel {1} : {2}", Region, msg.Channel, msg.Message); - string txt = msg.Message; - if (null != avatar) + if (null != avatar && cs.RelayChat && (msg.Channel == 0 || msg.Channel == DEBUG_CHANNEL)) { - if ((!cs.RelayChat) || (msg.Channel != 0 && msg.Channel != DEBUG_CHANNEL)) - return; + string txt = msg.Message; + if (txt.StartsWith("/me ")) + txt = String.Format("{0} {1}", fromName, msg.Message.Substring(4)); + + cs.irc.PrivMsg(cs.PrivateMessageFormat, fromName, Region, txt); + return; } - else + + if (null == avatar && cs.RelayPrivateChannels && null != cs.AccessPassword && + msg.Channel == cs.RelayChannelOut) { - if (cs.RelayPrivateChannels && msg.Channel == cs.RelayChannelOut) + Match m = cs.AccessPasswordRegex.Match(msg.Message); + if (null != m) { - if (null != cs.AccessPassword) - { - Match m = cs.AccessPasswordRegex.Match(msg.Message); - if (null != m) - { - if (m.Groups["avatar"].ToString() != "") - fromName = m.Groups["avatar"].ToString(); - if (m.Groups["message"].ToString() != "") - txt = m.Groups["message"].ToString(); - } - } + m_log.DebugFormat("[IRC] relaying message from {0}: {1}", m.Groups["avatar"].ToString(), + m.Groups["message"].ToString()); + cs.irc.PrivMsg(cs.PrivateMessageFormat, m.Groups["avatar"].ToString(), + scene.RegionInfo.RegionName, m.Groups["message"].ToString()); } - fromName = "OBJECT: " + fromName; } - - if (txt.StartsWith("/me ")) - txt = String.Format("{0} {1}", fromName, msg.Message.Substring(4)); - m_log.DebugFormat("[IRC] relaying message from {0}: {1}", fromName, txt); - cs.irc.PrivMsg(cs.PrivateMessageFormat, fromName, Region, txt); } - // This method gives the region an opportunity to interfere with + // This method gives the region an opportunity to interfere with // message delivery. For now we just enforce the enable/disable // flag. @@ -435,7 +428,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Chat } } - // This supports any local message traffic that might be needed in + // This supports any local message traffic that might be needed in // support of command processing. At present there is none. internal void LocalChat(string msg) diff --git a/OpenSim/Region/OptionalModules/Avatar/Concierge/ConciergeModule.cs b/OpenSim/Region/OptionalModules/Avatar/Concierge/ConciergeModule.cs index c48e585..a5dc0ad 100644 --- a/OpenSim/Region/OptionalModules/Avatar/Concierge/ConciergeModule.cs +++ b/OpenSim/Region/OptionalModules/Avatar/Concierge/ConciergeModule.cs @@ -53,15 +53,13 @@ namespace OpenSim.Region.OptionalModules.Avatar.Concierge { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - private const int DEBUG_CHANNEL = 2147483647; +// private const int DEBUG_CHANNEL = 2147483647; use base value - private List m_scenes = new List(); + private new List m_scenes = new List(); private List m_conciergedScenes = new List(); private bool m_replacingChatModule = false; - private IConfig m_config; - private string m_whoami = "conferencier"; private Regex m_regions = null; private string m_welcomes = null; @@ -72,63 +70,62 @@ namespace OpenSim.Region.OptionalModules.Avatar.Concierge private string m_brokerURI = String.Empty; private int m_brokerUpdateTimeout = 300; - internal object m_syncy = new object(); + internal new object m_syncy = new object(); - internal bool m_enabled = false; + internal new bool m_enabled = false; #region ISharedRegionModule Members - public override void Initialise(IConfigSource config) + public override void Initialise(IConfigSource configSource) { - m_config = config.Configs["Concierge"]; + IConfig config = configSource.Configs["Concierge"]; - if (null == m_config) + if (config == null) return; - if (!m_config.GetBoolean("enabled", false)) + if (!config.GetBoolean("enabled", false)) return; m_enabled = true; - // check whether ChatModule has been disabled: if yes, // then we'll "stand in" try { - if (config.Configs["Chat"] == null) + if (configSource.Configs["Chat"] == null) { // if Chat module has not been configured it's // enabled by default, so we are not going to // replace it. m_replacingChatModule = false; } - else + else { - m_replacingChatModule = !config.Configs["Chat"].GetBoolean("enabled", true); + m_replacingChatModule = !configSource.Configs["Chat"].GetBoolean("enabled", true); } } catch (Exception) { m_replacingChatModule = false; } - + m_log.InfoFormat("[Concierge] {0} ChatModule", m_replacingChatModule ? "replacing" : "not replacing"); // take note of concierge channel and of identity - m_conciergeChannel = config.Configs["Concierge"].GetInt("concierge_channel", m_conciergeChannel); - m_whoami = m_config.GetString("whoami", "conferencier"); - m_welcomes = m_config.GetString("welcomes", m_welcomes); - m_announceEntering = m_config.GetString("announce_entering", m_announceEntering); - m_announceLeaving = m_config.GetString("announce_leaving", m_announceLeaving); - m_xmlRpcPassword = m_config.GetString("password", m_xmlRpcPassword); - m_brokerURI = m_config.GetString("broker", m_brokerURI); - m_brokerUpdateTimeout = m_config.GetInt("broker_timeout", m_brokerUpdateTimeout); - + m_conciergeChannel = configSource.Configs["Concierge"].GetInt("concierge_channel", m_conciergeChannel); + m_whoami = config.GetString("whoami", "conferencier"); + m_welcomes = config.GetString("welcomes", m_welcomes); + m_announceEntering = config.GetString("announce_entering", m_announceEntering); + m_announceLeaving = config.GetString("announce_leaving", m_announceLeaving); + m_xmlRpcPassword = config.GetString("password", m_xmlRpcPassword); + m_brokerURI = config.GetString("broker", m_brokerURI); + m_brokerUpdateTimeout = config.GetInt("broker_timeout", m_brokerUpdateTimeout); + m_log.InfoFormat("[Concierge] reporting as \"{0}\" to our users", m_whoami); // calculate regions Regex if (m_regions == null) { - string regions = m_config.GetString("regions", String.Empty); + string regions = config.GetString("regions", String.Empty); if (!String.IsNullOrEmpty(regions)) { m_regions = new Regex(@regions, RegexOptions.Compiled | RegexOptions.IgnoreCase); @@ -136,7 +133,6 @@ namespace OpenSim.Region.OptionalModules.Avatar.Concierge } } - public override void AddRegion(Scene scene) { if (!m_enabled) return; @@ -211,7 +207,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Concierge { } - new public Type ReplaceableInterface + new public Type ReplaceableInterface { get { return null; } } @@ -282,7 +278,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Concierge // range of chat to cover the whole // region. however, we don't do this for whisper // (got to have some privacy) - if (c.Type != ChatTypeEnum.Whisper) + if (c.Type != ChatTypeEnum.Whisper) { base.OnChatBroadcast(sender, c); return; @@ -300,17 +296,17 @@ namespace OpenSim.Region.OptionalModules.Avatar.Concierge { client.OnLogout += OnClientLoggedOut; - if (m_replacingChatModule) + if (m_replacingChatModule) client.OnChatFromClient += OnChatFromClient; } - + public void OnClientLoggedOut(IClientAPI client) { client.OnLogout -= OnClientLoggedOut; client.OnConnectionClosed -= OnClientLoggedOut; - + if (m_conciergedScenes.Contains(client.Scene)) { Scene scene = client.Scene as Scene; @@ -328,7 +324,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Concierge Scene scene = agent.Scene; m_log.DebugFormat("[Concierge]: {0} enters {1}", agent.Name, scene.RegionInfo.RegionName); WelcomeAvatar(agent, scene); - AnnounceToAgentsRegion(scene, String.Format(m_announceEntering, agent.Name, + AnnounceToAgentsRegion(scene, String.Format(m_announceEntering, agent.Name, scene.RegionInfo.RegionName, scene.GetRootAgentCount())); UpdateBroker(scene); } @@ -341,7 +337,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Concierge { Scene scene = agent.Scene; m_log.DebugFormat("[Concierge]: {0} leaves {1}", agent.Name, scene.RegionInfo.RegionName); - AnnounceToAgentsRegion(scene, String.Format(m_announceLeaving, agent.Name, + AnnounceToAgentsRegion(scene, String.Format(m_announceLeaving, agent.Name, scene.RegionInfo.RegionName, scene.GetRootAgentCount())); UpdateBroker(scene); } @@ -378,7 +374,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Concierge scene.ForEachRootScenePresence(delegate(ScenePresence sp) { - list.Append(String.Format(" \n", sp.Name, sp.UUID)); + list.Append(String.Format(" \n", sp.Name, sp.UUID)); }); list.Append(""); @@ -441,7 +437,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Concierge private void UpdateBrokerDone(IAsyncResult result) { BrokerState bs = null; - try + try { bs = result.AsyncState as BrokerState; HttpWebRequest updatePost = bs.Poster; @@ -454,19 +450,18 @@ namespace OpenSim.Region.OptionalModules.Avatar.Concierge catch (WebException we) { m_log.ErrorFormat("[Concierge] broker update to {0} failed with status {1}", bs.Uri, we.Status); - if (null != we.Response) + if (null != we.Response) { using (HttpWebResponse resp = we.Response as HttpWebResponse) { m_log.ErrorFormat("[Concierge] response from {0} status code: {1}", bs.Uri, resp.StatusCode); m_log.ErrorFormat("[Concierge] response from {0} status desc: {1}", bs.Uri, resp.StatusDescription); m_log.ErrorFormat("[Concierge] response from {0} server: {1}", bs.Uri, resp.Server); - - if (resp.ContentLength > 0) + + if (resp.ContentLength > 0) { - StreamReader content = new StreamReader(resp.GetResponseStream()); - m_log.ErrorFormat("[Concierge] response from {0} content: {1}", bs.Uri, content.ReadToEnd()); - content.Close(); + using(StreamReader content = new StreamReader(resp.GetResponseStream())) + m_log.ErrorFormat("[Concierge] response from {0} content: {1}", bs.Uri, content.ReadToEnd()); } } } @@ -480,12 +475,12 @@ namespace OpenSim.Region.OptionalModules.Avatar.Concierge // welcome file there: if yes, send it to the agent if (!String.IsNullOrEmpty(m_welcomes)) { - string[] welcomes = new string[] { + string[] welcomes = new string[] { Path.Combine(m_welcomes, agent.Scene.RegionInfo.RegionName), Path.Combine(m_welcomes, "DEFAULT")}; foreach (string welcome in welcomes) { - if (File.Exists(welcome)) + if (File.Exists(welcome)) { try { @@ -504,7 +499,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Concierge { m_log.ErrorFormat("[Concierge]: welcome file {0} is malformed: {1}", welcome, fe); } - } + } return; } m_log.DebugFormat("[Concierge]: no welcome message for region {0}", scene.RegionInfo.RegionName); @@ -516,7 +511,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Concierge // protected void AnnounceToAgentsRegion(Scene scene, string msg) // { // ScenePresence agent = null; - // if ((client.Scene is Scene) && (client.Scene as Scene).TryGetScenePresence(client.AgentId, out agent)) + // if ((client.Scene is Scene) && (client.Scene as Scene).TryGetScenePresence(client.AgentId, out agent)) // AnnounceToAgentsRegion(agent, msg); // else // m_log.DebugFormat("[Concierge]: could not find an agent for client {0}", client.Name); @@ -591,7 +586,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Concierge string regionName = (string)requestData["region"]; IScene scene = m_scenes.Find(delegate(IScene s) { return s.RegionInfo.RegionName == regionName; }); - if (scene == null) + if (scene == null) throw new Exception(String.Format("unknown region \"{0}\"", regionName)); if (!m_conciergedScenes.Contains(scene)) diff --git a/OpenSim/Region/OptionalModules/Avatar/Friends/FriendsCommandsModule.cs b/OpenSim/Region/OptionalModules/Avatar/Friends/FriendsCommandsModule.cs index 4e84364..31fc56a 100644 --- a/OpenSim/Region/OptionalModules/Avatar/Friends/FriendsCommandsModule.cs +++ b/OpenSim/Region/OptionalModules/Avatar/Friends/FriendsCommandsModule.cs @@ -61,31 +61,31 @@ namespace OpenSim.Region.OptionalModules.Avatar.Friends private IPresenceService m_presenceService; // private IAvatarFactoryModule m_avatarFactory; - - public string Name { get { return "Appearance Information Module"; } } - + + public string Name { get { return "Appearance Information Module"; } } + public Type ReplaceableInterface { get { return null; } } - + public void Initialise(IConfigSource source) { // m_log.DebugFormat("[FRIENDS COMMAND MODULE]: INITIALIZED MODULE"); } - + public void PostInitialise() { // m_log.DebugFormat("[FRIENDS COMMAND MODULE]: POST INITIALIZED MODULE"); } - + public void Close() { // m_log.DebugFormat("[FRIENDS COMMAND MODULE]: CLOSED MODULE"); } - + public void AddRegion(Scene scene) { // m_log.DebugFormat("[FRIENDS COMMANDO MODULE]: REGION {0} ADDED", scene.RegionInfo.RegionName); } - + public void RemoveRegion(Scene scene) { // m_log.DebugFormat("[FRIENDS COMMAND MODULE]: REGION {0} REMOVED", scene.RegionInfo.RegionName); @@ -107,7 +107,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Friends m_scene.AddCommand( "Friends", this, "friends show", "friends show [--cache] ", - "Show the friends for the given user if they exist.\n", + "Show the friends for the given user if they exist.", "The --cache option will show locally cached information for that user.", HandleFriendsShowCommand); } @@ -197,4 +197,4 @@ namespace OpenSim.Region.OptionalModules.Avatar.Friends } } } -} \ No newline at end of file +} diff --git a/OpenSim/Region/OptionalModules/Avatar/SitStand/SitStandCommandsModule.cs b/OpenSim/Region/OptionalModules/Avatar/SitStand/SitStandCommandsModule.cs index 5a6b284..1b5ee04 100644 --- a/OpenSim/Region/OptionalModules/Avatar/SitStand/SitStandCommandsModule.cs +++ b/OpenSim/Region/OptionalModules/Avatar/SitStand/SitStandCommandsModule.cs @@ -54,34 +54,34 @@ namespace OpenSim.Region.OptionalModules.Avatar.SitStand private Scene m_scene; public string Name { get { return "SitStand Command Module"; } } - + public Type ReplaceableInterface { get { return null; } } - + public void Initialise(IConfigSource source) { // m_log.DebugFormat("[ANIMATIONS COMMAND MODULE]: INITIALIZED MODULE"); } - + public void PostInitialise() { // m_log.DebugFormat("[ANIMATIONS COMMAND MODULE]: POST INITIALIZED MODULE"); } - + public void Close() { // m_log.DebugFormat("[ANIMATIONS COMMAND MODULE]: CLOSED MODULE"); } - + public void AddRegion(Scene scene) { // m_log.DebugFormat("[ANIMATIONS COMMAND MODULE]: REGION {0} ADDED", scene.RegionInfo.RegionName); } - + public void RemoveRegion(Scene scene) { // m_log.DebugFormat("[ATTACHMENTS COMMAND MODULE]: REGION {0} REMOVED", scene.RegionInfo.RegionName); - } - + } + public void RegionLoaded(Scene scene) { // m_log.DebugFormat("[ANIMATIONS COMMAND MODULE]: REGION {0} LOADED", scene.RegionInfo.RegionName); @@ -143,7 +143,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.SitStand if (sitPart != null) { MainConsole.Instance.OutputFormat( - "Sitting {0} on {1} {2} in {3}", + "Sitting {0} on {1} {2} in {3}", sp.Name, sitPart.ParentGroup.Name, sitPart.ParentGroup.UUID, m_scene.Name); sp.HandleAgentRequestSit(sp.ControllingClient, sp.UUID, sitPart.UUID, Vector3.Zero); @@ -202,14 +202,14 @@ namespace OpenSim.Region.OptionalModules.Avatar.SitStand foreach (ScenePresence sp in scenePresences) { - if (!sp.IsChildAgent && nameRegex.IsMatch(sp.Name)) + if (!sp.IsChildAgent && nameRegex.IsMatch(sp.Name)) scenePresencesMatched.Add(sp); } } else { ScenePresence sp = m_scene.GetScenePresence(firstName, lastName); - + if (sp != null && !sp.IsChildAgent) scenePresencesMatched.Add(sp); } diff --git a/OpenSim/Region/OptionalModules/Avatar/Voice/FreeSwitchVoice/FreeSwitchVoiceModule.cs b/OpenSim/Region/OptionalModules/Avatar/Voice/FreeSwitchVoice/FreeSwitchVoiceModule.cs index 45af212..c6d7fe6 100644 --- a/OpenSim/Region/OptionalModules/Avatar/Voice/FreeSwitchVoice/FreeSwitchVoiceModule.cs +++ b/OpenSim/Region/OptionalModules/Avatar/Voice/FreeSwitchVoice/FreeSwitchVoiceModule.cs @@ -143,7 +143,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice if (String.IsNullOrEmpty(m_freeSwitchRealm) || String.IsNullOrEmpty(m_freeSwitchAPIPrefix)) { - m_log.Error("[FreeSwitchVoice]: Freeswitch service mis-configured. Not starting."); + m_log.Error("[FreeSwitchVoice]: Freeswitch service mis-configured. Not starting."); return; } @@ -168,9 +168,9 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice MainServer.Instance.AddHTTPHandler(String.Format("{0}/viv_buddy.php", m_freeSwitchAPIPrefix), FreeSwitchSLVoiceBuddyHTTPHandler); - + MainServer.Instance.AddHTTPHandler(String.Format("{0}/viv_watcher.php", m_freeSwitchAPIPrefix), - FreeSwitchSLVoiceWatcherHTTPHandler); + FreeSwitchSLVoiceWatcherHTTPHandler); m_log.InfoFormat("[FreeSwitchVoice]: using FreeSwitch server {0}", m_freeSwitchRealm); @@ -302,7 +302,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice public void OnRegisterCaps(Scene scene, UUID agentID, Caps caps) { m_log.DebugFormat( - "[FreeSwitchVoice]: OnRegisterCaps() called with agentID {0} caps {1} in scene {2}", + "[FreeSwitchVoice]: OnRegisterCaps() called with agentID {0} caps {1} in scene {2}", agentID, caps, scene.RegionInfo.RegionName); string capsBase = "/CAPS/" + caps.CapsObjectPath; @@ -352,7 +352,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice { m_log.DebugFormat( "[FreeSwitchVoice][PROVISIONVOICE]: ProvisionVoiceAccountRequest() request: {0}, path: {1}, param: {2}", request, path, param); - + ScenePresence avatar = scene.GetScenePresence(agentID); if (avatar == null) { @@ -423,9 +423,9 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice UUID agentID, Caps caps) { m_log.DebugFormat( - "[FreeSwitchVoice][PARCELVOICE]: ParcelVoiceInfoRequest() on {0} for {1}", + "[FreeSwitchVoice][PARCELVOICE]: ParcelVoiceInfoRequest() on {0} for {1}", scene.RegionInfo.RegionName, agentID); - + ScenePresence avatar = scene.GetScenePresence(agentID); string avatarName = avatar.Name; @@ -512,7 +512,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice m_log.DebugFormat("[FreeSwitchVoice][CHATSESSION]: avatar \"{0}\": request: {1}, path: {2}, param: {3}", avatarName, request, path, param); - + return "true"; } @@ -575,7 +575,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice public Hashtable FreeSwitchSLVoiceGetPreloginHTTPHandler(Hashtable request) { - m_log.Debug("[FreeSwitchVoice]: FreeSwitchSLVoiceGetPreloginHTTPHandler called"); +// m_log.Debug("[FreeSwitchVoice] FreeSwitchSLVoiceGetPreloginHTTPHandler called"); Hashtable response = new Hashtable(); response["content_type"] = "text/xml"; @@ -610,7 +610,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice public Hashtable FreeSwitchSLVoiceBuddyHTTPHandler(Hashtable request) { m_log.Debug("[FreeSwitchVoice]: FreeSwitchSLVoiceBuddyHTTPHandler called"); - + Hashtable response = new Hashtable(); response["int_response_code"] = 200; response["str_response_string"] = string.Empty; @@ -678,16 +678,16 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice // Regex normalizeEndLines = new Regex(@"(\r\n|\n)", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.Multiline); // // m_log.DebugFormat( -// "[FREESWITCH]: FreeSwitchSLVoiceBuddyHTTPHandler() response {0}", +// "[FREESWITCH]: FreeSwitchSLVoiceBuddyHTTPHandler() response {0}", // normalizeEndLines.Replace((string)response["str_response_string"],"")); - + return response; } public Hashtable FreeSwitchSLVoiceWatcherHTTPHandler(Hashtable request) { m_log.Debug("[FreeSwitchVoice]: FreeSwitchSLVoiceWatcherHTTPHandler called"); - + Hashtable response = new Hashtable(); response["int_response_code"] = 200; response["content-type"] = "text/xml"; @@ -700,8 +700,8 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice StringBuilder resp = new StringBuilder(); resp.Append(""); - - // FIXME: This is enough of a response to stop viewer 2 complaining about a login failure and get voice to work. If we don't + + // FIXME: This is enough of a response to stop viewer 2 complaining about a login failure and get voice to work. If we don't // give an OK response, then viewer 2 engages in an continuous viv_signin.php, viv_buddy.php, viv_watcher.php loop // Viewer 1 appeared happy to ignore the lack of reply and still works with this reply. // @@ -711,22 +711,22 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice lib_session {0} {0} - ", auth_token)); - + ", auth_token)); + response["str_response_string"] = resp.ToString(); - + // Regex normalizeEndLines = new Regex(@"(\r\n|\n)", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.Multiline); // // m_log.DebugFormat( -// "[FREESWITCH]: FreeSwitchSLVoiceWatcherHTTPHandler() response {0}", +// "[FREESWITCH]: FreeSwitchSLVoiceWatcherHTTPHandler() response {0}", // normalizeEndLines.Replace((string)response["str_response_string"],"")); - + return response; } - + public Hashtable FreeSwitchSLVoiceSigninHTTPHandler(Hashtable request) { - m_log.Debug("[FreeSwitchVoice]: FreeSwitchSLVoiceSigninHTTPHandler called"); + //m_log.Debug("[FreeSwitchVoice] FreeSwitchSLVoiceSigninHTTPHandler called"); // string requestbody = (string)request["body"]; // string uri = (string)request["uri"]; // string contenttype = (string)request["content-type"]; @@ -771,10 +771,10 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice ", userid, pos, avatarName); - response["int_response_code"] = 200; - + response["int_response_code"] = 200; + // m_log.DebugFormat("[FreeSwitchVoice]: Sending FreeSwitchSLVoiceSigninHTTPHandler response"); - + return response; } @@ -859,23 +859,23 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice response["keepalive"] = false; response["int_response_code"] = 500; - Hashtable requestBody = ParseRequestBody((string)request["body"]); + Hashtable requestBody = ParseRequestBody((string)request["body"]); - string section = (string) requestBody["section"]; + string section = (string) requestBody["section"]; if (section == "directory") { string eventCallingFunction = (string)requestBody["Event-Calling-Function"]; m_log.DebugFormat( - "[FreeSwitchVoice]: Received request for config section directory, event calling function '{0}'", - eventCallingFunction); - + "[FreeSwitchVoice]: Received request for config section directory, event calling function '{0}'", + eventCallingFunction); + response = m_FreeswitchService.HandleDirectoryRequest(requestBody); } else if (section == "dialplan") - { + { m_log.DebugFormat("[FreeSwitchVoice]: Received request for config section dialplan"); - + response = m_FreeswitchService.HandleDialplanRequest(requestBody); } else diff --git a/OpenSim/Region/OptionalModules/Avatar/Voice/VivoxVoice/VivoxVoiceModule.cs b/OpenSim/Region/OptionalModules/Avatar/Voice/VivoxVoice/VivoxVoiceModule.cs index dd44564..defaa9c 100644 --- a/OpenSim/Region/OptionalModules/Avatar/Voice/VivoxVoice/VivoxVoiceModule.cs +++ b/OpenSim/Region/OptionalModules/Avatar/Voice/VivoxVoice/VivoxVoiceModule.cs @@ -114,13 +114,14 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice private static Dictionary m_parents = new Dictionary(); private static bool m_dumpXml; - + private IConfig m_config; private object m_Lock; public void Initialise(IConfigSource config) { + MainConsole.Instance.Commands.AddCommand("vivox", false, "vivox debug", "vivox debug |", "Set vivox debugging", HandleDebug); m_config = config.Configs["VivoxVoice"]; @@ -152,22 +153,22 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice // Validate against constraints and default if necessary if (m_vivoxChannelRollOff < CHAN_ROLL_OFF_MIN || m_vivoxChannelRollOff > CHAN_ROLL_OFF_MAX) { - m_log.WarnFormat("[VivoxVoice] Invalid value for roll off ({0}), reset to {1}.", + m_log.WarnFormat("[VivoxVoice] Invalid value for roll off ({0}), reset to {1}.", m_vivoxChannelRollOff, CHAN_ROLL_OFF_DEFAULT); m_vivoxChannelRollOff = CHAN_ROLL_OFF_DEFAULT; } if (m_vivoxChannelMaximumRange < CHAN_MAX_RANGE_MIN || m_vivoxChannelMaximumRange > CHAN_MAX_RANGE_MAX) { - m_log.WarnFormat("[VivoxVoice] Invalid value for maximum range ({0}), reset to {1}.", + m_log.WarnFormat("[VivoxVoice] Invalid value for maximum range ({0}), reset to {1}.", m_vivoxChannelMaximumRange, CHAN_MAX_RANGE_DEFAULT); m_vivoxChannelMaximumRange = CHAN_MAX_RANGE_DEFAULT; } - if (m_vivoxChannelClampingDistance < CHAN_CLAMPING_DISTANCE_MIN || + if (m_vivoxChannelClampingDistance < CHAN_CLAMPING_DISTANCE_MIN || m_vivoxChannelClampingDistance > CHAN_CLAMPING_DISTANCE_MAX) { - m_log.WarnFormat("[VivoxVoice] Invalid value for clamping distance ({0}), reset to {1}.", + m_log.WarnFormat("[VivoxVoice] Invalid value for clamping distance ({0}), reset to {1}.", m_vivoxChannelClampingDistance, CHAN_CLAMPING_DISTANCE_DEFAULT); m_vivoxChannelClampingDistance = CHAN_CLAMPING_DISTANCE_DEFAULT; } @@ -179,7 +180,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice case "presentation" : break; case "auditorium" : break; default : - m_log.WarnFormat("[VivoxVoice] Invalid value for channel mode ({0}), reset to {1}.", + m_log.WarnFormat("[VivoxVoice] Invalid value for channel mode ({0}), reset to {1}.", m_vivoxChannelMode, CHAN_MODE_DEFAULT); m_vivoxChannelMode = CHAN_MODE_DEFAULT; break; @@ -190,7 +191,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice case "positional" : break; case "channel" : break; default : - m_log.WarnFormat("[VivoxVoice] Invalid value for channel type ({0}), reset to {1}.", + m_log.WarnFormat("[VivoxVoice] Invalid value for channel type ({0}), reset to {1}.", m_vivoxChannelType, CHAN_TYPE_DEFAULT); m_vivoxChannelType = CHAN_TYPE_DEFAULT; break; @@ -229,7 +230,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice public void AddRegion(Scene scene) { - if (m_pluginEnabled) + if (m_pluginEnabled) { lock (vlock) { @@ -237,13 +238,13 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice string sceneUUID = scene.RegionInfo.RegionID.ToString(); string sceneName = scene.RegionInfo.RegionName; - + // Make sure that all local channels are deleted. // So we have to search for the children, and then do an // iteration over the set of chidren identified. // This assumes that there is just one directory per // region. - + if (VivoxTryGetDirectory(sceneUUID + "D", out channelId)) { m_log.DebugFormat("[VivoxVoice]: region {0}: uuid {1}: located directory id {2}", @@ -262,7 +263,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice { if (!IsOK(VivoxDeleteChannel(channelId, id))) m_log.WarnFormat("[VivoxVoice] Channel delete failed {0}:{1}:{2}", i, channelId, id); - } + } } } } @@ -310,7 +311,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice public void RemoveRegion(Scene scene) { - if (m_pluginEnabled) + if (m_pluginEnabled) { lock (vlock) { @@ -318,7 +319,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice string sceneUUID = scene.RegionInfo.RegionID.ToString(); string sceneName = scene.RegionInfo.RegionName; - + // Make sure that all local channels are deleted. // So we have to search for the children, and then do an // iteration over the set of chidren identified. @@ -342,7 +343,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice { if (!IsOK(VivoxDeleteChannel(channelId, id))) m_log.WarnFormat("[VivoxVoice] Channel delete failed {0}:{1}:{2}", i, channelId, id); - } + } } } } @@ -352,7 +353,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice // Remove the channel umbrella entry - lock (m_parents) + lock (m_parents) { if (m_parents.ContainsKey(sceneUUID)) { @@ -374,7 +375,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice VivoxLogout(); } - public Type ReplaceableInterface + public Type ReplaceableInterface { get { return null; } } @@ -395,11 +396,11 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice // (login, region crossing). We contribute two capabilities to // the set of capabilities handed back to the client: // ProvisionVoiceAccountRequest and ParcelVoiceInfoRequest. - // + // // ProvisionVoiceAccountRequest allows the client to obtain // the voice account credentials for the avatar it is // controlling (e.g., user name, password, etc). - // + // // ParcelVoiceInfoRequest is invoked whenever the client // changes from one region or parcel to another. // @@ -475,8 +476,8 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice avatarName = avatar.Name; m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: scene = {0}, agentID = {1}", scene, agentID); - m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: request: {0}, path: {1}, param: {2}", - request, path, param); +// m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: request: {0}, path: {1}, param: {2}", +// request, path, param); XmlElement resp; bool retry = false; @@ -492,9 +493,9 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice if (XmlFind(resp, "response.level0.status", out code)) { - if (code != "OK") + if (code != "OK") { - if (XmlFind(resp, "response.level0.body.code", out code)) + if (XmlFind(resp, "response.level0.body.code", out code)) { // If the request was recognized, then this should be set to something switch (code) @@ -529,27 +530,27 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice switch (code) { case "201" : // Account expired - m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : expired credentials", + m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : expired credentials", avatarName); m_adminConnected = false; retry = DoAdminLogin(); break; - + case "202" : // Missing credentials - m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : missing credentials", + m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : missing credentials", avatarName); break; - + case "212" : // Not authorized m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : not authorized", avatarName); break; - + case "300" : // Required parameter missing - m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : parameter missing", + m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : parameter missing", avatarName); break; - + case "400" : // Create failed m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : create failed", avatarName); @@ -557,7 +558,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice } } break; - + case "404" : // Failed to retrieve account m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : retrieve failed"); // [AMW] Sleep and retry for a fixed period? Or just abandon? @@ -574,7 +575,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: Get Account Request failed for \"{0}\"", avatarName); throw new Exception("Unable to execute request"); } - + // Unconditionally change the password on each request VivoxPassword(agentname, password); @@ -583,7 +584,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice string r = LLSDHelpers.SerialiseLLSDReply(voiceAccountResponse); - m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: avatar \"{0}\": {1}", avatarName, r); +// m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: avatar \"{0}\": {1}", avatarName, r); return r; } @@ -612,7 +613,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice string avatarName = avatar.Name; // - check whether we have a region channel in our cache - // - if not: + // - if not: // create it and cache it // - send it to the client // - send channel_uri: as "sip:regionID@m_sipDomain" @@ -621,7 +622,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice LLSDParcelVoiceInfoResponse parcelVoiceInfo; string channel_uri; - if (null == scene.LandChannel) + if (null == scene.LandChannel) throw new Exception(String.Format("region \"{0}\": avatar \"{1}\": land data not yet available", scene.RegionInfo.RegionName, avatarName)); @@ -630,24 +631,28 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice // voice, if all do retrieve or obtain the parcel // voice channel LandData land = scene.GetLandData(avatar.AbsolutePosition); + if (land == null) + { + return ""; + } - m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": request: {4}, path: {5}, param: {6}", - scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName, request, path, param); +// m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": request: {4}, path: {5}, param: {6}", +// scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName, request, path, param); // m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: avatar \"{0}\": location: {1} {2} {3}", // avatarName, avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y, avatar.AbsolutePosition.Z); // TODO: EstateSettings don't seem to get propagated... if (!scene.RegionInfo.EstateSettings.AllowVoice) { - m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": voice not enabled in estate settings", - scene.RegionInfo.RegionName); + //m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": voice not enabled in estate settings", + // scene.RegionInfo.RegionName); channel_uri = String.Empty; } if ((land.Flags & (uint)ParcelFlags.AllowVoiceChat) == 0) { - m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": voice not enabled for parcel", - scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName); + //m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": voice not enabled for parcel", + // scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName); channel_uri = String.Empty; } else @@ -662,15 +667,15 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice parcelVoiceInfo = new LLSDParcelVoiceInfoResponse(scene.RegionInfo.RegionName, land.LocalID, creds); string r = LLSDHelpers.SerialiseLLSDReply(parcelVoiceInfo); - m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": {4}", - scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName, r); +// m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": {4}", +// scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName, r); return r; } catch (Exception e) { - m_log.ErrorFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": avatar \"{1}\": {2}, retry later", + m_log.ErrorFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": avatar \"{1}\": {2}, retry later", scene.RegionInfo.RegionName, avatarName, e.Message); - m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": avatar \"{1}\": {2} failed", + m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": avatar \"{1}\": {2} failed", scene.RegionInfo.RegionName, avatarName, e.ToString()); return ""; @@ -690,11 +695,11 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice public string ChatSessionRequest(Scene scene, string request, string path, string param, UUID agentID, Caps caps) { - ScenePresence avatar = scene.GetScenePresence(agentID); - string avatarName = avatar.Name; +// ScenePresence avatar = scene.GetScenePresence(agentID); +// string avatarName = avatar.Name; - m_log.DebugFormat("[VivoxVoice][CHATSESSION]: avatar \"{0}\": request: {1}, path: {2}, param: {3}", - avatarName, request, path, param); +// m_log.DebugFormat("[VivoxVoice][CHATSESSION]: avatar \"{0}\": request: {1}, path: {2}, param: {3}", +// avatarName, request, path, param); return "true"; } @@ -716,17 +721,17 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice { landName = String.Format("{0}:{1}", scene.RegionInfo.RegionName, land.Name); landUUID = land.GlobalID.ToString(); - m_log.DebugFormat("[VivoxVoice]: Region:Parcel \"{0}\": parcel id {1}: using channel name {2}", + m_log.DebugFormat("[VivoxVoice]: Region:Parcel \"{0}\": parcel id {1}: using channel name {2}", landName, land.LocalID, landUUID); } else { landName = String.Format("{0}:{1}", scene.RegionInfo.RegionName, scene.RegionInfo.RegionName); landUUID = scene.RegionInfo.RegionID.ToString(); - m_log.DebugFormat("[VivoxVoice]: Region:Parcel \"{0}\": parcel id {1}: using channel name {2}", + m_log.DebugFormat("[VivoxVoice]: Region:Parcel \"{0}\": parcel id {1}: using channel name {2}", landName, land.LocalID, landUUID); } - + lock (vlock) { // Added by Adam to help debug channel not availible errors. @@ -737,7 +742,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice else throw new Exception("vivox channel uri not available"); - m_log.DebugFormat("[VivoxVoice]: Region:Parcel \"{0}\": parent channel id {1}: retrieved parcel channel_uri {2} ", + m_log.DebugFormat("[VivoxVoice]: Region:Parcel \"{0}\": parent channel id {1}: retrieved parcel channel_uri {2} ", landName, parentId, channelUri); } @@ -767,6 +772,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice return VivoxCall(requrl, false); } + private static readonly string m_vivoxGetAccountPath = "http://{0}/api2/viv_get_acct.php?auth_token={1}&user_name={2}"; /// @@ -779,6 +785,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice return VivoxCall(requrl, true); } + private static readonly string m_vivoxNewAccountPath = "http://{0}/api2/viv_adm_acct_new.php?username={1}&pwd={2}&auth_token={3}"; /// @@ -793,6 +800,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice return VivoxCall(requrl, true); } + private static readonly string m_vivoxPasswordPath = "http://{0}/api2/viv_adm_password.php?user_name={1}&new_pwd={2}&auth_token={3}"; /// @@ -804,18 +812,19 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice return VivoxCall(requrl, true); } + private static readonly string m_vivoxChannelPath = "http://{0}/api2/viv_chan_mod.php?mode={1}&chan_name={2}&auth_token={3}"; /// /// Create a channel. - /// Once again, there a multitude of options possible. In the simplest case + /// Once again, there a multitude of options possible. In the simplest case /// we specify only the name and get a non-persistent cannel in return. Non /// persistent means that the channel gets deleted if no-one uses it for /// 5 hours. To accomodate future requirements, it may be a good idea to /// initially create channels under the umbrella of a parent ID based upon /// the region name. That way we have a context for side channels, if those /// are required in a later phase. - /// + /// /// In this case the call handles parent and description as optional values. /// private bool VivoxTryCreateChannel(string parent, string channelId, string description, out string channelUri) @@ -837,7 +846,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice requrl = String.Format("{0}&chan_dist_model={1}", requrl, m_vivoxChannelDistanceModel); requrl = String.Format("{0}&chan_max_range={1}", requrl, m_vivoxChannelMaximumRange); requrl = String.Format("{0}&chan_clamping_distance={1}", requrl, m_vivoxChannelClampingDistance); - + XmlElement resp = VivoxCall(requrl, true); if (XmlFind(resp, "response.level0.body.chan_uri", out channelUri)) return true; @@ -880,7 +889,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice /// /// Retrieve a channel. - /// Once again, there a multitude of options possible. In the simplest case + /// Once again, there a multitude of options possible. In the simplest case /// we specify only the name and get a non-persistent cannel in return. Non /// persistent means that the channel gets deleted if no-one uses it for /// 5 hours. To accomodate future requirements, it may be a good idea to @@ -889,7 +898,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice /// are required in a later phase. /// In this case the call handles parent and description as optional values. /// - private bool VivoxTryGetChannel(string channelParent, string channelName, + private bool VivoxTryGetChannel(string channelParent, string channelName, out string channelId, out string channelUri) { string count; @@ -997,7 +1006,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice string type; // skip if not a directory - if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.type", i, out type) || + if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.type", i, out type) || type != "dir") continue; @@ -1019,7 +1028,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice return false; } - // private static readonly string m_vivoxChannelById = "http://{0}/api2/viv_chan_mod.php?mode={1}&chan_id={2}&auth_token={3}"; + // private static readonly string m_vivoxChannelById = "https://{0}/api2/viv_chan_mod.php?mode={1}&chan_id={2}&auth_token={3}"; // private XmlElement VivoxGetChannelById(string parent, string channelid) // { @@ -1035,7 +1044,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice /// /// Delete a channel. - /// Once again, there a multitude of options possible. In the simplest case + /// Once again, there a multitude of options possible. In the simplest case /// we specify only the name and get a non-persistent cannel in return. Non /// persistent means that the channel gets deleted if no-one uses it for /// 5 hours. To accomodate future requirements, it may be a good idea to @@ -1044,6 +1053,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice /// are required in a later phase. /// In this case the call handles parent and description as optional values. /// + private XmlElement VivoxDeleteChannel(string parent, string channelid) { string requrl = String.Format(m_vivoxChannelDel, m_vivoxServer, "delete", channelid, m_authToken); @@ -1059,6 +1069,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice /// /// Return information on channels in the given directory /// + private XmlElement VivoxListChildren(string channelid) { string requrl = String.Format(m_vivoxChannelSearch, m_vivoxServer, channelid, m_authToken); @@ -1087,7 +1098,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice // return VivoxGetChannelById(null, id); // } // } - // } + // } // } // } @@ -1095,12 +1106,12 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice // return VivoxGetChannel(null, Guid.NewGuid().ToString()); // } - + /// /// This method handles the WEB side of making a request over the /// Vivox interface. The returned values are tansferred to a has /// table which is returned as the result. - /// The outcome of the call can be determined by examining the + /// The outcome of the call can be determined by examining the /// status value in the hash table. /// private XmlElement VivoxCall(string requrl, bool admin) @@ -1114,9 +1125,10 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice return null; doc = new XmlDocument(); + doc.XmlResolver = null; // Let's serialize all calls to Vivox. Most of these are driven by - // the clients (CAPs), when the user arrives at the region. We don't + // the clients (CAPs), when the user arrives at the region. We don't // want to issue many simultaneous http requests to Vivox, because mono // doesn't like that lock (m_Lock) @@ -1124,7 +1136,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice try { // Otherwise prepare the request - m_log.DebugFormat("[VivoxVoice] Sending request <{0}>", requrl); + //m_log.DebugFormat("[VivoxVoice] Sending request <{0}>", requrl); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(requrl); @@ -1135,7 +1147,10 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice using (HttpWebResponse rsp = (HttpWebResponse)req.GetResponse()) using (Stream s = rsp.GetResponseStream()) using (XmlTextReader rdr = new XmlTextReader(s)) - doc.Load(rdr); + { + rdr.ProhibitDtd = true; + doc.Load(rdr); + } } catch (Exception e) { @@ -1162,7 +1177,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice /// /// Login has been factored in this way because it gets called - /// from several places in the module, and we want it to work + /// from several places in the module, and we want it to work /// the same way each time. /// private bool DoAdminLogin() @@ -1177,15 +1192,15 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice XmlElement resp = null; resp = VivoxLogin(m_vivoxAdminUser, m_vivoxAdminPassword); - - if (XmlFind(resp, "response.level0.body.status", out status)) + + if (XmlFind(resp, "response.level0.body.status", out status)) { if (status == "Ok") { m_log.Info("[VivoxVoice] Admin connection established"); if (XmlFind(resp, "response.level0.body.auth_token", out m_authToken)) { - if (m_dumpXml) m_log.DebugFormat("[VivoxVoice] Auth Token <{0}>", + if (m_dumpXml) m_log.DebugFormat("[VivoxVoice] Auth Token <{0}>", m_authToken); m_adminConnected = true; } @@ -1204,9 +1219,9 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice /// /// The XmlScan routine is provided to aid in the - /// reverse engineering of incompletely + /// reverse engineering of incompletely /// documented packets returned by the Vivox - /// voice server. It is only called if the + /// voice server. It is only called if the /// m_dumpXml switch is set. /// private void XmlScanl(XmlElement e, int index) @@ -1251,7 +1266,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice private bool XmlFind(XmlElement root, string tag, int nth, out string result) { if (root == null || tag == null || tag == String.Empty) - { + { result = String.Empty; return false; } @@ -1262,7 +1277,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice { int nth = 0; if (root == null || tag == null || tag == String.Empty) - { + { result = String.Empty; return false; } @@ -1273,7 +1288,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice /// XmlSearch is initially called by XmlFind, and then /// recursively called by itself until the document /// supplied to XmlFind is either exhausted or the name hierarchy - /// is matched. + /// is matched. /// /// If the hierarchy is matched, the value is returned in /// result, and true returned as the function's @@ -1287,7 +1302,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice result = String.Empty; return false; } - + if (tags.Length-index == 1) { if (nth == 0) @@ -1324,5 +1339,21 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.VivoxVoice result = String.Empty; return false; } + + private void HandleDebug(string module, string[] cmd) + { + if (cmd.Length < 3) + { + MainConsole.Instance.Output("Error: missing on/off flag"); + return; + } + + if (cmd[2] == "on") + m_dumpXml = true; + else if (cmd[2] == "off") + m_dumpXml = false; + else + MainConsole.Instance.Output("Error: only on and off are supported"); + } } } diff --git a/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/GroupsMessagingModule.cs b/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/GroupsMessagingModule.cs index e1b6abb..8791235 100644 --- a/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/GroupsMessagingModule.cs +++ b/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/GroupsMessagingModule.cs @@ -125,7 +125,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups { if (!m_groupMessagingEnabled) return; - + scene.RegisterModuleInterface(this); scene.AddCommand( @@ -136,7 +136,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups "This setting turns on very verbose groups messaging debugging", HandleDebugGroupsMessagingVerbose); } - + public void RegionLoaded(Scene scene) { if (!m_groupMessagingEnabled) @@ -205,7 +205,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups m_msgTransferModule = null; } - public Type ReplaceableInterface + public Type ReplaceableInterface { get { return null; } } @@ -253,7 +253,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups { if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); - + GroupRecord groupInfo = m_groupData.GetGroupRecord(agentID, groupID, null); if (groupInfo != null) @@ -270,7 +270,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups { SendMessageToGroup(im, groupID, new UUID(im.fromAgentID), null); } - + public void SendMessageToGroup( GridInstantMessage im, UUID groupID, UUID sendingAgentForGroupCalls, Func sendCondition) { @@ -294,28 +294,19 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups m_usersOnlineCache.Add(groupID, onlineAgents, m_usersOnlineCacheExpirySeconds); } - attemptDeliveryUuidSet + attemptDeliveryUuidSet = new HashSet(Array.ConvertAll(onlineAgents, pi => pi.UserID)); - - //Array.ForEach(onlineAgents, pi => attemptDeliveryUuidSet.Add(pi.UserID)); - - //groupMembers = groupMembers.Where(gmd => onlineAgentsUuidSet.Contains(gmd.AgentID.ToString())).ToList(); - - // if (m_debugEnabled) -// m_log.DebugFormat( -// "[GROUPS-MESSAGING]: SendMessageToGroup called for group {0} with {1} visible members, {2} online", -// groupID, groupMembersCount, groupMembers.Count()); } else { - attemptDeliveryUuidSet + attemptDeliveryUuidSet = new HashSet(groupMembers.ConvertAll(gmd => gmd.AgentID.ToString())); if (m_debugEnabled) m_log.DebugFormat( "[GROUPS-MESSAGING]: SendMessageToGroup called for group {0} with {1} visible members", groupID, groupMembers.Count); - } + } foreach (GroupMembersData member in groupMembers) { @@ -323,9 +314,9 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups { if (!sendCondition(member)) { - if (m_debugEnabled) + if (m_debugEnabled) m_log.DebugFormat( - "[GROUPS-MESSAGING]: Not sending to {0} as they do not fulfill send condition", + "[GROUPS-MESSAGING]: Not sending to {0} as they do not fulfill send condition", member.AgentID); continue; @@ -334,7 +325,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups else if (m_groupData.hasAgentDroppedGroupChatSession(member.AgentID, groupID)) { // Don't deliver messages to people who have dropped this session - if (m_debugEnabled) + if (m_debugEnabled) m_log.DebugFormat( "[GROUPS-MESSAGING]: {0} has dropped session, not delivering to them", member.AgentID); @@ -369,9 +360,9 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups // If they're not local, forward across the grid m_msgTransferModule.SendInstantMessage(msg, delegate(bool success) { }); - if (m_debugEnabled) + if (m_debugEnabled) m_log.DebugFormat( - "[GROUPS-MESSAGING]: Delivering to {0} via grid took {1} ms", + "[GROUPS-MESSAGING]: Delivering to {0} via grid took {1} ms", member.AgentID, Environment.TickCount - startTick); } else @@ -381,21 +372,22 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups ProcessMessageFromGroupSession(msg, client); // Deliver locally, directly - if (m_debugEnabled) + if (m_debugEnabled) m_log.DebugFormat( - "[GROUPS-MESSAGING]: Delivering to {0} locally took {1} ms", + "[GROUPS-MESSAGING]: Delivering to {0} locally took {1} ms", member.AgentID, Environment.TickCount - startTick); } } - else + else if(im.dialog != (byte)InstantMessageDialog.SessionAdd && + im.dialog != (byte)InstantMessageDialog.SessionDrop) { int startTick = Environment.TickCount; m_msgTransferModule.HandleUndeliverableMessage(msg, delegate(bool success) { }); - if (m_debugEnabled) + if (m_debugEnabled) m_log.DebugFormat( - "[GROUPS-MESSAGING]: Handling undeliverable message for {0} took {1} ms", + "[GROUPS-MESSAGING]: Handling undeliverable message for {0} took {1} ms", member.AgentID, Environment.TickCount - startTick); } } @@ -405,7 +397,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups "[GROUPS-MESSAGING]: Total SendMessageToGroup for group {0} with {1} members, {2} candidates for delivery took {3} ms", groupID, groupMembersCount, attemptDeliveryUuidSet.Count(), Environment.TickCount - requestStartTick); } - + #region SimGridEventHandlers void OnClientLogin(IClientAPI client) @@ -425,7 +417,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups // The instant message module will only deliver messages of dialog types: // MessageFromAgent, StartTyping, StopTyping, MessageFromObject // - // Any other message type will not be delivered to a client by the + // Any other message type will not be delivered to a client by the // Instant Message Module if (m_debugEnabled) @@ -436,28 +428,20 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups } // Incoming message from a group - if ((msg.fromGroup == true) && + if ((msg.fromGroup == true) && ((msg.dialog == (byte)InstantMessageDialog.SessionSend) || (msg.dialog == (byte)InstantMessageDialog.SessionAdd) || (msg.dialog == (byte)InstantMessageDialog.SessionDrop))) { IClientAPI client = null; - if (msg.dialog == (byte)InstantMessageDialog.SessionSend) - { - client = GetActiveClient(new UUID(msg.toAgentID)); + client = GetActiveClient(new UUID(msg.toAgentID)); - if (client != null) - { - if (m_debugEnabled) - m_log.DebugFormat("[GROUPS-MESSAGING]: Delivering to {0} locally", client.Name); - } - else - { - m_log.WarnFormat("[GROUPS-MESSAGING]: Received a message over the grid for a client that isn't here: {0}", msg.toAgentID); + if (client == null) + { + m_log.WarnFormat("[GROUPS-MESSAGING]: Received a message over the grid for a client that isn't here: {0}", msg.toAgentID); - return; - } + return; } ProcessMessageFromGroupSession(msg, client); @@ -466,83 +450,101 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups private void ProcessMessageFromGroupSession(GridInstantMessage msg, IClientAPI client) { - if (m_debugEnabled) + if (m_debugEnabled) m_log.DebugFormat( "[GROUPS-MESSAGING]: Session message from {0} going to agent {1}, sessionID {2}, type {3}", msg.fromAgentName, msg.toAgentID, msg.imSessionID, (InstantMessageDialog)msg.dialog); - UUID AgentID = new UUID(msg.fromAgentID); + UUID fromAgentID = new UUID(msg.fromAgentID); UUID GroupID = new UUID(msg.imSessionID); + IEventQueue eq = client.Scene.RequestModuleInterface(); switch (msg.dialog) { case (byte)InstantMessageDialog.SessionAdd: - m_groupData.AgentInvitedToGroupChatSession(AgentID, GroupID); + m_groupData.AgentInvitedToGroupChatSession(fromAgentID, GroupID); + if(eq != null) + eq.ChatterBoxSessionAgentListUpdates( + GroupID + , fromAgentID + , client.AgentId + , false //canVoiceChat + , false //isModerator + , false //text mute + , true // enter + ); break; case (byte)InstantMessageDialog.SessionDrop: - m_groupData.AgentDroppedFromGroupChatSession(AgentID, GroupID); + m_groupData.AgentDroppedFromGroupChatSession(fromAgentID, GroupID); + if(eq != null) + eq.ChatterBoxSessionAgentListUpdates( + GroupID + , fromAgentID + , client.AgentId + , false //canVoiceChat + , false //isModerator + , false //text mute + , false // leave + ); break; case (byte)InstantMessageDialog.SessionSend: - if (!m_groupData.hasAgentDroppedGroupChatSession(AgentID, GroupID) - && !m_groupData.hasAgentBeenInvitedToGroupChatSession(AgentID, GroupID) - ) + if (!m_groupData.hasAgentDroppedGroupChatSession(client.AgentId, GroupID)) { - // Agent not in session and hasn't dropped from session - // Add them to the session for now, and Invite them - m_groupData.AgentInvitedToGroupChatSession(AgentID, GroupID); - - GroupRecord groupInfo = m_groupData.GetGroupRecord(UUID.Zero, GroupID, null); - if (groupInfo != null) + if(!m_groupData.hasAgentBeenInvitedToGroupChatSession(client.AgentId, GroupID)) { - if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Sending chatterbox invite instant message"); - // Force? open the group session dialog??? - // and simultanously deliver the message, so we don't need to do a seperate client.SendInstantMessage(msg); - IEventQueue eq = client.Scene.RequestModuleInterface(); - eq.ChatterboxInvitation( - GroupID - , groupInfo.GroupName - , new UUID(msg.fromAgentID) - , msg.message - , new UUID(msg.toAgentID) - , msg.fromAgentName - , msg.dialog - , msg.timestamp - , msg.offline == 1 - , (int)msg.ParentEstateID - , msg.Position - , 1 - , new UUID(msg.imSessionID) - , msg.fromGroup - , Utils.StringToBytes(groupInfo.GroupName) - ); - - eq.ChatterBoxSessionAgentListUpdates( - new UUID(GroupID) - , new UUID(msg.fromAgentID) - , new UUID(msg.toAgentID) - , false //canVoiceChat - , false //isModerator - , false //text mute - ); + GroupRecord groupInfo = m_groupData.GetGroupRecord(UUID.Zero, GroupID, null); + if (groupInfo != null) + { + if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Sending chatterbox invite instant message"); + + if(eq != null) + { + eq.ChatterboxInvitation( + GroupID + , groupInfo.GroupName + , fromAgentID + , msg.message + , client.AgentId + , msg.fromAgentName + , msg.dialog + , msg.timestamp + , msg.offline == 1 + , (int)msg.ParentEstateID + , msg.Position + , 1 + , new UUID(msg.imSessionID) + , msg.fromGroup + , Utils.StringToBytes(groupInfo.GroupName) + ); + } + } + } + else + { + client.SendInstantMessage(msg); } - break; - } - else if (!m_groupData.hasAgentDroppedGroupChatSession(AgentID, GroupID)) - { - // User hasn't dropped, so they're in the session, - // maybe we should deliver it. - client.SendInstantMessage(msg); +// if (!m_groupData.hasAgentBeenInvitedToGroupChatSession(fromAgentID, GroupID)) + { + m_groupData.AgentInvitedToGroupChatSession(fromAgentID, GroupID); + eq.ChatterBoxSessionAgentListUpdates( + GroupID + , fromAgentID + , client.AgentId + , false //canVoiceChat + , false //isModerator + , false //text mute + , true // enter + ); + } } - break; default: client.SendInstantMessage(msg); - break;; } } @@ -559,41 +561,32 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups DebugGridInstantMessage(im); } + UUID GroupID = new UUID(im.imSessionID); + UUID AgentID = new UUID(im.fromAgentID); + // Start group IM session if ((im.dialog == (byte)InstantMessageDialog.SessionGroupStart)) { if (m_debugEnabled) m_log.InfoFormat("[GROUPS-MESSAGING]: imSessionID({0}) toAgentID({1})", im.imSessionID, im.toAgentID); - UUID GroupID = new UUID(im.imSessionID); - UUID AgentID = new UUID(im.fromAgentID); - GroupRecord groupInfo = m_groupData.GetGroupRecord(UUID.Zero, GroupID, null); - + if (groupInfo != null) { m_groupData.AgentInvitedToGroupChatSession(AgentID, GroupID); ChatterBoxSessionStartReplyViaCaps(remoteClient, groupInfo.GroupName, GroupID); - IEventQueue queue = remoteClient.Scene.RequestModuleInterface(); - queue.ChatterBoxSessionAgentListUpdates( - GroupID - , AgentID - , new UUID(im.toAgentID) - , false //canVoiceChat - , false //isModerator - , false //text mute - ); + // we need to send here a list of known participants. + im.dialog = (byte)InstantMessageDialog.SessionAdd; + SendMessageToGroup(im, GroupID); } } // Send a message from locally connected client to a group if ((im.dialog == (byte)InstantMessageDialog.SessionSend)) { - UUID GroupID = new UUID(im.imSessionID); - UUID AgentID = new UUID(im.fromAgentID); - - if (m_debugEnabled) + if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Send message to session for group {0} with session ID {1}", GroupID, im.imSessionID.ToString()); //If this agent is sending a message, then they want to be in the session @@ -601,6 +594,16 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups SendMessageToGroup(im, GroupID); } + + if ((im.dialog == (byte)InstantMessageDialog.SessionDrop)) + { + if (m_debugEnabled) + m_log.DebugFormat("[GROUPS-MESSAGING]: Send message to session for group {0} with session ID {1}", GroupID, im.imSessionID.ToString()); + + m_groupData.AgentDroppedFromGroupChatSession(AgentID, GroupID); + + SendMessageToGroup(im, GroupID); + } } #endregion @@ -656,7 +659,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups /// private IClientAPI GetActiveClient(UUID agentID) { - if (m_debugEnabled) + if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Looking for local client {0}", agentID); IClientAPI child = null; @@ -669,14 +672,14 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups { if (!sp.IsChildAgent) { - if (m_debugEnabled) + if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Found root agent for client : {0}", sp.ControllingClient.Name); return sp.ControllingClient; } else { - if (m_debugEnabled) + if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Found child agent for client : {0}", sp.ControllingClient.Name); child = sp.ControllingClient; @@ -687,12 +690,12 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups // If we didn't find a root, then just return whichever child we found, or null if none if (child == null) { - if (m_debugEnabled) + if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Could not find local client for agent : {0}", agentID); } else { - if (m_debugEnabled) + if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Returning child agent for client : {0}", child.Name); } diff --git a/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/GroupsModule.cs b/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/GroupsModule.cs index 1565da9..65d50bb 100644 --- a/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/GroupsModule.cs +++ b/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/GroupsModule.cs @@ -50,19 +50,19 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups /// ; To use this module, you must specify the following in your OpenSim.ini /// [GROUPS] /// Enabled = true - /// + /// /// Module = GroupsModule /// NoticesEnabled = true /// DebugEnabled = true - /// + /// /// GroupsServicesConnectorModule = XmlRpcGroupsServicesConnector /// XmlRpcServiceURL = http://osflotsam.org/xmlrpc.php /// XmlRpcServiceReadKey = 1234 /// XmlRpcServiceWriteKey = 1234 - /// + /// /// MessagingModule = GroupsMessagingModule /// MessagingEnabled = true - /// + /// /// ; Disables HTTP Keep-Alive for Groups Module HTTP Requests, work around for /// ; a problem discovered on some Windows based region servers. Only disable /// ; if you see a large number (dozens) of the following Exceptions: @@ -79,7 +79,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups private IMessageTransferModule m_msgTransferModule; private IGroupsMessagingModule m_groupsMessagingModule; - + private IGroupsServicesConnector m_groupData; // Configuration settings @@ -205,10 +205,10 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups } scene.EventManager.OnNewClient += OnNewClient; + scene.EventManager.OnMakeRootAgent += OnMakeRoot; + scene.EventManager.OnMakeChildAgent += OnMakeChild; scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage; - // The InstantMessageModule itself doesn't do this, - // so lets see if things explode if we don't do it - // scene.EventManager.OnClientClosed += OnClientClosed; + scene.EventManager.OnClientClosed += OnClientClosed; } @@ -217,6 +217,13 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups if (!m_groupsEnabled) return; + if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); + + scene.EventManager.OnNewClient -= OnNewClient; + scene.EventManager.OnMakeRootAgent -= OnMakeRoot; + scene.EventManager.OnMakeChildAgent -= OnMakeChild; + scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage; + scene.EventManager.OnClientClosed -= OnClientClosed; if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); lock (m_sceneList) @@ -233,7 +240,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups if (m_debugEnabled) m_log.Debug("[GROUPS]: Shutting down Groups module."); } - public Type ReplaceableInterface + public Type ReplaceableInterface { get { return null; } } @@ -255,84 +262,124 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups #endregion #region EventHandlers + + private void OnMakeRoot(ScenePresence sp) + { + if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); + + sp.ControllingClient.OnUUIDGroupNameRequest += HandleUUIDGroupNameRequest; + // Used for Notices and Group Invites/Accept/Reject + sp.ControllingClient.OnInstantMessage += OnInstantMessage; + + // comented out because some viewers no longer suport it + // sp.ControllingClient.AddGenericPacketHandler("avatargroupsrequest", AvatarGroupsRequest); + + // Send out group data update for compatibility. + // There might be some problem with the thread we're generating this on but not + // doing the update at this time causes problems (Mantis #7920 and #7915) + // TODO: move sending this update to a later time in the rootification of the client. + if(!sp.haveGroupInformation) + SendAgentGroupDataUpdate(sp.ControllingClient, false); + } + + private void OnMakeChild(ScenePresence sp) + { + if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); + + sp.ControllingClient.OnUUIDGroupNameRequest -= HandleUUIDGroupNameRequest; + sp.ControllingClient.OnInstantMessage -= OnInstantMessage; + } + private void OnNewClient(IClientAPI client) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); - client.OnUUIDGroupNameRequest += HandleUUIDGroupNameRequest; client.OnAgentDataUpdateRequest += OnAgentDataUpdateRequest; client.OnRequestAvatarProperties += OnRequestAvatarProperties; - // Used for Notices and Group Invites/Accept/Reject - client.OnInstantMessage += OnInstantMessage; - // Send client their groups information. - SendAgentGroupDataUpdate(client, client.AgentId); } +/* this should be the right message to ask for other avatars groups + + private void AvatarGroupsRequest(Object sender, string method, List args) + { + if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); + + if (!(sender is IClientAPI)) + return; + + IClientAPI remoteClient = (IClientAPI)sender; + + UUID avatarID; + UUID.TryParse(args[0], out avatarID); + + if (avatarID != UUID.Zero) + { + GroupMembershipData[] avatarGroups = GetProfileListedGroupMemberships(remoteClient, avatarID); + remoteClient.SendAvatarGroupsReply(avatarID, avatarGroups); + } + } +*/ + + // this should not be used to send groups memberships, but some viewers do expect it + // it does send unnecessary memberships, when viewers just want other properties information private void OnRequestAvatarProperties(IClientAPI remoteClient, UUID avatarID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); - //GroupMembershipData[] avatarGroups = m_groupData.GetAgentGroupMemberships(GetRequestingAgentID(remoteClient), avatarID).ToArray(); GroupMembershipData[] avatarGroups = GetProfileListedGroupMemberships(remoteClient, avatarID); remoteClient.SendAvatarGroupsReply(avatarID, avatarGroups); } - /* - * This becomes very problematic in a shared module. In a shared module you may have more then one - * reference to IClientAPI's, one for 0 or 1 root connections, and 0 or more child connections. - * The OnClientClosed event does not provide anything to indicate which one of those should be closed - * nor does it provide what scene it was from so that the specific reference can be looked up. - * The InstantMessageModule.cs does not currently worry about unregistering the handles, - * and it should be an issue, since it's the client that references us not the other way around - * , so as long as we don't keep a reference to the client laying around, the client can still be GC'ed - private void OnClientClosed(UUID AgentId) + + private void OnClientClosed(UUID AgentId, Scene scene) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); + if (scene == null) + return; - lock (m_ActiveClients) + ScenePresence sp = scene.GetScenePresence(AgentId); + IClientAPI client = sp.ControllingClient; + if (client != null) { - if (m_ActiveClients.ContainsKey(AgentId)) + client.OnAgentDataUpdateRequest -= OnAgentDataUpdateRequest; + client.OnRequestAvatarProperties -= OnRequestAvatarProperties; + // make child possible not called? + client.OnUUIDGroupNameRequest -= HandleUUIDGroupNameRequest; + client.OnInstantMessage -= OnInstantMessage; + } + +/* + lock (m_ActiveClients) { - IClientAPI client = m_ActiveClients[AgentId]; - client.OnUUIDGroupNameRequest -= HandleUUIDGroupNameRequest; - client.OnAgentDataUpdateRequest -= OnAgentDataUpdateRequest; - client.OnDirFindQuery -= OnDirFindQuery; - client.OnInstantMessage -= OnInstantMessage; + if (m_ActiveClients.ContainsKey(AgentId)) + { + IClientAPI client = m_ActiveClients[AgentId]; + client.OnUUIDGroupNameRequest -= HandleUUIDGroupNameRequest; + client.OnAgentDataUpdateRequest -= OnAgentDataUpdateRequest; + client.OnDirFindQuery -= OnDirFindQuery; + client.OnInstantMessage -= OnInstantMessage; - m_ActiveClients.Remove(AgentId); - } + m_ActiveClients.Remove(AgentId); + } else - { - if (m_debugEnabled) m_log.WarnFormat("[GROUPS]: Client closed that wasn't registered here."); + { + if (m_debugEnabled) m_log.WarnFormat("[GROUPS]: Client closed that wasn't registered here."); + } } - - - } +*/ } - */ private void OnAgentDataUpdateRequest(IClientAPI remoteClient, UUID dataForAgentID, UUID sessionID) { - if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); - - UUID activeGroupID = UUID.Zero; - string activeGroupTitle = string.Empty; - string activeGroupName = string.Empty; - ulong activeGroupPowers = (ulong)GroupPowers.None; - - GroupMembershipData membership = m_groupData.GetAgentActiveMembership(GetRequestingAgentID(remoteClient), dataForAgentID); - if (membership != null) - { - activeGroupID = membership.GroupID; - activeGroupTitle = membership.GroupTitle; - activeGroupPowers = membership.GroupPowers; - } - - SendAgentDataUpdate(remoteClient, dataForAgentID, activeGroupID, activeGroupName, activeGroupPowers, activeGroupTitle); + // this a private message for own agent only + if (dataForAgentID != GetRequestingAgentID(remoteClient)) + return; - SendScenePresenceUpdate(dataForAgentID, activeGroupTitle); + SendAgentGroupDataUpdate(remoteClient, false); + // its a info request not a change, so nothing is sent to others + // they do get the group title with the avatar object update on arrivel to a region } private void HandleUUIDGroupNameRequest(UUID GroupID, IClientAPI remoteClient) @@ -340,7 +387,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); string GroupName; - + GroupRecord group = m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), GroupID, null); if (group != null) { @@ -356,9 +403,9 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups private void OnInstantMessage(IClientAPI remoteClient, GridInstantMessage im) { - if (m_debugEnabled) + if (m_debugEnabled) m_log.DebugFormat( - "[GROUPS]: {0} called for {1}, message type {2}", + "[GROUPS]: {0} called for {1}, message type {2}", System.Reflection.MethodBase.GetCurrentMethod().Name, remoteClient.Name, (InstantMessageDialog)im.dialog); // Group invitations @@ -403,11 +450,11 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups OutgoingInstantMessage(msg, inviteInfo.AgentID); - UpdateAllClientsWithGroupInfo(inviteInfo.AgentID); - - // TODO: If the inviter is still online, they need an agent dataupdate - // and maybe group membership updates for the invitee - + IClientAPI inviteeClient = GetActiveRootClient(inviteInfo.AgentID); + if(inviteeClient !=null) + { + SendAgentGroupDataUpdate(inviteeClient,true); + } m_groupData.RemoveAgentToGroupInvite(GetRequestingAgentID(remoteClient), inviteID); } @@ -459,8 +506,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups //variable will be set to null and attachment will //not be included with the group notice. Scene scene = (Scene)remoteClient.Scene; - item = new InventoryItemBase(itemID, ownerID); - item = scene.InventoryService.GetItem(item); + item = scene.InventoryService.GetItem(ownerID, itemID); if (item != null) { @@ -523,20 +569,20 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups if (targetUser != null) { m_log.DebugFormat( - "[GROUPS]: Prepping group notice {0} for agent: {1} who Accepts Notices ({2})", + "[GROUPS]: Prepping group notice {0} for agent: {1} who Accepts Notices ({2})", NoticeID, targetUser.FirstName + " " + targetUser.LastName, member.AcceptNotices); } else { m_log.DebugFormat( - "[GROUPS]: Prepping group notice {0} for agent: {1} who Accepts Notices ({2})", + "[GROUPS]: Prepping group notice {0} for agent: {1} who Accepts Notices ({2})", NoticeID, member.AgentID, member.AcceptNotices); } } } } - GridInstantMessage msg + GridInstantMessage msg = CreateGroupNoticeIM(UUID.Zero, NoticeID, (byte)OpenMetaverse.InstantMessageDialog.GroupNotice); if (m_groupsMessagingModule != null) @@ -553,7 +599,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups UUID noticeID = new UUID(im.imSessionID); - if (m_debugEnabled) + if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Requesting notice {0} for {1}", noticeID, remoteClient.AgentId); GroupNoticeInfo notice = m_groupData.GetGroupNotice(GetRequestingAgentID(remoteClient), noticeID); @@ -579,10 +625,10 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups } else { - if (m_debugEnabled) + if (m_debugEnabled) m_log.DebugFormat( - "[GROUPS]: Could not find notice {0} for {1} on GroupNoticeInventoryAccepted.", - noticeID, remoteClient.AgentId); + "[GROUPS]: Could not find notice {0} for {1} on GroupNoticeInventoryAccepted.", + noticeID, remoteClient.AgentId); } } @@ -598,15 +644,16 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups // so we need to send local updates to the agent. UUID ejecteeID = new UUID(im.toAgentID); - + im.imSessionID = UUID.Zero.Guid; im.dialog = (byte)InstantMessageDialog.MessageFromAgent; OutgoingInstantMessage(im, ejecteeID); - IClientAPI ejectee = GetActiveClient(ejecteeID); + IClientAPI ejectee = GetActiveRootClient(ejecteeID); if (ejectee != null) { UUID groupID = new UUID(im.imSessionID); ejectee.SendAgentDropGroup(groupID); + SendAgentGroupDataUpdate(ejectee,true); } } } @@ -626,7 +673,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups case (byte)InstantMessageDialog.GroupInvitation: case (byte)InstantMessageDialog.GroupNotice: UUID toAgentID = new UUID(msg.toAgentID); - IClientAPI localClient = GetActiveClient(toAgentID); + IClientAPI localClient = GetActiveRootClient(toAgentID); if (localClient != null) { localClient.SendInstantMessage(msg); @@ -651,18 +698,16 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups { return m_groupData.GetGroupRecord(UUID.Zero, UUID.Zero, name); } - + public void ActivateGroup(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); - m_groupData.SetAgentActiveGroup(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID); + UUID agentID = GetRequestingAgentID(remoteClient); + m_groupData.SetAgentActiveGroup(agentID, agentID, groupID); - // Changing active group changes title, active powers, all kinds of things - // anyone who is in any region that can see this client, should probably be - // updated with new group info. At a minimum, they should get ScenePresence - // updated with new title. - UpdateAllClientsWithGroupInfo(GetRequestingAgentID(remoteClient)); + // llClientView does this + SendAgentGroupDataUpdate(remoteClient, true); } /// @@ -672,7 +717,6 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); - List agentRoles = m_groupData.GetAgentGroupRoles(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID); GroupMembershipData agentMembership = m_groupData.GetAgentGroupMembership(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID); @@ -695,10 +739,10 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups public List GroupMembersRequest(IClientAPI remoteClient, UUID groupID) { - if (m_debugEnabled) + if (m_debugEnabled) m_log.DebugFormat( "[GROUPS]: GroupMembersRequest called for {0} from client {1}", groupID, remoteClient.Name); - + List data = m_groupData.GetGroupMembers(GetRequestingAgentID(remoteClient), groupID); if (m_debugEnabled) @@ -710,7 +754,6 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups } return data; - } public List GroupRoleDataRequest(IClientAPI remoteClient, UUID groupID) @@ -744,7 +787,6 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups GroupProfileData profile = new GroupProfileData(); - GroupRecord groupInfo = m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), groupID, null); if (groupInfo != null) { @@ -770,7 +812,11 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups profile.MemberTitle = memberInfo.GroupTitle; profile.PowersMask = memberInfo.GroupPowers; } - +/* + this should save xmlrpc calls, but seems to return wrong GroupMembershipCount and GroupRolesCount + UUID agent = GetRequestingAgentID(remoteClient); + GroupProfileData profile = m_groupData.GetMemberGroupProfile(agent, groupID, agent); +*/ return profile; } @@ -783,7 +829,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups public GroupMembershipData GetMembershipData(UUID groupID, UUID agentID) { - if (m_debugEnabled) + if (m_debugEnabled) m_log.DebugFormat( "[GROUPS]: {0} called with groupID={1}, agentID={2}", System.Reflection.MethodBase.GetCurrentMethod().Name, groupID, agentID); @@ -791,6 +837,11 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups return m_groupData.GetAgentGroupMembership(UUID.Zero, agentID, groupID); } + public GroupMembershipData GetActiveMembershipData(UUID agentID) + { + return m_groupData.GetAgentActiveMembership(agentID, agentID); + } + public void UpdateGroupInfo(IClientAPI remoteClient, UUID groupID, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); @@ -811,7 +862,9 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); - if (m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), UUID.Zero, name) != null) + GroupRecord groupRecord = m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), UUID.Zero, name); + + if (groupRecord != null) { remoteClient.SendCreateGroupReply(UUID.Zero, false, "A group with the same name already exists."); return UUID.Zero; @@ -824,31 +877,31 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups if (avatar != null) { - if (avatar.UserLevel < m_levelGroupCreate) + if (avatar.GodController.UserLevel < m_levelGroupCreate) { - remoteClient.SendCreateGroupReply(UUID.Zero, false, "You have got insufficient permissions to create a group."); + remoteClient.SendCreateGroupReply(UUID.Zero, false, "You have insufficient permissions to create a group."); return UUID.Zero; } } // check funds - // is there is a money module present ? + // is there a money module present ? IMoneyModule money = scene.RequestModuleInterface(); - if (money != null) + if (money != null && money.GroupCreationCharge > 0) { - // do the transaction, that is if the agent has got sufficient funds + // do the transaction, that is if the agent has sufficient funds if (!money.AmountCovered(remoteClient.AgentId, money.GroupCreationCharge)) { - remoteClient.SendCreateGroupReply(UUID.Zero, false, "You have got insufficient funds to create a group."); + remoteClient.SendCreateGroupReply(UUID.Zero, false, "You have insufficient funds to create a group."); return UUID.Zero; } - money.ApplyCharge(GetRequestingAgentID(remoteClient), money.GroupCreationCharge, MoneyTransactionType.GroupCreate); + money.ApplyCharge(GetRequestingAgentID(remoteClient), money.GroupCreationCharge, MoneyTransactionType.GroupCreate, name); } UUID groupID = m_groupData.CreateGroup(GetRequestingAgentID(remoteClient), name, charter, showInList, insigniaID, membershipFee, openEnrollment, allowPublish, maturePublish, GetRequestingAgentID(remoteClient)); - remoteClient.SendCreateGroupReply(groupID, true, "Group created successfullly"); + remoteClient.SendCreateGroupReply(groupID, true, "Group created successfully"); // Update the founder with new group information. - SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient)); + SendAgentGroupDataUpdate(remoteClient, true); return groupID; } @@ -873,7 +926,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups if (membership != null) { return membership.GroupTitle; - } + } return string.Empty; } @@ -889,10 +942,9 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups // TODO: Not sure what all is needed here, but if the active group role change is for the group // the client currently has set active, then we need to do a scene presence update too // if (m_groupData.GetAgentActiveMembership(GetRequestingAgentID(remoteClient)).GroupID == GroupID) - - UpdateAllClientsWithGroupInfo(GetRequestingAgentID(remoteClient)); - } + SendDataUpdate(remoteClient, true); + } public void GroupRoleUpdate(IClientAPI remoteClient, UUID groupID, UUID roleID, string name, string description, string title, ulong powers, byte updateType) { @@ -929,7 +981,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups } // TODO: This update really should send out updates for everyone in the role that just got changed. - SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient)); + SendAgentGroupDataUpdate(remoteClient, false); } public void GroupRoleChanges(IClientAPI remoteClient, UUID groupID, UUID roleID, UUID memberID, uint changes) @@ -947,7 +999,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups case 1: // Remove m_groupData.RemoveAgentFromGroupRole(GetRequestingAgentID(remoteClient), memberID, groupID, roleID); - + break; default: m_log.ErrorFormat("[GROUPS]: {0} does not understand changes == {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, changes); @@ -955,7 +1007,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups } // TODO: This update really should send out updates for everyone in the role that just got changed. - SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient)); + SendAgentGroupDataUpdate(remoteClient, false); } public void GroupNoticeRequest(IClientAPI remoteClient, UUID groupNoticeID) @@ -983,7 +1035,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups msg.toAgentID = agentID.Guid; msg.dialog = dialog; msg.fromGroup = true; - msg.offline = (byte)0; + msg.offline = (byte)1; // Allow this message to be stored for offline use msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = UUID.Zero.Guid; @@ -1035,14 +1087,6 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups return msg; } - public void SendAgentGroupDataUpdate(IClientAPI remoteClient) - { - if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); - - // Send agent information about his groups - SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient)); - } - public void JoinGroupRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); @@ -1050,10 +1094,23 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups // Should check to see if OpenEnrollment, or if there's an outstanding invitation m_groupData.AddAgentToGroup(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID, UUID.Zero); + // check funds + // is there a money module present ? + GroupRecord groupRecord = m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), groupID, null); + IMoneyModule money = remoteClient.Scene.RequestModuleInterface(); + if (money != null && groupRecord.MembershipFee > 0) + { + // do the transaction, that is if the agent has sufficient funds + if (!money.AmountCovered(GetRequestingAgentID(remoteClient), groupRecord.MembershipFee)) { + remoteClient.SendCreateGroupReply(UUID.Zero, false, "You have insufficient funds to join the group."); + return; + } + money.ApplyCharge(GetRequestingAgentID(remoteClient), groupRecord.MembershipFee, MoneyTransactionType.GroupJoin, groupRecord.GroupName); + } + remoteClient.SendJoinGroupReply(groupID, true); - // Should this send updates to everyone in the group? - SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient)); + SendAgentGroupDataUpdate(remoteClient, true); } public void LeaveGroupRequest(IClientAPI remoteClient, UUID groupID) @@ -1068,7 +1125,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups // SL sends out notifcations to the group messaging session that the person has left // Should this also update everyone who is in the group? - SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient)); + SendAgentGroupDataUpdate(remoteClient, true); } public void EjectGroupMemberRequest(IClientAPI remoteClient, UUID groupID, UUID ejecteeID) @@ -1120,17 +1177,41 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups } GroupRecord groupInfo = m_groupData.GetGroupRecord(agentID, groupID, null); - - UserAccount account = m_sceneList[0].UserAccountService.GetUserAccount(regionInfo.ScopeID, ejecteeID); - if ((groupInfo == null) || (account == null)) - { + if (groupInfo == null) return; - } + + + IClientAPI ejecteeClient = GetActiveRootClient(ejecteeID); // Send Message to Ejectee GridInstantMessage msg = new GridInstantMessage(); - - msg.imSessionID = UUID.Zero.Guid; + + string ejecteeName = "Unknown member"; + // if local send a normal message + if(ejecteeClient != null) + { + msg.imSessionID = UUID.Zero.Guid; + msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.MessageFromAgent; + // also execute and send update + ejecteeClient.SendAgentDropGroup(groupID); + SendAgentGroupDataUpdate(ejecteeClient,true); + ejecteeName = ejecteeClient.Name; + } + else // send + { + // Interop, received special 210 code for ejecting a group member + // this only works within the comms servers domain, and won't work hypergrid + // TODO:FIXME: Use a presence server of some kind to find out where the + // client actually is, and try contacting that region directly to notify them, + // or provide the notification via xmlrpc update queue + + msg.imSessionID = groupInfo.GroupID.Guid; + msg.dialog = (byte)210; //interop + UserAccount account = m_sceneList[0].UserAccountService.GetUserAccount(regionInfo.ScopeID, ejecteeID); + if (account != null) + ejecteeName = account.FirstName + " " + account.LastName; + } + msg.fromAgentID = agentID.Guid; // msg.fromAgentID = info.GroupID; msg.toAgentID = ejecteeID.Guid; @@ -1138,7 +1219,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups msg.timestamp = 0; msg.fromAgentName = agentName; msg.message = string.Format("You have been ejected from '{1}' by {0}.", agentName, groupInfo.GroupName); - msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.MessageFromAgent; +// msg.fromGroup = false; msg.offline = (byte)0; msg.ParentEstateID = 0; @@ -1148,11 +1229,6 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups OutgoingInstantMessage(msg, ejecteeID); // Message to ejector - // Interop, received special 210 code for ejecting a group member - // this only works within the comms servers domain, and won't work hypergrid - // TODO:FIXME: Use a presence server of some kind to find out where the - // client actually is, and try contacting that region directly to notify them, - // or provide the notification via xmlrpc update queue msg = new GridInstantMessage(); msg.imSessionID = UUID.Zero.Guid; @@ -1160,15 +1236,11 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups msg.toAgentID = agentID.Guid; msg.timestamp = 0; msg.fromAgentName = agentName; - if (account != null) - { - msg.message = string.Format("{2} has been ejected from '{1}' by {0}.", agentName, groupInfo.GroupName, account.FirstName + " " + account.LastName); - } - else - { - msg.message = string.Format("{2} has been ejected from '{1}' by {0}.", agentName, groupInfo.GroupName, "Unknown member"); - } - msg.dialog = (byte)210; //interop + + msg.message = string.Format("{2} has been ejected from '{1}' by {0}.", agentName, groupInfo.GroupName, ejecteeName); + +// msg.dialog = (byte)210; //interop + msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.MessageFromAgent; msg.fromGroup = false; msg.offline = (byte)0; msg.ParentEstateID = 0; @@ -1176,11 +1248,6 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups msg.RegionID = regionInfo.RegionID.Guid; msg.binaryBucket = new byte[0]; OutgoingInstantMessage(msg, agentID); - - - // SL sends out messages to everyone in the group - // Who all should receive updates and what should they be updated with? - UpdateAllClientsWithGroupInfo(ejecteeID); } public void InviteGroupRequest(IClientAPI remoteClient, UUID groupID, UUID invitedAgentID, UUID roleID) @@ -1275,6 +1342,19 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups #region Client/Update Tools + private IClientAPI GetActiveRootClient(UUID agentID) + { + foreach (Scene scene in m_sceneList) + { + ScenePresence sp = scene.GetScenePresence(agentID); + if (sp != null && !sp.IsChildAgent && !sp.IsDeleted) + { + return sp.ControllingClient; + } + } + return null; + } + /// /// Try to find an active IClientAPI reference for agentID giving preference to root connections /// @@ -1286,7 +1366,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups foreach (Scene scene in m_sceneList) { ScenePresence sp = scene.GetScenePresence(agentID); - if (sp != null) + if (sp != null && !sp.IsDeleted) { if (!sp.IsChildAgent) { @@ -1303,67 +1383,6 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups return child; } - /// - /// Send 'remoteClient' the group membership 'data' for agent 'dataForAgentID'. - /// - private void SendGroupMembershipInfoViaCaps(IClientAPI remoteClient, UUID dataForAgentID, GroupMembershipData[] data) - { - if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); - - OSDArray AgentData = new OSDArray(1); - OSDMap AgentDataMap = new OSDMap(1); - AgentDataMap.Add("AgentID", OSD.FromUUID(dataForAgentID)); - AgentData.Add(AgentDataMap); - - OSDArray GroupData = new OSDArray(data.Length); - OSDArray NewGroupData = new OSDArray(data.Length); - - foreach (GroupMembershipData membership in data) - { - if (GetRequestingAgentID(remoteClient) != dataForAgentID) - { - if (!membership.ListInProfile) - { - // If we're sending group info to remoteclient about another agent, - // filter out groups the other agent doesn't want to share. - continue; - } - } - - OSDMap GroupDataMap = new OSDMap(6); - OSDMap NewGroupDataMap = new OSDMap(1); - - GroupDataMap.Add("GroupID", OSD.FromUUID(membership.GroupID)); - GroupDataMap.Add("GroupPowers", OSD.FromULong(membership.GroupPowers)); - GroupDataMap.Add("AcceptNotices", OSD.FromBoolean(membership.AcceptNotices)); - GroupDataMap.Add("GroupInsigniaID", OSD.FromUUID(membership.GroupPicture)); - GroupDataMap.Add("Contribution", OSD.FromInteger(membership.Contribution)); - GroupDataMap.Add("GroupName", OSD.FromString(membership.GroupName)); - NewGroupDataMap.Add("ListInProfile", OSD.FromBoolean(membership.ListInProfile)); - - GroupData.Add(GroupDataMap); - NewGroupData.Add(NewGroupDataMap); - } - - OSDMap llDataStruct = new OSDMap(3); - llDataStruct.Add("AgentData", AgentData); - llDataStruct.Add("GroupData", GroupData); - llDataStruct.Add("NewGroupData", NewGroupData); - - if (m_debugEnabled) - { - m_log.InfoFormat("[GROUPS]: {0}", OSDParser.SerializeJsonString(llDataStruct)); - } - - IEventQueue queue = remoteClient.Scene.RequestModuleInterface(); - - if (queue != null) - { - queue.Enqueue(queue.BuildEvent("AgentGroupDataUpdate", llDataStruct), GetRequestingAgentID(remoteClient)); - } - - } - private void SendScenePresenceUpdate(UUID AgentID, string Title) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Updating scene title for {0} with title: {1}", AgentID, Title); @@ -1380,54 +1399,40 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups presence.Grouptitle = Title; if (! presence.IsChildAgent) - presence.SendAvatarDataToAllClients(); + presence.SendAvatarDataToAllAgents(); } } } } - /// - /// Send updates to all clients who might be interested in groups data for dataForClientID - /// - private void UpdateAllClientsWithGroupInfo(UUID dataForClientID) + public void SendAgentGroupDataUpdate(IClientAPI remoteClient) { - if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); - - // TODO: Probably isn't nessesary to update every client in every scene. - // Need to examine client updates and do only what's nessesary. - lock (m_sceneList) - { - foreach (Scene scene in m_sceneList) - { - scene.ForEachClient(delegate(IClientAPI client) { SendAgentGroupDataUpdate(client, dataForClientID); }); - } - } + SendAgentGroupDataUpdate(remoteClient, true); } /// - /// Update remoteClient with group information about dataForAgentID + /// Tell remoteClient about its agent groups, and optionally send title to others /// - private void SendAgentGroupDataUpdate(IClientAPI remoteClient, UUID dataForAgentID) + private void SendAgentGroupDataUpdate(IClientAPI remoteClient, bool tellOthers) { if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: {0} called for {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, remoteClient.Name); + // NPCs currently don't have a CAPs structure or event queues. There is a strong argument for conveying this information + // to them anyway since it makes writing server-side bots a lot easier, but for now we don't do anything. + if (remoteClient.SceneAgent.PresenceType == PresenceType.Npc) + return; + // TODO: All the client update functions need to be reexamined because most do too much and send too much stuff - OnAgentDataUpdateRequest(remoteClient, dataForAgentID, UUID.Zero); + UUID agentID = GetRequestingAgentID(remoteClient); - // Need to send a group membership update to the client - // UDP version doesn't seem to behave nicely. But we're going to send it out here - // with an empty group membership to hopefully remove groups being displayed due - // to the core Groups Stub - remoteClient.SendGroupMembership(new GroupMembershipData[0]); + SendDataUpdate(remoteClient, tellOthers); - GroupMembershipData[] membershipArray = GetProfileListedGroupMemberships(remoteClient, dataForAgentID); - SendGroupMembershipInfoViaCaps(remoteClient, dataForAgentID, membershipArray); - remoteClient.SendAvatarGroupsReply(dataForAgentID, membershipArray); + GroupMembershipData[] membershipArray = GetProfileListedGroupMemberships(remoteClient, agentID); + remoteClient.UpdateGroupMembership(membershipArray); - if (remoteClient.AgentId == dataForAgentID) - remoteClient.RefreshGroupMembership(); - } + remoteClient.SendAgentGroupDataUpdate(agentID, membershipArray); + } /// /// Get a list of groups memberships for the agent that are marked "ListInProfile" @@ -1465,7 +1470,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups membershipArray = membershipData.ToArray(); } } - + if (m_debugEnabled) { m_log.InfoFormat("[GROUPS]: Get group membership information for {0} requested by {1}", dataForAgentID, requestingClient.AgentId); @@ -1478,13 +1483,27 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups return membershipArray; } - - private void SendAgentDataUpdate(IClientAPI remoteClient, UUID dataForAgentID, UUID activeGroupID, string activeGroupName, ulong activeGroupPowers, string activeGroupTitle) + //tell remoteClient about its agent group info, and optionally send title to others + private void SendDataUpdate(IClientAPI remoteClient, bool tellOthers) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); - // TODO: All the client update functions need to be reexamined because most do too much and send too much stuff - UserAccount account = m_sceneList[0].UserAccountService.GetUserAccount(remoteClient.Scene.RegionInfo.ScopeID, dataForAgentID); + UUID activeGroupID = UUID.Zero; + string activeGroupTitle = string.Empty; + string activeGroupName = string.Empty; + ulong activeGroupPowers = (ulong)GroupPowers.None; + + UUID agentID = GetRequestingAgentID(remoteClient); + GroupMembershipData membership = m_groupData.GetAgentActiveMembership(agentID, agentID); + if (membership != null) + { + activeGroupID = membership.GroupID; + activeGroupTitle = membership.GroupTitle; + activeGroupPowers = membership.GroupPowers; + activeGroupName = membership.GroupName; + } + + UserAccount account = m_sceneList[0].UserAccountService.GetUserAccount(remoteClient.Scene.RegionInfo.ScopeID, agentID); string firstname, lastname; if (account != null) { @@ -1497,9 +1516,17 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups lastname = "Unknown"; } - remoteClient.SendAgentDataUpdate(dataForAgentID, activeGroupID, firstname, + remoteClient.SendAgentDataUpdate(agentID, activeGroupID, firstname, lastname, activeGroupPowers, activeGroupName, activeGroupTitle); + + + if (tellOthers) + SendScenePresenceUpdate(agentID, activeGroupTitle); + + ScenePresence sp = (ScenePresence)remoteClient.SceneAgent; + if (sp != null) + sp.Grouptitle = activeGroupTitle; } #endregion @@ -1510,7 +1537,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups { if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); - IClientAPI localClient = GetActiveClient(msgTo); + IClientAPI localClient = GetActiveRootClient(msgTo); if (localClient != null) { if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: MsgTo ({0}) is local, delivering directly", localClient.Name); diff --git a/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/IGroupsServicesConnector.cs b/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/IGroupsServicesConnector.cs index 6b5b40a..08c7096 100644 --- a/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/IGroupsServicesConnector.cs +++ b/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/IGroupsServicesConnector.cs @@ -43,7 +43,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups /// /// The UUID of the user making the request. /// - /// The ID of the record to retrieve. + /// The ID of the record to retrieve. /// GroupName may be specified instead, in which case this parameter will be UUID.Zero /// /// @@ -51,7 +51,8 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups /// GroupID may be specified instead, in which case this parmeter will be null. /// GroupRecord GetGroupRecord(UUID RequestingAgentID, UUID GroupID, string GroupName); - + GroupProfileData GetMemberGroupProfile(UUID requestingAgentID, UUID GroupID, UUID AgentID); + List FindGroups(UUID RequestingAgentID, string search); List GetGroupMembers(UUID RequestingAgentID, UUID GroupID); @@ -88,7 +89,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups /// If the user is a member of the group then the data structure is returned. If not, then null is returned. /// GroupMembershipData GetAgentGroupMembership(UUID RequestingAgentID, UUID AgentID, UUID GroupID); - + /// /// Get information about the groups to which a user belongs. /// diff --git a/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/SimianGroupsServicesConnectorModule.cs b/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/SimianGroupsServicesConnectorModule.cs index 1cb4747..98c7ed4 100644 --- a/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/SimianGroupsServicesConnectorModule.cs +++ b/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/SimianGroupsServicesConnectorModule.cs @@ -48,16 +48,16 @@ using OpenSim.Services.Interfaces; /*************************************************************************** * Simian Data Map * =============== - * + * * OwnerID -> Type -> Key * ----------------------- - * + * * UserID -> Group -> ActiveGroup * + GroupID - * + * * UserID -> GroupSessionDropped -> GroupID * UserID -> GroupSessionInvited -> GroupID - * + * * UserID -> GroupMember -> GroupID * + SelectedRoleID [UUID] * + AcceptNotices [bool] @@ -65,9 +65,9 @@ using OpenSim.Services.Interfaces; * + Contribution [int] * * UserID -> GroupRole[GroupID] -> RoleID - * - * - * GroupID -> Group -> GroupName + * + * + * GroupID -> Group -> GroupName * + Charter * + ShowInList * + InsigniaID @@ -79,17 +79,17 @@ using OpenSim.Services.Interfaces; * + EveryonePowers * + OwnerRoleID * + OwnersPowers - * + * * GroupID -> GroupRole -> RoleID * + Name * + Description * + Title * + Powers - * + * * GroupID -> GroupMemberInvite -> InviteID * + AgentID * + RoleID - * + * * GroupID -> GroupNotice -> NoticeID * + TimeStamp [uint] * + FromName [string] @@ -106,12 +106,12 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - public const GroupPowers m_DefaultEveryonePowers = GroupPowers.AllowSetHome | - GroupPowers.Accountable | - GroupPowers.JoinChat | - GroupPowers.AllowVoiceChat | - GroupPowers.ReceiveNotices | - GroupPowers.StartProposal | + public const GroupPowers m_DefaultEveryonePowers = GroupPowers.AllowSetHome | + GroupPowers.Accountable | + GroupPowers.JoinChat | + GroupPowers.AllowVoiceChat | + GroupPowers.ReceiveNotices | + GroupPowers.StartProposal | GroupPowers.VoteOnProposal; // Would this be cleaner as (GroupPowers)ulong.MaxValue; @@ -168,12 +168,12 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups private bool m_debugEnabled = false; private Dictionary m_pendingRequests = new Dictionary(); - + private ExpiringCache m_memoryCache; private int m_cacheTimeout = 30; // private IUserAccountService m_accountService = null; - + #region Region Module interfaceBase Members @@ -229,10 +229,10 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] Groups Cache Timeout set to {0}.", m_cacheTimeout); } - + m_memoryCache = new ExpiringCache(); - + // If we got all the config options we need, lets start'er'up m_connectorEnabled = true; @@ -244,7 +244,6 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups public void Close() { - m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR]: Closing {0}", this.Name); } public void AddRegion(OpenSim.Region.Framework.Scenes.Scene scene) @@ -288,8 +287,8 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups /// /// Create a Group, including Everyone and Owners Role, place FounderID in both groups, select Owner as selected role, and newly created group as agent's active role. /// - public UUID CreateGroup(UUID requestingAgentID, string name, string charter, bool showInList, UUID insigniaID, - int membershipFee, bool openEnrollment, bool allowPublish, + public UUID CreateGroup(UUID requestingAgentID, string name, string charter, bool showInList, UUID insigniaID, + int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish, UUID founderID) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); @@ -314,7 +313,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups { AddGroupRole(requestingAgentID, GroupID, UUID.Zero, "Everyone", "Members of " + name, "Member of " + name, (ulong)m_DefaultEveryonePowers); AddGroupRole(requestingAgentID, GroupID, OwnerRoleID, "Owners", "Owners of " + name, "Owner of " + name, (ulong)m_DefaultOwnerPowers); - + AddAgentToGroup(requestingAgentID, requestingAgentID, GroupID, OwnerRoleID); return GroupID; @@ -326,8 +325,8 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups } - public void UpdateGroup(UUID requestingAgentID, UUID groupID, string charter, bool showInList, - UUID insigniaID, int membershipFee, bool openEnrollment, + public void UpdateGroup(UUID requestingAgentID, UUID groupID, string charter, bool showInList, + UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); @@ -351,7 +350,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups } - public void AddGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID, string name, string description, + public void AddGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); @@ -394,7 +393,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups } - public void UpdateGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID, string name, string description, + public void UpdateGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); @@ -435,7 +434,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups { return null; } - } + } else if (!string.IsNullOrEmpty(groupName)) { if (!SimianGetFirstGenericEntry("Group", groupName, out groupID, out GroupInfoMap)) @@ -482,7 +481,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups { MemberGroupProfile.Charter = groupProfile["Charter"].AsString(); } - + MemberGroupProfile.ShowInList = groupProfile["ShowInList"].AsString() == "1"; MemberGroupProfile.InsigniaID = groupProfile["InsigniaID"].AsUUID(); MemberGroupProfile.MembershipFee = groupProfile["MembershipFee"].AsInteger(); @@ -490,7 +489,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups MemberGroupProfile.AllowPublish = groupProfile["AllowPublish"].AsBoolean(); MemberGroupProfile.MaturePublish = groupProfile["MaturePublish"].AsBoolean(); MemberGroupProfile.FounderID = groupProfile["FounderID"].AsUUID();; - MemberGroupProfile.OwnerRole = groupProfile["OwnerRoleID"].AsUUID(); + MemberGroupProfile.OwnerRole = groupProfile["OwnerRoleID"].AsUUID(); Dictionary Members; if (SimianGetGenericEntries("GroupMember",groupID.ToString(), out Members)) @@ -547,7 +546,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups { GroupMemberInfo = new OSDMap(); } - + GroupMemberInfo["AcceptNotices"] = OSD.FromBoolean(acceptNotices); GroupMemberInfo["ListInProfile"] = OSD.FromBoolean(listInProfile); GroupMemberInfo["Contribution"] = OSD.FromInteger(0); @@ -625,7 +624,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups // Remove Group Member information for this group SimianRemoveGenericEntry(agentID, "GroupMember", groupID.ToString()); - // By using a Simian Generics Type consisting of a prefix and a groupID, + // By using a Simian Generics Type consisting of a prefix and a groupID, // combined with RoleID as key allows us to get a list of roles a particular member // of a group is assigned to. string GroupRoleMemberType = "GroupRole" + groupID.ToString(); @@ -697,7 +696,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups { data.members = 0; } - + // TODO: sort results? // data.searchOrder = order; @@ -722,8 +721,8 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups data.AcceptNotices = UserGroupMemberInfo["AcceptNotices"].AsBoolean(); data.Contribution = UserGroupMemberInfo["Contribution"].AsInteger(); data.ListInProfile = UserGroupMemberInfo["ListInProfile"].AsBoolean(); - data.ActiveRole = UserGroupMemberInfo["SelectedRoleID"].AsUUID(); - + data.ActiveRole = UserGroupMemberInfo["SelectedRoleID"].AsUUID(); + /////////////////////////////// // Agent Specific Information: // @@ -731,7 +730,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups if (SimianGetGenericEntry(agentID, "Group", "ActiveGroup", out UserActiveGroup)) { data.Active = UserActiveGroup["GroupID"].AsUUID().Equals(groupID); - } + } /////////////////////////////// // Role Specific Information: @@ -741,8 +740,8 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups { data.GroupTitle = GroupRoleInfo["Title"].AsString(); data.GroupPowers = GroupRoleInfo["Powers"].AsULong(); - } - + } + /////////////////////////////// // Group Specific Information: // @@ -760,7 +759,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups data.MembershipFee = GroupInfo["MembershipFee"].AsInteger(); data.OpenEnrollment = GroupInfo["OpenEnrollment"].AsBoolean(); data.ShowInList = GroupInfo["ShowInList"].AsBoolean(); - } + } } return data; @@ -795,7 +794,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups memberships.Add(GetAgentGroupMembership(requestingAgentID, agentID, UUID.Parse(key))); } } - + return memberships; } @@ -1018,7 +1017,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups Notice["BinaryBucket"] = OSD.FromBinary(binaryBucket); SimianAddGeneric(groupID, "GroupNotice", noticeID.ToString(), Notice); - + } #endregion @@ -1251,7 +1250,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups { "OwnerID", ownerID.ToString() }, { "Type", type } }; - + OSDMap response = CachedPostRequest(requestArgs); @@ -1358,7 +1357,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups || requestArgs["RequestMethod"] == "AddGeneric") { m_log.WarnFormat("[SIMIAN GROUPS CONNECTOR]: clearing generics cache"); - + // Any and all updates cause the cache to clear m_memoryCache.Clear(); @@ -1384,14 +1383,14 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups { if (m_memoryCache.TryGetValue(CacheKey, out response)) return response; - + if (! m_pendingRequests.ContainsKey(CacheKey)) { m_pendingRequests.Add(CacheKey,true); firstRequest = true; } } - + if (firstRequest) { // if it wasn't in the cache, pass the request to the Simian Grid Services @@ -1403,7 +1402,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups { m_log.ErrorFormat("[SIMIAN GROUPS CONNECTOR]: request failed {0}", CacheKey); } - + // and cache the response lock (m_memoryCache) { @@ -1421,7 +1420,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups // { // m_log.WarnFormat("[SIMIAN GROUPS CONNECTOR]: query not in the cache"); // Util.PrintCallStack(); - + // // if it wasn't in the cache, pass the request to the Simian Grid Services // response = WebUtil.PostToService(m_groupsServerURI, requestArgs); diff --git a/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/Tests/GroupsModuleTests.cs b/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/Tests/GroupsModuleTests.cs index 9a42bac..ccfcd8b 100644 --- a/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/Tests/GroupsModuleTests.cs +++ b/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/Tests/GroupsModuleTests.cs @@ -74,14 +74,15 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups.Tests [Test] public void TestSendAgentGroupDataUpdate() { +/* AgentGroupDataUpdate is udp TestHelpers.InMethod(); // TestHelpers.EnableLogging(); - + TestScene scene = new SceneHelpers().SetupScene(); IConfigSource configSource = new IniConfigSource(); - IConfig config = configSource.AddConfig("Groups"); + IConfig config = configSource.AddConfig("Groups"); config.Set("Enabled", true); - config.Set("Module", "GroupsModule"); + config.Set("Module", "GroupsModule"); config.Set("DebugEnabled", true); GroupsModule gm = new GroupsModule(); @@ -98,6 +99,13 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups.Tests Hashtable eventsResponse = eqgm.GetEvents(UUID.Zero, sp.UUID); + if((int)eventsResponse["int_response_code"] != (int)HttpStatusCode.OK) + { + eventsResponse = eqgm.GetEvents(UUID.Zero, sp.UUID); + if((int)eventsResponse["int_response_code"] != (int)HttpStatusCode.OK) + eventsResponse = eqgm.GetEvents(UUID.Zero, sp.UUID); + } + Assert.That((int)eventsResponse["int_response_code"], Is.EqualTo((int)HttpStatusCode.OK)); // Console.WriteLine("Response [{0}]", (string)eventsResponse["str_response_string"]); @@ -116,7 +124,8 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups.Tests Assert.That(foundUpdate, Is.True, "Did not find AgentGroupDataUpdate in response"); - // TODO: More checking of more actual event data. + // TODO: More checking of more actual event data. +*/ } [Test] @@ -124,7 +133,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups.Tests { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); - + TestScene scene = new SceneHelpers().SetupScene(); MessageTransferModule mtm = new MessageTransferModule(); @@ -135,12 +144,12 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups.Tests IConfigSource configSource = new IniConfigSource(); { - IConfig config = configSource.AddConfig("Messaging"); + IConfig config = configSource.AddConfig("Messaging"); config.Set("MessageTransferModule", mtm.Name); } { - IConfig config = configSource.AddConfig("Groups"); + IConfig config = configSource.AddConfig("Groups"); config.Set("Enabled", true); config.Set("Module", gm.Name); config.Set("DebugEnabled", true); diff --git a/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/XmlRpcGroupsServicesConnectorModule.cs b/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/XmlRpcGroupsServicesConnectorModule.cs index 20555e4..fab7e8c 100644 --- a/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/XmlRpcGroupsServicesConnectorModule.cs +++ b/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/XmlRpcGroupsServicesConnectorModule.cs @@ -53,17 +53,17 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups private bool m_debugEnabled = false; - public const GroupPowers DefaultEveryonePowers - = GroupPowers.AllowSetHome - | GroupPowers.Accountable - | GroupPowers.JoinChat - | GroupPowers.AllowVoiceChat - | GroupPowers.ReceiveNotices - | GroupPowers.StartProposal + public const GroupPowers DefaultEveryonePowers + = GroupPowers.AllowSetHome + | GroupPowers.Accountable + | GroupPowers.JoinChat + | GroupPowers.AllowVoiceChat + | GroupPowers.ReceiveNotices + | GroupPowers.StartProposal | GroupPowers.VoteOnProposal; // Would this be cleaner as (GroupPowers)ulong.MaxValue? - public const GroupPowers DefaultOwnerPowers + public const GroupPowers DefaultOwnerPowers = GroupPowers.Accountable | GroupPowers.AllowEditLand | GroupPowers.AllowFly @@ -114,7 +114,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups private string m_groupsServerURI = string.Empty; - private bool m_disableKeepAlive = false; + private bool m_disableKeepAlive = true; private string m_groupReadKey = string.Empty; private string m_groupWriteKey = string.Empty; @@ -174,13 +174,13 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups return; } - m_disableKeepAlive = groupsConfig.GetBoolean("XmlRpcDisableKeepAlive", false); + m_disableKeepAlive = groupsConfig.GetBoolean("XmlRpcDisableKeepAlive", true); m_groupReadKey = groupsConfig.GetString("XmlRpcServiceReadKey", string.Empty); m_groupWriteKey = groupsConfig.GetString("XmlRpcServiceWriteKey", string.Empty); - m_cacheTimeout = groupsConfig.GetInt("GroupsCacheTimeout", 30); + if (m_cacheTimeout == 0) { m_log.WarnFormat("[XMLRPC-GROUPS-CONNECTOR]: Groups Cache Disabled."); @@ -200,7 +200,6 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups public void Close() { - m_log.DebugFormat("[XMLRPC-GROUPS-CONNECTOR]: Closing {0}", this.Name); } public void AddRegion(OpenSim.Region.Framework.Scenes.Scene scene) @@ -383,10 +382,11 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups GroupMembershipData MemberInfo = GetAgentGroupMembership(requestingAgentID, AgentID, GroupID); GroupProfileData MemberGroupProfile = GroupProfileHashtableToGroupProfileData(respData); - - MemberGroupProfile.MemberTitle = MemberInfo.GroupTitle; - MemberGroupProfile.PowersMask = MemberInfo.GroupPowers; - + if(MemberInfo != null) + { + MemberGroupProfile.MemberTitle = MemberInfo.GroupTitle; + MemberGroupProfile.PowersMask = MemberInfo.GroupPowers; + } return MemberGroupProfile; } @@ -666,6 +666,8 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups data.ListInProfile = ((string)membership["ListInProfile"]) == "1"; data.AgentPowers = ulong.Parse((string)membership["AgentPowers"]); data.Title = (string)membership["Title"]; + if(membership.ContainsKey("OnlineStatus")) + data.OnlineStatus = (string)membership["OnlineStatus"]; members.Add(data); } @@ -803,11 +805,12 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups { if (m_groupsAgentsDroppedFromChatSession.ContainsKey(groupID)) { + if (m_groupsAgentsInvitedToChatSession[groupID].Contains(agentID)) + m_groupsAgentsInvitedToChatSession[groupID].Remove(agentID); + // If not in dropped list, add if (!m_groupsAgentsDroppedFromChatSession[groupID].Contains(agentID)) - { m_groupsAgentsDroppedFromChatSession[groupID].Add(agentID); - } } } @@ -818,9 +821,10 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups // If nessesary, remove from dropped list if (m_groupsAgentsDroppedFromChatSession[groupID].Contains(agentID)) - { m_groupsAgentsDroppedFromChatSession[groupID].Remove(agentID); - } + + if (!m_groupsAgentsInvitedToChatSession[groupID].Contains(agentID)) + m_groupsAgentsInvitedToChatSession[groupID].Add(agentID); } private void CreateGroupChatSessionTracking(UUID groupID) @@ -975,35 +979,42 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups try { - resp = req.Send(m_groupsServerURI, 10000); - - if ((m_cacheTimeout > 0) && (CacheKey != null)) - { - m_memoryCache.AddOrUpdate(CacheKey, resp, TimeSpan.FromSeconds(m_cacheTimeout)); - } + resp = req.Send(m_groupsServerURI); } catch (Exception e) { m_log.ErrorFormat( - "[XMLRPC-GROUPS-CONNECTOR]: An error has occured while attempting to access the XmlRpcGroups server method {0} at {1}", - function, m_groupsServerURI); - - m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: {0}{1}", e.Message, e.StackTrace); + "[XMLRPC-GROUPS-CONNECTOR]: An error has occured while attempting to access the XmlRpcGroups server method {0} at {1}: {2}", + function, m_groupsServerURI, e.Message); - foreach (string ResponseLine in req.RequestResponse.Split(new string[] { Environment.NewLine }, StringSplitOptions.None)) + if(m_debugEnabled) { - m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: {0} ", ResponseLine); + m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: {0}", e.StackTrace); + + foreach (string ResponseLine in req.RequestResponse.Split(new string[] { Environment.NewLine }, StringSplitOptions.None)) + { + m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: {0} ", ResponseLine); + } + + foreach (string key in param.Keys) + { + m_log.WarnFormat("[XMLRPC-GROUPS-CONNECTOR]: {0} :: {1}", key, param[key].ToString()); + } } - foreach (string key in param.Keys) + if ((m_cacheTimeout > 0) && (CacheKey != null)) { - m_log.WarnFormat("[XMLRPC-GROUPS-CONNECTOR]: {0} :: {1}", key, param[key].ToString()); + m_memoryCache.AddOrUpdate(CacheKey, resp, 10.0); } - Hashtable respData = new Hashtable(); respData.Add("error", e.ToString()); return respData; } + + if ((m_cacheTimeout > 0) && (CacheKey != null)) + { + m_memoryCache.AddOrUpdate(CacheKey, resp, 10.0); + } } if (resp.Value is Hashtable) @@ -1042,7 +1053,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups private void LogRespDataToConsoleError(UUID requestingAgentID, string function, Hashtable param, Hashtable respData) { m_log.ErrorFormat( - "[XMLRPC-GROUPS-CONNECTOR]: Error when calling {0} for {1} with params {2}. Response params are {3}", + "[XMLRPC-GROUPS-CONNECTOR]: Error when calling {0} for {1} with params {2}. Response params are {3}", function, requestingAgentID, Util.PrettyFormatToSingleLine(param), Util.PrettyFormatToSingleLine(respData)); } @@ -1134,6 +1145,7 @@ namespace Nwc.XmlRpc request.ContentType = "text/xml"; request.AllowWriteStreamBuffering = true; request.KeepAlive = !_disableKeepAlive; + request.Timeout = 30000; using (Stream stream = request.GetRequestStream()) { @@ -1141,7 +1153,7 @@ namespace Nwc.XmlRpc { _serializer.Serialize(xml, this); xml.Flush(); - } + } } XmlRpcResponse resp; diff --git a/OpenSim/Region/OptionalModules/DataSnapshot/DataSnapshotManager.cs b/OpenSim/Region/OptionalModules/DataSnapshot/DataSnapshotManager.cs index 0c3446d..0436f96 100644 --- a/OpenSim/Region/OptionalModules/DataSnapshot/DataSnapshotManager.cs +++ b/OpenSim/Region/OptionalModules/DataSnapshot/DataSnapshotManager.cs @@ -101,7 +101,7 @@ namespace OpenSim.Region.DataSnapshot public void Initialise(IConfigSource config) { - if (!m_configLoaded) + if (!m_configLoaded) { m_configLoaded = true; //m_log.Debug("[DATASNAPSHOT]: Loading configuration"); @@ -248,7 +248,7 @@ namespace OpenSim.Region.DataSnapshot m_snapStore.ForceSceneStale(scene); } - public void Close() + public void Close() { if (!m_enabled) return; @@ -432,7 +432,6 @@ namespace OpenSim.Region.DataSnapshot m_log.Info("[DATASNAPSHOT]: data service " + url + " notified. Secret: " + m_Secret); } } - } #endregion diff --git a/OpenSim/Region/OptionalModules/DataSnapshot/LandSnapshot.cs b/OpenSim/Region/OptionalModules/DataSnapshot/LandSnapshot.cs index b8c90cd..8e6a30e 100644 --- a/OpenSim/Region/OptionalModules/DataSnapshot/LandSnapshot.cs +++ b/OpenSim/Region/OptionalModules/DataSnapshot/LandSnapshot.cs @@ -120,12 +120,15 @@ namespace OpenSim.Region.DataSnapshot.Providers public XmlNode RequestSnapshotData(XmlDocument nodeFactory) { + XmlNode parent = nodeFactory.CreateNode(XmlNodeType.Element, "parceldata", ""); ILandChannel landChannel = m_scene.LandChannel; + if(landChannel == null) + return parent; + List parcels = landChannel.AllParcels(); IDwellModule dwellModule = m_scene.RequestModuleInterface(); - XmlNode parent = nodeFactory.CreateNode(XmlNodeType.Element, "parceldata", ""); if (parcels != null) { @@ -140,7 +143,7 @@ namespace OpenSim.Region.DataSnapshot.Providers LandData parcel = land.LandData; if (m_parent.ExposureLevel.Equals("all") || - (m_parent.ExposureLevel.Equals("minimum") && + (m_parent.ExposureLevel.Equals("minimum") && (parcel.Flags & (uint)ParcelFlags.ShowDirectory) == (uint)ParcelFlags.ShowDirectory)) { @@ -265,8 +268,12 @@ namespace OpenSim.Region.DataSnapshot.Providers { XmlNode username = nodeFactory.CreateNode(XmlNodeType.Element, "name", ""); UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, userOwnerUUID); - username.InnerText = account.FirstName + " " + account.LastName; + if(account != null) + username.InnerText = account.FirstName + " " + account.LastName; + else + username.InnerText = "UnKnown"; userblock.AppendChild(username); + } catch (Exception) { diff --git a/OpenSim/Region/OptionalModules/DataSnapshot/ObjectSnapshot.cs b/OpenSim/Region/OptionalModules/DataSnapshot/ObjectSnapshot.cs index 0bb4044..caca303 100644 --- a/OpenSim/Region/OptionalModules/DataSnapshot/ObjectSnapshot.cs +++ b/OpenSim/Region/OptionalModules/DataSnapshot/ObjectSnapshot.cs @@ -83,7 +83,8 @@ namespace OpenSim.Region.DataSnapshot.Providers { this.Stale = true; }; client.OnObjectPermissions += delegate(IClientAPI controller, UUID agentID, UUID sessionID, byte field, uint localId, uint mask, byte set) { this.Stale = true; }; - client.OnRezObject += delegate(IClientAPI remoteClient, UUID itemID, Vector3 RayEnd, + client.OnRezObject += delegate(IClientAPI remoteClient, UUID itemID, UUID groupID, + Vector3 RayEnd, Vector3 RayStart, UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection, bool RezSelected, bool RemoveItem, UUID fromTaskID) { this.Stale = true; }; diff --git a/OpenSim/Region/OptionalModules/Example/BareBonesNonShared/BareBonesNonSharedModule.cs b/OpenSim/Region/OptionalModules/Example/BareBonesNonShared/BareBonesNonSharedModule.cs index bbf7168..95a2dd6 100644 --- a/OpenSim/Region/OptionalModules/Example/BareBonesNonShared/BareBonesNonSharedModule.cs +++ b/OpenSim/Region/OptionalModules/Example/BareBonesNonShared/BareBonesNonSharedModule.cs @@ -46,12 +46,12 @@ namespace OpenSim.Region.OptionalModules.Example.BareBonesNonShared /// /// /// This module is the simplest possible example of a non-shared region module (a module where each scene/region - /// in the simulator has its own copy). If anybody wants to create a more complex example in the future then + /// in the simulator has its own copy). If anybody wants to create a more complex example in the future then /// please create a separate class. - /// - /// This module is not active by default. If you want to see it in action, + /// + /// This module is not active by default. If you want to see it in action, /// then just uncomment the line below starting with [Extension(Path... - /// + /// /// When the module is enabled it will print messages when it receives certain events to the screen and the log /// file. /// @@ -59,34 +59,34 @@ namespace OpenSim.Region.OptionalModules.Example.BareBonesNonShared public class BareBonesNonSharedModule : INonSharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - public string Name { get { return "Bare Bones Non Shared Module"; } } - + + public string Name { get { return "Bare Bones Non Shared Module"; } } + public Type ReplaceableInterface { get { return null; } } - + public void Initialise(IConfigSource source) { m_log.DebugFormat("[BARE BONES NON SHARED]: INITIALIZED MODULE"); } - + public void Close() { m_log.DebugFormat("[BARE BONES NON SHARED]: CLOSED MODULE"); } - + public void AddRegion(Scene scene) { m_log.DebugFormat("[BARE BONES NON SHARED]: REGION {0} ADDED", scene.RegionInfo.RegionName); } - + public void RemoveRegion(Scene scene) { m_log.DebugFormat("[BARE BONES NON SHARED]: REGION {0} REMOVED", scene.RegionInfo.RegionName); - } - + } + public void RegionLoaded(Scene scene) { m_log.DebugFormat("[BARE BONES NON SHARED]: REGION {0} LOADED", scene.RegionInfo.RegionName); - } + } } } \ No newline at end of file diff --git a/OpenSim/Region/OptionalModules/Example/BareBonesShared/BareBonesSharedModule.cs b/OpenSim/Region/OptionalModules/Example/BareBonesShared/BareBonesSharedModule.cs index 46fea3e..1271e3f 100644 --- a/OpenSim/Region/OptionalModules/Example/BareBonesShared/BareBonesSharedModule.cs +++ b/OpenSim/Region/OptionalModules/Example/BareBonesShared/BareBonesSharedModule.cs @@ -46,52 +46,52 @@ namespace OpenSim.Region.OptionalModules.Example.BareBonesShared /// /// /// This module is the simplest possible example of a shared region module (a module which is shared by every - /// scene/region running on the simulator). If anybody wants to create a more complex example in the future then + /// scene/region running on the simulator). If anybody wants to create a more complex example in the future then /// please create a separate class. - /// - /// This module is not active by default. If you want to see it in action, + /// + /// This module is not active by default. If you want to see it in action, /// then just uncomment the line below starting with [Extension(Path... - /// + /// /// When the module is enabled it will print messages when it receives certain events to the screen and the log /// file. /// //[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "BareBonesSharedModule")] public class BareBonesSharedModule : ISharedRegionModule { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - public string Name { get { return "Bare Bones Shared Module"; } } - + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + public string Name { get { return "Bare Bones Shared Module"; } } + public Type ReplaceableInterface { get { return null; } } - + public void Initialise(IConfigSource source) { m_log.DebugFormat("[BARE BONES SHARED]: INITIALIZED MODULE"); } - + public void PostInitialise() { m_log.DebugFormat("[BARE BONES SHARED]: POST INITIALIZED MODULE"); } - + public void Close() { m_log.DebugFormat("[BARE BONES SHARED]: CLOSED MODULE"); } - + public void AddRegion(Scene scene) { m_log.DebugFormat("[BARE BONES SHARED]: REGION {0} ADDED", scene.RegionInfo.RegionName); } - + public void RemoveRegion(Scene scene) { m_log.DebugFormat("[BARE BONES SHARED]: REGION {0} REMOVED", scene.RegionInfo.RegionName); - } - + } + public void RegionLoaded(Scene scene) { m_log.DebugFormat("[BARE BONES SHARED]: REGION {0} LOADED", scene.RegionInfo.RegionName); - } + } } } \ No newline at end of file diff --git a/OpenSim/Region/OptionalModules/Example/WebSocketEchoTest/WebSocketEchoModule.cs b/OpenSim/Region/OptionalModules/Example/WebSocketEchoTest/WebSocketEchoModule.cs index 5bf0ed4..0747cc0 100644 --- a/OpenSim/Region/OptionalModules/Example/WebSocketEchoTest/WebSocketEchoModule.cs +++ b/OpenSim/Region/OptionalModules/Example/WebSocketEchoTest/WebSocketEchoModule.cs @@ -40,7 +40,7 @@ using OpenSim.Framework.Servers.HttpServer; namespace OpenSim.Region.OptionalModules.WebSocketEchoModule { - + [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "WebSocketEchoModule")] public class WebSocketEchoModule : ISharedRegionModule { @@ -111,7 +111,7 @@ namespace OpenSim.Region.OptionalModules.WebSocketEchoModule obj.SendPingCheck(); } - + private void HandlerOnOnUpgradeCompleted(object sender, UpgradeCompletedEventArgs completeddata) { WebSocketHttpServerHandler obj = sender as WebSocketHttpServerHandler; @@ -136,14 +136,14 @@ namespace OpenSim.Region.OptionalModules.WebSocketEchoModule obj.Dispose(); } - // Shutting down.. so shut down all sockets. + // Shutting down.. so shut down all sockets. // Note.. this should be done outside of an ienumerable if you're also hook to the close event. public void Close() { if (!enabled) return; - - // We convert this to a for loop so we're not in in an IEnumerable when the close + + // We convert this to a for loop so we're not in in an IEnumerable when the close //call triggers an event which then removes item from _activeHandlers that we're enumerating WebSocketHttpServerHandler[] items = new WebSocketHttpServerHandler[_activeHandlers.Count]; _activeHandlers.CopyTo(items); diff --git a/OpenSim/Region/OptionalModules/Framework/Monitoring/EtcdMonitoringModule.cs b/OpenSim/Region/OptionalModules/Framework/Monitoring/EtcdMonitoringModule.cs new file mode 100644 index 0000000..921bbfb --- /dev/null +++ b/OpenSim/Region/OptionalModules/Framework/Monitoring/EtcdMonitoringModule.cs @@ -0,0 +1,195 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Text; +using log4net; +using Mono.Addins; +using Nini.Config; +using OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Framework.Console; +using OpenSim.Region.Framework.Interfaces; +using OpenSim.Region.Framework.Scenes; +using netcd; +using netcd.Serialization; +using netcd.Advanced; +using netcd.Advanced.Requests; + +namespace OpenSim.Region.OptionalModules.Framework.Monitoring +{ + /// + /// Allows to store monitoring data in etcd, a high availability + /// name-value store. + /// + [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "EtcdMonitoringModule")] + public class EtcdMonitoringModule : INonSharedRegionModule, IEtcdModule + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + protected Scene m_scene; + protected IEtcdClient m_client; + protected bool m_enabled = false; + protected string m_etcdBasePath = String.Empty; + protected bool m_appendRegionID = true; + + public string Name + { + get { return "EtcdMonitoringModule"; } + } + + public Type ReplaceableInterface + { + get { return null; } + } + + public void Initialise(IConfigSource source) + { + if (source.Configs["Etcd"] == null) + return; + + IConfig etcdConfig = source.Configs["Etcd"]; + + string etcdUrls = etcdConfig.GetString("EtcdUrls", String.Empty); + if (etcdUrls == String.Empty) + return; + + m_etcdBasePath = etcdConfig.GetString("BasePath", m_etcdBasePath); + m_appendRegionID = etcdConfig.GetBoolean("AppendRegionID", m_appendRegionID); + + if (!m_etcdBasePath.EndsWith("/")) + m_etcdBasePath += "/"; + + try + { + string[] endpoints = etcdUrls.Split(new char[] {','}); + List uris = new List(); + foreach (string endpoint in endpoints) + uris.Add(new Uri(endpoint.Trim())); + + m_client = new EtcdClient(uris.ToArray(), new DefaultSerializer(), new DefaultSerializer()); + } + catch (Exception e) + { + m_log.DebugFormat("[ETCD]: Error initializing connection: " + e.ToString()); + return; + } + + m_log.DebugFormat("[ETCD]: Etcd module configured"); + m_enabled = true; + } + + public void Close() + { + //m_client = null; + m_scene = null; + } + + public void AddRegion(Scene scene) + { + m_scene = scene; + + if (m_enabled) + { + if (m_appendRegionID) + m_etcdBasePath += m_scene.RegionInfo.RegionID.ToString() + "/"; + + m_log.DebugFormat("[ETCD]: Using base path {0} for all keys", m_etcdBasePath); + + try + { + m_client.Advanced.CreateDirectory(new CreateDirectoryRequest() {Key = m_etcdBasePath}); + } + catch (Exception e) + { + m_log.ErrorFormat("Exception trying to create base path {0}: " + e.ToString(), m_etcdBasePath); + } + + scene.RegisterModuleInterface(this); + } + } + + public void RemoveRegion(Scene scene) + { + } + + public void RegionLoaded(Scene scene) + { + } + + public bool Store(string k, string v) + { + return Store(k, v, 0); + } + + public bool Store(string k, string v, int ttl) + { + Response resp = m_client.Advanced.SetKey(new SetKeyRequest() { Key = m_etcdBasePath + k, Value = v, TimeToLive = ttl }); + + if (resp == null) + return false; + + if (resp.ErrorCode.HasValue) + { + m_log.DebugFormat("[ETCD]: Error {0} ({1}) storing {2} => {3}", resp.Cause, (int)resp.ErrorCode, m_etcdBasePath + k, v); + + return false; + } + + return true; + } + + public string Get(string k) + { + Response resp = m_client.Advanced.GetKey(new GetKeyRequest() { Key = m_etcdBasePath + k }); + + if (resp == null) + return String.Empty; + + if (resp.ErrorCode.HasValue) + { + m_log.DebugFormat("[ETCD]: Error {0} ({1}) getting {2}", resp.Cause, (int)resp.ErrorCode, m_etcdBasePath + k); + + return String.Empty; + } + + return resp.Node.Value; + } + + public void Delete(string k) + { + m_client.Advanced.DeleteKey(new DeleteKeyRequest() { Key = m_etcdBasePath + k }); + } + + public void Watch(string k, Action callback) + { + m_client.Advanced.WatchKey(new WatchKeyRequest() { Key = m_etcdBasePath + k, Callback = (x) => { callback(x.Node.Value); } }); + } + } +} diff --git a/OpenSim/Region/OptionalModules/Framework/Monitoring/MonitorServicesModule.cs b/OpenSim/Region/OptionalModules/Framework/Monitoring/MonitorServicesModule.cs index a25e034..95bb13e 100644 --- a/OpenSim/Region/OptionalModules/Framework/Monitoring/MonitorServicesModule.cs +++ b/OpenSim/Region/OptionalModules/Framework/Monitoring/MonitorServicesModule.cs @@ -48,11 +48,11 @@ namespace OpenSim.Region.OptionalModules.Framework.Monitoring protected Scene m_scene; // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - + public string Name { get { return "Services Health Monitoring Module"; } } - + public Type ReplaceableInterface { get { return null; } } - + public void Initialise(IConfigSource source) { } @@ -64,7 +64,7 @@ namespace OpenSim.Region.OptionalModules.Framework.Monitoring public void Close() { } - + public void AddRegion(Scene scene) { if (m_scene == null) diff --git a/OpenSim/Region/OptionalModules/Materials/MaterialsModule.cs b/OpenSim/Region/OptionalModules/Materials/MaterialsModule.cs index e95889d..e8cb052 100644 --- a/OpenSim/Region/OptionalModules/Materials/MaterialsModule.cs +++ b/OpenSim/Region/OptionalModules/Materials/MaterialsModule.cs @@ -59,15 +59,20 @@ namespace OpenSim.Region.OptionalModules.Materials { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - public string Name { get { return "MaterialsModule"; } } - + public string Name { get { return "MaterialsModule"; } } + public Type ReplaceableInterface { get { return null; } } + IAssetCache m_cache; private Scene m_scene = null; private bool m_enabled = false; private int m_maxMaterialsPerTransaction = 50; - public Dictionary m_regionMaterials = new Dictionary(); + public Dictionary m_Materials = new Dictionary(); + public Dictionary m_MaterialsRefCount = new Dictionary(); + + private Dictionary m_changes = new Dictionary(); + private Dictionary m_changesTime = new Dictionary(); public void Initialise(IConfigSource source) { @@ -83,13 +88,13 @@ namespace OpenSim.Region.OptionalModules.Materials if (m_enabled) m_log.DebugFormat("[Materials]: Initialized"); } - + public void Close() { if (!m_enabled) return; } - + public void AddRegion(Scene scene) { if (!m_enabled) @@ -98,6 +103,56 @@ namespace OpenSim.Region.OptionalModules.Materials m_scene = scene; m_scene.EventManager.OnRegisterCaps += OnRegisterCaps; m_scene.EventManager.OnObjectAddedToScene += EventManager_OnObjectAddedToScene; + m_scene.EventManager.OnBackup += EventManager_OnBackup; + } + + private void EventManager_OnBackup(ISimulationDataService datastore, bool forcedBackup) + { + List toStore; + List hashlist; + + + lock (m_Materials) + { + if(m_changes.Count == 0) + return; + + if(forcedBackup) + { + toStore = new List(m_changes.Values); + m_changes.Clear(); + m_changesTime.Clear(); + } + else + { + toStore = new List(); + hashlist = new List(); + double storetime = Util.GetTimeStampMS() - 60000; + foreach(KeyValuePair kvp in m_changesTime) + { + if(kvp.Value < storetime) + { + toStore.Add(m_changes[kvp.Key]); + hashlist.Add(kvp.Key); + } + } + foreach(ulong u in hashlist) + { + m_changesTime.Remove(u); + m_changes.Remove(u); + } + } + + if(toStore.Count > 0) + Util.FireAndForget(delegate + { + foreach(AssetBase a in toStore) + { + a.Local = false; + m_scene.AssetService.Store(a); + } + }); + } } private void EventManager_OnObjectAddedToScene(SceneObjectGroup obj) @@ -111,7 +166,7 @@ namespace OpenSim.Region.OptionalModules.Materials { string capsBase = "/CAPS/" + caps.CapsObjectPath; - IRequestHandler renderMaterialsPostHandler + IRequestHandler renderMaterialsPostHandler = new RestStreamHandler("POST", capsBase + "/", (request, path, param, httpRequest, httpResponse) => RenderMaterialsPostCap(request, agentID), @@ -122,7 +177,7 @@ namespace OpenSim.Region.OptionalModules.Materials // and POST handlers, (at least at the time this was originally written), so we first set up a POST // handler normally and then add a GET handler via MainServer - IRequestHandler renderMaterialsGetHandler + IRequestHandler renderMaterialsGetHandler = new RestStreamHandler("GET", capsBase + "/", (request, path, param, httpRequest, httpResponse) => RenderMaterialsGetCap(request), @@ -130,14 +185,14 @@ namespace OpenSim.Region.OptionalModules.Materials MainServer.Instance.AddStreamHandler(renderMaterialsGetHandler); // materials viewer seems to use either POST or PUT, so assign POST handler for PUT as well - IRequestHandler renderMaterialsPutHandler + IRequestHandler renderMaterialsPutHandler = new RestStreamHandler("PUT", capsBase + "/", (request, path, param, httpRequest, httpResponse) - => RenderMaterialsPostCap(request, agentID), + => RenderMaterialsPutCap(request, agentID), "RenderMaterials", null); MainServer.Instance.AddStreamHandler(renderMaterialsPutHandler); } - + public void RemoveRegion(Scene scene) { if (!m_enabled) @@ -145,12 +200,14 @@ namespace OpenSim.Region.OptionalModules.Materials m_scene.EventManager.OnRegisterCaps -= OnRegisterCaps; m_scene.EventManager.OnObjectAddedToScene -= EventManager_OnObjectAddedToScene; - } - + m_scene.EventManager.OnBackup -= EventManager_OnBackup; + } + public void RegionLoaded(Scene scene) { if (!m_enabled) return; + m_cache = scene.RequestModuleInterface(); ISimulatorFeaturesModule featuresModule = scene.RequestModuleInterface(); if (featuresModule != null) featuresModule.OnSimulatorFeaturesRequest += OnSimulatorFeaturesRequest; @@ -203,8 +260,17 @@ namespace OpenSim.Region.OptionalModules.Materials { try { - lock (m_regionMaterials) - m_regionMaterials[matMap["ID"].AsUUID()] = (OSDMap)matMap["Material"]; + lock (m_Materials) + { + UUID id = matMap["ID"].AsUUID(); + if(m_Materials.ContainsKey(id)) + m_MaterialsRefCount[id]++; + else + { + m_Materials[id] = (OSDMap)matMap["Material"]; + m_MaterialsRefCount[id] = 1; + } + } } catch (Exception e) { @@ -219,7 +285,7 @@ namespace OpenSim.Region.OptionalModules.Materials /// Find the materials used in the SOP, and add them to 'm_regionMaterials'. /// private void GetStoredMaterialsInPart(SceneObjectPart part) - { + { if (part.Shape == null) return; @@ -233,7 +299,7 @@ namespace OpenSim.Region.OptionalModules.Materials GetStoredMaterialInFace(part, te.DefaultTexture); else m_log.WarnFormat( - "[Materials]: Default texture for part {0} (part of object {1}) in {2} unexpectedly null. Ignoring.", + "[Materials]: Default texture for part {0} (part of object {1}) in {2} unexpectedly null. Ignoring.", part.Name, part.ParentGroup.Name, m_scene.Name); foreach (Primitive.TextureEntryFace face in te.FaceTextures) @@ -252,18 +318,22 @@ namespace OpenSim.Region.OptionalModules.Materials if (id == UUID.Zero) return; - lock (m_regionMaterials) + lock (m_Materials) { - if (m_regionMaterials.ContainsKey(id)) + if (m_Materials.ContainsKey(id)) + { + m_MaterialsRefCount[id]++; return; - - byte[] data = m_scene.AssetService.GetData(id.ToString()); - if (data == null) + } + + AssetBase matAsset = m_scene.AssetService.Get(id.ToString()); + if (matAsset == null || matAsset.Data == null || matAsset.Data.Length == 0 ) { - m_log.WarnFormat("[Materials]: Prim \"{0}\" ({1}) contains unknown material ID {2}", part.Name, part.UUID, id); + //m_log.WarnFormat("[Materials]: Prim \"{0}\" ({1}) contains unknown material ID {2}", part.Name, part.UUID, id); return; } + byte[] data = matAsset.Data; OSDMap mat; try { @@ -275,7 +345,8 @@ namespace OpenSim.Region.OptionalModules.Materials return; } - m_regionMaterials[id] = mat; + m_Materials[id] = mat; + m_MaterialsRefCount[id] = 1; } } @@ -284,8 +355,6 @@ namespace OpenSim.Region.OptionalModules.Materials OSDMap req = (OSDMap)OSDParser.DeserializeLLSDXml(request); OSDMap resp = new OSDMap(); - OSDMap materialsFromViewer = null; - OSDArray respArr = new OSDArray(); if (req.ContainsKey("Zipped")) @@ -294,154 +363,224 @@ namespace OpenSim.Region.OptionalModules.Materials byte[] inBytes = req["Zipped"].AsBinary(); - try + try { osd = ZDecompressBytesToOsd(inBytes); - if (osd != null) + if (osd != null && osd is OSDArray) { - if (osd is OSDArray) // assume array of MaterialIDs designating requested material entries + foreach (OSD elem in (OSDArray)osd) { - foreach (OSD elem in (OSDArray)osd) + try { - try - { - UUID id = new UUID(elem.AsBinary(), 0); + UUID id = new UUID(elem.AsBinary(), 0); - lock (m_regionMaterials) + lock (m_Materials) + { + if (m_Materials.ContainsKey(id)) { - if (m_regionMaterials.ContainsKey(id)) - { - OSDMap matMap = new OSDMap(); - matMap["ID"] = OSD.FromBinary(id.GetBytes()); - matMap["Material"] = m_regionMaterials[id]; - respArr.Add(matMap); - } - else - { - m_log.Warn("[Materials]: request for unknown material ID: " + id.ToString()); + OSDMap matMap = new OSDMap(); + matMap["ID"] = OSD.FromBinary(id.GetBytes()); + matMap["Material"] = m_Materials[id]; + respArr.Add(matMap); + } + else + { + m_log.Warn("[Materials]: request for unknown material ID: " + id.ToString()); - // Theoretically we could try to load the material from the assets service, - // but that shouldn't be necessary because the viewer should only request - // materials that exist in a prim on the region, and all of these materials - // are already stored in m_regionMaterials. - } + // Theoretically we could try to load the material from the assets service, + // but that shouldn't be necessary because the viewer should only request + // materials that exist in a prim on the region, and all of these materials + // are already stored in m_regionMaterials. } } - catch (Exception e) - { - m_log.Error("Error getting materials in response to viewer request", e); - continue; - } + } + catch (Exception e) + { + m_log.Error("Error getting materials in response to viewer request", e); + continue; } } - else if (osd is OSDMap) // request to assign a material - { - materialsFromViewer = osd as OSDMap; + } + } + catch (Exception e) + { + m_log.Warn("[Materials]: exception decoding zipped CAP payload ", e); + //return ""; + } + } + + resp["Zipped"] = ZCompressOSD(respArr, false); + string response = OSDParser.SerializeLLSDXmlString(resp); + + //m_log.Debug("[Materials]: cap request: " + request); + //m_log.Debug("[Materials]: cap request (zipped portion): " + ZippedOsdBytesToString(req["Zipped"].AsBinary())); + //m_log.Debug("[Materials]: cap response: " + response); + return response; + } + + public string RenderMaterialsPutCap(string request, UUID agentID) + { + OSDMap req = (OSDMap)OSDParser.DeserializeLLSDXml(request); + OSDMap resp = new OSDMap(); + + OSDMap materialsFromViewer = null; + + OSDArray respArr = new OSDArray(); + + HashSet parts = new HashSet(); + if (req.ContainsKey("Zipped")) + { + OSD osd = null; + + byte[] inBytes = req["Zipped"].AsBinary(); - if (materialsFromViewer.ContainsKey("FullMaterialsPerFace")) + try + { + osd = ZDecompressBytesToOsd(inBytes); + + if (osd != null && osd is OSDMap) + { + materialsFromViewer = osd as OSDMap; + + if (materialsFromViewer.ContainsKey("FullMaterialsPerFace")) + { + OSD matsOsd = materialsFromViewer["FullMaterialsPerFace"]; + if (matsOsd is OSDArray) { - OSD matsOsd = materialsFromViewer["FullMaterialsPerFace"]; - if (matsOsd is OSDArray) - { - OSDArray matsArr = matsOsd as OSDArray; + OSDArray matsArr = matsOsd as OSDArray; - try + try + { + foreach (OSDMap matsMap in matsArr) { - foreach (OSDMap matsMap in matsArr) - { - uint primLocalID = 0; - try { - primLocalID = matsMap["ID"].AsUInteger(); - } - catch (Exception e) { - m_log.Warn("[Materials]: cannot decode \"ID\" from matsMap: " + e.Message); - continue; - } + uint primLocalID = 0; + try { + primLocalID = matsMap["ID"].AsUInteger(); + } + catch (Exception e) { + m_log.Warn("[Materials]: cannot decode \"ID\" from matsMap: " + e.Message); + continue; + } - OSDMap mat = null; - try - { - mat = matsMap["Material"] as OSDMap; - } - catch (Exception e) - { - m_log.Warn("[Materials]: cannot decode \"Material\" from matsMap: " + e.Message); - continue; - } + SceneObjectPart sop = m_scene.GetSceneObjectPart(primLocalID); + if (sop == null) + { + m_log.WarnFormat("[Materials]: SOP not found for localId: {0}", primLocalID.ToString()); + continue; + } - SceneObjectPart sop = m_scene.GetSceneObjectPart(primLocalID); - if (sop == null) - { - m_log.WarnFormat("[Materials]: SOP not found for localId: {0}", primLocalID.ToString()); - continue; - } + if (!m_scene.Permissions.CanEditObject(sop.UUID, agentID)) + { + m_log.WarnFormat("User {0} can't edit object {1} {2}", agentID, sop.Name, sop.UUID); + continue; + } - if (!m_scene.Permissions.CanEditObject(sop.UUID, agentID)) - { - m_log.WarnFormat("User {0} can't edit object {1} {2}", agentID, sop.Name, sop.UUID); - continue; - } + OSDMap mat = null; + try + { + mat = matsMap["Material"] as OSDMap; + } + catch (Exception e) + { + m_log.Warn("[Materials]: cannot decode \"Material\" from matsMap: " + e.Message); + continue; + } - Primitive.TextureEntry te = new Primitive.TextureEntry(sop.Shape.TextureEntry, 0, sop.Shape.TextureEntry.Length); - if (te == null) - { - m_log.WarnFormat("[Materials]: Error in TextureEntry for SOP {0} {1}", sop.Name, sop.UUID); - continue; - } + Primitive.TextureEntry te = new Primitive.TextureEntry(sop.Shape.TextureEntry, 0, sop.Shape.TextureEntry.Length); + if (te == null) + { + m_log.WarnFormat("[Materials]: Error in TextureEntry for SOP {0} {1}", sop.Name, sop.UUID); + continue; + } + UUID id; + if (mat == null) + { + // This happens then the user removes a material from a prim + id = UUID.Zero; + } + else + { + id = getNewID(mat); + } - UUID id; - if (mat == null) - { - // This happens then the user removes a material from a prim - id = UUID.Zero; - } + int face = -1; + UUID oldid = UUID.Zero; + if (matsMap.ContainsKey("Face")) + { + face = matsMap["Face"].AsInteger(); + Primitive.TextureEntryFace faceEntry = te.CreateFace((uint)face); + oldid = faceEntry.MaterialID; + faceEntry.MaterialID = id; + } + else + { + if (te.DefaultTexture == null) + m_log.WarnFormat("[Materials]: TextureEntry.DefaultTexture is null in {0} {1}", sop.Name, sop.UUID); else { - id = StoreMaterialAsAsset(agentID, mat, sop); + oldid = te.DefaultTexture.MaterialID; + te.DefaultTexture.MaterialID = id; } + } + //m_log.DebugFormat("[Materials]: in \"{0}\" {1}, setting material ID for face {2} to {3}", sop.Name, sop.UUID, face, id); - int face = -1; + // We can't use sop.UpdateTextureEntry(te) because it filters, so do it manually + sop.Shape.TextureEntry = te.GetBytes(); - if (matsMap.ContainsKey("Face")) - { - face = matsMap["Face"].AsInteger(); - Primitive.TextureEntryFace faceEntry = te.CreateFace((uint)face); - faceEntry.MaterialID = id; - } - else + lock(m_Materials) + { + if(oldid != UUID.Zero && m_MaterialsRefCount.ContainsKey(oldid)) { - if (te.DefaultTexture == null) - m_log.WarnFormat("[Materials]: TextureEntry.DefaultTexture is null in {0} {1}", sop.Name, sop.UUID); - else - te.DefaultTexture.MaterialID = id; + m_MaterialsRefCount[oldid]--; + if(m_MaterialsRefCount[oldid] <= 0) + { + m_Materials.Remove(oldid); + m_MaterialsRefCount.Remove(oldid); + m_cache.Expire(oldid.ToString()); + } } - //m_log.DebugFormat("[Materials]: in \"{0}\" {1}, setting material ID for face {2} to {3}", sop.Name, sop.UUID, face, id); - - // We can't use sop.UpdateTextureEntry(te) because it filters, so do it manually - sop.Shape.TextureEntry = te.GetBytes(); - - if (sop.ParentGroup != null) + if(id != UUID.Zero) { - sop.TriggerScriptChangedEvent(Changed.TEXTURE); - sop.UpdateFlag = UpdateRequired.FULL; - sop.ParentGroup.HasGroupChanged = true; - sop.ScheduleFullUpdate(); + AssetBase asset = CacheMaterialAsAsset(id, agentID, mat, sop); + if(asset != null) + { + ulong materialHash = (ulong)primLocalID << 32; + if(face < 0) + materialHash += 0xffffffff; + else + materialHash +=(ulong)face; + + m_changes[materialHash] = asset; + m_changesTime[materialHash] = Util.GetTimeStampMS(); + } } } + + if(!parts.Contains(sop)) + parts.Add(sop); } - catch (Exception e) + + foreach(SceneObjectPart sop in parts) { - m_log.Warn("[Materials]: exception processing received material ", e); + if (sop.ParentGroup != null && !sop.ParentGroup.IsDeleted) + { + sop.TriggerScriptChangedEvent(Changed.TEXTURE); + sop.ScheduleFullUpdate(); + sop.ParentGroup.HasGroupChanged = true; + } } } + catch (Exception e) + { + m_log.Warn("[Materials]: exception processing received material ", e); + } } } } - } catch (Exception e) { @@ -450,7 +589,6 @@ namespace OpenSim.Region.OptionalModules.Materials } } - resp["Zipped"] = ZCompressOSD(respArr, false); string response = OSDParser.SerializeLLSDXmlString(resp); @@ -460,6 +598,40 @@ namespace OpenSim.Region.OptionalModules.Materials return response; } + private UUID getNewID(OSDMap mat) + { + // ugly and done twice but keep compatibility for now + Byte[] data = System.Text.Encoding.ASCII.GetBytes(OSDParser.SerializeLLSDXmlString(mat)); + using (var md5 = MD5.Create()) + return new UUID(md5.ComputeHash(data), 0); + } + + private AssetBase CacheMaterialAsAsset(UUID id, UUID agentID, OSDMap mat, SceneObjectPart sop) + { + AssetBase asset = null; + lock (m_Materials) + { + if (!m_Materials.ContainsKey(id)) + { + m_Materials[id] = mat; + m_MaterialsRefCount[id] = 1; + + byte[] data = System.Text.Encoding.ASCII.GetBytes(OSDParser.SerializeLLSDXmlString(mat)); + + // This asset might exist already, but it's ok to try to store it again + string name = "Material " + ChooseMaterialName(mat, sop); + name = name.Substring(0, Math.Min(64, name.Length)).Trim(); + asset = new AssetBase(id, name, (sbyte)OpenSimAssetType.Material, agentID.ToString()); + asset.Data = data; + asset.Local = true; + m_cache.Cache(asset); + } + else + m_MaterialsRefCount[id]++; + } + return asset; + } + private UUID StoreMaterialAsAsset(UUID agentID, OSDMap mat, SceneObjectPart sop) { UUID id; @@ -469,11 +641,12 @@ namespace OpenSim.Region.OptionalModules.Materials using (var md5 = MD5.Create()) id = new UUID(md5.ComputeHash(data), 0); - lock (m_regionMaterials) + lock (m_Materials) { - if (!m_regionMaterials.ContainsKey(id)) + if (!m_Materials.ContainsKey(id)) { - m_regionMaterials[id] = mat; + m_Materials[id] = mat; + m_MaterialsRefCount[id] = 1; // This asset might exist already, but it's ok to try to store it again string name = "Material " + ChooseMaterialName(mat, sop); @@ -482,6 +655,8 @@ namespace OpenSim.Region.OptionalModules.Materials asset.Data = data; m_scene.AssetService.Store(asset); } + else + m_MaterialsRefCount[id]++; } return id; } @@ -509,7 +684,7 @@ namespace OpenSim.Region.OptionalModules.Materials if (sop.Name != "Primitive") return sop.Name; - + if ((sop.ParentGroup != null) && (sop.ParentGroup.Name != "Primitive")) return sop.ParentGroup.Name; @@ -523,9 +698,9 @@ namespace OpenSim.Region.OptionalModules.Materials int matsCount = 0; OSDArray allOsd = new OSDArray(); - lock (m_regionMaterials) + lock (m_Materials) { - foreach (KeyValuePair kvp in m_regionMaterials) + foreach (KeyValuePair kvp in m_Materials) { OSDMap matMap = new OSDMap(); @@ -573,7 +748,7 @@ namespace OpenSim.Region.OptionalModules.Materials using (MemoryStream msSinkCompressed = new MemoryStream()) { - using (Ionic.Zlib.ZlibStream zOut = new Ionic.Zlib.ZlibStream(msSinkCompressed, + using (Ionic.Zlib.ZlibStream zOut = new Ionic.Zlib.ZlibStream(msSinkCompressed, Ionic.Zlib.CompressionMode.Compress, CompressionLevel.BestCompression, true)) { zOut.Write(data, 0, data.Length); diff --git a/OpenSim/Region/OptionalModules/PhysicsParameters/PhysicsParameters.cs b/OpenSim/Region/OptionalModules/PhysicsParameters/PhysicsParameters.cs old mode 100644 new mode 100755 index 1d9179c..bcfb34d --- a/OpenSim/Region/OptionalModules/PhysicsParameters/PhysicsParameters.cs +++ b/OpenSim/Region/OptionalModules/PhysicsParameters/PhysicsParameters.cs @@ -54,10 +54,10 @@ namespace OpenSim.Region.OptionalModules.PhysicsParameters private static bool m_commandsLoaded = false; #region ISharedRegionModule - public string Name { get { return "Runtime Physics Parameter Module"; } } - + public string Name { get { return "Runtime Physics Parameter Module"; } } + public Type ReplaceableInterface { get { return null; } } - + public void Initialise(IConfigSource source) { // m_log.DebugFormat("{0}: INITIALIZED MODULE", LogHeader); @@ -68,29 +68,29 @@ namespace OpenSim.Region.OptionalModules.PhysicsParameters // m_log.DebugFormat("[{0}: POST INITIALIZED MODULE", LogHeader); InstallInterfaces(); } - + public void Close() { // m_log.DebugFormat("{0}: CLOSED MODULE", LogHeader); } - + public void AddRegion(Scene scene) { // m_log.DebugFormat("{0}: REGION {1} ADDED", LogHeader, scene.RegionInfo.RegionName); m_scenes.Add(scene); } - + public void RemoveRegion(Scene scene) { // m_log.DebugFormat("{0}: REGION {1} REMOVED", LogHeader, scene.RegionInfo.RegionName); if (m_scenes.Contains(scene)) m_scenes.Remove(scene); - } - + } + public void RegionLoaded(Scene scene) { // m_log.DebugFormat("{0}: REGION {1} LOADED", LogHeader, scene.RegionInfo.RegionName); - } + } #endregion INonSharedRegionModule private const string getInvocation = "physics get [|ALL]"; diff --git a/OpenSim/Region/OptionalModules/PrimLimitsModule/PrimLimitsModule.cs b/OpenSim/Region/OptionalModules/PrimLimitsModule/PrimLimitsModule.cs index 395bbf1..61b6d68 100644 --- a/OpenSim/Region/OptionalModules/PrimLimitsModule/PrimLimitsModule.cs +++ b/OpenSim/Region/OptionalModules/PrimLimitsModule/PrimLimitsModule.cs @@ -52,14 +52,15 @@ namespace OpenSim.Region.OptionalModules private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private bool m_enabled; - public string Name { get { return "PrimLimitsModule"; } } - + private Scene m_scene; + public string Name { get { return "PrimLimitsModule"; } } + public Type ReplaceableInterface { get { return null; } } - + public void Initialise(IConfigSource config) { string permissionModules = Util.GetConfigVarFromSections(config, "permissionmodules", - new string[] { "Startup", "Permissions" }, "DefaultPermissionsModule"); + new string[] { "Startup", "Permissions" }, "DefaultPermissionsModule"); List modules = new List(permissionModules.Split(',').Select(m => m.Trim())); @@ -69,46 +70,47 @@ namespace OpenSim.Region.OptionalModules m_log.DebugFormat("[PRIM LIMITS]: Initialized module"); m_enabled = true; } - + public void Close() { } - + public void AddRegion(Scene scene) { if (!m_enabled) - { return; - } + + m_scene = scene; scene.Permissions.OnRezObject += CanRezObject; scene.Permissions.OnObjectEntry += CanObjectEnter; + scene.Permissions.OnObjectEnterWithScripts += CanObjectEnterWithScripts; scene.Permissions.OnDuplicateObject += CanDuplicateObject; m_log.DebugFormat("[PRIM LIMITS]: Region {0} added", scene.RegionInfo.RegionName); } - + public void RemoveRegion(Scene scene) { - if (m_enabled) - { + if (!m_enabled) return; - } - scene.Permissions.OnRezObject -= CanRezObject; - scene.Permissions.OnObjectEntry -= CanObjectEnter; - scene.Permissions.OnDuplicateObject -= CanDuplicateObject; - } - + m_scene.Permissions.OnRezObject -= CanRezObject; + m_scene.Permissions.OnObjectEntry -= CanObjectEnter; + scene.Permissions.OnObjectEnterWithScripts -= CanObjectEnterWithScripts; + m_scene.Permissions.OnDuplicateObject -= CanDuplicateObject; + } + public void RegionLoaded(Scene scene) { m_dialogModule = scene.RequestModuleInterface(); } - private bool CanRezObject(int objectCount, UUID ownerID, Vector3 objectPosition, Scene scene) + private bool CanRezObject(int objectCount, UUID ownerID, Vector3 objectPosition) { - ILandObject lo = scene.LandChannel.GetLandObject(objectPosition.X, objectPosition.Y); + + ILandObject lo = m_scene.LandChannel.GetLandObject(objectPosition.X, objectPosition.Y); - string response = DoCommonChecks(objectCount, ownerID, lo, scene); + string response = DoCommonChecks(objectCount, ownerID, lo); if (response != null) { @@ -119,78 +121,99 @@ namespace OpenSim.Region.OptionalModules } //OnDuplicateObject - private bool CanDuplicateObject(int objectCount, UUID objectID, UUID ownerID, Scene scene, Vector3 objectPosition) + private bool CanDuplicateObject(SceneObjectGroup sog, ScenePresence sp) { - ILandObject lo = scene.LandChannel.GetLandObject(objectPosition.X, objectPosition.Y); + Vector3 objectPosition = sog.AbsolutePosition; + ILandObject lo = m_scene.LandChannel.GetLandObject(objectPosition.X, objectPosition.Y); - string response = DoCommonChecks(objectCount, ownerID, lo, scene); + string response = DoCommonChecks(sog.PrimCount, sp.UUID, lo); if (response != null) { - m_dialogModule.SendAlertToUser(ownerID, response); + m_dialogModule.SendAlertToUser(sp.UUID, response); return false; } return true; } - private bool CanObjectEnter(UUID objectID, bool enteringRegion, Vector3 newPoint, Scene scene) + private bool CanObjectEnter(SceneObjectGroup sog, bool enteringRegion, Vector3 newPoint) { - SceneObjectPart obj = scene.GetSceneObjectPart(objectID); - Vector3 oldPoint = obj.GroupPosition; - int objectCount = obj.ParentGroup.PrimCount; - ILandObject oldParcel = scene.LandChannel.GetLandObject(oldPoint.X, oldPoint.Y); - ILandObject newParcel = scene.LandChannel.GetLandObject(newPoint.X, newPoint.Y); - - // newParcel will be null only if it outside of our current region. If this is the case, then the - // receiving permissions will perform the check. - if (newParcel == null) + float newX = newPoint.X; + float newY = newPoint.Y; + if (newX < -1.0f || newX > (m_scene.RegionInfo.RegionSizeX + 1.0f) || + newY < -1.0f || newY > (m_scene.RegionInfo.RegionSizeY + 1.0f) ) return true; - // The prim hasn't crossed a region boundary so we don't need to worry - // about prim counts here - if(oldParcel.Equals(newParcel)) - { + if (sog == null) + return false; + + ILandObject newParcel = m_scene.LandChannel.GetLandObject(newX, newY); + + if (newParcel == null) return true; - } - // Prim counts are determined by the location of the root prim. if we're - // moving a child prim, just let it pass - if(!obj.IsRoot) + if(!enteringRegion) { - return true; + Vector3 oldPoint = sog.AbsolutePosition; + ILandObject oldParcel = m_scene.LandChannel.GetLandObject(oldPoint.X, oldPoint.Y); + if(oldParcel != null && oldParcel.Equals(newParcel)) + return true; } + int objectCount = sog.PrimCount; + // TODO: Add Special Case here for temporary prims - string response = DoCommonChecks(objectCount, obj.OwnerID, newParcel, scene); + string response = DoCommonChecks(objectCount, sog.OwnerID, newParcel); if (response != null) { - m_dialogModule.SendAlertToUser(obj.OwnerID, response); + if(m_dialogModule != null) + m_dialogModule.SendAlertToUser(sog.OwnerID, response); return false; } return true; } - private string DoCommonChecks(int objectCount, UUID ownerID, ILandObject lo, Scene scene) + private bool CanObjectEnterWithScripts(SceneObjectGroup sog, ILandObject newParcel) + { + if (sog == null) + return false; + + if (newParcel == null) + return true; + + int objectCount = sog.PrimCount; + + // TODO: Add Special Case here for temporary prims + + string response = DoCommonChecks(objectCount, sog.OwnerID, newParcel); + + if (response != null) + return false; + + return true; + } + + private string DoCommonChecks(int objectCount, UUID ownerID, ILandObject lo) { string response = null; - int simulatorCapacity = lo.GetSimulatorMaxPrimCount(); - if ((objectCount + lo.PrimCounts.Total) > simulatorCapacity) + int OwnedParcelsCapacity = lo.GetSimulatorMaxPrimCount(); + if ((objectCount + lo.PrimCounts.Total) > OwnedParcelsCapacity) { - response = "Unable to rez object because the parcel is too full"; + response = "Unable to rez object because the parcel is full"; } else { - int maxPrimsPerUser = scene.RegionInfo.MaxPrimsPerUser; + int maxPrimsPerUser = m_scene.RegionInfo.MaxPrimsPerUser; if (maxPrimsPerUser >= 0) { // per-user prim limit is set if (ownerID != lo.LandData.OwnerID || lo.LandData.IsGroupOwned) { // caller is not the sole Parcel owner - EstateSettings estateSettings = scene.RegionInfo.EstateSettings; + EstateSettings estateSettings = m_scene.RegionInfo.EstateSettings; if (ownerID != estateSettings.EstateOwner) { // caller is NOT the Estate owner diff --git a/OpenSim/Region/OptionalModules/Properties/AssemblyInfo.cs b/OpenSim/Region/OptionalModules/Properties/AssemblyInfo.cs index dc6ca6f..cbfd2d2 100644 --- a/OpenSim/Region/OptionalModules/Properties/AssemblyInfo.cs +++ b/OpenSim/Region/OptionalModules/Properties/AssemblyInfo.cs @@ -3,7 +3,7 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Mono.Addins; -// General Information about an assembly is controlled through the following +// General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("OpenSim.Region.OptionalModules")] @@ -15,8 +15,8 @@ using Mono.Addins; [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] @@ -26,11 +26,11 @@ using Mono.Addins; // Version information for an assembly consists of the following four values: // // Major Version -// Minor Version +// Minor Version // Build Number // Revision // -[assembly: AssemblyVersion("0.8.3.*")] +[assembly: AssemblyVersion(OpenSim.VersionInfo.AssemblyVersionNumber)] [assembly: Addin("OpenSim.Region.OptionalModules", OpenSim.VersionInfo.VersionNumber)] diff --git a/OpenSim/Region/OptionalModules/RegionCombinerModule/RegionCombinerClientEventForwarder.cs b/OpenSim/Region/OptionalModules/RegionCombinerModule/RegionCombinerClientEventForwarder.cs deleted file mode 100644 index 721d396..0000000 --- a/OpenSim/Region/OptionalModules/RegionCombinerModule/RegionCombinerClientEventForwarder.cs +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using OpenMetaverse; -using OpenSim.Region.Framework.Scenes; - -namespace OpenSim.Region.RegionCombinerModule -{ -public class RegionCombinerClientEventForwarder - { - private Scene m_rootScene; - private Dictionary m_virtScene = new Dictionary(); - private Dictionary m_forwarders = new Dictionary(); - - public RegionCombinerClientEventForwarder(RegionConnections rootScene) - { - m_rootScene = rootScene.RegionScene; - } - - public void AddSceneToEventForwarding(Scene virtualScene) - { - lock (m_virtScene) - { - if (m_virtScene.ContainsKey(virtualScene.RegionInfo.originRegionID)) - { - m_virtScene[virtualScene.RegionInfo.originRegionID] = virtualScene; - } - else - { - m_virtScene.Add(virtualScene.RegionInfo.originRegionID, virtualScene); - } - } - - lock (m_forwarders) - { - // TODO: Fix this to unregister if this happens - if (m_forwarders.ContainsKey(virtualScene.RegionInfo.originRegionID)) - m_forwarders.Remove(virtualScene.RegionInfo.originRegionID); - - RegionCombinerIndividualEventForwarder forwarder = - new RegionCombinerIndividualEventForwarder(m_rootScene, virtualScene); - m_forwarders.Add(virtualScene.RegionInfo.originRegionID, forwarder); - - virtualScene.EventManager.OnNewClient += forwarder.ClientConnect; - virtualScene.EventManager.OnClientClosed += forwarder.ClientClosed; - } - } - - public void RemoveSceneFromEventForwarding (Scene virtualScene) - { - lock (m_forwarders) - { - RegionCombinerIndividualEventForwarder forwarder = m_forwarders[virtualScene.RegionInfo.originRegionID]; - virtualScene.EventManager.OnNewClient -= forwarder.ClientConnect; - virtualScene.EventManager.OnClientClosed -= forwarder.ClientClosed; - m_forwarders.Remove(virtualScene.RegionInfo.originRegionID); - } - lock (m_virtScene) - { - if (m_virtScene.ContainsKey(virtualScene.RegionInfo.originRegionID)) - { - m_virtScene.Remove(virtualScene.RegionInfo.originRegionID); - } - } - } - } -} \ No newline at end of file diff --git a/OpenSim/Region/OptionalModules/RegionCombinerModule/RegionCombinerIndividualEventForwarder.cs b/OpenSim/Region/OptionalModules/RegionCombinerModule/RegionCombinerIndividualEventForwarder.cs deleted file mode 100644 index 83732e2..0000000 --- a/OpenSim/Region/OptionalModules/RegionCombinerModule/RegionCombinerIndividualEventForwarder.cs +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using OpenMetaverse; -using OpenSim.Framework; -using OpenSim.Region.CoreModules.Avatar.Attachments; -using OpenSim.Region.CoreModules.Avatar.Gods; -using OpenSim.Region.Framework.Interfaces; -using OpenSim.Region.Framework.Scenes; - -namespace OpenSim.Region.RegionCombinerModule -{ - public class RegionCombinerIndividualEventForwarder - { - private Scene m_rootScene; - private Scene m_virtScene; - - public RegionCombinerIndividualEventForwarder(Scene rootScene, Scene virtScene) - { - m_rootScene = rootScene; - m_virtScene = virtScene; - } - - public void ClientConnect(IClientAPI client) - { - m_virtScene.UnSubscribeToClientPrimEvents(client); - m_virtScene.UnSubscribeToClientPrimRezEvents(client); - m_virtScene.UnSubscribeToClientInventoryEvents(client); - if(m_virtScene.AttachmentsModule != null) - ((AttachmentsModule)m_virtScene.AttachmentsModule).UnsubscribeFromClientEvents(client); - //m_virtScene.UnSubscribeToClientTeleportEvents(client); - m_virtScene.UnSubscribeToClientScriptEvents(client); - - IGodsModule virtGodsModule = m_virtScene.RequestModuleInterface(); - if (virtGodsModule != null) - ((GodsModule)virtGodsModule).UnsubscribeFromClientEvents(client); - - m_virtScene.UnSubscribeToClientNetworkEvents(client); - - m_rootScene.SubscribeToClientPrimEvents(client); - client.OnAddPrim += LocalAddNewPrim; - client.OnRezObject += LocalRezObject; - - m_rootScene.SubscribeToClientInventoryEvents(client); - if (m_rootScene.AttachmentsModule != null) - ((AttachmentsModule)m_rootScene.AttachmentsModule).SubscribeToClientEvents(client); - //m_rootScene.SubscribeToClientTeleportEvents(client); - m_rootScene.SubscribeToClientScriptEvents(client); - - IGodsModule rootGodsModule = m_virtScene.RequestModuleInterface(); - if (rootGodsModule != null) - ((GodsModule)rootGodsModule).UnsubscribeFromClientEvents(client); - - m_rootScene.SubscribeToClientNetworkEvents(client); - } - - public void ClientClosed(UUID clientid, Scene scene) - { - } - - /// - /// Fixes position based on the region the Rez event came in on - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - private void LocalRezObject(IClientAPI remoteclient, UUID itemid, Vector3 rayend, Vector3 raystart, - UUID raytargetid, byte bypassraycast, bool rayendisintersection, bool rezselected, bool removeitem, - UUID fromtaskid) - { - int differenceX = (int)m_virtScene.RegionInfo.RegionLocX - (int)m_rootScene.RegionInfo.RegionLocX; - int differenceY = (int)m_virtScene.RegionInfo.RegionLocY - (int)m_rootScene.RegionInfo.RegionLocY; - rayend.X += differenceX * (int)Constants.RegionSize; - rayend.Y += differenceY * (int)Constants.RegionSize; - raystart.X += differenceX * (int)Constants.RegionSize; - raystart.Y += differenceY * (int)Constants.RegionSize; - - m_rootScene.RezObject(remoteclient, itemid, rayend, raystart, raytargetid, bypassraycast, - rayendisintersection, rezselected, removeitem, fromtaskid); - } - /// - /// Fixes position based on the region the AddPrimShape event came in on - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - private void LocalAddNewPrim(UUID ownerid, UUID groupid, Vector3 rayend, Quaternion rot, - PrimitiveBaseShape shape, byte bypassraycast, Vector3 raystart, UUID raytargetid, - byte rayendisintersection) - { - int differenceX = (int)m_virtScene.RegionInfo.RegionLocX - (int)m_rootScene.RegionInfo.RegionLocX; - int differenceY = (int)m_virtScene.RegionInfo.RegionLocY - (int)m_rootScene.RegionInfo.RegionLocY; - rayend.X += differenceX * (int)Constants.RegionSize; - rayend.Y += differenceY * (int)Constants.RegionSize; - raystart.X += differenceX * (int)Constants.RegionSize; - raystart.Y += differenceY * (int)Constants.RegionSize; - m_rootScene.AddNewPrim(ownerid, groupid, rayend, rot, shape, bypassraycast, raystart, raytargetid, - rayendisintersection); - } - } -} \ No newline at end of file diff --git a/OpenSim/Region/OptionalModules/RegionCombinerModule/RegionCombinerLargeLandChannel.cs b/OpenSim/Region/OptionalModules/RegionCombinerModule/RegionCombinerLargeLandChannel.cs deleted file mode 100644 index 4bf2a82..0000000 --- a/OpenSim/Region/OptionalModules/RegionCombinerModule/RegionCombinerLargeLandChannel.cs +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using System.Reflection; -using log4net; -using OpenMetaverse; -using OpenSim.Framework; -using OpenSim.Region.Framework.Interfaces; -using OpenSim.Region.CoreModules.World.Land; - -namespace OpenSim.Region.RegionCombinerModule -{ - public class RegionCombinerLargeLandChannel : ILandChannel - { -// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private RegionData RegData; - private ILandChannel RootRegionLandChannel; - private readonly List RegionConnections; - - #region ILandChannel Members - - public RegionCombinerLargeLandChannel(RegionData regData, ILandChannel rootRegionLandChannel, - List regionConnections) - { - RegData = regData; - RootRegionLandChannel = rootRegionLandChannel; - RegionConnections = regionConnections; - } - - public List ParcelsNearPoint(Vector3 position) - { - //m_log.DebugFormat("[LANDPARCELNEARPOINT]: {0}>", position); - return RootRegionLandChannel.ParcelsNearPoint(position - RegData.Offset); - } - - public List AllParcels() - { - return RootRegionLandChannel.AllParcels(); - } - - public void Clear(bool setupDefaultParcel) - { - RootRegionLandChannel.Clear(setupDefaultParcel); - } - - public ILandObject GetLandObject(Vector3 position) - { - return GetLandObject(position.X, position.Y); - } - - public ILandObject GetLandObject(int x, int y) - { - return GetLandObject((float)x, (float)y); - -// m_log.DebugFormat("[BIGLANDTESTINT]: <{0},{1}>", x, y); -// -// if (x > 0 && x <= (int)Constants.RegionSize && y > 0 && y <= (int)Constants.RegionSize) -// { -// return RootRegionLandChannel.GetLandObject(x, y); -// } -// else -// { -// int offsetX = (x / (int)Constants.RegionSize); -// int offsetY = (y / (int)Constants.RegionSize); -// offsetX *= (int)Constants.RegionSize; -// offsetY *= (int)Constants.RegionSize; -// -// foreach (RegionData regionData in RegionConnections) -// { -// if (regionData.Offset.X == offsetX && regionData.Offset.Y == offsetY) -// { -// m_log.DebugFormat( -// "[REGION COMBINER LARGE LAND CHANNEL]: Found region {0} at offset {1},{2}", -// regionData.RegionScene.Name, offsetX, offsetY); -// -// return regionData.RegionScene.LandChannel.GetLandObject(x - offsetX, y - offsetY); -// } -// } -// //ILandObject obj = new LandObject(UUID.Zero, false, RegData.RegionScene); -// //obj.LandData.Name = "NO LAND"; -// //return obj; -// } -// -// m_log.DebugFormat("[REGION COMBINER LARGE LAND CHANNEL]: No region found at {0},{1}, returning null", x, y); -// -// return null; - } - - public ILandObject GetLandObject(int localID) - { - // XXX: Possibly should be looking in every land channel, not just the root. - return RootRegionLandChannel.GetLandObject(localID); - } - - public ILandObject GetLandObject(float x, float y) - { -// m_log.DebugFormat("[BIGLANDTESTFLOAT]: <{0},{1}>", x, y); - - if (x > 0 && x <= (int)Constants.RegionSize && y > 0 && y <= (int)Constants.RegionSize) - { - return RootRegionLandChannel.GetLandObject(x, y); - } - else - { - int offsetX = (int)(x/(int) Constants.RegionSize); - int offsetY = (int)(y/(int) Constants.RegionSize); - offsetX *= (int) Constants.RegionSize; - offsetY *= (int) Constants.RegionSize; - - foreach (RegionData regionData in RegionConnections) - { - if (regionData.Offset.X == offsetX && regionData.Offset.Y == offsetY) - { -// m_log.DebugFormat( -// "[REGION COMBINER LARGE LAND CHANNEL]: Found region {0} at offset {1},{2}", -// regionData.RegionScene.Name, offsetX, offsetY); - - return regionData.RegionScene.LandChannel.GetLandObject(x - offsetX, y - offsetY); - } - } - -// ILandObject obj = new LandObject(UUID.Zero, false, RegData.RegionScene); -// obj.LandData.Name = "NO LAND"; -// return obj; - } - -// m_log.DebugFormat("[REGION COMBINER LARGE LAND CHANNEL]: No region found at {0},{1}, returning null", x, y); - - return null; - } - - public bool IsForcefulBansAllowed() - { - return RootRegionLandChannel.IsForcefulBansAllowed(); - } - - public void UpdateLandObject(int localID, LandData data) - { - RootRegionLandChannel.UpdateLandObject(localID, data); - } - - public void Join(int start_x, int start_y, int end_x, int end_y, UUID attempting_user_id) - { - RootRegionLandChannel.Join(start_x, start_y, end_x, end_y, attempting_user_id); - } - - public void Subdivide(int start_x, int start_y, int end_x, int end_y, UUID attempting_user_id) - { - RootRegionLandChannel.Subdivide(start_x, start_y, end_x, end_y, attempting_user_id); - } - - public void ReturnObjectsInParcel(int localID, uint returnType, UUID[] agentIDs, UUID[] taskIDs, IClientAPI remoteClient) - { - RootRegionLandChannel.ReturnObjectsInParcel(localID, returnType, agentIDs, taskIDs, remoteClient); - } - - public void setParcelObjectMaxOverride(overrideParcelMaxPrimCountDelegate overrideDel) - { - RootRegionLandChannel.setParcelObjectMaxOverride(overrideDel); - } - - public void setSimulatorObjectMaxOverride(overrideSimulatorMaxPrimCountDelegate overrideDel) - { - RootRegionLandChannel.setSimulatorObjectMaxOverride(overrideDel); - } - - public void SetParcelOtherCleanTime(IClientAPI remoteClient, int localID, int otherCleanTime) - { - RootRegionLandChannel.SetParcelOtherCleanTime(remoteClient, localID, otherCleanTime); - } - - #endregion - } -} \ No newline at end of file diff --git a/OpenSim/Region/OptionalModules/RegionCombinerModule/RegionCombinerModule.cs b/OpenSim/Region/OptionalModules/RegionCombinerModule/RegionCombinerModule.cs deleted file mode 100644 index 32eead0..0000000 --- a/OpenSim/Region/OptionalModules/RegionCombinerModule/RegionCombinerModule.cs +++ /dev/null @@ -1,880 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using System.Reflection; -using log4net; -using Nini.Config; -using OpenMetaverse; -using OpenSim.Framework; -using OpenSim.Framework.Client; -using OpenSim.Region.Framework.Interfaces; -using OpenSim.Region.Framework.Scenes; -using OpenSim.Framework.Console; -using OpenSim.Region.PhysicsModules.SharedBase; -using Mono.Addins; - -namespace OpenSim.Region.RegionCombinerModule -{ - [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "RegionCombinerModule")] - public class RegionCombinerModule : ISharedRegionModule, IRegionCombinerModule - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); -// private static string LogHeader = "[REGION COMBINER MODULE]"; - - public string Name - { - get { return "RegionCombinerModule"; } - } - - public Type ReplaceableInterface - { - get { return null; } - } - - /// - /// Is this module enabled? - /// - private bool m_combineContiguousRegions = false; - - /// - /// This holds the root regions for the megaregions. - /// - /// - /// Usually there is only ever one megaregion (and hence only one entry here). - /// - private Dictionary m_regions = new Dictionary(); - - /// - /// The scenes that comprise the megaregion. - /// - private Dictionary m_startingScenes = new Dictionary(); - - public void Initialise(IConfigSource source) - { - IConfig myConfig = source.Configs["Startup"]; - m_combineContiguousRegions = myConfig.GetBoolean("CombineContiguousRegions", false); - if (m_combineContiguousRegions) - m_log.ErrorFormat("[REGION COMBINER MODULE]: THIS MODULE IS BEING MARKED OBSOLETE AND MAY SOON BE REMOVED. PLEASE USE VARREGIONS INSTEAD."); - - MainConsole.Instance.Commands.AddCommand( - "RegionCombinerModule", false, "fix-phantoms", "fix-phantoms", - "Fixes phantom objects after an import to a megaregion or a change from a megaregion back to normal regions", - FixPhantoms); - } - - public void Close() - { - } - - public void AddRegion(Scene scene) - { - if (m_combineContiguousRegions) - scene.RegisterModuleInterface(this); - } - - public void RemoveRegion(Scene scene) - { - lock (m_startingScenes) - m_startingScenes.Remove(scene.RegionInfo.originRegionID); - } - - public void RegionLoaded(Scene scene) - { - lock (m_startingScenes) - m_startingScenes.Add(scene.RegionInfo.originRegionID, scene); - - if (m_combineContiguousRegions) - { - RegionLoadedDoWork(scene); - - scene.EventManager.OnNewPresence += NewPresence; - } - } - - public bool IsRootForMegaregion(UUID regionId) - { - lock (m_regions) - return m_regions.ContainsKey(regionId); - } - - public Vector2 GetSizeOfMegaregion(UUID regionId) - { - lock (m_regions) - { - if (m_regions.ContainsKey(regionId)) - { - RegionConnections rootConn = m_regions[regionId]; - - return new Vector2((float)rootConn.XEnd, (float)rootConn.YEnd); - } - } - - throw new Exception(string.Format("Region with id {0} not found", regionId)); - } - - // Test to see if this postiion (relative to the region) is within the area covered - // by this megaregion. - public bool PositionIsInMegaregion(UUID currentRegion, int xx, int yy) - { - bool ret = false; - if (xx < 0 || yy < 0) - return ret; - - foreach (RegionConnections rootRegion in m_regions.Values) - { - if (currentRegion == rootRegion.RegionId) - { - // The caller is in the root region so this is an easy test - if (xx < rootRegion.XEnd && yy < rootRegion.YEnd) - { - ret = true; - } - break; - } - else - { - // Maybe the caller is in one of the sub-regions - foreach (RegionData childRegion in rootRegion.ConnectedRegions) - { - if (currentRegion == childRegion.RegionId) - { - // This is a child. Diddle the offsets and check if in - Vector3 positionInMegaregion = childRegion.Offset; - positionInMegaregion.X += xx; - positionInMegaregion.Y += yy; - if (positionInMegaregion.X < rootRegion.XEnd && positionInMegaregion.Y < rootRegion.YEnd) - { - ret = true; - } - break; - } - } - } - } - - return ret; - } - - private void NewPresence(ScenePresence presence) - { - if (presence.IsChildAgent) - { - byte[] throttleData; - - try - { - throttleData = presence.ControllingClient.GetThrottlesPacked(1); - } - catch (NotImplementedException) - { - return; - } - - if (throttleData == null) - return; - - if (throttleData.Length == 0) - return; - - if (throttleData.Length != 28) - return; - - byte[] adjData; - int pos = 0; - - if (!BitConverter.IsLittleEndian) - { - byte[] newData = new byte[7 * 4]; - Buffer.BlockCopy(throttleData, 0, newData, 0, 7 * 4); - - for (int i = 0; i < 7; i++) - Array.Reverse(newData, i * 4, 4); - - adjData = newData; - } - else - { - adjData = throttleData; - } - - // 0.125f converts from bits to bytes - int resend = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); pos += 4; - int land = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); pos += 4; - int wind = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); pos += 4; - int cloud = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); pos += 4; - int task = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); pos += 4; - int texture = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); pos += 4; - int asset = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); - // State is a subcategory of task that we allocate a percentage to - - - //int total = resend + land + wind + cloud + task + texture + asset; - - byte[] data = new byte[7 * 4]; - int ii = 0; - - Buffer.BlockCopy(Utils.FloatToBytes(resend), 0, data, ii, 4); ii += 4; - Buffer.BlockCopy(Utils.FloatToBytes(land * 50), 0, data, ii, 4); ii += 4; - Buffer.BlockCopy(Utils.FloatToBytes(wind), 0, data, ii, 4); ii += 4; - Buffer.BlockCopy(Utils.FloatToBytes(cloud), 0, data, ii, 4); ii += 4; - Buffer.BlockCopy(Utils.FloatToBytes(task), 0, data, ii, 4); ii += 4; - Buffer.BlockCopy(Utils.FloatToBytes(texture), 0, data, ii, 4); ii += 4; - Buffer.BlockCopy(Utils.FloatToBytes(asset), 0, data, ii, 4); - - try - { - presence.ControllingClient.SetChildAgentThrottle(data); - } - catch (NotImplementedException) - { - return; - } - } - } - - private void RegionLoadedDoWork(Scene scene) - { -/* - // For testing on a single instance - if (scene.RegionInfo.RegionLocX == 1004 && scene.RegionInfo.RegionLocY == 1000) - return; - // -*/ - - RegionConnections newConn = new RegionConnections(); - newConn.ConnectedRegions = new List(); - newConn.RegionScene = scene; - newConn.RegionLandChannel = scene.LandChannel; - newConn.RegionId = scene.RegionInfo.originRegionID; - newConn.X = scene.RegionInfo.RegionLocX; - newConn.Y = scene.RegionInfo.RegionLocY; - newConn.XEnd = scene.RegionInfo.RegionSizeX; - newConn.YEnd = scene.RegionInfo.RegionSizeX; - - lock (m_regions) - { - bool connectedYN = false; - - foreach (RegionConnections rootConn in m_regions.Values) - { - #region commented - /* - // If we're one region over +x +y - //xxy - //xxx - //xxx - if ((((int)conn.X * (int)Constants.RegionSize) + conn.XEnd - == (regionConnections.X * (int)Constants.RegionSize)) - && (((int)conn.Y * (int)Constants.RegionSize) - conn.YEnd - == (regionConnections.Y * (int)Constants.RegionSize))) - { - Vector3 offset = Vector3.Zero; - offset.X = (((regionConnections.X * (int) Constants.RegionSize)) - - ((conn.X * (int) Constants.RegionSize))); - offset.Y = (((regionConnections.Y * (int) Constants.RegionSize)) - - ((conn.Y * (int) Constants.RegionSize))); - - Vector3 extents = Vector3.Zero; - extents.Y = regionConnections.YEnd + conn.YEnd; - extents.X = conn.XEnd + conn.XEnd; - - m_log.DebugFormat("Scene: {0} to the northwest of Scene{1}. Offset: {2}. Extents:{3}", - conn.RegionScene.RegionInfo.RegionName, - regionConnections.RegionScene.RegionInfo.RegionName, - offset, extents); - - scene.PhysicsScene.Combine(conn.RegionScene.PhysicsScene, offset, extents); - - connectedYN = true; - break; - } - */ - - /* - //If we're one region over x +y - //xxx - //xxx - //xyx - if ((((int)conn.X * (int)Constants.RegionSize) - == (regionConnections.X * (int)Constants.RegionSize)) - && (((int)conn.Y * (int)Constants.RegionSize) - conn.YEnd - == (regionConnections.Y * (int)Constants.RegionSize))) - { - Vector3 offset = Vector3.Zero; - offset.X = (((regionConnections.X * (int)Constants.RegionSize)) - - ((conn.X * (int)Constants.RegionSize))); - offset.Y = (((regionConnections.Y * (int)Constants.RegionSize)) - - ((conn.Y * (int)Constants.RegionSize))); - - Vector3 extents = Vector3.Zero; - extents.Y = regionConnections.YEnd + conn.YEnd; - extents.X = conn.XEnd; - - m_log.DebugFormat("Scene: {0} to the north of Scene{1}. Offset: {2}. Extents:{3}", - conn.RegionScene.RegionInfo.RegionName, - regionConnections.RegionScene.RegionInfo.RegionName, offset, extents); - - scene.PhysicsScene.Combine(conn.RegionScene.PhysicsScene, offset, extents); - connectedYN = true; - break; - } - */ - - /* - // If we're one region over -x +y - //xxx - //xxx - //yxx - if ((((int)conn.X * (int)Constants.RegionSize) - conn.XEnd - == (regionConnections.X * (int)Constants.RegionSize)) - && (((int)conn.Y * (int)Constants.RegionSize) - conn.YEnd - == (regionConnections.Y * (int)Constants.RegionSize))) - { - Vector3 offset = Vector3.Zero; - offset.X = (((regionConnections.X * (int)Constants.RegionSize)) - - ((conn.X * (int)Constants.RegionSize))); - offset.Y = (((regionConnections.Y * (int)Constants.RegionSize)) - - ((conn.Y * (int)Constants.RegionSize))); - - Vector3 extents = Vector3.Zero; - extents.Y = regionConnections.YEnd + conn.YEnd; - extents.X = conn.XEnd + conn.XEnd; - - m_log.DebugFormat("Scene: {0} to the northeast of Scene. Offset: {2}. Extents:{3}", - conn.RegionScene.RegionInfo.RegionName, - regionConnections.RegionScene.RegionInfo.RegionName, offset, extents); - - scene.PhysicsScene.Combine(conn.RegionScene.PhysicsScene, offset, extents); - - - connectedYN = true; - break; - } - */ - - /* - // If we're one region over -x y - //xxx - //yxx - //xxx - if ((((int)conn.X * (int)Constants.RegionSize) - conn.XEnd - == (regionConnections.X * (int)Constants.RegionSize)) - && (((int)conn.Y * (int)Constants.RegionSize) - == (regionConnections.Y * (int)Constants.RegionSize))) - { - Vector3 offset = Vector3.Zero; - offset.X = (((regionConnections.X * (int)Constants.RegionSize)) - - ((conn.X * (int)Constants.RegionSize))); - offset.Y = (((regionConnections.Y * (int)Constants.RegionSize)) - - ((conn.Y * (int)Constants.RegionSize))); - - Vector3 extents = Vector3.Zero; - extents.Y = regionConnections.YEnd; - extents.X = conn.XEnd + conn.XEnd; - - m_log.DebugFormat("Scene: {0} to the east of Scene{1} Offset: {2}. Extents:{3}", - conn.RegionScene.RegionInfo.RegionName, - regionConnections.RegionScene.RegionInfo.RegionName, offset, extents); - - scene.PhysicsScene.Combine(conn.RegionScene.PhysicsScene, offset, extents); - - connectedYN = true; - break; - } - */ - - /* - // If we're one region over -x -y - //yxx - //xxx - //xxx - if ((((int)conn.X * (int)Constants.RegionSize) - conn.XEnd - == (regionConnections.X * (int)Constants.RegionSize)) - && (((int)conn.Y * (int)Constants.RegionSize) + conn.YEnd - == (regionConnections.Y * (int)Constants.RegionSize))) - { - Vector3 offset = Vector3.Zero; - offset.X = (((regionConnections.X * (int)Constants.RegionSize)) - - ((conn.X * (int)Constants.RegionSize))); - offset.Y = (((regionConnections.Y * (int)Constants.RegionSize)) - - ((conn.Y * (int)Constants.RegionSize))); - - Vector3 extents = Vector3.Zero; - extents.Y = regionConnections.YEnd + conn.YEnd; - extents.X = conn.XEnd + conn.XEnd; - - m_log.DebugFormat("Scene: {0} to the northeast of Scene{1} Offset: {2}. Extents:{3}", - conn.RegionScene.RegionInfo.RegionName, - regionConnections.RegionScene.RegionInfo.RegionName, offset, extents); - - scene.PhysicsScene.Combine(conn.RegionScene.PhysicsScene, offset, extents); - - connectedYN = true; - break; - } - */ - #endregion - - - // Check to see if this new region is adjacent to the root region. - // Note that we expect the regions to be combined from the root region outward - // thus the requirement for the ordering in the configuration files. - - // If we're one region over +x y (i.e. root region is to the west) - //xxx - //xxy - //xxx - if (rootConn.PosX + rootConn.XEnd >= newConn.PosX && rootConn.PosY >= newConn.PosY) - { - connectedYN = DoWorkForOneRegionOverPlusXY(rootConn, newConn, scene); - break; - } - - // If we're one region over x +y (i.e. root region is to the south) - //xyx - //xxx - //xxx - if (rootConn.PosX >= newConn.PosX && rootConn.PosY + rootConn.YEnd >= newConn.PosY) - { - connectedYN = DoWorkForOneRegionOverPlusXY(rootConn, newConn, scene); - break; - } - - // If we're one region over +x +y (i.e. root region is to the south-west) - //xxy - //xxx - //xxx - if (rootConn.PosX + rootConn.XEnd >= newConn.PosX && rootConn.PosY + rootConn.YEnd >= newConn.PosY) - { - connectedYN = DoWorkForOneRegionOverPlusXY(rootConn, newConn, scene); - break; - } - } - - // If !connectYN means that this region is a root region - if (!connectedYN) - { - DoWorkForRootRegion(newConn, scene); - } - } - } - - private bool DoWorkForOneRegionOverPlusXY(RegionConnections rootConn, RegionConnections newConn, Scene scene) - { - // Offset (in meters) from the base of this region to the base of the root region. - Vector3 offset = Vector3.Zero; - offset.X = newConn.PosX - rootConn.PosX; - offset.Y = newConn.PosY - rootConn.PosY; - - // The new total size of the region (in meters) - // We just extend the X and Y dimensions so the extent might temporarily include areas without regions. - Vector3 extents = Vector3.Zero; - extents.X = Math.Max(rootConn.XEnd, offset.X + newConn.RegionScene.RegionInfo.RegionSizeX); - extents.Y = Math.Max(rootConn.YEnd, offset.Y + newConn.RegionScene.RegionInfo.RegionSizeY); - - rootConn.UpdateExtents(extents); - - m_log.DebugFormat( - "[REGION COMBINER MODULE]: Root region {0} is to the west of region {1}, Offset: {2}, Extents: {3}", - rootConn.RegionScene.RegionInfo.RegionName, - newConn.RegionScene.RegionInfo.RegionName, offset, extents); - - RegionData ConnectedRegion = new RegionData(); - ConnectedRegion.Offset = offset; - ConnectedRegion.RegionId = scene.RegionInfo.originRegionID; - ConnectedRegion.RegionScene = scene; - rootConn.ConnectedRegions.Add(ConnectedRegion); - - // Inform root region Physics about the extents of this region - rootConn.RegionScene.PhysicsScene.Combine(null, Vector3.Zero, extents); - - // Inform Child region that it needs to forward it's terrain to the root region - scene.PhysicsScene.Combine(rootConn.RegionScene.PhysicsScene, offset, Vector3.Zero); - - // Reset Terrain.. since terrain loads before we get here, we need to load - // it again so it loads in the root region - scene.PhysicsScene.SetTerrain(scene.Heightmap.GetFloatsSerialised()); - - // Create a client event forwarder and add this region's events to the root region. - if (rootConn.ClientEventForwarder != null) - rootConn.ClientEventForwarder.AddSceneToEventForwarding(scene); - - return true; - } - - /* - * 20140215 radams1: The border stuff was removed and the addition of regions to the mega-regions - * was generalized. These functions are not needed for the generalized solution but left for reference. - private bool DoWorkForOneRegionOverXPlusY(RegionConnections rootConn, RegionConnections newConn, Scene scene) - { - Vector3 offset = Vector3.Zero; - offset.X = newConn.PosX - rootConn.PosX; - offset.Y = newConn.PosY - rootConn.PosY; - - Vector3 extents = Vector3.Zero; - extents.Y = newConn.YEnd + rootConn.YEnd; - extents.X = rootConn.XEnd; - rootConn.UpdateExtents(extents); - - RegionData ConnectedRegion = new RegionData(); - ConnectedRegion.Offset = offset; - ConnectedRegion.RegionId = scene.RegionInfo.originRegionID; - ConnectedRegion.RegionScene = scene; - rootConn.ConnectedRegions.Add(ConnectedRegion); - - m_log.DebugFormat( - "[REGION COMBINER MODULE]: Root region {0} is to the south of region {1}, Offset: {2}, Extents: {3}", - rootConn.RegionScene.RegionInfo.RegionName, - newConn.RegionScene.RegionInfo.RegionName, offset, extents); - - rootConn.RegionScene.PhysicsScene.Combine(null, Vector3.Zero, extents); - scene.PhysicsScene.Combine(rootConn.RegionScene.PhysicsScene, offset, Vector3.Zero); - - // Reset Terrain.. since terrain normally loads first. - //conn.RegionScene.PhysicsScene.SetTerrain(conn.RegionScene.Heightmap.GetFloatsSerialised()); - scene.PhysicsScene.SetTerrain(scene.Heightmap.GetFloatsSerialised()); - //conn.RegionScene.PhysicsScene.SetTerrain(conn.RegionScene.Heightmap.GetFloatsSerialised()); - - if (rootConn.ClientEventForwarder != null) - rootConn.ClientEventForwarder.AddSceneToEventForwarding(scene); - - return true; - } - - private bool DoWorkForOneRegionOverPlusXPlusY(RegionConnections rootConn, RegionConnections newConn, Scene scene) - { - Vector3 offset = Vector3.Zero; - offset.X = newConn.PosX - rootConn.PosX; - offset.Y = newConn.PosY - rootConn.PosY; - - Vector3 extents = Vector3.Zero; - - // We do not want to inflate the extents for regions strictly to the NE of the root region, since this - // would double count regions strictly to the north and east that have already been added. -// extents.Y = regionConnections.YEnd + conn.YEnd; -// extents.X = regionConnections.XEnd + conn.XEnd; -// conn.UpdateExtents(extents); - - extents.Y = rootConn.YEnd; - extents.X = rootConn.XEnd; - - RegionData ConnectedRegion = new RegionData(); - ConnectedRegion.Offset = offset; - ConnectedRegion.RegionId = scene.RegionInfo.originRegionID; - ConnectedRegion.RegionScene = scene; - - rootConn.ConnectedRegions.Add(ConnectedRegion); - - m_log.DebugFormat( - "[REGION COMBINER MODULE]: Region {0} is to the southwest of Scene {1}, Offset: {2}, Extents: {3}", - rootConn.RegionScene.RegionInfo.RegionName, - newConn.RegionScene.RegionInfo.RegionName, offset, extents); - - rootConn.RegionScene.PhysicsScene.Combine(null, Vector3.Zero, extents); - scene.PhysicsScene.Combine(rootConn.RegionScene.PhysicsScene, offset, Vector3.Zero); - - // Reset Terrain.. since terrain normally loads first. - //conn.RegionScene.PhysicsScene.SetTerrain(conn.RegionScene.Heightmap.GetFloatsSerialised()); - scene.PhysicsScene.SetTerrain(scene.Heightmap.GetFloatsSerialised()); - //conn.RegionScene.PhysicsScene.SetTerrain(conn.RegionScene.Heightmap.GetFloatsSerialised()); - - if (rootConn.ClientEventForwarder != null) - rootConn.ClientEventForwarder.AddSceneToEventForwarding(scene); - - return true; - - //scene.PhysicsScene.Combine(conn.RegionScene.PhysicsScene, offset,extents); - } - */ - - private void DoWorkForRootRegion(RegionConnections rootConn, Scene scene) - { - m_log.DebugFormat("[REGION COMBINER MODULE]: Adding root region {0}", scene.RegionInfo.RegionName); - - RegionData rdata = new RegionData(); - rdata.Offset = Vector3.Zero; - rdata.RegionId = scene.RegionInfo.originRegionID; - rdata.RegionScene = scene; - // save it's land channel - rootConn.RegionLandChannel = scene.LandChannel; - - // Substitue our landchannel - RegionCombinerLargeLandChannel lnd = new RegionCombinerLargeLandChannel(rdata, scene.LandChannel, - rootConn.ConnectedRegions); - - scene.LandChannel = lnd; - - // Forward the permissions modules of each of the connected regions to the root region - lock (m_regions) - { - foreach (RegionData r in rootConn.ConnectedRegions) - { - ForwardPermissionRequests(rootConn, r.RegionScene); - } - - // Create the root region's Client Event Forwarder - rootConn.ClientEventForwarder = new RegionCombinerClientEventForwarder(rootConn); - - // Sets up the CoarseLocationUpdate forwarder for this root region - scene.EventManager.OnNewPresence += SetCoarseLocationDelegate; - - // Adds this root region to a dictionary of regions that are connectable - m_regions.Add(scene.RegionInfo.originRegionID, rootConn); - } - } - - private void SetCoarseLocationDelegate(ScenePresence presence) - { - presence.SetSendCoarseLocationMethod(SendCoarseLocationUpdates); - } - - // This delegate was refactored for non-combined regions. - // This combined region version will not use the pre-compiled lists of locations and ids - private void SendCoarseLocationUpdates(UUID sceneId, ScenePresence presence, List coarseLocations, List avatarUUIDs) - { - RegionConnections connectiondata = null; - lock (m_regions) - { - if (m_regions.ContainsKey(sceneId)) - connectiondata = m_regions[sceneId]; - else - return; - } - - List CoarseLocations = new List(); - List AvatarUUIDs = new List(); - - connectiondata.RegionScene.ForEachRootScenePresence(delegate(ScenePresence sp) - { - if (sp.UUID != presence.UUID) - { - CoarseLocations.Add(sp.AbsolutePosition); - AvatarUUIDs.Add(sp.UUID); - } - }); - - DistributeCoarseLocationUpdates(CoarseLocations, AvatarUUIDs, connectiondata, presence); - } - - private void DistributeCoarseLocationUpdates(List locations, List uuids, - RegionConnections connectiondata, ScenePresence rootPresence) - { - RegionData[] rdata = connectiondata.ConnectedRegions.ToArray(); - //List clients = new List(); - Dictionary updates = new Dictionary(); - - // Root Region entry - RegionCoarseLocationStruct rootupdatedata = new RegionCoarseLocationStruct(); - rootupdatedata.Locations = new List(); - rootupdatedata.Uuids = new List(); - rootupdatedata.Offset = Vector2.Zero; - - rootupdatedata.UserAPI = rootPresence.ControllingClient; - - if (rootupdatedata.UserAPI != null) - updates.Add(Vector2.Zero, rootupdatedata); - - //Each Region needs an entry or we will end up with dead minimap dots - foreach (RegionData regiondata in rdata) - { - Vector2 offset = new Vector2(regiondata.Offset.X, regiondata.Offset.Y); - RegionCoarseLocationStruct updatedata = new RegionCoarseLocationStruct(); - updatedata.Locations = new List(); - updatedata.Uuids = new List(); - updatedata.Offset = offset; - - if (offset == Vector2.Zero) - updatedata.UserAPI = rootPresence.ControllingClient; - else - updatedata.UserAPI = LocateUsersChildAgentIClientAPI(offset, rootPresence.UUID, rdata); - - if (updatedata.UserAPI != null) - updates.Add(offset, updatedata); - } - - // go over the locations and assign them to an IClientAPI - for (int i = 0; i < locations.Count; i++) - //{locations[i]/(int) Constants.RegionSize; - { - Vector3 pPosition = new Vector3((int)locations[i].X / (int)Constants.RegionSize, - (int)locations[i].Y / (int)Constants.RegionSize, locations[i].Z); - Vector2 offset = new Vector2(pPosition.X*(int) Constants.RegionSize, - pPosition.Y*(int) Constants.RegionSize); - - if (!updates.ContainsKey(offset)) - { - // This shouldn't happen - RegionCoarseLocationStruct updatedata = new RegionCoarseLocationStruct(); - updatedata.Locations = new List(); - updatedata.Uuids = new List(); - updatedata.Offset = offset; - - if (offset == Vector2.Zero) - updatedata.UserAPI = rootPresence.ControllingClient; - else - updatedata.UserAPI = LocateUsersChildAgentIClientAPI(offset, rootPresence.UUID, rdata); - - updates.Add(offset,updatedata); - } - - updates[offset].Locations.Add(locations[i]); - updates[offset].Uuids.Add(uuids[i]); - } - - // Send out the CoarseLocationupdates from their respective client connection based on where the avatar is - foreach (Vector2 offset in updates.Keys) - { - if (updates[offset].UserAPI != null) - { - updates[offset].UserAPI.SendCoarseLocationUpdate(updates[offset].Uuids,updates[offset].Locations); - } - } - } - - /// - /// Locates a the Client of a particular region in an Array of RegionData based on offset - /// - /// - /// - /// - /// IClientAPI or null - private IClientAPI LocateUsersChildAgentIClientAPI(Vector2 offset, UUID uUID, RegionData[] rdata) - { - IClientAPI returnclient = null; - foreach (RegionData r in rdata) - { - if (r.Offset.X == offset.X && r.Offset.Y == offset.Y) - { - return r.RegionScene.SceneGraph.GetControllingClient(uUID); - } - } - - return returnclient; - } - - public void PostInitialise() - { - } - -// /// -// /// TODO: -// /// -// /// -// public void UnCombineRegion(RegionData rdata) -// { -// lock (m_regions) -// { -// if (m_regions.ContainsKey(rdata.RegionId)) -// { -// // uncombine root region and virtual regions -// } -// else -// { -// foreach (RegionConnections r in m_regions.Values) -// { -// foreach (RegionData rd in r.ConnectedRegions) -// { -// if (rd.RegionId == rdata.RegionId) -// { -// // uncombine virtual region -// } -// } -// } -// } -// } -// } - - public void ForwardPermissionRequests(RegionConnections BigRegion, Scene VirtualRegion) - { - if (BigRegion.PermissionModule == null) - BigRegion.PermissionModule = new RegionCombinerPermissionModule(BigRegion.RegionScene); - - VirtualRegion.Permissions.OnBypassPermissions += BigRegion.PermissionModule.BypassPermissions; - VirtualRegion.Permissions.OnSetBypassPermissions += BigRegion.PermissionModule.SetBypassPermissions; - VirtualRegion.Permissions.OnPropagatePermissions += BigRegion.PermissionModule.PropagatePermissions; - VirtualRegion.Permissions.OnGenerateClientFlags += BigRegion.PermissionModule.GenerateClientFlags; - VirtualRegion.Permissions.OnAbandonParcel += BigRegion.PermissionModule.CanAbandonParcel; - VirtualRegion.Permissions.OnReclaimParcel += BigRegion.PermissionModule.CanReclaimParcel; - VirtualRegion.Permissions.OnDeedParcel += BigRegion.PermissionModule.CanDeedParcel; - VirtualRegion.Permissions.OnDeedObject += BigRegion.PermissionModule.CanDeedObject; - VirtualRegion.Permissions.OnIsGod += BigRegion.PermissionModule.IsGod; - VirtualRegion.Permissions.OnDuplicateObject += BigRegion.PermissionModule.CanDuplicateObject; - VirtualRegion.Permissions.OnDeleteObject += BigRegion.PermissionModule.CanDeleteObject; //MAYBE FULLY IMPLEMENTED - VirtualRegion.Permissions.OnEditObject += BigRegion.PermissionModule.CanEditObject; //MAYBE FULLY IMPLEMENTED - VirtualRegion.Permissions.OnEditParcelProperties += BigRegion.PermissionModule.CanEditParcelProperties; //MAYBE FULLY IMPLEMENTED - VirtualRegion.Permissions.OnInstantMessage += BigRegion.PermissionModule.CanInstantMessage; - VirtualRegion.Permissions.OnInventoryTransfer += BigRegion.PermissionModule.CanInventoryTransfer; //NOT YET IMPLEMENTED - VirtualRegion.Permissions.OnIssueEstateCommand += BigRegion.PermissionModule.CanIssueEstateCommand; //FULLY IMPLEMENTED - VirtualRegion.Permissions.OnMoveObject += BigRegion.PermissionModule.CanMoveObject; //MAYBE FULLY IMPLEMENTED - VirtualRegion.Permissions.OnObjectEntry += BigRegion.PermissionModule.CanObjectEntry; - VirtualRegion.Permissions.OnReturnObjects += BigRegion.PermissionModule.CanReturnObjects; //NOT YET IMPLEMENTED - VirtualRegion.Permissions.OnRezObject += BigRegion.PermissionModule.CanRezObject; //MAYBE FULLY IMPLEMENTED - VirtualRegion.Permissions.OnRunConsoleCommand += BigRegion.PermissionModule.CanRunConsoleCommand; - VirtualRegion.Permissions.OnRunScript += BigRegion.PermissionModule.CanRunScript; //NOT YET IMPLEMENTED - VirtualRegion.Permissions.OnCompileScript += BigRegion.PermissionModule.CanCompileScript; - VirtualRegion.Permissions.OnSellParcel += BigRegion.PermissionModule.CanSellParcel; - VirtualRegion.Permissions.OnTakeObject += BigRegion.PermissionModule.CanTakeObject; - VirtualRegion.Permissions.OnTakeCopyObject += BigRegion.PermissionModule.CanTakeCopyObject; - VirtualRegion.Permissions.OnTerraformLand += BigRegion.PermissionModule.CanTerraformLand; - VirtualRegion.Permissions.OnLinkObject += BigRegion.PermissionModule.CanLinkObject; //NOT YET IMPLEMENTED - VirtualRegion.Permissions.OnDelinkObject += BigRegion.PermissionModule.CanDelinkObject; //NOT YET IMPLEMENTED - VirtualRegion.Permissions.OnBuyLand += BigRegion.PermissionModule.CanBuyLand; //NOT YET IMPLEMENTED - VirtualRegion.Permissions.OnViewNotecard += BigRegion.PermissionModule.CanViewNotecard; //NOT YET IMPLEMENTED - VirtualRegion.Permissions.OnViewScript += BigRegion.PermissionModule.CanViewScript; //NOT YET IMPLEMENTED - VirtualRegion.Permissions.OnEditNotecard += BigRegion.PermissionModule.CanEditNotecard; //NOT YET IMPLEMENTED - VirtualRegion.Permissions.OnEditScript += BigRegion.PermissionModule.CanEditScript; //NOT YET IMPLEMENTED - VirtualRegion.Permissions.OnCreateObjectInventory += BigRegion.PermissionModule.CanCreateObjectInventory; //NOT IMPLEMENTED HERE - VirtualRegion.Permissions.OnEditObjectInventory += BigRegion.PermissionModule.CanEditObjectInventory;//MAYBE FULLY IMPLEMENTED - VirtualRegion.Permissions.OnCopyObjectInventory += BigRegion.PermissionModule.CanCopyObjectInventory; //NOT YET IMPLEMENTED - VirtualRegion.Permissions.OnDeleteObjectInventory += BigRegion.PermissionModule.CanDeleteObjectInventory; //NOT YET IMPLEMENTED - VirtualRegion.Permissions.OnResetScript += BigRegion.PermissionModule.CanResetScript; - VirtualRegion.Permissions.OnCreateUserInventory += BigRegion.PermissionModule.CanCreateUserInventory; //NOT YET IMPLEMENTED - VirtualRegion.Permissions.OnCopyUserInventory += BigRegion.PermissionModule.CanCopyUserInventory; //NOT YET IMPLEMENTED - VirtualRegion.Permissions.OnEditUserInventory += BigRegion.PermissionModule.CanEditUserInventory; //NOT YET IMPLEMENTED - VirtualRegion.Permissions.OnDeleteUserInventory += BigRegion.PermissionModule.CanDeleteUserInventory; //NOT YET IMPLEMENTED - VirtualRegion.Permissions.OnTeleport += BigRegion.PermissionModule.CanTeleport; //NOT YET IMPLEMENTED - } - - #region console commands - - public void FixPhantoms(string module, string[] cmdparams) - { - List scenes = new List(m_startingScenes.Values); - - foreach (Scene s in scenes) - { - MainConsole.Instance.OutputFormat("Fixing phantoms for {0}", s.RegionInfo.RegionName); - - s.ForEachSOG(so => so.AbsolutePosition = so.AbsolutePosition); - } - } - - #endregion - } -} diff --git a/OpenSim/Region/OptionalModules/RegionCombinerModule/RegionCombinerPermissionModule.cs b/OpenSim/Region/OptionalModules/RegionCombinerModule/RegionCombinerPermissionModule.cs deleted file mode 100644 index 07dd68b..0000000 --- a/OpenSim/Region/OptionalModules/RegionCombinerModule/RegionCombinerPermissionModule.cs +++ /dev/null @@ -1,270 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using OpenMetaverse; -using OpenSim.Framework; -using OpenSim.Region.Framework.Interfaces; -using OpenSim.Region.Framework.Scenes; - -namespace OpenSim.Region.RegionCombinerModule -{ - public class RegionCombinerPermissionModule - { - private Scene m_rootScene; - - public RegionCombinerPermissionModule(Scene RootScene) - { - m_rootScene = RootScene; - } - - #region Permission Override - - public bool BypassPermissions() - { - return m_rootScene.Permissions.BypassPermissions(); - } - - public void SetBypassPermissions(bool value) - { - m_rootScene.Permissions.SetBypassPermissions(value); - } - - public bool PropagatePermissions() - { - return m_rootScene.Permissions.PropagatePermissions(); - } - - public uint GenerateClientFlags(UUID userid, UUID objectidid) - { - return m_rootScene.Permissions.GenerateClientFlags(userid,objectidid); - } - - public bool CanAbandonParcel(UUID user, ILandObject parcel, Scene scene) - { - return m_rootScene.Permissions.CanAbandonParcel(user,parcel); - } - - public bool CanReclaimParcel(UUID user, ILandObject parcel, Scene scene) - { - return m_rootScene.Permissions.CanReclaimParcel(user, parcel); - } - - public bool CanDeedParcel(UUID user, ILandObject parcel, Scene scene) - { - return m_rootScene.Permissions.CanDeedParcel(user, parcel); - } - - public bool CanDeedObject(UUID user, UUID @group, Scene scene) - { - return m_rootScene.Permissions.CanDeedObject(user,@group); - } - - public bool IsGod(UUID user, Scene requestfromscene) - { - return m_rootScene.Permissions.IsGod(user); - } - - public bool CanDuplicateObject(int objectcount, UUID objectid, UUID owner, Scene scene, Vector3 objectposition) - { - return m_rootScene.Permissions.CanDuplicateObject(objectcount, objectid, owner, objectposition); - } - - public bool CanDeleteObject(UUID objectid, UUID deleter, Scene scene) - { - return m_rootScene.Permissions.CanDeleteObject(objectid, deleter); - } - - public bool CanEditObject(UUID objectid, UUID editorid, Scene scene) - { - return m_rootScene.Permissions.CanEditObject(objectid, editorid); - } - - public bool CanEditParcelProperties(UUID user, ILandObject parcel, GroupPowers g, Scene scene) - { - return m_rootScene.Permissions.CanEditParcelProperties(user, parcel, g); - } - - public bool CanInstantMessage(UUID user, UUID target, Scene startscene) - { - return m_rootScene.Permissions.CanInstantMessage(user, target); - } - - public bool CanInventoryTransfer(UUID user, UUID target, Scene startscene) - { - return m_rootScene.Permissions.CanInventoryTransfer(user, target); - } - - public bool CanIssueEstateCommand(UUID user, Scene requestfromscene, bool ownercommand) - { - return m_rootScene.Permissions.CanIssueEstateCommand(user, ownercommand); - } - - public bool CanMoveObject(UUID objectid, UUID moverid, Scene scene) - { - return m_rootScene.Permissions.CanMoveObject(objectid, moverid); - } - - public bool CanObjectEntry(UUID objectid, bool enteringregion, Vector3 newpoint, Scene scene) - { - return m_rootScene.Permissions.CanObjectEntry(objectid, enteringregion, newpoint); - } - - public bool CanReturnObjects(ILandObject land, UUID user, List objects, Scene scene) - { - return m_rootScene.Permissions.CanReturnObjects(land, user, objects); - } - - public bool CanRezObject(int objectcount, UUID owner, Vector3 objectposition, Scene scene) - { - return m_rootScene.Permissions.CanRezObject(objectcount, owner, objectposition); - } - - public bool CanRunConsoleCommand(UUID user, Scene requestfromscene) - { - return m_rootScene.Permissions.CanRunConsoleCommand(user); - } - - public bool CanRunScript(UUID script, UUID objectid, UUID user, Scene scene) - { - return m_rootScene.Permissions.CanRunScript(script, objectid, user); - } - - public bool CanCompileScript(UUID owneruuid, int scripttype, Scene scene) - { - return m_rootScene.Permissions.CanCompileScript(owneruuid, scripttype); - } - - public bool CanSellParcel(UUID user, ILandObject parcel, Scene scene) - { - return m_rootScene.Permissions.CanSellParcel(user, parcel); - } - - public bool CanTakeObject(UUID objectid, UUID stealer, Scene scene) - { - return m_rootScene.Permissions.CanTakeObject(objectid, stealer); - } - - public bool CanTakeCopyObject(UUID objectid, UUID userid, Scene inscene) - { - return m_rootScene.Permissions.CanTakeObject(objectid, userid); - } - - public bool CanTerraformLand(UUID user, Vector3 position, Scene requestfromscene) - { - return m_rootScene.Permissions.CanTerraformLand(user, position); - } - - public bool CanLinkObject(UUID user, UUID objectid) - { - return m_rootScene.Permissions.CanLinkObject(user, objectid); - } - - public bool CanDelinkObject(UUID user, UUID objectid) - { - return m_rootScene.Permissions.CanDelinkObject(user, objectid); - } - - public bool CanBuyLand(UUID user, ILandObject parcel, Scene scene) - { - return m_rootScene.Permissions.CanBuyLand(user, parcel); - } - - public bool CanViewNotecard(UUID script, UUID objectid, UUID user, Scene scene) - { - return m_rootScene.Permissions.CanViewNotecard(script, objectid, user); - } - - public bool CanViewScript(UUID script, UUID objectid, UUID user, Scene scene) - { - return m_rootScene.Permissions.CanViewScript(script, objectid, user); - } - - public bool CanEditNotecard(UUID notecard, UUID objectid, UUID user, Scene scene) - { - return m_rootScene.Permissions.CanEditNotecard(notecard, objectid, user); - } - - public bool CanEditScript(UUID script, UUID objectid, UUID user, Scene scene) - { - return m_rootScene.Permissions.CanEditScript(script, objectid, user); - } - - public bool CanCreateObjectInventory(int invtype, UUID objectid, UUID userid) - { - return m_rootScene.Permissions.CanCreateObjectInventory(invtype, objectid, userid); - } - - public bool CanEditObjectInventory(UUID objectid, UUID editorid, Scene scene) - { - return m_rootScene.Permissions.CanEditObjectInventory(objectid, editorid); - } - - public bool CanCopyObjectInventory(UUID itemid, UUID objectid, UUID userid) - { - return m_rootScene.Permissions.CanCopyObjectInventory(itemid, objectid, userid); - } - - public bool CanDeleteObjectInventory(UUID itemid, UUID objectid, UUID userid) - { - return m_rootScene.Permissions.CanDeleteObjectInventory(itemid, objectid, userid); - } - - public bool CanResetScript(UUID prim, UUID script, UUID user, Scene scene) - { - return m_rootScene.Permissions.CanResetScript(prim, script, user); - } - - public bool CanCreateUserInventory(int invtype, UUID userid) - { - return m_rootScene.Permissions.CanCreateUserInventory(invtype, userid); - } - - public bool CanCopyUserInventory(UUID itemid, UUID userid) - { - return m_rootScene.Permissions.CanCopyUserInventory(itemid, userid); - } - - public bool CanEditUserInventory(UUID itemid, UUID userid) - { - return m_rootScene.Permissions.CanEditUserInventory(itemid, userid); - } - - public bool CanDeleteUserInventory(UUID itemid, UUID userid) - { - return m_rootScene.Permissions.CanDeleteUserInventory(itemid, userid); - } - - public bool CanTeleport(UUID userid, Scene scene) - { - return m_rootScene.Permissions.CanTeleport(userid); - } - - #endregion - } -} diff --git a/OpenSim/Region/OptionalModules/RegionCombinerModule/RegionConnections.cs b/OpenSim/Region/OptionalModules/RegionCombinerModule/RegionConnections.cs deleted file mode 100644 index 62a3a91..0000000 --- a/OpenSim/Region/OptionalModules/RegionCombinerModule/RegionConnections.cs +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using OpenMetaverse; -using OpenSim.Framework; -using OpenSim.Region.Framework.Interfaces; -using OpenSim.Region.Framework.Scenes; - -namespace OpenSim.Region.RegionCombinerModule -{ - public class RegionConnections - { - /// - /// Root Region ID - /// - public UUID RegionId; - - /// - /// Root Region Scene - /// - public Scene RegionScene; - - /// - /// LargeLandChannel for combined region - /// - public ILandChannel RegionLandChannel; - - /// - /// The x map co-ordinate for this region (where each co-ordinate is a Constants.RegionSize block). - /// - public uint X; - - /// - /// The y co-ordinate for this region (where each cor-odinate is a Constants.RegionSize block). - /// - public uint Y; - - /// - /// The X meters position of this connection. - /// - public uint PosX { get { return Util.RegionToWorldLoc(X); } } - - /// - /// The Y meters co-ordinate of this connection. - /// - public uint PosY { get { return Util.RegionToWorldLoc(Y); } } - - /// - /// The size of the megaregion in meters. - /// - public uint XEnd; - - /// - /// The size of the megaregion in meters. - /// - public uint YEnd; - - public List ConnectedRegions; - public RegionCombinerPermissionModule PermissionModule; - public RegionCombinerClientEventForwarder ClientEventForwarder; - - public void UpdateExtents(Vector3 extents) - { - XEnd = (uint)extents.X; - YEnd = (uint)extents.Y; - } - } -} \ No newline at end of file diff --git a/OpenSim/Region/OptionalModules/RegionCombinerModule/RegionCourseLocation.cs b/OpenSim/Region/OptionalModules/RegionCombinerModule/RegionCourseLocation.cs deleted file mode 100644 index 224ac99..0000000 --- a/OpenSim/Region/OptionalModules/RegionCombinerModule/RegionCourseLocation.cs +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using OpenMetaverse; -using OpenSim.Framework; - -namespace OpenSim.Region.RegionCombinerModule -{ - - struct RegionCoarseLocationStruct - { - public List Locations; - public List Uuids; - public IClientAPI UserAPI; - public Vector2 Offset; - } -} \ No newline at end of file diff --git a/OpenSim/Region/OptionalModules/RegionCombinerModule/RegionData.cs b/OpenSim/Region/OptionalModules/RegionCombinerModule/RegionData.cs deleted file mode 100644 index 42fca9f..0000000 --- a/OpenSim/Region/OptionalModules/RegionCombinerModule/RegionData.cs +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using OpenMetaverse; -using OpenSim.Region.Framework.Scenes; - -namespace OpenSim.Region.RegionCombinerModule -{ - public class RegionData - { - public UUID RegionId; - public Scene RegionScene; - // Offset of this region from the base of the root region. - public Vector3 Offset; - } -} \ No newline at end of file diff --git a/OpenSim/Region/OptionalModules/Scripting/JsonStore/JsonStore.cs b/OpenSim/Region/OptionalModules/Scripting/JsonStore/JsonStore.cs index c38bb3e..9343aab 100644 --- a/OpenSim/Region/OptionalModules/Scripting/JsonStore/JsonStore.cs +++ b/OpenSim/Region/OptionalModules/Scripting/JsonStore/JsonStore.cs @@ -1,5 +1,5 @@ /* - * Copyright (c) Contributors + * Copyright (c) Contributors * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without @@ -67,7 +67,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore protected List m_TakeStore; protected List m_ReadStore; - + // add separators for quoted paths and array references protected static Regex m_ParsePassOne = new Regex("({[^}]+}|\\[[0-9]+\\]|\\[\\+\\])"); @@ -98,10 +98,10 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore /// // ----------------------------------------------------------------- public int StringSpace { get; set; } - + // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- public static bool CanonicalPathExpression(string ipath, out string opath) @@ -116,13 +116,13 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore opath = PathExpressionToKey(path); return true; } - + // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- - public JsonStore() + public JsonStore() { StringSpace = 0; m_TakeStore = new List(); @@ -132,17 +132,17 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore public JsonStore(string value) : this() { // This is going to throw an exception if the value is not - // a valid JSON chunk. Calling routines should catch the + // a valid JSON chunk. Calling routines should catch the // exception and handle it appropriately if (String.IsNullOrEmpty(value)) ValueStore = new OSDMap(); else ValueStore = OSDParser.DeserializeJson(value); } - + // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- public JsonStoreNodeType GetNodeType(string expr) @@ -150,27 +150,27 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore Stack path; if (! ParsePathExpression(expr,out path)) return JsonStoreNodeType.Undefined; - + OSD result = ProcessPathExpression(ValueStore,path); if (result == null) return JsonStoreNodeType.Undefined; - + if (result is OSDMap) return JsonStoreNodeType.Object; - + if (result is OSDArray) return JsonStoreNodeType.Array; - + if (OSDBaseType(result.Type)) return JsonStoreNodeType.Value; - + return JsonStoreNodeType.Undefined; } - + // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- public JsonStoreValueType GetValueType(string expr) @@ -178,18 +178,18 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore Stack path; if (! ParsePathExpression(expr,out path)) return JsonStoreValueType.Undefined; - + OSD result = ProcessPathExpression(ValueStore,path); if (result == null) return JsonStoreValueType.Undefined; - + if (result is OSDMap) return JsonStoreValueType.Undefined; - + if (result is OSDArray) return JsonStoreValueType.Undefined; - + if (result is OSDBoolean) return JsonStoreValueType.Boolean; @@ -204,10 +204,10 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore return JsonStoreValueType.Undefined; } - + // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- public int ArrayLength(string expr) @@ -228,7 +228,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- public bool GetValue(string expr, out string value, bool useJson) @@ -241,23 +241,23 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore } OSD result = ProcessPathExpression(ValueStore,path); - return ConvertOutputValue(result,out value,useJson); + return ConvertOutputValue(result,out value,useJson); } - - + + // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- public bool RemoveValue(string expr) { return SetValueFromExpression(expr,null); } - + // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- public bool SetValue(string expr, string value, bool useJson) @@ -272,7 +272,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore { // There doesn't appear to be a good way to determine if the // value is valid Json other than to let the parser crash - try + try { ovalue = OSDParser.DeserializeJson(value); } @@ -292,13 +292,13 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore { ovalue = new OSDString(value); } - + return SetValueFromExpression(expr,ovalue); } - + // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- public bool TakeValue(string expr, bool useJson, TakeValueCallback cback) @@ -315,7 +315,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore m_TakeStore.Add(new TakeValueCallbackClass(pexpr,useJson,cback)); return false; } - + string value = String.Empty; if (! ConvertOutputValue(result,out value,useJson)) { @@ -332,7 +332,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- public bool ReadValue(string expr, bool useJson, TakeValueCallback cback) @@ -349,7 +349,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore m_ReadStore.Add(new TakeValueCallbackClass(pexpr,useJson,cback)); return false; } - + string value = String.Empty; if (! ConvertOutputValue(result,out value,useJson)) { @@ -362,10 +362,10 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore return true; } - + // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- protected bool SetValueFromExpression(string expr, OSD ovalue) @@ -447,7 +447,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore Match match = hmatches[0]; GroupCollection groups = match.Groups; string hkey = groups[1].Value; - + if (result is OSDMap) { // this is the assignment case @@ -456,7 +456,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore { StringSpace -= ComputeSizeOf(hmap[hkey]); StringSpace += ComputeSizeOf(ovalue); - + hmap[hkey] = ovalue; InvokeNextCallback(pexpr + pkey); return true; @@ -483,13 +483,13 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- protected bool InvokeNextCallback(string pexpr) { // Process all of the reads that match the expression first - List reads = + List reads = m_ReadStore.FindAll(delegate(TakeValueCallbackClass tb) { return pexpr.StartsWith(tb.Path); }); foreach (TakeValueCallbackClass readcb in reads) @@ -501,7 +501,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore // Process one take next TakeValueCallbackClass takecb = m_TakeStore.Find(delegate(TakeValueCallbackClass tb) { return pexpr.StartsWith(tb.Path); }); - + if (takecb != null) { m_TakeStore.Remove(takecb); @@ -525,13 +525,13 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore // add front and rear separators expr = "." + expr + "."; - + // add separators for quoted exprs and array references expr = m_ParsePassOne.Replace(expr,".$1.",-1,0); - + // add quotes to bare identifier expr = m_ParsePassThree.Replace(expr,".{$1}",-1,0); - + // remove extra separators expr = m_ParsePassFour.Replace(expr,".",-1,0); @@ -550,7 +550,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore // ----------------------------------------------------------------- /// - /// + /// /// /// path is a stack where the top level of the path is at the bottom of the stack // ----------------------------------------------------------------- @@ -558,13 +558,13 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore { if (path.Count == 0) return map; - + string pkey = path.Pop(); OSD rmap = ProcessPathExpression(map,path); if (rmap == null) return null; - + // ---------- Check for an array index ---------- MatchCollection amatches = m_SimpleArrayPattern.Matches(pkey,0); @@ -582,7 +582,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore GroupCollection groups = match.Groups; string akey = groups[1].Value; int aval = Convert.ToInt32(akey); - + if (aval < amap.Count) return (OSD) amap[aval]; @@ -599,13 +599,13 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore m_log.WarnFormat("[JsonStore] wrong type for key {2}, expecting {0}, got {1}",OSDType.Map,rmap.Type,pkey); return null; } - + OSDMap hmap = rmap as OSDMap; Match match = hmatches[0]; GroupCollection groups = match.Groups; string hkey = groups[1].Value; - + if (hmap.ContainsKey(hkey)) return (OSD) hmap[hkey]; @@ -619,13 +619,13 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- protected static bool ConvertOutputValue(OSD result, out string value, bool useJson) { value = String.Empty; - + // If we couldn't process the path if (result == null) return false; @@ -646,13 +646,13 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore return true; } - value = "'" + result.AsString() + "'"; + value = "'" + result.AsString() + "'"; return true; } if (OSDBaseType(result.Type)) { - value = result.AsString(); + value = result.AsString(); return true; } @@ -661,24 +661,24 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- protected static string PathExpressionToKey(Stack path) { if (path.Count == 0) return ""; - + string pkey = ""; foreach (string k in path) pkey = (pkey == "") ? k : (k + "." + pkey); - + return pkey; } // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- protected static bool OSDBaseType(OSDType type) @@ -705,7 +705,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- protected static int ComputeSizeOf(OSD value) @@ -731,7 +731,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore private Scene m_scene; private UUID m_objectID; - protected override OSD ValueStore + protected override OSD ValueStore { get { @@ -741,7 +741,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore // This is bad return null; } - + return sop.DynAttrs.TopLevelMap; } @@ -761,5 +761,5 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore StringSpace = ComputeSizeOf(ValueStore); } } - + } diff --git a/OpenSim/Region/OptionalModules/Scripting/JsonStore/JsonStoreCommands.cs b/OpenSim/Region/OptionalModules/Scripting/JsonStore/JsonStoreCommands.cs index d4b19dd..9bf9cb0 100644 --- a/OpenSim/Region/OptionalModules/Scripting/JsonStore/JsonStoreCommands.cs +++ b/OpenSim/Region/OptionalModules/Scripting/JsonStore/JsonStoreCommands.cs @@ -1,5 +1,5 @@ /* - * Copyright (c) Contributors + * Copyright (c) Contributors * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without @@ -79,7 +79,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore // ----------------------------------------------------------------- public void Initialise(IConfigSource config) { - try + try { if ((m_config = config.Configs["JsonStore"]) == null) { @@ -127,7 +127,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore if (m_enabled) { m_scene = scene; - + } } @@ -143,7 +143,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore // ----------------------------------------------------------------- /// - /// Called when all modules have been added for a region. This is + /// Called when all modules have been added for a region. This is /// where we hook up events /// // ----------------------------------------------------------------- diff --git a/OpenSim/Region/OptionalModules/Scripting/JsonStore/JsonStoreModule.cs b/OpenSim/Region/OptionalModules/Scripting/JsonStore/JsonStoreModule.cs index 26044f0..ae8341f 100644 --- a/OpenSim/Region/OptionalModules/Scripting/JsonStore/JsonStoreModule.cs +++ b/OpenSim/Region/OptionalModules/Scripting/JsonStore/JsonStoreModule.cs @@ -1,5 +1,5 @@ /* - * Copyright (c) Contributors + * Copyright (c) Contributors * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without @@ -83,7 +83,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore // ----------------------------------------------------------------- public void Initialise(IConfigSource config) { - try + try { if ((m_config = config.Configs["JsonStore"]) == null) { @@ -159,7 +159,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore // ----------------------------------------------------------------- /// - /// Called when all modules have been added for a region. This is + /// Called when all modules have been added for a region. This is /// where we hook up events /// // ----------------------------------------------------------------- @@ -184,7 +184,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore #region SceneEvents // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- public void EventManagerOnObjectBeingRemovedFromScene(SceneObjectGroup obj) @@ -196,10 +196,10 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore #region ScriptInvocationInteface - + // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- public JsonStoreStats GetStoreStats() @@ -210,13 +210,13 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore { stats.StoreCount = m_JsonValueStore.Count; } - + return stats; } - + // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- public bool AttachObjectStore(UUID objectID) @@ -235,17 +235,17 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore { if (m_JsonValueStore.ContainsKey(objectID)) return true; - + JsonStore map = new JsonObjectStore(m_scene,objectID); m_JsonValueStore.Add(objectID,map); } - + return true; } - + // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- public bool CreateStore(string value, ref UUID result) @@ -254,12 +254,12 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore result = UUID.Random(); JsonStore map = null; - + if (! m_enabled) return false; - + try - { + { map = new JsonStore(value); } catch (Exception) @@ -270,13 +270,13 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore lock (m_JsonValueStore) m_JsonValueStore.Add(result,map); - + return true; } // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- public bool DestroyStore(UUID storeID) @@ -289,7 +289,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- public bool TestStore(UUID storeID) @@ -302,7 +302,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- public JsonStoreNodeType GetNodeType(UUID storeID, string path) @@ -318,7 +318,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore return JsonStoreNodeType.Undefined; } } - + try { lock (map) @@ -334,7 +334,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- public JsonStoreValueType GetValueType(UUID storeID, string path) @@ -350,7 +350,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore return JsonStoreValueType.Undefined; } } - + try { lock (map) @@ -366,7 +366,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- public bool SetValue(UUID storeID, string path, string value, bool useJson) @@ -382,7 +382,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore return false; } } - + try { lock (map) @@ -393,7 +393,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore storeID,map.StringSpace,m_maxStringSpace); return false; } - + return map.SetValue(path,value,useJson); } } @@ -404,10 +404,10 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore return false; } - + // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- public bool RemoveValue(UUID storeID, string path) @@ -423,7 +423,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore return false; } } - + try { lock (map) @@ -436,10 +436,10 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore return false; } - + // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- public int GetArrayLength(UUID storeID, string path) @@ -464,19 +464,19 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore { m_log.Error("[JsonStore]: unable to retrieve value", e); } - + return -1; } // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- public bool GetValue(UUID storeID, string path, bool useJson, out string value) { value = String.Empty; - + if (! m_enabled) return false; JsonStore map = null; @@ -497,13 +497,13 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore { m_log.Error("[JsonStore]: unable to retrieve value", e); } - + return false; } // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- public void TakeValue(UUID storeID, string path, bool useJson, TakeValueCallback cback) @@ -536,13 +536,13 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore { m_log.Error("[JsonStore] unable to retrieve value", e); } - + cback(String.Empty); } // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- public void ReadValue(UUID storeID, string path, bool useJson, TakeValueCallback cback) @@ -575,7 +575,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore { m_log.Error("[JsonStore]: unable to retrieve value", e); } - + cback(String.Empty); } diff --git a/OpenSim/Region/OptionalModules/Scripting/JsonStore/JsonStoreScriptModule.cs b/OpenSim/Region/OptionalModules/Scripting/JsonStore/JsonStoreScriptModule.cs index 01de21c..fe8d962 100644 --- a/OpenSim/Region/OptionalModules/Scripting/JsonStore/JsonStoreScriptModule.cs +++ b/OpenSim/Region/OptionalModules/Scripting/JsonStore/JsonStoreScriptModule.cs @@ -1,5 +1,5 @@ /* - * Copyright (c) Contributors + * Copyright (c) Contributors * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without @@ -83,7 +83,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore // ----------------------------------------------------------------- public void Initialise(IConfigSource config) { - try + try { if ((m_config = config.Configs["JsonStore"]) == null) { @@ -166,7 +166,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore // ----------------------------------------------------------------- /// - /// Called when all modules have been added for a region. This is + /// Called when all modules have been added for a region. This is /// where we hook up events /// // ----------------------------------------------------------------- @@ -251,7 +251,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore #region ScriptInvocationInteface // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- [ScriptInvocation] @@ -260,13 +260,13 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore UUID uuid = UUID.Zero; if (! m_store.AttachObjectStore(hostID)) GenerateRuntimeError("Failed to create Json store"); - + return hostID; } // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- [ScriptInvocation] @@ -275,12 +275,12 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore UUID uuid = UUID.Zero; if (! m_store.CreateStore(value, ref uuid)) GenerateRuntimeError("Failed to create Json store"); - + lock (m_scriptStores) { if (! m_scriptStores.ContainsKey(scriptID)) m_scriptStores[scriptID] = new HashSet(); - + m_scriptStores[scriptID].Add(uuid); } return uuid; @@ -288,7 +288,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- [ScriptInvocation] @@ -305,7 +305,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- [ScriptInvocation] @@ -316,7 +316,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- [ScriptInvocation] @@ -330,7 +330,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- [ScriptInvocation] @@ -341,10 +341,10 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore o => DoJsonReadNotecard(reqID, hostID, scriptID, storeID, path, notecardIdentifier), null, "JsonStoreScriptModule.JsonReadNotecard"); return reqID; } - + // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- [ScriptInvocation] @@ -358,7 +358,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- [ScriptInvocation] @@ -366,7 +366,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore { string ipath = ConvertList2Path(pathlist); string opath; - + if (JsonStore.CanonicalPathExpression(ipath,out opath)) return opath; @@ -375,10 +375,10 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore // the entire store return "**INVALID**"; } - + // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- [ScriptInvocation] @@ -389,7 +389,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- [ScriptInvocation] @@ -400,7 +400,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- [ScriptInvocation] @@ -417,7 +417,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- [ScriptInvocation] @@ -425,10 +425,10 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore { return m_store.RemoveValue(storeID,path) ? 1 : 0; } - + // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- [ScriptInvocation] @@ -436,10 +436,10 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore { return m_store.GetArrayLength(storeID,path); } - + // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- [ScriptInvocation] @@ -457,10 +457,10 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore m_store.GetValue(storeID,path,true, out value); return value; } - + // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- [ScriptInvocation] @@ -480,10 +480,10 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore o => DoJsonTakeValue(scriptID,reqID,storeID,path,true), null, "JsonStoreScriptModule.DoJsonTakeValueJson"); return reqID; } - + // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- [ScriptInvocation] @@ -503,12 +503,12 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore o => DoJsonReadValue(scriptID,reqID,storeID,path,true), null, "JsonStoreScriptModule.DoJsonReadValueJson"); return reqID; } - + #endregion // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- protected void GenerateRuntimeError(string msg) @@ -516,10 +516,10 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore m_log.InfoFormat("[JsonStore] runtime error: {0}",msg); throw new Exception("JsonStore Runtime Error: " + msg); } - + // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- protected void DispatchValue(UUID scriptID, UUID reqID, string value) @@ -529,7 +529,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- private void DoJsonTakeValue(UUID scriptID, UUID reqID, UUID storeID, string path, bool useJson) @@ -543,14 +543,14 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore { m_log.InfoFormat("[JsonStoreScripts]: unable to retrieve value; {0}",e.ToString()); } - + DispatchValue(scriptID,reqID,String.Empty); } // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- private void DoJsonReadValue(UUID scriptID, UUID reqID, UUID storeID, string path, bool useJson) @@ -564,13 +564,13 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore { m_log.InfoFormat("[JsonStoreScripts]: unable to retrieve value; {0}",e.ToString()); } - + DispatchValue(scriptID,reqID,String.Empty); } // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- private void DoJsonReadNotecard( @@ -580,7 +580,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore if (!UUID.TryParse(notecardIdentifier, out assetID)) { - SceneObjectPart part = m_scene.GetSceneObjectPart(hostID); + SceneObjectPart part = m_scene.GetSceneObjectPart(hostID); assetID = ScriptUtils.GetAssetIdFromItemName(part, notecardIdentifier, (int)AssetType.Notecard); } @@ -590,10 +590,10 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore if (a.Type != (sbyte)AssetType.Notecard) GenerateRuntimeError(String.Format("Invalid notecard asset {0}", assetID)); - + m_log.DebugFormat("[JsonStoreScripts]: read notecard in context {0}",storeID); - try + try { string jsondata = SLUtil.ParseNotecardToString(a.Data); int result = m_store.SetValue(storeID, path, jsondata,true) ? 1 : 0; @@ -612,10 +612,10 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore GenerateRuntimeError(String.Format("Json parsing failed for {0}", assetID)); m_comms.DispatchReply(scriptID, 0, "", reqID.ToString()); } - + // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- private void DoJsonWriteNotecard(UUID reqID, UUID hostID, UUID scriptID, UUID storeID, string path, string name) @@ -626,9 +626,9 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore m_comms.DispatchReply(scriptID,0,UUID.Zero.ToString(),reqID.ToString()); return; } - + SceneObjectPart host = m_scene.GetSceneObjectPart(hostID); - + // Create new asset UUID assetID = UUID.Random(); AssetBase asset = new AssetBase(assetID, name, (sbyte)AssetType.Notecard, host.OwnerID.ToString()); @@ -665,7 +665,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore taskItem.AssetID = asset.FullID; host.Inventory.AddInventoryItem(taskItem, false); - + host.ParentGroup.InvalidateEffectivePerms(); m_comms.DispatchReply(scriptID,1,assetID.ToString(),reqID.ToString()); } @@ -681,7 +681,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore for (int i = 0; i < pathlist.Length; i++) { string token = ""; - + if (pathlist[i] is string) { token = pathlist[i].ToString(); @@ -699,16 +699,16 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore { token = "." + pathlist[i].ToString() + "."; } - + path += token + "."; } - + return path; } - + // ----------------------------------------------------------------- /// - /// + /// /// // ----------------------------------------------------------------- private void DoJsonRezObject(UUID hostID, UUID scriptID, UUID reqID, string name, Vector3 pos, Vector3 vel, Quaternion rot, string param) @@ -728,6 +728,8 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore // hpos = host.RootPart.GetWorldPosition() // float dist = (float)llVecDist(hpos, pos); + // if (dist > m_ScriptDistanceFactor * 10.0f) + // return; TaskInventoryItem item = host.RootPart.Inventory.GetInventoryItem(name); if (item == null) @@ -744,8 +746,10 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore List objlist; List veclist; - - bool success = host.RootPart.Inventory.GetRezReadySceneObjects(item, out objlist, out veclist); + + Vector3 bbox = new Vector3(); + float offsetHeight; + bool success = host.RootPart.Inventory.GetRezReadySceneObjects(item, out objlist, out veclist, out bbox, out offsetHeight); if (! success) { GenerateRuntimeError("Failed to create object"); @@ -779,7 +783,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore group.RootPart.Shape.LastAttachPoint = (byte)group.AttachmentPoint; } - group.FromPartID = host.RootPart.UUID; + group.RezzerID = host.RootPart.UUID; m_scene.AddNewSceneObject(group, true, curpos, rot, vel); UUID storeID = group.UUID; @@ -797,7 +801,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore group.ScheduleGroupForFullUpdate(); - // send the reply back to the host object, use the integer param to indicate the number + // send the reply back to the host object, use the integer param to indicate the number // of remaining objects m_comms.DispatchReply(scriptID, objlist.Count-i-1, group.RootPart.UUID.ToString(), reqID.ToString()); } diff --git a/OpenSim/Region/OptionalModules/Scripting/JsonStore/Tests/JsonStoreScriptModuleTests.cs b/OpenSim/Region/OptionalModules/Scripting/JsonStore/Tests/JsonStoreScriptModuleTests.cs index 99a7076..77ee785 100644 --- a/OpenSim/Region/OptionalModules/Scripting/JsonStore/Tests/JsonStoreScriptModuleTests.cs +++ b/OpenSim/Region/OptionalModules/Scripting/JsonStore/Tests/JsonStoreScriptModuleTests.cs @@ -180,7 +180,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests TestHelpers.InMethod(); // TestHelpers.EnableLogging(); - UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : { 'World' : 'Two' } }"); + UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : { 'World' : 'Two' } }"); { string value = (string)InvokeOp("JsonGetValue", storeId, "Hello.World"); @@ -213,7 +213,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests TestHelpers.InMethod(); // TestHelpers.EnableLogging(); - UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : { 'World' : 'Two' } }"); + UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : { 'World' : 'Two' } }"); { string value = (string)InvokeOp("JsonGetJson", storeId, "Hello.World"); @@ -246,11 +246,11 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests // TestHelpers.InMethod(); //// TestHelpers.EnableLogging(); // -// UUID storeId +// UUID storeId // = (UUID)m_smcm.InvokeOperation( -// UUID.Zero, UUID.Zero, "JsonCreateStore", new object[] { "{ 'Hello' : 'World' }" }); +// UUID.Zero, UUID.Zero, "JsonCreateStore", new object[] { "{ 'Hello' : 'World' }" }); // -// string value +// string value // = (string)m_smcm.InvokeOperation( // UUID.Zero, UUID.Zero, "JsonTakeValue", new object[] { storeId, "Hello" }); // @@ -271,7 +271,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests // Test remove of node in object pointing to a string { - UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : 'World' }"); + UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : 'World' }"); int returnValue = (int)InvokeOp( "JsonRemoveValue", storeId, "Hello"); Assert.That(returnValue, Is.EqualTo(1)); @@ -285,7 +285,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests // Test remove of node in object pointing to another object { - UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : { 'World' : 'Wally' } }"); + UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : { 'World' : 'Wally' } }"); int returnValue = (int)InvokeOp( "JsonRemoveValue", storeId, "Hello"); Assert.That(returnValue, Is.EqualTo(1)); @@ -299,7 +299,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests // Test remove of node in an array { - UUID storeId + UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : [ 'value1', 'value2' ] }"); int returnValue = (int)InvokeOp( "JsonRemoveValue", storeId, "Hello[0]"); @@ -320,7 +320,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests // Test remove of non-existing value { - UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : 'World' }"); + UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : 'World' }"); int fakeValueRemove = (int)InvokeOp("JsonRemoveValue", storeId, "Cheese"); Assert.That(fakeValueRemove, Is.EqualTo(0)); @@ -340,7 +340,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests // TestHelpers.InMethod(); //// TestHelpers.EnableLogging(); // -// UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : { 'World' : 'One' } }"); +// UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : { 'World' : 'One' } }"); // // { // int result = (int)InvokeOp("JsonTestPath", storeId, "Hello.World"); @@ -372,7 +372,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests // TestHelpers.InMethod(); //// TestHelpers.EnableLogging(); // -// UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : { 'World' : 'One' } }"); +// UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : { 'World' : 'One' } }"); // // { // int result = (int)InvokeOp("JsonTestPathJson", storeId, "Hello.World"); @@ -437,7 +437,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests TestHelpers.InMethod(); // TestHelpers.EnableLogging(); - UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : { 'World' : [ 'one', 2 ] } }"); + UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello' : { 'World' : [ 'one', 2 ] } }"); { int result = (int)InvokeOp("JsonGetNodeType", storeId, "."); @@ -509,7 +509,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests // TestHelpers.EnableLogging(); { - UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); + UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); int result = (int)InvokeOp("JsonSetValue", storeId, "Fun", "Times"); Assert.That(result, Is.EqualTo(1)); @@ -520,7 +520,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests // Test setting a key containing periods with delineation { - UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); + UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); int result = (int)InvokeOp("JsonSetValue", storeId, "{Fun.Circus}", "Times"); Assert.That(result, Is.EqualTo(1)); @@ -533,7 +533,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests // Test setting a key containing unbalanced ] without delineation. Expecting failure { - UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); + UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); int result = (int)InvokeOp("JsonSetValue", storeId, "Fun]Circus", "Times"); Assert.That(result, Is.EqualTo(0)); @@ -544,7 +544,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests // Test setting a key containing unbalanced [ without delineation. Expecting failure { - UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); + UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); int result = (int)InvokeOp("JsonSetValue", storeId, "Fun[Circus", "Times"); Assert.That(result, Is.EqualTo(0)); @@ -555,7 +555,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests // Test setting a key containing unbalanced [] without delineation. Expecting failure { - UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); + UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); int result = (int)InvokeOp("JsonSetValue", storeId, "Fun[]Circus", "Times"); Assert.That(result, Is.EqualTo(0)); @@ -566,7 +566,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests // Test setting a key containing unbalanced ] with delineation { - UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); + UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); int result = (int)InvokeOp("JsonSetValue", storeId, "{Fun]Circus}", "Times"); Assert.That(result, Is.EqualTo(1)); @@ -577,7 +577,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests // Test setting a key containing unbalanced [ with delineation { - UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); + UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); int result = (int)InvokeOp("JsonSetValue", storeId, "{Fun[Circus}", "Times"); Assert.That(result, Is.EqualTo(1)); @@ -588,7 +588,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests // Test setting a key containing empty balanced [] with delineation { - UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); + UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); int result = (int)InvokeOp("JsonSetValue", storeId, "{Fun[]Circus}", "Times"); Assert.That(result, Is.EqualTo(1)); @@ -600,7 +600,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests // // Commented out as this currently unexpectedly fails. // // Test setting a key containing brackets around an integer with delineation // { -// UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); +// UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); // // int result = (int)InvokeOp("JsonSetValue", storeId, "{Fun[0]Circus}", "Times"); // Assert.That(result, Is.EqualTo(1)); @@ -610,10 +610,10 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests // } // *** Test {} *** - + // Test setting a key containing unbalanced } without delineation. Expecting failure (?) { - UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); + UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); int result = (int)InvokeOp("JsonSetValue", storeId, "Fun}Circus", "Times"); Assert.That(result, Is.EqualTo(0)); @@ -624,7 +624,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests // Test setting a key containing unbalanced { without delineation. Expecting failure (?) { - UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); + UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); int result = (int)InvokeOp("JsonSetValue", storeId, "Fun{Circus", "Times"); Assert.That(result, Is.EqualTo(0)); @@ -636,7 +636,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests // // Commented out as this currently unexpectedly fails. // // Test setting a key containing unbalanced } // { -// UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); +// UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); // // int result = (int)InvokeOp("JsonSetValue", storeId, "{Fun}Circus}", "Times"); // Assert.That(result, Is.EqualTo(0)); @@ -644,7 +644,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests // Test setting a key containing unbalanced { with delineation { - UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); + UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); int result = (int)InvokeOp("JsonSetValue", storeId, "{Fun{Circus}", "Times"); Assert.That(result, Is.EqualTo(1)); @@ -655,7 +655,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests // Test setting a key containing balanced {} with delineation. This should fail. { - UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); + UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); int result = (int)InvokeOp("JsonSetValue", storeId, "{Fun{Filled}Circus}", "Times"); Assert.That(result, Is.EqualTo(0)); @@ -666,7 +666,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests // Test setting to location that does not exist. This should fail. { - UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); + UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{}"); int result = (int)InvokeOp("JsonSetValue", storeId, "Fun.Circus", "Times"); Assert.That(result, Is.EqualTo(0)); @@ -691,7 +691,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests // Single quoted token case { - UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ }"); + UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ }"); int result = (int)InvokeOp("JsonSetJson", storeId, "Fun", "'Times'"); Assert.That(result, Is.EqualTo(1)); @@ -702,7 +702,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests // Sub-tree case { - UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ }"); + UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ }"); int result = (int)InvokeOp("JsonSetJson", storeId, "Fun", "{ 'Filled' : 'Times' }"); Assert.That(result, Is.EqualTo(1)); @@ -713,7 +713,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests // If setting single strings in JsonSetValueJson, these must be single quoted tokens, not bare strings. { - UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ }"); + UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ }"); int result = (int)InvokeOp("JsonSetJson", storeId, "Fun", "Times"); Assert.That(result, Is.EqualTo(0)); @@ -724,7 +724,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests // Test setting to location that does not exist. This should fail. { - UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ }"); + UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ }"); int result = (int)InvokeOp("JsonSetJson", storeId, "Fun.Circus", "'Times'"); Assert.That(result, Is.EqualTo(0)); @@ -757,7 +757,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests SceneObjectGroup so = SceneHelpers.CreateSceneObject(1, TestHelpers.ParseTail(0x1)); m_scene.AddSceneObject(so); - UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello':'World' }"); + UUID storeId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello':'World' }"); { string notecardName = "nc1"; @@ -820,14 +820,14 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests SceneObjectGroup so = SceneHelpers.CreateSceneObject(1, TestHelpers.ParseTail(0x1)); m_scene.AddSceneObject(so); - UUID creatingStoreId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello':'World' }"); + UUID creatingStoreId = (UUID)InvokeOp("JsonCreateStore", "{ 'Hello':'World' }"); // Write notecard InvokeOpOnHost("JsonWriteNotecard", so.UUID, creatingStoreId, "", notecardName); { // Read notecard - UUID receivingStoreId = (UUID)InvokeOp("JsonCreateStore", "{}"); + UUID receivingStoreId = (UUID)InvokeOp("JsonCreateStore", "{}"); UUID readNotecardRequestId = (UUID)InvokeOpOnHost("JsonReadNotecard", so.UUID, receivingStoreId, "", notecardName); Assert.That(readNotecardRequestId, Is.Not.EqualTo(UUID.Zero)); @@ -837,10 +837,10 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests { // Read notecard to new single component path - UUID receivingStoreId = (UUID)InvokeOp("JsonCreateStore", "{}"); + UUID receivingStoreId = (UUID)InvokeOp("JsonCreateStore", "{}"); UUID readNotecardRequestId = (UUID)InvokeOpOnHost("JsonReadNotecard", so.UUID, receivingStoreId, "make", notecardName); Assert.That(readNotecardRequestId, Is.Not.EqualTo(UUID.Zero)); - + string value = (string)InvokeOp("JsonGetValue", receivingStoreId, "Hello"); Assert.That(value, Is.EqualTo("")); @@ -850,7 +850,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests { // Read notecard to new multi-component path. This should not work. - UUID receivingStoreId = (UUID)InvokeOp("JsonCreateStore", "{}"); + UUID receivingStoreId = (UUID)InvokeOp("JsonCreateStore", "{}"); UUID readNotecardRequestId = (UUID)InvokeOpOnHost("JsonReadNotecard", so.UUID, receivingStoreId, "make.it", notecardName); Assert.That(readNotecardRequestId, Is.Not.EqualTo(UUID.Zero)); @@ -863,7 +863,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests { // Read notecard to existing multi-component path. This should work - UUID receivingStoreId = (UUID)InvokeOp("JsonCreateStore", "{ 'make' : { 'it' : 'so' } }"); + UUID receivingStoreId = (UUID)InvokeOp("JsonCreateStore", "{ 'make' : { 'it' : 'so' } }"); UUID readNotecardRequestId = (UUID)InvokeOpOnHost("JsonReadNotecard", so.UUID, receivingStoreId, "make.it", notecardName); Assert.That(readNotecardRequestId, Is.Not.EqualTo(UUID.Zero)); @@ -876,7 +876,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.JsonStore.Tests { // Read notecard to invalid path. This should not work. - UUID receivingStoreId = (UUID)InvokeOp("JsonCreateStore", "{ 'make' : { 'it' : 'so' } }"); + UUID receivingStoreId = (UUID)InvokeOp("JsonCreateStore", "{ 'make' : { 'it' : 'so' } }"); UUID readNotecardRequestId = (UUID)InvokeOpOnHost("JsonReadNotecard", so.UUID, receivingStoreId, "/", notecardName); Assert.That(readNotecardRequestId, Is.Not.EqualTo(UUID.Zero)); diff --git a/OpenSim/Region/OptionalModules/Scripting/Minimodule/Interfaces/IAvatarAttachment.cs b/OpenSim/Region/OptionalModules/Scripting/Minimodule/Interfaces/IAvatarAttachment.cs index 1993948..2368a23 100644 --- a/OpenSim/Region/OptionalModules/Scripting/Minimodule/Interfaces/IAvatarAttachment.cs +++ b/OpenSim/Region/OptionalModules/Scripting/Minimodule/Interfaces/IAvatarAttachment.cs @@ -33,7 +33,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule /// Describes where on the avatar the attachment is located /// int Location { get ; } - + //// /// Accessor to the rez'ed asset, representing the attachment /// diff --git a/OpenSim/Region/OptionalModules/Scripting/Minimodule/Interfaces/IInventoryItem.cs b/OpenSim/Region/OptionalModules/Scripting/Minimodule/Interfaces/IInventoryItem.cs index a8e545c..d61f52a 100644 --- a/OpenSim/Region/OptionalModules/Scripting/Minimodule/Interfaces/IInventoryItem.cs +++ b/OpenSim/Region/OptionalModules/Scripting/Minimodule/Interfaces/IInventoryItem.cs @@ -30,7 +30,7 @@ using OpenMetaverse; using OpenMetaverse.Assets; namespace OpenSim.Region.OptionalModules.Scripting.Minimodule -{ +{ /// /// This implements the methods needed to operate on individual inventory items. /// diff --git a/OpenSim/Region/OptionalModules/Scripting/Minimodule/Interfaces/IObject.cs b/OpenSim/Region/OptionalModules/Scripting/Minimodule/Interfaces/IObject.cs index e189489..dc2edd9 100644 --- a/OpenSim/Region/OptionalModules/Scripting/Minimodule/Interfaces/IObject.cs +++ b/OpenSim/Region/OptionalModules/Scripting/Minimodule/Interfaces/IObject.cs @@ -60,19 +60,19 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule /// /// Returns whether or not this object is still in the world. /// Eg, if you store an IObject reference, however the object - /// is deleted before you use it, it will throw a NullReference + /// is deleted before you use it, it will throw a NullReference /// exception. 'Exists' allows you to check the object is still /// in play before utilizing it. /// /// /// IObject deleteMe = World.Objects[0]; - /// + /// /// if (deleteMe.Exists) { /// deleteMe.Say("Hello, I still exist!"); /// } - /// + /// /// World.Objects.Remove(deleteMe); - /// + /// /// if (!deleteMe.Exists) { /// Host.Console.Info("I was deleted"); /// } @@ -81,7 +81,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule /// Objects should be near-guarunteed to exist for any event which /// passes them as an argument. Storing an object for a longer period /// of time however will limit their reliability. - /// + /// /// It is a good practice to use Try/Catch blocks handling for /// NullReferenceException, when accessing remote objects. /// @@ -118,8 +118,8 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule IObject[] Children { get; } /// - /// Returns a list of materials attached to this object. Each may contain unique texture - /// and other visual information. For primitive based objects, this correlates with + /// Returns a list of materials attached to this object. Each may contain unique texture + /// and other visual information. For primitive based objects, this correlates with /// Object Faces. For mesh based objects, this correlates with Materials. /// IObjectMaterial[] Materials { get; } @@ -152,7 +152,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule String TouchText { get; set; } /// - /// Text to be associated with this object, in the + /// Text to be associated with this object, in the /// Second Life(r) viewer, this is shown above the /// object. /// diff --git a/OpenSim/Region/OptionalModules/Scripting/Minimodule/InventoryItem.cs b/OpenSim/Region/OptionalModules/Scripting/Minimodule/InventoryItem.cs index bf85cbc..bec8f38 100644 --- a/OpenSim/Region/OptionalModules/Scripting/Minimodule/InventoryItem.cs +++ b/OpenSim/Region/OptionalModules/Scripting/Minimodule/InventoryItem.cs @@ -40,7 +40,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule { TaskInventoryItem m_privateItem; Scene m_rootScene; - + public InventoryItem(Scene rootScene, TaskInventoryItem internalItem) { m_rootScene = rootScene; @@ -77,10 +77,10 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule throw new ApplicationException("[MRM] There is no legal conversion from IInventoryItem to InventoryItem"); } } - + public int Type { get { return m_privateItem.Type; } } public UUID AssetID { get { return m_privateItem.AssetID; } } - + // This method exposes OpenSim/OpenMetaverse internals and needs to be replaced with a IAsset specific to MRM. public T RetrieveAsset() where T : OpenMetaverse.Assets.Asset, new() { @@ -89,7 +89,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule if ((sbyte)result.AssetType != a.Type) throw new ApplicationException("[MRM] The supplied asset class does not match the found asset"); - + result.AssetData = a.Data; result.Decode(); return result; diff --git a/OpenSim/Region/OptionalModules/Scripting/Minimodule/MicroScheduler.cs b/OpenSim/Region/OptionalModules/Scripting/Minimodule/MicroScheduler.cs index 73fe8b8..5861486 100644 --- a/OpenSim/Region/OptionalModules/Scripting/Minimodule/MicroScheduler.cs +++ b/OpenSim/Region/OptionalModules/Scripting/Minimodule/MicroScheduler.cs @@ -35,7 +35,7 @@ using OpenSim.Region.OptionalModules.Scripting.Minimodule.Interfaces; namespace OpenSim.Region.OptionalModules.Scripting.Minimodule { - public class MicroScheduler : System.MarshalByRefObject, IMicrothreader + public class MicroScheduler : System.MarshalByRefObject, IMicrothreader { private readonly List m_threads = new List(); diff --git a/OpenSim/Region/OptionalModules/Scripting/Minimodule/SOPObject.cs b/OpenSim/Region/OptionalModules/Scripting/Minimodule/SOPObject.cs index 47b9c09..5513cd5 100644 --- a/OpenSim/Region/OptionalModules/Scripting/Minimodule/SOPObject.cs +++ b/OpenSim/Region/OptionalModules/Scripting/Minimodule/SOPObject.cs @@ -165,7 +165,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule get { return GetSOP().Description; } set { - if (CanEdit()) + if (CanEdit()) GetSOP().Description = value; } } @@ -192,7 +192,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule rets = new IObject[total]; int i = 0; - + foreach (SceneObjectPart part in my.ParentGroup.Parts) { rets[i++] = new SOPObject(m_rootScene, part.LocalId, m_security); @@ -273,8 +273,8 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule public Vector3 SitTarget { get { return GetSOP().SitTargetPosition; } - set - { + set + { if (CanEdit()) { GetSOP().SitTargetPosition = value; @@ -285,8 +285,8 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule public string SitTargetText { get { return GetSOP().SitName; } - set - { + set + { if (CanEdit()) { GetSOP().SitName = value; @@ -297,7 +297,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule public string TouchText { get { return GetSOP().TouchName; } - set + set { if (CanEdit()) { @@ -309,7 +309,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule public string Text { get { return GetSOP().Text; } - set + set { if (CanEdit()) { @@ -382,11 +382,11 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule get { return this; } } - public IObjectInventory Inventory + public IObjectInventory Inventory { get { return new SOPObjectInventory(m_rootScene, GetSOP().TaskInventory); } } - + #region Public Functions public void Say(string msg) @@ -406,7 +406,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule SceneObjectPart sop = GetSOP(); m_rootScene.SimChat(Utils.StringToBytes(msg), ChatTypeEnum.Say,channel, sop.AbsolutePosition, sop.Name, sop.UUID, false); } - + public void Dialog(UUID avatar, string message, string[] buttons, int chat_channel) { if (!CanEdit()) @@ -445,9 +445,9 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule dm.SendDialogToUser( avatar, GetSOP().Name, GetSOP().UUID, GetSOP().OwnerID, message, new UUID("00000000-0000-2222-3333-100000001000"), chat_channel, buttons); - + } - + #endregion @@ -540,7 +540,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule if (hasCut) ret += 2; if (hasDimple) ret += 2; if (hasHollow) - ret += 1; // GOTCHA: LSL shows 2 additional sides here. + ret += 1; // GOTCHA: LSL shows 2 additional sides here. // This has been fixed, but may cause porting issues. break; case (int) PrimType.Torus: diff --git a/OpenSim/Region/OptionalModules/Scripting/Minimodule/SOPObjectInventory.cs b/OpenSim/Region/OptionalModules/Scripting/Minimodule/SOPObjectInventory.cs index d20f4a4..8c3158c 100644 --- a/OpenSim/Region/OptionalModules/Scripting/Minimodule/SOPObjectInventory.cs +++ b/OpenSim/Region/OptionalModules/Scripting/Minimodule/SOPObjectInventory.cs @@ -61,25 +61,25 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule.Object if (!m_publicInventory.ContainsKey(privateItem.ItemID)) m_publicInventory.Add(privateItem.ItemID, new InventoryItem(m_rootScene, privateItem)); } - + #region IDictionary implementation public void Add (UUID key, IInventoryItem value) { m_publicInventory.Add(key, value); m_privateInventory.Add(key, InventoryItem.FromInterface(value).ToTaskInventoryItem()); } - + public bool ContainsKey (UUID key) { return m_privateInventory.ContainsKey(key); } - + public bool Remove (UUID key) { m_publicInventory.Remove(key); return m_privateInventory.Remove(key); } - + public bool TryGetValue (UUID key, out IInventoryItem value) { value = null; @@ -89,7 +89,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule.Object { // wasn't found in the public inventory TaskInventoryItem privateItem; - + result = m_privateInventory.TryGetValue(key, out privateItem); if (result) { @@ -98,16 +98,16 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule.Object } } else return true; - + return result; } - + public ICollection Keys { get { return m_privateInventory.Keys; } } - + public ICollection Values { get { SynchronizeDictionaries(); @@ -139,41 +139,41 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule.Object { Add(item.Key, item.Value); } - + public void Clear () { m_publicInventory.Clear(); m_privateInventory.Clear(); } - + public bool Contains (KeyValuePair item) { return m_privateInventory.ContainsKey(item.Key); } - + public void CopyTo (KeyValuePair[] array, int arrayIndex) { throw new NotImplementedException(); } - + public bool Remove (KeyValuePair item) { return Remove(item.Key); } - + public int Count { get { return m_privateInventory.Count; } } - + public bool IsReadOnly { get { return false; } } #endregion - + #region Explicit implementations IInventoryItem System.Collections.Generic.IDictionary.this[UUID key] { @@ -189,13 +189,13 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule.Object m_privateInventory[key] = InventoryItem.FromInterface(value).ToTaskInventoryItem(); } } - + void System.Collections.Generic.ICollection>.CopyTo(System.Collections.Generic.KeyValuePair[] array, int offset) { throw new NotImplementedException(); } #endregion - + public IInventoryItem this[string name] { get { @@ -204,7 +204,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule.Object { if (!m_publicInventory.ContainsKey(i.ItemID)) m_publicInventory.Add(i.ItemID, new InventoryItem(m_rootScene, i)); - + return m_publicInventory[i.ItemID]; } throw new KeyNotFoundException(); diff --git a/OpenSim/Region/OptionalModules/Scripting/Minimodule/SPAvatar.cs b/OpenSim/Region/OptionalModules/Scripting/Minimodule/SPAvatar.cs index d192309..a380f66 100644 --- a/OpenSim/Region/OptionalModules/Scripting/Minimodule/SPAvatar.cs +++ b/OpenSim/Region/OptionalModules/Scripting/Minimodule/SPAvatar.cs @@ -70,18 +70,18 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule get { return GetSP().AbsolutePosition; } set { GetSP().Teleport(value); } } - + public bool IsChildAgent { get { return GetSP().IsChildAgent; } } - + #region IAvatar implementation public IAvatarAttachment[] Attachments { get { List attachments = new List(); - + List internalAttachments = GetSP().Appearance.GetAttachments(); foreach (AvatarAttachment attach in internalAttachments) { @@ -89,7 +89,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule new UUID(attach.ItemID), new UUID(attach.AssetID), m_security)); } - + return attachments.ToArray(); } } diff --git a/OpenSim/Region/OptionalModules/Scripting/Minimodule/SPAvatarAttachment.cs b/OpenSim/Region/OptionalModules/Scripting/Minimodule/SPAvatarAttachment.cs index 570459a..bcf6053 100644 --- a/OpenSim/Region/OptionalModules/Scripting/Minimodule/SPAvatarAttachment.cs +++ b/OpenSim/Region/OptionalModules/Scripting/Minimodule/SPAvatarAttachment.cs @@ -41,7 +41,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule private readonly UUID m_assetId; private readonly ISecurityCredential m_security; - + public SPAvatarAttachment(Scene rootScene, IAvatar self, int location, UUID itemId, UUID assetId, ISecurityCredential security) { m_rootScene = rootScene; @@ -51,9 +51,9 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule //m_itemId = itemId; m_assetId = assetId; } - + public int Location { get { return m_location; } } - + public IObject Asset { get diff --git a/OpenSim/Region/OptionalModules/Scripting/Minimodule/Test/TestModule.cs b/OpenSim/Region/OptionalModules/Scripting/Minimodule/Test/TestModule.cs index 13d0140..724c2a9 100644 --- a/OpenSim/Region/OptionalModules/Scripting/Minimodule/Test/TestModule.cs +++ b/OpenSim/Region/OptionalModules/Scripting/Minimodule/Test/TestModule.cs @@ -51,7 +51,7 @@ namespace OpenSim public void Microthread(IEnumerable thread) { - + } public void RunMicrothread() @@ -92,7 +92,7 @@ namespace OpenSim public override void Stop() { - + } } } diff --git a/OpenSim/Region/OptionalModules/Scripting/Minimodule/World.cs b/OpenSim/Region/OptionalModules/Scripting/Minimodule/World.cs index f2324d2..36f70d0 100644 --- a/OpenSim/Region/OptionalModules/Scripting/Minimodule/World.cs +++ b/OpenSim/Region/OptionalModules/Scripting/Minimodule/World.cs @@ -34,7 +34,7 @@ using OpenSim.Region.OptionalModules.Scripting.Minimodule.WorldX; namespace OpenSim.Region.OptionalModules.Scripting.Minimodule { - public class World : System.MarshalByRefObject, IWorld, IWorldAudio + public class World : System.MarshalByRefObject, IWorld, IWorldAudio { private readonly Scene m_internalScene; private readonly ISecurityCredential m_security; @@ -149,7 +149,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule e.Sender = new SOPObject(m_internalScene, ((SceneObjectPart) chat.SenderObject).LocalId, m_security); e.Text = chat.Message; e.Channel = chat.Channel; - + _OnChat(this, e); return; } @@ -160,7 +160,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule e.Sender = new SPAvatar(m_internalScene, chat.SenderUUID, m_security); e.Text = chat.Message; e.Channel = chat.Channel; - + _OnChat(this, e); return; } diff --git a/OpenSim/Region/OptionalModules/Scripting/RegionReadyModule/RegionReadyModule.cs b/OpenSim/Region/OptionalModules/Scripting/RegionReadyModule/RegionReadyModule.cs index 870c0bb..a1dd711 100644 --- a/OpenSim/Region/OptionalModules/Scripting/RegionReadyModule/RegionReadyModule.cs +++ b/OpenSim/Region/OptionalModules/Scripting/RegionReadyModule/RegionReadyModule.cs @@ -46,7 +46,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.RegionReady [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "RegionReadyModule")] public class RegionReadyModule : IRegionReadyModule, INonSharedRegionModule { - private static readonly ILog m_log = + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IConfig m_config = null; @@ -57,24 +57,24 @@ namespace OpenSim.Region.OptionalModules.Scripting.RegionReady private bool m_enabled = false; private bool m_disable_logins; private string m_uri = string.Empty; - + Scene m_scene; - + #region INonSharedRegionModule interface - public Type ReplaceableInterface - { + public Type ReplaceableInterface + { get { return null; } } - + public void Initialise(IConfigSource config) { m_config = config.Configs["RegionReady"]; - if (m_config != null) + if (m_config != null) { m_enabled = m_config.GetBoolean("enabled", false); - - if (m_enabled) + + if (m_enabled) { m_channelNotify = m_config.GetInt("channel_notify", m_channelNotify); m_disable_logins = m_config.GetBoolean("login_disable", false); @@ -106,7 +106,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.RegionReady m_scene.EventManager.OnEmptyScriptCompileQueue += OnEmptyScriptCompileQueue; // This should always show up to the user but should not trigger warn/errors as these messages are - // expected and are not simulator problems. Ideally, there would be a status level in log4net but + // expected and are not simulator problems. Ideally, there would be a status level in log4net but // failing that, we will print out to console instead. MainConsole.Instance.OutputFormat("Region {0} - LOGINS DISABLED DURING INITIALIZATION.", m_scene.Name); @@ -152,12 +152,12 @@ namespace OpenSim.Region.OptionalModules.Scripting.RegionReady { m_log.DebugFormat("[RegionReady]: Script compile queue empty!"); - if (m_firstEmptyCompileQueue || m_oarFileLoading) + if (m_firstEmptyCompileQueue || m_oarFileLoading) { OSChatMessage c = new OSChatMessage(); - if (m_firstEmptyCompileQueue) + if (m_firstEmptyCompileQueue) c.Message = "server_startup,"; - else + else c.Message = "oar_file_load,"; m_firstEmptyCompileQueue = false; m_oarFileLoading = false; @@ -165,7 +165,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.RegionReady m_scene.Backup(false); c.From = "RegionReady"; - if (m_lastOarLoadedOk) + if (m_lastOarLoadedOk) c.Message += "1,"; else c.Message += "0,"; @@ -193,7 +193,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.RegionReady { m_oarFileLoading = true; - if (message==String.Empty) + if (message==String.Empty) { m_lastOarLoadedOk = true; } @@ -214,6 +214,10 @@ namespace OpenSim.Region.OptionalModules.Scripting.RegionReady m_scene.EventManager.OnEmptyScriptCompileQueue -= OnEmptyScriptCompileQueue; m_scene.LoginLock = false; + GC.Collect(); + GC.WaitForPendingFinalizers(); + GC.Collect(); + if (!m_scene.StartDisabled) { m_scene.LoginsEnabled = true; @@ -222,7 +226,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.RegionReady // m_scene.RegionInfo.RegionName, m_oarFileLoading.ToString()); // Putting this out to console to make it eye-catching for people who are running OpenSimulator - // without info log messages enabled. Making this a warning is arguably misleading since it isn't a + // without info log messages enabled. Making this a warning is arguably misleading since it isn't a // warning, and monitor scripts looking for warn/error/fatal messages will received false positives. // Arguably, log4net needs a status log level (like Apache). MainConsole.Instance.OutputFormat("INITIALIZATION COMPLETE FOR {0} - LOGINS ENABLED", m_scene.Name); @@ -252,7 +256,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.RegionReady // m_scene.EventManager.OnRezScript += OnRezScript; // m_oarFileLoading = true; // m_firstEmptyCompileQueue = true; -// +// // m_scene.LoginsDisabled = true; // m_scene.LoginLock = true; // if ( m_uri != string.Empty ) diff --git a/OpenSim/Region/OptionalModules/Scripting/XmlRpcRouterModule/XmlRpcGridRouterModule.cs b/OpenSim/Region/OptionalModules/Scripting/XmlRpcRouterModule/XmlRpcGridRouterModule.cs index 744d1e3..bf33996 100644 --- a/OpenSim/Region/OptionalModules/Scripting/XmlRpcRouterModule/XmlRpcGridRouterModule.cs +++ b/OpenSim/Region/OptionalModules/Scripting/XmlRpcRouterModule/XmlRpcGridRouterModule.cs @@ -54,7 +54,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.XmlRpcGridRouterModule public class XmlRpcGridRouter : INonSharedRegionModule, IXmlRpcRouter { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - + private Dictionary m_Channels = new Dictionary(); @@ -94,7 +94,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.XmlRpcGridRouterModule { scriptEngine.OnScriptRemoved += this.ScriptRemoved; scriptEngine.OnObjectRemoved += this.ObjectRemoved; - + } } @@ -131,7 +131,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.XmlRpcGridRouterModule if (!m_Enabled) return; - m_log.InfoFormat("[XMLRPC GRID ROUTER]: New receiver Obj: {0} Ch: {1} ID: {2} URI: {3}", + m_log.InfoFormat("[XMLRPC GRID ROUTER]: New receiver Obj: {0} Ch: {1} ID: {2} URI: {3}", objectID.ToString(), channel.ToString(), itemID.ToString(), uri); XmlRpcInfo info = new XmlRpcInfo(); @@ -178,7 +178,7 @@ namespace OpenSim.Region.OptionalModules.Scripting.XmlRpcGridRouterModule { if(!m_Channels.ContainsKey(itemID)) { - m_log.InfoFormat("[XMLRPC GRID ROUTER]: Attempted to unregister non-existing Item: {0}", itemID.ToString()); + //m_log.InfoFormat("[XMLRPC GRID ROUTER]: Attempted to unregister non-existing Item: {0}", itemID.ToString()); return false; } diff --git a/OpenSim/Region/OptionalModules/Scripting/XmlRpcRouterModule/XmlRpcRouterModule.cs b/OpenSim/Region/OptionalModules/Scripting/XmlRpcRouterModule/XmlRpcRouterModule.cs index 943675e..32549d6 100644 --- a/OpenSim/Region/OptionalModules/Scripting/XmlRpcRouterModule/XmlRpcRouterModule.cs +++ b/OpenSim/Region/OptionalModules/Scripting/XmlRpcRouterModule/XmlRpcRouterModule.cs @@ -98,7 +98,10 @@ namespace OpenSim.Region.OptionalModules.Scripting.XmlRpcRouterModule public void RegisterNewReceiver(IScriptModule scriptEngine, UUID channel, UUID objectID, UUID itemID, string uri) { - scriptEngine.PostScriptEvent(itemID, "xmlrpc_uri", new Object[] {uri}); + if (m_Enabled) + { + scriptEngine.PostScriptEvent(itemID, "xmlrpc_uri", new Object[] { uri }); + } } public void UnRegisterReceiver(string channelID, UUID itemID) diff --git a/OpenSim/Region/OptionalModules/ServiceConnectorsIn/Freeswitch/FreeswitchServiceInConnectorModule.cs b/OpenSim/Region/OptionalModules/ServiceConnectorsIn/Freeswitch/FreeswitchServiceInConnectorModule.cs index 78c870a..8654896 100644 --- a/OpenSim/Region/OptionalModules/ServiceConnectorsIn/Freeswitch/FreeswitchServiceInConnectorModule.cs +++ b/OpenSim/Region/OptionalModules/ServiceConnectorsIn/Freeswitch/FreeswitchServiceInConnectorModule.cs @@ -44,7 +44,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsIn.Freeswitch { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static bool m_Enabled = false; - + private IConfigSource m_Config; bool m_Registered = false; @@ -73,7 +73,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsIn.Freeswitch { } - public Type ReplaceableInterface + public Type ReplaceableInterface { get { return null; } } diff --git a/OpenSim/Region/OptionalModules/UserStatistics/Clients_report.cs b/OpenSim/Region/OptionalModules/UserStatistics/Clients_report.cs index 4a6f7be..d3b97b1 100644 --- a/OpenSim/Region/OptionalModules/UserStatistics/Clients_report.cs +++ b/OpenSim/Region/OptionalModules/UserStatistics/Clients_report.cs @@ -97,9 +97,8 @@ namespace OpenSim.Region.UserStatistics sdr.Read(); totalregions = Convert.ToInt32(sdr["regcnt"]); } - sdr.Close(); - sdr.Dispose(); + cmd.Dispose(); sql = "select client_version, count(*) as cnt, avg(avg_sim_fps) as simfps from stats_session_data group by client_version order by count(*) desc LIMIT 10;"; @@ -116,20 +115,20 @@ namespace OpenSim.Region.UserStatistics udata.fps = Convert.ToSingle(sdr["simfps"]); clidata.Add(udata); totalclients += udata.count; - + } } sdr.Close(); - sdr.Dispose(); + cmd.Dispose(); if (totalregions > 1) { sql = "select region_id, client_version, count(*) as cnt, avg(avg_sim_fps) as simfps from stats_session_data group by region_id, client_version order by region_id, count(*) desc;"; cmd = new SqliteCommand(sql, dbConn); - + sdr = cmd.ExecuteReader(); - + if (sdr.HasRows) { while (sdr.Read()) @@ -143,16 +142,13 @@ namespace OpenSim.Region.UserStatistics } } sdr.Close(); - sdr.Dispose(); - - + cmd.Dispose(); } - } - + foreach (ClientVersionData cvd in cliRegData) { - + if (regionTotals.ContainsKey(cvd.region_id)) { int regiontotal = (int)regionTotals[cvd.region_id]; @@ -163,9 +159,6 @@ namespace OpenSim.Region.UserStatistics { regionTotals.Add(cvd.region_id, cvd.count); } - - - } modeldata["ClientData"] = clidata; diff --git a/OpenSim/Region/OptionalModules/UserStatistics/Default_Report.cs b/OpenSim/Region/OptionalModules/UserStatistics/Default_Report.cs index fabe3d4..fcc7cee 100644 --- a/OpenSim/Region/OptionalModules/UserStatistics/Default_Report.cs +++ b/OpenSim/Region/OptionalModules/UserStatistics/Default_Report.cs @@ -61,7 +61,7 @@ namespace OpenSim.Region.UserStatistics Hashtable nh = new Hashtable(); nh.Add("hdata", mData); nh.Add("Reports", pParams["Reports"]); - + return nh; } @@ -76,7 +76,7 @@ namespace OpenSim.Region.UserStatistics public string rep_Default_report_view(stats_default_page_values values) { - + StringBuilder output = new StringBuilder(); @@ -105,7 +105,7 @@ TD.align_top { vertical-align: top; } "; HTMLUtil.HtmlHeaders_O(ref output); - + HTMLUtil.InsertProtoTypeAJAX(ref output); string[] ajaxUpdaterDivs = new string[3]; int[] ajaxUpdaterSeconds = new int[3]; @@ -124,7 +124,7 @@ TD.align_top { vertical-align: top; } ajaxUpdaterReportFragments[2] = "activelogajax.html"; HTMLUtil.InsertPeriodicUpdaters(ref output, ajaxUpdaterDivs, ajaxUpdaterSeconds, ajaxUpdaterReportFragments); - + output.Append(STYLESHEET); HTMLUtil.HtmlHeaders_C(ref output); HTMLUtil.AddReportLinks(ref output, values.stats_reports, ""); @@ -200,7 +200,7 @@ TD.align_top { vertical-align: top; } return output.ToString(); } - + public stats_default_page_values rep_DefaultReport_data(SqliteConnection db, List m_scene) { @@ -208,8 +208,8 @@ TD.align_top { vertical-align: top; } returnstruct.all_scenes = m_scene.ToArray(); lock (db) { - string SQL = @"SELECT COUNT(DISTINCT agent_id) as agents, COUNT(*) as sessions, AVG(avg_fps) as client_fps, - AVG(avg_sim_fps) as savg_sim_fps, AVG(avg_ping) as sav_ping, SUM(n_out_kb) as num_in_kb, + string SQL = @"SELECT COUNT(DISTINCT agent_id) as agents, COUNT(*) as sessions, AVG(avg_fps) as client_fps, + AVG(avg_sim_fps) as savg_sim_fps, AVG(avg_ping) as sav_ping, SUM(n_out_kb) as num_in_kb, SUM(n_out_pk) as num_in_packets, SUM(n_in_kb) as num_out_kb, SUM(n_in_pk) as num_out_packets, AVG(mem_use) as sav_mem_use FROM stats_session_data;"; SqliteCommand cmd = new SqliteCommand(SQL, db); @@ -227,7 +227,10 @@ TD.align_top { vertical-align: top; } returnstruct.avg_client_mem_use = Convert.ToSingle(sdr["sav_mem_use"]); } + sdr.Close(); + cmd.Dispose(); } + return returnstruct; } @@ -273,5 +276,5 @@ TD.align_top { vertical-align: top; } public Dictionary sim_stat_data; public Dictionary stats_reports; } - + } diff --git a/OpenSim/Region/OptionalModules/UserStatistics/HTMLUtil.cs b/OpenSim/Region/OptionalModules/UserStatistics/HTMLUtil.cs index c07619f..20e045a 100644 --- a/OpenSim/Region/OptionalModules/UserStatistics/HTMLUtil.cs +++ b/OpenSim/Region/OptionalModules/UserStatistics/HTMLUtil.cs @@ -95,7 +95,7 @@ namespace OpenSim.Region.UserStatistics { o.Append("\n"); } - + public static void BLOCKQUOTE_O(ref StringBuilder o, string pclass) { o.Append("ActiveLog\n"); @@ -102,13 +102,13 @@ namespace OpenSim.Region.UserStatistics } } StringBuilder replaceStr = new StringBuilder(); - //string titlecolorresults = - + //string titlecolorresults = + string formatresult = Regex.Replace(TitleColor.Replace(result[i], "$1"), "[^ABCDEFabcdef0-9]", ""); if (formatresult.Length > 6) { formatresult = formatresult.Substring(0, 6); - + } for (int j = formatresult.Length; j <= 5; j++) formatresult += "0"; @@ -116,12 +116,12 @@ namespace OpenSim.Region.UserStatistics replaceStr.Append(formatresult); replaceStr.Append("\">$3] $4
"); string repstr = replaceStr.ToString(); - + output.Append(formatopen); output.Append(webFormat.Replace(result[i], repstr)); output.Append(formatclose); } - + return output.ToString(); } diff --git a/OpenSim/Region/OptionalModules/UserStatistics/Prototype_distributor.cs b/OpenSim/Region/OptionalModules/UserStatistics/Prototype_distributor.cs index 6f8b2aa..63dc87e 100644 --- a/OpenSim/Region/OptionalModules/UserStatistics/Prototype_distributor.cs +++ b/OpenSim/Region/OptionalModules/UserStatistics/Prototype_distributor.cs @@ -44,7 +44,7 @@ namespace OpenSim.Region.UserStatistics jsFileName = "prototype.js"; } - public Prototype_distributor(string jsName) + public Prototype_distributor(string jsName) { jsFileName = jsName; } diff --git a/OpenSim/Region/OptionalModules/UserStatistics/Sessions_Report.cs b/OpenSim/Region/OptionalModules/UserStatistics/Sessions_Report.cs index 0e94912..8d5434f 100644 --- a/OpenSim/Region/OptionalModules/UserStatistics/Sessions_Report.cs +++ b/OpenSim/Region/OptionalModules/UserStatistics/Sessions_Report.cs @@ -52,7 +52,7 @@ namespace OpenSim.Region.UserStatistics SqliteConnection dbConn = (SqliteConnection)pParams["DatabaseConnection"]; List lstSessions = new List(); Hashtable requestvars = (Hashtable) pParams["RequestVars"]; - + string puserUUID = string.Empty; string clientVersionString = string.Empty; @@ -113,7 +113,7 @@ namespace OpenSim.Region.UserStatistics cmd.Parameters.Add(new SqliteParameter(":client_version", clientVersionString)); SqliteDataReader sdr = cmd.ExecuteReader(); - + if (sdr.HasRows) { UUID userUUID = UUID.Zero; @@ -134,7 +134,7 @@ namespace OpenSim.Region.UserStatistics } ShortSessionData ssd = new ShortSessionData(); - + ssd.last_update = Utils.UnixTimeToDateTime((uint)Convert.ToInt32(sdr["last_updated"])); ssd.start_time = Utils.UnixTimeToDateTime((uint)Convert.ToInt32(sdr["start_time"])); ssd.session_id = UUID.Parse(sdr["session_id"].ToString()); @@ -145,8 +145,7 @@ namespace OpenSim.Region.UserStatistics } } sdr.Close(); - sdr.Dispose(); - + cmd.Dispose(); } modeldata["SessionData"] = lstSessions; return modeldata; @@ -249,7 +248,7 @@ TD.align_top { vertical-align: top; } output.Append(sesdata.client_version); HTMLUtil.TD_C(ref output); HTMLUtil.TR_C(ref output); - + } HTMLUtil.TR_O(ref output, ""); HTMLUtil.TD_O(ref output, "align_top", 1, 5); diff --git a/OpenSim/Region/OptionalModules/UserStatistics/SimStatsAJAX.cs b/OpenSim/Region/OptionalModules/UserStatistics/SimStatsAJAX.cs index 06d9e91..513686d 100644 --- a/OpenSim/Region/OptionalModules/UserStatistics/SimStatsAJAX.cs +++ b/OpenSim/Region/OptionalModules/UserStatistics/SimStatsAJAX.cs @@ -50,7 +50,7 @@ namespace OpenSim.Region.UserStatistics public Hashtable ProcessModel(Hashtable pParams) { List m_scene = (List)pParams["Scenes"]; - + Hashtable nh = new Hashtable(); nh.Add("hdata", m_scene); nh.Add("simstats", pParams["SimStats"]); @@ -207,9 +207,9 @@ namespace OpenSim.Region.UserStatistics HTMLUtil.TD_C(ref output); HTMLUtil.TR_C(ref output); HTMLUtil.TABLE_C(ref output); - + } - + return output.ToString(); } @@ -218,7 +218,7 @@ namespace OpenSim.Region.UserStatistics ///
         /// {"REGIONNAME": {
         ///     "region": "REGIONNAME",
-        ///     "timeDilation": "101", 
+        ///     "timeDilation": "101",
         ///     ...     // the rest of the stat info
         ///     },
         ///  ...    // entries for each region
diff --git a/OpenSim/Region/OptionalModules/UserStatistics/WebStatsModule.cs b/OpenSim/Region/OptionalModules/UserStatistics/WebStatsModule.cs
index f6772db..c15b194 100644
--- a/OpenSim/Region/OptionalModules/UserStatistics/WebStatsModule.cs
+++ b/OpenSim/Region/OptionalModules/UserStatistics/WebStatsModule.cs
@@ -57,7 +57,7 @@ namespace OpenSim.Region.UserStatistics
     {
         private static readonly ILog m_log =
             LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
-        
+
         private static SqliteConnection dbConn;
 
         /// 
@@ -67,7 +67,7 @@ namespace OpenSim.Region.UserStatistics
 
         private List m_scenes = new List();
         private Dictionary reports = new Dictionary();
-        private Dictionary m_simstatsCounters = new Dictionary(); 
+        private Dictionary m_simstatsCounters = new Dictionary();
         private const int updateStatsMod = 6;
         private int updateLogMod = 1;
         private volatile int updateLogCounter = 0;
@@ -96,7 +96,7 @@ namespace OpenSim.Region.UserStatistics
 
             //IConfig startupConfig = config.Configs["Startup"];
 
-            dbConn = new SqliteConnection("URI=file:../db/LocalUserStatistics.db,version=3");
+            dbConn = new SqliteConnection("URI=file:LocalUserStatistics.db,version=3");
             dbConn.Open();
             CreateTables(dbConn);
 
@@ -217,7 +217,7 @@ namespace OpenSim.Region.UserStatistics
                     {
                         m_loglines = readLogLines(10);
 
-                        if (updateLogCounter > 10000) 
+                        if (updateLogCounter > 10000)
                             updateLogCounter = 1;
                     }
 
@@ -228,12 +228,12 @@ namespace OpenSim.Region.UserStatistics
                         ss.ConsumeSimStats(stats);
                     }
                 }
-            } 
+            }
             catch (KeyNotFoundException)
             {
             }
         }
-        
+
         private Hashtable HandleUnknownCAPSRequest(Hashtable request)
         {
             //string regpath = request["uri"].ToString();
@@ -257,7 +257,7 @@ namespace OpenSim.Region.UserStatistics
             int response_code = 404;
             string contenttype = "text/html";
             bool jsonFormatOutput = false;
-            
+
             string strOut = string.Empty;
 
             // The request patch should be "/SStats/reportName" where 'reportName'
@@ -288,15 +288,15 @@ namespace OpenSim.Region.UserStatistics
                 repParams["SimStats"] = m_simstatsCounters;
                 repParams["LogLines"] = m_loglines;
                 repParams["Reports"] = reports;
-                
+
                 concurrencyCounter++;
 
-                if (jsonFormatOutput) 
+                if (jsonFormatOutput)
                 {
                     strOut = rep.RenderJson(rep.ProcessModel(repParams));
                     contenttype = "text/json";
                 }
-                else 
+                else
                 {
                     strOut = rep.RenderView(rep.ProcessModel(repParams));
                 }
@@ -312,7 +312,7 @@ namespace OpenSim.Region.UserStatistics
                 }
 
                 concurrencyCounter--;
-                
+
                 response_code = 200;
             }
             else
@@ -463,7 +463,7 @@ namespace OpenSim.Region.UserStatistics
                                       UUID agentID, Caps caps)
         {
 //            m_log.DebugFormat("[WEB STATS MODULE]: Received viewer starts report from {0}", agentID);
- 
+
             UpdateUserStats(ParseViewerStats(request, agentID), dbConn);
 
             return String.Empty;
@@ -525,7 +525,7 @@ namespace OpenSim.Region.UserStatistics
                     }
                 }
             }
-           
+
             usd = uid.session_data;
 
             if (message.Type != OSDType.Map)
@@ -747,16 +747,16 @@ namespace OpenSim.Region.UserStatistics
             );";
 
         private const string SQL_STATS_TABLE_INSERT = @"INSERT OR REPLACE INTO stats_session_data (
-session_id, agent_id, region_id, last_updated, remote_ip, name_f, name_l, avg_agents_in_view, min_agents_in_view, max_agents_in_view, 
-mode_agents_in_view, avg_fps, min_fps, max_fps, mode_fps, a_language, mem_use, meters_traveled, avg_ping, min_ping, max_ping, mode_ping, 
+session_id, agent_id, region_id, last_updated, remote_ip, name_f, name_l, avg_agents_in_view, min_agents_in_view, max_agents_in_view,
+mode_agents_in_view, avg_fps, min_fps, max_fps, mode_fps, a_language, mem_use, meters_traveled, avg_ping, min_ping, max_ping, mode_ping,
 regions_visited, run_time, avg_sim_fps, min_sim_fps, max_sim_fps, mode_sim_fps, start_time, client_version, s_cpu, s_gpu, s_os, s_ram,
 d_object_kb, d_texture_kb, d_world_kb, n_in_kb, n_in_pk, n_out_kb, n_out_pk, f_dropped, f_failed_resends, f_invalid, f_off_circuit,
 f_resent, f_send_packet
 )
 VALUES
 (
-:session_id, :agent_id, :region_id, :last_updated, :remote_ip, :name_f, :name_l, :avg_agents_in_view, :min_agents_in_view, :max_agents_in_view, 
-:mode_agents_in_view, :avg_fps, :min_fps, :max_fps, :mode_fps, :a_language, :mem_use, :meters_traveled, :avg_ping, :min_ping, :max_ping, :mode_ping, 
+:session_id, :agent_id, :region_id, :last_updated, :remote_ip, :name_f, :name_l, :avg_agents_in_view, :min_agents_in_view, :max_agents_in_view,
+:mode_agents_in_view, :avg_fps, :min_fps, :max_fps, :mode_fps, :a_language, :mem_use, :meters_traveled, :avg_ping, :min_ping, :max_ping, :mode_ping,
 :regions_visited, :run_time, :avg_sim_fps, :min_sim_fps, :max_sim_fps, :mode_sim_fps, :start_time, :client_version, :s_cpu, :s_gpu, :s_os, :s_ram,
 :d_object_kb, :d_texture_kb, :d_world_kb, :n_in_kb, :n_in_pk, :n_out_kb, :n_out_pk, :f_dropped, :f_failed_resends, :f_invalid, :f_off_circuit,
 :f_resent, :f_send_packet
@@ -980,7 +980,7 @@ VALUES
 
             if ((srtArr[srtArr.Length - 1]) == 0 || (srtArr[srtArr.Length - 1]) == 1)
                 return 0;
-           
+
             float freqtest = (float)freq.Length / freq.Rank;
 
             for (i = 0; i < freqtest; i++)
@@ -1116,7 +1116,7 @@ VALUES
         public List _sim_fps;
         public List _agents_in_view;
     }
-  
+
     #endregion
 
     public class USimStatsData
@@ -1197,7 +1197,7 @@ VALUES
             m_pendingDownloads = stats.StatsBlock[17].StatValue;
             m_pendingUploads = stats.StatsBlock[18].StatValue;
             m_activeScripts = stats.StatsBlock[19].StatValue;
-            m_scriptLinesPerSecond = stats.StatsBlock[20].StatValue;
+            m_scriptLinesPerSecond = stats.ExtraStatsBlock[0].StatValue;
         }
     }
 }
\ No newline at end of file
diff --git a/OpenSim/Region/OptionalModules/ViewerSupport/CameraOnlyModeModule.cs b/OpenSim/Region/OptionalModules/ViewerSupport/CameraOnlyModeModule.cs
index 7ae4223..54f3ab6 100644
--- a/OpenSim/Region/OptionalModules/ViewerSupport/CameraOnlyModeModule.cs
+++ b/OpenSim/Region/OptionalModules/ViewerSupport/CameraOnlyModeModule.cs
@@ -108,8 +108,7 @@ namespace OpenSim.Region.OptionalModules.ViewerSupport
         {
             if (m_Enabled)
             {
-                IEntityTransferModule et = m_scene.RequestModuleInterface();
-                m_Helper = new SimulatorFeaturesHelper(scene, et);
+                m_Helper = new SimulatorFeaturesHelper(scene);
 
                 ISimulatorFeaturesModule featuresModule = m_scene.RequestModuleInterface();
                 if (featuresModule != null)
@@ -124,7 +123,7 @@ namespace OpenSim.Region.OptionalModules.ViewerSupport
         private void OnSimulatorFeaturesRequest(UUID agentID, ref OSDMap features)
         {
             m_log.DebugFormat("[CAMERA-ONLY MODE]: OnSimulatorFeaturesRequest in {0}", m_scene.RegionInfo.RegionName);
-            if (m_Helper.ShouldSend(agentID) && m_Helper.UserLevel(agentID) <= m_UserLevel)
+            if (m_Helper.UserLevel(agentID) <= m_UserLevel)
             {
                 OSDMap extrasMap;
                 if (features.ContainsKey("OpenSimExtras"))
@@ -162,7 +161,7 @@ namespace OpenSim.Region.OptionalModules.ViewerSupport
                 {
                     foreach (SceneObjectGroup sog in attachs)
                     {
-                        m_log.DebugFormat("[CAMERA-ONLY MODE]: Forcibly detaching attach {0} from {1} in {2}", 
+                        m_log.DebugFormat("[CAMERA-ONLY MODE]: Forcibly detaching attach {0} from {1} in {2}",
                             sog.Name, sp.Name, m_scene.RegionInfo.RegionName);
 
                         m_scene.AttachmentsModule.DetachSingleAttachmentToInv(sp, sog);
diff --git a/OpenSim/Region/OptionalModules/ViewerSupport/DynamicFloaterModule.cs b/OpenSim/Region/OptionalModules/ViewerSupport/DynamicFloaterModule.cs
index e76e8f2..ed44a5a 100644
--- a/OpenSim/Region/OptionalModules/ViewerSupport/DynamicFloaterModule.cs
+++ b/OpenSim/Region/OptionalModules/ViewerSupport/DynamicFloaterModule.cs
@@ -134,7 +134,7 @@ namespace OpenSim.Region.OptionalModules.ViewerSupport
             }
             else
             {
-                using (FileStream fs = File.Open(dialogData.XmlName + ".xml", FileMode.Open))
+                using (FileStream fs = File.Open(dialogData.XmlName + ".xml", FileMode.Open, FileAccess.Read))
                 {
                     using (StreamReader sr = new StreamReader(fs))
                         xml = sr.ReadToEnd().Replace("\n", "");
diff --git a/OpenSim/Region/OptionalModules/ViewerSupport/DynamicMenuModule.cs b/OpenSim/Region/OptionalModules/ViewerSupport/DynamicMenuModule.cs
index d37369c..9833086 100644
--- a/OpenSim/Region/OptionalModules/ViewerSupport/DynamicMenuModule.cs
+++ b/OpenSim/Region/OptionalModules/ViewerSupport/DynamicMenuModule.cs
@@ -131,8 +131,11 @@ namespace OpenSim.Region.OptionalModules.ViewerSupport
             {
                 foreach (MenuItemData d in m_menuItems[UUID.Zero])
                 {
-                    if (d.Mode == UserMode.God && (!m_scene.Permissions.IsGod(agentID)))
-                        continue;
+                    if (!m_scene.Permissions.IsGod(agentID))
+                    {
+                        if (d.Mode == UserMode.RegionManager && (!m_scene.Permissions.IsAdministrator(agentID)))
+                            continue;
+                    }
 
                     OSDMap loc = null;
                     switch (d.Location)
@@ -156,7 +159,7 @@ namespace OpenSim.Region.OptionalModules.ViewerSupport
 
                     if (loc == null)
                         continue;
-                    
+
                     loc[d.Title] = OSD.FromString(d.Title);
                 }
             }
@@ -190,7 +193,7 @@ namespace OpenSim.Region.OptionalModules.ViewerSupport
 
                     if (loc == null)
                         continue;
-                    
+
                     loc[d.Title] = OSD.FromString(d.Title);
                 }
             }
diff --git a/OpenSim/Region/OptionalModules/ViewerSupport/GodNamesModule.cs b/OpenSim/Region/OptionalModules/ViewerSupport/GodNamesModule.cs
index e0537a4..8ed0bb3 100644
--- a/OpenSim/Region/OptionalModules/ViewerSupport/GodNamesModule.cs
+++ b/OpenSim/Region/OptionalModules/ViewerSupport/GodNamesModule.cs
@@ -50,7 +50,7 @@ namespace OpenSim.Region.OptionalModules.ViewerSupport
         private static List m_lastNames = new List();
         private static List m_fullNames = new List();
 
-        public void Initialise(IConfigSource config) 
+        public void Initialise(IConfigSource config)
         {
             IConfig moduleConfig = config.Configs["GodNames"];
 
@@ -133,7 +133,7 @@ namespace OpenSim.Region.OptionalModules.ViewerSupport
                 fnames.Add(name);
             }
             ((OSDMap)namesmap)["full_names"] = fnames;
-            
+
             OSDArray lnames = new OSDArray();
             foreach (string name in m_lastNames) {
                 lnames.Add(name);
diff --git a/OpenSim/Region/OptionalModules/ViewerSupport/SimulatorFeaturesHelper.cs b/OpenSim/Region/OptionalModules/ViewerSupport/SimulatorFeaturesHelper.cs
index 2661522..2c2042d 100644
--- a/OpenSim/Region/OptionalModules/ViewerSupport/SimulatorFeaturesHelper.cs
+++ b/OpenSim/Region/OptionalModules/ViewerSupport/SimulatorFeaturesHelper.cs
@@ -49,90 +49,15 @@ using TeleportFlags = OpenSim.Framework.Constants.TeleportFlags;
 
 namespace OpenSim.Region.OptionalModules.ViewerSupport
 {
-    public class SimulatorFeaturesHelper 
+    public class SimulatorFeaturesHelper
     {
         private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
 
-        private IEntityTransferModule m_TransferModule;
         private Scene m_scene;
 
-        private struct RegionSend {
-            public UUID region;
-            public bool send;
-        };
-        // Using a static cache so that we don't have to perform the time-consuming tests
-        // in ShouldSend on Extra SimFeatures that go on the same response but come from
-        // different modules.
-        // This cached is indexed on the agentID and maps to a list of regions
-        private static ExpiringCache> m_Cache = new ExpiringCache>();
-        private const double TIMEOUT = 1.0; // time in cache
-
-        public SimulatorFeaturesHelper(Scene scene, IEntityTransferModule et)
+        public SimulatorFeaturesHelper(Scene scene)
         {
             m_scene = scene;
-            m_TransferModule = et;
-        }
-
-        public bool ShouldSend(UUID agentID)
-        {
-            List rsendlist;
-            RegionSend rsend;
-            if (m_Cache.TryGetValue(agentID, out rsendlist))
-            {
-                rsend = rsendlist.Find(r => r.region == m_scene.RegionInfo.RegionID);
-                if (rsend.region != UUID.Zero) // Found it
-                {
-                    return rsend.send;
-                }
-            }
-
-            // Relatively complex logic for deciding whether to send the extra SimFeature or not.
-            // This is because the viewer calls this cap to all sims that it knows about,
-            // including the departing sims and non-neighbors (those that are cached).
-            rsend.region = m_scene.RegionInfo.RegionID;
-            rsend.send = false;
-            IClientAPI client = null;
-            int counter = 200;
-
-            // Let's wait a little to see if we get a client here
-            while (!m_scene.TryGetClient(agentID, out client) && counter-- > 0)
-                Thread.Sleep(50);
-
-            if (client != null)
-            {
-                ScenePresence sp = WaitGetScenePresence(agentID);
-
-                if (sp != null)
-                {
-                    // On the receiving region, the call to this cap may arrive before
-                    // the agent is root. Make sure we only proceed from here when the agent
-                    // has been made root
-                    counter = 200;
-                    while ((sp.IsInTransit || sp.IsChildAgent) && counter-- > 0)
-                    {
-                        Thread.Sleep(50);
-                    }
-
-                    // The viewer calls this cap on the departing sims too. Make sure
-                    // that we only proceed after the agent is not in transit anymore.
-                    // The agent must be root and not going anywhere
-                    if (!sp.IsChildAgent && !m_TransferModule.IsInTransit(agentID))
-                        rsend.send = true;
-
-                }
-            }
-            //else
-            //    m_log.DebugFormat("[XXX]: client is null");
-
-
-            if (rsendlist == null)
-            {
-                rsendlist = new List();
-                m_Cache.AddOrUpdate(agentID, rsendlist, TIMEOUT);
-            }
-            rsendlist.Add(rsend);
-
-            return rsend.send;
         }
 
         public int UserLevel(UUID agentID)
@@ -144,28 +69,5 @@ namespace OpenSim.Region.OptionalModules.ViewerSupport
 
             return level;
         }
-
-        protected virtual ScenePresence WaitGetScenePresence(UUID agentID)
-        {
-            int ntimes = 20;
-            ScenePresence sp = null;
-            while ((sp = m_scene.GetScenePresence(agentID)) == null && (ntimes-- > 0))
-                Thread.Sleep(1000);
-
-            if (sp == null)
-                m_log.WarnFormat(
-                    "[XXX]: Did not find presence with id {0} in {1} before timeout",
-                    agentID, m_scene.RegionInfo.RegionName);
-            else
-            {
-                ntimes = 10;
-                while (sp.IsInTransit && (ntimes-- > 0))
-                    Thread.Sleep(1000);
-            }
-
-            return sp;
-        }
-
     }
-
 }
diff --git a/OpenSim/Region/OptionalModules/ViewerSupport/SpecialUIModule.cs b/OpenSim/Region/OptionalModules/ViewerSupport/SpecialUIModule.cs
index 3fe922d..fa8fc66 100644
--- a/OpenSim/Region/OptionalModules/ViewerSupport/SpecialUIModule.cs
+++ b/OpenSim/Region/OptionalModules/ViewerSupport/SpecialUIModule.cs
@@ -102,8 +102,7 @@ namespace OpenSim.Region.OptionalModules.ViewerSupport
         {
             if (m_Enabled)
             {
-                IEntityTransferModule et = m_scene.RequestModuleInterface();
-                m_Helper = new SimulatorFeaturesHelper(scene, et);
+                m_Helper = new SimulatorFeaturesHelper(scene);
 
                 ISimulatorFeaturesModule featuresModule = m_scene.RequestModuleInterface();
                 if (featuresModule != null)
@@ -118,7 +117,7 @@ namespace OpenSim.Region.OptionalModules.ViewerSupport
         private void OnSimulatorFeaturesRequest(UUID agentID, ref OSDMap features)
         {
             m_log.DebugFormat("[SPECIAL UI]: OnSimulatorFeaturesRequest in {0}", m_scene.RegionInfo.RegionName);
-            if (m_Helper.ShouldSend(agentID) && m_Helper.UserLevel(agentID) <= m_UserLevel)
+            if (m_Helper.UserLevel(agentID) <= m_UserLevel)
             {
                 OSDMap extrasMap;
                 OSDMap specialUI = new OSDMap();
diff --git a/OpenSim/Region/OptionalModules/World/AutoBackup/AutoBackupModule.cs b/OpenSim/Region/OptionalModules/World/AutoBackup/AutoBackupModule.cs
index ceb3332..a14d819 100644
--- a/OpenSim/Region/OptionalModules/World/AutoBackup/AutoBackupModule.cs
+++ b/OpenSim/Region/OptionalModules/World/AutoBackup/AutoBackupModule.cs
@@ -59,70 +59,58 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
     /// 
     /// 
     /// Config Settings Documentation.
-    /// Each configuration setting can be specified in two places: OpenSim.ini or Regions.ini.
-    /// If specified in Regions.ini, the settings should be within the region's section name.
-    /// If specified in OpenSim.ini, the settings should be within the [AutoBackupModule] section.
+    /// Configuration setting can be specified in two places: OpenSim.ini and/or Regions.ini.
+    ///
+    /// OpenSim.ini only settings section [AutoBackupModule]
+    /// AutoBackupModuleEnabled: True/False. Default: False. If True, use the auto backup module.
+    ///     if false module is disable and all rest is ignored
+    /// AutoBackupInterval: Double, non-negative value. Default: 720 (12 hours).
+    /// 	The number of minutes between each backup attempt.
+    /// AutoBackupDir: String. Default: "." (the current directory).
+    /// 	A directory (absolute or relative) where backups should be saved.
+    /// AutoBackupKeepFilesForDays remove files older than this number of days. 0  disables
+    /// 
+    /// Next can be set on OpenSim.ini, as default, and or per region in Regions.ini
     /// Region-specific settings take precedence.
     /// 
-    /// AutoBackupModuleEnabled: True/False. Default: False. If True, use the auto backup module. This setting does not support per-region basis.
-    ///     All other settings under [AutoBackupModule] are ignored if AutoBackupModuleEnabled is false, even per-region settings!
-    /// AutoBackup: True/False. Default: False. If True, activate auto backup functionality. 
-    /// 	This is the only required option for enabling auto-backup; the other options have sane defaults. 
-    /// 	If False for a particular region, the auto-backup module becomes a no-op for the region, and all other AutoBackup* settings are ignored.
-    /// 	If False globally (the default), only regions that specifically override it in Regions.ini will get AutoBackup functionality.
-    /// AutoBackupInterval: Double, non-negative value. Default: 720 (12 hours). 
-    /// 	The number of minutes between each backup attempt. 
-    /// 	If a negative or zero value is given, it is equivalent to setting AutoBackup = False.
-    /// AutoBackupBusyCheck: True/False. Default: True. 
-    /// 	If True, we will only take an auto-backup if a set of conditions are met. 
-    /// 	These conditions are heuristics to try and avoid taking a backup when the sim is busy.
+    /// AutoBackup: True/False. Default: False. If True, activate auto backup functionality.
+    ///     controls backup per region, with default optionaly set on OpenSim.ini
+    
     /// AutoBackupSkipAssets
     ///     If true, assets are not saved to the oar file. Considerably reduces impact on simulator when backing up. Intended for when assets db is backed up separately
     /// AutoBackupKeepFilesForDays
     ///     Backup files older than this value (in days) are deleted during the current backup process, 0 will disable this and keep all backup files indefinitely
-    /// AutoBackupScript: String. Default: not specified (disabled). 
+    /// AutoBackupScript: String. Default: not specified (disabled).
     /// 	File path to an executable script or binary to run when an automatic backup is taken.
     ///  The file should really be (Windows) an .exe or .bat, or (Linux/Mac) a shell script or binary.
     ///  Trying to "run" directories, or things with weird file associations on Win32, might cause unexpected results!
-    /// 	argv[1] of the executed file/script will be the file name of the generated OAR. 
+    /// 	argv[1] of the executed file/script will be the file name of the generated OAR.
     /// 	If the process can't be spawned for some reason (file not found, no execute permission, etc), write a warning to the console.
     /// AutoBackupNaming: string. Default: Time.
     /// 	One of three strings (case insensitive):
     /// 	"Time": Current timestamp is appended to file name. An existing file will never be overwritten.
-    ///  "Sequential": A number is appended to the file name. So if RegionName_x.oar exists, we'll save to RegionName_{x+1}.oar next. An existing file will never be overwritten.
-    ///  "Overwrite": Always save to file named "${AutoBackupDir}/RegionName.oar", even if we have to overwrite an existing file.
-    /// AutoBackupDir: String. Default: "." (the current directory).
-    /// 	A directory (absolute or relative) where backups should be saved.
-    /// AutoBackupDilationThreshold: float. Default: 0.5. Lower bound on time dilation required for BusyCheck heuristics to pass.
-    ///  If the time dilation is below this value, don't take a backup right now.
-    /// AutoBackupAgentThreshold: int. Default: 10. Upper bound on # of agents in region required for BusyCheck heuristics to pass.
-    ///  If the number of agents is greater than this value, don't take a backup right now
-    /// Save memory by setting low initial capacities. Minimizes impact in common cases of all regions using same interval, and instances hosting 1 ~ 4 regions.
-    /// Also helps if you don't want AutoBackup at all.
+    ///     "Sequential": A number is appended to the file name. So if RegionName_x.oar exists, we'll save to RegionName_{x+1}.oar next. An existing file will never be overwritten.
+    ///     "Overwrite": Always save to file named "${AutoBackupDir}/RegionName.oar", even if we have to overwrite an existing file.
     /// 
     [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "AutoBackupModule")]
     public class AutoBackupModule : ISharedRegionModule
     {
         private static readonly ILog m_log =
             LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
-        private readonly Dictionary m_pendingSaves = new Dictionary(1);
         private readonly AutoBackupModuleState m_defaultState = new AutoBackupModuleState();
         private readonly Dictionary m_states =
             new Dictionary(1);
-        private readonly Dictionary> m_timerMap =
-            new Dictionary>(1);
-        private readonly Dictionary m_timers = new Dictionary(1);
 
         private delegate T DefaultGetter(string settingName, T defaultValue);
         private bool m_enabled;
         private ICommandConsole m_console;
         private List m_Scenes = new List ();
-
-
-        /// 
-        /// Whether the shared module should be enabled at all. NOT the same as m_Enabled in AutoBackupModuleState!
-        /// 
-        private bool m_closed;
+        private Timer m_masterTimer;
+        private bool m_busy;
+        private int m_KeepFilesForDays = -1;
+        private string m_backupDir;
+        private bool m_doneFirst;
+        private double m_baseInterval;
 
         private IConfigSource m_configSource;
 
@@ -159,36 +147,38 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
         void IRegionModuleBase.Initialise(IConfigSource source)
         {
             // Determine if we have been enabled at all in OpenSim.ini -- this is part and parcel of being an optional module
-            this.m_configSource = source;
+            m_configSource = source;
             IConfig moduleConfig = source.Configs["AutoBackupModule"];
             if (moduleConfig == null)
             {
-                this.m_enabled = false;
+                m_enabled = false;
                 return;
             }
-            else
-            {
-                this.m_enabled = moduleConfig.GetBoolean("AutoBackupModuleEnabled", false);
-                if (this.m_enabled)
-                {
-                    m_log.Info("[AUTO BACKUP]: AutoBackupModule enabled");
-                }
-                else
-                {
-                    return;
-                }
-            }
 
-            Timer defTimer = new Timer(43200000);
-            this.m_defaultState.Timer = defTimer;
-            this.m_timers.Add(43200000, defTimer);
-            defTimer.Elapsed += this.HandleElapsed;
-            defTimer.AutoReset = true;
-            defTimer.Start();
+            m_enabled = moduleConfig.GetBoolean("AutoBackupModuleEnabled", false);
+            if(!m_enabled)
+                return;
+
+            ParseDefaultConfig(moduleConfig);
+            if(!m_enabled)
+                return;
+
+            m_log.Debug("[AUTO BACKUP]: Default config:");
+            m_log.Debug(m_defaultState.ToString());
+
+            m_log.Info("[AUTO BACKUP]: AutoBackupModule enabled");
+            m_masterTimer = new Timer();
+            m_masterTimer.Interval = m_baseInterval;
+            m_masterTimer.Elapsed += HandleElapsed;
+            m_masterTimer.AutoReset = false;
+
+            m_console = MainConsole.Instance;
 
-            AutoBackupModuleState abms = this.ParseConfig(null, true);
-            m_log.Debug("[AUTO BACKUP]: Here is the default config:");
-            m_log.Debug(abms.ToString());
+            m_console.Commands.AddCommand (
+                        "AutoBackup", true, "dooarbackup",
+                        "dooarbackup  | ALL",
+                        "saves the single region  to a oar or ALL regions in instance to oars, using same settings as AutoBackup. Note it restarts time interval", DoBackup);
+            m_busy = true;            
         }
 
         /// 
@@ -196,13 +186,11 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
         /// 
         void IRegionModuleBase.Close()
         {
-            if (!this.m_enabled)
-            {
+            if (!m_enabled)
                 return;
-            }
 
             // We don't want any timers firing while the sim's coming down; strange things may happen.
-            this.StopAllTimers();
+            m_masterTimer.Dispose();
         }
 
         /// 
@@ -211,18 +199,11 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
         /// 
         void IRegionModuleBase.AddRegion (Scene scene)
         {
-            if (!this.m_enabled) {
+            if (!m_enabled)
                 return;
-            }
-            lock (m_Scenes) {
-                m_Scenes.Add (scene);
-            }
-            m_console = MainConsole.Instance;
 
-            m_console.Commands.AddCommand (
-                "AutoBackup", false, "dobackup",
-                "dobackup",
-                "do backup.", DoBackup);
+            lock (m_Scenes)
+                m_Scenes.Add (scene);
         }
 
         /// 
@@ -231,28 +212,14 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
         /// The scene (region) to stop performing AutoBackup on.
         void IRegionModuleBase.RemoveRegion(Scene scene)
         {
-            if (!this.m_enabled)
-            {
+            if (m_enabled)
                 return;
-            }
-            m_Scenes.Remove (scene);
-            if (this.m_states.ContainsKey(scene))
-            {
-                AutoBackupModuleState abms = this.m_states[scene];
 
-                // Remove this scene out of the timer map list
-                Timer timer = abms.Timer;
-                List list = this.m_timerMap[timer];
-                list.Remove(scene);
-
-                // Shut down the timer if this was the last scene for the timer
-                if (list.Count == 0)
-                {
-                    this.m_timerMap.Remove(timer);
-                    this.m_timers.Remove(timer.Interval);
-                    timer.Close();
-                }
-                this.m_states.Remove(scene);
+            lock(m_Scenes)
+            {
+                if (m_states.ContainsKey(scene))
+                    m_states.Remove(scene);
+                m_Scenes.Remove(scene);
             }
         }
 
@@ -263,22 +230,29 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
         /// The scene to (possibly) perform AutoBackup on.
         void IRegionModuleBase.RegionLoaded(Scene scene)
         {
-            if (!this.m_enabled)
-            {
+            if (!m_enabled)
                 return;
-            }
 
             // This really ought not to happen, but just in case, let's pretend it didn't...
             if (scene == null)
-            {
                 return;
-            }
 
-            AutoBackupModuleState abms = this.ParseConfig(scene, false);
-            m_log.Debug("[AUTO BACKUP]: Config for " + scene.RegionInfo.RegionName);
-            m_log.Debug((abms == null ? "DEFAULT" : abms.ToString()));
+            AutoBackupModuleState abms = ParseConfig(scene);
+            if(abms == null)
+            {
+                m_log.Debug("[AUTO BACKUP]: Config for " + scene.RegionInfo.RegionName);
+                m_log.Debug("DEFAULT");
+                abms = new AutoBackupModuleState(m_defaultState);
+            }
+            else
+            {
+                m_log.Debug("[AUTO BACKUP]: Config for " + scene.RegionInfo.RegionName);
+                m_log.Debug(abms.ToString());
+            }
 
             m_states.Add(scene, abms);
+            m_busy = false;
+            m_masterTimer.Start();
         }
 
         /// 
@@ -292,356 +266,174 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
 
         private void DoBackup (string module, string[] args)
         {
-            if (args.Length != 2) {
-                MainConsole.Instance.OutputFormat ("Usage: dobackup ");
+            if (!m_enabled)
                 return;
-            }  
-            bool found = false;
-            string name = args [1];
-            lock (m_Scenes) {
-                foreach (Scene s in m_Scenes) {
-                    string test = s.Name.ToString ();
-                    if (test == name) {
-                        found = true;
-                        DoRegionBackup (s);
-                    }
-                }
-                if (!found) {
-                    MainConsole.Instance.OutputFormat ("No such region {0}. Nothing to backup", name);
-                }
-            }
-        }
 
-        /// 
-        /// Set up internal state for a given scene. Fairly complex code.
-        /// When this method returns, we've started auto-backup timers, put members in Dictionaries, and created a State object for this scene.
-        /// 
-        /// The scene to look at.
-        /// Whether this call is intended to figure out what we consider the "default" config (applied to all regions unless overridden by per-region settings).
-        /// An AutoBackupModuleState contains most information you should need to know relevant to auto-backup, as applicable to a single region.
-        private AutoBackupModuleState ParseConfig(IScene scene, bool parseDefault)
-        {
-            string sRegionName;
-            string sRegionLabel;
-//            string prepend;
-            AutoBackupModuleState state;
-
-            if (parseDefault)
-            {
-                sRegionName = null;
-                sRegionLabel = "DEFAULT";
-//                prepend = "";
-                state = this.m_defaultState;
-            }
-            else
-            {
-                sRegionName = scene.RegionInfo.RegionName;
-                sRegionLabel = sRegionName;
-//                prepend = sRegionName + ".";
-                state = null;
-            }
-
-            // Read the config settings and set variables.
-            IConfig regionConfig = (scene != null ? scene.Config.Configs[sRegionName] : null);
-            IConfig config = this.m_configSource.Configs["AutoBackupModule"];
-            if (config == null)
+            if (args.Length != 2)
             {
-                // defaultState would be disabled too if the section doesn't exist.
-                state = this.m_defaultState;
-                return state;
-            }
-
-            bool tmpEnabled = ResolveBoolean("AutoBackup", this.m_defaultState.Enabled, config, regionConfig);
-            if (state == null && tmpEnabled != this.m_defaultState.Enabled)
-                //Varies from default state
-            {
-                state = new AutoBackupModuleState();
+                MainConsole.Instance.OutputFormat ("Usage: dooarbackup ");
+                return;
             }
 
-            if (state != null)
+            if(m_busy)
             {
-                state.Enabled = tmpEnabled;
+                MainConsole.Instance.OutputFormat ("Already doing a backup, please try later");
+                return;
             }
 
-            // If you don't want AutoBackup, we stop.
-            if ((state == null && !this.m_defaultState.Enabled) || (state != null && !state.Enabled))
-            {
-                return state;
-            }
-            else
-            {
-                m_log.Info("[AUTO BACKUP]: Region " + sRegionLabel + " is AutoBackup ENABLED.");
-            }
+            m_masterTimer.Stop();
+            m_busy = true;    
 
-            // Borrow an existing timer if one exists for the same interval; otherwise, make a new one.
-            double interval =
-                this.ResolveDouble("AutoBackupInterval", this.m_defaultState.IntervalMinutes,
-                 config, regionConfig) * 60000.0;
-            if (state == null && interval != this.m_defaultState.IntervalMinutes * 60000.0)
-            {
-                state = new AutoBackupModuleState();
-            }
+            bool found = false;
+            string name = args [1];
+            Scene[] scenes;
+            lock (m_Scenes)
+                scenes = m_Scenes.ToArray();
 
-            if (this.m_timers.ContainsKey(interval))
-            {
-                if (state != null)
-                {
-                    state.Timer = this.m_timers[interval];
-                }
-                m_log.Debug("[AUTO BACKUP]: Reusing timer for " + interval + " msec for region " +
-                            sRegionLabel);
-            }
-            else
-            {
-                // 0 or negative interval == do nothing.
-                if (interval <= 0.0 && state != null)
-                {
-                    state.Enabled = false;
-                    return state;
-                }
-                if (state == null)
-                {
-                    state = new AutoBackupModuleState();
-                }
-                Timer tim = new Timer(interval);
-                state.Timer = tim;
-                //Milliseconds -> minutes
-                this.m_timers.Add(interval, tim);
-                tim.Elapsed += this.HandleElapsed;
-                tim.AutoReset = true;
-                tim.Start();
-            }
+            if(scenes == null)
+                return;
 
-            // Add the current region to the list of regions tied to this timer.
-            if (scene != null)
+            Scene s;
+            try
             {
-                if (state != null)
+                if(name == "ALL")
                 {
-                    if (this.m_timerMap.ContainsKey(state.Timer))
+                    for(int i = 0; i < scenes.Length; i++)
                     {
-                        this.m_timerMap[state.Timer].Add(scene);
-                    }
-                    else
-                    {
-                        List scns = new List(1);
-                        scns.Add(scene);
-                        this.m_timerMap.Add(state.Timer, scns);
+                        s = scenes[i];
+                        DoRegionBackup(s);
+                        if (!m_enabled)
+                            return;
                     }
+                    return;
                 }
-                else
+
+                for(int i = 0; i < scenes.Length; i++)
                 {
-                    if (this.m_timerMap.ContainsKey(this.m_defaultState.Timer))
+                    s = scenes[i];
+                    if (s.Name == name)
                     {
-                        this.m_timerMap[this.m_defaultState.Timer].Add(scene);
-                    }
-                    else
-                    {
-                        List scns = new List(1);
-                        scns.Add(scene);
-                        this.m_timerMap.Add(this.m_defaultState.Timer, scns);
+                        found = true;
+                        DoRegionBackup(s);
+                        break;
                     }
                 }
             }
-
-            bool tmpBusyCheck = ResolveBoolean("AutoBackupBusyCheck",
-                                                  this.m_defaultState.BusyCheck, config, regionConfig);
-            if (state == null && tmpBusyCheck != this.m_defaultState.BusyCheck)
+            catch { }
+            finally
             {
-                state = new AutoBackupModuleState();
-            }
+                if (m_enabled)
+                    m_masterTimer.Start();
+                m_busy = false;
+            }               
+            if (!found)
+                    MainConsole.Instance.OutputFormat ("No such region {0}. Nothing to backup", name);
+        }
 
-            if (state != null)
-            {
-                state.BusyCheck = tmpBusyCheck;
-            }
+        private void ParseDefaultConfig(IConfig config)
+        {          
 
-            // Included Option To Skip Assets
-            bool tmpSkipAssets = ResolveBoolean("AutoBackupSkipAssets",
-                                                  this.m_defaultState.SkipAssets, config, regionConfig);
-            if (state == null && tmpSkipAssets != this.m_defaultState.SkipAssets)
+            m_backupDir = ".";
+            string backupDir = config.GetString("AutoBackupDir", ".");
+            if (backupDir != ".")
             {
-                state = new AutoBackupModuleState();
+                try
+                {
+                DirectoryInfo dirinfo = new DirectoryInfo(backupDir);
+                if (!dirinfo.Exists)
+                    dirinfo.Create();
+                }
+                catch (Exception e)
+                {
+                    m_enabled = false;
+                    m_log.WarnFormat("[AUTO BACKUP]: Error accessing backup folder {0}. Module disabled. {1}",
+                            backupDir, e);
+                    return;
+                }
             }
+            m_backupDir = backupDir;
 
-            if (state != null)
-            {
-                state.SkipAssets = tmpSkipAssets;
-            }
+            double interval = config.GetDouble("AutoBackupInterval", 720);
+            interval *= 60000.0;
+            m_baseInterval = interval;
 
             // How long to keep backup files in days, 0 Disables this feature
-            int tmpKeepFilesForDays = ResolveInt("AutoBackupKeepFilesForDays",
-                                                  this.m_defaultState.KeepFilesForDays, config, regionConfig);
-            if (state == null && tmpKeepFilesForDays != this.m_defaultState.KeepFilesForDays)
-            {
-                state = new AutoBackupModuleState();
-            }
+            m_KeepFilesForDays = config.GetInt("AutoBackupKeepFilesForDays",m_KeepFilesForDays);
 
-            if (state != null)
-            {
-                state.KeepFilesForDays = tmpKeepFilesForDays;
-            }
+            m_defaultState.Enabled = config.GetBoolean("AutoBackup", m_defaultState.Enabled);
+
+            m_defaultState.SkipAssets = config.GetBoolean("AutoBackupSkipAssets",m_defaultState.SkipAssets);
 
             // Set file naming algorithm
-            string stmpNamingType = ResolveString("AutoBackupNaming",
-                                                     this.m_defaultState.NamingType.ToString(), config, regionConfig);
+            string stmpNamingType = config.GetString("AutoBackupNaming", m_defaultState.NamingType.ToString());
             NamingType tmpNamingType;
             if (stmpNamingType.Equals("Time", StringComparison.CurrentCultureIgnoreCase))
-            {
                 tmpNamingType = NamingType.Time;
-            }
             else if (stmpNamingType.Equals("Sequential", StringComparison.CurrentCultureIgnoreCase))
-            {
                 tmpNamingType = NamingType.Sequential;
-            }
             else if (stmpNamingType.Equals("Overwrite", StringComparison.CurrentCultureIgnoreCase))
-            {
                 tmpNamingType = NamingType.Overwrite;
-            }
             else
             {
-                m_log.Warn("Unknown naming type specified for region " + sRegionLabel + ": " +
-                           stmpNamingType);
+                m_log.Warn("Unknown naming type specified for Default");
                 tmpNamingType = NamingType.Time;
             }
+            m_defaultState.NamingType = tmpNamingType;
 
-            if (state == null && tmpNamingType != this.m_defaultState.NamingType)
-            {
-                state = new AutoBackupModuleState();
-            }
+            m_defaultState.Script = config.GetString("AutoBackupScript", m_defaultState.Script);
 
-            if (state != null)
-            {
-                state.NamingType = tmpNamingType;
-            }
+        }
 
-            string tmpScript = ResolveString("AutoBackupScript",
-                                                this.m_defaultState.Script, config, regionConfig);
-            if (state == null && tmpScript != this.m_defaultState.Script)
-            {
-                state = new AutoBackupModuleState();
-            }
+        /// 
+        /// Set up internal state for a given scene. Fairly complex code.
+        /// When this method returns, we've started auto-backup timers, put members in Dictionaries, and created a State object for this scene.
+        /// 
+        /// The scene to look at.
+        /// Whether this call is intended to figure out what we consider the "default" config (applied to all regions unless overridden by per-region settings).
+        /// An AutoBackupModuleState contains most information you should need to know relevant to auto-backup, as applicable to a single region.
+        private AutoBackupModuleState ParseConfig(IScene scene)
+        {
+            if(scene == null)
+                return null;
 
-            if (state != null)
-            {
-                state.Script = tmpScript;
-            }
+            string sRegionName;
+            AutoBackupModuleState state = null;
 
-            string tmpBackupDir = ResolveString("AutoBackupDir", ".", config, regionConfig);
-            if (state == null && tmpBackupDir != this.m_defaultState.BackupDir)
-            {
-                state = new AutoBackupModuleState();
-            }
+            sRegionName = scene.RegionInfo.RegionName;
 
-            if (state != null)
-            {
-                state.BackupDir = tmpBackupDir;
-                // Let's give the user some convenience and auto-mkdir
-                if (state.BackupDir != ".")
-                {
-                    try
-                    {
-                        DirectoryInfo dirinfo = new DirectoryInfo(state.BackupDir);
-                        if (!dirinfo.Exists)
-                        {
-                            dirinfo.Create();
-                        }
-                    }
-                    catch (Exception e)
-                    {
-                        m_log.Warn(
-                            "[AUTO BACKUP]: BAD NEWS. You won't be able to save backups to directory " +
-                            state.BackupDir +
-                            " because it doesn't exist or there's a permissions issue with it. Here's the exception.",
-                            e);
-                    }
-                }
-            }
+            // Read the config settings and set variables.
+            IConfig regionConfig = scene.Config.Configs[sRegionName];
+            if (regionConfig == null)
+                return null;
 
-            if(state == null)
-                return m_defaultState;
+            state = new AutoBackupModuleState();
 
-            return state;
-        }
+            state.Enabled = regionConfig.GetBoolean("AutoBackup", m_defaultState.Enabled);
 
-        /// 
-        /// Helper function for ParseConfig.
-        /// 
-        /// 
-        /// 
-        /// 
-        /// 
-        /// 
-        private bool ResolveBoolean(string settingName, bool defaultValue, IConfig global, IConfig local)
-        {
-            if(local != null)
-            {
-                return local.GetBoolean(settingName, global.GetBoolean(settingName, defaultValue));
-            }
-            else
-            {
-                return global.GetBoolean(settingName, defaultValue);
-            }
-        }
+            // Included Option To Skip Assets
+            state.SkipAssets = regionConfig.GetBoolean("AutoBackupSkipAssets", m_defaultState.SkipAssets);
 
-        /// 
-        /// Helper function for ParseConfig.
-        /// 
-        /// 
-        /// 
-        /// 
-        /// 
-        /// 
-        private double ResolveDouble(string settingName, double defaultValue, IConfig global, IConfig local)
-        {
-            if (local != null)
-            {
-                return local.GetDouble(settingName, global.GetDouble(settingName, defaultValue));
-            }
+            // Set file naming algorithm
+            string stmpNamingType = regionConfig.GetString("AutoBackupNaming", m_defaultState.NamingType.ToString());
+            NamingType tmpNamingType;
+            if (stmpNamingType.Equals("Time", StringComparison.CurrentCultureIgnoreCase))
+                tmpNamingType = NamingType.Time;
+            else if (stmpNamingType.Equals("Sequential", StringComparison.CurrentCultureIgnoreCase))
+                tmpNamingType = NamingType.Sequential;
+            else if (stmpNamingType.Equals("Overwrite", StringComparison.CurrentCultureIgnoreCase))
+                tmpNamingType = NamingType.Overwrite;
             else
             {
-                return global.GetDouble(settingName, defaultValue);
+                m_log.Warn("Unknown naming type specified for region " + sRegionName + ": " +
+                           stmpNamingType);
+                tmpNamingType = NamingType.Time;
             }
-        }
+            m_defaultState.NamingType = tmpNamingType;
 
-        /// 
-        /// Helper function for ParseConfig.
-        /// 
-        /// 
-        /// 
-        /// 
-        /// 
-        /// 
-        private int ResolveInt(string settingName, int defaultValue, IConfig global, IConfig local)
-        {
-            if (local != null)
-            {
-                return local.GetInt(settingName, global.GetInt(settingName, defaultValue));
-            }
-            else
-            {
-                return global.GetInt(settingName, defaultValue);
-            }
+            state.Script = regionConfig.GetString("AutoBackupScript", m_defaultState.Script);
+            return state;
         }
 
-        /// 
-        /// Helper function for ParseConfig.
-        /// 
-        /// 
-        /// 
-        /// 
-        /// 
-        /// 
-        private string ResolveString(string settingName, string defaultValue, IConfig global, IConfig local)
-        {
-            if (local != null)
-            {
-                return local.GetString(settingName, global.GetString(settingName, defaultValue));
-            }
-            else
-            {
-                return global.GetString(settingName, defaultValue);
-            }
-        }
 
         /// 
         /// Called when any auto-backup timer expires. This starts the code path for actually performing a backup.
@@ -650,63 +442,27 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
         /// 
         private void HandleElapsed(object sender, ElapsedEventArgs e)
         {
-            // TODO: heuristic thresholds are per-region, so we should probably run heuristics once per region
-            // XXX: Running heuristics once per region could add undue performance penalty for something that's supposed to
-            // check whether the region is too busy! Especially on sims with LOTS of regions.
-            // Alternative: make heuristics thresholds global to the module rather than per-region. Less flexible,
-            //  but would allow us to be semantically correct while being easier on perf.
-            // Alternative 2: Run heuristics once per unique set of heuristics threshold parameters! Ay yi yi...
-            // Alternative 3: Don't support per-region heuristics at all; just accept them as a global only parameter.
-            // Since this is pretty experimental, I haven't decided which alternative makes the most sense.
-            if (this.m_closed)
-            {
+            if (!m_enabled || m_busy)
                 return;
-            }
-            bool heuristicsRun = false;
-            bool heuristicsPassed = false;
-            if (!this.m_timerMap.ContainsKey((Timer) sender))
+
+            m_busy = true;
+            if(m_doneFirst && m_KeepFilesForDays > 0)
+                RemoveOldFiles();
+
+            foreach (IScene scene in m_Scenes)
             {
-                m_log.Debug("[AUTO BACKUP]: Code-up error: timerMap doesn't contain timer " + sender);
+                if (!m_enabled)
+                    return;
+                DoRegionBackup(scene);
             }
 
-            List tmap = this.m_timerMap[(Timer) sender];
-            if (tmap != null && tmap.Count > 0)
+            if (m_enabled)
             {
-                foreach (IScene scene in tmap)
-                {
-                    AutoBackupModuleState state = this.m_states[scene];
-                    bool heuristics = state.BusyCheck;
-
-                    // Fast path: heuristics are on; already ran em; and sim is fine; OR, no heuristics for the region.
-                    if ((heuristics && heuristicsRun && heuristicsPassed) || !heuristics)
-                    {
-                        this.DoRegionBackup(scene);
-                        // Heuristics are on; ran but we're too busy -- keep going. Maybe another region will have heuristics off!
-                    }
-                    else if (heuristicsRun)
-                    {
-                        m_log.Info("[AUTO BACKUP]: Heuristics: too busy to backup " +
-                                   scene.RegionInfo.RegionName + " right now.");
-                        continue;
-                        // Logical Deduction: heuristics are on but haven't been run
-                    }
-                    else
-                    {
-                        heuristicsPassed = this.RunHeuristics(scene);
-                        heuristicsRun = true;
-                        if (!heuristicsPassed)
-                        {
-                            m_log.Info("[AUTO BACKUP]: Heuristics: too busy to backup " +
-                                       scene.RegionInfo.RegionName + " right now.");
-                            continue;
-                        }
-                        this.DoRegionBackup(scene);
-                    }
-
-                    // Remove Old Backups
-                    this.RemoveOldFiles(state);
-                }
+                m_masterTimer.Start();
+                m_busy = false;
             }
+
+            m_doneFirst = true;
         }
 
         /// 
@@ -723,21 +479,29 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
                 return;
             }
 
-            AutoBackupModuleState state = this.m_states[scene];
+            m_busy = true;
+
+            AutoBackupModuleState state;
+            if(!m_states.TryGetValue(scene, out state))
+                return;
+
+            if(state == null || !state.Enabled)
+                return;
+
             IRegionArchiverModule iram = scene.RequestModuleInterface();
+            if(iram == null)
+                return;
+
             string savePath = BuildOarPath(scene.RegionInfo.RegionName,
-                                                state.BackupDir,
+                                                m_backupDir,
                                                 state.NamingType);
             if (savePath == null)
             {
                 m_log.Warn("[AUTO BACKUP]: savePath is null in HandleElapsed");
                 return;
             }
-            Guid guid = Guid.NewGuid();
-            m_pendingSaves.Add(guid, scene);
-            state.LiveRequests.Add(guid, savePath);
-            ((Scene) scene).EventManager.OnOarFileSaved += new EventManager.OarFileSaved(EventManager_OnOarFileSaved);
 
+            Guid guid = Guid.NewGuid();
             m_log.Info("[AUTO BACKUP]: Backing up region " + scene.RegionInfo.RegionName);
 
             // Must pass options, even if dictionary is empty!
@@ -747,47 +511,37 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
                 options["noassets"] = true;
 
             iram.ArchiveRegion(savePath, guid, options);
+            ExecuteScript(state.Script, savePath);
         }
 
         // For the given state, remove backup files older than the states KeepFilesForDays property
-        private void RemoveOldFiles(AutoBackupModuleState state)
+        private void RemoveOldFiles()
         {
-            // 0 Means Disabled, Keep Files Indefinitely
-            if (state.KeepFilesForDays > 0)
+            string[] files;
+            try
             {
-                string[] files = Directory.GetFiles(state.BackupDir, "*.oar");
-                DateTime CuttOffDate = DateTime.Now.AddDays(0 - state.KeepFilesForDays);
-
-                foreach (string file in files)
-                {
-                    try
-                    {
-                        FileInfo fi = new FileInfo(file);
-                        if (fi.CreationTime < CuttOffDate)
-                            fi.Delete();
-                    }
-                    catch (Exception Ex)
-                    {
-                        m_log.Error("[AUTO BACKUP]: Error deleting old backup file '" + file + "': " + Ex.Message);
-                    }
-                }
+                files = Directory.GetFiles(m_backupDir, "*.oar");
+            }
+            catch (Exception Ex)
+            {
+                m_log.Error("[AUTO BACKUP]: Error reading backup folder " + m_backupDir + ": " + Ex.Message);
+                return;
             }
-        }
 
-        /// 
-        /// Called by the Event Manager when the OnOarFileSaved event is fired.
-        /// 
-        /// 
-        /// 
-        void EventManager_OnOarFileSaved(Guid guid, string message)
-        {
-            // Ignore if the OAR save is being done by some other part of the system
-            if (m_pendingSaves.ContainsKey(guid))
+            DateTime CuttOffDate = DateTime.Now.AddDays(-m_KeepFilesForDays);
+
+            foreach (string file in files)
             {
-                AutoBackupModuleState abms = m_states[(m_pendingSaves[guid])];
-                ExecuteScript(abms.Script, abms.LiveRequests[guid]);
-                m_pendingSaves.Remove(guid);
-                abms.LiveRequests.Remove(guid);
+                try
+                {
+                    FileInfo fi = new FileInfo(file);
+                    if (fi.CreationTime < CuttOffDate)
+                        fi.Delete();
+                }
+                catch (Exception Ex)
+                {
+                    m_log.Error("[AUTO BACKUP]: Error deleting old backup file '" + file + "': " + Ex.Message);
+                }
             }
         }
 
@@ -817,63 +571,6 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
             return output;
         }
 
-        /// Return value of true ==> not too busy; false ==> too busy to backup an OAR right now, or error.
-        private bool RunHeuristics(IScene region)
-        {
-            try
-            {
-                return this.RunTimeDilationHeuristic(region) && this.RunAgentLimitHeuristic(region);
-            }
-            catch (Exception e)
-            {
-                m_log.Warn("[AUTO BACKUP]: Exception in RunHeuristics", e);
-                return false;
-            }
-        }
-
-        /// 
-        /// If the time dilation right at this instant is less than the threshold specified in AutoBackupDilationThreshold (default 0.5),
-        /// then we return false and trip the busy heuristic's "too busy" path (i.e. don't save an OAR).
-        /// AutoBackupDilationThreshold is a _LOWER BOUND_. Lower Time Dilation is bad, so if you go lower than our threshold, it's "too busy".
-        /// 
-        /// 
-        /// Returns true if we're not too busy; false means we've got worse time dilation than the threshold.
-        private bool RunTimeDilationHeuristic(IScene region)
-        {
-            string regionName = region.RegionInfo.RegionName;
-            return region.TimeDilation >=
-                   this.m_configSource.Configs["AutoBackupModule"].GetFloat(
-                       regionName + ".AutoBackupDilationThreshold", 0.5f);
-        }
-
-        /// 
-        /// If the root agent count right at this instant is less than the threshold specified in AutoBackupAgentThreshold (default 10),
-        /// then we return false and trip the busy heuristic's "too busy" path (i.e., don't save an OAR).
-        /// AutoBackupAgentThreshold is an _UPPER BOUND_. Higher Agent Count is bad, so if you go higher than our threshold, it's "too busy".
-        /// 
-        /// 
-        /// Returns true if we're not too busy; false means we've got more agents on the sim than the threshold.
-        private bool RunAgentLimitHeuristic(IScene region)
-        {
-            string regionName = region.RegionInfo.RegionName;
-            try
-            {
-                Scene scene = (Scene) region;
-                // TODO: Why isn't GetRootAgentCount() a method in the IScene interface? Seems generally useful...
-                return scene.GetRootAgentCount() <=
-                       this.m_configSource.Configs["AutoBackupModule"].GetInt(
-                           regionName + ".AutoBackupAgentThreshold", 10);
-            }
-            catch (InvalidCastException ice)
-            {
-                m_log.Debug(
-                    "[AUTO BACKUP]: I NEED MAINTENANCE: IScene is not a Scene; can't get root agent count!",
-                    ice);
-                return true;
-                // Non-obstructionist safest answer...
-            }
-        }
-
         /// 
         /// Run the script or executable specified by the "AutoBackupScript" config setting.
         /// Of course this is a security risk if you let anyone modify OpenSim.ini and they want to run some nasty bash script.
@@ -920,18 +617,6 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
         }
 
         /// 
-        /// Quickly stop all timers from firing.
-        /// 
-        private void StopAllTimers()
-        {
-            foreach (Timer t in this.m_timerMap.Keys)
-            {
-                t.Close();
-            }
-            this.m_closed = true;
-        }
-
-        /// 
         /// Determine the next unique filename by number, for "Sequential" AutoBackupNamingType.
         /// 
         /// 
@@ -1033,5 +718,3 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
         }
     }
 }
-
-
diff --git a/OpenSim/Region/OptionalModules/World/AutoBackup/AutoBackupModuleState.cs b/OpenSim/Region/OptionalModules/World/AutoBackup/AutoBackupModuleState.cs
index ce7c368..fb87677 100644
--- a/OpenSim/Region/OptionalModules/World/AutoBackup/AutoBackupModuleState.cs
+++ b/OpenSim/Region/OptionalModules/World/AutoBackup/AutoBackupModuleState.cs
@@ -35,29 +35,23 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
     /// If you use this class in any way outside of AutoBackupModule, you should treat the class as opaque.
     /// Since it is not part of the framework, you really should not rely upon it outside of the AutoBackupModule implementation.
     /// 
-    /// 
+    ///
     public class AutoBackupModuleState
     {
-        private Dictionary m_liveRequests = null;
-
         public AutoBackupModuleState()
         {
-            this.Enabled = false;
-            this.BackupDir = ".";
-            this.BusyCheck = true;
-            this.SkipAssets = false;
-            this.Timer = null;
-            this.NamingType = NamingType.Time;
-            this.Script = null;
-            this.KeepFilesForDays = 0;
+            Enabled = false;
+            SkipAssets = false;
+            NamingType = NamingType.Time;
+            Script = null;
         }
 
-        public Dictionary LiveRequests
+        public AutoBackupModuleState(AutoBackupModuleState copyFrom)
         {
-            get {
-                return this.m_liveRequests ??
-                       (this.m_liveRequests = new Dictionary(1));
-            }
+            Enabled = copyFrom.Enabled;
+            SkipAssets = copyFrom.SkipAssets;
+            NamingType = copyFrom.NamingType;
+            Script = copyFrom.Script;
         }
 
         public bool Enabled
@@ -66,33 +60,6 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
             set;
         }
 
-        public System.Timers.Timer Timer
-        {
-            get;
-            set;
-        }
-
-        public double IntervalMinutes
-        {
-            get
-            {
-                if (this.Timer == null)
-                {
-                    return -1.0;
-                }
-                else
-                {
-                    return this.Timer.Interval / 60000.0;
-                }
-            }
-        }
-
-        public bool BusyCheck
-        {
-            get;
-            set;
-        }
-
         public bool SkipAssets
         {
             get;
@@ -105,36 +72,19 @@ namespace OpenSim.Region.OptionalModules.World.AutoBackup
             set;
         }
 
-        public string BackupDir
-        {
-            get;
-            set;
-        }
-
         public NamingType NamingType
         {
             get;
             set;
         }
 
-        public int KeepFilesForDays
-        {
-            get;
-            set;
-        }
-
         public new string ToString()
         {
             string retval = "";
-
             retval += "[AUTO BACKUP]: AutoBackup: " + (Enabled ? "ENABLED" : "DISABLED") + "\n";
-            retval += "[AUTO BACKUP]: Interval: " + IntervalMinutes + " minutes" + "\n";
-            retval += "[AUTO BACKUP]: Do Busy Check: " + (BusyCheck ? "Yes" : "No") + "\n";
             retval += "[AUTO BACKUP]: Naming Type: " + NamingType.ToString() + "\n";
-            retval += "[AUTO BACKUP]: Backup Dir: " + BackupDir + "\n";
             retval += "[AUTO BACKUP]: Script: " + Script + "\n";
             return retval;
         }
     }
 }
-
diff --git a/OpenSim/Region/OptionalModules/World/MoneyModule/SampleMoneyModule.cs b/OpenSim/Region/OptionalModules/World/MoneyModule/SampleMoneyModule.cs
index 5f47810..b32a429 100644
--- a/OpenSim/Region/OptionalModules/World/MoneyModule/SampleMoneyModule.cs
+++ b/OpenSim/Region/OptionalModules/World/MoneyModule/SampleMoneyModule.cs
@@ -65,10 +65,10 @@ namespace OpenSim.Region.OptionalModules.World.MoneyModule
         /// 
         // private UUID EconomyBaseAccount = UUID.Zero;
 
-        private float EnergyEfficiency = 0f;
+        private float EnergyEfficiency = 1f;
         // private ObjectPaid handerOnObjectPaid;
         private bool m_enabled = true;
-        private bool m_sellEnabled = false;
+        private bool m_sellEnabled = true;
 
         private IConfigSource m_gConfig;
 
@@ -85,12 +85,12 @@ namespace OpenSim.Region.OptionalModules.World.MoneyModule
 
         private int ObjectCount = 0;
         private int PriceEnergyUnit = 0;
-        private int PriceGroupCreate = 0;
+        private int PriceGroupCreate = -1;
         private int PriceObjectClaim = 0;
         private float PriceObjectRent = 0f;
-        private float PriceObjectScaleFactor = 0f;
+        private float PriceObjectScaleFactor = 10f;
         private int PriceParcelClaim = 0;
-        private float PriceParcelClaimFactor = 0f;
+        private float PriceParcelClaimFactor = 1f;
         private int PriceParcelRent = 0;
         private int PricePublicObjectDecay = 0;
         private int PricePublicObjectDelete = 0;
@@ -98,7 +98,7 @@ namespace OpenSim.Region.OptionalModules.World.MoneyModule
         private int PriceUpload = 0;
         private int TeleportMinPrice = 0;
 
-        private float TeleportPriceExponent = 0f;
+        private float TeleportPriceExponent = 2f;
 
 
         #region IMoneyModule Members
@@ -124,13 +124,7 @@ namespace OpenSim.Region.OptionalModules.World.MoneyModule
         public void Initialise(IConfigSource config)
         {
             m_gConfig = config;
-
-            IConfig startupConfig = m_gConfig.Configs["Startup"];
-            IConfig economyConfig = m_gConfig.Configs["Economy"];
-
-
-            ReadConfigAndPopulate(startupConfig, "Startup");
-            ReadConfigAndPopulate(economyConfig, "Economy");
+            ReadConfigAndPopulate();
         }
 
         public void AddRegion(Scene scene)
@@ -151,13 +145,13 @@ namespace OpenSim.Region.OptionalModules.World.MoneyModule
                         // to the command line parameters you use to start up your client
                         // This commonly looks like -helperuri http://127.0.0.1:9000/
 
-                       
+
                         // Local Server..  enables functionality only.
                         httpServer.AddXmlRPCHandler("getCurrencyQuote", quote_func);
                         httpServer.AddXmlRPCHandler("buyCurrency", buy_func);
                         httpServer.AddXmlRPCHandler("preflightBuyLandPrep", preflightBuyLandPrep_func);
                         httpServer.AddXmlRPCHandler("buyLandPrep", landBuy_func);
-                       
+
                     }
 
                     if (m_scenel.ContainsKey(scene.RegionInfo.RegionHandle))
@@ -205,13 +199,14 @@ namespace OpenSim.Region.OptionalModules.World.MoneyModule
         {
         }
 
-        public bool ObjectGiveMoney(UUID objectID, UUID fromID, UUID toID, int amount)
+        public bool ObjectGiveMoney(UUID objectID, UUID fromID, UUID toID, int amount, UUID txn, out string result)
         {
+            result = String.Empty;
             string description = String.Format("Object {0} pays {1}", resolveObjectName(objectID), resolveAgentName(toID));
 
             bool give_result = doMoneyTransfer(fromID, toID, amount, 2, description);
 
-            
+
             BalanceUpdate(fromID, toID, give_result, description);
 
             return give_result;
@@ -240,35 +235,51 @@ namespace OpenSim.Region.OptionalModules.World.MoneyModule
         /// 
         /// Parse Configuration
         /// 
-        /// 
-        /// 
-        /// 
-        private void ReadConfigAndPopulate(IConfig startupConfig, string config)
+        private void ReadConfigAndPopulate()
         {
-            if (config == "Startup" && startupConfig != null)
+            // we are enabled by default
+
+            IConfig startupConfig = m_gConfig.Configs["Startup"];
+
+            if(startupConfig == null) // should not happen
+                return;
+
+            IConfig economyConfig = m_gConfig.Configs["Economy"];
+
+            // economymodule may be at startup or Economy (legacy)
+            string mmodule = startupConfig.GetString("economymodule","");
+            if(String.IsNullOrEmpty(mmodule))
             {
-                m_enabled = (startupConfig.GetString("economymodule", "BetaGridLikeMoneyModule") == "BetaGridLikeMoneyModule");
+                if(economyConfig != null)
+                    mmodule = economyConfig.GetString("economymodule","");
             }
 
-            if (config == "Economy" && startupConfig != null)
+            if(!String.IsNullOrEmpty(mmodule) && mmodule != Name)
             {
-                PriceEnergyUnit = startupConfig.GetInt("PriceEnergyUnit", 100);
-                PriceObjectClaim = startupConfig.GetInt("PriceObjectClaim", 10);
-                PricePublicObjectDecay = startupConfig.GetInt("PricePublicObjectDecay", 4);
-                PricePublicObjectDelete = startupConfig.GetInt("PricePublicObjectDelete", 4);
-                PriceParcelClaim = startupConfig.GetInt("PriceParcelClaim", 1);
-                PriceParcelClaimFactor = startupConfig.GetFloat("PriceParcelClaimFactor", 1f);
-                PriceUpload = startupConfig.GetInt("PriceUpload", 0);
-                PriceRentLight = startupConfig.GetInt("PriceRentLight", 5);
-                TeleportMinPrice = startupConfig.GetInt("TeleportMinPrice", 2);
-                TeleportPriceExponent = startupConfig.GetFloat("TeleportPriceExponent", 2f);
-                EnergyEfficiency = startupConfig.GetFloat("EnergyEfficiency", 1);
-                PriceObjectRent = startupConfig.GetFloat("PriceObjectRent", 1);
-                PriceObjectScaleFactor = startupConfig.GetFloat("PriceObjectScaleFactor", 10);
-                PriceParcelRent = startupConfig.GetInt("PriceParcelRent", 1);
-                PriceGroupCreate = startupConfig.GetInt("PriceGroupCreate", -1);
-                m_sellEnabled = startupConfig.GetBoolean("SellEnabled", false);
+                // some other money module selected
+                m_enabled = false;
+                return;
             }
+            
+            if(economyConfig == null)
+                return;
+
+            PriceEnergyUnit = economyConfig.GetInt("PriceEnergyUnit", 0);
+            PriceObjectClaim = economyConfig.GetInt("PriceObjectClaim", 0);
+            PricePublicObjectDecay = economyConfig.GetInt("PricePublicObjectDecay", 4);
+            PricePublicObjectDelete = economyConfig.GetInt("PricePublicObjectDelete", 0);
+            PriceParcelClaim = economyConfig.GetInt("PriceParcelClaim", 0);
+            PriceParcelClaimFactor = economyConfig.GetFloat("PriceParcelClaimFactor", 1f);
+            PriceUpload = economyConfig.GetInt("PriceUpload", 0);
+            PriceRentLight = economyConfig.GetInt("PriceRentLight", 0);
+            TeleportMinPrice = economyConfig.GetInt("TeleportMinPrice", 0);
+            TeleportPriceExponent = economyConfig.GetFloat("TeleportPriceExponent", 2f);
+            EnergyEfficiency = economyConfig.GetFloat("EnergyEfficiency", 1);
+            PriceObjectRent = economyConfig.GetFloat("PriceObjectRent", 0);
+            PriceObjectScaleFactor = economyConfig.GetFloat("PriceObjectScaleFactor", 10);
+            PriceParcelRent = economyConfig.GetInt("PriceParcelRent", 0);
+            PriceGroupCreate = economyConfig.GetInt("PriceGroupCreate", -1);
+            m_sellEnabled = economyConfig.GetBoolean("SellEnabled", true);
         }
 
         private void GetClientFunds(IClientAPI client)
@@ -302,7 +313,7 @@ namespace OpenSim.Region.OptionalModules.World.MoneyModule
         private bool doMoneyTransfer(UUID Sender, UUID Receiver, int amount, int transactiontype, string description)
         {
             bool result = true;
-            
+
             return result;
         }
 
@@ -376,10 +387,10 @@ namespace OpenSim.Region.OptionalModules.World.MoneyModule
             else
             {
                 m_log.ErrorFormat(
-                    "[MONEY]: Could not resolve user {0}", 
+                    "[MONEY]: Could not resolve user {0}",
                     agentID);
             }
-            
+
             return String.Empty;
         }
 
@@ -463,7 +474,7 @@ namespace OpenSim.Region.OptionalModules.World.MoneyModule
             Hashtable quoteResponse = new Hashtable();
             XmlRpcResponse returnval = new XmlRpcResponse();
 
-            
+
             Hashtable currencyResponse = new Hashtable();
             currencyResponse.Add("estimatedCost", 0);
             currencyResponse.Add("currencyBuy", amount);
@@ -474,7 +485,7 @@ namespace OpenSim.Region.OptionalModules.World.MoneyModule
 
             returnval.Value = quoteResponse;
             return returnval;
-            
+
 
 
         }
@@ -484,7 +495,7 @@ namespace OpenSim.Region.OptionalModules.World.MoneyModule
             // Hashtable requestData = (Hashtable) request.Params[0];
             // UUID agentId = UUID.Zero;
             // int amount = 0;
-           
+
             XmlRpcResponse returnval = new XmlRpcResponse();
             Hashtable returnresp = new Hashtable();
             returnresp.Add("success", true);
@@ -535,7 +546,7 @@ namespace OpenSim.Region.OptionalModules.World.MoneyModule
 
             // UUID agentId = UUID.Zero;
             // int amount = 0;
-           
+
             retparam.Add("success", true);
             ret.Value = retparam;
 
@@ -552,7 +563,7 @@ namespace OpenSim.Region.OptionalModules.World.MoneyModule
         /// 
         private void CheckExistAndRefreshFunds(UUID agentID)
         {
-            
+
         }
 
         /// 
@@ -562,14 +573,14 @@ namespace OpenSim.Region.OptionalModules.World.MoneyModule
         /// 
         private int GetFundsForAgentID(UUID AgentID)
         {
-            int returnfunds = 82101;	// Set it to the OpenSim version, plus the IG build number.  Muahahaha;
-            
+            int returnfunds = 0;
+
             return returnfunds;
         }
 
         // private void SetLocalFundsForAgentID(UUID AgentID, int amount)
         // {
-            
+
         // }
 
         #endregion
@@ -688,7 +699,7 @@ namespace OpenSim.Region.OptionalModules.World.MoneyModule
         /// 
         public void ClientClosed(UUID AgentID, Scene scene)
         {
-            
+
         }
 
         /// 
@@ -707,19 +718,19 @@ namespace OpenSim.Region.OptionalModules.World.MoneyModule
 
         private void ValidateLandBuy(Object osender, EventManager.LandBuyArgs e)
         {
-            
-            
+
+
             lock (e)
             {
                 e.economyValidated = true;
             }
-       
-            
+
+
         }
 
         private void processLandBuy(Object osender, EventManager.LandBuyArgs e)
         {
-            
+
         }
 
         /// 
@@ -729,7 +740,7 @@ namespace OpenSim.Region.OptionalModules.World.MoneyModule
         /// 
         private void MoneyTransferAction(Object osender, EventManager.MoneyTransferArgs e)
         {
-            
+
         }
 
         /// 
@@ -738,7 +749,7 @@ namespace OpenSim.Region.OptionalModules.World.MoneyModule
         /// 
         private void MakeChildAgent(ScenePresence avatar)
         {
-            
+
         }
 
         /// 
@@ -747,7 +758,7 @@ namespace OpenSim.Region.OptionalModules.World.MoneyModule
         /// 
         private void ClientLoggedOut(UUID AgentId, Scene scene)
         {
-            
+
         }
 
         /// 
@@ -767,7 +778,7 @@ namespace OpenSim.Region.OptionalModules.World.MoneyModule
         /// 
         private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, UUID regionID)
         {
-            
+
             //m_log.Info("[FRIEND]: " + avatar.Name + " status:" + (!avatar.IsChildAgent).ToString());
         }
 
@@ -808,12 +819,12 @@ namespace OpenSim.Region.OptionalModules.World.MoneyModule
 
             Scene s = LocateSceneClientIn(remoteClient.AgentId);
 
-            // Implmenting base sale data checking here so the default OpenSimulator implementation isn't useless 
+            // Implmenting base sale data checking here so the default OpenSimulator implementation isn't useless
             // combined with other implementations.  We're actually validating that the client is sending the data
             // that it should.   In theory, the client should already know what to send here because it'll see it when it
-            // gets the object data.   If the data sent by the client doesn't match the object, the viewer probably has an 
-            // old idea of what the object properties are.   Viewer developer Hazim informed us that the base module 
-            // didn't check the client sent data against the object do any.   Since the base modules are the 
+            // gets the object data.   If the data sent by the client doesn't match the object, the viewer probably has an
+            // old idea of what the object properties are.   Viewer developer Hazim informed us that the base module
+            // didn't check the client sent data against the object do any.   Since the base modules are the
             // 'crowning glory' examples of good practice..
 
             // Validate that the object exists in the scene the user is in
@@ -823,15 +834,15 @@ namespace OpenSim.Region.OptionalModules.World.MoneyModule
                 remoteClient.SendAgentAlertMessage("Unable to buy now. The object was not found.", false);
                 return;
             }
-            
-            // Validate that the client sent the price that the object is being sold for 
+
+            // Validate that the client sent the price that the object is being sold for
             if (part.SalePrice != salePrice)
             {
                 remoteClient.SendAgentAlertMessage("Cannot buy at this price. Buy Failed. If you continue to get this relog.", false);
                 return;
             }
 
-            // Validate that the client sent the proper sale type the object has set 
+            // Validate that the client sent the proper sale type the object has set
             if (part.ObjectSaleType != saleType)
             {
                 remoteClient.SendAgentAlertMessage("Cannot buy this way. Buy Failed. If you continue to get this relog.", false);
@@ -842,6 +853,15 @@ namespace OpenSim.Region.OptionalModules.World.MoneyModule
             if (module != null)
                 module.BuyObject(remoteClient, categoryID, localID, saleType, salePrice);
         }
+
+        public void MoveMoney(UUID fromUser, UUID toUser, int amount, string text)
+        {
+        }
+
+        public bool MoveMoney(UUID fromUser, UUID toUser, int amount, MoneyTransactionType type, string text)
+        {
+            return true;
+        }
     }
 
     public enum TransactionType : int
diff --git a/OpenSim/Region/OptionalModules/World/NPC/NPCAvatar.cs b/OpenSim/Region/OptionalModules/World/NPC/NPCAvatar.cs
index fb644b7..bb23f2f 100644
--- a/OpenSim/Region/OptionalModules/World/NPC/NPCAvatar.cs
+++ b/OpenSim/Region/OptionalModules/World/NPC/NPCAvatar.cs
@@ -43,9 +43,13 @@ namespace OpenSim.Region.OptionalModules.World.NPC
     public class NPCAvatar : IClientAPI, INPC
     {
         public bool SenseAsAgent { get; set; }
+        public UUID Owner
+        {
+            get { return m_ownerID;}
+        }
 
         public delegate void ChatToNPC(
-            string message, byte type, Vector3 fromPos, string fromName, 
+            string message, byte type, Vector3 fromPos, string fromName,
             UUID fromAgentID, UUID ownerID, byte source, byte audible);
 
         /// 
@@ -61,9 +65,14 @@ namespace OpenSim.Region.OptionalModules.World.NPC
         private readonly string m_firstname;
         private readonly string m_lastname;
         private readonly Vector3 m_startPos;
-        private readonly UUID m_uuid;
+        private UUID m_uuid = UUID.Random();
         private readonly Scene m_scene;
         private readonly UUID m_ownerID;
+        private UUID m_hostGroupID;
+        private string m_profileAbout = "";
+        private UUID m_profileImage = UUID.Zero;
+        private string m_born;
+        public List SelectedObjects {get; private set;}
 
         public NPCAvatar(
             string firstname, string lastname, Vector3 position, UUID ownerID, bool senseAsAgent, Scene scene)
@@ -75,6 +84,7 @@ namespace OpenSim.Region.OptionalModules.World.NPC
             m_scene = scene;
             m_ownerID = ownerID;
             SenseAsAgent = senseAsAgent;
+            m_hostGroupID = UUID.Zero;
         }
 
         public NPCAvatar(
@@ -87,6 +97,25 @@ namespace OpenSim.Region.OptionalModules.World.NPC
             m_scene = scene;
             m_ownerID = ownerID;
             SenseAsAgent = senseAsAgent;
+            m_hostGroupID = UUID.Zero;
+        }
+
+        public string profileAbout
+        {
+            get { return m_profileAbout; }
+            set
+            {
+                if(value.Length > 255)
+                    m_profileAbout = value.Substring(0,255);
+                else
+                    m_profileAbout = value;
+            }
+        }
+
+        public UUID profileImage
+        {
+            get { return m_profileImage; }
+            set { m_profileImage = value; }
         }
 
         public IScene Scene
@@ -94,6 +123,8 @@ namespace OpenSim.Region.OptionalModules.World.NPC
             get { return m_scene; }
         }
 
+        public int PingTimeMS { get { return 0; } }
+
         public UUID OwnerID
         {
             get { return m_ownerID; }
@@ -187,9 +218,15 @@ namespace OpenSim.Region.OptionalModules.World.NPC
         {
 
         }
-        
-        public void SendSitResponse(UUID TargetID, Vector3 OffsetPos, Quaternion SitOrientation, bool autopilot,
-                                        Vector3 CameraAtOffset, Vector3 CameraEyeOffset, bool ForceMouseLook)
+
+        public void SendFindAgent(UUID HunterID, UUID PreyID, double GlobalX, double GlobalY)
+        {
+
+        }
+
+        public void SendSitResponse(UUID TargetID, Vector3 OffsetPos,
+                    Quaternion SitOrientation, bool autopilot,
+                    Vector3 CameraAtOffset, Vector3 CameraEyeOffset, bool ForceMouseLook)
         {
 
         }
@@ -248,7 +285,7 @@ namespace OpenSim.Region.OptionalModules.World.NPC
 #pragma warning disable 67
         public event Action OnLogout;
         public event ObjectPermissions OnObjectPermissions;
-
+        public event MoveItemsAndLeaveCopy OnMoveItemsAndLeaveCopy;
         public event MoneyTransferRequest OnMoneyTransferRequest;
         public event ParcelBuy OnParcelBuy;
         public event Action OnConnectionClosed;
@@ -268,6 +305,7 @@ namespace OpenSim.Region.OptionalModules.World.NPC
         public event ObjectDrop OnObjectDrop;
         public event StartAnim OnStartAnim;
         public event StopAnim OnStopAnim;
+        public event ChangeAnim OnChangeAnim;
         public event LinkObjects OnLinkObjects;
         public event DelinkObjects OnDelinkObjects;
         public event RequestMapBlocks OnRequestMapBlocks;
@@ -280,6 +318,7 @@ namespace OpenSim.Region.OptionalModules.World.NPC
         public event SetAlwaysRun OnSetAlwaysRun;
 
         public event DeRezObject OnDeRezObject;
+        public event RezRestoreToWorld OnRezRestoreToWorld;
         public event Action OnRegionHandShakeReply;
         public event GenericCall1 OnRequestWearables;
         public event Action OnCompleteMovementToRegion;
@@ -318,6 +357,7 @@ namespace OpenSim.Region.OptionalModules.World.NPC
         public event UpdatePrimTexture OnUpdatePrimTexture;
         public event UpdateVector OnUpdatePrimGroupPosition;
         public event UpdateVector OnUpdatePrimSinglePosition;
+        public event ClientChangeObject onClientChangeObject;
         public event UpdatePrimRotation OnUpdatePrimGroupRotation;
         public event UpdatePrimSingleRotationPosition OnUpdatePrimSingleRotationPosition;
         public event UpdatePrimSingleRotation OnUpdatePrimSingleRotation;
@@ -456,7 +496,7 @@ namespace OpenSim.Region.OptionalModules.World.NPC
         public event ClassifiedInfoRequest OnClassifiedInfoRequest;
         public event ClassifiedInfoUpdate OnClassifiedInfoUpdate;
         public event ClassifiedDelete OnClassifiedDelete;
-        public event ClassifiedDelete OnClassifiedGodDelete;
+        public event ClassifiedGodDelete OnClassifiedGodDelete;
 
         public event EventNotificationAddRequest OnEventNotificationAddRequest;
         public event EventNotificationRemoveRequest OnEventNotificationRemoveRequest;
@@ -479,7 +519,7 @@ namespace OpenSim.Region.OptionalModules.World.NPC
         public event AvatarInterestUpdate OnAvatarInterestUpdate;
 
         public event PlacesQuery OnPlacesQuery;
-        
+
         public event FindAgentUpdate OnFindAgent;
         public event TrackAgentUpdate OnTrackAgent;
         public event NewUserReport OnUserReport;
@@ -495,11 +535,12 @@ namespace OpenSim.Region.OptionalModules.World.NPC
         public event GroupVoteHistoryRequest OnGroupVoteHistoryRequest;
         public event SimWideDeletesDelegate OnSimWideDeletes;
         public event SendPostcard OnSendPostcard;
+        public event ChangeInventoryItemFlags OnChangeInventoryItemFlags;
         public event MuteListEntryUpdate OnUpdateMuteListEntry;
         public event MuteListEntryRemove OnRemoveMuteListEntry;
         public event GodlikeMessage onGodlikeMessage;
         public event GodUpdateRegionInfoUpdate OnGodUpdateRegionInfoUpdate;
-
+        public event GenericCall2 OnUpdateThrottles;
 #pragma warning restore 67
 
         #endregion
@@ -522,6 +563,7 @@ namespace OpenSim.Region.OptionalModules.World.NPC
         public virtual UUID AgentId
         {
             get { return m_uuid; }
+            set { m_uuid = value; }
         }
 
         public UUID SessionId
@@ -562,24 +604,40 @@ namespace OpenSim.Region.OptionalModules.World.NPC
         }
         public UUID ActiveGroupId
         {
-            get { return UUID.Zero; }
+            get { return m_hostGroupID; }
+            set { m_hostGroupID = value; }
         }
 
         public string ActiveGroupName
         {
             get { return String.Empty; }
+            set { }
         }
 
         public ulong ActiveGroupPowers
         {
             get { return 0; }
+            set { }
+        }
+
+        public string Born
+        {
+            get { return m_born; }
+            set { m_born = value; }
         }
 
         public bool IsGroupMember(UUID groupID)
         {
-            return false;
+            return (m_hostGroupID == groupID);
+        }
+
+        public Dictionary GetGroupPowers()
+        {
+            return new Dictionary();
         }
 
+        public void SetGroupPowers(Dictionary powers) { }
+
         public ulong GetGroupPowers(UUID groupID)
         {
             return 0;
@@ -627,6 +685,17 @@ namespace OpenSim.Region.OptionalModules.World.NPC
         public virtual void SetChildAgentThrottle(byte[] throttle)
         {
         }
+
+        public virtual void SetChildAgentThrottle(byte[] throttle, float factor)
+        {
+
+        }
+
+        public void SetAgentThrottleSilent(int throttle, int setting)
+        {
+
+
+        }
         public byte[] GetThrottlesPacked(float multiplier)
         {
             return new byte[0];
@@ -665,6 +734,11 @@ namespace OpenSim.Region.OptionalModules.World.NPC
 
         }
 
+        public virtual bool CanSendLayerData()
+        {
+            return false;
+        }
+
         public virtual void SendLayerData(float[] map)
         {
         }
@@ -676,9 +750,9 @@ namespace OpenSim.Region.OptionalModules.World.NPC
         {
         }
 
-        public virtual void SendWindData(Vector2[] windSpeeds) { }
+        public virtual void SendWindData(int version, Vector2[] windSpeeds) { }
 
-        public virtual void SendCloudData(float[] cloudCover) { }
+        public virtual void SendCloudData(int version, float[] cloudCover) { }
 
         public virtual void MoveAgentIntoRegion(RegionInfo regInfo, Vector3 pos, Vector3 look)
         {
@@ -739,7 +813,11 @@ namespace OpenSim.Region.OptionalModules.World.NPC
         {
         }
 
-        public void SendAvatarDataImmediate(ISceneEntity avatar)
+        public void SendEntityFullUpdateImmediate(ISceneEntity avatar)
+        {
+        }
+
+        public void SendEntityTerseUpdateImmediate(ISceneEntity ent)
         {
         }
 
@@ -772,6 +850,10 @@ namespace OpenSim.Region.OptionalModules.World.NPC
         {
         }
 
+        public void SendInventoryItemCreateUpdate(InventoryItemBase Item, UUID transactionID, uint callbackId)
+        {
+        }
+
         public virtual void SendRemoveInventoryItem(UUID itemID)
         {
         }
@@ -788,7 +870,7 @@ namespace OpenSim.Region.OptionalModules.World.NPC
         {
         }
 
-        public virtual void SendXferPacket(ulong xferID, uint packet, byte[] data)
+        public virtual void SendXferPacket(ulong xferID, uint packet, byte[] data, bool isTaskInventory)
         {
         }
         public virtual void SendAbortXferPacket(ulong xferID)
@@ -833,6 +915,10 @@ namespace OpenSim.Region.OptionalModules.World.NPC
         {
         }
 
+        public void SendAlertMessage(string message, string info)
+        {
+        }
+
         public void SendSystemAlertMessage(string message)
         {
         }
@@ -849,7 +935,7 @@ namespace OpenSim.Region.OptionalModules.World.NPC
                 OnRegionHandShakeReply(this);
             }
         }
-        
+
         public void SendAssetUploadCompleteMessage(sbyte AssetType, bool Success, UUID AssetFullID)
         {
         }
@@ -869,7 +955,7 @@ namespace OpenSim.Region.OptionalModules.World.NPC
         public void SendImageFirstPart(ushort numParts, UUID ImageUUID, uint ImageSize, byte[] ImageData, byte imageCodec)
         {
         }
-        
+
         public void SendImageNotFound(UUID imageid)
         {
         }
@@ -877,7 +963,7 @@ namespace OpenSim.Region.OptionalModules.World.NPC
         public void SendImageNextPart(ushort partNumber, UUID imageUuid, byte[] imageData)
         {
         }
-        
+
         public void SendShutdownConnectionNotice()
         {
         }
@@ -888,7 +974,7 @@ namespace OpenSim.Region.OptionalModules.World.NPC
 
         public void SendObjectPropertiesFamilyData(ISceneEntity Entity, uint RequestFlags)
         {
-            
+
         }
 
         public void SendObjectPropertiesReply(ISceneEntity entity)
@@ -902,12 +988,12 @@ namespace OpenSim.Region.OptionalModules.World.NPC
         public void SendViewerEffect(ViewerEffectPacket.EffectBlock[] effectBlocks)
         {
         }
-            
+
         public void SendViewerTime(int phase)
         {
         }
 
-        public void SendAvatarProperties(UUID avatarID, string aboutText, string bornOn, Byte[] charterMember,
+        public void SendAvatarProperties(UUID avatarID, string aboutText, string bornOn, Byte[] membershipType,
                                          string flAbout, uint flags, UUID flImageID, UUID imageID, string profileURL,
                                          UUID partnerID)
         {
@@ -933,10 +1019,10 @@ namespace OpenSim.Region.OptionalModules.World.NPC
 
         public void Close()
         {
-            Close(false);
+            Close(true, false);
         }
 
-        public void Close(bool force)
+        public void Close(bool sendStop, bool force)
         {
             // Remove ourselves from the scene
             m_scene.RemoveClient(AgentId, false);
@@ -947,7 +1033,7 @@ namespace OpenSim.Region.OptionalModules.World.NPC
             // We never start the client, so always fail.
             throw new NotImplementedException();
         }
-        
+
         public void Stop()
         {
         }
@@ -1142,11 +1228,11 @@ namespace OpenSim.Region.OptionalModules.World.NPC
         public void SendJoinGroupReply(UUID groupID, bool success)
         {
         }
-        
+
         public void SendEjectGroupMemberReply(UUID agentID, UUID groupID, bool success)
         {
         }
-        
+
         public void SendLeaveGroupReply(UUID groupID, bool success)
         {
         }
@@ -1155,6 +1241,10 @@ namespace OpenSim.Region.OptionalModules.World.NPC
         {
         }
 
+        public void SendAgentGroupDataUpdate(UUID avatarID, GroupMembershipData[] data)
+        {
+        }
+
         public void SendTerminateFriend(UUID exFriendID)
         {
         }
@@ -1208,10 +1298,26 @@ namespace OpenSim.Region.OptionalModules.World.NPC
         {
         }
 
+        public void UpdateGroupMembership(GroupMembershipData[] data)
+        {
+        }
+
+        public void GroupMembershipRemove(UUID GroupID)
+        {
+        }
+
+        public void GroupMembershipAddReplace(UUID GroupID,ulong GroupPowers)
+        {
+        }
+
         public void SendUseCachedMuteList()
         {
         }
 
+        public void SendEmpytMuteList()
+        {
+        }
+
         public void SendMuteListUpdate(string filename)
         {
         }
@@ -1220,7 +1326,7 @@ namespace OpenSim.Region.OptionalModules.World.NPC
         {
         }
         #endregion
-        
+
         public void SendRebakeAvatarTextures(UUID textureID)
         {
         }
@@ -1228,15 +1334,15 @@ namespace OpenSim.Region.OptionalModules.World.NPC
         public void SendAvatarInterestsReply(UUID avatarID, uint wantMask, string wantText, uint skillsMask, string skillsText, string languages)
         {
         }
-        
+
         public void SendGroupAccountingDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID, int amt)
         {
         }
-        
+
         public void SendGroupAccountingSummary(IClientAPI sender,UUID groupID, uint moneyAmt, int totalTier, int usedTier)
         {
         }
-        
+
         public void SendGroupTransactionsSummaryDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID,int amt)
         {
         }
@@ -1256,7 +1362,7 @@ namespace OpenSim.Region.OptionalModules.World.NPC
         public void SendTextBoxRequest(string message, int chatChannel, string objectname, UUID ownerID, string ownerFirstName, string ownerLastName, UUID objectId)
         {
         }
-        
+
         public void SendAgentTerseUpdate(ISceneEntity presence)
         {
         }
@@ -1265,9 +1371,22 @@ namespace OpenSim.Region.OptionalModules.World.NPC
         {
         }
 
+        public void SendSelectedPartsProprieties(List parts)
+        {
+        }
+
         public void SendPartPhysicsProprieties(ISceneEntity entity)
         {
         }
 
+        public void SendPartFullUpdate(ISceneEntity ent, uint? parentID)
+        {
+        }
+
+        public int GetAgentThrottleSilent(int throttle)
+        {
+            return 0;
+        }
+
     }
 }
diff --git a/OpenSim/Region/OptionalModules/World/NPC/NPCModule.cs b/OpenSim/Region/OptionalModules/World/NPC/NPCModule.cs
index 3b94dff..ced82e6 100644
--- a/OpenSim/Region/OptionalModules/World/NPC/NPCModule.cs
+++ b/OpenSim/Region/OptionalModules/World/NPC/NPCModule.cs
@@ -52,6 +52,11 @@ namespace OpenSim.Region.OptionalModules.World.NPC
         private Dictionary m_avatars =
                 new Dictionary();
 
+
+
+        private NPCOptionsFlags m_NPCOptionFlags;
+        public NPCOptionsFlags NPCOptionFlags {get {return m_NPCOptionFlags;}}
+
         public bool Enabled { get; private set; }
 
         public void Initialise(IConfigSource source)
@@ -59,6 +64,21 @@ namespace OpenSim.Region.OptionalModules.World.NPC
             IConfig config = source.Configs["NPC"];
 
             Enabled = (config != null && config.GetBoolean("Enabled", false));
+            m_NPCOptionFlags = NPCOptionsFlags.None;
+            if(Enabled)
+            {
+                if(config.GetBoolean("AllowNotOwned", true))
+                    m_NPCOptionFlags |= NPCOptionsFlags.AllowNotOwned;
+
+                if(config.GetBoolean("AllowSenseAsAvatar", true))
+                    m_NPCOptionFlags |= NPCOptionsFlags.AllowSenseAsAvatar;
+
+                if(config.GetBoolean("AllowCloneOtherAvatars", true))
+                    m_NPCOptionFlags |= NPCOptionsFlags.AllowCloneOtherAvatars;
+
+                if(config.GetBoolean("NoNPCGroup", true))
+                    m_NPCOptionFlags |= NPCOptionsFlags.NoNPCGroup;
+            }
         }
 
         public void AddRegion(Scene scene)
@@ -137,17 +157,18 @@ namespace OpenSim.Region.OptionalModules.World.NPC
         }
 
         public UUID CreateNPC(string firstname, string lastname,
-                Vector3 position, UUID owner, bool senseAsAgent, Scene scene,
+                Vector3 position, UUID owner,  bool senseAsAgent, Scene scene,
                 AvatarAppearance appearance)
         {
-            return CreateNPC(firstname, lastname, position, UUID.Zero, owner, senseAsAgent, scene, appearance);
+            return CreateNPC(firstname, lastname, position, UUID.Zero, owner, "", UUID.Zero, senseAsAgent, scene, appearance);
         }
 
         public UUID CreateNPC(string firstname, string lastname,
-                Vector3 position, UUID agentID, UUID owner, bool senseAsAgent, Scene scene,
+                Vector3 position, UUID agentID, UUID owner, string groupTitle, UUID groupID, bool senseAsAgent, Scene scene,
                 AvatarAppearance appearance)
         {
             NPCAvatar npcAvatar = null;
+            string born = DateTime.UtcNow.ToString();
 
             try
             {
@@ -167,10 +188,9 @@ namespace OpenSim.Region.OptionalModules.World.NPC
             npcAvatar.CircuitCode = (uint)Util.RandomClass.Next(0,
                     int.MaxValue);
 
-            m_log.DebugFormat(
-                "[NPC MODULE]: Creating NPC {0} {1} {2}, owner={3}, senseAsAgent={4} at {5} in {6}",
-                firstname, lastname, npcAvatar.AgentId, owner,
-                senseAsAgent, position, scene.RegionInfo.RegionName);
+//            m_log.DebugFormat(
+//                "[NPC MODULE]: Creating NPC {0} {1} {2}, owner={3}, senseAsAgent={4} at {5} in {6}",
+//                firstname, lastname, npcAvatar.AgentId, owner, senseAsAgent, position, scene.RegionInfo.RegionName);
 
             AgentCircuitData acd = new AgentCircuitData();
             acd.AgentID = npcAvatar.AgentId;
@@ -181,30 +201,44 @@ namespace OpenSim.Region.OptionalModules.World.NPC
             AvatarAppearance npcAppearance = new AvatarAppearance(appearance, true);
             acd.Appearance = npcAppearance;
 
-            lock (m_avatars)
+            /*
+            for (int i = 0;
+                    i < acd.Appearance.Texture.FaceTextures.Length; i++)
             {
-                scene.AuthenticateHandler.AddNewCircuit(npcAvatar.CircuitCode,
-                        acd);
-                scene.AddNewAgent(npcAvatar, PresenceType.Npc);
+                m_log.DebugFormat(
+                        "[NPC MODULE]: NPC avatar {0} has texture id {1} : {2}",
+                        acd.AgentID, i,
+                        acd.Appearance.Texture.FaceTextures[i]);
+            }
+            */
 
-                ScenePresence sp;
-                if (scene.TryGetScenePresence(npcAvatar.AgentId, out sp))
-                {
-                    sp.CompleteMovement(npcAvatar, false);
-                    m_avatars.Add(npcAvatar.AgentId, npcAvatar);
-                    m_log.DebugFormat("[NPC MODULE]: Created NPC {0} {1}", npcAvatar.AgentId, sp.Name);
+//            ManualResetEvent ev = new ManualResetEvent(false);
 
-                    return npcAvatar.AgentId;
-                }
-                else
+//            Util.FireAndForget(delegate(object x) {
+                lock (m_avatars)
                 {
-                    m_log.WarnFormat(
-                        "[NPC MODULE]: Could not find scene presence for NPC {0} {1}",
-                        sp.Name, sp.UUID);
+                    scene.AuthenticateHandler.AddNewCircuit(npcAvatar.CircuitCode, acd);
+                    scene.AddNewAgent(npcAvatar, PresenceType.Npc);
 
-                    return UUID.Zero;
+                    ScenePresence sp;
+                    if (scene.TryGetScenePresence(npcAvatar.AgentId, out sp))
+                    {
+                        npcAvatar.Born = born;
+                        npcAvatar.ActiveGroupId = groupID;
+                        sp.CompleteMovement(npcAvatar, false);
+                        sp.Grouptitle = groupTitle;
+                        m_avatars.Add(npcAvatar.AgentId, npcAvatar);
+//                        m_log.DebugFormat("[NPC MODULE]: Created NPC {0} {1}", npcAvatar.AgentId, sp.Name);
+                    }
                 }
-            }
+//                ev.Set();
+//            });
+
+//            ev.WaitOne();
+
+//            m_log.DebugFormat("[NPC MODULE]: Created NPC with id {0}", npcAvatar.AgentId);
+
+            return npcAvatar.AgentId;
         }
 
         public bool MoveToTarget(UUID agentID, Scene scene, Vector3 pos,
@@ -220,6 +254,11 @@ namespace OpenSim.Region.OptionalModules.World.NPC
                         if (sp.IsSatOnObject || sp.SitGround)
                             return false;
 
+//                        m_log.DebugFormat(
+//                                "[NPC MODULE]: Moving {0} to {1} in {2}, noFly {3}, landAtTarget {4}",
+//                                sp.Name, pos, scene.RegionInfo.RegionName,
+//                                noFly, landAtTarget);
+
                         sp.MoveToTarget(pos, noFly, landAtTarget);
                         sp.SetAlwaysRun = running;
 
@@ -382,6 +421,10 @@ namespace OpenSim.Region.OptionalModules.World.NPC
             {
                 if (m_avatars.TryGetValue(agentID, out av))
                 {
+                    /*
+                    m_log.DebugFormat("[NPC MODULE]: Found {0} {1} to remove",
+                            agentID, av.Name);
+                    */
                     doRemove = true;
                 }
             }
@@ -410,9 +453,15 @@ namespace OpenSim.Region.OptionalModules.World.NPC
             {
                 NPCAvatar av;
                 if (m_avatars.TryGetValue(npcID, out av))
+                {
+                    if (npcID == callerID)
+                        return true;
                     return CheckPermissions(av, callerID);
+                }
                 else
+                {
                     return false;
+                }
             }
         }
 
diff --git a/OpenSim/Region/OptionalModules/World/NPC/Tests/NPCModuleTests.cs b/OpenSim/Region/OptionalModules/World/NPC/Tests/NPCModuleTests.cs
index 77dfd40..9a1ea73 100644
--- a/OpenSim/Region/OptionalModules/World/NPC/Tests/NPCModuleTests.cs
+++ b/OpenSim/Region/OptionalModules/World/NPC/Tests/NPCModuleTests.cs
@@ -112,7 +112,7 @@ namespace OpenSim.Region.OptionalModules.World.NPC.Tests
             // ScenePresence.SendInitialData() to reset our entire appearance.
             m_scene.AssetService.Store(AssetHelpers.CreateNotecardAsset(originalFace8TextureId));
 
-            m_afMod.SetAppearance(sp, originalTe, null, null);
+            m_afMod.SetAppearance(sp, originalTe, null, new WearableCacheItem[0] );
 
             UUID npcId = m_npcMod.CreateNPC("John", "Smith", new Vector3(128, 128, 30), UUID.Zero, true, m_scene, sp.Appearance);
 
@@ -209,10 +209,10 @@ namespace OpenSim.Region.OptionalModules.World.NPC.Tests
             UserAccountHelpers.CreateUserWithInventory(m_scene, userId);
             ScenePresence sp = SceneHelpers.AddScenePresence(m_scene, userId);
 
-            InventoryItemBase att1Item 
+            InventoryItemBase att1Item
                 = UserInventoryHelpers.CreateInventoryItem(
                     m_scene, "att1", TestHelpers.ParseTail(0x2), TestHelpers.ParseTail(0x3), sp.UUID, InventoryType.Object);
-            InventoryItemBase att2Item 
+            InventoryItemBase att2Item
                 = UserInventoryHelpers.CreateInventoryItem(
                     m_scene, "att2", TestHelpers.ParseTail(0x12), TestHelpers.ParseTail(0x13), sp.UUID, InventoryType.Object);
 
@@ -483,4 +483,4 @@ namespace OpenSim.Region.OptionalModules.World.NPC.Tests
             Assert.That(npc.ParentID, Is.EqualTo(0));
         }
     }
-}
\ No newline at end of file
+}
diff --git a/OpenSim/Region/OptionalModules/World/SceneCommands/SceneCommandsModule.cs b/OpenSim/Region/OptionalModules/World/SceneCommands/SceneCommandsModule.cs
index 0927c4f..7e3bd7f 100644
--- a/OpenSim/Region/OptionalModules/World/SceneCommands/SceneCommandsModule.cs
+++ b/OpenSim/Region/OptionalModules/World/SceneCommands/SceneCommandsModule.cs
@@ -54,38 +54,38 @@ namespace OpenSim.Region.OptionalModules.Avatar.Attachments
         private Scene m_scene;
 
         public string Name { get { return "Scene Commands Module"; } }
-        
+
         public Type ReplaceableInterface { get { return null; } }
-        
+
         public void Initialise(IConfigSource source)
         {
 //            m_log.DebugFormat("[SCENE COMMANDS MODULE]: INITIALIZED MODULE");
         }
-        
+
         public void PostInitialise()
         {
 //            m_log.DebugFormat("[SCENE COMMANDS MODULE]: POST INITIALIZED MODULE");
         }
-        
+
         public void Close()
         {
 //            m_log.DebugFormat("[SCENE COMMANDS MODULE]: CLOSED MODULE");
         }
-        
+
         public void AddRegion(Scene scene)
         {
 //            m_log.DebugFormat("[SCENE COMMANDS MODULE]: REGION {0} ADDED", scene.RegionInfo.RegionName);
 
             m_scene = scene;
-            
+
             m_scene.RegisterModuleInterface(this);
         }
-        
+
         public void RemoveRegion(Scene scene)
         {
 //            m_log.DebugFormat("[SCENE COMMANDS MODULE]: REGION {0} REMOVED", scene.RegionInfo.RegionName);
-        }        
-        
+        }
+
         public void RegionLoaded(Scene scene)
         {
 //            m_log.DebugFormat("[ATTACHMENTS COMMAND MODULE]: REGION {0} LOADED", scene.RegionInfo.RegionName);
@@ -96,19 +96,11 @@ namespace OpenSim.Region.OptionalModules.Avatar.Attachments
                 "List current scene options.",
                       "active          - if false then main scene update and maintenance loops are suspended.\n"
                     + "animations      - if true  then extra animations debug information is logged.\n"
-                    + "appear-refresh  - if true  then appearance is resent to other avatars every 60 seconds.\n"
-                    + "child-repri     - how far an avatar must move in meters before we update the position of its child agents in neighbouring regions.\n"
-                    + "client-pos-upd  - the tolerance before clients are updated with new rotation information for an avatar.\n"
-                    + "client-rot-upd  - the tolerance before clients are updated with new rotation information for an avatar.\n"
-                    + "client-vel-upd  - the tolerance before clients are updated with new velocity information for an avatar.\n"
-                    + "root-upd-per    - if greater than 1, terse updates are only sent to root agents other than the originator on every n updates.\n"
-                    + "child-upd-per   - if greater than 1, terse updates are only sent to child agents on every n updates.\n"                    
                     + "collisions      - if false then collisions with other objects are turned off.\n"
                     + "pbackup         - if false then periodic scene backup is turned off.\n"
                     + "physics         - if false then all physics objects are non-physical.\n"
                     + "scripting       - if false then no scripting operations happen.\n"
                     + "teleport        - if true  then some extra teleport debug information is logged.\n"
-                    + "update-on-timer - If true  then the scene is updated via a timer.  If false then a thread with sleep is used.\n"
                     + "updates         - if true  then any frame which exceeds double the maximum desired frame time is logged.",
                 HandleDebugSceneGetCommand);
 
@@ -118,19 +110,11 @@ namespace OpenSim.Region.OptionalModules.Avatar.Attachments
                 "Turn on scene debugging options.",
                       "active          - if false then main scene update and maintenance loops are suspended.\n"
                     + "animations      - if true  then extra animations debug information is logged.\n"
-                    + "appear-refresh  - if true  then appearance is resent to other avatars every 60 seconds.\n"
-                    + "child-repri     - how far an avatar must move in meters before we update the position of its child agents in neighbouring regions.\n"
-                    + "client-pos-upd  - the tolerance before clients are updated with new rotation information for an avatar.\n"
-                    + "client-rot-upd  - the tolerance before clients are updated with new rotation information for an avatar.\n"
-                    + "client-vel-upd  - the tolerance before clients are updated with new velocity information for an avatar.\n"
-                    + "root-upd-per    - if greater than 1, terse updates are only sent to root agents other than the originator on every n updates.\n"
-                    + "child-upd-per   - if greater than 1, terse updates are only sent to child agents on every n updates.\n"
                     + "collisions      - if false then collisions with other objects are turned off.\n"
                     + "pbackup         - if false then periodic scene backup is turned off.\n"
                     + "physics         - if false then all physics objects are non-physical.\n"
                     + "scripting       - if false then no scripting operations happen.\n"
                     + "teleport        - if true  then some extra teleport debug information is logged.\n"
-                    + "update-on-timer - If true  then the scene is updated via a timer.  If false then a thread with sleep is used.\n"
                     + "updates         - if true  then any frame which exceeds double the maximum desired frame time is logged.",
                 HandleDebugSceneSetCommand);
         }
@@ -155,18 +139,10 @@ namespace OpenSim.Region.OptionalModules.Avatar.Attachments
             ConsoleDisplayList cdl = new ConsoleDisplayList();
             cdl.AddRow("active", m_scene.Active);
             cdl.AddRow("animations", m_scene.DebugAnimations);
-            cdl.AddRow("appear-refresh", m_scene.SendPeriodicAppearanceUpdates);
-            cdl.AddRow("child-repri", m_scene.ChildReprioritizationDistance);
-            cdl.AddRow("client-pos-upd", m_scene.RootPositionUpdateTolerance);
-            cdl.AddRow("client-rot-upd", m_scene.RootRotationUpdateTolerance);
-            cdl.AddRow("client-vel-upd", m_scene.RootVelocityUpdateTolerance);
-            cdl.AddRow("root-upd-per", m_scene.RootTerseUpdatePeriod);
-            cdl.AddRow("child-upd-per", m_scene.ChildTerseUpdatePeriod);
             cdl.AddRow("pbackup", m_scene.PeriodicBackup);
             cdl.AddRow("physics", m_scene.PhysicsEnabled);
             cdl.AddRow("scripting", m_scene.ScriptsEnabled);
             cdl.AddRow("teleport", m_scene.DebugTeleporting);
-            cdl.AddRow("update-on-timer", m_scene.UpdateOnTimer);
             cdl.AddRow("updates", m_scene.DebugUpdates);
 
             MainConsole.Instance.OutputFormat("Scene {0} options:", m_scene.Name);
@@ -210,69 +186,6 @@ namespace OpenSim.Region.OptionalModules.Avatar.Attachments
                     m_scene.DebugAnimations = active;
             }
 
-            if (options.ContainsKey("appear-refresh"))
-            {
-                bool newValue;
-
-                // FIXME: This can only come from the console at the moment but might not always be true.
-                if (ConsoleUtil.TryParseConsoleBool(MainConsole.Instance, options["appear-refresh"], out newValue))
-                    m_scene.SendPeriodicAppearanceUpdates = newValue;     
-            }
-
-            if (options.ContainsKey("child-repri"))
-            {
-                double newValue;
-
-                // FIXME: This can only come from the console at the moment but might not always be true.
-                if (ConsoleUtil.TryParseConsoleDouble(MainConsole.Instance, options["child-repri"], out newValue))
-                    m_scene.ChildReprioritizationDistance = newValue;                
-            }
-
-            if (options.ContainsKey("client-pos-upd"))
-            {
-                float newValue;
-
-                // FIXME: This can only come from the console at the moment but might not always be true.
-                if (ConsoleUtil.TryParseConsoleFloat(MainConsole.Instance, options["client-pos-upd"], out newValue))
-                    m_scene.RootPositionUpdateTolerance = newValue;    
-            }
-
-            if (options.ContainsKey("client-rot-upd"))
-            {
-                float newValue;
-
-                // FIXME: This can only come from the console at the moment but might not always be true.
-                if (ConsoleUtil.TryParseConsoleFloat(MainConsole.Instance, options["client-rot-upd"], out newValue))
-                    m_scene.RootRotationUpdateTolerance = newValue;    
-            }
-
-            if (options.ContainsKey("client-vel-upd"))
-            {
-                float newValue;
-
-                // FIXME: This can only come from the console at the moment but might not always be true.
-                if (ConsoleUtil.TryParseConsoleFloat(MainConsole.Instance, options["client-vel-upd"], out newValue))
-                    m_scene.RootVelocityUpdateTolerance = newValue;    
-            }
-
-            if (options.ContainsKey("root-upd-per"))
-            {
-                int newValue;
-
-                // FIXME: This can only come from the console at the moment but might not always be true.
-                if (ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, options["root-upd-per"], out newValue))
-                    m_scene.RootTerseUpdatePeriod = newValue;    
-            }
-
-            if (options.ContainsKey("child-upd-per"))
-            {
-                int newValue;
-
-                // FIXME: This can only come from the console at the moment but might not always be true.
-                if (ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, options["child-upd-per"], out newValue))
-                    m_scene.ChildTerseUpdatePeriod = newValue;    
-            }
-
             if (options.ContainsKey("pbackup"))
             {
                 bool active;
@@ -308,21 +221,6 @@ namespace OpenSim.Region.OptionalModules.Avatar.Attachments
                     m_scene.DebugTeleporting = enableTeleportDebugging;
             }
 
-            if (options.ContainsKey("update-on-timer"))
-            {
-                bool enableUpdateOnTimer;
-                if (bool.TryParse(options["update-on-timer"], out enableUpdateOnTimer))
-                {
-                    m_scene.UpdateOnTimer = enableUpdateOnTimer;
-                    m_scene.Active = false;
-
-                    while (m_scene.IsRunning)
-                        Thread.Sleep(20);
-
-                    m_scene.Active = true;
-                }
-            }
-
             if (options.ContainsKey("updates"))
             {
                 bool enableUpdateDebugging;
@@ -334,4 +232,4 @@ namespace OpenSim.Region.OptionalModules.Avatar.Attachments
             }
         }
     }
-}
\ No newline at end of file
+}
diff --git a/OpenSim/Region/OptionalModules/World/TreePopulator/TreePopulatorModule.cs b/OpenSim/Region/OptionalModules/World/TreePopulator/TreePopulatorModule.cs
index e4a3382..6e1f8bb 100644
--- a/OpenSim/Region/OptionalModules/World/TreePopulator/TreePopulatorModule.cs
+++ b/OpenSim/Region/OptionalModules/World/TreePopulator/TreePopulatorModule.cs
@@ -27,8 +27,13 @@
 
 using System;
 using System.Collections.Generic;
+using System.IO;
 using System.Reflection;
 using System.Timers;
+using System.Threading;
+using System.Xml;
+using System.Xml.Serialization;
+
 using OpenMetaverse;
 using log4net;
 using Mono.Addins;
@@ -38,17 +43,15 @@ using OpenSim.Region.CoreModules.Framework.InterfaceCommander;
 using OpenSim.Region.Framework.Interfaces;
 using OpenSim.Region.Framework.Scenes;
 
-using System.Xml;
-using System.Xml.Serialization;
-using System.IO;
+using Timer= System.Timers.Timer;
 
 namespace OpenSim.Region.OptionalModules.World.TreePopulator
 {
     /// 
-    /// Version 2.02 - Still hacky 
+    /// Version 2.02 - Still hacky
     /// 
     [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "TreePopulatorModule")]
-    public class TreePopulatorModule : INonSharedRegionModule, ICommandableModule, IVegetationModule
+    public class TreePopulatorModule : INonSharedRegionModule, ICommandableModule
     {
         private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
         private readonly Commander m_commander = new Commander("tree");
@@ -60,7 +63,7 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
             public string m_name;
             public Boolean m_frozen;
             public Tree m_tree_type;
-            public int m_tree_quantity; 
+            public int m_tree_quantity;
             public float m_treeline_low;
             public float m_treeline_high;
             public Vector3 m_seed_point;
@@ -78,24 +81,24 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
             {
             }
 
-            public Copse(string fileName, Boolean planted) 
+            public Copse(string fileName, Boolean planted)
             {
                 Copse cp = (Copse)DeserializeObject(fileName);
 
-                this.m_name = cp.m_name;
-                this.m_frozen = cp.m_frozen;
-                this.m_tree_quantity = cp.m_tree_quantity;
-                this.m_treeline_high = cp.m_treeline_high;
-                this.m_treeline_low = cp.m_treeline_low;
-                this.m_range = cp.m_range;
-                this.m_tree_type = cp.m_tree_type;
-                this.m_seed_point = cp.m_seed_point;
-                this.m_initial_scale = cp.m_initial_scale;
-                this.m_maximum_scale = cp.m_maximum_scale;
-                this.m_initial_scale = cp.m_initial_scale;
-                this.m_rate = cp.m_rate;
-                this.m_planted = planted;
-                this.m_trees = new List();
+                m_name = cp.m_name;
+                m_frozen = cp.m_frozen;
+                m_tree_quantity = cp.m_tree_quantity;
+                m_treeline_high = cp.m_treeline_high;
+                m_treeline_low = cp.m_treeline_low;
+                m_range = cp.m_range;
+                m_tree_type = cp.m_tree_type;
+                m_seed_point = cp.m_seed_point;
+                m_initial_scale = cp.m_initial_scale;
+                m_maximum_scale = cp.m_maximum_scale;
+                m_initial_scale = cp.m_initial_scale;
+                m_rate = cp.m_rate;
+                m_planted = planted;
+                m_trees = new List();
             }
 
             public Copse(string copsedef)
@@ -103,61 +106,63 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
                 char[] delimiterChars = {':', ';'};
                 string[] field = copsedef.Split(delimiterChars);
 
-                this.m_name = field[1].Trim();
-                this.m_frozen = (copsedef[0] == 'F');
-                this.m_tree_quantity = int.Parse(field[2]);
-                this.m_treeline_high = float.Parse(field[3], Culture.NumberFormatInfo);
-                this.m_treeline_low = float.Parse(field[4], Culture.NumberFormatInfo);
-                this.m_range = double.Parse(field[5], Culture.NumberFormatInfo);
-                this.m_tree_type = (Tree) Enum.Parse(typeof(Tree),field[6]);
-                this.m_seed_point = Vector3.Parse(field[7]);
-                this.m_initial_scale = Vector3.Parse(field[8]);
-                this.m_maximum_scale = Vector3.Parse(field[9]);
-                this.m_rate = Vector3.Parse(field[10]);
-                this.m_planted = true;
-                this.m_trees = new List();
+                m_name = field[1].Trim();
+                m_frozen = (copsedef[0] == 'F');
+                m_tree_quantity = int.Parse(field[2]);
+                m_treeline_high = float.Parse(field[3], Culture.NumberFormatInfo);
+                m_treeline_low = float.Parse(field[4], Culture.NumberFormatInfo);
+                m_range = double.Parse(field[5], Culture.NumberFormatInfo);
+                m_tree_type = (Tree) Enum.Parse(typeof(Tree),field[6]);
+                m_seed_point = Vector3.Parse(field[7]);
+                m_initial_scale = Vector3.Parse(field[8]);
+                m_maximum_scale = Vector3.Parse(field[9]);
+                m_rate = Vector3.Parse(field[10]);
+                m_planted = true;
+                m_trees = new List();
             }
 
             public Copse(string name, int quantity, float high, float low, double range, Vector3 point, Tree type, Vector3 scale, Vector3 max_scale, Vector3 rate, List trees)
             {
-                this.m_name = name;
-                this.m_frozen = false;
-                this.m_tree_quantity = quantity;
-                this.m_treeline_high = high;
-                this.m_treeline_low = low;
-                this.m_range = range;
-                this.m_tree_type = type;
-                this.m_seed_point = point;
-                this.m_initial_scale = scale;
-                this.m_maximum_scale = max_scale;
-                this.m_rate = rate;
-                this.m_planted = false;
-                this.m_trees = trees;
+                m_name = name;
+                m_frozen = false;
+                m_tree_quantity = quantity;
+                m_treeline_high = high;
+                m_treeline_low = low;
+                m_range = range;
+                m_tree_type = type;
+                m_seed_point = point;
+                m_initial_scale = scale;
+                m_maximum_scale = max_scale;
+                m_rate = rate;
+                m_planted = false;
+                m_trees = trees;
             }
 
             public override string ToString()
             {
-                string frozen = (this.m_frozen ? "F" : "A");
+                string frozen = (m_frozen ? "F" : "A");
 
-                return string.Format("{0}TPM: {1}; {2}; {3:0.0}; {4:0.0}; {5:0.0}; {6}; {7:0.0}; {8:0.0}; {9:0.0}; {10:0.00};", 
+                return string.Format("{0}TPM: {1}; {2}; {3:0.0}; {4:0.0}; {5:0.0}; {6}; {7:0.0}; {8:0.0}; {9:0.0}; {10:0.00};",
                     frozen,
-                    this.m_name,
-                    this.m_tree_quantity,
-                    this.m_treeline_high,
-                    this.m_treeline_low,
-                    this.m_range,
-                    this.m_tree_type,
-                    this.m_seed_point.ToString(),
-                    this.m_initial_scale.ToString(),
-                    this.m_maximum_scale.ToString(),
-                    this.m_rate.ToString());
+                    m_name,
+                    m_tree_quantity,
+                    m_treeline_high,
+                    m_treeline_low,
+                    m_range,
+                    m_tree_type,
+                    m_seed_point.ToString(),
+                    m_initial_scale.ToString(),
+                    m_maximum_scale.ToString(),
+                    m_rate.ToString());
             }
         }
 
-        private List m_copse;
-
-        private double m_update_ms = 1000.0; // msec between updates 
+        private List m_copses = new List();
+        private object mylock;
+        private double m_update_ms = 1000.0; // msec between updates
         private bool m_active_trees = false;
+        private bool m_enabled = true; // original default
+        private bool m_allowGrow = true; // original default
 
         Timer CalculateTrees;
 
@@ -174,51 +179,51 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
 
         public void Initialise(IConfigSource config)
         {
-            
-            // ini file settings
-            try
+            IConfig moduleConfig = config.Configs["Trees"];
+            if (moduleConfig != null)
             {
-                m_active_trees = config.Configs["Trees"].GetBoolean("active_trees", m_active_trees);
-            }
-            catch (Exception)
-            {
-                m_log.Debug("[TREES]: ini failure for active_trees - using default");
+                m_enabled = moduleConfig.GetBoolean("enabled", m_enabled);
+                m_active_trees = moduleConfig.GetBoolean("active_trees", m_active_trees);
+                m_allowGrow = moduleConfig.GetBoolean("allowGrow", m_allowGrow);
+                m_update_ms = moduleConfig.GetDouble("update_rate", m_update_ms);
             }
 
-            try
-            {
-                m_update_ms = config.Configs["Trees"].GetDouble("update_rate", m_update_ms);
-            }
-            catch (Exception)
-            {
-                m_log.Debug("[TREES]: ini failure for update_rate - using default");
-            }
+            if(!m_enabled)
+                return;
+
+            m_copses =  new List();
+            mylock = new object();
 
             InstallCommands();
 
-            m_log.Debug("[TREES]: Initialised tree module");
+            m_log.Debug("[TREES]: Initialised tree populator module");
         }
 
         public void AddRegion(Scene scene)
         {
+            if(!m_enabled)
+                return;
             m_scene = scene;
             m_scene.RegisterModuleCommander(m_commander);
             m_scene.EventManager.OnPluginConsole += EventManager_OnPluginConsole;
-
+            m_scene.EventManager.OnPrimsLoaded += EventManager_OnPrimsLoaded;
         }
 
         public void RemoveRegion(Scene scene)
         {
-        }
+            if(!m_enabled)
+                return;
+            if(m_active_trees && CalculateTrees != null)
+            {
+                CalculateTrees.Dispose();
+                CalculateTrees = null;
+            }
+            m_scene.EventManager.OnPluginConsole -= EventManager_OnPluginConsole;
+            m_scene.EventManager.OnPrimsLoaded -= EventManager_OnPrimsLoaded;
+        }   
 
         public void RegionLoaded(Scene scene)
         {
-            ReloadCopse();
-            if (m_copse.Count > 0)
-                m_log.Info("[TREES]: Copse load complete");
-
-            if (m_active_trees)
-                activeizeTreeze(true);
         }
 
         public void Close()
@@ -240,6 +245,16 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
 
         //--------------------------------------------------------------
 
+        private void EventManager_OnPrimsLoaded(Scene s)
+        {
+            ReloadCopse();
+            if (m_copses.Count > 0)
+                m_log.Info("[TREES]: Copses loaded" );
+
+            if (m_active_trees)
+                activeizeTreeze(true);
+        }
+
         #region ICommandableModule Members
 
         private void HandleTreeActive(Object[] args)
@@ -267,25 +282,57 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
             string copsename = ((string)args[0]).Trim();
             Boolean freezeState = (Boolean) args[1];
 
-            foreach (Copse cp in m_copse)
+            lock(mylock)
             {
-                if (cp.m_name == copsename && (!cp.m_frozen && freezeState || cp.m_frozen && !freezeState))
+                foreach (Copse cp in m_copses)
                 {
-                    cp.m_frozen = freezeState;
-                    foreach (UUID tree in cp.m_trees)
+                    if (cp.m_name != copsename)
+                        continue;
+
+                    if(!cp.m_frozen && freezeState || cp.m_frozen && !freezeState)
                     {
-                        SceneObjectPart sop = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
-                        sop.Name = (freezeState ? sop.Name.Replace("ATPM", "FTPM") : sop.Name.Replace("FTPM", "ATPM"));
-                        sop.ParentGroup.HasGroupChanged = true;
-                    }
+                        cp.m_frozen = freezeState;
+                        List losttrees = new List();
+                        foreach (UUID tree in cp.m_trees)
+                        {
+                            SceneObjectGroup sog = m_scene.GetSceneObjectGroup(tree);
+                            if(sog != null && !sog.IsDeleted)
+                            {
+                                SceneObjectPart sop = sog.RootPart;
+                                string name = sop.Name;
+                                if(freezeState)
+                                {
+                                    if(name.StartsWith("FTPM"))
+                                        continue;
+                                    if(!name.StartsWith("ATPM"))
+                                        continue;
+                                    sop.Name = sop.Name.Replace("ATPM", "FTPM");
+                                }
+                                else
+                                {
+                                    if(name.StartsWith("ATPM"))
+                                        continue;
+                                    if(!name.StartsWith("FTPM"))
+                                        continue;
+                                    sop.Name = sop.Name.Replace("FTPM", "ATPM");
+                                }
+                                sop.ParentGroup.HasGroupChanged = true;
+                                sog.ScheduleGroupForFullUpdate();
+                            }
+                            else
+                               losttrees.Add(tree);
+                        }
+                        foreach (UUID tree in losttrees)
+                            cp.m_trees.Remove(tree);
 
-                    m_log.InfoFormat("[TREES]: Activity for copse {0} is frozen {1}", copsename, freezeState);
-                    return;
-                }
-                else if (cp.m_name == copsename && (cp.m_frozen && freezeState || !cp.m_frozen && !freezeState))
-                {
-                    m_log.InfoFormat("[TREES]: Copse {0} is already in the requested freeze state", copsename);
-                    return;
+                        m_log.InfoFormat("[TREES]: Activity for copse {0} is frozen {1}", copsename, freezeState);
+                        return;
+                    }
+                    else
+                    {
+                        m_log.InfoFormat("[TREES]: Copse {0} is already in the requested freeze state", copsename);
+                        return;
+                    }
                 }
             }
             m_log.InfoFormat("[TREES]: Copse {0} was not found - command failed", copsename);
@@ -297,17 +344,21 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
 
             m_log.InfoFormat("[TREES]: Loading copse definition....");
 
-            copse = new Copse(((string)args[0]), false);
-            foreach (Copse cp in m_copse)
+            lock(mylock)
             {
-                if (cp.m_name == copse.m_name)
+                copse = new Copse(((string)args[0]), false);
                 {
-                    m_log.InfoFormat("[TREES]: Copse: {0} is already defined - command failed", copse.m_name);
-                    return;
+                    foreach (Copse cp in m_copses)
+                    {
+                        if (cp.m_name == copse.m_name)
+                        {
+                            m_log.InfoFormat("[TREES]: Copse: {0} is already defined - command failed", copse.m_name);
+                            return;
+                        }
+                    }
                 }
+                m_copses.Add(copse);
             }
-
-            m_copse.Add(copse);
             m_log.InfoFormat("[TREES]: Loaded copse: {0}", copse.ToString());
         }
 
@@ -318,20 +369,24 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
             m_log.InfoFormat("[TREES]: New tree planting for copse {0}", copsename);
             UUID uuid = m_scene.RegionInfo.EstateSettings.EstateOwner;
 
-            foreach (Copse copse in m_copse)
+            lock(mylock)
             {
-                if (copse.m_name == copsename)
+                foreach (Copse copse in m_copses)
                 {
-                    if (!copse.m_planted)
-                    {
-                        // The first tree for a copse is created here
-                        CreateTree(uuid, copse, copse.m_seed_point);
-                        copse.m_planted = true;
-                        return;
-                    }
-                    else
+                    if (copse.m_name == copsename)
                     {
-                        m_log.InfoFormat("[TREES]: Copse {0} has already been planted", copsename);
+                        if (!copse.m_planted)
+                        {
+                            // The first tree for a copse is created here
+                            CreateTree(uuid, copse, copse.m_seed_point, true);
+                            copse.m_planted = true;
+                            return;
+                        }
+                        else
+                        {
+                            m_log.InfoFormat("[TREES]: Copse {0} has already been planted", copsename);
+                            return;
+                        }
                     }
                 }
             }
@@ -376,45 +431,49 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
             string copsename = ((string)args[0]).Trim();
             Copse copseIdentity = null;
 
-            foreach (Copse cp in m_copse)
+            lock(mylock)
             {
-                if (cp.m_name == copsename)
+                foreach (Copse cp in m_copses)
                 {
-                    copseIdentity = cp;
+                    if (cp.m_name == copsename)
+                    {
+                        copseIdentity = cp;
+                    }
                 }
-            }
 
-            if (copseIdentity != null)
-            {
-                foreach (UUID tree in copseIdentity.m_trees)
+                if (copseIdentity != null)
                 {
-                    if (m_scene.Entities.ContainsKey(tree))
-                    {
-                        SceneObjectPart selectedTree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
-                        // Delete tree and alert clients (not silent)
-                        m_scene.DeleteSceneObject(selectedTree.ParentGroup, false);
-                    }
-                    else
+                    foreach (UUID tree in copseIdentity.m_trees)
                     {
-                        m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
+                        if (m_scene.Entities.ContainsKey(tree))
+                        {
+                            SceneObjectPart selectedTree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
+                            // Delete tree and alert clients (not silent)
+                            m_scene.DeleteSceneObject(selectedTree.ParentGroup, false);
+                        }
+                        else
+                        {
+                            m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
+                        }
                     }
+                    copseIdentity.m_trees = null;
+                    m_copses.Remove(copseIdentity);
+                    m_log.InfoFormat("[TREES]: Copse {0} has been removed", copsename);
+                }
+                else
+                {
+                    m_log.InfoFormat("[TREES]: Copse {0} was not found - command failed", copsename);
                 }
-                copseIdentity.m_trees = new List();
-                m_copse.Remove(copseIdentity);
-                m_log.InfoFormat("[TREES]: Copse {0} has been removed", copsename);
-            }
-            else
-            {
-                m_log.InfoFormat("[TREES]: Copse {0} was not found - command failed", copsename);
             }
         }
 
         private void HandleTreeStatistics(Object[] args)
         {
-            m_log.InfoFormat("[TREES]: Activity State: {0};  Update Rate: {1}", m_active_trees, m_update_ms);
-            foreach (Copse cp in m_copse)
+            m_log.InfoFormat("[TREES]: region {0}:", m_scene.Name);
+            m_log.InfoFormat("[TREES]:    Activity State: {0};  Update Rate: {1}", m_active_trees, m_update_ms);
+            foreach (Copse cp in m_copses)
             {
-                m_log.InfoFormat("[TREES]: Copse {0}; {1} trees; frozen {2}", cp.m_name, cp.m_trees.Count, cp.m_frozen);
+                m_log.InfoFormat("[TREES]:    Copse {0}; {1} trees; frozen {2}", cp.m_name, cp.m_trees.Count, cp.m_frozen);
             }
         }
 
@@ -442,7 +501,7 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
             treeRateCommand.AddArgument("updateRate", "The required update rate (minimum 1000.0)", "Double");
 
             Command treeReloadCommand =
-                new Command("reload", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeReload, "Reload copse definitions from the in-scene trees");
+                new Command("reload", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeReload, "Reload copses from the in-scene trees");
 
             Command treeRemoveCommand =
                 new Command("remove", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeRemove, "Remove a copse definition and all its in-scene trees");
@@ -499,34 +558,17 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
             treeShape.Scale = scale;
             treeShape.State = (byte)treeType;
 
-            return m_scene.AddNewPrim(uuid, groupID, position, rotation, treeShape);
-        }
-
-        #endregion
-
-        #region IEntityCreator Members
-
-        protected static readonly PCode[] creationCapabilities = new PCode[] { PCode.NewTree, PCode.Tree };
-        public PCode[] CreationCapabilities { get { return creationCapabilities; } }
-
-        public SceneObjectGroup CreateEntity(
-            UUID ownerID, UUID groupID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape)
-        {
-            if (Array.IndexOf(creationCapabilities, (PCode)shape.PCode) < 0)
-            {
-                m_log.DebugFormat("[VEGETATION]: PCode {0} not handled by {1}", shape.PCode, Name);
-                return null;
-            }
-
-            SceneObjectGroup sceneObject = new SceneObjectGroup(ownerID, pos, rot, shape);
-            SceneObjectPart rootPart = sceneObject.GetPart(sceneObject.UUID);
+            SceneObjectGroup sog = new SceneObjectGroup(uuid, position, rotation, treeShape);
+            SceneObjectPart rootPart = sog.RootPart;
 
             rootPart.AddFlag(PrimFlags.Phantom);
 
-            m_scene.AddNewSceneObject(sceneObject, true);
-            sceneObject.SetGroup(groupID, null);
-
-            return sceneObject;
+            sog.SetGroup(groupID, null);
+            m_scene.AddNewSceneObject(sog, true, false);
+            sog.IsSelected = false;
+            rootPart.IsSelected = false;
+            sog.InvalidateEffectivePerms();
+            return sog;
         }
 
         #endregion
@@ -569,26 +611,27 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
 
         private void ReloadCopse()
         {
-            m_copse = new List();
+            m_copses = new List();
 
-            EntityBase[] objs = m_scene.GetEntities();
-            foreach (EntityBase obj in objs)
+            List grps = m_scene.GetSceneObjectGroups();
+            foreach (SceneObjectGroup grp in grps)
             {
-                if (obj is SceneObjectGroup)
-                {
-                    SceneObjectGroup grp = (SceneObjectGroup)obj;
+                if(grp.RootPart.Shape.PCode != (byte)PCode.NewTree && grp.RootPart.Shape.PCode != (byte)PCode.Tree)
+                    continue;
 
-                    if (grp.Name.Length > 5 && (grp.Name.Substring(0, 5) == "ATPM:" || grp.Name.Substring(0, 5) == "FTPM:"))
+                if (grp.Name.Length > 5 && (grp.Name.Substring(0, 5) == "ATPM:" || grp.Name.Substring(0, 5) == "FTPM:"))
+                {
+                    // Create a new copse definition or add uuid to an existing definition
+                    try
                     {
-                        // Create a new copse definition or add uuid to an existing definition
-                        try
-                        {
-                            Boolean copsefound = false;
-                            Copse copse = new Copse(grp.Name);
+                        Boolean copsefound = false;
+                        Copse grpcopse = new Copse(grp.Name);
 
-                            foreach (Copse cp in m_copse)
+                        lock(mylock)
+                        {
+                            foreach (Copse cp in m_copses)
                             {
-                                if (cp.m_name == copse.m_name)
+                                if (cp.m_name == grpcopse.m_name)
                                 {
                                     copsefound = true;
                                     cp.m_trees.Add(grp.UUID);
@@ -598,15 +641,15 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
 
                             if (!copsefound)
                             {
-                                m_log.InfoFormat("[TREES]: Found copse {0}", grp.Name);
-                                m_copse.Add(copse);
-                                copse.m_trees.Add(grp.UUID);
+                                m_log.InfoFormat("[TREES]: adding copse {0}", grpcopse.m_name);
+                                grpcopse.m_trees.Add(grp.UUID);
+                                m_copses.Add(grpcopse);
                             }
                         }
-                        catch
-                        {
-                            m_log.InfoFormat("[TREES]: Ill formed copse definition {0} - ignoring", grp.Name);
-                        }
+                    }
+                    catch
+                    {
+                        m_log.InfoFormat("[TREES]: Ill formed copse definition {0} - ignoring", grp.Name);
                     }
                 }
             }
@@ -617,166 +660,265 @@ namespace OpenSim.Region.OptionalModules.World.TreePopulator
         {
             if (activeYN)
             {
-                CalculateTrees = new Timer(m_update_ms);
+                if(CalculateTrees == null)
+                    CalculateTrees = new Timer(m_update_ms);
                 CalculateTrees.Elapsed += CalculateTrees_Elapsed;
+                CalculateTrees.AutoReset = false;
                 CalculateTrees.Start();
             }
-            else 
+            else
             {
                  CalculateTrees.Stop();
             }
-        } 
+        }
 
         private void growTrees()
         {
-            foreach (Copse copse in m_copse)
+            if(!m_allowGrow)
+                return;
+
+            foreach (Copse copse in m_copses)
             {
-                if (!copse.m_frozen)
+                if (copse.m_frozen)
+                    continue;
+
+                if(copse.m_trees.Count == 0)
+                    continue;
+
+                float maxscale = copse.m_maximum_scale.Z;
+                float ratescale = 1.0f;
+                List losttrees = new List();
+                foreach (UUID tree in copse.m_trees)
                 {
-                    foreach (UUID tree in copse.m_trees)
-                    {
-                        if (m_scene.Entities.ContainsKey(tree))
-                        {
-                            SceneObjectPart s_tree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
+                    SceneObjectGroup sog = m_scene.GetSceneObjectGroup(tree);
 
-                            if (s_tree.Scale.X < copse.m_maximum_scale.X && s_tree.Scale.Y < copse.m_maximum_scale.Y && s_tree.Scale.Z < copse.m_maximum_scale.Z)
-                            {
-                                s_tree.Scale += copse.m_rate;
-                                s_tree.ParentGroup.HasGroupChanged = true;
-                                s_tree.ScheduleFullUpdate();
-                            }
-                        }
-                        else
+                    if (sog != null && !sog.IsDeleted)
+                    {
+                        SceneObjectPart s_tree = sog.RootPart;
+                        if (s_tree.Scale.Z < maxscale)
                         {
-                            m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
+                            ratescale = (float)Util.RandomClass.NextDouble();
+                            if(ratescale < 0.2f)
+                                ratescale = 0.2f;
+                            s_tree.Scale += copse.m_rate * ratescale;
+                            sog.HasGroupChanged = true;
+                            s_tree.ScheduleFullUpdate();
                         }
                     }
+                    else
+                        losttrees.Add(tree);
                 }
+
+                foreach (UUID tree in losttrees)
+                    copse.m_trees.Remove(tree);
             }
         }
 
         private void seedTrees()
         {
-            foreach (Copse copse in m_copse)
+            foreach (Copse copse in m_copses)
             {
-                if (!copse.m_frozen)
+                if (copse.m_frozen)
+                    continue;
+
+                if(copse.m_trees.Count == 0)
+                    return;
+
+                bool low = copse.m_trees.Count < (int)(copse.m_tree_quantity * 0.8f);
+
+                if (!low && Util.RandomClass.NextDouble() < 0.75)
+                    return;
+
+                int maxbirths =  (int)(copse.m_tree_quantity) - copse.m_trees.Count;
+                if(maxbirths <= 1)
+                    return;
+
+                if(maxbirths > 20)
+                    maxbirths = 20;
+
+                float minscale = 0;
+                if(!low && m_allowGrow)
+                    minscale = copse.m_maximum_scale.Z * 0.75f;;
+
+                int i = 0;
+                UUID[] current = copse.m_trees.ToArray();
+                while(--maxbirths > 0)
                 {
-                    foreach (UUID tree in copse.m_trees)
+                    if(current.Length > 1)
+                        i = Util.RandomClass.Next(current.Length -1);
+
+                    UUID tree = current[i];
+                    SceneObjectGroup sog = m_scene.GetSceneObjectGroup(tree);
+
+                    if (sog != null && !sog.IsDeleted)
                     {
-                        if (m_scene.Entities.ContainsKey(tree))
-                        {
-                            SceneObjectPart s_tree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
+                        SceneObjectPart s_tree = sog.RootPart;
 
-                            if (copse.m_trees.Count < copse.m_tree_quantity)
-                            {
-                                // Tree has grown enough to seed if it has grown by at least 25% of seeded to full grown height
-                                if (s_tree.Scale.Z > copse.m_initial_scale.Z + (copse.m_maximum_scale.Z - copse.m_initial_scale.Z) / 4.0) 
-                                {
-                                    if (Util.RandomClass.NextDouble() > 0.75)
-                                    {
-                                        SpawnChild(copse, s_tree);
-                                    }
-                                }
-                            }
-                        }
-                        else
-                        {
-                            m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
-                        }
+                        // Tree has grown enough to seed if it has grown by at least 25% of seeded to full grown height
+                        if (s_tree.Scale.Z > minscale)
+                                SpawnChild(copse, s_tree, true);
                     }
-                }
+                    else if(copse.m_trees.Contains(tree))
+                        copse.m_trees.Remove(tree);
+                }                   
             }
         }
 
         private void killTrees()
         {
-            foreach (Copse copse in m_copse)
+            foreach (Copse copse in m_copses)
             {
-                if (!copse.m_frozen && copse.m_trees.Count >= copse.m_tree_quantity)
-                {
-                    foreach (UUID tree in copse.m_trees)
-                    {
-                        double killLikelyhood = 0.0;
+                if (copse.m_frozen)
+                    continue;
 
-                        if (m_scene.Entities.ContainsKey(tree))
-                        {
-                            SceneObjectPart selectedTree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
-                            double selectedTreeScale = Math.Sqrt(Math.Pow(selectedTree.Scale.X, 2) +
-                                                                 Math.Pow(selectedTree.Scale.Y, 2) +
-                                                                 Math.Pow(selectedTree.Scale.Z, 2));
-
-                            foreach (UUID picktree in copse.m_trees)
-                            {
-                                if (picktree != tree)
-                                {
-                                    SceneObjectPart pickedTree = ((SceneObjectGroup)m_scene.Entities[picktree]).RootPart;
-
-                                    double pickedTreeScale = Math.Sqrt(Math.Pow(pickedTree.Scale.X, 2) +
-                                                                       Math.Pow(pickedTree.Scale.Y, 2) +
-                                                                       Math.Pow(pickedTree.Scale.Z, 2));
+                if (Util.RandomClass.NextDouble() < 0.25)
+                    return;
 
-                                    double pickedTreeDistance = Vector3.Distance(pickedTree.AbsolutePosition, selectedTree.AbsolutePosition);
+                int maxbdeaths = copse.m_trees.Count - (int)(copse.m_tree_quantity * .98f) ;
+                if(maxbdeaths < 1)
+                    return;
 
-                                    killLikelyhood += (selectedTreeScale / (pickedTreeScale * pickedTreeDistance)) * 0.1;
-                                }
-                            }
+                float odds;
+                float scale = 1.0f / copse.m_maximum_scale.Z;
 
-                            if (Util.RandomClass.NextDouble() < killLikelyhood)
-                            {
-                                // Delete tree and alert clients (not silent)
-                                m_scene.DeleteSceneObject(selectedTree.ParentGroup, false);
-                                copse.m_trees.Remove(selectedTree.ParentGroup.UUID);
-                                break;
-                            }
+                int ntries = maxbdeaths * 4;
+                while(ntries-- > 0 )
+                {
+                    int next = 0;
+                    if (copse.m_trees.Count > 1)
+                        next = Util.RandomClass.Next(copse.m_trees.Count - 1);
+                    UUID tree = copse.m_trees[next];
+                    SceneObjectGroup sog = m_scene.GetSceneObjectGroup(tree);
+                    if (sog != null && !sog.IsDeleted)
+                    {
+                        if(m_allowGrow)
+                        {
+                            odds = sog.RootPart.Scale.Z * scale;
+                            odds = odds * odds * odds;
+                            odds *= (float)Util.RandomClass.NextDouble();
                         }
                         else
                         {
-                            m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
+                            odds = (float)Util.RandomClass.NextDouble();
+                            odds = odds * odds * odds;
                         }
+
+                        if(odds > 0.9f)
+                        {
+                            m_scene.DeleteSceneObject(sog, false);
+                            if(maxbdeaths <= 0)
+                                break;
+                        }
+                    }            
+                    else
+                    {
+                        copse.m_trees.Remove(tree);
+                        if(copse.m_trees.Count - (int)(copse.m_tree_quantity * .98f) <= 0 )
+                            break;
                     }
                 }
             }
         }
 
-        private void SpawnChild(Copse copse, SceneObjectPart s_tree)
+        private void SpawnChild(Copse copse, SceneObjectPart s_tree, bool low)
         {
             Vector3 position = new Vector3();
-
-            double randX = ((Util.RandomClass.NextDouble() * 2.0) - 1.0) * (s_tree.Scale.X * 3);
-            double randY = ((Util.RandomClass.NextDouble() * 2.0) - 1.0) * (s_tree.Scale.X * 3);
-
+           
+            float randX = copse.m_maximum_scale.X * 1.25f;
+            float randY = copse.m_maximum_scale.Y * 1.25f;
+            
+            float r = (float)Util.RandomClass.NextDouble();
+            randX *=  2.0f * r - 1.0f;
             position.X = s_tree.AbsolutePosition.X + (float)randX;
+            
+            r = (float)Util.RandomClass.NextDouble();
+            randY *=  2.0f * r - 1.0f;
             position.Y = s_tree.AbsolutePosition.Y + (float)randY;
 
-            if (position.X <= (m_scene.RegionInfo.RegionSizeX - 1) && position.X >= 0 &&
-                position.Y <= (m_scene.RegionInfo.RegionSizeY - 1) && position.Y >= 0 &&
-                Util.GetDistanceTo(position, copse.m_seed_point) <= copse.m_range)
-            {
-                UUID uuid = m_scene.RegionInfo.EstateSettings.EstateOwner;
+            if (position.X > (m_scene.RegionInfo.RegionSizeX - 1) || position.X <= 0 ||
+                position.Y > (m_scene.RegionInfo.RegionSizeY - 1) || position.Y <= 0)
+                return;
 
-                CreateTree(uuid, copse, position);
-            }
+            randX = position.X - copse.m_seed_point.X;
+            randX *= randX;
+            randY = position.Y - copse.m_seed_point.Y;
+            randY *= randY;
+            randX += randY;
+
+            if(randX > copse.m_range * copse.m_range)
+                return;
+
+            UUID uuid = m_scene.RegionInfo.EstateSettings.EstateOwner;
+            CreateTree(uuid, copse, position, low);
         }
 
-        private void CreateTree(UUID uuid, Copse copse, Vector3 position)
+        private void CreateTree(UUID uuid, Copse copse, Vector3 position, bool randomScale)
         {
-
             position.Z = (float)m_scene.Heightmap[(int)position.X, (int)position.Y];
-            if (position.Z >= copse.m_treeline_low && position.Z <= copse.m_treeline_high)
-            {
-                SceneObjectGroup tree = AddTree(uuid, UUID.Zero, copse.m_initial_scale, Quaternion.Identity, position, copse.m_tree_type, false);
+            if (position.Z < copse.m_treeline_low || position.Z > copse.m_treeline_high)
+                return;
 
-                tree.Name = copse.ToString();
-                copse.m_trees.Add(tree.UUID);
-                tree.SendGroupFullUpdate();
+            Vector3 scale = copse.m_initial_scale;
+            if(randomScale)
+            {
+                try
+                {
+                    float t;
+                    float r = (float)Util.RandomClass.NextDouble();
+                    r *= (float)Util.RandomClass.NextDouble();
+                    r *= (float)Util.RandomClass.NextDouble();
+
+                    t = copse.m_maximum_scale.X / copse.m_initial_scale.X;
+                    if(t < 1.0)
+                        t = 1 / t;
+                    t = t * r + 1.0f;
+                    scale.X *= t;
+
+                    t = copse.m_maximum_scale.Y / copse.m_initial_scale.Y;
+                    if(t < 1.0)
+                        t = 1 / t;
+                    t = t * r + 1.0f;
+                    scale.Y *= t;
+
+                    t = copse.m_maximum_scale.Z / copse.m_initial_scale.Z;
+                    if(t < 1.0)
+                        t = 1 / t;
+                    t = t * r + 1.0f;
+                    scale.Z *= t;
+                }
+                catch
+                {
+                    scale = copse.m_initial_scale;
+                }
             }
+
+            SceneObjectGroup tree = AddTree(uuid, UUID.Zero, scale, Quaternion.Identity, position, copse.m_tree_type, false);
+            tree.Name = copse.ToString();
+            copse.m_trees.Add(tree.UUID);
+            tree.RootPart.ScheduleFullUpdate();
         }
 
         private void CalculateTrees_Elapsed(object sender, ElapsedEventArgs e)
         {
-            growTrees();
-            seedTrees();
-            killTrees();
+            if(!m_scene.IsRunning)
+                return;
+            
+            if(Monitor.TryEnter(mylock))
+            {
+                try
+                {
+                    if(m_scene.LoginsEnabled )
+                    {
+                        growTrees();
+                        seedTrees();
+                        killTrees();
+                    }
+                }
+                catch { }
+                if(CalculateTrees != null)
+                    CalculateTrees.Start();
+                Monitor.Exit(mylock);
+            }
         }
     }
 }
-- 
cgit v1.1