aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Region/Framework
diff options
context:
space:
mode:
Diffstat (limited to 'OpenSim/Region/Framework')
-rw-r--r--OpenSim/Region/Framework/Interfaces/IAgentAssetTransactions.cs2
-rw-r--r--OpenSim/Region/Framework/Interfaces/IAttachmentsModule.cs10
-rw-r--r--OpenSim/Region/Framework/Interfaces/IAvatarFactoryModule.cs6
-rw-r--r--OpenSim/Region/Framework/Interfaces/IBakedTextureModule.cs19
-rw-r--r--OpenSim/Region/Framework/Interfaces/IEntityInventory.cs3
-rw-r--r--OpenSim/Region/Framework/Interfaces/IEntityTransferModule.cs32
-rw-r--r--OpenSim/Region/Framework/Interfaces/IEstateModule.cs1
-rw-r--r--OpenSim/Region/Framework/Interfaces/IEventQueue.cs2
-rw-r--r--OpenSim/Region/Framework/Interfaces/IInterregionComms.cs8
-rw-r--r--OpenSim/Region/Framework/Interfaces/IRegionConsole.cs4
-rw-r--r--OpenSim/Region/Framework/Interfaces/IRestartModule.cs1
-rw-r--r--OpenSim/Region/Framework/Interfaces/ISearchModule.cs2
-rw-r--r--OpenSim/Region/Framework/Interfaces/ISimulationDataService.cs2
-rw-r--r--OpenSim/Region/Framework/Interfaces/ISimulationDataStore.cs1
-rw-r--r--OpenSim/Region/Framework/Interfaces/ISnmpModule.cs27
-rw-r--r--OpenSim/Region/Framework/Interfaces/IUserAccountCacheModule.cs13
-rw-r--r--OpenSim/Region/Framework/Interfaces/IWorldComm.cs2
-rw-r--r--OpenSim/Region/Framework/Scenes/Animation/ScenePresenceAnimator.cs19
-rw-r--r--OpenSim/Region/Framework/Scenes/CollisionSounds.cs304
-rw-r--r--OpenSim/Region/Framework/Scenes/EventManager.cs43
-rw-r--r--OpenSim/Region/Framework/Scenes/KeyframeMotion.cs707
-rw-r--r--OpenSim/Region/Framework/Scenes/Prioritizer.cs16
-rw-r--r--OpenSim/Region/Framework/Scenes/SOPMaterial.cs95
-rw-r--r--OpenSim/Region/Framework/Scenes/SOPVehicle.cs791
-rw-r--r--OpenSim/Region/Framework/Scenes/Scene.Inventory.cs348
-rw-r--r--OpenSim/Region/Framework/Scenes/Scene.PacketHandlers.cs150
-rw-r--r--OpenSim/Region/Framework/Scenes/Scene.cs868
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneBase.cs3
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneCommunicationService.cs32
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneGraph.cs479
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneManager.cs251
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneObjectGroup.Inventory.cs17
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs1414
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneObjectPart.cs1731
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs767
-rw-r--r--OpenSim/Region/Framework/Scenes/ScenePresence.cs1072
-rw-r--r--OpenSim/Region/Framework/Scenes/Serialization/SceneObjectSerializer.cs135
-rw-r--r--OpenSim/Region/Framework/Scenes/SimStatsReporter.cs124
-rw-r--r--OpenSim/Region/Framework/Scenes/Tests/SceneObjectResizeTests.cs2
-rw-r--r--OpenSim/Region/Framework/Scenes/Tests/SceneObjectUndoRedoTests.cs184
-rw-r--r--OpenSim/Region/Framework/Scenes/Tests/SceneObjectUserGroupTests.cs3
-rw-r--r--OpenSim/Region/Framework/Scenes/UndoState.cs367
-rw-r--r--OpenSim/Region/Framework/Scenes/UuidGatherer.cs4
43 files changed, 7604 insertions, 2457 deletions
diff --git a/OpenSim/Region/Framework/Interfaces/IAgentAssetTransactions.cs b/OpenSim/Region/Framework/Interfaces/IAgentAssetTransactions.cs
index 0cc8fb6..e0aad2b 100644
--- a/OpenSim/Region/Framework/Interfaces/IAgentAssetTransactions.cs
+++ b/OpenSim/Region/Framework/Interfaces/IAgentAssetTransactions.cs
@@ -36,7 +36,7 @@ namespace OpenSim.Region.Framework.Interfaces
36 void HandleItemUpdateFromTransaction(IClientAPI remoteClient, UUID transactionID, 36 void HandleItemUpdateFromTransaction(IClientAPI remoteClient, UUID transactionID,
37 InventoryItemBase item); 37 InventoryItemBase item);
38 38
39 void HandleItemCreationFromTransaction(IClientAPI remoteClient, UUID transactionID, UUID folderID, 39 bool HandleItemCreationFromTransaction(IClientAPI remoteClient, UUID transactionID, UUID folderID,
40 uint callbackID, string description, string name, sbyte invType, 40 uint callbackID, string description, string name, sbyte invType,
41 sbyte type, byte wearableType, uint nextOwnerMask); 41 sbyte type, byte wearableType, uint nextOwnerMask);
42 42
diff --git a/OpenSim/Region/Framework/Interfaces/IAttachmentsModule.cs b/OpenSim/Region/Framework/Interfaces/IAttachmentsModule.cs
index 620ec22..d781eae 100644
--- a/OpenSim/Region/Framework/Interfaces/IAttachmentsModule.cs
+++ b/OpenSim/Region/Framework/Interfaces/IAttachmentsModule.cs
@@ -26,6 +26,7 @@
26 */ 26 */
27 27
28using System; 28using System;
29using System.Xml;
29using System.Collections.Generic; 30using System.Collections.Generic;
30using OpenMetaverse; 31using OpenMetaverse;
31using OpenSim.Framework; 32using OpenSim.Framework;
@@ -83,7 +84,7 @@ namespace OpenSim.Region.Framework.Interfaces
83 /// <param name="AttachmentPt"></param> 84 /// <param name="AttachmentPt"></param>
84 /// <param name="silent"></param> 85 /// <param name="silent"></param>
85 /// <returns>true if the object was successfully attached, false otherwise</returns> 86 /// <returns>true if the object was successfully attached, false otherwise</returns>
86 bool AttachObject(IScenePresence sp, SceneObjectGroup grp, uint AttachmentPt, bool silent, bool temp); 87 bool AttachObject(IScenePresence sp, SceneObjectGroup grp, uint AttachmentPt, bool silent, bool useAttachmentInfo, bool temp);
87 88
88 /// <summary> 89 /// <summary>
89 /// Rez an attachment from user inventory and change inventory status to match. 90 /// Rez an attachment from user inventory and change inventory status to match.
@@ -92,7 +93,11 @@ namespace OpenSim.Region.Framework.Interfaces
92 /// <param name="itemID"></param> 93 /// <param name="itemID"></param>
93 /// <param name="AttachmentPt"></param> 94 /// <param name="AttachmentPt"></param>
94 /// <returns>The scene object that was attached. Null if the scene object could not be found</returns> 95 /// <returns>The scene object that was attached. Null if the scene object could not be found</returns>
95 SceneObjectGroup RezSingleAttachmentFromInventory(IScenePresence sp, UUID itemID, uint AttachmentPt); 96 ISceneEntity RezSingleAttachmentFromInventory(IScenePresence sp, UUID itemID, uint AttachmentPt);
97
98 // Same as above, but also load script states from a separate doc
99 ISceneEntity RezSingleAttachmentFromInventory(
100 IScenePresence presence, UUID itemID, uint AttachmentPt, XmlDocument doc);
96 101
97 /// <summary> 102 /// <summary>
98 /// Rez multiple attachments from a user's inventory 103 /// Rez multiple attachments from a user's inventory
@@ -124,7 +129,6 @@ namespace OpenSim.Region.Framework.Interfaces
124 /// <param name="grp">The attachment to detach.</param> 129 /// <param name="grp">The attachment to detach.</param>
125 void DetachSingleAttachmentToInv(IScenePresence sp, SceneObjectGroup grp); 130 void DetachSingleAttachmentToInv(IScenePresence sp, SceneObjectGroup grp);
126 131
127 /// <summary>
128 /// Update the position of an attachment. 132 /// Update the position of an attachment.
129 /// </summary> 133 /// </summary>
130 /// <param name="sog"></param> 134 /// <param name="sog"></param>
diff --git a/OpenSim/Region/Framework/Interfaces/IAvatarFactoryModule.cs b/OpenSim/Region/Framework/Interfaces/IAvatarFactoryModule.cs
index 34aca33..d25c930 100644
--- a/OpenSim/Region/Framework/Interfaces/IAvatarFactoryModule.cs
+++ b/OpenSim/Region/Framework/Interfaces/IAvatarFactoryModule.cs
@@ -35,8 +35,8 @@ namespace OpenSim.Region.Framework.Interfaces
35 35
36 public interface IAvatarFactoryModule 36 public interface IAvatarFactoryModule
37 { 37 {
38 void SetAppearance(IScenePresence sp, AvatarAppearance appearance); 38 void SetAppearance(IScenePresence sp, AvatarAppearance appearance, WearableCacheItem[] cacheItems);
39 void SetAppearance(IScenePresence sp, Primitive.TextureEntry textureEntry, byte[] visualParams); 39 void SetAppearance(IScenePresence sp, Primitive.TextureEntry textureEntry, byte[] visualParams, WearableCacheItem[] cacheItems);
40 40
41 /// <summary> 41 /// <summary>
42 /// Send the appearance of an avatar to others in the scene. 42 /// Send the appearance of an avatar to others in the scene.
@@ -52,6 +52,8 @@ namespace OpenSim.Region.Framework.Interfaces
52 /// <returns>An empty list if this agent has no baked textures (e.g. because it's a child agent)</returns> 52 /// <returns>An empty list if this agent has no baked textures (e.g. because it's a child agent)</returns>
53 Dictionary<BakeType, Primitive.TextureEntryFace> GetBakedTextureFaces(UUID agentId); 53 Dictionary<BakeType, Primitive.TextureEntryFace> GetBakedTextureFaces(UUID agentId);
54 54
55
56 WearableCacheItem[] GetCachedItems(UUID agentId);
55 /// <summary> 57 /// <summary>
56 /// Save the baked textures for the given agent permanently in the asset database. 58 /// Save the baked textures for the given agent permanently in the asset database.
57 /// </summary> 59 /// </summary>
diff --git a/OpenSim/Region/Framework/Interfaces/IBakedTextureModule.cs b/OpenSim/Region/Framework/Interfaces/IBakedTextureModule.cs
new file mode 100644
index 0000000..21ed44f
--- /dev/null
+++ b/OpenSim/Region/Framework/Interfaces/IBakedTextureModule.cs
@@ -0,0 +1,19 @@
1////////////////////////////////////////////////////////////////
2//
3// (c) 2009, 2010 Careminster Limited and Melanie Thielker
4//
5// All rights reserved
6//
7using System;
8using Nini.Config;
9using OpenSim.Framework;
10using OpenMetaverse;
11
12namespace OpenSim.Services.Interfaces
13{
14 public interface IBakedTextureModule
15 {
16 WearableCacheItem[] Get(UUID id);
17 void Store(UUID id, WearableCacheItem[] data);
18 }
19}
diff --git a/OpenSim/Region/Framework/Interfaces/IEntityInventory.cs b/OpenSim/Region/Framework/Interfaces/IEntityInventory.cs
index 150193d..8028d87 100644
--- a/OpenSim/Region/Framework/Interfaces/IEntityInventory.cs
+++ b/OpenSim/Region/Framework/Interfaces/IEntityInventory.cs
@@ -133,6 +133,8 @@ namespace OpenSim.Region.Framework.Interfaces
133 /// </returns> 133 /// </returns>
134 bool CreateScriptInstance(UUID itemId, int startParam, bool postOnRez, string engine, int stateSource); 134 bool CreateScriptInstance(UUID itemId, int startParam, bool postOnRez, string engine, int stateSource);
135 135
136 ArrayList CreateScriptInstanceEr(UUID itemId, int startParam, bool postOnRez, string engine, int stateSource);
137
136 /// <summary> 138 /// <summary>
137 /// Stop and remove a script which is in this prim's inventory from the scene. 139 /// Stop and remove a script which is in this prim's inventory from the scene.
138 /// </summary> 140 /// </summary>
@@ -316,5 +318,6 @@ namespace OpenSim.Region.Framework.Interfaces
316 /// A <see cref="Dictionary`2"/> 318 /// A <see cref="Dictionary`2"/>
317 /// </returns> 319 /// </returns>
318 Dictionary<UUID, string> GetScriptStates(); 320 Dictionary<UUID, string> GetScriptStates();
321 Dictionary<UUID, string> GetScriptStates(bool oldIDs);
319 } 322 }
320} 323}
diff --git a/OpenSim/Region/Framework/Interfaces/IEntityTransferModule.cs b/OpenSim/Region/Framework/Interfaces/IEntityTransferModule.cs
index 69be83e..1949a90 100644
--- a/OpenSim/Region/Framework/Interfaces/IEntityTransferModule.cs
+++ b/OpenSim/Region/Framework/Interfaces/IEntityTransferModule.cs
@@ -35,6 +35,8 @@ using OpenSim.Region.Framework.Scenes;
35 35
36namespace OpenSim.Region.Framework.Interfaces 36namespace OpenSim.Region.Framework.Interfaces
37{ 37{
38 public delegate ScenePresence CrossAgentToNewRegionDelegate(ScenePresence agent, Vector3 pos, GridRegion neighbourRegion, bool isFlying, string version);
39
38 public interface IEntityTransferModule 40 public interface IEntityTransferModule
39 { 41 {
40 /// <summary> 42 /// <summary>
@@ -50,29 +52,10 @@ namespace OpenSim.Region.Framework.Interfaces
50 /// <param name='teleportFlags'></param> 52 /// <param name='teleportFlags'></param>
51 void Teleport(ScenePresence agent, ulong regionHandle, Vector3 position, Vector3 lookAt, uint teleportFlags); 53 void Teleport(ScenePresence agent, ulong regionHandle, Vector3 position, Vector3 lookAt, uint teleportFlags);
52 54
53 /// <summary> 55 bool TeleportHome(UUID id, IClientAPI client);
54 /// Teleport an agent directly to a given region without checking whether the region should be subsituted.
55 /// </summary>
56 /// <remarks>
57 /// Please use Teleport() instead unless you know exactly what you're doing.
58 /// Do not use for same region teleports.
59 /// </remarks>
60 /// <param name='sp'></param>
61 /// <param name='reg'></param>
62 /// <param name='finalDestination'>/param>
63 /// <param name='position'></param>
64 /// <param name='lookAt'></param>
65 /// <param name='teleportFlags'></param>
66 void DoTeleport(
67 ScenePresence sp, GridRegion reg, GridRegion finalDestination,
68 Vector3 position, Vector3 lookAt, uint teleportFlags);
69 56
70 /// <summary> 57 void DoTeleport(ScenePresence sp, GridRegion reg, GridRegion finalDestination,
71 /// Teleports the agent for the given client to their home destination. 58 Vector3 position, Vector3 lookAt, uint teleportFlags);
72 /// </summary>
73 /// <param name='id'></param>
74 /// <param name='client'></param>
75 void TeleportHome(UUID id, IClientAPI client);
76 59
77 /// <summary> 60 /// <summary>
78 /// Show whether the given agent is being teleported. 61 /// Show whether the given agent is being teleported.
@@ -89,7 +72,12 @@ namespace OpenSim.Region.Framework.Interfaces
89 72
90 void EnableChildAgent(ScenePresence agent, GridRegion region); 73 void EnableChildAgent(ScenePresence agent, GridRegion region);
91 74
75 GridRegion GetDestination(Scene scene, UUID agentID, Vector3 pos, out uint xDest, out uint yDest, out string version, out Vector3 newpos);
76
92 void Cross(SceneObjectGroup sog, Vector3 position, bool silent); 77 void Cross(SceneObjectGroup sog, Vector3 position, bool silent);
78
79 ScenePresence CrossAgentToNewRegionAsync(ScenePresence agent, Vector3 pos, GridRegion neighbourRegion, bool isFlying, string version);
80
93 } 81 }
94 82
95 public interface IUserAgentVerificationModule 83 public interface IUserAgentVerificationModule
diff --git a/OpenSim/Region/Framework/Interfaces/IEstateModule.cs b/OpenSim/Region/Framework/Interfaces/IEstateModule.cs
index 1983984..292efa4 100644
--- a/OpenSim/Region/Framework/Interfaces/IEstateModule.cs
+++ b/OpenSim/Region/Framework/Interfaces/IEstateModule.cs
@@ -45,6 +45,7 @@ namespace OpenSim.Region.Framework.Interfaces
45 /// Tell all clients about the current state of the region (terrain textures, water height, etc.). 45 /// Tell all clients about the current state of the region (terrain textures, water height, etc.).
46 /// </summary> 46 /// </summary>
47 void sendRegionHandshakeToAll(); 47 void sendRegionHandshakeToAll();
48 void TriggerEstateInfoChange();
48 49
49 /// <summary> 50 /// <summary>
50 /// Fires the OnRegionInfoChange event. 51 /// Fires the OnRegionInfoChange event.
diff --git a/OpenSim/Region/Framework/Interfaces/IEventQueue.cs b/OpenSim/Region/Framework/Interfaces/IEventQueue.cs
index bfa5d17..5512642 100644
--- a/OpenSim/Region/Framework/Interfaces/IEventQueue.cs
+++ b/OpenSim/Region/Framework/Interfaces/IEventQueue.cs
@@ -59,5 +59,7 @@ namespace OpenSim.Region.Framework.Interfaces
59 void GroupMembership(AgentGroupDataUpdatePacket groupUpdate, UUID avatarID); 59 void GroupMembership(AgentGroupDataUpdatePacket groupUpdate, UUID avatarID);
60 OSD ScriptRunningEvent(UUID objectID, UUID itemID, bool running, bool mono); 60 OSD ScriptRunningEvent(UUID objectID, UUID itemID, bool running, bool mono);
61 OSD BuildEvent(string eventName, OSD eventBody); 61 OSD BuildEvent(string eventName, OSD eventBody);
62 void partPhysicsProperties(uint localID, byte physhapetype, float density, float friction, float bounce, float gravmod, UUID avatarID);
63
62 } 64 }
63} 65}
diff --git a/OpenSim/Region/Framework/Interfaces/IInterregionComms.cs b/OpenSim/Region/Framework/Interfaces/IInterregionComms.cs
index 2d6287f..67a500f 100644
--- a/OpenSim/Region/Framework/Interfaces/IInterregionComms.cs
+++ b/OpenSim/Region/Framework/Interfaces/IInterregionComms.cs
@@ -68,6 +68,14 @@ namespace OpenSim.Region.Framework.Interfaces
68 bool SendReleaseAgent(ulong regionHandle, UUID id, string uri); 68 bool SendReleaseAgent(ulong regionHandle, UUID id, string uri);
69 69
70 /// <summary> 70 /// <summary>
71 /// Close chid agent.
72 /// </summary>
73 /// <param name="regionHandle"></param>
74 /// <param name="id"></param>
75 /// <returns></returns>
76 bool SendCloseChildAgent(ulong regionHandle, UUID id);
77
78 /// <summary>
71 /// Close agent. 79 /// Close agent.
72 /// </summary> 80 /// </summary>
73 /// <param name="regionHandle"></param> 81 /// <param name="regionHandle"></param>
diff --git a/OpenSim/Region/Framework/Interfaces/IRegionConsole.cs b/OpenSim/Region/Framework/Interfaces/IRegionConsole.cs
index 4d261d6..5d5ce34 100644
--- a/OpenSim/Region/Framework/Interfaces/IRegionConsole.cs
+++ b/OpenSim/Region/Framework/Interfaces/IRegionConsole.cs
@@ -30,8 +30,12 @@ using OpenSim.Framework;
30 30
31namespace OpenSim.Region.Framework.Interfaces 31namespace OpenSim.Region.Framework.Interfaces
32{ 32{
33 public delegate void ConsoleMessage(UUID toAgentID, string message);
34
33 public interface IRegionConsole 35 public interface IRegionConsole
34 { 36 {
37 event ConsoleMessage OnConsoleMessage;
38
35 bool RunCommand(string command, UUID invokerID); 39 bool RunCommand(string command, UUID invokerID);
36 void SendConsoleOutput(UUID agentID, string message); 40 void SendConsoleOutput(UUID agentID, string message);
37 void AddCommand(string module, bool shared, string command, string help, string longhelp, CommandDelegate fn); 41 void AddCommand(string module, bool shared, string command, string help, string longhelp, CommandDelegate fn);
diff --git a/OpenSim/Region/Framework/Interfaces/IRestartModule.cs b/OpenSim/Region/Framework/Interfaces/IRestartModule.cs
index c68550f..9b25beb 100644
--- a/OpenSim/Region/Framework/Interfaces/IRestartModule.cs
+++ b/OpenSim/Region/Framework/Interfaces/IRestartModule.cs
@@ -35,5 +35,6 @@ namespace OpenSim.Region.Framework.Interfaces
35 TimeSpan TimeUntilRestart { get; } 35 TimeSpan TimeUntilRestart { get; }
36 void ScheduleRestart(UUID initiator, string message, int[] alerts, bool notice); 36 void ScheduleRestart(UUID initiator, string message, int[] alerts, bool notice);
37 void AbortRestart(string message); 37 void AbortRestart(string message);
38 void DelayRestart(int seconds, string message);
38 } 39 }
39} 40}
diff --git a/OpenSim/Region/Framework/Interfaces/ISearchModule.cs b/OpenSim/Region/Framework/Interfaces/ISearchModule.cs
index 64bf72c..d56d188 100644
--- a/OpenSim/Region/Framework/Interfaces/ISearchModule.cs
+++ b/OpenSim/Region/Framework/Interfaces/ISearchModule.cs
@@ -31,6 +31,6 @@ namespace OpenSim.Framework
31{ 31{
32 public interface ISearchModule 32 public interface ISearchModule
33 { 33 {
34 34 void Refresh();
35 } 35 }
36} 36}
diff --git a/OpenSim/Region/Framework/Interfaces/ISimulationDataService.cs b/OpenSim/Region/Framework/Interfaces/ISimulationDataService.cs
index 085b5ca..3e97a7a 100644
--- a/OpenSim/Region/Framework/Interfaces/ISimulationDataService.cs
+++ b/OpenSim/Region/Framework/Interfaces/ISimulationDataService.cs
@@ -116,6 +116,8 @@ namespace OpenSim.Region.Framework.Interfaces
116 /// <param name="regionUUID">the region UUID</param> 116 /// <param name="regionUUID">the region UUID</param>
117 void RemoveRegionEnvironmentSettings(UUID regionUUID); 117 void RemoveRegionEnvironmentSettings(UUID regionUUID);
118 118
119 UUID[] GetObjectIDs(UUID regionID);
120
119 void SaveExtra(UUID regionID, string name, string value); 121 void SaveExtra(UUID regionID, string name, string value);
120 122
121 void RemoveExtra(UUID regionID, string name); 123 void RemoveExtra(UUID regionID, string name);
diff --git a/OpenSim/Region/Framework/Interfaces/ISimulationDataStore.cs b/OpenSim/Region/Framework/Interfaces/ISimulationDataStore.cs
index 3787ca0..17bd48b 100644
--- a/OpenSim/Region/Framework/Interfaces/ISimulationDataStore.cs
+++ b/OpenSim/Region/Framework/Interfaces/ISimulationDataStore.cs
@@ -106,6 +106,7 @@ namespace OpenSim.Region.Framework.Interfaces
106 RegionLightShareData LoadRegionWindlightSettings(UUID regionUUID); 106 RegionLightShareData LoadRegionWindlightSettings(UUID regionUUID);
107 void StoreRegionWindlightSettings(RegionLightShareData wl); 107 void StoreRegionWindlightSettings(RegionLightShareData wl);
108 void RemoveRegionWindlightSettings(UUID regionID); 108 void RemoveRegionWindlightSettings(UUID regionID);
109 UUID[] GetObjectIDs(UUID regionID);
109 110
110 /// <summary> 111 /// <summary>
111 /// Load Environment settings from region storage 112 /// Load Environment settings from region storage
diff --git a/OpenSim/Region/Framework/Interfaces/ISnmpModule.cs b/OpenSim/Region/Framework/Interfaces/ISnmpModule.cs
new file mode 100644
index 0000000..e01f649
--- /dev/null
+++ b/OpenSim/Region/Framework/Interfaces/ISnmpModule.cs
@@ -0,0 +1,27 @@
1///////////////////////////////////////////////////////////////////
2//
3// (c) Careminster LImited, Melanie Thielker and the Meta7 Team
4//
5// This file is not open source. All rights reserved
6// Mod 2
7
8using OpenSim.Region.Framework.Scenes;
9
10public interface ISnmpModule
11{
12 void Trap(int code, string Message, Scene scene);
13 void Critical(string Message, Scene scene);
14 void Warning(string Message, Scene scene);
15 void Major(string Message, Scene scene);
16 void ColdStart(int step , Scene scene);
17 void Shutdown(int step , Scene scene);
18 //
19 // Node Start/stop events
20 //
21 void LinkUp(Scene scene);
22 void LinkDown(Scene scene);
23 void BootInfo(string data, Scene scene);
24 void trapDebug(string Module,string data, Scene scene);
25 void trapXMRE(int data, string Message, Scene scene);
26
27}
diff --git a/OpenSim/Region/Framework/Interfaces/IUserAccountCacheModule.cs b/OpenSim/Region/Framework/Interfaces/IUserAccountCacheModule.cs
new file mode 100644
index 0000000..d1a4d8e
--- /dev/null
+++ b/OpenSim/Region/Framework/Interfaces/IUserAccountCacheModule.cs
@@ -0,0 +1,13 @@
1///////////////////////////////////////////////////////////////////
2//
3// (c) Careminster Limited, Melanie Thielker and the Meta7 Team
4//
5// This file is not open source. All rights reserved
6//
7
8using OpenSim.Region.Framework.Scenes;
9
10public interface IUserAccountCacheModule
11{
12 void Remove(string name);
13}
diff --git a/OpenSim/Region/Framework/Interfaces/IWorldComm.cs b/OpenSim/Region/Framework/Interfaces/IWorldComm.cs
index d76a0d7..20e0199 100644
--- a/OpenSim/Region/Framework/Interfaces/IWorldComm.cs
+++ b/OpenSim/Region/Framework/Interfaces/IWorldComm.cs
@@ -127,7 +127,7 @@ namespace OpenSim.Region.Framework.Interfaces
127 /// <param name='msg'> 127 /// <param name='msg'>
128 /// Message. 128 /// Message.
129 /// </param> 129 /// </param>
130 void DeliverMessageTo(UUID target, int channel, Vector3 pos, string name, UUID id, string msg); 130 bool DeliverMessageTo(UUID target, int channel, Vector3 pos, string name, UUID id, string msg, out string error);
131 131
132 /// <summary> 132 /// <summary>
133 /// Are there any listen events ready to be dispatched? 133 /// Are there any listen events ready to be dispatched?
diff --git a/OpenSim/Region/Framework/Scenes/Animation/ScenePresenceAnimator.cs b/OpenSim/Region/Framework/Scenes/Animation/ScenePresenceAnimator.cs
index e92a087..65c279e 100644
--- a/OpenSim/Region/Framework/Scenes/Animation/ScenePresenceAnimator.cs
+++ b/OpenSim/Region/Framework/Scenes/Animation/ScenePresenceAnimator.cs
@@ -80,12 +80,13 @@ namespace OpenSim.Region.Framework.Scenes.Animation
80 m_scenePresence = sp; 80 m_scenePresence = sp;
81 CurrentMovementAnimation = "CROUCH"; 81 CurrentMovementAnimation = "CROUCH";
82 } 82 }
83 83
84 public void AddAnimation(UUID animID, UUID objectID) 84 public void AddAnimation(UUID animID, UUID objectID)
85 { 85 {
86 if (m_scenePresence.IsChildAgent) 86 if (m_scenePresence.IsChildAgent)
87 return; 87 return;
88 88
89 // m_log.DebugFormat("[SCENE PRESENCE ANIMATOR]: Adding animation {0} for {1}", animID, m_scenePresence.Name);
89 if (m_scenePresence.Scene.DebugAnimations) 90 if (m_scenePresence.Scene.DebugAnimations)
90 m_log.DebugFormat( 91 m_log.DebugFormat(
91 "[SCENE PRESENCE ANIMATOR]: Adding animation {0} {1} for {2}", 92 "[SCENE PRESENCE ANIMATOR]: Adding animation {0} {1} for {2}",
@@ -134,6 +135,22 @@ namespace OpenSim.Region.Framework.Scenes.Animation
134 SendAnimPack(); 135 SendAnimPack();
135 } 136 }
136 137
138 public void avnChangeAnim(UUID animID, bool addRemove, bool sendPack)
139 {
140 if (m_scenePresence.IsChildAgent)
141 return;
142
143 if (animID != UUID.Zero)
144 {
145 if (addRemove)
146 m_animations.Add(animID, m_scenePresence.ControllingClient.NextAnimationSequenceNumber, UUID.Zero);
147 else
148 m_animations.Remove(animID, true);
149 }
150 if(sendPack)
151 SendAnimPack();
152 }
153
137 // Called from scripts 154 // Called from scripts
138 public void RemoveAnimation(string name) 155 public void RemoveAnimation(string name)
139 { 156 {
diff --git a/OpenSim/Region/Framework/Scenes/CollisionSounds.cs b/OpenSim/Region/Framework/Scenes/CollisionSounds.cs
new file mode 100644
index 0000000..075724e
--- /dev/null
+++ b/OpenSim/Region/Framework/Scenes/CollisionSounds.cs
@@ -0,0 +1,304 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27// Ubit 2012
28
29using System;
30using System.Reflection;
31using System.Collections.Generic;
32using OpenMetaverse;
33using OpenSim.Framework;
34using log4net;
35
36namespace OpenSim.Region.Framework.Scenes
37{
38 public struct CollisionForSoundInfo
39 {
40 public uint colliderID;
41 public Vector3 position;
42 public float relativeVel;
43 }
44
45 public static class CollisionSounds
46 {
47 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
48
49 private const int MaxMaterials = 7;
50 // part part
51
52 private static UUID snd_StoneStone = new UUID("be7295c0-a158-11e1-b3dd-0800200c9a66");
53 private static UUID snd_StoneMetal = new UUID("be7295c0-a158-11e1-b3dd-0800201c9a66");
54 private static UUID snd_StoneGlass = new UUID("be7295c0-a158-11e1-b3dd-0800202c9a66");
55 private static UUID snd_StoneWood = new UUID("be7295c0-a158-11e1-b3dd-0800203c9a66");
56 private static UUID snd_StoneFlesh = new UUID("be7295c0-a158-11e1-b3dd-0800204c9a66");
57 private static UUID snd_StonePlastic = new UUID("be7295c0-a158-11e1-b3dd-0800205c9a66");
58 private static UUID snd_StoneRubber = new UUID("be7295c0-a158-11e1-b3dd-0800206c9a66");
59
60 private static UUID snd_MetalMetal = new UUID("be7295c0-a158-11e1-b3dd-0801201c9a66");
61 private static UUID snd_MetalGlass = new UUID("be7295c0-a158-11e1-b3dd-0801202c9a66");
62 private static UUID snd_MetalWood = new UUID("be7295c0-a158-11e1-b3dd-0801203c9a66");
63 private static UUID snd_MetalFlesh = new UUID("be7295c0-a158-11e1-b3dd-0801204c9a66");
64 private static UUID snd_MetalPlastic = new UUID("be7295c0-a158-11e1-b3dd-0801205c9a66");
65 private static UUID snd_MetalRubber = new UUID("be7295c0-a158-11e1-b3dd-0801206c9a66");
66
67 private static UUID snd_GlassGlass = new UUID("be7295c0-a158-11e1-b3dd-0802202c9a66");
68 private static UUID snd_GlassWood = new UUID("be7295c0-a158-11e1-b3dd-0802203c9a66");
69 private static UUID snd_GlassFlesh = new UUID("be7295c0-a158-11e1-b3dd-0802204c9a66");
70 private static UUID snd_GlassPlastic = new UUID("be7295c0-a158-11e1-b3dd-0802205c9a66");
71 private static UUID snd_GlassRubber = new UUID("be7295c0-a158-11e1-b3dd-0802206c9a66");
72
73 private static UUID snd_WoodWood = new UUID("be7295c0-a158-11e1-b3dd-0803203c9a66");
74 private static UUID snd_WoodFlesh = new UUID("be7295c0-a158-11e1-b3dd-0803204c9a66");
75 private static UUID snd_WoodPlastic = new UUID("be7295c0-a158-11e1-b3dd-0803205c9a66");
76 private static UUID snd_WoodRubber = new UUID("be7295c0-a158-11e1-b3dd-0803206c9a66");
77
78 private static UUID snd_FleshFlesh = new UUID("be7295c0-a158-11e1-b3dd-0804204c9a66");
79 private static UUID snd_FleshPlastic = new UUID("be7295c0-a158-11e1-b3dd-0804205c9a66");
80 private static UUID snd_FleshRubber = new UUID("be7295c0-a158-11e1-b3dd-0804206c9a66");
81
82 private static UUID snd_PlasticPlastic = new UUID("be7295c0-a158-11e1-b3dd-0805205c9a66");
83 private static UUID snd_PlasticRubber = new UUID("be7295c0-a158-11e1-b3dd-0805206c9a66");
84
85 private static UUID snd_RubberRubber = new UUID("be7295c0-a158-11e1-b3dd-0806206c9a66");
86
87 // terrain part
88 private static UUID snd_TerrainStone = new UUID("be7295c0-a158-11e1-b3dd-0807200c9a66");
89 private static UUID snd_TerrainMetal = new UUID("be7295c0-a158-11e1-b3dd-0807200c9a66");
90 private static UUID snd_TerrainGlass = new UUID("be7295c0-a158-11e1-b3dd-0807200c9a66");
91 private static UUID snd_TerrainWood = new UUID("be7295c0-a158-11e1-b3dd-0807200c9a66");
92 private static UUID snd_TerrainFlesh = new UUID("be7295c0-a158-11e1-b3dd-0807200c9a66");
93 private static UUID snd_TerrainPlastic = new UUID("be7295c0-a158-11e1-b3dd-0807200c9a66");
94 private static UUID snd_TerrainRubber = new UUID("be7295c0-a158-11e1-b3dd-0807200c9a66");
95
96 public static UUID[] m_TerrainPart = {
97 snd_TerrainStone,
98 snd_TerrainMetal,
99 snd_TerrainGlass,
100 snd_TerrainWood,
101 snd_TerrainFlesh,
102 snd_TerrainPlastic,
103 snd_TerrainRubber
104 };
105
106 // simetric sounds
107 public static UUID[] m_PartPart = {
108 snd_StoneStone, snd_StoneMetal, snd_StoneGlass, snd_StoneWood, snd_StoneFlesh, snd_StonePlastic, snd_StoneRubber,
109 snd_StoneMetal, snd_MetalMetal, snd_MetalGlass, snd_MetalWood, snd_MetalFlesh, snd_MetalPlastic, snd_MetalRubber,
110 snd_StoneGlass, snd_MetalGlass, snd_GlassGlass, snd_GlassWood, snd_GlassFlesh, snd_GlassPlastic, snd_GlassRubber,
111 snd_StoneWood, snd_MetalWood, snd_GlassWood, snd_WoodWood, snd_WoodFlesh, snd_WoodPlastic, snd_WoodRubber,
112 snd_StoneFlesh, snd_MetalFlesh, snd_GlassFlesh, snd_WoodFlesh, snd_FleshFlesh, snd_FleshPlastic, snd_FleshRubber,
113 snd_StonePlastic, snd_MetalPlastic, snd_GlassPlastic, snd_WoodPlastic, snd_FleshPlastic, snd_PlasticPlastic, snd_PlasticRubber,
114 snd_StoneRubber, snd_MetalRubber, snd_GlassRubber, snd_WoodRubber, snd_FleshRubber, snd_PlasticRubber, snd_RubberRubber
115 };
116
117 public static void PartCollisionSound(SceneObjectPart part, List<CollisionForSoundInfo> collidersinfolist)
118 {
119 if (collidersinfolist.Count == 0 || part == null)
120 return;
121
122 if (part.VolumeDetectActive || (part.Flags & PrimFlags.Physics) == 0)
123 return;
124
125 if (part.ParentGroup == null)
126 return;
127
128 if (part.CollisionSoundType < 0)
129 return;
130
131 float volume = 0.0f;
132 bool HaveSound = false;
133
134 UUID soundID = part.CollisionSound;
135
136 if (part.CollisionSoundType > 0)
137 {
138 // soundID = part.CollisionSound;
139 volume = part.CollisionSoundVolume;
140 if (volume == 0.0f)
141 return;
142 HaveSound = true;
143 }
144
145 bool doneownsound = false;
146
147 int thisMaterial = (int)part.Material;
148 if (thisMaterial >= MaxMaterials)
149 thisMaterial = 3;
150 int thisMatScaled = thisMaterial * MaxMaterials;
151
152 CollisionForSoundInfo colInfo;
153 uint id;
154
155 for(int i = 0; i< collidersinfolist.Count; i++)
156 {
157 colInfo = collidersinfolist[i];
158
159 id = colInfo.colliderID;
160 if (id == 0) // terrain collision
161 {
162 if (!doneownsound)
163 {
164 if (!HaveSound)
165 {
166 volume = Math.Abs(colInfo.relativeVel);
167 if (volume < 0.2f)
168 continue;
169
170 volume *= volume * .0625f; // 4m/s == full volume
171 if (volume > 1.0f)
172 volume = 1.0f;
173
174 soundID = m_TerrainPart[thisMaterial];
175 }
176 part.SendCollisionSound(soundID, volume, colInfo.position);
177 doneownsound = true;
178 }
179 continue;
180 }
181
182 SceneObjectPart otherPart = part.ParentGroup.Scene.GetSceneObjectPart(id);
183 if (otherPart != null)
184 {
185 if (otherPart.CollisionSoundType < 0 || otherPart.VolumeDetectActive)
186 continue;
187
188 if (!HaveSound)
189 {
190 if (otherPart.CollisionSoundType > 0)
191 {
192 soundID = otherPart.CollisionSound;
193 volume = otherPart.CollisionSoundVolume;
194 if (volume == 0.0f)
195 continue;
196 }
197 else
198 {
199 volume = Math.Abs(colInfo.relativeVel);
200 if (volume < 0.2f)
201 continue;
202
203 volume *= volume * .0625f; // 4m/s == full volume
204 if (volume > 1.0f)
205 volume = 1.0f;
206
207 int otherMaterial = (int)otherPart.Material;
208 if (otherMaterial >= MaxMaterials)
209 otherMaterial = 3;
210
211 soundID = m_PartPart[thisMatScaled + otherMaterial];
212 }
213 }
214
215 if (doneownsound)
216 otherPart.SendCollisionSound(soundID, volume, colInfo.position);
217 else
218 {
219 part.SendCollisionSound(soundID, volume, colInfo.position);
220 doneownsound = true;
221 }
222 }
223 }
224 }
225
226 public static void AvatarCollisionSound(ScenePresence av, List<CollisionForSoundInfo> collidersinfolist)
227 {
228 if (collidersinfolist.Count == 0 || av == null)
229 return;
230
231 UUID soundID;
232 int otherMaterial;
233
234 int thisMaterial = 4; // flesh
235
236 int thisMatScaled = thisMaterial * MaxMaterials;
237
238 // bool doneownsound = false;
239
240 CollisionForSoundInfo colInfo;
241 uint id;
242 float volume;
243
244 for(int i = 0; i< collidersinfolist.Count; i++)
245 {
246 colInfo = collidersinfolist[i];
247
248 id = colInfo.colliderID;
249
250 if (id == 0) // no terrain collision sounds for now
251 {
252 continue;
253// volume = Math.Abs(colInfo.relativeVel);
254// if (volume < 0.2f)
255// continue;
256
257 }
258
259 SceneObjectPart otherPart = av.Scene.GetSceneObjectPart(id);
260 if (otherPart != null)
261 {
262 if (otherPart.CollisionSoundType < 0)
263 continue;
264 if (otherPart.CollisionSoundType > 0 && otherPart.CollisionSoundVolume > 0f)
265 otherPart.SendCollisionSound(otherPart.CollisionSound, otherPart.CollisionSoundVolume, colInfo.position);
266 else
267 {
268 volume = Math.Abs(colInfo.relativeVel);
269 // Most noral collisions (running into walls, stairs)
270 // should never be heard.
271 if (volume < 3.2f)
272 continue;
273// m_log.DebugFormat("Collision speed was {0}", volume);
274
275 // Cap to 0.2 times volume because climbing stairs should not be noisy
276 // Also changed scaling
277 volume *= volume * .0125f; // 4m/s == volume 0.2
278 if (volume > 0.2f)
279 volume = 0.2f;
280 otherMaterial = (int)otherPart.Material;
281 if (otherMaterial >= MaxMaterials)
282 otherMaterial = 3;
283
284 soundID = m_PartPart[thisMatScaled + otherMaterial];
285 otherPart.SendCollisionSound(soundID, volume, colInfo.position);
286 }
287 continue;
288 }
289/*
290 else if (!doneownsound)
291 {
292 ScenePresence otherav = av.Scene.GetScenePresence(Id);
293 if (otherav != null && (!otherav.IsChildAgent))
294 {
295 soundID = snd_FleshFlesh;
296 av.SendCollisionSound(soundID, 1.0);
297 doneownsound = true;
298 }
299 }
300 */
301 }
302 }
303 }
304}
diff --git a/OpenSim/Region/Framework/Scenes/EventManager.cs b/OpenSim/Region/Framework/Scenes/EventManager.cs
index 902ded1..ac5f433 100644
--- a/OpenSim/Region/Framework/Scenes/EventManager.cs
+++ b/OpenSim/Region/Framework/Scenes/EventManager.cs
@@ -90,6 +90,10 @@ namespace OpenSim.Region.Framework.Scenes
90 /// </remarks> 90 /// </remarks>
91 public event OnTerrainTickDelegate OnTerrainTick; 91 public event OnTerrainTickDelegate OnTerrainTick;
92 92
93 public delegate void OnTerrainUpdateDelegate();
94
95 public event OnTerrainUpdateDelegate OnTerrainUpdate;
96
93 public delegate void OnBackupDelegate(ISimulationDataService datastore, bool forceBackup); 97 public delegate void OnBackupDelegate(ISimulationDataService datastore, bool forceBackup);
94 98
95 /// <summary> 99 /// <summary>
@@ -339,8 +343,6 @@ namespace OpenSim.Region.Framework.Scenes
339 /// in <see cref="Scene.SetScriptRunning"/> 343 /// in <see cref="Scene.SetScriptRunning"/>
340 /// via <see cref="OpenSim.Framework.IClientAPI.OnSetScriptRunning"/>, 344 /// via <see cref="OpenSim.Framework.IClientAPI.OnSetScriptRunning"/>,
341 /// via <see cref="OpenSim.Region.ClientStack.LindenUDP.HandleSetScriptRunning"/> 345 /// via <see cref="OpenSim.Region.ClientStack.LindenUDP.HandleSetScriptRunning"/>
342 /// XXX: This is only triggered when it is the client that starts the script, not in other situations where
343 /// a script is started, unlike OnStopScript!
344 /// </remarks> 346 /// </remarks>
345 public event StartScript OnStartScript; 347 public event StartScript OnStartScript;
346 348
@@ -354,7 +356,6 @@ namespace OpenSim.Region.Framework.Scenes
354 /// in <see cref="SceneObjectPartInventory.CreateScriptInstance"/>, 356 /// in <see cref="SceneObjectPartInventory.CreateScriptInstance"/>,
355 /// <see cref="SceneObjectPartInventory.StopScriptInstance"/>, 357 /// <see cref="SceneObjectPartInventory.StopScriptInstance"/>,
356 /// <see cref="Scene.SetScriptRunning"/> 358 /// <see cref="Scene.SetScriptRunning"/>
357 /// XXX: This is triggered when a sciprt is stopped for any reason, unlike OnStartScript!
358 /// </remarks> 359 /// </remarks>
359 public event StopScript OnStopScript; 360 public event StopScript OnStopScript;
360 361
@@ -815,6 +816,10 @@ namespace OpenSim.Region.Framework.Scenes
815 public event ParcelPrimCountTainted OnParcelPrimCountTainted; 816 public event ParcelPrimCountTainted OnParcelPrimCountTainted;
816 public event GetScriptRunning OnGetScriptRunning; 817 public event GetScriptRunning OnGetScriptRunning;
817 818
819 public delegate void ThrottleUpdate(ScenePresence scenePresence);
820
821 public event ThrottleUpdate OnThrottleUpdate;
822
818 /// <summary> 823 /// <summary>
819 /// RegisterCapsEvent is called by Scene after the Caps object 824 /// RegisterCapsEvent is called by Scene after the Caps object
820 /// has been instantiated and before it is return to the 825 /// has been instantiated and before it is return to the
@@ -1396,6 +1401,26 @@ namespace OpenSim.Region.Framework.Scenes
1396 } 1401 }
1397 } 1402 }
1398 } 1403 }
1404 public void TriggerTerrainUpdate()
1405 {
1406 OnTerrainUpdateDelegate handlerTerrainUpdate = OnTerrainUpdate;
1407 if (handlerTerrainUpdate != null)
1408 {
1409 foreach (OnTerrainUpdateDelegate d in handlerTerrainUpdate.GetInvocationList())
1410 {
1411 try
1412 {
1413 d();
1414 }
1415 catch (Exception e)
1416 {
1417 m_log.ErrorFormat(
1418 "[EVENT MANAGER]: Delegate for TriggerTerrainUpdate failed - continuing. {0} {1}",
1419 e.Message, e.StackTrace);
1420 }
1421 }
1422 }
1423 }
1399 1424
1400 public void TriggerTerrainTick() 1425 public void TriggerTerrainTick()
1401 { 1426 {
@@ -1686,6 +1711,7 @@ namespace OpenSim.Region.Framework.Scenes
1686 m_log.ErrorFormat( 1711 m_log.ErrorFormat(
1687 "[EVENT MANAGER]: Delegate for TriggerRemoveScript failed - continuing. {0} {1}", 1712 "[EVENT MANAGER]: Delegate for TriggerRemoveScript failed - continuing. {0} {1}",
1688 e.Message, e.StackTrace); 1713 e.Message, e.StackTrace);
1714 m_log.ErrorFormat(Environment.StackTrace);
1689 } 1715 }
1690 } 1716 }
1691 } 1717 }
@@ -2922,6 +2948,7 @@ namespace OpenSim.Region.Framework.Scenes
2922 { 2948 {
2923 foreach (Action<Scene> d in handler.GetInvocationList()) 2949 foreach (Action<Scene> d in handler.GetInvocationList())
2924 { 2950 {
2951 m_log.InfoFormat("[EVENT MANAGER]: TriggerSceneShuttingDown invoque {0}", d.Method.Name.ToString());
2925 try 2952 try
2926 { 2953 {
2927 d(s); 2954 d(s);
@@ -2934,6 +2961,7 @@ namespace OpenSim.Region.Framework.Scenes
2934 } 2961 }
2935 } 2962 }
2936 } 2963 }
2964 m_log.Info("[EVENT MANAGER]: TriggerSceneShuttingDown done");
2937 } 2965 }
2938 2966
2939 public void TriggerOnRegionStarted(Scene scene) 2967 public void TriggerOnRegionStarted(Scene scene)
@@ -3103,5 +3131,14 @@ namespace OpenSim.Region.Framework.Scenes
3103 } 3131 }
3104 } 3132 }
3105 } 3133 }
3134
3135 public void TriggerThrottleUpdate(ScenePresence scenePresence)
3136 {
3137 ThrottleUpdate handler = OnThrottleUpdate;
3138 if (handler != null)
3139 {
3140 handler(scenePresence);
3141 }
3142 }
3106 } 3143 }
3107} 3144}
diff --git a/OpenSim/Region/Framework/Scenes/KeyframeMotion.cs b/OpenSim/Region/Framework/Scenes/KeyframeMotion.cs
new file mode 100644
index 0000000..5cfba39
--- /dev/null
+++ b/OpenSim/Region/Framework/Scenes/KeyframeMotion.cs
@@ -0,0 +1,707 @@
1// Proprietary code of Avination Virtual Limited
2// (c) 2012 Melanie Thielker
3//
4
5using System;
6using System.Timers;
7using System.Collections;
8using System.Collections.Generic;
9using System.IO;
10using System.Diagnostics;
11using System.Reflection;
12using System.Threading;
13using OpenMetaverse;
14using OpenSim.Framework;
15using OpenSim.Region.Framework.Interfaces;
16using OpenSim.Region.Physics.Manager;
17using OpenSim.Region.Framework.Scenes.Serialization;
18using System.Runtime.Serialization.Formatters.Binary;
19using System.Runtime.Serialization;
20using Timer = System.Timers.Timer;
21using log4net;
22
23namespace OpenSim.Region.Framework.Scenes
24{
25 [Serializable]
26 public class KeyframeMotion
27 {
28 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
29
30 public enum PlayMode : int
31 {
32 Forward = 0,
33 Reverse = 1,
34 Loop = 2,
35 PingPong = 3
36 };
37
38 [Flags]
39 public enum DataFormat : int
40 {
41 Translation = 2,
42 Rotation = 1
43 }
44
45 [Serializable]
46 public struct Keyframe
47 {
48 public Vector3? Position;
49 public Quaternion? Rotation;
50 public Quaternion StartRotation;
51 public int TimeMS;
52 public int TimeTotal;
53 public Vector3 AngularVelocity;
54 };
55
56 private Vector3 m_serializedPosition;
57 private Vector3 m_basePosition;
58 private Quaternion m_baseRotation;
59
60 private Keyframe m_currentFrame;
61
62 private List<Keyframe> m_frames = new List<Keyframe>();
63
64 private Keyframe[] m_keyframes;
65
66 [NonSerialized()]
67 protected Timer m_timer = null;
68
69 // timer lock
70 [NonSerialized()]
71 private object m_onTimerLock;
72
73 // timer overrun detect
74 // prevents overlap or timer events threads frozen on the lock
75 [NonSerialized()]
76 private bool m_inOnTimer;
77
78 // skip timer events.
79 //timer.stop doesn't assure there aren't event threads still being fired
80 [NonSerialized()]
81 private bool m_timerStopped;
82
83 [NonSerialized()]
84 private bool m_isCrossing;
85
86 [NonSerialized()]
87 private bool m_waitingCrossing;
88
89 // retry position for cross fail
90 [NonSerialized()]
91 private Vector3 m_nextPosition;
92
93 [NonSerialized()]
94 private SceneObjectGroup m_group;
95
96 private PlayMode m_mode = PlayMode.Forward;
97 private DataFormat m_data = DataFormat.Translation | DataFormat.Rotation;
98
99 private bool m_running = false;
100 [NonSerialized()]
101 private bool m_selected = false;
102
103 private int m_iterations = 0;
104
105 private const double timerInterval = 50.0;
106
107 public DataFormat Data
108 {
109 get { return m_data; }
110 }
111
112 public bool Selected
113 {
114 set
115 {
116 if (m_group != null)
117 {
118 if (!value)
119 {
120 // Once we're let go, recompute positions
121 if (m_selected)
122 UpdateSceneObject(m_group);
123 }
124 else
125 {
126 // Save selection position in case we get moved
127 if (!m_selected)
128 {
129 StopTimer();
130 m_serializedPosition = m_group.AbsolutePosition;
131 }
132 }
133 }
134 m_isCrossing = false;
135 m_waitingCrossing = false;
136 m_selected = value;
137 }
138 }
139
140 private void StartTimer()
141 {
142 if (m_timer == null)
143 return;
144 m_timerStopped = false;
145 m_timer.Start();
146 }
147
148 private void StopTimer()
149 {
150 if (m_timer == null || m_timerStopped)
151 return;
152 m_timerStopped = true;
153 m_timer.Stop();
154 }
155
156 private void RemoveTimer()
157 {
158 if (m_timer == null)
159 return;
160 m_timerStopped = true;
161 m_timer.Stop();
162 m_timer.Elapsed -= OnTimer;
163 m_timer = null;
164 }
165
166
167 public static KeyframeMotion FromData(SceneObjectGroup grp, Byte[] data)
168 {
169 KeyframeMotion newMotion = null;
170
171 try
172 {
173 MemoryStream ms = new MemoryStream(data);
174 BinaryFormatter fmt = new BinaryFormatter();
175
176 newMotion = (KeyframeMotion)fmt.Deserialize(ms);
177
178 newMotion.m_group = grp;
179
180 if (grp != null && grp.IsSelected)
181 newMotion.m_selected = true;
182
183 newMotion.m_onTimerLock = new object();
184 newMotion.m_timerStopped = false;
185 newMotion.m_inOnTimer = false;
186 newMotion.m_isCrossing = false;
187 newMotion.m_waitingCrossing = false;
188 }
189 catch
190 {
191 newMotion = null;
192 }
193
194 return newMotion;
195 }
196
197 public void UpdateSceneObject(SceneObjectGroup grp)
198 {
199// lock (m_onTimerLock)
200 {
201 m_isCrossing = false;
202 m_waitingCrossing = false;
203 StopTimer();
204
205 if (grp == null)
206 return;
207
208 m_group = grp;
209 Vector3 grppos = grp.AbsolutePosition;
210 Vector3 offset = grppos - m_serializedPosition;
211 // avoid doing it more than once
212 // current this will happen draging a prim to other region
213 m_serializedPosition = grppos;
214
215 m_basePosition += offset;
216 m_currentFrame.Position += offset;
217
218 m_nextPosition += offset;
219
220 for (int i = 0; i < m_frames.Count; i++)
221 {
222 Keyframe k = m_frames[i];
223 k.Position += offset;
224 m_frames[i]=k;
225 }
226
227 if (m_running)
228 Start();
229 }
230 }
231
232 public KeyframeMotion(SceneObjectGroup grp, PlayMode mode, DataFormat data)
233 {
234 m_mode = mode;
235 m_data = data;
236
237 m_group = grp;
238 if (grp != null)
239 {
240 m_basePosition = grp.AbsolutePosition;
241 m_baseRotation = grp.GroupRotation;
242 }
243
244 m_onTimerLock = new object();
245 m_timerStopped = true;
246 m_inOnTimer = false;
247 m_isCrossing = false;
248 m_waitingCrossing = false;
249 }
250
251 public void SetKeyframes(Keyframe[] frames)
252 {
253 m_keyframes = frames;
254 }
255
256 public KeyframeMotion Copy(SceneObjectGroup newgrp)
257 {
258 StopTimer();
259
260 KeyframeMotion newmotion = new KeyframeMotion(null, m_mode, m_data);
261
262 newmotion.m_group = newgrp;
263
264 if (m_keyframes != null)
265 {
266 newmotion.m_keyframes = new Keyframe[m_keyframes.Length];
267 m_keyframes.CopyTo(newmotion.m_keyframes, 0);
268 }
269
270 newmotion.m_frames = new List<Keyframe>(m_frames);
271
272 newmotion.m_basePosition = m_basePosition;
273 newmotion.m_baseRotation = m_baseRotation;
274
275 if (m_selected)
276 newmotion.m_serializedPosition = m_serializedPosition;
277 else
278 {
279 if (m_group != null)
280 newmotion.m_serializedPosition = m_group.AbsolutePosition;
281 else
282 newmotion.m_serializedPosition = m_serializedPosition;
283 }
284
285 newmotion.m_currentFrame = m_currentFrame;
286
287 newmotion.m_iterations = m_iterations;
288 newmotion.m_running = m_running;
289
290 if (m_running && !m_waitingCrossing)
291 StartTimer();
292
293 return newmotion;
294 }
295
296 public void Delete()
297 {
298 m_running = false;
299 RemoveTimer();
300 m_isCrossing = false;
301 m_waitingCrossing = false;
302 m_frames.Clear();
303 m_keyframes = null;
304 }
305
306 public void Start()
307 {
308 m_isCrossing = false;
309 m_waitingCrossing = false;
310 if (m_keyframes != null && m_group != null && m_keyframes.Length > 0)
311 {
312 if (m_timer == null)
313 {
314 m_timer = new Timer();
315 m_timer.Interval = timerInterval;
316 m_timer.AutoReset = true;
317 m_timer.Elapsed += OnTimer;
318 }
319 else
320 {
321 StopTimer();
322 m_timer.Interval = timerInterval;
323 }
324
325 m_inOnTimer = false;
326 StartTimer();
327 m_running = true;
328 }
329 else
330 {
331 m_running = false;
332 RemoveTimer();
333 }
334 }
335
336 public void Stop()
337 {
338 m_running = false;
339 m_isCrossing = false;
340 m_waitingCrossing = false;
341
342 RemoveTimer();
343
344 m_basePosition = m_group.AbsolutePosition;
345 m_baseRotation = m_group.GroupRotation;
346
347 m_group.RootPart.Velocity = Vector3.Zero;
348 m_group.RootPart.AngularVelocity = Vector3.Zero;
349 m_group.SendGroupRootTerseUpdate();
350// m_group.RootPart.ScheduleTerseUpdate();
351 m_frames.Clear();
352 }
353
354 public void Pause()
355 {
356 m_running = false;
357 RemoveTimer();
358
359 m_group.RootPart.Velocity = Vector3.Zero;
360 m_group.RootPart.AngularVelocity = Vector3.Zero;
361 m_group.SendGroupRootTerseUpdate();
362// m_group.RootPart.ScheduleTerseUpdate();
363
364 }
365
366 private void GetNextList()
367 {
368 m_frames.Clear();
369 Vector3 pos = m_basePosition;
370 Quaternion rot = m_baseRotation;
371
372 if (m_mode == PlayMode.Loop || m_mode == PlayMode.PingPong || m_iterations == 0)
373 {
374 int direction = 1;
375 if (m_mode == PlayMode.Reverse || ((m_mode == PlayMode.PingPong) && ((m_iterations & 1) != 0)))
376 direction = -1;
377
378 int start = 0;
379 int end = m_keyframes.Length;
380// if (m_mode == PlayMode.PingPong && m_keyframes.Length > 1)
381// end = m_keyframes.Length - 1;
382
383 if (direction < 0)
384 {
385 start = m_keyframes.Length - 1;
386 end = -1;
387// if (m_mode == PlayMode.PingPong && m_keyframes.Length > 1)
388// end = 0;
389 }
390
391 for (int i = start; i != end ; i += direction)
392 {
393 Keyframe k = m_keyframes[i];
394
395 if (k.Position.HasValue)
396 {
397 k.Position = (k.Position * direction);
398// k.Velocity = (Vector3)k.Position / (k.TimeMS / 1000.0f);
399 k.Position += pos;
400 }
401 else
402 {
403 k.Position = pos;
404// k.Velocity = Vector3.Zero;
405 }
406
407 k.StartRotation = rot;
408 if (k.Rotation.HasValue)
409 {
410 if (direction == -1)
411 k.Rotation = Quaternion.Conjugate((Quaternion)k.Rotation);
412 k.Rotation = rot * k.Rotation;
413 }
414 else
415 {
416 k.Rotation = rot;
417 }
418
419/* ang vel not in use for now
420
421 float angle = 0;
422
423 float aa = k.StartRotation.X * k.StartRotation.X + k.StartRotation.Y * k.StartRotation.Y + k.StartRotation.Z * k.StartRotation.Z + k.StartRotation.W * k.StartRotation.W;
424 float bb = ((Quaternion)k.Rotation).X * ((Quaternion)k.Rotation).X + ((Quaternion)k.Rotation).Y * ((Quaternion)k.Rotation).Y + ((Quaternion)k.Rotation).Z * ((Quaternion)k.Rotation).Z + ((Quaternion)k.Rotation).W * ((Quaternion)k.Rotation).W;
425 float aa_bb = aa * bb;
426
427 if (aa_bb == 0)
428 {
429 angle = 0;
430 }
431 else
432 {
433 float ab = k.StartRotation.X * ((Quaternion)k.Rotation).X +
434 k.StartRotation.Y * ((Quaternion)k.Rotation).Y +
435 k.StartRotation.Z * ((Quaternion)k.Rotation).Z +
436 k.StartRotation.W * ((Quaternion)k.Rotation).W;
437 float q = (ab * ab) / aa_bb;
438
439 if (q > 1.0f)
440 {
441 angle = 0;
442 }
443 else
444 {
445 angle = (float)Math.Acos(2 * q - 1);
446 }
447 }
448
449 k.AngularVelocity = (new Vector3(0, 0, 1) * (Quaternion)k.Rotation) * (angle / (k.TimeMS / 1000));
450 */
451 k.TimeTotal = k.TimeMS;
452
453 m_frames.Add(k);
454
455 pos = (Vector3)k.Position;
456 rot = (Quaternion)k.Rotation;
457 }
458
459 m_basePosition = pos;
460 m_baseRotation = rot;
461
462 m_iterations++;
463 }
464 }
465
466 protected void OnTimer(object sender, ElapsedEventArgs e)
467 {
468 if (m_timerStopped) // trap events still in air even after a timer.stop
469 return;
470
471 if (m_inOnTimer) // don't let overruns to happen
472 {
473 m_log.Warn("[KeyFrame]: timer overrun");
474 return;
475 }
476
477 if (m_group == null)
478 return;
479
480 lock (m_onTimerLock)
481 {
482
483 m_inOnTimer = true;
484
485 bool update = false;
486
487 try
488 {
489 if (m_selected)
490 {
491 if (m_group.RootPart.Velocity != Vector3.Zero)
492 {
493 m_group.RootPart.Velocity = Vector3.Zero;
494 m_group.SendGroupRootTerseUpdate();
495// m_group.RootPart.ScheduleTerseUpdate();
496
497 }
498 m_inOnTimer = false;
499 return;
500 }
501
502 if (m_isCrossing)
503 {
504 // if crossing and timer running then cross failed
505 // wait some time then
506 // retry to set the position that evtually caused the outbound
507 // if still outside region this will call startCrossing below
508 m_isCrossing = false;
509 m_group.AbsolutePosition = m_nextPosition;
510 if (!m_isCrossing)
511 {
512 StopTimer();
513 m_timer.Interval = timerInterval;
514 StartTimer();
515 }
516 m_inOnTimer = false;
517 return;
518 }
519
520 if (m_frames.Count == 0)
521 {
522 GetNextList();
523
524 if (m_frames.Count == 0)
525 {
526 Stop();
527 m_inOnTimer = false;
528 return;
529 }
530
531 m_currentFrame = m_frames[0];
532 m_currentFrame.TimeMS += (int)timerInterval;
533
534 //force a update on a keyframe transition
535 update = true;
536 }
537
538 m_currentFrame.TimeMS -= (int)timerInterval;
539
540 // Do the frame processing
541 double steps = (double)m_currentFrame.TimeMS / timerInterval;
542
543 if (steps <= 0.0)
544 {
545 m_group.RootPart.Velocity = Vector3.Zero;
546 m_group.RootPart.AngularVelocity = Vector3.Zero;
547
548 m_nextPosition = (Vector3)m_currentFrame.Position;
549 m_group.AbsolutePosition = m_nextPosition;
550
551 // we are sending imediate updates, no doing force a extra terseUpdate
552// m_group.UpdateGroupRotationR((Quaternion)m_currentFrame.Rotation);
553
554 m_group.RootPart.RotationOffset = (Quaternion)m_currentFrame.Rotation;
555 m_frames.RemoveAt(0);
556 if (m_frames.Count > 0)
557 m_currentFrame = m_frames[0];
558
559 update = true;
560 }
561 else
562 {
563 float complete = ((float)m_currentFrame.TimeTotal - (float)m_currentFrame.TimeMS) / (float)m_currentFrame.TimeTotal;
564
565 Vector3 v = (Vector3)m_currentFrame.Position - m_group.AbsolutePosition;
566 Vector3 motionThisFrame = v / (float)steps;
567 v = v * 1000 / m_currentFrame.TimeMS;
568
569 if (Vector3.Mag(motionThisFrame) >= 0.05f)
570 {
571 // m_group.AbsolutePosition += motionThisFrame;
572 m_nextPosition = m_group.AbsolutePosition + motionThisFrame;
573 m_group.AbsolutePosition = m_nextPosition;
574
575 m_group.RootPart.Velocity = v;
576 update = true;
577 }
578
579 if ((Quaternion)m_currentFrame.Rotation != m_group.GroupRotation)
580 {
581 Quaternion current = m_group.GroupRotation;
582
583 Quaternion step = Quaternion.Slerp(m_currentFrame.StartRotation, (Quaternion)m_currentFrame.Rotation, complete);
584 step.Normalize();
585/* use simpler change detection
586 * float angle = 0;
587
588 float aa = current.X * current.X + current.Y * current.Y + current.Z * current.Z + current.W * current.W;
589 float bb = step.X * step.X + step.Y * step.Y + step.Z * step.Z + step.W * step.W;
590 float aa_bb = aa * bb;
591
592 if (aa_bb == 0)
593 {
594 angle = 0;
595 }
596 else
597 {
598 float ab = current.X * step.X +
599 current.Y * step.Y +
600 current.Z * step.Z +
601 current.W * step.W;
602 float q = (ab * ab) / aa_bb;
603
604 if (q > 1.0f)
605 {
606 angle = 0;
607 }
608 else
609 {
610 angle = (float)Math.Acos(2 * q - 1);
611 }
612 }
613
614 if (angle > 0.01f)
615 */
616 if(Math.Abs(step.X - current.X) > 0.001f
617 || Math.Abs(step.Y - current.Y) > 0.001f
618 || Math.Abs(step.Z - current.Z) > 0.001f)
619 // assuming w is a dependente var
620
621 {
622// m_group.UpdateGroupRotationR(step);
623 m_group.RootPart.RotationOffset = step;
624
625 //m_group.RootPart.UpdateAngularVelocity(m_currentFrame.AngularVelocity / 2);
626 update = true;
627 }
628 }
629 }
630
631 if (update)
632 m_group.SendGroupRootTerseUpdate();
633// m_group.RootPart.ScheduleTerseUpdate();
634
635
636 }
637 catch ( Exception ex)
638 {
639 // still happening sometimes
640 // lets try to see where
641 m_log.Warn("[KeyFrame]: timer overrun" + ex.Message);
642 }
643
644 finally
645 {
646 // make sure we do not let this frozen
647 m_inOnTimer = false;
648 }
649 }
650 }
651
652 public Byte[] Serialize()
653 {
654 StopTimer();
655 MemoryStream ms = new MemoryStream();
656
657 BinaryFormatter fmt = new BinaryFormatter();
658 SceneObjectGroup tmp = m_group;
659 m_group = null;
660 if (!m_selected && tmp != null)
661 m_serializedPosition = tmp.AbsolutePosition;
662 fmt.Serialize(ms, this);
663 m_group = tmp;
664 if (m_running && !m_waitingCrossing)
665 StartTimer();
666
667 return ms.ToArray();
668 }
669
670 public void StartCrossingCheck()
671 {
672 // timer will be restart by crossingFailure
673 // or never since crossing worked and this
674 // should be deleted
675 StopTimer();
676
677 m_isCrossing = true;
678 m_waitingCrossing = true;
679
680// to remove / retune to smoth crossings
681 if (m_group.RootPart.Velocity != Vector3.Zero)
682 {
683 m_group.RootPart.Velocity = Vector3.Zero;
684 m_group.SendGroupRootTerseUpdate();
685// m_group.RootPart.ScheduleTerseUpdate();
686 }
687 }
688
689 public void CrossingFailure()
690 {
691 m_waitingCrossing = false;
692
693 if (m_group != null)
694 {
695 m_group.RootPart.Velocity = Vector3.Zero;
696 m_group.SendGroupRootTerseUpdate();
697// m_group.RootPart.ScheduleTerseUpdate();
698
699 if (m_running && m_timer != null)
700 {
701 m_timer.Interval = 60000;
702 StartTimer();
703 }
704 }
705 }
706 }
707}
diff --git a/OpenSim/Region/Framework/Scenes/Prioritizer.cs b/OpenSim/Region/Framework/Scenes/Prioritizer.cs
index 1b10e3c..ddae073 100644
--- a/OpenSim/Region/Framework/Scenes/Prioritizer.cs
+++ b/OpenSim/Region/Framework/Scenes/Prioritizer.cs
@@ -157,7 +157,7 @@ namespace OpenSim.Region.Framework.Scenes
157 157
158 private uint GetPriorityByBestAvatarResponsiveness(IClientAPI client, ISceneEntity entity) 158 private uint GetPriorityByBestAvatarResponsiveness(IClientAPI client, ISceneEntity entity)
159 { 159 {
160 uint pqueue = ComputeDistancePriority(client,entity,true); 160 uint pqueue = ComputeDistancePriority(client,entity,false);
161 161
162 ScenePresence presence = m_scene.GetScenePresence(client.AgentId); 162 ScenePresence presence = m_scene.GetScenePresence(client.AgentId);
163 if (presence != null) 163 if (presence != null)
@@ -212,9 +212,15 @@ namespace OpenSim.Region.Framework.Scenes
212 } 212 }
213 213
214 // Use the camera position for local agents and avatar position for remote agents 214 // Use the camera position for local agents and avatar position for remote agents
215 Vector3 presencePos = (presence.IsChildAgent) ? 215 // Why would I want that? They could be camming but I still see them at the
216 presence.AbsolutePosition : 216 // avatar position, so why should I update them as if they were at their
217 presence.CameraPosition; 217 // camera positions? Makes no sense!
218 // TODO: Fix this mess
219 //Vector3 presencePos = (presence.IsChildAgent) ?
220 // presence.AbsolutePosition :
221 // presence.CameraPosition;
222
223 Vector3 presencePos = presence.AbsolutePosition;
218 224
219 // Compute the distance... 225 // Compute the distance...
220 double distance = Vector3.Distance(presencePos, entityPos); 226 double distance = Vector3.Distance(presencePos, entityPos);
@@ -226,7 +232,7 @@ namespace OpenSim.Region.Framework.Scenes
226 232
227 for (int i = 0; i < queues - 1; i++) 233 for (int i = 0; i < queues - 1; i++)
228 { 234 {
229 if (distance < 10 * Math.Pow(2.0,i)) 235 if (distance < 30 * Math.Pow(2.0,i))
230 break; 236 break;
231 pqueue++; 237 pqueue++;
232 } 238 }
diff --git a/OpenSim/Region/Framework/Scenes/SOPMaterial.cs b/OpenSim/Region/Framework/Scenes/SOPMaterial.cs
new file mode 100644
index 0000000..10ac37c
--- /dev/null
+++ b/OpenSim/Region/Framework/Scenes/SOPMaterial.cs
@@ -0,0 +1,95 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using OpenMetaverse;
31using OpenSim.Framework;
32
33namespace OpenSim.Region.Framework.Scenes
34{
35 public static class SOPMaterialData
36 {
37 public enum SopMaterial : int // redundante and not in use for now
38 {
39 Stone = 0,
40 Metal = 1,
41 Glass = 2,
42 Wood = 3,
43 Flesh = 4,
44 Plastic = 5,
45 Rubber = 6,
46 light = 7 // compatibility with old viewers
47 }
48
49 private struct MaterialData
50 {
51 public float friction;
52 public float bounce;
53 public MaterialData(float f, float b)
54 {
55 friction = f;
56 bounce = b;
57 }
58 }
59
60 private static MaterialData[] m_materialdata = {
61 new MaterialData(0.8f,0.4f), // Stone
62 new MaterialData(0.3f,0.4f), // Metal
63 new MaterialData(0.2f,0.7f), // Glass
64 new MaterialData(0.6f,0.5f), // Wood
65 new MaterialData(0.9f,0.3f), // Flesh
66 new MaterialData(0.4f,0.7f), // Plastic
67 new MaterialData(0.9f,0.95f), // Rubber
68 new MaterialData(0.0f,0.0f) // light ??
69 };
70
71 public static Material MaxMaterial
72 {
73 get { return (Material)(m_materialdata.Length - 1); }
74 }
75
76 public static float friction(Material material)
77 {
78 int indx = (int)material;
79 if (indx < m_materialdata.Length)
80 return (m_materialdata[indx].friction);
81 else
82 return 0;
83 }
84
85 public static float bounce(Material material)
86 {
87 int indx = (int)material;
88 if (indx < m_materialdata.Length)
89 return (m_materialdata[indx].bounce);
90 else
91 return 0;
92 }
93
94 }
95} \ No newline at end of file
diff --git a/OpenSim/Region/Framework/Scenes/SOPVehicle.cs b/OpenSim/Region/Framework/Scenes/SOPVehicle.cs
new file mode 100644
index 0000000..9cb901a
--- /dev/null
+++ b/OpenSim/Region/Framework/Scenes/SOPVehicle.cs
@@ -0,0 +1,791 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using OpenMetaverse;
31using OpenSim.Framework;
32using OpenSim.Region.Physics.Manager;
33using System.Text;
34using System.IO;
35using System.Xml;
36using OpenSim.Framework.Serialization;
37using OpenSim.Framework.Serialization.External;
38using OpenSim.Region.Framework.Scenes.Serialization;
39
40namespace OpenSim.Region.Framework.Scenes
41{
42 public class SOPVehicle
43 {
44 public VehicleData vd;
45
46 public Vehicle Type
47 {
48 get { return vd.m_type; }
49 }
50
51 public SOPVehicle()
52 {
53 vd = new VehicleData();
54 ProcessTypeChange(Vehicle.TYPE_NONE); // is needed?
55 }
56
57 public void ProcessFloatVehicleParam(Vehicle pParam, float pValue)
58 {
59 float len;
60 float timestep = 0.01f;
61 switch (pParam)
62 {
63 case Vehicle.ANGULAR_DEFLECTION_EFFICIENCY:
64 if (pValue < 0f) pValue = 0f;
65 if (pValue > 1f) pValue = 1f;
66 vd.m_angularDeflectionEfficiency = pValue;
67 break;
68 case Vehicle.ANGULAR_DEFLECTION_TIMESCALE:
69 if (pValue < timestep) pValue = timestep;
70 vd.m_angularDeflectionTimescale = pValue;
71 break;
72 case Vehicle.ANGULAR_MOTOR_DECAY_TIMESCALE:
73 if (pValue < timestep) pValue = timestep;
74 else if (pValue > 120) pValue = 120;
75 vd.m_angularMotorDecayTimescale = pValue;
76 break;
77 case Vehicle.ANGULAR_MOTOR_TIMESCALE:
78 if (pValue < timestep) pValue = timestep;
79 vd.m_angularMotorTimescale = pValue;
80 break;
81 case Vehicle.BANKING_EFFICIENCY:
82 if (pValue < -1f) pValue = -1f;
83 if (pValue > 1f) pValue = 1f;
84 vd.m_bankingEfficiency = pValue;
85 break;
86 case Vehicle.BANKING_MIX:
87 if (pValue < 0f) pValue = 0f;
88 if (pValue > 1f) pValue = 1f;
89 vd.m_bankingMix = pValue;
90 break;
91 case Vehicle.BANKING_TIMESCALE:
92 if (pValue < timestep) pValue = timestep;
93 vd.m_bankingTimescale = pValue;
94 break;
95 case Vehicle.BUOYANCY:
96 if (pValue < -1f) pValue = -1f;
97 if (pValue > 1f) pValue = 1f;
98 vd.m_VehicleBuoyancy = pValue;
99 break;
100 case Vehicle.HOVER_EFFICIENCY:
101 if (pValue < 0f) pValue = 0f;
102 if (pValue > 1f) pValue = 1f;
103 vd.m_VhoverEfficiency = pValue;
104 break;
105 case Vehicle.HOVER_HEIGHT:
106 vd.m_VhoverHeight = pValue;
107 break;
108 case Vehicle.HOVER_TIMESCALE:
109 if (pValue < timestep) pValue = timestep;
110 vd.m_VhoverTimescale = pValue;
111 break;
112 case Vehicle.LINEAR_DEFLECTION_EFFICIENCY:
113 if (pValue < 0f) pValue = 0f;
114 if (pValue > 1f) pValue = 1f;
115 vd.m_linearDeflectionEfficiency = pValue;
116 break;
117 case Vehicle.LINEAR_DEFLECTION_TIMESCALE:
118 if (pValue < timestep) pValue = timestep;
119 vd.m_linearDeflectionTimescale = pValue;
120 break;
121 case Vehicle.LINEAR_MOTOR_DECAY_TIMESCALE:
122 if (pValue < timestep) pValue = timestep;
123 else if (pValue > 120) pValue = 120;
124 vd.m_linearMotorDecayTimescale = pValue;
125 break;
126 case Vehicle.LINEAR_MOTOR_TIMESCALE:
127 if (pValue < timestep) pValue = timestep;
128 vd.m_linearMotorTimescale = pValue;
129 break;
130 case Vehicle.VERTICAL_ATTRACTION_EFFICIENCY:
131 if (pValue < 0f) pValue = 0f;
132 if (pValue > 1f) pValue = 1f;
133 vd.m_verticalAttractionEfficiency = pValue;
134 break;
135 case Vehicle.VERTICAL_ATTRACTION_TIMESCALE:
136 if (pValue < timestep) pValue = timestep;
137 vd.m_verticalAttractionTimescale = pValue;
138 break;
139
140 // These are vector properties but the engine lets you use a single float value to
141 // set all of the components to the same value
142 case Vehicle.ANGULAR_FRICTION_TIMESCALE:
143 if (pValue < timestep) pValue = timestep;
144 vd.m_angularFrictionTimescale = new Vector3(pValue, pValue, pValue);
145 break;
146 case Vehicle.ANGULAR_MOTOR_DIRECTION:
147 vd.m_angularMotorDirection = new Vector3(pValue, pValue, pValue);
148 len = vd.m_angularMotorDirection.Length();
149 if (len > 12.566f)
150 vd.m_angularMotorDirection *= (12.566f / len);
151 break;
152 case Vehicle.LINEAR_FRICTION_TIMESCALE:
153 if (pValue < timestep) pValue = timestep;
154 vd.m_linearFrictionTimescale = new Vector3(pValue, pValue, pValue);
155 break;
156 case Vehicle.LINEAR_MOTOR_DIRECTION:
157 vd.m_linearMotorDirection = new Vector3(pValue, pValue, pValue);
158 len = vd.m_linearMotorDirection.Length();
159 if (len > 30.0f)
160 vd.m_linearMotorDirection *= (30.0f / len);
161 break;
162 case Vehicle.LINEAR_MOTOR_OFFSET:
163 vd.m_linearMotorOffset = new Vector3(pValue, pValue, pValue);
164 len = vd.m_linearMotorOffset.Length();
165 if (len > 100.0f)
166 vd.m_linearMotorOffset *= (100.0f / len);
167 break;
168 }
169 }//end ProcessFloatVehicleParam
170
171 public void ProcessVectorVehicleParam(Vehicle pParam, Vector3 pValue)
172 {
173 float len;
174 float timestep = 0.01f;
175 switch (pParam)
176 {
177 case Vehicle.ANGULAR_FRICTION_TIMESCALE:
178 if (pValue.X < timestep) pValue.X = timestep;
179 if (pValue.Y < timestep) pValue.Y = timestep;
180 if (pValue.Z < timestep) pValue.Z = timestep;
181
182 vd.m_angularFrictionTimescale = new Vector3(pValue.X, pValue.Y, pValue.Z);
183 break;
184 case Vehicle.ANGULAR_MOTOR_DIRECTION:
185 vd.m_angularMotorDirection = new Vector3(pValue.X, pValue.Y, pValue.Z);
186 // Limit requested angular speed to 2 rps= 4 pi rads/sec
187 len = vd.m_angularMotorDirection.Length();
188 if (len > 12.566f)
189 vd.m_angularMotorDirection *= (12.566f / len);
190 break;
191 case Vehicle.LINEAR_FRICTION_TIMESCALE:
192 if (pValue.X < timestep) pValue.X = timestep;
193 if (pValue.Y < timestep) pValue.Y = timestep;
194 if (pValue.Z < timestep) pValue.Z = timestep;
195 vd.m_linearFrictionTimescale = new Vector3(pValue.X, pValue.Y, pValue.Z);
196 break;
197 case Vehicle.LINEAR_MOTOR_DIRECTION:
198 vd.m_linearMotorDirection = new Vector3(pValue.X, pValue.Y, pValue.Z);
199 len = vd.m_linearMotorDirection.Length();
200 if (len > 30.0f)
201 vd.m_linearMotorDirection *= (30.0f / len);
202 break;
203 case Vehicle.LINEAR_MOTOR_OFFSET:
204 vd.m_linearMotorOffset = new Vector3(pValue.X, pValue.Y, pValue.Z);
205 len = vd.m_linearMotorOffset.Length();
206 if (len > 100.0f)
207 vd.m_linearMotorOffset *= (100.0f / len);
208 break;
209 }
210 }//end ProcessVectorVehicleParam
211
212 public void ProcessRotationVehicleParam(Vehicle pParam, Quaternion pValue)
213 {
214 switch (pParam)
215 {
216 case Vehicle.REFERENCE_FRAME:
217 vd.m_referenceFrame = pValue;
218 break;
219 }
220 }//end ProcessRotationVehicleParam
221
222 public void ProcessVehicleFlags(int pParam, bool remove)
223 {
224 if (remove)
225 {
226 vd.m_flags &= ~((VehicleFlag)pParam);
227 }
228 else
229 {
230 vd.m_flags |= (VehicleFlag)pParam;
231 }
232 }//end ProcessVehicleFlags
233
234 public void ProcessTypeChange(Vehicle pType)
235 {
236 vd.m_linearMotorDirection = Vector3.Zero;
237 vd.m_angularMotorDirection = Vector3.Zero;
238 vd.m_linearMotorOffset = Vector3.Zero;
239 vd.m_referenceFrame = Quaternion.Identity;
240
241 // Set Defaults For Type
242 vd.m_type = pType;
243 switch (pType)
244 {
245 case Vehicle.TYPE_NONE:
246 vd.m_linearFrictionTimescale = new Vector3(1000, 1000, 1000);
247 vd.m_angularFrictionTimescale = new Vector3(1000, 1000, 1000);
248 vd.m_linearMotorTimescale = 1000;
249 vd.m_linearMotorDecayTimescale = 120;
250 vd.m_angularMotorTimescale = 1000;
251 vd.m_angularMotorDecayTimescale = 1000;
252 vd.m_VhoverHeight = 0;
253 vd.m_VhoverEfficiency = 1;
254 vd.m_VhoverTimescale = 1000;
255 vd.m_VehicleBuoyancy = 0;
256 vd.m_linearDeflectionEfficiency = 0;
257 vd.m_linearDeflectionTimescale = 1000;
258 vd.m_angularDeflectionEfficiency = 0;
259 vd.m_angularDeflectionTimescale = 1000;
260 vd.m_bankingEfficiency = 0;
261 vd.m_bankingMix = 1;
262 vd.m_bankingTimescale = 1000;
263 vd.m_verticalAttractionEfficiency = 0;
264 vd.m_verticalAttractionTimescale = 1000;
265
266 vd.m_flags = (VehicleFlag)0;
267 break;
268
269 case Vehicle.TYPE_SLED:
270 vd.m_linearFrictionTimescale = new Vector3(30, 1, 1000);
271 vd.m_angularFrictionTimescale = new Vector3(1000, 1000, 1000);
272 vd.m_linearMotorTimescale = 1000;
273 vd.m_linearMotorDecayTimescale = 120;
274 vd.m_angularMotorTimescale = 1000;
275 vd.m_angularMotorDecayTimescale = 120;
276 vd.m_VhoverHeight = 0;
277 vd.m_VhoverEfficiency = 1;
278 vd.m_VhoverTimescale = 10;
279 vd.m_VehicleBuoyancy = 0;
280 vd.m_linearDeflectionEfficiency = 1;
281 vd.m_linearDeflectionTimescale = 1;
282 vd.m_angularDeflectionEfficiency = 0;
283 vd.m_angularDeflectionTimescale = 1000;
284 vd.m_bankingEfficiency = 0;
285 vd.m_bankingMix = 1;
286 vd.m_bankingTimescale = 10;
287 vd.m_flags &=
288 ~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY |
289 VehicleFlag.HOVER_GLOBAL_HEIGHT | VehicleFlag.HOVER_UP_ONLY);
290 vd.m_flags |= (VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.LIMIT_ROLL_ONLY | VehicleFlag.LIMIT_MOTOR_UP);
291 break;
292 case Vehicle.TYPE_CAR:
293 vd.m_linearFrictionTimescale = new Vector3(100, 2, 1000);
294 vd.m_angularFrictionTimescale = new Vector3(1000, 1000, 1000);
295 vd.m_linearMotorTimescale = 1;
296 vd.m_linearMotorDecayTimescale = 60;
297 vd.m_angularMotorTimescale = 1;
298 vd.m_angularMotorDecayTimescale = 0.8f;
299 vd.m_VhoverHeight = 0;
300 vd.m_VhoverEfficiency = 0;
301 vd.m_VhoverTimescale = 1000;
302 vd.m_VehicleBuoyancy = 0;
303 vd.m_linearDeflectionEfficiency = 1;
304 vd.m_linearDeflectionTimescale = 2;
305 vd.m_angularDeflectionEfficiency = 0;
306 vd.m_angularDeflectionTimescale = 10;
307 vd.m_verticalAttractionEfficiency = 1f;
308 vd.m_verticalAttractionTimescale = 10f;
309 vd.m_bankingEfficiency = -0.2f;
310 vd.m_bankingMix = 1;
311 vd.m_bankingTimescale = 1;
312 vd.m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY | VehicleFlag.HOVER_GLOBAL_HEIGHT);
313 vd.m_flags |= (VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.LIMIT_ROLL_ONLY |
314 VehicleFlag.LIMIT_MOTOR_UP | VehicleFlag.HOVER_UP_ONLY);
315 break;
316 case Vehicle.TYPE_BOAT:
317 vd.m_linearFrictionTimescale = new Vector3(10, 3, 2);
318 vd.m_angularFrictionTimescale = new Vector3(10, 10, 10);
319 vd.m_linearMotorTimescale = 5;
320 vd.m_linearMotorDecayTimescale = 60;
321 vd.m_angularMotorTimescale = 4;
322 vd.m_angularMotorDecayTimescale = 4;
323 vd.m_VhoverHeight = 0;
324 vd.m_VhoverEfficiency = 0.5f;
325 vd.m_VhoverTimescale = 2;
326 vd.m_VehicleBuoyancy = 1;
327 vd.m_linearDeflectionEfficiency = 0.5f;
328 vd.m_linearDeflectionTimescale = 3;
329 vd.m_angularDeflectionEfficiency = 0.5f;
330 vd.m_angularDeflectionTimescale = 5;
331 vd.m_verticalAttractionEfficiency = 0.5f;
332 vd.m_verticalAttractionTimescale = 5f;
333 vd.m_bankingEfficiency = -0.3f;
334 vd.m_bankingMix = 0.8f;
335 vd.m_bankingTimescale = 1;
336 vd.m_flags &= ~(VehicleFlag.HOVER_TERRAIN_ONLY |
337 VehicleFlag.HOVER_GLOBAL_HEIGHT |
338 VehicleFlag.HOVER_UP_ONLY |
339 VehicleFlag.LIMIT_ROLL_ONLY);
340 vd.m_flags |= (VehicleFlag.NO_DEFLECTION_UP |
341 VehicleFlag.LIMIT_MOTOR_UP |
342 VehicleFlag.HOVER_WATER_ONLY);
343 break;
344 case Vehicle.TYPE_AIRPLANE:
345 vd.m_linearFrictionTimescale = new Vector3(200, 10, 5);
346 vd.m_angularFrictionTimescale = new Vector3(20, 20, 20);
347 vd.m_linearMotorTimescale = 2;
348 vd.m_linearMotorDecayTimescale = 60;
349 vd.m_angularMotorTimescale = 4;
350 vd.m_angularMotorDecayTimescale = 8;
351 vd.m_VhoverHeight = 0;
352 vd.m_VhoverEfficiency = 0.5f;
353 vd.m_VhoverTimescale = 1000;
354 vd.m_VehicleBuoyancy = 0;
355 vd.m_linearDeflectionEfficiency = 0.5f;
356 vd.m_linearDeflectionTimescale = 0.5f;
357 vd.m_angularDeflectionEfficiency = 1;
358 vd.m_angularDeflectionTimescale = 2;
359 vd.m_verticalAttractionEfficiency = 0.9f;
360 vd.m_verticalAttractionTimescale = 2f;
361 vd.m_bankingEfficiency = 1;
362 vd.m_bankingMix = 0.7f;
363 vd.m_bankingTimescale = 2;
364 vd.m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY |
365 VehicleFlag.HOVER_TERRAIN_ONLY |
366 VehicleFlag.HOVER_GLOBAL_HEIGHT |
367 VehicleFlag.HOVER_UP_ONLY |
368 VehicleFlag.NO_DEFLECTION_UP |
369 VehicleFlag.LIMIT_MOTOR_UP);
370 vd.m_flags |= (VehicleFlag.LIMIT_ROLL_ONLY);
371 break;
372 case Vehicle.TYPE_BALLOON:
373 vd.m_linearFrictionTimescale = new Vector3(5, 5, 5);
374 vd.m_angularFrictionTimescale = new Vector3(10, 10, 10);
375 vd.m_linearMotorTimescale = 5;
376 vd.m_linearMotorDecayTimescale = 60;
377 vd.m_angularMotorTimescale = 6;
378 vd.m_angularMotorDecayTimescale = 10;
379 vd.m_VhoverHeight = 5;
380 vd.m_VhoverEfficiency = 0.8f;
381 vd.m_VhoverTimescale = 10;
382 vd.m_VehicleBuoyancy = 1;
383 vd.m_linearDeflectionEfficiency = 0;
384 vd.m_linearDeflectionTimescale = 5;
385 vd.m_angularDeflectionEfficiency = 0;
386 vd.m_angularDeflectionTimescale = 5;
387 vd.m_verticalAttractionEfficiency = 0f;
388 vd.m_verticalAttractionTimescale = 1000f;
389 vd.m_bankingEfficiency = 0;
390 vd.m_bankingMix = 0.7f;
391 vd.m_bankingTimescale = 5;
392 vd.m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY |
393 VehicleFlag.HOVER_TERRAIN_ONLY |
394 VehicleFlag.HOVER_UP_ONLY |
395 VehicleFlag.NO_DEFLECTION_UP |
396 VehicleFlag.LIMIT_MOTOR_UP);
397 vd.m_flags |= (VehicleFlag.LIMIT_ROLL_ONLY |
398 VehicleFlag.HOVER_GLOBAL_HEIGHT);
399 break;
400 }
401 }
402 public void SetVehicle(PhysicsActor ph)
403 {
404 if (ph == null)
405 return;
406 ph.SetVehicle(vd);
407 }
408
409 private XmlTextWriter writer;
410
411 private void XWint(string name, int i)
412 {
413 writer.WriteElementString(name, i.ToString());
414 }
415
416 private void XWfloat(string name, float f)
417 {
418 writer.WriteElementString(name, f.ToString(Utils.EnUsCulture));
419 }
420
421 private void XWVector(string name, Vector3 vec)
422 {
423 writer.WriteStartElement(name);
424 writer.WriteElementString("X", vec.X.ToString(Utils.EnUsCulture));
425 writer.WriteElementString("Y", vec.Y.ToString(Utils.EnUsCulture));
426 writer.WriteElementString("Z", vec.Z.ToString(Utils.EnUsCulture));
427 writer.WriteEndElement();
428 }
429
430 private void XWQuat(string name, Quaternion quat)
431 {
432 writer.WriteStartElement(name);
433 writer.WriteElementString("X", quat.X.ToString(Utils.EnUsCulture));
434 writer.WriteElementString("Y", quat.Y.ToString(Utils.EnUsCulture));
435 writer.WriteElementString("Z", quat.Z.ToString(Utils.EnUsCulture));
436 writer.WriteElementString("W", quat.W.ToString(Utils.EnUsCulture));
437 writer.WriteEndElement();
438 }
439
440 public void ToXml2(XmlTextWriter twriter)
441 {
442 writer = twriter;
443 writer.WriteStartElement("Vehicle");
444
445 XWint("TYPE", (int)vd.m_type);
446 XWint("FLAGS", (int)vd.m_flags);
447
448 // Linear properties
449 XWVector("LMDIR", vd.m_linearMotorDirection);
450 XWVector("LMFTIME", vd.m_linearFrictionTimescale);
451 XWfloat("LMDTIME", vd.m_linearMotorDecayTimescale);
452 XWfloat("LMTIME", vd.m_linearMotorTimescale);
453 XWVector("LMOFF", vd.m_linearMotorOffset);
454
455 //Angular properties
456 XWVector("AMDIR", vd.m_angularMotorDirection);
457 XWfloat("AMTIME", vd.m_angularMotorTimescale);
458 XWfloat("AMDTIME", vd.m_angularMotorDecayTimescale);
459 XWVector("AMFTIME", vd.m_angularFrictionTimescale);
460
461 //Deflection properties
462 XWfloat("ADEFF", vd.m_angularDeflectionEfficiency);
463 XWfloat("ADTIME", vd.m_angularDeflectionTimescale);
464 XWfloat("LDEFF", vd.m_linearDeflectionEfficiency);
465 XWfloat("LDTIME", vd.m_linearDeflectionTimescale);
466
467 //Banking properties
468 XWfloat("BEFF", vd.m_bankingEfficiency);
469 XWfloat("BMIX", vd.m_bankingMix);
470 XWfloat("BTIME", vd.m_bankingTimescale);
471
472 //Hover and Buoyancy properties
473 XWfloat("HHEI", vd.m_VhoverHeight);
474 XWfloat("HEFF", vd.m_VhoverEfficiency);
475 XWfloat("HTIME", vd.m_VhoverTimescale);
476 XWfloat("VBUO", vd.m_VehicleBuoyancy);
477
478 //Attractor properties
479 XWfloat("VAEFF", vd.m_verticalAttractionEfficiency);
480 XWfloat("VATIME", vd.m_verticalAttractionTimescale);
481
482 XWQuat("REF_FRAME", vd.m_referenceFrame);
483
484 writer.WriteEndElement();
485 writer = null;
486 }
487
488
489
490 XmlTextReader reader;
491
492 private int XRint()
493 {
494 return reader.ReadElementContentAsInt();
495 }
496
497 private float XRfloat()
498 {
499 return reader.ReadElementContentAsFloat();
500 }
501
502 public Vector3 XRvector()
503 {
504 Vector3 vec;
505 reader.ReadStartElement();
506 vec.X = reader.ReadElementContentAsFloat();
507 vec.Y = reader.ReadElementContentAsFloat();
508 vec.Z = reader.ReadElementContentAsFloat();
509 reader.ReadEndElement();
510 return vec;
511 }
512
513 public Quaternion XRquat()
514 {
515 Quaternion q;
516 reader.ReadStartElement();
517 q.X = reader.ReadElementContentAsFloat();
518 q.Y = reader.ReadElementContentAsFloat();
519 q.Z = reader.ReadElementContentAsFloat();
520 q.W = reader.ReadElementContentAsFloat();
521 reader.ReadEndElement();
522 return q;
523 }
524
525 public static bool EReadProcessors(
526 Dictionary<string, Action> processors,
527 XmlTextReader xtr)
528 {
529 bool errors = false;
530
531 string nodeName = string.Empty;
532 while (xtr.NodeType != XmlNodeType.EndElement)
533 {
534 nodeName = xtr.Name;
535
536 // m_log.DebugFormat("[ExternalRepresentationUtils]: Processing: {0}", nodeName);
537
538 Action p = null;
539 if (processors.TryGetValue(xtr.Name, out p))
540 {
541 // m_log.DebugFormat("[ExternalRepresentationUtils]: Found {0} processor, nodeName);
542
543 try
544 {
545 p();
546 }
547 catch (Exception e)
548 {
549 errors = true;
550 if (xtr.NodeType == XmlNodeType.EndElement)
551 xtr.Read();
552 }
553 }
554 else
555 {
556 // m_log.DebugFormat("[LandDataSerializer]: caught unknown element {0}", nodeName);
557 xtr.ReadOuterXml(); // ignore
558 }
559 }
560
561 return errors;
562 }
563
564
565 public string ToXml2()
566 {
567 MemoryStream ms = new MemoryStream(512);
568 UTF8Encoding enc = new UTF8Encoding();
569 XmlTextWriter xwriter = new XmlTextWriter(ms, enc);
570 ToXml2(xwriter);
571 xwriter.Flush();
572 string s = ms.GetStreamString();
573 xwriter.Close();
574 return s;
575 }
576
577 public static SOPVehicle FromXml2(string text)
578 {
579 if (text == String.Empty)
580 return null;
581
582 UTF8Encoding enc = new UTF8Encoding();
583 MemoryStream ms = new MemoryStream(enc.GetBytes(text));
584 XmlTextReader xreader = new XmlTextReader(ms);
585
586 SOPVehicle v = new SOPVehicle();
587 bool error;
588
589 v.FromXml2(xreader, out error);
590
591 xreader.Close();
592
593 if (error)
594 {
595 v = null;
596 return null;
597 }
598 return v;
599 }
600
601 public static SOPVehicle FromXml2(XmlTextReader reader)
602 {
603 SOPVehicle vehicle = new SOPVehicle();
604
605 bool errors = false;
606
607 vehicle.FromXml2(reader, out errors);
608 if (errors)
609 return null;
610
611 return vehicle;
612 }
613
614 private void FromXml2(XmlTextReader _reader, out bool errors)
615 {
616 errors = false;
617 reader = _reader;
618
619 Dictionary<string, Action> m_VehicleXmlProcessors
620 = new Dictionary<string, Action>();
621
622 m_VehicleXmlProcessors.Add("TYPE", ProcessXR_type);
623 m_VehicleXmlProcessors.Add("FLAGS", ProcessXR_flags);
624
625 // Linear properties
626 m_VehicleXmlProcessors.Add("LMDIR", ProcessXR_linearMotorDirection);
627 m_VehicleXmlProcessors.Add("LMFTIME", ProcessXR_linearFrictionTimescale);
628 m_VehicleXmlProcessors.Add("LMDTIME", ProcessXR_linearMotorDecayTimescale);
629 m_VehicleXmlProcessors.Add("LMTIME", ProcessXR_linearMotorTimescale);
630 m_VehicleXmlProcessors.Add("LMOFF", ProcessXR_linearMotorOffset);
631
632 //Angular properties
633 m_VehicleXmlProcessors.Add("AMDIR", ProcessXR_angularMotorDirection);
634 m_VehicleXmlProcessors.Add("AMTIME", ProcessXR_angularMotorTimescale);
635 m_VehicleXmlProcessors.Add("AMDTIME", ProcessXR_angularMotorDecayTimescale);
636 m_VehicleXmlProcessors.Add("AMFTIME", ProcessXR_angularFrictionTimescale);
637
638 //Deflection properties
639 m_VehicleXmlProcessors.Add("ADEFF", ProcessXR_angularDeflectionEfficiency);
640 m_VehicleXmlProcessors.Add("ADTIME", ProcessXR_angularDeflectionTimescale);
641 m_VehicleXmlProcessors.Add("LDEFF", ProcessXR_linearDeflectionEfficiency);
642 m_VehicleXmlProcessors.Add("LDTIME", ProcessXR_linearDeflectionTimescale);
643
644 //Banking properties
645 m_VehicleXmlProcessors.Add("BEFF", ProcessXR_bankingEfficiency);
646 m_VehicleXmlProcessors.Add("BMIX", ProcessXR_bankingMix);
647 m_VehicleXmlProcessors.Add("BTIME", ProcessXR_bankingTimescale);
648
649 //Hover and Buoyancy properties
650 m_VehicleXmlProcessors.Add("HHEI", ProcessXR_VhoverHeight);
651 m_VehicleXmlProcessors.Add("HEFF", ProcessXR_VhoverEfficiency);
652 m_VehicleXmlProcessors.Add("HTIME", ProcessXR_VhoverTimescale);
653
654 m_VehicleXmlProcessors.Add("VBUO", ProcessXR_VehicleBuoyancy);
655
656 //Attractor properties
657 m_VehicleXmlProcessors.Add("VAEFF", ProcessXR_verticalAttractionEfficiency);
658 m_VehicleXmlProcessors.Add("VATIME", ProcessXR_verticalAttractionTimescale);
659
660 m_VehicleXmlProcessors.Add("REF_FRAME", ProcessXR_referenceFrame);
661
662 vd = new VehicleData();
663
664 reader.ReadStartElement("Vehicle", String.Empty);
665
666 errors = EReadProcessors(
667 m_VehicleXmlProcessors,
668 reader);
669
670 reader.ReadEndElement();
671 reader = null;
672 }
673
674 private void ProcessXR_type()
675 {
676 vd.m_type = (Vehicle)XRint();
677 }
678 private void ProcessXR_flags()
679 {
680 vd.m_flags = (VehicleFlag)XRint();
681 }
682 // Linear properties
683 private void ProcessXR_linearMotorDirection()
684 {
685 vd.m_linearMotorDirection = XRvector();
686 }
687
688 private void ProcessXR_linearFrictionTimescale()
689 {
690 vd.m_linearFrictionTimescale = XRvector();
691 }
692
693 private void ProcessXR_linearMotorDecayTimescale()
694 {
695 vd.m_linearMotorDecayTimescale = XRfloat();
696 }
697 private void ProcessXR_linearMotorTimescale()
698 {
699 vd.m_linearMotorTimescale = XRfloat();
700 }
701 private void ProcessXR_linearMotorOffset()
702 {
703 vd.m_linearMotorOffset = XRvector();
704 }
705
706
707 //Angular properties
708 private void ProcessXR_angularMotorDirection()
709 {
710 vd.m_angularMotorDirection = XRvector();
711 }
712 private void ProcessXR_angularMotorTimescale()
713 {
714 vd.m_angularMotorTimescale = XRfloat();
715 }
716 private void ProcessXR_angularMotorDecayTimescale()
717 {
718 vd.m_angularMotorDecayTimescale = XRfloat();
719 }
720 private void ProcessXR_angularFrictionTimescale()
721 {
722 vd.m_angularFrictionTimescale = XRvector();
723 }
724
725 //Deflection properties
726 private void ProcessXR_angularDeflectionEfficiency()
727 {
728 vd.m_angularDeflectionEfficiency = XRfloat();
729 }
730 private void ProcessXR_angularDeflectionTimescale()
731 {
732 vd.m_angularDeflectionTimescale = XRfloat();
733 }
734 private void ProcessXR_linearDeflectionEfficiency()
735 {
736 vd.m_linearDeflectionEfficiency = XRfloat();
737 }
738 private void ProcessXR_linearDeflectionTimescale()
739 {
740 vd.m_linearDeflectionTimescale = XRfloat();
741 }
742
743 //Banking properties
744 private void ProcessXR_bankingEfficiency()
745 {
746 vd.m_bankingEfficiency = XRfloat();
747 }
748 private void ProcessXR_bankingMix()
749 {
750 vd.m_bankingMix = XRfloat();
751 }
752 private void ProcessXR_bankingTimescale()
753 {
754 vd.m_bankingTimescale = XRfloat();
755 }
756
757 //Hover and Buoyancy properties
758 private void ProcessXR_VhoverHeight()
759 {
760 vd.m_VhoverHeight = XRfloat();
761 }
762 private void ProcessXR_VhoverEfficiency()
763 {
764 vd.m_VhoverEfficiency = XRfloat();
765 }
766 private void ProcessXR_VhoverTimescale()
767 {
768 vd.m_VhoverTimescale = XRfloat();
769 }
770
771 private void ProcessXR_VehicleBuoyancy()
772 {
773 vd.m_VehicleBuoyancy = XRfloat();
774 }
775
776 //Attractor properties
777 private void ProcessXR_verticalAttractionEfficiency()
778 {
779 vd.m_verticalAttractionEfficiency = XRfloat();
780 }
781 private void ProcessXR_verticalAttractionTimescale()
782 {
783 vd.m_verticalAttractionTimescale = XRfloat();
784 }
785
786 private void ProcessXR_referenceFrame()
787 {
788 vd.m_referenceFrame = XRquat();
789 }
790 }
791}
diff --git a/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs b/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs
index 92bf85a..9f0a0e2 100644
--- a/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs
+++ b/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs
@@ -101,12 +101,12 @@ namespace OpenSim.Region.Framework.Scenes
101 engine.StartProcessing(); 101 engine.StartProcessing();
102 } 102 }
103 103
104 public void AddUploadedInventoryItem(UUID agentID, InventoryItemBase item) 104 public void AddUploadedInventoryItem(UUID agentID, InventoryItemBase item, uint cost)
105 { 105 {
106 IMoneyModule money = RequestModuleInterface<IMoneyModule>(); 106 IMoneyModule money = RequestModuleInterface<IMoneyModule>();
107 if (money != null) 107 if (money != null)
108 { 108 {
109 money.ApplyUploadCharge(agentID, money.UploadCharge, "Asset upload"); 109 money.ApplyUploadCharge(agentID, (int)cost, "Asset upload");
110 } 110 }
111 111
112 AddInventoryItem(item); 112 AddInventoryItem(item);
@@ -169,7 +169,7 @@ namespace OpenSim.Region.Framework.Scenes
169 return false; 169 return false;
170 } 170 }
171 } 171 }
172 172
173 if (InventoryService.AddItem(item)) 173 if (InventoryService.AddItem(item))
174 { 174 {
175 int userlevel = 0; 175 int userlevel = 0;
@@ -324,8 +324,7 @@ namespace OpenSim.Region.Framework.Scenes
324 324
325 // Update item with new asset 325 // Update item with new asset
326 item.AssetID = asset.FullID; 326 item.AssetID = asset.FullID;
327 if (group.UpdateInventoryItem(item)) 327 group.UpdateInventoryItem(item);
328 remoteClient.SendAgentAlertMessage("Script saved", false);
329 328
330 part.SendPropertiesToClient(remoteClient); 329 part.SendPropertiesToClient(remoteClient);
331 330
@@ -336,12 +335,7 @@ namespace OpenSim.Region.Framework.Scenes
336 { 335 {
337 // Needs to determine which engine was running it and use that 336 // Needs to determine which engine was running it and use that
338 // 337 //
339 part.Inventory.CreateScriptInstance(item.ItemID, 0, false, DefaultScriptEngine, 0); 338 errors = part.Inventory.CreateScriptInstanceEr(item.ItemID, 0, false, DefaultScriptEngine, 1);
340 errors = part.Inventory.GetScriptErrors(item.ItemID);
341 }
342 else
343 {
344 remoteClient.SendAgentAlertMessage("Script saved", false);
345 } 339 }
346 340
347 // Tell anyone managing scripts that a script has been reloaded/changed 341 // Tell anyone managing scripts that a script has been reloaded/changed
@@ -409,6 +403,7 @@ namespace OpenSim.Region.Framework.Scenes
409 403
410 if (UUID.Zero == transactionID) 404 if (UUID.Zero == transactionID)
411 { 405 {
406 item.Flags = (item.Flags & ~(uint)255) | (itemUpd.Flags & (uint)255);
412 item.Name = itemUpd.Name; 407 item.Name = itemUpd.Name;
413 item.Description = itemUpd.Description; 408 item.Description = itemUpd.Description;
414 409
@@ -793,6 +788,8 @@ namespace OpenSim.Region.Framework.Scenes
793 return; 788 return;
794 } 789 }
795 790
791 if (newName == null) newName = item.Name;
792
796 AssetBase asset = AssetService.Get(item.AssetID.ToString()); 793 AssetBase asset = AssetService.Get(item.AssetID.ToString());
797 794
798 if (asset != null) 795 if (asset != null)
@@ -853,6 +850,24 @@ namespace OpenSim.Region.Framework.Scenes
853 } 850 }
854 851
855 /// <summary> 852 /// <summary>
853 /// Move an item within the agent's inventory, and leave a copy (used in making a new outfit)
854 /// </summary>
855 public void MoveInventoryItemsLeaveCopy(IClientAPI remoteClient, List<InventoryItemBase> items, UUID destfolder)
856 {
857 List<InventoryItemBase> moveitems = new List<InventoryItemBase>();
858 foreach (InventoryItemBase b in items)
859 {
860 CopyInventoryItem(remoteClient, 0, remoteClient.AgentId, b.ID, b.Folder, null);
861 InventoryItemBase n = InventoryService.GetItem(b);
862 n.Folder = destfolder;
863 moveitems.Add(n);
864 remoteClient.SendInventoryItemCreateUpdate(n, 0);
865 }
866
867 MoveInventoryItem(remoteClient, moveitems);
868 }
869
870 /// <summary>
856 /// Move an item within the agent's inventory. 871 /// Move an item within the agent's inventory.
857 /// </summary> 872 /// </summary>
858 /// <param name="remoteClient"></param> 873 /// <param name="remoteClient"></param>
@@ -887,11 +902,22 @@ namespace OpenSim.Region.Framework.Scenes
887 public void CreateNewInventoryItem( 902 public void CreateNewInventoryItem(
888 IClientAPI remoteClient, string creatorID, string creatorData, UUID folderID, 903 IClientAPI remoteClient, string creatorID, string creatorData, UUID folderID,
889 string name, string description, uint flags, uint callbackID, 904 string name, string description, uint flags, uint callbackID,
890 AssetBase asset, sbyte invType, uint nextOwnerMask, int creationDate) 905 AssetBase asset, sbyte invType, uint nextOwnerMask, int creationDate, UUID transationID)
891 { 906 {
892 CreateNewInventoryItem( 907 CreateNewInventoryItem(
893 remoteClient, creatorID, creatorData, folderID, name, description, flags, callbackID, asset, invType, 908 remoteClient, creatorID, creatorData, folderID, name, description, flags, callbackID, asset, invType,
894 (uint)PermissionMask.All, (uint)PermissionMask.All, 0, nextOwnerMask, 0, creationDate); 909 (uint)PermissionMask.All, (uint)PermissionMask.All, 0, nextOwnerMask, 0, creationDate, transationID);
910 }
911
912
913 private void CreateNewInventoryItem(
914 IClientAPI remoteClient, string creatorID, string creatorData, UUID folderID,
915 string name, string description, uint flags, uint callbackID, AssetBase asset, sbyte invType,
916 uint baseMask, uint currentMask, uint everyoneMask, uint nextOwnerMask, uint groupMask, int creationDate)
917 {
918 CreateNewInventoryItem(remoteClient, creatorID, creatorData, folderID,
919 name, description, flags, callbackID, asset, invType,
920 baseMask, currentMask, everyoneMask, nextOwnerMask, groupMask, creationDate, UUID.Zero);
895 } 921 }
896 922
897 /// <summary> 923 /// <summary>
@@ -916,7 +942,7 @@ namespace OpenSim.Region.Framework.Scenes
916 private void CreateNewInventoryItem( 942 private void CreateNewInventoryItem(
917 IClientAPI remoteClient, string creatorID, string creatorData, UUID folderID, 943 IClientAPI remoteClient, string creatorID, string creatorData, UUID folderID,
918 string name, string description, uint flags, uint callbackID, AssetBase asset, sbyte invType, 944 string name, string description, uint flags, uint callbackID, AssetBase asset, sbyte invType,
919 uint baseMask, uint currentMask, uint everyoneMask, uint nextOwnerMask, uint groupMask, int creationDate) 945 uint baseMask, uint currentMask, uint everyoneMask, uint nextOwnerMask, uint groupMask, int creationDate,UUID transationID)
920 { 946 {
921 InventoryItemBase item = new InventoryItemBase(); 947 InventoryItemBase item = new InventoryItemBase();
922 item.Owner = remoteClient.AgentId; 948 item.Owner = remoteClient.AgentId;
@@ -939,7 +965,7 @@ namespace OpenSim.Region.Framework.Scenes
939 965
940 if (AddInventoryItem(item)) 966 if (AddInventoryItem(item))
941 { 967 {
942 remoteClient.SendInventoryItemCreateUpdate(item, callbackID); 968 remoteClient.SendInventoryItemCreateUpdate(item, transationID, callbackID);
943 } 969 }
944 else 970 else
945 { 971 {
@@ -1214,6 +1240,10 @@ namespace OpenSim.Region.Framework.Scenes
1214 { 1240 {
1215 SceneObjectPart part = GetSceneObjectPart(primLocalId); 1241 SceneObjectPart part = GetSceneObjectPart(primLocalId);
1216 1242
1243 // Can't move a null item
1244 if (itemId == UUID.Zero)
1245 return;
1246
1217 if (null == part) 1247 if (null == part)
1218 { 1248 {
1219 m_log.WarnFormat( 1249 m_log.WarnFormat(
@@ -1318,21 +1348,28 @@ namespace OpenSim.Region.Framework.Scenes
1318 return; 1348 return;
1319 } 1349 }
1320 1350
1321 if (part.OwnerID != destPart.OwnerID) 1351 // Can't transfer this
1352 //
1353 if (part.OwnerID != destPart.OwnerID && (srcTaskItem.CurrentPermissions & (uint)PermissionMask.Transfer) == 0)
1354 return;
1355
1356 bool overrideNoMod = false;
1357 if ((part.GetEffectiveObjectFlags() & (uint)PrimFlags.AllowInventoryDrop) != 0)
1358 overrideNoMod = true;
1359
1360 if (part.OwnerID != destPart.OwnerID && (destPart.GetEffectiveObjectFlags() & (uint)PrimFlags.AllowInventoryDrop) == 0)
1322 { 1361 {
1323 // Source must have transfer permissions 1362 // object cannot copy items to an object owned by a different owner
1324 if ((srcTaskItem.CurrentPermissions & (uint)PermissionMask.Transfer) == 0) 1363 // unless llAllowInventoryDrop has been called
1325 return;
1326 1364
1327 // Object cannot copy items to an object owned by a different owner 1365 return;
1328 // unless llAllowInventoryDrop has been called on the destination
1329 if ((destPart.GetEffectiveObjectFlags() & (uint)PrimFlags.AllowInventoryDrop) == 0)
1330 return;
1331 } 1366 }
1332 1367
1333 // must have both move and modify permission to put an item in an object 1368 // must have both move and modify permission to put an item in an object
1334 if ((part.OwnerMask & ((uint)PermissionMask.Move | (uint)PermissionMask.Modify)) == 0) 1369 if (((part.OwnerMask & (uint)PermissionMask.Modify) == 0) && (!overrideNoMod))
1370 {
1335 return; 1371 return;
1372 }
1336 1373
1337 TaskInventoryItem destTaskItem = new TaskInventoryItem(); 1374 TaskInventoryItem destTaskItem = new TaskInventoryItem();
1338 1375
@@ -1388,6 +1425,14 @@ namespace OpenSim.Region.Framework.Scenes
1388 1425
1389 public UUID MoveTaskInventoryItems(UUID destID, string category, SceneObjectPart host, List<UUID> items) 1426 public UUID MoveTaskInventoryItems(UUID destID, string category, SceneObjectPart host, List<UUID> items)
1390 { 1427 {
1428 SceneObjectPart destPart = GetSceneObjectPart(destID);
1429 if (destPart != null) // Move into a prim
1430 {
1431 foreach(UUID itemID in items)
1432 MoveTaskInventoryItem(destID, host, itemID);
1433 return destID; // Prim folder ID == prim ID
1434 }
1435
1391 InventoryFolderBase rootFolder = InventoryService.GetRootFolder(destID); 1436 InventoryFolderBase rootFolder = InventoryService.GetRootFolder(destID);
1392 1437
1393 UUID newFolderID = UUID.Random(); 1438 UUID newFolderID = UUID.Random();
@@ -1570,12 +1615,12 @@ namespace OpenSim.Region.Framework.Scenes
1570 AgentTransactionsModule.HandleTaskItemUpdateFromTransaction( 1615 AgentTransactionsModule.HandleTaskItemUpdateFromTransaction(
1571 remoteClient, part, transactionID, currentItem); 1616 remoteClient, part, transactionID, currentItem);
1572 1617
1573 if ((InventoryType)itemInfo.InvType == InventoryType.Notecard) 1618// if ((InventoryType)itemInfo.InvType == InventoryType.Notecard)
1574 remoteClient.SendAgentAlertMessage("Notecard saved", false); 1619// remoteClient.SendAgentAlertMessage("Notecard saved", false);
1575 else if ((InventoryType)itemInfo.InvType == InventoryType.LSL) 1620// else if ((InventoryType)itemInfo.InvType == InventoryType.LSL)
1576 remoteClient.SendAgentAlertMessage("Script saved", false); 1621// remoteClient.SendAgentAlertMessage("Script saved", false);
1577 else 1622// else
1578 remoteClient.SendAgentAlertMessage("Item saved", false); 1623// remoteClient.SendAgentAlertMessage("Item saved", false);
1579 } 1624 }
1580 1625
1581 // Base ALWAYS has move 1626 // Base ALWAYS has move
@@ -1945,23 +1990,32 @@ namespace OpenSim.Region.Framework.Scenes
1945 // build a list of eligible objects 1990 // build a list of eligible objects
1946 List<uint> deleteIDs = new List<uint>(); 1991 List<uint> deleteIDs = new List<uint>();
1947 List<SceneObjectGroup> deleteGroups = new List<SceneObjectGroup>(); 1992 List<SceneObjectGroup> deleteGroups = new List<SceneObjectGroup>();
1948 1993 List<SceneObjectGroup> takeGroups = new List<SceneObjectGroup>();
1949 // Start with true for both, then remove the flags if objects
1950 // that we can't derez are part of the selection
1951 bool permissionToTake = true;
1952 bool permissionToTakeCopy = true;
1953 bool permissionToDelete = true;
1954 1994
1955 foreach (uint localID in localIDs) 1995 foreach (uint localID in localIDs)
1956 { 1996 {
1997 // Start with true for both, then remove the flags if objects
1998 // that we can't derez are part of the selection
1999 bool permissionToTake = true;
2000 bool permissionToTakeCopy = true;
2001 bool permissionToDelete = true;
2002
1957 // Invalid id 2003 // Invalid id
1958 SceneObjectPart part = GetSceneObjectPart(localID); 2004 SceneObjectPart part = GetSceneObjectPart(localID);
1959 if (part == null) 2005 if (part == null)
2006 {
2007 //Client still thinks the object exists, kill it
2008 deleteIDs.Add(localID);
1960 continue; 2009 continue;
2010 }
1961 2011
1962 // Already deleted by someone else 2012 // Already deleted by someone else
1963 if (part.ParentGroup.IsDeleted) 2013 if (part.ParentGroup.IsDeleted)
2014 {
2015 //Client still thinks the object exists, kill it
2016 deleteIDs.Add(localID);
1964 continue; 2017 continue;
2018 }
1965 2019
1966 // Can't delete child prims 2020 // Can't delete child prims
1967 if (part != part.ParentGroup.RootPart) 2021 if (part != part.ParentGroup.RootPart)
@@ -1969,8 +2023,8 @@ namespace OpenSim.Region.Framework.Scenes
1969 2023
1970 SceneObjectGroup grp = part.ParentGroup; 2024 SceneObjectGroup grp = part.ParentGroup;
1971 2025
1972 deleteIDs.Add(localID); 2026 // If child prims have invalid perms, fix them
1973 deleteGroups.Add(grp); 2027 grp.AdjustChildPrimPermissions();
1974 2028
1975 // If child prims have invalid perms, fix them 2029 // If child prims have invalid perms, fix them
1976 grp.AdjustChildPrimPermissions(); 2030 grp.AdjustChildPrimPermissions();
@@ -1991,81 +2045,193 @@ namespace OpenSim.Region.Framework.Scenes
1991 } 2045 }
1992 else 2046 else
1993 { 2047 {
1994 if (!Permissions.CanTakeCopyObject(grp.UUID, remoteClient.AgentId)) 2048 if (action == DeRezAction.TakeCopy)
2049 {
2050 if (!Permissions.CanTakeCopyObject(grp.UUID, remoteClient.AgentId))
2051 permissionToTakeCopy = false;
2052 }
2053 else
2054 {
1995 permissionToTakeCopy = false; 2055 permissionToTakeCopy = false;
1996 2056 }
1997 if (!Permissions.CanTakeObject(grp.UUID, remoteClient.AgentId)) 2057 if (!Permissions.CanTakeObject(grp.UUID, remoteClient.AgentId))
1998 permissionToTake = false; 2058 permissionToTake = false;
1999 2059
2000 if (!Permissions.CanDeleteObject(grp.UUID, remoteClient.AgentId)) 2060 if (!Permissions.CanDeleteObject(grp.UUID, remoteClient.AgentId))
2001 permissionToDelete = false; 2061 permissionToDelete = false;
2002 } 2062 }
2003 }
2004 2063
2005 // Handle god perms 2064 // Handle god perms
2006 if ((remoteClient != null) && Permissions.IsGod(remoteClient.AgentId)) 2065 if ((remoteClient != null) && Permissions.IsGod(remoteClient.AgentId))
2007 { 2066 {
2008 permissionToTake = true; 2067 permissionToTake = true;
2009 permissionToTakeCopy = true; 2068 permissionToTakeCopy = true;
2010 permissionToDelete = true; 2069 permissionToDelete = true;
2011 } 2070 }
2012 2071
2013 // If we're re-saving, we don't even want to delete 2072 // If we're re-saving, we don't even want to delete
2014 if (action == DeRezAction.SaveToExistingUserInventoryItem) 2073 if (action == DeRezAction.SaveToExistingUserInventoryItem)
2015 permissionToDelete = false; 2074 permissionToDelete = false;
2016 2075
2017 // if we want to take a copy, we also don't want to delete 2076 // if we want to take a copy, we also don't want to delete
2018 // Note: after this point, the permissionToTakeCopy flag 2077 // Note: after this point, the permissionToTakeCopy flag
2019 // becomes irrelevant. It already includes the permissionToTake 2078 // becomes irrelevant. It already includes the permissionToTake
2020 // permission and after excluding no copy items here, we can 2079 // permission and after excluding no copy items here, we can
2021 // just use that. 2080 // just use that.
2022 if (action == DeRezAction.TakeCopy) 2081 if (action == DeRezAction.TakeCopy)
2023 { 2082 {
2024 // If we don't have permission, stop right here 2083 // If we don't have permission, stop right here
2025 if (!permissionToTakeCopy) 2084 if (!permissionToTakeCopy)
2026 return; 2085 return;
2027 2086
2028 permissionToTake = true; 2087 permissionToTake = true;
2029 // Don't delete 2088 // Don't delete
2030 permissionToDelete = false; 2089 permissionToDelete = false;
2031 } 2090 }
2032 2091
2033 if (action == DeRezAction.Return) 2092 if (action == DeRezAction.Return)
2034 {
2035 if (remoteClient != null)
2036 { 2093 {
2037 if (Permissions.CanReturnObjects( 2094 if (remoteClient != null)
2038 null,
2039 remoteClient.AgentId,
2040 deleteGroups))
2041 { 2095 {
2042 permissionToTake = true; 2096 if (Permissions.CanReturnObjects(
2043 permissionToDelete = true; 2097 null,
2044 2098 remoteClient.AgentId,
2045 foreach (SceneObjectGroup g in deleteGroups) 2099 new List<SceneObjectGroup>() {grp}))
2046 { 2100 {
2047 AddReturn(g.OwnerID == g.GroupID ? g.LastOwnerID : g.OwnerID, g.Name, g.AbsolutePosition, "parcel owner return"); 2101 permissionToTake = true;
2102 permissionToDelete = true;
2103
2104 AddReturn(grp.OwnerID == grp.GroupID ? grp.LastOwnerID : grp.OwnerID, grp.Name, grp.AbsolutePosition, "parcel owner return");
2048 } 2105 }
2049 } 2106 }
2107 else // Auto return passes through here with null agent
2108 {
2109 permissionToTake = true;
2110 permissionToDelete = true;
2111 }
2050 } 2112 }
2051 else // Auto return passes through here with null agent 2113
2114 if (permissionToTake && (!permissionToDelete))
2115 takeGroups.Add(grp);
2116
2117 if (permissionToDelete)
2052 { 2118 {
2053 permissionToTake = true; 2119 if (permissionToTake)
2054 permissionToDelete = true; 2120 deleteGroups.Add(grp);
2121 deleteIDs.Add(grp.LocalId);
2055 } 2122 }
2056 } 2123 }
2057 2124
2058 if (permissionToTake && (action != DeRezAction.Delete || this.m_useTrashOnDelete)) 2125 SendKillObject(deleteIDs);
2126
2127 if (deleteGroups.Count > 0)
2059 { 2128 {
2129 foreach (SceneObjectGroup g in deleteGroups)
2130 deleteIDs.Remove(g.LocalId);
2131
2060 m_asyncSceneObjectDeleter.DeleteToInventory( 2132 m_asyncSceneObjectDeleter.DeleteToInventory(
2061 action, destinationID, deleteGroups, remoteClient, 2133 action, destinationID, deleteGroups, remoteClient,
2062 permissionToDelete); 2134 true);
2135 }
2136 if (takeGroups.Count > 0)
2137 {
2138 m_asyncSceneObjectDeleter.DeleteToInventory(
2139 action, destinationID, takeGroups, remoteClient,
2140 false);
2063 } 2141 }
2064 else if (permissionToDelete) 2142 if (deleteIDs.Count > 0)
2065 { 2143 {
2066 foreach (SceneObjectGroup g in deleteGroups) 2144 foreach (SceneObjectGroup g in deleteGroups)
2067 DeleteSceneObject(g, false); 2145 DeleteSceneObject(g, true);
2146 }
2147 }
2148
2149 public UUID attachObjectAssetStore(IClientAPI remoteClient, SceneObjectGroup grp, UUID AgentId, out UUID itemID)
2150 {
2151 itemID = UUID.Zero;
2152 if (grp != null)
2153 {
2154 Vector3 inventoryStoredPosition = new Vector3
2155 (((grp.AbsolutePosition.X > (int)Constants.RegionSize)
2156 ? 250
2157 : grp.AbsolutePosition.X)
2158 ,
2159 (grp.AbsolutePosition.X > (int)Constants.RegionSize)
2160 ? 250
2161 : grp.AbsolutePosition.X,
2162 grp.AbsolutePosition.Z);
2163
2164 Vector3 originalPosition = grp.AbsolutePosition;
2165
2166 grp.AbsolutePosition = inventoryStoredPosition;
2167
2168 string sceneObjectXml = SceneObjectSerializer.ToOriginalXmlFormat(grp);
2169
2170 grp.AbsolutePosition = originalPosition;
2171
2172 AssetBase asset = CreateAsset(
2173 grp.GetPartName(grp.LocalId),
2174 grp.GetPartDescription(grp.LocalId),
2175 (sbyte)AssetType.Object,
2176 Utils.StringToBytes(sceneObjectXml),
2177 remoteClient.AgentId);
2178 AssetService.Store(asset);
2179
2180 InventoryItemBase item = new InventoryItemBase();
2181 item.CreatorId = grp.RootPart.CreatorID.ToString();
2182 item.CreatorData = grp.RootPart.CreatorData;
2183 item.Owner = remoteClient.AgentId;
2184 item.ID = UUID.Random();
2185 item.AssetID = asset.FullID;
2186 item.Description = asset.Description;
2187 item.Name = asset.Name;
2188 item.AssetType = asset.Type;
2189 item.InvType = (int)InventoryType.Object;
2190
2191 InventoryFolderBase folder = InventoryService.GetFolderForType(remoteClient.AgentId, AssetType.Object);
2192 if (folder != null)
2193 item.Folder = folder.ID;
2194 else // oopsies
2195 item.Folder = UUID.Zero;
2196
2197 // Set up base perms properly
2198 uint permsBase = (uint)(PermissionMask.Move | PermissionMask.Copy | PermissionMask.Transfer | PermissionMask.Modify);
2199 permsBase &= grp.RootPart.BaseMask;
2200 permsBase |= (uint)PermissionMask.Move;
2201
2202 // Make sure we don't lock it
2203 grp.RootPart.NextOwnerMask |= (uint)PermissionMask.Move;
2204
2205 if ((remoteClient.AgentId != grp.RootPart.OwnerID) && Permissions.PropagatePermissions())
2206 {
2207 item.BasePermissions = permsBase & grp.RootPart.NextOwnerMask;
2208 item.CurrentPermissions = permsBase & grp.RootPart.NextOwnerMask;
2209 item.NextPermissions = permsBase & grp.RootPart.NextOwnerMask;
2210 item.EveryOnePermissions = permsBase & grp.RootPart.EveryoneMask & grp.RootPart.NextOwnerMask;
2211 item.GroupPermissions = permsBase & grp.RootPart.GroupMask & grp.RootPart.NextOwnerMask;
2212 }
2213 else
2214 {
2215 item.BasePermissions = permsBase;
2216 item.CurrentPermissions = permsBase & grp.RootPart.OwnerMask;
2217 item.NextPermissions = permsBase & grp.RootPart.NextOwnerMask;
2218 item.EveryOnePermissions = permsBase & grp.RootPart.EveryoneMask;
2219 item.GroupPermissions = permsBase & grp.RootPart.GroupMask;
2220 }
2221 item.CreationDate = Util.UnixTimeSinceEpoch();
2222
2223 // sets itemID so client can show item as 'attached' in inventory
2224 grp.FromItemID = item.ID;
2225
2226 if (AddInventoryItem(item))
2227 remoteClient.SendInventoryItemCreateUpdate(item, 0);
2228 else
2229 m_dialogModule.SendAlertToUser(remoteClient, "Operation failed");
2230
2231 itemID = item.ID;
2232 return item.AssetID;
2068 } 2233 }
2234 return UUID.Zero;
2069 } 2235 }
2070 2236
2071 /// <summary> 2237 /// <summary>
@@ -2195,6 +2361,9 @@ namespace OpenSim.Region.Framework.Scenes
2195 2361
2196 public void SetScriptRunning(IClientAPI controllingClient, UUID objectID, UUID itemID, bool running) 2362 public void SetScriptRunning(IClientAPI controllingClient, UUID objectID, UUID itemID, bool running)
2197 { 2363 {
2364 if (!Permissions.CanEditScript(itemID, objectID, controllingClient.AgentId))
2365 return;
2366
2198 SceneObjectPart part = GetSceneObjectPart(objectID); 2367 SceneObjectPart part = GetSceneObjectPart(objectID);
2199 if (part == null) 2368 if (part == null)
2200 return; 2369 return;
@@ -2251,7 +2420,10 @@ namespace OpenSim.Region.Framework.Scenes
2251 } 2420 }
2252 else 2421 else
2253 { 2422 {
2254 if (!Permissions.CanEditObject(sog.UUID, remoteClient.AgentId)) 2423 if (!Permissions.IsGod(remoteClient.AgentId) && sog.OwnerID != remoteClient.AgentId)
2424 continue;
2425
2426 if (!Permissions.CanTransferObject(sog.UUID, groupID))
2255 continue; 2427 continue;
2256 2428
2257 if (sog.GroupID != groupID) 2429 if (sog.GroupID != groupID)
@@ -2363,6 +2535,12 @@ namespace OpenSim.Region.Framework.Scenes
2363 } 2535 }
2364 2536
2365 m_sceneGraph.LinkObjects(root, children); 2537 m_sceneGraph.LinkObjects(root, children);
2538
2539 ScenePresence sp;
2540 if (TryGetScenePresence(agentId, out sp))
2541 {
2542 root.SendPropertiesToClient(sp.ControllingClient);
2543 }
2366 } 2544 }
2367 2545
2368 private string PermissionString(uint permissions) 2546 private string PermissionString(uint permissions)
diff --git a/OpenSim/Region/Framework/Scenes/Scene.PacketHandlers.cs b/OpenSim/Region/Framework/Scenes/Scene.PacketHandlers.cs
index df43271..ce6415a 100644
--- a/OpenSim/Region/Framework/Scenes/Scene.PacketHandlers.cs
+++ b/OpenSim/Region/Framework/Scenes/Scene.PacketHandlers.cs
@@ -50,7 +50,7 @@ namespace OpenSim.Region.Framework.Scenes
50 /// <param name='targetID'></param> 50 /// <param name='targetID'></param>
51 /// <param name='fromAgent'></param> 51 /// <param name='fromAgent'></param>
52 /// <param name='broadcast'></param> 52 /// <param name='broadcast'></param>
53 protected void SimChat(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName, 53 public void SimChat(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName,
54 UUID fromID, UUID targetID, bool fromAgent, bool broadcast) 54 UUID fromID, UUID targetID, bool fromAgent, bool broadcast)
55 { 55 {
56 OSChatMessage args = new OSChatMessage(); 56 OSChatMessage args = new OSChatMessage();
@@ -61,6 +61,7 @@ namespace OpenSim.Region.Framework.Scenes
61 args.Position = fromPos; 61 args.Position = fromPos;
62 args.SenderUUID = fromID; 62 args.SenderUUID = fromID;
63 args.Scene = this; 63 args.Scene = this;
64 args.Destination = targetID;
64 65
65 if (fromAgent) 66 if (fromAgent)
66 { 67 {
@@ -75,7 +76,7 @@ namespace OpenSim.Region.Framework.Scenes
75 } 76 }
76 77
77 args.From = fromName; 78 args.From = fromName;
78 args.TargetUUID = targetID; 79 //args.
79 80
80// m_log.DebugFormat( 81// m_log.DebugFormat(
81// "[SCENE]: Sending message {0} on channel {1}, type {2} from {3}, broadcast {4}", 82// "[SCENE]: Sending message {0} on channel {1}, type {2} from {3}, broadcast {4}",
@@ -86,7 +87,7 @@ namespace OpenSim.Region.Framework.Scenes
86 else 87 else
87 EventManager.TriggerOnChatFromWorld(this, args); 88 EventManager.TriggerOnChatFromWorld(this, args);
88 } 89 }
89 90
90 protected void SimChat(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName, 91 protected void SimChat(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName,
91 UUID fromID, bool fromAgent, bool broadcast) 92 UUID fromID, bool fromAgent, bool broadcast)
92 { 93 {
@@ -130,19 +131,6 @@ namespace OpenSim.Region.Framework.Scenes
130 { 131 {
131 SimChat(message, type, channel, fromPos, fromName, fromID, fromAgent, true); 132 SimChat(message, type, channel, fromPos, fromName, fromID, fromAgent, true);
132 } 133 }
133 /// <summary>
134 ///
135 /// </summary>
136 /// <param name="message"></param>
137 /// <param name="type"></param>
138 /// <param name="fromPos"></param>
139 /// <param name="fromName"></param>
140 /// <param name="fromAgentID"></param>
141 /// <param name="targetID"></param>
142 public void SimChatToAgent(UUID targetID, byte[] message, Vector3 fromPos, string fromName, UUID fromID, bool fromAgent)
143 {
144 SimChat(message, ChatTypeEnum.Say, 0, fromPos, fromName, fromID, targetID, fromAgent, false);
145 }
146 134
147 /// <summary> 135 /// <summary>
148 /// Invoked when the client requests a prim. 136 /// Invoked when the client requests a prim.
@@ -164,27 +152,47 @@ namespace OpenSim.Region.Framework.Scenes
164 /// <param name="remoteClient"></param> 152 /// <param name="remoteClient"></param>
165 public void SelectPrim(uint primLocalID, IClientAPI remoteClient) 153 public void SelectPrim(uint primLocalID, IClientAPI remoteClient)
166 { 154 {
155 /*
156 SceneObjectPart part = GetSceneObjectPart(primLocalID);
157
158 if (null == part)
159 return;
160
161 if (part.IsRoot)
162 {
163 SceneObjectGroup sog = part.ParentGroup;
164 sog.SendPropertiesToClient(remoteClient);
165
166 // A prim is only tainted if it's allowed to be edited by the person clicking it.
167 if (Permissions.CanEditObject(sog.UUID, remoteClient.AgentId)
168 || Permissions.CanMoveObject(sog.UUID, remoteClient.AgentId))
169 {
170 sog.IsSelected = true;
171 EventManager.TriggerParcelPrimCountTainted();
172 }
173 }
174 else
175 {
176 part.SendPropertiesToClient(remoteClient);
177 }
178 */
167 SceneObjectPart part = GetSceneObjectPart(primLocalID); 179 SceneObjectPart part = GetSceneObjectPart(primLocalID);
168 180
169 if (null == part) 181 if (null == part)
170 return; 182 return;
171 183
172 if (part.IsRoot) 184 SceneObjectGroup sog = part.ParentGroup;
173 { 185 if (sog == null)
174 SceneObjectGroup sog = part.ParentGroup; 186 return;
175 sog.SendPropertiesToClient(remoteClient);
176 sog.IsSelected = true;
177 187
178 // A prim is only tainted if it's allowed to be edited by the person clicking it. 188 part.SendPropertiesToClient(remoteClient);
179 if (Permissions.CanEditObject(sog.UUID, remoteClient.AgentId) 189
180 || Permissions.CanMoveObject(sog.UUID, remoteClient.AgentId)) 190 // A prim is only tainted if it's allowed to be edited by the person clicking it.
181 { 191 if (Permissions.CanEditObject(sog.UUID, remoteClient.AgentId)
182 EventManager.TriggerParcelPrimCountTainted(); 192 || Permissions.CanMoveObject(sog.UUID, remoteClient.AgentId))
183 }
184 }
185 else
186 { 193 {
187 part.SendPropertiesToClient(remoteClient); 194 part.IsSelected = true;
195 EventManager.TriggerParcelPrimCountTainted();
188 } 196 }
189 } 197 }
190 198
@@ -237,7 +245,7 @@ namespace OpenSim.Region.Framework.Scenes
237 SceneObjectPart part = GetSceneObjectPart(primLocalID); 245 SceneObjectPart part = GetSceneObjectPart(primLocalID);
238 if (part == null) 246 if (part == null)
239 return; 247 return;
240 248 /*
241 // A deselect packet contains all the local prims being deselected. However, since selection is still 249 // A deselect packet contains all the local prims being deselected. However, since selection is still
242 // group based we only want the root prim to trigger a full update - otherwise on objects with many prims 250 // group based we only want the root prim to trigger a full update - otherwise on objects with many prims
243 // we end up sending many duplicate ObjectUpdates 251 // we end up sending many duplicate ObjectUpdates
@@ -250,7 +258,9 @@ namespace OpenSim.Region.Framework.Scenes
250 // handled by group, but by prim. Legacy cruft. 258 // handled by group, but by prim. Legacy cruft.
251 // TODO: Make selection flagging per prim! 259 // TODO: Make selection flagging per prim!
252 // 260 //
253 part.ParentGroup.IsSelected = false; 261 if (Permissions.CanEditObject(part.ParentGroup.UUID, remoteClient.AgentId)
262 || Permissions.CanMoveObject(part.ParentGroup.UUID, remoteClient.AgentId))
263 part.ParentGroup.IsSelected = false;
254 264
255 if (part.ParentGroup.IsAttachment) 265 if (part.ParentGroup.IsAttachment)
256 isAttachment = true; 266 isAttachment = true;
@@ -270,6 +280,22 @@ namespace OpenSim.Region.Framework.Scenes
270 part.UUID, remoteClient.AgentId)) 280 part.UUID, remoteClient.AgentId))
271 EventManager.TriggerParcelPrimCountTainted(); 281 EventManager.TriggerParcelPrimCountTainted();
272 } 282 }
283 */
284
285 bool oldgprSelect = part.ParentGroup.IsSelected;
286
287 // This is wrong, wrong, wrong. Selection should not be
288 // handled by group, but by prim. Legacy cruft.
289 // TODO: Make selection flagging per prim!
290 //
291 if (Permissions.CanEditObject(part.ParentGroup.UUID, remoteClient.AgentId)
292 || Permissions.CanMoveObject(part.ParentGroup.UUID, remoteClient.AgentId))
293 {
294 part.IsSelected = false;
295 if (!part.ParentGroup.IsAttachment && oldgprSelect != part.ParentGroup.IsSelected)
296 EventManager.TriggerParcelPrimCountTainted();
297 }
298
273 } 299 }
274 300
275 public virtual void ProcessMoneyTransferRequest(UUID source, UUID destination, int amount, 301 public virtual void ProcessMoneyTransferRequest(UUID source, UUID destination, int amount,
@@ -412,6 +438,20 @@ namespace OpenSim.Region.Framework.Scenes
412 ); 438 );
413 } 439 }
414 440
441 private class DescendentsRequestData
442 {
443 public IClientAPI RemoteClient;
444 public UUID FolderID;
445 public UUID OwnerID;
446 public bool FetchFolders;
447 public bool FetchItems;
448 public int SortOrder;
449 }
450
451 private Queue<DescendentsRequestData> m_descendentsRequestQueue = new Queue<DescendentsRequestData>();
452 private Object m_descendentsRequestLock = new Object();
453 private bool m_descendentsRequestProcessing = false;
454
415 /// <summary> 455 /// <summary>
416 /// Tell the client about the various child items and folders contained in the requested folder. 456 /// Tell the client about the various child items and folders contained in the requested folder.
417 /// </summary> 457 /// </summary>
@@ -448,17 +488,38 @@ namespace OpenSim.Region.Framework.Scenes
448 } 488 }
449 } 489 }
450 490
451 // We're going to send the reply async, because there may be 491 lock (m_descendentsRequestLock)
452 // an enormous quantity of packets -- basically the entire inventory! 492 {
453 // We don't want to block the client thread while all that is happening. 493 if (!m_descendentsRequestProcessing)
454 SendInventoryDelegate d = SendInventoryAsync; 494 {
455 d.BeginInvoke(remoteClient, folderID, ownerID, fetchFolders, fetchItems, sortOrder, SendInventoryComplete, d); 495 m_descendentsRequestProcessing = true;
496
497 // We're going to send the reply async, because there may be
498 // an enormous quantity of packets -- basically the entire inventory!
499 // We don't want to block the client thread while all that is happening.
500 SendInventoryDelegate d = SendInventoryAsync;
501 d.BeginInvoke(remoteClient, folderID, ownerID, fetchFolders, fetchItems, sortOrder, SendInventoryComplete, d);
502
503 return;
504 }
505
506 DescendentsRequestData req = new DescendentsRequestData();
507 req.RemoteClient = remoteClient;
508 req.FolderID = folderID;
509 req.OwnerID = ownerID;
510 req.FetchFolders = fetchFolders;
511 req.FetchItems = fetchItems;
512 req.SortOrder = sortOrder;
513
514 m_descendentsRequestQueue.Enqueue(req);
515 }
456 } 516 }
457 517
458 delegate void SendInventoryDelegate(IClientAPI remoteClient, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder); 518 delegate void SendInventoryDelegate(IClientAPI remoteClient, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder);
459 519
460 void SendInventoryAsync(IClientAPI remoteClient, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder) 520 void SendInventoryAsync(IClientAPI remoteClient, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder)
461 { 521 {
522 Thread.Sleep(20);
462 SendInventoryUpdate(remoteClient, new InventoryFolderBase(folderID), fetchFolders, fetchItems); 523 SendInventoryUpdate(remoteClient, new InventoryFolderBase(folderID), fetchFolders, fetchItems);
463 } 524 }
464 525
@@ -466,6 +527,21 @@ namespace OpenSim.Region.Framework.Scenes
466 { 527 {
467 SendInventoryDelegate d = (SendInventoryDelegate)iar.AsyncState; 528 SendInventoryDelegate d = (SendInventoryDelegate)iar.AsyncState;
468 d.EndInvoke(iar); 529 d.EndInvoke(iar);
530
531 lock (m_descendentsRequestLock)
532 {
533 if (m_descendentsRequestQueue.Count > 0)
534 {
535 DescendentsRequestData req = m_descendentsRequestQueue.Dequeue();
536
537 d = SendInventoryAsync;
538 d.BeginInvoke(req.RemoteClient, req.FolderID, req.OwnerID, req.FetchFolders, req.FetchItems, req.SortOrder, SendInventoryComplete, d);
539
540 return;
541 }
542
543 m_descendentsRequestProcessing = false;
544 }
469 } 545 }
470 546
471 /// <summary> 547 /// <summary>
diff --git a/OpenSim/Region/Framework/Scenes/Scene.cs b/OpenSim/Region/Framework/Scenes/Scene.cs
index 5778176..6ca7ef2 100644
--- a/OpenSim/Region/Framework/Scenes/Scene.cs
+++ b/OpenSim/Region/Framework/Scenes/Scene.cs
@@ -226,8 +226,8 @@ namespace OpenSim.Region.Framework.Scenes
226 // TODO: need to figure out how allow client agents but deny 226 // TODO: need to figure out how allow client agents but deny
227 // root agents when ACL denies access to root agent 227 // root agents when ACL denies access to root agent
228 public bool m_strictAccessControl = true; 228 public bool m_strictAccessControl = true;
229 229 public bool m_seeIntoBannedRegion = false;
230 public int MaxUndoCount { get; set; } 230 public int MaxUndoCount = 5;
231 231
232 // Using this for RegionReady module to prevent LoginsDisabled from changing under our feet; 232 // Using this for RegionReady module to prevent LoginsDisabled from changing under our feet;
233 public bool LoginLock = false; 233 public bool LoginLock = false;
@@ -243,11 +243,13 @@ namespace OpenSim.Region.Framework.Scenes
243 243
244 protected int m_splitRegionID; 244 protected int m_splitRegionID;
245 protected Timer m_restartWaitTimer = new Timer(); 245 protected Timer m_restartWaitTimer = new Timer();
246 protected Timer m_timerWatchdog = new Timer();
246 protected List<RegionInfo> m_regionRestartNotifyList = new List<RegionInfo>(); 247 protected List<RegionInfo> m_regionRestartNotifyList = new List<RegionInfo>();
247 protected List<RegionInfo> m_neighbours = new List<RegionInfo>(); 248 protected List<RegionInfo> m_neighbours = new List<RegionInfo>();
248 protected string m_simulatorVersion = "OpenSimulator Server"; 249 protected string m_simulatorVersion = "OpenSimulator Server";
249 protected AgentCircuitManager m_authenticateHandler; 250 protected AgentCircuitManager m_authenticateHandler;
250 protected SceneCommunicationService m_sceneGridService; 251 protected SceneCommunicationService m_sceneGridService;
252 protected ISnmpModule m_snmpService = null;
251 253
252 protected ISimulationDataService m_SimulationDataService; 254 protected ISimulationDataService m_SimulationDataService;
253 protected IEstateDataService m_EstateDataService; 255 protected IEstateDataService m_EstateDataService;
@@ -310,8 +312,8 @@ namespace OpenSim.Region.Framework.Scenes
310 private int m_update_presences = 1; // Update scene presence movements 312 private int m_update_presences = 1; // Update scene presence movements
311 private int m_update_events = 1; 313 private int m_update_events = 1;
312 private int m_update_backup = 200; 314 private int m_update_backup = 200;
313 private int m_update_terrain = 50; 315 private int m_update_terrain = 1000;
314// private int m_update_land = 1; 316 private int m_update_land = 10;
315 private int m_update_coarse_locations = 50; 317 private int m_update_coarse_locations = 50;
316 318
317 private int agentMS; 319 private int agentMS;
@@ -324,13 +326,13 @@ namespace OpenSim.Region.Framework.Scenes
324 private int backupMS; 326 private int backupMS;
325 private int terrainMS; 327 private int terrainMS;
326 private int landMS; 328 private int landMS;
327 private int spareMS;
328 329
329 /// <summary> 330 /// <summary>
330 /// Tick at which the last frame was processed. 331 /// Tick at which the last frame was processed.
331 /// </summary> 332 /// </summary>
332 private int m_lastFrameTick; 333 private int m_lastFrameTick;
333 334
335 public bool CombineRegions = false;
334 /// <summary> 336 /// <summary>
335 /// Tick at which the last maintenance run occurred. 337 /// Tick at which the last maintenance run occurred.
336 /// </summary> 338 /// </summary>
@@ -359,6 +361,11 @@ namespace OpenSim.Region.Framework.Scenes
359 /// </summary> 361 /// </summary>
360 private int m_LastLogin; 362 private int m_LastLogin;
361 363
364 private int m_lastIncoming;
365 private int m_lastOutgoing;
366 private int m_hbRestarts = 0;
367
368
362 /// <summary> 369 /// <summary>
363 /// Thread that runs the scene loop. 370 /// Thread that runs the scene loop.
364 /// </summary> 371 /// </summary>
@@ -399,7 +406,7 @@ namespace OpenSim.Region.Framework.Scenes
399 private volatile bool m_active; 406 private volatile bool m_active;
400 407
401// private int m_lastUpdate; 408// private int m_lastUpdate;
402// private bool m_firstHeartbeat = true; 409 private bool m_firstHeartbeat = true;
403 410
404 private UpdatePrioritizationSchemes m_priorityScheme = UpdatePrioritizationSchemes.Time; 411 private UpdatePrioritizationSchemes m_priorityScheme = UpdatePrioritizationSchemes.Time;
405 private bool m_reprioritizationEnabled = true; 412 private bool m_reprioritizationEnabled = true;
@@ -443,6 +450,19 @@ namespace OpenSim.Region.Framework.Scenes
443 get { return m_sceneGridService; } 450 get { return m_sceneGridService; }
444 } 451 }
445 452
453 public ISnmpModule SnmpService
454 {
455 get
456 {
457 if (m_snmpService == null)
458 {
459 m_snmpService = RequestModuleInterface<ISnmpModule>();
460 }
461
462 return m_snmpService;
463 }
464 }
465
446 public ISimulationDataService SimulationDataService 466 public ISimulationDataService SimulationDataService
447 { 467 {
448 get 468 get
@@ -736,6 +756,8 @@ namespace OpenSim.Region.Framework.Scenes
736 m_SimulationDataService = simDataService; 756 m_SimulationDataService = simDataService;
737 m_EstateDataService = estateDataService; 757 m_EstateDataService = estateDataService;
738 m_regionHandle = RegionInfo.RegionHandle; 758 m_regionHandle = RegionInfo.RegionHandle;
759 m_lastIncoming = 0;
760 m_lastOutgoing = 0;
739 761
740 m_asyncSceneObjectDeleter = new AsyncSceneObjectGroupDeleter(this); 762 m_asyncSceneObjectDeleter = new AsyncSceneObjectGroupDeleter(this);
741 m_asyncSceneObjectDeleter.Enabled = true; 763 m_asyncSceneObjectDeleter.Enabled = true;
@@ -825,132 +847,141 @@ namespace OpenSim.Region.Framework.Scenes
825 847
826 // Region config overrides global config 848 // Region config overrides global config
827 // 849 //
828 if (m_config.Configs["Startup"] != null) 850 try
829 { 851 {
830 IConfig startupConfig = m_config.Configs["Startup"]; 852 if (m_config.Configs["Startup"] != null)
831
832 StartDisabled = startupConfig.GetBoolean("StartDisabled", false);
833
834 m_defaultDrawDistance = startupConfig.GetFloat("DefaultDrawDistance", m_defaultDrawDistance);
835 UseBackup = startupConfig.GetBoolean("UseSceneBackup", UseBackup);
836 if (!UseBackup)
837 m_log.InfoFormat("[SCENE]: Backup has been disabled for {0}", RegionInfo.RegionName);
838
839 //Animation states
840 m_useFlySlow = startupConfig.GetBoolean("enableflyslow", false);
841
842 MaxUndoCount = startupConfig.GetInt("MaxPrimUndos", 20);
843
844 PhysicalPrims = startupConfig.GetBoolean("physical_prim", PhysicalPrims);
845 CollidablePrims = startupConfig.GetBoolean("collidable_prim", CollidablePrims);
846
847 m_minNonphys = startupConfig.GetFloat("NonPhysicalPrimMin", m_minNonphys);
848 if (RegionInfo.NonphysPrimMin > 0)
849 { 853 {
850 m_minNonphys = RegionInfo.NonphysPrimMin; 854 IConfig startupConfig = m_config.Configs["Startup"];
851 }
852 855
853 m_maxNonphys = startupConfig.GetFloat("NonPhysicalPrimMax", m_maxNonphys); 856 StartDisabled = startupConfig.GetBoolean("StartDisabled", false);
854 if (RegionInfo.NonphysPrimMax > 0)
855 {
856 m_maxNonphys = RegionInfo.NonphysPrimMax;
857 }
858 857
859 m_minPhys = startupConfig.GetFloat("PhysicalPrimMin", m_minPhys); 858 m_defaultDrawDistance = startupConfig.GetFloat("DefaultDrawDistance",m_defaultDrawDistance);
860 if (RegionInfo.PhysPrimMin > 0) 859 UseBackup = startupConfig.GetBoolean("UseSceneBackup", UseBackup);
861 { 860 if (!UseBackup)
862 m_minPhys = RegionInfo.PhysPrimMin; 861 m_log.InfoFormat("[SCENE]: Backup has been disabled for {0}", RegionInfo.RegionName);
863 } 862
863 //Animation states
864 m_useFlySlow = startupConfig.GetBoolean("enableflyslow", false);
864 865
865 m_maxPhys = startupConfig.GetFloat("PhysicalPrimMax", m_maxPhys); 866 PhysicalPrims = startupConfig.GetBoolean("physical_prim", true);
866 if (RegionInfo.PhysPrimMax > 0) 867 CollidablePrims = startupConfig.GetBoolean("collidable_prim", true);
867 {
868 m_maxPhys = RegionInfo.PhysPrimMax;
869 }
870 868
871 // Here, if clamping is requested in either global or 869 m_minNonphys = startupConfig.GetFloat("NonPhysicalPrimMin", m_minNonphys);
872 // local config, it will be used 870 if (RegionInfo.NonphysPrimMin > 0)
873 // 871 {
874 m_clampPrimSize = startupConfig.GetBoolean("ClampPrimSize", m_clampPrimSize); 872 m_minNonphys = RegionInfo.NonphysPrimMin;
875 if (RegionInfo.ClampPrimSize) 873 }
876 {
877 m_clampPrimSize = true;
878 }
879 874
880 m_linksetCapacity = startupConfig.GetInt("LinksetPrims", m_linksetCapacity); 875 m_maxNonphys = startupConfig.GetFloat("NonPhysicalPrimMax", m_maxNonphys);
881 if (RegionInfo.LinksetCapacity > 0) 876 if (RegionInfo.NonphysPrimMax > 0)
882 { 877 {
883 m_linksetCapacity = RegionInfo.LinksetCapacity; 878 m_maxNonphys = RegionInfo.NonphysPrimMax;
884 } 879 }
885 880
886 m_useTrashOnDelete = startupConfig.GetBoolean("UseTrashOnDelete", m_useTrashOnDelete); 881 m_minPhys = startupConfig.GetFloat("PhysicalPrimMin", m_minPhys);
887 m_trustBinaries = startupConfig.GetBoolean("TrustBinaries", m_trustBinaries); 882 if (RegionInfo.PhysPrimMin > 0)
888 m_allowScriptCrossings = startupConfig.GetBoolean("AllowScriptCrossing", m_allowScriptCrossings); 883 {
889 m_dontPersistBefore = 884 m_minPhys = RegionInfo.PhysPrimMin;
890 startupConfig.GetLong("MinimumTimeBeforePersistenceConsidered", DEFAULT_MIN_TIME_FOR_PERSISTENCE); 885 }
891 m_dontPersistBefore *= 10000000;
892 m_persistAfter =
893 startupConfig.GetLong("MaximumTimeBeforePersistenceConsidered", DEFAULT_MAX_TIME_FOR_PERSISTENCE);
894 m_persistAfter *= 10000000;
895 886
896 m_defaultScriptEngine = startupConfig.GetString("DefaultScriptEngine", "XEngine"); 887 m_maxPhys = startupConfig.GetFloat("PhysicalPrimMax", m_maxPhys);
897 888
898 SpawnPointRouting = startupConfig.GetString("SpawnPointRouting", "closest"); 889 if (RegionInfo.PhysPrimMax > 0)
899 TelehubAllowLandmarks = startupConfig.GetBoolean("TelehubAllowLandmark", false); 890 {
891 m_maxPhys = RegionInfo.PhysPrimMax;
892 }
900 893
901 m_strictAccessControl = startupConfig.GetBoolean("StrictAccessControl", m_strictAccessControl); 894 m_linksetCapacity = startupConfig.GetInt("LinksetPrims", m_linksetCapacity);
895 if (RegionInfo.LinksetCapacity > 0)
896 {
897 m_linksetCapacity = RegionInfo.LinksetCapacity;
898 }
902 899
903 m_generateMaptiles = startupConfig.GetBoolean("GenerateMaptiles", true); 900 SpawnPointRouting = startupConfig.GetString("SpawnPointRouting", "closest");
904 if (m_generateMaptiles) 901 TelehubAllowLandmarks = startupConfig.GetBoolean("TelehubAllowLandmark", false);
905 { 902
906 int maptileRefresh = startupConfig.GetInt("MaptileRefresh", 0); 903 // Here, if clamping is requested in either global or
907 if (maptileRefresh != 0) 904 // local config, it will be used
905 //
906 m_clampPrimSize = startupConfig.GetBoolean("ClampPrimSize", m_clampPrimSize);
907 if (RegionInfo.ClampPrimSize)
908 { 908 {
909 m_mapGenerationTimer.Interval = maptileRefresh * 1000; 909 m_clampPrimSize = true;
910 m_mapGenerationTimer.Elapsed += RegenerateMaptileAndReregister;
911 m_mapGenerationTimer.AutoReset = true;
912 m_mapGenerationTimer.Start();
913 } 910 }
914 }
915 else
916 {
917 string tile = startupConfig.GetString("MaptileStaticUUID", UUID.Zero.ToString());
918 UUID tileID;
919 911
920 if (UUID.TryParse(tile, out tileID)) 912 m_useTrashOnDelete = startupConfig.GetBoolean("UseTrashOnDelete",m_useTrashOnDelete);
913 m_trustBinaries = startupConfig.GetBoolean("TrustBinaries", m_trustBinaries);
914 m_allowScriptCrossings = startupConfig.GetBoolean("AllowScriptCrossing", m_allowScriptCrossings);
915 m_dontPersistBefore =
916 startupConfig.GetLong("MinimumTimeBeforePersistenceConsidered", DEFAULT_MIN_TIME_FOR_PERSISTENCE);
917 m_dontPersistBefore *= 10000000;
918 m_persistAfter =
919 startupConfig.GetLong("MaximumTimeBeforePersistenceConsidered", DEFAULT_MAX_TIME_FOR_PERSISTENCE);
920 m_persistAfter *= 10000000;
921
922 m_defaultScriptEngine = startupConfig.GetString("DefaultScriptEngine", "XEngine");
923 m_log.InfoFormat("[SCENE]: Default script engine {0}", m_defaultScriptEngine);
924
925 m_strictAccessControl = startupConfig.GetBoolean("StrictAccessControl", m_strictAccessControl);
926 m_seeIntoBannedRegion = startupConfig.GetBoolean("SeeIntoBannedRegion", m_seeIntoBannedRegion);
927 CombineRegions = startupConfig.GetBoolean("CombineContiguousRegions", false);
928
929 m_generateMaptiles = startupConfig.GetBoolean("GenerateMaptiles", true);
930 if (m_generateMaptiles)
921 { 931 {
922 RegionInfo.RegionSettings.TerrainImageID = tileID; 932 int maptileRefresh = startupConfig.GetInt("MaptileRefresh", 0);
933 if (maptileRefresh != 0)
934 {
935 m_mapGenerationTimer.Interval = maptileRefresh * 1000;
936 m_mapGenerationTimer.Elapsed += RegenerateMaptileAndReregister;
937 m_mapGenerationTimer.AutoReset = true;
938 m_mapGenerationTimer.Start();
939 }
923 } 940 }
924 } 941 else
942 {
943 string tile = startupConfig.GetString("MaptileStaticUUID", UUID.Zero.ToString());
944 UUID tileID;
925 945
926 string grant = startupConfig.GetString("AllowedClients", String.Empty); 946 if (UUID.TryParse(tile, out tileID))
927 if (grant.Length > 0) 947 {
928 { 948 RegionInfo.RegionSettings.TerrainImageID = tileID;
929 foreach (string viewer in grant.Split('|')) 949 }
950 }
951
952 string grant = startupConfig.GetString("AllowedClients", String.Empty);
953 if (grant.Length > 0)
930 { 954 {
931 m_AllowedViewers.Add(viewer.Trim().ToLower()); 955 foreach (string viewer in grant.Split(','))
956 {
957 m_AllowedViewers.Add(viewer.Trim().ToLower());
958 }
932 } 959 }
933 }
934 960
935 grant = startupConfig.GetString("BannedClients", String.Empty); 961 grant = startupConfig.GetString("BannedClients", String.Empty);
936 if (grant.Length > 0) 962 if (grant.Length > 0)
937 {
938 foreach (string viewer in grant.Split('|'))
939 { 963 {
940 m_BannedViewers.Add(viewer.Trim().ToLower()); 964 foreach (string viewer in grant.Split(','))
965 {
966 m_BannedViewers.Add(viewer.Trim().ToLower());
967 }
941 } 968 }
942 }
943 969
944 MinFrameTime = startupConfig.GetFloat( "MinFrameTime", MinFrameTime); 970 MinFrameTime = startupConfig.GetFloat( "MinFrameTime", MinFrameTime);
945 m_update_backup = startupConfig.GetInt( "UpdateStorageEveryNFrames", m_update_backup); 971 m_update_backup = startupConfig.GetInt( "UpdateStorageEveryNFrames", m_update_backup);
946 m_update_coarse_locations = startupConfig.GetInt( "UpdateCoarseLocationsEveryNFrames", m_update_coarse_locations); 972 m_update_coarse_locations = startupConfig.GetInt( "UpdateCoarseLocationsEveryNFrames", m_update_coarse_locations);
947 m_update_entitymovement = startupConfig.GetInt( "UpdateEntityMovementEveryNFrames", m_update_entitymovement); 973 m_update_entitymovement = startupConfig.GetInt( "UpdateEntityMovementEveryNFrames", m_update_entitymovement);
948 m_update_events = startupConfig.GetInt( "UpdateEventsEveryNFrames", m_update_events); 974 m_update_events = startupConfig.GetInt( "UpdateEventsEveryNFrames", m_update_events);
949 m_update_objects = startupConfig.GetInt( "UpdateObjectsEveryNFrames", m_update_objects); 975 m_update_objects = startupConfig.GetInt( "UpdateObjectsEveryNFrames", m_update_objects);
950 m_update_physics = startupConfig.GetInt( "UpdatePhysicsEveryNFrames", m_update_physics); 976 m_update_physics = startupConfig.GetInt( "UpdatePhysicsEveryNFrames", m_update_physics);
951 m_update_presences = startupConfig.GetInt( "UpdateAgentsEveryNFrames", m_update_presences); 977 m_update_presences = startupConfig.GetInt( "UpdateAgentsEveryNFrames", m_update_presences);
952 m_update_terrain = startupConfig.GetInt( "UpdateTerrainEveryNFrames", m_update_terrain); 978 m_update_terrain = startupConfig.GetInt( "UpdateTerrainEveryNFrames", m_update_terrain);
953 m_update_temp_cleaning = startupConfig.GetInt( "UpdateTempCleaningEveryNFrames", m_update_temp_cleaning); 979 m_update_temp_cleaning = startupConfig.GetInt( "UpdateTempCleaningEveryNFrames", m_update_temp_cleaning);
980 }
981 }
982 catch (Exception e)
983 {
984 m_log.Error("[SCENE]: Failed to load StartupConfig: " + e.ToString());
954 } 985 }
955 986
956 // FIXME: Ultimately this should be in a module. 987 // FIXME: Ultimately this should be in a module.
@@ -995,6 +1026,8 @@ namespace OpenSim.Region.Framework.Scenes
995 StatsReporter = new SimStatsReporter(this); 1026 StatsReporter = new SimStatsReporter(this);
996 StatsReporter.OnSendStatsResult += SendSimStatsPackets; 1027 StatsReporter.OnSendStatsResult += SendSimStatsPackets;
997 StatsReporter.OnStatsIncorrect += m_sceneGraph.RecalculateStats; 1028 StatsReporter.OnStatsIncorrect += m_sceneGraph.RecalculateStats;
1029
1030 MainConsole.Instance.Commands.AddCommand("scene", false, "gc collect", "gc collect", "gc collect", "Cause the garbage collector to make a single pass", HandleGcCollect);
998 } 1031 }
999 1032
1000 public Scene(RegionInfo regInfo) : base(regInfo) 1033 public Scene(RegionInfo regInfo) : base(regInfo)
@@ -1290,8 +1323,11 @@ namespace OpenSim.Region.Framework.Scenes
1290 // Stop all client threads. 1323 // Stop all client threads.
1291 ForEachScenePresence(delegate(ScenePresence avatar) { avatar.ControllingClient.Close(); }); 1324 ForEachScenePresence(delegate(ScenePresence avatar) { avatar.ControllingClient.Close(); });
1292 1325
1293 m_log.Debug("[SCENE]: Persisting changed objects"); 1326 m_log.Debug("[SCENE]: TriggerSceneShuttingDown");
1294 EventManager.TriggerSceneShuttingDown(this); 1327 EventManager.TriggerSceneShuttingDown(this);
1328
1329 m_log.Debug("[SCENE]: Persisting changed objects");
1330
1295 Backup(false); 1331 Backup(false);
1296 m_sceneGraph.Close(); 1332 m_sceneGraph.Close();
1297 1333
@@ -1305,6 +1341,7 @@ namespace OpenSim.Region.Framework.Scenes
1305 // attempt to reference a null or disposed physics scene. 1341 // attempt to reference a null or disposed physics scene.
1306 if (PhysicsScene != null) 1342 if (PhysicsScene != null)
1307 { 1343 {
1344 m_log.Debug("[SCENE]: Dispose Physics");
1308 PhysicsScene phys = PhysicsScene; 1345 PhysicsScene phys = PhysicsScene;
1309 // remove the physics engine from both Scene and SceneGraph 1346 // remove the physics engine from both Scene and SceneGraph
1310 PhysicsScene = null; 1347 PhysicsScene = null;
@@ -1327,11 +1364,29 @@ namespace OpenSim.Region.Framework.Scenes
1327 //m_heartbeatTimer.Elapsed += new ElapsedEventHandler(Heartbeat); 1364 //m_heartbeatTimer.Elapsed += new ElapsedEventHandler(Heartbeat);
1328 if (m_heartbeatThread != null) 1365 if (m_heartbeatThread != null)
1329 { 1366 {
1367 m_hbRestarts++;
1368 if(m_hbRestarts > 10)
1369 Environment.Exit(1);
1370 m_log.ErrorFormat("[SCENE]: Restarting heartbeat thread because it hasn't reported in in region {0}", RegionInfo.RegionName);
1371
1372//int pid = System.Diagnostics.Process.GetCurrentProcess().Id;
1373//System.Diagnostics.Process proc = new System.Diagnostics.Process();
1374//proc.EnableRaisingEvents=false;
1375//proc.StartInfo.FileName = "/bin/kill";
1376//proc.StartInfo.Arguments = "-QUIT " + pid.ToString();
1377//proc.Start();
1378//proc.WaitForExit();
1379//Thread.Sleep(1000);
1380//Environment.Exit(1);
1330 m_heartbeatThread.Abort(); 1381 m_heartbeatThread.Abort();
1382 Watchdog.AbortThread(m_heartbeatThread.ManagedThreadId);
1331 m_heartbeatThread = null; 1383 m_heartbeatThread = null;
1332 } 1384 }
1333// m_lastUpdate = Util.EnvironmentTickCount(); 1385// m_lastUpdate = Util.EnvironmentTickCount();
1334 1386
1387// m_sceneGraph.PreparePhysicsSimulation();
1388
1389
1335 m_heartbeatThread 1390 m_heartbeatThread
1336 = Watchdog.StartThread( 1391 = Watchdog.StartThread(
1337 Heartbeat, string.Format("Heartbeat ({0})", RegionInfo.RegionName), ThreadPriority.Normal, false, false); 1392 Heartbeat, string.Format("Heartbeat ({0})", RegionInfo.RegionName), ThreadPriority.Normal, false, false);
@@ -1474,16 +1529,20 @@ namespace OpenSim.Region.Framework.Scenes
1474 endFrame = Frame + frames; 1529 endFrame = Frame + frames;
1475 1530
1476 float physicsFPS = 0f; 1531 float physicsFPS = 0f;
1477 int previousFrameTick, tmpMS; 1532 int tmpMS;
1478 int maintc = Util.EnvironmentTickCount(); 1533 int previousFrameTick;
1534 int maintc;
1535 int sleepMS;
1536 int framestart;
1479 1537
1480 while (!m_shuttingDown && ((endFrame == null && Active) || Frame < endFrame)) 1538 while (!m_shuttingDown && ((endFrame == null && Active) || Frame < endFrame))
1481 { 1539 {
1540 framestart = Util.EnvironmentTickCount();
1482 ++Frame; 1541 ++Frame;
1483 1542
1484// m_log.DebugFormat("[SCENE]: Processing frame {0} in {1}", Frame, RegionInfo.RegionName); 1543// m_log.DebugFormat("[SCENE]: Processing frame {0} in {1}", Frame, RegionInfo.RegionName);
1485 1544
1486 agentMS = tempOnRezMS = eventMS = backupMS = terrainMS = landMS = spareMS = 0; 1545 agentMS = tempOnRezMS = eventMS = backupMS = terrainMS = landMS = 0;
1487 1546
1488 try 1547 try
1489 { 1548 {
@@ -1535,6 +1594,7 @@ namespace OpenSim.Region.Framework.Scenes
1535 m_sceneGraph.UpdatePresences(); 1594 m_sceneGraph.UpdatePresences();
1536 1595
1537 agentMS += Util.EnvironmentTickCountSubtract(tmpMS); 1596 agentMS += Util.EnvironmentTickCountSubtract(tmpMS);
1597
1538 1598
1539 // Delete temp-on-rez stuff 1599 // Delete temp-on-rez stuff
1540 if (Frame % m_update_temp_cleaning == 0 && !m_cleaningTemps) 1600 if (Frame % m_update_temp_cleaning == 0 && !m_cleaningTemps)
@@ -1616,34 +1676,37 @@ namespace OpenSim.Region.Framework.Scenes
1616 1676
1617 Watchdog.UpdateThread(); 1677 Watchdog.UpdateThread();
1618 1678
1679 otherMS = tempOnRezMS + eventMS + backupMS + terrainMS + landMS;
1680
1681 StatsReporter.AddPhysicsFPS(physicsFPS);
1682 StatsReporter.AddTimeDilation(TimeDilation);
1683 StatsReporter.AddFPS(1);
1684
1685 StatsReporter.addAgentMS(agentMS);
1686 StatsReporter.addPhysicsMS(physicsMS + physicsMS2);
1687 StatsReporter.addOtherMS(otherMS);
1688 StatsReporter.addScriptLines(m_sceneGraph.GetScriptLPS());
1689
1619 previousFrameTick = m_lastFrameTick; 1690 previousFrameTick = m_lastFrameTick;
1620 m_lastFrameTick = Util.EnvironmentTickCount(); 1691 m_lastFrameTick = Util.EnvironmentTickCount();
1621 tmpMS = Util.EnvironmentTickCountSubtract(m_lastFrameTick, maintc); 1692 tmpMS = Util.EnvironmentTickCountSubtract(m_lastFrameTick, framestart);
1622 tmpMS = (int)(MinFrameTime * 1000) - tmpMS; 1693 tmpMS = (int)(MinFrameTime * 1000) - tmpMS;
1623 1694
1695 m_firstHeartbeat = false;
1696
1697 sleepMS = Util.EnvironmentTickCount();
1698
1624 if (tmpMS > 0) 1699 if (tmpMS > 0)
1625 {
1626 Thread.Sleep(tmpMS); 1700 Thread.Sleep(tmpMS);
1627 spareMS += tmpMS;
1628 }
1629
1630 frameMS = Util.EnvironmentTickCountSubtract(maintc);
1631 maintc = Util.EnvironmentTickCount();
1632 1701
1633 otherMS = tempOnRezMS + eventMS + backupMS + terrainMS + landMS; 1702 sleepMS = Util.EnvironmentTickCountSubtract(sleepMS);
1703 frameMS = Util.EnvironmentTickCountSubtract(framestart);
1704 StatsReporter.addSleepMS(sleepMS);
1705 StatsReporter.addFrameMS(frameMS);
1634 1706
1635 // if (Frame%m_update_avatars == 0) 1707 // if (Frame%m_update_avatars == 0)
1636 // UpdateInWorldTime(); 1708 // UpdateInWorldTime();
1637 StatsReporter.AddPhysicsFPS(physicsFPS);
1638 StatsReporter.AddTimeDilation(TimeDilation);
1639 StatsReporter.AddFPS(1);
1640 1709
1641 StatsReporter.addFrameMS(frameMS);
1642 StatsReporter.addAgentMS(agentMS);
1643 StatsReporter.addPhysicsMS(physicsMS + physicsMS2);
1644 StatsReporter.addOtherMS(otherMS);
1645 StatsReporter.AddSpareMS(spareMS);
1646 StatsReporter.addScriptLines(m_sceneGraph.GetScriptLPS());
1647 1710
1648 // Optionally warn if a frame takes double the amount of time that it should. 1711 // Optionally warn if a frame takes double the amount of time that it should.
1649 if (DebugUpdates 1712 if (DebugUpdates
@@ -1761,7 +1824,7 @@ namespace OpenSim.Region.Framework.Scenes
1761 msg.fromAgentName = "Server"; 1824 msg.fromAgentName = "Server";
1762 msg.dialog = (byte)19; // Object msg 1825 msg.dialog = (byte)19; // Object msg
1763 msg.fromGroup = false; 1826 msg.fromGroup = false;
1764 msg.offline = (byte)0; 1827 msg.offline = (byte)1;
1765 msg.ParentEstateID = RegionInfo.EstateSettings.ParentEstateID; 1828 msg.ParentEstateID = RegionInfo.EstateSettings.ParentEstateID;
1766 msg.Position = Vector3.Zero; 1829 msg.Position = Vector3.Zero;
1767 msg.RegionID = RegionInfo.RegionID.Guid; 1830 msg.RegionID = RegionInfo.RegionID.Guid;
@@ -1983,6 +2046,19 @@ namespace OpenSim.Region.Framework.Scenes
1983 EventManager.TriggerPrimsLoaded(this); 2046 EventManager.TriggerPrimsLoaded(this);
1984 } 2047 }
1985 2048
2049 public bool SuportsRayCastFiltered()
2050 {
2051 if (PhysicsScene == null)
2052 return false;
2053 return PhysicsScene.SuportsRaycastWorldFiltered();
2054 }
2055
2056 public object RayCastFiltered(Vector3 position, Vector3 direction, float length, int Count, RayFilterFlags filter)
2057 {
2058 if (PhysicsScene == null)
2059 return null;
2060 return PhysicsScene.RaycastWorld(position, direction, length, Count,filter);
2061 }
1986 2062
1987 /// <summary> 2063 /// <summary>
1988 /// Gets a new rez location based on the raycast and the size of the object that is being rezzed. 2064 /// Gets a new rez location based on the raycast and the size of the object that is being rezzed.
@@ -1999,14 +2075,24 @@ namespace OpenSim.Region.Framework.Scenes
1999 /// <returns></returns> 2075 /// <returns></returns>
2000 public Vector3 GetNewRezLocation(Vector3 RayStart, Vector3 RayEnd, UUID RayTargetID, Quaternion rot, byte bypassRayCast, byte RayEndIsIntersection, bool frontFacesOnly, Vector3 scale, bool FaceCenter) 2076 public Vector3 GetNewRezLocation(Vector3 RayStart, Vector3 RayEnd, UUID RayTargetID, Quaternion rot, byte bypassRayCast, byte RayEndIsIntersection, bool frontFacesOnly, Vector3 scale, bool FaceCenter)
2001 { 2077 {
2078
2079 float wheight = (float)RegionInfo.RegionSettings.WaterHeight;
2080 Vector3 wpos = Vector3.Zero;
2081 // Check for water surface intersection from above
2082 if ( (RayStart.Z > wheight) && (RayEnd.Z < wheight) )
2083 {
2084 float ratio = (RayStart.Z - wheight) / (RayStart.Z - RayEnd.Z);
2085 wpos.X = RayStart.X - (ratio * (RayStart.X - RayEnd.X));
2086 wpos.Y = RayStart.Y - (ratio * (RayStart.Y - RayEnd.Y));
2087 wpos.Z = wheight;
2088 }
2089
2002 Vector3 pos = Vector3.Zero; 2090 Vector3 pos = Vector3.Zero;
2003 if (RayEndIsIntersection == (byte)1) 2091 if (RayEndIsIntersection == (byte)1)
2004 { 2092 {
2005 pos = RayEnd; 2093 pos = RayEnd;
2006 return pos;
2007 } 2094 }
2008 2095 else if (RayTargetID != UUID.Zero)
2009 if (RayTargetID != UUID.Zero)
2010 { 2096 {
2011 SceneObjectPart target = GetSceneObjectPart(RayTargetID); 2097 SceneObjectPart target = GetSceneObjectPart(RayTargetID);
2012 2098
@@ -2028,7 +2114,7 @@ namespace OpenSim.Region.Framework.Scenes
2028 EntityIntersection ei = target.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, FaceCenter); 2114 EntityIntersection ei = target.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, FaceCenter);
2029 2115
2030 // Un-comment out the following line to Get Raytrace results printed to the console. 2116 // Un-comment out the following line to Get Raytrace results printed to the console.
2031 // m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString()); 2117 // m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
2032 float ScaleOffset = 0.5f; 2118 float ScaleOffset = 0.5f;
2033 2119
2034 // If we hit something 2120 // If we hit something
@@ -2051,13 +2137,10 @@ namespace OpenSim.Region.Framework.Scenes
2051 //pos.Z -= 0.25F; 2137 //pos.Z -= 0.25F;
2052 2138
2053 } 2139 }
2054
2055 return pos;
2056 } 2140 }
2057 else 2141 else
2058 { 2142 {
2059 // We don't have a target here, so we're going to raytrace all the objects in the scene. 2143 // We don't have a target here, so we're going to raytrace all the objects in the scene.
2060
2061 EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection), true, false); 2144 EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection), true, false);
2062 2145
2063 // Un-comment the following line to print the raytrace results to the console. 2146 // Un-comment the following line to print the raytrace results to the console.
@@ -2066,13 +2149,12 @@ namespace OpenSim.Region.Framework.Scenes
2066 if (ei.HitTF) 2149 if (ei.HitTF)
2067 { 2150 {
2068 pos = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z); 2151 pos = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
2069 } else 2152 }
2153 else
2070 { 2154 {
2071 // fall back to our stupid functionality 2155 // fall back to our stupid functionality
2072 pos = RayEnd; 2156 pos = RayEnd;
2073 } 2157 }
2074
2075 return pos;
2076 } 2158 }
2077 } 2159 }
2078 else 2160 else
@@ -2083,8 +2165,12 @@ namespace OpenSim.Region.Framework.Scenes
2083 //increase height so its above the ground. 2165 //increase height so its above the ground.
2084 //should be getting the normal of the ground at the rez point and using that? 2166 //should be getting the normal of the ground at the rez point and using that?
2085 pos.Z += scale.Z / 2f; 2167 pos.Z += scale.Z / 2f;
2086 return pos; 2168// return pos;
2087 } 2169 }
2170
2171 // check against posible water intercept
2172 if (wpos.Z > pos.Z) pos = wpos;
2173 return pos;
2088 } 2174 }
2089 2175
2090 2176
@@ -2175,12 +2261,12 @@ namespace OpenSim.Region.Framework.Scenes
2175 { 2261 {
2176 if (m_sceneGraph.AddRestoredSceneObject(sceneObject, attachToBackup, alreadyPersisted, sendClientUpdates)) 2262 if (m_sceneGraph.AddRestoredSceneObject(sceneObject, attachToBackup, alreadyPersisted, sendClientUpdates))
2177 { 2263 {
2264 sceneObject.IsDeleted = false;
2178 EventManager.TriggerObjectAddedToScene(sceneObject); 2265 EventManager.TriggerObjectAddedToScene(sceneObject);
2179 return true; 2266 return true;
2180 } 2267 }
2181 2268
2182 return false; 2269 return false;
2183
2184 } 2270 }
2185 2271
2186 /// <summary> 2272 /// <summary>
@@ -2272,6 +2358,15 @@ namespace OpenSim.Region.Framework.Scenes
2272 /// </summary> 2358 /// </summary>
2273 public void DeleteAllSceneObjects() 2359 public void DeleteAllSceneObjects()
2274 { 2360 {
2361 DeleteAllSceneObjects(false);
2362 }
2363
2364 /// <summary>
2365 /// Delete every object from the scene. This does not include attachments worn by avatars.
2366 /// </summary>
2367 public void DeleteAllSceneObjects(bool exceptNoCopy)
2368 {
2369 List<SceneObjectGroup> toReturn = new List<SceneObjectGroup>();
2275 lock (Entities) 2370 lock (Entities)
2276 { 2371 {
2277 EntityBase[] entities = Entities.GetEntities(); 2372 EntityBase[] entities = Entities.GetEntities();
@@ -2280,11 +2375,24 @@ namespace OpenSim.Region.Framework.Scenes
2280 if (e is SceneObjectGroup) 2375 if (e is SceneObjectGroup)
2281 { 2376 {
2282 SceneObjectGroup sog = (SceneObjectGroup)e; 2377 SceneObjectGroup sog = (SceneObjectGroup)e;
2283 if (!sog.IsAttachment) 2378 if (sog != null && !sog.IsAttachment)
2284 DeleteSceneObject((SceneObjectGroup)e, false); 2379 {
2380 if (!exceptNoCopy || ((sog.GetEffectivePermissions() & (uint)PermissionMask.Copy) != 0))
2381 {
2382 DeleteSceneObject((SceneObjectGroup)e, false);
2383 }
2384 else
2385 {
2386 toReturn.Add((SceneObjectGroup)e);
2387 }
2388 }
2285 } 2389 }
2286 } 2390 }
2287 } 2391 }
2392 if (toReturn.Count > 0)
2393 {
2394 returnObjects(toReturn.ToArray(), UUID.Zero);
2395 }
2288 } 2396 }
2289 2397
2290 /// <summary> 2398 /// <summary>
@@ -2319,6 +2427,12 @@ namespace OpenSim.Region.Framework.Scenes
2319 2427
2320 foreach (SceneObjectPart part in partList) 2428 foreach (SceneObjectPart part in partList)
2321 { 2429 {
2430 if (part.KeyframeMotion != null)
2431 {
2432 part.KeyframeMotion.Delete();
2433 part.KeyframeMotion = null;
2434 }
2435
2322 if (part.IsJoint() && ((part.Flags & PrimFlags.Physics) != 0)) 2436 if (part.IsJoint() && ((part.Flags & PrimFlags.Physics) != 0))
2323 { 2437 {
2324 PhysicsScene.RequestJointDeletion(part.Name); // FIXME: what if the name changed? 2438 PhysicsScene.RequestJointDeletion(part.Name); // FIXME: what if the name changed?
@@ -2336,6 +2450,8 @@ namespace OpenSim.Region.Framework.Scenes
2336 } 2450 }
2337 2451
2338 group.DeleteGroupFromScene(silent); 2452 group.DeleteGroupFromScene(silent);
2453 if (!silent)
2454 SendKillObject(new List<uint>() { group.LocalId });
2339 2455
2340// m_log.DebugFormat("[SCENE]: Exit DeleteSceneObject() for {0} {1}", group.Name, group.UUID); 2456// m_log.DebugFormat("[SCENE]: Exit DeleteSceneObject() for {0} {1}", group.Name, group.UUID);
2341 } 2457 }
@@ -2626,7 +2742,7 @@ namespace OpenSim.Region.Framework.Scenes
2626 // If the user is banned, we won't let any of their objects 2742 // If the user is banned, we won't let any of their objects
2627 // enter. Period. 2743 // enter. Period.
2628 // 2744 //
2629 if (RegionInfo.EstateSettings.IsBanned(newObject.OwnerID)) 2745 if (RegionInfo.EstateSettings.IsBanned(newObject.OwnerID, 36))
2630 { 2746 {
2631 m_log.InfoFormat("[INTERREGION]: Denied prim crossing for banned avatar {0}", newObject.OwnerID); 2747 m_log.InfoFormat("[INTERREGION]: Denied prim crossing for banned avatar {0}", newObject.OwnerID);
2632 return false; 2748 return false;
@@ -2634,6 +2750,8 @@ namespace OpenSim.Region.Framework.Scenes
2634 2750
2635 if (newPosition != Vector3.Zero) 2751 if (newPosition != Vector3.Zero)
2636 newObject.RootPart.GroupPosition = newPosition; 2752 newObject.RootPart.GroupPosition = newPosition;
2753 if (newObject.RootPart.KeyframeMotion != null)
2754 newObject.RootPart.KeyframeMotion.UpdateSceneObject(newObject);
2637 2755
2638 if (!AddSceneObject(newObject)) 2756 if (!AddSceneObject(newObject))
2639 { 2757 {
@@ -2678,6 +2796,23 @@ namespace OpenSim.Region.Framework.Scenes
2678 /// <returns>True if the SceneObjectGroup was added, False if it was not</returns> 2796 /// <returns>True if the SceneObjectGroup was added, False if it was not</returns>
2679 public bool AddSceneObject(SceneObjectGroup sceneObject) 2797 public bool AddSceneObject(SceneObjectGroup sceneObject)
2680 { 2798 {
2799 if (sceneObject.OwnerID == UUID.Zero)
2800 {
2801 m_log.ErrorFormat("[SCENE]: Owner ID for {0} was zero", sceneObject.UUID);
2802 return false;
2803 }
2804
2805 // If the user is banned, we won't let any of their objects
2806 // enter. Period.
2807 //
2808 int flags = GetUserFlags(sceneObject.OwnerID);
2809 if (RegionInfo.EstateSettings.IsBanned(sceneObject.OwnerID, flags))
2810 {
2811 m_log.InfoFormat("[INTERREGION]: Denied prim crossing for banned avatar {0}", sceneObject.OwnerID);
2812
2813 return false;
2814 }
2815
2681 // Force allocation of new LocalId 2816 // Force allocation of new LocalId
2682 // 2817 //
2683 SceneObjectPart[] parts = sceneObject.Parts; 2818 SceneObjectPart[] parts = sceneObject.Parts;
@@ -2711,16 +2846,27 @@ namespace OpenSim.Region.Framework.Scenes
2711 RootPrim.RemFlag(PrimFlags.TemporaryOnRez); 2846 RootPrim.RemFlag(PrimFlags.TemporaryOnRez);
2712 2847
2713 if (AttachmentsModule != null) 2848 if (AttachmentsModule != null)
2714 AttachmentsModule.AttachObject(sp, grp, 0, false, false); 2849 AttachmentsModule.AttachObject(sp, grp, 0, false, false, false);
2715 } 2850 }
2716 else 2851 else
2717 { 2852 {
2853 m_log.DebugFormat("[SCENE]: Attachment {0} arrived and scene presence was not found, setting to temp", sceneObject.UUID);
2718 RootPrim.RemFlag(PrimFlags.TemporaryOnRez); 2854 RootPrim.RemFlag(PrimFlags.TemporaryOnRez);
2719 RootPrim.AddFlag(PrimFlags.TemporaryOnRez); 2855 RootPrim.AddFlag(PrimFlags.TemporaryOnRez);
2720 } 2856 }
2857 if (sceneObject.OwnerID == UUID.Zero)
2858 {
2859 m_log.ErrorFormat("[SCENE]: Owner ID for {0} was zero after attachment processing. BUG!", sceneObject.UUID);
2860 return false;
2861 }
2721 } 2862 }
2722 else 2863 else
2723 { 2864 {
2865 if (sceneObject.OwnerID == UUID.Zero)
2866 {
2867 m_log.ErrorFormat("[SCENE]: Owner ID for non-attachment {0} was zero", sceneObject.UUID);
2868 return false;
2869 }
2724 AddRestoredSceneObject(sceneObject, true, false); 2870 AddRestoredSceneObject(sceneObject, true, false);
2725 } 2871 }
2726 2872
@@ -2737,6 +2883,24 @@ namespace OpenSim.Region.Framework.Scenes
2737 return 2; // StateSource.PrimCrossing 2883 return 2; // StateSource.PrimCrossing
2738 } 2884 }
2739 2885
2886 public int GetUserFlags(UUID user)
2887 {
2888 //Unfortunately the SP approach means that the value is cached until region is restarted
2889 /*
2890 ScenePresence sp;
2891 if (TryGetScenePresence(user, out sp))
2892 {
2893 return sp.UserFlags;
2894 }
2895 else
2896 {
2897 */
2898 UserAccount uac = UserAccountService.GetUserAccount(RegionInfo.ScopeID, user);
2899 if (uac == null)
2900 return 0;
2901 return uac.UserFlags;
2902 //}
2903 }
2740 #endregion 2904 #endregion
2741 2905
2742 #region Add/Remove Avatar Methods 2906 #region Add/Remove Avatar Methods
@@ -2769,7 +2933,7 @@ namespace OpenSim.Region.Framework.Scenes
2769 = (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin) != 0 2933 = (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin) != 0
2770 || (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaLogin) != 0; 2934 || (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaLogin) != 0;
2771 2935
2772 // CheckHeartbeat(); 2936 CheckHeartbeat();
2773 2937
2774 sp = GetScenePresence(client.AgentId); 2938 sp = GetScenePresence(client.AgentId);
2775 2939
@@ -2800,6 +2964,7 @@ namespace OpenSim.Region.Framework.Scenes
2800 // start the scripts again (since this is done in RezAttachments()). 2964 // start the scripts again (since this is done in RezAttachments()).
2801 // XXX: This is convoluted. 2965 // XXX: This is convoluted.
2802 sp.IsChildAgent = false; 2966 sp.IsChildAgent = false;
2967 sp.IsLoggingIn = true;
2803 2968
2804 if (AttachmentsModule != null) 2969 if (AttachmentsModule != null)
2805 Util.FireAndForget(delegate(object o) { AttachmentsModule.RezAttachments(sp); }); 2970 Util.FireAndForget(delegate(object o) { AttachmentsModule.RezAttachments(sp); });
@@ -2913,19 +3078,14 @@ namespace OpenSim.Region.Framework.Scenes
2913 // and the scene presence and the client, if they exist 3078 // and the scene presence and the client, if they exist
2914 try 3079 try
2915 { 3080 {
2916 // We need to wait for the client to make UDP contact first. 3081 ScenePresence sp = GetScenePresence(agentID);
2917 // It's the UDP contact that creates the scene presence 3082
2918 ScenePresence sp = WaitGetScenePresence(agentID);
2919 if (sp != null) 3083 if (sp != null)
2920 { 3084 {
2921 PresenceService.LogoutAgent(sp.ControllingClient.SessionId); 3085 PresenceService.LogoutAgent(sp.ControllingClient.SessionId);
2922
2923 sp.ControllingClient.Close(); 3086 sp.ControllingClient.Close();
2924 } 3087 }
2925 else 3088
2926 {
2927 m_log.WarnFormat("[SCENE]: Could not find scene presence for {0}", agentID);
2928 }
2929 // BANG! SLASH! 3089 // BANG! SLASH!
2930 m_authenticateHandler.RemoveCircuit(agentID); 3090 m_authenticateHandler.RemoveCircuit(agentID);
2931 3091
@@ -2970,6 +3130,8 @@ namespace OpenSim.Region.Framework.Scenes
2970 client.OnUpdatePrimGroupPosition += m_sceneGraph.UpdatePrimGroupPosition; 3130 client.OnUpdatePrimGroupPosition += m_sceneGraph.UpdatePrimGroupPosition;
2971 client.OnUpdatePrimSinglePosition += m_sceneGraph.UpdatePrimSinglePosition; 3131 client.OnUpdatePrimSinglePosition += m_sceneGraph.UpdatePrimSinglePosition;
2972 3132
3133 client.onClientChangeObject += m_sceneGraph.ClientChangeObject;
3134
2973 client.OnUpdatePrimGroupRotation += m_sceneGraph.UpdatePrimGroupRotation; 3135 client.OnUpdatePrimGroupRotation += m_sceneGraph.UpdatePrimGroupRotation;
2974 client.OnUpdatePrimGroupMouseRotation += m_sceneGraph.UpdatePrimGroupRotation; 3136 client.OnUpdatePrimGroupMouseRotation += m_sceneGraph.UpdatePrimGroupRotation;
2975 client.OnUpdatePrimSingleRotation += m_sceneGraph.UpdatePrimSingleRotation; 3137 client.OnUpdatePrimSingleRotation += m_sceneGraph.UpdatePrimSingleRotation;
@@ -3026,6 +3188,7 @@ namespace OpenSim.Region.Framework.Scenes
3026 client.OnFetchInventory += m_asyncInventorySender.HandleFetchInventory; 3188 client.OnFetchInventory += m_asyncInventorySender.HandleFetchInventory;
3027 client.OnUpdateInventoryItem += UpdateInventoryItemAsset; 3189 client.OnUpdateInventoryItem += UpdateInventoryItemAsset;
3028 client.OnCopyInventoryItem += CopyInventoryItem; 3190 client.OnCopyInventoryItem += CopyInventoryItem;
3191 client.OnMoveItemsAndLeaveCopy += MoveInventoryItemsLeaveCopy;
3029 client.OnMoveInventoryItem += MoveInventoryItem; 3192 client.OnMoveInventoryItem += MoveInventoryItem;
3030 client.OnRemoveInventoryItem += RemoveInventoryItem; 3193 client.OnRemoveInventoryItem += RemoveInventoryItem;
3031 client.OnRemoveInventoryFolder += RemoveInventoryFolder; 3194 client.OnRemoveInventoryFolder += RemoveInventoryFolder;
@@ -3097,6 +3260,8 @@ namespace OpenSim.Region.Framework.Scenes
3097 client.OnUpdatePrimGroupPosition -= m_sceneGraph.UpdatePrimGroupPosition; 3260 client.OnUpdatePrimGroupPosition -= m_sceneGraph.UpdatePrimGroupPosition;
3098 client.OnUpdatePrimSinglePosition -= m_sceneGraph.UpdatePrimSinglePosition; 3261 client.OnUpdatePrimSinglePosition -= m_sceneGraph.UpdatePrimSinglePosition;
3099 3262
3263 client.onClientChangeObject -= m_sceneGraph.ClientChangeObject;
3264
3100 client.OnUpdatePrimGroupRotation -= m_sceneGraph.UpdatePrimGroupRotation; 3265 client.OnUpdatePrimGroupRotation -= m_sceneGraph.UpdatePrimGroupRotation;
3101 client.OnUpdatePrimGroupMouseRotation -= m_sceneGraph.UpdatePrimGroupRotation; 3266 client.OnUpdatePrimGroupMouseRotation -= m_sceneGraph.UpdatePrimGroupRotation;
3102 client.OnUpdatePrimSingleRotation -= m_sceneGraph.UpdatePrimSingleRotation; 3267 client.OnUpdatePrimSingleRotation -= m_sceneGraph.UpdatePrimSingleRotation;
@@ -3199,7 +3364,7 @@ namespace OpenSim.Region.Framework.Scenes
3199 /// </summary> 3364 /// </summary>
3200 /// <param name="agentId">The avatar's Unique ID</param> 3365 /// <param name="agentId">The avatar's Unique ID</param>
3201 /// <param name="client">The IClientAPI for the client</param> 3366 /// <param name="client">The IClientAPI for the client</param>
3202 public virtual void TeleportClientHome(UUID agentId, IClientAPI client) 3367 public virtual bool TeleportClientHome(UUID agentId, IClientAPI client)
3203 { 3368 {
3204 if (EntityTransferModule != null) 3369 if (EntityTransferModule != null)
3205 { 3370 {
@@ -3210,6 +3375,7 @@ namespace OpenSim.Region.Framework.Scenes
3210 m_log.DebugFormat("[SCENE]: Unable to teleport user home: no AgentTransferModule is active"); 3375 m_log.DebugFormat("[SCENE]: Unable to teleport user home: no AgentTransferModule is active");
3211 client.SendTeleportFailed("Unable to perform teleports on this simulator."); 3376 client.SendTeleportFailed("Unable to perform teleports on this simulator.");
3212 } 3377 }
3378 return false;
3213 } 3379 }
3214 3380
3215 /// <summary> 3381 /// <summary>
@@ -3319,6 +3485,16 @@ namespace OpenSim.Region.Framework.Scenes
3319 /// <param name="flags"></param> 3485 /// <param name="flags"></param>
3320 public virtual void SetHomeRezPoint(IClientAPI remoteClient, ulong regionHandle, Vector3 position, Vector3 lookAt, uint flags) 3486 public virtual void SetHomeRezPoint(IClientAPI remoteClient, ulong regionHandle, Vector3 position, Vector3 lookAt, uint flags)
3321 { 3487 {
3488 //Add half the avatar's height so that the user doesn't fall through prims
3489 ScenePresence presence;
3490 if (TryGetScenePresence(remoteClient.AgentId, out presence))
3491 {
3492 if (presence.Appearance != null)
3493 {
3494 position.Z = position.Z + (presence.Appearance.AvatarHeight / 2);
3495 }
3496 }
3497
3322 if (GridUserService != null && GridUserService.SetHome(remoteClient.AgentId.ToString(), RegionInfo.RegionID, position, lookAt)) 3498 if (GridUserService != null && GridUserService.SetHome(remoteClient.AgentId.ToString(), RegionInfo.RegionID, position, lookAt))
3323 // FUBAR ALERT: this needs to be "Home position set." so the viewer saves a home-screenshot. 3499 // FUBAR ALERT: this needs to be "Home position set." so the viewer saves a home-screenshot.
3324 m_dialogModule.SendAlertToUser(remoteClient, "Home position set."); 3500 m_dialogModule.SendAlertToUser(remoteClient, "Home position set.");
@@ -3456,6 +3632,7 @@ namespace OpenSim.Region.Framework.Scenes
3456 // It's possible for child agents to have transactions if changes are being made cross-border. 3632 // It's possible for child agents to have transactions if changes are being made cross-border.
3457 if (AgentTransactionsModule != null) 3633 if (AgentTransactionsModule != null)
3458 AgentTransactionsModule.RemoveAgentAssetTransactions(agentID); 3634 AgentTransactionsModule.RemoveAgentAssetTransactions(agentID);
3635 m_log.Debug("[Scene] The avatar has left the building");
3459 } 3636 }
3460 catch (Exception e) 3637 catch (Exception e)
3461 { 3638 {
@@ -3648,38 +3825,39 @@ namespace OpenSim.Region.Framework.Scenes
3648 agent.firstname, agent.lastname, agent.Viewer); 3825 agent.firstname, agent.lastname, agent.Viewer);
3649 reason = "Access denied, your viewer is banned by the region owner"; 3826 reason = "Access denied, your viewer is banned by the region owner";
3650 return false; 3827 return false;
3651 } 3828 }
3829
3652 3830
3653 ILandObject land; 3831 ScenePresence sp = GetScenePresence(agent.AgentID);
3832
3833 if (sp != null && !sp.IsChildAgent)
3834 {
3835 // We have a zombie from a crashed session.
3836 // Or the same user is trying to be root twice here, won't work.
3837 // Kill it.
3838 m_log.WarnFormat(
3839 "[SCENE]: Existing root scene presence detected for {0} {1} in {2} when connecting. Removing existing presence.",
3840 sp.Name, sp.UUID, RegionInfo.RegionName);
3841
3842 sp.ControllingClient.Close(true, true);
3843 sp = null;
3844 }
3654 3845
3655 lock (agent) 3846 lock (agent)
3656 { 3847 {
3657 ScenePresence sp = GetScenePresence(agent.AgentID);
3658
3659 if (sp != null && !sp.IsChildAgent)
3660 {
3661 // We have a zombie from a crashed session.
3662 // Or the same user is trying to be root twice here, won't work.
3663 // Kill it.
3664 m_log.WarnFormat(
3665 "[SCENE]: Existing root scene presence detected for {0} {1} in {2} when connecting. Removing existing presence.",
3666 sp.Name, sp.UUID, RegionInfo.RegionName);
3667
3668 sp.ControllingClient.Close(true);
3669 sp = null;
3670 }
3671
3672 land = LandChannel.GetLandObject(agent.startpos.X, agent.startpos.Y);
3673
3674 //On login test land permisions 3848 //On login test land permisions
3675 if (vialogin) 3849 if (vialogin)
3676 { 3850 {
3677 if (land != null && !TestLandRestrictions(agent, land, out reason)) 3851 IUserAccountCacheModule cache = RequestModuleInterface<IUserAccountCacheModule>();
3852 if (cache != null)
3853 cache.Remove(agent.firstname + " " + agent.lastname);
3854 if (!TestLandRestrictions(agent.AgentID, out reason, ref agent.startpos.X, ref agent.startpos.Y))
3678 { 3855 {
3856 m_log.DebugFormat("[CONNECTION BEGIN]: Denying access to {0} due to no land access", agent.AgentID.ToString());
3679 return false; 3857 return false;
3680 } 3858 }
3681 } 3859 }
3682 3860
3683 if (sp == null) // We don't have an [child] agent here already 3861 if (sp == null) // We don't have an [child] agent here already
3684 { 3862 {
3685 if (requirePresenceLookup) 3863 if (requirePresenceLookup)
@@ -3688,34 +3866,36 @@ namespace OpenSim.Region.Framework.Scenes
3688 { 3866 {
3689 if (!VerifyUserPresence(agent, out reason)) 3867 if (!VerifyUserPresence(agent, out reason))
3690 return false; 3868 return false;
3691 } 3869 } catch (Exception e)
3692 catch (Exception e)
3693 { 3870 {
3694 m_log.ErrorFormat( 3871 m_log.ErrorFormat(
3695 "[SCENE]: Exception verifying presence {0}{1}", e.Message, e.StackTrace); 3872 "[SCENE]: Exception verifying presence {0}{1}", e.Message, e.StackTrace);
3696
3697 return false; 3873 return false;
3698 } 3874 }
3699 } 3875 }
3700 3876
3701 try 3877 try
3702 { 3878 {
3703 if (!AuthorizeUser(agent, out reason)) 3879 // Always check estate if this is a login. Always
3704 return false; 3880 // check if banned regions are to be blacked out.
3881 if (vialogin || (!m_seeIntoBannedRegion))
3882 {
3883 if (!AuthorizeUser(agent, out reason))
3884 return false;
3885 }
3705 } 3886 }
3706 catch (Exception e) 3887 catch (Exception e)
3707 { 3888 {
3708 m_log.ErrorFormat( 3889 m_log.ErrorFormat(
3709 "[SCENE]: Exception authorizing user {0}{1}", e.Message, e.StackTrace); 3890 "[SCENE]: Exception authorizing user {0}{1}", e.Message, e.StackTrace);
3710
3711 return false; 3891 return false;
3712 } 3892 }
3713 3893
3714 m_log.InfoFormat( 3894 m_log.InfoFormat(
3715 "[SCENE]: Region {0} authenticated and authorized incoming {1} agent {2} {3} {4} (circuit code {5})", 3895 "[SCENE]: Region {0} authenticated and authorized incoming {1} agent {2} {3} {4} (circuit code {5})",
3716 RegionInfo.RegionName, (agent.child ? "child" : "root"), agent.firstname, agent.lastname, 3896 RegionInfo.RegionName, (agent.child ? "child" : "root"), agent.firstname, agent.lastname,
3717 agent.AgentID, agent.circuitcode); 3897 agent.AgentID, agent.circuitcode);
3718 3898
3719 if (CapsModule != null) 3899 if (CapsModule != null)
3720 { 3900 {
3721 CapsModule.SetAgentCapsSeeds(agent); 3901 CapsModule.SetAgentCapsSeeds(agent);
@@ -3727,15 +3907,15 @@ namespace OpenSim.Region.Framework.Scenes
3727 // Let the SP know how we got here. This has a lot of interesting 3907 // Let the SP know how we got here. This has a lot of interesting
3728 // uses down the line. 3908 // uses down the line.
3729 sp.TeleportFlags = (TPFlags)teleportFlags; 3909 sp.TeleportFlags = (TPFlags)teleportFlags;
3730 3910
3731 if (sp.IsChildAgent) 3911 if (sp.IsChildAgent)
3732 { 3912 {
3733 m_log.DebugFormat( 3913 m_log.DebugFormat(
3734 "[SCENE]: Adjusting known seeds for existing agent {0} in {1}", 3914 "[SCENE]: Adjusting known seeds for existing agent {0} in {1}",
3735 agent.AgentID, RegionInfo.RegionName); 3915 agent.AgentID, RegionInfo.RegionName);
3736 3916
3737 sp.AdjustKnownSeeds(); 3917 sp.AdjustKnownSeeds();
3738 3918
3739 if (CapsModule != null) 3919 if (CapsModule != null)
3740 CapsModule.SetAgentCapsSeeds(agent); 3920 CapsModule.SetAgentCapsSeeds(agent);
3741 } 3921 }
@@ -3837,6 +4017,8 @@ namespace OpenSim.Region.Framework.Scenes
3837 } 4017 }
3838 4018
3839 // Honor parcel landing type and position. 4019 // Honor parcel landing type and position.
4020 /*
4021 ILandObject land = LandChannel.GetLandObject(agent.startpos.X, agent.startpos.Y);
3840 if (land != null) 4022 if (land != null)
3841 { 4023 {
3842 if (land.LandData.LandingType == (byte)1 && land.LandData.UserLocation != Vector3.Zero) 4024 if (land.LandData.LandingType == (byte)1 && land.LandData.UserLocation != Vector3.Zero)
@@ -3844,25 +4026,43 @@ namespace OpenSim.Region.Framework.Scenes
3844 agent.startpos = land.LandData.UserLocation; 4026 agent.startpos = land.LandData.UserLocation;
3845 } 4027 }
3846 } 4028 }
4029 */// This is now handled properly in ScenePresence.MakeRootAgent
3847 } 4030 }
3848 4031
3849 return true; 4032 return true;
3850 } 4033 }
3851 4034
3852 private bool TestLandRestrictions(AgentCircuitData agent, ILandObject land, out string reason) 4035 public bool TestLandRestrictions(UUID agentID, out string reason, ref float posX, ref float posY)
3853 { 4036 {
3854 bool banned = land.IsBannedFromLand(agent.AgentID); 4037 if (posX < 0)
3855 bool restricted = land.IsRestrictedFromLand(agent.AgentID); 4038 posX = 0;
4039 else if (posX >= 256)
4040 posX = 255.999f;
4041 if (posY < 0)
4042 posY = 0;
4043 else if (posY >= 256)
4044 posY = 255.999f;
4045
4046 reason = String.Empty;
4047 if (Permissions.IsGod(agentID))
4048 return true;
4049
4050 ILandObject land = LandChannel.GetLandObject(posX, posY);
4051 if (land == null)
4052 return false;
4053
4054 bool banned = land.IsBannedFromLand(agentID);
4055 bool restricted = land.IsRestrictedFromLand(agentID);
3856 4056
3857 if (banned || restricted) 4057 if (banned || restricted)
3858 { 4058 {
3859 ILandObject nearestParcel = GetNearestAllowedParcel(agent.AgentID, agent.startpos.X, agent.startpos.Y); 4059 ILandObject nearestParcel = GetNearestAllowedParcel(agentID, posX, posY);
3860 if (nearestParcel != null) 4060 if (nearestParcel != null)
3861 { 4061 {
3862 //Move agent to nearest allowed 4062 //Move agent to nearest allowed
3863 Vector3 newPosition = GetParcelCenterAtGround(nearestParcel); 4063 Vector3 newPosition = GetParcelCenterAtGround(nearestParcel);
3864 agent.startpos.X = newPosition.X; 4064 posX = newPosition.X;
3865 agent.startpos.Y = newPosition.Y; 4065 posY = newPosition.Y;
3866 } 4066 }
3867 else 4067 else
3868 { 4068 {
@@ -3924,7 +4124,7 @@ namespace OpenSim.Region.Framework.Scenes
3924 4124
3925 if (!m_strictAccessControl) return true; 4125 if (!m_strictAccessControl) return true;
3926 if (Permissions.IsGod(agent.AgentID)) return true; 4126 if (Permissions.IsGod(agent.AgentID)) return true;
3927 4127
3928 if (AuthorizationService != null) 4128 if (AuthorizationService != null)
3929 { 4129 {
3930 if (!AuthorizationService.IsAuthorizedForRegion( 4130 if (!AuthorizationService.IsAuthorizedForRegion(
@@ -3939,7 +4139,7 @@ namespace OpenSim.Region.Framework.Scenes
3939 4139
3940 if (RegionInfo.EstateSettings != null) 4140 if (RegionInfo.EstateSettings != null)
3941 { 4141 {
3942 if (RegionInfo.EstateSettings.IsBanned(agent.AgentID)) 4142 if (RegionInfo.EstateSettings.IsBanned(agent.AgentID, 0))
3943 { 4143 {
3944 m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user is on the banlist", 4144 m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user is on the banlist",
3945 agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName); 4145 agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
@@ -4129,6 +4329,15 @@ namespace OpenSim.Region.Framework.Scenes
4129 4329
4130 // XPTO: if this agent is not allowed here as root, always return false 4330 // XPTO: if this agent is not allowed here as root, always return false
4131 4331
4332 // We have to wait until the viewer contacts this region after receiving EAC.
4333 // That calls AddNewClient, which finally creates the ScenePresence
4334 int flags = GetUserFlags(cAgentData.AgentID);
4335 if (RegionInfo.EstateSettings.IsBanned(cAgentData.AgentID, flags))
4336 {
4337 m_log.DebugFormat("[SCENE]: Denying root agent entry to {0}: banned", cAgentData.AgentID);
4338 return false;
4339 }
4340
4132 // TODO: This check should probably be in QueryAccess(). 4341 // TODO: This check should probably be in QueryAccess().
4133 ILandObject nearestParcel = GetNearestAllowedParcel(cAgentData.AgentID, Constants.RegionSize / 2, Constants.RegionSize / 2); 4342 ILandObject nearestParcel = GetNearestAllowedParcel(cAgentData.AgentID, Constants.RegionSize / 2, Constants.RegionSize / 2);
4134 if (nearestParcel == null) 4343 if (nearestParcel == null)
@@ -4193,7 +4402,7 @@ namespace OpenSim.Region.Framework.Scenes
4193 /// <param name='agentID'></param> 4402 /// <param name='agentID'></param>
4194 protected virtual ScenePresence WaitGetScenePresence(UUID agentID) 4403 protected virtual ScenePresence WaitGetScenePresence(UUID agentID)
4195 { 4404 {
4196 int ntimes = 10; 4405 int ntimes = 30;
4197 ScenePresence sp = null; 4406 ScenePresence sp = null;
4198 while ((sp = GetScenePresence(agentID)) == null && (ntimes-- > 0)) 4407 while ((sp = GetScenePresence(agentID)) == null && (ntimes-- > 0))
4199 Thread.Sleep(1000); 4408 Thread.Sleep(1000);
@@ -4223,6 +4432,16 @@ namespace OpenSim.Region.Framework.Scenes
4223 return false; 4432 return false;
4224 } 4433 }
4225 4434
4435 public bool IncomingCloseAgent(UUID agentID)
4436 {
4437 return IncomingCloseAgent(agentID, false);
4438 }
4439
4440 public bool IncomingCloseChildAgent(UUID agentID)
4441 {
4442 return IncomingCloseAgent(agentID, true);
4443 }
4444
4226 /// <summary> 4445 /// <summary>
4227 /// Tell a single agent to disconnect from the region. 4446 /// Tell a single agent to disconnect from the region.
4228 /// </summary> 4447 /// </summary>
@@ -4238,7 +4457,7 @@ namespace OpenSim.Region.Framework.Scenes
4238 ScenePresence presence = m_sceneGraph.GetScenePresence(agentID); 4457 ScenePresence presence = m_sceneGraph.GetScenePresence(agentID);
4239 if (presence != null) 4458 if (presence != null)
4240 { 4459 {
4241 presence.ControllingClient.Close(force); 4460 presence.ControllingClient.Close(force, force);
4242 return true; 4461 return true;
4243 } 4462 }
4244 4463
@@ -4898,35 +5117,81 @@ namespace OpenSim.Region.Framework.Scenes
4898 SimulationDataService.RemoveObject(uuid, RegionInfo.RegionID); 5117 SimulationDataService.RemoveObject(uuid, RegionInfo.RegionID);
4899 } 5118 }
4900 5119
4901 public int GetHealth() 5120 public int GetHealth(out int flags, out string message)
4902 { 5121 {
4903 // Returns: 5122 // Returns:
4904 // 1 = sim is up and accepting http requests. The heartbeat has 5123 // 1 = sim is up and accepting http requests. The heartbeat has
4905 // stopped and the sim is probably locked up, but a remote 5124 // stopped and the sim is probably locked up, but a remote
4906 // admin restart may succeed 5125 // admin restart may succeed
4907 // 5126 //
4908 // 2 = Sim is up and the heartbeat is running. The sim is likely 5127 // 2 = Sim is up and the heartbeat is running. The sim is likely
4909 // usable for people within and logins _may_ work 5128 // usable for people within
5129 //
5130 // 3 = Sim is up and one packet thread is running. Sim is
5131 // unstable and will not accept new logins
4910 // 5132 //
4911 // 3 = We have seen a new user enter within the past 4 minutes 5133 // 4 = Sim is up and both packet threads are running. Sim is
5134 // likely usable
5135 //
5136 // 5 = We have seen a new user enter within the past 4 minutes
4912 // which can be seen as positive confirmation of sim health 5137 // which can be seen as positive confirmation of sim health
4913 // 5138 //
5139
5140 flags = 0;
5141 message = String.Empty;
5142
5143 CheckHeartbeat();
5144
5145 if (m_firstHeartbeat || (m_lastIncoming == 0 && m_lastOutgoing == 0))
5146 {
5147 // We're still starting
5148 // 0 means "in startup", it can't happen another way, since
5149 // to get here, we must be able to accept http connections
5150 return 0;
5151 }
5152
4914 int health=1; // Start at 1, means we're up 5153 int health=1; // Start at 1, means we're up
4915 5154
4916 if ((Util.EnvironmentTickCountSubtract(m_lastFrameTick)) < 1000) 5155 if ((Util.EnvironmentTickCountSubtract(m_lastFrameTick)) < 1000)
4917 health += 1; 5156 {
5157 health+=1;
5158 flags |= 1;
5159 }
5160
5161 if (Util.EnvironmentTickCountSubtract(m_lastIncoming) < 1000)
5162 {
5163 health+=1;
5164 flags |= 2;
5165 }
5166
5167 if (Util.EnvironmentTickCountSubtract(m_lastOutgoing) < 1000)
5168 {
5169 health+=1;
5170 flags |= 4;
5171 }
4918 else 5172 else
5173 {
5174int pid = System.Diagnostics.Process.GetCurrentProcess().Id;
5175System.Diagnostics.Process proc = new System.Diagnostics.Process();
5176proc.EnableRaisingEvents=false;
5177proc.StartInfo.FileName = "/bin/kill";
5178proc.StartInfo.Arguments = "-QUIT " + pid.ToString();
5179proc.Start();
5180proc.WaitForExit();
5181Thread.Sleep(1000);
5182Environment.Exit(1);
5183 }
5184
5185 if (flags != 7)
4919 return health; 5186 return health;
4920 5187
4921 // A login in the last 4 mins? We can't be doing too badly 5188 // A login in the last 4 mins? We can't be doing too badly
4922 // 5189 //
4923 if ((Util.EnvironmentTickCountSubtract(m_LastLogin)) < 240000) 5190 if (Util.EnvironmentTickCountSubtract(m_LastLogin) < 240000)
4924 health++; 5191 health++;
4925 else 5192 else
4926 return health; 5193 return health;
4927 5194
4928// CheckHeartbeat();
4929
4930 return health; 5195 return health;
4931 } 5196 }
4932 5197
@@ -5014,7 +5279,7 @@ namespace OpenSim.Region.Framework.Scenes
5014 bool wasUsingPhysics = ((jointProxyObject.Flags & PrimFlags.Physics) != 0); 5279 bool wasUsingPhysics = ((jointProxyObject.Flags & PrimFlags.Physics) != 0);
5015 if (wasUsingPhysics) 5280 if (wasUsingPhysics)
5016 { 5281 {
5017 jointProxyObject.UpdatePrimFlags(false, false, true, false); // FIXME: possible deadlock here; check to make sure all the scene alterations set into motion here won't deadlock 5282 jointProxyObject.UpdatePrimFlags(false, false, true, false,false); // FIXME: possible deadlock here; check to make sure all the scene alterations set into motion here won't deadlock
5018 } 5283 }
5019 } 5284 }
5020 5285
@@ -5113,14 +5378,14 @@ namespace OpenSim.Region.Framework.Scenes
5113 return (((vsn.X * xdiff) + (vsn.Y * ydiff)) / (-1 * vsn.Z)) + p0.Z; 5378 return (((vsn.X * xdiff) + (vsn.Y * ydiff)) / (-1 * vsn.Z)) + p0.Z;
5114 } 5379 }
5115 5380
5116// private void CheckHeartbeat() 5381 private void CheckHeartbeat()
5117// { 5382 {
5118// if (m_firstHeartbeat) 5383 if (m_firstHeartbeat)
5119// return; 5384 return;
5120// 5385
5121// if (Util.EnvironmentTickCountSubtract(m_lastFrameTick) > 2000) 5386 if ((Util.EnvironmentTickCountSubtract(m_lastFrameTick)) > 5000)
5122// StartTimer(); 5387 Start();
5123// } 5388 }
5124 5389
5125 public override ISceneObject DeserializeObject(string representation) 5390 public override ISceneObject DeserializeObject(string representation)
5126 { 5391 {
@@ -5132,9 +5397,14 @@ namespace OpenSim.Region.Framework.Scenes
5132 get { return m_allowScriptCrossings; } 5397 get { return m_allowScriptCrossings; }
5133 } 5398 }
5134 5399
5135 public Vector3? GetNearestAllowedPosition(ScenePresence avatar) 5400 public Vector3 GetNearestAllowedPosition(ScenePresence avatar)
5136 { 5401 {
5137 ILandObject nearestParcel = GetNearestAllowedParcel(avatar.UUID, avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y); 5402 return GetNearestAllowedPosition(avatar, null);
5403 }
5404
5405 public Vector3 GetNearestAllowedPosition(ScenePresence avatar, ILandObject excludeParcel)
5406 {
5407 ILandObject nearestParcel = GetNearestAllowedParcel(avatar.UUID, avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y, excludeParcel);
5138 5408
5139 if (nearestParcel != null) 5409 if (nearestParcel != null)
5140 { 5410 {
@@ -5143,10 +5413,7 @@ namespace OpenSim.Region.Framework.Scenes
5143 Vector3? nearestPoint = GetNearestPointInParcelAlongDirectionFromPoint(avatar.AbsolutePosition, dir, nearestParcel); 5413 Vector3? nearestPoint = GetNearestPointInParcelAlongDirectionFromPoint(avatar.AbsolutePosition, dir, nearestParcel);
5144 if (nearestPoint != null) 5414 if (nearestPoint != null)
5145 { 5415 {
5146// m_log.DebugFormat( 5416 Debug.WriteLine("Found a sane previous position based on velocity, sending them to: " + nearestPoint.ToString());
5147// "[SCENE]: Found a sane previous position based on velocity for {0}, sending them to {1} in {2}",
5148// avatar.Name, nearestPoint, nearestParcel.LandData.Name);
5149
5150 return nearestPoint.Value; 5417 return nearestPoint.Value;
5151 } 5418 }
5152 5419
@@ -5156,17 +5423,20 @@ namespace OpenSim.Region.Framework.Scenes
5156 nearestPoint = GetNearestPointInParcelAlongDirectionFromPoint(avatar.AbsolutePosition, dir, nearestParcel); 5423 nearestPoint = GetNearestPointInParcelAlongDirectionFromPoint(avatar.AbsolutePosition, dir, nearestParcel);
5157 if (nearestPoint != null) 5424 if (nearestPoint != null)
5158 { 5425 {
5159// m_log.DebugFormat( 5426 Debug.WriteLine("They had a zero velocity, sending them to: " + nearestPoint.ToString());
5160// "[SCENE]: {0} had a zero velocity, sending them to {1}", avatar.Name, nearestPoint);
5161
5162 return nearestPoint.Value; 5427 return nearestPoint.Value;
5163 } 5428 }
5164 5429
5165 //Ultimate backup if we have no idea where they are 5430 ILandObject dest = LandChannel.GetLandObject(avatar.lastKnownAllowedPosition.X, avatar.lastKnownAllowedPosition.Y);
5166// m_log.DebugFormat( 5431 if (dest != excludeParcel)
5167// "[SCENE]: No idea where {0} is, sending them to {1}", avatar.Name, avatar.lastKnownAllowedPosition); 5432 {
5433 // Ultimate backup if we have no idea where they are and
5434 // the last allowed position was in another parcel
5435 Debug.WriteLine("Have no idea where they are, sending them to: " + avatar.lastKnownAllowedPosition.ToString());
5436 return avatar.lastKnownAllowedPosition;
5437 }
5168 5438
5169 return avatar.lastKnownAllowedPosition; 5439 // else fall through to region edge
5170 } 5440 }
5171 5441
5172 //Go to the edge, this happens in teleporting to a region with no available parcels 5442 //Go to the edge, this happens in teleporting to a region with no available parcels
@@ -5200,13 +5470,18 @@ namespace OpenSim.Region.Framework.Scenes
5200 5470
5201 public ILandObject GetNearestAllowedParcel(UUID avatarId, float x, float y) 5471 public ILandObject GetNearestAllowedParcel(UUID avatarId, float x, float y)
5202 { 5472 {
5473 return GetNearestAllowedParcel(avatarId, x, y, null);
5474 }
5475
5476 public ILandObject GetNearestAllowedParcel(UUID avatarId, float x, float y, ILandObject excludeParcel)
5477 {
5203 List<ILandObject> all = AllParcels(); 5478 List<ILandObject> all = AllParcels();
5204 float minParcelDistance = float.MaxValue; 5479 float minParcelDistance = float.MaxValue;
5205 ILandObject nearestParcel = null; 5480 ILandObject nearestParcel = null;
5206 5481
5207 foreach (var parcel in all) 5482 foreach (var parcel in all)
5208 { 5483 {
5209 if (!parcel.IsEitherBannedOrRestricted(avatarId)) 5484 if (!parcel.IsEitherBannedOrRestricted(avatarId) && parcel != excludeParcel)
5210 { 5485 {
5211 float parcelDistance = GetParcelDistancefromPoint(parcel, x, y); 5486 float parcelDistance = GetParcelDistancefromPoint(parcel, x, y);
5212 if (parcelDistance < minParcelDistance) 5487 if (parcelDistance < minParcelDistance)
@@ -5422,7 +5697,55 @@ namespace OpenSim.Region.Framework.Scenes
5422 mapModule.GenerateMaptile(); 5697 mapModule.GenerateMaptile();
5423 } 5698 }
5424 5699
5425 private void RegenerateMaptileAndReregister(object sender, ElapsedEventArgs e) 5700// public void CleanDroppedAttachments()
5701// {
5702// List<SceneObjectGroup> objectsToDelete =
5703// new List<SceneObjectGroup>();
5704//
5705// lock (m_cleaningAttachments)
5706// {
5707// ForEachSOG(delegate (SceneObjectGroup grp)
5708// {
5709// if (grp.RootPart.Shape.PCode == 0 && grp.RootPart.Shape.State != 0 && (!objectsToDelete.Contains(grp)))
5710// {
5711// UUID agentID = grp.OwnerID;
5712// if (agentID == UUID.Zero)
5713// {
5714// objectsToDelete.Add(grp);
5715// return;
5716// }
5717//
5718// ScenePresence sp = GetScenePresence(agentID);
5719// if (sp == null)
5720// {
5721// objectsToDelete.Add(grp);
5722// return;
5723// }
5724// }
5725// });
5726// }
5727//
5728// foreach (SceneObjectGroup grp in objectsToDelete)
5729// {
5730// m_log.InfoFormat("[SCENE]: Deleting dropped attachment {0} of user {1}", grp.UUID, grp.OwnerID);
5731// DeleteSceneObject(grp, true);
5732// }
5733// }
5734
5735 public void ThreadAlive(int threadCode)
5736 {
5737 switch(threadCode)
5738 {
5739 case 1: // Incoming
5740 m_lastIncoming = Util.EnvironmentTickCount();
5741 break;
5742 case 2: // Incoming
5743 m_lastOutgoing = Util.EnvironmentTickCount();
5744 break;
5745 }
5746 }
5747
5748 public void RegenerateMaptileAndReregister(object sender, ElapsedEventArgs e)
5426 { 5749 {
5427 RegenerateMaptile(); 5750 RegenerateMaptile();
5428 5751
@@ -5450,6 +5773,8 @@ namespace OpenSim.Region.Framework.Scenes
5450 /// <returns></returns> 5773 /// <returns></returns>
5451 public bool QueryAccess(UUID agentID, Vector3 position, out string reason) 5774 public bool QueryAccess(UUID agentID, Vector3 position, out string reason)
5452 { 5775 {
5776 reason = "You are banned from the region";
5777
5453 if (EntityTransferModule.IsInTransit(agentID)) 5778 if (EntityTransferModule.IsInTransit(agentID))
5454 { 5779 {
5455 reason = "Agent is still in transit from this region"; 5780 reason = "Agent is still in transit from this region";
@@ -5461,6 +5786,12 @@ namespace OpenSim.Region.Framework.Scenes
5461 return false; 5786 return false;
5462 } 5787 }
5463 5788
5789 if (Permissions.IsGod(agentID))
5790 {
5791 reason = String.Empty;
5792 return true;
5793 }
5794
5464 // FIXME: Root agent count is currently known to be inaccurate. This forces a recount before we check. 5795 // FIXME: Root agent count is currently known to be inaccurate. This forces a recount before we check.
5465 // However, the long term fix is to make sure root agent count is always accurate. 5796 // However, the long term fix is to make sure root agent count is always accurate.
5466 m_sceneGraph.RecalculateStats(); 5797 m_sceneGraph.RecalculateStats();
@@ -5481,6 +5812,41 @@ namespace OpenSim.Region.Framework.Scenes
5481 } 5812 }
5482 } 5813 }
5483 5814
5815 ScenePresence presence = GetScenePresence(agentID);
5816 IClientAPI client = null;
5817 AgentCircuitData aCircuit = null;
5818
5819 if (presence != null)
5820 {
5821 client = presence.ControllingClient;
5822 if (client != null)
5823 aCircuit = client.RequestClientInfo();
5824 }
5825
5826 // We may be called before there is a presence or a client.
5827 // Fake AgentCircuitData to keep IAuthorizationModule smiling
5828 if (client == null)
5829 {
5830 aCircuit = new AgentCircuitData();
5831 aCircuit.AgentID = agentID;
5832 aCircuit.firstname = String.Empty;
5833 aCircuit.lastname = String.Empty;
5834 }
5835
5836 try
5837 {
5838 if (!AuthorizeUser(aCircuit, out reason))
5839 {
5840 // m_log.DebugFormat("[SCENE]: Denying access for {0}", agentID);
5841 return false;
5842 }
5843 }
5844 catch (Exception e)
5845 {
5846 m_log.DebugFormat("[SCENE]: Exception authorizing agent: {0} "+ e.StackTrace, e.Message);
5847 return false;
5848 }
5849
5484 if (position == Vector3.Zero) // Teleport 5850 if (position == Vector3.Zero) // Teleport
5485 { 5851 {
5486 if (!RegionInfo.EstateSettings.AllowDirectTeleport) 5852 if (!RegionInfo.EstateSettings.AllowDirectTeleport)
@@ -5509,13 +5875,46 @@ namespace OpenSim.Region.Framework.Scenes
5509 } 5875 }
5510 } 5876 }
5511 } 5877 }
5878
5879 float posX = 128.0f;
5880 float posY = 128.0f;
5881
5882 if (!TestLandRestrictions(agentID, out reason, ref posX, ref posY))
5883 {
5884 // m_log.DebugFormat("[SCENE]: Denying {0} because they are banned on all parcels", agentID);
5885 return false;
5886 }
5887 }
5888 else // Walking
5889 {
5890 ILandObject land = LandChannel.GetLandObject(position.X, position.Y);
5891 if (land == null)
5892 return false;
5893
5894 bool banned = land.IsBannedFromLand(agentID);
5895 bool restricted = land.IsRestrictedFromLand(agentID);
5896
5897 if (banned || restricted)
5898 return false;
5512 } 5899 }
5513 5900
5514 reason = String.Empty; 5901 reason = String.Empty;
5515 return true; 5902 return true;
5516 } 5903 }
5517 5904
5518 /// <summary> 5905 public void StartTimerWatchdog()
5906 {
5907 m_timerWatchdog.Interval = 1000;
5908 m_timerWatchdog.Elapsed += TimerWatchdog;
5909 m_timerWatchdog.AutoReset = true;
5910 m_timerWatchdog.Start();
5911 }
5912
5913 public void TimerWatchdog(object sender, ElapsedEventArgs e)
5914 {
5915 CheckHeartbeat();
5916 }
5917
5519 /// This method deals with movement when an avatar is automatically moving (but this is distinct from the 5918 /// This method deals with movement when an avatar is automatically moving (but this is distinct from the
5520 /// autopilot that moves an avatar to a sit target!. 5919 /// autopilot that moves an avatar to a sit target!.
5521 /// </summary> 5920 /// </summary>
@@ -5594,6 +5993,11 @@ namespace OpenSim.Region.Framework.Scenes
5594 return m_SpawnPoint - 1; 5993 return m_SpawnPoint - 1;
5595 } 5994 }
5596 5995
5996 private void HandleGcCollect(string module, string[] args)
5997 {
5998 GC.Collect();
5999 }
6000
5597 /// <summary> 6001 /// <summary>
5598 /// Wrappers to get physics modules retrieve assets. 6002 /// Wrappers to get physics modules retrieve assets.
5599 /// </summary> 6003 /// </summary>
diff --git a/OpenSim/Region/Framework/Scenes/SceneBase.cs b/OpenSim/Region/Framework/Scenes/SceneBase.cs
index d3e968e..74c9582 100644
--- a/OpenSim/Region/Framework/Scenes/SceneBase.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneBase.cs
@@ -143,7 +143,6 @@ namespace OpenSim.Region.Framework.Scenes
143 143
144 protected ulong m_regionHandle; 144 protected ulong m_regionHandle;
145 protected string m_regionName; 145 protected string m_regionName;
146 protected RegionInfo m_regInfo;
147 146
148 public ITerrainChannel Heightmap; 147 public ITerrainChannel Heightmap;
149 148
@@ -168,6 +167,8 @@ namespace OpenSim.Region.Framework.Scenes
168 get { return m_permissions; } 167 get { return m_permissions; }
169 } 168 }
170 169
170 protected string m_datastore;
171
171 /* Used by the loadbalancer plugin on GForge */ 172 /* Used by the loadbalancer plugin on GForge */
172 protected RegionStatus m_regStatus; 173 protected RegionStatus m_regStatus;
173 public RegionStatus RegionStatus 174 public RegionStatus RegionStatus
diff --git a/OpenSim/Region/Framework/Scenes/SceneCommunicationService.cs b/OpenSim/Region/Framework/Scenes/SceneCommunicationService.cs
index 305f8a4..775a4c2 100644
--- a/OpenSim/Region/Framework/Scenes/SceneCommunicationService.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneCommunicationService.cs
@@ -194,10 +194,13 @@ namespace OpenSim.Region.Framework.Scenes
194 } 194 }
195 } 195 }
196 196
197 public delegate void SendCloseChildAgentDelegate(UUID agentID, ulong regionHandle);
198
197 /// <summary> 199 /// <summary>
198 /// Closes a child agent on a given region 200 /// This Closes child agents on neighboring regions
201 /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
199 /// </summary> 202 /// </summary>
200 protected void SendCloseChildAgent(UUID agentID, ulong regionHandle) 203 protected void SendCloseChildAgentAsync(UUID agentID, ulong regionHandle)
201 { 204 {
202 // let's do our best, but there's not much we can do if the neighbour doesn't accept. 205 // let's do our best, but there's not much we can do if the neighbour doesn't accept.
203 206
@@ -206,30 +209,29 @@ namespace OpenSim.Region.Framework.Scenes
206 Utils.LongToUInts(regionHandle, out x, out y); 209 Utils.LongToUInts(regionHandle, out x, out y);
207 210
208 GridRegion destination = m_scene.GridService.GetRegionByPosition(m_regionInfo.ScopeID, (int)x, (int)y); 211 GridRegion destination = m_scene.GridService.GetRegionByPosition(m_regionInfo.ScopeID, (int)x, (int)y);
212 m_scene.SimulationService.CloseChildAgent(destination, agentID);
213 }
209 214
210 m_log.DebugFormat( 215 private void SendCloseChildAgentCompleted(IAsyncResult iar)
211 "[SCENE COMMUNICATION SERVICE]: Sending close agent ID {0} to {1}", agentID, destination.RegionName); 216 {
212 217 SendCloseChildAgentDelegate icon = (SendCloseChildAgentDelegate)iar.AsyncState;
213 m_scene.SimulationService.CloseAgent(destination, agentID); 218 icon.EndInvoke(iar);
214 } 219 }
215 220
216 /// <summary>
217 /// Closes a child agents in a collection of regions. Does so asynchronously
218 /// so that the caller doesn't wait.
219 /// </summary>
220 /// <param name="agentID"></param>
221 /// <param name="regionslst"></param>
222 public void SendCloseChildAgentConnections(UUID agentID, List<ulong> regionslst) 221 public void SendCloseChildAgentConnections(UUID agentID, List<ulong> regionslst)
223 { 222 {
224 foreach (ulong handle in regionslst) 223 foreach (ulong handle in regionslst)
225 { 224 {
226 SendCloseChildAgent(agentID, handle); 225 SendCloseChildAgentDelegate d = SendCloseChildAgentAsync;
226 d.BeginInvoke(agentID, handle,
227 SendCloseChildAgentCompleted,
228 d);
227 } 229 }
228 } 230 }
229 231
230 public List<GridRegion> RequestNamedRegions(string name, int maxNumber) 232 public List<GridRegion> RequestNamedRegions(string name, int maxNumber)
231 { 233 {
232 return m_scene.GridService.GetRegionsByName(UUID.Zero, name, maxNumber); 234 return m_scene.GridService.GetRegionsByName(UUID.Zero, name, maxNumber);
233 } 235 }
234 } 236 }
235} \ No newline at end of file 237}
diff --git a/OpenSim/Region/Framework/Scenes/SceneGraph.cs b/OpenSim/Region/Framework/Scenes/SceneGraph.cs
index a4383fd..e599e90 100644
--- a/OpenSim/Region/Framework/Scenes/SceneGraph.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneGraph.cs
@@ -41,6 +41,12 @@ namespace OpenSim.Region.Framework.Scenes
41{ 41{
42 public delegate void PhysicsCrash(); 42 public delegate void PhysicsCrash();
43 43
44 public delegate void AttachToBackupDelegate(SceneObjectGroup sog);
45
46 public delegate void DetachFromBackupDelegate(SceneObjectGroup sog);
47
48 public delegate void ChangedBackupDelegate(SceneObjectGroup sog);
49
44 /// <summary> 50 /// <summary>
45 /// This class used to be called InnerScene and may not yet truly be a SceneGraph. The non scene graph components 51 /// This class used to be called InnerScene and may not yet truly be a SceneGraph. The non scene graph components
46 /// should be migrated out over time. 52 /// should be migrated out over time.
@@ -54,11 +60,15 @@ namespace OpenSim.Region.Framework.Scenes
54 protected internal event PhysicsCrash UnRecoverableError; 60 protected internal event PhysicsCrash UnRecoverableError;
55 private PhysicsCrash handlerPhysicsCrash = null; 61 private PhysicsCrash handlerPhysicsCrash = null;
56 62
63 public event AttachToBackupDelegate OnAttachToBackup;
64 public event DetachFromBackupDelegate OnDetachFromBackup;
65 public event ChangedBackupDelegate OnChangeBackup;
66
57 #endregion 67 #endregion
58 68
59 #region Fields 69 #region Fields
60 70
61 protected object m_presenceLock = new object(); 71 protected OpenMetaverse.ReaderWriterLockSlim m_scenePresencesLock = new OpenMetaverse.ReaderWriterLockSlim();
62 protected Dictionary<UUID, ScenePresence> m_scenePresenceMap = new Dictionary<UUID, ScenePresence>(); 72 protected Dictionary<UUID, ScenePresence> m_scenePresenceMap = new Dictionary<UUID, ScenePresence>();
63 protected List<ScenePresence> m_scenePresenceArray = new List<ScenePresence>(); 73 protected List<ScenePresence> m_scenePresenceArray = new List<ScenePresence>();
64 74
@@ -127,13 +137,18 @@ namespace OpenSim.Region.Framework.Scenes
127 137
128 protected internal void Close() 138 protected internal void Close()
129 { 139 {
130 lock (m_presenceLock) 140 m_scenePresencesLock.EnterWriteLock();
141 try
131 { 142 {
132 Dictionary<UUID, ScenePresence> newmap = new Dictionary<UUID, ScenePresence>(); 143 Dictionary<UUID, ScenePresence> newmap = new Dictionary<UUID, ScenePresence>();
133 List<ScenePresence> newlist = new List<ScenePresence>(); 144 List<ScenePresence> newlist = new List<ScenePresence>();
134 m_scenePresenceMap = newmap; 145 m_scenePresenceMap = newmap;
135 m_scenePresenceArray = newlist; 146 m_scenePresenceArray = newlist;
136 } 147 }
148 finally
149 {
150 m_scenePresencesLock.ExitWriteLock();
151 }
137 152
138 lock (SceneObjectGroupsByFullID) 153 lock (SceneObjectGroupsByFullID)
139 SceneObjectGroupsByFullID.Clear(); 154 SceneObjectGroupsByFullID.Clear();
@@ -254,6 +269,33 @@ namespace OpenSim.Region.Framework.Scenes
254 protected internal bool AddRestoredSceneObject( 269 protected internal bool AddRestoredSceneObject(
255 SceneObjectGroup sceneObject, bool attachToBackup, bool alreadyPersisted, bool sendClientUpdates) 270 SceneObjectGroup sceneObject, bool attachToBackup, bool alreadyPersisted, bool sendClientUpdates)
256 { 271 {
272 if (!m_parentScene.CombineRegions)
273 {
274 // KF: Check for out-of-region, move inside and make static.
275 Vector3 npos = new Vector3(sceneObject.RootPart.GroupPosition.X,
276 sceneObject.RootPart.GroupPosition.Y,
277 sceneObject.RootPart.GroupPosition.Z);
278 if (!(((sceneObject.RootPart.Shape.PCode == (byte)PCode.Prim) && (sceneObject.RootPart.Shape.State != 0))) && (npos.X < 0.0 || npos.Y < 0.0 || npos.Z < 0.0 ||
279 npos.X > Constants.RegionSize ||
280 npos.Y > Constants.RegionSize))
281 {
282 if (npos.X < 0.0) npos.X = 1.0f;
283 if (npos.Y < 0.0) npos.Y = 1.0f;
284 if (npos.Z < 0.0) npos.Z = 0.0f;
285 if (npos.X > Constants.RegionSize) npos.X = Constants.RegionSize - 1.0f;
286 if (npos.Y > Constants.RegionSize) npos.Y = Constants.RegionSize - 1.0f;
287
288 foreach (SceneObjectPart part in sceneObject.Parts)
289 {
290 part.GroupPosition = npos;
291 }
292 sceneObject.RootPart.Velocity = Vector3.Zero;
293 sceneObject.RootPart.AngularVelocity = Vector3.Zero;
294 sceneObject.RootPart.Acceleration = Vector3.Zero;
295 sceneObject.RootPart.Velocity = Vector3.Zero;
296 }
297 }
298
257 if (attachToBackup && (!alreadyPersisted)) 299 if (attachToBackup && (!alreadyPersisted))
258 { 300 {
259 sceneObject.ForceInventoryPersistence(); 301 sceneObject.ForceInventoryPersistence();
@@ -317,9 +359,8 @@ namespace OpenSim.Region.Framework.Scenes
317 if (pa != null && pa.IsPhysical && vel != Vector3.Zero) 359 if (pa != null && pa.IsPhysical && vel != Vector3.Zero)
318 { 360 {
319 sceneObject.RootPart.ApplyImpulse((vel * sceneObject.GetMass()), false); 361 sceneObject.RootPart.ApplyImpulse((vel * sceneObject.GetMass()), false);
320 sceneObject.Velocity = vel;
321 } 362 }
322 363
323 return true; 364 return true;
324 } 365 }
325 366
@@ -344,6 +385,11 @@ namespace OpenSim.Region.Framework.Scenes
344 /// </returns> 385 /// </returns>
345 protected bool AddSceneObject(SceneObjectGroup sceneObject, bool attachToBackup, bool sendClientUpdates) 386 protected bool AddSceneObject(SceneObjectGroup sceneObject, bool attachToBackup, bool sendClientUpdates)
346 { 387 {
388 if (sceneObject == null)
389 {
390 m_log.ErrorFormat("[SCENEGRAPH]: Tried to add null scene object");
391 return false;
392 }
347 if (sceneObject.UUID == UUID.Zero) 393 if (sceneObject.UUID == UUID.Zero)
348 { 394 {
349 m_log.ErrorFormat( 395 m_log.ErrorFormat(
@@ -475,6 +521,30 @@ namespace OpenSim.Region.Framework.Scenes
475 m_updateList[obj.UUID] = obj; 521 m_updateList[obj.UUID] = obj;
476 } 522 }
477 523
524 public void FireAttachToBackup(SceneObjectGroup obj)
525 {
526 if (OnAttachToBackup != null)
527 {
528 OnAttachToBackup(obj);
529 }
530 }
531
532 public void FireDetachFromBackup(SceneObjectGroup obj)
533 {
534 if (OnDetachFromBackup != null)
535 {
536 OnDetachFromBackup(obj);
537 }
538 }
539
540 public void FireChangeBackup(SceneObjectGroup obj)
541 {
542 if (OnChangeBackup != null)
543 {
544 OnChangeBackup(obj);
545 }
546 }
547
478 /// <summary> 548 /// <summary>
479 /// Process all pending updates 549 /// Process all pending updates
480 /// </summary> 550 /// </summary>
@@ -519,12 +589,12 @@ namespace OpenSim.Region.Framework.Scenes
519 589
520 protected internal void AddPhysicalPrim(int number) 590 protected internal void AddPhysicalPrim(int number)
521 { 591 {
522 m_physicalPrim++; 592 m_physicalPrim += number;
523 } 593 }
524 594
525 protected internal void RemovePhysicalPrim(int number) 595 protected internal void RemovePhysicalPrim(int number)
526 { 596 {
527 m_physicalPrim--; 597 m_physicalPrim -= number;
528 } 598 }
529 599
530 protected internal void AddToScriptLPS(int number) 600 protected internal void AddToScriptLPS(int number)
@@ -592,7 +662,8 @@ namespace OpenSim.Region.Framework.Scenes
592 662
593 Entities[presence.UUID] = presence; 663 Entities[presence.UUID] = presence;
594 664
595 lock (m_presenceLock) 665 m_scenePresencesLock.EnterWriteLock();
666 try
596 { 667 {
597 Dictionary<UUID, ScenePresence> newmap = new Dictionary<UUID, ScenePresence>(m_scenePresenceMap); 668 Dictionary<UUID, ScenePresence> newmap = new Dictionary<UUID, ScenePresence>(m_scenePresenceMap);
598 List<ScenePresence> newlist = new List<ScenePresence>(m_scenePresenceArray); 669 List<ScenePresence> newlist = new List<ScenePresence>(m_scenePresenceArray);
@@ -616,6 +687,10 @@ namespace OpenSim.Region.Framework.Scenes
616 m_scenePresenceMap = newmap; 687 m_scenePresenceMap = newmap;
617 m_scenePresenceArray = newlist; 688 m_scenePresenceArray = newlist;
618 } 689 }
690 finally
691 {
692 m_scenePresencesLock.ExitWriteLock();
693 }
619 } 694 }
620 695
621 /// <summary> 696 /// <summary>
@@ -630,7 +705,8 @@ namespace OpenSim.Region.Framework.Scenes
630 agentID); 705 agentID);
631 } 706 }
632 707
633 lock (m_presenceLock) 708 m_scenePresencesLock.EnterWriteLock();
709 try
634 { 710 {
635 Dictionary<UUID, ScenePresence> newmap = new Dictionary<UUID, ScenePresence>(m_scenePresenceMap); 711 Dictionary<UUID, ScenePresence> newmap = new Dictionary<UUID, ScenePresence>(m_scenePresenceMap);
636 List<ScenePresence> newlist = new List<ScenePresence>(m_scenePresenceArray); 712 List<ScenePresence> newlist = new List<ScenePresence>(m_scenePresenceArray);
@@ -652,6 +728,10 @@ namespace OpenSim.Region.Framework.Scenes
652 m_log.WarnFormat("[SCENE GRAPH]: Tried to remove non-existent scene presence with agent ID {0} from scene ScenePresences list", agentID); 728 m_log.WarnFormat("[SCENE GRAPH]: Tried to remove non-existent scene presence with agent ID {0} from scene ScenePresences list", agentID);
653 } 729 }
654 } 730 }
731 finally
732 {
733 m_scenePresencesLock.ExitWriteLock();
734 }
655 } 735 }
656 736
657 protected internal void SwapRootChildAgent(bool direction_RC_CR_T_F) 737 protected internal void SwapRootChildAgent(bool direction_RC_CR_T_F)
@@ -1205,6 +1285,52 @@ namespace OpenSim.Region.Framework.Scenes
1205 1285
1206 #region Client Event handlers 1286 #region Client Event handlers
1207 1287
1288 protected internal void ClientChangeObject(uint localID, object odata, IClientAPI remoteClient)
1289 {
1290 SceneObjectPart part = GetSceneObjectPart(localID);
1291 ObjectChangeData data = (ObjectChangeData)odata;
1292
1293 if (part != null)
1294 {
1295 SceneObjectGroup grp = part.ParentGroup;
1296 if (grp != null)
1297 {
1298 if (m_parentScene.Permissions.CanEditObject(grp.UUID, remoteClient.AgentId))
1299 {
1300 // These two are exceptions SL makes in the interpretation
1301 // of the change flags. Must check them here because otherwise
1302 // the group flag (see below) would be lost
1303 if (data.change == ObjectChangeType.groupS)
1304 data.change = ObjectChangeType.primS;
1305 if (data.change == ObjectChangeType.groupPS)
1306 data.change = ObjectChangeType.primPS;
1307 part.StoreUndoState(data.change); // lets test only saving what we changed
1308 grp.doChangeObject(part, (ObjectChangeData)data);
1309 }
1310 else
1311 {
1312 // Is this any kind of group operation?
1313 if ((data.change & ObjectChangeType.Group) != 0)
1314 {
1315 // Is a move and/or rotation requested?
1316 if ((data.change & (ObjectChangeType.Position | ObjectChangeType.Rotation)) != 0)
1317 {
1318 // Are we allowed to move it?
1319 if (m_parentScene.Permissions.CanMoveObject(grp.UUID, remoteClient.AgentId))
1320 {
1321 // Strip all but move and rotation from request
1322 data.change &= (ObjectChangeType.Group | ObjectChangeType.Position | ObjectChangeType.Rotation);
1323
1324 part.StoreUndoState(data.change);
1325 grp.doChangeObject(part, (ObjectChangeData)data);
1326 }
1327 }
1328 }
1329 }
1330 }
1331 }
1332 }
1333
1208 /// <summary> 1334 /// <summary>
1209 /// Update the scale of an individual prim. 1335 /// Update the scale of an individual prim.
1210 /// </summary> 1336 /// </summary>
@@ -1219,7 +1345,17 @@ namespace OpenSim.Region.Framework.Scenes
1219 { 1345 {
1220 if (m_parentScene.Permissions.CanEditObject(part.ParentGroup.UUID, remoteClient.AgentId)) 1346 if (m_parentScene.Permissions.CanEditObject(part.ParentGroup.UUID, remoteClient.AgentId))
1221 { 1347 {
1348 bool physbuild = false;
1349 if (part.ParentGroup.RootPart.PhysActor != null)
1350 {
1351 part.ParentGroup.RootPart.PhysActor.Building = true;
1352 physbuild = true;
1353 }
1354
1222 part.Resize(scale); 1355 part.Resize(scale);
1356
1357 if (physbuild)
1358 part.ParentGroup.RootPart.PhysActor.Building = false;
1223 } 1359 }
1224 } 1360 }
1225 } 1361 }
@@ -1231,7 +1367,17 @@ namespace OpenSim.Region.Framework.Scenes
1231 { 1367 {
1232 if (m_parentScene.Permissions.CanEditObject(group.UUID, remoteClient.AgentId)) 1368 if (m_parentScene.Permissions.CanEditObject(group.UUID, remoteClient.AgentId))
1233 { 1369 {
1370 bool physbuild = false;
1371 if (group.RootPart.PhysActor != null)
1372 {
1373 group.RootPart.PhysActor.Building = true;
1374 physbuild = true;
1375 }
1376
1234 group.GroupResize(scale); 1377 group.GroupResize(scale);
1378
1379 if (physbuild)
1380 group.RootPart.PhysActor.Building = false;
1235 } 1381 }
1236 } 1382 }
1237 } 1383 }
@@ -1359,8 +1505,13 @@ namespace OpenSim.Region.Framework.Scenes
1359 { 1505 {
1360 if (group.IsAttachment || (group.RootPart.Shape.PCode == 9 && group.RootPart.Shape.State != 0)) 1506 if (group.IsAttachment || (group.RootPart.Shape.PCode == 9 && group.RootPart.Shape.State != 0))
1361 { 1507 {
1362 if (m_parentScene.AttachmentsModule != null) 1508 // Set the new attachment point data in the object
1363 m_parentScene.AttachmentsModule.UpdateAttachmentPosition(group, pos); 1509 byte attachmentPoint = group.GetAttachmentPoint();
1510 group.UpdateGroupPosition(pos);
1511 group.IsAttachment = false;
1512 group.AbsolutePosition = group.RootPart.AttachedPos;
1513 group.AttachmentPoint = attachmentPoint;
1514 group.HasGroupChanged = true;
1364 } 1515 }
1365 else 1516 else
1366 { 1517 {
@@ -1408,7 +1559,7 @@ namespace OpenSim.Region.Framework.Scenes
1408 /// <param name="SetPhantom"></param> 1559 /// <param name="SetPhantom"></param>
1409 /// <param name="remoteClient"></param> 1560 /// <param name="remoteClient"></param>
1410 protected internal void UpdatePrimFlags( 1561 protected internal void UpdatePrimFlags(
1411 uint localID, bool UsePhysics, bool SetTemporary, bool SetPhantom, IClientAPI remoteClient) 1562 uint localID, bool UsePhysics, bool SetTemporary, bool SetPhantom, ExtraPhysicsData PhysData, IClientAPI remoteClient)
1412 { 1563 {
1413 SceneObjectGroup group = GetGroupByPrim(localID); 1564 SceneObjectGroup group = GetGroupByPrim(localID);
1414 if (group != null) 1565 if (group != null)
@@ -1416,7 +1567,28 @@ namespace OpenSim.Region.Framework.Scenes
1416 if (m_parentScene.Permissions.CanEditObject(group.UUID, remoteClient.AgentId)) 1567 if (m_parentScene.Permissions.CanEditObject(group.UUID, remoteClient.AgentId))
1417 { 1568 {
1418 // VolumeDetect can't be set via UI and will always be off when a change is made there 1569 // VolumeDetect can't be set via UI and will always be off when a change is made there
1419 group.UpdatePrimFlags(localID, UsePhysics, SetTemporary, SetPhantom, false); 1570 // now only change volume dtc if phantom off
1571
1572 if (PhysData.PhysShapeType == PhysShapeType.invalid) // check for extraPhysics data
1573 {
1574 bool vdtc;
1575 if (SetPhantom) // if phantom keep volumedtc
1576 vdtc = group.RootPart.VolumeDetectActive;
1577 else // else turn it off
1578 vdtc = false;
1579
1580 group.UpdatePrimFlags(localID, UsePhysics, SetTemporary, SetPhantom, vdtc);
1581 }
1582 else
1583 {
1584 SceneObjectPart part = GetSceneObjectPart(localID);
1585 if (part != null)
1586 {
1587 part.UpdateExtraPhysics(PhysData);
1588 if (part.UpdatePhysRequired)
1589 remoteClient.SendPartPhysicsProprieties(part);
1590 }
1591 }
1420 } 1592 }
1421 } 1593 }
1422 } 1594 }
@@ -1560,6 +1732,7 @@ namespace OpenSim.Region.Framework.Scenes
1560 { 1732 {
1561 part.Material = Convert.ToByte(material); 1733 part.Material = Convert.ToByte(material);
1562 group.HasGroupChanged = true; 1734 group.HasGroupChanged = true;
1735 remoteClient.SendPartPhysicsProprieties(part);
1563 } 1736 }
1564 } 1737 }
1565 } 1738 }
@@ -1624,6 +1797,12 @@ namespace OpenSim.Region.Framework.Scenes
1624 /// <param name="childPrims"></param> 1797 /// <param name="childPrims"></param>
1625 protected internal void LinkObjects(SceneObjectPart root, List<SceneObjectPart> children) 1798 protected internal void LinkObjects(SceneObjectPart root, List<SceneObjectPart> children)
1626 { 1799 {
1800 if (root.KeyframeMotion != null)
1801 {
1802 root.KeyframeMotion.Stop();
1803 root.KeyframeMotion = null;
1804 }
1805
1627 SceneObjectGroup parentGroup = root.ParentGroup; 1806 SceneObjectGroup parentGroup = root.ParentGroup;
1628 if (parentGroup == null) return; 1807 if (parentGroup == null) return;
1629 1808
@@ -1632,8 +1811,10 @@ namespace OpenSim.Region.Framework.Scenes
1632 return; 1811 return;
1633 1812
1634 Monitor.Enter(m_updateLock); 1813 Monitor.Enter(m_updateLock);
1814
1635 try 1815 try
1636 { 1816 {
1817
1637 List<SceneObjectGroup> childGroups = new List<SceneObjectGroup>(); 1818 List<SceneObjectGroup> childGroups = new List<SceneObjectGroup>();
1638 1819
1639 // We do this in reverse to get the link order of the prims correct 1820 // We do this in reverse to get the link order of the prims correct
@@ -1648,9 +1829,13 @@ namespace OpenSim.Region.Framework.Scenes
1648 // Make sure no child prim is set for sale 1829 // Make sure no child prim is set for sale
1649 // So that, on delink, no prims are unwittingly 1830 // So that, on delink, no prims are unwittingly
1650 // left for sale and sold off 1831 // left for sale and sold off
1651 child.RootPart.ObjectSaleType = 0; 1832
1652 child.RootPart.SalePrice = 10; 1833 if (child != null)
1653 childGroups.Add(child); 1834 {
1835 child.RootPart.ObjectSaleType = 0;
1836 child.RootPart.SalePrice = 10;
1837 childGroups.Add(child);
1838 }
1654 } 1839 }
1655 1840
1656 foreach (SceneObjectGroup child in childGroups) 1841 foreach (SceneObjectGroup child in childGroups)
@@ -1679,6 +1864,16 @@ namespace OpenSim.Region.Framework.Scenes
1679 } 1864 }
1680 finally 1865 finally
1681 { 1866 {
1867 lock (SceneObjectGroupsByLocalPartID)
1868 {
1869 foreach (SceneObjectPart part in parentGroup.Parts)
1870 SceneObjectGroupsByLocalPartID[part.LocalId] = parentGroup;
1871 }
1872
1873 parentGroup.AdjustChildPrimPermissions();
1874 parentGroup.HasGroupChanged = true;
1875 parentGroup.ProcessBackup(m_parentScene.SimulationDataService, true);
1876 parentGroup.ScheduleGroupForFullUpdate();
1682 Monitor.Exit(m_updateLock); 1877 Monitor.Exit(m_updateLock);
1683 } 1878 }
1684 } 1879 }
@@ -1701,6 +1896,11 @@ namespace OpenSim.Region.Framework.Scenes
1701 { 1896 {
1702 if (part != null) 1897 if (part != null)
1703 { 1898 {
1899 if (part.KeyframeMotion != null)
1900 {
1901 part.KeyframeMotion.Stop();
1902 part.KeyframeMotion = null;
1903 }
1704 if (part.ParentGroup.PrimCount != 1) // Skip single 1904 if (part.ParentGroup.PrimCount != 1) // Skip single
1705 { 1905 {
1706 if (part.LinkNum < 2) // Root 1906 if (part.LinkNum < 2) // Root
@@ -1715,21 +1915,23 @@ namespace OpenSim.Region.Framework.Scenes
1715 1915
1716 SceneObjectGroup group = part.ParentGroup; 1916 SceneObjectGroup group = part.ParentGroup;
1717 if (!affectedGroups.Contains(group)) 1917 if (!affectedGroups.Contains(group))
1918 {
1718 affectedGroups.Add(group); 1919 affectedGroups.Add(group);
1920 }
1719 } 1921 }
1720 } 1922 }
1721 } 1923 }
1722 1924
1723 foreach (SceneObjectPart child in childParts) 1925 if (childParts.Count > 0)
1724 { 1926 {
1725 // Unlink all child parts from their groups 1927 foreach (SceneObjectPart child in childParts)
1726 // 1928 {
1727 child.ParentGroup.DelinkFromGroup(child, true); 1929 // Unlink all child parts from their groups
1728 1930 //
1729 // These are not in affected groups and will not be 1931 child.ParentGroup.DelinkFromGroup(child, true);
1730 // handled further. Do the honors here. 1932 child.ParentGroup.HasGroupChanged = true;
1731 child.ParentGroup.HasGroupChanged = true; 1933 child.ParentGroup.ScheduleGroupForFullUpdate();
1732 child.ParentGroup.ScheduleGroupForFullUpdate(); 1934 }
1733 } 1935 }
1734 1936
1735 foreach (SceneObjectPart root in rootParts) 1937 foreach (SceneObjectPart root in rootParts)
@@ -1743,52 +1945,61 @@ namespace OpenSim.Region.Framework.Scenes
1743 List<SceneObjectPart> newSet = new List<SceneObjectPart>(group.Parts); 1945 List<SceneObjectPart> newSet = new List<SceneObjectPart>(group.Parts);
1744 int numChildren = newSet.Count; 1946 int numChildren = newSet.Count;
1745 1947
1948 if (numChildren == 1)
1949 break;
1950
1746 // If there are prims left in a link set, but the root is 1951 // If there are prims left in a link set, but the root is
1747 // slated for unlink, we need to do this 1952 // slated for unlink, we need to do this
1953 // Unlink the remaining set
1748 // 1954 //
1749 if (numChildren != 1) 1955 bool sendEventsToRemainder = true;
1750 { 1956 if (numChildren > 1)
1751 // Unlink the remaining set 1957 sendEventsToRemainder = false;
1752 //
1753 bool sendEventsToRemainder = true;
1754 if (numChildren > 1)
1755 sendEventsToRemainder = false;
1756 1958
1757 foreach (SceneObjectPart p in newSet) 1959 foreach (SceneObjectPart p in newSet)
1960 {
1961 if (p != group.RootPart)
1758 { 1962 {
1759 if (p != group.RootPart) 1963 group.DelinkFromGroup(p, sendEventsToRemainder);
1760 group.DelinkFromGroup(p, sendEventsToRemainder); 1964 if (numChildren > 2)
1965 {
1966 }
1967 else
1968 {
1969 p.ParentGroup.HasGroupChanged = true;
1970 p.ParentGroup.ScheduleGroupForFullUpdate();
1971 }
1761 } 1972 }
1973 }
1974
1975 // If there is more than one prim remaining, we
1976 // need to re-link
1977 //
1978 if (numChildren > 2)
1979 {
1980 // Remove old root
1981 //
1982 if (newSet.Contains(root))
1983 newSet.Remove(root);
1762 1984
1763 // If there is more than one prim remaining, we 1985 // Preserve link ordering
1764 // need to re-link
1765 // 1986 //
1766 if (numChildren > 2) 1987 newSet.Sort(delegate (SceneObjectPart a, SceneObjectPart b)
1767 { 1988 {
1768 // Remove old root 1989 return a.LinkNum.CompareTo(b.LinkNum);
1769 // 1990 });
1770 if (newSet.Contains(root))
1771 newSet.Remove(root);
1772
1773 // Preserve link ordering
1774 //
1775 newSet.Sort(delegate (SceneObjectPart a, SceneObjectPart b)
1776 {
1777 return a.LinkNum.CompareTo(b.LinkNum);
1778 });
1779 1991
1780 // Determine new root 1992 // Determine new root
1781 // 1993 //
1782 SceneObjectPart newRoot = newSet[0]; 1994 SceneObjectPart newRoot = newSet[0];
1783 newSet.RemoveAt(0); 1995 newSet.RemoveAt(0);
1784 1996
1785 foreach (SceneObjectPart newChild in newSet) 1997 foreach (SceneObjectPart newChild in newSet)
1786 newChild.ClearUpdateSchedule(); 1998 newChild.ClearUpdateSchedule();
1787 1999
1788 LinkObjects(newRoot, newSet); 2000 LinkObjects(newRoot, newSet);
1789 if (!affectedGroups.Contains(newRoot.ParentGroup)) 2001 if (!affectedGroups.Contains(newRoot.ParentGroup))
1790 affectedGroups.Add(newRoot.ParentGroup); 2002 affectedGroups.Add(newRoot.ParentGroup);
1791 }
1792 } 2003 }
1793 } 2004 }
1794 2005
@@ -1796,6 +2007,12 @@ namespace OpenSim.Region.Framework.Scenes
1796 // 2007 //
1797 foreach (SceneObjectGroup g in affectedGroups) 2008 foreach (SceneObjectGroup g in affectedGroups)
1798 { 2009 {
2010 // Child prims that have been unlinked and deleted will
2011 // return unless the root is deleted. This will remove them
2012 // from the database. They will be rewritten immediately,
2013 // minus the rows for the unlinked child prims.
2014 g.AdjustChildPrimPermissions();
2015 m_parentScene.SimulationDataService.RemoveObject(g.UUID, m_parentScene.RegionInfo.RegionID);
1799 g.TriggerScriptChangedEvent(Changed.LINK); 2016 g.TriggerScriptChangedEvent(Changed.LINK);
1800 g.HasGroupChanged = true; // Persist 2017 g.HasGroupChanged = true; // Persist
1801 g.ScheduleGroupForFullUpdate(); 2018 g.ScheduleGroupForFullUpdate();
@@ -1869,108 +2086,96 @@ namespace OpenSim.Region.Framework.Scenes
1869 /// <param name="GroupID"></param> 2086 /// <param name="GroupID"></param>
1870 /// <param name="rot"></param> 2087 /// <param name="rot"></param>
1871 /// <returns>null if duplication fails, otherwise the duplicated object</returns> 2088 /// <returns>null if duplication fails, otherwise the duplicated object</returns>
1872 public SceneObjectGroup DuplicateObject( 2089 /// <summary>
1873 uint originalPrimID, Vector3 offset, uint flags, UUID AgentID, UUID GroupID, Quaternion rot) 2090 public SceneObjectGroup DuplicateObject(uint originalPrimID, Vector3 offset, uint flags, UUID AgentID, UUID GroupID, Quaternion rot)
1874 { 2091 {
1875 Monitor.Enter(m_updateLock); 2092// m_log.DebugFormat(
2093// "[SCENE]: Duplication of object {0} at offset {1} requested by agent {2}",
2094// originalPrimID, offset, AgentID);
1876 2095
1877 try 2096 SceneObjectGroup original = GetGroupByPrim(originalPrimID);
2097 if (original != null)
1878 { 2098 {
1879 // m_log.DebugFormat( 2099 if (m_parentScene.Permissions.CanDuplicateObject(
1880 // "[SCENE]: Duplication of object {0} at offset {1} requested by agent {2}", 2100 original.PrimCount, original.UUID, AgentID, original.AbsolutePosition))
1881 // originalPrimID, offset, AgentID);
1882
1883 SceneObjectGroup original = GetGroupByPrim(originalPrimID);
1884 if (original == null)
1885 { 2101 {
1886 m_log.WarnFormat( 2102 SceneObjectGroup copy = original.Copy(true);
1887 "[SCENEGRAPH]: Attempt to duplicate nonexistant prim id {0} by {1}", originalPrimID, AgentID); 2103 copy.AbsolutePosition = copy.AbsolutePosition + offset;
1888 2104
1889 return null; 2105 if (original.OwnerID != AgentID)
1890 } 2106 {
2107 copy.SetOwnerId(AgentID);
2108 copy.SetRootPartOwner(copy.RootPart, AgentID, GroupID);
1891 2109
1892 if (!m_parentScene.Permissions.CanDuplicateObject( 2110 SceneObjectPart[] partList = copy.Parts;
1893 original.PrimCount, original.UUID, AgentID, original.AbsolutePosition))
1894 return null;
1895 2111
1896 SceneObjectGroup copy = original.Copy(true); 2112 if (m_parentScene.Permissions.PropagatePermissions())
1897 copy.AbsolutePosition = copy.AbsolutePosition + offset; 2113 {
2114 foreach (SceneObjectPart child in partList)
2115 {
2116 child.Inventory.ChangeInventoryOwner(AgentID);
2117 child.TriggerScriptChangedEvent(Changed.OWNER);
2118 child.ApplyNextOwnerPermissions();
2119 }
2120 }
2121 }
1898 2122
1899 if (original.OwnerID != AgentID) 2123 // FIXME: This section needs to be refactored so that it just calls AddSceneObject()
1900 { 2124 Entities.Add(copy);
1901 copy.SetOwnerId(AgentID);
1902 copy.SetRootPartOwner(copy.RootPart, AgentID, GroupID);
1903 2125
1904 SceneObjectPart[] partList = copy.Parts; 2126 lock (SceneObjectGroupsByFullID)
2127 SceneObjectGroupsByFullID[copy.UUID] = copy;
1905 2128
1906 if (m_parentScene.Permissions.PropagatePermissions()) 2129 SceneObjectPart[] children = copy.Parts;
2130
2131 lock (SceneObjectGroupsByFullPartID)
1907 { 2132 {
1908 foreach (SceneObjectPart child in partList) 2133 SceneObjectGroupsByFullPartID[copy.UUID] = copy;
1909 { 2134 foreach (SceneObjectPart part in children)
1910 child.Inventory.ChangeInventoryOwner(AgentID); 2135 SceneObjectGroupsByFullPartID[part.UUID] = copy;
1911 child.TriggerScriptChangedEvent(Changed.OWNER);
1912 child.ApplyNextOwnerPermissions();
1913 }
1914 } 2136 }
1915 2137
1916 copy.RootPart.ObjectSaleType = 0; 2138 lock (SceneObjectGroupsByLocalPartID)
1917 copy.RootPart.SalePrice = 10; 2139 {
1918 } 2140 SceneObjectGroupsByLocalPartID[copy.LocalId] = copy;
2141 foreach (SceneObjectPart part in children)
2142 SceneObjectGroupsByLocalPartID[part.LocalId] = copy;
2143 }
2144 // PROBABLE END OF FIXME
1919 2145
1920 // FIXME: This section needs to be refactored so that it just calls AddSceneObject() 2146 // Since we copy from a source group that is in selected
1921 Entities.Add(copy); 2147 // state, but the copy is shown deselected in the viewer,
1922 2148 // We need to clear the selection flag here, else that
1923 lock (SceneObjectGroupsByFullID) 2149 // prim never gets persisted at all. The client doesn't
1924 SceneObjectGroupsByFullID[copy.UUID] = copy; 2150 // think it's selected, so it will never send a deselect...
1925 2151 copy.IsSelected = false;
1926 SceneObjectPart[] children = copy.Parts; 2152
1927 2153 m_numPrim += copy.Parts.Length;
1928 lock (SceneObjectGroupsByFullPartID) 2154
1929 { 2155 if (rot != Quaternion.Identity)
1930 SceneObjectGroupsByFullPartID[copy.UUID] = copy; 2156 {
1931 foreach (SceneObjectPart part in children) 2157 copy.UpdateGroupRotationR(rot);
1932 SceneObjectGroupsByFullPartID[part.UUID] = copy; 2158 }
1933 }
1934
1935 lock (SceneObjectGroupsByLocalPartID)
1936 {
1937 SceneObjectGroupsByLocalPartID[copy.LocalId] = copy;
1938 foreach (SceneObjectPart part in children)
1939 SceneObjectGroupsByLocalPartID[part.LocalId] = copy;
1940 }
1941 // PROBABLE END OF FIXME
1942
1943 // Since we copy from a source group that is in selected
1944 // state, but the copy is shown deselected in the viewer,
1945 // We need to clear the selection flag here, else that
1946 // prim never gets persisted at all. The client doesn't
1947 // think it's selected, so it will never send a deselect...
1948 copy.IsSelected = false;
1949
1950 m_numPrim += copy.Parts.Length;
1951
1952 if (rot != Quaternion.Identity)
1953 {
1954 copy.UpdateGroupRotationR(rot);
1955 }
1956 2159
1957 copy.CreateScriptInstances(0, false, m_parentScene.DefaultScriptEngine, 1); 2160 copy.CreateScriptInstances(0, false, m_parentScene.DefaultScriptEngine, 1);
1958 copy.HasGroupChanged = true; 2161 copy.HasGroupChanged = true;
1959 copy.ScheduleGroupForFullUpdate(); 2162 copy.ScheduleGroupForFullUpdate();
1960 copy.ResumeScripts(); 2163 copy.ResumeScripts();
1961 2164
1962 // required for physics to update it's position 2165 // required for physics to update it's position
1963 copy.AbsolutePosition = copy.AbsolutePosition; 2166 copy.AbsolutePosition = copy.AbsolutePosition;
1964 2167
1965 return copy; 2168 return copy;
2169 }
1966 } 2170 }
1967 finally 2171 else
1968 { 2172 {
1969 Monitor.Exit(m_updateLock); 2173 m_log.WarnFormat("[SCENE]: Attempted to duplicate nonexistant prim id {0}", GroupID);
1970 } 2174 }
2175
2176 return null;
1971 } 2177 }
1972 2178
1973 /// <summary>
1974 /// Calculates the distance between two Vector3s 2179 /// Calculates the distance between two Vector3s
1975 /// </summary> 2180 /// </summary>
1976 /// <param name="v1"></param> 2181 /// <param name="v1"></param>
diff --git a/OpenSim/Region/Framework/Scenes/SceneManager.cs b/OpenSim/Region/Framework/Scenes/SceneManager.cs
index 1e2e973..0e0b6c3 100644
--- a/OpenSim/Region/Framework/Scenes/SceneManager.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneManager.cs
@@ -99,11 +99,12 @@ namespace OpenSim.Region.Framework.Scenes
99 } 99 }
100 } 100 }
101 101
102 private readonly List<Scene> m_localScenes = new List<Scene>(); 102 private readonly DoubleDictionary<UUID, string, Scene> m_localScenes = new DoubleDictionary<UUID, string, Scene>();
103 private Scene m_currentScene = null;
103 104
104 public List<Scene> Scenes 105 public List<Scene> Scenes
105 { 106 {
106 get { return new List<Scene>(m_localScenes); } 107 get { return new List<Scene>(m_localScenes.FindAll(delegate(Scene s) { return true; })); }
107 } 108 }
108 109
109 /// <summary> 110 /// <summary>
@@ -120,13 +121,10 @@ namespace OpenSim.Region.Framework.Scenes
120 { 121 {
121 if (CurrentScene == null) 122 if (CurrentScene == null)
122 { 123 {
123 lock (m_localScenes) 124 List<Scene> sceneList = Scenes;
124 { 125 if (sceneList.Count == 0)
125 if (m_localScenes.Count > 0) 126 return null;
126 return m_localScenes[0]; 127 return sceneList[0];
127 else
128 return null;
129 }
130 } 128 }
131 else 129 else
132 { 130 {
@@ -138,41 +136,35 @@ namespace OpenSim.Region.Framework.Scenes
138 public SceneManager() 136 public SceneManager()
139 { 137 {
140 m_instance = this; 138 m_instance = this;
141 m_localScenes = new List<Scene>(); 139 m_localScenes = new DoubleDictionary<UUID, string, Scene>();
142 } 140 }
143 141
144 public void Close() 142 public void Close()
145 { 143 {
144 List<Scene> localScenes = null;
145
146 lock (m_localScenes) 146 lock (m_localScenes)
147 { 147 {
148 for (int i = 0; i < m_localScenes.Count; i++) 148 localScenes = Scenes;
149 { 149 }
150 m_localScenes[i].Close(); 150
151 } 151 for (int i = 0; i < localScenes.Count; i++)
152 {
153 localScenes[i].Close();
152 } 154 }
153 } 155 }
154 156
155 public void Close(Scene cscene) 157 public void Close(Scene cscene)
156 { 158 {
157 lock (m_localScenes) 159 if (!m_localScenes.ContainsKey(cscene.RegionInfo.RegionID))
158 { 160 return;
159 if (m_localScenes.Contains(cscene)) 161 cscene.Close();
160 {
161 for (int i = 0; i < m_localScenes.Count; i++)
162 {
163 if (m_localScenes[i].Equals(cscene))
164 {
165 m_localScenes[i].Close();
166 }
167 }
168 }
169 }
170 } 162 }
171 163
172 public void Add(Scene scene) 164 public void Add(Scene scene)
173 { 165 {
174 lock (m_localScenes) 166 lock (m_localScenes)
175 m_localScenes.Add(scene); 167 m_localScenes.Add(scene.RegionInfo.RegionID, scene.RegionInfo.RegionName, scene);
176 168
177 scene.OnRestart += HandleRestart; 169 scene.OnRestart += HandleRestart;
178 scene.EventManager.OnRegionReadyStatusChange += HandleRegionReadyStatusChange; 170 scene.EventManager.OnRegionReadyStatusChange += HandleRegionReadyStatusChange;
@@ -184,15 +176,8 @@ namespace OpenSim.Region.Framework.Scenes
184 176
185 lock (m_localScenes) 177 lock (m_localScenes)
186 { 178 {
187 for (int i = 0; i < m_localScenes.Count; i++) 179 m_localScenes.TryGetValue(rdata.RegionID, out restartedScene);
188 { 180 m_localScenes.Remove(rdata.RegionID);
189 if (rdata.RegionName == m_localScenes[i].RegionInfo.RegionName)
190 {
191 restartedScene = m_localScenes[i];
192 m_localScenes.RemoveAt(i);
193 break;
194 }
195 }
196 } 181 }
197 182
198 // If the currently selected scene has been restarted, then we can't reselect here since we the scene 183 // If the currently selected scene has been restarted, then we can't reselect here since we the scene
@@ -207,39 +192,36 @@ namespace OpenSim.Region.Framework.Scenes
207 private void HandleRegionReadyStatusChange(IScene scene) 192 private void HandleRegionReadyStatusChange(IScene scene)
208 { 193 {
209 lock (m_localScenes) 194 lock (m_localScenes)
210 AllRegionsReady = m_localScenes.TrueForAll(s => s.Ready); 195 AllRegionsReady = m_localScenes.FindAll(s => !s.Ready).Count == 0;
211 } 196 }
212 197
213 public void SendSimOnlineNotification(ulong regionHandle) 198 public void SendSimOnlineNotification(ulong regionHandle)
214 { 199 {
215 RegionInfo Result = null; 200 RegionInfo Result = null;
216 201
217 lock (m_localScenes) 202 Scene s = m_localScenes.FindValue(delegate(Scene x)
218 {
219 for (int i = 0; i < m_localScenes.Count; i++)
220 {
221 if (m_localScenes[i].RegionInfo.RegionHandle == regionHandle)
222 { 203 {
223 // Inform other regions to tell their avatar about me 204 if (x.RegionInfo.RegionHandle == regionHandle)
224 Result = m_localScenes[i].RegionInfo; 205 return true;
225 } 206 return false;
226 } 207 });
208
209 if (s != null)
210 {
211 List<Scene> sceneList = Scenes;
227 212
228 if (Result != null) 213 for (int i = 0; i < sceneList.Count; i++)
229 { 214 {
230 for (int i = 0; i < m_localScenes.Count; i++) 215 if (sceneList[i]!= s)
231 { 216 {
232 if (m_localScenes[i].RegionInfo.RegionHandle != regionHandle) 217 // Inform other regions to tell their avatar about me
233 { 218 //sceneList[i].OtherRegionUp(Result);
234 // Inform other regions to tell their avatar about me
235 //m_localScenes[i].OtherRegionUp(Result);
236 }
237 } 219 }
238 } 220 }
239 else 221 }
240 { 222 else
241 m_log.Error("[REGION]: Unable to notify Other regions of this Region coming up"); 223 {
242 } 224 m_log.Error("[REGION]: Unable to notify Other regions of this Region coming up");
243 } 225 }
244 } 226 }
245 227
@@ -343,8 +325,8 @@ namespace OpenSim.Region.Framework.Scenes
343 { 325 {
344 if (CurrentScene == null) 326 if (CurrentScene == null)
345 { 327 {
346 lock (m_localScenes) 328 List<Scene> sceneList = Scenes;
347 m_localScenes.ForEach(func); 329 sceneList.ForEach(func);
348 } 330 }
349 else 331 else
350 { 332 {
@@ -373,16 +355,12 @@ namespace OpenSim.Region.Framework.Scenes
373 } 355 }
374 else 356 else
375 { 357 {
376 lock (m_localScenes) 358 Scene s;
359
360 if (m_localScenes.TryGetValue(regionName, out s))
377 { 361 {
378 foreach (Scene scene in m_localScenes) 362 m_currentScene = s;
379 { 363 return true;
380 if (String.Compare(scene.RegionInfo.RegionName, regionName, true) == 0)
381 {
382 CurrentScene = scene;
383 return true;
384 }
385 }
386 } 364 }
387 365
388 return false; 366 return false;
@@ -391,18 +369,14 @@ namespace OpenSim.Region.Framework.Scenes
391 369
392 public bool TrySetCurrentScene(UUID regionID) 370 public bool TrySetCurrentScene(UUID regionID)
393 { 371 {
394 m_log.Debug("Searching for Region: '" + regionID + "'"); 372// m_log.Debug("Searching for Region: '" + regionID + "'");
395 373
396 lock (m_localScenes) 374 Scene s;
375
376 if (m_localScenes.TryGetValue(regionID, out s))
397 { 377 {
398 foreach (Scene scene in m_localScenes) 378 m_currentScene = s;
399 { 379 return true;
400 if (scene.RegionInfo.RegionID == regionID)
401 {
402 CurrentScene = scene;
403 return true;
404 }
405 }
406 } 380 }
407 381
408 return false; 382 return false;
@@ -410,52 +384,24 @@ namespace OpenSim.Region.Framework.Scenes
410 384
411 public bool TryGetScene(string regionName, out Scene scene) 385 public bool TryGetScene(string regionName, out Scene scene)
412 { 386 {
413 lock (m_localScenes) 387 return m_localScenes.TryGetValue(regionName, out scene);
414 {
415 foreach (Scene mscene in m_localScenes)
416 {
417 if (String.Compare(mscene.RegionInfo.RegionName, regionName, true) == 0)
418 {
419 scene = mscene;
420 return true;
421 }
422 }
423 }
424
425 scene = null;
426 return false;
427 } 388 }
428 389
429 public bool TryGetScene(UUID regionID, out Scene scene) 390 public bool TryGetScene(UUID regionID, out Scene scene)
430 { 391 {
431 lock (m_localScenes) 392 return m_localScenes.TryGetValue(regionID, out scene);
432 {
433 foreach (Scene mscene in m_localScenes)
434 {
435 if (mscene.RegionInfo.RegionID == regionID)
436 {
437 scene = mscene;
438 return true;
439 }
440 }
441 }
442
443 scene = null;
444 return false;
445 } 393 }
446 394
447 public bool TryGetScene(uint locX, uint locY, out Scene scene) 395 public bool TryGetScene(uint locX, uint locY, out Scene scene)
448 { 396 {
449 lock (m_localScenes) 397 List<Scene> sceneList = Scenes;
398 foreach (Scene mscene in sceneList)
450 { 399 {
451 foreach (Scene mscene in m_localScenes) 400 if (mscene.RegionInfo.RegionLocX == locX &&
401 mscene.RegionInfo.RegionLocY == locY)
452 { 402 {
453 if (mscene.RegionInfo.RegionLocX == locX && 403 scene = mscene;
454 mscene.RegionInfo.RegionLocY == locY) 404 return true;
455 {
456 scene = mscene;
457 return true;
458 }
459 } 405 }
460 } 406 }
461 407
@@ -465,16 +411,14 @@ namespace OpenSim.Region.Framework.Scenes
465 411
466 public bool TryGetScene(IPEndPoint ipEndPoint, out Scene scene) 412 public bool TryGetScene(IPEndPoint ipEndPoint, out Scene scene)
467 { 413 {
468 lock (m_localScenes) 414 List<Scene> sceneList = Scenes;
415 foreach (Scene mscene in sceneList)
469 { 416 {
470 foreach (Scene mscene in m_localScenes) 417 if ((mscene.RegionInfo.InternalEndPoint.Equals(ipEndPoint.Address)) &&
418 (mscene.RegionInfo.InternalEndPoint.Port == ipEndPoint.Port))
471 { 419 {
472 if ((mscene.RegionInfo.InternalEndPoint.Equals(ipEndPoint.Address)) && 420 scene = mscene;
473 (mscene.RegionInfo.InternalEndPoint.Port == ipEndPoint.Port)) 421 return true;
474 {
475 scene = mscene;
476 return true;
477 }
478 } 422 }
479 } 423 }
480 424
@@ -539,15 +483,10 @@ namespace OpenSim.Region.Framework.Scenes
539 483
540 public RegionInfo GetRegionInfo(UUID regionID) 484 public RegionInfo GetRegionInfo(UUID regionID)
541 { 485 {
542 lock (m_localScenes) 486 Scene s;
487 if (m_localScenes.TryGetValue(regionID, out s))
543 { 488 {
544 foreach (Scene scene in m_localScenes) 489 return s.RegionInfo;
545 {
546 if (scene.RegionInfo.RegionID == regionID)
547 {
548 return scene.RegionInfo;
549 }
550 }
551 } 490 }
552 491
553 return null; 492 return null;
@@ -565,14 +504,12 @@ namespace OpenSim.Region.Framework.Scenes
565 504
566 public bool TryGetScenePresence(UUID avatarId, out ScenePresence avatar) 505 public bool TryGetScenePresence(UUID avatarId, out ScenePresence avatar)
567 { 506 {
568 lock (m_localScenes) 507 List<Scene> sceneList = Scenes;
508 foreach (Scene scene in sceneList)
569 { 509 {
570 foreach (Scene scene in m_localScenes) 510 if (scene.TryGetScenePresence(avatarId, out avatar))
571 { 511 {
572 if (scene.TryGetScenePresence(avatarId, out avatar)) 512 return true;
573 {
574 return true;
575 }
576 } 513 }
577 } 514 }
578 515
@@ -582,15 +519,13 @@ namespace OpenSim.Region.Framework.Scenes
582 519
583 public bool TryGetRootScenePresence(UUID avatarId, out ScenePresence avatar) 520 public bool TryGetRootScenePresence(UUID avatarId, out ScenePresence avatar)
584 { 521 {
585 lock (m_localScenes) 522 List<Scene> sceneList = Scenes;
523 foreach (Scene scene in sceneList)
586 { 524 {
587 foreach (Scene scene in m_localScenes) 525 avatar = scene.GetScenePresence(avatarId);
588 {
589 avatar = scene.GetScenePresence(avatarId);
590 526
591 if (avatar != null && !avatar.IsChildAgent) 527 if (avatar != null && !avatar.IsChildAgent)
592 return true; 528 return true;
593 }
594 } 529 }
595 530
596 avatar = null; 531 avatar = null;
@@ -600,21 +535,19 @@ namespace OpenSim.Region.Framework.Scenes
600 public void CloseScene(Scene scene) 535 public void CloseScene(Scene scene)
601 { 536 {
602 lock (m_localScenes) 537 lock (m_localScenes)
603 m_localScenes.Remove(scene); 538 m_localScenes.Remove(scene.RegionInfo.RegionID);
604 539
605 scene.Close(); 540 scene.Close();
606 } 541 }
607 542
608 public bool TryGetAvatarByName(string avatarName, out ScenePresence avatar) 543 public bool TryGetAvatarByName(string avatarName, out ScenePresence avatar)
609 { 544 {
610 lock (m_localScenes) 545 List<Scene> sceneList = Scenes;
546 foreach (Scene scene in sceneList)
611 { 547 {
612 foreach (Scene scene in m_localScenes) 548 if (scene.TryGetAvatarByName(avatarName, out avatar))
613 { 549 {
614 if (scene.TryGetAvatarByName(avatarName, out avatar)) 550 return true;
615 {
616 return true;
617 }
618 } 551 }
619 } 552 }
620 553
@@ -624,14 +557,12 @@ namespace OpenSim.Region.Framework.Scenes
624 557
625 public bool TryGetRootScenePresenceByName(string firstName, string lastName, out ScenePresence sp) 558 public bool TryGetRootScenePresenceByName(string firstName, string lastName, out ScenePresence sp)
626 { 559 {
627 lock (m_localScenes) 560 List<Scene> sceneList = Scenes;
561 foreach (Scene scene in sceneList)
628 { 562 {
629 foreach (Scene scene in m_localScenes) 563 sp = scene.GetScenePresence(firstName, lastName);
630 { 564 if (sp != null && !sp.IsChildAgent)
631 sp = scene.GetScenePresence(firstName, lastName); 565 return true;
632 if (sp != null && !sp.IsChildAgent)
633 return true;
634 }
635 } 566 }
636 567
637 sp = null; 568 sp = null;
@@ -640,8 +571,8 @@ namespace OpenSim.Region.Framework.Scenes
640 571
641 public void ForEachScene(Action<Scene> action) 572 public void ForEachScene(Action<Scene> action)
642 { 573 {
643 lock (m_localScenes) 574 List<Scene> sceneList = Scenes;
644 m_localScenes.ForEach(action); 575 sceneList.ForEach(action);
645 } 576 }
646 } 577 }
647} 578}
diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectGroup.Inventory.cs b/OpenSim/Region/Framework/Scenes/SceneObjectGroup.Inventory.cs
index ddf5da0..26524fb 100644
--- a/OpenSim/Region/Framework/Scenes/SceneObjectGroup.Inventory.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneObjectGroup.Inventory.cs
@@ -81,10 +81,6 @@ namespace OpenSim.Region.Framework.Scenes
81 /// <summary> 81 /// <summary>
82 /// Stop and remove the scripts contained in all the prims in this group 82 /// Stop and remove the scripts contained in all the prims in this group
83 /// </summary> 83 /// </summary>
84 /// <param name="sceneObjectBeingDeleted">
85 /// Should be true if these scripts are being removed because the scene
86 /// object is being deleted. This will prevent spurious updates to the client.
87 /// </param>
88 public void RemoveScriptInstances(bool sceneObjectBeingDeleted) 84 public void RemoveScriptInstances(bool sceneObjectBeingDeleted)
89 { 85 {
90 SceneObjectPart[] parts = m_parts.GetArray(); 86 SceneObjectPart[] parts = m_parts.GetArray();
@@ -247,6 +243,11 @@ namespace OpenSim.Region.Framework.Scenes
247 243
248 public uint GetEffectivePermissions() 244 public uint GetEffectivePermissions()
249 { 245 {
246 return GetEffectivePermissions(false);
247 }
248
249 public uint GetEffectivePermissions(bool useBase)
250 {
250 uint perms=(uint)(PermissionMask.Modify | 251 uint perms=(uint)(PermissionMask.Modify |
251 PermissionMask.Copy | 252 PermissionMask.Copy |
252 PermissionMask.Move | 253 PermissionMask.Move |
@@ -258,7 +259,10 @@ namespace OpenSim.Region.Framework.Scenes
258 for (int i = 0; i < parts.Length; i++) 259 for (int i = 0; i < parts.Length; i++)
259 { 260 {
260 SceneObjectPart part = parts[i]; 261 SceneObjectPart part = parts[i];
261 ownerMask &= part.OwnerMask; 262 if (useBase)
263 ownerMask &= part.BaseMask;
264 else
265 ownerMask &= part.OwnerMask;
262 perms &= part.Inventory.MaskEffectivePermissions(); 266 perms &= part.Inventory.MaskEffectivePermissions();
263 } 267 }
264 268
@@ -400,6 +404,9 @@ namespace OpenSim.Region.Framework.Scenes
400 404
401 public void ResumeScripts() 405 public void ResumeScripts()
402 { 406 {
407 if (m_scene.RegionInfo.RegionSettings.DisableScripts)
408 return;
409
403 SceneObjectPart[] parts = m_parts.GetArray(); 410 SceneObjectPart[] parts = m_parts.GetArray();
404 for (int i = 0; i < parts.Length; i++) 411 for (int i = 0; i < parts.Length; i++)
405 parts[i].Inventory.ResumeScripts(); 412 parts[i].Inventory.ResumeScripts();
diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs b/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs
index 15795e5..dd8541c 100644
--- a/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs
@@ -24,12 +24,13 @@
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */ 26 */
27 27
28using System; 28using System;
29using System.ComponentModel; 29using System.ComponentModel;
30using System.Collections.Generic; 30using System.Collections.Generic;
31using System.Drawing; 31using System.Drawing;
32using System.IO; 32using System.IO;
33using System.Diagnostics;
33using System.Linq; 34using System.Linq;
34using System.Threading; 35using System.Threading;
35using System.Xml; 36using System.Xml;
@@ -43,6 +44,7 @@ using OpenSim.Region.Framework.Scenes.Serialization;
43 44
44namespace OpenSim.Region.Framework.Scenes 45namespace OpenSim.Region.Framework.Scenes
45{ 46{
47
46 [Flags] 48 [Flags]
47 public enum scriptEvents 49 public enum scriptEvents
48 { 50 {
@@ -115,8 +117,12 @@ namespace OpenSim.Region.Framework.Scenes
115 /// since the group's last persistent backup 117 /// since the group's last persistent backup
116 /// </summary> 118 /// </summary>
117 private bool m_hasGroupChanged = false; 119 private bool m_hasGroupChanged = false;
118 private long timeFirstChanged; 120 private long timeFirstChanged = 0;
119 private long timeLastChanged; 121 private long timeLastChanged = 0;
122 private long m_maxPersistTime = 0;
123 private long m_minPersistTime = 0;
124// private Random m_rand;
125 private List<ScenePresence> m_linkedAvatars = new List<ScenePresence>();
120 126
121 /// <summary> 127 /// <summary>
122 /// This indicates whether the object has changed such that it needs to be repersisted to permenant storage 128 /// This indicates whether the object has changed such that it needs to be repersisted to permenant storage
@@ -133,9 +139,44 @@ namespace OpenSim.Region.Framework.Scenes
133 { 139 {
134 if (value) 140 if (value)
135 { 141 {
142
143 if (m_isBackedUp)
144 {
145 m_scene.SceneGraph.FireChangeBackup(this);
146 }
136 timeLastChanged = DateTime.Now.Ticks; 147 timeLastChanged = DateTime.Now.Ticks;
137 if (!m_hasGroupChanged) 148 if (!m_hasGroupChanged)
138 timeFirstChanged = DateTime.Now.Ticks; 149 timeFirstChanged = DateTime.Now.Ticks;
150 if (m_rootPart != null && m_rootPart.UUID != null && m_scene != null)
151 {
152/*
153 if (m_rand == null)
154 {
155 byte[] val = new byte[16];
156 m_rootPart.UUID.ToBytes(val, 0);
157 m_rand = new Random(BitConverter.ToInt32(val, 0));
158 }
159 */
160 if (m_scene.GetRootAgentCount() == 0)
161 {
162 //If the region is empty, this change has been made by an automated process
163 //and thus we delay the persist time by a random amount between 1.5 and 2.5.
164
165// float factor = 1.5f + (float)(m_rand.NextDouble());
166 float factor = 2.0f;
167 m_maxPersistTime = (long)((float)m_scene.m_persistAfter * factor);
168 m_minPersistTime = (long)((float)m_scene.m_dontPersistBefore * factor);
169 }
170 else
171 {
172 //If the region is not empty, we want to obey the minimum and maximum persist times
173 //but add a random factor so we stagger the object persistance a little
174// m_maxPersistTime = (long)((float)m_scene.m_persistAfter * (1.0d - (m_rand.NextDouble() / 5.0d))); //Multiply by 1.0-1.5
175// m_minPersistTime = (long)((float)m_scene.m_dontPersistBefore * (1.0d + (m_rand.NextDouble() / 2.0d))); //Multiply by 0.8-1.0
176 m_maxPersistTime = m_scene.m_persistAfter;
177 m_minPersistTime = m_scene.m_dontPersistBefore;
178 }
179 }
139 } 180 }
140 m_hasGroupChanged = value; 181 m_hasGroupChanged = value;
141 182
@@ -150,7 +191,7 @@ namespace OpenSim.Region.Framework.Scenes
150 /// Has the group changed due to an unlink operation? We record this in order to optimize deletion, since 191 /// Has the group changed due to an unlink operation? We record this in order to optimize deletion, since
151 /// an unlinked group currently has to be persisted to the database before we can perform an unlink operation. 192 /// an unlinked group currently has to be persisted to the database before we can perform an unlink operation.
152 /// </summary> 193 /// </summary>
153 public bool HasGroupChangedDueToDelink { get; private set; } 194 public bool HasGroupChangedDueToDelink { get; set; }
154 195
155 private bool isTimeToPersist() 196 private bool isTimeToPersist()
156 { 197 {
@@ -160,8 +201,19 @@ namespace OpenSim.Region.Framework.Scenes
160 return false; 201 return false;
161 if (m_scene.ShuttingDown) 202 if (m_scene.ShuttingDown)
162 return true; 203 return true;
204
205 if (m_minPersistTime == 0 || m_maxPersistTime == 0)
206 {
207 m_maxPersistTime = m_scene.m_persistAfter;
208 m_minPersistTime = m_scene.m_dontPersistBefore;
209 }
210
163 long currentTime = DateTime.Now.Ticks; 211 long currentTime = DateTime.Now.Ticks;
164 if (currentTime - timeLastChanged > m_scene.m_dontPersistBefore || currentTime - timeFirstChanged > m_scene.m_persistAfter) 212
213 if (timeLastChanged == 0) timeLastChanged = currentTime;
214 if (timeFirstChanged == 0) timeFirstChanged = currentTime;
215
216 if (currentTime - timeLastChanged > m_minPersistTime || currentTime - timeFirstChanged > m_maxPersistTime)
165 return true; 217 return true;
166 return false; 218 return false;
167 } 219 }
@@ -264,11 +316,13 @@ namespace OpenSim.Region.Framework.Scenes
264 get { return RootPart.VolumeDetectActive; } 316 get { return RootPart.VolumeDetectActive; }
265 } 317 }
266 318
267 private Vector3 lastPhysGroupPos;
268 private Quaternion lastPhysGroupRot;
269
270 private bool m_isBackedUp; 319 private bool m_isBackedUp;
271 320
321 public bool IsBackedUp
322 {
323 get { return m_isBackedUp; }
324 }
325
272 protected MapAndArray<UUID, SceneObjectPart> m_parts = new MapAndArray<UUID, SceneObjectPart>(); 326 protected MapAndArray<UUID, SceneObjectPart> m_parts = new MapAndArray<UUID, SceneObjectPart>();
273 327
274 protected ulong m_regionHandle; 328 protected ulong m_regionHandle;
@@ -280,10 +334,10 @@ namespace OpenSim.Region.Framework.Scenes
280 334
281 private bool m_scriptListens_atTarget; 335 private bool m_scriptListens_atTarget;
282 private bool m_scriptListens_notAtTarget; 336 private bool m_scriptListens_notAtTarget;
283
284 private bool m_scriptListens_atRotTarget; 337 private bool m_scriptListens_atRotTarget;
285 private bool m_scriptListens_notAtRotTarget; 338 private bool m_scriptListens_notAtRotTarget;
286 339
340 public bool m_dupeInProgress = false;
287 internal Dictionary<UUID, string> m_savedScriptState; 341 internal Dictionary<UUID, string> m_savedScriptState;
288 342
289 #region Properties 343 #region Properties
@@ -320,6 +374,16 @@ namespace OpenSim.Region.Framework.Scenes
320 get { return m_parts.Count; } 374 get { return m_parts.Count; }
321 } 375 }
322 376
377// protected Quaternion m_rotation = Quaternion.Identity;
378//
379// public virtual Quaternion Rotation
380// {
381// get { return m_rotation; }
382// set {
383// m_rotation = value;
384// }
385// }
386
323 public Quaternion GroupRotation 387 public Quaternion GroupRotation
324 { 388 {
325 get { return m_rootPart.RotationOffset; } 389 get { return m_rootPart.RotationOffset; }
@@ -426,7 +490,15 @@ namespace OpenSim.Region.Framework.Scenes
426 { 490 {
427 return (IsAttachment || (m_rootPart.Shape.PCode == 9 && m_rootPart.Shape.State != 0)); 491 return (IsAttachment || (m_rootPart.Shape.PCode == 9 && m_rootPart.Shape.State != 0));
428 } 492 }
429 493
494
495
496 private struct avtocrossInfo
497 {
498 public ScenePresence av;
499 public uint ParentID;
500 }
501
430 /// <summary> 502 /// <summary>
431 /// The absolute position of this scene object in the scene 503 /// The absolute position of this scene object in the scene
432 /// </summary> 504 /// </summary>
@@ -454,10 +526,129 @@ namespace OpenSim.Region.Framework.Scenes
454 || Scene.TestBorderCross(val, Cardinals.S)) 526 || Scene.TestBorderCross(val, Cardinals.S))
455 && !IsAttachmentCheckFull() && (!Scene.LoadingPrims)) 527 && !IsAttachmentCheckFull() && (!Scene.LoadingPrims))
456 { 528 {
457 m_scene.CrossPrimGroupIntoNewRegion(val, this, true); 529 IEntityTransferModule entityTransfer = m_scene.RequestModuleInterface<IEntityTransferModule>();
530 uint x = 0;
531 uint y = 0;
532 string version = String.Empty;
533 Vector3 newpos = Vector3.Zero;
534 OpenSim.Services.Interfaces.GridRegion destination = null;
535
536 if (m_rootPart.KeyframeMotion != null)
537 m_rootPart.KeyframeMotion.StartCrossingCheck();
538
539 bool canCross = true;
540 foreach (ScenePresence av in m_linkedAvatars)
541 {
542 // We need to cross these agents. First, let's find
543 // out if any of them can't cross for some reason.
544 // We have to deny the crossing entirely if any
545 // of them are banned. Alternatively, we could
546 // unsit banned agents....
547
548
549 // We set the avatar position as being the object
550 // position to get the region to send to
551 if ((destination = entityTransfer.GetDestination(m_scene, av.UUID, val, out x, out y, out version, out newpos)) == null)
552 {
553 canCross = false;
554 break;
555 }
556
557 m_log.DebugFormat("[SCENE OBJECT]: Avatar {0} needs to be crossed to {1}", av.Name, destination.RegionName);
558 }
559
560 if (canCross)
561 {
562 // We unparent the SP quietly so that it won't
563 // be made to stand up
564
565 List<avtocrossInfo> avsToCross = new List<avtocrossInfo>();
566
567 foreach (ScenePresence av in m_linkedAvatars)
568 {
569 avtocrossInfo avinfo = new avtocrossInfo();
570 SceneObjectPart parentPart = m_scene.GetSceneObjectPart(av.ParentID);
571 if (parentPart != null)
572 av.ParentUUID = parentPart.UUID;
573
574 avinfo.av = av;
575 avinfo.ParentID = av.ParentID;
576 avsToCross.Add(avinfo);
577
578 av.ParentID = 0;
579 }
580
581 // m_linkedAvatars.Clear();
582 m_scene.CrossPrimGroupIntoNewRegion(val, this, true);
583
584 // Normalize
585 if (val.X >= Constants.RegionSize)
586 val.X -= Constants.RegionSize;
587 if (val.Y >= Constants.RegionSize)
588 val.Y -= Constants.RegionSize;
589 if (val.X < 0)
590 val.X += Constants.RegionSize;
591 if (val.Y < 0)
592 val.Y += Constants.RegionSize;
593
594 // If it's deleted, crossing was successful
595 if (IsDeleted)
596 {
597 // foreach (ScenePresence av in m_linkedAvatars)
598 foreach (avtocrossInfo avinfo in avsToCross)
599 {
600 ScenePresence av = avinfo.av;
601 if (!av.IsInTransit) // just in case...
602 {
603 m_log.DebugFormat("[SCENE OBJECT]: Crossing avatar {0} to {1}", av.Name, val);
604
605 av.IsInTransit = true;
606
607 CrossAgentToNewRegionDelegate d = entityTransfer.CrossAgentToNewRegionAsync;
608 d.BeginInvoke(av, val, destination, av.Flying, version, CrossAgentToNewRegionCompleted, d);
609 }
610 else
611 m_log.DebugFormat("[SCENE OBJECT]: Crossing avatar alreasy in transit {0} to {1}", av.Name, val);
612 }
613 avsToCross.Clear();
614 return;
615 }
616 else // cross failed, put avas back ??
617 {
618 foreach (avtocrossInfo avinfo in avsToCross)
619 {
620 ScenePresence av = avinfo.av;
621 av.ParentUUID = UUID.Zero;
622 av.ParentID = avinfo.ParentID;
623// m_linkedAvatars.Add(av);
624 }
625 }
626 avsToCross.Clear();
627
628 }
629 else
630 {
631 if (m_rootPart.KeyframeMotion != null)
632 m_rootPart.KeyframeMotion.CrossingFailure();
633
634 if (RootPart.PhysActor != null)
635 {
636 RootPart.PhysActor.CrossingFailure();
637 }
638 }
639 Vector3 oldp = AbsolutePosition;
640 val.X = Util.Clamp<float>(oldp.X, 0.5f, (float)Constants.RegionSize - 0.5f);
641 val.Y = Util.Clamp<float>(oldp.Y, 0.5f, (float)Constants.RegionSize - 0.5f);
642 val.Z = Util.Clamp<float>(oldp.Z, 0.5f, 4096.0f);
458 } 643 }
459 } 644 }
460 645
646/* don't see the need but worse don't see where is restored to false if things stay in
647 foreach (SceneObjectPart part in m_parts.GetArray())
648 {
649 part.IgnoreUndoUpdate = true;
650 }
651 */
461 if (RootPart.GetStatusSandbox()) 652 if (RootPart.GetStatusSandbox())
462 { 653 {
463 if (Util.GetDistanceTo(RootPart.StatusSandboxPos, value) > 10) 654 if (Util.GetDistanceTo(RootPart.StatusSandboxPos, value) > 10)
@@ -475,9 +666,38 @@ namespace OpenSim.Region.Framework.Scenes
475 // Restuff the new GroupPosition into each SOP of the linkset. 666 // Restuff the new GroupPosition into each SOP of the linkset.
476 // This has the affect of resetting and tainting the physics actors. 667 // This has the affect of resetting and tainting the physics actors.
477 SceneObjectPart[] parts = m_parts.GetArray(); 668 SceneObjectPart[] parts = m_parts.GetArray();
478 for (int i = 0; i < parts.Length; i++) 669 bool triggerScriptEvent = m_rootPart.GroupPosition != val;
479 parts[i].GroupPosition = val; 670 if (m_dupeInProgress)
671 triggerScriptEvent = false;
672 foreach (SceneObjectPart part in parts)
673 {
674 part.GroupPosition = val;
675 if (triggerScriptEvent)
676 part.TriggerScriptChangedEvent(Changed.POSITION);
677 }
480 678
679/*
680 This seems not needed and should not be needed:
681 sp absolute position depends on sit part absolute position fixed above.
682 sp ParentPosition is not used anywhere.
683 Since presence is sitting, viewer considers it 'linked' to root prim, so it will move/rotate it
684 Sending a extra packet with avatar position is not only bandwidth waste, but may cause jitter in viewers due to UPD nature.
685
686 if (!m_dupeInProgress)
687 {
688 foreach (ScenePresence av in m_linkedAvatars)
689 {
690 SceneObjectPart p = m_scene.GetSceneObjectPart(av.ParentID);
691 if (p != null && m_parts.TryGetValue(p.UUID, out p))
692 {
693 Vector3 offset = p.GetWorldPosition() - av.ParentPosition;
694 av.AbsolutePosition += offset;
695// av.ParentPosition = p.GetWorldPosition(); //ParentPosition gets cleared by AbsolutePosition
696 av.SendAvatarDataToAllAgents();
697 }
698 }
699 }
700*/
481 //if (m_rootPart.PhysActor != null) 701 //if (m_rootPart.PhysActor != null)
482 //{ 702 //{
483 //m_rootPart.PhysActor.Position = 703 //m_rootPart.PhysActor.Position =
@@ -491,6 +711,40 @@ namespace OpenSim.Region.Framework.Scenes
491 } 711 }
492 } 712 }
493 713
714 public override Vector3 Velocity
715 {
716 get { return RootPart.Velocity; }
717 set { RootPart.Velocity = value; }
718 }
719
720 private void CrossAgentToNewRegionCompleted(IAsyncResult iar)
721 {
722 CrossAgentToNewRegionDelegate icon = (CrossAgentToNewRegionDelegate)iar.AsyncState;
723 ScenePresence agent = icon.EndInvoke(iar);
724
725 //// If the cross was successful, this agent is a child agent
726 if (agent.IsChildAgent)
727 {
728 if (agent.ParentUUID != UUID.Zero)
729 {
730 agent.ParentPart = null;
731// agent.ParentPosition = Vector3.Zero;
732// agent.ParentUUID = UUID.Zero;
733 }
734 }
735
736 agent.ParentUUID = UUID.Zero;
737
738// agent.Reset();
739// else // Not successful
740// agent.RestoreInCurrentScene();
741
742 // In any case
743 agent.IsInTransit = false;
744
745 m_log.DebugFormat("[SCENE OBJECT]: Crossing agent {0} {1} completed.", agent.Firstname, agent.Lastname);
746 }
747
494 public override uint LocalId 748 public override uint LocalId
495 { 749 {
496 get { return m_rootPart.LocalId; } 750 get { return m_rootPart.LocalId; }
@@ -561,6 +815,11 @@ namespace OpenSim.Region.Framework.Scenes
561 m_isSelected = value; 815 m_isSelected = value;
562 // Tell physics engine that group is selected 816 // Tell physics engine that group is selected
563 817
818 // this is not right
819 // but ode engines should only really need to know about root part
820 // so they can put entire object simulation on hold and not colliding
821 // keep as was for now
822
564 PhysicsActor pa = m_rootPart.PhysActor; 823 PhysicsActor pa = m_rootPart.PhysActor;
565 if (pa != null) 824 if (pa != null)
566 { 825 {
@@ -577,6 +836,42 @@ namespace OpenSim.Region.Framework.Scenes
577 childPa.Selected = value; 836 childPa.Selected = value;
578 } 837 }
579 } 838 }
839 if (RootPart.KeyframeMotion != null)
840 RootPart.KeyframeMotion.Selected = value;
841 }
842 }
843
844 public void PartSelectChanged(bool partSelect)
845 {
846 // any part selected makes group selected
847 if (m_isSelected == partSelect)
848 return;
849
850 if (partSelect)
851 {
852 IsSelected = partSelect;
853// if (!IsAttachment)
854// ScheduleGroupForFullUpdate();
855 }
856 else
857 {
858 // bad bad bad 2 heavy for large linksets
859 // since viewer does send lot of (un)selects
860 // this needs to be replaced by a specific list or count ?
861 // but that will require extra code in several places
862
863 SceneObjectPart[] parts = m_parts.GetArray();
864 for (int i = 0; i < parts.Length; i++)
865 {
866 SceneObjectPart part = parts[i];
867 if (part.IsSelected)
868 return;
869 }
870 IsSelected = partSelect;
871 if (!IsAttachment)
872 {
873 ScheduleGroupForFullUpdate();
874 }
580 } 875 }
581 } 876 }
582 877
@@ -674,6 +969,7 @@ namespace OpenSim.Region.Framework.Scenes
674 /// </summary> 969 /// </summary>
675 public SceneObjectGroup() 970 public SceneObjectGroup()
676 { 971 {
972
677 } 973 }
678 974
679 /// <summary> 975 /// <summary>
@@ -691,8 +987,8 @@ namespace OpenSim.Region.Framework.Scenes
691 /// Constructor. This object is added to the scene later via AttachToScene() 987 /// Constructor. This object is added to the scene later via AttachToScene()
692 /// </summary> 988 /// </summary>
693 public SceneObjectGroup(UUID ownerID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape) 989 public SceneObjectGroup(UUID ownerID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape)
694 :this(new SceneObjectPart(ownerID, shape, pos, rot, Vector3.Zero)) 990 {
695 { 991 SetRootPart(new SceneObjectPart(ownerID, shape, pos, rot, Vector3.Zero));
696 } 992 }
697 993
698 /// <summary> 994 /// <summary>
@@ -727,6 +1023,9 @@ namespace OpenSim.Region.Framework.Scenes
727 /// </summary> 1023 /// </summary>
728 public virtual void AttachToBackup() 1024 public virtual void AttachToBackup()
729 { 1025 {
1026 if (IsAttachment) return;
1027 m_scene.SceneGraph.FireAttachToBackup(this);
1028
730 if (InSceneBackup) 1029 if (InSceneBackup)
731 { 1030 {
732 //m_log.DebugFormat( 1031 //m_log.DebugFormat(
@@ -769,6 +1068,13 @@ namespace OpenSim.Region.Framework.Scenes
769 1068
770 ApplyPhysics(); 1069 ApplyPhysics();
771 1070
1071 if (RootPart.PhysActor != null)
1072 RootPart.Force = RootPart.Force;
1073 if (RootPart.PhysActor != null)
1074 RootPart.Torque = RootPart.Torque;
1075 if (RootPart.PhysActor != null)
1076 RootPart.Buoyancy = RootPart.Buoyancy;
1077
772 // Don't trigger the update here - otherwise some client issues occur when multiple updates are scheduled 1078 // Don't trigger the update here - otherwise some client issues occur when multiple updates are scheduled
773 // for the same object with very different properties. The caller must schedule the update. 1079 // for the same object with very different properties. The caller must schedule the update.
774 //ScheduleGroupForFullUpdate(); 1080 //ScheduleGroupForFullUpdate();
@@ -784,6 +1090,10 @@ namespace OpenSim.Region.Framework.Scenes
784 EntityIntersection result = new EntityIntersection(); 1090 EntityIntersection result = new EntityIntersection();
785 1091
786 SceneObjectPart[] parts = m_parts.GetArray(); 1092 SceneObjectPart[] parts = m_parts.GetArray();
1093
1094 // Find closest hit here
1095 float idist = float.MaxValue;
1096
787 for (int i = 0; i < parts.Length; i++) 1097 for (int i = 0; i < parts.Length; i++)
788 { 1098 {
789 SceneObjectPart part = parts[i]; 1099 SceneObjectPart part = parts[i];
@@ -798,11 +1108,6 @@ namespace OpenSim.Region.Framework.Scenes
798 1108
799 EntityIntersection inter = part.TestIntersectionOBB(hRay, parentrotation, frontFacesOnly, faceCenters); 1109 EntityIntersection inter = part.TestIntersectionOBB(hRay, parentrotation, frontFacesOnly, faceCenters);
800 1110
801 // This may need to be updated to the maximum draw distance possible..
802 // We might (and probably will) be checking for prim creation from other sims
803 // when the camera crosses the border.
804 float idist = Constants.RegionSize;
805
806 if (inter.HitTF) 1111 if (inter.HitTF)
807 { 1112 {
808 // We need to find the closest prim to return to the testcaller along the ray 1113 // We need to find the closest prim to return to the testcaller along the ray
@@ -813,10 +1118,11 @@ namespace OpenSim.Region.Framework.Scenes
813 result.obj = part; 1118 result.obj = part;
814 result.normal = inter.normal; 1119 result.normal = inter.normal;
815 result.distance = inter.distance; 1120 result.distance = inter.distance;
1121
1122 idist = inter.distance;
816 } 1123 }
817 } 1124 }
818 } 1125 }
819
820 return result; 1126 return result;
821 } 1127 }
822 1128
@@ -828,25 +1134,27 @@ namespace OpenSim.Region.Framework.Scenes
828 /// <returns></returns> 1134 /// <returns></returns>
829 public void GetAxisAlignedBoundingBoxRaw(out float minX, out float maxX, out float minY, out float maxY, out float minZ, out float maxZ) 1135 public void GetAxisAlignedBoundingBoxRaw(out float minX, out float maxX, out float minY, out float maxY, out float minZ, out float maxZ)
830 { 1136 {
831 maxX = -256f; 1137 maxX = float.MinValue;
832 maxY = -256f; 1138 maxY = float.MinValue;
833 maxZ = -256f; 1139 maxZ = float.MinValue;
834 minX = 256f; 1140 minX = float.MaxValue;
835 minY = 256f; 1141 minY = float.MaxValue;
836 minZ = 8192f; 1142 minZ = float.MaxValue;
837 1143
838 SceneObjectPart[] parts = m_parts.GetArray(); 1144 SceneObjectPart[] parts = m_parts.GetArray();
839 for (int i = 0; i < parts.Length; i++) 1145 foreach (SceneObjectPart part in parts)
840 { 1146 {
841 SceneObjectPart part = parts[i];
842
843 Vector3 worldPos = part.GetWorldPosition(); 1147 Vector3 worldPos = part.GetWorldPosition();
844 Vector3 offset = worldPos - AbsolutePosition; 1148 Vector3 offset = worldPos - AbsolutePosition;
845 Quaternion worldRot; 1149 Quaternion worldRot;
846 if (part.ParentID == 0) 1150 if (part.ParentID == 0)
1151 {
847 worldRot = part.RotationOffset; 1152 worldRot = part.RotationOffset;
1153 }
848 else 1154 else
1155 {
849 worldRot = part.GetWorldRotation(); 1156 worldRot = part.GetWorldRotation();
1157 }
850 1158
851 Vector3 frontTopLeft; 1159 Vector3 frontTopLeft;
852 Vector3 frontTopRight; 1160 Vector3 frontTopRight;
@@ -858,6 +1166,8 @@ namespace OpenSim.Region.Framework.Scenes
858 Vector3 backBottomLeft; 1166 Vector3 backBottomLeft;
859 Vector3 backBottomRight; 1167 Vector3 backBottomRight;
860 1168
1169 // Vector3[] corners = new Vector3[8];
1170
861 Vector3 orig = Vector3.Zero; 1171 Vector3 orig = Vector3.Zero;
862 1172
863 frontTopLeft.X = orig.X - (part.Scale.X / 2); 1173 frontTopLeft.X = orig.X - (part.Scale.X / 2);
@@ -892,6 +1202,38 @@ namespace OpenSim.Region.Framework.Scenes
892 backBottomRight.Y = orig.Y + (part.Scale.Y / 2); 1202 backBottomRight.Y = orig.Y + (part.Scale.Y / 2);
893 backBottomRight.Z = orig.Z - (part.Scale.Z / 2); 1203 backBottomRight.Z = orig.Z - (part.Scale.Z / 2);
894 1204
1205
1206
1207 //m_log.InfoFormat("pre corner 1 is {0} {1} {2}", frontTopLeft.X, frontTopLeft.Y, frontTopLeft.Z);
1208 //m_log.InfoFormat("pre corner 2 is {0} {1} {2}", frontTopRight.X, frontTopRight.Y, frontTopRight.Z);
1209 //m_log.InfoFormat("pre corner 3 is {0} {1} {2}", frontBottomRight.X, frontBottomRight.Y, frontBottomRight.Z);
1210 //m_log.InfoFormat("pre corner 4 is {0} {1} {2}", frontBottomLeft.X, frontBottomLeft.Y, frontBottomLeft.Z);
1211 //m_log.InfoFormat("pre corner 5 is {0} {1} {2}", backTopLeft.X, backTopLeft.Y, backTopLeft.Z);
1212 //m_log.InfoFormat("pre corner 6 is {0} {1} {2}", backTopRight.X, backTopRight.Y, backTopRight.Z);
1213 //m_log.InfoFormat("pre corner 7 is {0} {1} {2}", backBottomRight.X, backBottomRight.Y, backBottomRight.Z);
1214 //m_log.InfoFormat("pre corner 8 is {0} {1} {2}", backBottomLeft.X, backBottomLeft.Y, backBottomLeft.Z);
1215
1216 //for (int i = 0; i < 8; i++)
1217 //{
1218 // corners[i] = corners[i] * worldRot;
1219 // corners[i] += offset;
1220
1221 // if (corners[i].X > maxX)
1222 // maxX = corners[i].X;
1223 // if (corners[i].X < minX)
1224 // minX = corners[i].X;
1225
1226 // if (corners[i].Y > maxY)
1227 // maxY = corners[i].Y;
1228 // if (corners[i].Y < minY)
1229 // minY = corners[i].Y;
1230
1231 // if (corners[i].Z > maxZ)
1232 // maxZ = corners[i].Y;
1233 // if (corners[i].Z < minZ)
1234 // minZ = corners[i].Z;
1235 //}
1236
895 frontTopLeft = frontTopLeft * worldRot; 1237 frontTopLeft = frontTopLeft * worldRot;
896 frontTopRight = frontTopRight * worldRot; 1238 frontTopRight = frontTopRight * worldRot;
897 frontBottomLeft = frontBottomLeft * worldRot; 1239 frontBottomLeft = frontBottomLeft * worldRot;
@@ -913,6 +1255,15 @@ namespace OpenSim.Region.Framework.Scenes
913 backTopLeft += offset; 1255 backTopLeft += offset;
914 backTopRight += offset; 1256 backTopRight += offset;
915 1257
1258 //m_log.InfoFormat("corner 1 is {0} {1} {2}", frontTopLeft.X, frontTopLeft.Y, frontTopLeft.Z);
1259 //m_log.InfoFormat("corner 2 is {0} {1} {2}", frontTopRight.X, frontTopRight.Y, frontTopRight.Z);
1260 //m_log.InfoFormat("corner 3 is {0} {1} {2}", frontBottomRight.X, frontBottomRight.Y, frontBottomRight.Z);
1261 //m_log.InfoFormat("corner 4 is {0} {1} {2}", frontBottomLeft.X, frontBottomLeft.Y, frontBottomLeft.Z);
1262 //m_log.InfoFormat("corner 5 is {0} {1} {2}", backTopLeft.X, backTopLeft.Y, backTopLeft.Z);
1263 //m_log.InfoFormat("corner 6 is {0} {1} {2}", backTopRight.X, backTopRight.Y, backTopRight.Z);
1264 //m_log.InfoFormat("corner 7 is {0} {1} {2}", backBottomRight.X, backBottomRight.Y, backBottomRight.Z);
1265 //m_log.InfoFormat("corner 8 is {0} {1} {2}", backBottomLeft.X, backBottomLeft.Y, backBottomLeft.Z);
1266
916 if (frontTopRight.X > maxX) 1267 if (frontTopRight.X > maxX)
917 maxX = frontTopRight.X; 1268 maxX = frontTopRight.X;
918 if (frontTopLeft.X > maxX) 1269 if (frontTopLeft.X > maxX)
@@ -1056,17 +1407,118 @@ namespace OpenSim.Region.Framework.Scenes
1056 1407
1057 #endregion 1408 #endregion
1058 1409
1410 public void GetResourcesCosts(SceneObjectPart apart,
1411 out float linksetResCost, out float linksetPhysCost, out float partCost, out float partPhysCost)
1412 {
1413 // this information may need to be cached
1414
1415 float cost;
1416 float tmpcost;
1417
1418 bool ComplexCost = false;
1419
1420 SceneObjectPart p;
1421 SceneObjectPart[] parts;
1422
1423 lock (m_parts)
1424 {
1425 parts = m_parts.GetArray();
1426 }
1427
1428 int nparts = parts.Length;
1429
1430
1431 for (int i = 0; i < nparts; i++)
1432 {
1433 p = parts[i];
1434
1435 if (p.UsesComplexCost)
1436 {
1437 ComplexCost = true;
1438 break;
1439 }
1440 }
1441
1442 if (ComplexCost)
1443 {
1444 linksetResCost = 0;
1445 linksetPhysCost = 0;
1446 partCost = 0;
1447 partPhysCost = 0;
1448
1449 for (int i = 0; i < nparts; i++)
1450 {
1451 p = parts[i];
1452
1453 cost = p.StreamingCost;
1454 tmpcost = p.SimulationCost;
1455 if (tmpcost > cost)
1456 cost = tmpcost;
1457 tmpcost = p.PhysicsCost;
1458 if (tmpcost > cost)
1459 cost = tmpcost;
1460
1461 linksetPhysCost += tmpcost;
1462 linksetResCost += cost;
1463
1464 if (p == apart)
1465 {
1466 partCost = cost;
1467 partPhysCost = tmpcost;
1468 }
1469 }
1470 }
1471 else
1472 {
1473 partPhysCost = 1.0f;
1474 partCost = 1.0f;
1475 linksetResCost = (float)nparts;
1476 linksetPhysCost = linksetResCost;
1477 }
1478 }
1479
1480 public void GetSelectedCosts(out float PhysCost, out float StreamCost, out float SimulCost)
1481 {
1482 SceneObjectPart p;
1483 SceneObjectPart[] parts;
1484
1485 lock (m_parts)
1486 {
1487 parts = m_parts.GetArray();
1488 }
1489
1490 int nparts = parts.Length;
1491
1492 PhysCost = 0;
1493 StreamCost = 0;
1494 SimulCost = 0;
1495
1496 for (int i = 0; i < nparts; i++)
1497 {
1498 p = parts[i];
1499
1500 StreamCost += p.StreamingCost;
1501 SimulCost += p.SimulationCost;
1502 PhysCost += p.PhysicsCost;
1503 }
1504 }
1505
1059 public void SaveScriptedState(XmlTextWriter writer) 1506 public void SaveScriptedState(XmlTextWriter writer)
1060 { 1507 {
1508 SaveScriptedState(writer, false);
1509 }
1510
1511 public void SaveScriptedState(XmlTextWriter writer, bool oldIDs)
1512 {
1061 XmlDocument doc = new XmlDocument(); 1513 XmlDocument doc = new XmlDocument();
1062 Dictionary<UUID,string> states = new Dictionary<UUID,string>(); 1514 Dictionary<UUID,string> states = new Dictionary<UUID,string>();
1063 1515
1064 SceneObjectPart[] parts = m_parts.GetArray(); 1516 SceneObjectPart[] parts = m_parts.GetArray();
1065 for (int i = 0; i < parts.Length; i++) 1517 for (int i = 0; i < parts.Length; i++)
1066 { 1518 {
1067 Dictionary<UUID, string> pstates = parts[i].Inventory.GetScriptStates(); 1519 Dictionary<UUID, string> pstates = parts[i].Inventory.GetScriptStates(oldIDs);
1068 foreach (KeyValuePair<UUID, string> kvp in pstates) 1520 foreach (KeyValuePair<UUID, string> kvp in pstates)
1069 states.Add(kvp.Key, kvp.Value); 1521 states[kvp.Key] = kvp.Value;
1070 } 1522 }
1071 1523
1072 if (states.Count > 0) 1524 if (states.Count > 0)
@@ -1086,6 +1538,169 @@ namespace OpenSim.Region.Framework.Scenes
1086 } 1538 }
1087 1539
1088 /// <summary> 1540 /// <summary>
1541 /// Add the avatar to this linkset (avatar is sat).
1542 /// </summary>
1543 /// <param name="agentID"></param>
1544 public void AddAvatar(UUID agentID)
1545 {
1546 ScenePresence presence;
1547 if (m_scene.TryGetScenePresence(agentID, out presence))
1548 {
1549 if (!m_linkedAvatars.Contains(presence))
1550 {
1551 m_linkedAvatars.Add(presence);
1552 }
1553 }
1554 }
1555
1556 /// <summary>
1557 /// Delete the avatar from this linkset (avatar is unsat).
1558 /// </summary>
1559 /// <param name="agentID"></param>
1560 public void DeleteAvatar(UUID agentID)
1561 {
1562 ScenePresence presence;
1563 if (m_scene.TryGetScenePresence(agentID, out presence))
1564 {
1565 if (m_linkedAvatars.Contains(presence))
1566 {
1567 m_linkedAvatars.Remove(presence);
1568 }
1569 }
1570 }
1571
1572 /// <summary>
1573 /// Returns the list of linked presences (avatars sat on this group)
1574 /// </summary>
1575 /// <param name="agentID"></param>
1576 public List<ScenePresence> GetLinkedAvatars()
1577 {
1578 return m_linkedAvatars;
1579 }
1580
1581 /// <summary>
1582 /// Attach this scene object to the given avatar.
1583 /// </summary>
1584 /// <param name="agentID"></param>
1585 /// <param name="attachmentpoint"></param>
1586 /// <param name="AttachOffset"></param>
1587 private void AttachToAgent(
1588 ScenePresence avatar, SceneObjectGroup so, uint attachmentpoint, Vector3 attachOffset, bool silent)
1589 {
1590 if (avatar != null)
1591 {
1592 // don't attach attachments to child agents
1593 if (avatar.IsChildAgent) return;
1594
1595 // Remove from database and parcel prim count
1596 m_scene.DeleteFromStorage(so.UUID);
1597 m_scene.EventManager.TriggerParcelPrimCountTainted();
1598
1599 so.AttachedAvatar = avatar.UUID;
1600
1601 if (so.RootPart.PhysActor != null)
1602 {
1603 m_scene.PhysicsScene.RemovePrim(so.RootPart.PhysActor);
1604 so.RootPart.PhysActor = null;
1605 }
1606
1607 so.AbsolutePosition = attachOffset;
1608 so.RootPart.AttachedPos = attachOffset;
1609 so.IsAttachment = true;
1610 so.RootPart.SetParentLocalId(avatar.LocalId);
1611 so.AttachmentPoint = attachmentpoint;
1612
1613 avatar.AddAttachment(this);
1614
1615 if (!silent)
1616 {
1617 // Killing it here will cause the client to deselect it
1618 // It then reappears on the avatar, deselected
1619 // through the full update below
1620 //
1621 if (IsSelected)
1622 {
1623 m_scene.SendKillObject(new List<uint> { m_rootPart.LocalId });
1624 }
1625
1626 IsSelected = false; // fudge....
1627 ScheduleGroupForFullUpdate();
1628 }
1629 }
1630 else
1631 {
1632 m_log.WarnFormat(
1633 "[SOG]: Tried to add attachment {0} to avatar with UUID {1} in region {2} but the avatar is not present",
1634 UUID, avatar.ControllingClient.AgentId, Scene.RegionInfo.RegionName);
1635 }
1636 }
1637
1638 public byte GetAttachmentPoint()
1639 {
1640 return m_rootPart.Shape.State;
1641 }
1642
1643 public void DetachToGround()
1644 {
1645 ScenePresence avatar = m_scene.GetScenePresence(AttachedAvatar);
1646 if (avatar == null)
1647 return;
1648
1649 avatar.RemoveAttachment(this);
1650
1651 Vector3 detachedpos = new Vector3(127f,127f,127f);
1652 if (avatar == null)
1653 return;
1654
1655 detachedpos = avatar.AbsolutePosition;
1656 FromItemID = UUID.Zero;
1657
1658 AbsolutePosition = detachedpos;
1659 AttachedAvatar = UUID.Zero;
1660
1661 //SceneObjectPart[] parts = m_parts.GetArray();
1662 //for (int i = 0; i < parts.Length; i++)
1663 // parts[i].AttachedAvatar = UUID.Zero;
1664
1665 m_rootPart.SetParentLocalId(0);
1666 AttachmentPoint = (byte)0;
1667 // must check if buildind should be true or false here
1668 m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_rootPart.VolumeDetectActive,false);
1669 HasGroupChanged = true;
1670 RootPart.Rezzed = DateTime.Now;
1671 RootPart.RemFlag(PrimFlags.TemporaryOnRez);
1672 AttachToBackup();
1673 m_scene.EventManager.TriggerParcelPrimCountTainted();
1674 m_rootPart.ScheduleFullUpdate();
1675 m_rootPart.ClearUndoState();
1676 }
1677
1678 public void DetachToInventoryPrep()
1679 {
1680 ScenePresence avatar = m_scene.GetScenePresence(AttachedAvatar);
1681 //Vector3 detachedpos = new Vector3(127f, 127f, 127f);
1682 if (avatar != null)
1683 {
1684 //detachedpos = avatar.AbsolutePosition;
1685 avatar.RemoveAttachment(this);
1686 }
1687
1688 AttachedAvatar = UUID.Zero;
1689
1690 /*SceneObjectPart[] parts = m_parts.GetArray();
1691 for (int i = 0; i < parts.Length; i++)
1692 parts[i].AttachedAvatar = UUID.Zero;*/
1693
1694 m_rootPart.SetParentLocalId(0);
1695 //m_rootPart.SetAttachmentPoint((byte)0);
1696 IsAttachment = false;
1697 AbsolutePosition = m_rootPart.AttachedPos;
1698 //m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_scene.m_physicalPrim);
1699 //AttachToBackup();
1700 //m_rootPart.ScheduleFullUpdate();
1701 }
1702
1703 /// <summary>
1089 /// 1704 ///
1090 /// </summary> 1705 /// </summary>
1091 /// <param name="part"></param> 1706 /// <param name="part"></param>
@@ -1125,7 +1740,10 @@ namespace OpenSim.Region.Framework.Scenes
1125 public void AddPart(SceneObjectPart part) 1740 public void AddPart(SceneObjectPart part)
1126 { 1741 {
1127 part.SetParent(this); 1742 part.SetParent(this);
1128 part.LinkNum = m_parts.Add(part.UUID, part); 1743 m_parts.Add(part.UUID, part);
1744
1745 part.LinkNum = m_parts.Count;
1746
1129 if (part.LinkNum == 2) 1747 if (part.LinkNum == 2)
1130 RootPart.LinkNum = 1; 1748 RootPart.LinkNum = 1;
1131 } 1749 }
@@ -1151,6 +1769,14 @@ namespace OpenSim.Region.Framework.Scenes
1151 parts[i].UUID = UUID.Random(); 1769 parts[i].UUID = UUID.Random();
1152 } 1770 }
1153 1771
1772 // helper provided for parts.
1773 public int GetSceneMaxUndo()
1774 {
1775 if (m_scene != null)
1776 return m_scene.MaxUndoCount;
1777 return 5;
1778 }
1779
1154 // justincc: I don't believe this hack is needed any longer, especially since the physics 1780 // justincc: I don't believe this hack is needed any longer, especially since the physics
1155 // parts of set AbsolutePosition were already commented out. By changing HasGroupChanged to false 1781 // parts of set AbsolutePosition were already commented out. By changing HasGroupChanged to false
1156 // this method was preventing proper reload of scene objects. 1782 // this method was preventing proper reload of scene objects.
@@ -1208,7 +1834,7 @@ namespace OpenSim.Region.Framework.Scenes
1208// "[SCENE OBJECT GROUP]: Processing OnGrabPart for {0} on {1} {2}, offsetPos {3}", 1834// "[SCENE OBJECT GROUP]: Processing OnGrabPart for {0} on {1} {2}, offsetPos {3}",
1209// remoteClient.Name, part.Name, part.LocalId, offsetPos); 1835// remoteClient.Name, part.Name, part.LocalId, offsetPos);
1210 1836
1211 part.StoreUndoState(); 1837// part.StoreUndoState();
1212 part.OnGrab(offsetPos, remoteClient); 1838 part.OnGrab(offsetPos, remoteClient);
1213 } 1839 }
1214 1840
@@ -1228,6 +1854,11 @@ namespace OpenSim.Region.Framework.Scenes
1228 /// <param name="silent">If true then deletion is not broadcast to clients</param> 1854 /// <param name="silent">If true then deletion is not broadcast to clients</param>
1229 public void DeleteGroupFromScene(bool silent) 1855 public void DeleteGroupFromScene(bool silent)
1230 { 1856 {
1857 // We need to keep track of this state in case this group is still queued for backup.
1858 IsDeleted = true;
1859
1860 DetachFromBackup();
1861
1231 SceneObjectPart[] parts = m_parts.GetArray(); 1862 SceneObjectPart[] parts = m_parts.GetArray();
1232 for (int i = 0; i < parts.Length; i++) 1863 for (int i = 0; i < parts.Length; i++)
1233 { 1864 {
@@ -1251,6 +1882,7 @@ namespace OpenSim.Region.Framework.Scenes
1251 } 1882 }
1252 }); 1883 });
1253 } 1884 }
1885
1254 } 1886 }
1255 1887
1256 public void AddScriptLPS(int count) 1888 public void AddScriptLPS(int count)
@@ -1320,28 +1952,43 @@ namespace OpenSim.Region.Framework.Scenes
1320 /// </summary> 1952 /// </summary>
1321 public void ApplyPhysics() 1953 public void ApplyPhysics()
1322 { 1954 {
1323 // Apply physics to the root prim
1324 m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_rootPart.VolumeDetectActive);
1325
1326 // Apply physics to child prims
1327 SceneObjectPart[] parts = m_parts.GetArray(); 1955 SceneObjectPart[] parts = m_parts.GetArray();
1328 if (parts.Length > 1) 1956 if (parts.Length > 1)
1329 { 1957 {
1958 ResetChildPrimPhysicsPositions();
1959
1960 // Apply physics to the root prim
1961 m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_rootPart.VolumeDetectActive, true);
1962
1963
1330 for (int i = 0; i < parts.Length; i++) 1964 for (int i = 0; i < parts.Length; i++)
1331 { 1965 {
1332 SceneObjectPart part = parts[i]; 1966 SceneObjectPart part = parts[i];
1333 if (part.LocalId != m_rootPart.LocalId) 1967 if (part.LocalId != m_rootPart.LocalId)
1334 part.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), part.VolumeDetectActive); 1968 part.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), part.VolumeDetectActive, true);
1335 } 1969 }
1336
1337 // Hack to get the physics scene geometries in the right spot 1970 // Hack to get the physics scene geometries in the right spot
1338 ResetChildPrimPhysicsPositions(); 1971// ResetChildPrimPhysicsPositions();
1972 if (m_rootPart.PhysActor != null)
1973 {
1974 m_rootPart.PhysActor.Building = false;
1975 }
1976 }
1977 else
1978 {
1979 // Apply physics to the root prim
1980 m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_rootPart.VolumeDetectActive, false);
1339 } 1981 }
1340 } 1982 }
1341 1983
1342 public void SetOwnerId(UUID userId) 1984 public void SetOwnerId(UUID userId)
1343 { 1985 {
1344 ForEachPart(delegate(SceneObjectPart part) { part.OwnerID = userId; }); 1986 ForEachPart(delegate(SceneObjectPart part)
1987 {
1988
1989 part.OwnerID = userId;
1990
1991 });
1345 } 1992 }
1346 1993
1347 public void ForEachPart(Action<SceneObjectPart> whatToDo) 1994 public void ForEachPart(Action<SceneObjectPart> whatToDo)
@@ -1373,11 +2020,17 @@ namespace OpenSim.Region.Framework.Scenes
1373 return; 2020 return;
1374 } 2021 }
1375 2022
2023 if ((RootPart.Flags & PrimFlags.TemporaryOnRez) != 0)
2024 return;
2025
1376 // Since this is the top of the section of call stack for backing up a particular scene object, don't let 2026 // Since this is the top of the section of call stack for backing up a particular scene object, don't let
1377 // any exception propogate upwards. 2027 // any exception propogate upwards.
1378 try 2028 try
1379 { 2029 {
1380 if (!m_scene.ShuttingDown) // if shutting down then there will be nothing to handle the return so leave till next restart 2030 if (!m_scene.ShuttingDown || // if shutting down then there will be nothing to handle the return so leave till next restart
2031 !m_scene.LoginsEnabled || // We're starting up or doing maintenance, don't mess with things
2032 m_scene.LoadingPrims) // Land may not be valid yet
2033
1381 { 2034 {
1382 ILandObject parcel = m_scene.LandChannel.GetLandObject( 2035 ILandObject parcel = m_scene.LandChannel.GetLandObject(
1383 m_rootPart.GroupPosition.X, m_rootPart.GroupPosition.Y); 2036 m_rootPart.GroupPosition.X, m_rootPart.GroupPosition.Y);
@@ -1404,6 +2057,7 @@ namespace OpenSim.Region.Framework.Scenes
1404 } 2057 }
1405 } 2058 }
1406 } 2059 }
2060
1407 } 2061 }
1408 2062
1409 if (m_scene.UseBackup && HasGroupChanged) 2063 if (m_scene.UseBackup && HasGroupChanged)
@@ -1411,10 +2065,30 @@ namespace OpenSim.Region.Framework.Scenes
1411 // don't backup while it's selected or you're asking for changes mid stream. 2065 // don't backup while it's selected or you're asking for changes mid stream.
1412 if (isTimeToPersist() || forcedBackup) 2066 if (isTimeToPersist() || forcedBackup)
1413 { 2067 {
2068 if (m_rootPart.PhysActor != null &&
2069 (!m_rootPart.PhysActor.IsPhysical))
2070 {
2071 // Possible ghost prim
2072 if (m_rootPart.PhysActor.Position != m_rootPart.GroupPosition)
2073 {
2074 foreach (SceneObjectPart part in m_parts.GetArray())
2075 {
2076 // Re-set physics actor positions and
2077 // orientations
2078 part.GroupPosition = m_rootPart.GroupPosition;
2079 }
2080 }
2081 }
1414// m_log.DebugFormat( 2082// m_log.DebugFormat(
1415// "[SCENE]: Storing {0}, {1} in {2}", 2083// "[SCENE]: Storing {0}, {1} in {2}",
1416// Name, UUID, m_scene.RegionInfo.RegionName); 2084// Name, UUID, m_scene.RegionInfo.RegionName);
1417 2085
2086 if (RootPart.Shape.PCode == 9 && RootPart.Shape.State != 0)
2087 {
2088 RootPart.Shape.State = 0;
2089 ScheduleGroupForFullUpdate();
2090 }
2091
1418 SceneObjectGroup backup_group = Copy(false); 2092 SceneObjectGroup backup_group = Copy(false);
1419 backup_group.RootPart.Velocity = RootPart.Velocity; 2093 backup_group.RootPart.Velocity = RootPart.Velocity;
1420 backup_group.RootPart.Acceleration = RootPart.Acceleration; 2094 backup_group.RootPart.Acceleration = RootPart.Acceleration;
@@ -1424,6 +2098,16 @@ namespace OpenSim.Region.Framework.Scenes
1424 HasGroupChangedDueToDelink = false; 2098 HasGroupChangedDueToDelink = false;
1425 2099
1426 m_scene.EventManager.TriggerOnSceneObjectPreSave(backup_group, this); 2100 m_scene.EventManager.TriggerOnSceneObjectPreSave(backup_group, this);
2101/*
2102 backup_group.ForEachPart(delegate(SceneObjectPart part)
2103 {
2104 if (part.KeyframeMotion != null)
2105 {
2106 part.KeyframeMotion = KeyframeMotion.FromData(backup_group, part.KeyframeMotion.Serialize());
2107// part.KeyframeMotion.UpdateSceneObject(this);
2108 }
2109 });
2110*/
1427 datastore.StoreObject(backup_group, m_scene.RegionInfo.RegionID); 2111 datastore.StoreObject(backup_group, m_scene.RegionInfo.RegionID);
1428 2112
1429 backup_group.ForEachPart(delegate(SceneObjectPart part) 2113 backup_group.ForEachPart(delegate(SceneObjectPart part)
@@ -1480,10 +2164,14 @@ namespace OpenSim.Region.Framework.Scenes
1480 /// <returns></returns> 2164 /// <returns></returns>
1481 public SceneObjectGroup Copy(bool userExposed) 2165 public SceneObjectGroup Copy(bool userExposed)
1482 { 2166 {
2167 m_dupeInProgress = true;
1483 SceneObjectGroup dupe = (SceneObjectGroup)MemberwiseClone(); 2168 SceneObjectGroup dupe = (SceneObjectGroup)MemberwiseClone();
1484 dupe.m_isBackedUp = false; 2169 dupe.m_isBackedUp = false;
1485 dupe.m_parts = new MapAndArray<OpenMetaverse.UUID, SceneObjectPart>(); 2170 dupe.m_parts = new MapAndArray<OpenMetaverse.UUID, SceneObjectPart>();
1486 2171
2172 // new group as no sitting avatars
2173 dupe.m_linkedAvatars = new List<ScenePresence>();
2174
1487 // Warning, The following code related to previousAttachmentStatus is needed so that clones of 2175 // Warning, The following code related to previousAttachmentStatus is needed so that clones of
1488 // attachments do not bordercross while they're being duplicated. This is hacktastic! 2176 // attachments do not bordercross while they're being duplicated. This is hacktastic!
1489 // Normally, setting AbsolutePosition will bordercross a prim if it's outside the region! 2177 // Normally, setting AbsolutePosition will bordercross a prim if it's outside the region!
@@ -1494,7 +2182,7 @@ namespace OpenSim.Region.Framework.Scenes
1494 // This is only necessary when userExposed is false! 2182 // This is only necessary when userExposed is false!
1495 2183
1496 bool previousAttachmentStatus = dupe.IsAttachment; 2184 bool previousAttachmentStatus = dupe.IsAttachment;
1497 2185
1498 if (!userExposed) 2186 if (!userExposed)
1499 dupe.IsAttachment = true; 2187 dupe.IsAttachment = true;
1500 2188
@@ -1507,16 +2195,17 @@ namespace OpenSim.Region.Framework.Scenes
1507 2195
1508 dupe.CopyRootPart(m_rootPart, OwnerID, GroupID, userExposed); 2196 dupe.CopyRootPart(m_rootPart, OwnerID, GroupID, userExposed);
1509 dupe.m_rootPart.LinkNum = m_rootPart.LinkNum; 2197 dupe.m_rootPart.LinkNum = m_rootPart.LinkNum;
2198
1510 2199
1511 if (userExposed) 2200 if (userExposed)
1512 dupe.m_rootPart.TrimPermissions(); 2201 dupe.m_rootPart.TrimPermissions();
1513 2202
1514 List<SceneObjectPart> partList = new List<SceneObjectPart>(m_parts.GetArray()); 2203 List<SceneObjectPart> partList = new List<SceneObjectPart>(m_parts.GetArray());
1515 2204
1516 partList.Sort(delegate(SceneObjectPart p1, SceneObjectPart p2) 2205 partList.Sort(delegate(SceneObjectPart p1, SceneObjectPart p2)
1517 { 2206 {
1518 return p1.LinkNum.CompareTo(p2.LinkNum); 2207 return p1.LinkNum.CompareTo(p2.LinkNum);
1519 } 2208 }
1520 ); 2209 );
1521 2210
1522 foreach (SceneObjectPart part in partList) 2211 foreach (SceneObjectPart part in partList)
@@ -1526,41 +2215,56 @@ namespace OpenSim.Region.Framework.Scenes
1526 { 2215 {
1527 newPart = dupe.CopyPart(part, OwnerID, GroupID, userExposed); 2216 newPart = dupe.CopyPart(part, OwnerID, GroupID, userExposed);
1528 newPart.LinkNum = part.LinkNum; 2217 newPart.LinkNum = part.LinkNum;
1529 } 2218 if (userExposed)
2219 newPart.ParentID = dupe.m_rootPart.LocalId;
2220 }
1530 else 2221 else
1531 { 2222 {
1532 newPart = dupe.m_rootPart; 2223 newPart = dupe.m_rootPart;
1533 } 2224 }
2225/*
2226 bool isphys = ((newPart.Flags & PrimFlags.Physics) != 0);
2227 bool isphan = ((newPart.Flags & PrimFlags.Phantom) != 0);
1534 2228
1535 // Need to duplicate the physics actor as well 2229 // Need to duplicate the physics actor as well
1536 PhysicsActor originalPartPa = part.PhysActor; 2230 if (userExposed && (isphys || !isphan || newPart.VolumeDetectActive))
1537 if (originalPartPa != null && userExposed)
1538 { 2231 {
1539 PrimitiveBaseShape pbs = newPart.Shape; 2232 PrimitiveBaseShape pbs = newPart.Shape;
1540
1541 newPart.PhysActor 2233 newPart.PhysActor
1542 = m_scene.PhysicsScene.AddPrimShape( 2234 = m_scene.PhysicsScene.AddPrimShape(
1543 string.Format("{0}/{1}", newPart.Name, newPart.UUID), 2235 string.Format("{0}/{1}", newPart.Name, newPart.UUID),
1544 pbs, 2236 pbs,
1545 newPart.AbsolutePosition, 2237 newPart.AbsolutePosition,
1546 newPart.Scale, 2238 newPart.Scale,
1547 newPart.RotationOffset, 2239 newPart.GetWorldRotation(),
1548 originalPartPa.IsPhysical, 2240 isphys,
2241 isphan,
1549 newPart.LocalId); 2242 newPart.LocalId);
1550 2243
1551 newPart.DoPhysicsPropertyUpdate(originalPartPa.IsPhysical, true); 2244 newPart.DoPhysicsPropertyUpdate(isphys, true);
1552 } 2245 */
2246 if (userExposed)
2247 newPart.ApplyPhysics((uint)newPart.Flags,newPart.VolumeDetectActive,true);
2248// }
2249 // copy keyframemotion
2250 if (part.KeyframeMotion != null)
2251 newPart.KeyframeMotion = part.KeyframeMotion.Copy(dupe);
1553 } 2252 }
1554 2253
1555 if (userExposed) 2254 if (userExposed)
1556 { 2255 {
1557 dupe.UpdateParentIDs(); 2256// done above dupe.UpdateParentIDs();
2257
2258 if (dupe.m_rootPart.PhysActor != null)
2259 dupe.m_rootPart.PhysActor.Building = false; // tell physics to finish building
2260
1558 dupe.HasGroupChanged = true; 2261 dupe.HasGroupChanged = true;
1559 dupe.AttachToBackup(); 2262 dupe.AttachToBackup();
1560 2263
1561 ScheduleGroupForFullUpdate(); 2264 ScheduleGroupForFullUpdate();
1562 } 2265 }
1563 2266
2267 m_dupeInProgress = false;
1564 return dupe; 2268 return dupe;
1565 } 2269 }
1566 2270
@@ -1572,11 +2276,24 @@ namespace OpenSim.Region.Framework.Scenes
1572 /// <param name="cGroupID"></param> 2276 /// <param name="cGroupID"></param>
1573 public void CopyRootPart(SceneObjectPart part, UUID cAgentID, UUID cGroupID, bool userExposed) 2277 public void CopyRootPart(SceneObjectPart part, UUID cAgentID, UUID cGroupID, bool userExposed)
1574 { 2278 {
1575 SetRootPart(part.Copy(m_scene.AllocateLocalId(), OwnerID, GroupID, 0, userExposed)); 2279 // SetRootPart(part.Copy(m_scene.AllocateLocalId(), OwnerID, GroupID, 0, userExposed));
2280 // give newpart a new local ID lettng old part keep same
2281 SceneObjectPart newpart = part.Copy(part.LocalId, OwnerID, GroupID, 0, userExposed);
2282 newpart.LocalId = m_scene.AllocateLocalId();
2283
2284 SetRootPart(newpart);
2285 if (userExposed)
2286 RootPart.Velocity = Vector3.Zero; // In case source is moving
1576 } 2287 }
1577 2288
1578 public void ScriptSetPhysicsStatus(bool usePhysics) 2289 public void ScriptSetPhysicsStatus(bool usePhysics)
1579 { 2290 {
2291 if (usePhysics)
2292 {
2293 if (RootPart.KeyframeMotion != null)
2294 RootPart.KeyframeMotion.Stop();
2295 RootPart.KeyframeMotion = null;
2296 }
1580 UpdatePrimFlags(RootPart.LocalId, usePhysics, IsTemporary, IsPhantom, IsVolumeDetect); 2297 UpdatePrimFlags(RootPart.LocalId, usePhysics, IsTemporary, IsPhantom, IsVolumeDetect);
1581 } 2298 }
1582 2299
@@ -1624,27 +2341,14 @@ namespace OpenSim.Region.Framework.Scenes
1624 2341
1625 if (pa != null) 2342 if (pa != null)
1626 { 2343 {
1627 pa.AddForce(impulse, true); 2344 // false to be applied as a impulse
1628 m_scene.PhysicsScene.AddPhysicsActorTaint(pa); 2345 pa.AddForce(impulse, false);
1629 }
1630 }
1631 }
1632
1633 public void applyAngularImpulse(Vector3 impulse)
1634 {
1635 PhysicsActor pa = RootPart.PhysActor;
1636
1637 if (pa != null)
1638 {
1639 if (!IsAttachment)
1640 {
1641 pa.AddAngularForce(impulse, true);
1642 m_scene.PhysicsScene.AddPhysicsActorTaint(pa); 2346 m_scene.PhysicsScene.AddPhysicsActorTaint(pa);
1643 } 2347 }
1644 } 2348 }
1645 } 2349 }
1646 2350
1647 public void setAngularImpulse(Vector3 impulse) 2351 public void ApplyAngularImpulse(Vector3 impulse)
1648 { 2352 {
1649 PhysicsActor pa = RootPart.PhysActor; 2353 PhysicsActor pa = RootPart.PhysActor;
1650 2354
@@ -1652,7 +2356,8 @@ namespace OpenSim.Region.Framework.Scenes
1652 { 2356 {
1653 if (!IsAttachment) 2357 if (!IsAttachment)
1654 { 2358 {
1655 pa.Torque = impulse; 2359 // false to be applied as a impulse
2360 pa.AddAngularForce(impulse, false);
1656 m_scene.PhysicsScene.AddPhysicsActorTaint(pa); 2361 m_scene.PhysicsScene.AddPhysicsActorTaint(pa);
1657 } 2362 }
1658 } 2363 }
@@ -1660,20 +2365,10 @@ namespace OpenSim.Region.Framework.Scenes
1660 2365
1661 public Vector3 GetTorque() 2366 public Vector3 GetTorque()
1662 { 2367 {
1663 PhysicsActor pa = RootPart.PhysActor; 2368 return RootPart.Torque;
1664
1665 if (pa != null)
1666 {
1667 if (!IsAttachment)
1668 {
1669 Vector3 torque = pa.Torque;
1670 return torque;
1671 }
1672 }
1673
1674 return Vector3.Zero;
1675 } 2369 }
1676 2370
2371 // This is used by both Double-Click Auto-Pilot and llMoveToTarget() in an attached object
1677 public void moveToTarget(Vector3 target, float tau) 2372 public void moveToTarget(Vector3 target, float tau)
1678 { 2373 {
1679 if (IsAttachment) 2374 if (IsAttachment)
@@ -1705,6 +2400,46 @@ namespace OpenSim.Region.Framework.Scenes
1705 pa.PIDActive = false; 2400 pa.PIDActive = false;
1706 } 2401 }
1707 2402
2403 public void rotLookAt(Quaternion target, float strength, float damping)
2404 {
2405 SceneObjectPart rootpart = m_rootPart;
2406 if (rootpart != null)
2407 {
2408 if (IsAttachment)
2409 {
2410 /*
2411 ScenePresence avatar = m_scene.GetScenePresence(rootpart.AttachedAvatar);
2412 if (avatar != null)
2413 {
2414 Rotate the Av?
2415 } */
2416 }
2417 else
2418 {
2419 if (rootpart.PhysActor != null)
2420 { // APID must be implemented in your physics system for this to function.
2421 rootpart.PhysActor.APIDTarget = new Quaternion(target.X, target.Y, target.Z, target.W);
2422 rootpart.PhysActor.APIDStrength = strength;
2423 rootpart.PhysActor.APIDDamping = damping;
2424 rootpart.PhysActor.APIDActive = true;
2425 }
2426 }
2427 }
2428 }
2429
2430 public void stopLookAt()
2431 {
2432 SceneObjectPart rootpart = m_rootPart;
2433 if (rootpart != null)
2434 {
2435 if (rootpart.PhysActor != null)
2436 { // APID must be implemented in your physics system for this to function.
2437 rootpart.PhysActor.APIDActive = false;
2438 }
2439 }
2440
2441 }
2442
1708 /// <summary> 2443 /// <summary>
1709 /// Uses a PID to attempt to clamp the object on the Z axis at the given height over tau seconds. 2444 /// Uses a PID to attempt to clamp the object on the Z axis at the given height over tau seconds.
1710 /// </summary> 2445 /// </summary>
@@ -1721,7 +2456,7 @@ namespace OpenSim.Region.Framework.Scenes
1721 { 2456 {
1722 pa.PIDHoverHeight = height; 2457 pa.PIDHoverHeight = height;
1723 pa.PIDHoverType = hoverType; 2458 pa.PIDHoverType = hoverType;
1724 pa.PIDTau = tau; 2459 pa.PIDHoverTau = tau;
1725 pa.PIDHoverActive = true; 2460 pa.PIDHoverActive = true;
1726 } 2461 }
1727 else 2462 else
@@ -1761,7 +2496,12 @@ namespace OpenSim.Region.Framework.Scenes
1761 /// <param name="cGroupID"></param> 2496 /// <param name="cGroupID"></param>
1762 public SceneObjectPart CopyPart(SceneObjectPart part, UUID cAgentID, UUID cGroupID, bool userExposed) 2497 public SceneObjectPart CopyPart(SceneObjectPart part, UUID cAgentID, UUID cGroupID, bool userExposed)
1763 { 2498 {
1764 SceneObjectPart newPart = part.Copy(m_scene.AllocateLocalId(), OwnerID, GroupID, m_parts.Count, userExposed); 2499 // give new ID to the new part, letting old keep original
2500 // SceneObjectPart newPart = part.Copy(m_scene.AllocateLocalId(), OwnerID, GroupID, m_parts.Count, userExposed);
2501 SceneObjectPart newPart = part.Copy(part.LocalId, OwnerID, GroupID, m_parts.Count, userExposed);
2502 newPart.LocalId = m_scene.AllocateLocalId();
2503 newPart.SetParent(this);
2504
1765 AddPart(newPart); 2505 AddPart(newPart);
1766 2506
1767 SetPartAsNonRoot(newPart); 2507 SetPartAsNonRoot(newPart);
@@ -1811,6 +2551,7 @@ namespace OpenSim.Region.Framework.Scenes
1811 2551
1812 #endregion 2552 #endregion
1813 2553
2554
1814 public override void Update() 2555 public override void Update()
1815 { 2556 {
1816 // Check that the group was not deleted before the scheduled update 2557 // Check that the group was not deleted before the scheduled update
@@ -1829,19 +2570,8 @@ namespace OpenSim.Region.Framework.Scenes
1829 // check to see if the physical position or rotation warrant an update. 2570 // check to see if the physical position or rotation warrant an update.
1830 if (m_rootPart.UpdateFlag == UpdateRequired.NONE) 2571 if (m_rootPart.UpdateFlag == UpdateRequired.NONE)
1831 { 2572 {
1832 bool UsePhysics = ((RootPart.Flags & PrimFlags.Physics) != 0); 2573 // rootpart SendScheduledUpdates will check if a update is needed
1833 2574 m_rootPart.UpdateFlag = UpdateRequired.TERSE;
1834 if (UsePhysics && !AbsolutePosition.ApproxEquals(lastPhysGroupPos, 0.02f))
1835 {
1836 m_rootPart.UpdateFlag = UpdateRequired.TERSE;
1837 lastPhysGroupPos = AbsolutePosition;
1838 }
1839
1840 if (UsePhysics && !GroupRotation.ApproxEquals(lastPhysGroupRot, 0.1f))
1841 {
1842 m_rootPart.UpdateFlag = UpdateRequired.TERSE;
1843 lastPhysGroupRot = GroupRotation;
1844 }
1845 } 2575 }
1846 2576
1847 SceneObjectPart[] parts = m_parts.GetArray(); 2577 SceneObjectPart[] parts = m_parts.GetArray();
@@ -1900,11 +2630,11 @@ namespace OpenSim.Region.Framework.Scenes
1900 /// Immediately send a full update for this scene object. 2630 /// Immediately send a full update for this scene object.
1901 /// </summary> 2631 /// </summary>
1902 public void SendGroupFullUpdate() 2632 public void SendGroupFullUpdate()
1903 { 2633 {
1904 if (IsDeleted) 2634 if (IsDeleted)
1905 return; 2635 return;
1906 2636
1907// m_log.DebugFormat("[SOG]: Sending immediate full group update for {0} {1}", Name, UUID); 2637// m_log.DebugFormat("[SOG]: Sending immediate full group update for {0} {1}", Name, UUID);
1908 2638
1909 RootPart.SendFullUpdateToAllClients(); 2639 RootPart.SendFullUpdateToAllClients();
1910 2640
@@ -2060,6 +2790,11 @@ namespace OpenSim.Region.Framework.Scenes
2060 // 'linkPart' == the root of the group being linked into this group 2790 // 'linkPart' == the root of the group being linked into this group
2061 SceneObjectPart linkPart = objectGroup.m_rootPart; 2791 SceneObjectPart linkPart = objectGroup.m_rootPart;
2062 2792
2793 if (m_rootPart.PhysActor != null)
2794 m_rootPart.PhysActor.Building = true;
2795 if (linkPart.PhysActor != null)
2796 linkPart.PhysActor.Building = true;
2797
2063 // physics flags from group to be applied to linked parts 2798 // physics flags from group to be applied to linked parts
2064 bool grpusephys = UsesPhysics; 2799 bool grpusephys = UsesPhysics;
2065 bool grptemporary = IsTemporary; 2800 bool grptemporary = IsTemporary;
@@ -2085,12 +2820,12 @@ namespace OpenSim.Region.Framework.Scenes
2085 Vector3 axPos = linkPart.OffsetPosition; 2820 Vector3 axPos = linkPart.OffsetPosition;
2086 // Rotate the linking root SOP's position to be relative to the new root prim 2821 // Rotate the linking root SOP's position to be relative to the new root prim
2087 Quaternion parentRot = m_rootPart.RotationOffset; 2822 Quaternion parentRot = m_rootPart.RotationOffset;
2088 axPos *= Quaternion.Inverse(parentRot); 2823 axPos *= Quaternion.Conjugate(parentRot);
2089 linkPart.OffsetPosition = axPos; 2824 linkPart.OffsetPosition = axPos;
2090 2825
2091 // Make the linking root SOP's rotation relative to the new root prim 2826 // Make the linking root SOP's rotation relative to the new root prim
2092 Quaternion oldRot = linkPart.RotationOffset; 2827 Quaternion oldRot = linkPart.RotationOffset;
2093 Quaternion newRot = Quaternion.Inverse(parentRot) * oldRot; 2828 Quaternion newRot = Quaternion.Conjugate(parentRot) * oldRot;
2094 linkPart.RotationOffset = newRot; 2829 linkPart.RotationOffset = newRot;
2095 2830
2096 // If there is only one SOP in a SOG, the LinkNum is zero. I.e., not a linkset. 2831 // If there is only one SOP in a SOG, the LinkNum is zero. I.e., not a linkset.
@@ -2124,7 +2859,7 @@ namespace OpenSim.Region.Framework.Scenes
2124 linkPart.CreateSelected = true; 2859 linkPart.CreateSelected = true;
2125 2860
2126 // let physics know preserve part volume dtc messy since UpdatePrimFlags doesn't look to parent changes for now 2861 // let physics know preserve part volume dtc messy since UpdatePrimFlags doesn't look to parent changes for now
2127 linkPart.UpdatePrimFlags(grpusephys, grptemporary, (IsPhantom || (linkPart.Flags & PrimFlags.Phantom) != 0), linkPart.VolumeDetectActive); 2862 linkPart.UpdatePrimFlags(grpusephys, grptemporary, (IsPhantom || (linkPart.Flags & PrimFlags.Phantom) != 0), linkPart.VolumeDetectActive, true);
2128 2863
2129 // If the added SOP is physical, also tell the physics engine about the link relationship. 2864 // If the added SOP is physical, also tell the physics engine about the link relationship.
2130 if (linkPart.PhysActor != null && m_rootPart.PhysActor != null && m_rootPart.PhysActor.IsPhysical) 2865 if (linkPart.PhysActor != null && m_rootPart.PhysActor != null && m_rootPart.PhysActor.IsPhysical)
@@ -2134,6 +2869,7 @@ namespace OpenSim.Region.Framework.Scenes
2134 } 2869 }
2135 2870
2136 linkPart.LinkNum = linkNum++; 2871 linkPart.LinkNum = linkNum++;
2872 linkPart.UpdatePrimFlags(UsesPhysics, IsTemporary, IsPhantom, IsVolumeDetect, false);
2137 2873
2138 // Get a list of the SOP's in the old group in order of their linknum's. 2874 // Get a list of the SOP's in the old group in order of their linknum's.
2139 SceneObjectPart[] ogParts = objectGroup.Parts; 2875 SceneObjectPart[] ogParts = objectGroup.Parts;
@@ -2152,7 +2888,7 @@ namespace OpenSim.Region.Framework.Scenes
2152 2888
2153 // Update the physics flags for the newly added SOP 2889 // Update the physics flags for the newly added SOP
2154 // (Is this necessary? LinkNonRootPart() has already called UpdatePrimFlags but with different flags!??) 2890 // (Is this necessary? LinkNonRootPart() has already called UpdatePrimFlags but with different flags!??)
2155 part.UpdatePrimFlags(grpusephys, grptemporary, (IsPhantom || (part.Flags & PrimFlags.Phantom) != 0), part.VolumeDetectActive); 2891 part.UpdatePrimFlags(grpusephys, grptemporary, (IsPhantom || (part.Flags & PrimFlags.Phantom) != 0), part.VolumeDetectActive, true);
2156 2892
2157 // If the added SOP is physical, also tell the physics engine about the link relationship. 2893 // If the added SOP is physical, also tell the physics engine about the link relationship.
2158 if (part.PhysActor != null && m_rootPart.PhysActor != null && m_rootPart.PhysActor.IsPhysical) 2894 if (part.PhysActor != null && m_rootPart.PhysActor != null && m_rootPart.PhysActor.IsPhysical)
@@ -2170,7 +2906,7 @@ namespace OpenSim.Region.Framework.Scenes
2170 objectGroup.IsDeleted = true; 2906 objectGroup.IsDeleted = true;
2171 2907
2172 objectGroup.m_parts.Clear(); 2908 objectGroup.m_parts.Clear();
2173 2909
2174 // Can't do this yet since backup still makes use of the root part without any synchronization 2910 // Can't do this yet since backup still makes use of the root part without any synchronization
2175// objectGroup.m_rootPart = null; 2911// objectGroup.m_rootPart = null;
2176 2912
@@ -2184,6 +2920,9 @@ namespace OpenSim.Region.Framework.Scenes
2184 // unmoved prims! 2920 // unmoved prims!
2185 ResetChildPrimPhysicsPositions(); 2921 ResetChildPrimPhysicsPositions();
2186 2922
2923 if (m_rootPart.PhysActor != null)
2924 m_rootPart.PhysActor.Building = false;
2925
2187 //HasGroupChanged = true; 2926 //HasGroupChanged = true;
2188 //ScheduleGroupForFullUpdate(); 2927 //ScheduleGroupForFullUpdate();
2189 } 2928 }
@@ -2251,7 +2990,10 @@ namespace OpenSim.Region.Framework.Scenes
2251// m_log.DebugFormat( 2990// m_log.DebugFormat(
2252// "[SCENE OBJECT GROUP]: Delinking part {0}, {1} from group with root part {2}, {3}", 2991// "[SCENE OBJECT GROUP]: Delinking part {0}, {1} from group with root part {2}, {3}",
2253// linkPart.Name, linkPart.UUID, RootPart.Name, RootPart.UUID); 2992// linkPart.Name, linkPart.UUID, RootPart.Name, RootPart.UUID);
2254 2993
2994 if (m_rootPart.PhysActor != null)
2995 m_rootPart.PhysActor.Building = true;
2996
2255 linkPart.ClearUndoState(); 2997 linkPart.ClearUndoState();
2256 2998
2257 Vector3 worldPos = linkPart.GetWorldPosition(); 2999 Vector3 worldPos = linkPart.GetWorldPosition();
@@ -2322,6 +3064,14 @@ namespace OpenSim.Region.Framework.Scenes
2322 3064
2323 // When we delete a group, we currently have to force persist to the database if the object id has changed 3065 // When we delete a group, we currently have to force persist to the database if the object id has changed
2324 // (since delete works by deleting all rows which have a given object id) 3066 // (since delete works by deleting all rows which have a given object id)
3067
3068 // this is as it seems to be in sl now
3069 if(linkPart.PhysicsShapeType == (byte)PhysShapeType.none)
3070 linkPart.PhysicsShapeType = linkPart.DefaultPhysicsShapeType(); // root prims can't have type none for now
3071
3072 if (m_rootPart.PhysActor != null)
3073 m_rootPart.PhysActor.Building = false;
3074
2325 objectGroup.HasGroupChangedDueToDelink = true; 3075 objectGroup.HasGroupChangedDueToDelink = true;
2326 3076
2327 return objectGroup; 3077 return objectGroup;
@@ -2333,6 +3083,8 @@ namespace OpenSim.Region.Framework.Scenes
2333 /// <param name="objectGroup"></param> 3083 /// <param name="objectGroup"></param>
2334 public virtual void DetachFromBackup() 3084 public virtual void DetachFromBackup()
2335 { 3085 {
3086 if (m_scene != null)
3087 m_scene.SceneGraph.FireDetachFromBackup(this);
2336 if (m_isBackedUp && Scene != null) 3088 if (m_isBackedUp && Scene != null)
2337 m_scene.EventManager.OnBackup -= ProcessBackup; 3089 m_scene.EventManager.OnBackup -= ProcessBackup;
2338 3090
@@ -2353,7 +3105,8 @@ namespace OpenSim.Region.Framework.Scenes
2353 Vector3 axPos = part.OffsetPosition; 3105 Vector3 axPos = part.OffsetPosition;
2354 axPos *= parentRot; 3106 axPos *= parentRot;
2355 part.OffsetPosition = axPos; 3107 part.OffsetPosition = axPos;
2356 part.GroupPosition = oldGroupPosition + part.OffsetPosition; 3108 Vector3 newPos = oldGroupPosition + part.OffsetPosition;
3109 part.GroupPosition = newPos;
2357 part.OffsetPosition = Vector3.Zero; 3110 part.OffsetPosition = Vector3.Zero;
2358 3111
2359 // Compution our rotation to be not relative to the old parent 3112 // Compution our rotation to be not relative to the old parent
@@ -2368,7 +3121,7 @@ namespace OpenSim.Region.Framework.Scenes
2368 part.LinkNum = linkNum; 3121 part.LinkNum = linkNum;
2369 3122
2370 // Compute the new position of this SOP relative to the group position 3123 // Compute the new position of this SOP relative to the group position
2371 part.OffsetPosition = part.GroupPosition - AbsolutePosition; 3124 part.OffsetPosition = newPos - AbsolutePosition;
2372 3125
2373 // (radams1 20120711: I don't know why part.OffsetPosition is set multiple times. 3126 // (radams1 20120711: I don't know why part.OffsetPosition is set multiple times.
2374 // It would have the affect of setting the physics engine position multiple 3127 // It would have the affect of setting the physics engine position multiple
@@ -2378,18 +3131,19 @@ namespace OpenSim.Region.Framework.Scenes
2378 // Rotate the relative position by the rotation of the group 3131 // Rotate the relative position by the rotation of the group
2379 Quaternion rootRotation = m_rootPart.RotationOffset; 3132 Quaternion rootRotation = m_rootPart.RotationOffset;
2380 Vector3 pos = part.OffsetPosition; 3133 Vector3 pos = part.OffsetPosition;
2381 pos *= Quaternion.Inverse(rootRotation); 3134 pos *= Quaternion.Conjugate(rootRotation);
2382 part.OffsetPosition = pos; 3135 part.OffsetPosition = pos;
2383 3136
2384 // Compute the SOP's rotation relative to the rotation of the group. 3137 // Compute the SOP's rotation relative to the rotation of the group.
2385 parentRot = m_rootPart.RotationOffset; 3138 parentRot = m_rootPart.RotationOffset;
2386 oldRot = part.RotationOffset; 3139 oldRot = part.RotationOffset;
2387 Quaternion newRot = Quaternion.Inverse(parentRot) * oldRot; 3140 Quaternion newRot = Quaternion.Conjugate(parentRot) * worldRot;
2388 part.RotationOffset = newRot; 3141 part.RotationOffset = newRot;
2389 3142
2390 // Since this SOP's state has changed, push those changes into the physics engine 3143 // Since this SOP's state has changed, push those changes into the physics engine
2391 // and the simulator. 3144 // and the simulator.
2392 part.UpdatePrimFlags(UsesPhysics, IsTemporary, IsPhantom, IsVolumeDetect); 3145 // done on caller
3146// part.UpdatePrimFlags(UsesPhysics, IsTemporary, IsPhantom, IsVolumeDetect, false);
2393 } 3147 }
2394 3148
2395 /// <summary> 3149 /// <summary>
@@ -2411,10 +3165,14 @@ namespace OpenSim.Region.Framework.Scenes
2411 { 3165 {
2412 if (!m_rootPart.BlockGrab) 3166 if (!m_rootPart.BlockGrab)
2413 { 3167 {
2414 Vector3 llmoveforce = pos - AbsolutePosition; 3168/* Vector3 llmoveforce = pos - AbsolutePosition;
2415 Vector3 grabforce = llmoveforce; 3169 Vector3 grabforce = llmoveforce;
2416 grabforce = (grabforce / 10) * pa.Mass; 3170 grabforce = (grabforce / 10) * pa.Mass;
2417 pa.AddForce(grabforce, true); 3171 */
3172 // empirically convert distance diference to a impulse
3173 Vector3 grabforce = pos - AbsolutePosition;
3174 grabforce = grabforce * (pa.Mass/ 10.0f);
3175 pa.AddForce(grabforce, false);
2418 m_scene.PhysicsScene.AddPhysicsActorTaint(pa); 3176 m_scene.PhysicsScene.AddPhysicsActorTaint(pa);
2419 } 3177 }
2420 } 3178 }
@@ -2610,6 +3368,8 @@ namespace OpenSim.Region.Framework.Scenes
2610 /// <param name="SetVolumeDetect"></param> 3368 /// <param name="SetVolumeDetect"></param>
2611 public void UpdatePrimFlags(uint localID, bool UsePhysics, bool SetTemporary, bool SetPhantom, bool SetVolumeDetect) 3369 public void UpdatePrimFlags(uint localID, bool UsePhysics, bool SetTemporary, bool SetPhantom, bool SetVolumeDetect)
2612 { 3370 {
3371 HasGroupChanged = true;
3372
2613 SceneObjectPart selectionPart = GetPart(localID); 3373 SceneObjectPart selectionPart = GetPart(localID);
2614 3374
2615 if (SetTemporary && Scene != null) 3375 if (SetTemporary && Scene != null)
@@ -2640,8 +3400,22 @@ namespace OpenSim.Region.Framework.Scenes
2640 } 3400 }
2641 } 3401 }
2642 3402
2643 for (int i = 0; i < parts.Length; i++) 3403 if (parts.Length > 1)
2644 parts[i].UpdatePrimFlags(UsePhysics, SetTemporary, SetPhantom, SetVolumeDetect); 3404 {
3405 m_rootPart.UpdatePrimFlags(UsePhysics, SetTemporary, SetPhantom, SetVolumeDetect, true);
3406
3407 for (int i = 0; i < parts.Length; i++)
3408 {
3409
3410 if (parts[i].UUID != m_rootPart.UUID)
3411 parts[i].UpdatePrimFlags(UsePhysics, SetTemporary, SetPhantom, SetVolumeDetect, true);
3412 }
3413
3414 if (m_rootPart.PhysActor != null)
3415 m_rootPart.PhysActor.Building = false;
3416 }
3417 else
3418 m_rootPart.UpdatePrimFlags(UsePhysics, SetTemporary, SetPhantom, SetVolumeDetect, false);
2645 } 3419 }
2646 } 3420 }
2647 3421
@@ -2654,6 +3428,17 @@ namespace OpenSim.Region.Framework.Scenes
2654 } 3428 }
2655 } 3429 }
2656 3430
3431
3432
3433 /// <summary>
3434 /// Gets the number of parts
3435 /// </summary>
3436 /// <returns></returns>
3437 public int GetPartCount()
3438 {
3439 return Parts.Count();
3440 }
3441
2657 /// <summary> 3442 /// <summary>
2658 /// Update the texture entry for this part 3443 /// Update the texture entry for this part
2659 /// </summary> 3444 /// </summary>
@@ -2670,11 +3455,20 @@ namespace OpenSim.Region.Framework.Scenes
2670 3455
2671 public void AdjustChildPrimPermissions() 3456 public void AdjustChildPrimPermissions()
2672 { 3457 {
3458 uint newOwnerMask = (uint)PermissionMask.All & 0xfffffff8; // Mask folded bits
3459 uint foldedPerms = RootPart.OwnerMask & 3;
3460
2673 ForEachPart(part => 3461 ForEachPart(part =>
2674 { 3462 {
3463 newOwnerMask &= part.BaseMask;
2675 if (part != RootPart) 3464 if (part != RootPart)
2676 part.ClonePermissions(RootPart); 3465 part.ClonePermissions(RootPart);
2677 }); 3466 });
3467
3468 uint lockMask = ~(uint)PermissionMask.Move;
3469 uint lockBit = RootPart.OwnerMask & (uint)PermissionMask.Move;
3470 RootPart.OwnerMask = (RootPart.OwnerMask & lockBit) | ((newOwnerMask | foldedPerms) & lockMask);
3471 RootPart.ScheduleFullUpdate();
2678 } 3472 }
2679 3473
2680 public void UpdatePermissions(UUID AgentID, byte field, uint localID, 3474 public void UpdatePermissions(UUID AgentID, byte field, uint localID,
@@ -2682,8 +3476,24 @@ namespace OpenSim.Region.Framework.Scenes
2682 { 3476 {
2683 RootPart.UpdatePermissions(AgentID, field, localID, mask, addRemTF); 3477 RootPart.UpdatePermissions(AgentID, field, localID, mask, addRemTF);
2684 3478
3479 bool god = Scene.Permissions.IsGod(AgentID);
3480
3481 if (field == 1 && god)
3482 {
3483 ForEachPart(part =>
3484 {
3485 part.BaseMask = RootPart.BaseMask;
3486 });
3487 }
3488
2685 AdjustChildPrimPermissions(); 3489 AdjustChildPrimPermissions();
2686 3490
3491 if (field == 1 && god) // Base mask was set. Update all child part inventories
3492 {
3493 foreach (SceneObjectPart part in Parts)
3494 part.Inventory.ApplyGodPermissions(RootPart.BaseMask);
3495 }
3496
2687 HasGroupChanged = true; 3497 HasGroupChanged = true;
2688 3498
2689 // Send the group's properties to all clients once all parts are updated 3499 // Send the group's properties to all clients once all parts are updated
@@ -2729,8 +3539,6 @@ namespace OpenSim.Region.Framework.Scenes
2729 3539
2730 PhysicsActor pa = m_rootPart.PhysActor; 3540 PhysicsActor pa = m_rootPart.PhysActor;
2731 3541
2732 RootPart.StoreUndoState(true);
2733
2734 if (Scene != null) 3542 if (Scene != null)
2735 { 3543 {
2736 scale.X = Math.Max(Scene.m_minNonphys, Math.Min(Scene.m_maxNonphys, scale.X)); 3544 scale.X = Math.Max(Scene.m_minNonphys, Math.Min(Scene.m_maxNonphys, scale.X));
@@ -2758,7 +3566,6 @@ namespace OpenSim.Region.Framework.Scenes
2758 SceneObjectPart obPart = parts[i]; 3566 SceneObjectPart obPart = parts[i];
2759 if (obPart.UUID != m_rootPart.UUID) 3567 if (obPart.UUID != m_rootPart.UUID)
2760 { 3568 {
2761// obPart.IgnoreUndoUpdate = true;
2762 Vector3 oldSize = new Vector3(obPart.Scale); 3569 Vector3 oldSize = new Vector3(obPart.Scale);
2763 3570
2764 float f = 1.0f; 3571 float f = 1.0f;
@@ -2870,8 +3677,6 @@ namespace OpenSim.Region.Framework.Scenes
2870 z *= a; 3677 z *= a;
2871 } 3678 }
2872 } 3679 }
2873
2874// obPart.IgnoreUndoUpdate = false;
2875 } 3680 }
2876 } 3681 }
2877 } 3682 }
@@ -2881,9 +3686,7 @@ namespace OpenSim.Region.Framework.Scenes
2881 prevScale.Y *= y; 3686 prevScale.Y *= y;
2882 prevScale.Z *= z; 3687 prevScale.Z *= z;
2883 3688
2884// RootPart.IgnoreUndoUpdate = true;
2885 RootPart.Resize(prevScale); 3689 RootPart.Resize(prevScale);
2886// RootPart.IgnoreUndoUpdate = false;
2887 3690
2888 for (int i = 0; i < parts.Length; i++) 3691 for (int i = 0; i < parts.Length; i++)
2889 { 3692 {
@@ -2891,8 +3694,6 @@ namespace OpenSim.Region.Framework.Scenes
2891 3694
2892 if (obPart.UUID != m_rootPart.UUID) 3695 if (obPart.UUID != m_rootPart.UUID)
2893 { 3696 {
2894 obPart.IgnoreUndoUpdate = true;
2895
2896 Vector3 currentpos = new Vector3(obPart.OffsetPosition); 3697 Vector3 currentpos = new Vector3(obPart.OffsetPosition);
2897 currentpos.X *= x; 3698 currentpos.X *= x;
2898 currentpos.Y *= y; 3699 currentpos.Y *= y;
@@ -2905,16 +3706,12 @@ namespace OpenSim.Region.Framework.Scenes
2905 3706
2906 obPart.Resize(newSize); 3707 obPart.Resize(newSize);
2907 obPart.UpdateOffSet(currentpos); 3708 obPart.UpdateOffSet(currentpos);
2908
2909 obPart.IgnoreUndoUpdate = false;
2910 } 3709 }
2911 3710
2912// obPart.IgnoreUndoUpdate = false; 3711 HasGroupChanged = true;
2913// obPart.StoreUndoState(); 3712 m_rootPart.TriggerScriptChangedEvent(Changed.SCALE);
3713 ScheduleGroupForTerseUpdate();
2914 } 3714 }
2915
2916// m_log.DebugFormat(
2917// "[SCENE OBJECT GROUP]: Finished group resizing {0} {1} to {2}", Name, LocalId, RootPart.Scale);
2918 } 3715 }
2919 3716
2920 #endregion 3717 #endregion
@@ -2927,14 +3724,6 @@ namespace OpenSim.Region.Framework.Scenes
2927 /// <param name="pos"></param> 3724 /// <param name="pos"></param>
2928 public void UpdateGroupPosition(Vector3 pos) 3725 public void UpdateGroupPosition(Vector3 pos)
2929 { 3726 {
2930// m_log.DebugFormat("[SCENE OBJECT GROUP]: Updating group position on {0} {1} to {2}", Name, LocalId, pos);
2931
2932 RootPart.StoreUndoState(true);
2933
2934// SceneObjectPart[] parts = m_parts.GetArray();
2935// for (int i = 0; i < parts.Length; i++)
2936// parts[i].StoreUndoState();
2937
2938 if (m_scene.EventManager.TriggerGroupMove(UUID, pos)) 3727 if (m_scene.EventManager.TriggerGroupMove(UUID, pos))
2939 { 3728 {
2940 if (IsAttachment) 3729 if (IsAttachment)
@@ -2967,21 +3756,17 @@ namespace OpenSim.Region.Framework.Scenes
2967 /// </summary> 3756 /// </summary>
2968 /// <param name="pos"></param> 3757 /// <param name="pos"></param>
2969 /// <param name="localID"></param> 3758 /// <param name="localID"></param>
3759 ///
3760
2970 public void UpdateSinglePosition(Vector3 pos, uint localID) 3761 public void UpdateSinglePosition(Vector3 pos, uint localID)
2971 { 3762 {
2972 SceneObjectPart part = GetPart(localID); 3763 SceneObjectPart part = GetPart(localID);
2973 3764
2974// SceneObjectPart[] parts = m_parts.GetArray();
2975// for (int i = 0; i < parts.Length; i++)
2976// parts[i].StoreUndoState();
2977
2978 if (part != null) 3765 if (part != null)
2979 { 3766 {
2980// m_log.DebugFormat( 3767// unlock parts position change
2981// "[SCENE OBJECT GROUP]: Updating single position of {0} {1} to {2}", part.Name, part.LocalId, pos); 3768 if (m_rootPart.PhysActor != null)
2982 3769 m_rootPart.PhysActor.Building = true;
2983 part.StoreUndoState(false);
2984 part.IgnoreUndoUpdate = true;
2985 3770
2986 if (part.UUID == m_rootPart.UUID) 3771 if (part.UUID == m_rootPart.UUID)
2987 { 3772 {
@@ -2992,8 +3777,10 @@ namespace OpenSim.Region.Framework.Scenes
2992 part.UpdateOffSet(pos); 3777 part.UpdateOffSet(pos);
2993 } 3778 }
2994 3779
3780 if (m_rootPart.PhysActor != null)
3781 m_rootPart.PhysActor.Building = false;
3782
2995 HasGroupChanged = true; 3783 HasGroupChanged = true;
2996 part.IgnoreUndoUpdate = false;
2997 } 3784 }
2998 } 3785 }
2999 3786
@@ -3003,13 +3790,7 @@ namespace OpenSim.Region.Framework.Scenes
3003 /// <param name="pos"></param> 3790 /// <param name="pos"></param>
3004 public void UpdateRootPosition(Vector3 pos) 3791 public void UpdateRootPosition(Vector3 pos)
3005 { 3792 {
3006// m_log.DebugFormat( 3793 // needs to be called with phys building true
3007// "[SCENE OBJECT GROUP]: Updating root position of {0} {1} to {2}", Name, LocalId, pos);
3008
3009// SceneObjectPart[] parts = m_parts.GetArray();
3010// for (int i = 0; i < parts.Length; i++)
3011// parts[i].StoreUndoState();
3012
3013 Vector3 newPos = new Vector3(pos.X, pos.Y, pos.Z); 3794 Vector3 newPos = new Vector3(pos.X, pos.Y, pos.Z);
3014 Vector3 oldPos = 3795 Vector3 oldPos =
3015 new Vector3(AbsolutePosition.X + m_rootPart.OffsetPosition.X, 3796 new Vector3(AbsolutePosition.X + m_rootPart.OffsetPosition.X,
@@ -3032,7 +3813,14 @@ namespace OpenSim.Region.Framework.Scenes
3032 AbsolutePosition = newPos; 3813 AbsolutePosition = newPos;
3033 3814
3034 HasGroupChanged = true; 3815 HasGroupChanged = true;
3035 ScheduleGroupForTerseUpdate(); 3816 if (m_rootPart.Undoing)
3817 {
3818 ScheduleGroupForFullUpdate();
3819 }
3820 else
3821 {
3822 ScheduleGroupForTerseUpdate();
3823 }
3036 } 3824 }
3037 3825
3038 #endregion 3826 #endregion
@@ -3045,24 +3833,16 @@ namespace OpenSim.Region.Framework.Scenes
3045 /// <param name="rot"></param> 3833 /// <param name="rot"></param>
3046 public void UpdateGroupRotationR(Quaternion rot) 3834 public void UpdateGroupRotationR(Quaternion rot)
3047 { 3835 {
3048// m_log.DebugFormat(
3049// "[SCENE OBJECT GROUP]: Updating group rotation R of {0} {1} to {2}", Name, LocalId, rot);
3050
3051// SceneObjectPart[] parts = m_parts.GetArray();
3052// for (int i = 0; i < parts.Length; i++)
3053// parts[i].StoreUndoState();
3054
3055 m_rootPart.StoreUndoState(true);
3056
3057 m_rootPart.UpdateRotation(rot); 3836 m_rootPart.UpdateRotation(rot);
3058 3837
3838/* this is done by rootpart RotationOffset set called by UpdateRotation
3059 PhysicsActor actor = m_rootPart.PhysActor; 3839 PhysicsActor actor = m_rootPart.PhysActor;
3060 if (actor != null) 3840 if (actor != null)
3061 { 3841 {
3062 actor.Orientation = m_rootPart.RotationOffset; 3842 actor.Orientation = m_rootPart.RotationOffset;
3063 m_scene.PhysicsScene.AddPhysicsActorTaint(actor); 3843 m_scene.PhysicsScene.AddPhysicsActorTaint(actor);
3064 } 3844 }
3065 3845*/
3066 HasGroupChanged = true; 3846 HasGroupChanged = true;
3067 ScheduleGroupForTerseUpdate(); 3847 ScheduleGroupForTerseUpdate();
3068 } 3848 }
@@ -3074,16 +3854,6 @@ namespace OpenSim.Region.Framework.Scenes
3074 /// <param name="rot"></param> 3854 /// <param name="rot"></param>
3075 public void UpdateGroupRotationPR(Vector3 pos, Quaternion rot) 3855 public void UpdateGroupRotationPR(Vector3 pos, Quaternion rot)
3076 { 3856 {
3077// m_log.DebugFormat(
3078// "[SCENE OBJECT GROUP]: Updating group rotation PR of {0} {1} to {2}", Name, LocalId, rot);
3079
3080// SceneObjectPart[] parts = m_parts.GetArray();
3081// for (int i = 0; i < parts.Length; i++)
3082// parts[i].StoreUndoState();
3083
3084 RootPart.StoreUndoState(true);
3085 RootPart.IgnoreUndoUpdate = true;
3086
3087 m_rootPart.UpdateRotation(rot); 3857 m_rootPart.UpdateRotation(rot);
3088 3858
3089 PhysicsActor actor = m_rootPart.PhysActor; 3859 PhysicsActor actor = m_rootPart.PhysActor;
@@ -3102,8 +3872,6 @@ namespace OpenSim.Region.Framework.Scenes
3102 3872
3103 HasGroupChanged = true; 3873 HasGroupChanged = true;
3104 ScheduleGroupForTerseUpdate(); 3874 ScheduleGroupForTerseUpdate();
3105
3106 RootPart.IgnoreUndoUpdate = false;
3107 } 3875 }
3108 3876
3109 /// <summary> 3877 /// <summary>
@@ -3116,13 +3884,11 @@ namespace OpenSim.Region.Framework.Scenes
3116 SceneObjectPart part = GetPart(localID); 3884 SceneObjectPart part = GetPart(localID);
3117 3885
3118 SceneObjectPart[] parts = m_parts.GetArray(); 3886 SceneObjectPart[] parts = m_parts.GetArray();
3119 for (int i = 0; i < parts.Length; i++)
3120 parts[i].StoreUndoState();
3121 3887
3122 if (part != null) 3888 if (part != null)
3123 { 3889 {
3124// m_log.DebugFormat( 3890 if (m_rootPart.PhysActor != null)
3125// "[SCENE OBJECT GROUP]: Updating single rotation of {0} {1} to {2}", part.Name, part.LocalId, rot); 3891 m_rootPart.PhysActor.Building = true;
3126 3892
3127 if (part.UUID == m_rootPart.UUID) 3893 if (part.UUID == m_rootPart.UUID)
3128 { 3894 {
@@ -3132,6 +3898,9 @@ namespace OpenSim.Region.Framework.Scenes
3132 { 3898 {
3133 part.UpdateRotation(rot); 3899 part.UpdateRotation(rot);
3134 } 3900 }
3901
3902 if (m_rootPart.PhysActor != null)
3903 m_rootPart.PhysActor.Building = false;
3135 } 3904 }
3136 } 3905 }
3137 3906
@@ -3145,12 +3914,8 @@ namespace OpenSim.Region.Framework.Scenes
3145 SceneObjectPart part = GetPart(localID); 3914 SceneObjectPart part = GetPart(localID);
3146 if (part != null) 3915 if (part != null)
3147 { 3916 {
3148// m_log.DebugFormat( 3917 if (m_rootPart.PhysActor != null)
3149// "[SCENE OBJECT GROUP]: Updating single position and rotation of {0} {1} to {2}", 3918 m_rootPart.PhysActor.Building = true;
3150// part.Name, part.LocalId, rot);
3151
3152 part.StoreUndoState();
3153 part.IgnoreUndoUpdate = true;
3154 3919
3155 if (part.UUID == m_rootPart.UUID) 3920 if (part.UUID == m_rootPart.UUID)
3156 { 3921 {
@@ -3163,7 +3928,8 @@ namespace OpenSim.Region.Framework.Scenes
3163 part.OffsetPosition = pos; 3928 part.OffsetPosition = pos;
3164 } 3929 }
3165 3930
3166 part.IgnoreUndoUpdate = false; 3931 if (m_rootPart.PhysActor != null)
3932 m_rootPart.PhysActor.Building = false;
3167 } 3933 }
3168 } 3934 }
3169 3935
@@ -3173,15 +3939,12 @@ namespace OpenSim.Region.Framework.Scenes
3173 /// <param name="rot"></param> 3939 /// <param name="rot"></param>
3174 public void UpdateRootRotation(Quaternion rot) 3940 public void UpdateRootRotation(Quaternion rot)
3175 { 3941 {
3176// m_log.DebugFormat( 3942 // needs to be called with phys building true
3177// "[SCENE OBJECT GROUP]: Updating root rotation of {0} {1} to {2}",
3178// Name, LocalId, rot);
3179
3180 Quaternion axRot = rot; 3943 Quaternion axRot = rot;
3181 Quaternion oldParentRot = m_rootPart.RotationOffset; 3944 Quaternion oldParentRot = m_rootPart.RotationOffset;
3182 3945
3183 m_rootPart.StoreUndoState(); 3946 //Don't use UpdateRotation because it schedules an update prematurely
3184 m_rootPart.UpdateRotation(rot); 3947 m_rootPart.RotationOffset = rot;
3185 3948
3186 PhysicsActor pa = m_rootPart.PhysActor; 3949 PhysicsActor pa = m_rootPart.PhysActor;
3187 3950
@@ -3197,35 +3960,145 @@ namespace OpenSim.Region.Framework.Scenes
3197 SceneObjectPart prim = parts[i]; 3960 SceneObjectPart prim = parts[i];
3198 if (prim.UUID != m_rootPart.UUID) 3961 if (prim.UUID != m_rootPart.UUID)
3199 { 3962 {
3200 prim.IgnoreUndoUpdate = true; 3963 Quaternion NewRot = oldParentRot * prim.RotationOffset;
3964 NewRot = Quaternion.Inverse(axRot) * NewRot;
3965 prim.RotationOffset = NewRot;
3966
3201 Vector3 axPos = prim.OffsetPosition; 3967 Vector3 axPos = prim.OffsetPosition;
3968
3202 axPos *= oldParentRot; 3969 axPos *= oldParentRot;
3203 axPos *= Quaternion.Inverse(axRot); 3970 axPos *= Quaternion.Inverse(axRot);
3204 prim.OffsetPosition = axPos; 3971 prim.OffsetPosition = axPos;
3205 Quaternion primsRot = prim.RotationOffset; 3972 }
3206 Quaternion newRot = oldParentRot * primsRot; 3973 }
3207 newRot = Quaternion.Inverse(axRot) * newRot;
3208 prim.RotationOffset = newRot;
3209 prim.ScheduleTerseUpdate();
3210 prim.IgnoreUndoUpdate = false;
3211 }
3212 }
3213
3214// for (int i = 0; i < parts.Length; i++)
3215// {
3216// SceneObjectPart childpart = parts[i];
3217// if (childpart != m_rootPart)
3218// {
3219//// childpart.IgnoreUndoUpdate = false;
3220//// childpart.StoreUndoState();
3221// }
3222// }
3223 3974
3224 m_rootPart.ScheduleTerseUpdate(); 3975 HasGroupChanged = true;
3976 ScheduleGroupForFullUpdate();
3977 }
3225 3978
3226// m_log.DebugFormat( 3979 private enum updatetype :int
3227// "[SCENE OBJECT GROUP]: Updated root rotation of {0} {1} to {2}", 3980 {
3228// Name, LocalId, rot); 3981 none = 0,
3982 partterse = 1,
3983 partfull = 2,
3984 groupterse = 3,
3985 groupfull = 4
3986 }
3987
3988 public void doChangeObject(SceneObjectPart part, ObjectChangeData data)
3989 {
3990 // TODO this still as excessive *.Schedule*Update()s
3991
3992 if (part != null && part.ParentGroup != null)
3993 {
3994 ObjectChangeType change = data.change;
3995 bool togroup = ((change & ObjectChangeType.Group) != 0);
3996 // bool uniform = ((what & ObjectChangeType.UniformScale) != 0); not in use
3997
3998 SceneObjectGroup group = part.ParentGroup;
3999 PhysicsActor pha = group.RootPart.PhysActor;
4000
4001 updatetype updateType = updatetype.none;
4002
4003 if (togroup)
4004 {
4005 // related to group
4006 if ((change & (ObjectChangeType.Rotation | ObjectChangeType.Position)) != 0)
4007 {
4008 if ((change & ObjectChangeType.Rotation) != 0)
4009 {
4010 group.RootPart.UpdateRotation(data.rotation);
4011 updateType = updatetype.none;
4012 }
4013 if ((change & ObjectChangeType.Position) != 0)
4014 {
4015 if (IsAttachment || m_scene.Permissions.CanObjectEntry(group.UUID, false, data.position))
4016 UpdateGroupPosition(data.position);
4017 updateType = updatetype.groupterse;
4018 }
4019 else
4020 // ugly rotation update of all parts
4021 {
4022 group.ResetChildPrimPhysicsPositions();
4023 }
4024
4025 }
4026 if ((change & ObjectChangeType.Scale) != 0)
4027 {
4028 if (pha != null)
4029 pha.Building = true;
4030
4031 group.GroupResize(data.scale);
4032 updateType = updatetype.none;
4033
4034 if (pha != null)
4035 pha.Building = false;
4036 }
4037 }
4038 else
4039 {
4040 // related to single prim in a link-set ( ie group)
4041 if (pha != null)
4042 pha.Building = true;
4043
4044 // root part is special
4045 // parts offset positions or rotations need to change also
4046
4047 if (part == group.RootPart)
4048 {
4049 if ((change & ObjectChangeType.Rotation) != 0)
4050 group.UpdateRootRotation(data.rotation);
4051 if ((change & ObjectChangeType.Position) != 0)
4052 group.UpdateRootPosition(data.position);
4053 if ((change & ObjectChangeType.Scale) != 0)
4054 part.Resize(data.scale);
4055 }
4056 else
4057 {
4058 if ((change & ObjectChangeType.Position) != 0)
4059 {
4060 part.OffsetPosition = data.position;
4061 updateType = updatetype.partterse;
4062 }
4063 if ((change & ObjectChangeType.Rotation) != 0)
4064 {
4065 part.UpdateRotation(data.rotation);
4066 updateType = updatetype.none;
4067 }
4068 if ((change & ObjectChangeType.Scale) != 0)
4069 {
4070 part.Resize(data.scale);
4071 updateType = updatetype.none;
4072 }
4073 }
4074
4075 if (pha != null)
4076 pha.Building = false;
4077 }
4078
4079 if (updateType != updatetype.none)
4080 {
4081 group.HasGroupChanged = true;
4082
4083 switch (updateType)
4084 {
4085 case updatetype.partterse:
4086 part.ScheduleTerseUpdate();
4087 break;
4088 case updatetype.partfull:
4089 part.ScheduleFullUpdate();
4090 break;
4091 case updatetype.groupterse:
4092 group.ScheduleGroupForTerseUpdate();
4093 break;
4094 case updatetype.groupfull:
4095 group.ScheduleGroupForFullUpdate();
4096 break;
4097 default:
4098 break;
4099 }
4100 }
4101 }
3229 } 4102 }
3230 4103
3231 #endregion 4104 #endregion
@@ -3324,10 +4197,11 @@ namespace OpenSim.Region.Framework.Scenes
3324 scriptPosTarget target = m_targets[idx]; 4197 scriptPosTarget target = m_targets[idx];
3325 if (Util.GetDistanceTo(target.targetPos, m_rootPart.GroupPosition) <= target.tolerance) 4198 if (Util.GetDistanceTo(target.targetPos, m_rootPart.GroupPosition) <= target.tolerance)
3326 { 4199 {
4200 at_target = true;
4201
3327 // trigger at_target 4202 // trigger at_target
3328 if (m_scriptListens_atTarget) 4203 if (m_scriptListens_atTarget)
3329 { 4204 {
3330 at_target = true;
3331 scriptPosTarget att = new scriptPosTarget(); 4205 scriptPosTarget att = new scriptPosTarget();
3332 att.targetPos = target.targetPos; 4206 att.targetPos = target.targetPos;
3333 att.tolerance = target.tolerance; 4207 att.tolerance = target.tolerance;
@@ -3445,11 +4319,50 @@ namespace OpenSim.Region.Framework.Scenes
3445 } 4319 }
3446 } 4320 }
3447 } 4321 }
3448 4322
4323 public Vector3 GetGeometricCenter()
4324 {
4325 // this is not real geometric center but a average of positions relative to root prim acording to
4326 // http://wiki.secondlife.com/wiki/llGetGeometricCenter
4327 // ignoring tortured prims details since sl also seems to ignore
4328 // so no real use in doing it on physics
4329
4330 Vector3 gc = Vector3.Zero;
4331
4332 int nparts = m_parts.Count;
4333 if (nparts <= 1)
4334 return gc;
4335
4336 SceneObjectPart[] parts = m_parts.GetArray();
4337 nparts = parts.Length; // just in case it changed
4338 if (nparts <= 1)
4339 return gc;
4340
4341 Quaternion parentRot = RootPart.RotationOffset;
4342 Vector3 pPos;
4343
4344 // average all parts positions
4345 for (int i = 0; i < nparts; i++)
4346 {
4347 // do it directly
4348 // gc += parts[i].GetWorldPosition();
4349 if (parts[i] != RootPart)
4350 {
4351 pPos = parts[i].OffsetPosition;
4352 gc += pPos;
4353 }
4354
4355 }
4356 gc /= nparts;
4357
4358 // relative to root:
4359// gc -= AbsolutePosition;
4360 return gc;
4361 }
4362
3449 public float GetMass() 4363 public float GetMass()
3450 { 4364 {
3451 float retmass = 0f; 4365 float retmass = 0f;
3452
3453 SceneObjectPart[] parts = m_parts.GetArray(); 4366 SceneObjectPart[] parts = m_parts.GetArray();
3454 for (int i = 0; i < parts.Length; i++) 4367 for (int i = 0; i < parts.Length; i++)
3455 retmass += parts[i].GetMass(); 4368 retmass += parts[i].GetMass();
@@ -3457,6 +4370,39 @@ namespace OpenSim.Region.Framework.Scenes
3457 return retmass; 4370 return retmass;
3458 } 4371 }
3459 4372
4373 // center of mass of full object
4374 public Vector3 GetCenterOfMass()
4375 {
4376 PhysicsActor pa = RootPart.PhysActor;
4377
4378 if(((RootPart.Flags & PrimFlags.Physics) !=0) && pa !=null)
4379 {
4380 // physics knows better about center of mass of physical prims
4381 Vector3 tmp = pa.CenterOfMass;
4382 return tmp;
4383 }
4384
4385 Vector3 Ptot = Vector3.Zero;
4386 float totmass = 0f;
4387 float m;
4388
4389 SceneObjectPart[] parts = m_parts.GetArray();
4390 for (int i = 0; i < parts.Length; i++)
4391 {
4392 m = parts[i].GetMass();
4393 Ptot += parts[i].GetPartCenterOfMass() * m;
4394 totmass += m;
4395 }
4396
4397 if (totmass == 0)
4398 totmass = 0;
4399 else
4400 totmass = 1 / totmass;
4401 Ptot *= totmass;
4402
4403 return Ptot;
4404 }
4405
3460 /// <summary> 4406 /// <summary>
3461 /// If the object is a sculpt/mesh, retrieve the mesh data for each part and reinsert it into each shape so that 4407 /// If the object is a sculpt/mesh, retrieve the mesh data for each part and reinsert it into each shape so that
3462 /// the physics engine can use it. 4408 /// the physics engine can use it.
@@ -3636,6 +4582,14 @@ namespace OpenSim.Region.Framework.Scenes
3636 FromItemID = uuid; 4582 FromItemID = uuid;
3637 } 4583 }
3638 4584
4585 public void ResetOwnerChangeFlag()
4586 {
4587 ForEachPart(delegate(SceneObjectPart part)
4588 {
4589 part.ResetOwnerChangeFlag();
4590 });
4591 }
4592
3639 #endregion 4593 #endregion
3640 } 4594 }
3641} 4595}
diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs b/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs
index e0ea344..d5d3dc1 100644
--- a/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs
@@ -62,7 +62,8 @@ namespace OpenSim.Region.Framework.Scenes
62 TELEPORT = 512, 62 TELEPORT = 512,
63 REGION_RESTART = 1024, 63 REGION_RESTART = 1024,
64 MEDIA = 2048, 64 MEDIA = 2048,
65 ANIMATION = 16384 65 ANIMATION = 16384,
66 POSITION = 32768
66 } 67 }
67 68
68 // I don't really know where to put this except here. 69 // I don't really know where to put this except here.
@@ -121,7 +122,18 @@ namespace OpenSim.Region.Framework.Scenes
121 /// Denote all sides of the prim 122 /// Denote all sides of the prim
122 /// </value> 123 /// </value>
123 public const int ALL_SIDES = -1; 124 public const int ALL_SIDES = -1;
124 125
126 private const scriptEvents PhysicsNeededSubsEvents = (
127 scriptEvents.collision | scriptEvents.collision_start | scriptEvents.collision_end |
128 scriptEvents.land_collision | scriptEvents.land_collision_start | scriptEvents.land_collision_end
129 );
130 private const scriptEvents PhyscicsPhantonSubsEvents = (
131 scriptEvents.land_collision | scriptEvents.land_collision_start | scriptEvents.land_collision_end
132 );
133 private const scriptEvents PhyscicsVolumeDtcSubsEvents = (
134 scriptEvents.collision_start | scriptEvents.collision_end
135 );
136
125 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); 137 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
126 138
127 /// <value> 139 /// <value>
@@ -132,7 +144,7 @@ namespace OpenSim.Region.Framework.Scenes
132 /// </remarks> 144 /// </remarks>
133 public bool IsRoot 145 public bool IsRoot
134 { 146 {
135 get { return ParentGroup.RootPart == this; } 147 get { return Object.ReferenceEquals(ParentGroup.RootPart, this); }
136 } 148 }
137 149
138 /// <summary> 150 /// <summary>
@@ -191,12 +203,25 @@ namespace OpenSim.Region.Framework.Scenes
191 203
192 public double SoundRadius; 204 public double SoundRadius;
193 205
206
194 public uint TimeStampFull; 207 public uint TimeStampFull;
195 208
196 public uint TimeStampLastActivity; // Will be used for AutoReturn 209 public uint TimeStampLastActivity; // Will be used for AutoReturn
197 210
198 public uint TimeStampTerse; 211 public uint TimeStampTerse;
199 212
213 // The following two are to hold the attachment data
214 // while an object is inworld
215 [XmlIgnore]
216 public byte AttachPoint = 0;
217
218 [XmlIgnore]
219 public Vector3 AttachOffset = Vector3.Zero;
220
221 [XmlIgnore]
222 public Quaternion AttachRotation = Quaternion.Identity;
223
224 [XmlIgnore]
200 public int STATUS_ROTATE_X; 225 public int STATUS_ROTATE_X;
201 226
202 public int STATUS_ROTATE_Y; 227 public int STATUS_ROTATE_Y;
@@ -223,8 +248,7 @@ namespace OpenSim.Region.Framework.Scenes
223 248
224 public Vector3 RotationAxis = Vector3.One; 249 public Vector3 RotationAxis = Vector3.One;
225 250
226 public bool VolumeDetectActive; // XmlIgnore set to avoid problems with persistance until I come to care for this 251 public bool VolumeDetectActive;
227 // Certainly this must be a persistant setting finally
228 252
229 public bool IsWaitingForFirstSpinUpdatePacket; 253 public bool IsWaitingForFirstSpinUpdatePacket;
230 254
@@ -264,10 +288,10 @@ namespace OpenSim.Region.Framework.Scenes
264 private Quaternion m_sitTargetOrientation = Quaternion.Identity; 288 private Quaternion m_sitTargetOrientation = Quaternion.Identity;
265 private Vector3 m_sitTargetPosition; 289 private Vector3 m_sitTargetPosition;
266 private string m_sitAnimation = "SIT"; 290 private string m_sitAnimation = "SIT";
291 private bool m_occupied; // KF if any av is sitting on this prim
267 private string m_text = String.Empty; 292 private string m_text = String.Empty;
268 private string m_touchName = String.Empty; 293 private string m_touchName = String.Empty;
269 private readonly List<UndoState> m_undo = new List<UndoState>(5); 294 private UndoRedoState m_UndoRedo = null;
270 private readonly List<UndoState> m_redo = new List<UndoState>(5);
271 295
272 private bool m_passTouches = false; 296 private bool m_passTouches = false;
273 private bool m_passCollisions = false; 297 private bool m_passCollisions = false;
@@ -295,8 +319,20 @@ namespace OpenSim.Region.Framework.Scenes
295 protected Vector3 m_lastVelocity; 319 protected Vector3 m_lastVelocity;
296 protected Vector3 m_lastAcceleration; 320 protected Vector3 m_lastAcceleration;
297 protected Vector3 m_lastAngularVelocity; 321 protected Vector3 m_lastAngularVelocity;
298 protected int m_lastTerseSent; 322 protected int m_lastUpdateSentTime;
299 323 protected float m_buoyancy = 0.0f;
324 protected Vector3 m_force;
325 protected Vector3 m_torque;
326
327 protected byte m_physicsShapeType = (byte)PhysShapeType.prim;
328 protected float m_density = 1000.0f; // in kg/m^3
329 protected float m_gravitymod = 1.0f;
330 protected float m_friction = 0.6f; // wood
331 protected float m_bounce = 0.5f; // wood
332
333
334 protected bool m_isSelected = false;
335
300 /// <summary> 336 /// <summary>
301 /// Stores media texture data 337 /// Stores media texture data
302 /// </summary> 338 /// </summary>
@@ -308,10 +344,25 @@ namespace OpenSim.Region.Framework.Scenes
308 private Vector3 m_cameraAtOffset; 344 private Vector3 m_cameraAtOffset;
309 private bool m_forceMouselook; 345 private bool m_forceMouselook;
310 346
311 // TODO: Collision sound should have default. 347
348 // 0 for default collision sounds, -1 for script disabled sound 1 for script defined sound
349 private sbyte m_collisionSoundType;
312 private UUID m_collisionSound; 350 private UUID m_collisionSound;
313 private float m_collisionSoundVolume; 351 private float m_collisionSoundVolume;
314 352
353 private int LastColSoundSentTime;
354
355
356 private SOPVehicle m_vehicleParams = null;
357
358 private KeyframeMotion m_keyframeMotion = null;
359
360 public KeyframeMotion KeyframeMotion
361 {
362 get; set;
363 }
364
365
315 #endregion Fields 366 #endregion Fields
316 367
317// ~SceneObjectPart() 368// ~SceneObjectPart()
@@ -340,6 +391,7 @@ namespace OpenSim.Region.Framework.Scenes
340 // this appears to have the same UUID (!) as the prim. If this isn't the case, one can't drag items from 391 // this appears to have the same UUID (!) as the prim. If this isn't the case, one can't drag items from
341 // the prim into an agent inventory (Linden client reports that the "Object not found for drop" in its log 392 // the prim into an agent inventory (Linden client reports that the "Object not found for drop" in its log
342 m_inventory = new SceneObjectPartInventory(this); 393 m_inventory = new SceneObjectPartInventory(this);
394 LastColSoundSentTime = Util.EnvironmentTickCount();
343 } 395 }
344 396
345 /// <summary> 397 /// <summary>
@@ -354,7 +406,7 @@ namespace OpenSim.Region.Framework.Scenes
354 UUID ownerID, PrimitiveBaseShape shape, Vector3 groupPosition, 406 UUID ownerID, PrimitiveBaseShape shape, Vector3 groupPosition,
355 Quaternion rotationOffset, Vector3 offsetPosition) : this() 407 Quaternion rotationOffset, Vector3 offsetPosition) : this()
356 { 408 {
357 m_name = "Primitive"; 409 m_name = "Object";
358 410
359 CreationDate = (int)Utils.DateTimeToUnixTime(Rezzed); 411 CreationDate = (int)Utils.DateTimeToUnixTime(Rezzed);
360 LastOwnerID = CreatorID = OwnerID = ownerID; 412 LastOwnerID = CreatorID = OwnerID = ownerID;
@@ -393,7 +445,7 @@ namespace OpenSim.Region.Framework.Scenes
393 private uint _ownerMask = (uint)PermissionMask.All; 445 private uint _ownerMask = (uint)PermissionMask.All;
394 private uint _groupMask = (uint)PermissionMask.None; 446 private uint _groupMask = (uint)PermissionMask.None;
395 private uint _everyoneMask = (uint)PermissionMask.None; 447 private uint _everyoneMask = (uint)PermissionMask.None;
396 private uint _nextOwnerMask = (uint)PermissionMask.All; 448 private uint _nextOwnerMask = (uint)(PermissionMask.Move | PermissionMask.Modify | PermissionMask.Transfer);
397 private PrimFlags _flags = PrimFlags.None; 449 private PrimFlags _flags = PrimFlags.None;
398 private DateTime m_expires; 450 private DateTime m_expires;
399 private DateTime m_rezzed; 451 private DateTime m_rezzed;
@@ -487,12 +539,16 @@ namespace OpenSim.Region.Framework.Scenes
487 } 539 }
488 540
489 /// <value> 541 /// <value>
490 /// Access should be via Inventory directly - this property temporarily remains for xml serialization purposes 542 /// Get the inventory list
491 /// </value> 543 /// </value>
492 public TaskInventoryDictionary TaskInventory 544 public TaskInventoryDictionary TaskInventory
493 { 545 {
494 get { return m_inventory.Items; } 546 get {
495 set { m_inventory.Items = value; } 547 return m_inventory.Items;
548 }
549 set {
550 m_inventory.Items = value;
551 }
496 } 552 }
497 553
498 /// <summary> 554 /// <summary>
@@ -542,20 +598,6 @@ namespace OpenSim.Region.Framework.Scenes
542 } 598 }
543 } 599 }
544 600
545 public byte Material
546 {
547 get { return (byte) m_material; }
548 set
549 {
550 m_material = (Material)value;
551
552 PhysicsActor pa = PhysActor;
553
554 if (pa != null)
555 pa.SetMaterial((int)value);
556 }
557 }
558
559 [XmlIgnore] 601 [XmlIgnore]
560 public bool PassTouches 602 public bool PassTouches
561 { 603 {
@@ -581,6 +623,18 @@ namespace OpenSim.Region.Framework.Scenes
581 } 623 }
582 } 624 }
583 625
626 public bool IsSelected
627 {
628 get { return m_isSelected; }
629 set
630 {
631 m_isSelected = value;
632 if (ParentGroup != null)
633 ParentGroup.PartSelectChanged(value);
634 }
635 }
636
637
584 public Dictionary<int, string> CollisionFilter 638 public Dictionary<int, string> CollisionFilter
585 { 639 {
586 get { return m_CollisionFilter; } 640 get { return m_CollisionFilter; }
@@ -649,14 +703,12 @@ namespace OpenSim.Region.Framework.Scenes
649 set { m_LoopSoundSlavePrims = value; } 703 set { m_LoopSoundSlavePrims = value; }
650 } 704 }
651 705
652
653 public Byte[] TextureAnimation 706 public Byte[] TextureAnimation
654 { 707 {
655 get { return m_TextureAnimation; } 708 get { return m_TextureAnimation; }
656 set { m_TextureAnimation = value; } 709 set { m_TextureAnimation = value; }
657 } 710 }
658 711
659
660 public Byte[] ParticleSystem 712 public Byte[] ParticleSystem
661 { 713 {
662 get { return m_particleSystem; } 714 get { return m_particleSystem; }
@@ -693,9 +745,12 @@ namespace OpenSim.Region.Framework.Scenes
693 { 745 {
694 // If this is a linkset, we don't want the physics engine mucking up our group position here. 746 // If this is a linkset, we don't want the physics engine mucking up our group position here.
695 PhysicsActor actor = PhysActor; 747 PhysicsActor actor = PhysActor;
696 // If physical and the root prim of a linkset, the position of the group is what physics thinks. 748 if (ParentID == 0)
697 if (actor != null && ParentID == 0) 749 {
698 m_groupPosition = actor.Position; 750 if (actor != null)
751 m_groupPosition = actor.Position;
752 return m_groupPosition;
753 }
699 754
700 // If I'm an attachment, my position is reported as the position of who I'm attached to 755 // If I'm an attachment, my position is reported as the position of who I'm attached to
701 if (ParentGroup.IsAttachment) 756 if (ParentGroup.IsAttachment)
@@ -705,14 +760,16 @@ namespace OpenSim.Region.Framework.Scenes
705 return sp.AbsolutePosition; 760 return sp.AbsolutePosition;
706 } 761 }
707 762
763 // use root prim's group position. Physics may have updated it
764 if (ParentGroup.RootPart != this)
765 m_groupPosition = ParentGroup.RootPart.GroupPosition;
708 return m_groupPosition; 766 return m_groupPosition;
709 } 767 }
710 set 768 set
711 { 769 {
712 m_groupPosition = value; 770 m_groupPosition = value;
713
714 PhysicsActor actor = PhysActor; 771 PhysicsActor actor = PhysActor;
715 if (actor != null) 772 if (actor != null && ParentGroup.Scene.PhysicsScene != null)
716 { 773 {
717 try 774 try
718 { 775 {
@@ -736,16 +793,6 @@ namespace OpenSim.Region.Framework.Scenes
736 m_log.ErrorFormat("[SCENEOBJECTPART]: GROUP POSITION. {0}", e); 793 m_log.ErrorFormat("[SCENEOBJECTPART]: GROUP POSITION. {0}", e);
737 } 794 }
738 } 795 }
739
740 // TODO if we decide to do sitting in a more SL compatible way (multiple avatars per prim), this has to be fixed, too
741 if (SitTargetAvatar != UUID.Zero)
742 {
743 ScenePresence avatar;
744 if (ParentGroup.Scene.TryGetScenePresence(SitTargetAvatar, out avatar))
745 {
746 avatar.ParentPosition = GetWorldPosition();
747 }
748 }
749 } 796 }
750 } 797 }
751 798
@@ -754,7 +801,7 @@ namespace OpenSim.Region.Framework.Scenes
754 get { return m_offsetPosition; } 801 get { return m_offsetPosition; }
755 set 802 set
756 { 803 {
757// StoreUndoState(); 804 Vector3 oldpos = m_offsetPosition;
758 m_offsetPosition = value; 805 m_offsetPosition = value;
759 806
760 if (ParentGroup != null && !ParentGroup.IsDeleted) 807 if (ParentGroup != null && !ParentGroup.IsDeleted)
@@ -766,10 +813,25 @@ namespace OpenSim.Region.Framework.Scenes
766 actor.Orientation = GetWorldRotation(); 813 actor.Orientation = GetWorldRotation();
767 814
768 // Tell the physics engines that this prim changed. 815 // Tell the physics engines that this prim changed.
769 if (ParentGroup.Scene != null) 816 if (ParentGroup.Scene != null && ParentGroup.Scene.PhysicsScene != null)
770 ParentGroup.Scene.PhysicsScene.AddPhysicsActorTaint(actor); 817 ParentGroup.Scene.PhysicsScene.AddPhysicsActorTaint(actor);
771 } 818 }
819
820 if (!m_parentGroup.m_dupeInProgress)
821 {
822 List<ScenePresence> avs = ParentGroup.GetLinkedAvatars();
823 foreach (ScenePresence av in avs)
824 {
825 if (av.ParentID == m_localId)
826 {
827 Vector3 offset = (m_offsetPosition - oldpos);
828 av.AbsolutePosition += offset;
829 av.SendAvatarDataToAllAgents();
830 }
831 }
832 }
772 } 833 }
834 TriggerScriptChangedEvent(Changed.POSITION);
773 } 835 }
774 } 836 }
775 837
@@ -820,7 +882,7 @@ namespace OpenSim.Region.Framework.Scenes
820 882
821 set 883 set
822 { 884 {
823 StoreUndoState(); 885// StoreUndoState();
824 m_rotationOffset = value; 886 m_rotationOffset = value;
825 887
826 PhysicsActor actor = PhysActor; 888 PhysicsActor actor = PhysActor;
@@ -908,19 +970,36 @@ namespace OpenSim.Region.Framework.Scenes
908 get 970 get
909 { 971 {
910 PhysicsActor actor = PhysActor; 972 PhysicsActor actor = PhysActor;
911 if ((actor != null) && actor.IsPhysical) 973 if ((actor != null) && actor.IsPhysical && ParentGroup.RootPart == this)
912 { 974 {
913 m_angularVelocity = actor.RotationalVelocity; 975 m_angularVelocity = actor.RotationalVelocity;
914 } 976 }
915 return m_angularVelocity; 977 return m_angularVelocity;
916 } 978 }
917 set { m_angularVelocity = value; } 979 set
980 {
981 m_angularVelocity = value;
982 PhysicsActor actor = PhysActor;
983 if ((actor != null) && actor.IsPhysical && ParentGroup.RootPart == this && VehicleType == (int)Vehicle.TYPE_NONE)
984 {
985 actor.RotationalVelocity = m_angularVelocity;
986 }
987 }
918 } 988 }
919 989
920 /// <summary></summary> 990 /// <summary></summary>
921 public Vector3 Acceleration 991 public Vector3 Acceleration
922 { 992 {
923 get { return m_acceleration; } 993 get
994 {
995 PhysicsActor actor = PhysActor;
996 if (actor != null)
997 {
998 m_acceleration = actor.Acceleration;
999 }
1000 return m_acceleration;
1001 }
1002
924 set { m_acceleration = value; } 1003 set { m_acceleration = value; }
925 } 1004 }
926 1005
@@ -988,7 +1067,10 @@ namespace OpenSim.Region.Framework.Scenes
988 public PrimitiveBaseShape Shape 1067 public PrimitiveBaseShape Shape
989 { 1068 {
990 get { return m_shape; } 1069 get { return m_shape; }
991 set { m_shape = value;} 1070 set
1071 {
1072 m_shape = value;
1073 }
992 } 1074 }
993 1075
994 /// <summary> 1076 /// <summary>
@@ -1001,7 +1083,6 @@ namespace OpenSim.Region.Framework.Scenes
1001 { 1083 {
1002 if (m_shape != null) 1084 if (m_shape != null)
1003 { 1085 {
1004 StoreUndoState();
1005 1086
1006 m_shape.Scale = value; 1087 m_shape.Scale = value;
1007 1088
@@ -1028,6 +1109,7 @@ namespace OpenSim.Region.Framework.Scenes
1028 } 1109 }
1029 1110
1030 public UpdateRequired UpdateFlag { get; set; } 1111 public UpdateRequired UpdateFlag { get; set; }
1112 public bool UpdatePhysRequired { get; set; }
1031 1113
1032 /// <summary> 1114 /// <summary>
1033 /// Used for media on a prim. 1115 /// Used for media on a prim.
@@ -1068,10 +1150,7 @@ namespace OpenSim.Region.Framework.Scenes
1068 { 1150 {
1069 get 1151 get
1070 { 1152 {
1071 if (ParentGroup.IsAttachment) 1153 return GroupPosition + (m_offsetPosition * ParentGroup.RootPart.RotationOffset);
1072 return GroupPosition;
1073
1074 return m_offsetPosition + m_groupPosition;
1075 } 1154 }
1076 } 1155 }
1077 1156
@@ -1249,6 +1328,13 @@ namespace OpenSim.Region.Framework.Scenes
1249 _flags = value; 1328 _flags = value;
1250 } 1329 }
1251 } 1330 }
1331
1332 [XmlIgnore]
1333 public bool IsOccupied // KF If an av is sittingon this prim
1334 {
1335 get { return m_occupied; }
1336 set { m_occupied = value; }
1337 }
1252 1338
1253 /// <summary> 1339 /// <summary>
1254 /// ID of the avatar that is sat on us if we have a sit target. If there is no such avatar then is UUID.Zero 1340 /// ID of the avatar that is sat on us if we have a sit target. If there is no such avatar then is UUID.Zero
@@ -1299,12 +1385,41 @@ namespace OpenSim.Region.Framework.Scenes
1299 set { m_sitAnimation = value; } 1385 set { m_sitAnimation = value; }
1300 } 1386 }
1301 1387
1388 public UUID invalidCollisionSoundUUID = new UUID("ffffffff-ffff-ffff-ffff-ffffffffffff");
1389
1390 // 0 for default collision sounds, -1 for script disabled sound 1 for script defined sound
1391 // runtime thing.. do not persist
1392 [XmlIgnore]
1393 public sbyte CollisionSoundType
1394 {
1395 get
1396 {
1397 return m_collisionSoundType;
1398 }
1399 set
1400 {
1401 m_collisionSoundType = value;
1402 if (value == -1)
1403 m_collisionSound = invalidCollisionSoundUUID;
1404 else if (value == 0)
1405 m_collisionSound = UUID.Zero;
1406 }
1407 }
1408
1302 public UUID CollisionSound 1409 public UUID CollisionSound
1303 { 1410 {
1304 get { return m_collisionSound; } 1411 get { return m_collisionSound; }
1305 set 1412 set
1306 { 1413 {
1307 m_collisionSound = value; 1414 m_collisionSound = value;
1415
1416 if (value == invalidCollisionSoundUUID)
1417 m_collisionSoundType = -1;
1418 else if (value == UUID.Zero)
1419 m_collisionSoundType = 0;
1420 else
1421 m_collisionSoundType = 1;
1422
1308 aggregateScriptEvents(); 1423 aggregateScriptEvents();
1309 } 1424 }
1310 } 1425 }
@@ -1315,6 +1430,324 @@ namespace OpenSim.Region.Framework.Scenes
1315 set { m_collisionSoundVolume = value; } 1430 set { m_collisionSoundVolume = value; }
1316 } 1431 }
1317 1432
1433 public float Buoyancy
1434 {
1435 get
1436 {
1437 if (ParentGroup.RootPart == this)
1438 return m_buoyancy;
1439
1440 return ParentGroup.RootPart.Buoyancy;
1441 }
1442 set
1443 {
1444 if (ParentGroup != null && ParentGroup.RootPart != null && ParentGroup.RootPart != this)
1445 {
1446 ParentGroup.RootPart.Buoyancy = value;
1447 return;
1448 }
1449 m_buoyancy = value;
1450 if (PhysActor != null)
1451 PhysActor.Buoyancy = value;
1452 }
1453 }
1454
1455 public Vector3 Force
1456 {
1457 get
1458 {
1459 if (ParentGroup.RootPart == this)
1460 return m_force;
1461
1462 return ParentGroup.RootPart.Force;
1463 }
1464
1465 set
1466 {
1467 if (ParentGroup != null && ParentGroup.RootPart != null && ParentGroup.RootPart != this)
1468 {
1469 ParentGroup.RootPart.Force = value;
1470 return;
1471 }
1472 m_force = value;
1473 if (PhysActor != null)
1474 PhysActor.Force = value;
1475 }
1476 }
1477
1478 public Vector3 Torque
1479 {
1480 get
1481 {
1482 if (ParentGroup.RootPart == this)
1483 return m_torque;
1484
1485 return ParentGroup.RootPart.Torque;
1486 }
1487
1488 set
1489 {
1490 if (ParentGroup != null && ParentGroup.RootPart != null && ParentGroup.RootPart != this)
1491 {
1492 ParentGroup.RootPart.Torque = value;
1493 return;
1494 }
1495 m_torque = value;
1496 if (PhysActor != null)
1497 PhysActor.Torque = value;
1498 }
1499 }
1500
1501 public byte Material
1502 {
1503 get { return (byte)m_material; }
1504 set
1505 {
1506 if (value >= 0 && value <= (byte)SOPMaterialData.MaxMaterial)
1507 {
1508 bool update = false;
1509
1510 if (m_material != (Material)value)
1511 {
1512 update = true;
1513 m_material = (Material)value;
1514 }
1515
1516 if (m_friction != SOPMaterialData.friction(m_material))
1517 {
1518 update = true;
1519 m_friction = SOPMaterialData.friction(m_material);
1520 }
1521
1522 if (m_bounce != SOPMaterialData.bounce(m_material))
1523 {
1524 update = true;
1525 m_bounce = SOPMaterialData.bounce(m_material);
1526 }
1527
1528 if (update)
1529 {
1530 if (PhysActor != null)
1531 {
1532 PhysActor.SetMaterial((int)value);
1533 }
1534 if(ParentGroup != null)
1535 ParentGroup.HasGroupChanged = true;
1536 ScheduleFullUpdateIfNone();
1537 UpdatePhysRequired = true;
1538 }
1539 }
1540 }
1541 }
1542
1543 // not a propriety to move to methods place later
1544 private bool HasMesh()
1545 {
1546 if (Shape != null && (Shape.SculptType == (byte)SculptType.Mesh))
1547 return true;
1548 return false;
1549 }
1550
1551 // not a propriety to move to methods place later
1552 public byte DefaultPhysicsShapeType()
1553 {
1554 byte type;
1555
1556 if (Shape != null && (Shape.SculptType == (byte)SculptType.Mesh))
1557 type = (byte)PhysShapeType.convex;
1558 else
1559 type = (byte)PhysShapeType.prim;
1560
1561 return type;
1562 }
1563
1564 [XmlIgnore]
1565 public bool UsesComplexCost
1566 {
1567 get
1568 {
1569 byte pst = PhysicsShapeType;
1570 if(pst == (byte) PhysShapeType.none || pst == (byte) PhysShapeType.convex || HasMesh())
1571 return true;
1572 return false;
1573 }
1574 }
1575
1576 [XmlIgnore]
1577 public float PhysicsCost
1578 {
1579 get
1580 {
1581 if(PhysicsShapeType == (byte)PhysShapeType.none)
1582 return 0;
1583
1584 float cost = 0.1f;
1585 if (PhysActor != null)
1586 cost = PhysActor.PhysicsCost;
1587 else
1588 cost = 0.1f;
1589
1590 if ((Flags & PrimFlags.Physics) != 0)
1591 cost *= (1.0f + 0.01333f * Scale.LengthSquared()); // 0.01333 == 0.04/3
1592 return cost;
1593 }
1594 }
1595
1596 [XmlIgnore]
1597 public float StreamingCost
1598 {
1599 get
1600 {
1601 float cost;
1602 if (PhysActor != null)
1603 cost = PhysActor.StreamCost;
1604 else
1605 cost = 1.0f;
1606 return 1.0f;
1607 }
1608 }
1609
1610 [XmlIgnore]
1611 public float SimulationCost
1612 {
1613 get
1614 {
1615 // ignoring scripts. Don't like considering them for this
1616 if((Flags & PrimFlags.Physics) != 0)
1617 return 1.0f;
1618
1619 return 0.5f;
1620 }
1621 }
1622
1623 public byte PhysicsShapeType
1624 {
1625 get { return m_physicsShapeType; }
1626 set
1627 {
1628 byte oldv = m_physicsShapeType;
1629
1630 if (value >= 0 && value <= (byte)PhysShapeType.convex)
1631 {
1632 if (value == (byte)PhysShapeType.none && ParentGroup != null && ParentGroup.RootPart == this)
1633 m_physicsShapeType = DefaultPhysicsShapeType();
1634 else
1635 m_physicsShapeType = value;
1636 }
1637 else
1638 m_physicsShapeType = DefaultPhysicsShapeType();
1639
1640 if (m_physicsShapeType != oldv && ParentGroup != null)
1641 {
1642 if (m_physicsShapeType == (byte)PhysShapeType.none)
1643 {
1644 if (PhysActor != null)
1645 {
1646 Velocity = new Vector3(0, 0, 0);
1647 Acceleration = new Vector3(0, 0, 0);
1648 if (ParentGroup.RootPart == this)
1649 AngularVelocity = new Vector3(0, 0, 0);
1650 ParentGroup.Scene.RemovePhysicalPrim(1);
1651 RemoveFromPhysics();
1652 }
1653 }
1654 else if (PhysActor == null)
1655 {
1656 ApplyPhysics((uint)Flags, VolumeDetectActive, false);
1657 UpdatePhysicsSubscribedEvents();
1658 }
1659 else
1660 {
1661 PhysActor.PhysicsShapeType = m_physicsShapeType;
1662// if (Shape.SculptEntry)
1663// CheckSculptAndLoad();
1664 }
1665
1666 if (ParentGroup != null)
1667 ParentGroup.HasGroupChanged = true;
1668 }
1669
1670 if (m_physicsShapeType != value)
1671 {
1672 UpdatePhysRequired = true;
1673 }
1674 }
1675 }
1676
1677 public float Density // in kg/m^3
1678 {
1679 get { return m_density; }
1680 set
1681 {
1682 if (value >=1 && value <= 22587.0)
1683 {
1684 m_density = value;
1685 UpdatePhysRequired = true;
1686 }
1687
1688 ScheduleFullUpdateIfNone();
1689
1690 if (ParentGroup != null)
1691 ParentGroup.HasGroupChanged = true;
1692 }
1693 }
1694
1695 public float GravityModifier
1696 {
1697 get { return m_gravitymod; }
1698 set
1699 {
1700 if( value >= -1 && value <=28.0f)
1701 {
1702 m_gravitymod = value;
1703 UpdatePhysRequired = true;
1704 }
1705
1706 ScheduleFullUpdateIfNone();
1707
1708 if (ParentGroup != null)
1709 ParentGroup.HasGroupChanged = true;
1710
1711 }
1712 }
1713
1714 public float Friction
1715 {
1716 get { return m_friction; }
1717 set
1718 {
1719 if (value >= 0 && value <= 255.0f)
1720 {
1721 m_friction = value;
1722 UpdatePhysRequired = true;
1723 }
1724
1725 ScheduleFullUpdateIfNone();
1726
1727 if (ParentGroup != null)
1728 ParentGroup.HasGroupChanged = true;
1729 }
1730 }
1731
1732 public float Bounciness
1733 {
1734 get { return m_bounce; }
1735 set
1736 {
1737 if (value >= 0 && value <= 1.0f)
1738 {
1739 m_bounce = value;
1740 UpdatePhysRequired = true;
1741 }
1742
1743 ScheduleFullUpdateIfNone();
1744
1745 if (ParentGroup != null)
1746 ParentGroup.HasGroupChanged = true;
1747 }
1748 }
1749
1750
1318 #endregion Public Properties with only Get 1751 #endregion Public Properties with only Get
1319 1752
1320 private uint ApplyMask(uint val, bool set, uint mask) 1753 private uint ApplyMask(uint val, bool set, uint mask)
@@ -1460,6 +1893,61 @@ namespace OpenSim.Region.Framework.Scenes
1460 } 1893 }
1461 } 1894 }
1462 1895
1896 // SetVelocity for LSL llSetVelocity.. may need revision if having other uses in future
1897 public void SetVelocity(Vector3 pVel, bool localGlobalTF)
1898 {
1899 if (ParentGroup == null || ParentGroup.IsDeleted)
1900 return;
1901
1902 if (ParentGroup.IsAttachment)
1903 return; // don't work on attachments (for now ??)
1904
1905 SceneObjectPart root = ParentGroup.RootPart;
1906
1907 if (root.VehicleType != (int)Vehicle.TYPE_NONE) // don't mess with vehicles
1908 return;
1909
1910 PhysicsActor pa = root.PhysActor;
1911
1912 if (pa == null || !pa.IsPhysical)
1913 return;
1914
1915 if (localGlobalTF)
1916 {
1917 pVel = pVel * GetWorldRotation();
1918 }
1919
1920 ParentGroup.Velocity = pVel;
1921 }
1922
1923 // SetAngularVelocity for LSL llSetAngularVelocity.. may need revision if having other uses in future
1924 public void SetAngularVelocity(Vector3 pAngVel, bool localGlobalTF)
1925 {
1926 if (ParentGroup == null || ParentGroup.IsDeleted)
1927 return;
1928
1929 if (ParentGroup.IsAttachment)
1930 return; // don't work on attachments (for now ??)
1931
1932 SceneObjectPart root = ParentGroup.RootPart;
1933
1934 if (root.VehicleType != (int)Vehicle.TYPE_NONE) // don't mess with vehicles
1935 return;
1936
1937 PhysicsActor pa = root.PhysActor;
1938
1939 if (pa == null || !pa.IsPhysical)
1940 return;
1941
1942 if (localGlobalTF)
1943 {
1944 pAngVel = pAngVel * GetWorldRotation();
1945 }
1946
1947 root.AngularVelocity = pAngVel;
1948 }
1949
1950
1463 /// <summary> 1951 /// <summary>
1464 /// hook to the physics scene to apply angular impulse 1952 /// hook to the physics scene to apply angular impulse
1465 /// This is sent up to the group, which then finds the root prim 1953 /// This is sent up to the group, which then finds the root prim
@@ -1480,7 +1968,7 @@ namespace OpenSim.Region.Framework.Scenes
1480 impulse = newimpulse; 1968 impulse = newimpulse;
1481 } 1969 }
1482 1970
1483 ParentGroup.applyAngularImpulse(impulse); 1971 ParentGroup.ApplyAngularImpulse(impulse);
1484 } 1972 }
1485 1973
1486 /// <summary> 1974 /// <summary>
@@ -1490,20 +1978,24 @@ namespace OpenSim.Region.Framework.Scenes
1490 /// </summary> 1978 /// </summary>
1491 /// <param name="impulsei">Vector force</param> 1979 /// <param name="impulsei">Vector force</param>
1492 /// <param name="localGlobalTF">true for the local frame, false for the global frame</param> 1980 /// <param name="localGlobalTF">true for the local frame, false for the global frame</param>
1493 public void SetAngularImpulse(Vector3 impulsei, bool localGlobalTF) 1981
1982 // this is actualy Set Torque.. keeping naming so not to edit lslapi also
1983 public void SetAngularImpulse(Vector3 torquei, bool localGlobalTF)
1494 { 1984 {
1495 Vector3 impulse = impulsei; 1985 Vector3 torque = torquei;
1496 1986
1497 if (localGlobalTF) 1987 if (localGlobalTF)
1498 { 1988 {
1989/*
1499 Quaternion grot = GetWorldRotation(); 1990 Quaternion grot = GetWorldRotation();
1500 Quaternion AXgrot = grot; 1991 Quaternion AXgrot = grot;
1501 Vector3 AXimpulsei = impulsei; 1992 Vector3 AXimpulsei = impulsei;
1502 Vector3 newimpulse = AXimpulsei * AXgrot; 1993 Vector3 newimpulse = AXimpulsei * AXgrot;
1503 impulse = newimpulse; 1994 */
1995 torque *= GetWorldRotation();
1504 } 1996 }
1505 1997
1506 ParentGroup.setAngularImpulse(impulse); 1998 Torque = torque;
1507 } 1999 }
1508 2000
1509 /// <summary> 2001 /// <summary>
@@ -1511,17 +2003,23 @@ namespace OpenSim.Region.Framework.Scenes
1511 /// </summary> 2003 /// </summary>
1512 /// <param name="rootObjectFlags"></param> 2004 /// <param name="rootObjectFlags"></param>
1513 /// <param name="VolumeDetectActive"></param> 2005 /// <param name="VolumeDetectActive"></param>
1514 public void ApplyPhysics(uint rootObjectFlags, bool VolumeDetectActive) 2006 /// <param name="building"></param>
2007
2008 public void ApplyPhysics(uint _ObjectFlags, bool _VolumeDetectActive, bool building)
1515 { 2009 {
2010 VolumeDetectActive = _VolumeDetectActive;
2011
1516 if (!ParentGroup.Scene.CollidablePrims) 2012 if (!ParentGroup.Scene.CollidablePrims)
1517 return; 2013 return;
1518 2014
1519// m_log.DebugFormat( 2015 if (PhysicsShapeType == (byte)PhysShapeType.none)
1520// "[SCENE OBJECT PART]: Applying physics to {0} {1}, m_physicalPrim {2}", 2016 return;
1521// Name, LocalId, UUID, m_physicalPrim); 2017
2018 bool isPhysical = (_ObjectFlags & (uint) PrimFlags.Physics) != 0;
2019 bool isPhantom = (_ObjectFlags & (uint)PrimFlags.Phantom) != 0;
1522 2020
1523 bool isPhysical = (rootObjectFlags & (uint) PrimFlags.Physics) != 0; 2021 if (_VolumeDetectActive)
1524 bool isPhantom = (rootObjectFlags & (uint) PrimFlags.Phantom) != 0; 2022 isPhantom = true;
1525 2023
1526 if (IsJoint()) 2024 if (IsJoint())
1527 { 2025 {
@@ -1529,22 +2027,14 @@ namespace OpenSim.Region.Framework.Scenes
1529 } 2027 }
1530 else 2028 else
1531 { 2029 {
1532 // Special case for VolumeDetection: If VolumeDetection is set, the phantom flag is locally ignored 2030 if ((!isPhantom || isPhysical || _VolumeDetectActive) && !ParentGroup.IsAttachment
1533 if (VolumeDetectActive) 2031 && !(Shape.PathCurve == (byte)Extrusion.Flexible))
1534 isPhantom = false;
1535
1536 // The only time the physics scene shouldn't know about the prim is if it's phantom or an attachment, which is phantom by definition
1537 // or flexible
1538 if (!isPhantom && !ParentGroup.IsAttachment && !(Shape.PathCurve == (byte)Extrusion.Flexible))
1539 { 2032 {
1540 // Added clarification.. since A rigid body is an object that you can kick around, etc. 2033 AddToPhysics(isPhysical, isPhantom, building, isPhysical);
1541 bool rigidBody = isPhysical && !isPhantom; 2034 UpdatePhysicsSubscribedEvents(); // not sure if appliable here
1542
1543 PhysicsActor pa = AddToPhysics(rigidBody);
1544
1545 if (pa != null)
1546 pa.SetVolumeDetect(VolumeDetectActive ? 1 : 0);
1547 } 2035 }
2036 else
2037 PhysActor = null; // just to be sure
1548 } 2038 }
1549 } 2039 }
1550 2040
@@ -1596,6 +2086,12 @@ namespace OpenSim.Region.Framework.Scenes
1596 dupe.Category = Category; 2086 dupe.Category = Category;
1597 dupe.m_rezzed = m_rezzed; 2087 dupe.m_rezzed = m_rezzed;
1598 2088
2089 dupe.m_UndoRedo = null;
2090 dupe.m_isSelected = false;
2091
2092 dupe.IgnoreUndoUpdate = false;
2093 dupe.Undoing = false;
2094
1599 dupe.m_inventory = new SceneObjectPartInventory(dupe); 2095 dupe.m_inventory = new SceneObjectPartInventory(dupe);
1600 dupe.m_inventory.Items = (TaskInventoryDictionary)m_inventory.Items.Clone(); 2096 dupe.m_inventory.Items = (TaskInventoryDictionary)m_inventory.Items.Clone();
1601 2097
@@ -1611,6 +2107,7 @@ namespace OpenSim.Region.Framework.Scenes
1611 2107
1612 // Move afterwards ResetIDs as it clears the localID 2108 // Move afterwards ResetIDs as it clears the localID
1613 dupe.LocalId = localID; 2109 dupe.LocalId = localID;
2110
1614 // This may be wrong... it might have to be applied in SceneObjectGroup to the object that's being duplicated. 2111 // This may be wrong... it might have to be applied in SceneObjectGroup to the object that's being duplicated.
1615 dupe.LastOwnerID = OwnerID; 2112 dupe.LastOwnerID = OwnerID;
1616 2113
@@ -1618,6 +2115,9 @@ namespace OpenSim.Region.Framework.Scenes
1618 Array.Copy(Shape.ExtraParams, extraP, extraP.Length); 2115 Array.Copy(Shape.ExtraParams, extraP, extraP.Length);
1619 dupe.Shape.ExtraParams = extraP; 2116 dupe.Shape.ExtraParams = extraP;
1620 2117
2118 // safeguard actual copy is done in sog.copy
2119 dupe.KeyframeMotion = null;
2120
1621 if (userExposed) 2121 if (userExposed)
1622 { 2122 {
1623/* 2123/*
@@ -1629,8 +2129,12 @@ namespace OpenSim.Region.Framework.Scenes
1629*/ 2129*/
1630 bool UsePhysics = ((dupe.Flags & PrimFlags.Physics) != 0); 2130 bool UsePhysics = ((dupe.Flags & PrimFlags.Physics) != 0);
1631 dupe.DoPhysicsPropertyUpdate(UsePhysics, true); 2131 dupe.DoPhysicsPropertyUpdate(UsePhysics, true);
2132// dupe.UpdatePhysicsSubscribedEvents(); // not sure...
1632 } 2133 }
1633 2134
2135 if (dupe.PhysActor != null)
2136 dupe.PhysActor.LocalID = localID;
2137
1634 ParentGroup.Scene.EventManager.TriggerOnSceneObjectPartCopy(dupe, this, userExposed); 2138 ParentGroup.Scene.EventManager.TriggerOnSceneObjectPartCopy(dupe, this, userExposed);
1635 2139
1636// m_log.DebugFormat("[SCENE OBJECT PART]: Clone of {0} {1} finished", Name, UUID); 2140// m_log.DebugFormat("[SCENE OBJECT PART]: Clone of {0} {1} finished", Name, UUID);
@@ -1649,10 +2153,10 @@ namespace OpenSim.Region.Framework.Scenes
1649 { 2153 {
1650 if (asset != null) 2154 if (asset != null)
1651 SculptTextureCallback(asset); 2155 SculptTextureCallback(asset);
1652 else 2156// else
1653 m_log.WarnFormat( 2157// m_log.WarnFormat(
1654 "[SCENE OBJECT PART]: Part {0} {1} requested mesh/sculpt data for asset id {2} from asset service but received no data", 2158// "[SCENE OBJECT PART]: Part {0} {1} requested mesh/sculpt data for asset id {2} from asset service but received no data",
1655 Name, UUID, id); 2159// Name, UUID, id);
1656 } 2160 }
1657*/ 2161*/
1658 /// <summary> 2162 /// <summary>
@@ -1751,6 +2255,7 @@ namespace OpenSim.Region.Framework.Scenes
1751 2255
1752 /// <summary> 2256 /// <summary>
1753 /// Do a physics propery update for this part. 2257 /// Do a physics propery update for this part.
2258 /// now also updates phantom and volume detector
1754 /// </summary> 2259 /// </summary>
1755 /// <param name="UsePhysics"></param> 2260 /// <param name="UsePhysics"></param>
1756 /// <param name="isNew"></param> 2261 /// <param name="isNew"></param>
@@ -1776,61 +2281,69 @@ namespace OpenSim.Region.Framework.Scenes
1776 { 2281 {
1777 if (pa.IsPhysical) // implies UsePhysics==false for this block 2282 if (pa.IsPhysical) // implies UsePhysics==false for this block
1778 { 2283 {
1779 if (!isNew) 2284 if (!isNew) // implies UsePhysics==false for this block
2285 {
1780 ParentGroup.Scene.RemovePhysicalPrim(1); 2286 ParentGroup.Scene.RemovePhysicalPrim(1);
1781 2287
1782 pa.OnRequestTerseUpdate -= PhysicsRequestingTerseUpdate; 2288 Velocity = new Vector3(0, 0, 0);
1783 pa.OnOutOfBounds -= PhysicsOutOfBounds; 2289 Acceleration = new Vector3(0, 0, 0);
1784 pa.delink(); 2290 if (ParentGroup.RootPart == this)
2291 AngularVelocity = new Vector3(0, 0, 0);
1785 2292
1786 if (ParentGroup.Scene.PhysicsScene.SupportsNINJAJoints && (!isNew)) 2293 if (pa.Phantom && !VolumeDetectActive)
1787 { 2294 {
1788 // destroy all joints connected to this now deactivated body 2295 RemoveFromPhysics();
1789 ParentGroup.Scene.PhysicsScene.RemoveAllJointsConnectedToActorThreadLocked(pa); 2296 return;
1790 } 2297 }
1791 2298
1792 // stop client-side interpolation of all joint proxy objects that have just been deleted 2299 pa.IsPhysical = UsePhysics;
1793 // this is done because RemoveAllJointsConnectedToActor invokes the OnJointDeactivated callback, 2300 pa.OnRequestTerseUpdate -= PhysicsRequestingTerseUpdate;
1794 // which stops client-side interpolation of deactivated joint proxy objects. 2301 pa.OnOutOfBounds -= PhysicsOutOfBounds;
2302 pa.delink();
2303 if (ParentGroup.Scene.PhysicsScene.SupportsNINJAJoints)
2304 {
2305 // destroy all joints connected to this now deactivated body
2306 ParentGroup.Scene.PhysicsScene.RemoveAllJointsConnectedToActorThreadLocked(pa);
2307 }
2308 }
1795 } 2309 }
1796 2310
1797 if (!UsePhysics && !isNew) 2311 if (pa.IsPhysical != UsePhysics)
1798 { 2312 pa.IsPhysical = UsePhysics;
1799 // reset velocity to 0 on physics switch-off. Without that, the client thinks the
1800 // prim still has velocity and continues to interpolate its position along the old
1801 // velocity-vector.
1802 Velocity = new Vector3(0, 0, 0);
1803 Acceleration = new Vector3(0, 0, 0);
1804 AngularVelocity = new Vector3(0, 0, 0);
1805 //RotationalVelocity = new Vector3(0, 0, 0);
1806 }
1807 2313
1808 pa.IsPhysical = UsePhysics; 2314 if (UsePhysics)
2315 {
2316 if (ParentGroup.RootPart.KeyframeMotion != null)
2317 ParentGroup.RootPart.KeyframeMotion.Stop();
2318 ParentGroup.RootPart.KeyframeMotion = null;
2319 ParentGroup.Scene.AddPhysicalPrim(1);
1809 2320
1810 // If we're not what we're supposed to be in the physics scene, recreate ourselves. 2321 PhysActor.OnRequestTerseUpdate += PhysicsRequestingTerseUpdate;
1811 //m_parentGroup.Scene.PhysicsScene.RemovePrim(PhysActor); 2322 PhysActor.OnOutOfBounds += PhysicsOutOfBounds;
1812 /// that's not wholesome. Had to make Scene public
1813 //PhysActor = null;
1814 2323
1815 if ((Flags & PrimFlags.Phantom) == 0) 2324 if (ParentID != 0 && ParentID != LocalId)
1816 {
1817 if (UsePhysics)
1818 { 2325 {
1819 ParentGroup.Scene.AddPhysicalPrim(1); 2326 PhysicsActor parentPa = ParentGroup.RootPart.PhysActor;
1820 2327
1821 pa.OnRequestTerseUpdate += PhysicsRequestingTerseUpdate; 2328 if (parentPa != null)
1822 pa.OnOutOfBounds += PhysicsOutOfBounds;
1823 if (ParentID != 0 && ParentID != LocalId)
1824 { 2329 {
1825 PhysicsActor parentPa = ParentGroup.RootPart.PhysActor; 2330 pa.link(parentPa);
1826
1827 if (parentPa != null)
1828 {
1829 pa.link(parentPa);
1830 }
1831 } 2331 }
1832 } 2332 }
1833 } 2333 }
2334 }
2335
2336 bool phan = ((Flags & PrimFlags.Phantom) != 0);
2337 if (pa.Phantom != phan)
2338 pa.Phantom = phan;
2339
2340// some engines dont' have this check still
2341// if (VolumeDetectActive != pa.IsVolumeDtc)
2342 {
2343 if (VolumeDetectActive)
2344 pa.SetVolumeDetect(1);
2345 else
2346 pa.SetVolumeDetect(0);
1834 } 2347 }
1835 2348
1836 // If this part is a sculpt then delay the physics update until we've asynchronously loaded the 2349 // If this part is a sculpt then delay the physics update until we've asynchronously loaded the
@@ -1949,42 +2462,63 @@ namespace OpenSim.Region.Framework.Scenes
1949 2462
1950 public Vector3 GetGeometricCenter() 2463 public Vector3 GetGeometricCenter()
1951 { 2464 {
2465 // this is not real geometric center but a average of positions relative to root prim acording to
2466 // http://wiki.secondlife.com/wiki/llGetGeometricCenter
2467 // ignoring tortured prims details since sl also seems to ignore
2468 // so no real use in doing it on physics
2469 if (ParentGroup.IsDeleted)
2470 return new Vector3(0, 0, 0);
2471
2472 return ParentGroup.GetGeometricCenter();
2473 }
2474
2475 public float GetMass()
2476 {
1952 PhysicsActor pa = PhysActor; 2477 PhysicsActor pa = PhysActor;
1953 2478
1954 if (pa != null) 2479 if (pa != null)
1955 return new Vector3(pa.GeometricCenter.X, pa.GeometricCenter.Y, pa.GeometricCenter.Z); 2480 return pa.Mass;
1956 else 2481 else
1957 return new Vector3(0, 0, 0); 2482 return 0;
1958 } 2483 }
1959 2484
1960 public Vector3 GetCenterOfMass() 2485 public Vector3 GetCenterOfMass()
1961 { 2486 {
2487 if (ParentGroup.RootPart == this)
2488 {
2489 if (ParentGroup.IsDeleted)
2490 return AbsolutePosition;
2491 return ParentGroup.GetCenterOfMass();
2492 }
2493
1962 PhysicsActor pa = PhysActor; 2494 PhysicsActor pa = PhysActor;
1963 2495
1964 if (pa != null) 2496 if (pa != null)
1965 return new Vector3(pa.CenterOfMass.X, pa.CenterOfMass.Y, pa.CenterOfMass.Z); 2497 {
2498 Vector3 tmp = pa.CenterOfMass;
2499 return tmp;
2500 }
1966 else 2501 else
1967 return new Vector3(0, 0, 0); 2502 return AbsolutePosition;
1968 } 2503 }
1969 2504
1970 public float GetMass() 2505 public Vector3 GetPartCenterOfMass()
1971 { 2506 {
1972 PhysicsActor pa = PhysActor; 2507 PhysicsActor pa = PhysActor;
1973 2508
1974 if (pa != null) 2509 if (pa != null)
1975 return pa.Mass; 2510 {
2511 Vector3 tmp = pa.CenterOfMass;
2512 return tmp;
2513 }
1976 else 2514 else
1977 return 0; 2515 return AbsolutePosition;
1978 } 2516 }
1979 2517
2518
1980 public Vector3 GetForce() 2519 public Vector3 GetForce()
1981 { 2520 {
1982 PhysicsActor pa = PhysActor; 2521 return Force;
1983
1984 if (pa != null)
1985 return pa.Force;
1986 else
1987 return Vector3.Zero;
1988 } 2522 }
1989 2523
1990 /// <summary> 2524 /// <summary>
@@ -2199,15 +2733,25 @@ namespace OpenSim.Region.Framework.Scenes
2199 2733
2200 private void SendLandCollisionEvent(scriptEvents ev, ScriptCollidingNotification notify) 2734 private void SendLandCollisionEvent(scriptEvents ev, ScriptCollidingNotification notify)
2201 { 2735 {
2202 if ((ParentGroup.RootPart.ScriptEvents & ev) != 0) 2736 bool sendToRoot = true;
2203 {
2204 ColliderArgs LandCollidingMessage = new ColliderArgs();
2205 List<DetectedObject> colliding = new List<DetectedObject>();
2206
2207 colliding.Add(CreateDetObjectForGround());
2208 LandCollidingMessage.Colliders = colliding;
2209 2737
2738 ColliderArgs LandCollidingMessage = new ColliderArgs();
2739 List<DetectedObject> colliding = new List<DetectedObject>();
2740
2741 colliding.Add(CreateDetObjectForGround());
2742 LandCollidingMessage.Colliders = colliding;
2743
2744 if (Inventory.ContainsScripts())
2745 {
2746 if (!PassCollisions)
2747 sendToRoot = false;
2748 }
2749 if ((ScriptEvents & ev) != 0)
2210 notify(LocalId, LandCollidingMessage); 2750 notify(LocalId, LandCollidingMessage);
2751
2752 if ((ParentGroup.RootPart.ScriptEvents & ev) != 0 && sendToRoot)
2753 {
2754 notify(ParentGroup.RootPart.LocalId, LandCollidingMessage);
2211 } 2755 }
2212 } 2756 }
2213 2757
@@ -2223,57 +2767,120 @@ namespace OpenSim.Region.Framework.Scenes
2223 List<uint> endedColliders = new List<uint>(); 2767 List<uint> endedColliders = new List<uint>();
2224 List<uint> startedColliders = new List<uint>(); 2768 List<uint> startedColliders = new List<uint>();
2225 2769
2226 // calculate things that started colliding this time 2770 if (collissionswith.Count == 0)
2227 // and build up list of colliders this time
2228 foreach (uint localid in collissionswith.Keys)
2229 { 2771 {
2230 thisHitColliders.Add(localid); 2772 if (m_lastColliders.Count == 0)
2231 if (!m_lastColliders.Contains(localid)) 2773 return; // nothing to do
2232 startedColliders.Add(localid);
2233 }
2234 2774
2235 // calculate things that ended colliding 2775 foreach (uint localID in m_lastColliders)
2236 foreach (uint localID in m_lastColliders) 2776 {
2237 {
2238 if (!thisHitColliders.Contains(localID))
2239 endedColliders.Add(localID); 2777 endedColliders.Add(localID);
2778 }
2779 m_lastColliders.Clear();
2240 } 2780 }
2241 2781
2242 //add the items that started colliding this time to the last colliders list. 2782 else
2243 foreach (uint localID in startedColliders) 2783 {
2244 m_lastColliders.Add(localID); 2784 List<CollisionForSoundInfo> soundinfolist = new List<CollisionForSoundInfo>();
2785
2786 // calculate things that started colliding this time
2787 // and build up list of colliders this time
2788 if (!VolumeDetectActive && CollisionSoundType >= 0)
2789 {
2790 CollisionForSoundInfo soundinfo;
2791 ContactPoint curcontact;
2245 2792
2246 // remove things that ended colliding from the last colliders list 2793 foreach (uint id in collissionswith.Keys)
2247 foreach (uint localID in endedColliders) 2794 {
2248 m_lastColliders.Remove(localID); 2795 thisHitColliders.Add(id);
2796 if (!m_lastColliders.Contains(id))
2797 {
2798 startedColliders.Add(id);
2249 2799
2250 // play the sound. 2800 curcontact = collissionswith[id];
2251 if (startedColliders.Count > 0 && CollisionSound != UUID.Zero && CollisionSoundVolume > 0.0f) 2801 if (Math.Abs(curcontact.RelativeSpeed) > 0.2)
2252 { 2802 {
2253 ISoundModule soundModule = ParentGroup.Scene.RequestModuleInterface<ISoundModule>(); 2803 soundinfo = new CollisionForSoundInfo();
2254 if (soundModule != null) 2804 soundinfo.colliderID = id;
2805 soundinfo.position = curcontact.Position;
2806 soundinfo.relativeVel = curcontact.RelativeSpeed;
2807 soundinfolist.Add(soundinfo);
2808 }
2809 }
2810 }
2811 }
2812 else
2255 { 2813 {
2256 soundModule.SendSound(UUID, CollisionSound, 2814 foreach (uint id in collissionswith.Keys)
2257 CollisionSoundVolume, true, (byte)0, 0, false, 2815 {
2258 false); 2816 thisHitColliders.Add(id);
2817 if (!m_lastColliders.Contains(id))
2818 startedColliders.Add(id);
2819 }
2820 }
2821
2822 // calculate things that ended colliding
2823 foreach (uint localID in m_lastColliders)
2824 {
2825 if (!thisHitColliders.Contains(localID))
2826 endedColliders.Add(localID);
2259 } 2827 }
2828
2829 //add the items that started colliding this time to the last colliders list.
2830 foreach (uint localID in startedColliders)
2831 m_lastColliders.Add(localID);
2832
2833 // remove things that ended colliding from the last colliders list
2834 foreach (uint localID in endedColliders)
2835 m_lastColliders.Remove(localID);
2836
2837 // play sounds.
2838 if (soundinfolist.Count > 0)
2839 CollisionSounds.PartCollisionSound(this, soundinfolist);
2260 } 2840 }
2261 2841
2262 SendCollisionEvent(scriptEvents.collision_start, startedColliders, ParentGroup.Scene.EventManager.TriggerScriptCollidingStart); 2842 SendCollisionEvent(scriptEvents.collision_start, startedColliders, ParentGroup.Scene.EventManager.TriggerScriptCollidingStart);
2263 SendCollisionEvent(scriptEvents.collision , m_lastColliders , ParentGroup.Scene.EventManager.TriggerScriptColliding); 2843 if (!VolumeDetectActive)
2844 SendCollisionEvent(scriptEvents.collision , m_lastColliders , ParentGroup.Scene.EventManager.TriggerScriptColliding);
2264 SendCollisionEvent(scriptEvents.collision_end , endedColliders , ParentGroup.Scene.EventManager.TriggerScriptCollidingEnd); 2845 SendCollisionEvent(scriptEvents.collision_end , endedColliders , ParentGroup.Scene.EventManager.TriggerScriptCollidingEnd);
2265 2846
2266 if (startedColliders.Contains(0)) 2847 if (startedColliders.Contains(0))
2267 { 2848 SendLandCollisionEvent(scriptEvents.land_collision_start, ParentGroup.Scene.EventManager.TriggerScriptLandCollidingStart);
2268 if (m_lastColliders.Contains(0)) 2849 if (m_lastColliders.Contains(0))
2269 SendLandCollisionEvent(scriptEvents.land_collision, ParentGroup.Scene.EventManager.TriggerScriptLandColliding); 2850 SendLandCollisionEvent(scriptEvents.land_collision, ParentGroup.Scene.EventManager.TriggerScriptLandColliding);
2270 else
2271 SendLandCollisionEvent(scriptEvents.land_collision_start, ParentGroup.Scene.EventManager.TriggerScriptLandCollidingStart);
2272 }
2273 if (endedColliders.Contains(0)) 2851 if (endedColliders.Contains(0))
2274 SendLandCollisionEvent(scriptEvents.land_collision_end, ParentGroup.Scene.EventManager.TriggerScriptLandCollidingEnd); 2852 SendLandCollisionEvent(scriptEvents.land_collision_end, ParentGroup.Scene.EventManager.TriggerScriptLandCollidingEnd);
2275 } 2853 }
2276 2854
2855 // The Collision sounds code calls this
2856 public void SendCollisionSound(UUID soundID, double volume, Vector3 position)
2857 {
2858 if (soundID == UUID.Zero)
2859 return;
2860
2861 ISoundModule soundModule = ParentGroup.Scene.RequestModuleInterface<ISoundModule>();
2862 if (soundModule == null)
2863 return;
2864
2865 if (volume > 1)
2866 volume = 1;
2867 if (volume < 0)
2868 volume = 0;
2869
2870 int now = Util.EnvironmentTickCount();
2871 if(Util.EnvironmentTickCountSubtract(now,LastColSoundSentTime) <200)
2872 return;
2873
2874 LastColSoundSentTime = now;
2875
2876 UUID ownerID = OwnerID;
2877 UUID objectID = ParentGroup.RootPart.UUID;
2878 UUID parentID = ParentGroup.UUID;
2879 ulong regionHandle = ParentGroup.Scene.RegionInfo.RegionHandle;
2880
2881 soundModule.TriggerSound(soundID, ownerID, objectID, parentID, volume, position, regionHandle, 0 );
2882 }
2883
2277 public void PhysicsOutOfBounds(Vector3 pos) 2884 public void PhysicsOutOfBounds(Vector3 pos)
2278 { 2885 {
2279 // Note: This is only being called on the root prim at this time. 2886 // Note: This is only being called on the root prim at this time.
@@ -2295,9 +2902,9 @@ namespace OpenSim.Region.Framework.Scenes
2295 Vector3 newpos = new Vector3(pa.Position.GetBytes(), 0); 2902 Vector3 newpos = new Vector3(pa.Position.GetBytes(), 0);
2296 2903
2297 if (ParentGroup.Scene.TestBorderCross(newpos, Cardinals.N) 2904 if (ParentGroup.Scene.TestBorderCross(newpos, Cardinals.N)
2298 | ParentGroup.Scene.TestBorderCross(newpos, Cardinals.S) 2905 || ParentGroup.Scene.TestBorderCross(newpos, Cardinals.S)
2299 | ParentGroup.Scene.TestBorderCross(newpos, Cardinals.E) 2906 || ParentGroup.Scene.TestBorderCross(newpos, Cardinals.E)
2300 | ParentGroup.Scene.TestBorderCross(newpos, Cardinals.W)) 2907 || ParentGroup.Scene.TestBorderCross(newpos, Cardinals.W))
2301 { 2908 {
2302 ParentGroup.AbsolutePosition = newpos; 2909 ParentGroup.AbsolutePosition = newpos;
2303 return; 2910 return;
@@ -2424,6 +3031,19 @@ namespace OpenSim.Region.Framework.Scenes
2424 APIDTarget = Quaternion.Identity; 3031 APIDTarget = Quaternion.Identity;
2425 } 3032 }
2426 3033
3034
3035
3036 public void ScheduleFullUpdateIfNone()
3037 {
3038 if (ParentGroup == null)
3039 return;
3040
3041// ??? ParentGroup.HasGroupChanged = true;
3042
3043 if (UpdateFlag != UpdateRequired.FULL)
3044 ScheduleFullUpdate();
3045 }
3046
2427 /// <summary> 3047 /// <summary>
2428 /// Schedules this prim for a full update 3048 /// Schedules this prim for a full update
2429 /// </summary> 3049 /// </summary>
@@ -2569,6 +3189,14 @@ namespace OpenSim.Region.Framework.Scenes
2569 if (ParentGroup == null) 3189 if (ParentGroup == null)
2570 return; 3190 return;
2571 3191
3192 // Update the "last" values
3193 m_lastPosition = OffsetPosition;
3194 m_lastRotation = RotationOffset;
3195 m_lastVelocity = Velocity;
3196 m_lastAcceleration = Acceleration;
3197 m_lastAngularVelocity = AngularVelocity;
3198 m_lastUpdateSentTime = Environment.TickCount;
3199
2572 ParentGroup.Scene.ForEachScenePresence(delegate(ScenePresence avatar) 3200 ParentGroup.Scene.ForEachScenePresence(delegate(ScenePresence avatar)
2573 { 3201 {
2574 SendFullUpdate(avatar.ControllingClient); 3202 SendFullUpdate(avatar.ControllingClient);
@@ -2627,8 +3255,8 @@ namespace OpenSim.Region.Framework.Scenes
2627 { 3255 {
2628 const float ROTATION_TOLERANCE = 0.01f; 3256 const float ROTATION_TOLERANCE = 0.01f;
2629 const float VELOCITY_TOLERANCE = 0.001f; 3257 const float VELOCITY_TOLERANCE = 0.001f;
2630 const float POSITION_TOLERANCE = 0.05f; 3258 const float POSITION_TOLERANCE = 0.05f; // I don't like this, but I suppose it's necessary
2631 const int TIME_MS_TOLERANCE = 3000; 3259 const int TIME_MS_TOLERANCE = 200; //llSetPos has a 200ms delay. This should NOT be 3 seconds.
2632 3260
2633 switch (UpdateFlag) 3261 switch (UpdateFlag)
2634 { 3262 {
@@ -2642,17 +3270,10 @@ namespace OpenSim.Region.Framework.Scenes
2642 Velocity.ApproxEquals(Vector3.Zero, VELOCITY_TOLERANCE) || 3270 Velocity.ApproxEquals(Vector3.Zero, VELOCITY_TOLERANCE) ||
2643 !AngularVelocity.ApproxEquals(m_lastAngularVelocity, VELOCITY_TOLERANCE) || 3271 !AngularVelocity.ApproxEquals(m_lastAngularVelocity, VELOCITY_TOLERANCE) ||
2644 !OffsetPosition.ApproxEquals(m_lastPosition, POSITION_TOLERANCE) || 3272 !OffsetPosition.ApproxEquals(m_lastPosition, POSITION_TOLERANCE) ||
2645 Environment.TickCount - m_lastTerseSent > TIME_MS_TOLERANCE) 3273 Environment.TickCount - m_lastUpdateSentTime > TIME_MS_TOLERANCE)
2646 { 3274 {
2647 SendTerseUpdateToAllClients(); 3275 SendTerseUpdateToAllClients();
2648 3276
2649 // Update the "last" values
2650 m_lastPosition = OffsetPosition;
2651 m_lastRotation = RotationOffset;
2652 m_lastVelocity = Velocity;
2653 m_lastAcceleration = Acceleration;
2654 m_lastAngularVelocity = AngularVelocity;
2655 m_lastTerseSent = Environment.TickCount;
2656 } 3277 }
2657 break; 3278 break;
2658 } 3279 }
@@ -2670,6 +3291,17 @@ namespace OpenSim.Region.Framework.Scenes
2670 /// </summary> 3291 /// </summary>
2671 public void SendTerseUpdateToAllClients() 3292 public void SendTerseUpdateToAllClients()
2672 { 3293 {
3294 if (ParentGroup == null || ParentGroup.Scene == null)
3295 return;
3296
3297 // Update the "last" values
3298 m_lastPosition = OffsetPosition;
3299 m_lastRotation = RotationOffset;
3300 m_lastVelocity = Velocity;
3301 m_lastAcceleration = Acceleration;
3302 m_lastAngularVelocity = AngularVelocity;
3303 m_lastUpdateSentTime = Environment.TickCount;
3304
2673 ParentGroup.Scene.ForEachClient(delegate(IClientAPI client) 3305 ParentGroup.Scene.ForEachClient(delegate(IClientAPI client)
2674 { 3306 {
2675 SendTerseUpdateToClient(client); 3307 SendTerseUpdateToClient(client);
@@ -2693,10 +3325,13 @@ namespace OpenSim.Region.Framework.Scenes
2693 3325
2694 public void SetBuoyancy(float fvalue) 3326 public void SetBuoyancy(float fvalue)
2695 { 3327 {
2696 PhysicsActor pa = PhysActor; 3328 Buoyancy = fvalue;
2697 3329/*
2698 if (pa != null) 3330 if (PhysActor != null)
2699 pa.Buoyancy = fvalue; 3331 {
3332 PhysActor.Buoyancy = fvalue;
3333 }
3334 */
2700 } 3335 }
2701 3336
2702 public void SetDieAtEdge(bool p) 3337 public void SetDieAtEdge(bool p)
@@ -2712,47 +3347,111 @@ namespace OpenSim.Region.Framework.Scenes
2712 PhysicsActor pa = PhysActor; 3347 PhysicsActor pa = PhysActor;
2713 3348
2714 if (pa != null) 3349 if (pa != null)
2715 pa.FloatOnWater = floatYN == 1; 3350 pa.FloatOnWater = (floatYN == 1);
2716 } 3351 }
2717 3352
2718 public void SetForce(Vector3 force) 3353 public void SetForce(Vector3 force)
2719 { 3354 {
2720 PhysicsActor pa = PhysActor; 3355 Force = force;
3356 }
2721 3357
2722 if (pa != null) 3358 public SOPVehicle VehicleParams
2723 pa.Force = force; 3359 {
3360 get
3361 {
3362 return m_vehicleParams;
3363 }
3364 set
3365 {
3366 m_vehicleParams = value;
3367 }
3368 }
3369
3370
3371 public int VehicleType
3372 {
3373 get
3374 {
3375 if (m_vehicleParams == null)
3376 return (int)Vehicle.TYPE_NONE;
3377 else
3378 return (int)m_vehicleParams.Type;
3379 }
3380 set
3381 {
3382 SetVehicleType(value);
3383 }
2724 } 3384 }
2725 3385
2726 public void SetVehicleType(int type) 3386 public void SetVehicleType(int type)
2727 { 3387 {
2728 PhysicsActor pa = PhysActor; 3388 m_vehicleParams = null;
3389
3390 if (type == (int)Vehicle.TYPE_NONE)
3391 {
3392 if (_parentID ==0 && PhysActor != null)
3393 PhysActor.VehicleType = (int)Vehicle.TYPE_NONE;
3394 return;
3395 }
3396 m_vehicleParams = new SOPVehicle();
3397 m_vehicleParams.ProcessTypeChange((Vehicle)type);
3398 {
3399 if (_parentID ==0 && PhysActor != null)
3400 PhysActor.VehicleType = type;
3401 return;
3402 }
3403 }
2729 3404
2730 if (pa != null) 3405 public void SetVehicleFlags(int param, bool remove)
2731 pa.VehicleType = type; 3406 {
3407 if (m_vehicleParams == null)
3408 return;
3409
3410 m_vehicleParams.ProcessVehicleFlags(param, remove);
3411
3412 if (_parentID ==0 && PhysActor != null)
3413 {
3414 PhysActor.VehicleFlags(param, remove);
3415 }
2732 } 3416 }
2733 3417
2734 public void SetVehicleFloatParam(int param, float value) 3418 public void SetVehicleFloatParam(int param, float value)
2735 { 3419 {
2736 PhysicsActor pa = PhysActor; 3420 if (m_vehicleParams == null)
3421 return;
2737 3422
2738 if (pa != null) 3423 m_vehicleParams.ProcessFloatVehicleParam((Vehicle)param, value);
2739 pa.VehicleFloatParam(param, value); 3424
3425 if (_parentID == 0 && PhysActor != null)
3426 {
3427 PhysActor.VehicleFloatParam(param, value);
3428 }
2740 } 3429 }
2741 3430
2742 public void SetVehicleVectorParam(int param, Vector3 value) 3431 public void SetVehicleVectorParam(int param, Vector3 value)
2743 { 3432 {
2744 PhysicsActor pa = PhysActor; 3433 if (m_vehicleParams == null)
3434 return;
2745 3435
2746 if (pa != null) 3436 m_vehicleParams.ProcessVectorVehicleParam((Vehicle)param, value);
2747 pa.VehicleVectorParam(param, value); 3437
3438 if (_parentID == 0 && PhysActor != null)
3439 {
3440 PhysActor.VehicleVectorParam(param, value);
3441 }
2748 } 3442 }
2749 3443
2750 public void SetVehicleRotationParam(int param, Quaternion rotation) 3444 public void SetVehicleRotationParam(int param, Quaternion rotation)
2751 { 3445 {
2752 PhysicsActor pa = PhysActor; 3446 if (m_vehicleParams == null)
3447 return;
2753 3448
2754 if (pa != null) 3449 m_vehicleParams.ProcessRotationVehicleParam((Vehicle)param, rotation);
2755 pa.VehicleRotationParam(param, rotation); 3450
3451 if (_parentID == 0 && PhysActor != null)
3452 {
3453 PhysActor.VehicleRotationParam(param, rotation);
3454 }
2756 } 3455 }
2757 3456
2758 /// <summary> 3457 /// <summary>
@@ -2953,14 +3652,6 @@ namespace OpenSim.Region.Framework.Scenes
2953 hasProfileCut = hasDimple; // is it the same thing? 3652 hasProfileCut = hasDimple; // is it the same thing?
2954 } 3653 }
2955 3654
2956 public void SetVehicleFlags(int param, bool remove)
2957 {
2958 PhysicsActor pa = PhysActor;
2959
2960 if (pa != null)
2961 pa.VehicleFlags(param, remove);
2962 }
2963
2964 public void SetGroup(UUID groupID, IClientAPI client) 3655 public void SetGroup(UUID groupID, IClientAPI client)
2965 { 3656 {
2966 // Scene.AddNewPrims() calls with client == null so can't use this. 3657 // Scene.AddNewPrims() calls with client == null so can't use this.
@@ -3064,67 +3755,16 @@ namespace OpenSim.Region.Framework.Scenes
3064 //ParentGroup.ScheduleGroupForFullUpdate(); 3755 //ParentGroup.ScheduleGroupForFullUpdate();
3065 } 3756 }
3066 3757
3067 public void StoreUndoState() 3758 public void StoreUndoState(ObjectChangeType change)
3068 {
3069 StoreUndoState(false);
3070 }
3071
3072 public void StoreUndoState(bool forGroup)
3073 { 3759 {
3074 if (ParentGroup == null || ParentGroup.Scene == null) 3760 if (m_UndoRedo == null)
3075 return; 3761 m_UndoRedo = new UndoRedoState(5);
3076
3077 if (Undoing)
3078 {
3079// m_log.DebugFormat(
3080// "[SCENE OBJECT PART]: Ignoring undo store for {0} {1} since already undoing", Name, LocalId);
3081 return;
3082 }
3083
3084 if (IgnoreUndoUpdate)
3085 {
3086// m_log.DebugFormat("[SCENE OBJECT PART]: Ignoring undo store for {0} {1}", Name, LocalId);
3087 return;
3088 }
3089 3762
3090 lock (m_undo) 3763 lock (m_UndoRedo)
3091 { 3764 {
3092 if (m_undo.Count > 0) 3765 if (!Undoing && !IgnoreUndoUpdate && ParentGroup != null) // just to read better - undo is in progress, or suspended
3093 {
3094 UndoState last = m_undo[m_undo.Count - 1];
3095 if (last != null)
3096 {
3097 // TODO: May need to fix for group comparison
3098 if (last.Compare(this))
3099 {
3100// m_log.DebugFormat(
3101// "[SCENE OBJECT PART]: Not storing undo for {0} {1} since current state is same as last undo state, initial stack size {2}",
3102// Name, LocalId, m_undo.Count);
3103
3104 return;
3105 }
3106 }
3107 }
3108
3109// m_log.DebugFormat(
3110// "[SCENE OBJECT PART]: Storing undo state for {0} {1}, forGroup {2}, initial stack size {3}",
3111// Name, LocalId, forGroup, m_undo.Count);
3112
3113 if (ParentGroup.Scene.MaxUndoCount > 0)
3114 { 3766 {
3115 UndoState nUndo = new UndoState(this, forGroup); 3767 m_UndoRedo.StoreUndo(this, change);
3116
3117 m_undo.Add(nUndo);
3118
3119 if (m_undo.Count > ParentGroup.Scene.MaxUndoCount)
3120 m_undo.RemoveAt(0);
3121
3122 if (m_redo.Count > 0)
3123 m_redo.Clear();
3124
3125// m_log.DebugFormat(
3126// "[SCENE OBJECT PART]: Stored undo state for {0} {1}, forGroup {2}, stack size now {3}",
3127// Name, LocalId, forGroup, m_undo.Count);
3128 } 3768 }
3129 } 3769 }
3130 } 3770 }
@@ -3136,88 +3776,46 @@ namespace OpenSim.Region.Framework.Scenes
3136 { 3776 {
3137 get 3777 get
3138 { 3778 {
3139 lock (m_undo) 3779 if (m_UndoRedo == null)
3140 return m_undo.Count; 3780 return 0;
3781 return m_UndoRedo.Count;
3141 } 3782 }
3142 } 3783 }
3143 3784
3144 public void Undo() 3785 public void Undo()
3145 { 3786 {
3146 lock (m_undo) 3787 if (m_UndoRedo == null || Undoing || ParentGroup == null)
3147 { 3788 return;
3148// m_log.DebugFormat(
3149// "[SCENE OBJECT PART]: Handling undo request for {0} {1}, stack size {2}",
3150// Name, LocalId, m_undo.Count);
3151
3152 if (m_undo.Count > 0)
3153 {
3154 UndoState goback = m_undo[m_undo.Count - 1];
3155 m_undo.RemoveAt(m_undo.Count - 1);
3156
3157 UndoState nUndo = null;
3158
3159 if (ParentGroup.Scene.MaxUndoCount > 0)
3160 {
3161 nUndo = new UndoState(this, goback.ForGroup);
3162 }
3163
3164 goback.PlaybackState(this);
3165
3166 if (nUndo != null)
3167 {
3168 m_redo.Add(nUndo);
3169
3170 if (m_redo.Count > ParentGroup.Scene.MaxUndoCount)
3171 m_redo.RemoveAt(0);
3172 }
3173 }
3174 3789
3175// m_log.DebugFormat( 3790 lock (m_UndoRedo)
3176// "[SCENE OBJECT PART]: Handled undo request for {0} {1}, stack size now {2}", 3791 {
3177// Name, LocalId, m_undo.Count); 3792 Undoing = true;
3793 m_UndoRedo.Undo(this);
3794 Undoing = false;
3178 } 3795 }
3179 } 3796 }
3180 3797
3181 public void Redo() 3798 public void Redo()
3182 { 3799 {
3183 lock (m_undo) 3800 if (m_UndoRedo == null || Undoing || ParentGroup == null)
3184 { 3801 return;
3185// m_log.DebugFormat(
3186// "[SCENE OBJECT PART]: Handling redo request for {0} {1}, stack size {2}",
3187// Name, LocalId, m_redo.Count);
3188
3189 if (m_redo.Count > 0)
3190 {
3191 UndoState gofwd = m_redo[m_redo.Count - 1];
3192 m_redo.RemoveAt(m_redo.Count - 1);
3193
3194 if (ParentGroup.Scene.MaxUndoCount > 0)
3195 {
3196 UndoState nUndo = new UndoState(this, gofwd.ForGroup);
3197
3198 m_undo.Add(nUndo);
3199
3200 if (m_undo.Count > ParentGroup.Scene.MaxUndoCount)
3201 m_undo.RemoveAt(0);
3202 }
3203
3204 gofwd.PlayfwdState(this);
3205 3802
3206// m_log.DebugFormat( 3803 lock (m_UndoRedo)
3207// "[SCENE OBJECT PART]: Handled redo request for {0} {1}, stack size now {2}", 3804 {
3208// Name, LocalId, m_redo.Count); 3805 Undoing = true;
3209 } 3806 m_UndoRedo.Redo(this);
3807 Undoing = false;
3210 } 3808 }
3211 } 3809 }
3212 3810
3213 public void ClearUndoState() 3811 public void ClearUndoState()
3214 { 3812 {
3215// m_log.DebugFormat("[SCENE OBJECT PART]: Clearing undo and redo stacks in {0} {1}", Name, LocalId); 3813 if (m_UndoRedo == null || Undoing)
3814 return;
3216 3815
3217 lock (m_undo) 3816 lock (m_UndoRedo)
3218 { 3817 {
3219 m_undo.Clear(); 3818 m_UndoRedo.Clear();
3220 m_redo.Clear();
3221 } 3819 }
3222 } 3820 }
3223 3821
@@ -3767,7 +4365,7 @@ namespace OpenSim.Region.Framework.Scenes
3767 if (god) 4365 if (god)
3768 { 4366 {
3769 BaseMask = ApplyMask(BaseMask, set, mask); 4367 BaseMask = ApplyMask(BaseMask, set, mask);
3770 Inventory.ApplyGodPermissions(_baseMask); 4368 Inventory.ApplyGodPermissions(BaseMask);
3771 } 4369 }
3772 4370
3773 break; 4371 break;
@@ -3786,7 +4384,7 @@ namespace OpenSim.Region.Framework.Scenes
3786 case 16: 4384 case 16:
3787 NextOwnerMask = ApplyMask(NextOwnerMask, set, mask) & 4385 NextOwnerMask = ApplyMask(NextOwnerMask, set, mask) &
3788 baseMask; 4386 baseMask;
3789 // Prevent the client from creating no mod, no copy 4387 // Prevent the client from creating no copy, no transfer
3790 // objects 4388 // objects
3791 if ((NextOwnerMask & (uint)PermissionMask.Copy) == 0) 4389 if ((NextOwnerMask & (uint)PermissionMask.Copy) == 0)
3792 NextOwnerMask |= (uint)PermissionMask.Transfer; 4390 NextOwnerMask |= (uint)PermissionMask.Transfer;
@@ -3804,20 +4402,20 @@ namespace OpenSim.Region.Framework.Scenes
3804 { 4402 {
3805 bool update = false; 4403 bool update = false;
3806 4404
3807 if (BaseMask != source.BaseMask || 4405 uint prevOwnerMask = OwnerMask;
3808 OwnerMask != source.OwnerMask || 4406 uint prevGroupMask = GroupMask;
3809 GroupMask != source.GroupMask || 4407 uint prevEveryoneMask = EveryoneMask;
3810 EveryoneMask != source.EveryoneMask || 4408 uint prevNextOwnerMask = NextOwnerMask;
3811 NextOwnerMask != source.NextOwnerMask)
3812 update = true;
3813 4409
3814 BaseMask = source.BaseMask; 4410 OwnerMask = source.OwnerMask & BaseMask;
3815 OwnerMask = source.OwnerMask; 4411 GroupMask = source.GroupMask & BaseMask;
3816 GroupMask = source.GroupMask; 4412 EveryoneMask = source.EveryoneMask & BaseMask;
3817 EveryoneMask = source.EveryoneMask; 4413 NextOwnerMask = source.NextOwnerMask & BaseMask;
3818 NextOwnerMask = source.NextOwnerMask;
3819 4414
3820 if (update) 4415 if (OwnerMask != prevOwnerMask ||
4416 GroupMask != prevGroupMask ||
4417 EveryoneMask != prevEveryoneMask ||
4418 NextOwnerMask != prevNextOwnerMask)
3821 SendFullUpdateToAllClients(); 4419 SendFullUpdateToAllClients();
3822 } 4420 }
3823 4421
@@ -3868,6 +4466,27 @@ namespace OpenSim.Region.Framework.Scenes
3868 } 4466 }
3869 } 4467 }
3870 4468
4469
4470 public void UpdateExtraPhysics(ExtraPhysicsData physdata)
4471 {
4472 if (physdata.PhysShapeType == PhysShapeType.invalid || ParentGroup == null)
4473 return;
4474
4475 if (PhysicsShapeType != (byte)physdata.PhysShapeType)
4476 {
4477 PhysicsShapeType = (byte)physdata.PhysShapeType;
4478
4479 }
4480
4481 if(Density != physdata.Density)
4482 Density = physdata.Density;
4483 if(GravityModifier != physdata.GravitationModifier)
4484 GravityModifier = physdata.GravitationModifier;
4485 if(Friction != physdata.Friction)
4486 Friction = physdata.Friction;
4487 if(Bounciness != physdata.Bounce)
4488 Bounciness = physdata.Bounce;
4489 }
3871 /// <summary> 4490 /// <summary>
3872 /// Update the flags on this prim. This covers properties such as phantom, physics and temporary. 4491 /// Update the flags on this prim. This covers properties such as phantom, physics and temporary.
3873 /// </summary> 4492 /// </summary>
@@ -3875,7 +4494,7 @@ namespace OpenSim.Region.Framework.Scenes
3875 /// <param name="SetTemporary"></param> 4494 /// <param name="SetTemporary"></param>
3876 /// <param name="SetPhantom"></param> 4495 /// <param name="SetPhantom"></param>
3877 /// <param name="SetVD"></param> 4496 /// <param name="SetVD"></param>
3878 public void UpdatePrimFlags(bool UsePhysics, bool SetTemporary, bool SetPhantom, bool SetVD) 4497 public void UpdatePrimFlags(bool UsePhysics, bool SetTemporary, bool SetPhantom, bool SetVD, bool building)
3879 { 4498 {
3880 bool wasUsingPhysics = ((Flags & PrimFlags.Physics) != 0); 4499 bool wasUsingPhysics = ((Flags & PrimFlags.Physics) != 0);
3881 bool wasTemporary = ((Flags & PrimFlags.TemporaryOnRez) != 0); 4500 bool wasTemporary = ((Flags & PrimFlags.TemporaryOnRez) != 0);
@@ -3885,214 +4504,230 @@ namespace OpenSim.Region.Framework.Scenes
3885 if ((UsePhysics == wasUsingPhysics) && (wasTemporary == SetTemporary) && (wasPhantom == SetPhantom) && (SetVD == wasVD)) 4504 if ((UsePhysics == wasUsingPhysics) && (wasTemporary == SetTemporary) && (wasPhantom == SetPhantom) && (SetVD == wasVD))
3886 return; 4505 return;
3887 4506
3888 PhysicsActor pa = PhysActor; 4507 VolumeDetectActive = SetVD;
3889
3890 // Special cases for VD. VD can only be called from a script
3891 // and can't be combined with changes to other states. So we can rely
3892 // that...
3893 // ... if VD is changed, all others are not.
3894 // ... if one of the others is changed, VD is not.
3895 if (SetVD) // VD is active, special logic applies
3896 {
3897 // State machine logic for VolumeDetect
3898 // More logic below
3899 bool phanReset = (SetPhantom != wasPhantom) && !SetPhantom;
3900
3901 if (phanReset) // Phantom changes from on to off switch VD off too
3902 {
3903 SetVD = false; // Switch it of for the course of this routine
3904 VolumeDetectActive = false; // and also permanently
3905
3906 if (pa != null)
3907 pa.SetVolumeDetect(0); // Let physics know about it too
3908 }
3909 else
3910 {
3911 // If volumedetect is active we don't want phantom to be applied.
3912 // If this is a new call to VD out of the state "phantom"
3913 // this will also cause the prim to be visible to physics
3914 SetPhantom = false;
3915 }
3916 }
3917 4508
3918 if (UsePhysics && IsJoint()) 4509 // volume detector implies phantom
3919 { 4510 if (VolumeDetectActive)
3920 SetPhantom = true; 4511 SetPhantom = true;
3921 }
3922 4512
3923 if (UsePhysics) 4513 if (UsePhysics)
3924 {
3925 AddFlag(PrimFlags.Physics); 4514 AddFlag(PrimFlags.Physics);
3926 if (!wasUsingPhysics)
3927 {
3928 DoPhysicsPropertyUpdate(UsePhysics, false);
3929 }
3930 }
3931 else 4515 else
3932 {
3933 RemFlag(PrimFlags.Physics); 4516 RemFlag(PrimFlags.Physics);
3934 if (wasUsingPhysics)
3935 {
3936 DoPhysicsPropertyUpdate(UsePhysics, false);
3937 }
3938 }
3939 4517
3940 if (SetPhantom 4518 if (SetPhantom)
3941 || ParentGroup.IsAttachment
3942 || (Shape.PathCurve == (byte)Extrusion.Flexible)) // note: this may have been changed above in the case of joints
3943 {
3944 AddFlag(PrimFlags.Phantom); 4519 AddFlag(PrimFlags.Phantom);
3945 4520 else
3946 if (PhysActor != null)
3947 {
3948 RemoveFromPhysics();
3949 pa = null;
3950 }
3951 }
3952 else // Not phantom
3953 {
3954 RemFlag(PrimFlags.Phantom); 4521 RemFlag(PrimFlags.Phantom);
3955 4522
3956 if (ParentGroup.Scene == null) 4523 if (SetTemporary)
3957 return; 4524 AddFlag(PrimFlags.TemporaryOnRez);
4525 else
4526 RemFlag(PrimFlags.TemporaryOnRez);
3958 4527
3959 if (ParentGroup.Scene.CollidablePrims && pa == null)
3960 {
3961 pa = AddToPhysics(UsePhysics);
3962 4528
3963 if (pa != null) 4529 if (ParentGroup.Scene == null)
3964 { 4530 return;
3965 pa.SetMaterial(Material); 4531
3966 DoPhysicsPropertyUpdate(UsePhysics, true); 4532 PhysicsActor pa = PhysActor;
3967
3968 if (
3969 ((AggregateScriptEvents & scriptEvents.collision) != 0) ||
3970 ((AggregateScriptEvents & scriptEvents.collision_end) != 0) ||
3971 ((AggregateScriptEvents & scriptEvents.collision_start) != 0) ||
3972 ((AggregateScriptEvents & scriptEvents.land_collision_start) != 0) ||
3973 ((AggregateScriptEvents & scriptEvents.land_collision) != 0) ||
3974 ((AggregateScriptEvents & scriptEvents.land_collision_end) != 0) ||
3975 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.collision) != 0) ||
3976 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.collision_end) != 0) ||
3977 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.collision_start) != 0) ||
3978 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.land_collision_start) != 0) ||
3979 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.land_collision) != 0) ||
3980 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.land_collision_end) != 0) ||
3981 (CollisionSound != UUID.Zero)
3982 )
3983 {
3984 pa.OnCollisionUpdate += PhysicsCollision;
3985 pa.SubscribeEvents(1000);
3986 }
3987 }
3988 }
3989 else // it already has a physical representation
3990 {
3991 DoPhysicsPropertyUpdate(UsePhysics, false); // Update physical status. If it's phantom this will remove the prim
3992 }
3993 }
3994 4533
3995 if (SetVD) 4534 if (pa != null && building && pa.Building != building)
4535 pa.Building = building;
4536
4537 if ((SetPhantom && !UsePhysics && !SetVD) || ParentGroup.IsAttachment || PhysicsShapeType == (byte)PhysShapeType.none
4538 || (Shape.PathCurve == (byte)Extrusion.Flexible))
3996 { 4539 {
3997 // If the above logic worked (this is urgent candidate to unit tests!)
3998 // we now have a physicsactor.
3999 // Defensive programming calls for a check here.
4000 // Better would be throwing an exception that could be catched by a unit test as the internal
4001 // logic should make sure, this Physactor is always here.
4002 if (pa != null) 4540 if (pa != null)
4003 { 4541 {
4004 pa.SetVolumeDetect(1); 4542 if(wasUsingPhysics)
4005 AddFlag(PrimFlags.Phantom); // We set this flag also if VD is active 4543 ParentGroup.Scene.RemovePhysicalPrim(1);
4006 VolumeDetectActive = true; 4544 RemoveFromPhysics();
4007 } 4545 }
4546
4547 Velocity = new Vector3(0, 0, 0);
4548 Acceleration = new Vector3(0, 0, 0);
4549 if (ParentGroup.RootPart == this)
4550 AngularVelocity = new Vector3(0, 0, 0);
4008 } 4551 }
4009 else if (SetVD != wasVD) 4552 else if (SetVD != wasVD)
4010 { 4553 {
4011 // Remove VolumeDetect in any case. Note, it's safe to call SetVolumeDetect as often as you like 4554 if (ParentGroup.Scene.CollidablePrims)
4012 // (mumbles, well, at least if you have infinte CPU powers :-)) 4555 {
4013 if (pa != null) 4556 if (pa == null)
4014 pa.SetVolumeDetect(0); 4557 {
4558 AddToPhysics(UsePhysics, SetPhantom, building, false);
4559 pa = PhysActor;
4560/*
4561 if (pa != null)
4562 {
4563 if (
4564// ((AggregateScriptEvents & scriptEvents.collision) != 0) ||
4565// ((AggregateScriptEvents & scriptEvents.collision_end) != 0) ||
4566// ((AggregateScriptEvents & scriptEvents.collision_start) != 0) ||
4567// ((AggregateScriptEvents & scriptEvents.land_collision_start) != 0) ||
4568// ((AggregateScriptEvents & scriptEvents.land_collision) != 0) ||
4569// ((AggregateScriptEvents & scriptEvents.land_collision_end) != 0) ||
4570 ((AggregateScriptEvents & PhysicsNeededSubsEvents) != 0) ||
4571 ((ParentGroup.RootPart.AggregateScriptEvents & PhysicsNeededSubsEvents) != 0) ||
4572 (CollisionSound != UUID.Zero)
4573 )
4574 {
4575 pa.OnCollisionUpdate += PhysicsCollision;
4576 pa.SubscribeEvents(1000);
4577 }
4578 }
4579*/
4580 }
4581 else // it already has a physical representation
4582 {
4583 DoPhysicsPropertyUpdate(UsePhysics, false); // Update physical status.
4584/* moved into DoPhysicsPropertyUpdate
4585 if(VolumeDetectActive)
4586 pa.SetVolumeDetect(1);
4587 else
4588 pa.SetVolumeDetect(0);
4589*/
4015 4590
4016 RemFlag(PrimFlags.Phantom); 4591 if (pa.Building != building)
4017 VolumeDetectActive = false; 4592 pa.Building = building;
4018 } 4593 }
4019 4594
4020 if (SetTemporary) 4595 UpdatePhysicsSubscribedEvents();
4021 { 4596 }
4022 AddFlag(PrimFlags.TemporaryOnRez); 4597 }
4023 }
4024 else
4025 {
4026 RemFlag(PrimFlags.TemporaryOnRez);
4027 }
4028 4598
4029 // m_log.Debug("Update: PHY:" + UsePhysics.ToString() + ", T:" + IsTemporary.ToString() + ", PHA:" + IsPhantom.ToString() + " S:" + CastsShadows.ToString()); 4599 // m_log.Debug("Update: PHY:" + UsePhysics.ToString() + ", T:" + IsTemporary.ToString() + ", PHA:" + IsPhantom.ToString() + " S:" + CastsShadows.ToString());
4030 4600
4601 // and last in case we have a new actor and not building
4602
4031 if (ParentGroup != null) 4603 if (ParentGroup != null)
4032 { 4604 {
4033 ParentGroup.HasGroupChanged = true; 4605 ParentGroup.HasGroupChanged = true;
4034 ScheduleFullUpdate(); 4606 ScheduleFullUpdate();
4035 } 4607 }
4036 4608
4037// m_log.DebugFormat("[SCENE OBJECT PART]: Updated PrimFlags on {0} {1} to {2}", Name, LocalId, Flags); 4609// m_log.DebugFormat("[SCENE OBJECT PART]: Updated PrimFlags on {0} {1} to {2}", Name, LocalId, Flags);
4038 } 4610 }
4039 4611
4040 /// <summary> 4612 /// <summary>
4041 /// Adds this part to the physics scene. 4613 /// Adds this part to the physics scene.
4614 /// and sets the PhysActor property
4042 /// </summary> 4615 /// </summary>
4043 /// <remarks>This method also sets the PhysActor property.</remarks> 4616 /// <param name="isPhysical">Add this prim as physical.</param>
4044 /// <param name="rigidBody">Add this prim with a rigid body.</param> 4617 /// <param name="isPhantom">Add this prim as phantom.</param>
4045 /// <returns> 4618 /// <param name="building">tells physics to delay full construction of object</param>
4046 /// The physics actor. null if there was a failure. 4619 /// <param name="applyDynamics">applies velocities, force and torque</param>
4047 /// </returns> 4620 private void AddToPhysics(bool isPhysical, bool isPhantom, bool building, bool applyDynamics)
4048 private PhysicsActor AddToPhysics(bool rigidBody) 4621 {
4049 {
4050 PhysicsActor pa; 4622 PhysicsActor pa;
4051 4623
4624 Vector3 velocity = Velocity;
4625 Vector3 rotationalVelocity = AngularVelocity;;
4626
4052 try 4627 try
4053 { 4628 {
4054 pa = ParentGroup.Scene.PhysicsScene.AddPrimShape( 4629 pa = ParentGroup.Scene.PhysicsScene.AddPrimShape(
4055 string.Format("{0}/{1}", Name, UUID), 4630 string.Format("{0}/{1}", Name, UUID),
4056 Shape, 4631 Shape,
4057 AbsolutePosition, 4632 AbsolutePosition,
4058 Scale, 4633 Scale,
4059 RotationOffset, 4634 GetWorldRotation(),
4060 rigidBody, 4635 isPhysical,
4061 m_localId); 4636 isPhantom,
4637 PhysicsShapeType,
4638 m_localId);
4062 } 4639 }
4063 catch (Exception e) 4640 catch (Exception e)
4064 { 4641 {
4065 m_log.ErrorFormat("[SCENE]: caught exception meshing object {0}. Object set to phantom. e={1}", m_uuid, e); 4642 m_log.ErrorFormat("[SCENE]: caught exception meshing object {0}. Object set to phantom. e={1}", m_uuid, e);
4066 pa = null; 4643 pa = null;
4067 } 4644 }
4068 4645
4069 // FIXME: Ideally we wouldn't set the property here to reduce situations where threads changing physical
4070 // properties can stop on each other. However, DoPhysicsPropertyUpdate() currently relies on PhysActor
4071 // being set.
4072 PhysActor = pa;
4073
4074 // Basic Physics can also return null as well as an exception catch.
4075 if (pa != null) 4646 if (pa != null)
4076 { 4647 {
4077 pa.SOPName = this.Name; // save object into the PhysActor so ODE internals know the joint/body info 4648 pa.SOPName = this.Name; // save object into the PhysActor so ODE internals know the joint/body info
4078 pa.SetMaterial(Material); 4649 pa.SetMaterial(Material);
4079 DoPhysicsPropertyUpdate(rigidBody, true); 4650
4651 if (VolumeDetectActive) // change if not the default only
4652 pa.SetVolumeDetect(1);
4653
4654 if (m_vehicleParams != null && LocalId == ParentGroup.RootPart.LocalId)
4655 m_vehicleParams.SetVehicle(pa);
4656
4657 // we are going to tell rest of code about physics so better have this here
4658 PhysActor = pa;
4659
4660 // DoPhysicsPropertyUpdate(isPhysical, true);
4661 // lets expand it here just with what it really needs to do
4662
4663 if (isPhysical)
4664 {
4665 if (ParentGroup.RootPart.KeyframeMotion != null)
4666 ParentGroup.RootPart.KeyframeMotion.Stop();
4667 ParentGroup.RootPart.KeyframeMotion = null;
4668 ParentGroup.Scene.AddPhysicalPrim(1);
4669
4670 pa.OnRequestTerseUpdate += PhysicsRequestingTerseUpdate;
4671 pa.OnOutOfBounds += PhysicsOutOfBounds;
4672
4673 if (ParentID != 0 && ParentID != LocalId)
4674 {
4675 PhysicsActor parentPa = ParentGroup.RootPart.PhysActor;
4676
4677 if (parentPa != null)
4678 {
4679 pa.link(parentPa);
4680 }
4681 }
4682 }
4683
4684 if (applyDynamics)
4685 // do independent of isphysical so parameters get setted (at least some)
4686 {
4687 Velocity = velocity;
4688 AngularVelocity = rotationalVelocity;
4689// pa.Velocity = velocity;
4690 pa.RotationalVelocity = rotationalVelocity;
4691
4692 // if not vehicle and root part apply force and torque
4693 if ((m_vehicleParams == null || m_vehicleParams.Type == Vehicle.TYPE_NONE)
4694 && LocalId == ParentGroup.RootPart.LocalId)
4695 {
4696 pa.Force = Force;
4697 pa.Torque = Torque;
4698 }
4699 }
4700
4701// if (Shape.SculptEntry)
4702// CheckSculptAndLoad();
4703// else
4704 ParentGroup.Scene.PhysicsScene.AddPhysicsActorTaint(pa);
4705
4706 if (!building)
4707 pa.Building = false;
4080 } 4708 }
4081 4709
4082 return pa; 4710 PhysActor = pa;
4083 } 4711 }
4084 4712
4085 /// <summary> 4713 /// <summary>
4086 /// This removes the part from the physics scene. 4714 /// This removes the part from the physics scene.
4087 /// </summary> 4715 /// </summary>
4088 /// <remarks> 4716 /// <remarks>
4089 /// This isn't the same as turning off physical, since even without being physical the prim has a physics 4717 /// This isn't the same as turning off physical, since even without being physical the prim has a physics
4090 /// representation for collision detection. Rather, this would be used in situations such as making a prim 4718 /// representation for collision detection.
4091 /// phantom.
4092 /// </remarks> 4719 /// </remarks>
4093 public void RemoveFromPhysics() 4720 public void RemoveFromPhysics()
4094 { 4721 {
4095 ParentGroup.Scene.PhysicsScene.RemovePrim(PhysActor); 4722 PhysicsActor pa = PhysActor;
4723 if (pa != null)
4724 {
4725 pa.OnCollisionUpdate -= PhysicsCollision;
4726 pa.OnRequestTerseUpdate -= PhysicsRequestingTerseUpdate;
4727 pa.OnOutOfBounds -= PhysicsOutOfBounds;
4728
4729 ParentGroup.Scene.PhysicsScene.RemovePrim(pa);
4730 }
4096 PhysActor = null; 4731 PhysActor = null;
4097 } 4732 }
4098 4733
@@ -4224,6 +4859,8 @@ namespace OpenSim.Region.Framework.Scenes
4224 { 4859 {
4225// m_log.DebugFormat("Processing CheckSculptAndLoad for {0} {1}", Name, LocalId); 4860// m_log.DebugFormat("Processing CheckSculptAndLoad for {0} {1}", Name, LocalId);
4226 4861
4862 return;
4863
4227 if (ParentGroup.IsDeleted) 4864 if (ParentGroup.IsDeleted)
4228 return; 4865 return;
4229 4866
@@ -4304,6 +4941,44 @@ namespace OpenSim.Region.Framework.Scenes
4304 ScheduleFullUpdate(); 4941 ScheduleFullUpdate();
4305 } 4942 }
4306 4943
4944
4945 private void UpdatePhysicsSubscribedEvents()
4946 {
4947 PhysicsActor pa = PhysActor;
4948 if (pa == null)
4949 return;
4950
4951 pa.OnCollisionUpdate -= PhysicsCollision;
4952
4953 bool hassound = (!VolumeDetectActive && CollisionSoundType >= 0 && ((Flags & PrimFlags.Physics) != 0));
4954
4955 scriptEvents CombinedEvents = AggregateScriptEvents;
4956
4957 // merge with root part
4958 if (ParentGroup != null && ParentGroup.RootPart != null)
4959 CombinedEvents |= ParentGroup.RootPart.AggregateScriptEvents;
4960
4961 // submit to this part case
4962 if (VolumeDetectActive)
4963 CombinedEvents &= PhyscicsVolumeDtcSubsEvents;
4964 else if ((Flags & PrimFlags.Phantom) != 0)
4965 CombinedEvents &= PhyscicsPhantonSubsEvents;
4966 else
4967 CombinedEvents &= PhysicsNeededSubsEvents;
4968
4969 if (hassound || CombinedEvents != 0)
4970 {
4971 // subscribe to physics updates.
4972 pa.OnCollisionUpdate += PhysicsCollision;
4973 pa.SubscribeEvents(50); // 20 reports per second
4974 }
4975 else
4976 {
4977 pa.UnSubscribeEvents();
4978 }
4979 }
4980
4981
4307 public void aggregateScriptEvents() 4982 public void aggregateScriptEvents()
4308 { 4983 {
4309 if (ParentGroup == null || ParentGroup.RootPart == null) 4984 if (ParentGroup == null || ParentGroup.RootPart == null)
@@ -4340,40 +5015,32 @@ namespace OpenSim.Region.Framework.Scenes
4340 { 5015 {
4341 objectflagupdate |= (uint) PrimFlags.AllowInventoryDrop; 5016 objectflagupdate |= (uint) PrimFlags.AllowInventoryDrop;
4342 } 5017 }
4343 5018/*
4344 PhysicsActor pa = PhysActor; 5019 PhysicsActor pa = PhysActor;
4345 5020 if (pa != null)
4346 if (
4347 ((AggregateScriptEvents & scriptEvents.collision) != 0) ||
4348 ((AggregateScriptEvents & scriptEvents.collision_end) != 0) ||
4349 ((AggregateScriptEvents & scriptEvents.collision_start) != 0) ||
4350 ((AggregateScriptEvents & scriptEvents.land_collision_start) != 0) ||
4351 ((AggregateScriptEvents & scriptEvents.land_collision) != 0) ||
4352 ((AggregateScriptEvents & scriptEvents.land_collision_end) != 0) ||
4353 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.collision) != 0) ||
4354 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.collision_end) != 0) ||
4355 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.collision_start) != 0) ||
4356 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.land_collision_start) != 0) ||
4357 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.land_collision) != 0) ||
4358 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.land_collision_end) != 0) ||
4359 (CollisionSound != UUID.Zero)
4360 )
4361 { 5021 {
4362 // subscribe to physics updates. 5022 if (
4363 if (pa != null) 5023// ((AggregateScriptEvents & scriptEvents.collision) != 0) ||
5024// ((AggregateScriptEvents & scriptEvents.collision_end) != 0) ||
5025// ((AggregateScriptEvents & scriptEvents.collision_start) != 0) ||
5026// ((AggregateScriptEvents & scriptEvents.land_collision_start) != 0) ||
5027// ((AggregateScriptEvents & scriptEvents.land_collision) != 0) ||
5028// ((AggregateScriptEvents & scriptEvents.land_collision_end) != 0) ||
5029 ((AggregateScriptEvents & PhysicsNeededSubsEvents) != 0) || ((ParentGroup.RootPart.AggregateScriptEvents & PhysicsNeededSubsEvents) != 0) || (CollisionSound != UUID.Zero)
5030 )
4364 { 5031 {
5032 // subscribe to physics updates.
4365 pa.OnCollisionUpdate += PhysicsCollision; 5033 pa.OnCollisionUpdate += PhysicsCollision;
4366 pa.SubscribeEvents(1000); 5034 pa.SubscribeEvents(1000);
4367 } 5035 }
4368 } 5036 else
4369 else
4370 {
4371 if (pa != null)
4372 { 5037 {
4373 pa.UnSubscribeEvents(); 5038 pa.UnSubscribeEvents();
4374 pa.OnCollisionUpdate -= PhysicsCollision; 5039 pa.OnCollisionUpdate -= PhysicsCollision;
4375 } 5040 }
4376 } 5041 }
5042 */
5043 UpdatePhysicsSubscribedEvents();
4377 5044
4378 //if ((GetEffectiveObjectFlags() & (uint)PrimFlags.Scripted) != 0) 5045 //if ((GetEffectiveObjectFlags() & (uint)PrimFlags.Scripted) != 0)
4379 //{ 5046 //{
@@ -4504,6 +5171,18 @@ namespace OpenSim.Region.Framework.Scenes
4504 return new Color4(color.R, color.G, color.B, (byte)(0xFF - color.A)); 5171 return new Color4(color.R, color.G, color.B, (byte)(0xFF - color.A));
4505 } 5172 }
4506 5173
5174 public void ResetOwnerChangeFlag()
5175 {
5176 List<UUID> inv = Inventory.GetInventoryList();
5177
5178 foreach (UUID itemID in inv)
5179 {
5180 TaskInventoryItem item = Inventory.GetInventoryItem(itemID);
5181 item.OwnerChanged = false;
5182 Inventory.UpdateInventoryItem(item, false, false);
5183 }
5184 }
5185
4507 /// <summary> 5186 /// <summary>
4508 /// Record an avatar sitting on this part. 5187 /// Record an avatar sitting on this part.
4509 /// </summary> 5188 /// </summary>
@@ -4597,4 +5276,4 @@ namespace OpenSim.Region.Framework.Scenes
4597 } 5276 }
4598 } 5277 }
4599 } 5278 }
4600} \ No newline at end of file 5279}
diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs b/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs
index db723fa..3a9a146 100644
--- a/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs
@@ -48,6 +48,9 @@ namespace OpenSim.Region.Framework.Scenes
48 private string m_inventoryFileName = String.Empty; 48 private string m_inventoryFileName = String.Empty;
49 private byte[] m_inventoryFileData = new byte[0]; 49 private byte[] m_inventoryFileData = new byte[0];
50 private uint m_inventoryFileNameSerial = 0; 50 private uint m_inventoryFileNameSerial = 0;
51 private bool m_inventoryPrivileged = false;
52
53 private Dictionary<UUID, ArrayList> m_scriptErrors = new Dictionary<UUID, ArrayList>();
51 54
52 /// <value> 55 /// <value>
53 /// The part to which the inventory belongs. 56 /// The part to which the inventory belongs.
@@ -84,7 +87,9 @@ namespace OpenSim.Region.Framework.Scenes
84 /// </value> 87 /// </value>
85 protected internal TaskInventoryDictionary Items 88 protected internal TaskInventoryDictionary Items
86 { 89 {
87 get { return m_items; } 90 get {
91 return m_items;
92 }
88 set 93 set
89 { 94 {
90 m_items = value; 95 m_items = value;
@@ -133,38 +138,45 @@ namespace OpenSim.Region.Framework.Scenes
133 public void ResetInventoryIDs() 138 public void ResetInventoryIDs()
134 { 139 {
135 if (null == m_part) 140 if (null == m_part)
136 return; 141 m_items.LockItemsForWrite(true);
137 142
138 lock (m_items) 143 if (Items.Count == 0)
139 { 144 {
140 if (0 == m_items.Count) 145 m_items.LockItemsForWrite(false);
141 return; 146 return;
147 }
142 148
143 IList<TaskInventoryItem> items = GetInventoryItems(); 149 IList<TaskInventoryItem> items = new List<TaskInventoryItem>(Items.Values);
144 m_items.Clear(); 150 Items.Clear();
145 151
146 foreach (TaskInventoryItem item in items) 152 foreach (TaskInventoryItem item in items)
147 { 153 {
148 item.ResetIDs(m_part.UUID); 154 item.ResetIDs(m_part.UUID);
149 m_items.Add(item.ItemID, item); 155 Items.Add(item.ItemID, item);
150 }
151 } 156 }
157 m_items.LockItemsForWrite(false);
152 } 158 }
153 159
154 public void ResetObjectID() 160 public void ResetObjectID()
155 { 161 {
156 lock (Items) 162 m_items.LockItemsForWrite(true);
163
164 if (Items.Count == 0)
157 { 165 {
158 IList<TaskInventoryItem> items = new List<TaskInventoryItem>(Items.Values); 166 m_items.LockItemsForWrite(false);
159 Items.Clear(); 167 return;
160
161 foreach (TaskInventoryItem item in items)
162 {
163 item.ParentPartID = m_part.UUID;
164 item.ParentID = m_part.UUID;
165 Items.Add(item.ItemID, item);
166 }
167 } 168 }
169
170 IList<TaskInventoryItem> items = new List<TaskInventoryItem>(Items.Values);
171 Items.Clear();
172
173 foreach (TaskInventoryItem item in items)
174 {
175 item.ParentPartID = m_part.UUID;
176 item.ParentID = m_part.UUID;
177 Items.Add(item.ItemID, item);
178 }
179 m_items.LockItemsForWrite(false);
168 } 180 }
169 181
170 /// <summary> 182 /// <summary>
@@ -173,17 +185,14 @@ namespace OpenSim.Region.Framework.Scenes
173 /// <param name="ownerId"></param> 185 /// <param name="ownerId"></param>
174 public void ChangeInventoryOwner(UUID ownerId) 186 public void ChangeInventoryOwner(UUID ownerId)
175 { 187 {
176 lock (Items) 188 List<TaskInventoryItem> items = GetInventoryItems();
177 { 189
178 if (0 == Items.Count) 190 if (items.Count == 0)
179 { 191 return;
180 return;
181 }
182 }
183 192
193 m_items.LockItemsForWrite(true);
184 HasInventoryChanged = true; 194 HasInventoryChanged = true;
185 m_part.ParentGroup.HasGroupChanged = true; 195 m_part.ParentGroup.HasGroupChanged = true;
186 List<TaskInventoryItem> items = GetInventoryItems();
187 foreach (TaskInventoryItem item in items) 196 foreach (TaskInventoryItem item in items)
188 { 197 {
189 if (ownerId != item.OwnerID) 198 if (ownerId != item.OwnerID)
@@ -194,6 +203,7 @@ namespace OpenSim.Region.Framework.Scenes
194 item.PermsGranter = UUID.Zero; 203 item.PermsGranter = UUID.Zero;
195 item.OwnerChanged = true; 204 item.OwnerChanged = true;
196 } 205 }
206 m_items.LockItemsForWrite(false);
197 } 207 }
198 208
199 /// <summary> 209 /// <summary>
@@ -202,12 +212,11 @@ namespace OpenSim.Region.Framework.Scenes
202 /// <param name="groupID"></param> 212 /// <param name="groupID"></param>
203 public void ChangeInventoryGroup(UUID groupID) 213 public void ChangeInventoryGroup(UUID groupID)
204 { 214 {
205 lock (Items) 215 m_items.LockItemsForWrite(true);
216 if (0 == Items.Count)
206 { 217 {
207 if (0 == Items.Count) 218 m_items.LockItemsForWrite(false);
208 { 219 return;
209 return;
210 }
211 } 220 }
212 221
213 // Don't let this set the HasGroupChanged flag for attachments 222 // Don't let this set the HasGroupChanged flag for attachments
@@ -219,12 +228,15 @@ namespace OpenSim.Region.Framework.Scenes
219 m_part.ParentGroup.HasGroupChanged = true; 228 m_part.ParentGroup.HasGroupChanged = true;
220 } 229 }
221 230
222 List<TaskInventoryItem> items = GetInventoryItems(); 231 IList<TaskInventoryItem> items = new List<TaskInventoryItem>(Items.Values);
223 foreach (TaskInventoryItem item in items) 232 foreach (TaskInventoryItem item in items)
224 { 233 {
225 if (groupID != item.GroupID) 234 if (groupID != item.GroupID)
235 {
226 item.GroupID = groupID; 236 item.GroupID = groupID;
237 }
227 } 238 }
239 m_items.LockItemsForWrite(false);
228 } 240 }
229 241
230 private void QueryScriptStates() 242 private void QueryScriptStates()
@@ -232,15 +244,18 @@ namespace OpenSim.Region.Framework.Scenes
232 if (m_part == null || m_part.ParentGroup == null || m_part.ParentGroup.Scene == null) 244 if (m_part == null || m_part.ParentGroup == null || m_part.ParentGroup.Scene == null)
233 return; 245 return;
234 246
235 lock (Items) 247 Items.LockItemsForRead(true);
248 foreach (TaskInventoryItem item in Items.Values)
236 { 249 {
237 foreach (TaskInventoryItem item in Items.Values) 250 if (item.InvType == (int)InventoryType.LSL)
238 { 251 {
239 bool running; 252 bool running;
240 if (TryGetScriptInstanceRunning(m_part.ParentGroup.Scene, item, out running)) 253 if (TryGetScriptInstanceRunning(m_part.ParentGroup.Scene, item, out running))
241 item.ScriptRunning = running; 254 item.ScriptRunning = running;
242 } 255 }
243 } 256 }
257
258 Items.LockItemsForRead(false);
244 } 259 }
245 260
246 public bool TryGetScriptInstanceRunning(UUID itemId, out bool running) 261 public bool TryGetScriptInstanceRunning(UUID itemId, out bool running)
@@ -317,7 +332,10 @@ namespace OpenSim.Region.Framework.Scenes
317 { 332 {
318 List<TaskInventoryItem> scripts = GetInventoryItems(InventoryType.LSL); 333 List<TaskInventoryItem> scripts = GetInventoryItems(InventoryType.LSL);
319 foreach (TaskInventoryItem item in scripts) 334 foreach (TaskInventoryItem item in scripts)
335 {
320 RemoveScriptInstance(item.ItemID, sceneObjectBeingDeleted); 336 RemoveScriptInstance(item.ItemID, sceneObjectBeingDeleted);
337 m_part.RemoveScriptEvents(item.ItemID);
338 }
321 } 339 }
322 340
323 /// <summary> 341 /// <summary>
@@ -339,7 +357,10 @@ namespace OpenSim.Region.Framework.Scenes
339// item.Name, item.ItemID, m_part.Name, m_part.UUID, m_part.ParentGroup.Scene.RegionInfo.RegionName); 357// item.Name, item.ItemID, m_part.Name, m_part.UUID, m_part.ParentGroup.Scene.RegionInfo.RegionName);
340 358
341 if (!m_part.ParentGroup.Scene.Permissions.CanRunScript(item.ItemID, m_part.UUID, item.OwnerID)) 359 if (!m_part.ParentGroup.Scene.Permissions.CanRunScript(item.ItemID, m_part.UUID, item.OwnerID))
360 {
361 StoreScriptError(item.ItemID, "no permission");
342 return false; 362 return false;
363 }
343 364
344 m_part.AddFlag(PrimFlags.Scripted); 365 m_part.AddFlag(PrimFlags.Scripted);
345 366
@@ -349,14 +370,13 @@ namespace OpenSim.Region.Framework.Scenes
349 if (stateSource == 2 && // Prim crossing 370 if (stateSource == 2 && // Prim crossing
350 m_part.ParentGroup.Scene.m_trustBinaries) 371 m_part.ParentGroup.Scene.m_trustBinaries)
351 { 372 {
352 lock (m_items) 373 m_items.LockItemsForWrite(true);
353 { 374 m_items[item.ItemID].PermsMask = 0;
354 m_items[item.ItemID].PermsMask = 0; 375 m_items[item.ItemID].PermsGranter = UUID.Zero;
355 m_items[item.ItemID].PermsGranter = UUID.Zero; 376 m_items.LockItemsForWrite(false);
356 }
357
358 m_part.ParentGroup.Scene.EventManager.TriggerRezScript( 377 m_part.ParentGroup.Scene.EventManager.TriggerRezScript(
359 m_part.LocalId, item.ItemID, String.Empty, startParam, postOnRez, engine, stateSource); 378 m_part.LocalId, item.ItemID, String.Empty, startParam, postOnRez, engine, stateSource);
379 StoreScriptErrors(item.ItemID, null);
360 m_part.ParentGroup.AddActiveScriptCount(1); 380 m_part.ParentGroup.AddActiveScriptCount(1);
361 m_part.ScheduleFullUpdate(); 381 m_part.ScheduleFullUpdate();
362 return true; 382 return true;
@@ -365,6 +385,8 @@ namespace OpenSim.Region.Framework.Scenes
365 AssetBase asset = m_part.ParentGroup.Scene.AssetService.Get(item.AssetID.ToString()); 385 AssetBase asset = m_part.ParentGroup.Scene.AssetService.Get(item.AssetID.ToString());
366 if (null == asset) 386 if (null == asset)
367 { 387 {
388 string msg = String.Format("asset ID {0} could not be found", item.AssetID);
389 StoreScriptError(item.ItemID, msg);
368 m_log.ErrorFormat( 390 m_log.ErrorFormat(
369 "[PRIM INVENTORY]: Couldn't start script {0}, {1} at {2} in {3} since asset ID {4} could not be found", 391 "[PRIM INVENTORY]: Couldn't start script {0}, {1} at {2} in {3} since asset ID {4} could not be found",
370 item.Name, item.ItemID, m_part.AbsolutePosition, 392 item.Name, item.ItemID, m_part.AbsolutePosition,
@@ -377,16 +399,18 @@ namespace OpenSim.Region.Framework.Scenes
377 if (m_part.ParentGroup.m_savedScriptState != null) 399 if (m_part.ParentGroup.m_savedScriptState != null)
378 item.OldItemID = RestoreSavedScriptState(item.LoadedItemID, item.OldItemID, item.ItemID); 400 item.OldItemID = RestoreSavedScriptState(item.LoadedItemID, item.OldItemID, item.ItemID);
379 401
380 lock (m_items) 402 m_items.LockItemsForWrite(true);
381 { 403
382 m_items[item.ItemID].OldItemID = item.OldItemID; 404 m_items[item.ItemID].OldItemID = item.OldItemID;
383 m_items[item.ItemID].PermsMask = 0; 405 m_items[item.ItemID].PermsMask = 0;
384 m_items[item.ItemID].PermsGranter = UUID.Zero; 406 m_items[item.ItemID].PermsGranter = UUID.Zero;
385 }
386 407
408 m_items.LockItemsForWrite(false);
409
387 string script = Utils.BytesToString(asset.Data); 410 string script = Utils.BytesToString(asset.Data);
388 m_part.ParentGroup.Scene.EventManager.TriggerRezScript( 411 m_part.ParentGroup.Scene.EventManager.TriggerRezScript(
389 m_part.LocalId, item.ItemID, script, startParam, postOnRez, engine, stateSource); 412 m_part.LocalId, item.ItemID, script, startParam, postOnRez, engine, stateSource);
413 StoreScriptErrors(item.ItemID, null);
390 if (!item.ScriptRunning) 414 if (!item.ScriptRunning)
391 m_part.ParentGroup.Scene.EventManager.TriggerStopScript( 415 m_part.ParentGroup.Scene.EventManager.TriggerStopScript(
392 m_part.LocalId, item.ItemID); 416 m_part.LocalId, item.ItemID);
@@ -459,22 +483,149 @@ namespace OpenSim.Region.Framework.Scenes
459 return stateID; 483 return stateID;
460 } 484 }
461 485
486 /// <summary>
487 /// Start a script which is in this prim's inventory.
488 /// Some processing may occur in the background, but this routine returns asap.
489 /// </summary>
490 /// <param name="itemId">
491 /// A <see cref="UUID"/>
492 /// </param>
462 public bool CreateScriptInstance(UUID itemId, int startParam, bool postOnRez, string engine, int stateSource) 493 public bool CreateScriptInstance(UUID itemId, int startParam, bool postOnRez, string engine, int stateSource)
463 { 494 {
464 TaskInventoryItem item = GetInventoryItem(itemId); 495 lock (m_scriptErrors)
465 if (item != null)
466 { 496 {
467 return CreateScriptInstance(item, startParam, postOnRez, engine, stateSource); 497 // Indicate to CreateScriptInstanceInternal() we don't want it to wait for completion
498 m_scriptErrors.Remove(itemId);
499 }
500 CreateScriptInstanceInternal(itemId, startParam, postOnRez, engine, stateSource);
501 return true;
502 }
503
504 private void CreateScriptInstanceInternal(UUID itemId, int startParam, bool postOnRez, string engine, int stateSource)
505 {
506 m_items.LockItemsForRead(true);
507 if (m_items.ContainsKey(itemId))
508 {
509 if (m_items.ContainsKey(itemId))
510 {
511 m_items.LockItemsForRead(false);
512 CreateScriptInstance(m_items[itemId], startParam, postOnRez, engine, stateSource);
513 }
514 else
515 {
516 m_items.LockItemsForRead(false);
517 string msg = String.Format("couldn't be found for prim {0}, {1} at {2} in {3}", m_part.Name, m_part.UUID,
518 m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
519 StoreScriptError(itemId, msg);
520 m_log.ErrorFormat(
521 "[PRIM INVENTORY]: " +
522 "Couldn't start script with ID {0} since it {1}", itemId, msg);
523 }
468 } 524 }
469 else 525 else
470 { 526 {
527 m_items.LockItemsForRead(false);
528 string msg = String.Format("couldn't be found for prim {0}, {1}", m_part.Name, m_part.UUID);
529 StoreScriptError(itemId, msg);
471 m_log.ErrorFormat( 530 m_log.ErrorFormat(
472 "[PRIM INVENTORY]: Couldn't start script with ID {0} since it couldn't be found for prim {1}, {2} at {3} in {4}", 531 "[PRIM INVENTORY]: Couldn't start script with ID {0} since it couldn't be found for prim {1}, {2} at {3} in {4}",
473 itemId, m_part.Name, m_part.UUID, 532 itemId, m_part.Name, m_part.UUID,
474 m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName); 533 m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
534 }
535
536 }
475 537
476 return false; 538 /// <summary>
539 /// Start a script which is in this prim's inventory and return any compilation error messages.
540 /// </summary>
541 /// <param name="itemId">
542 /// A <see cref="UUID"/>
543 /// </param>
544 public ArrayList CreateScriptInstanceEr(UUID itemId, int startParam, bool postOnRez, string engine, int stateSource)
545 {
546 ArrayList errors;
547
548 // Indicate to CreateScriptInstanceInternal() we want it to
549 // post any compilation/loading error messages
550 lock (m_scriptErrors)
551 {
552 m_scriptErrors[itemId] = null;
553 }
554
555 // Perform compilation/loading
556 CreateScriptInstanceInternal(itemId, startParam, postOnRez, engine, stateSource);
557
558 // Wait for and retrieve any errors
559 lock (m_scriptErrors)
560 {
561 while ((errors = m_scriptErrors[itemId]) == null)
562 {
563 if (!System.Threading.Monitor.Wait(m_scriptErrors, 15000))
564 {
565 m_log.ErrorFormat(
566 "[PRIM INVENTORY]: " +
567 "timedout waiting for script {0} errors", itemId);
568 errors = m_scriptErrors[itemId];
569 if (errors == null)
570 {
571 errors = new ArrayList(1);
572 errors.Add("timedout waiting for errors");
573 }
574 break;
575 }
576 }
577 m_scriptErrors.Remove(itemId);
477 } 578 }
579 return errors;
580 }
581
582 // Signal to CreateScriptInstanceEr() that compilation/loading is complete
583 private void StoreScriptErrors(UUID itemId, ArrayList errors)
584 {
585 lock (m_scriptErrors)
586 {
587 // If compilation/loading initiated via CreateScriptInstance(),
588 // it does not want the errors, so just get out
589 if (!m_scriptErrors.ContainsKey(itemId))
590 {
591 return;
592 }
593
594 // Initiated via CreateScriptInstanceEr(), if we know what the
595 // errors are, save them and wake CreateScriptInstanceEr().
596 if (errors != null)
597 {
598 m_scriptErrors[itemId] = errors;
599 System.Threading.Monitor.PulseAll(m_scriptErrors);
600 return;
601 }
602 }
603
604 // Initiated via CreateScriptInstanceEr() but we don't know what
605 // the errors are yet, so retrieve them from the script engine.
606 // This may involve some waiting internal to GetScriptErrors().
607 errors = GetScriptErrors(itemId);
608
609 // Get a default non-null value to indicate success.
610 if (errors == null)
611 {
612 errors = new ArrayList();
613 }
614
615 // Post to CreateScriptInstanceEr() and wake it up
616 lock (m_scriptErrors)
617 {
618 m_scriptErrors[itemId] = errors;
619 System.Threading.Monitor.PulseAll(m_scriptErrors);
620 }
621 }
622
623 // Like StoreScriptErrors(), but just posts a single string message
624 private void StoreScriptError(UUID itemId, string message)
625 {
626 ArrayList errors = new ArrayList(1);
627 errors.Add(message);
628 StoreScriptErrors(itemId, errors);
478 } 629 }
479 630
480 /// <summary> 631 /// <summary>
@@ -487,15 +638,7 @@ namespace OpenSim.Region.Framework.Scenes
487 /// </param> 638 /// </param>
488 public void RemoveScriptInstance(UUID itemId, bool sceneObjectBeingDeleted) 639 public void RemoveScriptInstance(UUID itemId, bool sceneObjectBeingDeleted)
489 { 640 {
490 bool scriptPresent = false; 641 if (m_items.ContainsKey(itemId))
491
492 lock (m_items)
493 {
494 if (m_items.ContainsKey(itemId))
495 scriptPresent = true;
496 }
497
498 if (scriptPresent)
499 { 642 {
500 if (!sceneObjectBeingDeleted) 643 if (!sceneObjectBeingDeleted)
501 m_part.RemoveScriptEvents(itemId); 644 m_part.RemoveScriptEvents(itemId);
@@ -565,14 +708,16 @@ namespace OpenSim.Region.Framework.Scenes
565 /// <returns></returns> 708 /// <returns></returns>
566 private bool InventoryContainsName(string name) 709 private bool InventoryContainsName(string name)
567 { 710 {
568 lock (m_items) 711 m_items.LockItemsForRead(true);
712 foreach (TaskInventoryItem item in m_items.Values)
569 { 713 {
570 foreach (TaskInventoryItem item in m_items.Values) 714 if (item.Name == name)
571 { 715 {
572 if (item.Name == name) 716 m_items.LockItemsForRead(false);
573 return true; 717 return true;
574 } 718 }
575 } 719 }
720 m_items.LockItemsForRead(false);
576 return false; 721 return false;
577 } 722 }
578 723
@@ -614,8 +759,9 @@ namespace OpenSim.Region.Framework.Scenes
614 /// <param name="item"></param> 759 /// <param name="item"></param>
615 public void AddInventoryItemExclusive(TaskInventoryItem item, bool allowedDrop) 760 public void AddInventoryItemExclusive(TaskInventoryItem item, bool allowedDrop)
616 { 761 {
617 List<TaskInventoryItem> il = GetInventoryItems(); 762 m_items.LockItemsForRead(true);
618 763 List<TaskInventoryItem> il = new List<TaskInventoryItem>(m_items.Values);
764 m_items.LockItemsForRead(false);
619 foreach (TaskInventoryItem i in il) 765 foreach (TaskInventoryItem i in il)
620 { 766 {
621 if (i.Name == item.Name) 767 if (i.Name == item.Name)
@@ -653,14 +799,14 @@ namespace OpenSim.Region.Framework.Scenes
653 item.Name = name; 799 item.Name = name;
654 item.GroupID = m_part.GroupID; 800 item.GroupID = m_part.GroupID;
655 801
656 lock (m_items) 802 m_items.LockItemsForWrite(true);
657 m_items.Add(item.ItemID, item); 803 m_items.Add(item.ItemID, item);
658 804 m_items.LockItemsForWrite(false);
659 if (allowedDrop) 805 if (allowedDrop)
660 m_part.TriggerScriptChangedEvent(Changed.ALLOWED_DROP); 806 m_part.TriggerScriptChangedEvent(Changed.ALLOWED_DROP);
661 else 807 else
662 m_part.TriggerScriptChangedEvent(Changed.INVENTORY); 808 m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
663 809
664 m_inventorySerial++; 810 m_inventorySerial++;
665 //m_inventorySerial += 2; 811 //m_inventorySerial += 2;
666 HasInventoryChanged = true; 812 HasInventoryChanged = true;
@@ -676,15 +822,15 @@ namespace OpenSim.Region.Framework.Scenes
676 /// <param name="items"></param> 822 /// <param name="items"></param>
677 public void RestoreInventoryItems(ICollection<TaskInventoryItem> items) 823 public void RestoreInventoryItems(ICollection<TaskInventoryItem> items)
678 { 824 {
679 lock (m_items) 825 m_items.LockItemsForWrite(true);
826 foreach (TaskInventoryItem item in items)
680 { 827 {
681 foreach (TaskInventoryItem item in items) 828 m_items.Add(item.ItemID, item);
682 { 829// m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
683 m_items.Add(item.ItemID, item);
684// m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
685 }
686 m_inventorySerial++;
687 } 830 }
831 m_items.LockItemsForWrite(false);
832
833 m_inventorySerial++;
688 } 834 }
689 835
690 /// <summary> 836 /// <summary>
@@ -695,23 +841,24 @@ namespace OpenSim.Region.Framework.Scenes
695 public TaskInventoryItem GetInventoryItem(UUID itemId) 841 public TaskInventoryItem GetInventoryItem(UUID itemId)
696 { 842 {
697 TaskInventoryItem item; 843 TaskInventoryItem item;
698 844 m_items.LockItemsForRead(true);
699 lock (m_items) 845 m_items.TryGetValue(itemId, out item);
700 m_items.TryGetValue(itemId, out item); 846 m_items.LockItemsForRead(false);
701
702 return item; 847 return item;
703 } 848 }
704 849
705 public TaskInventoryItem GetInventoryItem(string name) 850 public TaskInventoryItem GetInventoryItem(string name)
706 { 851 {
707 lock (m_items) 852 m_items.LockItemsForRead(true);
853 foreach (TaskInventoryItem item in m_items.Values)
708 { 854 {
709 foreach (TaskInventoryItem item in m_items.Values) 855 if (item.Name == name)
710 { 856 {
711 if (item.Name == name) 857 m_items.LockItemsForRead(false);
712 return item; 858 return item;
713 } 859 }
714 } 860 }
861 m_items.LockItemsForRead(false);
715 862
716 return null; 863 return null;
717 } 864 }
@@ -720,15 +867,16 @@ namespace OpenSim.Region.Framework.Scenes
720 { 867 {
721 List<TaskInventoryItem> items = new List<TaskInventoryItem>(); 868 List<TaskInventoryItem> items = new List<TaskInventoryItem>();
722 869
723 lock (m_items) 870 m_items.LockItemsForRead(true);
871
872 foreach (TaskInventoryItem item in m_items.Values)
724 { 873 {
725 foreach (TaskInventoryItem item in m_items.Values) 874 if (item.Name == name)
726 { 875 items.Add(item);
727 if (item.Name == name)
728 items.Add(item);
729 }
730 } 876 }
731 877
878 m_items.LockItemsForRead(false);
879
732 return items; 880 return items;
733 } 881 }
734 882
@@ -747,6 +895,10 @@ namespace OpenSim.Region.Framework.Scenes
747 string xmlData = Utils.BytesToString(rezAsset.Data); 895 string xmlData = Utils.BytesToString(rezAsset.Data);
748 SceneObjectGroup group = SceneObjectSerializer.FromOriginalXmlFormat(xmlData); 896 SceneObjectGroup group = SceneObjectSerializer.FromOriginalXmlFormat(xmlData);
749 897
898 group.RootPart.AttachPoint = group.RootPart.Shape.State;
899 group.RootPart.AttachOffset = group.AbsolutePosition;
900 group.RootPart.AttachRotation = group.GroupRotation;
901
750 group.ResetIDs(); 902 group.ResetIDs();
751 903
752 SceneObjectPart rootPart = group.GetPart(group.UUID); 904 SceneObjectPart rootPart = group.GetPart(group.UUID);
@@ -821,8 +973,9 @@ namespace OpenSim.Region.Framework.Scenes
821 973
822 public bool UpdateInventoryItem(TaskInventoryItem item, bool fireScriptEvents, bool considerChanged) 974 public bool UpdateInventoryItem(TaskInventoryItem item, bool fireScriptEvents, bool considerChanged)
823 { 975 {
824 TaskInventoryItem it = GetInventoryItem(item.ItemID); 976 m_items.LockItemsForWrite(true);
825 if (it != null) 977
978 if (m_items.ContainsKey(item.ItemID))
826 { 979 {
827// m_log.DebugFormat("[PRIM INVENTORY]: Updating item {0} in {1}", item.Name, m_part.Name); 980// m_log.DebugFormat("[PRIM INVENTORY]: Updating item {0} in {1}", item.Name, m_part.Name);
828 981
@@ -835,14 +988,10 @@ namespace OpenSim.Region.Framework.Scenes
835 item.GroupID = m_part.GroupID; 988 item.GroupID = m_part.GroupID;
836 989
837 if (item.AssetID == UUID.Zero) 990 if (item.AssetID == UUID.Zero)
838 item.AssetID = it.AssetID; 991 item.AssetID = m_items[item.ItemID].AssetID;
839 992
840 lock (m_items) 993 m_items[item.ItemID] = item;
841 { 994 m_inventorySerial++;
842 m_items[item.ItemID] = item;
843 m_inventorySerial++;
844 }
845
846 if (fireScriptEvents) 995 if (fireScriptEvents)
847 m_part.TriggerScriptChangedEvent(Changed.INVENTORY); 996 m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
848 997
@@ -851,7 +1000,7 @@ namespace OpenSim.Region.Framework.Scenes
851 HasInventoryChanged = true; 1000 HasInventoryChanged = true;
852 m_part.ParentGroup.HasGroupChanged = true; 1001 m_part.ParentGroup.HasGroupChanged = true;
853 } 1002 }
854 1003 m_items.LockItemsForWrite(false);
855 return true; 1004 return true;
856 } 1005 }
857 else 1006 else
@@ -862,8 +1011,9 @@ namespace OpenSim.Region.Framework.Scenes
862 item.ItemID, m_part.Name, m_part.UUID, 1011 item.ItemID, m_part.Name, m_part.UUID,
863 m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName); 1012 m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
864 } 1013 }
865 return false; 1014 m_items.LockItemsForWrite(false);
866 1015
1016 return false;
867 } 1017 }
868 1018
869 /// <summary> 1019 /// <summary>
@@ -874,43 +1024,59 @@ namespace OpenSim.Region.Framework.Scenes
874 /// in this prim's inventory.</returns> 1024 /// in this prim's inventory.</returns>
875 public int RemoveInventoryItem(UUID itemID) 1025 public int RemoveInventoryItem(UUID itemID)
876 { 1026 {
877 TaskInventoryItem item = GetInventoryItem(itemID); 1027 m_items.LockItemsForRead(true);
878 if (item != null) 1028
1029 if (m_items.ContainsKey(itemID))
879 { 1030 {
880 int type = m_items[itemID].InvType; 1031 int type = m_items[itemID].InvType;
1032 m_items.LockItemsForRead(false);
881 if (type == 10) // Script 1033 if (type == 10) // Script
882 { 1034 {
883 m_part.RemoveScriptEvents(itemID);
884 m_part.ParentGroup.Scene.EventManager.TriggerRemoveScript(m_part.LocalId, itemID); 1035 m_part.ParentGroup.Scene.EventManager.TriggerRemoveScript(m_part.LocalId, itemID);
885 } 1036 }
1037 m_items.LockItemsForWrite(true);
886 m_items.Remove(itemID); 1038 m_items.Remove(itemID);
1039 m_items.LockItemsForWrite(false);
887 m_inventorySerial++; 1040 m_inventorySerial++;
888 m_part.TriggerScriptChangedEvent(Changed.INVENTORY); 1041 m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
889 1042
890 HasInventoryChanged = true; 1043 HasInventoryChanged = true;
891 m_part.ParentGroup.HasGroupChanged = true; 1044 m_part.ParentGroup.HasGroupChanged = true;
892 1045
893 if (!ContainsScripts()) 1046 int scriptcount = 0;
1047 m_items.LockItemsForRead(true);
1048 foreach (TaskInventoryItem item in m_items.Values)
1049 {
1050 if (item.Type == 10)
1051 {
1052 scriptcount++;
1053 }
1054 }
1055 m_items.LockItemsForRead(false);
1056
1057
1058 if (scriptcount <= 0)
1059 {
894 m_part.RemFlag(PrimFlags.Scripted); 1060 m_part.RemFlag(PrimFlags.Scripted);
1061 }
895 1062
896 m_part.ScheduleFullUpdate(); 1063 m_part.ScheduleFullUpdate();
897 1064
898 return type; 1065 return type;
899
900 } 1066 }
901 else 1067 else
902 { 1068 {
1069 m_items.LockItemsForRead(false);
903 m_log.ErrorFormat( 1070 m_log.ErrorFormat(
904 "[PRIM INVENTORY]: " + 1071 "[PRIM INVENTORY]: " +
905 "Tried to remove item ID {0} from prim {1}, {2} at {3} in {4} but the item does not exist in this inventory", 1072 "Tried to remove item ID {0} from prim {1}, {2} but the item does not exist in this inventory",
906 itemID, m_part.Name, m_part.UUID, 1073 itemID, m_part.Name, m_part.UUID);
907 m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
908 } 1074 }
909 1075
910 return -1; 1076 return -1;
911 } 1077 }
912 1078
913 private bool CreateInventoryFile() 1079 private bool CreateInventoryFileName()
914 { 1080 {
915// m_log.DebugFormat( 1081// m_log.DebugFormat(
916// "[PRIM INVENTORY]: Creating inventory file for {0} {1} {2}, serial {3}", 1082// "[PRIM INVENTORY]: Creating inventory file for {0} {1} {2}, serial {3}",
@@ -919,70 +1085,12 @@ namespace OpenSim.Region.Framework.Scenes
919 if (m_inventoryFileName == String.Empty || 1085 if (m_inventoryFileName == String.Empty ||
920 m_inventoryFileNameSerial < m_inventorySerial) 1086 m_inventoryFileNameSerial < m_inventorySerial)
921 { 1087 {
922 // Something changed, we need to create a new file
923 m_inventoryFileName = "inventory_" + UUID.Random().ToString() + ".tmp"; 1088 m_inventoryFileName = "inventory_" + UUID.Random().ToString() + ".tmp";
924 m_inventoryFileNameSerial = m_inventorySerial; 1089 m_inventoryFileNameSerial = m_inventorySerial;
925 1090
926 InventoryStringBuilder invString = new InventoryStringBuilder(m_part.UUID, UUID.Zero);
927
928 lock (m_items)
929 {
930 foreach (TaskInventoryItem item in m_items.Values)
931 {
932// m_log.DebugFormat(
933// "[PRIM INVENTORY]: Adding item {0} {1} for serial {2} on prim {3} {4} {5}",
934// item.Name, item.ItemID, m_inventorySerial, m_part.Name, m_part.UUID, m_part.LocalId);
935
936 UUID ownerID = item.OwnerID;
937 uint everyoneMask = 0;
938 uint baseMask = item.BasePermissions;
939 uint ownerMask = item.CurrentPermissions;
940 uint groupMask = item.GroupPermissions;
941
942 invString.AddItemStart();
943 invString.AddNameValueLine("item_id", item.ItemID.ToString());
944 invString.AddNameValueLine("parent_id", m_part.UUID.ToString());
945
946 invString.AddPermissionsStart();
947
948 invString.AddNameValueLine("base_mask", Utils.UIntToHexString(baseMask));
949 invString.AddNameValueLine("owner_mask", Utils.UIntToHexString(ownerMask));
950 invString.AddNameValueLine("group_mask", Utils.UIntToHexString(groupMask));
951 invString.AddNameValueLine("everyone_mask", Utils.UIntToHexString(everyoneMask));
952 invString.AddNameValueLine("next_owner_mask", Utils.UIntToHexString(item.NextPermissions));
953
954 invString.AddNameValueLine("creator_id", item.CreatorID.ToString());
955 invString.AddNameValueLine("owner_id", ownerID.ToString());
956
957 invString.AddNameValueLine("last_owner_id", item.LastOwnerID.ToString());
958
959 invString.AddNameValueLine("group_id", item.GroupID.ToString());
960 invString.AddSectionEnd();
961
962 invString.AddNameValueLine("asset_id", item.AssetID.ToString());
963 invString.AddNameValueLine("type", Utils.AssetTypeToString((AssetType)item.Type));
964 invString.AddNameValueLine("inv_type", Utils.InventoryTypeToString((InventoryType)item.InvType));
965 invString.AddNameValueLine("flags", Utils.UIntToHexString(item.Flags));
966
967 invString.AddSaleStart();
968 invString.AddNameValueLine("sale_type", "not");
969 invString.AddNameValueLine("sale_price", "0");
970 invString.AddSectionEnd();
971
972 invString.AddNameValueLine("name", item.Name + "|");
973 invString.AddNameValueLine("desc", item.Description + "|");
974
975 invString.AddNameValueLine("creation_date", item.CreationDate.ToString());
976 invString.AddSectionEnd();
977 }
978 }
979
980 m_inventoryFileData = Utils.StringToBytes(invString.BuildString);
981
982 return true; 1091 return true;
983 } 1092 }
984 1093
985 // No need to recreate, the existing file is fine
986 return false; 1094 return false;
987 } 1095 }
988 1096
@@ -992,43 +1100,110 @@ namespace OpenSim.Region.Framework.Scenes
992 /// <param name="xferManager"></param> 1100 /// <param name="xferManager"></param>
993 public void RequestInventoryFile(IClientAPI client, IXfer xferManager) 1101 public void RequestInventoryFile(IClientAPI client, IXfer xferManager)
994 { 1102 {
995 lock (m_items) 1103 bool changed = CreateInventoryFileName();
996 {
997 // Don't send a inventory xfer name if there are no items. Doing so causes viewer 3 to crash when rezzing
998 // a new script if any previous deletion has left the prim inventory empty.
999 if (m_items.Count == 0) // No inventory
1000 {
1001// m_log.DebugFormat(
1002// "[PRIM INVENTORY]: Not sending inventory data for part {0} {1} {2} for {3} since no items",
1003// m_part.Name, m_part.LocalId, m_part.UUID, client.Name);
1004 1104
1005 client.SendTaskInventory(m_part.UUID, 0, new byte[0]); 1105 bool includeAssets = false;
1006 return; 1106 if (m_part.ParentGroup.Scene.Permissions.CanEditObjectInventory(m_part.UUID, client.AgentId))
1007 } 1107 includeAssets = true;
1108
1109 if (m_inventoryPrivileged != includeAssets)
1110 changed = true;
1111
1112 InventoryStringBuilder invString = new InventoryStringBuilder(m_part.UUID, UUID.Zero);
1113
1114 Items.LockItemsForRead(true);
1115
1116 if (m_inventorySerial == 0) // No inventory
1117 {
1118 client.SendTaskInventory(m_part.UUID, 0, new byte[0]);
1119 Items.LockItemsForRead(false);
1120 return;
1121 }
1008 1122
1009 CreateInventoryFile(); 1123 if (m_items.Count == 0) // No inventory
1124 {
1125 client.SendTaskInventory(m_part.UUID, 0, new byte[0]);
1126 Items.LockItemsForRead(false);
1127 return;
1128 }
1010 1129
1011 // In principle, we should only do the rest if the inventory changed; 1130 if (!changed)
1012 // by sending m_inventorySerial to the client, it ought to know 1131 {
1013 // that nothing changed and that it doesn't need to request the file.
1014 // Unfortunately, it doesn't look like the client optimizes this;
1015 // the client seems to always come back and request the Xfer,
1016 // no matter what value m_inventorySerial has.
1017 // FIXME: Could probably be > 0 here rather than > 2
1018 if (m_inventoryFileData.Length > 2) 1132 if (m_inventoryFileData.Length > 2)
1019 { 1133 {
1020 // Add the file for Xfer 1134 xferManager.AddNewFile(m_inventoryFileName,
1021 // m_log.DebugFormat( 1135 m_inventoryFileData);
1022 // "[PRIM INVENTORY]: Adding inventory file {0} (length {1}) for transfer on {2} {3} {4}", 1136 client.SendTaskInventory(m_part.UUID, (short)m_inventorySerial,
1023 // m_inventoryFileName, m_inventoryFileData.Length, m_part.Name, m_part.UUID, m_part.LocalId); 1137 Util.StringToBytes256(m_inventoryFileName));
1024 1138
1025 xferManager.AddNewFile(m_inventoryFileName, m_inventoryFileData); 1139 Items.LockItemsForRead(false);
1140 return;
1026 } 1141 }
1027
1028 // Tell the client we're ready to Xfer the file
1029 client.SendTaskInventory(m_part.UUID, (short)m_inventorySerial,
1030 Util.StringToBytes256(m_inventoryFileName));
1031 } 1142 }
1143
1144 m_inventoryPrivileged = includeAssets;
1145
1146 foreach (TaskInventoryItem item in m_items.Values)
1147 {
1148 UUID ownerID = item.OwnerID;
1149 uint everyoneMask = 0;
1150 uint baseMask = item.BasePermissions;
1151 uint ownerMask = item.CurrentPermissions;
1152 uint groupMask = item.GroupPermissions;
1153
1154 invString.AddItemStart();
1155 invString.AddNameValueLine("item_id", item.ItemID.ToString());
1156 invString.AddNameValueLine("parent_id", m_part.UUID.ToString());
1157
1158 invString.AddPermissionsStart();
1159
1160 invString.AddNameValueLine("base_mask", Utils.UIntToHexString(baseMask));
1161 invString.AddNameValueLine("owner_mask", Utils.UIntToHexString(ownerMask));
1162 invString.AddNameValueLine("group_mask", Utils.UIntToHexString(groupMask));
1163 invString.AddNameValueLine("everyone_mask", Utils.UIntToHexString(everyoneMask));
1164 invString.AddNameValueLine("next_owner_mask", Utils.UIntToHexString(item.NextPermissions));
1165
1166 invString.AddNameValueLine("creator_id", item.CreatorID.ToString());
1167 invString.AddNameValueLine("owner_id", ownerID.ToString());
1168
1169 invString.AddNameValueLine("last_owner_id", item.LastOwnerID.ToString());
1170
1171 invString.AddNameValueLine("group_id", item.GroupID.ToString());
1172 invString.AddSectionEnd();
1173
1174 if (includeAssets)
1175 invString.AddNameValueLine("asset_id", item.AssetID.ToString());
1176 else
1177 invString.AddNameValueLine("asset_id", UUID.Zero.ToString());
1178 invString.AddNameValueLine("type", Utils.AssetTypeToString((AssetType)item.Type));
1179 invString.AddNameValueLine("inv_type", Utils.InventoryTypeToString((InventoryType)item.InvType));
1180 invString.AddNameValueLine("flags", Utils.UIntToHexString(item.Flags));
1181
1182 invString.AddSaleStart();
1183 invString.AddNameValueLine("sale_type", "not");
1184 invString.AddNameValueLine("sale_price", "0");
1185 invString.AddSectionEnd();
1186
1187 invString.AddNameValueLine("name", item.Name + "|");
1188 invString.AddNameValueLine("desc", item.Description + "|");
1189
1190 invString.AddNameValueLine("creation_date", item.CreationDate.ToString());
1191 invString.AddSectionEnd();
1192 }
1193
1194 Items.LockItemsForRead(false);
1195
1196 m_inventoryFileData = Utils.StringToBytes(invString.BuildString);
1197
1198 if (m_inventoryFileData.Length > 2)
1199 {
1200 xferManager.AddNewFile(m_inventoryFileName, m_inventoryFileData);
1201 client.SendTaskInventory(m_part.UUID, (short)m_inventorySerial,
1202 Util.StringToBytes256(m_inventoryFileName));
1203 return;
1204 }
1205
1206 client.SendTaskInventory(m_part.UUID, 0, new byte[0]);
1032 } 1207 }
1033 1208
1034 /// <summary> 1209 /// <summary>
@@ -1037,13 +1212,19 @@ namespace OpenSim.Region.Framework.Scenes
1037 /// <param name="datastore"></param> 1212 /// <param name="datastore"></param>
1038 public void ProcessInventoryBackup(ISimulationDataService datastore) 1213 public void ProcessInventoryBackup(ISimulationDataService datastore)
1039 { 1214 {
1040 if (HasInventoryChanged) 1215// Removed this because linking will cause an immediate delete of the new
1041 { 1216// child prim from the database and the subsequent storing of the prim sees
1042 HasInventoryChanged = false; 1217// the inventory of it as unchanged and doesn't store it at all. The overhead
1043 List<TaskInventoryItem> items = GetInventoryItems(); 1218// of storing prim inventory needlessly is much less than the aggravation
1044 datastore.StorePrimInventory(m_part.UUID, items); 1219// of prim inventory loss.
1220// if (HasInventoryChanged)
1221// {
1222 Items.LockItemsForRead(true);
1223 datastore.StorePrimInventory(m_part.UUID, Items.Values);
1224 Items.LockItemsForRead(false);
1045 1225
1046 } 1226 HasInventoryChanged = false;
1227// }
1047 } 1228 }
1048 1229
1049 public class InventoryStringBuilder 1230 public class InventoryStringBuilder
@@ -1109,87 +1290,63 @@ namespace OpenSim.Region.Framework.Scenes
1109 { 1290 {
1110 uint mask=0x7fffffff; 1291 uint mask=0x7fffffff;
1111 1292
1112 lock (m_items) 1293 foreach (TaskInventoryItem item in m_items.Values)
1113 { 1294 {
1114 foreach (TaskInventoryItem item in m_items.Values) 1295 if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Copy) == 0)
1296 mask &= ~((uint)PermissionMask.Copy >> 13);
1297 if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Transfer) == 0)
1298 mask &= ~((uint)PermissionMask.Transfer >> 13);
1299 if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Modify) == 0)
1300 mask &= ~((uint)PermissionMask.Modify >> 13);
1301
1302 if (item.InvType == (int)InventoryType.Object)
1115 { 1303 {
1116 if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Copy) == 0) 1304 if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0)
1117 mask &= ~((uint)PermissionMask.Copy >> 13); 1305 mask &= ~((uint)PermissionMask.Copy >> 13);
1118 if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Transfer) == 0) 1306 if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0)
1119 mask &= ~((uint)PermissionMask.Transfer >> 13); 1307 mask &= ~((uint)PermissionMask.Transfer >> 13);
1120 if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Modify) == 0) 1308 if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0)
1121 mask &= ~((uint)PermissionMask.Modify >> 13); 1309 mask &= ~((uint)PermissionMask.Modify >> 13);
1122
1123 if (item.InvType != (int)InventoryType.Object)
1124 {
1125 if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Copy) == 0)
1126 mask &= ~((uint)PermissionMask.Copy >> 13);
1127 if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Transfer) == 0)
1128 mask &= ~((uint)PermissionMask.Transfer >> 13);
1129 if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Modify) == 0)
1130 mask &= ~((uint)PermissionMask.Modify >> 13);
1131 }
1132 else
1133 {
1134 if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0)
1135 mask &= ~((uint)PermissionMask.Copy >> 13);
1136 if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0)
1137 mask &= ~((uint)PermissionMask.Transfer >> 13);
1138 if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0)
1139 mask &= ~((uint)PermissionMask.Modify >> 13);
1140 }
1141
1142 if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
1143 mask &= ~(uint)PermissionMask.Copy;
1144 if ((item.CurrentPermissions & (uint)PermissionMask.Transfer) == 0)
1145 mask &= ~(uint)PermissionMask.Transfer;
1146 if ((item.CurrentPermissions & (uint)PermissionMask.Modify) == 0)
1147 mask &= ~(uint)PermissionMask.Modify;
1148 } 1310 }
1311
1312 if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
1313 mask &= ~(uint)PermissionMask.Copy;
1314 if ((item.CurrentPermissions & (uint)PermissionMask.Transfer) == 0)
1315 mask &= ~(uint)PermissionMask.Transfer;
1316 if ((item.CurrentPermissions & (uint)PermissionMask.Modify) == 0)
1317 mask &= ~(uint)PermissionMask.Modify;
1149 } 1318 }
1150
1151 return mask; 1319 return mask;
1152 } 1320 }
1153 1321
1154 public void ApplyNextOwnerPermissions() 1322 public void ApplyNextOwnerPermissions()
1155 { 1323 {
1156 lock (m_items) 1324 foreach (TaskInventoryItem item in m_items.Values)
1157 { 1325 {
1158 foreach (TaskInventoryItem item in m_items.Values) 1326 if (item.InvType == (int)InventoryType.Object && (item.CurrentPermissions & 7) != 0)
1159 { 1327 {
1160// m_log.DebugFormat ( 1328 if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0)
1161// "[SCENE OBJECT PART INVENTORY]: Applying next permissions {0} to {1} in {2} with current {3}, base {4}, everyone {5}", 1329 item.CurrentPermissions &= ~(uint)PermissionMask.Copy;
1162// item.NextPermissions, item.Name, m_part.Name, item.CurrentPermissions, item.BasePermissions, item.EveryonePermissions); 1330 if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0)
1163 1331 item.CurrentPermissions &= ~(uint)PermissionMask.Transfer;
1164 if (item.InvType == (int)InventoryType.Object && (item.CurrentPermissions & 7) != 0) 1332 if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0)
1165 { 1333 item.CurrentPermissions &= ~(uint)PermissionMask.Modify;
1166 if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0)
1167 item.CurrentPermissions &= ~(uint)PermissionMask.Copy;
1168 if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0)
1169 item.CurrentPermissions &= ~(uint)PermissionMask.Transfer;
1170 if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0)
1171 item.CurrentPermissions &= ~(uint)PermissionMask.Modify;
1172 }
1173
1174 item.CurrentPermissions &= item.NextPermissions;
1175 item.BasePermissions &= item.NextPermissions;
1176 item.EveryonePermissions &= item.NextPermissions;
1177 item.OwnerChanged = true;
1178 item.PermsMask = 0;
1179 item.PermsGranter = UUID.Zero;
1180 } 1334 }
1335 item.CurrentPermissions &= item.NextPermissions;
1336 item.BasePermissions &= item.NextPermissions;
1337 item.EveryonePermissions &= item.NextPermissions;
1338 item.OwnerChanged = true;
1339 item.PermsMask = 0;
1340 item.PermsGranter = UUID.Zero;
1181 } 1341 }
1182 } 1342 }
1183 1343
1184 public void ApplyGodPermissions(uint perms) 1344 public void ApplyGodPermissions(uint perms)
1185 { 1345 {
1186 lock (m_items) 1346 foreach (TaskInventoryItem item in m_items.Values)
1187 { 1347 {
1188 foreach (TaskInventoryItem item in m_items.Values) 1348 item.CurrentPermissions = perms;
1189 { 1349 item.BasePermissions = perms;
1190 item.CurrentPermissions = perms;
1191 item.BasePermissions = perms;
1192 }
1193 } 1350 }
1194 1351
1195 m_inventorySerial++; 1352 m_inventorySerial++;
@@ -1202,14 +1359,11 @@ namespace OpenSim.Region.Framework.Scenes
1202 /// <returns></returns> 1359 /// <returns></returns>
1203 public bool ContainsScripts() 1360 public bool ContainsScripts()
1204 { 1361 {
1205 lock (m_items) 1362 foreach (TaskInventoryItem item in m_items.Values)
1206 { 1363 {
1207 foreach (TaskInventoryItem item in m_items.Values) 1364 if (item.InvType == (int)InventoryType.LSL)
1208 { 1365 {
1209 if (item.InvType == (int)InventoryType.LSL) 1366 return true;
1210 {
1211 return true;
1212 }
1213 } 1367 }
1214 } 1368 }
1215 1369
@@ -1223,17 +1377,15 @@ namespace OpenSim.Region.Framework.Scenes
1223 public int ScriptCount() 1377 public int ScriptCount()
1224 { 1378 {
1225 int count = 0; 1379 int count = 0;
1226 lock (m_items) 1380 Items.LockItemsForRead(true);
1381 foreach (TaskInventoryItem item in m_items.Values)
1227 { 1382 {
1228 foreach (TaskInventoryItem item in m_items.Values) 1383 if (item.InvType == (int)InventoryType.LSL)
1229 { 1384 {
1230 if (item.InvType == (int)InventoryType.LSL) 1385 count++;
1231 {
1232 count++;
1233 }
1234 } 1386 }
1235 } 1387 }
1236 1388 Items.LockItemsForRead(false);
1237 return count; 1389 return count;
1238 } 1390 }
1239 /// <summary> 1391 /// <summary>
@@ -1269,11 +1421,8 @@ namespace OpenSim.Region.Framework.Scenes
1269 { 1421 {
1270 List<UUID> ret = new List<UUID>(); 1422 List<UUID> ret = new List<UUID>();
1271 1423
1272 lock (m_items) 1424 foreach (TaskInventoryItem item in m_items.Values)
1273 { 1425 ret.Add(item.ItemID);
1274 foreach (TaskInventoryItem item in m_items.Values)
1275 ret.Add(item.ItemID);
1276 }
1277 1426
1278 return ret; 1427 return ret;
1279 } 1428 }
@@ -1282,8 +1431,9 @@ namespace OpenSim.Region.Framework.Scenes
1282 { 1431 {
1283 List<TaskInventoryItem> ret = new List<TaskInventoryItem>(); 1432 List<TaskInventoryItem> ret = new List<TaskInventoryItem>();
1284 1433
1285 lock (m_items) 1434 Items.LockItemsForRead(true);
1286 ret = new List<TaskInventoryItem>(m_items.Values); 1435 ret = new List<TaskInventoryItem>(m_items.Values);
1436 Items.LockItemsForRead(false);
1287 1437
1288 return ret; 1438 return ret;
1289 } 1439 }
@@ -1292,18 +1442,24 @@ namespace OpenSim.Region.Framework.Scenes
1292 { 1442 {
1293 List<TaskInventoryItem> ret = new List<TaskInventoryItem>(); 1443 List<TaskInventoryItem> ret = new List<TaskInventoryItem>();
1294 1444
1295 lock (m_items) 1445 Items.LockItemsForRead(true);
1296 { 1446
1297 foreach (TaskInventoryItem item in m_items.Values) 1447 foreach (TaskInventoryItem item in m_items.Values)
1298 if (item.InvType == (int)type) 1448 if (item.InvType == (int)type)
1299 ret.Add(item); 1449 ret.Add(item);
1300 } 1450
1451 Items.LockItemsForRead(false);
1301 1452
1302 return ret; 1453 return ret;
1303 } 1454 }
1304 1455
1305 public Dictionary<UUID, string> GetScriptStates() 1456 public Dictionary<UUID, string> GetScriptStates()
1306 { 1457 {
1458 return GetScriptStates(false);
1459 }
1460
1461 public Dictionary<UUID, string> GetScriptStates(bool oldIDs)
1462 {
1307 Dictionary<UUID, string> ret = new Dictionary<UUID, string>(); 1463 Dictionary<UUID, string> ret = new Dictionary<UUID, string>();
1308 1464
1309 if (m_part.ParentGroup.Scene == null) // Group not in a scene 1465 if (m_part.ParentGroup.Scene == null) // Group not in a scene
@@ -1329,14 +1485,21 @@ namespace OpenSim.Region.Framework.Scenes
1329 string n = e.GetXMLState(item.ItemID); 1485 string n = e.GetXMLState(item.ItemID);
1330 if (n != String.Empty) 1486 if (n != String.Empty)
1331 { 1487 {
1332 if (!ret.ContainsKey(item.ItemID)) 1488 if (oldIDs)
1333 ret[item.ItemID] = n; 1489 {
1490 if (!ret.ContainsKey(item.OldItemID))
1491 ret[item.OldItemID] = n;
1492 }
1493 else
1494 {
1495 if (!ret.ContainsKey(item.ItemID))
1496 ret[item.ItemID] = n;
1497 }
1334 break; 1498 break;
1335 } 1499 }
1336 } 1500 }
1337 } 1501 }
1338 } 1502 }
1339
1340 return ret; 1503 return ret;
1341 } 1504 }
1342 1505
diff --git a/OpenSim/Region/Framework/Scenes/ScenePresence.cs b/OpenSim/Region/Framework/Scenes/ScenePresence.cs
index a90872e..f024f52 100644
--- a/OpenSim/Region/Framework/Scenes/ScenePresence.cs
+++ b/OpenSim/Region/Framework/Scenes/ScenePresence.cs
@@ -63,6 +63,7 @@ namespace OpenSim.Region.Framework.Scenes
63 63
64 struct ScriptControllers 64 struct ScriptControllers
65 { 65 {
66 public UUID objectID;
66 public UUID itemID; 67 public UUID itemID;
67 public ScriptControlled ignoreControls; 68 public ScriptControlled ignoreControls;
68 public ScriptControlled eventControls; 69 public ScriptControlled eventControls;
@@ -99,7 +100,7 @@ namespace OpenSim.Region.Framework.Scenes
99 /// rotation, prim cut, prim twist, prim taper, and prim shear. See mantis 100 /// rotation, prim cut, prim twist, prim taper, and prim shear. See mantis
100 /// issue #1716 101 /// issue #1716
101 /// </summary> 102 /// </summary>
102 public static readonly Vector3 SIT_TARGET_ADJUSTMENT = new Vector3(0.0f, 0.0f, 0.418f); 103 public static readonly Vector3 SIT_TARGET_ADJUSTMENT = new Vector3(0.0f, 0.0f, 0.4f);
103 104
104 /// <summary> 105 /// <summary>
105 /// Movement updates for agents in neighboring regions are sent directly to clients. 106 /// Movement updates for agents in neighboring regions are sent directly to clients.
@@ -139,6 +140,8 @@ namespace OpenSim.Region.Framework.Scenes
139 private Vector3 m_lastPosition; 140 private Vector3 m_lastPosition;
140 private Quaternion m_lastRotation; 141 private Quaternion m_lastRotation;
141 private Vector3 m_lastVelocity; 142 private Vector3 m_lastVelocity;
143 private Vector3 m_lastSize = new Vector3(0.45f,0.6f,1.9f);
144
142 145
143 private Vector3? m_forceToApply; 146 private Vector3? m_forceToApply;
144 private int m_userFlags; 147 private int m_userFlags;
@@ -171,6 +174,7 @@ namespace OpenSim.Region.Framework.Scenes
171// private int m_lastColCount = -1; //KF: Look for Collision chnages 174// private int m_lastColCount = -1; //KF: Look for Collision chnages
172// private int m_updateCount = 0; //KF: Update Anims for a while 175// private int m_updateCount = 0; //KF: Update Anims for a while
173// private static readonly int UPDATE_COUNT = 10; // how many frames to update for 176// private static readonly int UPDATE_COUNT = 10; // how many frames to update for
177 private List<uint> m_lastColliders = new List<uint>();
174 178
175 private TeleportFlags m_teleportFlags; 179 private TeleportFlags m_teleportFlags;
176 public TeleportFlags TeleportFlags 180 public TeleportFlags TeleportFlags
@@ -221,8 +225,6 @@ namespace OpenSim.Region.Framework.Scenes
221 /// </summary> 225 /// </summary>
222 public bool LandAtTarget { get; private set; } 226 public bool LandAtTarget { get; private set; }
223 227
224 private bool m_followCamAuto;
225
226 private int m_movementUpdateCount; 228 private int m_movementUpdateCount;
227 private const int NumMovementsBetweenRayCast = 5; 229 private const int NumMovementsBetweenRayCast = 5;
228 230
@@ -230,6 +232,13 @@ namespace OpenSim.Region.Framework.Scenes
230 //private int m_moveToPositionStateStatus; 232 //private int m_moveToPositionStateStatus;
231 //***************************************************** 233 //*****************************************************
232 234
235 private bool m_collisionEventFlag = false;
236 private object m_collisionEventLock = new Object();
237
238 private int m_movementAnimationUpdateCounter = 0;
239
240 private Vector3 m_prevSitOffset;
241
233 protected AvatarAppearance m_appearance; 242 protected AvatarAppearance m_appearance;
234 243
235 public AvatarAppearance Appearance 244 public AvatarAppearance Appearance
@@ -344,6 +353,9 @@ namespace OpenSim.Region.Framework.Scenes
344 /// </summary> 353 /// </summary>
345 protected Vector3 m_lastCameraPosition; 354 protected Vector3 m_lastCameraPosition;
346 355
356 private Vector4 m_lastCameraCollisionPlane = new Vector4(0f, 0f, 0f, 1);
357 private bool m_doingCamRayCast = false;
358
347 public Vector3 CameraPosition { get; set; } 359 public Vector3 CameraPosition { get; set; }
348 360
349 public Quaternion CameraRotation 361 public Quaternion CameraRotation
@@ -424,7 +436,7 @@ namespace OpenSim.Region.Framework.Scenes
424 get { return (IClientCore)ControllingClient; } 436 get { return (IClientCore)ControllingClient; }
425 } 437 }
426 438
427 public Vector3 ParentPosition { get; set; } 439// public Vector3 ParentPosition { get; set; }
428 440
429 /// <summary> 441 /// <summary>
430 /// Position of this avatar relative to the region the avatar is in 442 /// Position of this avatar relative to the region the avatar is in
@@ -482,7 +494,7 @@ namespace OpenSim.Region.Framework.Scenes
482 if (ParentID == 0) 494 if (ParentID == 0)
483 { 495 {
484 m_pos = value; 496 m_pos = value;
485 ParentPosition = Vector3.Zero; 497// ParentPosition = Vector3.Zero;
486 } 498 }
487 499
488 //m_log.DebugFormat( 500 //m_log.DebugFormat(
@@ -551,7 +563,24 @@ namespace OpenSim.Region.Framework.Scenes
551// Scene.RegionInfo.RegionName, Name, m_velocity); 563// Scene.RegionInfo.RegionName, Name, m_velocity);
552 } 564 }
553 } 565 }
566/*
567 public override Vector3 AngularVelocity
568 {
569 get
570 {
571 if (PhysicsActor != null)
572 {
573 m_rotationalvelocity = PhysicsActor.RotationalVelocity;
574
575 // m_log.DebugFormat(
576 // "[SCENE PRESENCE]: Set velocity {0} for {1} in {2} via getting Velocity!",
577 // m_velocity, Name, Scene.RegionInfo.RegionName);
578 }
554 579
580 return m_rotationalvelocity;
581 }
582 }
583*/
555 private Quaternion m_bodyRot = Quaternion.Identity; 584 private Quaternion m_bodyRot = Quaternion.Identity;
556 585
557 public Quaternion Rotation 586 public Quaternion Rotation
@@ -562,19 +591,34 @@ namespace OpenSim.Region.Framework.Scenes
562 m_bodyRot = value; 591 m_bodyRot = value;
563 if (PhysicsActor != null) 592 if (PhysicsActor != null)
564 { 593 {
565 PhysicsActor.Orientation = m_bodyRot; 594 try
595 {
596 PhysicsActor.Orientation = m_bodyRot;
597 }
598 catch (Exception e)
599 {
600 m_log.Error("[SCENE PRESENCE]: Orientation " + e.Message);
601 }
566 } 602 }
567// m_log.DebugFormat("[SCENE PRESENCE]: Body rot for {0} set to {1}", Name, m_bodyRot); 603// m_log.DebugFormat("[SCENE PRESENCE]: Body rot for {0} set to {1}", Name, m_bodyRot);
568 } 604 }
569 } 605 }
570 606
571 public bool IsChildAgent { get; set; } 607 public bool IsChildAgent { get; set; }
608 public bool IsLoggingIn { get; set; }
572 609
573 /// <summary> 610 /// <summary>
574 /// If the avatar is sitting, the local ID of the prim that it's sitting on. If not sitting then zero. 611 /// If the avatar is sitting, the local ID of the prim that it's sitting on. If not sitting then zero.
575 /// </summary> 612 /// </summary>
576 public uint ParentID { get; set; } 613 public uint ParentID { get; set; }
577 614
615 public UUID ParentUUID
616 {
617 get { return m_parentUUID; }
618 set { m_parentUUID = value; }
619 }
620 private UUID m_parentUUID = UUID.Zero;
621
578 /// <summary> 622 /// <summary>
579 /// Are we sitting on an object? 623 /// Are we sitting on an object?
580 /// </summary> 624 /// </summary>
@@ -698,6 +742,7 @@ namespace OpenSim.Region.Framework.Scenes
698 AttachmentsSyncLock = new Object(); 742 AttachmentsSyncLock = new Object();
699 AllowMovement = true; 743 AllowMovement = true;
700 IsChildAgent = true; 744 IsChildAgent = true;
745 IsLoggingIn = false;
701 m_sendCoarseLocationsMethod = SendCoarseLocationsDefault; 746 m_sendCoarseLocationsMethod = SendCoarseLocationsDefault;
702 Animator = new ScenePresenceAnimator(this); 747 Animator = new ScenePresenceAnimator(this);
703 PresenceType = type; 748 PresenceType = type;
@@ -741,6 +786,33 @@ namespace OpenSim.Region.Framework.Scenes
741 Appearance = appearance; 786 Appearance = appearance;
742 } 787 }
743 788
789 private void RegionHeartbeatEnd(Scene scene)
790 {
791 if (IsChildAgent)
792 return;
793
794 m_movementAnimationUpdateCounter ++;
795 if (m_movementAnimationUpdateCounter >= 2)
796 {
797 m_movementAnimationUpdateCounter = 0;
798 if (Animator != null)
799 {
800 // If the parentID == 0 we are not sitting
801 // if !SitGournd then we are not sitting on the ground
802 // Fairly straightforward, now here comes the twist
803 // if ParentUUID is NOT UUID.Zero, we are looking to
804 // be sat on an object that isn't there yet. Should
805 // be treated as if sat.
806 if(ParentID == 0 && !SitGround && ParentUUID == UUID.Zero) // skip it if sitting
807 Animator.UpdateMovementAnimations();
808 }
809 else
810 {
811 m_scene.EventManager.OnRegionHeartbeatEnd -= RegionHeartbeatEnd;
812 }
813 }
814 }
815
744 public void RegisterToEvents() 816 public void RegisterToEvents()
745 { 817 {
746 ControllingClient.OnCompleteMovementToRegion += CompleteMovement; 818 ControllingClient.OnCompleteMovementToRegion += CompleteMovement;
@@ -750,8 +822,10 @@ namespace OpenSim.Region.Framework.Scenes
750 ControllingClient.OnSetAlwaysRun += HandleSetAlwaysRun; 822 ControllingClient.OnSetAlwaysRun += HandleSetAlwaysRun;
751 ControllingClient.OnStartAnim += HandleStartAnim; 823 ControllingClient.OnStartAnim += HandleStartAnim;
752 ControllingClient.OnStopAnim += HandleStopAnim; 824 ControllingClient.OnStopAnim += HandleStopAnim;
825 ControllingClient.OnChangeAnim += avnHandleChangeAnim;
753 ControllingClient.OnForceReleaseControls += HandleForceReleaseControls; 826 ControllingClient.OnForceReleaseControls += HandleForceReleaseControls;
754 ControllingClient.OnAutoPilotGo += MoveToTarget; 827 ControllingClient.OnAutoPilotGo += MoveToTarget;
828 ControllingClient.OnUpdateThrottles += RaiseUpdateThrottles;
755 829
756 // ControllingClient.OnChildAgentStatus += new StatusChange(this.ChildStatusChange); 830 // ControllingClient.OnChildAgentStatus += new StatusChange(this.ChildStatusChange);
757 // ControllingClient.OnStopMovement += new GenericCall2(this.StopMovement); 831 // ControllingClient.OnStopMovement += new GenericCall2(this.StopMovement);
@@ -810,10 +884,40 @@ namespace OpenSim.Region.Framework.Scenes
810 "[SCENE]: Upgrading child to root agent for {0} in {1}", 884 "[SCENE]: Upgrading child to root agent for {0} in {1}",
811 Name, m_scene.RegionInfo.RegionName); 885 Name, m_scene.RegionInfo.RegionName);
812 886
813 //m_log.DebugFormat("[SCENE]: known regions in {0}: {1}", Scene.RegionInfo.RegionName, KnownChildRegionHandles.Count);
814
815 bool wasChild = IsChildAgent; 887 bool wasChild = IsChildAgent;
816 IsChildAgent = false; 888
889 if (ParentUUID != UUID.Zero)
890 {
891 m_log.DebugFormat("[SCENE PRESENCE]: Sitting avatar back on prim {0}", ParentUUID);
892 SceneObjectPart part = m_scene.GetSceneObjectPart(ParentUUID);
893 if (part == null)
894 {
895 m_log.ErrorFormat("[SCENE PRESENCE]: Can't find prim {0} to sit on", ParentUUID);
896 }
897 else
898 {
899 part.ParentGroup.AddAvatar(UUID);
900 if (part.SitTargetPosition != Vector3.Zero)
901 part.SitTargetAvatar = UUID;
902// ParentPosition = part.GetWorldPosition();
903 ParentID = part.LocalId;
904 ParentPart = part;
905 m_pos = m_prevSitOffset;
906// pos = ParentPosition;
907 pos = part.GetWorldPosition();
908 }
909 ParentUUID = UUID.Zero;
910
911 IsChildAgent = false;
912
913// Animator.TrySetMovementAnimation("SIT");
914 }
915 else
916 {
917 IsChildAgent = false;
918 IsLoggingIn = false;
919 }
920
817 921
818 IGroupsModule gm = m_scene.RequestModuleInterface<IGroupsModule>(); 922 IGroupsModule gm = m_scene.RequestModuleInterface<IGroupsModule>();
819 if (gm != null) 923 if (gm != null)
@@ -823,62 +927,99 @@ namespace OpenSim.Region.Framework.Scenes
823 927
824 m_scene.EventManager.TriggerSetRootAgentScene(m_uuid, m_scene); 928 m_scene.EventManager.TriggerSetRootAgentScene(m_uuid, m_scene);
825 929
826 // Moved this from SendInitialData to ensure that Appearance is initialized 930 UUID groupUUID = UUID.Zero;
827 // before the inventory is processed in MakeRootAgent. This fixes a race condition 931 string GroupName = string.Empty;
828 // related to the handling of attachments 932 ulong groupPowers = 0;
829 //m_scene.GetAvatarAppearance(ControllingClient, out Appearance); 933
830 if (m_scene.TestBorderCross(pos, Cardinals.E)) 934 // ----------------------------------
935 // Previous Agent Difference - AGNI sends an unsolicited AgentDataUpdate upon root agent status
936 try
831 { 937 {
832 Border crossedBorder = m_scene.GetCrossedBorder(pos, Cardinals.E); 938 if (gm != null)
833 pos.X = crossedBorder.BorderLine.Z - 1; 939 {
940 groupUUID = ControllingClient.ActiveGroupId;
941 GroupRecord record = gm.GetGroupRecord(groupUUID);
942 if (record != null)
943 GroupName = record.GroupName;
944 GroupMembershipData groupMembershipData = gm.GetMembershipData(groupUUID, m_uuid);
945 if (groupMembershipData != null)
946 groupPowers = groupMembershipData.GroupPowers;
947 }
948 ControllingClient.SendAgentDataUpdate(m_uuid, groupUUID, Firstname, Lastname, groupPowers, GroupName,
949 Grouptitle);
834 } 950 }
835 951 catch (Exception e)
836 if (m_scene.TestBorderCross(pos, Cardinals.N))
837 { 952 {
838 Border crossedBorder = m_scene.GetCrossedBorder(pos, Cardinals.N); 953 m_log.Debug("[AGENTUPDATE]: " + e.ToString());
839 pos.Y = crossedBorder.BorderLine.Z - 1;
840 } 954 }
955 // ------------------------------------
841 956
842 CheckAndAdjustLandingPoint(ref pos); 957 if (ParentID == 0)
843
844 if (pos.X < 0f || pos.Y < 0f || pos.Z < 0f)
845 { 958 {
846 m_log.WarnFormat( 959 // Moved this from SendInitialData to ensure that Appearance is initialized
847 "[SCENE PRESENCE]: MakeRootAgent() was given an illegal position of {0} for avatar {1}, {2}. Clamping", 960 // before the inventory is processed in MakeRootAgent. This fixes a race condition
848 pos, Name, UUID); 961 // related to the handling of attachments
962 //m_scene.GetAvatarAppearance(ControllingClient, out Appearance);
963 if (m_scene.TestBorderCross(pos, Cardinals.E))
964 {
965 Border crossedBorder = m_scene.GetCrossedBorder(pos, Cardinals.E);
966 pos.X = crossedBorder.BorderLine.Z - 1;
967 }
849 968
850 if (pos.X < 0f) pos.X = 0f; 969 if (m_scene.TestBorderCross(pos, Cardinals.N))
851 if (pos.Y < 0f) pos.Y = 0f; 970 {
852 if (pos.Z < 0f) pos.Z = 0f; 971 Border crossedBorder = m_scene.GetCrossedBorder(pos, Cardinals.N);
853 } 972 pos.Y = crossedBorder.BorderLine.Z - 1;
973 }
854 974
855 float localAVHeight = 1.56f; 975 CheckAndAdjustLandingPoint(ref pos);
856 if (Appearance.AvatarHeight > 0)
857 localAVHeight = Appearance.AvatarHeight;
858 976
859 float posZLimit = 0; 977 if (pos.X < 0f || pos.Y < 0f || pos.Z < 0f)
978 {
979 m_log.WarnFormat(
980 "[SCENE PRESENCE]: MakeRootAgent() was given an illegal position of {0} for avatar {1}, {2}. Clamping",
981 pos, Name, UUID);
860 982
861 if (pos.X < Constants.RegionSize && pos.Y < Constants.RegionSize) 983 if (pos.X < 0f) pos.X = 0f;
862 posZLimit = (float)m_scene.Heightmap[(int)pos.X, (int)pos.Y]; 984 if (pos.Y < 0f) pos.Y = 0f;
863 985 if (pos.Z < 0f) pos.Z = 0f;
864 float newPosZ = posZLimit + localAVHeight / 2; 986 }
865 if (posZLimit >= (pos.Z - (localAVHeight / 2)) && !(Single.IsInfinity(newPosZ) || Single.IsNaN(newPosZ)))
866 {
867 pos.Z = newPosZ;
868 }
869 AbsolutePosition = pos;
870 987
871 AddToPhysicalScene(isFlying); 988 float localAVHeight = 1.56f;
989 if (Appearance.AvatarHeight > 0)
990 localAVHeight = Appearance.AvatarHeight;
872 991
873 if (ForceFly) 992 float posZLimit = 0;
874 {
875 Flying = true;
876 }
877 else if (FlyDisabled)
878 {
879 Flying = false;
880 }
881 993
994 if (pos.X < Constants.RegionSize && pos.Y < Constants.RegionSize)
995 posZLimit = (float)m_scene.Heightmap[(int)pos.X, (int)pos.Y];
996
997 float newPosZ = posZLimit + localAVHeight / 2;
998 if (posZLimit >= (pos.Z - (localAVHeight / 2)) && !(Single.IsInfinity(newPosZ) || Single.IsNaN(newPosZ)))
999 {
1000 pos.Z = newPosZ;
1001 }
1002 AbsolutePosition = pos;
1003
1004 if (m_teleportFlags == TeleportFlags.Default)
1005 {
1006 Vector3 vel = Velocity;
1007 AddToPhysicalScene(isFlying);
1008 if (PhysicsActor != null)
1009 PhysicsActor.SetMomentum(vel);
1010 }
1011 else
1012 AddToPhysicalScene(isFlying);
1013
1014 if (ForceFly)
1015 {
1016 Flying = true;
1017 }
1018 else if (FlyDisabled)
1019 {
1020 Flying = false;
1021 }
1022 }
882 // Don't send an animation pack here, since on a region crossing this will sometimes cause a flying 1023 // Don't send an animation pack here, since on a region crossing this will sometimes cause a flying
883 // avatar to return to the standing position in mid-air. On login it looks like this is being sent 1024 // avatar to return to the standing position in mid-air. On login it looks like this is being sent
884 // elsewhere anyway 1025 // elsewhere anyway
@@ -898,14 +1039,19 @@ namespace OpenSim.Region.Framework.Scenes
898 "[SCENE PRESENCE]: Restarting scripts in attachments for {0} in {1}", Name, Scene.Name); 1039 "[SCENE PRESENCE]: Restarting scripts in attachments for {0} in {1}", Name, Scene.Name);
899 1040
900 // Resume scripts 1041 // Resume scripts
901 foreach (SceneObjectGroup sog in m_attachments) 1042 Util.FireAndForget(delegate(object x) {
902 { 1043 foreach (SceneObjectGroup sog in m_attachments)
903 sog.RootPart.ParentGroup.CreateScriptInstances(0, false, m_scene.DefaultScriptEngine, GetStateSource()); 1044 {
904 sog.ResumeScripts(); 1045 sog.ScheduleGroupForFullUpdate();
905 } 1046 sog.RootPart.ParentGroup.CreateScriptInstances(0, false, m_scene.DefaultScriptEngine, GetStateSource());
1047 sog.ResumeScripts();
1048 }
1049 });
906 } 1050 }
907 } 1051 }
908 1052
1053 SendAvatarDataToAllAgents();
1054
909 // send the animations of the other presences to me 1055 // send the animations of the other presences to me
910 m_scene.ForEachRootScenePresence(delegate(ScenePresence presence) 1056 m_scene.ForEachRootScenePresence(delegate(ScenePresence presence)
911 { 1057 {
@@ -916,9 +1062,12 @@ namespace OpenSim.Region.Framework.Scenes
916 // If we don't reset the movement flag here, an avatar that crosses to a neighbouring sim and returns will 1062 // If we don't reset the movement flag here, an avatar that crosses to a neighbouring sim and returns will
917 // stall on the border crossing since the existing child agent will still have the last movement 1063 // stall on the border crossing since the existing child agent will still have the last movement
918 // recorded, which stops the input from being processed. 1064 // recorded, which stops the input from being processed.
1065
919 MovementFlag = 0; 1066 MovementFlag = 0;
920 1067
921 m_scene.EventManager.TriggerOnMakeRootAgent(this); 1068 m_scene.EventManager.TriggerOnMakeRootAgent(this);
1069
1070 m_scene.EventManager.OnRegionHeartbeatEnd += RegionHeartbeatEnd;
922 } 1071 }
923 1072
924 public int GetStateSource() 1073 public int GetStateSource()
@@ -946,12 +1095,16 @@ namespace OpenSim.Region.Framework.Scenes
946 /// </remarks> 1095 /// </remarks>
947 public void MakeChildAgent() 1096 public void MakeChildAgent()
948 { 1097 {
1098 m_scene.EventManager.OnRegionHeartbeatEnd -= RegionHeartbeatEnd;
1099
949 m_log.DebugFormat("[SCENE PRESENCE]: Making {0} a child agent in {1}", Name, Scene.RegionInfo.RegionName); 1100 m_log.DebugFormat("[SCENE PRESENCE]: Making {0} a child agent in {1}", Name, Scene.RegionInfo.RegionName);
950 1101
951 // Reset these so that teleporting in and walking out isn't seen 1102 // Reset these so that teleporting in and walking out isn't seen
952 // as teleporting back 1103 // as teleporting back
953 TeleportFlags = TeleportFlags.Default; 1104 TeleportFlags = TeleportFlags.Default;
954 1105
1106 MovementFlag = 0;
1107
955 // It looks like Animator is set to null somewhere, and MakeChild 1108 // It looks like Animator is set to null somewhere, and MakeChild
956 // is called after that. Probably in aborted teleports. 1109 // is called after that. Probably in aborted teleports.
957 if (Animator == null) 1110 if (Animator == null)
@@ -959,6 +1112,7 @@ namespace OpenSim.Region.Framework.Scenes
959 else 1112 else
960 Animator.ResetAnimations(); 1113 Animator.ResetAnimations();
961 1114
1115
962// m_log.DebugFormat( 1116// m_log.DebugFormat(
963// "[SCENE PRESENCE]: Downgrading root agent {0}, {1} to a child agent in {2}", 1117// "[SCENE PRESENCE]: Downgrading root agent {0}, {1} to a child agent in {2}",
964// Name, UUID, m_scene.RegionInfo.RegionName); 1118// Name, UUID, m_scene.RegionInfo.RegionName);
@@ -970,6 +1124,7 @@ namespace OpenSim.Region.Framework.Scenes
970 IsChildAgent = true; 1124 IsChildAgent = true;
971 m_scene.SwapRootAgentCount(true); 1125 m_scene.SwapRootAgentCount(true);
972 RemoveFromPhysicalScene(); 1126 RemoveFromPhysicalScene();
1127 ParentID = 0; // Child agents can't be sitting
973 1128
974 // FIXME: Set RegionHandle to the region handle of the scene this agent is moving into 1129 // FIXME: Set RegionHandle to the region handle of the scene this agent is moving into
975 1130
@@ -985,9 +1140,9 @@ namespace OpenSim.Region.Framework.Scenes
985 { 1140 {
986// PhysicsActor.OnRequestTerseUpdate -= SendTerseUpdateToAllClients; 1141// PhysicsActor.OnRequestTerseUpdate -= SendTerseUpdateToAllClients;
987 PhysicsActor.OnOutOfBounds -= OutOfBoundsCall; 1142 PhysicsActor.OnOutOfBounds -= OutOfBoundsCall;
988 m_scene.PhysicsScene.RemoveAvatar(PhysicsActor);
989 PhysicsActor.UnSubscribeEvents();
990 PhysicsActor.OnCollisionUpdate -= PhysicsCollisionUpdate; 1143 PhysicsActor.OnCollisionUpdate -= PhysicsCollisionUpdate;
1144 PhysicsActor.UnSubscribeEvents();
1145 m_scene.PhysicsScene.RemoveAvatar(PhysicsActor);
991 PhysicsActor = null; 1146 PhysicsActor = null;
992 } 1147 }
993// else 1148// else
@@ -1004,7 +1159,7 @@ namespace OpenSim.Region.Framework.Scenes
1004 /// <param name="pos"></param> 1159 /// <param name="pos"></param>
1005 public void Teleport(Vector3 pos) 1160 public void Teleport(Vector3 pos)
1006 { 1161 {
1007 TeleportWithMomentum(pos, null); 1162 TeleportWithMomentum(pos, Vector3.Zero);
1008 } 1163 }
1009 1164
1010 public void TeleportWithMomentum(Vector3 pos, Vector3? v) 1165 public void TeleportWithMomentum(Vector3 pos, Vector3? v)
@@ -1028,6 +1183,41 @@ namespace OpenSim.Region.Framework.Scenes
1028 SendTerseUpdateToAllClients(); 1183 SendTerseUpdateToAllClients();
1029 } 1184 }
1030 1185
1186 public void avnLocalTeleport(Vector3 newpos, Vector3? newvel, bool rotateToVelXY)
1187 {
1188 CheckLandingPoint(ref newpos);
1189 AbsolutePosition = newpos;
1190
1191 if (newvel.HasValue)
1192 {
1193 if ((Vector3)newvel == Vector3.Zero)
1194 {
1195 if (PhysicsActor != null)
1196 PhysicsActor.SetMomentum(Vector3.Zero);
1197 m_velocity = Vector3.Zero;
1198 }
1199 else
1200 {
1201 if (PhysicsActor != null)
1202 PhysicsActor.SetMomentum((Vector3)newvel);
1203 m_velocity = (Vector3)newvel;
1204
1205 if (rotateToVelXY)
1206 {
1207 Vector3 lookAt = (Vector3)newvel;
1208 lookAt.Z = 0;
1209 lookAt.Normalize();
1210 ControllingClient.SendLocalTeleport(newpos, lookAt, (uint)TeleportFlags.ViaLocation);
1211 return;
1212 }
1213 }
1214 }
1215
1216 SendTerseUpdateToAllClients();
1217 }
1218
1219
1220
1031 public void StopFlying() 1221 public void StopFlying()
1032 { 1222 {
1033 ControllingClient.StopFlying(this); 1223 ControllingClient.StopFlying(this);
@@ -1118,6 +1308,13 @@ namespace OpenSim.Region.Framework.Scenes
1118 PhysicsActor.Size = new Vector3(0.45f, 0.6f, height); 1308 PhysicsActor.Size = new Vector3(0.45f, 0.6f, height);
1119 } 1309 }
1120 1310
1311 public void SetSize(Vector3 size, float feetoffset)
1312 {
1313 if (PhysicsActor != null && !IsChildAgent)
1314 PhysicsActor.setAvatarSize(size, feetoffset);
1315
1316 }
1317
1121 /// <summary> 1318 /// <summary>
1122 /// Complete Avatar's movement into the region. 1319 /// Complete Avatar's movement into the region.
1123 /// </summary> 1320 /// </summary>
@@ -1137,7 +1334,8 @@ namespace OpenSim.Region.Framework.Scenes
1137 1334
1138 Vector3 look = Velocity; 1335 Vector3 look = Velocity;
1139 1336
1140 if ((look.X == 0) && (look.Y == 0) && (look.Z == 0)) 1337 // if ((look.X == 0) && (look.Y == 0) && (look.Z == 0))
1338 if ((Math.Abs(look.X) < 0.1) && (Math.Abs(look.Y) < 0.1) && (Math.Abs(look.Z) < 0.1))
1141 { 1339 {
1142 look = new Vector3(0.99f, 0.042f, 0); 1340 look = new Vector3(0.99f, 0.042f, 0);
1143 } 1341 }
@@ -1187,13 +1385,15 @@ namespace OpenSim.Region.Framework.Scenes
1187 // Create child agents in neighbouring regions 1385 // Create child agents in neighbouring regions
1188 if (openChildAgents && !IsChildAgent) 1386 if (openChildAgents && !IsChildAgent)
1189 { 1387 {
1388
1190 IEntityTransferModule m_agentTransfer = m_scene.RequestModuleInterface<IEntityTransferModule>(); 1389 IEntityTransferModule m_agentTransfer = m_scene.RequestModuleInterface<IEntityTransferModule>();
1191 if (m_agentTransfer != null) 1390 if (m_agentTransfer != null)
1192 Util.FireAndForget(delegate { m_agentTransfer.EnableChildAgents(this); }); 1391 m_agentTransfer.EnableChildAgents(this);
1193 1392
1194 IFriendsModule friendsModule = m_scene.RequestModuleInterface<IFriendsModule>(); 1393 IFriendsModule friendsModule = m_scene.RequestModuleInterface<IFriendsModule>();
1195 if (friendsModule != null) 1394 if (friendsModule != null)
1196 friendsModule.SendFriendsOnlineIfNeeded(ControllingClient); 1395 friendsModule.SendFriendsOnlineIfNeeded(ControllingClient);
1396
1197 } 1397 }
1198 1398
1199// m_log.DebugFormat( 1399// m_log.DebugFormat(
@@ -1209,35 +1409,43 @@ namespace OpenSim.Region.Framework.Scenes
1209 /// <param name="collisionPoint"></param> 1409 /// <param name="collisionPoint"></param>
1210 /// <param name="localid"></param> 1410 /// <param name="localid"></param>
1211 /// <param name="distance"></param> 1411 /// <param name="distance"></param>
1412 ///
1413
1414 private void UpdateCameraCollisionPlane(Vector4 plane)
1415 {
1416 if (m_lastCameraCollisionPlane != plane)
1417 {
1418 m_lastCameraCollisionPlane = plane;
1419 ControllingClient.SendCameraConstraint(plane);
1420 }
1421 }
1422
1212 public void RayCastCameraCallback(bool hitYN, Vector3 collisionPoint, uint localid, float distance, Vector3 pNormal) 1423 public void RayCastCameraCallback(bool hitYN, Vector3 collisionPoint, uint localid, float distance, Vector3 pNormal)
1213 { 1424 {
1214 const float POSITION_TOLERANCE = 0.02f; 1425 const float POSITION_TOLERANCE = 0.02f;
1215 const float VELOCITY_TOLERANCE = 0.02f;
1216 const float ROTATION_TOLERANCE = 0.02f; 1426 const float ROTATION_TOLERANCE = 0.02f;
1217 1427
1218 if (m_followCamAuto) 1428 m_doingCamRayCast = false;
1429 if (hitYN && localid != LocalId)
1219 { 1430 {
1220 if (hitYN) 1431 CameraConstraintActive = true;
1221 { 1432 pNormal.X = (float)Math.Round(pNormal.X, 2);
1222 CameraConstraintActive = true; 1433 pNormal.Y = (float)Math.Round(pNormal.Y, 2);
1223 //m_log.DebugFormat("[RAYCASTRESULT]: {0}, {1}, {2}, {3}", hitYN, collisionPoint, localid, distance); 1434 pNormal.Z = (float)Math.Round(pNormal.Z, 2);
1224 1435 pNormal.Normalize();
1225 Vector3 normal = Vector3.Normalize(new Vector3(0f, 0f, collisionPoint.Z) - collisionPoint); 1436 collisionPoint.X = (float)Math.Round(collisionPoint.X, 1);
1226 ControllingClient.SendCameraConstraint(new Vector4(normal.X, normal.Y, normal.Z, -1 * Vector3.Distance(new Vector3(0,0,collisionPoint.Z),collisionPoint))); 1437 collisionPoint.Y = (float)Math.Round(collisionPoint.Y, 1);
1227 } 1438 collisionPoint.Z = (float)Math.Round(collisionPoint.Z, 1);
1228 else 1439
1229 { 1440 Vector4 plane = new Vector4(pNormal.X, pNormal.Y, pNormal.Z, Vector3.Dot(collisionPoint, pNormal));
1230 if (!m_pos.ApproxEquals(m_lastPosition, POSITION_TOLERANCE) || 1441 UpdateCameraCollisionPlane(plane);
1231 !Velocity.ApproxEquals(m_lastVelocity, VELOCITY_TOLERANCE) || 1442 }
1232 !Rotation.ApproxEquals(m_lastRotation, ROTATION_TOLERANCE)) 1443 else if (!m_pos.ApproxEquals(m_lastPosition, POSITION_TOLERANCE) ||
1233 { 1444 !Rotation.ApproxEquals(m_lastRotation, ROTATION_TOLERANCE))
1234 if (CameraConstraintActive) 1445 {
1235 { 1446 Vector4 plane = new Vector4(0.9f, 0.0f, 0.361f, -9000f); // not right...
1236 ControllingClient.SendCameraConstraint(new Vector4(0f, 0.5f, 0.9f, -3000f)); 1447 UpdateCameraCollisionPlane(plane);
1237 CameraConstraintActive = false; 1448 CameraConstraintActive = false;
1238 }
1239 }
1240 }
1241 } 1449 }
1242 } 1450 }
1243 1451
@@ -1312,12 +1520,6 @@ namespace OpenSim.Region.Framework.Scenes
1312 // DrawDistance = agentData.Far; 1520 // DrawDistance = agentData.Far;
1313 DrawDistance = Scene.DefaultDrawDistance; 1521 DrawDistance = Scene.DefaultDrawDistance;
1314 1522
1315 // Check if Client has camera in 'follow cam' or 'build' mode.
1316 Vector3 camdif = (Vector3.One * Rotation - Vector3.One * CameraRotation);
1317
1318 m_followCamAuto = ((CameraUpAxis.Z > 0.959f && CameraUpAxis.Z < 0.98f)
1319 && (Math.Abs(camdif.X) < 0.4f && Math.Abs(camdif.Y) < 0.4f)) ? true : false;
1320
1321 m_mouseLook = (flags & AgentManager.ControlFlags.AGENT_CONTROL_MOUSELOOK) != 0; 1523 m_mouseLook = (flags & AgentManager.ControlFlags.AGENT_CONTROL_MOUSELOOK) != 0;
1322 m_leftButtonDown = (flags & AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN) != 0; 1524 m_leftButtonDown = (flags & AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN) != 0;
1323 1525
@@ -1337,14 +1539,38 @@ namespace OpenSim.Region.Framework.Scenes
1337 StandUp(); 1539 StandUp();
1338 } 1540 }
1339 1541
1340 //m_log.DebugFormat("[FollowCam]: {0}", m_followCamAuto);
1341 // Raycast from the avatar's head to the camera to see if there's anything blocking the view 1542 // Raycast from the avatar's head to the camera to see if there's anything blocking the view
1342 if ((m_movementUpdateCount % NumMovementsBetweenRayCast) == 0 && m_scene.PhysicsScene.SupportsRayCast()) 1543 // this exclude checks may not be complete
1544
1545 if (m_movementUpdateCount % NumMovementsBetweenRayCast == 0 && m_scene.PhysicsScene.SupportsRayCast())
1343 { 1546 {
1344 if (m_followCamAuto) 1547 if (!m_doingCamRayCast && !m_mouseLook && ParentID == 0)
1548 {
1549 Vector3 posAdjusted = AbsolutePosition;
1550// posAdjusted.Z += 0.5f * Appearance.AvatarSize.Z - 0.5f;
1551 posAdjusted.Z += 1.0f; // viewer current camera focus point
1552 Vector3 tocam = CameraPosition - posAdjusted;
1553 tocam.X = (float)Math.Round(tocam.X, 1);
1554 tocam.Y = (float)Math.Round(tocam.Y, 1);
1555 tocam.Z = (float)Math.Round(tocam.Z, 1);
1556
1557 float distTocamlen = tocam.Length();
1558 if (distTocamlen > 0.3f)
1559 {
1560 tocam *= (1.0f / distTocamlen);
1561 posAdjusted.X = (float)Math.Round(posAdjusted.X, 1);
1562 posAdjusted.Y = (float)Math.Round(posAdjusted.Y, 1);
1563 posAdjusted.Z = (float)Math.Round(posAdjusted.Z, 1);
1564
1565 m_doingCamRayCast = true;
1566 m_scene.PhysicsScene.RaycastWorld(posAdjusted, tocam, distTocamlen + 1.0f, RayCastCameraCallback);
1567 }
1568 }
1569 else if (CameraConstraintActive && (m_mouseLook || ParentID != 0))
1345 { 1570 {
1346 Vector3 posAdjusted = m_pos + HEAD_ADJUSTMENT; 1571 Vector4 plane = new Vector4(0.9f, 0.0f, 0.361f, -10000f); // not right...
1347 m_scene.PhysicsScene.RaycastWorld(m_pos, Vector3.Normalize(CameraPosition - posAdjusted), Vector3.Distance(CameraPosition, posAdjusted) + 0.3f, RayCastCameraCallback); 1572 UpdateCameraCollisionPlane(plane);
1573 CameraConstraintActive = false;
1348 } 1574 }
1349 } 1575 }
1350 1576
@@ -1782,7 +2008,8 @@ namespace OpenSim.Region.Framework.Scenes
1782// m_log.DebugFormat("[SCENE PRESENCE]: Resetting move to target for {0}", Name); 2008// m_log.DebugFormat("[SCENE PRESENCE]: Resetting move to target for {0}", Name);
1783 2009
1784 MovingToTarget = false; 2010 MovingToTarget = false;
1785 MoveToPositionTarget = Vector3.Zero; 2011// MoveToPositionTarget = Vector3.Zero;
2012 m_forceToApply = null; // cancel possible last action
1786 2013
1787 // We need to reset the control flag as the ScenePresenceAnimator uses this to determine the correct 2014 // We need to reset the control flag as the ScenePresenceAnimator uses this to determine the correct
1788 // resting animation (e.g. hover or stand). NPCs don't have a client that will quickly reset this flag. 2015 // resting animation (e.g. hover or stand). NPCs don't have a client that will quickly reset this flag.
@@ -1800,12 +2027,17 @@ namespace OpenSim.Region.Framework.Scenes
1800// m_log.DebugFormat("[SCENE PRESENCE]: StandUp() for {0}", Name); 2027// m_log.DebugFormat("[SCENE PRESENCE]: StandUp() for {0}", Name);
1801 2028
1802 SitGround = false; 2029 SitGround = false;
2030
2031/* move this down so avatar gets physical in the new position and not where it is siting
1803 if (PhysicsActor == null) 2032 if (PhysicsActor == null)
1804 AddToPhysicalScene(false); 2033 AddToPhysicalScene(false);
2034 */
1805 2035
1806 if (ParentID != 0) 2036 if (ParentID != 0)
1807 { 2037 {
1808 SceneObjectPart part = ParentPart; 2038 SceneObjectPart part = ParentPart;
2039 UnRegisterSeatControls(part.ParentGroup.UUID);
2040
1809 TaskInventoryDictionary taskIDict = part.TaskInventory; 2041 TaskInventoryDictionary taskIDict = part.TaskInventory;
1810 if (taskIDict != null) 2042 if (taskIDict != null)
1811 { 2043 {
@@ -1821,14 +2053,22 @@ namespace OpenSim.Region.Framework.Scenes
1821 } 2053 }
1822 } 2054 }
1823 2055
1824 ParentPosition = part.GetWorldPosition(); 2056 part.ParentGroup.DeleteAvatar(UUID);
2057// ParentPosition = part.GetWorldPosition();
1825 ControllingClient.SendClearFollowCamProperties(part.ParentUUID); 2058 ControllingClient.SendClearFollowCamProperties(part.ParentUUID);
1826 2059
1827 m_pos += ParentPosition + new Vector3(0.0f, 0.0f, 2.0f * m_sitAvatarHeight); 2060// m_pos += ParentPosition + new Vector3(0.0f, 0.0f, 2.0f * m_sitAvatarHeight);
1828 ParentPosition = Vector3.Zero; 2061// ParentPosition = Vector3.Zero;
2062 m_pos = part.AbsolutePosition + (m_pos * part.GetWorldRotation()) + new Vector3(0.0f, 0.0f, 2.0f * m_sitAvatarHeight);
2063 if (part.SitTargetAvatar == UUID)
2064 m_bodyRot = part.GetWorldRotation() * part.SitTargetOrientation;
1829 2065
1830 ParentID = 0; 2066 ParentID = 0;
1831 ParentPart = null; 2067 ParentPart = null;
2068
2069 if (PhysicsActor == null)
2070 AddToPhysicalScene(false);
2071
1832 SendAvatarDataToAllAgents(); 2072 SendAvatarDataToAllAgents();
1833 m_requestedSitTargetID = 0; 2073 m_requestedSitTargetID = 0;
1834 2074
@@ -1838,6 +2078,9 @@ namespace OpenSim.Region.Framework.Scenes
1838 part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK); 2078 part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK);
1839 } 2079 }
1840 2080
2081 else if (PhysicsActor == null)
2082 AddToPhysicalScene(false);
2083
1841 Animator.TrySetMovementAnimation("STAND"); 2084 Animator.TrySetMovementAnimation("STAND");
1842 } 2085 }
1843 2086
@@ -1885,11 +2128,8 @@ namespace OpenSim.Region.Framework.Scenes
1885 if (part == null) 2128 if (part == null)
1886 return; 2129 return;
1887 2130
1888 // TODO: determine position to sit at based on scene geometry; don't trust offset from client
1889 // see http://wiki.secondlife.com/wiki/User:Andrew_Linden/Office_Hours/2007_11_06 for details on how LL does it
1890
1891 if (PhysicsActor != null) 2131 if (PhysicsActor != null)
1892 m_sitAvatarHeight = PhysicsActor.Size.Z; 2132 m_sitAvatarHeight = PhysicsActor.Size.Z * 0.5f;
1893 2133
1894 bool canSit = false; 2134 bool canSit = false;
1895 Vector3 pos = part.AbsolutePosition + offset; 2135 Vector3 pos = part.AbsolutePosition + offset;
@@ -1906,31 +2146,31 @@ namespace OpenSim.Region.Framework.Scenes
1906 } 2146 }
1907 else 2147 else
1908 { 2148 {
2149 if (PhysicsSit(part,offset)) // physics engine
2150 return;
2151
1909 if (Util.GetDistanceTo(AbsolutePosition, pos) <= 10) 2152 if (Util.GetDistanceTo(AbsolutePosition, pos) <= 10)
1910 { 2153 {
1911// m_log.DebugFormat(
1912// "[SCENE PRESENCE]: Sitting {0} on {1} {2} because sit target is unset and within 10m",
1913// Name, part.Name, part.LocalId);
1914 2154
1915 AbsolutePosition = pos + new Vector3(0.0f, 0.0f, m_sitAvatarHeight); 2155 AbsolutePosition = pos + new Vector3(0.0f, 0.0f, m_sitAvatarHeight);
1916 canSit = true; 2156 canSit = true;
1917 } 2157 }
1918// else
1919// {
1920// m_log.DebugFormat(
1921// "[SCENE PRESENCE]: Ignoring sit request of {0} on {1} {2} because sit target is unset and outside 10m",
1922// Name, part.Name, part.LocalId);
1923// }
1924 } 2158 }
1925 2159
1926 if (canSit) 2160 if (canSit)
1927 { 2161 {
2162
1928 if (PhysicsActor != null) 2163 if (PhysicsActor != null)
1929 { 2164 {
1930 // We can remove the physicsActor until they stand up. 2165 // We can remove the physicsActor until they stand up.
1931 RemoveFromPhysicalScene(); 2166 RemoveFromPhysicalScene();
1932 } 2167 }
1933 2168
2169 if (MovingToTarget)
2170 ResetMoveToTarget();
2171
2172 Velocity = Vector3.Zero;
2173
1934 part.AddSittingAvatar(UUID); 2174 part.AddSittingAvatar(UUID);
1935 2175
1936 cameraAtOffset = part.GetCameraAtOffset(); 2176 cameraAtOffset = part.GetCameraAtOffset();
@@ -1938,7 +2178,7 @@ namespace OpenSim.Region.Framework.Scenes
1938 forceMouselook = part.GetForceMouselook(); 2178 forceMouselook = part.GetForceMouselook();
1939 2179
1940 ControllingClient.SendSitResponse( 2180 ControllingClient.SendSitResponse(
1941 targetID, offset, sitOrientation, false, cameraAtOffset, cameraEyeOffset, forceMouselook); 2181 part.UUID, offset, sitOrientation, false, cameraAtOffset, cameraEyeOffset, forceMouselook);
1942 2182
1943 m_requestedSitTargetUUID = targetID; 2183 m_requestedSitTargetUUID = targetID;
1944 2184
@@ -1952,6 +2192,9 @@ namespace OpenSim.Region.Framework.Scenes
1952 2192
1953 public void HandleAgentRequestSit(IClientAPI remoteClient, UUID agentID, UUID targetID, Vector3 offset) 2193 public void HandleAgentRequestSit(IClientAPI remoteClient, UUID agentID, UUID targetID, Vector3 offset)
1954 { 2194 {
2195 if (IsChildAgent)
2196 return;
2197
1955 if (ParentID != 0) 2198 if (ParentID != 0)
1956 { 2199 {
1957 if (ParentPart.UUID == targetID) 2200 if (ParentPart.UUID == targetID)
@@ -1967,14 +2210,6 @@ namespace OpenSim.Region.Framework.Scenes
1967 m_requestedSitTargetID = part.LocalId; 2210 m_requestedSitTargetID = part.LocalId;
1968 m_requestedSitTargetUUID = targetID; 2211 m_requestedSitTargetUUID = targetID;
1969 2212
1970// m_log.DebugFormat("[SIT]: Client requested Sit Position: {0}", offset);
1971
1972 if (m_scene.PhysicsScene.SupportsRayCast())
1973 {
1974 //m_scene.PhysicsScene.RaycastWorld(Vector3.Zero,Vector3.Zero, 0.01f,new RaycastCallback());
1975 //SitRayCastAvatarPosition(part);
1976 //return;
1977 }
1978 } 2213 }
1979 else 2214 else
1980 { 2215 {
@@ -1984,197 +2219,111 @@ namespace OpenSim.Region.Framework.Scenes
1984 SendSitResponse(targetID, offset, Quaternion.Identity); 2219 SendSitResponse(targetID, offset, Quaternion.Identity);
1985 } 2220 }
1986 2221
1987 /* 2222 // returns false if does not suport so older sit can be tried
1988 public void SitRayCastAvatarPosition(SceneObjectPart part) 2223 public bool PhysicsSit(SceneObjectPart part, Vector3 offset)
1989 { 2224 {
1990 Vector3 EndRayCastPosition = part.AbsolutePosition + m_requestedSitOffset; 2225 if (part == null || part.ParentGroup.IsAttachment)
1991 Vector3 StartRayCastPosition = AbsolutePosition;
1992 Vector3 direction = Vector3.Normalize(EndRayCastPosition - StartRayCastPosition);
1993 float distance = Vector3.Distance(EndRayCastPosition, StartRayCastPosition);
1994 m_scene.PhysicsScene.RaycastWorld(StartRayCastPosition, direction, distance, SitRayCastAvatarPositionResponse);
1995 }
1996
1997 public void SitRayCastAvatarPositionResponse(bool hitYN, Vector3 collisionPoint, uint localid, float pdistance, Vector3 normal)
1998 {
1999 SceneObjectPart part = FindNextAvailableSitTarget(m_requestedSitTargetUUID);
2000 if (part != null)
2001 {
2002 if (hitYN)
2003 {
2004 if (collisionPoint.ApproxEquals(m_requestedSitOffset + part.AbsolutePosition, 0.2f))
2005 {
2006 SitRaycastFindEdge(collisionPoint, normal);
2007 m_log.DebugFormat("[SIT]: Raycast Avatar Position succeeded at point: {0}, normal:{1}", collisionPoint, normal);
2008 }
2009 else
2010 {
2011 SitRayCastAvatarPositionCameraZ(part);
2012 }
2013 }
2014 else
2015 {
2016 SitRayCastAvatarPositionCameraZ(part);
2017 }
2018 }
2019 else
2020 { 2226 {
2021 ControllingClient.SendAlertMessage("Sit position no longer exists"); 2227 return true;
2022 m_requestedSitTargetUUID = UUID.Zero;
2023 m_requestedSitTargetID = 0;
2024 m_requestedSitOffset = Vector3.Zero;
2025 } 2228 }
2026 2229
2027 } 2230 if ( m_scene.PhysicsScene == null)
2028 2231 return false;
2029 public void SitRayCastAvatarPositionCameraZ(SceneObjectPart part)
2030 {
2031 // Next, try to raycast from the camera Z position
2032 Vector3 EndRayCastPosition = part.AbsolutePosition + m_requestedSitOffset;
2033 Vector3 StartRayCastPosition = AbsolutePosition; StartRayCastPosition.Z = CameraPosition.Z;
2034 Vector3 direction = Vector3.Normalize(EndRayCastPosition - StartRayCastPosition);
2035 float distance = Vector3.Distance(EndRayCastPosition, StartRayCastPosition);
2036 m_scene.PhysicsScene.RaycastWorld(StartRayCastPosition, direction, distance, SitRayCastAvatarPositionCameraZResponse);
2037 }
2038 2232
2039 public void SitRayCastAvatarPositionCameraZResponse(bool hitYN, Vector3 collisionPoint, uint localid, float pdistance, Vector3 normal) 2233 if (part.PhysActor == null)
2040 {
2041 SceneObjectPart part = FindNextAvailableSitTarget(m_requestedSitTargetUUID);
2042 if (part != null)
2043 { 2234 {
2044 if (hitYN) 2235 // none physcis shape
2045 { 2236 if (part.PhysicsShapeType == (byte)PhysicsShapeType.None)
2046 if (collisionPoint.ApproxEquals(m_requestedSitOffset + part.AbsolutePosition, 0.2f)) 2237 ControllingClient.SendAlertMessage(" There is no suitable surface to sit on, try another spot.");
2047 {
2048 SitRaycastFindEdge(collisionPoint, normal);
2049 m_log.DebugFormat("[SIT]: Raycast Avatar Position + CameraZ succeeded at point: {0}, normal:{1}", collisionPoint, normal);
2050 }
2051 else
2052 {
2053 SitRayCastCameraPosition(part);
2054 }
2055 }
2056 else 2238 else
2057 { 2239 { // non physical phantom TODO
2058 SitRayCastCameraPosition(part); 2240 ControllingClient.SendAlertMessage(" There is no suitable surface to sit on, try another spot.");
2241 return false;
2059 } 2242 }
2060 } 2243 return true;
2061 else
2062 {
2063 ControllingClient.SendAlertMessage("Sit position no longer exists");
2064 m_requestedSitTargetUUID = UUID.Zero;
2065 m_requestedSitTargetID = 0;
2066 m_requestedSitOffset = Vector3.Zero;
2067 } 2244 }
2068 2245
2069 }
2070 2246
2071 public void SitRayCastCameraPosition(SceneObjectPart part) 2247 // not doing autopilot
2072 { 2248 m_requestedSitTargetID = 0;
2073 // Next, try to raycast from the camera position
2074 Vector3 EndRayCastPosition = part.AbsolutePosition + m_requestedSitOffset;
2075 Vector3 StartRayCastPosition = CameraPosition;
2076 Vector3 direction = Vector3.Normalize(EndRayCastPosition - StartRayCastPosition);
2077 float distance = Vector3.Distance(EndRayCastPosition, StartRayCastPosition);
2078 m_scene.PhysicsScene.RaycastWorld(StartRayCastPosition, direction, distance, SitRayCastCameraPositionResponse);
2079 }
2080 2249
2081 public void SitRayCastCameraPositionResponse(bool hitYN, Vector3 collisionPoint, uint localid, float pdistance, Vector3 normal) 2250 if (m_scene.PhysicsScene.SitAvatar(part.PhysActor, AbsolutePosition, CameraPosition, offset, new Vector3(0.35f, 0, 0.65f), PhysicsSitResponse) != 0)
2082 { 2251 return true;
2083 SceneObjectPart part = FindNextAvailableSitTarget(m_requestedSitTargetUUID);
2084 if (part != null)
2085 {
2086 if (hitYN)
2087 {
2088 if (collisionPoint.ApproxEquals(m_requestedSitOffset + part.AbsolutePosition, 0.2f))
2089 {
2090 SitRaycastFindEdge(collisionPoint, normal);
2091 m_log.DebugFormat("[SIT]: Raycast Camera Position succeeded at point: {0}, normal:{1}", collisionPoint, normal);
2092 }
2093 else
2094 {
2095 SitRayHorizontal(part);
2096 }
2097 }
2098 else
2099 {
2100 SitRayHorizontal(part);
2101 }
2102 }
2103 else
2104 {
2105 ControllingClient.SendAlertMessage("Sit position no longer exists");
2106 m_requestedSitTargetUUID = UUID.Zero;
2107 m_requestedSitTargetID = 0;
2108 m_requestedSitOffset = Vector3.Zero;
2109 }
2110 2252
2253 return false;
2111 } 2254 }
2112 2255
2113 public void SitRayHorizontal(SceneObjectPart part) 2256
2257 private bool CanEnterLandPosition(Vector3 testPos)
2114 { 2258 {
2115 // Next, try to raycast from the avatar position to fwd 2259 ILandObject land = m_scene.LandChannel.GetLandObject(testPos.X, testPos.Y);
2116 Vector3 EndRayCastPosition = part.AbsolutePosition + m_requestedSitOffset; 2260
2117 Vector3 StartRayCastPosition = CameraPosition; 2261 if (land == null || land.LandData.Name == "NO_LAND")
2118 Vector3 direction = Vector3.Normalize(EndRayCastPosition - StartRayCastPosition); 2262 return true;
2119 float distance = Vector3.Distance(EndRayCastPosition, StartRayCastPosition); 2263
2120 m_scene.PhysicsScene.RaycastWorld(StartRayCastPosition, direction, distance, SitRayCastHorizontalResponse); 2264 return land.CanBeOnThisLand(UUID,testPos.Z);
2121 } 2265 }
2122 2266
2123 public void SitRayCastHorizontalResponse(bool hitYN, Vector3 collisionPoint, uint localid, float pdistance, Vector3 normal) 2267 // status
2268 // < 0 ignore
2269 // 0 bad sit spot
2270 public void PhysicsSitResponse(int status, uint partID, Vector3 offset, Quaternion Orientation)
2124 { 2271 {
2125 SceneObjectPart part = FindNextAvailableSitTarget(m_requestedSitTargetUUID); 2272 if (status < 0)
2126 if (part != null) 2273 return;
2274
2275 if (status == 0)
2127 { 2276 {
2128 if (hitYN) 2277 ControllingClient.SendAlertMessage(" There is no suitable surface to sit on, try another spot.");
2129 { 2278 return;
2130 if (collisionPoint.ApproxEquals(m_requestedSitOffset + part.AbsolutePosition, 0.2f))
2131 {
2132 SitRaycastFindEdge(collisionPoint, normal);
2133 m_log.DebugFormat("[SIT]: Raycast Horizontal Position succeeded at point: {0}, normal:{1}", collisionPoint, normal);
2134 // Next, try to raycast from the camera position
2135 Vector3 EndRayCastPosition = part.AbsolutePosition + m_requestedSitOffset;
2136 Vector3 StartRayCastPosition = CameraPosition;
2137 Vector3 direction = Vector3.Normalize(EndRayCastPosition - StartRayCastPosition);
2138 float distance = Vector3.Distance(EndRayCastPosition, StartRayCastPosition);
2139 //m_scene.PhysicsScene.RaycastWorld(StartRayCastPosition, direction, distance, SitRayCastResponseAvatarPosition);
2140 }
2141 else
2142 {
2143 ControllingClient.SendAlertMessage("Sit position not accessable.");
2144 m_requestedSitTargetUUID = UUID.Zero;
2145 m_requestedSitTargetID = 0;
2146 m_requestedSitOffset = Vector3.Zero;
2147 }
2148 }
2149 else
2150 {
2151 ControllingClient.SendAlertMessage("Sit position not accessable.");
2152 m_requestedSitTargetUUID = UUID.Zero;
2153 m_requestedSitTargetID = 0;
2154 m_requestedSitOffset = Vector3.Zero;
2155 }
2156 } 2279 }
2157 else 2280
2281 SceneObjectPart part = m_scene.GetSceneObjectPart(partID);
2282 if (part == null)
2283 return;
2284
2285 Vector3 targetPos = part.GetWorldPosition() + offset * part.GetWorldRotation();
2286 if(!CanEnterLandPosition(targetPos))
2158 { 2287 {
2159 ControllingClient.SendAlertMessage("Sit position no longer exists"); 2288 ControllingClient.SendAlertMessage(" Sit position on restricted land, try another spot");
2160 m_requestedSitTargetUUID = UUID.Zero; 2289 return;
2161 m_requestedSitTargetID = 0;
2162 m_requestedSitOffset = Vector3.Zero;
2163 } 2290 }
2164 2291
2165 } 2292 RemoveFromPhysicalScene();
2166 2293
2167 private void SitRaycastFindEdge(Vector3 collisionPoint, Vector3 collisionNormal) 2294 if (MovingToTarget)
2168 { 2295 ResetMoveToTarget();
2169 int i = 0; 2296
2170 //throw new NotImplementedException(); 2297 Velocity = Vector3.Zero;
2171 //m_requestedSitTargetUUID = UUID.Zero; 2298
2172 //m_requestedSitTargetID = 0; 2299 part.AddSittingAvatar(UUID);
2173 //m_requestedSitOffset = Vector3.Zero;
2174 2300
2175 SendSitResponse(ControllingClient, m_requestedSitTargetUUID, collisionPoint - m_requestedSitOffset, Quaternion.Identity); 2301 Vector3 cameraAtOffset = part.GetCameraAtOffset();
2302 Vector3 cameraEyeOffset = part.GetCameraEyeOffset();
2303 bool forceMouselook = part.GetForceMouselook();
2304
2305 ControllingClient.SendSitResponse(
2306 part.UUID, offset, Orientation, false, cameraAtOffset, cameraEyeOffset, forceMouselook);
2307
2308 // not using autopilot
2309
2310 Rotation = Orientation;
2311 m_pos = offset;
2312
2313 m_requestedSitTargetID = 0;
2314 part.ParentGroup.AddAvatar(UUID);
2315
2316 ParentPart = part;
2317 ParentID = part.LocalId;
2318 if(status == 3)
2319 Animator.TrySetMovementAnimation("SIT_GROUND");
2320 else
2321 Animator.TrySetMovementAnimation("SIT");
2322 SendAvatarDataToAllAgents();
2323
2324 part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK);
2176 } 2325 }
2177 */ 2326
2178 2327
2179 public void HandleAgentSit(IClientAPI remoteClient, UUID agentID) 2328 public void HandleAgentSit(IClientAPI remoteClient, UUID agentID)
2180 { 2329 {
@@ -2191,6 +2340,7 @@ namespace OpenSim.Region.Framework.Scenes
2191 return; 2340 return;
2192 } 2341 }
2193 2342
2343
2194 if (part.SitTargetAvatar == UUID) 2344 if (part.SitTargetAvatar == UUID)
2195 { 2345 {
2196 Vector3 sitTargetPos = part.SitTargetPosition; 2346 Vector3 sitTargetPos = part.SitTargetPosition;
@@ -2205,14 +2355,39 @@ namespace OpenSim.Region.Framework.Scenes
2205 2355
2206 //Quaternion result = (sitTargetOrient * vq) * nq; 2356 //Quaternion result = (sitTargetOrient * vq) * nq;
2207 2357
2208 m_pos = sitTargetPos + SIT_TARGET_ADJUSTMENT; 2358 double x, y, z, m;
2359
2360 Quaternion r = sitTargetOrient;
2361 m = r.X * r.X + r.Y * r.Y + r.Z * r.Z + r.W * r.W;
2362
2363 if (Math.Abs(1.0 - m) > 0.000001)
2364 {
2365 m = 1.0 / Math.Sqrt(m);
2366 r.X *= (float)m;
2367 r.Y *= (float)m;
2368 r.Z *= (float)m;
2369 r.W *= (float)m;
2370 }
2371
2372 x = 2 * (r.X * r.Z + r.Y * r.W);
2373 y = 2 * (-r.X * r.W + r.Y * r.Z);
2374 z = -r.X * r.X - r.Y * r.Y + r.Z * r.Z + r.W * r.W;
2375
2376 Vector3 up = new Vector3((float)x, (float)y, (float)z);
2377 Vector3 sitOffset = up * Appearance.AvatarHeight * 0.02638f;
2378
2379 m_pos = sitTargetPos + sitOffset + SIT_TARGET_ADJUSTMENT;
2380
2381// m_pos = sitTargetPos + SIT_TARGET_ADJUSTMENT - sitOffset;
2209 Rotation = sitTargetOrient; 2382 Rotation = sitTargetOrient;
2210 ParentPosition = part.AbsolutePosition; 2383// ParentPosition = part.AbsolutePosition;
2384 part.ParentGroup.AddAvatar(UUID);
2211 } 2385 }
2212 else 2386 else
2213 { 2387 {
2214 m_pos -= part.AbsolutePosition; 2388 m_pos -= part.AbsolutePosition;
2215 ParentPosition = part.AbsolutePosition; 2389// ParentPosition = part.AbsolutePosition;
2390 part.ParentGroup.AddAvatar(UUID);
2216 2391
2217// m_log.DebugFormat( 2392// m_log.DebugFormat(
2218// "[SCENE PRESENCE]: Sitting {0} at position {1} ({2} + {3}) on part {4} {5} without sit target", 2393// "[SCENE PRESENCE]: Sitting {0} at position {1} ({2} + {3}) on part {4} {5} without sit target",
@@ -2262,6 +2437,13 @@ namespace OpenSim.Region.Framework.Scenes
2262 Animator.RemoveAnimation(animID, false); 2437 Animator.RemoveAnimation(animID, false);
2263 } 2438 }
2264 2439
2440 public void avnHandleChangeAnim(UUID animID, bool addRemove,bool sendPack)
2441 {
2442 Animator.avnChangeAnim(animID, addRemove, sendPack);
2443 }
2444
2445
2446
2265 /// <summary> 2447 /// <summary>
2266 /// Rotate the avatar to the given rotation and apply a movement in the given relative vector 2448 /// Rotate the avatar to the given rotation and apply a movement in the given relative vector
2267 /// </summary> 2449 /// </summary>
@@ -2315,14 +2497,15 @@ namespace OpenSim.Region.Framework.Scenes
2315 direc.Z *= 2.6f; 2497 direc.Z *= 2.6f;
2316 2498
2317 // TODO: PreJump and jump happen too quickly. Many times prejump gets ignored. 2499 // TODO: PreJump and jump happen too quickly. Many times prejump gets ignored.
2318 Animator.TrySetMovementAnimation("PREJUMP"); 2500// Animator.TrySetMovementAnimation("PREJUMP");
2319 Animator.TrySetMovementAnimation("JUMP"); 2501// Animator.TrySetMovementAnimation("JUMP");
2320 } 2502 }
2321 } 2503 }
2322 } 2504 }
2323 2505
2324 // TODO: Add the force instead of only setting it to support multiple forces per frame? 2506 // TODO: Add the force instead of only setting it to support multiple forces per frame?
2325 m_forceToApply = direc; 2507 m_forceToApply = direc;
2508 Animator.UpdateMovementAnimations();
2326 } 2509 }
2327 2510
2328 #endregion 2511 #endregion
@@ -2340,16 +2523,12 @@ namespace OpenSim.Region.Framework.Scenes
2340 // NOTE: Velocity is not the same as m_velocity. Velocity will attempt to 2523 // NOTE: Velocity is not the same as m_velocity. Velocity will attempt to
2341 // grab the latest PhysicsActor velocity, whereas m_velocity is often 2524 // grab the latest PhysicsActor velocity, whereas m_velocity is often
2342 // storing a requested force instead of an actual traveling velocity 2525 // storing a requested force instead of an actual traveling velocity
2526 if (Appearance.AvatarSize != m_lastSize && !IsLoggingIn)
2527 SendAvatarDataToAllAgents();
2343 2528
2344 // Throw away duplicate or insignificant updates 2529 if (!Rotation.ApproxEquals(m_lastRotation, ROTATION_TOLERANCE) ||
2345 if ( 2530 !Velocity.ApproxEquals(m_lastVelocity, VELOCITY_TOLERANCE) ||
2346 // If the velocity has become zero, send it no matter what. 2531 !m_pos.ApproxEquals(m_lastPosition, POSITION_TOLERANCE))
2347 (Velocity != m_lastVelocity && Velocity == Vector3.Zero)
2348 // otherwise, if things have changed reasonably, send the update
2349 || (!Rotation.ApproxEquals(m_lastRotation, ROTATION_TOLERANCE)
2350 || !Velocity.ApproxEquals(m_lastVelocity, VELOCITY_TOLERANCE)
2351 || !m_pos.ApproxEquals(m_lastPosition, POSITION_TOLERANCE)))
2352
2353 { 2532 {
2354 SendTerseUpdateToAllClients(); 2533 SendTerseUpdateToAllClients();
2355 2534
@@ -2538,6 +2717,8 @@ namespace OpenSim.Region.Framework.Scenes
2538 return; 2717 return;
2539 } 2718 }
2540 2719
2720 m_lastSize = Appearance.AvatarSize;
2721
2541 int count = 0; 2722 int count = 0;
2542 m_scene.ForEachScenePresence(delegate(ScenePresence scenePresence) 2723 m_scene.ForEachScenePresence(delegate(ScenePresence scenePresence)
2543 { 2724 {
@@ -2645,6 +2826,8 @@ namespace OpenSim.Region.Framework.Scenes
2645 2826
2646 avatar.ControllingClient.SendAppearance( 2827 avatar.ControllingClient.SendAppearance(
2647 UUID, Appearance.VisualParams, Appearance.Texture.GetBytes()); 2828 UUID, Appearance.VisualParams, Appearance.Texture.GetBytes());
2829
2830
2648 } 2831 }
2649 2832
2650 #endregion 2833 #endregion
@@ -2719,8 +2902,9 @@ namespace OpenSim.Region.Framework.Scenes
2719 2902
2720 // If we don't have a PhysActor, we can't cross anyway 2903 // If we don't have a PhysActor, we can't cross anyway
2721 // Also don't do this while sat, sitting avatars cross with the 2904 // Also don't do this while sat, sitting avatars cross with the
2722 // object they sit on. 2905 // object they sit on. ParentUUID denoted a pending sit, don't
2723 if (ParentID != 0 || PhysicsActor == null) 2906 // interfere with it.
2907 if (ParentID != 0 || PhysicsActor == null || ParentUUID != UUID.Zero)
2724 return; 2908 return;
2725 2909
2726 if (!IsInTransit) 2910 if (!IsInTransit)
@@ -2981,6 +3165,10 @@ namespace OpenSim.Region.Framework.Scenes
2981 } 3165 }
2982 3166
2983 private static Vector3 marker = new Vector3(-1f, -1f, -1f); 3167 private static Vector3 marker = new Vector3(-1f, -1f, -1f);
3168 private void RaiseUpdateThrottles()
3169 {
3170 m_scene.EventManager.TriggerThrottleUpdate(this);
3171 }
2984 /// <summary> 3172 /// <summary>
2985 /// This updates important decision making data about a child agent 3173 /// This updates important decision making data about a child agent
2986 /// The main purpose is to figure out what objects to send to a child agent that's in a neighboring region 3174 /// The main purpose is to figure out what objects to send to a child agent that's in a neighboring region
@@ -3061,6 +3249,9 @@ namespace OpenSim.Region.Framework.Scenes
3061 cAgent.AlwaysRun = SetAlwaysRun; 3249 cAgent.AlwaysRun = SetAlwaysRun;
3062 3250
3063 cAgent.Appearance = new AvatarAppearance(Appearance); 3251 cAgent.Appearance = new AvatarAppearance(Appearance);
3252
3253 cAgent.ParentPart = ParentUUID;
3254 cAgent.SitOffset = m_pos;
3064 3255
3065 lock (scriptedcontrols) 3256 lock (scriptedcontrols)
3066 { 3257 {
@@ -3069,7 +3260,7 @@ namespace OpenSim.Region.Framework.Scenes
3069 3260
3070 foreach (ScriptControllers c in scriptedcontrols.Values) 3261 foreach (ScriptControllers c in scriptedcontrols.Values)
3071 { 3262 {
3072 controls[i++] = new ControllerData(c.itemID, (uint)c.ignoreControls, (uint)c.eventControls); 3263 controls[i++] = new ControllerData(c.objectID, c.itemID, (uint)c.ignoreControls, (uint)c.eventControls);
3073 } 3264 }
3074 cAgent.Controllers = controls; 3265 cAgent.Controllers = controls;
3075 } 3266 }
@@ -3102,6 +3293,8 @@ namespace OpenSim.Region.Framework.Scenes
3102 CameraAtAxis = cAgent.AtAxis; 3293 CameraAtAxis = cAgent.AtAxis;
3103 CameraLeftAxis = cAgent.LeftAxis; 3294 CameraLeftAxis = cAgent.LeftAxis;
3104 CameraUpAxis = cAgent.UpAxis; 3295 CameraUpAxis = cAgent.UpAxis;
3296 ParentUUID = cAgent.ParentPart;
3297 m_prevSitOffset = cAgent.SitOffset;
3105 3298
3106 // When we get to the point of re-computing neighbors everytime this 3299 // When we get to the point of re-computing neighbors everytime this
3107 // changes, then start using the agent's drawdistance rather than the 3300 // changes, then start using the agent's drawdistance rather than the
@@ -3139,6 +3332,7 @@ namespace OpenSim.Region.Framework.Scenes
3139 foreach (ControllerData c in cAgent.Controllers) 3332 foreach (ControllerData c in cAgent.Controllers)
3140 { 3333 {
3141 ScriptControllers sc = new ScriptControllers(); 3334 ScriptControllers sc = new ScriptControllers();
3335 sc.objectID = c.ObjectID;
3142 sc.itemID = c.ItemID; 3336 sc.itemID = c.ItemID;
3143 sc.ignoreControls = (ScriptControlled)c.IgnoreControls; 3337 sc.ignoreControls = (ScriptControlled)c.IgnoreControls;
3144 sc.eventControls = (ScriptControlled)c.EventControls; 3338 sc.eventControls = (ScriptControlled)c.EventControls;
@@ -3206,20 +3400,27 @@ namespace OpenSim.Region.Framework.Scenes
3206 } 3400 }
3207 3401
3208 if (Appearance.AvatarHeight == 0) 3402 if (Appearance.AvatarHeight == 0)
3209 Appearance.SetHeight(); 3403// Appearance.SetHeight();
3404 Appearance.SetSize(new Vector3(0.45f,0.6f,1.9f));
3210 3405
3211 PhysicsScene scene = m_scene.PhysicsScene; 3406 PhysicsScene scene = m_scene.PhysicsScene;
3212 3407
3213 Vector3 pVec = AbsolutePosition; 3408 Vector3 pVec = AbsolutePosition;
3214 3409
3410/*
3215 PhysicsActor = scene.AddAvatar( 3411 PhysicsActor = scene.AddAvatar(
3216 LocalId, Firstname + "." + Lastname, pVec, 3412 LocalId, Firstname + "." + Lastname, pVec,
3217 new Vector3(0f, 0f, Appearance.AvatarHeight), isFlying); 3413 new Vector3(0.45f, 0.6f, Appearance.AvatarHeight), isFlying);
3414*/
3415
3416 PhysicsActor = scene.AddAvatar(
3417 LocalId, Firstname + "." + Lastname, pVec,
3418 Appearance.AvatarBoxSize,Appearance.AvatarFeetOffset, isFlying);
3218 3419
3219 //PhysicsActor.OnRequestTerseUpdate += SendTerseUpdateToAllClients; 3420 //PhysicsActor.OnRequestTerseUpdate += SendTerseUpdateToAllClients;
3220 PhysicsActor.OnCollisionUpdate += PhysicsCollisionUpdate; 3421 PhysicsActor.OnCollisionUpdate += PhysicsCollisionUpdate;
3221 PhysicsActor.OnOutOfBounds += OutOfBoundsCall; // Called for PhysicsActors when there's something wrong 3422 PhysicsActor.OnOutOfBounds += OutOfBoundsCall; // Called for PhysicsActors when there's something wrong
3222 PhysicsActor.SubscribeEvents(500); 3423 PhysicsActor.SubscribeEvents(100);
3223 PhysicsActor.LocalID = LocalId; 3424 PhysicsActor.LocalID = LocalId;
3224 } 3425 }
3225 3426
@@ -3233,6 +3434,7 @@ namespace OpenSim.Region.Framework.Scenes
3233 ControllingClient.SendAgentAlertMessage("Physics is having a problem with your avatar. You may not be able to move until you relog.", true); 3434 ControllingClient.SendAgentAlertMessage("Physics is having a problem with your avatar. You may not be able to move until you relog.", true);
3234 } 3435 }
3235 3436
3437
3236 /// <summary> 3438 /// <summary>
3237 /// Event called by the physics plugin to tell the avatar about a collision. 3439 /// Event called by the physics plugin to tell the avatar about a collision.
3238 /// </summary> 3440 /// </summary>
@@ -3246,7 +3448,7 @@ namespace OpenSim.Region.Framework.Scenes
3246 /// <param name="e"></param> 3448 /// <param name="e"></param>
3247 public void PhysicsCollisionUpdate(EventArgs e) 3449 public void PhysicsCollisionUpdate(EventArgs e)
3248 { 3450 {
3249 if (IsChildAgent) 3451 if (IsChildAgent || Animator == null)
3250 return; 3452 return;
3251 3453
3252 //if ((Math.Abs(Velocity.X) > 0.1e-9f) || (Math.Abs(Velocity.Y) > 0.1e-9f)) 3454 //if ((Math.Abs(Velocity.X) > 0.1e-9f) || (Math.Abs(Velocity.Y) > 0.1e-9f))
@@ -3262,7 +3464,6 @@ namespace OpenSim.Region.Framework.Scenes
3262 CollisionEventUpdate collisionData = (CollisionEventUpdate)e; 3464 CollisionEventUpdate collisionData = (CollisionEventUpdate)e;
3263 Dictionary<uint, ContactPoint> coldata = collisionData.m_objCollisionList; 3465 Dictionary<uint, ContactPoint> coldata = collisionData.m_objCollisionList;
3264 3466
3265 CollisionPlane = Vector4.UnitW;
3266 3467
3267// // No collisions at all means we may be flying. Update always 3468// // No collisions at all means we may be flying. Update always
3268// // to make falling work 3469// // to make falling work
@@ -3274,6 +3475,7 @@ namespace OpenSim.Region.Framework.Scenes
3274 3475
3275 if (coldata.Count != 0) 3476 if (coldata.Count != 0)
3276 { 3477 {
3478/*
3277 switch (Animator.CurrentMovementAnimation) 3479 switch (Animator.CurrentMovementAnimation)
3278 { 3480 {
3279 case "STAND": 3481 case "STAND":
@@ -3282,24 +3484,38 @@ namespace OpenSim.Region.Framework.Scenes
3282 case "CROUCH": 3484 case "CROUCH":
3283 case "CROUCHWALK": 3485 case "CROUCHWALK":
3284 { 3486 {
3487 */
3285 ContactPoint lowest; 3488 ContactPoint lowest;
3286 lowest.SurfaceNormal = Vector3.Zero; 3489 lowest.SurfaceNormal = Vector3.Zero;
3287 lowest.Position = Vector3.Zero; 3490 lowest.Position = Vector3.Zero;
3288 lowest.Position.Z = Single.NaN; 3491 lowest.Position.Z = float.MaxValue;
3289 3492
3290 foreach (ContactPoint contact in coldata.Values) 3493 foreach (ContactPoint contact in coldata.Values)
3291 { 3494 {
3292 if (Single.IsNaN(lowest.Position.Z) || contact.Position.Z < lowest.Position.Z) 3495
3496 if (contact.CharacterFeet && contact.Position.Z < lowest.Position.Z)
3293 { 3497 {
3294 lowest = contact; 3498 lowest = contact;
3295 } 3499 }
3296 } 3500 }
3297 3501
3298 CollisionPlane = new Vector4(-lowest.SurfaceNormal, -Vector3.Dot(lowest.Position, lowest.SurfaceNormal)); 3502 if (lowest.Position.Z != float.MaxValue)
3503 {
3504 lowest.SurfaceNormal = -lowest.SurfaceNormal;
3505 CollisionPlane = new Vector4(lowest.SurfaceNormal, Vector3.Dot(lowest.Position, lowest.SurfaceNormal));
3506 }
3507 else
3508 CollisionPlane = Vector4.UnitW;
3509/*
3299 } 3510 }
3300 break; 3511 break;
3301 } 3512 }
3513*/
3302 } 3514 }
3515 else
3516 CollisionPlane = Vector4.UnitW;
3517
3518 RaiseCollisionScriptEvents(coldata);
3303 3519
3304 // Gods do not take damage and Invulnerable is set depending on parcel/region flags 3520 // Gods do not take damage and Invulnerable is set depending on parcel/region flags
3305 if (Invulnerable || GodLevel > 0) 3521 if (Invulnerable || GodLevel > 0)
@@ -3398,6 +3614,13 @@ namespace OpenSim.Region.Framework.Scenes
3398 // m_reprioritizationTimer.Dispose(); 3614 // m_reprioritizationTimer.Dispose();
3399 3615
3400 RemoveFromPhysicalScene(); 3616 RemoveFromPhysicalScene();
3617
3618 m_scene.EventManager.OnRegionHeartbeatEnd -= RegionHeartbeatEnd;
3619
3620// if (Animator != null)
3621// Animator.Close();
3622 Animator = null;
3623
3401 } 3624 }
3402 3625
3403 public void AddAttachment(SceneObjectGroup gobj) 3626 public void AddAttachment(SceneObjectGroup gobj)
@@ -3631,10 +3854,18 @@ namespace OpenSim.Region.Framework.Scenes
3631 3854
3632 public void RegisterControlEventsToScript(int controls, int accept, int pass_on, uint Obj_localID, UUID Script_item_UUID) 3855 public void RegisterControlEventsToScript(int controls, int accept, int pass_on, uint Obj_localID, UUID Script_item_UUID)
3633 { 3856 {
3857 SceneObjectPart p = m_scene.GetSceneObjectPart(Obj_localID);
3858 if (p == null)
3859 return;
3860
3861 ControllingClient.SendTakeControls(controls, false, false);
3862 ControllingClient.SendTakeControls(controls, true, false);
3863
3634 ScriptControllers obj = new ScriptControllers(); 3864 ScriptControllers obj = new ScriptControllers();
3635 obj.ignoreControls = ScriptControlled.CONTROL_ZERO; 3865 obj.ignoreControls = ScriptControlled.CONTROL_ZERO;
3636 obj.eventControls = ScriptControlled.CONTROL_ZERO; 3866 obj.eventControls = ScriptControlled.CONTROL_ZERO;
3637 3867
3868 obj.objectID = p.ParentGroup.UUID;
3638 obj.itemID = Script_item_UUID; 3869 obj.itemID = Script_item_UUID;
3639 if (pass_on == 0 && accept == 0) 3870 if (pass_on == 0 && accept == 0)
3640 { 3871 {
@@ -3683,6 +3914,21 @@ namespace OpenSim.Region.Framework.Scenes
3683 ControllingClient.SendTakeControls(int.MaxValue, false, false); 3914 ControllingClient.SendTakeControls(int.MaxValue, false, false);
3684 } 3915 }
3685 3916
3917 private void UnRegisterSeatControls(UUID obj)
3918 {
3919 List<UUID> takers = new List<UUID>();
3920
3921 foreach (ScriptControllers c in scriptedcontrols.Values)
3922 {
3923 if (c.objectID == obj)
3924 takers.Add(c.itemID);
3925 }
3926 foreach (UUID t in takers)
3927 {
3928 UnRegisterControlEventsToScript(0, t);
3929 }
3930 }
3931
3686 public void UnRegisterControlEventsToScript(uint Obj_localID, UUID Script_item_UUID) 3932 public void UnRegisterControlEventsToScript(uint Obj_localID, UUID Script_item_UUID)
3687 { 3933 {
3688 ScriptControllers takecontrols; 3934 ScriptControllers takecontrols;
@@ -4001,6 +4247,12 @@ namespace OpenSim.Region.Framework.Scenes
4001 4247
4002 private void CheckAndAdjustLandingPoint(ref Vector3 pos) 4248 private void CheckAndAdjustLandingPoint(ref Vector3 pos)
4003 { 4249 {
4250 string reason;
4251
4252 // Honor bans
4253 if (!m_scene.TestLandRestrictions(UUID, out reason, ref pos.X, ref pos.Y))
4254 return;
4255
4004 SceneObjectGroup telehub = null; 4256 SceneObjectGroup telehub = null;
4005 if (m_scene.RegionInfo.RegionSettings.TelehubObject != UUID.Zero && (telehub = m_scene.GetSceneObjectGroup(m_scene.RegionInfo.RegionSettings.TelehubObject)) != null) 4257 if (m_scene.RegionInfo.RegionSettings.TelehubObject != UUID.Zero && (telehub = m_scene.GetSceneObjectGroup(m_scene.RegionInfo.RegionSettings.TelehubObject)) != null)
4006 { 4258 {
@@ -4040,11 +4292,206 @@ namespace OpenSim.Region.Framework.Scenes
4040 pos = land.LandData.UserLocation; 4292 pos = land.LandData.UserLocation;
4041 } 4293 }
4042 } 4294 }
4043 4295
4044 land.SendLandUpdateToClient(ControllingClient); 4296 land.SendLandUpdateToClient(ControllingClient);
4045 } 4297 }
4046 } 4298 }
4047 4299
4300 private DetectedObject CreateDetObject(SceneObjectPart obj)
4301 {
4302 DetectedObject detobj = new DetectedObject();
4303 detobj.keyUUID = obj.UUID;
4304 detobj.nameStr = obj.Name;
4305 detobj.ownerUUID = obj.OwnerID;
4306 detobj.posVector = obj.AbsolutePosition;
4307 detobj.rotQuat = obj.GetWorldRotation();
4308 detobj.velVector = obj.Velocity;
4309 detobj.colliderType = 0;
4310 detobj.groupUUID = obj.GroupID;
4311
4312 return detobj;
4313 }
4314
4315 private DetectedObject CreateDetObject(ScenePresence av)
4316 {
4317 DetectedObject detobj = new DetectedObject();
4318 detobj.keyUUID = av.UUID;
4319 detobj.nameStr = av.ControllingClient.Name;
4320 detobj.ownerUUID = av.UUID;
4321 detobj.posVector = av.AbsolutePosition;
4322 detobj.rotQuat = av.Rotation;
4323 detobj.velVector = av.Velocity;
4324 detobj.colliderType = 0;
4325 detobj.groupUUID = av.ControllingClient.ActiveGroupId;
4326
4327 return detobj;
4328 }
4329
4330 private DetectedObject CreateDetObjectForGround()
4331 {
4332 DetectedObject detobj = new DetectedObject();
4333 detobj.keyUUID = UUID.Zero;
4334 detobj.nameStr = "";
4335 detobj.ownerUUID = UUID.Zero;
4336 detobj.posVector = AbsolutePosition;
4337 detobj.rotQuat = Quaternion.Identity;
4338 detobj.velVector = Vector3.Zero;
4339 detobj.colliderType = 0;
4340 detobj.groupUUID = UUID.Zero;
4341
4342 return detobj;
4343 }
4344
4345 private ColliderArgs CreateColliderArgs(SceneObjectPart dest, List<uint> colliders)
4346 {
4347 ColliderArgs colliderArgs = new ColliderArgs();
4348 List<DetectedObject> colliding = new List<DetectedObject>();
4349 foreach (uint localId in colliders)
4350 {
4351 if (localId == 0)
4352 continue;
4353
4354 SceneObjectPart obj = m_scene.GetSceneObjectPart(localId);
4355 if (obj != null)
4356 {
4357 if (!dest.CollisionFilteredOut(obj.UUID, obj.Name))
4358 colliding.Add(CreateDetObject(obj));
4359 }
4360 else
4361 {
4362 ScenePresence av = m_scene.GetScenePresence(localId);
4363 if (av != null && (!av.IsChildAgent))
4364 {
4365 if (!dest.CollisionFilteredOut(av.UUID, av.Name))
4366 colliding.Add(CreateDetObject(av));
4367 }
4368 }
4369 }
4370
4371 colliderArgs.Colliders = colliding;
4372
4373 return colliderArgs;
4374 }
4375
4376 private delegate void ScriptCollidingNotification(uint localID, ColliderArgs message);
4377
4378 private void SendCollisionEvent(SceneObjectGroup dest, scriptEvents ev, List<uint> colliders, ScriptCollidingNotification notify)
4379 {
4380 ColliderArgs CollidingMessage;
4381
4382 if (colliders.Count > 0)
4383 {
4384 if ((dest.RootPart.ScriptEvents & ev) != 0)
4385 {
4386 CollidingMessage = CreateColliderArgs(dest.RootPart, colliders);
4387
4388 if (CollidingMessage.Colliders.Count > 0)
4389 notify(dest.RootPart.LocalId, CollidingMessage);
4390 }
4391 }
4392 }
4393
4394 private void SendLandCollisionEvent(SceneObjectGroup dest, scriptEvents ev, ScriptCollidingNotification notify)
4395 {
4396 if ((dest.RootPart.ScriptEvents & ev) != 0)
4397 {
4398 ColliderArgs LandCollidingMessage = new ColliderArgs();
4399 List<DetectedObject> colliding = new List<DetectedObject>();
4400
4401 colliding.Add(CreateDetObjectForGround());
4402 LandCollidingMessage.Colliders = colliding;
4403
4404 notify(dest.RootPart.LocalId, LandCollidingMessage);
4405 }
4406 }
4407
4408 private void RaiseCollisionScriptEvents(Dictionary<uint, ContactPoint> coldata)
4409 {
4410 try
4411 {
4412 List<uint> thisHitColliders = new List<uint>();
4413 List<uint> endedColliders = new List<uint>();
4414 List<uint> startedColliders = new List<uint>();
4415 List<CollisionForSoundInfo> soundinfolist = new List<CollisionForSoundInfo>();
4416 CollisionForSoundInfo soundinfo;
4417 ContactPoint curcontact;
4418
4419 if (coldata.Count == 0)
4420 {
4421 if (m_lastColliders.Count == 0)
4422 return; // nothing to do
4423
4424 foreach (uint localID in m_lastColliders)
4425 {
4426 endedColliders.Add(localID);
4427 }
4428 m_lastColliders.Clear();
4429 }
4430
4431 else
4432 {
4433 foreach (uint id in coldata.Keys)
4434 {
4435 thisHitColliders.Add(id);
4436 if (!m_lastColliders.Contains(id))
4437 {
4438 startedColliders.Add(id);
4439 curcontact = coldata[id];
4440 if (Math.Abs(curcontact.RelativeSpeed) > 0.2)
4441 {
4442 soundinfo = new CollisionForSoundInfo();
4443 soundinfo.colliderID = id;
4444 soundinfo.position = curcontact.Position;
4445 soundinfo.relativeVel = curcontact.RelativeSpeed;
4446 soundinfolist.Add(soundinfo);
4447 }
4448 }
4449 //m_log.Debug("[SCENE PRESENCE]: Collided with:" + localid.ToString() + " at depth of: " + collissionswith[localid].ToString());
4450 }
4451
4452 // calculate things that ended colliding
4453 foreach (uint localID in m_lastColliders)
4454 {
4455 if (!thisHitColliders.Contains(localID))
4456 {
4457 endedColliders.Add(localID);
4458 }
4459 }
4460 //add the items that started colliding this time to the last colliders list.
4461 foreach (uint localID in startedColliders)
4462 {
4463 m_lastColliders.Add(localID);
4464 }
4465 // remove things that ended colliding from the last colliders list
4466 foreach (uint localID in endedColliders)
4467 {
4468 m_lastColliders.Remove(localID);
4469 }
4470
4471 if (soundinfolist.Count > 0)
4472 CollisionSounds.AvatarCollisionSound(this, soundinfolist);
4473 }
4474
4475 foreach (SceneObjectGroup att in GetAttachments())
4476 {
4477 SendCollisionEvent(att, scriptEvents.collision_start, startedColliders, m_scene.EventManager.TriggerScriptCollidingStart);
4478 SendCollisionEvent(att, scriptEvents.collision , m_lastColliders , m_scene.EventManager.TriggerScriptColliding);
4479 SendCollisionEvent(att, scriptEvents.collision_end , endedColliders , m_scene.EventManager.TriggerScriptCollidingEnd);
4480
4481 if (startedColliders.Contains(0))
4482 SendLandCollisionEvent(att, scriptEvents.land_collision_start, m_scene.EventManager.TriggerScriptLandCollidingStart);
4483 if (m_lastColliders.Contains(0))
4484 SendLandCollisionEvent(att, scriptEvents.land_collision, m_scene.EventManager.TriggerScriptLandColliding);
4485 if (endedColliders.Contains(0))
4486 SendLandCollisionEvent(att, scriptEvents.land_collision_end, m_scene.EventManager.TriggerScriptLandCollidingEnd);
4487 }
4488 }
4489 finally
4490 {
4491 m_collisionEventFlag = false;
4492 }
4493 }
4494
4048 private void TeleportFlagsDebug() { 4495 private void TeleportFlagsDebug() {
4049 4496
4050 // Some temporary debugging help to show all the TeleportFlags we have... 4497 // Some temporary debugging help to show all the TeleportFlags we have...
@@ -4069,6 +4516,5 @@ namespace OpenSim.Region.Framework.Scenes
4069 m_log.InfoFormat("[SCENE PRESENCE]: TELEPORT ******************"); 4516 m_log.InfoFormat("[SCENE PRESENCE]: TELEPORT ******************");
4070 4517
4071 } 4518 }
4072
4073 } 4519 }
4074} 4520}
diff --git a/OpenSim/Region/Framework/Scenes/Serialization/SceneObjectSerializer.cs b/OpenSim/Region/Framework/Scenes/Serialization/SceneObjectSerializer.cs
index 2d4c60a..123c158 100644
--- a/OpenSim/Region/Framework/Scenes/Serialization/SceneObjectSerializer.cs
+++ b/OpenSim/Region/Framework/Scenes/Serialization/SceneObjectSerializer.cs
@@ -262,6 +262,12 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
262 sr.Close(); 262 sr.Close();
263 } 263 }
264 264
265 XmlNodeList keymotion = doc.GetElementsByTagName("KeyframeMotion");
266 if (keymotion.Count > 0)
267 sceneObject.RootPart.KeyframeMotion = KeyframeMotion.FromData(sceneObject, Convert.FromBase64String(keymotion[0].InnerText));
268 else
269 sceneObject.RootPart.KeyframeMotion = null;
270
265 // Script state may, or may not, exist. Not having any, is NOT 271 // Script state may, or may not, exist. Not having any, is NOT
266 // ever a problem. 272 // ever a problem.
267 sceneObject.LoadScriptState(doc); 273 sceneObject.LoadScriptState(doc);
@@ -366,6 +372,23 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
366 m_SOPXmlProcessors.Add("PayPrice2", ProcessPayPrice2); 372 m_SOPXmlProcessors.Add("PayPrice2", ProcessPayPrice2);
367 m_SOPXmlProcessors.Add("PayPrice3", ProcessPayPrice3); 373 m_SOPXmlProcessors.Add("PayPrice3", ProcessPayPrice3);
368 m_SOPXmlProcessors.Add("PayPrice4", ProcessPayPrice4); 374 m_SOPXmlProcessors.Add("PayPrice4", ProcessPayPrice4);
375
376 m_SOPXmlProcessors.Add("Buoyancy", ProcessBuoyancy);
377 m_SOPXmlProcessors.Add("Force", ProcessForce);
378 m_SOPXmlProcessors.Add("Torque", ProcessTorque);
379 m_SOPXmlProcessors.Add("VolumeDetectActive", ProcessVolumeDetectActive);
380
381
382 m_SOPXmlProcessors.Add("Vehicle", ProcessVehicle);
383
384 m_SOPXmlProcessors.Add("PhysicsShapeType", ProcessPhysicsShapeType);
385 m_SOPXmlProcessors.Add("Density", ProcessDensity);
386 m_SOPXmlProcessors.Add("Friction", ProcessFriction);
387 m_SOPXmlProcessors.Add("Bounce", ProcessBounce);
388 m_SOPXmlProcessors.Add("GravityModifier", ProcessGravityModifier);
389 m_SOPXmlProcessors.Add("CameraEyeOffset", ProcessCameraEyeOffset);
390 m_SOPXmlProcessors.Add("CameraAtOffset", ProcessCameraAtOffset);
391
369 #endregion 392 #endregion
370 393
371 #region TaskInventoryXmlProcessors initialization 394 #region TaskInventoryXmlProcessors initialization
@@ -393,7 +416,7 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
393 m_TaskInventoryXmlProcessors.Add("PermsMask", ProcessTIPermsMask); 416 m_TaskInventoryXmlProcessors.Add("PermsMask", ProcessTIPermsMask);
394 m_TaskInventoryXmlProcessors.Add("Type", ProcessTIType); 417 m_TaskInventoryXmlProcessors.Add("Type", ProcessTIType);
395 m_TaskInventoryXmlProcessors.Add("OwnerChanged", ProcessTIOwnerChanged); 418 m_TaskInventoryXmlProcessors.Add("OwnerChanged", ProcessTIOwnerChanged);
396 419
397 #endregion 420 #endregion
398 421
399 #region ShapeXmlProcessors initialization 422 #region ShapeXmlProcessors initialization
@@ -593,6 +616,58 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
593 obj.ClickAction = (byte)reader.ReadElementContentAsInt("ClickAction", String.Empty); 616 obj.ClickAction = (byte)reader.ReadElementContentAsInt("ClickAction", String.Empty);
594 } 617 }
595 618
619 private static void ProcessPhysicsShapeType(SceneObjectPart obj, XmlTextReader reader)
620 {
621 obj.PhysicsShapeType = (byte)reader.ReadElementContentAsInt("PhysicsShapeType", String.Empty);
622 }
623
624 private static void ProcessDensity(SceneObjectPart obj, XmlTextReader reader)
625 {
626 obj.Density = reader.ReadElementContentAsFloat("Density", String.Empty);
627 }
628
629 private static void ProcessFriction(SceneObjectPart obj, XmlTextReader reader)
630 {
631 obj.Friction = reader.ReadElementContentAsFloat("Friction", String.Empty);
632 }
633
634 private static void ProcessBounce(SceneObjectPart obj, XmlTextReader reader)
635 {
636 obj.Bounciness = reader.ReadElementContentAsFloat("Bounce", String.Empty);
637 }
638
639 private static void ProcessGravityModifier(SceneObjectPart obj, XmlTextReader reader)
640 {
641 obj.GravityModifier = reader.ReadElementContentAsFloat("GravityModifier", String.Empty);
642 }
643
644 private static void ProcessCameraEyeOffset(SceneObjectPart obj, XmlTextReader reader)
645 {
646 obj.SetCameraEyeOffset(Util.ReadVector(reader, "CameraEyeOffset"));
647 }
648
649 private static void ProcessCameraAtOffset(SceneObjectPart obj, XmlTextReader reader)
650 {
651 obj.SetCameraAtOffset(Util.ReadVector(reader, "CameraAtOffset"));
652 }
653
654 private static void ProcessVehicle(SceneObjectPart obj, XmlTextReader reader)
655 {
656 SOPVehicle vehicle = SOPVehicle.FromXml2(reader);
657
658 if (vehicle == null)
659 {
660 obj.VehicleParams = null;
661 m_log.DebugFormat(
662 "[SceneObjectSerializer]: Parsing Vehicle for object part {0} {1} encountered errors. Please see earlier log entries.",
663 obj.Name, obj.UUID);
664 }
665 else
666 {
667 obj.VehicleParams = vehicle;
668 }
669 }
670
596 private static void ProcessShape(SceneObjectPart obj, XmlTextReader reader) 671 private static void ProcessShape(SceneObjectPart obj, XmlTextReader reader)
597 { 672 {
598 List<string> errorNodeNames; 673 List<string> errorNodeNames;
@@ -757,6 +832,25 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
757 obj.PayPrice[4] = (int)reader.ReadElementContentAsInt("PayPrice4", String.Empty); 832 obj.PayPrice[4] = (int)reader.ReadElementContentAsInt("PayPrice4", String.Empty);
758 } 833 }
759 834
835 private static void ProcessBuoyancy(SceneObjectPart obj, XmlTextReader reader)
836 {
837 obj.Buoyancy = (float)reader.ReadElementContentAsFloat("Buoyancy", String.Empty);
838 }
839
840 private static void ProcessForce(SceneObjectPart obj, XmlTextReader reader)
841 {
842 obj.Force = Util.ReadVector(reader, "Force");
843 }
844 private static void ProcessTorque(SceneObjectPart obj, XmlTextReader reader)
845 {
846 obj.Torque = Util.ReadVector(reader, "Torque");
847 }
848
849 private static void ProcessVolumeDetectActive(SceneObjectPart obj, XmlTextReader reader)
850 {
851 obj.VolumeDetectActive = Util.ReadBoolean(reader);
852 }
853
760 #endregion 854 #endregion
761 855
762 #region TaskInventoryXmlProcessors 856 #region TaskInventoryXmlProcessors
@@ -1144,6 +1238,16 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
1144 }); 1238 });
1145 1239
1146 writer.WriteEndElement(); 1240 writer.WriteEndElement();
1241
1242 if (sog.RootPart.KeyframeMotion != null)
1243 {
1244 Byte[] data = sog.RootPart.KeyframeMotion.Serialize();
1245
1246 writer.WriteStartElement(String.Empty, "KeyframeMotion", String.Empty);
1247 writer.WriteBase64(data, 0, data.Length);
1248 writer.WriteEndElement();
1249 }
1250
1147 writer.WriteEndElement(); 1251 writer.WriteEndElement();
1148 } 1252 }
1149 1253
@@ -1243,6 +1347,29 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
1243 writer.WriteElementString("PayPrice3", sop.PayPrice[3].ToString()); 1347 writer.WriteElementString("PayPrice3", sop.PayPrice[3].ToString());
1244 writer.WriteElementString("PayPrice4", sop.PayPrice[4].ToString()); 1348 writer.WriteElementString("PayPrice4", sop.PayPrice[4].ToString());
1245 1349
1350 writer.WriteElementString("Buoyancy", sop.Buoyancy.ToString());
1351
1352 WriteVector(writer, "Force", sop.Force);
1353 WriteVector(writer, "Torque", sop.Torque);
1354
1355 writer.WriteElementString("VolumeDetectActive", sop.VolumeDetectActive.ToString().ToLower());
1356
1357 if (sop.VehicleParams != null)
1358 sop.VehicleParams.ToXml2(writer);
1359
1360 if(sop.PhysicsShapeType != sop.DefaultPhysicsShapeType())
1361 writer.WriteElementString("PhysicsShapeType", sop.PhysicsShapeType.ToString().ToLower());
1362 if (sop.Density != 1000.0f)
1363 writer.WriteElementString("Density", sop.Density.ToString().ToLower());
1364 if (sop.Friction != 0.6f)
1365 writer.WriteElementString("Friction", sop.Friction.ToString().ToLower());
1366 if (sop.Bounciness != 0.5f)
1367 writer.WriteElementString("Bounce", sop.Bounciness.ToString().ToLower());
1368 if (sop.GravityModifier != 1.0f)
1369 writer.WriteElementString("GravityModifier", sop.GravityModifier.ToString().ToLower());
1370 WriteVector(writer, "CameraEyeOffset", sop.GetCameraEyeOffset());
1371 WriteVector(writer, "CameraAtOffset", sop.GetCameraAtOffset());
1372
1246 writer.WriteEndElement(); 1373 writer.WriteEndElement();
1247 } 1374 }
1248 1375
@@ -1467,12 +1594,6 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
1467 { 1594 {
1468 TaskInventoryDictionary tinv = new TaskInventoryDictionary(); 1595 TaskInventoryDictionary tinv = new TaskInventoryDictionary();
1469 1596
1470 if (reader.IsEmptyElement)
1471 {
1472 reader.Read();
1473 return tinv;
1474 }
1475
1476 reader.ReadStartElement(name, String.Empty); 1597 reader.ReadStartElement(name, String.Empty);
1477 1598
1478 while (reader.Name == "TaskInventoryItem") 1599 while (reader.Name == "TaskInventoryItem")
diff --git a/OpenSim/Region/Framework/Scenes/SimStatsReporter.cs b/OpenSim/Region/Framework/Scenes/SimStatsReporter.cs
index b9d615e..5398ab9 100644
--- a/OpenSim/Region/Framework/Scenes/SimStatsReporter.cs
+++ b/OpenSim/Region/Framework/Scenes/SimStatsReporter.cs
@@ -175,7 +175,7 @@ namespace OpenSim.Region.Framework.Scenes
175 175
176 // saved last reported value so there is something available for llGetRegionFPS 176 // saved last reported value so there is something available for llGetRegionFPS
177 private float lastReportedSimFPS; 177 private float lastReportedSimFPS;
178 private float[] lastReportedSimStats = new float[22]; 178 private float[] lastReportedSimStats = new float[23];
179 private float m_pfps; 179 private float m_pfps;
180 180
181 /// <summary> 181 /// <summary>
@@ -189,12 +189,13 @@ namespace OpenSim.Region.Framework.Scenes
189 private int m_objectUpdates; 189 private int m_objectUpdates;
190 190
191 private int m_frameMS; 191 private int m_frameMS;
192 private int m_spareMS; 192
193 private int m_netMS; 193 private int m_netMS;
194 private int m_agentMS; 194 private int m_agentMS;
195 private int m_physicsMS; 195 private int m_physicsMS;
196 private int m_imageMS; 196 private int m_imageMS;
197 private int m_otherMS; 197 private int m_otherMS;
198 private int m_sleeptimeMS;
198 199
199//Ckrinke: (3-21-08) Comment out to remove a compiler warning. Bring back into play when needed. 200//Ckrinke: (3-21-08) Comment out to remove a compiler warning. Bring back into play when needed.
200//Ckrinke private int m_scriptMS = 0; 201//Ckrinke private int m_scriptMS = 0;
@@ -289,7 +290,7 @@ namespace OpenSim.Region.Framework.Scenes
289 290
290 private void statsHeartBeat(object sender, EventArgs e) 291 private void statsHeartBeat(object sender, EventArgs e)
291 { 292 {
292 SimStatsPacket.StatBlock[] sb = new SimStatsPacket.StatBlock[22]; 293 SimStatsPacket.StatBlock[] sb = new SimStatsPacket.StatBlock[23];
293 SimStatsPacket.RegionBlock rb = new SimStatsPacket.RegionBlock(); 294 SimStatsPacket.RegionBlock rb = new SimStatsPacket.RegionBlock();
294 295
295 // Know what's not thread safe in Mono... modifying timers. 296 // Know what's not thread safe in Mono... modifying timers.
@@ -327,6 +328,35 @@ namespace OpenSim.Region.Framework.Scenes
327 physfps = 0; 328 physfps = 0;
328 329
329#endregion 330#endregion
331 float factor = 1 / m_statsUpdateFactor;
332
333 if (reportedFPS <= 0)
334 reportedFPS = 1;
335
336 float perframe = 1.0f / (float)reportedFPS;
337
338 float TotalFrameTime = m_frameMS * perframe;
339
340 float targetframetime = 1100.0f / (float)m_nominalReportedFps;
341
342 float sparetime;
343 float sleeptime;
344
345 if (TotalFrameTime > targetframetime)
346 {
347 sparetime = 0;
348 sleeptime = 0;
349 }
350 else
351 {
352 sparetime = m_frameMS - m_physicsMS - m_agentMS;
353 sparetime *= perframe;
354 if (sparetime < 0)
355 sparetime = 0;
356 else if (sparetime > TotalFrameTime)
357 sparetime = TotalFrameTime;
358 sleeptime = m_sleeptimeMS * perframe;
359 }
330 360
331 m_rootAgents = m_scene.SceneGraph.GetRootAgentCount(); 361 m_rootAgents = m_scene.SceneGraph.GetRootAgentCount();
332 m_childAgents = m_scene.SceneGraph.GetChildAgentCount(); 362 m_childAgents = m_scene.SceneGraph.GetChildAgentCount();
@@ -338,25 +368,15 @@ namespace OpenSim.Region.Framework.Scenes
338 // so that stat numbers are always consistent. 368 // so that stat numbers are always consistent.
339 CheckStatSanity(); 369 CheckStatSanity();
340 370
341 //Our time dilation is 0.91 when we're running a full speed, 371 // other MS is actually simulation time
342 // therefore to make sure we get an appropriate range, 372 // m_otherMS = m_frameMS - m_physicsMS - m_imageMS - m_netMS - m_agentMS;
343 // we have to factor in our error. (0.10f * statsUpdateFactor) 373 // m_imageMS m_netMS are not included in m_frameMS
344 // multiplies the fix for the error times the amount of times it'll occur a second
345 // / 10 divides the value by the number of times the sim heartbeat runs (10fps)
346 // Then we divide the whole amount by the amount of seconds pass in between stats updates.
347
348 // 'statsUpdateFactor' is how often stats packets are sent in seconds. Used below to change
349 // values to X-per-second values.
350 374
351 uint thisFrame = m_scene.Frame; 375 m_otherMS = m_frameMS - m_physicsMS - m_agentMS - m_sleeptimeMS;
352 float framesUpdated = (float)(thisFrame - m_lastUpdateFrame) * m_reportedFpsCorrectionFactor; 376 if (m_otherMS < 0)
353 m_lastUpdateFrame = thisFrame; 377 m_otherMS = 0;
354 378
355 // Avoid div-by-zero if somehow we've not updated any frames. 379 for (int i = 0; i < 23; i++)
356 if (framesUpdated == 0)
357 framesUpdated = 1;
358
359 for (int i = 0; i < 22; i++)
360 { 380 {
361 sb[i] = new SimStatsPacket.StatBlock(); 381 sb[i] = new SimStatsPacket.StatBlock();
362 } 382 }
@@ -386,19 +406,19 @@ namespace OpenSim.Region.Framework.Scenes
386 sb[7].StatValue = m_activePrim; 406 sb[7].StatValue = m_activePrim;
387 407
388 sb[8].StatID = (uint)Stats.FrameMS; 408 sb[8].StatID = (uint)Stats.FrameMS;
389 sb[8].StatValue = m_frameMS / framesUpdated; 409 sb[8].StatValue = TotalFrameTime;
390 410
391 sb[9].StatID = (uint)Stats.NetMS; 411 sb[9].StatID = (uint)Stats.NetMS;
392 sb[9].StatValue = m_netMS / framesUpdated; 412 sb[9].StatValue = m_netMS * perframe;
393 413
394 sb[10].StatID = (uint)Stats.PhysicsMS; 414 sb[10].StatID = (uint)Stats.PhysicsMS;
395 sb[10].StatValue = m_physicsMS / framesUpdated; 415 sb[10].StatValue = m_physicsMS * perframe;
396 416
397 sb[11].StatID = (uint)Stats.ImageMS ; 417 sb[11].StatID = (uint)Stats.ImageMS ;
398 sb[11].StatValue = m_imageMS / framesUpdated; 418 sb[11].StatValue = m_imageMS * perframe;
399 419
400 sb[12].StatID = (uint)Stats.OtherMS; 420 sb[12].StatID = (uint)Stats.OtherMS;
401 sb[12].StatValue = m_otherMS / framesUpdated; 421 sb[12].StatValue = m_otherMS * perframe;
402 422
403 sb[13].StatID = (uint)Stats.InPacketsPerSecond; 423 sb[13].StatID = (uint)Stats.InPacketsPerSecond;
404 sb[13].StatValue = (m_inPacketsPerSecond / m_statsUpdateFactor); 424 sb[13].StatValue = (m_inPacketsPerSecond / m_statsUpdateFactor);
@@ -410,7 +430,7 @@ namespace OpenSim.Region.Framework.Scenes
410 sb[15].StatValue = m_unAckedBytes; 430 sb[15].StatValue = m_unAckedBytes;
411 431
412 sb[16].StatID = (uint)Stats.AgentMS; 432 sb[16].StatID = (uint)Stats.AgentMS;
413 sb[16].StatValue = m_agentMS / framesUpdated; 433 sb[16].StatValue = m_agentMS * perframe;
414 434
415 sb[17].StatID = (uint)Stats.PendingDownloads; 435 sb[17].StatID = (uint)Stats.PendingDownloads;
416 sb[17].StatValue = m_pendingDownloads; 436 sb[17].StatValue = m_pendingDownloads;
@@ -425,7 +445,10 @@ namespace OpenSim.Region.Framework.Scenes
425 sb[20].StatValue = m_scriptLinesPerSecond / m_statsUpdateFactor; 445 sb[20].StatValue = m_scriptLinesPerSecond / m_statsUpdateFactor;
426 446
427 sb[21].StatID = (uint)Stats.SimSpareMs; 447 sb[21].StatID = (uint)Stats.SimSpareMs;
428 sb[21].StatValue = m_spareMS / framesUpdated; 448 sb[21].StatValue = sparetime;
449
450 sb[22].StatID = (uint)Stats.SimSleepMs;
451 sb[22].StatValue = sleeptime;
429 452
430 for (int i = 0; i < 22; i++) 453 for (int i = 0; i < 22; i++)
431 { 454 {
@@ -444,28 +467,32 @@ namespace OpenSim.Region.Framework.Scenes
444 } 467 }
445 468
446 // Extra statistics that aren't currently sent to clients 469 // Extra statistics that aren't currently sent to clients
447 lock (m_lastReportedExtraSimStats) 470 if (m_scene.PhysicsScene != null)
448 { 471 {
449 m_lastReportedExtraSimStats[LastReportedObjectUpdateStatName] = m_objectUpdates / m_statsUpdateFactor; 472 lock (m_lastReportedExtraSimStats)
450 m_lastReportedExtraSimStats[SlowFramesStat.ShortName] = (float)SlowFramesStat.Value;
451
452 Dictionary<string, float> physicsStats = m_scene.PhysicsScene.GetStats();
453
454 if (physicsStats != null)
455 { 473 {
456 foreach (KeyValuePair<string, float> tuple in physicsStats) 474 m_lastReportedExtraSimStats[LastReportedObjectUpdateStatName] = m_objectUpdates / m_statsUpdateFactor;
475 m_lastReportedExtraSimStats[SlowFramesStat.ShortName] = (float)SlowFramesStat.Value;
476
477 Dictionary<string, float> physicsStats = m_scene.PhysicsScene.GetStats();
478
479 if (physicsStats != null)
457 { 480 {
458 // FIXME: An extremely dirty hack to divide MS stats per frame rather than per second 481 foreach (KeyValuePair<string, float> tuple in physicsStats)
459 // Need to change things so that stats source can indicate whether they are per second or 482 {
460 // per frame. 483 // FIXME: An extremely dirty hack to divide MS stats per frame rather than per second
461 if (tuple.Key.EndsWith("MS")) 484 // Need to change things so that stats source can indicate whether they are per second or
462 m_lastReportedExtraSimStats[tuple.Key] = tuple.Value / framesUpdated; 485 // per frame.
463 else 486 if (tuple.Key.EndsWith("MS"))
464 m_lastReportedExtraSimStats[tuple.Key] = tuple.Value / m_statsUpdateFactor; 487 m_lastReportedExtraSimStats[tuple.Key] = tuple.Value * perframe;
488 else
489 m_lastReportedExtraSimStats[tuple.Key] = tuple.Value / m_statsUpdateFactor;
490 }
465 } 491 }
466 } 492 }
467 } 493 }
468 494
495// LastReportedObjectUpdates = m_objectUpdates / m_statsUpdateFactor;
469 ResetValues(); 496 ResetValues();
470 } 497 }
471 } 498 }
@@ -488,7 +515,8 @@ namespace OpenSim.Region.Framework.Scenes
488 m_physicsMS = 0; 515 m_physicsMS = 0;
489 m_imageMS = 0; 516 m_imageMS = 0;
490 m_otherMS = 0; 517 m_otherMS = 0;
491 m_spareMS = 0; 518// m_spareMS = 0;
519 m_sleeptimeMS = 0;
492 520
493//Ckrinke This variable is not used, so comment to remove compiler warning until it is used. 521//Ckrinke This variable is not used, so comment to remove compiler warning until it is used.
494//Ckrinke m_scriptMS = 0; 522//Ckrinke m_scriptMS = 0;
@@ -572,11 +600,6 @@ namespace OpenSim.Region.Framework.Scenes
572 SlowFramesStat.Value++; 600 SlowFramesStat.Value++;
573 } 601 }
574 602
575 public void AddSpareMS(int ms)
576 {
577 m_spareMS += ms;
578 }
579
580 public void addNetMS(int ms) 603 public void addNetMS(int ms)
581 { 604 {
582 m_netMS += ms; 605 m_netMS += ms;
@@ -602,6 +625,11 @@ namespace OpenSim.Region.Framework.Scenes
602 m_otherMS += ms; 625 m_otherMS += ms;
603 } 626 }
604 627
628 public void addSleepMS(int ms)
629 {
630 m_sleeptimeMS += ms;
631 }
632
605 public void AddPendingDownloads(int count) 633 public void AddPendingDownloads(int count)
606 { 634 {
607 m_pendingDownloads += count; 635 m_pendingDownloads += count;
diff --git a/OpenSim/Region/Framework/Scenes/Tests/SceneObjectResizeTests.cs b/OpenSim/Region/Framework/Scenes/Tests/SceneObjectResizeTests.cs
index c264433..1182c96 100644
--- a/OpenSim/Region/Framework/Scenes/Tests/SceneObjectResizeTests.cs
+++ b/OpenSim/Region/Framework/Scenes/Tests/SceneObjectResizeTests.cs
@@ -62,6 +62,8 @@ namespace OpenSim.Region.Framework.Scenes.Tests
62 Assert.That(g1Post.RootPart.Scale.X, Is.EqualTo(2)); 62 Assert.That(g1Post.RootPart.Scale.X, Is.EqualTo(2));
63 Assert.That(g1Post.RootPart.Scale.Y, Is.EqualTo(3)); 63 Assert.That(g1Post.RootPart.Scale.Y, Is.EqualTo(3));
64 Assert.That(g1Post.RootPart.Scale.Z, Is.EqualTo(4)); 64 Assert.That(g1Post.RootPart.Scale.Z, Is.EqualTo(4));
65
66 Assert.That(g1Post.RootPart.UndoCount, Is.EqualTo(1));
65 } 67 }
66 68
67 /// <summary> 69 /// <summary>
diff --git a/OpenSim/Region/Framework/Scenes/Tests/SceneObjectUndoRedoTests.cs b/OpenSim/Region/Framework/Scenes/Tests/SceneObjectUndoRedoTests.cs
deleted file mode 100644
index 96973de..0000000
--- a/OpenSim/Region/Framework/Scenes/Tests/SceneObjectUndoRedoTests.cs
+++ /dev/null
@@ -1,184 +0,0 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Reflection;
30using NUnit.Framework;
31using OpenMetaverse;
32using OpenSim.Framework;
33using OpenSim.Framework.Communications;
34using OpenSim.Region.Framework.Scenes;
35using OpenSim.Tests.Common;
36using OpenSim.Tests.Common.Mock;
37
38namespace OpenSim.Region.Framework.Scenes.Tests
39{
40 /// <summary>
41 /// Tests for undo/redo
42 /// </summary>
43 public class SceneObjectUndoRedoTests : OpenSimTestCase
44 {
45 [Test]
46 public void TestUndoRedoResizeSceneObject()
47 {
48 TestHelpers.InMethod();
49// TestHelpers.EnableLogging();
50
51 Vector3 firstSize = new Vector3(2, 3, 4);
52 Vector3 secondSize = new Vector3(5, 6, 7);
53
54 Scene scene = new SceneHelpers().SetupScene();
55 scene.MaxUndoCount = 20;
56 SceneObjectGroup g1 = SceneHelpers.AddSceneObject(scene);
57
58 // TODO: It happens to be the case that we are not storing undo states for SOPs which are not yet in a SOG,
59 // which is the way that AddSceneObject() sets up the object (i.e. it creates the SOP first). However,
60 // this is somewhat by chance. Really, we shouldn't be storing undo states at all if the object is not
61 // in a scene.
62 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(0));
63
64 g1.GroupResize(firstSize);
65 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(1));
66
67 g1.GroupResize(secondSize);
68 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(2));
69
70 g1.RootPart.Undo();
71 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(1));
72 Assert.That(g1.GroupScale, Is.EqualTo(firstSize));
73
74 g1.RootPart.Redo();
75 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(2));
76 Assert.That(g1.GroupScale, Is.EqualTo(secondSize));
77 }
78
79 [Test]
80 public void TestUndoLimit()
81 {
82 TestHelpers.InMethod();
83
84 Vector3 firstSize = new Vector3(2, 3, 4);
85 Vector3 secondSize = new Vector3(5, 6, 7);
86 Vector3 thirdSize = new Vector3(8, 9, 10);
87 Vector3 fourthSize = new Vector3(11, 12, 13);
88
89 Scene scene = new SceneHelpers().SetupScene();
90 scene.MaxUndoCount = 2;
91 SceneObjectGroup g1 = SceneHelpers.AddSceneObject(scene);
92
93 g1.GroupResize(firstSize);
94 g1.GroupResize(secondSize);
95 g1.GroupResize(thirdSize);
96 g1.GroupResize(fourthSize);
97
98 g1.RootPart.Undo();
99 g1.RootPart.Undo();
100 g1.RootPart.Undo();
101
102 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(0));
103 Assert.That(g1.GroupScale, Is.EqualTo(secondSize));
104 }
105
106 [Test]
107 public void TestNoUndoOnObjectsNotInScene()
108 {
109 TestHelpers.InMethod();
110
111 Vector3 firstSize = new Vector3(2, 3, 4);
112 Vector3 secondSize = new Vector3(5, 6, 7);
113 Vector3 thirdSize = new Vector3(8, 9, 10);
114 Vector3 fourthSize = new Vector3(11, 12, 13);
115
116 Scene scene = new SceneHelpers().SetupScene();
117 scene.MaxUndoCount = 20;
118 SceneObjectGroup g1 = SceneHelpers.CreateSceneObject(1, TestHelpers.ParseTail(0x1));
119
120 g1.GroupResize(firstSize);
121 g1.GroupResize(secondSize);
122
123 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(0));
124
125 g1.RootPart.Undo();
126
127 Assert.That(g1.GroupScale, Is.EqualTo(secondSize));
128 }
129
130 [Test]
131 public void TestUndoBeyondAvailable()
132 {
133 TestHelpers.InMethod();
134
135 Vector3 newSize = new Vector3(2, 3, 4);
136
137 Scene scene = new SceneHelpers().SetupScene();
138 scene.MaxUndoCount = 20;
139 SceneObjectGroup g1 = SceneHelpers.AddSceneObject(scene);
140 Vector3 originalSize = g1.GroupScale;
141
142 g1.RootPart.Undo();
143
144 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(0));
145 Assert.That(g1.GroupScale, Is.EqualTo(originalSize));
146
147 g1.GroupResize(newSize);
148 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(1));
149 Assert.That(g1.GroupScale, Is.EqualTo(newSize));
150
151 g1.RootPart.Undo();
152 g1.RootPart.Undo();
153
154 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(0));
155 Assert.That(g1.GroupScale, Is.EqualTo(originalSize));
156 }
157
158 [Test]
159 public void TestRedoBeyondAvailable()
160 {
161 TestHelpers.InMethod();
162
163 Vector3 newSize = new Vector3(2, 3, 4);
164
165 Scene scene = new SceneHelpers().SetupScene();
166 scene.MaxUndoCount = 20;
167 SceneObjectGroup g1 = SceneHelpers.AddSceneObject(scene);
168 Vector3 originalSize = g1.GroupScale;
169
170 g1.RootPart.Redo();
171
172 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(0));
173 Assert.That(g1.GroupScale, Is.EqualTo(originalSize));
174
175 g1.GroupResize(newSize);
176 g1.RootPart.Undo();
177 g1.RootPart.Redo();
178 g1.RootPart.Redo();
179
180 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(1));
181 Assert.That(g1.GroupScale, Is.EqualTo(newSize));
182 }
183 }
184} \ No newline at end of file
diff --git a/OpenSim/Region/Framework/Scenes/Tests/SceneObjectUserGroupTests.cs b/OpenSim/Region/Framework/Scenes/Tests/SceneObjectUserGroupTests.cs
index 2b79271..c7eaff9 100644
--- a/OpenSim/Region/Framework/Scenes/Tests/SceneObjectUserGroupTests.cs
+++ b/OpenSim/Region/Framework/Scenes/Tests/SceneObjectUserGroupTests.cs
@@ -44,7 +44,7 @@ using OpenSim.Tests.Common.Mock;
44namespace OpenSim.Region.Framework.Scenes.Tests 44namespace OpenSim.Region.Framework.Scenes.Tests
45{ 45{
46 [TestFixture] 46 [TestFixture]
47 public class SceneObjectUserGroupTests : OpenSimTestCase 47 public class SceneObjectUserGroupTests
48 { 48 {
49 /// <summary> 49 /// <summary>
50 /// Test share with group object functionality 50 /// Test share with group object functionality
@@ -54,6 +54,7 @@ namespace OpenSim.Region.Framework.Scenes.Tests
54 public void TestShareWithGroup() 54 public void TestShareWithGroup()
55 { 55 {
56 TestHelpers.InMethod(); 56 TestHelpers.InMethod();
57// log4net.Config.XmlConfigurator.Configure();
57 58
58 UUID userId = UUID.Parse("10000000-0000-0000-0000-000000000001"); 59 UUID userId = UUID.Parse("10000000-0000-0000-0000-000000000001");
59 60
diff --git a/OpenSim/Region/Framework/Scenes/UndoState.cs b/OpenSim/Region/Framework/Scenes/UndoState.cs
index 860172c..7bbf1bd 100644
--- a/OpenSim/Region/Framework/Scenes/UndoState.cs
+++ b/OpenSim/Region/Framework/Scenes/UndoState.cs
@@ -27,202 +27,307 @@
27 27
28using System; 28using System;
29using System.Reflection; 29using System.Reflection;
30using System.Collections.Generic;
30using log4net; 31using log4net;
31using OpenMetaverse; 32using OpenMetaverse;
33using OpenSim.Framework;
32using OpenSim.Region.Framework.Interfaces; 34using OpenSim.Region.Framework.Interfaces;
33 35
34namespace OpenSim.Region.Framework.Scenes 36namespace OpenSim.Region.Framework.Scenes
35{ 37{
36 public class UndoState 38 public class UndoState
37 { 39 {
38// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); 40 const int UNDOEXPIRESECONDS = 300; // undo expire time (nice to have it came from a ini later)
39
40 public Vector3 Position = Vector3.Zero;
41 public Vector3 Scale = Vector3.Zero;
42 public Quaternion Rotation = Quaternion.Identity;
43
44 /// <summary>
45 /// Is this undo state for an entire group?
46 /// </summary>
47 public bool ForGroup;
48 41
42 public ObjectChangeData data;
43 public DateTime creationtime;
49 /// <summary> 44 /// <summary>
50 /// Constructor. 45 /// Constructor.
51 /// </summary> 46 /// </summary>
52 /// <param name="part"></param> 47 /// <param name="part"></param>
53 /// <param name="forGroup">True if the undo is for an entire group</param> 48 /// <param name="change">bit field with what is changed</param>
54 public UndoState(SceneObjectPart part, bool forGroup) 49 ///
50 public UndoState(SceneObjectPart part, ObjectChangeType change)
55 { 51 {
56 if (part.ParentID == 0) 52 data = new ObjectChangeData();
57 { 53 data.change = change;
58 ForGroup = forGroup; 54 creationtime = DateTime.UtcNow;
59
60// if (ForGroup)
61 Position = part.ParentGroup.AbsolutePosition;
62// else
63// Position = part.OffsetPosition;
64
65// m_log.DebugFormat(
66// "[UNDO STATE]: Storing undo position {0} for root part", Position);
67 55
68 Rotation = part.RotationOffset; 56 if (part.ParentGroup.RootPart == part)
69 57 {
70// m_log.DebugFormat( 58 if ((change & ObjectChangeType.Position) != 0)
71// "[UNDO STATE]: Storing undo rotation {0} for root part", Rotation); 59 data.position = part.ParentGroup.AbsolutePosition;
72 60 if ((change & ObjectChangeType.Rotation) != 0)
73 Scale = part.Shape.Scale; 61 data.rotation = part.RotationOffset;
74 62 if ((change & ObjectChangeType.Scale) != 0)
75// m_log.DebugFormat( 63 data.scale = part.Shape.Scale;
76// "[UNDO STATE]: Storing undo scale {0} for root part", Scale);
77 } 64 }
78 else 65 else
79 { 66 {
80 Position = part.OffsetPosition; 67 if ((change & ObjectChangeType.Position) != 0)
81// m_log.DebugFormat( 68 data.position = part.OffsetPosition;
82// "[UNDO STATE]: Storing undo position {0} for child part", Position); 69 if ((change & ObjectChangeType.Rotation) != 0)
70 data.rotation = part.RotationOffset;
71 if ((change & ObjectChangeType.Scale) != 0)
72 data.scale = part.Shape.Scale;
73 }
74 }
75 /// <summary>
76 /// check if undo or redo is too old
77 /// </summary>
83 78
84 Rotation = part.RotationOffset; 79 public bool checkExpire()
85// m_log.DebugFormat( 80 {
86// "[UNDO STATE]: Storing undo rotation {0} for child part", Rotation); 81 TimeSpan t = DateTime.UtcNow - creationtime;
82 if (t.Seconds > UNDOEXPIRESECONDS)
83 return true;
84 return false;
85 }
87 86
88 Scale = part.Shape.Scale; 87 /// <summary>
89// m_log.DebugFormat( 88 /// updates undo or redo creation time to now
90// "[UNDO STATE]: Storing undo scale {0} for child part", Scale); 89 /// </summary>
91 } 90 public void updateExpire()
91 {
92 creationtime = DateTime.UtcNow;
92 } 93 }
93 94
94 /// <summary> 95 /// <summary>
95 /// Compare the relevant state in the given part to this state. 96 /// Compare the relevant state in the given part to this state.
96 /// </summary> 97 /// </summary>
97 /// <param name="part"></param> 98 /// <param name="part"></param>
98 /// <returns>true if both the part's position, rotation and scale match those in this undo state. False otherwise.</returns> 99 /// <returns>true what fiels and related data are equal, False otherwise.</returns>
99 public bool Compare(SceneObjectPart part) 100 ///
101 public bool Compare(SceneObjectPart part, ObjectChangeType change)
100 { 102 {
103 if (data.change != change) // if diferent targets, then they are diferent
104 return false;
105
101 if (part != null) 106 if (part != null)
102 { 107 {
103 if (part.ParentID == 0) 108 if (part.ParentID == 0)
104 return 109 {
105 Position == part.ParentGroup.AbsolutePosition 110 if ((change & ObjectChangeType.Position) != 0 && data.position != part.ParentGroup.AbsolutePosition)
106 && Rotation == part.RotationOffset 111 return false;
107 && Scale == part.Shape.Scale; 112 }
108 else 113 else
109 return 114 {
110 Position == part.OffsetPosition 115 if ((change & ObjectChangeType.Position) != 0 && data.position != part.OffsetPosition)
111 && Rotation == part.RotationOffset 116 return false;
112 && Scale == part.Shape.Scale; 117 }
113 } 118
119 if ((change & ObjectChangeType.Rotation) != 0 && data.rotation != part.RotationOffset)
120 return false;
121 if ((change & ObjectChangeType.Rotation) != 0 && data.scale == part.Shape.Scale)
122 return false;
123 return true;
114 124
125 }
115 return false; 126 return false;
116 } 127 }
117 128
118 public void PlaybackState(SceneObjectPart part) 129 /// <summary>
130 /// executes the undo or redo to a part or its group
131 /// </summary>
132 /// <param name="part"></param>
133 ///
134
135 public void PlayState(SceneObjectPart part)
119 { 136 {
120 part.Undoing = true; 137 part.Undoing = true;
121 138
122 if (part.ParentID == 0) 139 SceneObjectGroup grp = part.ParentGroup;
123 {
124// m_log.DebugFormat(
125// "[UNDO STATE]: Undoing position to {0} for root part {1} {2}",
126// Position, part.Name, part.LocalId);
127 140
128 if (Position != Vector3.Zero) 141 if (grp != null)
129 { 142 {
130 if (ForGroup) 143 grp.doChangeObject(part, data);
131 part.ParentGroup.AbsolutePosition = Position; 144 }
132 else 145 part.Undoing = false;
133 part.ParentGroup.UpdateRootPosition(Position); 146 }
134 } 147 }
135 148
136// m_log.DebugFormat( 149 public class UndoRedoState
137// "[UNDO STATE]: Undoing rotation {0} to {1} for root part {2} {3}", 150 {
138// part.RotationOffset, Rotation, part.Name, part.LocalId); 151 int size;
152 public LinkedList<UndoState> m_redo = new LinkedList<UndoState>();
153 public LinkedList<UndoState> m_undo = new LinkedList<UndoState>();
139 154
140 if (ForGroup) 155 /// <summary>
141 part.UpdateRotation(Rotation); 156 /// creates a new UndoRedoState with default states memory size
142 else 157 /// </summary>
143 part.ParentGroup.UpdateRootRotation(Rotation);
144 158
145 if (Scale != Vector3.Zero) 159 public UndoRedoState()
146 { 160 {
147// m_log.DebugFormat( 161 size = 5;
148// "[UNDO STATE]: Undoing scale {0} to {1} for root part {2} {3}", 162 }
149// part.Shape.Scale, Scale, part.Name, part.LocalId);
150 163
151 if (ForGroup) 164 /// <summary>
152 part.ParentGroup.GroupResize(Scale); 165 /// creates a new UndoRedoState with states memory having indicated size
153 else 166 /// </summary>
154 part.Resize(Scale); 167 /// <param name="size"></param>
155 }
156 168
157 part.ParentGroup.ScheduleGroupForTerseUpdate(); 169 public UndoRedoState(int _size)
158 } 170 {
171 if (_size < 3)
172 size = 3;
159 else 173 else
160 { 174 size = _size;
161 // Note: Updating these properties on sop automatically schedules an update if needed 175 }
162 if (Position != Vector3.Zero)
163 {
164// m_log.DebugFormat(
165// "[UNDO STATE]: Undoing position {0} to {1} for child part {2} {3}",
166// part.OffsetPosition, Position, part.Name, part.LocalId);
167 176
168 part.OffsetPosition = Position; 177 /// <summary>
169 } 178 /// returns number of undo entries in memory
179 /// </summary>
170 180
171// m_log.DebugFormat( 181 public int Count
172// "[UNDO STATE]: Undoing rotation {0} to {1} for child part {2} {3}", 182 {
173// part.RotationOffset, Rotation, part.Name, part.LocalId); 183 get { return m_undo.Count; }
184 }
174 185
175 part.UpdateRotation(Rotation); 186 /// <summary>
187 /// clears all undo and redo entries
188 /// </summary>
176 189
177 if (Scale != Vector3.Zero) 190 public void Clear()
191 {
192 m_undo.Clear();
193 m_redo.Clear();
194 }
195
196 /// <summary>
197 /// adds a new state undo to part or its group, with changes indicated by what bits
198 /// </summary>
199 /// <param name="part"></param>
200 /// <param name="change">bit field with what is changed</param>
201
202 public void StoreUndo(SceneObjectPart part, ObjectChangeType change)
203 {
204 lock (m_undo)
205 {
206 UndoState last;
207
208 if (m_redo.Count > 0) // last code seems to clear redo on every new undo
178 { 209 {
179// m_log.DebugFormat( 210 m_redo.Clear();
180// "[UNDO STATE]: Undoing scale {0} to {1} for child part {2} {3}", 211 }
181// part.Shape.Scale, Scale, part.Name, part.LocalId);
182 212
183 part.Resize(Scale); 213 if (m_undo.Count > 0)
214 {
215 // check expired entry
216 last = m_undo.First.Value;
217 if (last != null && last.checkExpire())
218 m_undo.Clear();
219 else
220 {
221 // see if we actually have a change
222 if (last != null)
223 {
224 if (last.Compare(part, change))
225 return;
226 }
227 }
184 } 228 }
185 }
186 229
187 part.Undoing = false; 230 // limite size
231 while (m_undo.Count >= size)
232 m_undo.RemoveLast();
233
234 UndoState nUndo = new UndoState(part, change);
235 m_undo.AddFirst(nUndo);
236 }
188 } 237 }
189 238
190 public void PlayfwdState(SceneObjectPart part) 239 /// <summary>
191 { 240 /// executes last state undo to part or its group
192 part.Undoing = true; 241 /// current state is pushed into redo
242 /// </summary>
243 /// <param name="part"></param>
193 244
194 if (part.ParentID == 0) 245 public void Undo(SceneObjectPart part)
246 {
247 lock (m_undo)
195 { 248 {
196 if (Position != Vector3.Zero) 249 UndoState nUndo;
197 part.ParentGroup.AbsolutePosition = Position;
198
199 if (Rotation != Quaternion.Identity)
200 part.UpdateRotation(Rotation);
201 250
202 if (Scale != Vector3.Zero) 251 // expire redo
252 if (m_redo.Count > 0)
203 { 253 {
204 if (ForGroup) 254 nUndo = m_redo.First.Value;
205 part.ParentGroup.GroupResize(Scale); 255 if (nUndo != null && nUndo.checkExpire())
206 else 256 m_redo.Clear();
207 part.Resize(Scale);
208 } 257 }
209 258
210 part.ParentGroup.ScheduleGroupForTerseUpdate(); 259 if (m_undo.Count > 0)
260 {
261 UndoState goback = m_undo.First.Value;
262 // check expired
263 if (goback != null && goback.checkExpire())
264 {
265 m_undo.Clear();
266 return;
267 }
268
269 if (goback != null)
270 {
271 m_undo.RemoveFirst();
272
273 // redo limite size
274 while (m_redo.Count >= size)
275 m_redo.RemoveLast();
276
277 nUndo = new UndoState(part, goback.data.change); // new value in part should it be full goback copy?
278 m_redo.AddFirst(nUndo);
279
280 goback.PlayState(part);
281 }
282 }
211 } 283 }
212 else 284 }
285
286 /// <summary>
287 /// executes last state redo to part or its group
288 /// current state is pushed into undo
289 /// </summary>
290 /// <param name="part"></param>
291
292 public void Redo(SceneObjectPart part)
293 {
294 lock (m_undo)
213 { 295 {
214 // Note: Updating these properties on sop automatically schedules an update if needed 296 UndoState nUndo;
215 if (Position != Vector3.Zero)
216 part.OffsetPosition = Position;
217 297
218 if (Rotation != Quaternion.Identity) 298 // expire undo
219 part.UpdateRotation(Rotation); 299 if (m_undo.Count > 0)
300 {
301 nUndo = m_undo.First.Value;
302 if (nUndo != null && nUndo.checkExpire())
303 m_undo.Clear();
304 }
220 305
221 if (Scale != Vector3.Zero) 306 if (m_redo.Count > 0)
222 part.Resize(Scale); 307 {
308 UndoState gofwd = m_redo.First.Value;
309 // check expired
310 if (gofwd != null && gofwd.checkExpire())
311 {
312 m_redo.Clear();
313 return;
314 }
315
316 if (gofwd != null)
317 {
318 m_redo.RemoveFirst();
319
320 // limite undo size
321 while (m_undo.Count >= size)
322 m_undo.RemoveLast();
323
324 nUndo = new UndoState(part, gofwd.data.change); // new value in part should it be full gofwd copy?
325 m_undo.AddFirst(nUndo);
326
327 gofwd.PlayState(part);
328 }
329 }
223 } 330 }
224
225 part.Undoing = false;
226 } 331 }
227 } 332 }
228 333
@@ -247,4 +352,4 @@ namespace OpenSim.Region.Framework.Scenes
247 m_terrainModule.UndoTerrain(m_terrainChannel); 352 m_terrainModule.UndoTerrain(m_terrainChannel);
248 } 353 }
249 } 354 }
250} \ No newline at end of file 355}
diff --git a/OpenSim/Region/Framework/Scenes/UuidGatherer.cs b/OpenSim/Region/Framework/Scenes/UuidGatherer.cs
index e238d01..2279e62 100644
--- a/OpenSim/Region/Framework/Scenes/UuidGatherer.cs
+++ b/OpenSim/Region/Framework/Scenes/UuidGatherer.cs
@@ -84,10 +84,6 @@ namespace OpenSim.Region.Framework.Scenes
84 /// <param name="assetUuids">The assets gathered</param> 84 /// <param name="assetUuids">The assets gathered</param>
85 public void GatherAssetUuids(UUID assetUuid, AssetType assetType, IDictionary<UUID, AssetType> assetUuids) 85 public void GatherAssetUuids(UUID assetUuid, AssetType assetType, IDictionary<UUID, AssetType> assetUuids)
86 { 86 {
87 // avoid infinite loops
88 if (assetUuids.ContainsKey(assetUuid))
89 return;
90
91 try 87 try
92 { 88 {
93 assetUuids[assetUuid] = assetType; 89 assetUuids[assetUuid] = assetType;