aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Region/Framework/Scenes
diff options
context:
space:
mode:
Diffstat (limited to 'OpenSim/Region/Framework/Scenes')
-rw-r--r--OpenSim/Region/Framework/Scenes/Animation/ScenePresenceAnimator.cs20
-rw-r--r--OpenSim/Region/Framework/Scenes/CollisionSounds.cs304
-rw-r--r--OpenSim/Region/Framework/Scenes/EventManager.cs25
-rw-r--r--OpenSim/Region/Framework/Scenes/KeyframeMotion.cs694
-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.cs325
-rw-r--r--OpenSim/Region/Framework/Scenes/Scene.PacketHandlers.cs155
-rw-r--r--OpenSim/Region/Framework/Scenes/Scene.cs836
-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.cs477
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneManager.cs267
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneObjectGroup.Inventory.cs17
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs1362
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneObjectPart.cs1716
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs782
-rw-r--r--OpenSim/Region/Framework/Scenes/ScenePresence.cs599
-rw-r--r--OpenSim/Region/Framework/Scenes/Serialization/SceneObjectSerializer.cs135
-rw-r--r--OpenSim/Region/Framework/Scenes/SimStatsReporter.cs122
-rw-r--r--OpenSim/Region/Framework/Scenes/Tests/SceneObjectUndoRedoTests.cs157
-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
25 files changed, 7149 insertions, 2155 deletions
diff --git a/OpenSim/Region/Framework/Scenes/Animation/ScenePresenceAnimator.cs b/OpenSim/Region/Framework/Scenes/Animation/ScenePresenceAnimator.cs
index ff53f45..50a176b 100644
--- a/OpenSim/Region/Framework/Scenes/Animation/ScenePresenceAnimator.cs
+++ b/OpenSim/Region/Framework/Scenes/Animation/ScenePresenceAnimator.cs
@@ -79,13 +79,13 @@ namespace OpenSim.Region.Framework.Scenes.Animation
79 m_scenePresence = sp; 79 m_scenePresence = sp;
80 CurrentMovementAnimation = "CROUCH"; 80 CurrentMovementAnimation = "CROUCH";
81 } 81 }
82 82
83 public void AddAnimation(UUID animID, UUID objectID) 83 public void AddAnimation(UUID animID, UUID objectID)
84 { 84 {
85 if (m_scenePresence.IsChildAgent) 85 if (m_scenePresence.IsChildAgent)
86 return; 86 return;
87 87
88// m_log.DebugFormat("[SCENE PRESENCE ANIMATOR]: Adding animation {0} for {1}", animID, m_scenePresence.Name); 88 // m_log.DebugFormat("[SCENE PRESENCE ANIMATOR]: Adding animation {0} for {1}", animID, m_scenePresence.Name);
89 89
90 if (m_animations.Add(animID, m_scenePresence.ControllingClient.NextAnimationSequenceNumber, objectID)) 90 if (m_animations.Add(animID, m_scenePresence.ControllingClient.NextAnimationSequenceNumber, objectID))
91 SendAnimPack(); 91 SendAnimPack();
@@ -117,6 +117,22 @@ namespace OpenSim.Region.Framework.Scenes.Animation
117 SendAnimPack(); 117 SendAnimPack();
118 } 118 }
119 119
120 public void avnChangeAnim(UUID animID, bool addRemove, bool sendPack)
121 {
122 if (m_scenePresence.IsChildAgent)
123 return;
124
125 if (animID != UUID.Zero)
126 {
127 if (addRemove)
128 m_animations.Add(animID, m_scenePresence.ControllingClient.NextAnimationSequenceNumber, UUID.Zero);
129 else
130 m_animations.Remove(animID);
131 }
132 if(sendPack)
133 SendAnimPack();
134 }
135
120 // Called from scripts 136 // Called from scripts
121 public void RemoveAnimation(string name) 137 public void RemoveAnimation(string name)
122 { 138 {
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 e25fa94..7133817 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>
@@ -1379,6 +1383,26 @@ namespace OpenSim.Region.Framework.Scenes
1379 } 1383 }
1380 } 1384 }
1381 } 1385 }
1386 public void TriggerTerrainUpdate()
1387 {
1388 OnTerrainUpdateDelegate handlerTerrainUpdate = OnTerrainUpdate;
1389 if (handlerTerrainUpdate != null)
1390 {
1391 foreach (OnTerrainUpdateDelegate d in handlerTerrainUpdate.GetInvocationList())
1392 {
1393 try
1394 {
1395 d();
1396 }
1397 catch (Exception e)
1398 {
1399 m_log.ErrorFormat(
1400 "[EVENT MANAGER]: Delegate for TriggerTerrainUpdate failed - continuing. {0} {1}",
1401 e.Message, e.StackTrace);
1402 }
1403 }
1404 }
1405 }
1382 1406
1383 public void TriggerTerrainTick() 1407 public void TriggerTerrainTick()
1384 { 1408 {
@@ -1669,6 +1693,7 @@ namespace OpenSim.Region.Framework.Scenes
1669 m_log.ErrorFormat( 1693 m_log.ErrorFormat(
1670 "[EVENT MANAGER]: Delegate for TriggerRemoveScript failed - continuing. {0} {1}", 1694 "[EVENT MANAGER]: Delegate for TriggerRemoveScript failed - continuing. {0} {1}",
1671 e.Message, e.StackTrace); 1695 e.Message, e.StackTrace);
1696 m_log.ErrorFormat(Environment.StackTrace);
1672 } 1697 }
1673 } 1698 }
1674 } 1699 }
diff --git a/OpenSim/Region/Framework/Scenes/KeyframeMotion.cs b/OpenSim/Region/Framework/Scenes/KeyframeMotion.cs
new file mode 100644
index 0000000..233e559
--- /dev/null
+++ b/OpenSim/Region/Framework/Scenes/KeyframeMotion.cs
@@ -0,0 +1,694 @@
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.UpdateAngularVelocity(Vector3.Zero);
349 m_group.SendGroupRootTerseUpdate();
350
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.UpdateAngularVelocity(Vector3.Zero);
361 m_group.SendGroupRootTerseUpdate();
362 }
363
364 private void GetNextList()
365 {
366 m_frames.Clear();
367 Vector3 pos = m_basePosition;
368 Quaternion rot = m_baseRotation;
369
370 if (m_mode == PlayMode.Loop || m_mode == PlayMode.PingPong || m_iterations == 0)
371 {
372 int direction = 1;
373 if (m_mode == PlayMode.Reverse || ((m_mode == PlayMode.PingPong) && ((m_iterations & 1) != 0)))
374 direction = -1;
375
376 int start = 0;
377 int end = m_keyframes.Length;
378// if (m_mode == PlayMode.PingPong && m_keyframes.Length > 1)
379// end = m_keyframes.Length - 1;
380
381 if (direction < 0)
382 {
383 start = m_keyframes.Length - 1;
384 end = -1;
385// if (m_mode == PlayMode.PingPong && m_keyframes.Length > 1)
386// end = 0;
387 }
388
389 for (int i = start; i != end ; i += direction)
390 {
391 Keyframe k = m_keyframes[i];
392
393 if (k.Position.HasValue)
394 {
395 k.Position = (k.Position * direction);
396// k.Velocity = (Vector3)k.Position / (k.TimeMS / 1000.0f);
397 k.Position += pos;
398 }
399 else
400 {
401 k.Position = pos;
402// k.Velocity = Vector3.Zero;
403 }
404
405 k.StartRotation = rot;
406 if (k.Rotation.HasValue)
407 {
408 if (direction == -1)
409 k.Rotation = Quaternion.Conjugate((Quaternion)k.Rotation);
410 k.Rotation = rot * k.Rotation;
411 }
412 else
413 {
414 k.Rotation = rot;
415 }
416
417/* ang vel not in use for now
418
419 float angle = 0;
420
421 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;
422 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;
423 float aa_bb = aa * bb;
424
425 if (aa_bb == 0)
426 {
427 angle = 0;
428 }
429 else
430 {
431 float ab = k.StartRotation.X * ((Quaternion)k.Rotation).X +
432 k.StartRotation.Y * ((Quaternion)k.Rotation).Y +
433 k.StartRotation.Z * ((Quaternion)k.Rotation).Z +
434 k.StartRotation.W * ((Quaternion)k.Rotation).W;
435 float q = (ab * ab) / aa_bb;
436
437 if (q > 1.0f)
438 {
439 angle = 0;
440 }
441 else
442 {
443 angle = (float)Math.Acos(2 * q - 1);
444 }
445 }
446
447 k.AngularVelocity = (new Vector3(0, 0, 1) * (Quaternion)k.Rotation) * (angle / (k.TimeMS / 1000));
448 */
449 k.TimeTotal = k.TimeMS;
450
451 m_frames.Add(k);
452
453 pos = (Vector3)k.Position;
454 rot = (Quaternion)k.Rotation;
455 }
456
457 m_basePosition = pos;
458 m_baseRotation = rot;
459
460 m_iterations++;
461 }
462 }
463
464 protected void OnTimer(object sender, ElapsedEventArgs e)
465 {
466 if (m_timerStopped) // trap events still in air even after a timer.stop
467 return;
468
469 if (m_inOnTimer) // don't let overruns to happen
470 {
471 m_log.Warn("[KeyFrame]: timer overrun");
472 return;
473 }
474
475 if (m_group == null)
476 return;
477
478 lock (m_onTimerLock)
479 {
480
481 m_inOnTimer = true;
482
483 bool update = false;
484
485 try
486 {
487 if (m_selected)
488 {
489 if (m_group.RootPart.Velocity != Vector3.Zero)
490 {
491 m_group.RootPart.Velocity = Vector3.Zero;
492 m_group.SendGroupRootTerseUpdate();
493 }
494 m_inOnTimer = false;
495 return;
496 }
497
498 if (m_isCrossing)
499 {
500 // if crossing and timer running then cross failed
501 // wait some time then
502 // retry to set the position that evtually caused the outbound
503 // if still outside region this will call startCrossing below
504 m_isCrossing = false;
505 m_group.AbsolutePosition = m_nextPosition;
506 if (!m_isCrossing)
507 {
508 StopTimer();
509 m_timer.Interval = timerInterval;
510 StartTimer();
511 }
512 m_inOnTimer = false;
513 return;
514 }
515
516 if (m_frames.Count == 0)
517 {
518 GetNextList();
519
520 if (m_frames.Count == 0)
521 {
522 Stop();
523 m_inOnTimer = false;
524 return;
525 }
526
527 m_currentFrame = m_frames[0];
528 m_currentFrame.TimeMS += (int)timerInterval;
529
530 //force a update on a keyframe transition
531 update = true;
532 }
533
534 m_currentFrame.TimeMS -= (int)timerInterval;
535
536 // Do the frame processing
537 double steps = (double)m_currentFrame.TimeMS / timerInterval;
538
539 if (steps <= 0.0)
540 {
541 m_group.RootPart.Velocity = Vector3.Zero;
542 m_group.RootPart.UpdateAngularVelocity(Vector3.Zero);
543
544 m_nextPosition = (Vector3)m_currentFrame.Position;
545 m_group.AbsolutePosition = m_nextPosition;
546
547 m_group.UpdateGroupRotationR((Quaternion)m_currentFrame.Rotation);
548
549 m_frames.RemoveAt(0);
550 if (m_frames.Count > 0)
551 m_currentFrame = m_frames[0];
552
553 update = true;
554 }
555 else
556 {
557 float complete = ((float)m_currentFrame.TimeTotal - (float)m_currentFrame.TimeMS) / (float)m_currentFrame.TimeTotal;
558
559 Vector3 v = (Vector3)m_currentFrame.Position - m_group.AbsolutePosition;
560 Vector3 motionThisFrame = v / (float)steps;
561 v = v * 1000 / m_currentFrame.TimeMS;
562
563 if (Vector3.Mag(motionThisFrame) >= 0.05f)
564 {
565 // m_group.AbsolutePosition += motionThisFrame;
566 m_nextPosition = m_group.AbsolutePosition + motionThisFrame;
567 m_group.AbsolutePosition = m_nextPosition;
568
569 m_group.RootPart.Velocity = v;
570 update = true;
571 }
572
573 if ((Quaternion)m_currentFrame.Rotation != m_group.GroupRotation)
574 {
575 Quaternion current = m_group.GroupRotation;
576
577 Quaternion step = Quaternion.Slerp(m_currentFrame.StartRotation, (Quaternion)m_currentFrame.Rotation, complete);
578/* use simpler change detection
579 * float angle = 0;
580
581 float aa = current.X * current.X + current.Y * current.Y + current.Z * current.Z + current.W * current.W;
582 float bb = step.X * step.X + step.Y * step.Y + step.Z * step.Z + step.W * step.W;
583 float aa_bb = aa * bb;
584
585 if (aa_bb == 0)
586 {
587 angle = 0;
588 }
589 else
590 {
591 float ab = current.X * step.X +
592 current.Y * step.Y +
593 current.Z * step.Z +
594 current.W * step.W;
595 float q = (ab * ab) / aa_bb;
596
597 if (q > 1.0f)
598 {
599 angle = 0;
600 }
601 else
602 {
603 angle = (float)Math.Acos(2 * q - 1);
604 }
605 }
606
607 if (angle > 0.01f)
608 */
609 if(Math.Abs(step.X - current.X) > 0.001f
610 || Math.Abs(step.Y - current.Y) > 0.001f
611 || Math.Abs(step.Z - current.Z) > 0.001f)
612 // assuming w is a dependente var
613
614 {
615 m_group.UpdateGroupRotationR(step);
616 //m_group.RootPart.UpdateAngularVelocity(m_currentFrame.AngularVelocity / 2);
617 update = true;
618 }
619 }
620 }
621
622 if (update)
623 m_group.SendGroupRootTerseUpdate();
624
625 }
626 catch ( Exception ex)
627 {
628 // still happening sometimes
629 // lets try to see where
630 m_log.Warn("[KeyFrame]: timer overrun" + ex.Message);
631 }
632
633 finally
634 {
635 // make sure we do not let this frozen
636 m_inOnTimer = false;
637 }
638 }
639 }
640
641 public Byte[] Serialize()
642 {
643 StopTimer();
644 MemoryStream ms = new MemoryStream();
645
646 BinaryFormatter fmt = new BinaryFormatter();
647 SceneObjectGroup tmp = m_group;
648 m_group = null;
649 if (!m_selected && tmp != null)
650 m_serializedPosition = tmp.AbsolutePosition;
651 fmt.Serialize(ms, this);
652 m_group = tmp;
653 if (m_running && !m_waitingCrossing)
654 StartTimer();
655
656 return ms.ToArray();
657 }
658
659 public void StartCrossingCheck()
660 {
661 // timer will be restart by crossingFailure
662 // or never since crossing worked and this
663 // should be deleted
664 StopTimer();
665
666 m_isCrossing = true;
667 m_waitingCrossing = true;
668
669// to remove / retune to smoth crossings
670 if (m_group.RootPart.Velocity != Vector3.Zero)
671 {
672 m_group.RootPart.Velocity = Vector3.Zero;
673 m_group.SendGroupRootTerseUpdate();
674 }
675 }
676
677 public void CrossingFailure()
678 {
679 m_waitingCrossing = false;
680
681 if (m_group != null)
682 {
683 m_group.RootPart.Velocity = Vector3.Zero;
684 m_group.SendGroupRootTerseUpdate();
685
686 if (m_running && m_timer != null)
687 {
688 m_timer.Interval = 60000;
689 StartTimer();
690 }
691 }
692 }
693 }
694}
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 3b59dc4..3d68081 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, 0);
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
@@ -795,6 +790,8 @@ namespace OpenSim.Region.Framework.Scenes
795 return; 790 return;
796 } 791 }
797 792
793 if (newName == null) newName = item.Name;
794
798 AssetBase asset = AssetService.Get(item.AssetID.ToString()); 795 AssetBase asset = AssetService.Get(item.AssetID.ToString());
799 796
800 if (asset != null) 797 if (asset != null)
@@ -855,6 +852,24 @@ namespace OpenSim.Region.Framework.Scenes
855 } 852 }
856 853
857 /// <summary> 854 /// <summary>
855 /// Move an item within the agent's inventory, and leave a copy (used in making a new outfit)
856 /// </summary>
857 public void MoveInventoryItemsLeaveCopy(IClientAPI remoteClient, List<InventoryItemBase> items, UUID destfolder)
858 {
859 List<InventoryItemBase> moveitems = new List<InventoryItemBase>();
860 foreach (InventoryItemBase b in items)
861 {
862 CopyInventoryItem(remoteClient, 0, remoteClient.AgentId, b.ID, b.Folder, null);
863 InventoryItemBase n = InventoryService.GetItem(b);
864 n.Folder = destfolder;
865 moveitems.Add(n);
866 remoteClient.SendInventoryItemCreateUpdate(n, 0);
867 }
868
869 MoveInventoryItem(remoteClient, moveitems);
870 }
871
872 /// <summary>
858 /// Move an item within the agent's inventory. 873 /// Move an item within the agent's inventory.
859 /// </summary> 874 /// </summary>
860 /// <param name="remoteClient"></param> 875 /// <param name="remoteClient"></param>
@@ -1216,6 +1231,10 @@ namespace OpenSim.Region.Framework.Scenes
1216 { 1231 {
1217 SceneObjectPart part = GetSceneObjectPart(primLocalId); 1232 SceneObjectPart part = GetSceneObjectPart(primLocalId);
1218 1233
1234 // Can't move a null item
1235 if (itemId == UUID.Zero)
1236 return;
1237
1219 if (null == part) 1238 if (null == part)
1220 { 1239 {
1221 m_log.WarnFormat( 1240 m_log.WarnFormat(
@@ -1320,21 +1339,28 @@ namespace OpenSim.Region.Framework.Scenes
1320 return; 1339 return;
1321 } 1340 }
1322 1341
1323 if (part.OwnerID != destPart.OwnerID) 1342 // Can't transfer this
1343 //
1344 if (part.OwnerID != destPart.OwnerID && (srcTaskItem.CurrentPermissions & (uint)PermissionMask.Transfer) == 0)
1345 return;
1346
1347 bool overrideNoMod = false;
1348 if ((part.GetEffectiveObjectFlags() & (uint)PrimFlags.AllowInventoryDrop) != 0)
1349 overrideNoMod = true;
1350
1351 if (part.OwnerID != destPart.OwnerID && (destPart.GetEffectiveObjectFlags() & (uint)PrimFlags.AllowInventoryDrop) == 0)
1324 { 1352 {
1325 // Source must have transfer permissions 1353 // object cannot copy items to an object owned by a different owner
1326 if ((srcTaskItem.CurrentPermissions & (uint)PermissionMask.Transfer) == 0) 1354 // unless llAllowInventoryDrop has been called
1327 return;
1328 1355
1329 // Object cannot copy items to an object owned by a different owner 1356 return;
1330 // unless llAllowInventoryDrop has been called on the destination
1331 if ((destPart.GetEffectiveObjectFlags() & (uint)PrimFlags.AllowInventoryDrop) == 0)
1332 return;
1333 } 1357 }
1334 1358
1335 // must have both move and modify permission to put an item in an object 1359 // must have both move and modify permission to put an item in an object
1336 if ((part.OwnerMask & ((uint)PermissionMask.Move | (uint)PermissionMask.Modify)) == 0) 1360 if (((part.OwnerMask & (uint)PermissionMask.Modify) == 0) && (!overrideNoMod))
1361 {
1337 return; 1362 return;
1363 }
1338 1364
1339 TaskInventoryItem destTaskItem = new TaskInventoryItem(); 1365 TaskInventoryItem destTaskItem = new TaskInventoryItem();
1340 1366
@@ -1390,6 +1416,14 @@ namespace OpenSim.Region.Framework.Scenes
1390 1416
1391 public UUID MoveTaskInventoryItems(UUID destID, string category, SceneObjectPart host, List<UUID> items) 1417 public UUID MoveTaskInventoryItems(UUID destID, string category, SceneObjectPart host, List<UUID> items)
1392 { 1418 {
1419 SceneObjectPart destPart = GetSceneObjectPart(destID);
1420 if (destPart != null) // Move into a prim
1421 {
1422 foreach(UUID itemID in items)
1423 MoveTaskInventoryItem(destID, host, itemID);
1424 return destID; // Prim folder ID == prim ID
1425 }
1426
1393 InventoryFolderBase rootFolder = InventoryService.GetRootFolder(destID); 1427 InventoryFolderBase rootFolder = InventoryService.GetRootFolder(destID);
1394 1428
1395 UUID newFolderID = UUID.Random(); 1429 UUID newFolderID = UUID.Random();
@@ -1572,12 +1606,12 @@ namespace OpenSim.Region.Framework.Scenes
1572 AgentTransactionsModule.HandleTaskItemUpdateFromTransaction( 1606 AgentTransactionsModule.HandleTaskItemUpdateFromTransaction(
1573 remoteClient, part, transactionID, currentItem); 1607 remoteClient, part, transactionID, currentItem);
1574 1608
1575 if ((InventoryType)itemInfo.InvType == InventoryType.Notecard) 1609// if ((InventoryType)itemInfo.InvType == InventoryType.Notecard)
1576 remoteClient.SendAgentAlertMessage("Notecard saved", false); 1610// remoteClient.SendAgentAlertMessage("Notecard saved", false);
1577 else if ((InventoryType)itemInfo.InvType == InventoryType.LSL) 1611// else if ((InventoryType)itemInfo.InvType == InventoryType.LSL)
1578 remoteClient.SendAgentAlertMessage("Script saved", false); 1612// remoteClient.SendAgentAlertMessage("Script saved", false);
1579 else 1613// else
1580 remoteClient.SendAgentAlertMessage("Item saved", false); 1614// remoteClient.SendAgentAlertMessage("Item saved", false);
1581 } 1615 }
1582 1616
1583 // Base ALWAYS has move 1617 // Base ALWAYS has move
@@ -1760,7 +1794,7 @@ namespace OpenSim.Region.Framework.Scenes
1760 } 1794 }
1761 1795
1762 AssetBase asset = CreateAsset(itemBase.Name, itemBase.Description, (sbyte)itemBase.AssetType, 1796 AssetBase asset = CreateAsset(itemBase.Name, itemBase.Description, (sbyte)itemBase.AssetType,
1763 Encoding.ASCII.GetBytes("default\n{\n state_entry()\n {\n llSay(0, \"Script running\");\n }\n}"), 1797 Encoding.ASCII.GetBytes("default\n{\n state_entry()\n {\n llSay(0, \"Script running\");\n }\n\n touch_start(integer num)\n {\n }\n}"),
1764 agentID); 1798 agentID);
1765 AssetService.Store(asset); 1799 AssetService.Store(asset);
1766 1800
@@ -1916,23 +1950,32 @@ namespace OpenSim.Region.Framework.Scenes
1916 // build a list of eligible objects 1950 // build a list of eligible objects
1917 List<uint> deleteIDs = new List<uint>(); 1951 List<uint> deleteIDs = new List<uint>();
1918 List<SceneObjectGroup> deleteGroups = new List<SceneObjectGroup>(); 1952 List<SceneObjectGroup> deleteGroups = new List<SceneObjectGroup>();
1919 1953 List<SceneObjectGroup> takeGroups = new List<SceneObjectGroup>();
1920 // Start with true for both, then remove the flags if objects
1921 // that we can't derez are part of the selection
1922 bool permissionToTake = true;
1923 bool permissionToTakeCopy = true;
1924 bool permissionToDelete = true;
1925 1954
1926 foreach (uint localID in localIDs) 1955 foreach (uint localID in localIDs)
1927 { 1956 {
1957 // Start with true for both, then remove the flags if objects
1958 // that we can't derez are part of the selection
1959 bool permissionToTake = true;
1960 bool permissionToTakeCopy = true;
1961 bool permissionToDelete = true;
1962
1928 // Invalid id 1963 // Invalid id
1929 SceneObjectPart part = GetSceneObjectPart(localID); 1964 SceneObjectPart part = GetSceneObjectPart(localID);
1930 if (part == null) 1965 if (part == null)
1966 {
1967 //Client still thinks the object exists, kill it
1968 deleteIDs.Add(localID);
1931 continue; 1969 continue;
1970 }
1932 1971
1933 // Already deleted by someone else 1972 // Already deleted by someone else
1934 if (part.ParentGroup.IsDeleted) 1973 if (part.ParentGroup.IsDeleted)
1974 {
1975 //Client still thinks the object exists, kill it
1976 deleteIDs.Add(localID);
1935 continue; 1977 continue;
1978 }
1936 1979
1937 // Can't delete child prims 1980 // Can't delete child prims
1938 if (part != part.ParentGroup.RootPart) 1981 if (part != part.ParentGroup.RootPart)
@@ -1940,8 +1983,8 @@ namespace OpenSim.Region.Framework.Scenes
1940 1983
1941 SceneObjectGroup grp = part.ParentGroup; 1984 SceneObjectGroup grp = part.ParentGroup;
1942 1985
1943 deleteIDs.Add(localID); 1986 // If child prims have invalid perms, fix them
1944 deleteGroups.Add(grp); 1987 grp.AdjustChildPrimPermissions();
1945 1988
1946 // If child prims have invalid perms, fix them 1989 // If child prims have invalid perms, fix them
1947 grp.AdjustChildPrimPermissions(); 1990 grp.AdjustChildPrimPermissions();
@@ -1962,81 +2005,193 @@ namespace OpenSim.Region.Framework.Scenes
1962 } 2005 }
1963 else 2006 else
1964 { 2007 {
1965 if (!Permissions.CanTakeCopyObject(grp.UUID, remoteClient.AgentId)) 2008 if (action == DeRezAction.TakeCopy)
2009 {
2010 if (!Permissions.CanTakeCopyObject(grp.UUID, remoteClient.AgentId))
2011 permissionToTakeCopy = false;
2012 }
2013 else
2014 {
1966 permissionToTakeCopy = false; 2015 permissionToTakeCopy = false;
1967 2016 }
1968 if (!Permissions.CanTakeObject(grp.UUID, remoteClient.AgentId)) 2017 if (!Permissions.CanTakeObject(grp.UUID, remoteClient.AgentId))
1969 permissionToTake = false; 2018 permissionToTake = false;
1970 2019
1971 if (!Permissions.CanDeleteObject(grp.UUID, remoteClient.AgentId)) 2020 if (!Permissions.CanDeleteObject(grp.UUID, remoteClient.AgentId))
1972 permissionToDelete = false; 2021 permissionToDelete = false;
1973 } 2022 }
1974 }
1975 2023
1976 // Handle god perms 2024 // Handle god perms
1977 if ((remoteClient != null) && Permissions.IsGod(remoteClient.AgentId)) 2025 if ((remoteClient != null) && Permissions.IsGod(remoteClient.AgentId))
1978 { 2026 {
1979 permissionToTake = true; 2027 permissionToTake = true;
1980 permissionToTakeCopy = true; 2028 permissionToTakeCopy = true;
1981 permissionToDelete = true; 2029 permissionToDelete = true;
1982 } 2030 }
1983 2031
1984 // If we're re-saving, we don't even want to delete 2032 // If we're re-saving, we don't even want to delete
1985 if (action == DeRezAction.SaveToExistingUserInventoryItem) 2033 if (action == DeRezAction.SaveToExistingUserInventoryItem)
1986 permissionToDelete = false; 2034 permissionToDelete = false;
1987 2035
1988 // if we want to take a copy, we also don't want to delete 2036 // if we want to take a copy, we also don't want to delete
1989 // Note: after this point, the permissionToTakeCopy flag 2037 // Note: after this point, the permissionToTakeCopy flag
1990 // becomes irrelevant. It already includes the permissionToTake 2038 // becomes irrelevant. It already includes the permissionToTake
1991 // permission and after excluding no copy items here, we can 2039 // permission and after excluding no copy items here, we can
1992 // just use that. 2040 // just use that.
1993 if (action == DeRezAction.TakeCopy) 2041 if (action == DeRezAction.TakeCopy)
1994 { 2042 {
1995 // If we don't have permission, stop right here 2043 // If we don't have permission, stop right here
1996 if (!permissionToTakeCopy) 2044 if (!permissionToTakeCopy)
1997 return; 2045 return;
1998 2046
1999 permissionToTake = true; 2047 permissionToTake = true;
2000 // Don't delete 2048 // Don't delete
2001 permissionToDelete = false; 2049 permissionToDelete = false;
2002 } 2050 }
2003 2051
2004 if (action == DeRezAction.Return) 2052 if (action == DeRezAction.Return)
2005 {
2006 if (remoteClient != null)
2007 { 2053 {
2008 if (Permissions.CanReturnObjects( 2054 if (remoteClient != null)
2009 null,
2010 remoteClient.AgentId,
2011 deleteGroups))
2012 { 2055 {
2013 permissionToTake = true; 2056 if (Permissions.CanReturnObjects(
2014 permissionToDelete = true; 2057 null,
2015 2058 remoteClient.AgentId,
2016 foreach (SceneObjectGroup g in deleteGroups) 2059 new List<SceneObjectGroup>() {grp}))
2017 { 2060 {
2018 AddReturn(g.OwnerID == g.GroupID ? g.LastOwnerID : g.OwnerID, g.Name, g.AbsolutePosition, "parcel owner return"); 2061 permissionToTake = true;
2062 permissionToDelete = true;
2063
2064 AddReturn(grp.OwnerID == grp.GroupID ? grp.LastOwnerID : grp.OwnerID, grp.Name, grp.AbsolutePosition, "parcel owner return");
2019 } 2065 }
2020 } 2066 }
2067 else // Auto return passes through here with null agent
2068 {
2069 permissionToTake = true;
2070 permissionToDelete = true;
2071 }
2021 } 2072 }
2022 else // Auto return passes through here with null agent 2073
2074 if (permissionToTake && (!permissionToDelete))
2075 takeGroups.Add(grp);
2076
2077 if (permissionToDelete)
2023 { 2078 {
2024 permissionToTake = true; 2079 if (permissionToTake)
2025 permissionToDelete = true; 2080 deleteGroups.Add(grp);
2081 deleteIDs.Add(grp.LocalId);
2026 } 2082 }
2027 } 2083 }
2028 2084
2029 if (permissionToTake && (action != DeRezAction.Delete || this.m_useTrashOnDelete)) 2085 SendKillObject(deleteIDs);
2086
2087 if (deleteGroups.Count > 0)
2030 { 2088 {
2089 foreach (SceneObjectGroup g in deleteGroups)
2090 deleteIDs.Remove(g.LocalId);
2091
2031 m_asyncSceneObjectDeleter.DeleteToInventory( 2092 m_asyncSceneObjectDeleter.DeleteToInventory(
2032 action, destinationID, deleteGroups, remoteClient, 2093 action, destinationID, deleteGroups, remoteClient,
2033 permissionToDelete); 2094 true);
2034 } 2095 }
2035 else if (permissionToDelete) 2096 if (takeGroups.Count > 0)
2097 {
2098 m_asyncSceneObjectDeleter.DeleteToInventory(
2099 action, destinationID, takeGroups, remoteClient,
2100 false);
2101 }
2102 if (deleteIDs.Count > 0)
2036 { 2103 {
2037 foreach (SceneObjectGroup g in deleteGroups) 2104 foreach (SceneObjectGroup g in deleteGroups)
2038 DeleteSceneObject(g, false); 2105 DeleteSceneObject(g, true);
2106 }
2107 }
2108
2109 public UUID attachObjectAssetStore(IClientAPI remoteClient, SceneObjectGroup grp, UUID AgentId, out UUID itemID)
2110 {
2111 itemID = UUID.Zero;
2112 if (grp != null)
2113 {
2114 Vector3 inventoryStoredPosition = new Vector3
2115 (((grp.AbsolutePosition.X > (int)Constants.RegionSize)
2116 ? 250
2117 : grp.AbsolutePosition.X)
2118 ,
2119 (grp.AbsolutePosition.X > (int)Constants.RegionSize)
2120 ? 250
2121 : grp.AbsolutePosition.X,
2122 grp.AbsolutePosition.Z);
2123
2124 Vector3 originalPosition = grp.AbsolutePosition;
2125
2126 grp.AbsolutePosition = inventoryStoredPosition;
2127
2128 string sceneObjectXml = SceneObjectSerializer.ToOriginalXmlFormat(grp);
2129
2130 grp.AbsolutePosition = originalPosition;
2131
2132 AssetBase asset = CreateAsset(
2133 grp.GetPartName(grp.LocalId),
2134 grp.GetPartDescription(grp.LocalId),
2135 (sbyte)AssetType.Object,
2136 Utils.StringToBytes(sceneObjectXml),
2137 remoteClient.AgentId);
2138 AssetService.Store(asset);
2139
2140 InventoryItemBase item = new InventoryItemBase();
2141 item.CreatorId = grp.RootPart.CreatorID.ToString();
2142 item.CreatorData = grp.RootPart.CreatorData;
2143 item.Owner = remoteClient.AgentId;
2144 item.ID = UUID.Random();
2145 item.AssetID = asset.FullID;
2146 item.Description = asset.Description;
2147 item.Name = asset.Name;
2148 item.AssetType = asset.Type;
2149 item.InvType = (int)InventoryType.Object;
2150
2151 InventoryFolderBase folder = InventoryService.GetFolderForType(remoteClient.AgentId, AssetType.Object);
2152 if (folder != null)
2153 item.Folder = folder.ID;
2154 else // oopsies
2155 item.Folder = UUID.Zero;
2156
2157 // Set up base perms properly
2158 uint permsBase = (uint)(PermissionMask.Move | PermissionMask.Copy | PermissionMask.Transfer | PermissionMask.Modify);
2159 permsBase &= grp.RootPart.BaseMask;
2160 permsBase |= (uint)PermissionMask.Move;
2161
2162 // Make sure we don't lock it
2163 grp.RootPart.NextOwnerMask |= (uint)PermissionMask.Move;
2164
2165 if ((remoteClient.AgentId != grp.RootPart.OwnerID) && Permissions.PropagatePermissions())
2166 {
2167 item.BasePermissions = permsBase & grp.RootPart.NextOwnerMask;
2168 item.CurrentPermissions = permsBase & grp.RootPart.NextOwnerMask;
2169 item.NextPermissions = permsBase & grp.RootPart.NextOwnerMask;
2170 item.EveryOnePermissions = permsBase & grp.RootPart.EveryoneMask & grp.RootPart.NextOwnerMask;
2171 item.GroupPermissions = permsBase & grp.RootPart.GroupMask & grp.RootPart.NextOwnerMask;
2172 }
2173 else
2174 {
2175 item.BasePermissions = permsBase;
2176 item.CurrentPermissions = permsBase & grp.RootPart.OwnerMask;
2177 item.NextPermissions = permsBase & grp.RootPart.NextOwnerMask;
2178 item.EveryOnePermissions = permsBase & grp.RootPart.EveryoneMask;
2179 item.GroupPermissions = permsBase & grp.RootPart.GroupMask;
2180 }
2181 item.CreationDate = Util.UnixTimeSinceEpoch();
2182
2183 // sets itemID so client can show item as 'attached' in inventory
2184 grp.FromItemID = item.ID;
2185
2186 if (AddInventoryItem(item))
2187 remoteClient.SendInventoryItemCreateUpdate(item, 0);
2188 else
2189 m_dialogModule.SendAlertToUser(remoteClient, "Operation failed");
2190
2191 itemID = item.ID;
2192 return item.AssetID;
2039 } 2193 }
2194 return UUID.Zero;
2040 } 2195 }
2041 2196
2042 /// <summary> 2197 /// <summary>
@@ -2166,6 +2321,9 @@ namespace OpenSim.Region.Framework.Scenes
2166 2321
2167 public void SetScriptRunning(IClientAPI controllingClient, UUID objectID, UUID itemID, bool running) 2322 public void SetScriptRunning(IClientAPI controllingClient, UUID objectID, UUID itemID, bool running)
2168 { 2323 {
2324 if (!Permissions.CanEditScript(itemID, objectID, controllingClient.AgentId))
2325 return;
2326
2169 SceneObjectPart part = GetSceneObjectPart(objectID); 2327 SceneObjectPart part = GetSceneObjectPart(objectID);
2170 if (part == null) 2328 if (part == null)
2171 return; 2329 return;
@@ -2222,7 +2380,10 @@ namespace OpenSim.Region.Framework.Scenes
2222 } 2380 }
2223 else 2381 else
2224 { 2382 {
2225 if (!Permissions.CanEditObject(sog.UUID, remoteClient.AgentId)) 2383 if (!Permissions.IsGod(remoteClient.AgentId) && sog.OwnerID != remoteClient.AgentId)
2384 continue;
2385
2386 if (!Permissions.CanTransferObject(sog.UUID, groupID))
2226 continue; 2387 continue;
2227 2388
2228 if (sog.GroupID != groupID) 2389 if (sog.GroupID != groupID)
diff --git a/OpenSim/Region/Framework/Scenes/Scene.PacketHandlers.cs b/OpenSim/Region/Framework/Scenes/Scene.PacketHandlers.cs
index 6e53951..16c0d25 100644
--- a/OpenSim/Region/Framework/Scenes/Scene.PacketHandlers.cs
+++ b/OpenSim/Region/Framework/Scenes/Scene.PacketHandlers.cs
@@ -38,9 +38,8 @@ namespace OpenSim.Region.Framework.Scenes
38{ 38{
39 public partial class Scene 39 public partial class Scene
40 { 40 {
41 41 public void SimChat(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName,
42 protected void SimChat(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName, 42 UUID fromID, bool fromAgent, bool broadcast, UUID destination)
43 UUID fromID, UUID targetID, bool fromAgent, bool broadcast)
44 { 43 {
45 OSChatMessage args = new OSChatMessage(); 44 OSChatMessage args = new OSChatMessage();
46 45
@@ -50,6 +49,7 @@ namespace OpenSim.Region.Framework.Scenes
50 args.Position = fromPos; 49 args.Position = fromPos;
51 args.SenderUUID = fromID; 50 args.SenderUUID = fromID;
52 args.Scene = this; 51 args.Scene = this;
52 args.Destination = destination;
53 53
54 if (fromAgent) 54 if (fromAgent)
55 { 55 {
@@ -64,18 +64,18 @@ namespace OpenSim.Region.Framework.Scenes
64 } 64 }
65 65
66 args.From = fromName; 66 args.From = fromName;
67 args.TargetUUID = targetID; 67 //args.
68 68
69 if (broadcast) 69 if (broadcast)
70 EventManager.TriggerOnChatBroadcast(this, args); 70 EventManager.TriggerOnChatBroadcast(this, args);
71 else 71 else
72 EventManager.TriggerOnChatFromWorld(this, args); 72 EventManager.TriggerOnChatFromWorld(this, args);
73 } 73 }
74 74
75 protected void SimChat(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName, 75 protected void SimChat(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName,
76 UUID fromID, bool fromAgent, bool broadcast) 76 UUID fromID, bool fromAgent, bool broadcast)
77 { 77 {
78 SimChat(message, type, channel, fromPos, fromName, fromID, UUID.Zero, fromAgent, broadcast); 78 SimChat(message, type, channel, fromPos, fromName, fromID, fromAgent, broadcast, UUID.Zero);
79 } 79 }
80 80
81 /// <summary> 81 /// <summary>
@@ -115,19 +115,6 @@ namespace OpenSim.Region.Framework.Scenes
115 { 115 {
116 SimChat(message, type, channel, fromPos, fromName, fromID, fromAgent, true); 116 SimChat(message, type, channel, fromPos, fromName, fromID, fromAgent, true);
117 } 117 }
118 /// <summary>
119 ///
120 /// </summary>
121 /// <param name="message"></param>
122 /// <param name="type"></param>
123 /// <param name="fromPos"></param>
124 /// <param name="fromName"></param>
125 /// <param name="fromAgentID"></param>
126 /// <param name="targetID"></param>
127 public void SimChatToAgent(UUID targetID, byte[] message, Vector3 fromPos, string fromName, UUID fromID, bool fromAgent)
128 {
129 SimChat(message, ChatTypeEnum.Say, 0, fromPos, fromName, fromID, targetID, fromAgent, false);
130 }
131 118
132 /// <summary> 119 /// <summary>
133 /// Invoked when the client requests a prim. 120 /// Invoked when the client requests a prim.
@@ -149,27 +136,47 @@ namespace OpenSim.Region.Framework.Scenes
149 /// <param name="remoteClient"></param> 136 /// <param name="remoteClient"></param>
150 public void SelectPrim(uint primLocalID, IClientAPI remoteClient) 137 public void SelectPrim(uint primLocalID, IClientAPI remoteClient)
151 { 138 {
139 /*
140 SceneObjectPart part = GetSceneObjectPart(primLocalID);
141
142 if (null == part)
143 return;
144
145 if (part.IsRoot)
146 {
147 SceneObjectGroup sog = part.ParentGroup;
148 sog.SendPropertiesToClient(remoteClient);
149
150 // A prim is only tainted if it's allowed to be edited by the person clicking it.
151 if (Permissions.CanEditObject(sog.UUID, remoteClient.AgentId)
152 || Permissions.CanMoveObject(sog.UUID, remoteClient.AgentId))
153 {
154 sog.IsSelected = true;
155 EventManager.TriggerParcelPrimCountTainted();
156 }
157 }
158 else
159 {
160 part.SendPropertiesToClient(remoteClient);
161 }
162 */
152 SceneObjectPart part = GetSceneObjectPart(primLocalID); 163 SceneObjectPart part = GetSceneObjectPart(primLocalID);
153 164
154 if (null == part) 165 if (null == part)
155 return; 166 return;
156 167
157 if (part.IsRoot) 168 SceneObjectGroup sog = part.ParentGroup;
158 { 169 if (sog == null)
159 SceneObjectGroup sog = part.ParentGroup; 170 return;
160 sog.SendPropertiesToClient(remoteClient);
161 sog.IsSelected = true;
162 171
163 // A prim is only tainted if it's allowed to be edited by the person clicking it. 172 part.SendPropertiesToClient(remoteClient);
164 if (Permissions.CanEditObject(sog.UUID, remoteClient.AgentId) 173
165 || Permissions.CanMoveObject(sog.UUID, remoteClient.AgentId)) 174 // A prim is only tainted if it's allowed to be edited by the person clicking it.
166 { 175 if (Permissions.CanEditObject(sog.UUID, remoteClient.AgentId)
167 EventManager.TriggerParcelPrimCountTainted(); 176 || Permissions.CanMoveObject(sog.UUID, remoteClient.AgentId))
168 }
169 }
170 else
171 { 177 {
172 part.SendPropertiesToClient(remoteClient); 178 part.IsSelected = true;
179 EventManager.TriggerParcelPrimCountTainted();
173 } 180 }
174 } 181 }
175 182
@@ -222,7 +229,7 @@ namespace OpenSim.Region.Framework.Scenes
222 SceneObjectPart part = GetSceneObjectPart(primLocalID); 229 SceneObjectPart part = GetSceneObjectPart(primLocalID);
223 if (part == null) 230 if (part == null)
224 return; 231 return;
225 232 /*
226 // A deselect packet contains all the local prims being deselected. However, since selection is still 233 // A deselect packet contains all the local prims being deselected. However, since selection is still
227 // group based we only want the root prim to trigger a full update - otherwise on objects with many prims 234 // group based we only want the root prim to trigger a full update - otherwise on objects with many prims
228 // we end up sending many duplicate ObjectUpdates 235 // we end up sending many duplicate ObjectUpdates
@@ -235,7 +242,9 @@ namespace OpenSim.Region.Framework.Scenes
235 // handled by group, but by prim. Legacy cruft. 242 // handled by group, but by prim. Legacy cruft.
236 // TODO: Make selection flagging per prim! 243 // TODO: Make selection flagging per prim!
237 // 244 //
238 part.ParentGroup.IsSelected = false; 245 if (Permissions.CanEditObject(part.ParentGroup.UUID, remoteClient.AgentId)
246 || Permissions.CanMoveObject(part.ParentGroup.UUID, remoteClient.AgentId))
247 part.ParentGroup.IsSelected = false;
239 248
240 if (part.ParentGroup.IsAttachment) 249 if (part.ParentGroup.IsAttachment)
241 isAttachment = true; 250 isAttachment = true;
@@ -255,6 +264,22 @@ namespace OpenSim.Region.Framework.Scenes
255 part.UUID, remoteClient.AgentId)) 264 part.UUID, remoteClient.AgentId))
256 EventManager.TriggerParcelPrimCountTainted(); 265 EventManager.TriggerParcelPrimCountTainted();
257 } 266 }
267 */
268
269 bool oldgprSelect = part.ParentGroup.IsSelected;
270
271 // This is wrong, wrong, wrong. Selection should not be
272 // handled by group, but by prim. Legacy cruft.
273 // TODO: Make selection flagging per prim!
274 //
275 if (Permissions.CanEditObject(part.ParentGroup.UUID, remoteClient.AgentId)
276 || Permissions.CanMoveObject(part.ParentGroup.UUID, remoteClient.AgentId))
277 {
278 part.IsSelected = false;
279 if (!part.ParentGroup.IsAttachment && oldgprSelect != part.ParentGroup.IsSelected)
280 EventManager.TriggerParcelPrimCountTainted();
281 }
282
258 } 283 }
259 284
260 public virtual void ProcessMoneyTransferRequest(UUID source, UUID destination, int amount, 285 public virtual void ProcessMoneyTransferRequest(UUID source, UUID destination, int amount,
@@ -397,6 +422,20 @@ namespace OpenSim.Region.Framework.Scenes
397 ); 422 );
398 } 423 }
399 424
425 private class DescendentsRequestData
426 {
427 public IClientAPI RemoteClient;
428 public UUID FolderID;
429 public UUID OwnerID;
430 public bool FetchFolders;
431 public bool FetchItems;
432 public int SortOrder;
433 }
434
435 private Queue<DescendentsRequestData> m_descendentsRequestQueue = new Queue<DescendentsRequestData>();
436 private Object m_descendentsRequestLock = new Object();
437 private bool m_descendentsRequestProcessing = false;
438
400 /// <summary> 439 /// <summary>
401 /// Tell the client about the various child items and folders contained in the requested folder. 440 /// Tell the client about the various child items and folders contained in the requested folder.
402 /// </summary> 441 /// </summary>
@@ -433,17 +472,38 @@ namespace OpenSim.Region.Framework.Scenes
433 } 472 }
434 } 473 }
435 474
436 // We're going to send the reply async, because there may be 475 lock (m_descendentsRequestLock)
437 // an enormous quantity of packets -- basically the entire inventory! 476 {
438 // We don't want to block the client thread while all that is happening. 477 if (!m_descendentsRequestProcessing)
439 SendInventoryDelegate d = SendInventoryAsync; 478 {
440 d.BeginInvoke(remoteClient, folderID, ownerID, fetchFolders, fetchItems, sortOrder, SendInventoryComplete, d); 479 m_descendentsRequestProcessing = true;
480
481 // We're going to send the reply async, because there may be
482 // an enormous quantity of packets -- basically the entire inventory!
483 // We don't want to block the client thread while all that is happening.
484 SendInventoryDelegate d = SendInventoryAsync;
485 d.BeginInvoke(remoteClient, folderID, ownerID, fetchFolders, fetchItems, sortOrder, SendInventoryComplete, d);
486
487 return;
488 }
489
490 DescendentsRequestData req = new DescendentsRequestData();
491 req.RemoteClient = remoteClient;
492 req.FolderID = folderID;
493 req.OwnerID = ownerID;
494 req.FetchFolders = fetchFolders;
495 req.FetchItems = fetchItems;
496 req.SortOrder = sortOrder;
497
498 m_descendentsRequestQueue.Enqueue(req);
499 }
441 } 500 }
442 501
443 delegate void SendInventoryDelegate(IClientAPI remoteClient, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder); 502 delegate void SendInventoryDelegate(IClientAPI remoteClient, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder);
444 503
445 void SendInventoryAsync(IClientAPI remoteClient, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder) 504 void SendInventoryAsync(IClientAPI remoteClient, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder)
446 { 505 {
506 Thread.Sleep(20);
447 SendInventoryUpdate(remoteClient, new InventoryFolderBase(folderID), fetchFolders, fetchItems); 507 SendInventoryUpdate(remoteClient, new InventoryFolderBase(folderID), fetchFolders, fetchItems);
448 } 508 }
449 509
@@ -451,6 +511,21 @@ namespace OpenSim.Region.Framework.Scenes
451 { 511 {
452 SendInventoryDelegate d = (SendInventoryDelegate)iar.AsyncState; 512 SendInventoryDelegate d = (SendInventoryDelegate)iar.AsyncState;
453 d.EndInvoke(iar); 513 d.EndInvoke(iar);
514
515 lock (m_descendentsRequestLock)
516 {
517 if (m_descendentsRequestQueue.Count > 0)
518 {
519 DescendentsRequestData req = m_descendentsRequestQueue.Dequeue();
520
521 d = SendInventoryAsync;
522 d.BeginInvoke(req.RemoteClient, req.FolderID, req.OwnerID, req.FetchFolders, req.FetchItems, req.SortOrder, SendInventoryComplete, d);
523
524 return;
525 }
526
527 m_descendentsRequestProcessing = false;
528 }
454 } 529 }
455 530
456 /// <summary> 531 /// <summary>
diff --git a/OpenSim/Region/Framework/Scenes/Scene.cs b/OpenSim/Region/Framework/Scenes/Scene.cs
index 872c061..129bf09 100644
--- a/OpenSim/Region/Framework/Scenes/Scene.cs
+++ b/OpenSim/Region/Framework/Scenes/Scene.cs
@@ -151,8 +151,8 @@ namespace OpenSim.Region.Framework.Scenes
151 // TODO: need to figure out how allow client agents but deny 151 // TODO: need to figure out how allow client agents but deny
152 // root agents when ACL denies access to root agent 152 // root agents when ACL denies access to root agent
153 public bool m_strictAccessControl = true; 153 public bool m_strictAccessControl = true;
154 154 public bool m_seeIntoBannedRegion = false;
155 public int MaxUndoCount { get; set; } 155 public int MaxUndoCount = 5;
156 156
157 // Using this for RegionReady module to prevent LoginsDisabled from changing under our feet; 157 // Using this for RegionReady module to prevent LoginsDisabled from changing under our feet;
158 public bool LoginLock = false; 158 public bool LoginLock = false;
@@ -168,12 +168,14 @@ namespace OpenSim.Region.Framework.Scenes
168 168
169 protected int m_splitRegionID; 169 protected int m_splitRegionID;
170 protected Timer m_restartWaitTimer = new Timer(); 170 protected Timer m_restartWaitTimer = new Timer();
171 protected Timer m_timerWatchdog = new Timer();
171 protected List<RegionInfo> m_regionRestartNotifyList = new List<RegionInfo>(); 172 protected List<RegionInfo> m_regionRestartNotifyList = new List<RegionInfo>();
172 protected List<RegionInfo> m_neighbours = new List<RegionInfo>(); 173 protected List<RegionInfo> m_neighbours = new List<RegionInfo>();
173 protected string m_simulatorVersion = "OpenSimulator Server"; 174 protected string m_simulatorVersion = "OpenSimulator Server";
174 protected ModuleLoader m_moduleLoader; 175 protected ModuleLoader m_moduleLoader;
175 protected AgentCircuitManager m_authenticateHandler; 176 protected AgentCircuitManager m_authenticateHandler;
176 protected SceneCommunicationService m_sceneGridService; 177 protected SceneCommunicationService m_sceneGridService;
178 protected ISnmpModule m_snmpService = null;
177 179
178 protected ISimulationDataService m_SimulationDataService; 180 protected ISimulationDataService m_SimulationDataService;
179 protected IEstateDataService m_EstateDataService; 181 protected IEstateDataService m_EstateDataService;
@@ -236,8 +238,8 @@ namespace OpenSim.Region.Framework.Scenes
236 private int m_update_presences = 1; // Update scene presence movements 238 private int m_update_presences = 1; // Update scene presence movements
237 private int m_update_events = 1; 239 private int m_update_events = 1;
238 private int m_update_backup = 200; 240 private int m_update_backup = 200;
239 private int m_update_terrain = 50; 241 private int m_update_terrain = 1000;
240// private int m_update_land = 1; 242 private int m_update_land = 10;
241 private int m_update_coarse_locations = 50; 243 private int m_update_coarse_locations = 50;
242 244
243 private int agentMS; 245 private int agentMS;
@@ -250,13 +252,13 @@ namespace OpenSim.Region.Framework.Scenes
250 private int backupMS; 252 private int backupMS;
251 private int terrainMS; 253 private int terrainMS;
252 private int landMS; 254 private int landMS;
253 private int spareMS;
254 255
255 /// <summary> 256 /// <summary>
256 /// Tick at which the last frame was processed. 257 /// Tick at which the last frame was processed.
257 /// </summary> 258 /// </summary>
258 private int m_lastFrameTick; 259 private int m_lastFrameTick;
259 260
261 public bool CombineRegions = false;
260 /// <summary> 262 /// <summary>
261 /// Tick at which the last maintenance run occurred. 263 /// Tick at which the last maintenance run occurred.
262 /// </summary> 264 /// </summary>
@@ -287,6 +289,11 @@ namespace OpenSim.Region.Framework.Scenes
287 /// </summary> 289 /// </summary>
288 private int m_LastLogin; 290 private int m_LastLogin;
289 291
292 private int m_lastIncoming;
293 private int m_lastOutgoing;
294 private int m_hbRestarts = 0;
295
296
290 /// <summary> 297 /// <summary>
291 /// Thread that runs the scene loop. 298 /// Thread that runs the scene loop.
292 /// </summary> 299 /// </summary>
@@ -302,7 +309,7 @@ namespace OpenSim.Region.Framework.Scenes
302 private volatile bool m_shuttingDown; 309 private volatile bool m_shuttingDown;
303 310
304// private int m_lastUpdate; 311// private int m_lastUpdate;
305// private bool m_firstHeartbeat = true; 312 private bool m_firstHeartbeat = true;
306 313
307 private UpdatePrioritizationSchemes m_priorityScheme = UpdatePrioritizationSchemes.Time; 314 private UpdatePrioritizationSchemes m_priorityScheme = UpdatePrioritizationSchemes.Time;
308 private bool m_reprioritizationEnabled = true; 315 private bool m_reprioritizationEnabled = true;
@@ -347,6 +354,19 @@ namespace OpenSim.Region.Framework.Scenes
347 get { return m_sceneGridService; } 354 get { return m_sceneGridService; }
348 } 355 }
349 356
357 public ISnmpModule SnmpService
358 {
359 get
360 {
361 if (m_snmpService == null)
362 {
363 m_snmpService = RequestModuleInterface<ISnmpModule>();
364 }
365
366 return m_snmpService;
367 }
368 }
369
350 public ISimulationDataService SimulationDataService 370 public ISimulationDataService SimulationDataService
351 { 371 {
352 get 372 get
@@ -646,6 +666,8 @@ namespace OpenSim.Region.Framework.Scenes
646 m_SimulationDataService = simDataService; 666 m_SimulationDataService = simDataService;
647 m_EstateDataService = estateDataService; 667 m_EstateDataService = estateDataService;
648 m_regionHandle = RegionInfo.RegionHandle; 668 m_regionHandle = RegionInfo.RegionHandle;
669 m_lastIncoming = 0;
670 m_lastOutgoing = 0;
649 671
650 m_asyncSceneObjectDeleter = new AsyncSceneObjectGroupDeleter(this); 672 m_asyncSceneObjectDeleter = new AsyncSceneObjectGroupDeleter(this);
651 m_asyncSceneObjectDeleter.Enabled = true; 673 m_asyncSceneObjectDeleter.Enabled = true;
@@ -728,137 +750,148 @@ namespace OpenSim.Region.Framework.Scenes
728 750
729 // Region config overrides global config 751 // Region config overrides global config
730 // 752 //
731 if (m_config.Configs["Startup"] != null) 753 try
732 { 754 {
733 IConfig startupConfig = m_config.Configs["Startup"]; 755 if (m_config.Configs["Startup"] != null)
734 756 {
735 StartDisabled = startupConfig.GetBoolean("StartDisabled", false); 757 IConfig startupConfig = m_config.Configs["Startup"];
736 758
737 m_defaultDrawDistance = startupConfig.GetFloat("DefaultDrawDistance", m_defaultDrawDistance); 759 StartDisabled = startupConfig.GetBoolean("StartDisabled", false);
738 m_useBackup = startupConfig.GetBoolean("UseSceneBackup", m_useBackup);
739 if (!m_useBackup)
740 m_log.InfoFormat("[SCENE]: Backup has been disabled for {0}", RegionInfo.RegionName);
741
742 //Animation states
743 m_useFlySlow = startupConfig.GetBoolean("enableflyslow", false);
744 760
745 PhysicalPrims = startupConfig.GetBoolean("physical_prim", PhysicalPrims); 761 m_defaultDrawDistance = startupConfig.GetFloat("DefaultDrawDistance",m_defaultDrawDistance);
746 CollidablePrims = startupConfig.GetBoolean("collidable_prim", CollidablePrims); 762 m_useBackup = startupConfig.GetBoolean("UseSceneBackup", m_useBackup);
763 if (!m_useBackup)
764 m_log.InfoFormat("[SCENE]: Backup has been disabled for {0}", RegionInfo.RegionName);
765
766 //Animation states
767 m_useFlySlow = startupConfig.GetBoolean("enableflyslow", false);
747 768
748 m_minNonphys = startupConfig.GetFloat("NonPhysicalPrimMin", m_minNonphys); 769 PhysicalPrims = startupConfig.GetBoolean("physical_prim", true);
749 if (RegionInfo.NonphysPrimMin > 0) 770 CollidablePrims = startupConfig.GetBoolean("collidable_prim", true);
750 {
751 m_minNonphys = RegionInfo.NonphysPrimMin;
752 }
753 771
754 m_maxNonphys = startupConfig.GetFloat("NonPhysicalPrimMax", m_maxNonphys); 772 m_minNonphys = startupConfig.GetFloat("NonPhysicalPrimMin", m_minNonphys);
755 if (RegionInfo.NonphysPrimMax > 0) 773 if (RegionInfo.NonphysPrimMin > 0)
756 { 774 {
757 m_maxNonphys = RegionInfo.NonphysPrimMax; 775 m_minNonphys = RegionInfo.NonphysPrimMin;
758 } 776 }
759 777
760 m_minPhys = startupConfig.GetFloat("PhysicalPrimMin", m_minPhys); 778 m_maxNonphys = startupConfig.GetFloat("NonPhysicalPrimMax", m_maxNonphys);
761 if (RegionInfo.PhysPrimMin > 0) 779 if (RegionInfo.NonphysPrimMax > 0)
762 { 780 {
763 m_minPhys = RegionInfo.PhysPrimMin; 781 m_maxNonphys = RegionInfo.NonphysPrimMax;
764 } 782 }
765 783
766 m_maxPhys = startupConfig.GetFloat("PhysicalPrimMax", m_maxPhys); 784 m_minPhys = startupConfig.GetFloat("PhysicalPrimMin", m_minPhys);
767 if (RegionInfo.PhysPrimMax > 0) 785 if (RegionInfo.PhysPrimMin > 0)
768 { 786 {
769 m_maxPhys = RegionInfo.PhysPrimMax; 787 m_minPhys = RegionInfo.PhysPrimMin;
770 } 788 }
771 789
772 // Here, if clamping is requested in either global or 790 m_maxPhys = startupConfig.GetFloat("PhysicalPrimMax", m_maxPhys);
773 // local config, it will be used
774 //
775 m_clampPrimSize = startupConfig.GetBoolean("ClampPrimSize", m_clampPrimSize);
776 if (RegionInfo.ClampPrimSize)
777 {
778 m_clampPrimSize = true;
779 }
780 791
781 m_linksetCapacity = startupConfig.GetInt("LinksetPrims", m_linksetCapacity); 792 if (RegionInfo.PhysPrimMax > 0)
782 if (RegionInfo.LinksetCapacity > 0) 793 {
783 { 794 m_maxPhys = RegionInfo.PhysPrimMax;
784 m_linksetCapacity = RegionInfo.LinksetCapacity; 795 }
785 }
786 796
787 m_useTrashOnDelete = startupConfig.GetBoolean("UseTrashOnDelete", m_useTrashOnDelete); 797 m_linksetCapacity = startupConfig.GetInt("LinksetPrims", m_linksetCapacity);
788 m_trustBinaries = startupConfig.GetBoolean("TrustBinaries", m_trustBinaries); 798 if (RegionInfo.LinksetCapacity > 0)
789 m_allowScriptCrossings = startupConfig.GetBoolean("AllowScriptCrossing", m_allowScriptCrossings); 799 {
790 m_dontPersistBefore = 800 m_linksetCapacity = RegionInfo.LinksetCapacity;
791 startupConfig.GetLong("MinimumTimeBeforePersistenceConsidered", DEFAULT_MIN_TIME_FOR_PERSISTENCE); 801 }
792 m_dontPersistBefore *= 10000000;
793 m_persistAfter =
794 startupConfig.GetLong("MaximumTimeBeforePersistenceConsidered", DEFAULT_MAX_TIME_FOR_PERSISTENCE);
795 m_persistAfter *= 10000000;
796 802
797 m_defaultScriptEngine = startupConfig.GetString("DefaultScriptEngine", "XEngine"); 803 SpawnPointRouting = startupConfig.GetString("SpawnPointRouting", "closest");
804 TelehubAllowLandmarks = startupConfig.GetBoolean("TelehubAllowLandmark", false);
798 805
799 SpawnPointRouting = startupConfig.GetString("SpawnPointRouting", "closest"); 806 // Here, if clamping is requested in either global or
800 TelehubAllowLandmarks = startupConfig.GetBoolean("TelehubAllowLandmark", false); 807 // local config, it will be used
808 //
809 m_clampPrimSize = startupConfig.GetBoolean("ClampPrimSize", m_clampPrimSize);
810 if (RegionInfo.ClampPrimSize)
811 {
812 m_clampPrimSize = true;
813 }
801 814
802 IConfig packetConfig = m_config.Configs["PacketPool"]; 815 m_useTrashOnDelete = startupConfig.GetBoolean("UseTrashOnDelete",m_useTrashOnDelete);
803 if (packetConfig != null) 816 m_trustBinaries = startupConfig.GetBoolean("TrustBinaries", m_trustBinaries);
804 { 817 m_allowScriptCrossings = startupConfig.GetBoolean("AllowScriptCrossing", m_allowScriptCrossings);
805 PacketPool.Instance.RecyclePackets = packetConfig.GetBoolean("RecyclePackets", true); 818 m_dontPersistBefore =
806 PacketPool.Instance.RecycleDataBlocks = packetConfig.GetBoolean("RecycleDataBlocks", true); 819 startupConfig.GetLong("MinimumTimeBeforePersistenceConsidered", DEFAULT_MIN_TIME_FOR_PERSISTENCE);
807 } 820 m_dontPersistBefore *= 10000000;
821 m_persistAfter =
822 startupConfig.GetLong("MaximumTimeBeforePersistenceConsidered", DEFAULT_MAX_TIME_FOR_PERSISTENCE);
823 m_persistAfter *= 10000000;
824
825 m_defaultScriptEngine = startupConfig.GetString("DefaultScriptEngine", "XEngine");
826 m_log.InfoFormat("[SCENE]: Default script engine {0}", m_defaultScriptEngine);
827
828 IConfig packetConfig = m_config.Configs["PacketPool"];
829 if (packetConfig != null)
830 {
831 PacketPool.Instance.RecyclePackets = packetConfig.GetBoolean("RecyclePackets", true);
832 PacketPool.Instance.RecycleDataBlocks = packetConfig.GetBoolean("RecycleDataBlocks", true);
833 }
808 834
809 m_strictAccessControl = startupConfig.GetBoolean("StrictAccessControl", m_strictAccessControl); 835 m_strictAccessControl = startupConfig.GetBoolean("StrictAccessControl", m_strictAccessControl);
836 m_seeIntoBannedRegion = startupConfig.GetBoolean("SeeIntoBannedRegion", m_seeIntoBannedRegion);
837 CombineRegions = startupConfig.GetBoolean("CombineContiguousRegions", false);
810 838
811 m_generateMaptiles = startupConfig.GetBoolean("GenerateMaptiles", true); 839 m_generateMaptiles = startupConfig.GetBoolean("GenerateMaptiles", true);
812 if (m_generateMaptiles) 840 if (m_generateMaptiles)
813 {
814 int maptileRefresh = startupConfig.GetInt("MaptileRefresh", 0);
815 if (maptileRefresh != 0)
816 { 841 {
817 m_mapGenerationTimer.Interval = maptileRefresh * 1000; 842 int maptileRefresh = startupConfig.GetInt("MaptileRefresh", 0);
818 m_mapGenerationTimer.Elapsed += RegenerateMaptileAndReregister; 843 if (maptileRefresh != 0)
819 m_mapGenerationTimer.AutoReset = true; 844 {
820 m_mapGenerationTimer.Start(); 845 m_mapGenerationTimer.Interval = maptileRefresh * 1000;
846 m_mapGenerationTimer.Elapsed += RegenerateMaptileAndReregister;
847 m_mapGenerationTimer.AutoReset = true;
848 m_mapGenerationTimer.Start();
849 }
821 } 850 }
822 } 851 else
823 else
824 {
825 string tile = startupConfig.GetString("MaptileStaticUUID", UUID.Zero.ToString());
826 UUID tileID;
827
828 if (UUID.TryParse(tile, out tileID))
829 { 852 {
830 RegionInfo.RegionSettings.TerrainImageID = tileID; 853 string tile = startupConfig.GetString("MaptileStaticUUID", UUID.Zero.ToString());
854 UUID tileID;
855
856 if (UUID.TryParse(tile, out tileID))
857 {
858 RegionInfo.RegionSettings.TerrainImageID = tileID;
859 }
831 } 860 }
832 }
833 861
834 string grant = startupConfig.GetString("AllowedClients", String.Empty); 862 string grant = startupConfig.GetString("AllowedClients", String.Empty);
835 if (grant.Length > 0) 863 if (grant.Length > 0)
836 {
837 foreach (string viewer in grant.Split('|'))
838 { 864 {
839 m_AllowedViewers.Add(viewer.Trim().ToLower()); 865 foreach (string viewer in grant.Split(','))
866 {
867 m_AllowedViewers.Add(viewer.Trim().ToLower());
868 }
840 } 869 }
841 }
842 870
843 grant = startupConfig.GetString("BannedClients", String.Empty); 871 grant = startupConfig.GetString("BannedClients", String.Empty);
844 if (grant.Length > 0) 872 if (grant.Length > 0)
845 {
846 foreach (string viewer in grant.Split('|'))
847 { 873 {
848 m_BannedViewers.Add(viewer.Trim().ToLower()); 874 foreach (string viewer in grant.Split(','))
875 {
876 m_BannedViewers.Add(viewer.Trim().ToLower());
877 }
849 } 878 }
850 }
851 879
852 MinFrameTime = startupConfig.GetFloat( "MinFrameTime", MinFrameTime); 880 MinFrameTime = startupConfig.GetFloat( "MinFrameTime", MinFrameTime);
853 m_update_backup = startupConfig.GetInt( "UpdateStorageEveryNFrames", m_update_backup); 881 m_update_backup = startupConfig.GetInt( "UpdateStorageEveryNFrames", m_update_backup);
854 m_update_coarse_locations = startupConfig.GetInt( "UpdateCoarseLocationsEveryNFrames", m_update_coarse_locations); 882 m_update_coarse_locations = startupConfig.GetInt( "UpdateCoarseLocationsEveryNFrames", m_update_coarse_locations);
855 m_update_entitymovement = startupConfig.GetInt( "UpdateEntityMovementEveryNFrames", m_update_entitymovement); 883 m_update_entitymovement = startupConfig.GetInt( "UpdateEntityMovementEveryNFrames", m_update_entitymovement);
856 m_update_events = startupConfig.GetInt( "UpdateEventsEveryNFrames", m_update_events); 884 m_update_events = startupConfig.GetInt( "UpdateEventsEveryNFrames", m_update_events);
857 m_update_objects = startupConfig.GetInt( "UpdateObjectsEveryNFrames", m_update_objects); 885 m_update_objects = startupConfig.GetInt( "UpdateObjectsEveryNFrames", m_update_objects);
858 m_update_physics = startupConfig.GetInt( "UpdatePhysicsEveryNFrames", m_update_physics); 886 m_update_physics = startupConfig.GetInt( "UpdatePhysicsEveryNFrames", m_update_physics);
859 m_update_presences = startupConfig.GetInt( "UpdateAgentsEveryNFrames", m_update_presences); 887 m_update_presences = startupConfig.GetInt( "UpdateAgentsEveryNFrames", m_update_presences);
860 m_update_terrain = startupConfig.GetInt( "UpdateTerrainEveryNFrames", m_update_terrain); 888 m_update_terrain = startupConfig.GetInt( "UpdateTerrainEveryNFrames", m_update_terrain);
861 m_update_temp_cleaning = startupConfig.GetInt( "UpdateTempCleaningEveryNFrames", m_update_temp_cleaning); 889 m_update_temp_cleaning = startupConfig.GetInt( "UpdateTempCleaningEveryNFrames", m_update_temp_cleaning);
890 }
891 }
892 catch (Exception e)
893 {
894 m_log.Error("[SCENE]: Failed to load StartupConfig: " + e.ToString());
862 } 895 }
863 896
864 // FIXME: Ultimately this should be in a module. 897 // FIXME: Ultimately this should be in a module.
@@ -903,6 +936,8 @@ namespace OpenSim.Region.Framework.Scenes
903 StatsReporter = new SimStatsReporter(this); 936 StatsReporter = new SimStatsReporter(this);
904 StatsReporter.OnSendStatsResult += SendSimStatsPackets; 937 StatsReporter.OnSendStatsResult += SendSimStatsPackets;
905 StatsReporter.OnStatsIncorrect += m_sceneGraph.RecalculateStats; 938 StatsReporter.OnStatsIncorrect += m_sceneGraph.RecalculateStats;
939
940 MainConsole.Instance.Commands.AddCommand("scene", false, "gc collect", "gc collect", "gc collect", "Cause the garbage collector to make a single pass", HandleGcCollect);
906 } 941 }
907 942
908 public Scene(RegionInfo regInfo) : base(regInfo) 943 public Scene(RegionInfo regInfo) : base(regInfo)
@@ -932,9 +967,6 @@ namespace OpenSim.Region.Framework.Scenes
932 WestBorders.Add(westBorder); 967 WestBorders.Add(westBorder);
933 BordersLocked = false; 968 BordersLocked = false;
934 969
935 // TODO: At some point this should be made configurable.
936 MaxUndoCount = 5;
937
938 m_eventManager = new EventManager(); 970 m_eventManager = new EventManager();
939 971
940 m_permissions = new ScenePermissions(this); 972 m_permissions = new ScenePermissions(this);
@@ -1308,7 +1340,22 @@ namespace OpenSim.Region.Framework.Scenes
1308 //m_heartbeatTimer.Elapsed += new ElapsedEventHandler(Heartbeat); 1340 //m_heartbeatTimer.Elapsed += new ElapsedEventHandler(Heartbeat);
1309 if (m_heartbeatThread != null) 1341 if (m_heartbeatThread != null)
1310 { 1342 {
1343 m_hbRestarts++;
1344 if(m_hbRestarts > 10)
1345 Environment.Exit(1);
1346 m_log.ErrorFormat("[SCENE]: Restarting heartbeat thread because it hasn't reported in in region {0}", RegionInfo.RegionName);
1347
1348//int pid = System.Diagnostics.Process.GetCurrentProcess().Id;
1349//System.Diagnostics.Process proc = new System.Diagnostics.Process();
1350//proc.EnableRaisingEvents=false;
1351//proc.StartInfo.FileName = "/bin/kill";
1352//proc.StartInfo.Arguments = "-QUIT " + pid.ToString();
1353//proc.Start();
1354//proc.WaitForExit();
1355//Thread.Sleep(1000);
1356//Environment.Exit(1);
1311 m_heartbeatThread.Abort(); 1357 m_heartbeatThread.Abort();
1358 Watchdog.AbortThread(m_heartbeatThread.ManagedThreadId);
1312 m_heartbeatThread = null; 1359 m_heartbeatThread = null;
1313 } 1360 }
1314// m_lastUpdate = Util.EnvironmentTickCount(); 1361// m_lastUpdate = Util.EnvironmentTickCount();
@@ -1455,16 +1502,20 @@ namespace OpenSim.Region.Framework.Scenes
1455 endFrame = Frame + frames; 1502 endFrame = Frame + frames;
1456 1503
1457 float physicsFPS = 0f; 1504 float physicsFPS = 0f;
1458 int previousFrameTick, tmpMS; 1505 int tmpMS;
1459 int maintc = Util.EnvironmentTickCount(); 1506 int previousFrameTick;
1507 int maintc;
1508 int sleepMS;
1509 int framestart;
1460 1510
1461 while (!m_shuttingDown && (endFrame == null || Frame < endFrame)) 1511 while (!m_shuttingDown && (endFrame == null || Frame < endFrame))
1462 { 1512 {
1513 framestart = Util.EnvironmentTickCount();
1463 ++Frame; 1514 ++Frame;
1464 1515
1465// m_log.DebugFormat("[SCENE]: Processing frame {0} in {1}", Frame, RegionInfo.RegionName); 1516// m_log.DebugFormat("[SCENE]: Processing frame {0} in {1}", Frame, RegionInfo.RegionName);
1466 1517
1467 agentMS = tempOnRezMS = eventMS = backupMS = terrainMS = landMS = spareMS = 0; 1518 agentMS = tempOnRezMS = eventMS = backupMS = terrainMS = landMS = 0;
1468 1519
1469 try 1520 try
1470 { 1521 {
@@ -1516,6 +1567,7 @@ namespace OpenSim.Region.Framework.Scenes
1516 m_sceneGraph.UpdatePresences(); 1567 m_sceneGraph.UpdatePresences();
1517 1568
1518 agentMS += Util.EnvironmentTickCountSubtract(tmpMS); 1569 agentMS += Util.EnvironmentTickCountSubtract(tmpMS);
1570
1519 1571
1520 // Delete temp-on-rez stuff 1572 // Delete temp-on-rez stuff
1521 if (Frame % m_update_temp_cleaning == 0 && !m_cleaningTemps) 1573 if (Frame % m_update_temp_cleaning == 0 && !m_cleaningTemps)
@@ -1597,34 +1649,37 @@ namespace OpenSim.Region.Framework.Scenes
1597 1649
1598 Watchdog.UpdateThread(); 1650 Watchdog.UpdateThread();
1599 1651
1652 otherMS = tempOnRezMS + eventMS + backupMS + terrainMS + landMS;
1653
1654 StatsReporter.AddPhysicsFPS(physicsFPS);
1655 StatsReporter.AddTimeDilation(TimeDilation);
1656 StatsReporter.AddFPS(1);
1657
1658 StatsReporter.addAgentMS(agentMS);
1659 StatsReporter.addPhysicsMS(physicsMS + physicsMS2);
1660 StatsReporter.addOtherMS(otherMS);
1661 StatsReporter.addScriptLines(m_sceneGraph.GetScriptLPS());
1662
1600 previousFrameTick = m_lastFrameTick; 1663 previousFrameTick = m_lastFrameTick;
1601 m_lastFrameTick = Util.EnvironmentTickCount(); 1664 m_lastFrameTick = Util.EnvironmentTickCount();
1602 tmpMS = Util.EnvironmentTickCountSubtract(m_lastFrameTick, maintc); 1665 tmpMS = Util.EnvironmentTickCountSubtract(m_lastFrameTick, framestart);
1603 tmpMS = (int)(MinFrameTime * 1000) - tmpMS; 1666 tmpMS = (int)(MinFrameTime * 1000) - tmpMS;
1604 1667
1668 m_firstHeartbeat = false;
1669
1670 sleepMS = Util.EnvironmentTickCount();
1671
1605 if (tmpMS > 0) 1672 if (tmpMS > 0)
1606 {
1607 Thread.Sleep(tmpMS); 1673 Thread.Sleep(tmpMS);
1608 spareMS += tmpMS;
1609 }
1610
1611 frameMS = Util.EnvironmentTickCountSubtract(maintc);
1612 maintc = Util.EnvironmentTickCount();
1613 1674
1614 otherMS = tempOnRezMS + eventMS + backupMS + terrainMS + landMS; 1675 sleepMS = Util.EnvironmentTickCountSubtract(sleepMS);
1676 frameMS = Util.EnvironmentTickCountSubtract(framestart);
1677 StatsReporter.addSleepMS(sleepMS);
1678 StatsReporter.addFrameMS(frameMS);
1615 1679
1616 // if (Frame%m_update_avatars == 0) 1680 // if (Frame%m_update_avatars == 0)
1617 // UpdateInWorldTime(); 1681 // UpdateInWorldTime();
1618 StatsReporter.AddPhysicsFPS(physicsFPS);
1619 StatsReporter.AddTimeDilation(TimeDilation);
1620 StatsReporter.AddFPS(1);
1621 1682
1622 StatsReporter.addFrameMS(frameMS);
1623 StatsReporter.addAgentMS(agentMS);
1624 StatsReporter.addPhysicsMS(physicsMS + physicsMS2);
1625 StatsReporter.addOtherMS(otherMS);
1626 StatsReporter.AddSpareMS(spareMS);
1627 StatsReporter.addScriptLines(m_sceneGraph.GetScriptLPS());
1628 1683
1629 // Optionally warn if a frame takes double the amount of time that it should. 1684 // Optionally warn if a frame takes double the amount of time that it should.
1630 if (DebugUpdates 1685 if (DebugUpdates
@@ -1652,9 +1707,9 @@ namespace OpenSim.Region.Framework.Scenes
1652 1707
1653 private void CheckAtTargets() 1708 private void CheckAtTargets()
1654 { 1709 {
1655 Dictionary<UUID, SceneObjectGroup>.ValueCollection objs; 1710 List<SceneObjectGroup> objs = new List<SceneObjectGroup>();
1656 lock (m_groupsWithTargets) 1711 lock (m_groupsWithTargets)
1657 objs = m_groupsWithTargets.Values; 1712 objs = new List<SceneObjectGroup>(m_groupsWithTargets.Values);
1658 1713
1659 foreach (SceneObjectGroup entry in objs) 1714 foreach (SceneObjectGroup entry in objs)
1660 entry.checkAtTargets(); 1715 entry.checkAtTargets();
@@ -1735,7 +1790,7 @@ namespace OpenSim.Region.Framework.Scenes
1735 msg.fromAgentName = "Server"; 1790 msg.fromAgentName = "Server";
1736 msg.dialog = (byte)19; // Object msg 1791 msg.dialog = (byte)19; // Object msg
1737 msg.fromGroup = false; 1792 msg.fromGroup = false;
1738 msg.offline = (byte)0; 1793 msg.offline = (byte)1;
1739 msg.ParentEstateID = RegionInfo.EstateSettings.ParentEstateID; 1794 msg.ParentEstateID = RegionInfo.EstateSettings.ParentEstateID;
1740 msg.Position = Vector3.Zero; 1795 msg.Position = Vector3.Zero;
1741 msg.RegionID = RegionInfo.RegionID.Guid; 1796 msg.RegionID = RegionInfo.RegionID.Guid;
@@ -1957,6 +2012,19 @@ namespace OpenSim.Region.Framework.Scenes
1957 EventManager.TriggerPrimsLoaded(this); 2012 EventManager.TriggerPrimsLoaded(this);
1958 } 2013 }
1959 2014
2015 public bool SuportsRayCastFiltered()
2016 {
2017 if (PhysicsScene == null)
2018 return false;
2019 return PhysicsScene.SuportsRaycastWorldFiltered();
2020 }
2021
2022 public object RayCastFiltered(Vector3 position, Vector3 direction, float length, int Count, RayFilterFlags filter)
2023 {
2024 if (PhysicsScene == null)
2025 return null;
2026 return PhysicsScene.RaycastWorld(position, direction, length, Count,filter);
2027 }
1960 2028
1961 /// <summary> 2029 /// <summary>
1962 /// Gets a new rez location based on the raycast and the size of the object that is being rezzed. 2030 /// Gets a new rez location based on the raycast and the size of the object that is being rezzed.
@@ -1973,14 +2041,24 @@ namespace OpenSim.Region.Framework.Scenes
1973 /// <returns></returns> 2041 /// <returns></returns>
1974 public Vector3 GetNewRezLocation(Vector3 RayStart, Vector3 RayEnd, UUID RayTargetID, Quaternion rot, byte bypassRayCast, byte RayEndIsIntersection, bool frontFacesOnly, Vector3 scale, bool FaceCenter) 2042 public Vector3 GetNewRezLocation(Vector3 RayStart, Vector3 RayEnd, UUID RayTargetID, Quaternion rot, byte bypassRayCast, byte RayEndIsIntersection, bool frontFacesOnly, Vector3 scale, bool FaceCenter)
1975 { 2043 {
2044
2045 float wheight = (float)RegionInfo.RegionSettings.WaterHeight;
2046 Vector3 wpos = Vector3.Zero;
2047 // Check for water surface intersection from above
2048 if ( (RayStart.Z > wheight) && (RayEnd.Z < wheight) )
2049 {
2050 float ratio = (RayStart.Z - wheight) / (RayStart.Z - RayEnd.Z);
2051 wpos.X = RayStart.X - (ratio * (RayStart.X - RayEnd.X));
2052 wpos.Y = RayStart.Y - (ratio * (RayStart.Y - RayEnd.Y));
2053 wpos.Z = wheight;
2054 }
2055
1976 Vector3 pos = Vector3.Zero; 2056 Vector3 pos = Vector3.Zero;
1977 if (RayEndIsIntersection == (byte)1) 2057 if (RayEndIsIntersection == (byte)1)
1978 { 2058 {
1979 pos = RayEnd; 2059 pos = RayEnd;
1980 return pos;
1981 } 2060 }
1982 2061 else if (RayTargetID != UUID.Zero)
1983 if (RayTargetID != UUID.Zero)
1984 { 2062 {
1985 SceneObjectPart target = GetSceneObjectPart(RayTargetID); 2063 SceneObjectPart target = GetSceneObjectPart(RayTargetID);
1986 2064
@@ -2002,7 +2080,7 @@ namespace OpenSim.Region.Framework.Scenes
2002 EntityIntersection ei = target.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, FaceCenter); 2080 EntityIntersection ei = target.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, FaceCenter);
2003 2081
2004 // Un-comment out the following line to Get Raytrace results printed to the console. 2082 // Un-comment out the following line to Get Raytrace results printed to the console.
2005 // m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString()); 2083 // m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
2006 float ScaleOffset = 0.5f; 2084 float ScaleOffset = 0.5f;
2007 2085
2008 // If we hit something 2086 // If we hit something
@@ -2025,13 +2103,10 @@ namespace OpenSim.Region.Framework.Scenes
2025 //pos.Z -= 0.25F; 2103 //pos.Z -= 0.25F;
2026 2104
2027 } 2105 }
2028
2029 return pos;
2030 } 2106 }
2031 else 2107 else
2032 { 2108 {
2033 // We don't have a target here, so we're going to raytrace all the objects in the scene. 2109 // We don't have a target here, so we're going to raytrace all the objects in the scene.
2034
2035 EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection), true, false); 2110 EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection), true, false);
2036 2111
2037 // Un-comment the following line to print the raytrace results to the console. 2112 // Un-comment the following line to print the raytrace results to the console.
@@ -2040,13 +2115,12 @@ namespace OpenSim.Region.Framework.Scenes
2040 if (ei.HitTF) 2115 if (ei.HitTF)
2041 { 2116 {
2042 pos = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z); 2117 pos = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
2043 } else 2118 }
2119 else
2044 { 2120 {
2045 // fall back to our stupid functionality 2121 // fall back to our stupid functionality
2046 pos = RayEnd; 2122 pos = RayEnd;
2047 } 2123 }
2048
2049 return pos;
2050 } 2124 }
2051 } 2125 }
2052 else 2126 else
@@ -2057,8 +2131,12 @@ namespace OpenSim.Region.Framework.Scenes
2057 //increase height so its above the ground. 2131 //increase height so its above the ground.
2058 //should be getting the normal of the ground at the rez point and using that? 2132 //should be getting the normal of the ground at the rez point and using that?
2059 pos.Z += scale.Z / 2f; 2133 pos.Z += scale.Z / 2f;
2060 return pos; 2134// return pos;
2061 } 2135 }
2136
2137 // check against posible water intercept
2138 if (wpos.Z > pos.Z) pos = wpos;
2139 return pos;
2062 } 2140 }
2063 2141
2064 2142
@@ -2147,7 +2225,10 @@ namespace OpenSim.Region.Framework.Scenes
2147 public bool AddRestoredSceneObject( 2225 public bool AddRestoredSceneObject(
2148 SceneObjectGroup sceneObject, bool attachToBackup, bool alreadyPersisted, bool sendClientUpdates) 2226 SceneObjectGroup sceneObject, bool attachToBackup, bool alreadyPersisted, bool sendClientUpdates)
2149 { 2227 {
2150 return m_sceneGraph.AddRestoredSceneObject(sceneObject, attachToBackup, alreadyPersisted, sendClientUpdates); 2228 bool result = m_sceneGraph.AddRestoredSceneObject(sceneObject, attachToBackup, alreadyPersisted, sendClientUpdates);
2229 if (result)
2230 sceneObject.IsDeleted = false;
2231 return result;
2151 } 2232 }
2152 2233
2153 /// <summary> 2234 /// <summary>
@@ -2239,6 +2320,15 @@ namespace OpenSim.Region.Framework.Scenes
2239 /// </summary> 2320 /// </summary>
2240 public void DeleteAllSceneObjects() 2321 public void DeleteAllSceneObjects()
2241 { 2322 {
2323 DeleteAllSceneObjects(false);
2324 }
2325
2326 /// <summary>
2327 /// Delete every object from the scene. This does not include attachments worn by avatars.
2328 /// </summary>
2329 public void DeleteAllSceneObjects(bool exceptNoCopy)
2330 {
2331 List<SceneObjectGroup> toReturn = new List<SceneObjectGroup>();
2242 lock (Entities) 2332 lock (Entities)
2243 { 2333 {
2244 EntityBase[] entities = Entities.GetEntities(); 2334 EntityBase[] entities = Entities.GetEntities();
@@ -2247,11 +2337,24 @@ namespace OpenSim.Region.Framework.Scenes
2247 if (e is SceneObjectGroup) 2337 if (e is SceneObjectGroup)
2248 { 2338 {
2249 SceneObjectGroup sog = (SceneObjectGroup)e; 2339 SceneObjectGroup sog = (SceneObjectGroup)e;
2250 if (!sog.IsAttachment) 2340 if (sog != null && !sog.IsAttachment)
2251 DeleteSceneObject((SceneObjectGroup)e, false); 2341 {
2342 if (!exceptNoCopy || ((sog.GetEffectivePermissions() & (uint)PermissionMask.Copy) != 0))
2343 {
2344 DeleteSceneObject((SceneObjectGroup)e, false);
2345 }
2346 else
2347 {
2348 toReturn.Add((SceneObjectGroup)e);
2349 }
2350 }
2252 } 2351 }
2253 } 2352 }
2254 } 2353 }
2354 if (toReturn.Count > 0)
2355 {
2356 returnObjects(toReturn.ToArray(), UUID.Zero);
2357 }
2255 } 2358 }
2256 2359
2257 /// <summary> 2360 /// <summary>
@@ -2286,6 +2389,12 @@ namespace OpenSim.Region.Framework.Scenes
2286 2389
2287 foreach (SceneObjectPart part in partList) 2390 foreach (SceneObjectPart part in partList)
2288 { 2391 {
2392 if (part.KeyframeMotion != null)
2393 {
2394 part.KeyframeMotion.Delete();
2395 part.KeyframeMotion = null;
2396 }
2397
2289 if (part.IsJoint() && ((part.Flags & PrimFlags.Physics) != 0)) 2398 if (part.IsJoint() && ((part.Flags & PrimFlags.Physics) != 0))
2290 { 2399 {
2291 PhysicsScene.RequestJointDeletion(part.Name); // FIXME: what if the name changed? 2400 PhysicsScene.RequestJointDeletion(part.Name); // FIXME: what if the name changed?
@@ -2303,6 +2412,8 @@ namespace OpenSim.Region.Framework.Scenes
2303 } 2412 }
2304 2413
2305 group.DeleteGroupFromScene(silent); 2414 group.DeleteGroupFromScene(silent);
2415 if (!silent)
2416 SendKillObject(new List<uint>() { group.LocalId });
2306 2417
2307// m_log.DebugFormat("[SCENE]: Exit DeleteSceneObject() for {0} {1}", group.Name, group.UUID); 2418// m_log.DebugFormat("[SCENE]: Exit DeleteSceneObject() for {0} {1}", group.Name, group.UUID);
2308 } 2419 }
@@ -2593,7 +2704,7 @@ namespace OpenSim.Region.Framework.Scenes
2593 // If the user is banned, we won't let any of their objects 2704 // If the user is banned, we won't let any of their objects
2594 // enter. Period. 2705 // enter. Period.
2595 // 2706 //
2596 if (RegionInfo.EstateSettings.IsBanned(newObject.OwnerID)) 2707 if (RegionInfo.EstateSettings.IsBanned(newObject.OwnerID, 36))
2597 { 2708 {
2598 m_log.InfoFormat("[INTERREGION]: Denied prim crossing for banned avatar {0}", newObject.OwnerID); 2709 m_log.InfoFormat("[INTERREGION]: Denied prim crossing for banned avatar {0}", newObject.OwnerID);
2599 return false; 2710 return false;
@@ -2601,6 +2712,8 @@ namespace OpenSim.Region.Framework.Scenes
2601 2712
2602 if (newPosition != Vector3.Zero) 2713 if (newPosition != Vector3.Zero)
2603 newObject.RootPart.GroupPosition = newPosition; 2714 newObject.RootPart.GroupPosition = newPosition;
2715 if (newObject.RootPart.KeyframeMotion != null)
2716 newObject.RootPart.KeyframeMotion.UpdateSceneObject(newObject);
2604 2717
2605 if (!AddSceneObject(newObject)) 2718 if (!AddSceneObject(newObject))
2606 { 2719 {
@@ -2645,6 +2758,23 @@ namespace OpenSim.Region.Framework.Scenes
2645 /// <returns>True if the SceneObjectGroup was added, False if it was not</returns> 2758 /// <returns>True if the SceneObjectGroup was added, False if it was not</returns>
2646 public bool AddSceneObject(SceneObjectGroup sceneObject) 2759 public bool AddSceneObject(SceneObjectGroup sceneObject)
2647 { 2760 {
2761 if (sceneObject.OwnerID == UUID.Zero)
2762 {
2763 m_log.ErrorFormat("[SCENE]: Owner ID for {0} was zero", sceneObject.UUID);
2764 return false;
2765 }
2766
2767 // If the user is banned, we won't let any of their objects
2768 // enter. Period.
2769 //
2770 int flags = GetUserFlags(sceneObject.OwnerID);
2771 if (RegionInfo.EstateSettings.IsBanned(sceneObject.OwnerID, flags))
2772 {
2773 m_log.InfoFormat("[INTERREGION]: Denied prim crossing for banned avatar {0}", sceneObject.OwnerID);
2774
2775 return false;
2776 }
2777
2648 // Force allocation of new LocalId 2778 // Force allocation of new LocalId
2649 // 2779 //
2650 SceneObjectPart[] parts = sceneObject.Parts; 2780 SceneObjectPart[] parts = sceneObject.Parts;
@@ -2678,16 +2808,27 @@ namespace OpenSim.Region.Framework.Scenes
2678 RootPrim.RemFlag(PrimFlags.TemporaryOnRez); 2808 RootPrim.RemFlag(PrimFlags.TemporaryOnRez);
2679 2809
2680 if (AttachmentsModule != null) 2810 if (AttachmentsModule != null)
2681 AttachmentsModule.AttachObject(sp, grp, 0, false, false); 2811 AttachmentsModule.AttachObject(sp, grp, 0, false, false, false);
2682 } 2812 }
2683 else 2813 else
2684 { 2814 {
2815 m_log.DebugFormat("[SCENE]: Attachment {0} arrived and scene presence was not found, setting to temp", sceneObject.UUID);
2685 RootPrim.RemFlag(PrimFlags.TemporaryOnRez); 2816 RootPrim.RemFlag(PrimFlags.TemporaryOnRez);
2686 RootPrim.AddFlag(PrimFlags.TemporaryOnRez); 2817 RootPrim.AddFlag(PrimFlags.TemporaryOnRez);
2687 } 2818 }
2819 if (sceneObject.OwnerID == UUID.Zero)
2820 {
2821 m_log.ErrorFormat("[SCENE]: Owner ID for {0} was zero after attachment processing. BUG!", sceneObject.UUID);
2822 return false;
2823 }
2688 } 2824 }
2689 else 2825 else
2690 { 2826 {
2827 if (sceneObject.OwnerID == UUID.Zero)
2828 {
2829 m_log.ErrorFormat("[SCENE]: Owner ID for non-attachment {0} was zero", sceneObject.UUID);
2830 return false;
2831 }
2691 AddRestoredSceneObject(sceneObject, true, false); 2832 AddRestoredSceneObject(sceneObject, true, false);
2692 } 2833 }
2693 2834
@@ -2704,6 +2845,24 @@ namespace OpenSim.Region.Framework.Scenes
2704 return 2; // StateSource.PrimCrossing 2845 return 2; // StateSource.PrimCrossing
2705 } 2846 }
2706 2847
2848 public int GetUserFlags(UUID user)
2849 {
2850 //Unfortunately the SP approach means that the value is cached until region is restarted
2851 /*
2852 ScenePresence sp;
2853 if (TryGetScenePresence(user, out sp))
2854 {
2855 return sp.UserFlags;
2856 }
2857 else
2858 {
2859 */
2860 UserAccount uac = UserAccountService.GetUserAccount(RegionInfo.ScopeID, user);
2861 if (uac == null)
2862 return 0;
2863 return uac.UserFlags;
2864 //}
2865 }
2707 #endregion 2866 #endregion
2708 2867
2709 #region Add/Remove Avatar Methods 2868 #region Add/Remove Avatar Methods
@@ -2717,7 +2876,7 @@ namespace OpenSim.Region.Framework.Scenes
2717 = (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin) != 0 2876 = (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin) != 0
2718 || (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaLogin) != 0; 2877 || (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaLogin) != 0;
2719 2878
2720// CheckHeartbeat(); 2879 CheckHeartbeat();
2721 2880
2722 ScenePresence sp = GetScenePresence(client.AgentId); 2881 ScenePresence sp = GetScenePresence(client.AgentId);
2723 2882
@@ -2771,7 +2930,15 @@ namespace OpenSim.Region.Framework.Scenes
2771 2930
2772 EventManager.TriggerOnNewClient(client); 2931 EventManager.TriggerOnNewClient(client);
2773 if (vialogin) 2932 if (vialogin)
2933 {
2774 EventManager.TriggerOnClientLogin(client); 2934 EventManager.TriggerOnClientLogin(client);
2935 // Send initial parcel data
2936/* this is done on TriggerOnNewClient by landmanegement respective event handler
2937 Vector3 pos = sp.AbsolutePosition;
2938 ILandObject land = LandChannel.GetLandObject(pos.X, pos.Y);
2939 land.SendLandUpdateToClient(client);
2940*/
2941 }
2775 2942
2776 return sp; 2943 return sp;
2777 } 2944 }
@@ -2860,19 +3027,14 @@ namespace OpenSim.Region.Framework.Scenes
2860 // and the scene presence and the client, if they exist 3027 // and the scene presence and the client, if they exist
2861 try 3028 try
2862 { 3029 {
2863 // We need to wait for the client to make UDP contact first. 3030 ScenePresence sp = GetScenePresence(agentID);
2864 // It's the UDP contact that creates the scene presence 3031
2865 ScenePresence sp = WaitGetScenePresence(agentID);
2866 if (sp != null) 3032 if (sp != null)
2867 { 3033 {
2868 PresenceService.LogoutAgent(sp.ControllingClient.SessionId); 3034 PresenceService.LogoutAgent(sp.ControllingClient.SessionId);
2869
2870 sp.ControllingClient.Close(); 3035 sp.ControllingClient.Close();
2871 } 3036 }
2872 else 3037
2873 {
2874 m_log.WarnFormat("[SCENE]: Could not find scene presence for {0}", agentID);
2875 }
2876 // BANG! SLASH! 3038 // BANG! SLASH!
2877 m_authenticateHandler.RemoveCircuit(agentID); 3039 m_authenticateHandler.RemoveCircuit(agentID);
2878 3040
@@ -2917,6 +3079,8 @@ namespace OpenSim.Region.Framework.Scenes
2917 client.OnUpdatePrimGroupPosition += m_sceneGraph.UpdatePrimGroupPosition; 3079 client.OnUpdatePrimGroupPosition += m_sceneGraph.UpdatePrimGroupPosition;
2918 client.OnUpdatePrimSinglePosition += m_sceneGraph.UpdatePrimSinglePosition; 3080 client.OnUpdatePrimSinglePosition += m_sceneGraph.UpdatePrimSinglePosition;
2919 3081
3082 client.onClientChangeObject += m_sceneGraph.ClientChangeObject;
3083
2920 client.OnUpdatePrimGroupRotation += m_sceneGraph.UpdatePrimGroupRotation; 3084 client.OnUpdatePrimGroupRotation += m_sceneGraph.UpdatePrimGroupRotation;
2921 client.OnUpdatePrimGroupMouseRotation += m_sceneGraph.UpdatePrimGroupRotation; 3085 client.OnUpdatePrimGroupMouseRotation += m_sceneGraph.UpdatePrimGroupRotation;
2922 client.OnUpdatePrimSingleRotation += m_sceneGraph.UpdatePrimSingleRotation; 3086 client.OnUpdatePrimSingleRotation += m_sceneGraph.UpdatePrimSingleRotation;
@@ -2973,6 +3137,7 @@ namespace OpenSim.Region.Framework.Scenes
2973 client.OnFetchInventory += m_asyncInventorySender.HandleFetchInventory; 3137 client.OnFetchInventory += m_asyncInventorySender.HandleFetchInventory;
2974 client.OnUpdateInventoryItem += UpdateInventoryItemAsset; 3138 client.OnUpdateInventoryItem += UpdateInventoryItemAsset;
2975 client.OnCopyInventoryItem += CopyInventoryItem; 3139 client.OnCopyInventoryItem += CopyInventoryItem;
3140 client.OnMoveItemsAndLeaveCopy += MoveInventoryItemsLeaveCopy;
2976 client.OnMoveInventoryItem += MoveInventoryItem; 3141 client.OnMoveInventoryItem += MoveInventoryItem;
2977 client.OnRemoveInventoryItem += RemoveInventoryItem; 3142 client.OnRemoveInventoryItem += RemoveInventoryItem;
2978 client.OnRemoveInventoryFolder += RemoveInventoryFolder; 3143 client.OnRemoveInventoryFolder += RemoveInventoryFolder;
@@ -3044,6 +3209,8 @@ namespace OpenSim.Region.Framework.Scenes
3044 client.OnUpdatePrimGroupPosition -= m_sceneGraph.UpdatePrimGroupPosition; 3209 client.OnUpdatePrimGroupPosition -= m_sceneGraph.UpdatePrimGroupPosition;
3045 client.OnUpdatePrimSinglePosition -= m_sceneGraph.UpdatePrimSinglePosition; 3210 client.OnUpdatePrimSinglePosition -= m_sceneGraph.UpdatePrimSinglePosition;
3046 3211
3212 client.onClientChangeObject -= m_sceneGraph.ClientChangeObject;
3213
3047 client.OnUpdatePrimGroupRotation -= m_sceneGraph.UpdatePrimGroupRotation; 3214 client.OnUpdatePrimGroupRotation -= m_sceneGraph.UpdatePrimGroupRotation;
3048 client.OnUpdatePrimGroupMouseRotation -= m_sceneGraph.UpdatePrimGroupRotation; 3215 client.OnUpdatePrimGroupMouseRotation -= m_sceneGraph.UpdatePrimGroupRotation;
3049 client.OnUpdatePrimSingleRotation -= m_sceneGraph.UpdatePrimSingleRotation; 3216 client.OnUpdatePrimSingleRotation -= m_sceneGraph.UpdatePrimSingleRotation;
@@ -3146,7 +3313,7 @@ namespace OpenSim.Region.Framework.Scenes
3146 /// </summary> 3313 /// </summary>
3147 /// <param name="agentId">The avatar's Unique ID</param> 3314 /// <param name="agentId">The avatar's Unique ID</param>
3148 /// <param name="client">The IClientAPI for the client</param> 3315 /// <param name="client">The IClientAPI for the client</param>
3149 public virtual void TeleportClientHome(UUID agentId, IClientAPI client) 3316 public virtual bool TeleportClientHome(UUID agentId, IClientAPI client)
3150 { 3317 {
3151 if (EntityTransferModule != null) 3318 if (EntityTransferModule != null)
3152 { 3319 {
@@ -3157,6 +3324,7 @@ namespace OpenSim.Region.Framework.Scenes
3157 m_log.DebugFormat("[SCENE]: Unable to teleport user home: no AgentTransferModule is active"); 3324 m_log.DebugFormat("[SCENE]: Unable to teleport user home: no AgentTransferModule is active");
3158 client.SendTeleportFailed("Unable to perform teleports on this simulator."); 3325 client.SendTeleportFailed("Unable to perform teleports on this simulator.");
3159 } 3326 }
3327 return false;
3160 } 3328 }
3161 3329
3162 /// <summary> 3330 /// <summary>
@@ -3266,6 +3434,16 @@ namespace OpenSim.Region.Framework.Scenes
3266 /// <param name="flags"></param> 3434 /// <param name="flags"></param>
3267 public virtual void SetHomeRezPoint(IClientAPI remoteClient, ulong regionHandle, Vector3 position, Vector3 lookAt, uint flags) 3435 public virtual void SetHomeRezPoint(IClientAPI remoteClient, ulong regionHandle, Vector3 position, Vector3 lookAt, uint flags)
3268 { 3436 {
3437 //Add half the avatar's height so that the user doesn't fall through prims
3438 ScenePresence presence;
3439 if (TryGetScenePresence(remoteClient.AgentId, out presence))
3440 {
3441 if (presence.Appearance != null)
3442 {
3443 position.Z = position.Z + (presence.Appearance.AvatarHeight / 2);
3444 }
3445 }
3446
3269 if (GridUserService != null && GridUserService.SetHome(remoteClient.AgentId.ToString(), RegionInfo.RegionID, position, lookAt)) 3447 if (GridUserService != null && GridUserService.SetHome(remoteClient.AgentId.ToString(), RegionInfo.RegionID, position, lookAt))
3270 // FUBAR ALERT: this needs to be "Home position set." so the viewer saves a home-screenshot. 3448 // FUBAR ALERT: this needs to be "Home position set." so the viewer saves a home-screenshot.
3271 m_dialogModule.SendAlertToUser(remoteClient, "Home position set."); 3449 m_dialogModule.SendAlertToUser(remoteClient, "Home position set.");
@@ -3382,6 +3560,7 @@ namespace OpenSim.Region.Framework.Scenes
3382 AgentTransactionsModule.RemoveAgentAssetTransactions(agentID); 3560 AgentTransactionsModule.RemoveAgentAssetTransactions(agentID);
3383 3561
3384 m_authenticateHandler.RemoveCircuit(avatar.ControllingClient.CircuitCode); 3562 m_authenticateHandler.RemoveCircuit(avatar.ControllingClient.CircuitCode);
3563 m_log.Debug("[Scene] The avatar has left the building");
3385 } 3564 }
3386 catch (Exception e) 3565 catch (Exception e)
3387 { 3566 {
@@ -3579,17 +3758,20 @@ namespace OpenSim.Region.Framework.Scenes
3579 "[SCENE]: Existing root scene presence detected for {0} {1} in {2} when connecting. Removing existing presence.", 3758 "[SCENE]: Existing root scene presence detected for {0} {1} in {2} when connecting. Removing existing presence.",
3580 sp.Name, sp.UUID, RegionInfo.RegionName); 3759 sp.Name, sp.UUID, RegionInfo.RegionName);
3581 3760
3582 sp.ControllingClient.Close(true); 3761 sp.ControllingClient.Close(true, true);
3583 sp = null; 3762 sp = null;
3584 } 3763 }
3585 3764
3586 ILandObject land = LandChannel.GetLandObject(agent.startpos.X, agent.startpos.Y);
3587 3765
3588 //On login test land permisions 3766 //On login test land permisions
3589 if (vialogin) 3767 if (vialogin)
3590 { 3768 {
3591 if (land != null && !TestLandRestrictions(agent, land, out reason)) 3769 IUserAccountCacheModule cache = RequestModuleInterface<IUserAccountCacheModule>();
3770 if (cache != null)
3771 cache.Remove(agent.firstname + " " + agent.lastname);
3772 if (!TestLandRestrictions(agent.AgentID, out reason, ref agent.startpos.X, ref agent.startpos.Y))
3592 { 3773 {
3774 m_log.DebugFormat("[CONNECTION BEGIN]: Denying access to {0} due to no land access", agent.AgentID.ToString());
3593 return false; 3775 return false;
3594 } 3776 }
3595 } 3777 }
@@ -3612,9 +3794,15 @@ namespace OpenSim.Region.Framework.Scenes
3612 3794
3613 try 3795 try
3614 { 3796 {
3615 if (!AuthorizeUser(agent, out reason)) 3797 // Always check estate if this is a login. Always
3616 return false; 3798 // check if banned regions are to be blacked out.
3617 } catch (Exception e) 3799 if (vialogin || (!m_seeIntoBannedRegion))
3800 {
3801 if (!AuthorizeUser(agent, out reason))
3802 return false;
3803 }
3804 }
3805 catch (Exception e)
3618 { 3806 {
3619 m_log.ErrorFormat( 3807 m_log.ErrorFormat(
3620 "[SCENE]: Exception authorizing user {0}{1}", e.Message, e.StackTrace); 3808 "[SCENE]: Exception authorizing user {0}{1}", e.Message, e.StackTrace);
@@ -3745,6 +3933,8 @@ namespace OpenSim.Region.Framework.Scenes
3745 } 3933 }
3746 3934
3747 // Honor parcel landing type and position. 3935 // Honor parcel landing type and position.
3936 /*
3937 ILandObject land = LandChannel.GetLandObject(agent.startpos.X, agent.startpos.Y);
3748 if (land != null) 3938 if (land != null)
3749 { 3939 {
3750 if (land.LandData.LandingType == (byte)1 && land.LandData.UserLocation != Vector3.Zero) 3940 if (land.LandData.LandingType == (byte)1 && land.LandData.UserLocation != Vector3.Zero)
@@ -3752,25 +3942,43 @@ namespace OpenSim.Region.Framework.Scenes
3752 agent.startpos = land.LandData.UserLocation; 3942 agent.startpos = land.LandData.UserLocation;
3753 } 3943 }
3754 } 3944 }
3945 */// This is now handled properly in ScenePresence.MakeRootAgent
3755 } 3946 }
3756 3947
3757 return true; 3948 return true;
3758 } 3949 }
3759 3950
3760 private bool TestLandRestrictions(AgentCircuitData agent, ILandObject land, out string reason) 3951 public bool TestLandRestrictions(UUID agentID, out string reason, ref float posX, ref float posY)
3761 { 3952 {
3762 bool banned = land.IsBannedFromLand(agent.AgentID); 3953 if (posX < 0)
3763 bool restricted = land.IsRestrictedFromLand(agent.AgentID); 3954 posX = 0;
3955 else if (posX >= 256)
3956 posX = 255.999f;
3957 if (posY < 0)
3958 posY = 0;
3959 else if (posY >= 256)
3960 posY = 255.999f;
3961
3962 reason = String.Empty;
3963 if (Permissions.IsGod(agentID))
3964 return true;
3965
3966 ILandObject land = LandChannel.GetLandObject(posX, posY);
3967 if (land == null)
3968 return false;
3969
3970 bool banned = land.IsBannedFromLand(agentID);
3971 bool restricted = land.IsRestrictedFromLand(agentID);
3764 3972
3765 if (banned || restricted) 3973 if (banned || restricted)
3766 { 3974 {
3767 ILandObject nearestParcel = GetNearestAllowedParcel(agent.AgentID, agent.startpos.X, agent.startpos.Y); 3975 ILandObject nearestParcel = GetNearestAllowedParcel(agentID, posX, posY);
3768 if (nearestParcel != null) 3976 if (nearestParcel != null)
3769 { 3977 {
3770 //Move agent to nearest allowed 3978 //Move agent to nearest allowed
3771 Vector3 newPosition = GetParcelCenterAtGround(nearestParcel); 3979 Vector3 newPosition = GetParcelCenterAtGround(nearestParcel);
3772 agent.startpos.X = newPosition.X; 3980 posX = newPosition.X;
3773 agent.startpos.Y = newPosition.Y; 3981 posY = newPosition.Y;
3774 } 3982 }
3775 else 3983 else
3776 { 3984 {
@@ -3832,7 +4040,7 @@ namespace OpenSim.Region.Framework.Scenes
3832 4040
3833 if (!m_strictAccessControl) return true; 4041 if (!m_strictAccessControl) return true;
3834 if (Permissions.IsGod(agent.AgentID)) return true; 4042 if (Permissions.IsGod(agent.AgentID)) return true;
3835 4043
3836 if (AuthorizationService != null) 4044 if (AuthorizationService != null)
3837 { 4045 {
3838 if (!AuthorizationService.IsAuthorizedForRegion( 4046 if (!AuthorizationService.IsAuthorizedForRegion(
@@ -3847,7 +4055,7 @@ namespace OpenSim.Region.Framework.Scenes
3847 4055
3848 if (RegionInfo.EstateSettings != null) 4056 if (RegionInfo.EstateSettings != null)
3849 { 4057 {
3850 if (RegionInfo.EstateSettings.IsBanned(agent.AgentID)) 4058 if (RegionInfo.EstateSettings.IsBanned(agent.AgentID, 0))
3851 { 4059 {
3852 m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user is on the banlist", 4060 m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user is on the banlist",
3853 agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName); 4061 agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
@@ -4037,6 +4245,15 @@ namespace OpenSim.Region.Framework.Scenes
4037 4245
4038 // XPTO: if this agent is not allowed here as root, always return false 4246 // XPTO: if this agent is not allowed here as root, always return false
4039 4247
4248 // We have to wait until the viewer contacts this region after receiving EAC.
4249 // That calls AddNewClient, which finally creates the ScenePresence
4250 int flags = GetUserFlags(cAgentData.AgentID);
4251 if (RegionInfo.EstateSettings.IsBanned(cAgentData.AgentID, flags))
4252 {
4253 m_log.DebugFormat("[SCENE]: Denying root agent entry to {0}: banned", cAgentData.AgentID);
4254 return false;
4255 }
4256
4040 // TODO: This check should probably be in QueryAccess(). 4257 // TODO: This check should probably be in QueryAccess().
4041 ILandObject nearestParcel = GetNearestAllowedParcel(cAgentData.AgentID, Constants.RegionSize / 2, Constants.RegionSize / 2); 4258 ILandObject nearestParcel = GetNearestAllowedParcel(cAgentData.AgentID, Constants.RegionSize / 2, Constants.RegionSize / 2);
4042 if (nearestParcel == null) 4259 if (nearestParcel == null)
@@ -4100,7 +4317,7 @@ namespace OpenSim.Region.Framework.Scenes
4100 /// <param name='agentID'></param> 4317 /// <param name='agentID'></param>
4101 protected virtual ScenePresence WaitGetScenePresence(UUID agentID) 4318 protected virtual ScenePresence WaitGetScenePresence(UUID agentID)
4102 { 4319 {
4103 int ntimes = 10; 4320 int ntimes = 30;
4104 ScenePresence sp = null; 4321 ScenePresence sp = null;
4105 while ((sp = GetScenePresence(agentID)) == null && (ntimes-- > 0)) 4322 while ((sp = GetScenePresence(agentID)) == null && (ntimes-- > 0))
4106 Thread.Sleep(1000); 4323 Thread.Sleep(1000);
@@ -4130,6 +4347,16 @@ namespace OpenSim.Region.Framework.Scenes
4130 return false; 4347 return false;
4131 } 4348 }
4132 4349
4350 public bool IncomingCloseAgent(UUID agentID)
4351 {
4352 return IncomingCloseAgent(agentID, false);
4353 }
4354
4355 public bool IncomingCloseChildAgent(UUID agentID)
4356 {
4357 return IncomingCloseAgent(agentID, true);
4358 }
4359
4133 /// <summary> 4360 /// <summary>
4134 /// Tell a single agent to disconnect from the region. 4361 /// Tell a single agent to disconnect from the region.
4135 /// </summary> 4362 /// </summary>
@@ -4145,7 +4372,7 @@ namespace OpenSim.Region.Framework.Scenes
4145 ScenePresence presence = m_sceneGraph.GetScenePresence(agentID); 4372 ScenePresence presence = m_sceneGraph.GetScenePresence(agentID);
4146 if (presence != null) 4373 if (presence != null)
4147 { 4374 {
4148 presence.ControllingClient.Close(force); 4375 presence.ControllingClient.Close(true, force);
4149 return true; 4376 return true;
4150 } 4377 }
4151 4378
@@ -4793,35 +5020,81 @@ namespace OpenSim.Region.Framework.Scenes
4793 SimulationDataService.RemoveObject(uuid, RegionInfo.RegionID); 5020 SimulationDataService.RemoveObject(uuid, RegionInfo.RegionID);
4794 } 5021 }
4795 5022
4796 public int GetHealth() 5023 public int GetHealth(out int flags, out string message)
4797 { 5024 {
4798 // Returns: 5025 // Returns:
4799 // 1 = sim is up and accepting http requests. The heartbeat has 5026 // 1 = sim is up and accepting http requests. The heartbeat has
4800 // stopped and the sim is probably locked up, but a remote 5027 // stopped and the sim is probably locked up, but a remote
4801 // admin restart may succeed 5028 // admin restart may succeed
4802 // 5029 //
4803 // 2 = Sim is up and the heartbeat is running. The sim is likely 5030 // 2 = Sim is up and the heartbeat is running. The sim is likely
4804 // usable for people within and logins _may_ work 5031 // usable for people within
5032 //
5033 // 3 = Sim is up and one packet thread is running. Sim is
5034 // unstable and will not accept new logins
4805 // 5035 //
4806 // 3 = We have seen a new user enter within the past 4 minutes 5036 // 4 = Sim is up and both packet threads are running. Sim is
5037 // likely usable
5038 //
5039 // 5 = We have seen a new user enter within the past 4 minutes
4807 // which can be seen as positive confirmation of sim health 5040 // which can be seen as positive confirmation of sim health
4808 // 5041 //
5042
5043 flags = 0;
5044 message = String.Empty;
5045
5046 CheckHeartbeat();
5047
5048 if (m_firstHeartbeat || (m_lastIncoming == 0 && m_lastOutgoing == 0))
5049 {
5050 // We're still starting
5051 // 0 means "in startup", it can't happen another way, since
5052 // to get here, we must be able to accept http connections
5053 return 0;
5054 }
5055
4809 int health=1; // Start at 1, means we're up 5056 int health=1; // Start at 1, means we're up
4810 5057
4811 if ((Util.EnvironmentTickCountSubtract(m_lastFrameTick)) < 1000) 5058 if ((Util.EnvironmentTickCountSubtract(m_lastFrameTick)) < 1000)
4812 health += 1; 5059 {
5060 health+=1;
5061 flags |= 1;
5062 }
5063
5064 if (Util.EnvironmentTickCountSubtract(m_lastIncoming) < 1000)
5065 {
5066 health+=1;
5067 flags |= 2;
5068 }
5069
5070 if (Util.EnvironmentTickCountSubtract(m_lastOutgoing) < 1000)
5071 {
5072 health+=1;
5073 flags |= 4;
5074 }
4813 else 5075 else
5076 {
5077int pid = System.Diagnostics.Process.GetCurrentProcess().Id;
5078System.Diagnostics.Process proc = new System.Diagnostics.Process();
5079proc.EnableRaisingEvents=false;
5080proc.StartInfo.FileName = "/bin/kill";
5081proc.StartInfo.Arguments = "-QUIT " + pid.ToString();
5082proc.Start();
5083proc.WaitForExit();
5084Thread.Sleep(1000);
5085Environment.Exit(1);
5086 }
5087
5088 if (flags != 7)
4814 return health; 5089 return health;
4815 5090
4816 // A login in the last 4 mins? We can't be doing too badly 5091 // A login in the last 4 mins? We can't be doing too badly
4817 // 5092 //
4818 if ((Util.EnvironmentTickCountSubtract(m_LastLogin)) < 240000) 5093 if (Util.EnvironmentTickCountSubtract(m_LastLogin) < 240000)
4819 health++; 5094 health++;
4820 else 5095 else
4821 return health; 5096 return health;
4822 5097
4823// CheckHeartbeat();
4824
4825 return health; 5098 return health;
4826 } 5099 }
4827 5100
@@ -4909,7 +5182,7 @@ namespace OpenSim.Region.Framework.Scenes
4909 bool wasUsingPhysics = ((jointProxyObject.Flags & PrimFlags.Physics) != 0); 5182 bool wasUsingPhysics = ((jointProxyObject.Flags & PrimFlags.Physics) != 0);
4910 if (wasUsingPhysics) 5183 if (wasUsingPhysics)
4911 { 5184 {
4912 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 5185 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
4913 } 5186 }
4914 } 5187 }
4915 5188
@@ -5008,14 +5281,14 @@ namespace OpenSim.Region.Framework.Scenes
5008 return (((vsn.X * xdiff) + (vsn.Y * ydiff)) / (-1 * vsn.Z)) + p0.Z; 5281 return (((vsn.X * xdiff) + (vsn.Y * ydiff)) / (-1 * vsn.Z)) + p0.Z;
5009 } 5282 }
5010 5283
5011// private void CheckHeartbeat() 5284 private void CheckHeartbeat()
5012// { 5285 {
5013// if (m_firstHeartbeat) 5286 if (m_firstHeartbeat)
5014// return; 5287 return;
5015// 5288
5016// if (Util.EnvironmentTickCountSubtract(m_lastFrameTick) > 2000) 5289 if ((Util.EnvironmentTickCountSubtract(m_lastFrameTick)) > 5000)
5017// StartTimer(); 5290 Start();
5018// } 5291 }
5019 5292
5020 public override ISceneObject DeserializeObject(string representation) 5293 public override ISceneObject DeserializeObject(string representation)
5021 { 5294 {
@@ -5027,9 +5300,14 @@ namespace OpenSim.Region.Framework.Scenes
5027 get { return m_allowScriptCrossings; } 5300 get { return m_allowScriptCrossings; }
5028 } 5301 }
5029 5302
5030 public Vector3? GetNearestAllowedPosition(ScenePresence avatar) 5303 public Vector3 GetNearestAllowedPosition(ScenePresence avatar)
5031 { 5304 {
5032 ILandObject nearestParcel = GetNearestAllowedParcel(avatar.UUID, avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y); 5305 return GetNearestAllowedPosition(avatar, null);
5306 }
5307
5308 public Vector3 GetNearestAllowedPosition(ScenePresence avatar, ILandObject excludeParcel)
5309 {
5310 ILandObject nearestParcel = GetNearestAllowedParcel(avatar.UUID, avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y, excludeParcel);
5033 5311
5034 if (nearestParcel != null) 5312 if (nearestParcel != null)
5035 { 5313 {
@@ -5038,10 +5316,7 @@ namespace OpenSim.Region.Framework.Scenes
5038 Vector3? nearestPoint = GetNearestPointInParcelAlongDirectionFromPoint(avatar.AbsolutePosition, dir, nearestParcel); 5316 Vector3? nearestPoint = GetNearestPointInParcelAlongDirectionFromPoint(avatar.AbsolutePosition, dir, nearestParcel);
5039 if (nearestPoint != null) 5317 if (nearestPoint != null)
5040 { 5318 {
5041// m_log.DebugFormat( 5319 Debug.WriteLine("Found a sane previous position based on velocity, sending them to: " + nearestPoint.ToString());
5042// "[SCENE]: Found a sane previous position based on velocity for {0}, sending them to {1} in {2}",
5043// avatar.Name, nearestPoint, nearestParcel.LandData.Name);
5044
5045 return nearestPoint.Value; 5320 return nearestPoint.Value;
5046 } 5321 }
5047 5322
@@ -5051,17 +5326,20 @@ namespace OpenSim.Region.Framework.Scenes
5051 nearestPoint = GetNearestPointInParcelAlongDirectionFromPoint(avatar.AbsolutePosition, dir, nearestParcel); 5326 nearestPoint = GetNearestPointInParcelAlongDirectionFromPoint(avatar.AbsolutePosition, dir, nearestParcel);
5052 if (nearestPoint != null) 5327 if (nearestPoint != null)
5053 { 5328 {
5054// m_log.DebugFormat( 5329 Debug.WriteLine("They had a zero velocity, sending them to: " + nearestPoint.ToString());
5055// "[SCENE]: {0} had a zero velocity, sending them to {1}", avatar.Name, nearestPoint);
5056
5057 return nearestPoint.Value; 5330 return nearestPoint.Value;
5058 } 5331 }
5059 5332
5060 //Ultimate backup if we have no idea where they are 5333 ILandObject dest = LandChannel.GetLandObject(avatar.lastKnownAllowedPosition.X, avatar.lastKnownAllowedPosition.Y);
5061// m_log.DebugFormat( 5334 if (dest != excludeParcel)
5062// "[SCENE]: No idea where {0} is, sending them to {1}", avatar.Name, avatar.lastKnownAllowedPosition); 5335 {
5336 // Ultimate backup if we have no idea where they are and
5337 // the last allowed position was in another parcel
5338 Debug.WriteLine("Have no idea where they are, sending them to: " + avatar.lastKnownAllowedPosition.ToString());
5339 return avatar.lastKnownAllowedPosition;
5340 }
5063 5341
5064 return avatar.lastKnownAllowedPosition; 5342 // else fall through to region edge
5065 } 5343 }
5066 5344
5067 //Go to the edge, this happens in teleporting to a region with no available parcels 5345 //Go to the edge, this happens in teleporting to a region with no available parcels
@@ -5095,13 +5373,18 @@ namespace OpenSim.Region.Framework.Scenes
5095 5373
5096 public ILandObject GetNearestAllowedParcel(UUID avatarId, float x, float y) 5374 public ILandObject GetNearestAllowedParcel(UUID avatarId, float x, float y)
5097 { 5375 {
5376 return GetNearestAllowedParcel(avatarId, x, y, null);
5377 }
5378
5379 public ILandObject GetNearestAllowedParcel(UUID avatarId, float x, float y, ILandObject excludeParcel)
5380 {
5098 List<ILandObject> all = AllParcels(); 5381 List<ILandObject> all = AllParcels();
5099 float minParcelDistance = float.MaxValue; 5382 float minParcelDistance = float.MaxValue;
5100 ILandObject nearestParcel = null; 5383 ILandObject nearestParcel = null;
5101 5384
5102 foreach (var parcel in all) 5385 foreach (var parcel in all)
5103 { 5386 {
5104 if (!parcel.IsEitherBannedOrRestricted(avatarId)) 5387 if (!parcel.IsEitherBannedOrRestricted(avatarId) && parcel != excludeParcel)
5105 { 5388 {
5106 float parcelDistance = GetParcelDistancefromPoint(parcel, x, y); 5389 float parcelDistance = GetParcelDistancefromPoint(parcel, x, y);
5107 if (parcelDistance < minParcelDistance) 5390 if (parcelDistance < minParcelDistance)
@@ -5343,7 +5626,55 @@ namespace OpenSim.Region.Framework.Scenes
5343 mapModule.GenerateMaptile(); 5626 mapModule.GenerateMaptile();
5344 } 5627 }
5345 5628
5346 private void RegenerateMaptileAndReregister(object sender, ElapsedEventArgs e) 5629// public void CleanDroppedAttachments()
5630// {
5631// List<SceneObjectGroup> objectsToDelete =
5632// new List<SceneObjectGroup>();
5633//
5634// lock (m_cleaningAttachments)
5635// {
5636// ForEachSOG(delegate (SceneObjectGroup grp)
5637// {
5638// if (grp.RootPart.Shape.PCode == 0 && grp.RootPart.Shape.State != 0 && (!objectsToDelete.Contains(grp)))
5639// {
5640// UUID agentID = grp.OwnerID;
5641// if (agentID == UUID.Zero)
5642// {
5643// objectsToDelete.Add(grp);
5644// return;
5645// }
5646//
5647// ScenePresence sp = GetScenePresence(agentID);
5648// if (sp == null)
5649// {
5650// objectsToDelete.Add(grp);
5651// return;
5652// }
5653// }
5654// });
5655// }
5656//
5657// foreach (SceneObjectGroup grp in objectsToDelete)
5658// {
5659// m_log.InfoFormat("[SCENE]: Deleting dropped attachment {0} of user {1}", grp.UUID, grp.OwnerID);
5660// DeleteSceneObject(grp, true);
5661// }
5662// }
5663
5664 public void ThreadAlive(int threadCode)
5665 {
5666 switch(threadCode)
5667 {
5668 case 1: // Incoming
5669 m_lastIncoming = Util.EnvironmentTickCount();
5670 break;
5671 case 2: // Incoming
5672 m_lastOutgoing = Util.EnvironmentTickCount();
5673 break;
5674 }
5675 }
5676
5677 public void RegenerateMaptileAndReregister(object sender, ElapsedEventArgs e)
5347 { 5678 {
5348 RegenerateMaptile(); 5679 RegenerateMaptile();
5349 5680
@@ -5371,6 +5702,8 @@ namespace OpenSim.Region.Framework.Scenes
5371 /// <returns></returns> 5702 /// <returns></returns>
5372 public bool QueryAccess(UUID agentID, Vector3 position, out string reason) 5703 public bool QueryAccess(UUID agentID, Vector3 position, out string reason)
5373 { 5704 {
5705 reason = "You are banned from the region";
5706
5374 if (EntityTransferModule.IsInTransit(agentID)) 5707 if (EntityTransferModule.IsInTransit(agentID))
5375 { 5708 {
5376 reason = "Agent is still in transit from this region"; 5709 reason = "Agent is still in transit from this region";
@@ -5382,6 +5715,12 @@ namespace OpenSim.Region.Framework.Scenes
5382 return false; 5715 return false;
5383 } 5716 }
5384 5717
5718 if (Permissions.IsGod(agentID))
5719 {
5720 reason = String.Empty;
5721 return true;
5722 }
5723
5385 // FIXME: Root agent count is currently known to be inaccurate. This forces a recount before we check. 5724 // FIXME: Root agent count is currently known to be inaccurate. This forces a recount before we check.
5386 // However, the long term fix is to make sure root agent count is always accurate. 5725 // However, the long term fix is to make sure root agent count is always accurate.
5387 m_sceneGraph.RecalculateStats(); 5726 m_sceneGraph.RecalculateStats();
@@ -5402,6 +5741,41 @@ namespace OpenSim.Region.Framework.Scenes
5402 } 5741 }
5403 } 5742 }
5404 5743
5744 ScenePresence presence = GetScenePresence(agentID);
5745 IClientAPI client = null;
5746 AgentCircuitData aCircuit = null;
5747
5748 if (presence != null)
5749 {
5750 client = presence.ControllingClient;
5751 if (client != null)
5752 aCircuit = client.RequestClientInfo();
5753 }
5754
5755 // We may be called before there is a presence or a client.
5756 // Fake AgentCircuitData to keep IAuthorizationModule smiling
5757 if (client == null)
5758 {
5759 aCircuit = new AgentCircuitData();
5760 aCircuit.AgentID = agentID;
5761 aCircuit.firstname = String.Empty;
5762 aCircuit.lastname = String.Empty;
5763 }
5764
5765 try
5766 {
5767 if (!AuthorizeUser(aCircuit, out reason))
5768 {
5769 // m_log.DebugFormat("[SCENE]: Denying access for {0}", agentID);
5770 return false;
5771 }
5772 }
5773 catch (Exception e)
5774 {
5775 m_log.DebugFormat("[SCENE]: Exception authorizing agent: {0} "+ e.StackTrace, e.Message);
5776 return false;
5777 }
5778
5405 if (position == Vector3.Zero) // Teleport 5779 if (position == Vector3.Zero) // Teleport
5406 { 5780 {
5407 if (!RegionInfo.EstateSettings.AllowDirectTeleport) 5781 if (!RegionInfo.EstateSettings.AllowDirectTeleport)
@@ -5430,13 +5804,46 @@ namespace OpenSim.Region.Framework.Scenes
5430 } 5804 }
5431 } 5805 }
5432 } 5806 }
5807
5808 float posX = 128.0f;
5809 float posY = 128.0f;
5810
5811 if (!TestLandRestrictions(agentID, out reason, ref posX, ref posY))
5812 {
5813 // m_log.DebugFormat("[SCENE]: Denying {0} because they are banned on all parcels", agentID);
5814 return false;
5815 }
5816 }
5817 else // Walking
5818 {
5819 ILandObject land = LandChannel.GetLandObject(position.X, position.Y);
5820 if (land == null)
5821 return false;
5822
5823 bool banned = land.IsBannedFromLand(agentID);
5824 bool restricted = land.IsRestrictedFromLand(agentID);
5825
5826 if (banned || restricted)
5827 return false;
5433 } 5828 }
5434 5829
5435 reason = String.Empty; 5830 reason = String.Empty;
5436 return true; 5831 return true;
5437 } 5832 }
5438 5833
5439 /// <summary> 5834 public void StartTimerWatchdog()
5835 {
5836 m_timerWatchdog.Interval = 1000;
5837 m_timerWatchdog.Elapsed += TimerWatchdog;
5838 m_timerWatchdog.AutoReset = true;
5839 m_timerWatchdog.Start();
5840 }
5841
5842 public void TimerWatchdog(object sender, ElapsedEventArgs e)
5843 {
5844 CheckHeartbeat();
5845 }
5846
5440 /// This method deals with movement when an avatar is automatically moving (but this is distinct from the 5847 /// This method deals with movement when an avatar is automatically moving (but this is distinct from the
5441 /// autopilot that moves an avatar to a sit target!. 5848 /// autopilot that moves an avatar to a sit target!.
5442 /// </summary> 5849 /// </summary>
@@ -5515,6 +5922,11 @@ namespace OpenSim.Region.Framework.Scenes
5515 return m_SpawnPoint - 1; 5922 return m_SpawnPoint - 1;
5516 } 5923 }
5517 5924
5925 private void HandleGcCollect(string module, string[] args)
5926 {
5927 GC.Collect();
5928 }
5929
5518 // Wrappers to get physics modules retrieve assets. Has to be done this way 5930 // Wrappers to get physics modules retrieve assets. Has to be done this way
5519 // because we can't assign the asset service to physics directly - at the 5931 // because we can't assign the asset service to physics directly - at the
5520 // time physics are instantiated it's not registered but it will be by 5932 // time physics are instantiated it's not registered but it will be by
diff --git a/OpenSim/Region/Framework/Scenes/SceneBase.cs b/OpenSim/Region/Framework/Scenes/SceneBase.cs
index b87a38a..7c8bd88 100644
--- a/OpenSim/Region/Framework/Scenes/SceneBase.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneBase.cs
@@ -149,7 +149,6 @@ namespace OpenSim.Region.Framework.Scenes
149 149
150 protected ulong m_regionHandle; 150 protected ulong m_regionHandle;
151 protected string m_regionName; 151 protected string m_regionName;
152 protected RegionInfo m_regInfo;
153 152
154 public ITerrainChannel Heightmap; 153 public ITerrainChannel Heightmap;
155 154
@@ -174,6 +173,8 @@ namespace OpenSim.Region.Framework.Scenes
174 get { return m_permissions; } 173 get { return m_permissions; }
175 } 174 }
176 175
176 protected string m_datastore;
177
177 /* Used by the loadbalancer plugin on GForge */ 178 /* Used by the loadbalancer plugin on GForge */
178 protected RegionStatus m_regStatus; 179 protected RegionStatus m_regStatus;
179 public RegionStatus RegionStatus 180 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 209a770..c4b7b27 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)
@@ -1181,6 +1261,52 @@ namespace OpenSim.Region.Framework.Scenes
1181 1261
1182 #region Client Event handlers 1262 #region Client Event handlers
1183 1263
1264 protected internal void ClientChangeObject(uint localID, object odata, IClientAPI remoteClient)
1265 {
1266 SceneObjectPart part = GetSceneObjectPart(localID);
1267 ObjectChangeData data = (ObjectChangeData)odata;
1268
1269 if (part != null)
1270 {
1271 SceneObjectGroup grp = part.ParentGroup;
1272 if (grp != null)
1273 {
1274 if (m_parentScene.Permissions.CanEditObject(grp.UUID, remoteClient.AgentId))
1275 {
1276 // These two are exceptions SL makes in the interpretation
1277 // of the change flags. Must check them here because otherwise
1278 // the group flag (see below) would be lost
1279 if (data.change == ObjectChangeType.groupS)
1280 data.change = ObjectChangeType.primS;
1281 if (data.change == ObjectChangeType.groupPS)
1282 data.change = ObjectChangeType.primPS;
1283 part.StoreUndoState(data.change); // lets test only saving what we changed
1284 grp.doChangeObject(part, (ObjectChangeData)data);
1285 }
1286 else
1287 {
1288 // Is this any kind of group operation?
1289 if ((data.change & ObjectChangeType.Group) != 0)
1290 {
1291 // Is a move and/or rotation requested?
1292 if ((data.change & (ObjectChangeType.Position | ObjectChangeType.Rotation)) != 0)
1293 {
1294 // Are we allowed to move it?
1295 if (m_parentScene.Permissions.CanMoveObject(grp.UUID, remoteClient.AgentId))
1296 {
1297 // Strip all but move and rotation from request
1298 data.change &= (ObjectChangeType.Group | ObjectChangeType.Position | ObjectChangeType.Rotation);
1299
1300 part.StoreUndoState(data.change);
1301 grp.doChangeObject(part, (ObjectChangeData)data);
1302 }
1303 }
1304 }
1305 }
1306 }
1307 }
1308 }
1309
1184 /// <summary> 1310 /// <summary>
1185 /// Update the scale of an individual prim. 1311 /// Update the scale of an individual prim.
1186 /// </summary> 1312 /// </summary>
@@ -1195,7 +1321,17 @@ namespace OpenSim.Region.Framework.Scenes
1195 { 1321 {
1196 if (m_parentScene.Permissions.CanEditObject(part.ParentGroup.UUID, remoteClient.AgentId)) 1322 if (m_parentScene.Permissions.CanEditObject(part.ParentGroup.UUID, remoteClient.AgentId))
1197 { 1323 {
1324 bool physbuild = false;
1325 if (part.ParentGroup.RootPart.PhysActor != null)
1326 {
1327 part.ParentGroup.RootPart.PhysActor.Building = true;
1328 physbuild = true;
1329 }
1330
1198 part.Resize(scale); 1331 part.Resize(scale);
1332
1333 if (physbuild)
1334 part.ParentGroup.RootPart.PhysActor.Building = false;
1199 } 1335 }
1200 } 1336 }
1201 } 1337 }
@@ -1207,7 +1343,17 @@ namespace OpenSim.Region.Framework.Scenes
1207 { 1343 {
1208 if (m_parentScene.Permissions.CanEditObject(group.UUID, remoteClient.AgentId)) 1344 if (m_parentScene.Permissions.CanEditObject(group.UUID, remoteClient.AgentId))
1209 { 1345 {
1346 bool physbuild = false;
1347 if (group.RootPart.PhysActor != null)
1348 {
1349 group.RootPart.PhysActor.Building = true;
1350 physbuild = true;
1351 }
1352
1210 group.GroupResize(scale); 1353 group.GroupResize(scale);
1354
1355 if (physbuild)
1356 group.RootPart.PhysActor.Building = false;
1211 } 1357 }
1212 } 1358 }
1213 } 1359 }
@@ -1335,8 +1481,13 @@ namespace OpenSim.Region.Framework.Scenes
1335 { 1481 {
1336 if (group.IsAttachment || (group.RootPart.Shape.PCode == 9 && group.RootPart.Shape.State != 0)) 1482 if (group.IsAttachment || (group.RootPart.Shape.PCode == 9 && group.RootPart.Shape.State != 0))
1337 { 1483 {
1338 if (m_parentScene.AttachmentsModule != null) 1484 // Set the new attachment point data in the object
1339 m_parentScene.AttachmentsModule.UpdateAttachmentPosition(group, pos); 1485 byte attachmentPoint = group.GetAttachmentPoint();
1486 group.UpdateGroupPosition(pos);
1487 group.IsAttachment = false;
1488 group.AbsolutePosition = group.RootPart.AttachedPos;
1489 group.AttachmentPoint = attachmentPoint;
1490 group.HasGroupChanged = true;
1340 } 1491 }
1341 else 1492 else
1342 { 1493 {
@@ -1384,7 +1535,7 @@ namespace OpenSim.Region.Framework.Scenes
1384 /// <param name="SetPhantom"></param> 1535 /// <param name="SetPhantom"></param>
1385 /// <param name="remoteClient"></param> 1536 /// <param name="remoteClient"></param>
1386 protected internal void UpdatePrimFlags( 1537 protected internal void UpdatePrimFlags(
1387 uint localID, bool UsePhysics, bool SetTemporary, bool SetPhantom, IClientAPI remoteClient) 1538 uint localID, bool UsePhysics, bool SetTemporary, bool SetPhantom, ExtraPhysicsData PhysData, IClientAPI remoteClient)
1388 { 1539 {
1389 SceneObjectGroup group = GetGroupByPrim(localID); 1540 SceneObjectGroup group = GetGroupByPrim(localID);
1390 if (group != null) 1541 if (group != null)
@@ -1392,7 +1543,28 @@ namespace OpenSim.Region.Framework.Scenes
1392 if (m_parentScene.Permissions.CanEditObject(group.UUID, remoteClient.AgentId)) 1543 if (m_parentScene.Permissions.CanEditObject(group.UUID, remoteClient.AgentId))
1393 { 1544 {
1394 // VolumeDetect can't be set via UI and will always be off when a change is made there 1545 // VolumeDetect can't be set via UI and will always be off when a change is made there
1395 group.UpdatePrimFlags(localID, UsePhysics, SetTemporary, SetPhantom, false); 1546 // now only change volume dtc if phantom off
1547
1548 if (PhysData.PhysShapeType == PhysShapeType.invalid) // check for extraPhysics data
1549 {
1550 bool vdtc;
1551 if (SetPhantom) // if phantom keep volumedtc
1552 vdtc = group.RootPart.VolumeDetectActive;
1553 else // else turn it off
1554 vdtc = false;
1555
1556 group.UpdatePrimFlags(localID, UsePhysics, SetTemporary, SetPhantom, vdtc);
1557 }
1558 else
1559 {
1560 SceneObjectPart part = GetSceneObjectPart(localID);
1561 if (part != null)
1562 {
1563 part.UpdateExtraPhysics(PhysData);
1564 if (part.UpdatePhysRequired)
1565 remoteClient.SendPartPhysicsProprieties(part);
1566 }
1567 }
1396 } 1568 }
1397 } 1569 }
1398 } 1570 }
@@ -1536,6 +1708,7 @@ namespace OpenSim.Region.Framework.Scenes
1536 { 1708 {
1537 part.Material = Convert.ToByte(material); 1709 part.Material = Convert.ToByte(material);
1538 group.HasGroupChanged = true; 1710 group.HasGroupChanged = true;
1711 remoteClient.SendPartPhysicsProprieties(part);
1539 } 1712 }
1540 } 1713 }
1541 } 1714 }
@@ -1600,6 +1773,12 @@ namespace OpenSim.Region.Framework.Scenes
1600 /// <param name="childPrims"></param> 1773 /// <param name="childPrims"></param>
1601 protected internal void LinkObjects(SceneObjectPart root, List<SceneObjectPart> children) 1774 protected internal void LinkObjects(SceneObjectPart root, List<SceneObjectPart> children)
1602 { 1775 {
1776 if (root.KeyframeMotion != null)
1777 {
1778 root.KeyframeMotion.Stop();
1779 root.KeyframeMotion = null;
1780 }
1781
1603 SceneObjectGroup parentGroup = root.ParentGroup; 1782 SceneObjectGroup parentGroup = root.ParentGroup;
1604 if (parentGroup == null) return; 1783 if (parentGroup == null) return;
1605 1784
@@ -1608,8 +1787,10 @@ namespace OpenSim.Region.Framework.Scenes
1608 return; 1787 return;
1609 1788
1610 Monitor.Enter(m_updateLock); 1789 Monitor.Enter(m_updateLock);
1790
1611 try 1791 try
1612 { 1792 {
1793
1613 List<SceneObjectGroup> childGroups = new List<SceneObjectGroup>(); 1794 List<SceneObjectGroup> childGroups = new List<SceneObjectGroup>();
1614 1795
1615 // We do this in reverse to get the link order of the prims correct 1796 // We do this in reverse to get the link order of the prims correct
@@ -1624,9 +1805,13 @@ namespace OpenSim.Region.Framework.Scenes
1624 // Make sure no child prim is set for sale 1805 // Make sure no child prim is set for sale
1625 // So that, on delink, no prims are unwittingly 1806 // So that, on delink, no prims are unwittingly
1626 // left for sale and sold off 1807 // left for sale and sold off
1627 child.RootPart.ObjectSaleType = 0; 1808
1628 child.RootPart.SalePrice = 10; 1809 if (child != null)
1629 childGroups.Add(child); 1810 {
1811 child.RootPart.ObjectSaleType = 0;
1812 child.RootPart.SalePrice = 10;
1813 childGroups.Add(child);
1814 }
1630 } 1815 }
1631 1816
1632 foreach (SceneObjectGroup child in childGroups) 1817 foreach (SceneObjectGroup child in childGroups)
@@ -1655,6 +1840,15 @@ namespace OpenSim.Region.Framework.Scenes
1655 } 1840 }
1656 finally 1841 finally
1657 { 1842 {
1843 lock (SceneObjectGroupsByLocalPartID)
1844 {
1845 foreach (SceneObjectPart part in parentGroup.Parts)
1846 SceneObjectGroupsByLocalPartID[part.LocalId] = parentGroup;
1847 }
1848
1849 parentGroup.HasGroupChanged = true;
1850 parentGroup.ProcessBackup(m_parentScene.SimulationDataService, true);
1851 parentGroup.ScheduleGroupForFullUpdate();
1658 Monitor.Exit(m_updateLock); 1852 Monitor.Exit(m_updateLock);
1659 } 1853 }
1660 } 1854 }
@@ -1677,6 +1871,11 @@ namespace OpenSim.Region.Framework.Scenes
1677 { 1871 {
1678 if (part != null) 1872 if (part != null)
1679 { 1873 {
1874 if (part.KeyframeMotion != null)
1875 {
1876 part.KeyframeMotion.Stop();
1877 part.KeyframeMotion = null;
1878 }
1680 if (part.ParentGroup.PrimCount != 1) // Skip single 1879 if (part.ParentGroup.PrimCount != 1) // Skip single
1681 { 1880 {
1682 if (part.LinkNum < 2) // Root 1881 if (part.LinkNum < 2) // Root
@@ -1691,21 +1890,23 @@ namespace OpenSim.Region.Framework.Scenes
1691 1890
1692 SceneObjectGroup group = part.ParentGroup; 1891 SceneObjectGroup group = part.ParentGroup;
1693 if (!affectedGroups.Contains(group)) 1892 if (!affectedGroups.Contains(group))
1893 {
1694 affectedGroups.Add(group); 1894 affectedGroups.Add(group);
1895 }
1695 } 1896 }
1696 } 1897 }
1697 } 1898 }
1698 1899
1699 foreach (SceneObjectPart child in childParts) 1900 if (childParts.Count > 0)
1700 { 1901 {
1701 // Unlink all child parts from their groups 1902 foreach (SceneObjectPart child in childParts)
1702 // 1903 {
1703 child.ParentGroup.DelinkFromGroup(child, true); 1904 // Unlink all child parts from their groups
1704 1905 //
1705 // These are not in affected groups and will not be 1906 child.ParentGroup.DelinkFromGroup(child, true);
1706 // handled further. Do the honors here. 1907 child.ParentGroup.HasGroupChanged = true;
1707 child.ParentGroup.HasGroupChanged = true; 1908 child.ParentGroup.ScheduleGroupForFullUpdate();
1708 child.ParentGroup.ScheduleGroupForFullUpdate(); 1909 }
1709 } 1910 }
1710 1911
1711 foreach (SceneObjectPart root in rootParts) 1912 foreach (SceneObjectPart root in rootParts)
@@ -1719,52 +1920,61 @@ namespace OpenSim.Region.Framework.Scenes
1719 List<SceneObjectPart> newSet = new List<SceneObjectPart>(group.Parts); 1920 List<SceneObjectPart> newSet = new List<SceneObjectPart>(group.Parts);
1720 int numChildren = newSet.Count; 1921 int numChildren = newSet.Count;
1721 1922
1923 if (numChildren == 1)
1924 break;
1925
1722 // If there are prims left in a link set, but the root is 1926 // If there are prims left in a link set, but the root is
1723 // slated for unlink, we need to do this 1927 // slated for unlink, we need to do this
1928 // Unlink the remaining set
1724 // 1929 //
1725 if (numChildren != 1) 1930 bool sendEventsToRemainder = true;
1726 { 1931 if (numChildren > 1)
1727 // Unlink the remaining set 1932 sendEventsToRemainder = false;
1728 //
1729 bool sendEventsToRemainder = true;
1730 if (numChildren > 1)
1731 sendEventsToRemainder = false;
1732 1933
1733 foreach (SceneObjectPart p in newSet) 1934 foreach (SceneObjectPart p in newSet)
1935 {
1936 if (p != group.RootPart)
1734 { 1937 {
1735 if (p != group.RootPart) 1938 group.DelinkFromGroup(p, sendEventsToRemainder);
1736 group.DelinkFromGroup(p, sendEventsToRemainder); 1939 if (numChildren > 2)
1940 {
1941 }
1942 else
1943 {
1944 p.ParentGroup.HasGroupChanged = true;
1945 p.ParentGroup.ScheduleGroupForFullUpdate();
1946 }
1737 } 1947 }
1948 }
1949
1950 // If there is more than one prim remaining, we
1951 // need to re-link
1952 //
1953 if (numChildren > 2)
1954 {
1955 // Remove old root
1956 //
1957 if (newSet.Contains(root))
1958 newSet.Remove(root);
1738 1959
1739 // If there is more than one prim remaining, we 1960 // Preserve link ordering
1740 // need to re-link
1741 // 1961 //
1742 if (numChildren > 2) 1962 newSet.Sort(delegate (SceneObjectPart a, SceneObjectPart b)
1743 { 1963 {
1744 // Remove old root 1964 return a.LinkNum.CompareTo(b.LinkNum);
1745 // 1965 });
1746 if (newSet.Contains(root))
1747 newSet.Remove(root);
1748
1749 // Preserve link ordering
1750 //
1751 newSet.Sort(delegate (SceneObjectPart a, SceneObjectPart b)
1752 {
1753 return a.LinkNum.CompareTo(b.LinkNum);
1754 });
1755 1966
1756 // Determine new root 1967 // Determine new root
1757 // 1968 //
1758 SceneObjectPart newRoot = newSet[0]; 1969 SceneObjectPart newRoot = newSet[0];
1759 newSet.RemoveAt(0); 1970 newSet.RemoveAt(0);
1760 1971
1761 foreach (SceneObjectPart newChild in newSet) 1972 foreach (SceneObjectPart newChild in newSet)
1762 newChild.ClearUpdateSchedule(); 1973 newChild.ClearUpdateSchedule();
1763 1974
1764 LinkObjects(newRoot, newSet); 1975 LinkObjects(newRoot, newSet);
1765 if (!affectedGroups.Contains(newRoot.ParentGroup)) 1976 if (!affectedGroups.Contains(newRoot.ParentGroup))
1766 affectedGroups.Add(newRoot.ParentGroup); 1977 affectedGroups.Add(newRoot.ParentGroup);
1767 }
1768 } 1978 }
1769 } 1979 }
1770 1980
@@ -1772,6 +1982,11 @@ namespace OpenSim.Region.Framework.Scenes
1772 // 1982 //
1773 foreach (SceneObjectGroup g in affectedGroups) 1983 foreach (SceneObjectGroup g in affectedGroups)
1774 { 1984 {
1985 // Child prims that have been unlinked and deleted will
1986 // return unless the root is deleted. This will remove them
1987 // from the database. They will be rewritten immediately,
1988 // minus the rows for the unlinked child prims.
1989 m_parentScene.SimulationDataService.RemoveObject(g.UUID, m_parentScene.RegionInfo.RegionID);
1775 g.TriggerScriptChangedEvent(Changed.LINK); 1990 g.TriggerScriptChangedEvent(Changed.LINK);
1776 g.HasGroupChanged = true; // Persist 1991 g.HasGroupChanged = true; // Persist
1777 g.ScheduleGroupForFullUpdate(); 1992 g.ScheduleGroupForFullUpdate();
@@ -1845,108 +2060,96 @@ namespace OpenSim.Region.Framework.Scenes
1845 /// <param name="GroupID"></param> 2060 /// <param name="GroupID"></param>
1846 /// <param name="rot"></param> 2061 /// <param name="rot"></param>
1847 /// <returns>null if duplication fails, otherwise the duplicated object</returns> 2062 /// <returns>null if duplication fails, otherwise the duplicated object</returns>
1848 public SceneObjectGroup DuplicateObject( 2063 /// <summary>
1849 uint originalPrimID, Vector3 offset, uint flags, UUID AgentID, UUID GroupID, Quaternion rot) 2064 public SceneObjectGroup DuplicateObject(uint originalPrimID, Vector3 offset, uint flags, UUID AgentID, UUID GroupID, Quaternion rot)
1850 { 2065 {
1851 Monitor.Enter(m_updateLock); 2066// m_log.DebugFormat(
2067// "[SCENE]: Duplication of object {0} at offset {1} requested by agent {2}",
2068// originalPrimID, offset, AgentID);
1852 2069
1853 try 2070 SceneObjectGroup original = GetGroupByPrim(originalPrimID);
2071 if (original != null)
1854 { 2072 {
1855 // m_log.DebugFormat( 2073 if (m_parentScene.Permissions.CanDuplicateObject(
1856 // "[SCENE]: Duplication of object {0} at offset {1} requested by agent {2}", 2074 original.PrimCount, original.UUID, AgentID, original.AbsolutePosition))
1857 // originalPrimID, offset, AgentID);
1858
1859 SceneObjectGroup original = GetGroupByPrim(originalPrimID);
1860 if (original == null)
1861 { 2075 {
1862 m_log.WarnFormat( 2076 SceneObjectGroup copy = original.Copy(true);
1863 "[SCENEGRAPH]: Attempt to duplicate nonexistant prim id {0} by {1}", originalPrimID, AgentID); 2077 copy.AbsolutePosition = copy.AbsolutePosition + offset;
1864 2078
1865 return null; 2079 if (original.OwnerID != AgentID)
1866 } 2080 {
2081 copy.SetOwnerId(AgentID);
2082 copy.SetRootPartOwner(copy.RootPart, AgentID, GroupID);
1867 2083
1868 if (!m_parentScene.Permissions.CanDuplicateObject( 2084 SceneObjectPart[] partList = copy.Parts;
1869 original.PrimCount, original.UUID, AgentID, original.AbsolutePosition))
1870 return null;
1871 2085
1872 SceneObjectGroup copy = original.Copy(true); 2086 if (m_parentScene.Permissions.PropagatePermissions())
1873 copy.AbsolutePosition = copy.AbsolutePosition + offset; 2087 {
2088 foreach (SceneObjectPart child in partList)
2089 {
2090 child.Inventory.ChangeInventoryOwner(AgentID);
2091 child.TriggerScriptChangedEvent(Changed.OWNER);
2092 child.ApplyNextOwnerPermissions();
2093 }
2094 }
2095 }
1874 2096
1875 if (original.OwnerID != AgentID) 2097 // FIXME: This section needs to be refactored so that it just calls AddSceneObject()
1876 { 2098 Entities.Add(copy);
1877 copy.SetOwnerId(AgentID);
1878 copy.SetRootPartOwner(copy.RootPart, AgentID, GroupID);
1879 2099
1880 SceneObjectPart[] partList = copy.Parts; 2100 lock (SceneObjectGroupsByFullID)
2101 SceneObjectGroupsByFullID[copy.UUID] = copy;
1881 2102
1882 if (m_parentScene.Permissions.PropagatePermissions()) 2103 SceneObjectPart[] children = copy.Parts;
2104
2105 lock (SceneObjectGroupsByFullPartID)
1883 { 2106 {
1884 foreach (SceneObjectPart child in partList) 2107 SceneObjectGroupsByFullPartID[copy.UUID] = copy;
1885 { 2108 foreach (SceneObjectPart part in children)
1886 child.Inventory.ChangeInventoryOwner(AgentID); 2109 SceneObjectGroupsByFullPartID[part.UUID] = copy;
1887 child.TriggerScriptChangedEvent(Changed.OWNER);
1888 child.ApplyNextOwnerPermissions();
1889 }
1890 } 2110 }
1891 2111
1892 copy.RootPart.ObjectSaleType = 0; 2112 lock (SceneObjectGroupsByLocalPartID)
1893 copy.RootPart.SalePrice = 10; 2113 {
1894 } 2114 SceneObjectGroupsByLocalPartID[copy.LocalId] = copy;
2115 foreach (SceneObjectPart part in children)
2116 SceneObjectGroupsByLocalPartID[part.LocalId] = copy;
2117 }
2118 // PROBABLE END OF FIXME
1895 2119
1896 // FIXME: This section needs to be refactored so that it just calls AddSceneObject() 2120 // Since we copy from a source group that is in selected
1897 Entities.Add(copy); 2121 // state, but the copy is shown deselected in the viewer,
1898 2122 // We need to clear the selection flag here, else that
1899 lock (SceneObjectGroupsByFullID) 2123 // prim never gets persisted at all. The client doesn't
1900 SceneObjectGroupsByFullID[copy.UUID] = copy; 2124 // think it's selected, so it will never send a deselect...
1901 2125 copy.IsSelected = false;
1902 SceneObjectPart[] children = copy.Parts; 2126
1903 2127 m_numPrim += copy.Parts.Length;
1904 lock (SceneObjectGroupsByFullPartID) 2128
1905 { 2129 if (rot != Quaternion.Identity)
1906 SceneObjectGroupsByFullPartID[copy.UUID] = copy; 2130 {
1907 foreach (SceneObjectPart part in children) 2131 copy.UpdateGroupRotationR(rot);
1908 SceneObjectGroupsByFullPartID[part.UUID] = copy; 2132 }
1909 }
1910
1911 lock (SceneObjectGroupsByLocalPartID)
1912 {
1913 SceneObjectGroupsByLocalPartID[copy.LocalId] = copy;
1914 foreach (SceneObjectPart part in children)
1915 SceneObjectGroupsByLocalPartID[part.LocalId] = copy;
1916 }
1917 // PROBABLE END OF FIXME
1918
1919 // Since we copy from a source group that is in selected
1920 // state, but the copy is shown deselected in the viewer,
1921 // We need to clear the selection flag here, else that
1922 // prim never gets persisted at all. The client doesn't
1923 // think it's selected, so it will never send a deselect...
1924 copy.IsSelected = false;
1925
1926 m_numPrim += copy.Parts.Length;
1927
1928 if (rot != Quaternion.Identity)
1929 {
1930 copy.UpdateGroupRotationR(rot);
1931 }
1932 2133
1933 copy.CreateScriptInstances(0, false, m_parentScene.DefaultScriptEngine, 1); 2134 copy.CreateScriptInstances(0, false, m_parentScene.DefaultScriptEngine, 1);
1934 copy.HasGroupChanged = true; 2135 copy.HasGroupChanged = true;
1935 copy.ScheduleGroupForFullUpdate(); 2136 copy.ScheduleGroupForFullUpdate();
1936 copy.ResumeScripts(); 2137 copy.ResumeScripts();
1937 2138
1938 // required for physics to update it's position 2139 // required for physics to update it's position
1939 copy.AbsolutePosition = copy.AbsolutePosition; 2140 copy.AbsolutePosition = copy.AbsolutePosition;
1940 2141
1941 return copy; 2142 return copy;
2143 }
1942 } 2144 }
1943 finally 2145 else
1944 { 2146 {
1945 Monitor.Exit(m_updateLock); 2147 m_log.WarnFormat("[SCENE]: Attempted to duplicate nonexistant prim id {0}", GroupID);
1946 } 2148 }
2149
2150 return null;
1947 } 2151 }
1948 2152
1949 /// <summary>
1950 /// Calculates the distance between two Vector3s 2153 /// Calculates the distance between two Vector3s
1951 /// </summary> 2154 /// </summary>
1952 /// <param name="v1"></param> 2155 /// <param name="v1"></param>
diff --git a/OpenSim/Region/Framework/Scenes/SceneManager.cs b/OpenSim/Region/Framework/Scenes/SceneManager.cs
index cb5b2ba..dba3a61 100644
--- a/OpenSim/Region/Framework/Scenes/SceneManager.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneManager.cs
@@ -99,12 +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 private Scene m_currentScene = null;
104 104
105 public List<Scene> Scenes 105 public List<Scene> Scenes
106 { 106 {
107 get { return new List<Scene>(m_localScenes); } 107 get { return new List<Scene>(m_localScenes.FindAll(delegate(Scene s) { return true; })); }
108 } 108 }
109 109
110 public Scene CurrentScene 110 public Scene CurrentScene
@@ -118,13 +118,10 @@ namespace OpenSim.Region.Framework.Scenes
118 { 118 {
119 if (m_currentScene == null) 119 if (m_currentScene == null)
120 { 120 {
121 lock (m_localScenes) 121 List<Scene> sceneList = Scenes;
122 { 122 if (sceneList.Count == 0)
123 if (m_localScenes.Count > 0) 123 return null;
124 return m_localScenes[0]; 124 return sceneList[0];
125 else
126 return null;
127 }
128 } 125 }
129 else 126 else
130 { 127 {
@@ -136,7 +133,7 @@ namespace OpenSim.Region.Framework.Scenes
136 public SceneManager() 133 public SceneManager()
137 { 134 {
138 m_instance = this; 135 m_instance = this;
139 m_localScenes = new List<Scene>(); 136 m_localScenes = new DoubleDictionary<UUID, string, Scene>();
140 } 137 }
141 138
142 public void Close() 139 public void Close()
@@ -144,20 +141,18 @@ namespace OpenSim.Region.Framework.Scenes
144 // collect known shared modules in sharedModules 141 // collect known shared modules in sharedModules
145 Dictionary<string, IRegionModule> sharedModules = new Dictionary<string, IRegionModule>(); 142 Dictionary<string, IRegionModule> sharedModules = new Dictionary<string, IRegionModule>();
146 143
147 lock (m_localScenes) 144 List<Scene> sceneList = Scenes;
145 for (int i = 0; i < sceneList.Count; i++)
148 { 146 {
149 for (int i = 0; i < m_localScenes.Count; i++) 147 // extract known shared modules from scene
148 foreach (string k in sceneList[i].Modules.Keys)
150 { 149 {
151 // extract known shared modules from scene 150 if (sceneList[i].Modules[k].IsSharedModule &&
152 foreach (string k in m_localScenes[i].Modules.Keys) 151 !sharedModules.ContainsKey(k))
153 { 152 sharedModules[k] = sceneList[i].Modules[k];
154 if (m_localScenes[i].Modules[k].IsSharedModule &&
155 !sharedModules.ContainsKey(k))
156 sharedModules[k] = m_localScenes[i].Modules[k];
157 }
158 // close scene/region
159 m_localScenes[i].Close();
160 } 153 }
154 // close scene/region
155 sceneList[i].Close();
161 } 156 }
162 157
163 // all regions/scenes are now closed, we can now safely 158 // all regions/scenes are now closed, we can now safely
@@ -166,29 +161,21 @@ namespace OpenSim.Region.Framework.Scenes
166 { 161 {
167 mod.Close(); 162 mod.Close();
168 } 163 }
164
165 m_localScenes.Clear();
169 } 166 }
170 167
171 public void Close(Scene cscene) 168 public void Close(Scene cscene)
172 { 169 {
173 lock (m_localScenes) 170 if (!m_localScenes.ContainsKey(cscene.RegionInfo.RegionID))
174 { 171 return;
175 if (m_localScenes.Contains(cscene)) 172 cscene.Close();
176 {
177 for (int i = 0; i < m_localScenes.Count; i++)
178 {
179 if (m_localScenes[i].Equals(cscene))
180 {
181 m_localScenes[i].Close();
182 }
183 }
184 }
185 }
186 } 173 }
187 174
188 public void Add(Scene scene) 175 public void Add(Scene scene)
189 { 176 {
190 lock (m_localScenes) 177 lock (m_localScenes)
191 m_localScenes.Add(scene); 178 m_localScenes.Add(scene.RegionInfo.RegionID, scene.RegionInfo.RegionName, scene);
192 179
193 scene.OnRestart += HandleRestart; 180 scene.OnRestart += HandleRestart;
194 scene.EventManager.OnRegionReadyStatusChange += HandleRegionReadyStatusChange; 181 scene.EventManager.OnRegionReadyStatusChange += HandleRegionReadyStatusChange;
@@ -200,23 +187,7 @@ namespace OpenSim.Region.Framework.Scenes
200 int RegionSceneElement = -1; 187 int RegionSceneElement = -1;
201 188
202 lock (m_localScenes) 189 lock (m_localScenes)
203 { 190 m_localScenes.Remove(rdata.RegionID);
204 for (int i = 0; i < m_localScenes.Count; i++)
205 {
206 if (rdata.RegionName == m_localScenes[i].RegionInfo.RegionName)
207 {
208 RegionSceneElement = i;
209 }
210 }
211
212 // Now we make sure the region is no longer known about by the SceneManager
213 // Prevents duplicates.
214
215 if (RegionSceneElement >= 0)
216 {
217 m_localScenes.RemoveAt(RegionSceneElement);
218 }
219 }
220 191
221 // Send signal to main that we're restarting this sim. 192 // Send signal to main that we're restarting this sim.
222 OnRestartSim(rdata); 193 OnRestartSim(rdata);
@@ -225,39 +196,36 @@ namespace OpenSim.Region.Framework.Scenes
225 private void HandleRegionReadyStatusChange(IScene scene) 196 private void HandleRegionReadyStatusChange(IScene scene)
226 { 197 {
227 lock (m_localScenes) 198 lock (m_localScenes)
228 AllRegionsReady = m_localScenes.TrueForAll(s => s.Ready); 199 AllRegionsReady = m_localScenes.FindAll(s => !s.Ready).Count == 0;
229 } 200 }
230 201
231 public void SendSimOnlineNotification(ulong regionHandle) 202 public void SendSimOnlineNotification(ulong regionHandle)
232 { 203 {
233 RegionInfo Result = null; 204 RegionInfo Result = null;
234 205
235 lock (m_localScenes) 206 Scene s = m_localScenes.FindValue(delegate(Scene x)
236 {
237 for (int i = 0; i < m_localScenes.Count; i++)
238 {
239 if (m_localScenes[i].RegionInfo.RegionHandle == regionHandle)
240 { 207 {
241 // Inform other regions to tell their avatar about me 208 if (x.RegionInfo.RegionHandle == regionHandle)
242 Result = m_localScenes[i].RegionInfo; 209 return true;
243 } 210 return false;
244 } 211 });
245 212
246 if (Result != null) 213 if (s != null)
214 {
215 List<Scene> sceneList = Scenes;
216
217 for (int i = 0; i < sceneList.Count; i++)
247 { 218 {
248 for (int i = 0; i < m_localScenes.Count; i++) 219 if (sceneList[i]!= s)
249 { 220 {
250 if (m_localScenes[i].RegionInfo.RegionHandle != regionHandle) 221 // Inform other regions to tell their avatar about me
251 { 222 //sceneList[i].OtherRegionUp(Result);
252 // Inform other regions to tell their avatar about me
253 //m_localScenes[i].OtherRegionUp(Result);
254 }
255 } 223 }
256 } 224 }
257 else 225 }
258 { 226 else
259 m_log.Error("[REGION]: Unable to notify Other regions of this Region coming up"); 227 {
260 } 228 m_log.Error("[REGION]: Unable to notify Other regions of this Region coming up");
261 } 229 }
262 } 230 }
263 231
@@ -361,8 +329,8 @@ namespace OpenSim.Region.Framework.Scenes
361 { 329 {
362 if (m_currentScene == null) 330 if (m_currentScene == null)
363 { 331 {
364 lock (m_localScenes) 332 List<Scene> sceneList = Scenes;
365 m_localScenes.ForEach(func); 333 sceneList.ForEach(func);
366 } 334 }
367 else 335 else
368 { 336 {
@@ -391,16 +359,12 @@ namespace OpenSim.Region.Framework.Scenes
391 } 359 }
392 else 360 else
393 { 361 {
394 lock (m_localScenes) 362 Scene s;
363
364 if (m_localScenes.TryGetValue(regionName, out s))
395 { 365 {
396 foreach (Scene scene in m_localScenes) 366 m_currentScene = s;
397 { 367 return true;
398 if (String.Compare(scene.RegionInfo.RegionName, regionName, true) == 0)
399 {
400 m_currentScene = scene;
401 return true;
402 }
403 }
404 } 368 }
405 369
406 return false; 370 return false;
@@ -409,18 +373,14 @@ namespace OpenSim.Region.Framework.Scenes
409 373
410 public bool TrySetCurrentScene(UUID regionID) 374 public bool TrySetCurrentScene(UUID regionID)
411 { 375 {
412 m_log.Debug("Searching for Region: '" + regionID + "'"); 376// m_log.Debug("Searching for Region: '" + regionID + "'");
413 377
414 lock (m_localScenes) 378 Scene s;
379
380 if (m_localScenes.TryGetValue(regionID, out s))
415 { 381 {
416 foreach (Scene scene in m_localScenes) 382 m_currentScene = s;
417 { 383 return true;
418 if (scene.RegionInfo.RegionID == regionID)
419 {
420 m_currentScene = scene;
421 return true;
422 }
423 }
424 } 384 }
425 385
426 return false; 386 return false;
@@ -428,52 +388,24 @@ namespace OpenSim.Region.Framework.Scenes
428 388
429 public bool TryGetScene(string regionName, out Scene scene) 389 public bool TryGetScene(string regionName, out Scene scene)
430 { 390 {
431 lock (m_localScenes) 391 return m_localScenes.TryGetValue(regionName, out scene);
432 {
433 foreach (Scene mscene in m_localScenes)
434 {
435 if (String.Compare(mscene.RegionInfo.RegionName, regionName, true) == 0)
436 {
437 scene = mscene;
438 return true;
439 }
440 }
441 }
442
443 scene = null;
444 return false;
445 } 392 }
446 393
447 public bool TryGetScene(UUID regionID, out Scene scene) 394 public bool TryGetScene(UUID regionID, out Scene scene)
448 { 395 {
449 lock (m_localScenes) 396 return m_localScenes.TryGetValue(regionID, out scene);
450 {
451 foreach (Scene mscene in m_localScenes)
452 {
453 if (mscene.RegionInfo.RegionID == regionID)
454 {
455 scene = mscene;
456 return true;
457 }
458 }
459 }
460
461 scene = null;
462 return false;
463 } 397 }
464 398
465 public bool TryGetScene(uint locX, uint locY, out Scene scene) 399 public bool TryGetScene(uint locX, uint locY, out Scene scene)
466 { 400 {
467 lock (m_localScenes) 401 List<Scene> sceneList = Scenes;
402 foreach (Scene mscene in sceneList)
468 { 403 {
469 foreach (Scene mscene in m_localScenes) 404 if (mscene.RegionInfo.RegionLocX == locX &&
405 mscene.RegionInfo.RegionLocY == locY)
470 { 406 {
471 if (mscene.RegionInfo.RegionLocX == locX && 407 scene = mscene;
472 mscene.RegionInfo.RegionLocY == locY) 408 return true;
473 {
474 scene = mscene;
475 return true;
476 }
477 } 409 }
478 } 410 }
479 411
@@ -483,16 +415,14 @@ namespace OpenSim.Region.Framework.Scenes
483 415
484 public bool TryGetScene(IPEndPoint ipEndPoint, out Scene scene) 416 public bool TryGetScene(IPEndPoint ipEndPoint, out Scene scene)
485 { 417 {
486 lock (m_localScenes) 418 List<Scene> sceneList = Scenes;
419 foreach (Scene mscene in sceneList)
487 { 420 {
488 foreach (Scene mscene in m_localScenes) 421 if ((mscene.RegionInfo.InternalEndPoint.Equals(ipEndPoint.Address)) &&
422 (mscene.RegionInfo.InternalEndPoint.Port == ipEndPoint.Port))
489 { 423 {
490 if ((mscene.RegionInfo.InternalEndPoint.Equals(ipEndPoint.Address)) && 424 scene = mscene;
491 (mscene.RegionInfo.InternalEndPoint.Port == ipEndPoint.Port)) 425 return true;
492 {
493 scene = mscene;
494 return true;
495 }
496 } 426 }
497 } 427 }
498 428
@@ -557,15 +487,10 @@ namespace OpenSim.Region.Framework.Scenes
557 487
558 public RegionInfo GetRegionInfo(UUID regionID) 488 public RegionInfo GetRegionInfo(UUID regionID)
559 { 489 {
560 lock (m_localScenes) 490 Scene s;
491 if (m_localScenes.TryGetValue(regionID, out s))
561 { 492 {
562 foreach (Scene scene in m_localScenes) 493 return s.RegionInfo;
563 {
564 if (scene.RegionInfo.RegionID == regionID)
565 {
566 return scene.RegionInfo;
567 }
568 }
569 } 494 }
570 495
571 return null; 496 return null;
@@ -583,14 +508,12 @@ namespace OpenSim.Region.Framework.Scenes
583 508
584 public bool TryGetScenePresence(UUID avatarId, out ScenePresence avatar) 509 public bool TryGetScenePresence(UUID avatarId, out ScenePresence avatar)
585 { 510 {
586 lock (m_localScenes) 511 List<Scene> sceneList = Scenes;
512 foreach (Scene scene in sceneList)
587 { 513 {
588 foreach (Scene scene in m_localScenes) 514 if (scene.TryGetScenePresence(avatarId, out avatar))
589 { 515 {
590 if (scene.TryGetScenePresence(avatarId, out avatar)) 516 return true;
591 {
592 return true;
593 }
594 } 517 }
595 } 518 }
596 519
@@ -600,15 +523,13 @@ namespace OpenSim.Region.Framework.Scenes
600 523
601 public bool TryGetRootScenePresence(UUID avatarId, out ScenePresence avatar) 524 public bool TryGetRootScenePresence(UUID avatarId, out ScenePresence avatar)
602 { 525 {
603 lock (m_localScenes) 526 List<Scene> sceneList = Scenes;
527 foreach (Scene scene in sceneList)
604 { 528 {
605 foreach (Scene scene in m_localScenes) 529 avatar = scene.GetScenePresence(avatarId);
606 {
607 avatar = scene.GetScenePresence(avatarId);
608 530
609 if (avatar != null && !avatar.IsChildAgent) 531 if (avatar != null && !avatar.IsChildAgent)
610 return true; 532 return true;
611 }
612 } 533 }
613 534
614 avatar = null; 535 avatar = null;
@@ -618,21 +539,19 @@ namespace OpenSim.Region.Framework.Scenes
618 public void CloseScene(Scene scene) 539 public void CloseScene(Scene scene)
619 { 540 {
620 lock (m_localScenes) 541 lock (m_localScenes)
621 m_localScenes.Remove(scene); 542 m_localScenes.Remove(scene.RegionInfo.RegionID);
622 543
623 scene.Close(); 544 scene.Close();
624 } 545 }
625 546
626 public bool TryGetAvatarByName(string avatarName, out ScenePresence avatar) 547 public bool TryGetAvatarByName(string avatarName, out ScenePresence avatar)
627 { 548 {
628 lock (m_localScenes) 549 List<Scene> sceneList = Scenes;
550 foreach (Scene scene in sceneList)
629 { 551 {
630 foreach (Scene scene in m_localScenes) 552 if (scene.TryGetAvatarByName(avatarName, out avatar))
631 { 553 {
632 if (scene.TryGetAvatarByName(avatarName, out avatar)) 554 return true;
633 {
634 return true;
635 }
636 } 555 }
637 } 556 }
638 557
@@ -642,14 +561,12 @@ namespace OpenSim.Region.Framework.Scenes
642 561
643 public bool TryGetRootScenePresenceByName(string firstName, string lastName, out ScenePresence sp) 562 public bool TryGetRootScenePresenceByName(string firstName, string lastName, out ScenePresence sp)
644 { 563 {
645 lock (m_localScenes) 564 List<Scene> sceneList = Scenes;
565 foreach (Scene scene in sceneList)
646 { 566 {
647 foreach (Scene scene in m_localScenes) 567 sp = scene.GetScenePresence(firstName, lastName);
648 { 568 if (sp != null && !sp.IsChildAgent)
649 sp = scene.GetScenePresence(firstName, lastName); 569 return true;
650 if (sp != null && !sp.IsChildAgent)
651 return true;
652 }
653 } 570 }
654 571
655 sp = null; 572 sp = null;
@@ -658,8 +575,8 @@ namespace OpenSim.Region.Framework.Scenes
658 575
659 public void ForEachScene(Action<Scene> action) 576 public void ForEachScene(Action<Scene> action)
660 { 577 {
661 lock (m_localScenes) 578 List<Scene> sceneList = Scenes;
662 m_localScenes.ForEach(action); 579 sceneList.ForEach(action);
663 } 580 }
664 } 581 }
665} 582}
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 ac26be7..f1df6d6 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 {
@@ -106,8 +108,12 @@ namespace OpenSim.Region.Framework.Scenes
106 /// since the group's last persistent backup 108 /// since the group's last persistent backup
107 /// </summary> 109 /// </summary>
108 private bool m_hasGroupChanged = false; 110 private bool m_hasGroupChanged = false;
109 private long timeFirstChanged; 111 private long timeFirstChanged = 0;
110 private long timeLastChanged; 112 private long timeLastChanged = 0;
113 private long m_maxPersistTime = 0;
114 private long m_minPersistTime = 0;
115 private Random m_rand;
116 private List<ScenePresence> m_linkedAvatars = new List<ScenePresence>();
111 117
112 /// <summary> 118 /// <summary>
113 /// This indicates whether the object has changed such that it needs to be repersisted to permenant storage 119 /// This indicates whether the object has changed such that it needs to be repersisted to permenant storage
@@ -124,9 +130,39 @@ namespace OpenSim.Region.Framework.Scenes
124 { 130 {
125 if (value) 131 if (value)
126 { 132 {
133 if (m_isBackedUp)
134 {
135 m_scene.SceneGraph.FireChangeBackup(this);
136 }
127 timeLastChanged = DateTime.Now.Ticks; 137 timeLastChanged = DateTime.Now.Ticks;
128 if (!m_hasGroupChanged) 138 if (!m_hasGroupChanged)
129 timeFirstChanged = DateTime.Now.Ticks; 139 timeFirstChanged = DateTime.Now.Ticks;
140 if (m_rootPart != null && m_rootPart.UUID != null && m_scene != null)
141 {
142 if (m_rand == null)
143 {
144 byte[] val = new byte[16];
145 m_rootPart.UUID.ToBytes(val, 0);
146 m_rand = new Random(BitConverter.ToInt32(val, 0));
147 }
148
149 if (m_scene.GetRootAgentCount() == 0)
150 {
151 //If the region is empty, this change has been made by an automated process
152 //and thus we delay the persist time by a random amount between 1.5 and 2.5.
153
154 float factor = 1.5f + (float)(m_rand.NextDouble());
155 m_maxPersistTime = (long)((float)m_scene.m_persistAfter * factor);
156 m_minPersistTime = (long)((float)m_scene.m_dontPersistBefore * factor);
157 }
158 else
159 {
160 //If the region is not empty, we want to obey the minimum and maximum persist times
161 //but add a random factor so we stagger the object persistance a little
162 m_maxPersistTime = (long)((float)m_scene.m_persistAfter * (1.0d - (m_rand.NextDouble() / 5.0d))); //Multiply by 1.0-1.5
163 m_minPersistTime = (long)((float)m_scene.m_dontPersistBefore * (1.0d + (m_rand.NextDouble() / 2.0d))); //Multiply by 0.8-1.0
164 }
165 }
130 } 166 }
131 m_hasGroupChanged = value; 167 m_hasGroupChanged = value;
132 168
@@ -141,7 +177,7 @@ namespace OpenSim.Region.Framework.Scenes
141 /// Has the group changed due to an unlink operation? We record this in order to optimize deletion, since 177 /// Has the group changed due to an unlink operation? We record this in order to optimize deletion, since
142 /// an unlinked group currently has to be persisted to the database before we can perform an unlink operation. 178 /// an unlinked group currently has to be persisted to the database before we can perform an unlink operation.
143 /// </summary> 179 /// </summary>
144 public bool HasGroupChangedDueToDelink { get; private set; } 180 public bool HasGroupChangedDueToDelink { get; set; }
145 181
146 private bool isTimeToPersist() 182 private bool isTimeToPersist()
147 { 183 {
@@ -151,8 +187,19 @@ namespace OpenSim.Region.Framework.Scenes
151 return false; 187 return false;
152 if (m_scene.ShuttingDown) 188 if (m_scene.ShuttingDown)
153 return true; 189 return true;
190
191 if (m_minPersistTime == 0 || m_maxPersistTime == 0)
192 {
193 m_maxPersistTime = m_scene.m_persistAfter;
194 m_minPersistTime = m_scene.m_dontPersistBefore;
195 }
196
154 long currentTime = DateTime.Now.Ticks; 197 long currentTime = DateTime.Now.Ticks;
155 if (currentTime - timeLastChanged > m_scene.m_dontPersistBefore || currentTime - timeFirstChanged > m_scene.m_persistAfter) 198
199 if (timeLastChanged == 0) timeLastChanged = currentTime;
200 if (timeFirstChanged == 0) timeFirstChanged = currentTime;
201
202 if (currentTime - timeLastChanged > m_minPersistTime || currentTime - timeFirstChanged > m_maxPersistTime)
156 return true; 203 return true;
157 return false; 204 return false;
158 } 205 }
@@ -271,10 +318,10 @@ namespace OpenSim.Region.Framework.Scenes
271 318
272 private bool m_scriptListens_atTarget; 319 private bool m_scriptListens_atTarget;
273 private bool m_scriptListens_notAtTarget; 320 private bool m_scriptListens_notAtTarget;
274
275 private bool m_scriptListens_atRotTarget; 321 private bool m_scriptListens_atRotTarget;
276 private bool m_scriptListens_notAtRotTarget; 322 private bool m_scriptListens_notAtRotTarget;
277 323
324 public bool m_dupeInProgress = false;
278 internal Dictionary<UUID, string> m_savedScriptState; 325 internal Dictionary<UUID, string> m_savedScriptState;
279 326
280 #region Properties 327 #region Properties
@@ -311,6 +358,16 @@ namespace OpenSim.Region.Framework.Scenes
311 get { return m_parts.Count; } 358 get { return m_parts.Count; }
312 } 359 }
313 360
361// protected Quaternion m_rotation = Quaternion.Identity;
362//
363// public virtual Quaternion Rotation
364// {
365// get { return m_rotation; }
366// set {
367// m_rotation = value;
368// }
369// }
370
314 public Quaternion GroupRotation 371 public Quaternion GroupRotation
315 { 372 {
316 get { return m_rootPart.RotationOffset; } 373 get { return m_rootPart.RotationOffset; }
@@ -417,7 +474,15 @@ namespace OpenSim.Region.Framework.Scenes
417 { 474 {
418 return (IsAttachment || (m_rootPart.Shape.PCode == 9 && m_rootPart.Shape.State != 0)); 475 return (IsAttachment || (m_rootPart.Shape.PCode == 9 && m_rootPart.Shape.State != 0));
419 } 476 }
420 477
478
479
480 private struct avtocrossInfo
481 {
482 public ScenePresence av;
483 public uint ParentID;
484 }
485
421 /// <summary> 486 /// <summary>
422 /// The absolute position of this scene object in the scene 487 /// The absolute position of this scene object in the scene
423 /// </summary> 488 /// </summary>
@@ -430,14 +495,136 @@ namespace OpenSim.Region.Framework.Scenes
430 495
431 if (Scene != null) 496 if (Scene != null)
432 { 497 {
433 if ((Scene.TestBorderCross(val - Vector3.UnitX, Cardinals.E) || Scene.TestBorderCross(val + Vector3.UnitX, Cardinals.W) 498 // if ((Scene.TestBorderCross(val - Vector3.UnitX, Cardinals.E) || Scene.TestBorderCross(val + Vector3.UnitX, Cardinals.W)
434 || Scene.TestBorderCross(val - Vector3.UnitY, Cardinals.N) || Scene.TestBorderCross(val + Vector3.UnitY, Cardinals.S)) 499 // || Scene.TestBorderCross(val - Vector3.UnitY, Cardinals.N) || Scene.TestBorderCross(val + Vector3.UnitY, Cardinals.S))
500 // && !IsAttachmentCheckFull() && (!Scene.LoadingPrims))
501 if ((Scene.TestBorderCross(val, Cardinals.E) || Scene.TestBorderCross(val, Cardinals.W)
502 || Scene.TestBorderCross(val, Cardinals.N) || Scene.TestBorderCross(val, Cardinals.S))
435 && !IsAttachmentCheckFull() && (!Scene.LoadingPrims)) 503 && !IsAttachmentCheckFull() && (!Scene.LoadingPrims))
436 { 504 {
437 m_scene.CrossPrimGroupIntoNewRegion(val, this, true); 505 IEntityTransferModule entityTransfer = m_scene.RequestModuleInterface<IEntityTransferModule>();
506 uint x = 0;
507 uint y = 0;
508 string version = String.Empty;
509 Vector3 newpos = Vector3.Zero;
510 OpenSim.Services.Interfaces.GridRegion destination = null;
511
512 if (m_rootPart.KeyframeMotion != null)
513 m_rootPart.KeyframeMotion.StartCrossingCheck();
514
515 bool canCross = true;
516 foreach (ScenePresence av in m_linkedAvatars)
517 {
518 // We need to cross these agents. First, let's find
519 // out if any of them can't cross for some reason.
520 // We have to deny the crossing entirely if any
521 // of them are banned. Alternatively, we could
522 // unsit banned agents....
523
524
525 // We set the avatar position as being the object
526 // position to get the region to send to
527 if ((destination = entityTransfer.GetDestination(m_scene, av.UUID, val, out x, out y, out version, out newpos)) == null)
528 {
529 canCross = false;
530 break;
531 }
532
533 m_log.DebugFormat("[SCENE OBJECT]: Avatar {0} needs to be crossed to {1}", av.Name, destination.RegionName);
534 }
535
536 if (canCross)
537 {
538 // We unparent the SP quietly so that it won't
539 // be made to stand up
540
541 List<avtocrossInfo> avsToCross = new List<avtocrossInfo>();
542
543 foreach (ScenePresence av in m_linkedAvatars)
544 {
545 avtocrossInfo avinfo = new avtocrossInfo();
546 SceneObjectPart parentPart = m_scene.GetSceneObjectPart(av.ParentID);
547 if (parentPart != null)
548 av.ParentUUID = parentPart.UUID;
549
550 avinfo.av = av;
551 avinfo.ParentID = av.ParentID;
552 avsToCross.Add(avinfo);
553
554 av.ParentID = 0;
555 }
556
557 // m_linkedAvatars.Clear();
558 m_scene.CrossPrimGroupIntoNewRegion(val, this, true);
559
560 // Normalize
561 if (val.X >= Constants.RegionSize)
562 val.X -= Constants.RegionSize;
563 if (val.Y >= Constants.RegionSize)
564 val.Y -= Constants.RegionSize;
565 if (val.X < 0)
566 val.X += Constants.RegionSize;
567 if (val.Y < 0)
568 val.Y += Constants.RegionSize;
569
570 // If it's deleted, crossing was successful
571 if (IsDeleted)
572 {
573 // foreach (ScenePresence av in m_linkedAvatars)
574 foreach (avtocrossInfo avinfo in avsToCross)
575 {
576 ScenePresence av = avinfo.av;
577 if (!av.IsInTransit) // just in case...
578 {
579 m_log.DebugFormat("[SCENE OBJECT]: Crossing avatar {0} to {1}", av.Name, val);
580
581 av.IsInTransit = true;
582
583 CrossAgentToNewRegionDelegate d = entityTransfer.CrossAgentToNewRegionAsync;
584 d.BeginInvoke(av, val, destination, av.Flying, version, CrossAgentToNewRegionCompleted, d);
585 }
586 else
587 m_log.DebugFormat("[SCENE OBJECT]: Crossing avatar alreasy in transit {0} to {1}", av.Name, val);
588 }
589 avsToCross.Clear();
590 return;
591 }
592 else // cross failed, put avas back ??
593 {
594 foreach (avtocrossInfo avinfo in avsToCross)
595 {
596 ScenePresence av = avinfo.av;
597 av.ParentUUID = UUID.Zero;
598 av.ParentID = avinfo.ParentID;
599// m_linkedAvatars.Add(av);
600 }
601 }
602 avsToCross.Clear();
603
604 }
605 else
606 {
607 if (m_rootPart.KeyframeMotion != null)
608 m_rootPart.KeyframeMotion.CrossingFailure();
609
610 if (RootPart.PhysActor != null)
611 {
612 RootPart.PhysActor.CrossingFailure();
613 }
614 }
615 Vector3 oldp = AbsolutePosition;
616 val.X = Util.Clamp<float>(oldp.X, 0.5f, (float)Constants.RegionSize - 0.5f);
617 val.Y = Util.Clamp<float>(oldp.Y, 0.5f, (float)Constants.RegionSize - 0.5f);
618 val.Z = Util.Clamp<float>(oldp.Z, 0.5f, 4096.0f);
438 } 619 }
439 } 620 }
440 621
622/* don't see the need but worse don't see where is restored to false if things stay in
623 foreach (SceneObjectPart part in m_parts.GetArray())
624 {
625 part.IgnoreUndoUpdate = true;
626 }
627 */
441 if (RootPart.GetStatusSandbox()) 628 if (RootPart.GetStatusSandbox())
442 { 629 {
443 if (Util.GetDistanceTo(RootPart.StatusSandboxPos, value) > 10) 630 if (Util.GetDistanceTo(RootPart.StatusSandboxPos, value) > 10)
@@ -455,9 +642,38 @@ namespace OpenSim.Region.Framework.Scenes
455 // Restuff the new GroupPosition into each SOP of the linkset. 642 // Restuff the new GroupPosition into each SOP of the linkset.
456 // This has the affect of resetting and tainting the physics actors. 643 // This has the affect of resetting and tainting the physics actors.
457 SceneObjectPart[] parts = m_parts.GetArray(); 644 SceneObjectPart[] parts = m_parts.GetArray();
458 for (int i = 0; i < parts.Length; i++) 645 bool triggerScriptEvent = m_rootPart.GroupPosition != val;
459 parts[i].GroupPosition = val; 646 if (m_dupeInProgress)
647 triggerScriptEvent = false;
648 foreach (SceneObjectPart part in parts)
649 {
650 part.GroupPosition = val;
651 if (triggerScriptEvent)
652 part.TriggerScriptChangedEvent(Changed.POSITION);
653 }
460 654
655/*
656 This seems not needed and should not be needed:
657 sp absolute position depends on sit part absolute position fixed above.
658 sp ParentPosition is not used anywhere.
659 Since presence is sitting, viewer considers it 'linked' to root prim, so it will move/rotate it
660 Sending a extra packet with avatar position is not only bandwidth waste, but may cause jitter in viewers due to UPD nature.
661
662 if (!m_dupeInProgress)
663 {
664 foreach (ScenePresence av in m_linkedAvatars)
665 {
666 SceneObjectPart p = m_scene.GetSceneObjectPart(av.ParentID);
667 if (p != null && m_parts.TryGetValue(p.UUID, out p))
668 {
669 Vector3 offset = p.GetWorldPosition() - av.ParentPosition;
670 av.AbsolutePosition += offset;
671// av.ParentPosition = p.GetWorldPosition(); //ParentPosition gets cleared by AbsolutePosition
672 av.SendAvatarDataToAllAgents();
673 }
674 }
675 }
676*/
461 //if (m_rootPart.PhysActor != null) 677 //if (m_rootPart.PhysActor != null)
462 //{ 678 //{
463 //m_rootPart.PhysActor.Position = 679 //m_rootPart.PhysActor.Position =
@@ -471,6 +687,40 @@ namespace OpenSim.Region.Framework.Scenes
471 } 687 }
472 } 688 }
473 689
690 public override Vector3 Velocity
691 {
692 get { return RootPart.Velocity; }
693 set { RootPart.Velocity = value; }
694 }
695
696 private void CrossAgentToNewRegionCompleted(IAsyncResult iar)
697 {
698 CrossAgentToNewRegionDelegate icon = (CrossAgentToNewRegionDelegate)iar.AsyncState;
699 ScenePresence agent = icon.EndInvoke(iar);
700
701 //// If the cross was successful, this agent is a child agent
702 if (agent.IsChildAgent)
703 {
704 if (agent.ParentUUID != UUID.Zero)
705 {
706 agent.ParentPart = null;
707// agent.ParentPosition = Vector3.Zero;
708// agent.ParentUUID = UUID.Zero;
709 }
710 }
711
712 agent.ParentUUID = UUID.Zero;
713
714// agent.Reset();
715// else // Not successful
716// agent.RestoreInCurrentScene();
717
718 // In any case
719 agent.IsInTransit = false;
720
721 m_log.DebugFormat("[SCENE OBJECT]: Crossing agent {0} {1} completed.", agent.Firstname, agent.Lastname);
722 }
723
474 public override uint LocalId 724 public override uint LocalId
475 { 725 {
476 get { return m_rootPart.LocalId; } 726 get { return m_rootPart.LocalId; }
@@ -541,6 +791,11 @@ namespace OpenSim.Region.Framework.Scenes
541 m_isSelected = value; 791 m_isSelected = value;
542 // Tell physics engine that group is selected 792 // Tell physics engine that group is selected
543 793
794 // this is not right
795 // but ode engines should only really need to know about root part
796 // so they can put entire object simulation on hold and not colliding
797 // keep as was for now
798
544 PhysicsActor pa = m_rootPart.PhysActor; 799 PhysicsActor pa = m_rootPart.PhysActor;
545 if (pa != null) 800 if (pa != null)
546 { 801 {
@@ -557,6 +812,42 @@ namespace OpenSim.Region.Framework.Scenes
557 childPa.Selected = value; 812 childPa.Selected = value;
558 } 813 }
559 } 814 }
815 if (RootPart.KeyframeMotion != null)
816 RootPart.KeyframeMotion.Selected = value;
817 }
818 }
819
820 public void PartSelectChanged(bool partSelect)
821 {
822 // any part selected makes group selected
823 if (m_isSelected == partSelect)
824 return;
825
826 if (partSelect)
827 {
828 IsSelected = partSelect;
829// if (!IsAttachment)
830// ScheduleGroupForFullUpdate();
831 }
832 else
833 {
834 // bad bad bad 2 heavy for large linksets
835 // since viewer does send lot of (un)selects
836 // this needs to be replaced by a specific list or count ?
837 // but that will require extra code in several places
838
839 SceneObjectPart[] parts = m_parts.GetArray();
840 for (int i = 0; i < parts.Length; i++)
841 {
842 SceneObjectPart part = parts[i];
843 if (part.IsSelected)
844 return;
845 }
846 IsSelected = partSelect;
847 if (!IsAttachment)
848 {
849 ScheduleGroupForFullUpdate();
850 }
560 } 851 }
561 } 852 }
562 853
@@ -642,6 +933,7 @@ namespace OpenSim.Region.Framework.Scenes
642 /// </summary> 933 /// </summary>
643 public SceneObjectGroup() 934 public SceneObjectGroup()
644 { 935 {
936
645 } 937 }
646 938
647 /// <summary> 939 /// <summary>
@@ -659,8 +951,8 @@ namespace OpenSim.Region.Framework.Scenes
659 /// Constructor. This object is added to the scene later via AttachToScene() 951 /// Constructor. This object is added to the scene later via AttachToScene()
660 /// </summary> 952 /// </summary>
661 public SceneObjectGroup(UUID ownerID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape) 953 public SceneObjectGroup(UUID ownerID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape)
662 :this(new SceneObjectPart(ownerID, shape, pos, rot, Vector3.Zero)) 954 {
663 { 955 SetRootPart(new SceneObjectPart(ownerID, shape, pos, rot, Vector3.Zero));
664 } 956 }
665 957
666 /// <summary> 958 /// <summary>
@@ -695,6 +987,9 @@ namespace OpenSim.Region.Framework.Scenes
695 /// </summary> 987 /// </summary>
696 public virtual void AttachToBackup() 988 public virtual void AttachToBackup()
697 { 989 {
990 if (IsAttachment) return;
991 m_scene.SceneGraph.FireAttachToBackup(this);
992
698 if (InSceneBackup) 993 if (InSceneBackup)
699 { 994 {
700 //m_log.DebugFormat( 995 //m_log.DebugFormat(
@@ -737,6 +1032,13 @@ namespace OpenSim.Region.Framework.Scenes
737 1032
738 ApplyPhysics(); 1033 ApplyPhysics();
739 1034
1035 if (RootPart.PhysActor != null)
1036 RootPart.Force = RootPart.Force;
1037 if (RootPart.PhysActor != null)
1038 RootPart.Torque = RootPart.Torque;
1039 if (RootPart.PhysActor != null)
1040 RootPart.Buoyancy = RootPart.Buoyancy;
1041
740 // Don't trigger the update here - otherwise some client issues occur when multiple updates are scheduled 1042 // Don't trigger the update here - otherwise some client issues occur when multiple updates are scheduled
741 // for the same object with very different properties. The caller must schedule the update. 1043 // for the same object with very different properties. The caller must schedule the update.
742 //ScheduleGroupForFullUpdate(); 1044 //ScheduleGroupForFullUpdate();
@@ -752,6 +1054,10 @@ namespace OpenSim.Region.Framework.Scenes
752 EntityIntersection result = new EntityIntersection(); 1054 EntityIntersection result = new EntityIntersection();
753 1055
754 SceneObjectPart[] parts = m_parts.GetArray(); 1056 SceneObjectPart[] parts = m_parts.GetArray();
1057
1058 // Find closest hit here
1059 float idist = float.MaxValue;
1060
755 for (int i = 0; i < parts.Length; i++) 1061 for (int i = 0; i < parts.Length; i++)
756 { 1062 {
757 SceneObjectPart part = parts[i]; 1063 SceneObjectPart part = parts[i];
@@ -766,11 +1072,6 @@ namespace OpenSim.Region.Framework.Scenes
766 1072
767 EntityIntersection inter = part.TestIntersectionOBB(hRay, parentrotation, frontFacesOnly, faceCenters); 1073 EntityIntersection inter = part.TestIntersectionOBB(hRay, parentrotation, frontFacesOnly, faceCenters);
768 1074
769 // This may need to be updated to the maximum draw distance possible..
770 // We might (and probably will) be checking for prim creation from other sims
771 // when the camera crosses the border.
772 float idist = Constants.RegionSize;
773
774 if (inter.HitTF) 1075 if (inter.HitTF)
775 { 1076 {
776 // We need to find the closest prim to return to the testcaller along the ray 1077 // We need to find the closest prim to return to the testcaller along the ray
@@ -781,10 +1082,11 @@ namespace OpenSim.Region.Framework.Scenes
781 result.obj = part; 1082 result.obj = part;
782 result.normal = inter.normal; 1083 result.normal = inter.normal;
783 result.distance = inter.distance; 1084 result.distance = inter.distance;
1085
1086 idist = inter.distance;
784 } 1087 }
785 } 1088 }
786 } 1089 }
787
788 return result; 1090 return result;
789 } 1091 }
790 1092
@@ -796,25 +1098,27 @@ namespace OpenSim.Region.Framework.Scenes
796 /// <returns></returns> 1098 /// <returns></returns>
797 public void GetAxisAlignedBoundingBoxRaw(out float minX, out float maxX, out float minY, out float maxY, out float minZ, out float maxZ) 1099 public void GetAxisAlignedBoundingBoxRaw(out float minX, out float maxX, out float minY, out float maxY, out float minZ, out float maxZ)
798 { 1100 {
799 maxX = -256f; 1101 maxX = float.MinValue;
800 maxY = -256f; 1102 maxY = float.MinValue;
801 maxZ = -256f; 1103 maxZ = float.MinValue;
802 minX = 256f; 1104 minX = float.MaxValue;
803 minY = 256f; 1105 minY = float.MaxValue;
804 minZ = 8192f; 1106 minZ = float.MaxValue;
805 1107
806 SceneObjectPart[] parts = m_parts.GetArray(); 1108 SceneObjectPart[] parts = m_parts.GetArray();
807 for (int i = 0; i < parts.Length; i++) 1109 foreach (SceneObjectPart part in parts)
808 { 1110 {
809 SceneObjectPart part = parts[i];
810
811 Vector3 worldPos = part.GetWorldPosition(); 1111 Vector3 worldPos = part.GetWorldPosition();
812 Vector3 offset = worldPos - AbsolutePosition; 1112 Vector3 offset = worldPos - AbsolutePosition;
813 Quaternion worldRot; 1113 Quaternion worldRot;
814 if (part.ParentID == 0) 1114 if (part.ParentID == 0)
1115 {
815 worldRot = part.RotationOffset; 1116 worldRot = part.RotationOffset;
1117 }
816 else 1118 else
1119 {
817 worldRot = part.GetWorldRotation(); 1120 worldRot = part.GetWorldRotation();
1121 }
818 1122
819 Vector3 frontTopLeft; 1123 Vector3 frontTopLeft;
820 Vector3 frontTopRight; 1124 Vector3 frontTopRight;
@@ -826,6 +1130,8 @@ namespace OpenSim.Region.Framework.Scenes
826 Vector3 backBottomLeft; 1130 Vector3 backBottomLeft;
827 Vector3 backBottomRight; 1131 Vector3 backBottomRight;
828 1132
1133 // Vector3[] corners = new Vector3[8];
1134
829 Vector3 orig = Vector3.Zero; 1135 Vector3 orig = Vector3.Zero;
830 1136
831 frontTopLeft.X = orig.X - (part.Scale.X / 2); 1137 frontTopLeft.X = orig.X - (part.Scale.X / 2);
@@ -860,6 +1166,38 @@ namespace OpenSim.Region.Framework.Scenes
860 backBottomRight.Y = orig.Y + (part.Scale.Y / 2); 1166 backBottomRight.Y = orig.Y + (part.Scale.Y / 2);
861 backBottomRight.Z = orig.Z - (part.Scale.Z / 2); 1167 backBottomRight.Z = orig.Z - (part.Scale.Z / 2);
862 1168
1169
1170
1171 //m_log.InfoFormat("pre corner 1 is {0} {1} {2}", frontTopLeft.X, frontTopLeft.Y, frontTopLeft.Z);
1172 //m_log.InfoFormat("pre corner 2 is {0} {1} {2}", frontTopRight.X, frontTopRight.Y, frontTopRight.Z);
1173 //m_log.InfoFormat("pre corner 3 is {0} {1} {2}", frontBottomRight.X, frontBottomRight.Y, frontBottomRight.Z);
1174 //m_log.InfoFormat("pre corner 4 is {0} {1} {2}", frontBottomLeft.X, frontBottomLeft.Y, frontBottomLeft.Z);
1175 //m_log.InfoFormat("pre corner 5 is {0} {1} {2}", backTopLeft.X, backTopLeft.Y, backTopLeft.Z);
1176 //m_log.InfoFormat("pre corner 6 is {0} {1} {2}", backTopRight.X, backTopRight.Y, backTopRight.Z);
1177 //m_log.InfoFormat("pre corner 7 is {0} {1} {2}", backBottomRight.X, backBottomRight.Y, backBottomRight.Z);
1178 //m_log.InfoFormat("pre corner 8 is {0} {1} {2}", backBottomLeft.X, backBottomLeft.Y, backBottomLeft.Z);
1179
1180 //for (int i = 0; i < 8; i++)
1181 //{
1182 // corners[i] = corners[i] * worldRot;
1183 // corners[i] += offset;
1184
1185 // if (corners[i].X > maxX)
1186 // maxX = corners[i].X;
1187 // if (corners[i].X < minX)
1188 // minX = corners[i].X;
1189
1190 // if (corners[i].Y > maxY)
1191 // maxY = corners[i].Y;
1192 // if (corners[i].Y < minY)
1193 // minY = corners[i].Y;
1194
1195 // if (corners[i].Z > maxZ)
1196 // maxZ = corners[i].Y;
1197 // if (corners[i].Z < minZ)
1198 // minZ = corners[i].Z;
1199 //}
1200
863 frontTopLeft = frontTopLeft * worldRot; 1201 frontTopLeft = frontTopLeft * worldRot;
864 frontTopRight = frontTopRight * worldRot; 1202 frontTopRight = frontTopRight * worldRot;
865 frontBottomLeft = frontBottomLeft * worldRot; 1203 frontBottomLeft = frontBottomLeft * worldRot;
@@ -881,6 +1219,15 @@ namespace OpenSim.Region.Framework.Scenes
881 backTopLeft += offset; 1219 backTopLeft += offset;
882 backTopRight += offset; 1220 backTopRight += offset;
883 1221
1222 //m_log.InfoFormat("corner 1 is {0} {1} {2}", frontTopLeft.X, frontTopLeft.Y, frontTopLeft.Z);
1223 //m_log.InfoFormat("corner 2 is {0} {1} {2}", frontTopRight.X, frontTopRight.Y, frontTopRight.Z);
1224 //m_log.InfoFormat("corner 3 is {0} {1} {2}", frontBottomRight.X, frontBottomRight.Y, frontBottomRight.Z);
1225 //m_log.InfoFormat("corner 4 is {0} {1} {2}", frontBottomLeft.X, frontBottomLeft.Y, frontBottomLeft.Z);
1226 //m_log.InfoFormat("corner 5 is {0} {1} {2}", backTopLeft.X, backTopLeft.Y, backTopLeft.Z);
1227 //m_log.InfoFormat("corner 6 is {0} {1} {2}", backTopRight.X, backTopRight.Y, backTopRight.Z);
1228 //m_log.InfoFormat("corner 7 is {0} {1} {2}", backBottomRight.X, backBottomRight.Y, backBottomRight.Z);
1229 //m_log.InfoFormat("corner 8 is {0} {1} {2}", backBottomLeft.X, backBottomLeft.Y, backBottomLeft.Z);
1230
884 if (frontTopRight.X > maxX) 1231 if (frontTopRight.X > maxX)
885 maxX = frontTopRight.X; 1232 maxX = frontTopRight.X;
886 if (frontTopLeft.X > maxX) 1233 if (frontTopLeft.X > maxX)
@@ -1024,17 +1371,118 @@ namespace OpenSim.Region.Framework.Scenes
1024 1371
1025 #endregion 1372 #endregion
1026 1373
1374 public void GetResourcesCosts(SceneObjectPart apart,
1375 out float linksetResCost, out float linksetPhysCost, out float partCost, out float partPhysCost)
1376 {
1377 // this information may need to be cached
1378
1379 float cost;
1380 float tmpcost;
1381
1382 bool ComplexCost = false;
1383
1384 SceneObjectPart p;
1385 SceneObjectPart[] parts;
1386
1387 lock (m_parts)
1388 {
1389 parts = m_parts.GetArray();
1390 }
1391
1392 int nparts = parts.Length;
1393
1394
1395 for (int i = 0; i < nparts; i++)
1396 {
1397 p = parts[i];
1398
1399 if (p.UsesComplexCost)
1400 {
1401 ComplexCost = true;
1402 break;
1403 }
1404 }
1405
1406 if (ComplexCost)
1407 {
1408 linksetResCost = 0;
1409 linksetPhysCost = 0;
1410 partCost = 0;
1411 partPhysCost = 0;
1412
1413 for (int i = 0; i < nparts; i++)
1414 {
1415 p = parts[i];
1416
1417 cost = p.StreamingCost;
1418 tmpcost = p.SimulationCost;
1419 if (tmpcost > cost)
1420 cost = tmpcost;
1421 tmpcost = p.PhysicsCost;
1422 if (tmpcost > cost)
1423 cost = tmpcost;
1424
1425 linksetPhysCost += tmpcost;
1426 linksetResCost += cost;
1427
1428 if (p == apart)
1429 {
1430 partCost = cost;
1431 partPhysCost = tmpcost;
1432 }
1433 }
1434 }
1435 else
1436 {
1437 partPhysCost = 1.0f;
1438 partCost = 1.0f;
1439 linksetResCost = (float)nparts;
1440 linksetPhysCost = linksetResCost;
1441 }
1442 }
1443
1444 public void GetSelectedCosts(out float PhysCost, out float StreamCost, out float SimulCost)
1445 {
1446 SceneObjectPart p;
1447 SceneObjectPart[] parts;
1448
1449 lock (m_parts)
1450 {
1451 parts = m_parts.GetArray();
1452 }
1453
1454 int nparts = parts.Length;
1455
1456 PhysCost = 0;
1457 StreamCost = 0;
1458 SimulCost = 0;
1459
1460 for (int i = 0; i < nparts; i++)
1461 {
1462 p = parts[i];
1463
1464 StreamCost += p.StreamingCost;
1465 SimulCost += p.SimulationCost;
1466 PhysCost += p.PhysicsCost;
1467 }
1468 }
1469
1027 public void SaveScriptedState(XmlTextWriter writer) 1470 public void SaveScriptedState(XmlTextWriter writer)
1028 { 1471 {
1472 SaveScriptedState(writer, false);
1473 }
1474
1475 public void SaveScriptedState(XmlTextWriter writer, bool oldIDs)
1476 {
1029 XmlDocument doc = new XmlDocument(); 1477 XmlDocument doc = new XmlDocument();
1030 Dictionary<UUID,string> states = new Dictionary<UUID,string>(); 1478 Dictionary<UUID,string> states = new Dictionary<UUID,string>();
1031 1479
1032 SceneObjectPart[] parts = m_parts.GetArray(); 1480 SceneObjectPart[] parts = m_parts.GetArray();
1033 for (int i = 0; i < parts.Length; i++) 1481 for (int i = 0; i < parts.Length; i++)
1034 { 1482 {
1035 Dictionary<UUID, string> pstates = parts[i].Inventory.GetScriptStates(); 1483 Dictionary<UUID, string> pstates = parts[i].Inventory.GetScriptStates(oldIDs);
1036 foreach (KeyValuePair<UUID, string> kvp in pstates) 1484 foreach (KeyValuePair<UUID, string> kvp in pstates)
1037 states.Add(kvp.Key, kvp.Value); 1485 states[kvp.Key] = kvp.Value;
1038 } 1486 }
1039 1487
1040 if (states.Count > 0) 1488 if (states.Count > 0)
@@ -1054,6 +1502,169 @@ namespace OpenSim.Region.Framework.Scenes
1054 } 1502 }
1055 1503
1056 /// <summary> 1504 /// <summary>
1505 /// Add the avatar to this linkset (avatar is sat).
1506 /// </summary>
1507 /// <param name="agentID"></param>
1508 public void AddAvatar(UUID agentID)
1509 {
1510 ScenePresence presence;
1511 if (m_scene.TryGetScenePresence(agentID, out presence))
1512 {
1513 if (!m_linkedAvatars.Contains(presence))
1514 {
1515 m_linkedAvatars.Add(presence);
1516 }
1517 }
1518 }
1519
1520 /// <summary>
1521 /// Delete the avatar from this linkset (avatar is unsat).
1522 /// </summary>
1523 /// <param name="agentID"></param>
1524 public void DeleteAvatar(UUID agentID)
1525 {
1526 ScenePresence presence;
1527 if (m_scene.TryGetScenePresence(agentID, out presence))
1528 {
1529 if (m_linkedAvatars.Contains(presence))
1530 {
1531 m_linkedAvatars.Remove(presence);
1532 }
1533 }
1534 }
1535
1536 /// <summary>
1537 /// Returns the list of linked presences (avatars sat on this group)
1538 /// </summary>
1539 /// <param name="agentID"></param>
1540 public List<ScenePresence> GetLinkedAvatars()
1541 {
1542 return m_linkedAvatars;
1543 }
1544
1545 /// <summary>
1546 /// Attach this scene object to the given avatar.
1547 /// </summary>
1548 /// <param name="agentID"></param>
1549 /// <param name="attachmentpoint"></param>
1550 /// <param name="AttachOffset"></param>
1551 private void AttachToAgent(
1552 ScenePresence avatar, SceneObjectGroup so, uint attachmentpoint, Vector3 attachOffset, bool silent)
1553 {
1554 if (avatar != null)
1555 {
1556 // don't attach attachments to child agents
1557 if (avatar.IsChildAgent) return;
1558
1559 // Remove from database and parcel prim count
1560 m_scene.DeleteFromStorage(so.UUID);
1561 m_scene.EventManager.TriggerParcelPrimCountTainted();
1562
1563 so.AttachedAvatar = avatar.UUID;
1564
1565 if (so.RootPart.PhysActor != null)
1566 {
1567 m_scene.PhysicsScene.RemovePrim(so.RootPart.PhysActor);
1568 so.RootPart.PhysActor = null;
1569 }
1570
1571 so.AbsolutePosition = attachOffset;
1572 so.RootPart.AttachedPos = attachOffset;
1573 so.IsAttachment = true;
1574 so.RootPart.SetParentLocalId(avatar.LocalId);
1575 so.AttachmentPoint = attachmentpoint;
1576
1577 avatar.AddAttachment(this);
1578
1579 if (!silent)
1580 {
1581 // Killing it here will cause the client to deselect it
1582 // It then reappears on the avatar, deselected
1583 // through the full update below
1584 //
1585 if (IsSelected)
1586 {
1587 m_scene.SendKillObject(new List<uint> { m_rootPart.LocalId });
1588 }
1589
1590 IsSelected = false; // fudge....
1591 ScheduleGroupForFullUpdate();
1592 }
1593 }
1594 else
1595 {
1596 m_log.WarnFormat(
1597 "[SOG]: Tried to add attachment {0} to avatar with UUID {1} in region {2} but the avatar is not present",
1598 UUID, avatar.ControllingClient.AgentId, Scene.RegionInfo.RegionName);
1599 }
1600 }
1601
1602 public byte GetAttachmentPoint()
1603 {
1604 return m_rootPart.Shape.State;
1605 }
1606
1607 public void DetachToGround()
1608 {
1609 ScenePresence avatar = m_scene.GetScenePresence(AttachedAvatar);
1610 if (avatar == null)
1611 return;
1612
1613 avatar.RemoveAttachment(this);
1614
1615 Vector3 detachedpos = new Vector3(127f,127f,127f);
1616 if (avatar == null)
1617 return;
1618
1619 detachedpos = avatar.AbsolutePosition;
1620 FromItemID = UUID.Zero;
1621
1622 AbsolutePosition = detachedpos;
1623 AttachedAvatar = UUID.Zero;
1624
1625 //SceneObjectPart[] parts = m_parts.GetArray();
1626 //for (int i = 0; i < parts.Length; i++)
1627 // parts[i].AttachedAvatar = UUID.Zero;
1628
1629 m_rootPart.SetParentLocalId(0);
1630 AttachmentPoint = (byte)0;
1631 // must check if buildind should be true or false here
1632 m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_rootPart.VolumeDetectActive,false);
1633 HasGroupChanged = true;
1634 RootPart.Rezzed = DateTime.Now;
1635 RootPart.RemFlag(PrimFlags.TemporaryOnRez);
1636 AttachToBackup();
1637 m_scene.EventManager.TriggerParcelPrimCountTainted();
1638 m_rootPart.ScheduleFullUpdate();
1639 m_rootPart.ClearUndoState();
1640 }
1641
1642 public void DetachToInventoryPrep()
1643 {
1644 ScenePresence avatar = m_scene.GetScenePresence(AttachedAvatar);
1645 //Vector3 detachedpos = new Vector3(127f, 127f, 127f);
1646 if (avatar != null)
1647 {
1648 //detachedpos = avatar.AbsolutePosition;
1649 avatar.RemoveAttachment(this);
1650 }
1651
1652 AttachedAvatar = UUID.Zero;
1653
1654 /*SceneObjectPart[] parts = m_parts.GetArray();
1655 for (int i = 0; i < parts.Length; i++)
1656 parts[i].AttachedAvatar = UUID.Zero;*/
1657
1658 m_rootPart.SetParentLocalId(0);
1659 //m_rootPart.SetAttachmentPoint((byte)0);
1660 IsAttachment = false;
1661 AbsolutePosition = m_rootPart.AttachedPos;
1662 //m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_scene.m_physicalPrim);
1663 //AttachToBackup();
1664 //m_rootPart.ScheduleFullUpdate();
1665 }
1666
1667 /// <summary>
1057 /// 1668 ///
1058 /// </summary> 1669 /// </summary>
1059 /// <param name="part"></param> 1670 /// <param name="part"></param>
@@ -1093,7 +1704,10 @@ namespace OpenSim.Region.Framework.Scenes
1093 public void AddPart(SceneObjectPart part) 1704 public void AddPart(SceneObjectPart part)
1094 { 1705 {
1095 part.SetParent(this); 1706 part.SetParent(this);
1096 part.LinkNum = m_parts.Add(part.UUID, part); 1707 m_parts.Add(part.UUID, part);
1708
1709 part.LinkNum = m_parts.Count;
1710
1097 if (part.LinkNum == 2) 1711 if (part.LinkNum == 2)
1098 RootPart.LinkNum = 1; 1712 RootPart.LinkNum = 1;
1099 } 1713 }
@@ -1184,7 +1798,7 @@ namespace OpenSim.Region.Framework.Scenes
1184// "[SCENE OBJECT GROUP]: Processing OnGrabPart for {0} on {1} {2}, offsetPos {3}", 1798// "[SCENE OBJECT GROUP]: Processing OnGrabPart for {0} on {1} {2}, offsetPos {3}",
1185// remoteClient.Name, part.Name, part.LocalId, offsetPos); 1799// remoteClient.Name, part.Name, part.LocalId, offsetPos);
1186 1800
1187 part.StoreUndoState(); 1801// part.StoreUndoState();
1188 part.OnGrab(offsetPos, remoteClient); 1802 part.OnGrab(offsetPos, remoteClient);
1189 } 1803 }
1190 1804
@@ -1204,6 +1818,11 @@ namespace OpenSim.Region.Framework.Scenes
1204 /// <param name="silent">If true then deletion is not broadcast to clients</param> 1818 /// <param name="silent">If true then deletion is not broadcast to clients</param>
1205 public void DeleteGroupFromScene(bool silent) 1819 public void DeleteGroupFromScene(bool silent)
1206 { 1820 {
1821 // We need to keep track of this state in case this group is still queued for backup.
1822 IsDeleted = true;
1823
1824 DetachFromBackup();
1825
1207 SceneObjectPart[] parts = m_parts.GetArray(); 1826 SceneObjectPart[] parts = m_parts.GetArray();
1208 for (int i = 0; i < parts.Length; i++) 1827 for (int i = 0; i < parts.Length; i++)
1209 { 1828 {
@@ -1227,6 +1846,7 @@ namespace OpenSim.Region.Framework.Scenes
1227 } 1846 }
1228 }); 1847 });
1229 } 1848 }
1849
1230 } 1850 }
1231 1851
1232 public void AddScriptLPS(int count) 1852 public void AddScriptLPS(int count)
@@ -1296,28 +1916,43 @@ namespace OpenSim.Region.Framework.Scenes
1296 /// </summary> 1916 /// </summary>
1297 public void ApplyPhysics() 1917 public void ApplyPhysics()
1298 { 1918 {
1299 // Apply physics to the root prim
1300 m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_rootPart.VolumeDetectActive);
1301
1302 // Apply physics to child prims
1303 SceneObjectPart[] parts = m_parts.GetArray(); 1919 SceneObjectPart[] parts = m_parts.GetArray();
1304 if (parts.Length > 1) 1920 if (parts.Length > 1)
1305 { 1921 {
1922 ResetChildPrimPhysicsPositions();
1923
1924 // Apply physics to the root prim
1925 m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_rootPart.VolumeDetectActive, true);
1926
1927
1306 for (int i = 0; i < parts.Length; i++) 1928 for (int i = 0; i < parts.Length; i++)
1307 { 1929 {
1308 SceneObjectPart part = parts[i]; 1930 SceneObjectPart part = parts[i];
1309 if (part.LocalId != m_rootPart.LocalId) 1931 if (part.LocalId != m_rootPart.LocalId)
1310 part.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), part.VolumeDetectActive); 1932 part.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), part.VolumeDetectActive, true);
1311 } 1933 }
1312
1313 // Hack to get the physics scene geometries in the right spot 1934 // Hack to get the physics scene geometries in the right spot
1314 ResetChildPrimPhysicsPositions(); 1935// ResetChildPrimPhysicsPositions();
1936 if (m_rootPart.PhysActor != null)
1937 {
1938 m_rootPart.PhysActor.Building = false;
1939 }
1940 }
1941 else
1942 {
1943 // Apply physics to the root prim
1944 m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_rootPart.VolumeDetectActive, false);
1315 } 1945 }
1316 } 1946 }
1317 1947
1318 public void SetOwnerId(UUID userId) 1948 public void SetOwnerId(UUID userId)
1319 { 1949 {
1320 ForEachPart(delegate(SceneObjectPart part) { part.OwnerID = userId; }); 1950 ForEachPart(delegate(SceneObjectPart part)
1951 {
1952
1953 part.OwnerID = userId;
1954
1955 });
1321 } 1956 }
1322 1957
1323 public void ForEachPart(Action<SceneObjectPart> whatToDo) 1958 public void ForEachPart(Action<SceneObjectPart> whatToDo)
@@ -1349,11 +1984,17 @@ namespace OpenSim.Region.Framework.Scenes
1349 return; 1984 return;
1350 } 1985 }
1351 1986
1987 if ((RootPart.Flags & PrimFlags.TemporaryOnRez) != 0)
1988 return;
1989
1352 // Since this is the top of the section of call stack for backing up a particular scene object, don't let 1990 // Since this is the top of the section of call stack for backing up a particular scene object, don't let
1353 // any exception propogate upwards. 1991 // any exception propogate upwards.
1354 try 1992 try
1355 { 1993 {
1356 if (!m_scene.ShuttingDown) // if shutting down then there will be nothing to handle the return so leave till next restart 1994 if (!m_scene.ShuttingDown || // if shutting down then there will be nothing to handle the return so leave till next restart
1995 !m_scene.LoginsEnabled || // We're starting up or doing maintenance, don't mess with things
1996 m_scene.LoadingPrims) // Land may not be valid yet
1997
1357 { 1998 {
1358 ILandObject parcel = m_scene.LandChannel.GetLandObject( 1999 ILandObject parcel = m_scene.LandChannel.GetLandObject(
1359 m_rootPart.GroupPosition.X, m_rootPart.GroupPosition.Y); 2000 m_rootPart.GroupPosition.X, m_rootPart.GroupPosition.Y);
@@ -1380,6 +2021,7 @@ namespace OpenSim.Region.Framework.Scenes
1380 } 2021 }
1381 } 2022 }
1382 } 2023 }
2024
1383 } 2025 }
1384 2026
1385 if (m_scene.UseBackup && HasGroupChanged) 2027 if (m_scene.UseBackup && HasGroupChanged)
@@ -1387,10 +2029,30 @@ namespace OpenSim.Region.Framework.Scenes
1387 // don't backup while it's selected or you're asking for changes mid stream. 2029 // don't backup while it's selected or you're asking for changes mid stream.
1388 if (isTimeToPersist() || forcedBackup) 2030 if (isTimeToPersist() || forcedBackup)
1389 { 2031 {
2032 if (m_rootPart.PhysActor != null &&
2033 (!m_rootPart.PhysActor.IsPhysical))
2034 {
2035 // Possible ghost prim
2036 if (m_rootPart.PhysActor.Position != m_rootPart.GroupPosition)
2037 {
2038 foreach (SceneObjectPart part in m_parts.GetArray())
2039 {
2040 // Re-set physics actor positions and
2041 // orientations
2042 part.GroupPosition = m_rootPart.GroupPosition;
2043 }
2044 }
2045 }
1390// m_log.DebugFormat( 2046// m_log.DebugFormat(
1391// "[SCENE]: Storing {0}, {1} in {2}", 2047// "[SCENE]: Storing {0}, {1} in {2}",
1392// Name, UUID, m_scene.RegionInfo.RegionName); 2048// Name, UUID, m_scene.RegionInfo.RegionName);
1393 2049
2050 if (RootPart.Shape.PCode == 9 && RootPart.Shape.State != 0)
2051 {
2052 RootPart.Shape.State = 0;
2053 ScheduleGroupForFullUpdate();
2054 }
2055
1394 SceneObjectGroup backup_group = Copy(false); 2056 SceneObjectGroup backup_group = Copy(false);
1395 backup_group.RootPart.Velocity = RootPart.Velocity; 2057 backup_group.RootPart.Velocity = RootPart.Velocity;
1396 backup_group.RootPart.Acceleration = RootPart.Acceleration; 2058 backup_group.RootPart.Acceleration = RootPart.Acceleration;
@@ -1400,6 +2062,16 @@ namespace OpenSim.Region.Framework.Scenes
1400 HasGroupChangedDueToDelink = false; 2062 HasGroupChangedDueToDelink = false;
1401 2063
1402 m_scene.EventManager.TriggerOnSceneObjectPreSave(backup_group, this); 2064 m_scene.EventManager.TriggerOnSceneObjectPreSave(backup_group, this);
2065/*
2066 backup_group.ForEachPart(delegate(SceneObjectPart part)
2067 {
2068 if (part.KeyframeMotion != null)
2069 {
2070 part.KeyframeMotion = KeyframeMotion.FromData(backup_group, part.KeyframeMotion.Serialize());
2071// part.KeyframeMotion.UpdateSceneObject(this);
2072 }
2073 });
2074*/
1403 datastore.StoreObject(backup_group, m_scene.RegionInfo.RegionID); 2075 datastore.StoreObject(backup_group, m_scene.RegionInfo.RegionID);
1404 2076
1405 backup_group.ForEachPart(delegate(SceneObjectPart part) 2077 backup_group.ForEachPart(delegate(SceneObjectPart part)
@@ -1456,10 +2128,14 @@ namespace OpenSim.Region.Framework.Scenes
1456 /// <returns></returns> 2128 /// <returns></returns>
1457 public SceneObjectGroup Copy(bool userExposed) 2129 public SceneObjectGroup Copy(bool userExposed)
1458 { 2130 {
2131 m_dupeInProgress = true;
1459 SceneObjectGroup dupe = (SceneObjectGroup)MemberwiseClone(); 2132 SceneObjectGroup dupe = (SceneObjectGroup)MemberwiseClone();
1460 dupe.m_isBackedUp = false; 2133 dupe.m_isBackedUp = false;
1461 dupe.m_parts = new MapAndArray<OpenMetaverse.UUID, SceneObjectPart>(); 2134 dupe.m_parts = new MapAndArray<OpenMetaverse.UUID, SceneObjectPart>();
1462 2135
2136 // new group as no sitting avatars
2137 dupe.m_linkedAvatars = new List<ScenePresence>();
2138
1463 // Warning, The following code related to previousAttachmentStatus is needed so that clones of 2139 // Warning, The following code related to previousAttachmentStatus is needed so that clones of
1464 // attachments do not bordercross while they're being duplicated. This is hacktastic! 2140 // attachments do not bordercross while they're being duplicated. This is hacktastic!
1465 // Normally, setting AbsolutePosition will bordercross a prim if it's outside the region! 2141 // Normally, setting AbsolutePosition will bordercross a prim if it's outside the region!
@@ -1470,7 +2146,7 @@ namespace OpenSim.Region.Framework.Scenes
1470 // This is only necessary when userExposed is false! 2146 // This is only necessary when userExposed is false!
1471 2147
1472 bool previousAttachmentStatus = dupe.IsAttachment; 2148 bool previousAttachmentStatus = dupe.IsAttachment;
1473 2149
1474 if (!userExposed) 2150 if (!userExposed)
1475 dupe.IsAttachment = true; 2151 dupe.IsAttachment = true;
1476 2152
@@ -1483,16 +2159,17 @@ namespace OpenSim.Region.Framework.Scenes
1483 2159
1484 dupe.CopyRootPart(m_rootPart, OwnerID, GroupID, userExposed); 2160 dupe.CopyRootPart(m_rootPart, OwnerID, GroupID, userExposed);
1485 dupe.m_rootPart.LinkNum = m_rootPart.LinkNum; 2161 dupe.m_rootPart.LinkNum = m_rootPart.LinkNum;
2162
1486 2163
1487 if (userExposed) 2164 if (userExposed)
1488 dupe.m_rootPart.TrimPermissions(); 2165 dupe.m_rootPart.TrimPermissions();
1489 2166
1490 List<SceneObjectPart> partList = new List<SceneObjectPart>(m_parts.GetArray()); 2167 List<SceneObjectPart> partList = new List<SceneObjectPart>(m_parts.GetArray());
1491 2168
1492 partList.Sort(delegate(SceneObjectPart p1, SceneObjectPart p2) 2169 partList.Sort(delegate(SceneObjectPart p1, SceneObjectPart p2)
1493 { 2170 {
1494 return p1.LinkNum.CompareTo(p2.LinkNum); 2171 return p1.LinkNum.CompareTo(p2.LinkNum);
1495 } 2172 }
1496 ); 2173 );
1497 2174
1498 foreach (SceneObjectPart part in partList) 2175 foreach (SceneObjectPart part in partList)
@@ -1502,41 +2179,56 @@ namespace OpenSim.Region.Framework.Scenes
1502 { 2179 {
1503 newPart = dupe.CopyPart(part, OwnerID, GroupID, userExposed); 2180 newPart = dupe.CopyPart(part, OwnerID, GroupID, userExposed);
1504 newPart.LinkNum = part.LinkNum; 2181 newPart.LinkNum = part.LinkNum;
1505 } 2182 if (userExposed)
2183 newPart.ParentID = dupe.m_rootPart.LocalId;
2184 }
1506 else 2185 else
1507 { 2186 {
1508 newPart = dupe.m_rootPart; 2187 newPart = dupe.m_rootPart;
1509 } 2188 }
2189/*
2190 bool isphys = ((newPart.Flags & PrimFlags.Physics) != 0);
2191 bool isphan = ((newPart.Flags & PrimFlags.Phantom) != 0);
1510 2192
1511 // Need to duplicate the physics actor as well 2193 // Need to duplicate the physics actor as well
1512 PhysicsActor originalPartPa = part.PhysActor; 2194 if (userExposed && (isphys || !isphan || newPart.VolumeDetectActive))
1513 if (originalPartPa != null && userExposed)
1514 { 2195 {
1515 PrimitiveBaseShape pbs = newPart.Shape; 2196 PrimitiveBaseShape pbs = newPart.Shape;
1516
1517 newPart.PhysActor 2197 newPart.PhysActor
1518 = m_scene.PhysicsScene.AddPrimShape( 2198 = m_scene.PhysicsScene.AddPrimShape(
1519 string.Format("{0}/{1}", newPart.Name, newPart.UUID), 2199 string.Format("{0}/{1}", newPart.Name, newPart.UUID),
1520 pbs, 2200 pbs,
1521 newPart.AbsolutePosition, 2201 newPart.AbsolutePosition,
1522 newPart.Scale, 2202 newPart.Scale,
1523 newPart.RotationOffset, 2203 newPart.GetWorldRotation(),
1524 originalPartPa.IsPhysical, 2204 isphys,
2205 isphan,
1525 newPart.LocalId); 2206 newPart.LocalId);
1526 2207
1527 newPart.DoPhysicsPropertyUpdate(originalPartPa.IsPhysical, true); 2208 newPart.DoPhysicsPropertyUpdate(isphys, true);
1528 } 2209 */
2210 if (userExposed)
2211 newPart.ApplyPhysics((uint)newPart.Flags,newPart.VolumeDetectActive,true);
2212// }
2213 // copy keyframemotion
2214 if (part.KeyframeMotion != null)
2215 newPart.KeyframeMotion = part.KeyframeMotion.Copy(dupe);
1529 } 2216 }
1530 2217
1531 if (userExposed) 2218 if (userExposed)
1532 { 2219 {
1533 dupe.UpdateParentIDs(); 2220// done above dupe.UpdateParentIDs();
2221
2222 if (dupe.m_rootPart.PhysActor != null)
2223 dupe.m_rootPart.PhysActor.Building = false; // tell physics to finish building
2224
1534 dupe.HasGroupChanged = true; 2225 dupe.HasGroupChanged = true;
1535 dupe.AttachToBackup(); 2226 dupe.AttachToBackup();
1536 2227
1537 ScheduleGroupForFullUpdate(); 2228 ScheduleGroupForFullUpdate();
1538 } 2229 }
1539 2230
2231 m_dupeInProgress = false;
1540 return dupe; 2232 return dupe;
1541 } 2233 }
1542 2234
@@ -1548,11 +2240,24 @@ namespace OpenSim.Region.Framework.Scenes
1548 /// <param name="cGroupID"></param> 2240 /// <param name="cGroupID"></param>
1549 public void CopyRootPart(SceneObjectPart part, UUID cAgentID, UUID cGroupID, bool userExposed) 2241 public void CopyRootPart(SceneObjectPart part, UUID cAgentID, UUID cGroupID, bool userExposed)
1550 { 2242 {
1551 SetRootPart(part.Copy(m_scene.AllocateLocalId(), OwnerID, GroupID, 0, userExposed)); 2243 // SetRootPart(part.Copy(m_scene.AllocateLocalId(), OwnerID, GroupID, 0, userExposed));
2244 // give newpart a new local ID lettng old part keep same
2245 SceneObjectPart newpart = part.Copy(part.LocalId, OwnerID, GroupID, 0, userExposed);
2246 newpart.LocalId = m_scene.AllocateLocalId();
2247
2248 SetRootPart(newpart);
2249 if (userExposed)
2250 RootPart.Velocity = Vector3.Zero; // In case source is moving
1552 } 2251 }
1553 2252
1554 public void ScriptSetPhysicsStatus(bool usePhysics) 2253 public void ScriptSetPhysicsStatus(bool usePhysics)
1555 { 2254 {
2255 if (usePhysics)
2256 {
2257 if (RootPart.KeyframeMotion != null)
2258 RootPart.KeyframeMotion.Stop();
2259 RootPart.KeyframeMotion = null;
2260 }
1556 UpdatePrimFlags(RootPart.LocalId, usePhysics, IsTemporary, IsPhantom, IsVolumeDetect); 2261 UpdatePrimFlags(RootPart.LocalId, usePhysics, IsTemporary, IsPhantom, IsVolumeDetect);
1557 } 2262 }
1558 2263
@@ -1600,13 +2305,14 @@ namespace OpenSim.Region.Framework.Scenes
1600 2305
1601 if (pa != null) 2306 if (pa != null)
1602 { 2307 {
1603 pa.AddForce(impulse, true); 2308 // false to be applied as a impulse
2309 pa.AddForce(impulse, false);
1604 m_scene.PhysicsScene.AddPhysicsActorTaint(pa); 2310 m_scene.PhysicsScene.AddPhysicsActorTaint(pa);
1605 } 2311 }
1606 } 2312 }
1607 } 2313 }
1608 2314
1609 public void applyAngularImpulse(Vector3 impulse) 2315 public void ApplyAngularImpulse(Vector3 impulse)
1610 { 2316 {
1611 PhysicsActor pa = RootPart.PhysActor; 2317 PhysicsActor pa = RootPart.PhysActor;
1612 2318
@@ -1614,21 +2320,8 @@ namespace OpenSim.Region.Framework.Scenes
1614 { 2320 {
1615 if (!IsAttachment) 2321 if (!IsAttachment)
1616 { 2322 {
1617 pa.AddAngularForce(impulse, true); 2323 // false to be applied as a impulse
1618 m_scene.PhysicsScene.AddPhysicsActorTaint(pa); 2324 pa.AddAngularForce(impulse, false);
1619 }
1620 }
1621 }
1622
1623 public void setAngularImpulse(Vector3 impulse)
1624 {
1625 PhysicsActor pa = RootPart.PhysActor;
1626
1627 if (pa != null)
1628 {
1629 if (!IsAttachment)
1630 {
1631 pa.Torque = impulse;
1632 m_scene.PhysicsScene.AddPhysicsActorTaint(pa); 2325 m_scene.PhysicsScene.AddPhysicsActorTaint(pa);
1633 } 2326 }
1634 } 2327 }
@@ -1636,20 +2329,10 @@ namespace OpenSim.Region.Framework.Scenes
1636 2329
1637 public Vector3 GetTorque() 2330 public Vector3 GetTorque()
1638 { 2331 {
1639 PhysicsActor pa = RootPart.PhysActor; 2332 return RootPart.Torque;
1640
1641 if (pa != null)
1642 {
1643 if (!IsAttachment)
1644 {
1645 Vector3 torque = pa.Torque;
1646 return torque;
1647 }
1648 }
1649
1650 return Vector3.Zero;
1651 } 2333 }
1652 2334
2335 // This is used by both Double-Click Auto-Pilot and llMoveToTarget() in an attached object
1653 public void moveToTarget(Vector3 target, float tau) 2336 public void moveToTarget(Vector3 target, float tau)
1654 { 2337 {
1655 if (IsAttachment) 2338 if (IsAttachment)
@@ -1681,6 +2364,46 @@ namespace OpenSim.Region.Framework.Scenes
1681 pa.PIDActive = false; 2364 pa.PIDActive = false;
1682 } 2365 }
1683 2366
2367 public void rotLookAt(Quaternion target, float strength, float damping)
2368 {
2369 SceneObjectPart rootpart = m_rootPart;
2370 if (rootpart != null)
2371 {
2372 if (IsAttachment)
2373 {
2374 /*
2375 ScenePresence avatar = m_scene.GetScenePresence(rootpart.AttachedAvatar);
2376 if (avatar != null)
2377 {
2378 Rotate the Av?
2379 } */
2380 }
2381 else
2382 {
2383 if (rootpart.PhysActor != null)
2384 { // APID must be implemented in your physics system for this to function.
2385 rootpart.PhysActor.APIDTarget = new Quaternion(target.X, target.Y, target.Z, target.W);
2386 rootpart.PhysActor.APIDStrength = strength;
2387 rootpart.PhysActor.APIDDamping = damping;
2388 rootpart.PhysActor.APIDActive = true;
2389 }
2390 }
2391 }
2392 }
2393
2394 public void stopLookAt()
2395 {
2396 SceneObjectPart rootpart = m_rootPart;
2397 if (rootpart != null)
2398 {
2399 if (rootpart.PhysActor != null)
2400 { // APID must be implemented in your physics system for this to function.
2401 rootpart.PhysActor.APIDActive = false;
2402 }
2403 }
2404
2405 }
2406
1684 /// <summary> 2407 /// <summary>
1685 /// Uses a PID to attempt to clamp the object on the Z axis at the given height over tau seconds. 2408 /// Uses a PID to attempt to clamp the object on the Z axis at the given height over tau seconds.
1686 /// </summary> 2409 /// </summary>
@@ -1697,7 +2420,7 @@ namespace OpenSim.Region.Framework.Scenes
1697 { 2420 {
1698 pa.PIDHoverHeight = height; 2421 pa.PIDHoverHeight = height;
1699 pa.PIDHoverType = hoverType; 2422 pa.PIDHoverType = hoverType;
1700 pa.PIDTau = tau; 2423 pa.PIDHoverTau = tau;
1701 pa.PIDHoverActive = true; 2424 pa.PIDHoverActive = true;
1702 } 2425 }
1703 else 2426 else
@@ -1737,7 +2460,12 @@ namespace OpenSim.Region.Framework.Scenes
1737 /// <param name="cGroupID"></param> 2460 /// <param name="cGroupID"></param>
1738 public SceneObjectPart CopyPart(SceneObjectPart part, UUID cAgentID, UUID cGroupID, bool userExposed) 2461 public SceneObjectPart CopyPart(SceneObjectPart part, UUID cAgentID, UUID cGroupID, bool userExposed)
1739 { 2462 {
1740 SceneObjectPart newPart = part.Copy(m_scene.AllocateLocalId(), OwnerID, GroupID, m_parts.Count, userExposed); 2463 // give new ID to the new part, letting old keep original
2464 // SceneObjectPart newPart = part.Copy(m_scene.AllocateLocalId(), OwnerID, GroupID, m_parts.Count, userExposed);
2465 SceneObjectPart newPart = part.Copy(part.LocalId, OwnerID, GroupID, m_parts.Count, userExposed);
2466 newPart.LocalId = m_scene.AllocateLocalId();
2467 newPart.SetParent(this);
2468
1741 AddPart(newPart); 2469 AddPart(newPart);
1742 2470
1743 SetPartAsNonRoot(newPart); 2471 SetPartAsNonRoot(newPart);
@@ -1876,11 +2604,11 @@ namespace OpenSim.Region.Framework.Scenes
1876 /// Immediately send a full update for this scene object. 2604 /// Immediately send a full update for this scene object.
1877 /// </summary> 2605 /// </summary>
1878 public void SendGroupFullUpdate() 2606 public void SendGroupFullUpdate()
1879 { 2607 {
1880 if (IsDeleted) 2608 if (IsDeleted)
1881 return; 2609 return;
1882 2610
1883// m_log.DebugFormat("[SOG]: Sending immediate full group update for {0} {1}", Name, UUID); 2611// m_log.DebugFormat("[SOG]: Sending immediate full group update for {0} {1}", Name, UUID);
1884 2612
1885 RootPart.SendFullUpdateToAllClients(); 2613 RootPart.SendFullUpdateToAllClients();
1886 2614
@@ -2036,6 +2764,11 @@ namespace OpenSim.Region.Framework.Scenes
2036 // 'linkPart' == the root of the group being linked into this group 2764 // 'linkPart' == the root of the group being linked into this group
2037 SceneObjectPart linkPart = objectGroup.m_rootPart; 2765 SceneObjectPart linkPart = objectGroup.m_rootPart;
2038 2766
2767 if (m_rootPart.PhysActor != null)
2768 m_rootPart.PhysActor.Building = true;
2769 if (linkPart.PhysActor != null)
2770 linkPart.PhysActor.Building = true;
2771
2039 // physics flags from group to be applied to linked parts 2772 // physics flags from group to be applied to linked parts
2040 bool grpusephys = UsesPhysics; 2773 bool grpusephys = UsesPhysics;
2041 bool grptemporary = IsTemporary; 2774 bool grptemporary = IsTemporary;
@@ -2061,12 +2794,12 @@ namespace OpenSim.Region.Framework.Scenes
2061 Vector3 axPos = linkPart.OffsetPosition; 2794 Vector3 axPos = linkPart.OffsetPosition;
2062 // Rotate the linking root SOP's position to be relative to the new root prim 2795 // Rotate the linking root SOP's position to be relative to the new root prim
2063 Quaternion parentRot = m_rootPart.RotationOffset; 2796 Quaternion parentRot = m_rootPart.RotationOffset;
2064 axPos *= Quaternion.Inverse(parentRot); 2797 axPos *= Quaternion.Conjugate(parentRot);
2065 linkPart.OffsetPosition = axPos; 2798 linkPart.OffsetPosition = axPos;
2066 2799
2067 // Make the linking root SOP's rotation relative to the new root prim 2800 // Make the linking root SOP's rotation relative to the new root prim
2068 Quaternion oldRot = linkPart.RotationOffset; 2801 Quaternion oldRot = linkPart.RotationOffset;
2069 Quaternion newRot = Quaternion.Inverse(parentRot) * oldRot; 2802 Quaternion newRot = Quaternion.Conjugate(parentRot) * oldRot;
2070 linkPart.RotationOffset = newRot; 2803 linkPart.RotationOffset = newRot;
2071 2804
2072 // If there is only one SOP in a SOG, the LinkNum is zero. I.e., not a linkset. 2805 // If there is only one SOP in a SOG, the LinkNum is zero. I.e., not a linkset.
@@ -2100,7 +2833,7 @@ namespace OpenSim.Region.Framework.Scenes
2100 linkPart.CreateSelected = true; 2833 linkPart.CreateSelected = true;
2101 2834
2102 // let physics know preserve part volume dtc messy since UpdatePrimFlags doesn't look to parent changes for now 2835 // let physics know preserve part volume dtc messy since UpdatePrimFlags doesn't look to parent changes for now
2103 linkPart.UpdatePrimFlags(grpusephys, grptemporary, (IsPhantom || (linkPart.Flags & PrimFlags.Phantom) != 0), linkPart.VolumeDetectActive); 2836 linkPart.UpdatePrimFlags(grpusephys, grptemporary, (IsPhantom || (linkPart.Flags & PrimFlags.Phantom) != 0), linkPart.VolumeDetectActive, true);
2104 2837
2105 // If the added SOP is physical, also tell the physics engine about the link relationship. 2838 // If the added SOP is physical, also tell the physics engine about the link relationship.
2106 if (linkPart.PhysActor != null && m_rootPart.PhysActor != null && m_rootPart.PhysActor.IsPhysical) 2839 if (linkPart.PhysActor != null && m_rootPart.PhysActor != null && m_rootPart.PhysActor.IsPhysical)
@@ -2110,6 +2843,7 @@ namespace OpenSim.Region.Framework.Scenes
2110 } 2843 }
2111 2844
2112 linkPart.LinkNum = linkNum++; 2845 linkPart.LinkNum = linkNum++;
2846 linkPart.UpdatePrimFlags(UsesPhysics, IsTemporary, IsPhantom, IsVolumeDetect, false);
2113 2847
2114 // Get a list of the SOP's in the old group in order of their linknum's. 2848 // Get a list of the SOP's in the old group in order of their linknum's.
2115 SceneObjectPart[] ogParts = objectGroup.Parts; 2849 SceneObjectPart[] ogParts = objectGroup.Parts;
@@ -2128,7 +2862,7 @@ namespace OpenSim.Region.Framework.Scenes
2128 2862
2129 // Update the physics flags for the newly added SOP 2863 // Update the physics flags for the newly added SOP
2130 // (Is this necessary? LinkNonRootPart() has already called UpdatePrimFlags but with different flags!??) 2864 // (Is this necessary? LinkNonRootPart() has already called UpdatePrimFlags but with different flags!??)
2131 part.UpdatePrimFlags(grpusephys, grptemporary, (IsPhantom || (part.Flags & PrimFlags.Phantom) != 0), part.VolumeDetectActive); 2865 part.UpdatePrimFlags(grpusephys, grptemporary, (IsPhantom || (part.Flags & PrimFlags.Phantom) != 0), part.VolumeDetectActive, true);
2132 2866
2133 // If the added SOP is physical, also tell the physics engine about the link relationship. 2867 // If the added SOP is physical, also tell the physics engine about the link relationship.
2134 if (part.PhysActor != null && m_rootPart.PhysActor != null && m_rootPart.PhysActor.IsPhysical) 2868 if (part.PhysActor != null && m_rootPart.PhysActor != null && m_rootPart.PhysActor.IsPhysical)
@@ -2146,7 +2880,7 @@ namespace OpenSim.Region.Framework.Scenes
2146 objectGroup.IsDeleted = true; 2880 objectGroup.IsDeleted = true;
2147 2881
2148 objectGroup.m_parts.Clear(); 2882 objectGroup.m_parts.Clear();
2149 2883
2150 // Can't do this yet since backup still makes use of the root part without any synchronization 2884 // Can't do this yet since backup still makes use of the root part without any synchronization
2151// objectGroup.m_rootPart = null; 2885// objectGroup.m_rootPart = null;
2152 2886
@@ -2160,6 +2894,9 @@ namespace OpenSim.Region.Framework.Scenes
2160 // unmoved prims! 2894 // unmoved prims!
2161 ResetChildPrimPhysicsPositions(); 2895 ResetChildPrimPhysicsPositions();
2162 2896
2897 if (m_rootPart.PhysActor != null)
2898 m_rootPart.PhysActor.Building = false;
2899
2163 //HasGroupChanged = true; 2900 //HasGroupChanged = true;
2164 //ScheduleGroupForFullUpdate(); 2901 //ScheduleGroupForFullUpdate();
2165 } 2902 }
@@ -2227,7 +2964,10 @@ namespace OpenSim.Region.Framework.Scenes
2227// m_log.DebugFormat( 2964// m_log.DebugFormat(
2228// "[SCENE OBJECT GROUP]: Delinking part {0}, {1} from group with root part {2}, {3}", 2965// "[SCENE OBJECT GROUP]: Delinking part {0}, {1} from group with root part {2}, {3}",
2229// linkPart.Name, linkPart.UUID, RootPart.Name, RootPart.UUID); 2966// linkPart.Name, linkPart.UUID, RootPart.Name, RootPart.UUID);
2230 2967
2968 if (m_rootPart.PhysActor != null)
2969 m_rootPart.PhysActor.Building = true;
2970
2231 linkPart.ClearUndoState(); 2971 linkPart.ClearUndoState();
2232 2972
2233 Vector3 worldPos = linkPart.GetWorldPosition(); 2973 Vector3 worldPos = linkPart.GetWorldPosition();
@@ -2298,6 +3038,14 @@ namespace OpenSim.Region.Framework.Scenes
2298 3038
2299 // When we delete a group, we currently have to force persist to the database if the object id has changed 3039 // When we delete a group, we currently have to force persist to the database if the object id has changed
2300 // (since delete works by deleting all rows which have a given object id) 3040 // (since delete works by deleting all rows which have a given object id)
3041
3042 // this is as it seems to be in sl now
3043 if(linkPart.PhysicsShapeType == (byte)PhysShapeType.none)
3044 linkPart.PhysicsShapeType = linkPart.DefaultPhysicsShapeType(); // root prims can't have type none for now
3045
3046 if (m_rootPart.PhysActor != null)
3047 m_rootPart.PhysActor.Building = false;
3048
2301 objectGroup.HasGroupChangedDueToDelink = true; 3049 objectGroup.HasGroupChangedDueToDelink = true;
2302 3050
2303 return objectGroup; 3051 return objectGroup;
@@ -2309,6 +3057,8 @@ namespace OpenSim.Region.Framework.Scenes
2309 /// <param name="objectGroup"></param> 3057 /// <param name="objectGroup"></param>
2310 public virtual void DetachFromBackup() 3058 public virtual void DetachFromBackup()
2311 { 3059 {
3060 if (m_scene != null)
3061 m_scene.SceneGraph.FireDetachFromBackup(this);
2312 if (m_isBackedUp && Scene != null) 3062 if (m_isBackedUp && Scene != null)
2313 m_scene.EventManager.OnBackup -= ProcessBackup; 3063 m_scene.EventManager.OnBackup -= ProcessBackup;
2314 3064
@@ -2329,7 +3079,8 @@ namespace OpenSim.Region.Framework.Scenes
2329 Vector3 axPos = part.OffsetPosition; 3079 Vector3 axPos = part.OffsetPosition;
2330 axPos *= parentRot; 3080 axPos *= parentRot;
2331 part.OffsetPosition = axPos; 3081 part.OffsetPosition = axPos;
2332 part.GroupPosition = oldGroupPosition + part.OffsetPosition; 3082 Vector3 newPos = oldGroupPosition + part.OffsetPosition;
3083 part.GroupPosition = newPos;
2333 part.OffsetPosition = Vector3.Zero; 3084 part.OffsetPosition = Vector3.Zero;
2334 3085
2335 // Compution our rotation to be not relative to the old parent 3086 // Compution our rotation to be not relative to the old parent
@@ -2344,7 +3095,7 @@ namespace OpenSim.Region.Framework.Scenes
2344 part.LinkNum = linkNum; 3095 part.LinkNum = linkNum;
2345 3096
2346 // Compute the new position of this SOP relative to the group position 3097 // Compute the new position of this SOP relative to the group position
2347 part.OffsetPosition = part.GroupPosition - AbsolutePosition; 3098 part.OffsetPosition = newPos - AbsolutePosition;
2348 3099
2349 // (radams1 20120711: I don't know why part.OffsetPosition is set multiple times. 3100 // (radams1 20120711: I don't know why part.OffsetPosition is set multiple times.
2350 // It would have the affect of setting the physics engine position multiple 3101 // It would have the affect of setting the physics engine position multiple
@@ -2354,18 +3105,19 @@ namespace OpenSim.Region.Framework.Scenes
2354 // Rotate the relative position by the rotation of the group 3105 // Rotate the relative position by the rotation of the group
2355 Quaternion rootRotation = m_rootPart.RotationOffset; 3106 Quaternion rootRotation = m_rootPart.RotationOffset;
2356 Vector3 pos = part.OffsetPosition; 3107 Vector3 pos = part.OffsetPosition;
2357 pos *= Quaternion.Inverse(rootRotation); 3108 pos *= Quaternion.Conjugate(rootRotation);
2358 part.OffsetPosition = pos; 3109 part.OffsetPosition = pos;
2359 3110
2360 // Compute the SOP's rotation relative to the rotation of the group. 3111 // Compute the SOP's rotation relative to the rotation of the group.
2361 parentRot = m_rootPart.RotationOffset; 3112 parentRot = m_rootPart.RotationOffset;
2362 oldRot = part.RotationOffset; 3113 oldRot = part.RotationOffset;
2363 Quaternion newRot = Quaternion.Inverse(parentRot) * oldRot; 3114 Quaternion newRot = Quaternion.Conjugate(parentRot) * worldRot;
2364 part.RotationOffset = newRot; 3115 part.RotationOffset = newRot;
2365 3116
2366 // Since this SOP's state has changed, push those changes into the physics engine 3117 // Since this SOP's state has changed, push those changes into the physics engine
2367 // and the simulator. 3118 // and the simulator.
2368 part.UpdatePrimFlags(UsesPhysics, IsTemporary, IsPhantom, IsVolumeDetect); 3119 // done on caller
3120// part.UpdatePrimFlags(UsesPhysics, IsTemporary, IsPhantom, IsVolumeDetect, false);
2369 } 3121 }
2370 3122
2371 /// <summary> 3123 /// <summary>
@@ -2387,10 +3139,14 @@ namespace OpenSim.Region.Framework.Scenes
2387 { 3139 {
2388 if (!m_rootPart.BlockGrab) 3140 if (!m_rootPart.BlockGrab)
2389 { 3141 {
2390 Vector3 llmoveforce = pos - AbsolutePosition; 3142/* Vector3 llmoveforce = pos - AbsolutePosition;
2391 Vector3 grabforce = llmoveforce; 3143 Vector3 grabforce = llmoveforce;
2392 grabforce = (grabforce / 10) * pa.Mass; 3144 grabforce = (grabforce / 10) * pa.Mass;
2393 pa.AddForce(grabforce, true); 3145 */
3146 // empirically convert distance diference to a impulse
3147 Vector3 grabforce = pos - AbsolutePosition;
3148 grabforce = grabforce * (pa.Mass/ 10.0f);
3149 pa.AddForce(grabforce, false);
2394 m_scene.PhysicsScene.AddPhysicsActorTaint(pa); 3150 m_scene.PhysicsScene.AddPhysicsActorTaint(pa);
2395 } 3151 }
2396 } 3152 }
@@ -2586,6 +3342,8 @@ namespace OpenSim.Region.Framework.Scenes
2586 /// <param name="SetVolumeDetect"></param> 3342 /// <param name="SetVolumeDetect"></param>
2587 public void UpdatePrimFlags(uint localID, bool UsePhysics, bool SetTemporary, bool SetPhantom, bool SetVolumeDetect) 3343 public void UpdatePrimFlags(uint localID, bool UsePhysics, bool SetTemporary, bool SetPhantom, bool SetVolumeDetect)
2588 { 3344 {
3345 HasGroupChanged = true;
3346
2589 SceneObjectPart selectionPart = GetPart(localID); 3347 SceneObjectPart selectionPart = GetPart(localID);
2590 3348
2591 if (SetTemporary && Scene != null) 3349 if (SetTemporary && Scene != null)
@@ -2616,8 +3374,22 @@ namespace OpenSim.Region.Framework.Scenes
2616 } 3374 }
2617 } 3375 }
2618 3376
2619 for (int i = 0; i < parts.Length; i++) 3377 if (parts.Length > 1)
2620 parts[i].UpdatePrimFlags(UsePhysics, SetTemporary, SetPhantom, SetVolumeDetect); 3378 {
3379 m_rootPart.UpdatePrimFlags(UsePhysics, SetTemporary, SetPhantom, SetVolumeDetect, true);
3380
3381 for (int i = 0; i < parts.Length; i++)
3382 {
3383
3384 if (parts[i].UUID != m_rootPart.UUID)
3385 parts[i].UpdatePrimFlags(UsePhysics, SetTemporary, SetPhantom, SetVolumeDetect, true);
3386 }
3387
3388 if (m_rootPart.PhysActor != null)
3389 m_rootPart.PhysActor.Building = false;
3390 }
3391 else
3392 m_rootPart.UpdatePrimFlags(UsePhysics, SetTemporary, SetPhantom, SetVolumeDetect, false);
2621 } 3393 }
2622 } 3394 }
2623 3395
@@ -2630,6 +3402,17 @@ namespace OpenSim.Region.Framework.Scenes
2630 } 3402 }
2631 } 3403 }
2632 3404
3405
3406
3407 /// <summary>
3408 /// Gets the number of parts
3409 /// </summary>
3410 /// <returns></returns>
3411 public int GetPartCount()
3412 {
3413 return Parts.Count();
3414 }
3415
2633 /// <summary> 3416 /// <summary>
2634 /// Update the texture entry for this part 3417 /// Update the texture entry for this part
2635 /// </summary> 3418 /// </summary>
@@ -2700,11 +3483,6 @@ namespace OpenSim.Region.Framework.Scenes
2700 /// <param name="scale"></param> 3483 /// <param name="scale"></param>
2701 public void GroupResize(Vector3 scale) 3484 public void GroupResize(Vector3 scale)
2702 { 3485 {
2703// m_log.DebugFormat(
2704// "[SCENE OBJECT GROUP]: Group resizing {0} {1} from {2} to {3}", Name, LocalId, RootPart.Scale, scale);
2705
2706 RootPart.StoreUndoState(true);
2707
2708 scale.X = Math.Max(Scene.m_minNonphys, Math.Min(Scene.m_maxNonphys, scale.X)); 3486 scale.X = Math.Max(Scene.m_minNonphys, Math.Min(Scene.m_maxNonphys, scale.X));
2709 scale.Y = Math.Max(Scene.m_minNonphys, Math.Min(Scene.m_maxNonphys, scale.Y)); 3487 scale.Y = Math.Max(Scene.m_minNonphys, Math.Min(Scene.m_maxNonphys, scale.Y));
2710 scale.Z = Math.Max(Scene.m_minNonphys, Math.Min(Scene.m_maxNonphys, scale.Z)); 3488 scale.Z = Math.Max(Scene.m_minNonphys, Math.Min(Scene.m_maxNonphys, scale.Z));
@@ -2731,7 +3509,6 @@ namespace OpenSim.Region.Framework.Scenes
2731 SceneObjectPart obPart = parts[i]; 3509 SceneObjectPart obPart = parts[i];
2732 if (obPart.UUID != m_rootPart.UUID) 3510 if (obPart.UUID != m_rootPart.UUID)
2733 { 3511 {
2734// obPart.IgnoreUndoUpdate = true;
2735 Vector3 oldSize = new Vector3(obPart.Scale); 3512 Vector3 oldSize = new Vector3(obPart.Scale);
2736 3513
2737 float f = 1.0f; 3514 float f = 1.0f;
@@ -2843,8 +3620,6 @@ namespace OpenSim.Region.Framework.Scenes
2843 z *= a; 3620 z *= a;
2844 } 3621 }
2845 } 3622 }
2846
2847// obPart.IgnoreUndoUpdate = false;
2848 } 3623 }
2849 } 3624 }
2850 } 3625 }
@@ -2854,9 +3629,7 @@ namespace OpenSim.Region.Framework.Scenes
2854 prevScale.Y *= y; 3629 prevScale.Y *= y;
2855 prevScale.Z *= z; 3630 prevScale.Z *= z;
2856 3631
2857// RootPart.IgnoreUndoUpdate = true;
2858 RootPart.Resize(prevScale); 3632 RootPart.Resize(prevScale);
2859// RootPart.IgnoreUndoUpdate = false;
2860 3633
2861 parts = m_parts.GetArray(); 3634 parts = m_parts.GetArray();
2862 for (int i = 0; i < parts.Length; i++) 3635 for (int i = 0; i < parts.Length; i++)
@@ -2865,8 +3638,6 @@ namespace OpenSim.Region.Framework.Scenes
2865 3638
2866 if (obPart.UUID != m_rootPart.UUID) 3639 if (obPart.UUID != m_rootPart.UUID)
2867 { 3640 {
2868 obPart.IgnoreUndoUpdate = true;
2869
2870 Vector3 currentpos = new Vector3(obPart.OffsetPosition); 3641 Vector3 currentpos = new Vector3(obPart.OffsetPosition);
2871 currentpos.X *= x; 3642 currentpos.X *= x;
2872 currentpos.Y *= y; 3643 currentpos.Y *= y;
@@ -2879,16 +3650,12 @@ namespace OpenSim.Region.Framework.Scenes
2879 3650
2880 obPart.Resize(newSize); 3651 obPart.Resize(newSize);
2881 obPart.UpdateOffSet(currentpos); 3652 obPart.UpdateOffSet(currentpos);
2882
2883 obPart.IgnoreUndoUpdate = false;
2884 } 3653 }
2885 3654
2886// obPart.IgnoreUndoUpdate = false; 3655 HasGroupChanged = true;
2887// obPart.StoreUndoState(); 3656 m_rootPart.TriggerScriptChangedEvent(Changed.SCALE);
3657 ScheduleGroupForTerseUpdate();
2888 } 3658 }
2889
2890// m_log.DebugFormat(
2891// "[SCENE OBJECT GROUP]: Finished group resizing {0} {1} to {2}", Name, LocalId, RootPart.Scale);
2892 } 3659 }
2893 3660
2894 #endregion 3661 #endregion
@@ -2901,14 +3668,6 @@ namespace OpenSim.Region.Framework.Scenes
2901 /// <param name="pos"></param> 3668 /// <param name="pos"></param>
2902 public void UpdateGroupPosition(Vector3 pos) 3669 public void UpdateGroupPosition(Vector3 pos)
2903 { 3670 {
2904// m_log.DebugFormat("[SCENE OBJECT GROUP]: Updating group position on {0} {1} to {2}", Name, LocalId, pos);
2905
2906 RootPart.StoreUndoState(true);
2907
2908// SceneObjectPart[] parts = m_parts.GetArray();
2909// for (int i = 0; i < parts.Length; i++)
2910// parts[i].StoreUndoState();
2911
2912 if (m_scene.EventManager.TriggerGroupMove(UUID, pos)) 3671 if (m_scene.EventManager.TriggerGroupMove(UUID, pos))
2913 { 3672 {
2914 if (IsAttachment) 3673 if (IsAttachment)
@@ -2941,21 +3700,17 @@ namespace OpenSim.Region.Framework.Scenes
2941 /// </summary> 3700 /// </summary>
2942 /// <param name="pos"></param> 3701 /// <param name="pos"></param>
2943 /// <param name="localID"></param> 3702 /// <param name="localID"></param>
3703 ///
3704
2944 public void UpdateSinglePosition(Vector3 pos, uint localID) 3705 public void UpdateSinglePosition(Vector3 pos, uint localID)
2945 { 3706 {
2946 SceneObjectPart part = GetPart(localID); 3707 SceneObjectPart part = GetPart(localID);
2947 3708
2948// SceneObjectPart[] parts = m_parts.GetArray();
2949// for (int i = 0; i < parts.Length; i++)
2950// parts[i].StoreUndoState();
2951
2952 if (part != null) 3709 if (part != null)
2953 { 3710 {
2954// m_log.DebugFormat( 3711// unlock parts position change
2955// "[SCENE OBJECT GROUP]: Updating single position of {0} {1} to {2}", part.Name, part.LocalId, pos); 3712 if (m_rootPart.PhysActor != null)
2956 3713 m_rootPart.PhysActor.Building = true;
2957 part.StoreUndoState(false);
2958 part.IgnoreUndoUpdate = true;
2959 3714
2960 if (part.UUID == m_rootPart.UUID) 3715 if (part.UUID == m_rootPart.UUID)
2961 { 3716 {
@@ -2966,8 +3721,10 @@ namespace OpenSim.Region.Framework.Scenes
2966 part.UpdateOffSet(pos); 3721 part.UpdateOffSet(pos);
2967 } 3722 }
2968 3723
3724 if (m_rootPart.PhysActor != null)
3725 m_rootPart.PhysActor.Building = false;
3726
2969 HasGroupChanged = true; 3727 HasGroupChanged = true;
2970 part.IgnoreUndoUpdate = false;
2971 } 3728 }
2972 } 3729 }
2973 3730
@@ -2977,13 +3734,7 @@ namespace OpenSim.Region.Framework.Scenes
2977 /// <param name="pos"></param> 3734 /// <param name="pos"></param>
2978 public void UpdateRootPosition(Vector3 pos) 3735 public void UpdateRootPosition(Vector3 pos)
2979 { 3736 {
2980// m_log.DebugFormat( 3737 // needs to be called with phys building true
2981// "[SCENE OBJECT GROUP]: Updating root position of {0} {1} to {2}", Name, LocalId, pos);
2982
2983// SceneObjectPart[] parts = m_parts.GetArray();
2984// for (int i = 0; i < parts.Length; i++)
2985// parts[i].StoreUndoState();
2986
2987 Vector3 newPos = new Vector3(pos.X, pos.Y, pos.Z); 3738 Vector3 newPos = new Vector3(pos.X, pos.Y, pos.Z);
2988 Vector3 oldPos = 3739 Vector3 oldPos =
2989 new Vector3(AbsolutePosition.X + m_rootPart.OffsetPosition.X, 3740 new Vector3(AbsolutePosition.X + m_rootPart.OffsetPosition.X,
@@ -3006,7 +3757,14 @@ namespace OpenSim.Region.Framework.Scenes
3006 AbsolutePosition = newPos; 3757 AbsolutePosition = newPos;
3007 3758
3008 HasGroupChanged = true; 3759 HasGroupChanged = true;
3009 ScheduleGroupForTerseUpdate(); 3760 if (m_rootPart.Undoing)
3761 {
3762 ScheduleGroupForFullUpdate();
3763 }
3764 else
3765 {
3766 ScheduleGroupForTerseUpdate();
3767 }
3010 } 3768 }
3011 3769
3012 #endregion 3770 #endregion
@@ -3019,24 +3777,16 @@ namespace OpenSim.Region.Framework.Scenes
3019 /// <param name="rot"></param> 3777 /// <param name="rot"></param>
3020 public void UpdateGroupRotationR(Quaternion rot) 3778 public void UpdateGroupRotationR(Quaternion rot)
3021 { 3779 {
3022// m_log.DebugFormat(
3023// "[SCENE OBJECT GROUP]: Updating group rotation R of {0} {1} to {2}", Name, LocalId, rot);
3024
3025// SceneObjectPart[] parts = m_parts.GetArray();
3026// for (int i = 0; i < parts.Length; i++)
3027// parts[i].StoreUndoState();
3028
3029 m_rootPart.StoreUndoState(true);
3030
3031 m_rootPart.UpdateRotation(rot); 3780 m_rootPart.UpdateRotation(rot);
3032 3781
3782/* this is done by rootpart RotationOffset set called by UpdateRotation
3033 PhysicsActor actor = m_rootPart.PhysActor; 3783 PhysicsActor actor = m_rootPart.PhysActor;
3034 if (actor != null) 3784 if (actor != null)
3035 { 3785 {
3036 actor.Orientation = m_rootPart.RotationOffset; 3786 actor.Orientation = m_rootPart.RotationOffset;
3037 m_scene.PhysicsScene.AddPhysicsActorTaint(actor); 3787 m_scene.PhysicsScene.AddPhysicsActorTaint(actor);
3038 } 3788 }
3039 3789*/
3040 HasGroupChanged = true; 3790 HasGroupChanged = true;
3041 ScheduleGroupForTerseUpdate(); 3791 ScheduleGroupForTerseUpdate();
3042 } 3792 }
@@ -3048,16 +3798,6 @@ namespace OpenSim.Region.Framework.Scenes
3048 /// <param name="rot"></param> 3798 /// <param name="rot"></param>
3049 public void UpdateGroupRotationPR(Vector3 pos, Quaternion rot) 3799 public void UpdateGroupRotationPR(Vector3 pos, Quaternion rot)
3050 { 3800 {
3051// m_log.DebugFormat(
3052// "[SCENE OBJECT GROUP]: Updating group rotation PR of {0} {1} to {2}", Name, LocalId, rot);
3053
3054// SceneObjectPart[] parts = m_parts.GetArray();
3055// for (int i = 0; i < parts.Length; i++)
3056// parts[i].StoreUndoState();
3057
3058 RootPart.StoreUndoState(true);
3059 RootPart.IgnoreUndoUpdate = true;
3060
3061 m_rootPart.UpdateRotation(rot); 3801 m_rootPart.UpdateRotation(rot);
3062 3802
3063 PhysicsActor actor = m_rootPart.PhysActor; 3803 PhysicsActor actor = m_rootPart.PhysActor;
@@ -3076,8 +3816,6 @@ namespace OpenSim.Region.Framework.Scenes
3076 3816
3077 HasGroupChanged = true; 3817 HasGroupChanged = true;
3078 ScheduleGroupForTerseUpdate(); 3818 ScheduleGroupForTerseUpdate();
3079
3080 RootPart.IgnoreUndoUpdate = false;
3081 } 3819 }
3082 3820
3083 /// <summary> 3821 /// <summary>
@@ -3090,13 +3828,11 @@ namespace OpenSim.Region.Framework.Scenes
3090 SceneObjectPart part = GetPart(localID); 3828 SceneObjectPart part = GetPart(localID);
3091 3829
3092 SceneObjectPart[] parts = m_parts.GetArray(); 3830 SceneObjectPart[] parts = m_parts.GetArray();
3093 for (int i = 0; i < parts.Length; i++)
3094 parts[i].StoreUndoState();
3095 3831
3096 if (part != null) 3832 if (part != null)
3097 { 3833 {
3098// m_log.DebugFormat( 3834 if (m_rootPart.PhysActor != null)
3099// "[SCENE OBJECT GROUP]: Updating single rotation of {0} {1} to {2}", part.Name, part.LocalId, rot); 3835 m_rootPart.PhysActor.Building = true;
3100 3836
3101 if (part.UUID == m_rootPart.UUID) 3837 if (part.UUID == m_rootPart.UUID)
3102 { 3838 {
@@ -3106,6 +3842,9 @@ namespace OpenSim.Region.Framework.Scenes
3106 { 3842 {
3107 part.UpdateRotation(rot); 3843 part.UpdateRotation(rot);
3108 } 3844 }
3845
3846 if (m_rootPart.PhysActor != null)
3847 m_rootPart.PhysActor.Building = false;
3109 } 3848 }
3110 } 3849 }
3111 3850
@@ -3119,12 +3858,8 @@ namespace OpenSim.Region.Framework.Scenes
3119 SceneObjectPart part = GetPart(localID); 3858 SceneObjectPart part = GetPart(localID);
3120 if (part != null) 3859 if (part != null)
3121 { 3860 {
3122// m_log.DebugFormat( 3861 if (m_rootPart.PhysActor != null)
3123// "[SCENE OBJECT GROUP]: Updating single position and rotation of {0} {1} to {2}", 3862 m_rootPart.PhysActor.Building = true;
3124// part.Name, part.LocalId, rot);
3125
3126 part.StoreUndoState();
3127 part.IgnoreUndoUpdate = true;
3128 3863
3129 if (part.UUID == m_rootPart.UUID) 3864 if (part.UUID == m_rootPart.UUID)
3130 { 3865 {
@@ -3137,7 +3872,8 @@ namespace OpenSim.Region.Framework.Scenes
3137 part.OffsetPosition = pos; 3872 part.OffsetPosition = pos;
3138 } 3873 }
3139 3874
3140 part.IgnoreUndoUpdate = false; 3875 if (m_rootPart.PhysActor != null)
3876 m_rootPart.PhysActor.Building = false;
3141 } 3877 }
3142 } 3878 }
3143 3879
@@ -3147,15 +3883,12 @@ namespace OpenSim.Region.Framework.Scenes
3147 /// <param name="rot"></param> 3883 /// <param name="rot"></param>
3148 public void UpdateRootRotation(Quaternion rot) 3884 public void UpdateRootRotation(Quaternion rot)
3149 { 3885 {
3150// m_log.DebugFormat( 3886 // needs to be called with phys building true
3151// "[SCENE OBJECT GROUP]: Updating root rotation of {0} {1} to {2}",
3152// Name, LocalId, rot);
3153
3154 Quaternion axRot = rot; 3887 Quaternion axRot = rot;
3155 Quaternion oldParentRot = m_rootPart.RotationOffset; 3888 Quaternion oldParentRot = m_rootPart.RotationOffset;
3156 3889
3157 m_rootPart.StoreUndoState(); 3890 //Don't use UpdateRotation because it schedules an update prematurely
3158 m_rootPart.UpdateRotation(rot); 3891 m_rootPart.RotationOffset = rot;
3159 3892
3160 PhysicsActor pa = m_rootPart.PhysActor; 3893 PhysicsActor pa = m_rootPart.PhysActor;
3161 3894
@@ -3171,35 +3904,145 @@ namespace OpenSim.Region.Framework.Scenes
3171 SceneObjectPart prim = parts[i]; 3904 SceneObjectPart prim = parts[i];
3172 if (prim.UUID != m_rootPart.UUID) 3905 if (prim.UUID != m_rootPart.UUID)
3173 { 3906 {
3174 prim.IgnoreUndoUpdate = true; 3907 Quaternion NewRot = oldParentRot * prim.RotationOffset;
3908 NewRot = Quaternion.Inverse(axRot) * NewRot;
3909 prim.RotationOffset = NewRot;
3910
3175 Vector3 axPos = prim.OffsetPosition; 3911 Vector3 axPos = prim.OffsetPosition;
3912
3176 axPos *= oldParentRot; 3913 axPos *= oldParentRot;
3177 axPos *= Quaternion.Inverse(axRot); 3914 axPos *= Quaternion.Inverse(axRot);
3178 prim.OffsetPosition = axPos; 3915 prim.OffsetPosition = axPos;
3179 Quaternion primsRot = prim.RotationOffset; 3916 }
3180 Quaternion newRot = oldParentRot * primsRot; 3917 }
3181 newRot = Quaternion.Inverse(axRot) * newRot;
3182 prim.RotationOffset = newRot;
3183 prim.ScheduleTerseUpdate();
3184 prim.IgnoreUndoUpdate = false;
3185 }
3186 }
3187
3188// for (int i = 0; i < parts.Length; i++)
3189// {
3190// SceneObjectPart childpart = parts[i];
3191// if (childpart != m_rootPart)
3192// {
3193//// childpart.IgnoreUndoUpdate = false;
3194//// childpart.StoreUndoState();
3195// }
3196// }
3197 3918
3198 m_rootPart.ScheduleTerseUpdate(); 3919 HasGroupChanged = true;
3920 ScheduleGroupForFullUpdate();
3921 }
3199 3922
3200// m_log.DebugFormat( 3923 private enum updatetype :int
3201// "[SCENE OBJECT GROUP]: Updated root rotation of {0} {1} to {2}", 3924 {
3202// Name, LocalId, rot); 3925 none = 0,
3926 partterse = 1,
3927 partfull = 2,
3928 groupterse = 3,
3929 groupfull = 4
3930 }
3931
3932 public void doChangeObject(SceneObjectPart part, ObjectChangeData data)
3933 {
3934 // TODO this still as excessive *.Schedule*Update()s
3935
3936 if (part != null && part.ParentGroup != null)
3937 {
3938 ObjectChangeType change = data.change;
3939 bool togroup = ((change & ObjectChangeType.Group) != 0);
3940 // bool uniform = ((what & ObjectChangeType.UniformScale) != 0); not in use
3941
3942 SceneObjectGroup group = part.ParentGroup;
3943 PhysicsActor pha = group.RootPart.PhysActor;
3944
3945 updatetype updateType = updatetype.none;
3946
3947 if (togroup)
3948 {
3949 // related to group
3950 if ((change & (ObjectChangeType.Rotation | ObjectChangeType.Position)) != 0)
3951 {
3952 if ((change & ObjectChangeType.Rotation) != 0)
3953 {
3954 group.RootPart.UpdateRotation(data.rotation);
3955 updateType = updatetype.none;
3956 }
3957 if ((change & ObjectChangeType.Position) != 0)
3958 {
3959 if (IsAttachment || m_scene.Permissions.CanObjectEntry(group.UUID, false, data.position))
3960 UpdateGroupPosition(data.position);
3961 updateType = updatetype.groupterse;
3962 }
3963 else
3964 // ugly rotation update of all parts
3965 {
3966 group.ResetChildPrimPhysicsPositions();
3967 }
3968
3969 }
3970 if ((change & ObjectChangeType.Scale) != 0)
3971 {
3972 if (pha != null)
3973 pha.Building = true;
3974
3975 group.GroupResize(data.scale);
3976 updateType = updatetype.none;
3977
3978 if (pha != null)
3979 pha.Building = false;
3980 }
3981 }
3982 else
3983 {
3984 // related to single prim in a link-set ( ie group)
3985 if (pha != null)
3986 pha.Building = true;
3987
3988 // root part is special
3989 // parts offset positions or rotations need to change also
3990
3991 if (part == group.RootPart)
3992 {
3993 if ((change & ObjectChangeType.Rotation) != 0)
3994 group.UpdateRootRotation(data.rotation);
3995 if ((change & ObjectChangeType.Position) != 0)
3996 group.UpdateRootPosition(data.position);
3997 if ((change & ObjectChangeType.Scale) != 0)
3998 part.Resize(data.scale);
3999 }
4000 else
4001 {
4002 if ((change & ObjectChangeType.Position) != 0)
4003 {
4004 part.OffsetPosition = data.position;
4005 updateType = updatetype.partterse;
4006 }
4007 if ((change & ObjectChangeType.Rotation) != 0)
4008 {
4009 part.UpdateRotation(data.rotation);
4010 updateType = updatetype.none;
4011 }
4012 if ((change & ObjectChangeType.Scale) != 0)
4013 {
4014 part.Resize(data.scale);
4015 updateType = updatetype.none;
4016 }
4017 }
4018
4019 if (pha != null)
4020 pha.Building = false;
4021 }
4022
4023 if (updateType != updatetype.none)
4024 {
4025 group.HasGroupChanged = true;
4026
4027 switch (updateType)
4028 {
4029 case updatetype.partterse:
4030 part.ScheduleTerseUpdate();
4031 break;
4032 case updatetype.partfull:
4033 part.ScheduleFullUpdate();
4034 break;
4035 case updatetype.groupterse:
4036 group.ScheduleGroupForTerseUpdate();
4037 break;
4038 case updatetype.groupfull:
4039 group.ScheduleGroupForFullUpdate();
4040 break;
4041 default:
4042 break;
4043 }
4044 }
4045 }
3203 } 4046 }
3204 4047
3205 #endregion 4048 #endregion
@@ -3298,10 +4141,11 @@ namespace OpenSim.Region.Framework.Scenes
3298 scriptPosTarget target = m_targets[idx]; 4141 scriptPosTarget target = m_targets[idx];
3299 if (Util.GetDistanceTo(target.targetPos, m_rootPart.GroupPosition) <= target.tolerance) 4142 if (Util.GetDistanceTo(target.targetPos, m_rootPart.GroupPosition) <= target.tolerance)
3300 { 4143 {
4144 at_target = true;
4145
3301 // trigger at_target 4146 // trigger at_target
3302 if (m_scriptListens_atTarget) 4147 if (m_scriptListens_atTarget)
3303 { 4148 {
3304 at_target = true;
3305 scriptPosTarget att = new scriptPosTarget(); 4149 scriptPosTarget att = new scriptPosTarget();
3306 att.targetPos = target.targetPos; 4150 att.targetPos = target.targetPos;
3307 att.tolerance = target.tolerance; 4151 att.tolerance = target.tolerance;
@@ -3419,11 +4263,50 @@ namespace OpenSim.Region.Framework.Scenes
3419 } 4263 }
3420 } 4264 }
3421 } 4265 }
3422 4266
4267 public Vector3 GetGeometricCenter()
4268 {
4269 // this is not real geometric center but a average of positions relative to root prim acording to
4270 // http://wiki.secondlife.com/wiki/llGetGeometricCenter
4271 // ignoring tortured prims details since sl also seems to ignore
4272 // so no real use in doing it on physics
4273
4274 Vector3 gc = Vector3.Zero;
4275
4276 int nparts = m_parts.Count;
4277 if (nparts <= 1)
4278 return gc;
4279
4280 SceneObjectPart[] parts = m_parts.GetArray();
4281 nparts = parts.Length; // just in case it changed
4282 if (nparts <= 1)
4283 return gc;
4284
4285 Quaternion parentRot = RootPart.RotationOffset;
4286 Vector3 pPos;
4287
4288 // average all parts positions
4289 for (int i = 0; i < nparts; i++)
4290 {
4291 // do it directly
4292 // gc += parts[i].GetWorldPosition();
4293 if (parts[i] != RootPart)
4294 {
4295 pPos = parts[i].OffsetPosition;
4296 gc += pPos;
4297 }
4298
4299 }
4300 gc /= nparts;
4301
4302 // relative to root:
4303// gc -= AbsolutePosition;
4304 return gc;
4305 }
4306
3423 public float GetMass() 4307 public float GetMass()
3424 { 4308 {
3425 float retmass = 0f; 4309 float retmass = 0f;
3426
3427 SceneObjectPart[] parts = m_parts.GetArray(); 4310 SceneObjectPart[] parts = m_parts.GetArray();
3428 for (int i = 0; i < parts.Length; i++) 4311 for (int i = 0; i < parts.Length; i++)
3429 retmass += parts[i].GetMass(); 4312 retmass += parts[i].GetMass();
@@ -3431,6 +4314,39 @@ namespace OpenSim.Region.Framework.Scenes
3431 return retmass; 4314 return retmass;
3432 } 4315 }
3433 4316
4317 // center of mass of full object
4318 public Vector3 GetCenterOfMass()
4319 {
4320 PhysicsActor pa = RootPart.PhysActor;
4321
4322 if(((RootPart.Flags & PrimFlags.Physics) !=0) && pa !=null)
4323 {
4324 // physics knows better about center of mass of physical prims
4325 Vector3 tmp = pa.CenterOfMass;
4326 return tmp;
4327 }
4328
4329 Vector3 Ptot = Vector3.Zero;
4330 float totmass = 0f;
4331 float m;
4332
4333 SceneObjectPart[] parts = m_parts.GetArray();
4334 for (int i = 0; i < parts.Length; i++)
4335 {
4336 m = parts[i].GetMass();
4337 Ptot += parts[i].GetPartCenterOfMass() * m;
4338 totmass += m;
4339 }
4340
4341 if (totmass == 0)
4342 totmass = 0;
4343 else
4344 totmass = 1 / totmass;
4345 Ptot *= totmass;
4346
4347 return Ptot;
4348 }
4349
3434 /// <summary> 4350 /// <summary>
3435 /// If the object is a sculpt/mesh, retrieve the mesh data for each part and reinsert it into each shape so that 4351 /// If the object is a sculpt/mesh, retrieve the mesh data for each part and reinsert it into each shape so that
3436 /// the physics engine can use it. 4352 /// the physics engine can use it.
@@ -3598,6 +4514,14 @@ namespace OpenSim.Region.Framework.Scenes
3598 FromItemID = uuid; 4514 FromItemID = uuid;
3599 } 4515 }
3600 4516
4517 public void ResetOwnerChangeFlag()
4518 {
4519 ForEachPart(delegate(SceneObjectPart part)
4520 {
4521 part.ResetOwnerChangeFlag();
4522 });
4523 }
4524
3601 #endregion 4525 #endregion
3602 } 4526 }
3603} 4527}
diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs b/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs
index 9e78242..4af508e 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>
@@ -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;
@@ -296,7 +320,19 @@ namespace OpenSim.Region.Framework.Scenes
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_lastTerseSent;
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)
@@ -769,7 +816,22 @@ namespace OpenSim.Region.Framework.Scenes
769 if (ParentGroup.Scene != null) 816 if (ParentGroup.Scene != 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,319 @@ 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.Cost;
1587
1588 if ((Flags & PrimFlags.Physics) != 0)
1589 cost *= (1.0f + 0.01333f * Scale.LengthSquared()); // 0.01333 == 0.04/3
1590 return cost;
1591 }
1592 }
1593
1594 [XmlIgnore]
1595 public float StreamingCost
1596 {
1597 get
1598 {
1599
1600
1601 return 0.1f;
1602 }
1603 }
1604
1605 [XmlIgnore]
1606 public float SimulationCost
1607 {
1608 get
1609 {
1610 // ignoring scripts. Don't like considering them for this
1611 if((Flags & PrimFlags.Physics) != 0)
1612 return 1.0f;
1613
1614 return 0.5f;
1615 }
1616 }
1617
1618 public byte PhysicsShapeType
1619 {
1620 get { return m_physicsShapeType; }
1621 set
1622 {
1623 byte oldv = m_physicsShapeType;
1624
1625 if (value >= 0 && value <= (byte)PhysShapeType.convex)
1626 {
1627 if (value == (byte)PhysShapeType.none && ParentGroup != null && ParentGroup.RootPart == this)
1628 m_physicsShapeType = DefaultPhysicsShapeType();
1629 else
1630 m_physicsShapeType = value;
1631 }
1632 else
1633 m_physicsShapeType = DefaultPhysicsShapeType();
1634
1635 if (m_physicsShapeType != oldv && ParentGroup != null)
1636 {
1637 if (m_physicsShapeType == (byte)PhysShapeType.none)
1638 {
1639 if (PhysActor != null)
1640 {
1641 Velocity = new Vector3(0, 0, 0);
1642 Acceleration = new Vector3(0, 0, 0);
1643 if (ParentGroup.RootPart == this)
1644 AngularVelocity = new Vector3(0, 0, 0);
1645 ParentGroup.Scene.RemovePhysicalPrim(1);
1646 RemoveFromPhysics();
1647 }
1648 }
1649 else if (PhysActor == null)
1650 {
1651 ApplyPhysics((uint)Flags, VolumeDetectActive, false);
1652 UpdatePhysicsSubscribedEvents();
1653 }
1654 else
1655 {
1656 PhysActor.PhysicsShapeType = m_physicsShapeType;
1657 if (Shape.SculptEntry)
1658 CheckSculptAndLoad();
1659 }
1660
1661 if (ParentGroup != null)
1662 ParentGroup.HasGroupChanged = true;
1663 }
1664
1665 if (m_physicsShapeType != value)
1666 {
1667 UpdatePhysRequired = true;
1668 }
1669 }
1670 }
1671
1672 public float Density // in kg/m^3
1673 {
1674 get { return m_density; }
1675 set
1676 {
1677 if (value >=1 && value <= 22587.0)
1678 {
1679 m_density = value;
1680 UpdatePhysRequired = true;
1681 }
1682
1683 ScheduleFullUpdateIfNone();
1684
1685 if (ParentGroup != null)
1686 ParentGroup.HasGroupChanged = true;
1687 }
1688 }
1689
1690 public float GravityModifier
1691 {
1692 get { return m_gravitymod; }
1693 set
1694 {
1695 if( value >= -1 && value <=28.0f)
1696 {
1697 m_gravitymod = value;
1698 UpdatePhysRequired = true;
1699 }
1700
1701 ScheduleFullUpdateIfNone();
1702
1703 if (ParentGroup != null)
1704 ParentGroup.HasGroupChanged = true;
1705
1706 }
1707 }
1708
1709 public float Friction
1710 {
1711 get { return m_friction; }
1712 set
1713 {
1714 if (value >= 0 && value <= 255.0f)
1715 {
1716 m_friction = value;
1717 UpdatePhysRequired = true;
1718 }
1719
1720 ScheduleFullUpdateIfNone();
1721
1722 if (ParentGroup != null)
1723 ParentGroup.HasGroupChanged = true;
1724 }
1725 }
1726
1727 public float Bounciness
1728 {
1729 get { return m_bounce; }
1730 set
1731 {
1732 if (value >= 0 && value <= 1.0f)
1733 {
1734 m_bounce = value;
1735 UpdatePhysRequired = true;
1736 }
1737
1738 ScheduleFullUpdateIfNone();
1739
1740 if (ParentGroup != null)
1741 ParentGroup.HasGroupChanged = true;
1742 }
1743 }
1744
1745
1318 #endregion Public Properties with only Get 1746 #endregion Public Properties with only Get
1319 1747
1320 private uint ApplyMask(uint val, bool set, uint mask) 1748 private uint ApplyMask(uint val, bool set, uint mask)
@@ -1460,6 +1888,61 @@ namespace OpenSim.Region.Framework.Scenes
1460 } 1888 }
1461 } 1889 }
1462 1890
1891 // SetVelocity for LSL llSetVelocity.. may need revision if having other uses in future
1892 public void SetVelocity(Vector3 pVel, bool localGlobalTF)
1893 {
1894 if (ParentGroup == null || ParentGroup.IsDeleted)
1895 return;
1896
1897 if (ParentGroup.IsAttachment)
1898 return; // don't work on attachments (for now ??)
1899
1900 SceneObjectPart root = ParentGroup.RootPart;
1901
1902 if (root.VehicleType != (int)Vehicle.TYPE_NONE) // don't mess with vehicles
1903 return;
1904
1905 PhysicsActor pa = root.PhysActor;
1906
1907 if (pa == null || !pa.IsPhysical)
1908 return;
1909
1910 if (localGlobalTF)
1911 {
1912 pVel = pVel * GetWorldRotation();
1913 }
1914
1915 ParentGroup.Velocity = pVel;
1916 }
1917
1918 // SetAngularVelocity for LSL llSetAngularVelocity.. may need revision if having other uses in future
1919 public void SetAngularVelocity(Vector3 pAngVel, bool localGlobalTF)
1920 {
1921 if (ParentGroup == null || ParentGroup.IsDeleted)
1922 return;
1923
1924 if (ParentGroup.IsAttachment)
1925 return; // don't work on attachments (for now ??)
1926
1927 SceneObjectPart root = ParentGroup.RootPart;
1928
1929 if (root.VehicleType != (int)Vehicle.TYPE_NONE) // don't mess with vehicles
1930 return;
1931
1932 PhysicsActor pa = root.PhysActor;
1933
1934 if (pa == null || !pa.IsPhysical)
1935 return;
1936
1937 if (localGlobalTF)
1938 {
1939 pAngVel = pAngVel * GetWorldRotation();
1940 }
1941
1942 root.AngularVelocity = pAngVel;
1943 }
1944
1945
1463 /// <summary> 1946 /// <summary>
1464 /// hook to the physics scene to apply angular impulse 1947 /// hook to the physics scene to apply angular impulse
1465 /// This is sent up to the group, which then finds the root prim 1948 /// This is sent up to the group, which then finds the root prim
@@ -1480,7 +1963,7 @@ namespace OpenSim.Region.Framework.Scenes
1480 impulse = newimpulse; 1963 impulse = newimpulse;
1481 } 1964 }
1482 1965
1483 ParentGroup.applyAngularImpulse(impulse); 1966 ParentGroup.ApplyAngularImpulse(impulse);
1484 } 1967 }
1485 1968
1486 /// <summary> 1969 /// <summary>
@@ -1490,20 +1973,24 @@ namespace OpenSim.Region.Framework.Scenes
1490 /// </summary> 1973 /// </summary>
1491 /// <param name="impulsei">Vector force</param> 1974 /// <param name="impulsei">Vector force</param>
1492 /// <param name="localGlobalTF">true for the local frame, false for the global frame</param> 1975 /// <param name="localGlobalTF">true for the local frame, false for the global frame</param>
1493 public void SetAngularImpulse(Vector3 impulsei, bool localGlobalTF) 1976
1977 // this is actualy Set Torque.. keeping naming so not to edit lslapi also
1978 public void SetAngularImpulse(Vector3 torquei, bool localGlobalTF)
1494 { 1979 {
1495 Vector3 impulse = impulsei; 1980 Vector3 torque = torquei;
1496 1981
1497 if (localGlobalTF) 1982 if (localGlobalTF)
1498 { 1983 {
1984/*
1499 Quaternion grot = GetWorldRotation(); 1985 Quaternion grot = GetWorldRotation();
1500 Quaternion AXgrot = grot; 1986 Quaternion AXgrot = grot;
1501 Vector3 AXimpulsei = impulsei; 1987 Vector3 AXimpulsei = impulsei;
1502 Vector3 newimpulse = AXimpulsei * AXgrot; 1988 Vector3 newimpulse = AXimpulsei * AXgrot;
1503 impulse = newimpulse; 1989 */
1990 torque *= GetWorldRotation();
1504 } 1991 }
1505 1992
1506 ParentGroup.setAngularImpulse(impulse); 1993 Torque = torque;
1507 } 1994 }
1508 1995
1509 /// <summary> 1996 /// <summary>
@@ -1511,17 +1998,23 @@ namespace OpenSim.Region.Framework.Scenes
1511 /// </summary> 1998 /// </summary>
1512 /// <param name="rootObjectFlags"></param> 1999 /// <param name="rootObjectFlags"></param>
1513 /// <param name="VolumeDetectActive"></param> 2000 /// <param name="VolumeDetectActive"></param>
1514 public void ApplyPhysics(uint rootObjectFlags, bool VolumeDetectActive) 2001 /// <param name="building"></param>
2002
2003 public void ApplyPhysics(uint _ObjectFlags, bool _VolumeDetectActive, bool building)
1515 { 2004 {
2005 VolumeDetectActive = _VolumeDetectActive;
2006
1516 if (!ParentGroup.Scene.CollidablePrims) 2007 if (!ParentGroup.Scene.CollidablePrims)
1517 return; 2008 return;
1518 2009
1519// m_log.DebugFormat( 2010 if (PhysicsShapeType == (byte)PhysShapeType.none)
1520// "[SCENE OBJECT PART]: Applying physics to {0} {1}, m_physicalPrim {2}", 2011 return;
1521// Name, LocalId, UUID, m_physicalPrim); 2012
2013 bool isPhysical = (_ObjectFlags & (uint) PrimFlags.Physics) != 0;
2014 bool isPhantom = (_ObjectFlags & (uint)PrimFlags.Phantom) != 0;
1522 2015
1523 bool isPhysical = (rootObjectFlags & (uint) PrimFlags.Physics) != 0; 2016 if (_VolumeDetectActive)
1524 bool isPhantom = (rootObjectFlags & (uint) PrimFlags.Phantom) != 0; 2017 isPhantom = true;
1525 2018
1526 if (IsJoint()) 2019 if (IsJoint())
1527 { 2020 {
@@ -1529,22 +2022,14 @@ namespace OpenSim.Region.Framework.Scenes
1529 } 2022 }
1530 else 2023 else
1531 { 2024 {
1532 // Special case for VolumeDetection: If VolumeDetection is set, the phantom flag is locally ignored 2025 if ((!isPhantom || isPhysical || _VolumeDetectActive) && !ParentGroup.IsAttachment
1533 if (VolumeDetectActive) 2026 && !(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 { 2027 {
1540 // Added clarification.. since A rigid body is an object that you can kick around, etc. 2028 AddToPhysics(isPhysical, isPhantom, building, isPhysical);
1541 bool rigidBody = isPhysical && !isPhantom; 2029 UpdatePhysicsSubscribedEvents(); // not sure if appliable here
1542
1543 PhysicsActor pa = AddToPhysics(rigidBody);
1544
1545 if (pa != null)
1546 pa.SetVolumeDetect(VolumeDetectActive ? 1 : 0);
1547 } 2030 }
2031 else
2032 PhysActor = null; // just to be sure
1548 } 2033 }
1549 } 2034 }
1550 2035
@@ -1596,6 +2081,12 @@ namespace OpenSim.Region.Framework.Scenes
1596 dupe.Category = Category; 2081 dupe.Category = Category;
1597 dupe.m_rezzed = m_rezzed; 2082 dupe.m_rezzed = m_rezzed;
1598 2083
2084 dupe.m_UndoRedo = null;
2085 dupe.m_isSelected = false;
2086
2087 dupe.IgnoreUndoUpdate = false;
2088 dupe.Undoing = false;
2089
1599 dupe.m_inventory = new SceneObjectPartInventory(dupe); 2090 dupe.m_inventory = new SceneObjectPartInventory(dupe);
1600 dupe.m_inventory.Items = (TaskInventoryDictionary)m_inventory.Items.Clone(); 2091 dupe.m_inventory.Items = (TaskInventoryDictionary)m_inventory.Items.Clone();
1601 2092
@@ -1611,6 +2102,7 @@ namespace OpenSim.Region.Framework.Scenes
1611 2102
1612 // Move afterwards ResetIDs as it clears the localID 2103 // Move afterwards ResetIDs as it clears the localID
1613 dupe.LocalId = localID; 2104 dupe.LocalId = localID;
2105
1614 // This may be wrong... it might have to be applied in SceneObjectGroup to the object that's being duplicated. 2106 // This may be wrong... it might have to be applied in SceneObjectGroup to the object that's being duplicated.
1615 dupe.LastOwnerID = OwnerID; 2107 dupe.LastOwnerID = OwnerID;
1616 2108
@@ -1618,6 +2110,9 @@ namespace OpenSim.Region.Framework.Scenes
1618 Array.Copy(Shape.ExtraParams, extraP, extraP.Length); 2110 Array.Copy(Shape.ExtraParams, extraP, extraP.Length);
1619 dupe.Shape.ExtraParams = extraP; 2111 dupe.Shape.ExtraParams = extraP;
1620 2112
2113 // safeguard actual copy is done in sog.copy
2114 dupe.KeyframeMotion = null;
2115
1621 if (userExposed) 2116 if (userExposed)
1622 { 2117 {
1623 if (dupe.m_shape.SculptEntry && dupe.m_shape.SculptTexture != UUID.Zero) 2118 if (dupe.m_shape.SculptEntry && dupe.m_shape.SculptTexture != UUID.Zero)
@@ -1628,8 +2123,12 @@ namespace OpenSim.Region.Framework.Scenes
1628 2123
1629 bool UsePhysics = ((dupe.Flags & PrimFlags.Physics) != 0); 2124 bool UsePhysics = ((dupe.Flags & PrimFlags.Physics) != 0);
1630 dupe.DoPhysicsPropertyUpdate(UsePhysics, true); 2125 dupe.DoPhysicsPropertyUpdate(UsePhysics, true);
2126// dupe.UpdatePhysicsSubscribedEvents(); // not sure...
1631 } 2127 }
1632 2128
2129 if (dupe.PhysActor != null)
2130 dupe.PhysActor.LocalID = localID;
2131
1633 ParentGroup.Scene.EventManager.TriggerOnSceneObjectPartCopy(dupe, this, userExposed); 2132 ParentGroup.Scene.EventManager.TriggerOnSceneObjectPartCopy(dupe, this, userExposed);
1634 2133
1635// m_log.DebugFormat("[SCENE OBJECT PART]: Clone of {0} {1} finished", Name, UUID); 2134// m_log.DebugFormat("[SCENE OBJECT PART]: Clone of {0} {1} finished", Name, UUID);
@@ -1749,6 +2248,7 @@ namespace OpenSim.Region.Framework.Scenes
1749 2248
1750 /// <summary> 2249 /// <summary>
1751 /// Do a physics propery update for this part. 2250 /// Do a physics propery update for this part.
2251 /// now also updates phantom and volume detector
1752 /// </summary> 2252 /// </summary>
1753 /// <param name="UsePhysics"></param> 2253 /// <param name="UsePhysics"></param>
1754 /// <param name="isNew"></param> 2254 /// <param name="isNew"></param>
@@ -1774,61 +2274,69 @@ namespace OpenSim.Region.Framework.Scenes
1774 { 2274 {
1775 if (pa.IsPhysical) // implies UsePhysics==false for this block 2275 if (pa.IsPhysical) // implies UsePhysics==false for this block
1776 { 2276 {
1777 if (!isNew) 2277 if (!isNew) // implies UsePhysics==false for this block
2278 {
1778 ParentGroup.Scene.RemovePhysicalPrim(1); 2279 ParentGroup.Scene.RemovePhysicalPrim(1);
1779 2280
1780 pa.OnRequestTerseUpdate -= PhysicsRequestingTerseUpdate; 2281 Velocity = new Vector3(0, 0, 0);
1781 pa.OnOutOfBounds -= PhysicsOutOfBounds; 2282 Acceleration = new Vector3(0, 0, 0);
1782 pa.delink(); 2283 if (ParentGroup.RootPart == this)
2284 AngularVelocity = new Vector3(0, 0, 0);
1783 2285
1784 if (ParentGroup.Scene.PhysicsScene.SupportsNINJAJoints && (!isNew)) 2286 if (pa.Phantom && !VolumeDetectActive)
1785 { 2287 {
1786 // destroy all joints connected to this now deactivated body 2288 RemoveFromPhysics();
1787 ParentGroup.Scene.PhysicsScene.RemoveAllJointsConnectedToActorThreadLocked(pa); 2289 return;
1788 } 2290 }
1789 2291
1790 // stop client-side interpolation of all joint proxy objects that have just been deleted 2292 pa.IsPhysical = UsePhysics;
1791 // this is done because RemoveAllJointsConnectedToActor invokes the OnJointDeactivated callback, 2293 pa.OnRequestTerseUpdate -= PhysicsRequestingTerseUpdate;
1792 // which stops client-side interpolation of deactivated joint proxy objects. 2294 pa.OnOutOfBounds -= PhysicsOutOfBounds;
2295 pa.delink();
2296 if (ParentGroup.Scene.PhysicsScene.SupportsNINJAJoints)
2297 {
2298 // destroy all joints connected to this now deactivated body
2299 ParentGroup.Scene.PhysicsScene.RemoveAllJointsConnectedToActorThreadLocked(pa);
2300 }
2301 }
1793 } 2302 }
1794 2303
1795 if (!UsePhysics && !isNew) 2304 if (pa.IsPhysical != UsePhysics)
1796 { 2305 pa.IsPhysical = UsePhysics;
1797 // reset velocity to 0 on physics switch-off. Without that, the client thinks the
1798 // prim still has velocity and continues to interpolate its position along the old
1799 // velocity-vector.
1800 Velocity = new Vector3(0, 0, 0);
1801 Acceleration = new Vector3(0, 0, 0);
1802 AngularVelocity = new Vector3(0, 0, 0);
1803 //RotationalVelocity = new Vector3(0, 0, 0);
1804 }
1805 2306
1806 pa.IsPhysical = UsePhysics; 2307 if (UsePhysics)
2308 {
2309 if (ParentGroup.RootPart.KeyframeMotion != null)
2310 ParentGroup.RootPart.KeyframeMotion.Stop();
2311 ParentGroup.RootPart.KeyframeMotion = null;
2312 ParentGroup.Scene.AddPhysicalPrim(1);
1807 2313
1808 // If we're not what we're supposed to be in the physics scene, recreate ourselves. 2314 PhysActor.OnRequestTerseUpdate += PhysicsRequestingTerseUpdate;
1809 //m_parentGroup.Scene.PhysicsScene.RemovePrim(PhysActor); 2315 PhysActor.OnOutOfBounds += PhysicsOutOfBounds;
1810 /// that's not wholesome. Had to make Scene public
1811 //PhysActor = null;
1812 2316
1813 if ((Flags & PrimFlags.Phantom) == 0) 2317 if (ParentID != 0 && ParentID != LocalId)
1814 {
1815 if (UsePhysics)
1816 { 2318 {
1817 ParentGroup.Scene.AddPhysicalPrim(1); 2319 PhysicsActor parentPa = ParentGroup.RootPart.PhysActor;
1818 2320
1819 pa.OnRequestTerseUpdate += PhysicsRequestingTerseUpdate; 2321 if (parentPa != null)
1820 pa.OnOutOfBounds += PhysicsOutOfBounds;
1821 if (ParentID != 0 && ParentID != LocalId)
1822 { 2322 {
1823 PhysicsActor parentPa = ParentGroup.RootPart.PhysActor; 2323 pa.link(parentPa);
1824
1825 if (parentPa != null)
1826 {
1827 pa.link(parentPa);
1828 }
1829 } 2324 }
1830 } 2325 }
1831 } 2326 }
2327 }
2328
2329 bool phan = ((Flags & PrimFlags.Phantom) != 0);
2330 if (pa.Phantom != phan)
2331 pa.Phantom = phan;
2332
2333// some engines dont' have this check still
2334// if (VolumeDetectActive != pa.IsVolumeDtc)
2335 {
2336 if (VolumeDetectActive)
2337 pa.SetVolumeDetect(1);
2338 else
2339 pa.SetVolumeDetect(0);
1832 } 2340 }
1833 2341
1834 // If this part is a sculpt then delay the physics update until we've asynchronously loaded the 2342 // If this part is a sculpt then delay the physics update until we've asynchronously loaded the
@@ -1947,12 +2455,26 @@ namespace OpenSim.Region.Framework.Scenes
1947 2455
1948 public Vector3 GetGeometricCenter() 2456 public Vector3 GetGeometricCenter()
1949 { 2457 {
1950 PhysicsActor pa = PhysActor; 2458 // this is not real geometric center but a average of positions relative to root prim acording to
1951 2459 // http://wiki.secondlife.com/wiki/llGetGeometricCenter
1952 if (pa != null) 2460 // ignoring tortured prims details since sl also seems to ignore
1953 return new Vector3(pa.CenterOfMass.X, pa.CenterOfMass.Y, pa.CenterOfMass.Z); 2461 // so no real use in doing it on physics
1954 else 2462 if (ParentGroup.IsDeleted)
1955 return new Vector3(0, 0, 0); 2463 return new Vector3(0, 0, 0);
2464
2465 return ParentGroup.GetGeometricCenter();
2466
2467 /*
2468 PhysicsActor pa = PhysActor;
2469
2470 if (pa != null)
2471 {
2472 Vector3 vtmp = pa.CenterOfMass;
2473 return vtmp;
2474 }
2475 else
2476 return new Vector3(0, 0, 0);
2477 */
1956 } 2478 }
1957 2479
1958 public float GetMass() 2480 public float GetMass()
@@ -1965,14 +2487,43 @@ namespace OpenSim.Region.Framework.Scenes
1965 return 0; 2487 return 0;
1966 } 2488 }
1967 2489
1968 public Vector3 GetForce() 2490 public Vector3 GetCenterOfMass()
1969 { 2491 {
2492 if (ParentGroup.RootPart == this)
2493 {
2494 if (ParentGroup.IsDeleted)
2495 return AbsolutePosition;
2496 return ParentGroup.GetCenterOfMass();
2497 }
2498
1970 PhysicsActor pa = PhysActor; 2499 PhysicsActor pa = PhysActor;
1971 2500
1972 if (pa != null) 2501 if (pa != null)
1973 return pa.Force; 2502 {
2503 Vector3 tmp = pa.CenterOfMass;
2504 return tmp;
2505 }
1974 else 2506 else
1975 return Vector3.Zero; 2507 return AbsolutePosition;
2508 }
2509
2510 public Vector3 GetPartCenterOfMass()
2511 {
2512 PhysicsActor pa = PhysActor;
2513
2514 if (pa != null)
2515 {
2516 Vector3 tmp = pa.CenterOfMass;
2517 return tmp;
2518 }
2519 else
2520 return AbsolutePosition;
2521 }
2522
2523
2524 public Vector3 GetForce()
2525 {
2526 return Force;
1976 } 2527 }
1977 2528
1978 /// <summary> 2529 /// <summary>
@@ -2187,15 +2738,25 @@ namespace OpenSim.Region.Framework.Scenes
2187 2738
2188 private void SendLandCollisionEvent(scriptEvents ev, ScriptCollidingNotification notify) 2739 private void SendLandCollisionEvent(scriptEvents ev, ScriptCollidingNotification notify)
2189 { 2740 {
2190 if ((ParentGroup.RootPart.ScriptEvents & ev) != 0) 2741 bool sendToRoot = true;
2191 { 2742
2192 ColliderArgs LandCollidingMessage = new ColliderArgs(); 2743 ColliderArgs LandCollidingMessage = new ColliderArgs();
2193 List<DetectedObject> colliding = new List<DetectedObject>(); 2744 List<DetectedObject> colliding = new List<DetectedObject>();
2194 2745
2195 colliding.Add(CreateDetObjectForGround()); 2746 colliding.Add(CreateDetObjectForGround());
2196 LandCollidingMessage.Colliders = colliding; 2747 LandCollidingMessage.Colliders = colliding;
2197 2748
2749 if (Inventory.ContainsScripts())
2750 {
2751 if (!PassCollisions)
2752 sendToRoot = false;
2753 }
2754 if ((ScriptEvents & ev) != 0)
2198 notify(LocalId, LandCollidingMessage); 2755 notify(LocalId, LandCollidingMessage);
2756
2757 if ((ParentGroup.RootPart.ScriptEvents & ev) != 0 && sendToRoot)
2758 {
2759 notify(ParentGroup.RootPart.LocalId, LandCollidingMessage);
2199 } 2760 }
2200 } 2761 }
2201 2762
@@ -2211,45 +2772,87 @@ namespace OpenSim.Region.Framework.Scenes
2211 List<uint> endedColliders = new List<uint>(); 2772 List<uint> endedColliders = new List<uint>();
2212 List<uint> startedColliders = new List<uint>(); 2773 List<uint> startedColliders = new List<uint>();
2213 2774
2214 // calculate things that started colliding this time 2775 if (collissionswith.Count == 0)
2215 // and build up list of colliders this time
2216 foreach (uint localid in collissionswith.Keys)
2217 { 2776 {
2218 thisHitColliders.Add(localid); 2777 if (m_lastColliders.Count == 0)
2219 if (!m_lastColliders.Contains(localid)) 2778 return; // nothing to do
2220 startedColliders.Add(localid);
2221 }
2222 2779
2223 // calculate things that ended colliding 2780 foreach (uint localID in m_lastColliders)
2224 foreach (uint localID in m_lastColliders) 2781 {
2225 {
2226 if (!thisHitColliders.Contains(localID))
2227 endedColliders.Add(localID); 2782 endedColliders.Add(localID);
2783 }
2784 m_lastColliders.Clear();
2228 } 2785 }
2229 2786
2230 //add the items that started colliding this time to the last colliders list. 2787 else
2231 foreach (uint localID in startedColliders) 2788 {
2232 m_lastColliders.Add(localID); 2789 List<CollisionForSoundInfo> soundinfolist = new List<CollisionForSoundInfo>();
2790
2791 // calculate things that started colliding this time
2792 // and build up list of colliders this time
2793 if (!VolumeDetectActive && CollisionSoundType >= 0)
2794 {
2795 CollisionForSoundInfo soundinfo;
2796 ContactPoint curcontact;
2797
2798 foreach (uint id in collissionswith.Keys)
2799 {
2800 thisHitColliders.Add(id);
2801 if (!m_lastColliders.Contains(id))
2802 {
2803 startedColliders.Add(id);
2804
2805 curcontact = collissionswith[id];
2806 if (Math.Abs(curcontact.RelativeSpeed) > 0.2)
2807 {
2808 soundinfo = new CollisionForSoundInfo();
2809 soundinfo.colliderID = id;
2810 soundinfo.position = curcontact.Position;
2811 soundinfo.relativeVel = curcontact.RelativeSpeed;
2812 soundinfolist.Add(soundinfo);
2813 }
2814 }
2815 }
2816 }
2817 else
2818 {
2819 foreach (uint id in collissionswith.Keys)
2820 {
2821 thisHitColliders.Add(id);
2822 if (!m_lastColliders.Contains(id))
2823 startedColliders.Add(id);
2824 }
2825 }
2826
2827 // calculate things that ended colliding
2828 foreach (uint localID in m_lastColliders)
2829 {
2830 if (!thisHitColliders.Contains(localID))
2831 endedColliders.Add(localID);
2832 }
2233 2833
2234 // remove things that ended colliding from the last colliders list 2834 //add the items that started colliding this time to the last colliders list.
2235 foreach (uint localID in endedColliders) 2835 foreach (uint localID in startedColliders)
2236 m_lastColliders.Remove(localID); 2836 m_lastColliders.Add(localID);
2237 2837
2238 // play the sound. 2838 // remove things that ended colliding from the last colliders list
2239 if (startedColliders.Count > 0 && CollisionSound != UUID.Zero && CollisionSoundVolume > 0.0f) 2839 foreach (uint localID in endedColliders)
2240 SendSound(CollisionSound.ToString(), CollisionSoundVolume, true, (byte)0, 0, false, false); 2840 m_lastColliders.Remove(localID);
2841
2842 // play sounds.
2843 if (soundinfolist.Count > 0)
2844 CollisionSounds.PartCollisionSound(this, soundinfolist);
2845 }
2241 2846
2242 SendCollisionEvent(scriptEvents.collision_start, startedColliders, ParentGroup.Scene.EventManager.TriggerScriptCollidingStart); 2847 SendCollisionEvent(scriptEvents.collision_start, startedColliders, ParentGroup.Scene.EventManager.TriggerScriptCollidingStart);
2243 SendCollisionEvent(scriptEvents.collision , m_lastColliders , ParentGroup.Scene.EventManager.TriggerScriptColliding); 2848 if (!VolumeDetectActive)
2849 SendCollisionEvent(scriptEvents.collision , m_lastColliders , ParentGroup.Scene.EventManager.TriggerScriptColliding);
2244 SendCollisionEvent(scriptEvents.collision_end , endedColliders , ParentGroup.Scene.EventManager.TriggerScriptCollidingEnd); 2850 SendCollisionEvent(scriptEvents.collision_end , endedColliders , ParentGroup.Scene.EventManager.TriggerScriptCollidingEnd);
2245 2851
2246 if (startedColliders.Contains(0)) 2852 if (startedColliders.Contains(0))
2247 { 2853 SendLandCollisionEvent(scriptEvents.land_collision_start, ParentGroup.Scene.EventManager.TriggerScriptLandCollidingStart);
2248 if (m_lastColliders.Contains(0)) 2854 if (m_lastColliders.Contains(0))
2249 SendLandCollisionEvent(scriptEvents.land_collision, ParentGroup.Scene.EventManager.TriggerScriptLandColliding); 2855 SendLandCollisionEvent(scriptEvents.land_collision, ParentGroup.Scene.EventManager.TriggerScriptLandColliding);
2250 else
2251 SendLandCollisionEvent(scriptEvents.land_collision_start, ParentGroup.Scene.EventManager.TriggerScriptLandCollidingStart);
2252 }
2253 if (endedColliders.Contains(0)) 2856 if (endedColliders.Contains(0))
2254 SendLandCollisionEvent(scriptEvents.land_collision_end, ParentGroup.Scene.EventManager.TriggerScriptLandCollidingEnd); 2857 SendLandCollisionEvent(scriptEvents.land_collision_end, ParentGroup.Scene.EventManager.TriggerScriptLandCollidingEnd);
2255 } 2858 }
@@ -2272,9 +2875,9 @@ namespace OpenSim.Region.Framework.Scenes
2272 Vector3 newpos = new Vector3(pa.Position.GetBytes(), 0); 2875 Vector3 newpos = new Vector3(pa.Position.GetBytes(), 0);
2273 2876
2274 if (ParentGroup.Scene.TestBorderCross(newpos, Cardinals.N) 2877 if (ParentGroup.Scene.TestBorderCross(newpos, Cardinals.N)
2275 | ParentGroup.Scene.TestBorderCross(newpos, Cardinals.S) 2878 || ParentGroup.Scene.TestBorderCross(newpos, Cardinals.S)
2276 | ParentGroup.Scene.TestBorderCross(newpos, Cardinals.E) 2879 || ParentGroup.Scene.TestBorderCross(newpos, Cardinals.E)
2277 | ParentGroup.Scene.TestBorderCross(newpos, Cardinals.W)) 2880 || ParentGroup.Scene.TestBorderCross(newpos, Cardinals.W))
2278 { 2881 {
2279 ParentGroup.AbsolutePosition = newpos; 2882 ParentGroup.AbsolutePosition = newpos;
2280 return; 2883 return;
@@ -2296,17 +2899,18 @@ namespace OpenSim.Region.Framework.Scenes
2296 //Trys to fetch sound id from prim's inventory. 2899 //Trys to fetch sound id from prim's inventory.
2297 //Prim's inventory doesn't support non script items yet 2900 //Prim's inventory doesn't support non script items yet
2298 2901
2299 lock (TaskInventory) 2902 TaskInventory.LockItemsForRead(true);
2903
2904 foreach (KeyValuePair<UUID, TaskInventoryItem> item in TaskInventory)
2300 { 2905 {
2301 foreach (KeyValuePair<UUID, TaskInventoryItem> item in TaskInventory) 2906 if (item.Value.Name == sound)
2302 { 2907 {
2303 if (item.Value.Name == sound) 2908 soundID = item.Value.ItemID;
2304 { 2909 break;
2305 soundID = item.Value.ItemID;
2306 break;
2307 }
2308 } 2910 }
2309 } 2911 }
2912
2913 TaskInventory.LockItemsForRead(false);
2310 } 2914 }
2311 2915
2312 ParentGroup.Scene.ForEachRootScenePresence(delegate(ScenePresence sp) 2916 ParentGroup.Scene.ForEachRootScenePresence(delegate(ScenePresence sp)
@@ -2428,6 +3032,19 @@ namespace OpenSim.Region.Framework.Scenes
2428 APIDTarget = Quaternion.Identity; 3032 APIDTarget = Quaternion.Identity;
2429 } 3033 }
2430 3034
3035
3036
3037 public void ScheduleFullUpdateIfNone()
3038 {
3039 if (ParentGroup == null)
3040 return;
3041
3042// ??? ParentGroup.HasGroupChanged = true;
3043
3044 if (UpdateFlag != UpdateRequired.FULL)
3045 ScheduleFullUpdate();
3046 }
3047
2431 /// <summary> 3048 /// <summary>
2432 /// Schedules this prim for a full update 3049 /// Schedules this prim for a full update
2433 /// </summary> 3050 /// </summary>
@@ -2630,8 +3247,8 @@ namespace OpenSim.Region.Framework.Scenes
2630 { 3247 {
2631 const float ROTATION_TOLERANCE = 0.01f; 3248 const float ROTATION_TOLERANCE = 0.01f;
2632 const float VELOCITY_TOLERANCE = 0.001f; 3249 const float VELOCITY_TOLERANCE = 0.001f;
2633 const float POSITION_TOLERANCE = 0.05f; 3250 const float POSITION_TOLERANCE = 0.05f; // I don't like this, but I suppose it's necessary
2634 const int TIME_MS_TOLERANCE = 3000; 3251 const int TIME_MS_TOLERANCE = 200; //llSetPos has a 200ms delay. This should NOT be 3 seconds.
2635 3252
2636 switch (UpdateFlag) 3253 switch (UpdateFlag)
2637 { 3254 {
@@ -2693,17 +3310,16 @@ namespace OpenSim.Region.Framework.Scenes
2693 if (!UUID.TryParse(sound, out soundID)) 3310 if (!UUID.TryParse(sound, out soundID))
2694 { 3311 {
2695 // search sound file from inventory 3312 // search sound file from inventory
2696 lock (TaskInventory) 3313 TaskInventory.LockItemsForRead(true);
3314 foreach (KeyValuePair<UUID, TaskInventoryItem> item in TaskInventory)
2697 { 3315 {
2698 foreach (KeyValuePair<UUID, TaskInventoryItem> item in TaskInventory) 3316 if (item.Value.Name == sound && item.Value.Type == (int)AssetType.Sound)
2699 { 3317 {
2700 if (item.Value.Name == sound && item.Value.Type == (int)AssetType.Sound) 3318 soundID = item.Value.ItemID;
2701 { 3319 break;
2702 soundID = item.Value.ItemID;
2703 break;
2704 }
2705 } 3320 }
2706 } 3321 }
3322 TaskInventory.LockItemsForRead(false);
2707 } 3323 }
2708 3324
2709 if (soundID == UUID.Zero) 3325 if (soundID == UUID.Zero)
@@ -2760,11 +3376,43 @@ namespace OpenSim.Region.Framework.Scenes
2760 } 3376 }
2761 } 3377 }
2762 3378
3379 public void SendCollisionSound(UUID soundID, double volume, Vector3 position)
3380 {
3381 if (soundID == UUID.Zero)
3382 return;
3383
3384 ISoundModule soundModule = ParentGroup.Scene.RequestModuleInterface<ISoundModule>();
3385 if (soundModule == null)
3386 return;
3387
3388 if (volume > 1)
3389 volume = 1;
3390 if (volume < 0)
3391 volume = 0;
3392
3393 int now = Util.EnvironmentTickCount();
3394 if(Util.EnvironmentTickCountSubtract(now,LastColSoundSentTime) <200)
3395 return;
3396
3397 LastColSoundSentTime = now;
3398
3399 UUID ownerID = OwnerID;
3400 UUID objectID = ParentGroup.RootPart.UUID;
3401 UUID parentID = ParentGroup.UUID;
3402 ulong regionHandle = ParentGroup.Scene.RegionInfo.RegionHandle;
3403
3404 soundModule.TriggerSound(soundID, ownerID, objectID, parentID, volume, position, regionHandle, 0 );
3405 }
3406
3407
2763 /// <summary> 3408 /// <summary>
2764 /// Send a terse update to all clients 3409 /// Send a terse update to all clients
2765 /// </summary> 3410 /// </summary>
2766 public void SendTerseUpdateToAllClients() 3411 public void SendTerseUpdateToAllClients()
2767 { 3412 {
3413 if (ParentGroup == null || ParentGroup.Scene == null)
3414 return;
3415
2768 ParentGroup.Scene.ForEachClient(delegate(IClientAPI client) 3416 ParentGroup.Scene.ForEachClient(delegate(IClientAPI client)
2769 { 3417 {
2770 SendTerseUpdateToClient(client); 3418 SendTerseUpdateToClient(client);
@@ -2788,10 +3436,13 @@ namespace OpenSim.Region.Framework.Scenes
2788 3436
2789 public void SetBuoyancy(float fvalue) 3437 public void SetBuoyancy(float fvalue)
2790 { 3438 {
2791 PhysicsActor pa = PhysActor; 3439 Buoyancy = fvalue;
2792 3440/*
2793 if (pa != null) 3441 if (PhysActor != null)
2794 pa.Buoyancy = fvalue; 3442 {
3443 PhysActor.Buoyancy = fvalue;
3444 }
3445 */
2795 } 3446 }
2796 3447
2797 public void SetDieAtEdge(bool p) 3448 public void SetDieAtEdge(bool p)
@@ -2807,47 +3458,111 @@ namespace OpenSim.Region.Framework.Scenes
2807 PhysicsActor pa = PhysActor; 3458 PhysicsActor pa = PhysActor;
2808 3459
2809 if (pa != null) 3460 if (pa != null)
2810 pa.FloatOnWater = floatYN == 1; 3461 pa.FloatOnWater = (floatYN == 1);
2811 } 3462 }
2812 3463
2813 public void SetForce(Vector3 force) 3464 public void SetForce(Vector3 force)
2814 { 3465 {
2815 PhysicsActor pa = PhysActor; 3466 Force = force;
3467 }
2816 3468
2817 if (pa != null) 3469 public SOPVehicle VehicleParams
2818 pa.Force = force; 3470 {
3471 get
3472 {
3473 return m_vehicleParams;
3474 }
3475 set
3476 {
3477 m_vehicleParams = value;
3478 }
3479 }
3480
3481
3482 public int VehicleType
3483 {
3484 get
3485 {
3486 if (m_vehicleParams == null)
3487 return (int)Vehicle.TYPE_NONE;
3488 else
3489 return (int)m_vehicleParams.Type;
3490 }
3491 set
3492 {
3493 SetVehicleType(value);
3494 }
2819 } 3495 }
2820 3496
2821 public void SetVehicleType(int type) 3497 public void SetVehicleType(int type)
2822 { 3498 {
2823 PhysicsActor pa = PhysActor; 3499 m_vehicleParams = null;
3500
3501 if (type == (int)Vehicle.TYPE_NONE)
3502 {
3503 if (_parentID ==0 && PhysActor != null)
3504 PhysActor.VehicleType = (int)Vehicle.TYPE_NONE;
3505 return;
3506 }
3507 m_vehicleParams = new SOPVehicle();
3508 m_vehicleParams.ProcessTypeChange((Vehicle)type);
3509 {
3510 if (_parentID ==0 && PhysActor != null)
3511 PhysActor.VehicleType = type;
3512 return;
3513 }
3514 }
2824 3515
2825 if (pa != null) 3516 public void SetVehicleFlags(int param, bool remove)
2826 pa.VehicleType = type; 3517 {
3518 if (m_vehicleParams == null)
3519 return;
3520
3521 m_vehicleParams.ProcessVehicleFlags(param, remove);
3522
3523 if (_parentID ==0 && PhysActor != null)
3524 {
3525 PhysActor.VehicleFlags(param, remove);
3526 }
2827 } 3527 }
2828 3528
2829 public void SetVehicleFloatParam(int param, float value) 3529 public void SetVehicleFloatParam(int param, float value)
2830 { 3530 {
2831 PhysicsActor pa = PhysActor; 3531 if (m_vehicleParams == null)
3532 return;
2832 3533
2833 if (pa != null) 3534 m_vehicleParams.ProcessFloatVehicleParam((Vehicle)param, value);
2834 pa.VehicleFloatParam(param, value); 3535
3536 if (_parentID == 0 && PhysActor != null)
3537 {
3538 PhysActor.VehicleFloatParam(param, value);
3539 }
2835 } 3540 }
2836 3541
2837 public void SetVehicleVectorParam(int param, Vector3 value) 3542 public void SetVehicleVectorParam(int param, Vector3 value)
2838 { 3543 {
2839 PhysicsActor pa = PhysActor; 3544 if (m_vehicleParams == null)
3545 return;
2840 3546
2841 if (pa != null) 3547 m_vehicleParams.ProcessVectorVehicleParam((Vehicle)param, value);
2842 pa.VehicleVectorParam(param, value); 3548
3549 if (_parentID == 0 && PhysActor != null)
3550 {
3551 PhysActor.VehicleVectorParam(param, value);
3552 }
2843 } 3553 }
2844 3554
2845 public void SetVehicleRotationParam(int param, Quaternion rotation) 3555 public void SetVehicleRotationParam(int param, Quaternion rotation)
2846 { 3556 {
2847 PhysicsActor pa = PhysActor; 3557 if (m_vehicleParams == null)
3558 return;
2848 3559
2849 if (pa != null) 3560 m_vehicleParams.ProcessRotationVehicleParam((Vehicle)param, rotation);
2850 pa.VehicleRotationParam(param, rotation); 3561
3562 if (_parentID == 0 && PhysActor != null)
3563 {
3564 PhysActor.VehicleRotationParam(param, rotation);
3565 }
2851 } 3566 }
2852 3567
2853 /// <summary> 3568 /// <summary>
@@ -3048,14 +3763,6 @@ namespace OpenSim.Region.Framework.Scenes
3048 hasProfileCut = hasDimple; // is it the same thing? 3763 hasProfileCut = hasDimple; // is it the same thing?
3049 } 3764 }
3050 3765
3051 public void SetVehicleFlags(int param, bool remove)
3052 {
3053 PhysicsActor pa = PhysActor;
3054
3055 if (pa != null)
3056 pa.VehicleFlags(param, remove);
3057 }
3058
3059 public void SetGroup(UUID groupID, IClientAPI client) 3766 public void SetGroup(UUID groupID, IClientAPI client)
3060 { 3767 {
3061 // Scene.AddNewPrims() calls with client == null so can't use this. 3768 // Scene.AddNewPrims() calls with client == null so can't use this.
@@ -3159,71 +3866,18 @@ namespace OpenSim.Region.Framework.Scenes
3159 //ParentGroup.ScheduleGroupForFullUpdate(); 3866 //ParentGroup.ScheduleGroupForFullUpdate();
3160 } 3867 }
3161 3868
3162 public void StoreUndoState() 3869 public void StoreUndoState(ObjectChangeType change)
3163 { 3870 {
3164 StoreUndoState(false); 3871 if (m_UndoRedo == null)
3165 } 3872 m_UndoRedo = new UndoRedoState(5);
3166 3873
3167 public void StoreUndoState(bool forGroup) 3874 lock (m_UndoRedo)
3168 {
3169 if (!Undoing)
3170 { 3875 {
3171 if (!IgnoreUndoUpdate) 3876 if (!Undoing && !IgnoreUndoUpdate && ParentGroup != null) // just to read better - undo is in progress, or suspended
3172 { 3877 {
3173 if (ParentGroup != null) 3878 m_UndoRedo.StoreUndo(this, change);
3174 {
3175 lock (m_undo)
3176 {
3177 if (m_undo.Count > 0)
3178 {
3179 UndoState last = m_undo[m_undo.Count - 1];
3180 if (last != null)
3181 {
3182 // TODO: May need to fix for group comparison
3183 if (last.Compare(this))
3184 {
3185 // m_log.DebugFormat(
3186 // "[SCENE OBJECT PART]: Not storing undo for {0} {1} since current state is same as last undo state, initial stack size {2}",
3187 // Name, LocalId, m_undo.Count);
3188
3189 return;
3190 }
3191 }
3192 }
3193
3194// m_log.DebugFormat(
3195// "[SCENE OBJECT PART]: Storing undo state for {0} {1}, forGroup {2}, initial stack size {3}",
3196// Name, LocalId, forGroup, m_undo.Count);
3197
3198 if (ParentGroup.GetSceneMaxUndo() > 0)
3199 {
3200 UndoState nUndo = new UndoState(this, forGroup);
3201
3202 m_undo.Add(nUndo);
3203
3204 if (m_undo.Count > ParentGroup.GetSceneMaxUndo())
3205 m_undo.RemoveAt(0);
3206
3207 if (m_redo.Count > 0)
3208 m_redo.Clear();
3209
3210// m_log.DebugFormat(
3211// "[SCENE OBJECT PART]: Stored undo state for {0} {1}, forGroup {2}, stack size now {3}",
3212// Name, LocalId, forGroup, m_undo.Count);
3213 }
3214 }
3215 }
3216 } 3879 }
3217// else
3218// {
3219// m_log.DebugFormat("[SCENE OBJECT PART]: Ignoring undo store for {0} {1}", Name, LocalId);
3220// }
3221 } 3880 }
3222// else
3223// {
3224// m_log.DebugFormat(
3225// "[SCENE OBJECT PART]: Ignoring undo store for {0} {1} since already undoing", Name, LocalId);
3226// }
3227 } 3881 }
3228 3882
3229 /// <summary> 3883 /// <summary>
@@ -3233,88 +3887,46 @@ namespace OpenSim.Region.Framework.Scenes
3233 { 3887 {
3234 get 3888 get
3235 { 3889 {
3236 lock (m_undo) 3890 if (m_UndoRedo == null)
3237 return m_undo.Count; 3891 return 0;
3892 return m_UndoRedo.Count;
3238 } 3893 }
3239 } 3894 }
3240 3895
3241 public void Undo() 3896 public void Undo()
3242 { 3897 {
3243 lock (m_undo) 3898 if (m_UndoRedo == null || Undoing || ParentGroup == null)
3244 { 3899 return;
3245// m_log.DebugFormat(
3246// "[SCENE OBJECT PART]: Handling undo request for {0} {1}, stack size {2}",
3247// Name, LocalId, m_undo.Count);
3248
3249 if (m_undo.Count > 0)
3250 {
3251 UndoState goback = m_undo[m_undo.Count - 1];
3252 m_undo.RemoveAt(m_undo.Count - 1);
3253
3254 UndoState nUndo = null;
3255
3256 if (ParentGroup.GetSceneMaxUndo() > 0)
3257 {
3258 nUndo = new UndoState(this, goback.ForGroup);
3259 }
3260
3261 goback.PlaybackState(this);
3262
3263 if (nUndo != null)
3264 {
3265 m_redo.Add(nUndo);
3266
3267 if (m_redo.Count > ParentGroup.GetSceneMaxUndo())
3268 m_redo.RemoveAt(0);
3269 }
3270 }
3271 3900
3272// m_log.DebugFormat( 3901 lock (m_UndoRedo)
3273// "[SCENE OBJECT PART]: Handled undo request for {0} {1}, stack size now {2}", 3902 {
3274// Name, LocalId, m_undo.Count); 3903 Undoing = true;
3904 m_UndoRedo.Undo(this);
3905 Undoing = false;
3275 } 3906 }
3276 } 3907 }
3277 3908
3278 public void Redo() 3909 public void Redo()
3279 { 3910 {
3280 lock (m_undo) 3911 if (m_UndoRedo == null || Undoing || ParentGroup == null)
3281 { 3912 return;
3282// m_log.DebugFormat(
3283// "[SCENE OBJECT PART]: Handling redo request for {0} {1}, stack size {2}",
3284// Name, LocalId, m_redo.Count);
3285
3286 if (m_redo.Count > 0)
3287 {
3288 UndoState gofwd = m_redo[m_redo.Count - 1];
3289 m_redo.RemoveAt(m_redo.Count - 1);
3290
3291 if (ParentGroup.GetSceneMaxUndo() > 0)
3292 {
3293 UndoState nUndo = new UndoState(this, gofwd.ForGroup);
3294
3295 m_undo.Add(nUndo);
3296
3297 if (m_undo.Count > ParentGroup.GetSceneMaxUndo())
3298 m_undo.RemoveAt(0);
3299 }
3300
3301 gofwd.PlayfwdState(this);
3302 3913
3303// m_log.DebugFormat( 3914 lock (m_UndoRedo)
3304// "[SCENE OBJECT PART]: Handled redo request for {0} {1}, stack size now {2}", 3915 {
3305// Name, LocalId, m_redo.Count); 3916 Undoing = true;
3306 } 3917 m_UndoRedo.Redo(this);
3918 Undoing = false;
3307 } 3919 }
3308 } 3920 }
3309 3921
3310 public void ClearUndoState() 3922 public void ClearUndoState()
3311 { 3923 {
3312// m_log.DebugFormat("[SCENE OBJECT PART]: Clearing undo and redo stacks in {0} {1}", Name, LocalId); 3924 if (m_UndoRedo == null || Undoing)
3925 return;
3313 3926
3314 lock (m_undo) 3927 lock (m_UndoRedo)
3315 { 3928 {
3316 m_undo.Clear(); 3929 m_UndoRedo.Clear();
3317 m_redo.Clear();
3318 } 3930 }
3319 } 3931 }
3320 3932
@@ -3965,6 +4577,27 @@ namespace OpenSim.Region.Framework.Scenes
3965 } 4577 }
3966 } 4578 }
3967 4579
4580
4581 public void UpdateExtraPhysics(ExtraPhysicsData physdata)
4582 {
4583 if (physdata.PhysShapeType == PhysShapeType.invalid || ParentGroup == null)
4584 return;
4585
4586 if (PhysicsShapeType != (byte)physdata.PhysShapeType)
4587 {
4588 PhysicsShapeType = (byte)physdata.PhysShapeType;
4589
4590 }
4591
4592 if(Density != physdata.Density)
4593 Density = physdata.Density;
4594 if(GravityModifier != physdata.GravitationModifier)
4595 GravityModifier = physdata.GravitationModifier;
4596 if(Friction != physdata.Friction)
4597 Friction = physdata.Friction;
4598 if(Bounciness != physdata.Bounce)
4599 Bounciness = physdata.Bounce;
4600 }
3968 /// <summary> 4601 /// <summary>
3969 /// Update the flags on this prim. This covers properties such as phantom, physics and temporary. 4602 /// Update the flags on this prim. This covers properties such as phantom, physics and temporary.
3970 /// </summary> 4603 /// </summary>
@@ -3972,7 +4605,7 @@ namespace OpenSim.Region.Framework.Scenes
3972 /// <param name="SetTemporary"></param> 4605 /// <param name="SetTemporary"></param>
3973 /// <param name="SetPhantom"></param> 4606 /// <param name="SetPhantom"></param>
3974 /// <param name="SetVD"></param> 4607 /// <param name="SetVD"></param>
3975 public void UpdatePrimFlags(bool UsePhysics, bool SetTemporary, bool SetPhantom, bool SetVD) 4608 public void UpdatePrimFlags(bool UsePhysics, bool SetTemporary, bool SetPhantom, bool SetVD, bool building)
3976 { 4609 {
3977 bool wasUsingPhysics = ((Flags & PrimFlags.Physics) != 0); 4610 bool wasUsingPhysics = ((Flags & PrimFlags.Physics) != 0);
3978 bool wasTemporary = ((Flags & PrimFlags.TemporaryOnRez) != 0); 4611 bool wasTemporary = ((Flags & PrimFlags.TemporaryOnRez) != 0);
@@ -3982,237 +4615,230 @@ namespace OpenSim.Region.Framework.Scenes
3982 if ((UsePhysics == wasUsingPhysics) && (wasTemporary == SetTemporary) && (wasPhantom == SetPhantom) && (SetVD == wasVD)) 4615 if ((UsePhysics == wasUsingPhysics) && (wasTemporary == SetTemporary) && (wasPhantom == SetPhantom) && (SetVD == wasVD))
3983 return; 4616 return;
3984 4617
3985 PhysicsActor pa = PhysActor; 4618 VolumeDetectActive = SetVD;
3986
3987 // Special cases for VD. VD can only be called from a script
3988 // and can't be combined with changes to other states. So we can rely
3989 // that...
3990 // ... if VD is changed, all others are not.
3991 // ... if one of the others is changed, VD is not.
3992 if (SetVD) // VD is active, special logic applies
3993 {
3994 // State machine logic for VolumeDetect
3995 // More logic below
3996 bool phanReset = (SetPhantom != wasPhantom) && !SetPhantom;
3997
3998 if (phanReset) // Phantom changes from on to off switch VD off too
3999 {
4000 SetVD = false; // Switch it of for the course of this routine
4001 VolumeDetectActive = false; // and also permanently
4002
4003 if (pa != null)
4004 pa.SetVolumeDetect(0); // Let physics know about it too
4005 }
4006 else
4007 {
4008 // If volumedetect is active we don't want phantom to be applied.
4009 // If this is a new call to VD out of the state "phantom"
4010 // this will also cause the prim to be visible to physics
4011 SetPhantom = false;
4012 }
4013 }
4014 4619
4015 if (UsePhysics && IsJoint()) 4620 // volume detector implies phantom
4016 { 4621 if (VolumeDetectActive)
4017 SetPhantom = true; 4622 SetPhantom = true;
4018 }
4019 4623
4020 if (UsePhysics) 4624 if (UsePhysics)
4021 {
4022 AddFlag(PrimFlags.Physics); 4625 AddFlag(PrimFlags.Physics);
4023 if (!wasUsingPhysics)
4024 {
4025 DoPhysicsPropertyUpdate(UsePhysics, false);
4026
4027 if (!ParentGroup.IsDeleted)
4028 {
4029 if (LocalId == ParentGroup.RootPart.LocalId)
4030 {
4031 ParentGroup.CheckSculptAndLoad();
4032 }
4033 }
4034 }
4035 }
4036 else 4626 else
4037 {
4038 RemFlag(PrimFlags.Physics); 4627 RemFlag(PrimFlags.Physics);
4039 if (wasUsingPhysics)
4040 {
4041 DoPhysicsPropertyUpdate(UsePhysics, false);
4042 }
4043 }
4044 4628
4045 if (SetPhantom 4629 if (SetPhantom)
4046 || ParentGroup.IsAttachment
4047 || (Shape.PathCurve == (byte)Extrusion.Flexible)) // note: this may have been changed above in the case of joints
4048 {
4049 AddFlag(PrimFlags.Phantom); 4630 AddFlag(PrimFlags.Phantom);
4631 else
4632 RemFlag(PrimFlags.Phantom);
4050 4633
4051 if (PhysActor != null) 4634 if (SetTemporary)
4635 AddFlag(PrimFlags.TemporaryOnRez);
4636 else
4637 RemFlag(PrimFlags.TemporaryOnRez);
4638
4639
4640 if (ParentGroup.Scene == null)
4641 return;
4642
4643 PhysicsActor pa = PhysActor;
4644
4645 if (pa != null && building && pa.Building != building)
4646 pa.Building = building;
4647
4648 if ((SetPhantom && !UsePhysics && !SetVD) || ParentGroup.IsAttachment || PhysicsShapeType == (byte)PhysShapeType.none
4649 || (Shape.PathCurve == (byte)Extrusion.Flexible))
4650 {
4651 if (pa != null)
4052 { 4652 {
4653 if(wasUsingPhysics)
4654 ParentGroup.Scene.RemovePhysicalPrim(1);
4053 RemoveFromPhysics(); 4655 RemoveFromPhysics();
4054 pa = null;
4055 } 4656 }
4657
4658 Velocity = new Vector3(0, 0, 0);
4659 Acceleration = new Vector3(0, 0, 0);
4660 if (ParentGroup.RootPart == this)
4661 AngularVelocity = new Vector3(0, 0, 0);
4056 } 4662 }
4057 else // Not phantom 4663 else
4058 { 4664 {
4059 RemFlag(PrimFlags.Phantom); 4665 if (ParentGroup.Scene.CollidablePrims)
4060
4061 if (ParentGroup.Scene == null)
4062 return;
4063
4064 if (ParentGroup.Scene.CollidablePrims && pa == null)
4065 { 4666 {
4066 pa = AddToPhysics(UsePhysics); 4667 if (pa == null)
4067
4068 if (pa != null)
4069 { 4668 {
4070 pa.SetMaterial(Material); 4669 AddToPhysics(UsePhysics, SetPhantom, building, false);
4071 DoPhysicsPropertyUpdate(UsePhysics, true); 4670 pa = PhysActor;
4072 4671/*
4073 if (!ParentGroup.IsDeleted) 4672 if (pa != null)
4074 { 4673 {
4075 if (LocalId == ParentGroup.RootPart.LocalId) 4674 if (
4675// ((AggregateScriptEvents & scriptEvents.collision) != 0) ||
4676// ((AggregateScriptEvents & scriptEvents.collision_end) != 0) ||
4677// ((AggregateScriptEvents & scriptEvents.collision_start) != 0) ||
4678// ((AggregateScriptEvents & scriptEvents.land_collision_start) != 0) ||
4679// ((AggregateScriptEvents & scriptEvents.land_collision) != 0) ||
4680// ((AggregateScriptEvents & scriptEvents.land_collision_end) != 0) ||
4681 ((AggregateScriptEvents & PhysicsNeededSubsEvents) != 0) ||
4682 ((ParentGroup.RootPart.AggregateScriptEvents & PhysicsNeededSubsEvents) != 0) ||
4683 (CollisionSound != UUID.Zero)
4684 )
4076 { 4685 {
4077 ParentGroup.CheckSculptAndLoad(); 4686 pa.OnCollisionUpdate += PhysicsCollision;
4687 pa.SubscribeEvents(1000);
4078 } 4688 }
4079 } 4689 }
4080 4690*/
4081 if (
4082 ((AggregateScriptEvents & scriptEvents.collision) != 0) ||
4083 ((AggregateScriptEvents & scriptEvents.collision_end) != 0) ||
4084 ((AggregateScriptEvents & scriptEvents.collision_start) != 0) ||
4085 ((AggregateScriptEvents & scriptEvents.land_collision_start) != 0) ||
4086 ((AggregateScriptEvents & scriptEvents.land_collision) != 0) ||
4087 ((AggregateScriptEvents & scriptEvents.land_collision_end) != 0) ||
4088 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.collision) != 0) ||
4089 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.collision_end) != 0) ||
4090 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.collision_start) != 0) ||
4091 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.land_collision_start) != 0) ||
4092 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.land_collision) != 0) ||
4093 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.land_collision_end) != 0) ||
4094 (CollisionSound != UUID.Zero)
4095 )
4096 {
4097 pa.OnCollisionUpdate += PhysicsCollision;
4098 pa.SubscribeEvents(1000);
4099 }
4100 } 4691 }
4101 } 4692 else // it already has a physical representation
4102 else // it already has a physical representation
4103 {
4104 DoPhysicsPropertyUpdate(UsePhysics, false); // Update physical status. If it's phantom this will remove the prim
4105
4106 if (!ParentGroup.IsDeleted)
4107 { 4693 {
4108 if (LocalId == ParentGroup.RootPart.LocalId) 4694 DoPhysicsPropertyUpdate(UsePhysics, false); // Update physical status.
4109 { 4695/* moved into DoPhysicsPropertyUpdate
4110 ParentGroup.CheckSculptAndLoad(); 4696 if(VolumeDetectActive)
4111 } 4697 pa.SetVolumeDetect(1);
4698 else
4699 pa.SetVolumeDetect(0);
4700*/
4701
4702 if (pa.Building != building)
4703 pa.Building = building;
4112 } 4704 }
4113 }
4114 }
4115 4705
4116 if (SetVD) 4706 UpdatePhysicsSubscribedEvents();
4117 {
4118 // If the above logic worked (this is urgent candidate to unit tests!)
4119 // we now have a physicsactor.
4120 // Defensive programming calls for a check here.
4121 // Better would be throwing an exception that could be catched by a unit test as the internal
4122 // logic should make sure, this Physactor is always here.
4123 if (pa != null)
4124 {
4125 pa.SetVolumeDetect(1);
4126 AddFlag(PrimFlags.Phantom); // We set this flag also if VD is active
4127 VolumeDetectActive = true;
4128 } 4707 }
4129 } 4708 }
4130 else
4131 {
4132 // Remove VolumeDetect in any case. Note, it's safe to call SetVolumeDetect as often as you like
4133 // (mumbles, well, at least if you have infinte CPU powers :-))
4134 if (pa != null)
4135 pa.SetVolumeDetect(0);
4136
4137 VolumeDetectActive = false;
4138 }
4139
4140 if (SetTemporary)
4141 {
4142 AddFlag(PrimFlags.TemporaryOnRez);
4143 }
4144 else
4145 {
4146 RemFlag(PrimFlags.TemporaryOnRez);
4147 }
4148 4709
4149 // m_log.Debug("Update: PHY:" + UsePhysics.ToString() + ", T:" + IsTemporary.ToString() + ", PHA:" + IsPhantom.ToString() + " S:" + CastsShadows.ToString()); 4710 // m_log.Debug("Update: PHY:" + UsePhysics.ToString() + ", T:" + IsTemporary.ToString() + ", PHA:" + IsPhantom.ToString() + " S:" + CastsShadows.ToString());
4150 4711
4712 // and last in case we have a new actor and not building
4713
4151 if (ParentGroup != null) 4714 if (ParentGroup != null)
4152 { 4715 {
4153 ParentGroup.HasGroupChanged = true; 4716 ParentGroup.HasGroupChanged = true;
4154 ScheduleFullUpdate(); 4717 ScheduleFullUpdate();
4155 } 4718 }
4156 4719
4157// m_log.DebugFormat("[SCENE OBJECT PART]: Updated PrimFlags on {0} {1} to {2}", Name, LocalId, Flags); 4720// m_log.DebugFormat("[SCENE OBJECT PART]: Updated PrimFlags on {0} {1} to {2}", Name, LocalId, Flags);
4158 } 4721 }
4159 4722
4160 /// <summary> 4723 /// <summary>
4161 /// Adds this part to the physics scene. 4724 /// Adds this part to the physics scene.
4725 /// and sets the PhysActor property
4162 /// </summary> 4726 /// </summary>
4163 /// <remarks>This method also sets the PhysActor property.</remarks> 4727 /// <param name="isPhysical">Add this prim as physical.</param>
4164 /// <param name="rigidBody">Add this prim with a rigid body.</param> 4728 /// <param name="isPhantom">Add this prim as phantom.</param>
4165 /// <returns> 4729 /// <param name="building">tells physics to delay full construction of object</param>
4166 /// The physics actor. null if there was a failure. 4730 /// <param name="applyDynamics">applies velocities, force and torque</param>
4167 /// </returns> 4731 private void AddToPhysics(bool isPhysical, bool isPhantom, bool building, bool applyDynamics)
4168 private PhysicsActor AddToPhysics(bool rigidBody) 4732 {
4169 {
4170 PhysicsActor pa; 4733 PhysicsActor pa;
4171 4734
4735 Vector3 velocity = Velocity;
4736 Vector3 rotationalVelocity = AngularVelocity;;
4737
4172 try 4738 try
4173 { 4739 {
4174 pa = ParentGroup.Scene.PhysicsScene.AddPrimShape( 4740 pa = ParentGroup.Scene.PhysicsScene.AddPrimShape(
4175 string.Format("{0}/{1}", Name, UUID), 4741 string.Format("{0}/{1}", Name, UUID),
4176 Shape, 4742 Shape,
4177 AbsolutePosition, 4743 AbsolutePosition,
4178 Scale, 4744 Scale,
4179 RotationOffset, 4745 GetWorldRotation(),
4180 rigidBody, 4746 isPhysical,
4181 m_localId); 4747 isPhantom,
4748 PhysicsShapeType,
4749 m_localId);
4182 } 4750 }
4183 catch 4751 catch (Exception ex)
4184 { 4752 {
4185 m_log.ErrorFormat("[SCENE]: caught exception meshing object {0}. Object set to phantom.", m_uuid); 4753 m_log.ErrorFormat("[SCENE]: AddToPhysics object {0} failed: {1}", m_uuid, ex.Message);
4186 pa = null; 4754 pa = null;
4187 } 4755 }
4188 4756
4189 // FIXME: Ideally we wouldn't set the property here to reduce situations where threads changing physical
4190 // properties can stop on each other. However, DoPhysicsPropertyUpdate() currently relies on PhysActor
4191 // being set.
4192 PhysActor = pa;
4193
4194 // Basic Physics can also return null as well as an exception catch.
4195 if (pa != null) 4757 if (pa != null)
4196 { 4758 {
4197 pa.SOPName = this.Name; // save object into the PhysActor so ODE internals know the joint/body info 4759 pa.SOPName = this.Name; // save object into the PhysActor so ODE internals know the joint/body info
4198 pa.SetMaterial(Material); 4760 pa.SetMaterial(Material);
4199 DoPhysicsPropertyUpdate(rigidBody, true); 4761
4762 if (VolumeDetectActive) // change if not the default only
4763 pa.SetVolumeDetect(1);
4764
4765 if (m_vehicleParams != null && LocalId == ParentGroup.RootPart.LocalId)
4766 m_vehicleParams.SetVehicle(pa);
4767
4768 // we are going to tell rest of code about physics so better have this here
4769 PhysActor = pa;
4770
4771 // DoPhysicsPropertyUpdate(isPhysical, true);
4772 // lets expand it here just with what it really needs to do
4773
4774 if (isPhysical)
4775 {
4776 if (ParentGroup.RootPart.KeyframeMotion != null)
4777 ParentGroup.RootPart.KeyframeMotion.Stop();
4778 ParentGroup.RootPart.KeyframeMotion = null;
4779 ParentGroup.Scene.AddPhysicalPrim(1);
4780
4781 pa.OnRequestTerseUpdate += PhysicsRequestingTerseUpdate;
4782 pa.OnOutOfBounds += PhysicsOutOfBounds;
4783
4784 if (ParentID != 0 && ParentID != LocalId)
4785 {
4786 PhysicsActor parentPa = ParentGroup.RootPart.PhysActor;
4787
4788 if (parentPa != null)
4789 {
4790 pa.link(parentPa);
4791 }
4792 }
4793 }
4794
4795 if (applyDynamics)
4796 // do independent of isphysical so parameters get setted (at least some)
4797 {
4798 Velocity = velocity;
4799 AngularVelocity = rotationalVelocity;
4800// pa.Velocity = velocity;
4801 pa.RotationalVelocity = rotationalVelocity;
4802
4803 // if not vehicle and root part apply force and torque
4804 if ((m_vehicleParams == null || m_vehicleParams.Type == Vehicle.TYPE_NONE)
4805 && LocalId == ParentGroup.RootPart.LocalId)
4806 {
4807 pa.Force = Force;
4808 pa.Torque = Torque;
4809 }
4810 }
4811
4812 if (Shape.SculptEntry)
4813 CheckSculptAndLoad();
4814 else
4815 ParentGroup.Scene.PhysicsScene.AddPhysicsActorTaint(pa);
4816
4817 if (!building)
4818 pa.Building = false;
4200 } 4819 }
4201 4820
4202 return pa; 4821 PhysActor = pa;
4203 } 4822 }
4204 4823
4205 /// <summary> 4824 /// <summary>
4206 /// This removes the part from the physics scene. 4825 /// This removes the part from the physics scene.
4207 /// </summary> 4826 /// </summary>
4208 /// <remarks> 4827 /// <remarks>
4209 /// This isn't the same as turning off physical, since even without being physical the prim has a physics 4828 /// This isn't the same as turning off physical, since even without being physical the prim has a physics
4210 /// representation for collision detection. Rather, this would be used in situations such as making a prim 4829 /// representation for collision detection.
4211 /// phantom.
4212 /// </remarks> 4830 /// </remarks>
4213 public void RemoveFromPhysics() 4831 public void RemoveFromPhysics()
4214 { 4832 {
4215 ParentGroup.Scene.PhysicsScene.RemovePrim(PhysActor); 4833 PhysicsActor pa = PhysActor;
4834 if (pa != null)
4835 {
4836 pa.OnCollisionUpdate -= PhysicsCollision;
4837 pa.OnRequestTerseUpdate -= PhysicsRequestingTerseUpdate;
4838 pa.OnOutOfBounds -= PhysicsOutOfBounds;
4839
4840 ParentGroup.Scene.PhysicsScene.RemovePrim(pa);
4841 }
4216 PhysActor = null; 4842 PhysActor = null;
4217 } 4843 }
4218 4844
@@ -4423,6 +5049,44 @@ namespace OpenSim.Region.Framework.Scenes
4423 ScheduleFullUpdate(); 5049 ScheduleFullUpdate();
4424 } 5050 }
4425 5051
5052
5053 private void UpdatePhysicsSubscribedEvents()
5054 {
5055 PhysicsActor pa = PhysActor;
5056 if (pa == null)
5057 return;
5058
5059 pa.OnCollisionUpdate -= PhysicsCollision;
5060
5061 bool hassound = (!VolumeDetectActive && CollisionSoundType >= 0 && ((Flags & PrimFlags.Physics) != 0));
5062
5063 scriptEvents CombinedEvents = AggregateScriptEvents;
5064
5065 // merge with root part
5066 if (ParentGroup != null && ParentGroup.RootPart != null)
5067 CombinedEvents |= ParentGroup.RootPart.AggregateScriptEvents;
5068
5069 // submit to this part case
5070 if (VolumeDetectActive)
5071 CombinedEvents &= PhyscicsVolumeDtcSubsEvents;
5072 else if ((Flags & PrimFlags.Phantom) != 0)
5073 CombinedEvents &= PhyscicsPhantonSubsEvents;
5074 else
5075 CombinedEvents &= PhysicsNeededSubsEvents;
5076
5077 if (hassound || CombinedEvents != 0)
5078 {
5079 // subscribe to physics updates.
5080 pa.OnCollisionUpdate += PhysicsCollision;
5081 pa.SubscribeEvents(50); // 20 reports per second
5082 }
5083 else
5084 {
5085 pa.UnSubscribeEvents();
5086 }
5087 }
5088
5089
4426 public void aggregateScriptEvents() 5090 public void aggregateScriptEvents()
4427 { 5091 {
4428 if (ParentGroup == null || ParentGroup.RootPart == null) 5092 if (ParentGroup == null || ParentGroup.RootPart == null)
@@ -4459,40 +5123,32 @@ namespace OpenSim.Region.Framework.Scenes
4459 { 5123 {
4460 objectflagupdate |= (uint) PrimFlags.AllowInventoryDrop; 5124 objectflagupdate |= (uint) PrimFlags.AllowInventoryDrop;
4461 } 5125 }
4462 5126/*
4463 PhysicsActor pa = PhysActor; 5127 PhysicsActor pa = PhysActor;
4464 5128 if (pa != null)
4465 if (
4466 ((AggregateScriptEvents & scriptEvents.collision) != 0) ||
4467 ((AggregateScriptEvents & scriptEvents.collision_end) != 0) ||
4468 ((AggregateScriptEvents & scriptEvents.collision_start) != 0) ||
4469 ((AggregateScriptEvents & scriptEvents.land_collision_start) != 0) ||
4470 ((AggregateScriptEvents & scriptEvents.land_collision) != 0) ||
4471 ((AggregateScriptEvents & scriptEvents.land_collision_end) != 0) ||
4472 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.collision) != 0) ||
4473 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.collision_end) != 0) ||
4474 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.collision_start) != 0) ||
4475 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.land_collision_start) != 0) ||
4476 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.land_collision) != 0) ||
4477 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.land_collision_end) != 0) ||
4478 (CollisionSound != UUID.Zero)
4479 )
4480 { 5129 {
4481 // subscribe to physics updates. 5130 if (
4482 if (pa != null) 5131// ((AggregateScriptEvents & scriptEvents.collision) != 0) ||
5132// ((AggregateScriptEvents & scriptEvents.collision_end) != 0) ||
5133// ((AggregateScriptEvents & scriptEvents.collision_start) != 0) ||
5134// ((AggregateScriptEvents & scriptEvents.land_collision_start) != 0) ||
5135// ((AggregateScriptEvents & scriptEvents.land_collision) != 0) ||
5136// ((AggregateScriptEvents & scriptEvents.land_collision_end) != 0) ||
5137 ((AggregateScriptEvents & PhysicsNeededSubsEvents) != 0) || ((ParentGroup.RootPart.AggregateScriptEvents & PhysicsNeededSubsEvents) != 0) || (CollisionSound != UUID.Zero)
5138 )
4483 { 5139 {
5140 // subscribe to physics updates.
4484 pa.OnCollisionUpdate += PhysicsCollision; 5141 pa.OnCollisionUpdate += PhysicsCollision;
4485 pa.SubscribeEvents(1000); 5142 pa.SubscribeEvents(1000);
4486 } 5143 }
4487 } 5144 else
4488 else
4489 {
4490 if (pa != null)
4491 { 5145 {
4492 pa.UnSubscribeEvents(); 5146 pa.UnSubscribeEvents();
4493 pa.OnCollisionUpdate -= PhysicsCollision; 5147 pa.OnCollisionUpdate -= PhysicsCollision;
4494 } 5148 }
4495 } 5149 }
5150 */
5151 UpdatePhysicsSubscribedEvents();
4496 5152
4497 //if ((GetEffectiveObjectFlags() & (uint)PrimFlags.Scripted) != 0) 5153 //if ((GetEffectiveObjectFlags() & (uint)PrimFlags.Scripted) != 0)
4498 //{ 5154 //{
@@ -4622,6 +5278,18 @@ namespace OpenSim.Region.Framework.Scenes
4622 return new Color4(color.R, color.G, color.B, (byte)(0xFF - color.A)); 5278 return new Color4(color.R, color.G, color.B, (byte)(0xFF - color.A));
4623 } 5279 }
4624 5280
5281 public void ResetOwnerChangeFlag()
5282 {
5283 List<UUID> inv = Inventory.GetInventoryList();
5284
5285 foreach (UUID itemID in inv)
5286 {
5287 TaskInventoryItem item = Inventory.GetInventoryItem(itemID);
5288 item.OwnerChanged = false;
5289 Inventory.UpdateInventoryItem(item, false, false);
5290 }
5291 }
5292
4625 /// <summary> 5293 /// <summary>
4626 /// Record an avatar sitting on this part. 5294 /// Record an avatar sitting on this part.
4627 /// </summary> 5295 /// </summary>
diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs b/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs
index 821fd81..e010864 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;
@@ -124,38 +129,45 @@ namespace OpenSim.Region.Framework.Scenes
124 public void ResetInventoryIDs() 129 public void ResetInventoryIDs()
125 { 130 {
126 if (null == m_part) 131 if (null == m_part)
127 return; 132 m_items.LockItemsForWrite(true);
128 133
129 lock (m_items) 134 if (Items.Count == 0)
130 { 135 {
131 if (0 == m_items.Count) 136 m_items.LockItemsForWrite(false);
132 return; 137 return;
138 }
133 139
134 IList<TaskInventoryItem> items = GetInventoryItems(); 140 IList<TaskInventoryItem> items = new List<TaskInventoryItem>(Items.Values);
135 m_items.Clear(); 141 Items.Clear();
136 142
137 foreach (TaskInventoryItem item in items) 143 foreach (TaskInventoryItem item in items)
138 { 144 {
139 item.ResetIDs(m_part.UUID); 145 item.ResetIDs(m_part.UUID);
140 m_items.Add(item.ItemID, item); 146 Items.Add(item.ItemID, item);
141 }
142 } 147 }
148 m_items.LockItemsForWrite(false);
143 } 149 }
144 150
145 public void ResetObjectID() 151 public void ResetObjectID()
146 { 152 {
147 lock (Items) 153 m_items.LockItemsForWrite(true);
154
155 if (Items.Count == 0)
148 { 156 {
149 IList<TaskInventoryItem> items = new List<TaskInventoryItem>(Items.Values); 157 m_items.LockItemsForWrite(false);
150 Items.Clear(); 158 return;
151
152 foreach (TaskInventoryItem item in items)
153 {
154 item.ParentPartID = m_part.UUID;
155 item.ParentID = m_part.UUID;
156 Items.Add(item.ItemID, item);
157 }
158 } 159 }
160
161 IList<TaskInventoryItem> items = new List<TaskInventoryItem>(Items.Values);
162 Items.Clear();
163
164 foreach (TaskInventoryItem item in items)
165 {
166 item.ParentPartID = m_part.UUID;
167 item.ParentID = m_part.UUID;
168 Items.Add(item.ItemID, item);
169 }
170 m_items.LockItemsForWrite(false);
159 } 171 }
160 172
161 /// <summary> 173 /// <summary>
@@ -164,17 +176,14 @@ namespace OpenSim.Region.Framework.Scenes
164 /// <param name="ownerId"></param> 176 /// <param name="ownerId"></param>
165 public void ChangeInventoryOwner(UUID ownerId) 177 public void ChangeInventoryOwner(UUID ownerId)
166 { 178 {
167 lock (Items) 179 List<TaskInventoryItem> items = GetInventoryItems();
168 { 180
169 if (0 == Items.Count) 181 if (items.Count == 0)
170 { 182 return;
171 return;
172 }
173 }
174 183
184 m_items.LockItemsForWrite(true);
175 HasInventoryChanged = true; 185 HasInventoryChanged = true;
176 m_part.ParentGroup.HasGroupChanged = true; 186 m_part.ParentGroup.HasGroupChanged = true;
177 List<TaskInventoryItem> items = GetInventoryItems();
178 foreach (TaskInventoryItem item in items) 187 foreach (TaskInventoryItem item in items)
179 { 188 {
180 if (ownerId != item.OwnerID) 189 if (ownerId != item.OwnerID)
@@ -185,6 +194,7 @@ namespace OpenSim.Region.Framework.Scenes
185 item.PermsGranter = UUID.Zero; 194 item.PermsGranter = UUID.Zero;
186 item.OwnerChanged = true; 195 item.OwnerChanged = true;
187 } 196 }
197 m_items.LockItemsForWrite(false);
188 } 198 }
189 199
190 /// <summary> 200 /// <summary>
@@ -193,12 +203,11 @@ namespace OpenSim.Region.Framework.Scenes
193 /// <param name="groupID"></param> 203 /// <param name="groupID"></param>
194 public void ChangeInventoryGroup(UUID groupID) 204 public void ChangeInventoryGroup(UUID groupID)
195 { 205 {
196 lock (Items) 206 m_items.LockItemsForWrite(true);
207 if (0 == Items.Count)
197 { 208 {
198 if (0 == Items.Count) 209 m_items.LockItemsForWrite(false);
199 { 210 return;
200 return;
201 }
202 } 211 }
203 212
204 // Don't let this set the HasGroupChanged flag for attachments 213 // Don't let this set the HasGroupChanged flag for attachments
@@ -210,12 +219,15 @@ namespace OpenSim.Region.Framework.Scenes
210 m_part.ParentGroup.HasGroupChanged = true; 219 m_part.ParentGroup.HasGroupChanged = true;
211 } 220 }
212 221
213 List<TaskInventoryItem> items = GetInventoryItems(); 222 IList<TaskInventoryItem> items = new List<TaskInventoryItem>(Items.Values);
214 foreach (TaskInventoryItem item in items) 223 foreach (TaskInventoryItem item in items)
215 { 224 {
216 if (groupID != item.GroupID) 225 if (groupID != item.GroupID)
226 {
217 item.GroupID = groupID; 227 item.GroupID = groupID;
228 }
218 } 229 }
230 m_items.LockItemsForWrite(false);
219 } 231 }
220 232
221 private void QueryScriptStates() 233 private void QueryScriptStates()
@@ -227,25 +239,25 @@ namespace OpenSim.Region.Framework.Scenes
227 if (engines == null) // No engine at all 239 if (engines == null) // No engine at all
228 return; 240 return;
229 241
230 lock (Items) 242 Items.LockItemsForRead(true);
243 foreach (TaskInventoryItem item in Items.Values)
231 { 244 {
232 foreach (TaskInventoryItem item in Items.Values) 245 if (item.InvType == (int)InventoryType.LSL)
233 { 246 {
234 if (item.InvType == (int)InventoryType.LSL) 247 foreach (IScriptModule e in engines)
235 { 248 {
236 foreach (IScriptModule e in engines) 249 bool running;
237 {
238 bool running;
239 250
240 if (e.HasScript(item.ItemID, out running)) 251 if (e.HasScript(item.ItemID, out running))
241 { 252 {
242 item.ScriptRunning = running; 253 item.ScriptRunning = running;
243 break; 254 break;
244 }
245 } 255 }
246 } 256 }
247 } 257 }
248 } 258 }
259
260 Items.LockItemsForRead(false);
249 } 261 }
250 262
251 public int CreateScriptInstances(int startParam, bool postOnRez, string engine, int stateSource) 263 public int CreateScriptInstances(int startParam, bool postOnRez, string engine, int stateSource)
@@ -290,7 +302,10 @@ namespace OpenSim.Region.Framework.Scenes
290 { 302 {
291 List<TaskInventoryItem> scripts = GetInventoryItems(InventoryType.LSL); 303 List<TaskInventoryItem> scripts = GetInventoryItems(InventoryType.LSL);
292 foreach (TaskInventoryItem item in scripts) 304 foreach (TaskInventoryItem item in scripts)
305 {
293 RemoveScriptInstance(item.ItemID, sceneObjectBeingDeleted); 306 RemoveScriptInstance(item.ItemID, sceneObjectBeingDeleted);
307 m_part.RemoveScriptEvents(item.ItemID);
308 }
294 } 309 }
295 310
296 /// <summary> 311 /// <summary>
@@ -312,7 +327,10 @@ namespace OpenSim.Region.Framework.Scenes
312// item.Name, item.ItemID, m_part.Name, m_part.UUID, m_part.ParentGroup.Scene.RegionInfo.RegionName); 327// item.Name, item.ItemID, m_part.Name, m_part.UUID, m_part.ParentGroup.Scene.RegionInfo.RegionName);
313 328
314 if (!m_part.ParentGroup.Scene.Permissions.CanRunScript(item.ItemID, m_part.UUID, item.OwnerID)) 329 if (!m_part.ParentGroup.Scene.Permissions.CanRunScript(item.ItemID, m_part.UUID, item.OwnerID))
330 {
331 StoreScriptError(item.ItemID, "no permission");
315 return false; 332 return false;
333 }
316 334
317 m_part.AddFlag(PrimFlags.Scripted); 335 m_part.AddFlag(PrimFlags.Scripted);
318 336
@@ -322,14 +340,13 @@ namespace OpenSim.Region.Framework.Scenes
322 if (stateSource == 2 && // Prim crossing 340 if (stateSource == 2 && // Prim crossing
323 m_part.ParentGroup.Scene.m_trustBinaries) 341 m_part.ParentGroup.Scene.m_trustBinaries)
324 { 342 {
325 lock (m_items) 343 m_items.LockItemsForWrite(true);
326 { 344 m_items[item.ItemID].PermsMask = 0;
327 m_items[item.ItemID].PermsMask = 0; 345 m_items[item.ItemID].PermsGranter = UUID.Zero;
328 m_items[item.ItemID].PermsGranter = UUID.Zero; 346 m_items.LockItemsForWrite(false);
329 }
330
331 m_part.ParentGroup.Scene.EventManager.TriggerRezScript( 347 m_part.ParentGroup.Scene.EventManager.TriggerRezScript(
332 m_part.LocalId, item.ItemID, String.Empty, startParam, postOnRez, engine, stateSource); 348 m_part.LocalId, item.ItemID, String.Empty, startParam, postOnRez, engine, stateSource);
349 StoreScriptErrors(item.ItemID, null);
333 m_part.ParentGroup.AddActiveScriptCount(1); 350 m_part.ParentGroup.AddActiveScriptCount(1);
334 m_part.ScheduleFullUpdate(); 351 m_part.ScheduleFullUpdate();
335 return true; 352 return true;
@@ -338,6 +355,8 @@ namespace OpenSim.Region.Framework.Scenes
338 AssetBase asset = m_part.ParentGroup.Scene.AssetService.Get(item.AssetID.ToString()); 355 AssetBase asset = m_part.ParentGroup.Scene.AssetService.Get(item.AssetID.ToString());
339 if (null == asset) 356 if (null == asset)
340 { 357 {
358 string msg = String.Format("asset ID {0} could not be found", item.AssetID);
359 StoreScriptError(item.ItemID, msg);
341 m_log.ErrorFormat( 360 m_log.ErrorFormat(
342 "[PRIM INVENTORY]: Couldn't start script {0}, {1} at {2} in {3} since asset ID {4} could not be found", 361 "[PRIM INVENTORY]: Couldn't start script {0}, {1} at {2} in {3} since asset ID {4} could not be found",
343 item.Name, item.ItemID, m_part.AbsolutePosition, 362 item.Name, item.ItemID, m_part.AbsolutePosition,
@@ -350,16 +369,18 @@ namespace OpenSim.Region.Framework.Scenes
350 if (m_part.ParentGroup.m_savedScriptState != null) 369 if (m_part.ParentGroup.m_savedScriptState != null)
351 item.OldItemID = RestoreSavedScriptState(item.LoadedItemID, item.OldItemID, item.ItemID); 370 item.OldItemID = RestoreSavedScriptState(item.LoadedItemID, item.OldItemID, item.ItemID);
352 371
353 lock (m_items) 372 m_items.LockItemsForWrite(true);
354 {
355 m_items[item.ItemID].OldItemID = item.OldItemID;
356 m_items[item.ItemID].PermsMask = 0;
357 m_items[item.ItemID].PermsGranter = UUID.Zero;
358 }
359 373
374 m_items[item.ItemID].OldItemID = item.OldItemID;
375 m_items[item.ItemID].PermsMask = 0;
376 m_items[item.ItemID].PermsGranter = UUID.Zero;
377
378 m_items.LockItemsForWrite(false);
379
360 string script = Utils.BytesToString(asset.Data); 380 string script = Utils.BytesToString(asset.Data);
361 m_part.ParentGroup.Scene.EventManager.TriggerRezScript( 381 m_part.ParentGroup.Scene.EventManager.TriggerRezScript(
362 m_part.LocalId, item.ItemID, script, startParam, postOnRez, engine, stateSource); 382 m_part.LocalId, item.ItemID, script, startParam, postOnRez, engine, stateSource);
383 StoreScriptErrors(item.ItemID, null);
363 if (!item.ScriptRunning) 384 if (!item.ScriptRunning)
364 m_part.ParentGroup.Scene.EventManager.TriggerStopScript( 385 m_part.ParentGroup.Scene.EventManager.TriggerStopScript(
365 m_part.LocalId, item.ItemID); 386 m_part.LocalId, item.ItemID);
@@ -432,24 +453,151 @@ namespace OpenSim.Region.Framework.Scenes
432 return stateID; 453 return stateID;
433 } 454 }
434 455
456 /// <summary>
457 /// Start a script which is in this prim's inventory.
458 /// Some processing may occur in the background, but this routine returns asap.
459 /// </summary>
460 /// <param name="itemId">
461 /// A <see cref="UUID"/>
462 /// </param>
435 public bool CreateScriptInstance(UUID itemId, int startParam, bool postOnRez, string engine, int stateSource) 463 public bool CreateScriptInstance(UUID itemId, int startParam, bool postOnRez, string engine, int stateSource)
436 { 464 {
437 TaskInventoryItem item = GetInventoryItem(itemId); 465 lock (m_scriptErrors)
438 if (item != null) 466 {
467 // Indicate to CreateScriptInstanceInternal() we don't want it to wait for completion
468 m_scriptErrors.Remove(itemId);
469 }
470 CreateScriptInstanceInternal(itemId, startParam, postOnRez, engine, stateSource);
471 return true;
472 }
473
474 private void CreateScriptInstanceInternal(UUID itemId, int startParam, bool postOnRez, string engine, int stateSource)
475 {
476 m_items.LockItemsForRead(true);
477 if (m_items.ContainsKey(itemId))
439 { 478 {
440 return CreateScriptInstance(item, startParam, postOnRez, engine, stateSource); 479 if (m_items.ContainsKey(itemId))
480 {
481 m_items.LockItemsForRead(false);
482 CreateScriptInstance(m_items[itemId], startParam, postOnRez, engine, stateSource);
483 }
484 else
485 {
486 m_items.LockItemsForRead(false);
487 string msg = String.Format("couldn't be found for prim {0}, {1} at {2} in {3}", m_part.Name, m_part.UUID,
488 m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
489 StoreScriptError(itemId, msg);
490 m_log.ErrorFormat(
491 "[PRIM INVENTORY]: " +
492 "Couldn't start script with ID {0} since it {1}", itemId, msg);
493 }
441 } 494 }
442 else 495 else
443 { 496 {
497 m_items.LockItemsForRead(false);
498 string msg = String.Format("couldn't be found for prim {0}, {1}", m_part.Name, m_part.UUID);
499 StoreScriptError(itemId, msg);
444 m_log.ErrorFormat( 500 m_log.ErrorFormat(
445 "[PRIM INVENTORY]: Couldn't start script with ID {0} since it couldn't be found for prim {1}, {2} at {3} in {4}", 501 "[PRIM INVENTORY]: Couldn't start script with ID {0} since it couldn't be found for prim {1}, {2} at {3} in {4}",
446 itemId, m_part.Name, m_part.UUID, 502 itemId, m_part.Name, m_part.UUID,
447 m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName); 503 m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
504 }
505
506 }
448 507
449 return false; 508 /// <summary>
509 /// Start a script which is in this prim's inventory and return any compilation error messages.
510 /// </summary>
511 /// <param name="itemId">
512 /// A <see cref="UUID"/>
513 /// </param>
514 public ArrayList CreateScriptInstanceEr(UUID itemId, int startParam, bool postOnRez, string engine, int stateSource)
515 {
516 ArrayList errors;
517
518 // Indicate to CreateScriptInstanceInternal() we want it to
519 // post any compilation/loading error messages
520 lock (m_scriptErrors)
521 {
522 m_scriptErrors[itemId] = null;
523 }
524
525 // Perform compilation/loading
526 CreateScriptInstanceInternal(itemId, startParam, postOnRez, engine, stateSource);
527
528 // Wait for and retrieve any errors
529 lock (m_scriptErrors)
530 {
531 while ((errors = m_scriptErrors[itemId]) == null)
532 {
533 if (!System.Threading.Monitor.Wait(m_scriptErrors, 15000))
534 {
535 m_log.ErrorFormat(
536 "[PRIM INVENTORY]: " +
537 "timedout waiting for script {0} errors", itemId);
538 errors = m_scriptErrors[itemId];
539 if (errors == null)
540 {
541 errors = new ArrayList(1);
542 errors.Add("timedout waiting for errors");
543 }
544 break;
545 }
546 }
547 m_scriptErrors.Remove(itemId);
548 }
549 return errors;
550 }
551
552 // Signal to CreateScriptInstanceEr() that compilation/loading is complete
553 private void StoreScriptErrors(UUID itemId, ArrayList errors)
554 {
555 lock (m_scriptErrors)
556 {
557 // If compilation/loading initiated via CreateScriptInstance(),
558 // it does not want the errors, so just get out
559 if (!m_scriptErrors.ContainsKey(itemId))
560 {
561 return;
562 }
563
564 // Initiated via CreateScriptInstanceEr(), if we know what the
565 // errors are, save them and wake CreateScriptInstanceEr().
566 if (errors != null)
567 {
568 m_scriptErrors[itemId] = errors;
569 System.Threading.Monitor.PulseAll(m_scriptErrors);
570 return;
571 }
572 }
573
574 // Initiated via CreateScriptInstanceEr() but we don't know what
575 // the errors are yet, so retrieve them from the script engine.
576 // This may involve some waiting internal to GetScriptErrors().
577 errors = GetScriptErrors(itemId);
578
579 // Get a default non-null value to indicate success.
580 if (errors == null)
581 {
582 errors = new ArrayList();
583 }
584
585 // Post to CreateScriptInstanceEr() and wake it up
586 lock (m_scriptErrors)
587 {
588 m_scriptErrors[itemId] = errors;
589 System.Threading.Monitor.PulseAll(m_scriptErrors);
450 } 590 }
451 } 591 }
452 592
593 // Like StoreScriptErrors(), but just posts a single string message
594 private void StoreScriptError(UUID itemId, string message)
595 {
596 ArrayList errors = new ArrayList(1);
597 errors.Add(message);
598 StoreScriptErrors(itemId, errors);
599 }
600
453 /// <summary> 601 /// <summary>
454 /// Stop and remove a script which is in this prim's inventory. 602 /// Stop and remove a script which is in this prim's inventory.
455 /// </summary> 603 /// </summary>
@@ -460,15 +608,7 @@ namespace OpenSim.Region.Framework.Scenes
460 /// </param> 608 /// </param>
461 public void RemoveScriptInstance(UUID itemId, bool sceneObjectBeingDeleted) 609 public void RemoveScriptInstance(UUID itemId, bool sceneObjectBeingDeleted)
462 { 610 {
463 bool scriptPresent = false; 611 if (m_items.ContainsKey(itemId))
464
465 lock (m_items)
466 {
467 if (m_items.ContainsKey(itemId))
468 scriptPresent = true;
469 }
470
471 if (scriptPresent)
472 { 612 {
473 if (!sceneObjectBeingDeleted) 613 if (!sceneObjectBeingDeleted)
474 m_part.RemoveScriptEvents(itemId); 614 m_part.RemoveScriptEvents(itemId);
@@ -538,14 +678,16 @@ namespace OpenSim.Region.Framework.Scenes
538 /// <returns></returns> 678 /// <returns></returns>
539 private bool InventoryContainsName(string name) 679 private bool InventoryContainsName(string name)
540 { 680 {
541 lock (m_items) 681 m_items.LockItemsForRead(true);
682 foreach (TaskInventoryItem item in m_items.Values)
542 { 683 {
543 foreach (TaskInventoryItem item in m_items.Values) 684 if (item.Name == name)
544 { 685 {
545 if (item.Name == name) 686 m_items.LockItemsForRead(false);
546 return true; 687 return true;
547 } 688 }
548 } 689 }
690 m_items.LockItemsForRead(false);
549 return false; 691 return false;
550 } 692 }
551 693
@@ -587,8 +729,9 @@ namespace OpenSim.Region.Framework.Scenes
587 /// <param name="item"></param> 729 /// <param name="item"></param>
588 public void AddInventoryItemExclusive(TaskInventoryItem item, bool allowedDrop) 730 public void AddInventoryItemExclusive(TaskInventoryItem item, bool allowedDrop)
589 { 731 {
590 List<TaskInventoryItem> il = GetInventoryItems(); 732 m_items.LockItemsForRead(true);
591 733 List<TaskInventoryItem> il = new List<TaskInventoryItem>(m_items.Values);
734 m_items.LockItemsForRead(false);
592 foreach (TaskInventoryItem i in il) 735 foreach (TaskInventoryItem i in il)
593 { 736 {
594 if (i.Name == item.Name) 737 if (i.Name == item.Name)
@@ -626,14 +769,14 @@ namespace OpenSim.Region.Framework.Scenes
626 item.Name = name; 769 item.Name = name;
627 item.GroupID = m_part.GroupID; 770 item.GroupID = m_part.GroupID;
628 771
629 lock (m_items) 772 m_items.LockItemsForWrite(true);
630 m_items.Add(item.ItemID, item); 773 m_items.Add(item.ItemID, item);
631 774 m_items.LockItemsForWrite(false);
632 if (allowedDrop) 775 if (allowedDrop)
633 m_part.TriggerScriptChangedEvent(Changed.ALLOWED_DROP); 776 m_part.TriggerScriptChangedEvent(Changed.ALLOWED_DROP);
634 else 777 else
635 m_part.TriggerScriptChangedEvent(Changed.INVENTORY); 778 m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
636 779
637 m_inventorySerial++; 780 m_inventorySerial++;
638 //m_inventorySerial += 2; 781 //m_inventorySerial += 2;
639 HasInventoryChanged = true; 782 HasInventoryChanged = true;
@@ -649,15 +792,15 @@ namespace OpenSim.Region.Framework.Scenes
649 /// <param name="items"></param> 792 /// <param name="items"></param>
650 public void RestoreInventoryItems(ICollection<TaskInventoryItem> items) 793 public void RestoreInventoryItems(ICollection<TaskInventoryItem> items)
651 { 794 {
652 lock (m_items) 795 m_items.LockItemsForWrite(true);
796 foreach (TaskInventoryItem item in items)
653 { 797 {
654 foreach (TaskInventoryItem item in items) 798 m_items.Add(item.ItemID, item);
655 { 799// m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
656 m_items.Add(item.ItemID, item);
657// m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
658 }
659 m_inventorySerial++;
660 } 800 }
801 m_items.LockItemsForWrite(false);
802
803 m_inventorySerial++;
661 } 804 }
662 805
663 /// <summary> 806 /// <summary>
@@ -668,23 +811,24 @@ namespace OpenSim.Region.Framework.Scenes
668 public TaskInventoryItem GetInventoryItem(UUID itemId) 811 public TaskInventoryItem GetInventoryItem(UUID itemId)
669 { 812 {
670 TaskInventoryItem item; 813 TaskInventoryItem item;
671 814 m_items.LockItemsForRead(true);
672 lock (m_items) 815 m_items.TryGetValue(itemId, out item);
673 m_items.TryGetValue(itemId, out item); 816 m_items.LockItemsForRead(false);
674
675 return item; 817 return item;
676 } 818 }
677 819
678 public TaskInventoryItem GetInventoryItem(string name) 820 public TaskInventoryItem GetInventoryItem(string name)
679 { 821 {
680 lock (m_items) 822 m_items.LockItemsForRead(true);
823 foreach (TaskInventoryItem item in m_items.Values)
681 { 824 {
682 foreach (TaskInventoryItem item in m_items.Values) 825 if (item.Name == name)
683 { 826 {
684 if (item.Name == name) 827 m_items.LockItemsForRead(false);
685 return item; 828 return item;
686 } 829 }
687 } 830 }
831 m_items.LockItemsForRead(false);
688 832
689 return null; 833 return null;
690 } 834 }
@@ -693,15 +837,16 @@ namespace OpenSim.Region.Framework.Scenes
693 { 837 {
694 List<TaskInventoryItem> items = new List<TaskInventoryItem>(); 838 List<TaskInventoryItem> items = new List<TaskInventoryItem>();
695 839
696 lock (m_items) 840 m_items.LockItemsForRead(true);
841
842 foreach (TaskInventoryItem item in m_items.Values)
697 { 843 {
698 foreach (TaskInventoryItem item in m_items.Values) 844 if (item.Name == name)
699 { 845 items.Add(item);
700 if (item.Name == name)
701 items.Add(item);
702 }
703 } 846 }
704 847
848 m_items.LockItemsForRead(false);
849
705 return items; 850 return items;
706 } 851 }
707 852
@@ -720,6 +865,10 @@ namespace OpenSim.Region.Framework.Scenes
720 string xmlData = Utils.BytesToString(rezAsset.Data); 865 string xmlData = Utils.BytesToString(rezAsset.Data);
721 SceneObjectGroup group = SceneObjectSerializer.FromOriginalXmlFormat(xmlData); 866 SceneObjectGroup group = SceneObjectSerializer.FromOriginalXmlFormat(xmlData);
722 867
868 group.RootPart.AttachPoint = group.RootPart.Shape.State;
869 group.RootPart.AttachOffset = group.AbsolutePosition;
870 group.RootPart.AttachRotation = group.GroupRotation;
871
723 group.ResetIDs(); 872 group.ResetIDs();
724 873
725 SceneObjectPart rootPart = group.GetPart(group.UUID); 874 SceneObjectPart rootPart = group.GetPart(group.UUID);
@@ -794,8 +943,9 @@ namespace OpenSim.Region.Framework.Scenes
794 943
795 public bool UpdateInventoryItem(TaskInventoryItem item, bool fireScriptEvents, bool considerChanged) 944 public bool UpdateInventoryItem(TaskInventoryItem item, bool fireScriptEvents, bool considerChanged)
796 { 945 {
797 TaskInventoryItem it = GetInventoryItem(item.ItemID); 946 m_items.LockItemsForWrite(true);
798 if (it != null) 947
948 if (m_items.ContainsKey(item.ItemID))
799 { 949 {
800// m_log.DebugFormat("[PRIM INVENTORY]: Updating item {0} in {1}", item.Name, m_part.Name); 950// m_log.DebugFormat("[PRIM INVENTORY]: Updating item {0} in {1}", item.Name, m_part.Name);
801 951
@@ -808,14 +958,10 @@ namespace OpenSim.Region.Framework.Scenes
808 item.GroupID = m_part.GroupID; 958 item.GroupID = m_part.GroupID;
809 959
810 if (item.AssetID == UUID.Zero) 960 if (item.AssetID == UUID.Zero)
811 item.AssetID = it.AssetID; 961 item.AssetID = m_items[item.ItemID].AssetID;
812 962
813 lock (m_items) 963 m_items[item.ItemID] = item;
814 { 964 m_inventorySerial++;
815 m_items[item.ItemID] = item;
816 m_inventorySerial++;
817 }
818
819 if (fireScriptEvents) 965 if (fireScriptEvents)
820 m_part.TriggerScriptChangedEvent(Changed.INVENTORY); 966 m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
821 967
@@ -824,7 +970,7 @@ namespace OpenSim.Region.Framework.Scenes
824 HasInventoryChanged = true; 970 HasInventoryChanged = true;
825 m_part.ParentGroup.HasGroupChanged = true; 971 m_part.ParentGroup.HasGroupChanged = true;
826 } 972 }
827 973 m_items.LockItemsForWrite(false);
828 return true; 974 return true;
829 } 975 }
830 else 976 else
@@ -835,8 +981,9 @@ namespace OpenSim.Region.Framework.Scenes
835 item.ItemID, m_part.Name, m_part.UUID, 981 item.ItemID, m_part.Name, m_part.UUID,
836 m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName); 982 m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
837 } 983 }
838 return false; 984 m_items.LockItemsForWrite(false);
839 985
986 return false;
840 } 987 }
841 988
842 /// <summary> 989 /// <summary>
@@ -847,43 +994,59 @@ namespace OpenSim.Region.Framework.Scenes
847 /// in this prim's inventory.</returns> 994 /// in this prim's inventory.</returns>
848 public int RemoveInventoryItem(UUID itemID) 995 public int RemoveInventoryItem(UUID itemID)
849 { 996 {
850 TaskInventoryItem item = GetInventoryItem(itemID); 997 m_items.LockItemsForRead(true);
851 if (item != null) 998
999 if (m_items.ContainsKey(itemID))
852 { 1000 {
853 int type = m_items[itemID].InvType; 1001 int type = m_items[itemID].InvType;
1002 m_items.LockItemsForRead(false);
854 if (type == 10) // Script 1003 if (type == 10) // Script
855 { 1004 {
856 m_part.RemoveScriptEvents(itemID);
857 m_part.ParentGroup.Scene.EventManager.TriggerRemoveScript(m_part.LocalId, itemID); 1005 m_part.ParentGroup.Scene.EventManager.TriggerRemoveScript(m_part.LocalId, itemID);
858 } 1006 }
1007 m_items.LockItemsForWrite(true);
859 m_items.Remove(itemID); 1008 m_items.Remove(itemID);
1009 m_items.LockItemsForWrite(false);
860 m_inventorySerial++; 1010 m_inventorySerial++;
861 m_part.TriggerScriptChangedEvent(Changed.INVENTORY); 1011 m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
862 1012
863 HasInventoryChanged = true; 1013 HasInventoryChanged = true;
864 m_part.ParentGroup.HasGroupChanged = true; 1014 m_part.ParentGroup.HasGroupChanged = true;
865 1015
866 if (!ContainsScripts()) 1016 int scriptcount = 0;
1017 m_items.LockItemsForRead(true);
1018 foreach (TaskInventoryItem item in m_items.Values)
1019 {
1020 if (item.Type == 10)
1021 {
1022 scriptcount++;
1023 }
1024 }
1025 m_items.LockItemsForRead(false);
1026
1027
1028 if (scriptcount <= 0)
1029 {
867 m_part.RemFlag(PrimFlags.Scripted); 1030 m_part.RemFlag(PrimFlags.Scripted);
1031 }
868 1032
869 m_part.ScheduleFullUpdate(); 1033 m_part.ScheduleFullUpdate();
870 1034
871 return type; 1035 return type;
872
873 } 1036 }
874 else 1037 else
875 { 1038 {
1039 m_items.LockItemsForRead(false);
876 m_log.ErrorFormat( 1040 m_log.ErrorFormat(
877 "[PRIM INVENTORY]: " + 1041 "[PRIM INVENTORY]: " +
878 "Tried to remove item ID {0} from prim {1}, {2} at {3} in {4} but the item does not exist in this inventory", 1042 "Tried to remove item ID {0} from prim {1}, {2} but the item does not exist in this inventory",
879 itemID, m_part.Name, m_part.UUID, 1043 itemID, m_part.Name, m_part.UUID);
880 m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
881 } 1044 }
882 1045
883 return -1; 1046 return -1;
884 } 1047 }
885 1048
886 private bool CreateInventoryFile() 1049 private bool CreateInventoryFileName()
887 { 1050 {
888// m_log.DebugFormat( 1051// m_log.DebugFormat(
889// "[PRIM INVENTORY]: Creating inventory file for {0} {1} {2}, serial {3}", 1052// "[PRIM INVENTORY]: Creating inventory file for {0} {1} {2}, serial {3}",
@@ -892,70 +1055,12 @@ namespace OpenSim.Region.Framework.Scenes
892 if (m_inventoryFileName == String.Empty || 1055 if (m_inventoryFileName == String.Empty ||
893 m_inventoryFileNameSerial < m_inventorySerial) 1056 m_inventoryFileNameSerial < m_inventorySerial)
894 { 1057 {
895 // Something changed, we need to create a new file
896 m_inventoryFileName = "inventory_" + UUID.Random().ToString() + ".tmp"; 1058 m_inventoryFileName = "inventory_" + UUID.Random().ToString() + ".tmp";
897 m_inventoryFileNameSerial = m_inventorySerial; 1059 m_inventoryFileNameSerial = m_inventorySerial;
898 1060
899 InventoryStringBuilder invString = new InventoryStringBuilder(m_part.UUID, UUID.Zero);
900
901 lock (m_items)
902 {
903 foreach (TaskInventoryItem item in m_items.Values)
904 {
905// m_log.DebugFormat(
906// "[PRIM INVENTORY]: Adding item {0} {1} for serial {2} on prim {3} {4} {5}",
907// item.Name, item.ItemID, m_inventorySerial, m_part.Name, m_part.UUID, m_part.LocalId);
908
909 UUID ownerID = item.OwnerID;
910 uint everyoneMask = 0;
911 uint baseMask = item.BasePermissions;
912 uint ownerMask = item.CurrentPermissions;
913 uint groupMask = item.GroupPermissions;
914
915 invString.AddItemStart();
916 invString.AddNameValueLine("item_id", item.ItemID.ToString());
917 invString.AddNameValueLine("parent_id", m_part.UUID.ToString());
918
919 invString.AddPermissionsStart();
920
921 invString.AddNameValueLine("base_mask", Utils.UIntToHexString(baseMask));
922 invString.AddNameValueLine("owner_mask", Utils.UIntToHexString(ownerMask));
923 invString.AddNameValueLine("group_mask", Utils.UIntToHexString(groupMask));
924 invString.AddNameValueLine("everyone_mask", Utils.UIntToHexString(everyoneMask));
925 invString.AddNameValueLine("next_owner_mask", Utils.UIntToHexString(item.NextPermissions));
926
927 invString.AddNameValueLine("creator_id", item.CreatorID.ToString());
928 invString.AddNameValueLine("owner_id", ownerID.ToString());
929
930 invString.AddNameValueLine("last_owner_id", item.LastOwnerID.ToString());
931
932 invString.AddNameValueLine("group_id", item.GroupID.ToString());
933 invString.AddSectionEnd();
934
935 invString.AddNameValueLine("asset_id", item.AssetID.ToString());
936 invString.AddNameValueLine("type", Utils.AssetTypeToString((AssetType)item.Type));
937 invString.AddNameValueLine("inv_type", Utils.InventoryTypeToString((InventoryType)item.InvType));
938 invString.AddNameValueLine("flags", Utils.UIntToHexString(item.Flags));
939
940 invString.AddSaleStart();
941 invString.AddNameValueLine("sale_type", "not");
942 invString.AddNameValueLine("sale_price", "0");
943 invString.AddSectionEnd();
944
945 invString.AddNameValueLine("name", item.Name + "|");
946 invString.AddNameValueLine("desc", item.Description + "|");
947
948 invString.AddNameValueLine("creation_date", item.CreationDate.ToString());
949 invString.AddSectionEnd();
950 }
951 }
952
953 m_inventoryFileData = Utils.StringToBytes(invString.BuildString);
954
955 return true; 1061 return true;
956 } 1062 }
957 1063
958 // No need to recreate, the existing file is fine
959 return false; 1064 return false;
960 } 1065 }
961 1066
@@ -965,43 +1070,110 @@ namespace OpenSim.Region.Framework.Scenes
965 /// <param name="xferManager"></param> 1070 /// <param name="xferManager"></param>
966 public void RequestInventoryFile(IClientAPI client, IXfer xferManager) 1071 public void RequestInventoryFile(IClientAPI client, IXfer xferManager)
967 { 1072 {
968 lock (m_items) 1073 bool changed = CreateInventoryFileName();
969 {
970 // Don't send a inventory xfer name if there are no items. Doing so causes viewer 3 to crash when rezzing
971 // a new script if any previous deletion has left the prim inventory empty.
972 if (m_items.Count == 0) // No inventory
973 {
974// m_log.DebugFormat(
975// "[PRIM INVENTORY]: Not sending inventory data for part {0} {1} {2} for {3} since no items",
976// m_part.Name, m_part.LocalId, m_part.UUID, client.Name);
977 1074
978 client.SendTaskInventory(m_part.UUID, 0, new byte[0]); 1075 bool includeAssets = false;
979 return; 1076 if (m_part.ParentGroup.Scene.Permissions.CanEditObjectInventory(m_part.UUID, client.AgentId))
980 } 1077 includeAssets = true;
1078
1079 if (m_inventoryPrivileged != includeAssets)
1080 changed = true;
981 1081
982 CreateInventoryFile(); 1082 InventoryStringBuilder invString = new InventoryStringBuilder(m_part.UUID, UUID.Zero);
1083
1084 Items.LockItemsForRead(true);
1085
1086 if (m_inventorySerial == 0) // No inventory
1087 {
1088 client.SendTaskInventory(m_part.UUID, 0, new byte[0]);
1089 Items.LockItemsForRead(false);
1090 return;
1091 }
1092
1093 if (m_items.Count == 0) // No inventory
1094 {
1095 client.SendTaskInventory(m_part.UUID, 0, new byte[0]);
1096 Items.LockItemsForRead(false);
1097 return;
1098 }
983 1099
984 // In principle, we should only do the rest if the inventory changed; 1100 if (!changed)
985 // by sending m_inventorySerial to the client, it ought to know 1101 {
986 // that nothing changed and that it doesn't need to request the file.
987 // Unfortunately, it doesn't look like the client optimizes this;
988 // the client seems to always come back and request the Xfer,
989 // no matter what value m_inventorySerial has.
990 // FIXME: Could probably be > 0 here rather than > 2
991 if (m_inventoryFileData.Length > 2) 1102 if (m_inventoryFileData.Length > 2)
992 { 1103 {
993 // Add the file for Xfer 1104 xferManager.AddNewFile(m_inventoryFileName,
994 // m_log.DebugFormat( 1105 m_inventoryFileData);
995 // "[PRIM INVENTORY]: Adding inventory file {0} (length {1}) for transfer on {2} {3} {4}", 1106 client.SendTaskInventory(m_part.UUID, (short)m_inventorySerial,
996 // m_inventoryFileName, m_inventoryFileData.Length, m_part.Name, m_part.UUID, m_part.LocalId); 1107 Util.StringToBytes256(m_inventoryFileName));
997 1108
998 xferManager.AddNewFile(m_inventoryFileName, m_inventoryFileData); 1109 Items.LockItemsForRead(false);
1110 return;
999 } 1111 }
1000
1001 // Tell the client we're ready to Xfer the file
1002 client.SendTaskInventory(m_part.UUID, (short)m_inventorySerial,
1003 Util.StringToBytes256(m_inventoryFileName));
1004 } 1112 }
1113
1114 m_inventoryPrivileged = includeAssets;
1115
1116 foreach (TaskInventoryItem item in m_items.Values)
1117 {
1118 UUID ownerID = item.OwnerID;
1119 uint everyoneMask = 0;
1120 uint baseMask = item.BasePermissions;
1121 uint ownerMask = item.CurrentPermissions;
1122 uint groupMask = item.GroupPermissions;
1123
1124 invString.AddItemStart();
1125 invString.AddNameValueLine("item_id", item.ItemID.ToString());
1126 invString.AddNameValueLine("parent_id", m_part.UUID.ToString());
1127
1128 invString.AddPermissionsStart();
1129
1130 invString.AddNameValueLine("base_mask", Utils.UIntToHexString(baseMask));
1131 invString.AddNameValueLine("owner_mask", Utils.UIntToHexString(ownerMask));
1132 invString.AddNameValueLine("group_mask", Utils.UIntToHexString(groupMask));
1133 invString.AddNameValueLine("everyone_mask", Utils.UIntToHexString(everyoneMask));
1134 invString.AddNameValueLine("next_owner_mask", Utils.UIntToHexString(item.NextPermissions));
1135
1136 invString.AddNameValueLine("creator_id", item.CreatorID.ToString());
1137 invString.AddNameValueLine("owner_id", ownerID.ToString());
1138
1139 invString.AddNameValueLine("last_owner_id", item.LastOwnerID.ToString());
1140
1141 invString.AddNameValueLine("group_id", item.GroupID.ToString());
1142 invString.AddSectionEnd();
1143
1144 if (includeAssets)
1145 invString.AddNameValueLine("asset_id", item.AssetID.ToString());
1146 else
1147 invString.AddNameValueLine("asset_id", UUID.Zero.ToString());
1148 invString.AddNameValueLine("type", Utils.AssetTypeToString((AssetType)item.Type));
1149 invString.AddNameValueLine("inv_type", Utils.InventoryTypeToString((InventoryType)item.InvType));
1150 invString.AddNameValueLine("flags", Utils.UIntToHexString(item.Flags));
1151
1152 invString.AddSaleStart();
1153 invString.AddNameValueLine("sale_type", "not");
1154 invString.AddNameValueLine("sale_price", "0");
1155 invString.AddSectionEnd();
1156
1157 invString.AddNameValueLine("name", item.Name + "|");
1158 invString.AddNameValueLine("desc", item.Description + "|");
1159
1160 invString.AddNameValueLine("creation_date", item.CreationDate.ToString());
1161 invString.AddSectionEnd();
1162 }
1163
1164 Items.LockItemsForRead(false);
1165
1166 m_inventoryFileData = Utils.StringToBytes(invString.BuildString);
1167
1168 if (m_inventoryFileData.Length > 2)
1169 {
1170 xferManager.AddNewFile(m_inventoryFileName, m_inventoryFileData);
1171 client.SendTaskInventory(m_part.UUID, (short)m_inventorySerial,
1172 Util.StringToBytes256(m_inventoryFileName));
1173 return;
1174 }
1175
1176 client.SendTaskInventory(m_part.UUID, 0, new byte[0]);
1005 } 1177 }
1006 1178
1007 /// <summary> 1179 /// <summary>
@@ -1010,13 +1182,19 @@ namespace OpenSim.Region.Framework.Scenes
1010 /// <param name="datastore"></param> 1182 /// <param name="datastore"></param>
1011 public void ProcessInventoryBackup(ISimulationDataService datastore) 1183 public void ProcessInventoryBackup(ISimulationDataService datastore)
1012 { 1184 {
1013 if (HasInventoryChanged) 1185// Removed this because linking will cause an immediate delete of the new
1014 { 1186// child prim from the database and the subsequent storing of the prim sees
1015 HasInventoryChanged = false; 1187// the inventory of it as unchanged and doesn't store it at all. The overhead
1016 List<TaskInventoryItem> items = GetInventoryItems(); 1188// of storing prim inventory needlessly is much less than the aggravation
1017 datastore.StorePrimInventory(m_part.UUID, items); 1189// of prim inventory loss.
1190// if (HasInventoryChanged)
1191// {
1192 Items.LockItemsForRead(true);
1193 datastore.StorePrimInventory(m_part.UUID, Items.Values);
1194 Items.LockItemsForRead(false);
1018 1195
1019 } 1196 HasInventoryChanged = false;
1197// }
1020 } 1198 }
1021 1199
1022 public class InventoryStringBuilder 1200 public class InventoryStringBuilder
@@ -1082,87 +1260,63 @@ namespace OpenSim.Region.Framework.Scenes
1082 { 1260 {
1083 uint mask=0x7fffffff; 1261 uint mask=0x7fffffff;
1084 1262
1085 lock (m_items) 1263 foreach (TaskInventoryItem item in m_items.Values)
1086 { 1264 {
1087 foreach (TaskInventoryItem item in m_items.Values) 1265 if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Copy) == 0)
1266 mask &= ~((uint)PermissionMask.Copy >> 13);
1267 if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Transfer) == 0)
1268 mask &= ~((uint)PermissionMask.Transfer >> 13);
1269 if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Modify) == 0)
1270 mask &= ~((uint)PermissionMask.Modify >> 13);
1271
1272 if (item.InvType == (int)InventoryType.Object)
1088 { 1273 {
1089 if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Copy) == 0) 1274 if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0)
1090 mask &= ~((uint)PermissionMask.Copy >> 13); 1275 mask &= ~((uint)PermissionMask.Copy >> 13);
1091 if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Transfer) == 0) 1276 if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0)
1092 mask &= ~((uint)PermissionMask.Transfer >> 13); 1277 mask &= ~((uint)PermissionMask.Transfer >> 13);
1093 if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Modify) == 0) 1278 if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0)
1094 mask &= ~((uint)PermissionMask.Modify >> 13); 1279 mask &= ~((uint)PermissionMask.Modify >> 13);
1095
1096 if (item.InvType != (int)InventoryType.Object)
1097 {
1098 if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Copy) == 0)
1099 mask &= ~((uint)PermissionMask.Copy >> 13);
1100 if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Transfer) == 0)
1101 mask &= ~((uint)PermissionMask.Transfer >> 13);
1102 if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Modify) == 0)
1103 mask &= ~((uint)PermissionMask.Modify >> 13);
1104 }
1105 else
1106 {
1107 if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0)
1108 mask &= ~((uint)PermissionMask.Copy >> 13);
1109 if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0)
1110 mask &= ~((uint)PermissionMask.Transfer >> 13);
1111 if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0)
1112 mask &= ~((uint)PermissionMask.Modify >> 13);
1113 }
1114
1115 if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
1116 mask &= ~(uint)PermissionMask.Copy;
1117 if ((item.CurrentPermissions & (uint)PermissionMask.Transfer) == 0)
1118 mask &= ~(uint)PermissionMask.Transfer;
1119 if ((item.CurrentPermissions & (uint)PermissionMask.Modify) == 0)
1120 mask &= ~(uint)PermissionMask.Modify;
1121 } 1280 }
1281
1282 if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
1283 mask &= ~(uint)PermissionMask.Copy;
1284 if ((item.CurrentPermissions & (uint)PermissionMask.Transfer) == 0)
1285 mask &= ~(uint)PermissionMask.Transfer;
1286 if ((item.CurrentPermissions & (uint)PermissionMask.Modify) == 0)
1287 mask &= ~(uint)PermissionMask.Modify;
1122 } 1288 }
1123
1124 return mask; 1289 return mask;
1125 } 1290 }
1126 1291
1127 public void ApplyNextOwnerPermissions() 1292 public void ApplyNextOwnerPermissions()
1128 { 1293 {
1129 lock (m_items) 1294 foreach (TaskInventoryItem item in m_items.Values)
1130 { 1295 {
1131 foreach (TaskInventoryItem item in m_items.Values) 1296 if (item.InvType == (int)InventoryType.Object && (item.CurrentPermissions & 7) != 0)
1132 { 1297 {
1133// m_log.DebugFormat ( 1298 if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0)
1134// "[SCENE OBJECT PART INVENTORY]: Applying next permissions {0} to {1} in {2} with current {3}, base {4}, everyone {5}", 1299 item.CurrentPermissions &= ~(uint)PermissionMask.Copy;
1135// item.NextPermissions, item.Name, m_part.Name, item.CurrentPermissions, item.BasePermissions, item.EveryonePermissions); 1300 if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0)
1136 1301 item.CurrentPermissions &= ~(uint)PermissionMask.Transfer;
1137 if (item.InvType == (int)InventoryType.Object && (item.CurrentPermissions & 7) != 0) 1302 if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0)
1138 { 1303 item.CurrentPermissions &= ~(uint)PermissionMask.Modify;
1139 if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0)
1140 item.CurrentPermissions &= ~(uint)PermissionMask.Copy;
1141 if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0)
1142 item.CurrentPermissions &= ~(uint)PermissionMask.Transfer;
1143 if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0)
1144 item.CurrentPermissions &= ~(uint)PermissionMask.Modify;
1145 }
1146
1147 item.CurrentPermissions &= item.NextPermissions;
1148 item.BasePermissions &= item.NextPermissions;
1149 item.EveryonePermissions &= item.NextPermissions;
1150 item.OwnerChanged = true;
1151 item.PermsMask = 0;
1152 item.PermsGranter = UUID.Zero;
1153 } 1304 }
1305 item.CurrentPermissions &= item.NextPermissions;
1306 item.BasePermissions &= item.NextPermissions;
1307 item.EveryonePermissions &= item.NextPermissions;
1308 item.OwnerChanged = true;
1309 item.PermsMask = 0;
1310 item.PermsGranter = UUID.Zero;
1154 } 1311 }
1155 } 1312 }
1156 1313
1157 public void ApplyGodPermissions(uint perms) 1314 public void ApplyGodPermissions(uint perms)
1158 { 1315 {
1159 lock (m_items) 1316 foreach (TaskInventoryItem item in m_items.Values)
1160 { 1317 {
1161 foreach (TaskInventoryItem item in m_items.Values) 1318 item.CurrentPermissions = perms;
1162 { 1319 item.BasePermissions = perms;
1163 item.CurrentPermissions = perms;
1164 item.BasePermissions = perms;
1165 }
1166 } 1320 }
1167 1321
1168 m_inventorySerial++; 1322 m_inventorySerial++;
@@ -1175,14 +1329,11 @@ namespace OpenSim.Region.Framework.Scenes
1175 /// <returns></returns> 1329 /// <returns></returns>
1176 public bool ContainsScripts() 1330 public bool ContainsScripts()
1177 { 1331 {
1178 lock (m_items) 1332 foreach (TaskInventoryItem item in m_items.Values)
1179 { 1333 {
1180 foreach (TaskInventoryItem item in m_items.Values) 1334 if (item.InvType == (int)InventoryType.LSL)
1181 { 1335 {
1182 if (item.InvType == (int)InventoryType.LSL) 1336 return true;
1183 {
1184 return true;
1185 }
1186 } 1337 }
1187 } 1338 }
1188 1339
@@ -1196,17 +1347,15 @@ namespace OpenSim.Region.Framework.Scenes
1196 public int ScriptCount() 1347 public int ScriptCount()
1197 { 1348 {
1198 int count = 0; 1349 int count = 0;
1199 lock (m_items) 1350 Items.LockItemsForRead(true);
1351 foreach (TaskInventoryItem item in m_items.Values)
1200 { 1352 {
1201 foreach (TaskInventoryItem item in m_items.Values) 1353 if (item.InvType == (int)InventoryType.LSL)
1202 { 1354 {
1203 if (item.InvType == (int)InventoryType.LSL) 1355 count++;
1204 {
1205 count++;
1206 }
1207 } 1356 }
1208 } 1357 }
1209 1358 Items.LockItemsForRead(false);
1210 return count; 1359 return count;
1211 } 1360 }
1212 /// <summary> 1361 /// <summary>
@@ -1242,11 +1391,8 @@ namespace OpenSim.Region.Framework.Scenes
1242 { 1391 {
1243 List<UUID> ret = new List<UUID>(); 1392 List<UUID> ret = new List<UUID>();
1244 1393
1245 lock (m_items) 1394 foreach (TaskInventoryItem item in m_items.Values)
1246 { 1395 ret.Add(item.ItemID);
1247 foreach (TaskInventoryItem item in m_items.Values)
1248 ret.Add(item.ItemID);
1249 }
1250 1396
1251 return ret; 1397 return ret;
1252 } 1398 }
@@ -1255,8 +1401,9 @@ namespace OpenSim.Region.Framework.Scenes
1255 { 1401 {
1256 List<TaskInventoryItem> ret = new List<TaskInventoryItem>(); 1402 List<TaskInventoryItem> ret = new List<TaskInventoryItem>();
1257 1403
1258 lock (m_items) 1404 Items.LockItemsForRead(true);
1259 ret = new List<TaskInventoryItem>(m_items.Values); 1405 ret = new List<TaskInventoryItem>(m_items.Values);
1406 Items.LockItemsForRead(false);
1260 1407
1261 return ret; 1408 return ret;
1262 } 1409 }
@@ -1265,18 +1412,24 @@ namespace OpenSim.Region.Framework.Scenes
1265 { 1412 {
1266 List<TaskInventoryItem> ret = new List<TaskInventoryItem>(); 1413 List<TaskInventoryItem> ret = new List<TaskInventoryItem>();
1267 1414
1268 lock (m_items) 1415 Items.LockItemsForRead(true);
1269 { 1416
1270 foreach (TaskInventoryItem item in m_items.Values) 1417 foreach (TaskInventoryItem item in m_items.Values)
1271 if (item.InvType == (int)type) 1418 if (item.InvType == (int)type)
1272 ret.Add(item); 1419 ret.Add(item);
1273 } 1420
1421 Items.LockItemsForRead(false);
1274 1422
1275 return ret; 1423 return ret;
1276 } 1424 }
1277 1425
1278 public Dictionary<UUID, string> GetScriptStates() 1426 public Dictionary<UUID, string> GetScriptStates()
1279 { 1427 {
1428 return GetScriptStates(false);
1429 }
1430
1431 public Dictionary<UUID, string> GetScriptStates(bool oldIDs)
1432 {
1280 Dictionary<UUID, string> ret = new Dictionary<UUID, string>(); 1433 Dictionary<UUID, string> ret = new Dictionary<UUID, string>();
1281 1434
1282 if (m_part.ParentGroup.Scene == null) // Group not in a scene 1435 if (m_part.ParentGroup.Scene == null) // Group not in a scene
@@ -1302,14 +1455,21 @@ namespace OpenSim.Region.Framework.Scenes
1302 string n = e.GetXMLState(item.ItemID); 1455 string n = e.GetXMLState(item.ItemID);
1303 if (n != String.Empty) 1456 if (n != String.Empty)
1304 { 1457 {
1305 if (!ret.ContainsKey(item.ItemID)) 1458 if (oldIDs)
1306 ret[item.ItemID] = n; 1459 {
1460 if (!ret.ContainsKey(item.OldItemID))
1461 ret[item.OldItemID] = n;
1462 }
1463 else
1464 {
1465 if (!ret.ContainsKey(item.ItemID))
1466 ret[item.ItemID] = n;
1467 }
1307 break; 1468 break;
1308 } 1469 }
1309 } 1470 }
1310 } 1471 }
1311 } 1472 }
1312
1313 return ret; 1473 return ret;
1314 } 1474 }
1315 1475
diff --git a/OpenSim/Region/Framework/Scenes/ScenePresence.cs b/OpenSim/Region/Framework/Scenes/ScenePresence.cs
index 1222ac6..adb3d38 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;
@@ -98,7 +99,7 @@ namespace OpenSim.Region.Framework.Scenes
98 /// rotation, prim cut, prim twist, prim taper, and prim shear. See mantis 99 /// rotation, prim cut, prim twist, prim taper, and prim shear. See mantis
99 /// issue #1716 100 /// issue #1716
100 /// </summary> 101 /// </summary>
101 public static readonly Vector3 SIT_TARGET_ADJUSTMENT = new Vector3(0.0f, 0.0f, 0.418f); 102 public static readonly Vector3 SIT_TARGET_ADJUSTMENT = new Vector3(0.0f, 0.0f, 0.4f);
102 103
103 /// <summary> 104 /// <summary>
104 /// Movement updates for agents in neighboring regions are sent directly to clients. 105 /// Movement updates for agents in neighboring regions are sent directly to clients.
@@ -170,6 +171,7 @@ namespace OpenSim.Region.Framework.Scenes
170// private int m_lastColCount = -1; //KF: Look for Collision chnages 171// private int m_lastColCount = -1; //KF: Look for Collision chnages
171// private int m_updateCount = 0; //KF: Update Anims for a while 172// private int m_updateCount = 0; //KF: Update Anims for a while
172// private static readonly int UPDATE_COUNT = 10; // how many frames to update for 173// private static readonly int UPDATE_COUNT = 10; // how many frames to update for
174 private List<uint> m_lastColliders = new List<uint>();
173 175
174 private TeleportFlags m_teleportFlags; 176 private TeleportFlags m_teleportFlags;
175 public TeleportFlags TeleportFlags 177 public TeleportFlags TeleportFlags
@@ -231,6 +233,13 @@ namespace OpenSim.Region.Framework.Scenes
231 //private int m_moveToPositionStateStatus; 233 //private int m_moveToPositionStateStatus;
232 //***************************************************** 234 //*****************************************************
233 235
236 private bool m_collisionEventFlag = false;
237 private object m_collisionEventLock = new Object();
238
239 private int m_movementAnimationUpdateCounter = 0;
240
241 private Vector3 m_prevSitOffset;
242
234 protected AvatarAppearance m_appearance; 243 protected AvatarAppearance m_appearance;
235 244
236 public AvatarAppearance Appearance 245 public AvatarAppearance Appearance
@@ -425,7 +434,7 @@ namespace OpenSim.Region.Framework.Scenes
425 get { return (IClientCore)ControllingClient; } 434 get { return (IClientCore)ControllingClient; }
426 } 435 }
427 436
428 public Vector3 ParentPosition { get; set; } 437// public Vector3 ParentPosition { get; set; }
429 438
430 /// <summary> 439 /// <summary>
431 /// Position of this avatar relative to the region the avatar is in 440 /// Position of this avatar relative to the region the avatar is in
@@ -483,7 +492,7 @@ namespace OpenSim.Region.Framework.Scenes
483 if (ParentID == 0) 492 if (ParentID == 0)
484 { 493 {
485 m_pos = value; 494 m_pos = value;
486 ParentPosition = Vector3.Zero; 495// ParentPosition = Vector3.Zero;
487 } 496 }
488 497
489 //m_log.DebugFormat( 498 //m_log.DebugFormat(
@@ -572,6 +581,13 @@ namespace OpenSim.Region.Framework.Scenes
572 /// </summary> 581 /// </summary>
573 public uint ParentID { get; set; } 582 public uint ParentID { get; set; }
574 583
584 public UUID ParentUUID
585 {
586 get { return m_parentUUID; }
587 set { m_parentUUID = value; }
588 }
589 private UUID m_parentUUID = UUID.Zero;
590
575 /// <summary> 591 /// <summary>
576 /// Are we sitting on an object? 592 /// Are we sitting on an object?
577 /// </summary> 593 /// </summary>
@@ -738,6 +754,33 @@ namespace OpenSim.Region.Framework.Scenes
738 Appearance = appearance; 754 Appearance = appearance;
739 } 755 }
740 756
757 private void RegionHeartbeatEnd(Scene scene)
758 {
759 if (IsChildAgent)
760 return;
761
762 m_movementAnimationUpdateCounter ++;
763 if (m_movementAnimationUpdateCounter >= 2)
764 {
765 m_movementAnimationUpdateCounter = 0;
766 if (Animator != null)
767 {
768 // If the parentID == 0 we are not sitting
769 // if !SitGournd then we are not sitting on the ground
770 // Fairly straightforward, now here comes the twist
771 // if ParentUUID is NOT UUID.Zero, we are looking to
772 // be sat on an object that isn't there yet. Should
773 // be treated as if sat.
774 if(ParentID == 0 && !SitGround && ParentUUID == UUID.Zero) // skip it if sitting
775 Animator.UpdateMovementAnimations();
776 }
777 else
778 {
779 m_scene.EventManager.OnRegionHeartbeatEnd -= RegionHeartbeatEnd;
780 }
781 }
782 }
783
741 public void RegisterToEvents() 784 public void RegisterToEvents()
742 { 785 {
743 ControllingClient.OnCompleteMovementToRegion += CompleteMovement; 786 ControllingClient.OnCompleteMovementToRegion += CompleteMovement;
@@ -747,6 +790,7 @@ namespace OpenSim.Region.Framework.Scenes
747 ControllingClient.OnSetAlwaysRun += HandleSetAlwaysRun; 790 ControllingClient.OnSetAlwaysRun += HandleSetAlwaysRun;
748 ControllingClient.OnStartAnim += HandleStartAnim; 791 ControllingClient.OnStartAnim += HandleStartAnim;
749 ControllingClient.OnStopAnim += HandleStopAnim; 792 ControllingClient.OnStopAnim += HandleStopAnim;
793 ControllingClient.OnChangeAnim += avnHandleChangeAnim;
750 ControllingClient.OnForceReleaseControls += HandleForceReleaseControls; 794 ControllingClient.OnForceReleaseControls += HandleForceReleaseControls;
751 ControllingClient.OnAutoPilotGo += MoveToTarget; 795 ControllingClient.OnAutoPilotGo += MoveToTarget;
752 796
@@ -807,10 +851,39 @@ namespace OpenSim.Region.Framework.Scenes
807 "[SCENE]: Upgrading child to root agent for {0} in {1}", 851 "[SCENE]: Upgrading child to root agent for {0} in {1}",
808 Name, m_scene.RegionInfo.RegionName); 852 Name, m_scene.RegionInfo.RegionName);
809 853
810 //m_log.DebugFormat("[SCENE]: known regions in {0}: {1}", Scene.RegionInfo.RegionName, KnownChildRegionHandles.Count);
811
812 bool wasChild = IsChildAgent; 854 bool wasChild = IsChildAgent;
813 IsChildAgent = false; 855
856 if (ParentUUID != UUID.Zero)
857 {
858 m_log.DebugFormat("[SCENE PRESENCE]: Sitting avatar back on prim {0}", ParentUUID);
859 SceneObjectPart part = m_scene.GetSceneObjectPart(ParentUUID);
860 if (part == null)
861 {
862 m_log.ErrorFormat("[SCENE PRESENCE]: Can't find prim {0} to sit on", ParentUUID);
863 }
864 else
865 {
866 part.ParentGroup.AddAvatar(UUID);
867 if (part.SitTargetPosition != Vector3.Zero)
868 part.SitTargetAvatar = UUID;
869// ParentPosition = part.GetWorldPosition();
870 ParentID = part.LocalId;
871 ParentPart = part;
872 m_pos = m_prevSitOffset;
873// pos = ParentPosition;
874 pos = part.GetWorldPosition();
875 }
876 ParentUUID = UUID.Zero;
877
878 IsChildAgent = false;
879
880// Animator.TrySetMovementAnimation("SIT");
881 }
882 else
883 {
884 IsChildAgent = false;
885 }
886
814 887
815 IGroupsModule gm = m_scene.RequestModuleInterface<IGroupsModule>(); 888 IGroupsModule gm = m_scene.RequestModuleInterface<IGroupsModule>();
816 if (gm != null) 889 if (gm != null)
@@ -820,62 +893,72 @@ namespace OpenSim.Region.Framework.Scenes
820 893
821 m_scene.EventManager.TriggerSetRootAgentScene(m_uuid, m_scene); 894 m_scene.EventManager.TriggerSetRootAgentScene(m_uuid, m_scene);
822 895
823 // Moved this from SendInitialData to ensure that Appearance is initialized 896 if (ParentID == 0)
824 // before the inventory is processed in MakeRootAgent. This fixes a race condition
825 // related to the handling of attachments
826 //m_scene.GetAvatarAppearance(ControllingClient, out Appearance);
827 if (m_scene.TestBorderCross(pos, Cardinals.E))
828 { 897 {
829 Border crossedBorder = m_scene.GetCrossedBorder(pos, Cardinals.E); 898 // Moved this from SendInitialData to ensure that Appearance is initialized
830 pos.X = crossedBorder.BorderLine.Z - 1; 899 // before the inventory is processed in MakeRootAgent. This fixes a race condition
831 } 900 // related to the handling of attachments
901 //m_scene.GetAvatarAppearance(ControllingClient, out Appearance);
902 if (m_scene.TestBorderCross(pos, Cardinals.E))
903 {
904 Border crossedBorder = m_scene.GetCrossedBorder(pos, Cardinals.E);
905 pos.X = crossedBorder.BorderLine.Z - 1;
906 }
832 907
833 if (m_scene.TestBorderCross(pos, Cardinals.N)) 908 if (m_scene.TestBorderCross(pos, Cardinals.N))
834 { 909 {
835 Border crossedBorder = m_scene.GetCrossedBorder(pos, Cardinals.N); 910 Border crossedBorder = m_scene.GetCrossedBorder(pos, Cardinals.N);
836 pos.Y = crossedBorder.BorderLine.Z - 1; 911 pos.Y = crossedBorder.BorderLine.Z - 1;
837 } 912 }
838 913
839 CheckAndAdjustLandingPoint(ref pos); 914 CheckAndAdjustLandingPoint(ref pos);
840 915
841 if (pos.X < 0f || pos.Y < 0f || pos.Z < 0f) 916 if (pos.X < 0f || pos.Y < 0f || pos.Z < 0f)
842 { 917 {
843 m_log.WarnFormat( 918 m_log.WarnFormat(
844 "[SCENE PRESENCE]: MakeRootAgent() was given an illegal position of {0} for avatar {1}, {2}. Clamping", 919 "[SCENE PRESENCE]: MakeRootAgent() was given an illegal position of {0} for avatar {1}, {2}. Clamping",
845 pos, Name, UUID); 920 pos, Name, UUID);
846 921
847 if (pos.X < 0f) pos.X = 0f; 922 if (pos.X < 0f) pos.X = 0f;
848 if (pos.Y < 0f) pos.Y = 0f; 923 if (pos.Y < 0f) pos.Y = 0f;
849 if (pos.Z < 0f) pos.Z = 0f; 924 if (pos.Z < 0f) pos.Z = 0f;
850 } 925 }
851 926
852 float localAVHeight = 1.56f; 927 float localAVHeight = 1.56f;
853 if (Appearance.AvatarHeight > 0) 928 if (Appearance.AvatarHeight > 0)
854 localAVHeight = Appearance.AvatarHeight; 929 localAVHeight = Appearance.AvatarHeight;
855 930
856 float posZLimit = 0; 931 float posZLimit = 0;
857 932
858 if (pos.X < Constants.RegionSize && pos.Y < Constants.RegionSize) 933 if (pos.X < Constants.RegionSize && pos.Y < Constants.RegionSize)
859 posZLimit = (float)m_scene.Heightmap[(int)pos.X, (int)pos.Y]; 934 posZLimit = (float)m_scene.Heightmap[(int)pos.X, (int)pos.Y];
860 935
861 float newPosZ = posZLimit + localAVHeight / 2; 936 float newPosZ = posZLimit + localAVHeight / 2;
862 if (posZLimit >= (pos.Z - (localAVHeight / 2)) && !(Single.IsInfinity(newPosZ) || Single.IsNaN(newPosZ))) 937 if (posZLimit >= (pos.Z - (localAVHeight / 2)) && !(Single.IsInfinity(newPosZ) || Single.IsNaN(newPosZ)))
863 { 938 {
864 pos.Z = newPosZ; 939 pos.Z = newPosZ;
865 } 940 }
866 AbsolutePosition = pos; 941 AbsolutePosition = pos;
867 942
868 AddToPhysicalScene(isFlying); 943 if (m_teleportFlags == TeleportFlags.Default)
944 {
945 Vector3 vel = Velocity;
946 AddToPhysicalScene(isFlying);
947 if (PhysicsActor != null)
948 PhysicsActor.SetMomentum(vel);
949 }
950 else
951 AddToPhysicalScene(isFlying);
869 952
870 if (ForceFly) 953 if (ForceFly)
871 { 954 {
872 Flying = true; 955 Flying = true;
873 } 956 }
874 else if (FlyDisabled) 957 else if (FlyDisabled)
875 { 958 {
876 Flying = false; 959 Flying = false;
960 }
877 } 961 }
878
879 // Don't send an animation pack here, since on a region crossing this will sometimes cause a flying 962 // Don't send an animation pack here, since on a region crossing this will sometimes cause a flying
880 // avatar to return to the standing position in mid-air. On login it looks like this is being sent 963 // avatar to return to the standing position in mid-air. On login it looks like this is being sent
881 // elsewhere anyway 964 // elsewhere anyway
@@ -895,14 +978,19 @@ namespace OpenSim.Region.Framework.Scenes
895 "[SCENE PRESENCE]: Restarting scripts in attachments for {0} in {1}", Name, Scene.Name); 978 "[SCENE PRESENCE]: Restarting scripts in attachments for {0} in {1}", Name, Scene.Name);
896 979
897 // Resume scripts 980 // Resume scripts
898 foreach (SceneObjectGroup sog in m_attachments) 981 Util.FireAndForget(delegate(object x) {
899 { 982 foreach (SceneObjectGroup sog in m_attachments)
900 sog.RootPart.ParentGroup.CreateScriptInstances(0, false, m_scene.DefaultScriptEngine, GetStateSource()); 983 {
901 sog.ResumeScripts(); 984 sog.ScheduleGroupForFullUpdate();
902 } 985 sog.RootPart.ParentGroup.CreateScriptInstances(0, false, m_scene.DefaultScriptEngine, GetStateSource());
986 sog.ResumeScripts();
987 }
988 });
903 } 989 }
904 } 990 }
905 991
992 SendAvatarDataToAllAgents();
993
906 // send the animations of the other presences to me 994 // send the animations of the other presences to me
907 m_scene.ForEachRootScenePresence(delegate(ScenePresence presence) 995 m_scene.ForEachRootScenePresence(delegate(ScenePresence presence)
908 { 996 {
@@ -913,9 +1001,12 @@ namespace OpenSim.Region.Framework.Scenes
913 // If we don't reset the movement flag here, an avatar that crosses to a neighbouring sim and returns will 1001 // If we don't reset the movement flag here, an avatar that crosses to a neighbouring sim and returns will
914 // stall on the border crossing since the existing child agent will still have the last movement 1002 // stall on the border crossing since the existing child agent will still have the last movement
915 // recorded, which stops the input from being processed. 1003 // recorded, which stops the input from being processed.
1004
916 MovementFlag = 0; 1005 MovementFlag = 0;
917 1006
918 m_scene.EventManager.TriggerOnMakeRootAgent(this); 1007 m_scene.EventManager.TriggerOnMakeRootAgent(this);
1008
1009 m_scene.EventManager.OnRegionHeartbeatEnd += RegionHeartbeatEnd;
919 } 1010 }
920 1011
921 public int GetStateSource() 1012 public int GetStateSource()
@@ -943,12 +1034,16 @@ namespace OpenSim.Region.Framework.Scenes
943 /// </remarks> 1034 /// </remarks>
944 public void MakeChildAgent() 1035 public void MakeChildAgent()
945 { 1036 {
1037 m_scene.EventManager.OnRegionHeartbeatEnd -= RegionHeartbeatEnd;
1038
946 m_log.DebugFormat("[SCENE PRESENCE]: Making {0} a child agent in {1}", Name, Scene.RegionInfo.RegionName); 1039 m_log.DebugFormat("[SCENE PRESENCE]: Making {0} a child agent in {1}", Name, Scene.RegionInfo.RegionName);
947 1040
948 // Reset these so that teleporting in and walking out isn't seen 1041 // Reset these so that teleporting in and walking out isn't seen
949 // as teleporting back 1042 // as teleporting back
950 TeleportFlags = TeleportFlags.Default; 1043 TeleportFlags = TeleportFlags.Default;
951 1044
1045 MovementFlag = 0;
1046
952 // It looks like Animator is set to null somewhere, and MakeChild 1047 // It looks like Animator is set to null somewhere, and MakeChild
953 // is called after that. Probably in aborted teleports. 1048 // is called after that. Probably in aborted teleports.
954 if (Animator == null) 1049 if (Animator == null)
@@ -956,6 +1051,7 @@ namespace OpenSim.Region.Framework.Scenes
956 else 1051 else
957 Animator.ResetAnimations(); 1052 Animator.ResetAnimations();
958 1053
1054
959// m_log.DebugFormat( 1055// m_log.DebugFormat(
960// "[SCENE PRESENCE]: Downgrading root agent {0}, {1} to a child agent in {2}", 1056// "[SCENE PRESENCE]: Downgrading root agent {0}, {1} to a child agent in {2}",
961// Name, UUID, m_scene.RegionInfo.RegionName); 1057// Name, UUID, m_scene.RegionInfo.RegionName);
@@ -967,6 +1063,7 @@ namespace OpenSim.Region.Framework.Scenes
967 IsChildAgent = true; 1063 IsChildAgent = true;
968 m_scene.SwapRootAgentCount(true); 1064 m_scene.SwapRootAgentCount(true);
969 RemoveFromPhysicalScene(); 1065 RemoveFromPhysicalScene();
1066 ParentID = 0; // Child agents can't be sitting
970 1067
971 // FIXME: Set RegionHandle to the region handle of the scene this agent is moving into 1068 // FIXME: Set RegionHandle to the region handle of the scene this agent is moving into
972 1069
@@ -982,9 +1079,9 @@ namespace OpenSim.Region.Framework.Scenes
982 { 1079 {
983// PhysicsActor.OnRequestTerseUpdate -= SendTerseUpdateToAllClients; 1080// PhysicsActor.OnRequestTerseUpdate -= SendTerseUpdateToAllClients;
984 PhysicsActor.OnOutOfBounds -= OutOfBoundsCall; 1081 PhysicsActor.OnOutOfBounds -= OutOfBoundsCall;
985 m_scene.PhysicsScene.RemoveAvatar(PhysicsActor);
986 PhysicsActor.UnSubscribeEvents();
987 PhysicsActor.OnCollisionUpdate -= PhysicsCollisionUpdate; 1082 PhysicsActor.OnCollisionUpdate -= PhysicsCollisionUpdate;
1083 PhysicsActor.UnSubscribeEvents();
1084 m_scene.PhysicsScene.RemoveAvatar(PhysicsActor);
988 PhysicsActor = null; 1085 PhysicsActor = null;
989 } 1086 }
990// else 1087// else
@@ -1001,7 +1098,7 @@ namespace OpenSim.Region.Framework.Scenes
1001 /// <param name="pos"></param> 1098 /// <param name="pos"></param>
1002 public void Teleport(Vector3 pos) 1099 public void Teleport(Vector3 pos)
1003 { 1100 {
1004 TeleportWithMomentum(pos, null); 1101 TeleportWithMomentum(pos, Vector3.Zero);
1005 } 1102 }
1006 1103
1007 public void TeleportWithMomentum(Vector3 pos, Vector3? v) 1104 public void TeleportWithMomentum(Vector3 pos, Vector3? v)
@@ -1025,6 +1122,41 @@ namespace OpenSim.Region.Framework.Scenes
1025 SendTerseUpdateToAllClients(); 1122 SendTerseUpdateToAllClients();
1026 } 1123 }
1027 1124
1125 public void avnLocalTeleport(Vector3 newpos, Vector3? newvel, bool rotateToVelXY)
1126 {
1127 CheckLandingPoint(ref newpos);
1128 AbsolutePosition = newpos;
1129
1130 if (newvel.HasValue)
1131 {
1132 if ((Vector3)newvel == Vector3.Zero)
1133 {
1134 if (PhysicsActor != null)
1135 PhysicsActor.SetMomentum(Vector3.Zero);
1136 m_velocity = Vector3.Zero;
1137 }
1138 else
1139 {
1140 if (PhysicsActor != null)
1141 PhysicsActor.SetMomentum((Vector3)newvel);
1142 m_velocity = (Vector3)newvel;
1143
1144 if (rotateToVelXY)
1145 {
1146 Vector3 lookAt = (Vector3)newvel;
1147 lookAt.Z = 0;
1148 lookAt.Normalize();
1149 ControllingClient.SendLocalTeleport(newpos, lookAt, (uint)TeleportFlags.ViaLocation);
1150 return;
1151 }
1152 }
1153 }
1154
1155 SendTerseUpdateToAllClients();
1156 }
1157
1158
1159
1028 public void StopFlying() 1160 public void StopFlying()
1029 { 1161 {
1030 ControllingClient.StopFlying(this); 1162 ControllingClient.StopFlying(this);
@@ -1134,7 +1266,8 @@ namespace OpenSim.Region.Framework.Scenes
1134 1266
1135 Vector3 look = Velocity; 1267 Vector3 look = Velocity;
1136 1268
1137 if ((look.X == 0) && (look.Y == 0) && (look.Z == 0)) 1269 // if ((look.X == 0) && (look.Y == 0) && (look.Z == 0))
1270 if ((Math.Abs(look.X) < 0.1) && (Math.Abs(look.Y) < 0.1) && (Math.Abs(look.Z) < 0.1))
1138 { 1271 {
1139 look = new Vector3(0.99f, 0.042f, 0); 1272 look = new Vector3(0.99f, 0.042f, 0);
1140 } 1273 }
@@ -1184,13 +1317,15 @@ namespace OpenSim.Region.Framework.Scenes
1184 // Create child agents in neighbouring regions 1317 // Create child agents in neighbouring regions
1185 if (openChildAgents && !IsChildAgent) 1318 if (openChildAgents && !IsChildAgent)
1186 { 1319 {
1320
1187 IEntityTransferModule m_agentTransfer = m_scene.RequestModuleInterface<IEntityTransferModule>(); 1321 IEntityTransferModule m_agentTransfer = m_scene.RequestModuleInterface<IEntityTransferModule>();
1188 if (m_agentTransfer != null) 1322 if (m_agentTransfer != null)
1189 Util.FireAndForget(delegate { m_agentTransfer.EnableChildAgents(this); }); 1323 m_agentTransfer.EnableChildAgents(this);
1190 1324
1191 IFriendsModule friendsModule = m_scene.RequestModuleInterface<IFriendsModule>(); 1325 IFriendsModule friendsModule = m_scene.RequestModuleInterface<IFriendsModule>();
1192 if (friendsModule != null) 1326 if (friendsModule != null)
1193 friendsModule.SendFriendsOnlineIfNeeded(ControllingClient); 1327 friendsModule.SendFriendsOnlineIfNeeded(ControllingClient);
1328
1194 } 1329 }
1195 1330
1196// m_log.DebugFormat( 1331// m_log.DebugFormat(
@@ -1340,8 +1475,18 @@ namespace OpenSim.Region.Framework.Scenes
1340 { 1475 {
1341 if (m_followCamAuto) 1476 if (m_followCamAuto)
1342 { 1477 {
1343 Vector3 posAdjusted = m_pos + HEAD_ADJUSTMENT; 1478 // Vector3 posAdjusted = m_pos + HEAD_ADJUSTMENT;
1344 m_scene.PhysicsScene.RaycastWorld(m_pos, Vector3.Normalize(CameraPosition - posAdjusted), Vector3.Distance(CameraPosition, posAdjusted) + 0.3f, RayCastCameraCallback); 1479 // m_scene.PhysicsScene.RaycastWorld(m_pos, Vector3.Normalize(CameraPosition - posAdjusted), Vector3.Distance(CameraPosition, posAdjusted) + 0.3f, RayCastCameraCallback);
1480
1481 Vector3 posAdjusted = AbsolutePosition + HEAD_ADJUSTMENT;
1482 Vector3 distTocam = CameraPosition - posAdjusted;
1483 float distTocamlen = distTocam.Length();
1484 if (distTocamlen > 0)
1485 {
1486 distTocam *= 1.0f / distTocamlen;
1487 m_scene.PhysicsScene.RaycastWorld(posAdjusted, distTocam, distTocamlen + 0.3f, RayCastCameraCallback);
1488 }
1489
1345 } 1490 }
1346 } 1491 }
1347 1492
@@ -1780,12 +1925,17 @@ namespace OpenSim.Region.Framework.Scenes
1780// m_log.DebugFormat("[SCENE PRESENCE]: StandUp() for {0}", Name); 1925// m_log.DebugFormat("[SCENE PRESENCE]: StandUp() for {0}", Name);
1781 1926
1782 SitGround = false; 1927 SitGround = false;
1928
1929/* move this down so avatar gets physical in the new position and not where it is siting
1783 if (PhysicsActor == null) 1930 if (PhysicsActor == null)
1784 AddToPhysicalScene(false); 1931 AddToPhysicalScene(false);
1932 */
1785 1933
1786 if (ParentID != 0) 1934 if (ParentID != 0)
1787 { 1935 {
1788 SceneObjectPart part = ParentPart; 1936 SceneObjectPart part = ParentPart;
1937 UnRegisterSeatControls(part.ParentGroup.UUID);
1938
1789 TaskInventoryDictionary taskIDict = part.TaskInventory; 1939 TaskInventoryDictionary taskIDict = part.TaskInventory;
1790 if (taskIDict != null) 1940 if (taskIDict != null)
1791 { 1941 {
@@ -1801,14 +1951,22 @@ namespace OpenSim.Region.Framework.Scenes
1801 } 1951 }
1802 } 1952 }
1803 1953
1804 ParentPosition = part.GetWorldPosition(); 1954 part.ParentGroup.DeleteAvatar(UUID);
1955// ParentPosition = part.GetWorldPosition();
1805 ControllingClient.SendClearFollowCamProperties(part.ParentUUID); 1956 ControllingClient.SendClearFollowCamProperties(part.ParentUUID);
1806 1957
1807 m_pos += ParentPosition + new Vector3(0.0f, 0.0f, 2.0f * m_sitAvatarHeight); 1958// m_pos += ParentPosition + new Vector3(0.0f, 0.0f, 2.0f * m_sitAvatarHeight);
1808 ParentPosition = Vector3.Zero; 1959// ParentPosition = Vector3.Zero;
1960 m_pos = part.AbsolutePosition + (m_pos * part.GetWorldRotation()) + new Vector3(0.0f, 0.0f, 2.0f * m_sitAvatarHeight);
1961 if (part.SitTargetAvatar == UUID)
1962 m_bodyRot = part.GetWorldRotation() * part.SitTargetOrientation;
1809 1963
1810 ParentID = 0; 1964 ParentID = 0;
1811 ParentPart = null; 1965 ParentPart = null;
1966
1967 if (PhysicsActor == null)
1968 AddToPhysicalScene(false);
1969
1812 SendAvatarDataToAllAgents(); 1970 SendAvatarDataToAllAgents();
1813 m_requestedSitTargetID = 0; 1971 m_requestedSitTargetID = 0;
1814 1972
@@ -1818,6 +1976,9 @@ namespace OpenSim.Region.Framework.Scenes
1818 part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK); 1976 part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK);
1819 } 1977 }
1820 1978
1979 else if (PhysicsActor == null)
1980 AddToPhysicalScene(false);
1981
1821 Animator.TrySetMovementAnimation("STAND"); 1982 Animator.TrySetMovementAnimation("STAND");
1822 } 1983 }
1823 1984
@@ -1869,7 +2030,7 @@ namespace OpenSim.Region.Framework.Scenes
1869 // see http://wiki.secondlife.com/wiki/User:Andrew_Linden/Office_Hours/2007_11_06 for details on how LL does it 2030 // see http://wiki.secondlife.com/wiki/User:Andrew_Linden/Office_Hours/2007_11_06 for details on how LL does it
1870 2031
1871 if (PhysicsActor != null) 2032 if (PhysicsActor != null)
1872 m_sitAvatarHeight = PhysicsActor.Size.Z; 2033 m_sitAvatarHeight = PhysicsActor.Size.Z * 0.5f;
1873 2034
1874 bool canSit = false; 2035 bool canSit = false;
1875 Vector3 pos = part.AbsolutePosition + offset; 2036 Vector3 pos = part.AbsolutePosition + offset;
@@ -1918,7 +2079,7 @@ namespace OpenSim.Region.Framework.Scenes
1918 forceMouselook = part.GetForceMouselook(); 2079 forceMouselook = part.GetForceMouselook();
1919 2080
1920 ControllingClient.SendSitResponse( 2081 ControllingClient.SendSitResponse(
1921 targetID, offset, sitOrientation, false, cameraAtOffset, cameraEyeOffset, forceMouselook); 2082 part.UUID, offset, sitOrientation, false, cameraAtOffset, cameraEyeOffset, forceMouselook);
1922 2083
1923 m_requestedSitTargetUUID = targetID; 2084 m_requestedSitTargetUUID = targetID;
1924 2085
@@ -1932,6 +2093,9 @@ namespace OpenSim.Region.Framework.Scenes
1932 2093
1933 public void HandleAgentRequestSit(IClientAPI remoteClient, UUID agentID, UUID targetID, Vector3 offset) 2094 public void HandleAgentRequestSit(IClientAPI remoteClient, UUID agentID, UUID targetID, Vector3 offset)
1934 { 2095 {
2096 if (IsChildAgent)
2097 return;
2098
1935 if (ParentID != 0) 2099 if (ParentID != 0)
1936 { 2100 {
1937 StandUp(); 2101 StandUp();
@@ -2209,14 +2373,39 @@ namespace OpenSim.Region.Framework.Scenes
2209 2373
2210 //Quaternion result = (sitTargetOrient * vq) * nq; 2374 //Quaternion result = (sitTargetOrient * vq) * nq;
2211 2375
2212 m_pos = sitTargetPos + SIT_TARGET_ADJUSTMENT; 2376 double x, y, z, m;
2377
2378 Quaternion r = sitTargetOrient;
2379 m = r.X * r.X + r.Y * r.Y + r.Z * r.Z + r.W * r.W;
2380
2381 if (Math.Abs(1.0 - m) > 0.000001)
2382 {
2383 m = 1.0 / Math.Sqrt(m);
2384 r.X *= (float)m;
2385 r.Y *= (float)m;
2386 r.Z *= (float)m;
2387 r.W *= (float)m;
2388 }
2389
2390 x = 2 * (r.X * r.Z + r.Y * r.W);
2391 y = 2 * (-r.X * r.W + r.Y * r.Z);
2392 z = -r.X * r.X - r.Y * r.Y + r.Z * r.Z + r.W * r.W;
2393
2394 Vector3 up = new Vector3((float)x, (float)y, (float)z);
2395 Vector3 sitOffset = up * Appearance.AvatarHeight * 0.02638f;
2396
2397 m_pos = sitTargetPos + sitOffset + SIT_TARGET_ADJUSTMENT;
2398
2399// m_pos = sitTargetPos + SIT_TARGET_ADJUSTMENT - sitOffset;
2213 Rotation = sitTargetOrient; 2400 Rotation = sitTargetOrient;
2214 ParentPosition = part.AbsolutePosition; 2401// ParentPosition = part.AbsolutePosition;
2402 part.ParentGroup.AddAvatar(UUID);
2215 } 2403 }
2216 else 2404 else
2217 { 2405 {
2218 m_pos -= part.AbsolutePosition; 2406 m_pos -= part.AbsolutePosition;
2219 ParentPosition = part.AbsolutePosition; 2407// ParentPosition = part.AbsolutePosition;
2408 part.ParentGroup.AddAvatar(UUID);
2220 2409
2221// m_log.DebugFormat( 2410// m_log.DebugFormat(
2222// "[SCENE PRESENCE]: Sitting {0} at position {1} ({2} + {3}) on part {4} {5} without sit target", 2411// "[SCENE PRESENCE]: Sitting {0} at position {1} ({2} + {3}) on part {4} {5} without sit target",
@@ -2261,6 +2450,13 @@ namespace OpenSim.Region.Framework.Scenes
2261 Animator.RemoveAnimation(animID); 2450 Animator.RemoveAnimation(animID);
2262 } 2451 }
2263 2452
2453 public void avnHandleChangeAnim(UUID animID, bool addRemove,bool sendPack)
2454 {
2455 Animator.avnChangeAnim(animID, addRemove, sendPack);
2456 }
2457
2458
2459
2264 /// <summary> 2460 /// <summary>
2265 /// Rotate the avatar to the given rotation and apply a movement in the given relative vector 2461 /// Rotate the avatar to the given rotation and apply a movement in the given relative vector
2266 /// </summary> 2462 /// </summary>
@@ -2314,14 +2510,15 @@ namespace OpenSim.Region.Framework.Scenes
2314 direc.Z *= 2.6f; 2510 direc.Z *= 2.6f;
2315 2511
2316 // TODO: PreJump and jump happen too quickly. Many times prejump gets ignored. 2512 // TODO: PreJump and jump happen too quickly. Many times prejump gets ignored.
2317 Animator.TrySetMovementAnimation("PREJUMP"); 2513// Animator.TrySetMovementAnimation("PREJUMP");
2318 Animator.TrySetMovementAnimation("JUMP"); 2514// Animator.TrySetMovementAnimation("JUMP");
2319 } 2515 }
2320 } 2516 }
2321 } 2517 }
2322 2518
2323 // TODO: Add the force instead of only setting it to support multiple forces per frame? 2519 // TODO: Add the force instead of only setting it to support multiple forces per frame?
2324 m_forceToApply = direc; 2520 m_forceToApply = direc;
2521 Animator.UpdateMovementAnimations();
2325 } 2522 }
2326 2523
2327 #endregion 2524 #endregion
@@ -2713,8 +2910,9 @@ namespace OpenSim.Region.Framework.Scenes
2713 2910
2714 // If we don't have a PhysActor, we can't cross anyway 2911 // If we don't have a PhysActor, we can't cross anyway
2715 // Also don't do this while sat, sitting avatars cross with the 2912 // Also don't do this while sat, sitting avatars cross with the
2716 // object they sit on. 2913 // object they sit on. ParentUUID denoted a pending sit, don't
2717 if (ParentID != 0 || PhysicsActor == null) 2914 // interfere with it.
2915 if (ParentID != 0 || PhysicsActor == null || ParentUUID != UUID.Zero)
2718 return; 2916 return;
2719 2917
2720 if (!IsInTransit) 2918 if (!IsInTransit)
@@ -3055,6 +3253,9 @@ namespace OpenSim.Region.Framework.Scenes
3055 cAgent.AlwaysRun = SetAlwaysRun; 3253 cAgent.AlwaysRun = SetAlwaysRun;
3056 3254
3057 cAgent.Appearance = new AvatarAppearance(Appearance); 3255 cAgent.Appearance = new AvatarAppearance(Appearance);
3256
3257 cAgent.ParentPart = ParentUUID;
3258 cAgent.SitOffset = m_pos;
3058 3259
3059 lock (scriptedcontrols) 3260 lock (scriptedcontrols)
3060 { 3261 {
@@ -3063,7 +3264,7 @@ namespace OpenSim.Region.Framework.Scenes
3063 3264
3064 foreach (ScriptControllers c in scriptedcontrols.Values) 3265 foreach (ScriptControllers c in scriptedcontrols.Values)
3065 { 3266 {
3066 controls[i++] = new ControllerData(c.itemID, (uint)c.ignoreControls, (uint)c.eventControls); 3267 controls[i++] = new ControllerData(c.objectID, c.itemID, (uint)c.ignoreControls, (uint)c.eventControls);
3067 } 3268 }
3068 cAgent.Controllers = controls; 3269 cAgent.Controllers = controls;
3069 } 3270 }
@@ -3074,6 +3275,7 @@ namespace OpenSim.Region.Framework.Scenes
3074 cAgent.Anims = Animator.Animations.ToArray(); 3275 cAgent.Anims = Animator.Animations.ToArray();
3075 } 3276 }
3076 catch { } 3277 catch { }
3278 cAgent.DefaultAnim = Animator.Animations.DefaultAnimation;
3077 3279
3078 if (Scene.AttachmentsModule != null) 3280 if (Scene.AttachmentsModule != null)
3079 Scene.AttachmentsModule.CopyAttachments(this, cAgent); 3281 Scene.AttachmentsModule.CopyAttachments(this, cAgent);
@@ -3094,6 +3296,8 @@ namespace OpenSim.Region.Framework.Scenes
3094 CameraAtAxis = cAgent.AtAxis; 3296 CameraAtAxis = cAgent.AtAxis;
3095 CameraLeftAxis = cAgent.LeftAxis; 3297 CameraLeftAxis = cAgent.LeftAxis;
3096 CameraUpAxis = cAgent.UpAxis; 3298 CameraUpAxis = cAgent.UpAxis;
3299 ParentUUID = cAgent.ParentPart;
3300 m_prevSitOffset = cAgent.SitOffset;
3097 3301
3098 // When we get to the point of re-computing neighbors everytime this 3302 // When we get to the point of re-computing neighbors everytime this
3099 // changes, then start using the agent's drawdistance rather than the 3303 // changes, then start using the agent's drawdistance rather than the
@@ -3131,6 +3335,7 @@ namespace OpenSim.Region.Framework.Scenes
3131 foreach (ControllerData c in cAgent.Controllers) 3335 foreach (ControllerData c in cAgent.Controllers)
3132 { 3336 {
3133 ScriptControllers sc = new ScriptControllers(); 3337 ScriptControllers sc = new ScriptControllers();
3338 sc.objectID = c.ObjectID;
3134 sc.itemID = c.ItemID; 3339 sc.itemID = c.ItemID;
3135 sc.ignoreControls = (ScriptControlled)c.IgnoreControls; 3340 sc.ignoreControls = (ScriptControlled)c.IgnoreControls;
3136 sc.eventControls = (ScriptControlled)c.EventControls; 3341 sc.eventControls = (ScriptControlled)c.EventControls;
@@ -3145,6 +3350,8 @@ namespace OpenSim.Region.Framework.Scenes
3145 // FIXME: Why is this null check necessary? Where are the cases where we get a null Anims object? 3350 // FIXME: Why is this null check necessary? Where are the cases where we get a null Anims object?
3146 if (cAgent.Anims != null) 3351 if (cAgent.Anims != null)
3147 Animator.Animations.FromArray(cAgent.Anims); 3352 Animator.Animations.FromArray(cAgent.Anims);
3353 if (cAgent.DefaultAnim != null)
3354 Animator.Animations.SetDefaultAnimation(cAgent.DefaultAnim.AnimID, cAgent.DefaultAnim.SequenceNum, UUID.Zero);
3148 3355
3149 if (Scene.AttachmentsModule != null) 3356 if (Scene.AttachmentsModule != null)
3150 Scene.AttachmentsModule.CopyAttachments(cAgent, this); 3357 Scene.AttachmentsModule.CopyAttachments(cAgent, this);
@@ -3207,7 +3414,7 @@ namespace OpenSim.Region.Framework.Scenes
3207 //PhysicsActor.OnRequestTerseUpdate += SendTerseUpdateToAllClients; 3414 //PhysicsActor.OnRequestTerseUpdate += SendTerseUpdateToAllClients;
3208 PhysicsActor.OnCollisionUpdate += PhysicsCollisionUpdate; 3415 PhysicsActor.OnCollisionUpdate += PhysicsCollisionUpdate;
3209 PhysicsActor.OnOutOfBounds += OutOfBoundsCall; // Called for PhysicsActors when there's something wrong 3416 PhysicsActor.OnOutOfBounds += OutOfBoundsCall; // Called for PhysicsActors when there's something wrong
3210 PhysicsActor.SubscribeEvents(500); 3417 PhysicsActor.SubscribeEvents(100);
3211 PhysicsActor.LocalID = LocalId; 3418 PhysicsActor.LocalID = LocalId;
3212 } 3419 }
3213 3420
@@ -3234,7 +3441,7 @@ namespace OpenSim.Region.Framework.Scenes
3234 /// <param name="e"></param> 3441 /// <param name="e"></param>
3235 public void PhysicsCollisionUpdate(EventArgs e) 3442 public void PhysicsCollisionUpdate(EventArgs e)
3236 { 3443 {
3237 if (IsChildAgent) 3444 if (IsChildAgent || Animator == null)
3238 return; 3445 return;
3239 3446
3240 //if ((Math.Abs(Velocity.X) > 0.1e-9f) || (Math.Abs(Velocity.Y) > 0.1e-9f)) 3447 //if ((Math.Abs(Velocity.X) > 0.1e-9f) || (Math.Abs(Velocity.Y) > 0.1e-9f))
@@ -3289,6 +3496,8 @@ namespace OpenSim.Region.Framework.Scenes
3289 } 3496 }
3290 } 3497 }
3291 3498
3499 RaiseCollisionScriptEvents(coldata);
3500
3292 // Gods do not take damage and Invulnerable is set depending on parcel/region flags 3501 // Gods do not take damage and Invulnerable is set depending on parcel/region flags
3293 if (Invulnerable || GodLevel > 0) 3502 if (Invulnerable || GodLevel > 0)
3294 return; 3503 return;
@@ -3386,6 +3595,13 @@ namespace OpenSim.Region.Framework.Scenes
3386 // m_reprioritizationTimer.Dispose(); 3595 // m_reprioritizationTimer.Dispose();
3387 3596
3388 RemoveFromPhysicalScene(); 3597 RemoveFromPhysicalScene();
3598
3599 m_scene.EventManager.OnRegionHeartbeatEnd -= RegionHeartbeatEnd;
3600
3601// if (Animator != null)
3602// Animator.Close();
3603 Animator = null;
3604
3389 } 3605 }
3390 3606
3391 public void AddAttachment(SceneObjectGroup gobj) 3607 public void AddAttachment(SceneObjectGroup gobj)
@@ -3619,10 +3835,18 @@ namespace OpenSim.Region.Framework.Scenes
3619 3835
3620 public void RegisterControlEventsToScript(int controls, int accept, int pass_on, uint Obj_localID, UUID Script_item_UUID) 3836 public void RegisterControlEventsToScript(int controls, int accept, int pass_on, uint Obj_localID, UUID Script_item_UUID)
3621 { 3837 {
3838 SceneObjectPart p = m_scene.GetSceneObjectPart(Obj_localID);
3839 if (p == null)
3840 return;
3841
3842 ControllingClient.SendTakeControls(controls, false, false);
3843 ControllingClient.SendTakeControls(controls, true, false);
3844
3622 ScriptControllers obj = new ScriptControllers(); 3845 ScriptControllers obj = new ScriptControllers();
3623 obj.ignoreControls = ScriptControlled.CONTROL_ZERO; 3846 obj.ignoreControls = ScriptControlled.CONTROL_ZERO;
3624 obj.eventControls = ScriptControlled.CONTROL_ZERO; 3847 obj.eventControls = ScriptControlled.CONTROL_ZERO;
3625 3848
3849 obj.objectID = p.ParentGroup.UUID;
3626 obj.itemID = Script_item_UUID; 3850 obj.itemID = Script_item_UUID;
3627 if (pass_on == 0 && accept == 0) 3851 if (pass_on == 0 && accept == 0)
3628 { 3852 {
@@ -3671,6 +3895,21 @@ namespace OpenSim.Region.Framework.Scenes
3671 ControllingClient.SendTakeControls(int.MaxValue, false, false); 3895 ControllingClient.SendTakeControls(int.MaxValue, false, false);
3672 } 3896 }
3673 3897
3898 private void UnRegisterSeatControls(UUID obj)
3899 {
3900 List<UUID> takers = new List<UUID>();
3901
3902 foreach (ScriptControllers c in scriptedcontrols.Values)
3903 {
3904 if (c.objectID == obj)
3905 takers.Add(c.itemID);
3906 }
3907 foreach (UUID t in takers)
3908 {
3909 UnRegisterControlEventsToScript(0, t);
3910 }
3911 }
3912
3674 public void UnRegisterControlEventsToScript(uint Obj_localID, UUID Script_item_UUID) 3913 public void UnRegisterControlEventsToScript(uint Obj_localID, UUID Script_item_UUID)
3675 { 3914 {
3676 ScriptControllers takecontrols; 3915 ScriptControllers takecontrols;
@@ -3989,6 +4228,12 @@ namespace OpenSim.Region.Framework.Scenes
3989 4228
3990 private void CheckAndAdjustLandingPoint(ref Vector3 pos) 4229 private void CheckAndAdjustLandingPoint(ref Vector3 pos)
3991 { 4230 {
4231 string reason;
4232
4233 // Honor bans
4234 if (!m_scene.TestLandRestrictions(UUID, out reason, ref pos.X, ref pos.Y))
4235 return;
4236
3992 SceneObjectGroup telehub = null; 4237 SceneObjectGroup telehub = null;
3993 if (m_scene.RegionInfo.RegionSettings.TelehubObject != UUID.Zero && (telehub = m_scene.GetSceneObjectGroup(m_scene.RegionInfo.RegionSettings.TelehubObject)) != null) 4238 if (m_scene.RegionInfo.RegionSettings.TelehubObject != UUID.Zero && (telehub = m_scene.GetSceneObjectGroup(m_scene.RegionInfo.RegionSettings.TelehubObject)) != null)
3994 { 4239 {
@@ -4028,11 +4273,206 @@ namespace OpenSim.Region.Framework.Scenes
4028 pos = land.LandData.UserLocation; 4273 pos = land.LandData.UserLocation;
4029 } 4274 }
4030 } 4275 }
4031 4276
4032 land.SendLandUpdateToClient(ControllingClient); 4277 land.SendLandUpdateToClient(ControllingClient);
4033 } 4278 }
4034 } 4279 }
4035 4280
4281 private DetectedObject CreateDetObject(SceneObjectPart obj)
4282 {
4283 DetectedObject detobj = new DetectedObject();
4284 detobj.keyUUID = obj.UUID;
4285 detobj.nameStr = obj.Name;
4286 detobj.ownerUUID = obj.OwnerID;
4287 detobj.posVector = obj.AbsolutePosition;
4288 detobj.rotQuat = obj.GetWorldRotation();
4289 detobj.velVector = obj.Velocity;
4290 detobj.colliderType = 0;
4291 detobj.groupUUID = obj.GroupID;
4292
4293 return detobj;
4294 }
4295
4296 private DetectedObject CreateDetObject(ScenePresence av)
4297 {
4298 DetectedObject detobj = new DetectedObject();
4299 detobj.keyUUID = av.UUID;
4300 detobj.nameStr = av.ControllingClient.Name;
4301 detobj.ownerUUID = av.UUID;
4302 detobj.posVector = av.AbsolutePosition;
4303 detobj.rotQuat = av.Rotation;
4304 detobj.velVector = av.Velocity;
4305 detobj.colliderType = 0;
4306 detobj.groupUUID = av.ControllingClient.ActiveGroupId;
4307
4308 return detobj;
4309 }
4310
4311 private DetectedObject CreateDetObjectForGround()
4312 {
4313 DetectedObject detobj = new DetectedObject();
4314 detobj.keyUUID = UUID.Zero;
4315 detobj.nameStr = "";
4316 detobj.ownerUUID = UUID.Zero;
4317 detobj.posVector = AbsolutePosition;
4318 detobj.rotQuat = Quaternion.Identity;
4319 detobj.velVector = Vector3.Zero;
4320 detobj.colliderType = 0;
4321 detobj.groupUUID = UUID.Zero;
4322
4323 return detobj;
4324 }
4325
4326 private ColliderArgs CreateColliderArgs(SceneObjectPart dest, List<uint> colliders)
4327 {
4328 ColliderArgs colliderArgs = new ColliderArgs();
4329 List<DetectedObject> colliding = new List<DetectedObject>();
4330 foreach (uint localId in colliders)
4331 {
4332 if (localId == 0)
4333 continue;
4334
4335 SceneObjectPart obj = m_scene.GetSceneObjectPart(localId);
4336 if (obj != null)
4337 {
4338 if (!dest.CollisionFilteredOut(obj.UUID, obj.Name))
4339 colliding.Add(CreateDetObject(obj));
4340 }
4341 else
4342 {
4343 ScenePresence av = m_scene.GetScenePresence(localId);
4344 if (av != null && (!av.IsChildAgent))
4345 {
4346 if (!dest.CollisionFilteredOut(av.UUID, av.Name))
4347 colliding.Add(CreateDetObject(av));
4348 }
4349 }
4350 }
4351
4352 colliderArgs.Colliders = colliding;
4353
4354 return colliderArgs;
4355 }
4356
4357 private delegate void ScriptCollidingNotification(uint localID, ColliderArgs message);
4358
4359 private void SendCollisionEvent(SceneObjectGroup dest, scriptEvents ev, List<uint> colliders, ScriptCollidingNotification notify)
4360 {
4361 ColliderArgs CollidingMessage;
4362
4363 if (colliders.Count > 0)
4364 {
4365 if ((dest.RootPart.ScriptEvents & ev) != 0)
4366 {
4367 CollidingMessage = CreateColliderArgs(dest.RootPart, colliders);
4368
4369 if (CollidingMessage.Colliders.Count > 0)
4370 notify(dest.RootPart.LocalId, CollidingMessage);
4371 }
4372 }
4373 }
4374
4375 private void SendLandCollisionEvent(SceneObjectGroup dest, scriptEvents ev, ScriptCollidingNotification notify)
4376 {
4377 if ((dest.RootPart.ScriptEvents & ev) != 0)
4378 {
4379 ColliderArgs LandCollidingMessage = new ColliderArgs();
4380 List<DetectedObject> colliding = new List<DetectedObject>();
4381
4382 colliding.Add(CreateDetObjectForGround());
4383 LandCollidingMessage.Colliders = colliding;
4384
4385 notify(dest.RootPart.LocalId, LandCollidingMessage);
4386 }
4387 }
4388
4389 private void RaiseCollisionScriptEvents(Dictionary<uint, ContactPoint> coldata)
4390 {
4391 try
4392 {
4393 List<uint> thisHitColliders = new List<uint>();
4394 List<uint> endedColliders = new List<uint>();
4395 List<uint> startedColliders = new List<uint>();
4396 List<CollisionForSoundInfo> soundinfolist = new List<CollisionForSoundInfo>();
4397 CollisionForSoundInfo soundinfo;
4398 ContactPoint curcontact;
4399
4400 if (coldata.Count == 0)
4401 {
4402 if (m_lastColliders.Count == 0)
4403 return; // nothing to do
4404
4405 foreach (uint localID in m_lastColliders)
4406 {
4407 endedColliders.Add(localID);
4408 }
4409 m_lastColliders.Clear();
4410 }
4411
4412 else
4413 {
4414 foreach (uint id in coldata.Keys)
4415 {
4416 thisHitColliders.Add(id);
4417 if (!m_lastColliders.Contains(id))
4418 {
4419 startedColliders.Add(id);
4420 curcontact = coldata[id];
4421 if (Math.Abs(curcontact.RelativeSpeed) > 0.2)
4422 {
4423 soundinfo = new CollisionForSoundInfo();
4424 soundinfo.colliderID = id;
4425 soundinfo.position = curcontact.Position;
4426 soundinfo.relativeVel = curcontact.RelativeSpeed;
4427 soundinfolist.Add(soundinfo);
4428 }
4429 }
4430 //m_log.Debug("[SCENE PRESENCE]: Collided with:" + localid.ToString() + " at depth of: " + collissionswith[localid].ToString());
4431 }
4432
4433 // calculate things that ended colliding
4434 foreach (uint localID in m_lastColliders)
4435 {
4436 if (!thisHitColliders.Contains(localID))
4437 {
4438 endedColliders.Add(localID);
4439 }
4440 }
4441 //add the items that started colliding this time to the last colliders list.
4442 foreach (uint localID in startedColliders)
4443 {
4444 m_lastColliders.Add(localID);
4445 }
4446 // remove things that ended colliding from the last colliders list
4447 foreach (uint localID in endedColliders)
4448 {
4449 m_lastColliders.Remove(localID);
4450 }
4451
4452 if (soundinfolist.Count > 0)
4453 CollisionSounds.AvatarCollisionSound(this, soundinfolist);
4454 }
4455
4456 foreach (SceneObjectGroup att in GetAttachments())
4457 {
4458 SendCollisionEvent(att, scriptEvents.collision_start, startedColliders, m_scene.EventManager.TriggerScriptCollidingStart);
4459 SendCollisionEvent(att, scriptEvents.collision , m_lastColliders , m_scene.EventManager.TriggerScriptColliding);
4460 SendCollisionEvent(att, scriptEvents.collision_end , endedColliders , m_scene.EventManager.TriggerScriptCollidingEnd);
4461
4462 if (startedColliders.Contains(0))
4463 SendLandCollisionEvent(att, scriptEvents.land_collision_start, m_scene.EventManager.TriggerScriptLandCollidingStart);
4464 if (m_lastColliders.Contains(0))
4465 SendLandCollisionEvent(att, scriptEvents.land_collision, m_scene.EventManager.TriggerScriptLandColliding);
4466 if (endedColliders.Contains(0))
4467 SendLandCollisionEvent(att, scriptEvents.land_collision_end, m_scene.EventManager.TriggerScriptLandCollidingEnd);
4468 }
4469 }
4470 finally
4471 {
4472 m_collisionEventFlag = false;
4473 }
4474 }
4475
4036 private void TeleportFlagsDebug() { 4476 private void TeleportFlagsDebug() {
4037 4477
4038 // Some temporary debugging help to show all the TeleportFlags we have... 4478 // Some temporary debugging help to show all the TeleportFlags we have...
@@ -4057,6 +4497,5 @@ namespace OpenSim.Region.Framework.Scenes
4057 m_log.InfoFormat("[SCENE PRESENCE]: TELEPORT ******************"); 4497 m_log.InfoFormat("[SCENE PRESENCE]: TELEPORT ******************");
4058 4498
4059 } 4499 }
4060
4061 } 4500 }
4062} 4501}
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 96317c3..756b1f4 100644
--- a/OpenSim/Region/Framework/Scenes/SimStatsReporter.cs
+++ b/OpenSim/Region/Framework/Scenes/SimStatsReporter.cs
@@ -164,7 +164,7 @@ namespace OpenSim.Region.Framework.Scenes
164 164
165 // saved last reported value so there is something available for llGetRegionFPS 165 // saved last reported value so there is something available for llGetRegionFPS
166 private float lastReportedSimFPS; 166 private float lastReportedSimFPS;
167 private float[] lastReportedSimStats = new float[22]; 167 private float[] lastReportedSimStats = new float[23];
168 private float m_pfps; 168 private float m_pfps;
169 169
170 /// <summary> 170 /// <summary>
@@ -178,12 +178,13 @@ namespace OpenSim.Region.Framework.Scenes
178 private int m_objectUpdates; 178 private int m_objectUpdates;
179 179
180 private int m_frameMS; 180 private int m_frameMS;
181 private int m_spareMS; 181
182 private int m_netMS; 182 private int m_netMS;
183 private int m_agentMS; 183 private int m_agentMS;
184 private int m_physicsMS; 184 private int m_physicsMS;
185 private int m_imageMS; 185 private int m_imageMS;
186 private int m_otherMS; 186 private int m_otherMS;
187 private int m_sleeptimeMS;
187 188
188//Ckrinke: (3-21-08) Comment out to remove a compiler warning. Bring back into play when needed. 189//Ckrinke: (3-21-08) Comment out to remove a compiler warning. Bring back into play when needed.
189//Ckrinke private int m_scriptMS = 0; 190//Ckrinke private int m_scriptMS = 0;
@@ -260,7 +261,7 @@ namespace OpenSim.Region.Framework.Scenes
260 261
261 private void statsHeartBeat(object sender, EventArgs e) 262 private void statsHeartBeat(object sender, EventArgs e)
262 { 263 {
263 SimStatsPacket.StatBlock[] sb = new SimStatsPacket.StatBlock[22]; 264 SimStatsPacket.StatBlock[] sb = new SimStatsPacket.StatBlock[23];
264 SimStatsPacket.RegionBlock rb = new SimStatsPacket.RegionBlock(); 265 SimStatsPacket.RegionBlock rb = new SimStatsPacket.RegionBlock();
265 266
266 // Know what's not thread safe in Mono... modifying timers. 267 // Know what's not thread safe in Mono... modifying timers.
@@ -298,6 +299,35 @@ namespace OpenSim.Region.Framework.Scenes
298 physfps = 0; 299 physfps = 0;
299 300
300#endregion 301#endregion
302 float factor = 1 / m_statsUpdateFactor;
303
304 if (reportedFPS <= 0)
305 reportedFPS = 1;
306
307 float perframe = 1.0f / (float)reportedFPS;
308
309 float TotalFrameTime = m_frameMS * perframe;
310
311 float targetframetime = 1100.0f / (float)m_nominalReportedFps;
312
313 float sparetime;
314 float sleeptime;
315
316 if (TotalFrameTime > targetframetime)
317 {
318 sparetime = 0;
319 sleeptime = 0;
320 }
321 else
322 {
323 sparetime = m_frameMS - m_physicsMS - m_agentMS;
324 sparetime *= perframe;
325 if (sparetime < 0)
326 sparetime = 0;
327 else if (sparetime > TotalFrameTime)
328 sparetime = TotalFrameTime;
329 sleeptime = m_sleeptimeMS * perframe;
330 }
301 331
302 m_rootAgents = m_scene.SceneGraph.GetRootAgentCount(); 332 m_rootAgents = m_scene.SceneGraph.GetRootAgentCount();
303 m_childAgents = m_scene.SceneGraph.GetChildAgentCount(); 333 m_childAgents = m_scene.SceneGraph.GetChildAgentCount();
@@ -309,25 +339,15 @@ namespace OpenSim.Region.Framework.Scenes
309 // so that stat numbers are always consistent. 339 // so that stat numbers are always consistent.
310 CheckStatSanity(); 340 CheckStatSanity();
311 341
312 //Our time dilation is 0.91 when we're running a full speed, 342 // other MS is actually simulation time
313 // therefore to make sure we get an appropriate range, 343 // m_otherMS = m_frameMS - m_physicsMS - m_imageMS - m_netMS - m_agentMS;
314 // we have to factor in our error. (0.10f * statsUpdateFactor) 344 // m_imageMS m_netMS are not included in m_frameMS
315 // multiplies the fix for the error times the amount of times it'll occur a second
316 // / 10 divides the value by the number of times the sim heartbeat runs (10fps)
317 // Then we divide the whole amount by the amount of seconds pass in between stats updates.
318
319 // 'statsUpdateFactor' is how often stats packets are sent in seconds. Used below to change
320 // values to X-per-second values.
321 345
322 uint thisFrame = m_scene.Frame; 346 m_otherMS = m_frameMS - m_physicsMS - m_agentMS - m_sleeptimeMS;
323 float framesUpdated = (float)(thisFrame - m_lastUpdateFrame) * m_reportedFpsCorrectionFactor; 347 if (m_otherMS < 0)
324 m_lastUpdateFrame = thisFrame; 348 m_otherMS = 0;
325 349
326 // Avoid div-by-zero if somehow we've not updated any frames. 350 for (int i = 0; i < 23; i++)
327 if (framesUpdated == 0)
328 framesUpdated = 1;
329
330 for (int i = 0; i < 22; i++)
331 { 351 {
332 sb[i] = new SimStatsPacket.StatBlock(); 352 sb[i] = new SimStatsPacket.StatBlock();
333 } 353 }
@@ -357,19 +377,19 @@ namespace OpenSim.Region.Framework.Scenes
357 sb[7].StatValue = m_activePrim; 377 sb[7].StatValue = m_activePrim;
358 378
359 sb[8].StatID = (uint)Stats.FrameMS; 379 sb[8].StatID = (uint)Stats.FrameMS;
360 sb[8].StatValue = m_frameMS / framesUpdated; 380 sb[8].StatValue = TotalFrameTime;
361 381
362 sb[9].StatID = (uint)Stats.NetMS; 382 sb[9].StatID = (uint)Stats.NetMS;
363 sb[9].StatValue = m_netMS / framesUpdated; 383 sb[9].StatValue = m_netMS * perframe;
364 384
365 sb[10].StatID = (uint)Stats.PhysicsMS; 385 sb[10].StatID = (uint)Stats.PhysicsMS;
366 sb[10].StatValue = m_physicsMS / framesUpdated; 386 sb[10].StatValue = m_physicsMS * perframe;
367 387
368 sb[11].StatID = (uint)Stats.ImageMS ; 388 sb[11].StatID = (uint)Stats.ImageMS ;
369 sb[11].StatValue = m_imageMS / framesUpdated; 389 sb[11].StatValue = m_imageMS * perframe;
370 390
371 sb[12].StatID = (uint)Stats.OtherMS; 391 sb[12].StatID = (uint)Stats.OtherMS;
372 sb[12].StatValue = m_otherMS / framesUpdated; 392 sb[12].StatValue = m_otherMS * perframe;
373 393
374 sb[13].StatID = (uint)Stats.InPacketsPerSecond; 394 sb[13].StatID = (uint)Stats.InPacketsPerSecond;
375 sb[13].StatValue = (m_inPacketsPerSecond / m_statsUpdateFactor); 395 sb[13].StatValue = (m_inPacketsPerSecond / m_statsUpdateFactor);
@@ -381,7 +401,7 @@ namespace OpenSim.Region.Framework.Scenes
381 sb[15].StatValue = m_unAckedBytes; 401 sb[15].StatValue = m_unAckedBytes;
382 402
383 sb[16].StatID = (uint)Stats.AgentMS; 403 sb[16].StatID = (uint)Stats.AgentMS;
384 sb[16].StatValue = m_agentMS / framesUpdated; 404 sb[16].StatValue = m_agentMS * perframe;
385 405
386 sb[17].StatID = (uint)Stats.PendingDownloads; 406 sb[17].StatID = (uint)Stats.PendingDownloads;
387 sb[17].StatValue = m_pendingDownloads; 407 sb[17].StatValue = m_pendingDownloads;
@@ -396,7 +416,10 @@ namespace OpenSim.Region.Framework.Scenes
396 sb[20].StatValue = m_scriptLinesPerSecond / m_statsUpdateFactor; 416 sb[20].StatValue = m_scriptLinesPerSecond / m_statsUpdateFactor;
397 417
398 sb[21].StatID = (uint)Stats.SimSpareMs; 418 sb[21].StatID = (uint)Stats.SimSpareMs;
399 sb[21].StatValue = m_spareMS / framesUpdated; 419 sb[21].StatValue = sparetime;
420
421 sb[22].StatID = (uint)Stats.SimSleepMs;
422 sb[22].StatValue = sleeptime;
400 423
401 for (int i = 0; i < 22; i++) 424 for (int i = 0; i < 22; i++)
402 { 425 {
@@ -415,27 +438,31 @@ namespace OpenSim.Region.Framework.Scenes
415 } 438 }
416 439
417 // Extra statistics that aren't currently sent to clients 440 // Extra statistics that aren't currently sent to clients
418 lock (m_lastReportedExtraSimStats) 441 if (m_scene.PhysicsScene != null)
419 { 442 {
420 m_lastReportedExtraSimStats[LastReportedObjectUpdateStatName] = m_objectUpdates / m_statsUpdateFactor; 443 lock (m_lastReportedExtraSimStats)
421
422 Dictionary<string, float> physicsStats = m_scene.PhysicsScene.GetStats();
423
424 if (physicsStats != null)
425 { 444 {
426 foreach (KeyValuePair<string, float> tuple in physicsStats) 445 m_lastReportedExtraSimStats[LastReportedObjectUpdateStatName] = m_objectUpdates / m_statsUpdateFactor;
446
447 Dictionary<string, float> physicsStats = m_scene.PhysicsScene.GetStats();
448
449 if (physicsStats != null)
427 { 450 {
428 // FIXME: An extremely dirty hack to divide MS stats per frame rather than per second 451 foreach (KeyValuePair<string, float> tuple in physicsStats)
429 // Need to change things so that stats source can indicate whether they are per second or 452 {
430 // per frame. 453 // FIXME: An extremely dirty hack to divide MS stats per frame rather than per second
431 if (tuple.Key.EndsWith("MS")) 454 // Need to change things so that stats source can indicate whether they are per second or
432 m_lastReportedExtraSimStats[tuple.Key] = tuple.Value / framesUpdated; 455 // per frame.
433 else 456 if (tuple.Key.EndsWith("MS"))
434 m_lastReportedExtraSimStats[tuple.Key] = tuple.Value / m_statsUpdateFactor; 457 m_lastReportedExtraSimStats[tuple.Key] = tuple.Value * perframe;
458 else
459 m_lastReportedExtraSimStats[tuple.Key] = tuple.Value / m_statsUpdateFactor;
460 }
435 } 461 }
436 } 462 }
437 } 463 }
438 464
465// LastReportedObjectUpdates = m_objectUpdates / m_statsUpdateFactor;
439 ResetValues(); 466 ResetValues();
440 } 467 }
441 } 468 }
@@ -458,7 +485,8 @@ namespace OpenSim.Region.Framework.Scenes
458 m_physicsMS = 0; 485 m_physicsMS = 0;
459 m_imageMS = 0; 486 m_imageMS = 0;
460 m_otherMS = 0; 487 m_otherMS = 0;
461 m_spareMS = 0; 488// m_spareMS = 0;
489 m_sleeptimeMS = 0;
462 490
463//Ckrinke This variable is not used, so comment to remove compiler warning until it is used. 491//Ckrinke This variable is not used, so comment to remove compiler warning until it is used.
464//Ckrinke m_scriptMS = 0; 492//Ckrinke m_scriptMS = 0;
@@ -537,11 +565,6 @@ namespace OpenSim.Region.Framework.Scenes
537 m_frameMS += ms; 565 m_frameMS += ms;
538 } 566 }
539 567
540 public void AddSpareMS(int ms)
541 {
542 m_spareMS += ms;
543 }
544
545 public void addNetMS(int ms) 568 public void addNetMS(int ms)
546 { 569 {
547 m_netMS += ms; 570 m_netMS += ms;
@@ -567,6 +590,11 @@ namespace OpenSim.Region.Framework.Scenes
567 m_otherMS += ms; 590 m_otherMS += ms;
568 } 591 }
569 592
593 public void addSleepMS(int ms)
594 {
595 m_sleeptimeMS += ms;
596 }
597
570 public void AddPendingDownloads(int count) 598 public void AddPendingDownloads(int count)
571 { 599 {
572 m_pendingDownloads += count; 600 m_pendingDownloads += count;
diff --git a/OpenSim/Region/Framework/Scenes/Tests/SceneObjectUndoRedoTests.cs b/OpenSim/Region/Framework/Scenes/Tests/SceneObjectUndoRedoTests.cs
deleted file mode 100644
index c93562d..0000000
--- a/OpenSim/Region/Framework/Scenes/Tests/SceneObjectUndoRedoTests.cs
+++ /dev/null
@@ -1,157 +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 SceneObjectGroup g1 = SceneHelpers.AddSceneObject(scene);
56
57 // TODO: It happens to be the case that we are not storing undo states for SOPs which are not yet in a SOG,
58 // which is the way that AddSceneObject() sets up the object (i.e. it creates the SOP first). However,
59 // this is somewhat by chance. Really, we shouldn't be storing undo states at all if the object is not
60 // in a scene.
61 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(0));
62
63 g1.GroupResize(firstSize);
64 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(1));
65
66 g1.GroupResize(secondSize);
67 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(2));
68
69 g1.RootPart.Undo();
70 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(1));
71 Assert.That(g1.GroupScale, Is.EqualTo(firstSize));
72
73 g1.RootPart.Redo();
74 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(2));
75 Assert.That(g1.GroupScale, Is.EqualTo(secondSize));
76 }
77
78 [Test]
79 public void TestUndoLimit()
80 {
81 TestHelpers.InMethod();
82
83 Vector3 firstSize = new Vector3(2, 3, 4);
84 Vector3 secondSize = new Vector3(5, 6, 7);
85 Vector3 thirdSize = new Vector3(8, 9, 10);
86 Vector3 fourthSize = new Vector3(11, 12, 13);
87
88 Scene scene = new SceneHelpers().SetupScene();
89 scene.MaxUndoCount = 2;
90 SceneObjectGroup g1 = SceneHelpers.AddSceneObject(scene);
91
92 g1.GroupResize(firstSize);
93 g1.GroupResize(secondSize);
94 g1.GroupResize(thirdSize);
95 g1.GroupResize(fourthSize);
96
97 g1.RootPart.Undo();
98 g1.RootPart.Undo();
99 g1.RootPart.Undo();
100
101 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(0));
102 Assert.That(g1.GroupScale, Is.EqualTo(secondSize));
103 }
104
105 [Test]
106 public void TestUndoBeyondAvailable()
107 {
108 TestHelpers.InMethod();
109
110 Vector3 newSize = new Vector3(2, 3, 4);
111
112 Scene scene = new SceneHelpers().SetupScene();
113 SceneObjectGroup g1 = SceneHelpers.AddSceneObject(scene);
114 Vector3 originalSize = g1.GroupScale;
115
116 g1.RootPart.Undo();
117
118 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(0));
119 Assert.That(g1.GroupScale, Is.EqualTo(originalSize));
120
121 g1.GroupResize(newSize);
122 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(1));
123 Assert.That(g1.GroupScale, Is.EqualTo(newSize));
124
125 g1.RootPart.Undo();
126 g1.RootPart.Undo();
127
128 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(0));
129 Assert.That(g1.GroupScale, Is.EqualTo(originalSize));
130 }
131
132 [Test]
133 public void TestRedoBeyondAvailable()
134 {
135 TestHelpers.InMethod();
136
137 Vector3 newSize = new Vector3(2, 3, 4);
138
139 Scene scene = new SceneHelpers().SetupScene();
140 SceneObjectGroup g1 = SceneHelpers.AddSceneObject(scene);
141 Vector3 originalSize = g1.GroupScale;
142
143 g1.RootPart.Redo();
144
145 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(0));
146 Assert.That(g1.GroupScale, Is.EqualTo(originalSize));
147
148 g1.GroupResize(newSize);
149 g1.RootPart.Undo();
150 g1.RootPart.Redo();
151 g1.RootPart.Redo();
152
153 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(1));
154 Assert.That(g1.GroupScale, Is.EqualTo(newSize));
155 }
156 }
157} \ 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 28cd09f..b5ef7b0 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;