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.cs422
-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.cs320
-rw-r--r--OpenSim/Region/Framework/Scenes/Scene.PacketHandlers.cs95
-rw-r--r--OpenSim/Region/Framework/Scenes/Scene.cs787
-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.cs484
-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.cs1363
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneObjectPart.cs1701
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs782
-rw-r--r--OpenSim/Region/Framework/Scenes/ScenePresence.cs583
-rw-r--r--OpenSim/Region/Framework/Scenes/Serialization/SceneObjectSerializer.cs121
-rw-r--r--OpenSim/Region/Framework/Scenes/SimStatsReporter.cs93
-rw-r--r--OpenSim/Region/Framework/Scenes/UndoState.cs367
-rw-r--r--OpenSim/Region/Framework/Scenes/UuidGatherer.cs4
23 files changed, 6741 insertions, 1951 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 6dea2f0..7cb3811 100644
--- a/OpenSim/Region/Framework/Scenes/EventManager.cs
+++ b/OpenSim/Region/Framework/Scenes/EventManager.cs
@@ -59,8 +59,12 @@ namespace OpenSim.Region.Framework.Scenes
59 59
60 public delegate void OnTerrainTickDelegate(); 60 public delegate void OnTerrainTickDelegate();
61 61
62 public delegate void OnTerrainUpdateDelegate();
63
62 public event OnTerrainTickDelegate OnTerrainTick; 64 public event OnTerrainTickDelegate OnTerrainTick;
63 65
66 public event OnTerrainUpdateDelegate OnTerrainUpdate;
67
64 public delegate void OnBackupDelegate(ISimulationDataService datastore, bool forceBackup); 68 public delegate void OnBackupDelegate(ISimulationDataService datastore, bool forceBackup);
65 69
66 public event OnBackupDelegate OnBackup; 70 public event OnBackupDelegate OnBackup;
@@ -905,6 +909,26 @@ namespace OpenSim.Region.Framework.Scenes
905 } 909 }
906 } 910 }
907 } 911 }
912 public void TriggerTerrainUpdate()
913 {
914 OnTerrainUpdateDelegate handlerTerrainUpdate = OnTerrainUpdate;
915 if (handlerTerrainUpdate != null)
916 {
917 foreach (OnTerrainUpdateDelegate d in handlerTerrainUpdate.GetInvocationList())
918 {
919 try
920 {
921 d();
922 }
923 catch (Exception e)
924 {
925 m_log.ErrorFormat(
926 "[EVENT MANAGER]: Delegate for TriggerTerrainUpdate failed - continuing. {0} {1}",
927 e.Message, e.StackTrace);
928 }
929 }
930 }
931 }
908 932
909 public void TriggerTerrainTick() 933 public void TriggerTerrainTick()
910 { 934 {
@@ -1195,6 +1219,7 @@ namespace OpenSim.Region.Framework.Scenes
1195 m_log.ErrorFormat( 1219 m_log.ErrorFormat(
1196 "[EVENT MANAGER]: Delegate for TriggerRemoveScript failed - continuing. {0} {1}", 1220 "[EVENT MANAGER]: Delegate for TriggerRemoveScript failed - continuing. {0} {1}",
1197 e.Message, e.StackTrace); 1221 e.Message, e.StackTrace);
1222 m_log.ErrorFormat(Environment.StackTrace);
1198 } 1223 }
1199 } 1224 }
1200 } 1225 }
diff --git a/OpenSim/Region/Framework/Scenes/KeyframeMotion.cs b/OpenSim/Region/Framework/Scenes/KeyframeMotion.cs
new file mode 100644
index 0000000..b7b0d27
--- /dev/null
+++ b/OpenSim/Region/Framework/Scenes/KeyframeMotion.cs
@@ -0,0 +1,422 @@
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 = 1,
42 Rotation = 2
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_basePosition;
57 private Quaternion m_baseRotation;
58 private Vector3 m_serializedPosition;
59
60 private Keyframe m_currentFrame;
61 private List<Keyframe> m_frames = new List<Keyframe>();
62
63 private Keyframe[] m_keyframes;
64
65 [NonSerialized()]
66 protected Timer m_timer = new Timer();
67
68 [NonSerialized()]
69 private SceneObjectGroup m_group;
70
71 private PlayMode m_mode = PlayMode.Forward;
72 private DataFormat m_data = DataFormat.Translation | DataFormat.Rotation;
73
74 private bool m_running = false;
75 [NonSerialized()]
76 private bool m_selected = false;
77
78 private int m_iterations = 0;
79
80 private const double timerInterval = 50.0;
81
82 public DataFormat Data
83 {
84 get { return m_data; }
85 }
86
87 public bool Selected
88 {
89 set
90 {
91 if (value)
92 {
93 // Once we're let go, recompute positions
94 if (m_selected)
95 UpdateSceneObject(m_group);
96 }
97 else
98 {
99 // Save selection position in case we get moved
100 if (!m_selected)
101 m_serializedPosition = m_group.AbsolutePosition;
102 }
103 m_selected = value; }
104 }
105
106 public static KeyframeMotion FromData(SceneObjectGroup grp, Byte[] data)
107 {
108 MemoryStream ms = new MemoryStream(data);
109
110 BinaryFormatter fmt = new BinaryFormatter();
111
112 KeyframeMotion newMotion = (KeyframeMotion)fmt.Deserialize(ms);
113
114 // This will be started when position is updated
115 newMotion.m_timer = new Timer();
116 newMotion.m_timer.Interval = (int)timerInterval;
117 newMotion.m_timer.AutoReset = true;
118 newMotion.m_timer.Elapsed += newMotion.OnTimer;
119
120 return newMotion;
121 }
122
123 public void UpdateSceneObject(SceneObjectGroup grp)
124 {
125 m_group = grp;
126 Vector3 offset = grp.AbsolutePosition - m_serializedPosition;
127
128 m_basePosition += offset;
129 m_currentFrame.Position += offset;
130 for (int i = 0 ; i < m_frames.Count ; i++)
131 {
132 Keyframe k = m_frames[i];
133 k.Position += offset;
134 m_frames[i] = k;
135 }
136
137 if (m_running)
138 Start();
139 }
140
141 public KeyframeMotion(SceneObjectGroup grp, PlayMode mode, DataFormat data)
142 {
143 m_mode = mode;
144 m_data = data;
145
146 m_group = grp;
147 m_basePosition = grp.AbsolutePosition;
148 m_baseRotation = grp.GroupRotation;
149
150 m_timer.Interval = (int)timerInterval;
151 m_timer.AutoReset = true;
152 m_timer.Elapsed += OnTimer;
153 }
154
155 public void SetKeyframes(Keyframe[] frames)
156 {
157 m_keyframes = frames;
158 }
159
160 public void Start()
161 {
162 if (m_keyframes.Length > 0)
163 m_timer.Start();
164 m_running = true;
165 }
166
167 public void Stop()
168 {
169 // Failed object creation
170 if (m_timer == null)
171 return;
172 m_timer.Stop();
173
174 m_basePosition = m_group.AbsolutePosition;
175 m_baseRotation = m_group.GroupRotation;
176
177 m_group.RootPart.Velocity = Vector3.Zero;
178 m_group.RootPart.UpdateAngularVelocity(Vector3.Zero);
179 m_group.SendGroupRootTerseUpdate();
180
181 m_frames.Clear();
182 m_running = false;
183 }
184
185 public void Pause()
186 {
187 m_group.RootPart.Velocity = Vector3.Zero;
188 m_group.RootPart.UpdateAngularVelocity(Vector3.Zero);
189 m_group.SendGroupRootTerseUpdate();
190
191 m_timer.Stop();
192 m_running = false;
193 }
194
195 private void GetNextList()
196 {
197 m_frames.Clear();
198 Vector3 pos = m_basePosition;
199 Quaternion rot = m_baseRotation;
200
201 if (m_mode == PlayMode.Loop || m_mode == PlayMode.PingPong || m_iterations == 0)
202 {
203 int direction = 1;
204 if (m_mode == PlayMode.Reverse || ((m_mode == PlayMode.PingPong) && ((m_iterations & 1) != 0)))
205 direction = -1;
206
207 int start = 0;
208 int end = m_keyframes.Length;
209// if (m_mode == PlayMode.PingPong && m_keyframes.Length > 1)
210// end = m_keyframes.Length - 1;
211
212 if (direction < 0)
213 {
214 start = m_keyframes.Length - 1;
215 end = -1;
216// if (m_mode == PlayMode.PingPong && m_keyframes.Length > 1)
217// end = 0;
218 }
219
220 for (int i = start; i != end ; i += direction)
221 {
222 Keyframe k = m_keyframes[i];
223
224 if (k.Position.HasValue)
225 k.Position = (k.Position * direction) + pos;
226 else
227 k.Position = pos;
228
229 k.StartRotation = rot;
230 if (k.Rotation.HasValue)
231 {
232 if (direction == -1)
233 k.Rotation = Quaternion.Conjugate((Quaternion)k.Rotation);
234 k.Rotation = rot * k.Rotation;
235 }
236 else
237 {
238 k.Rotation = rot;
239 }
240
241 float angle = 0;
242
243 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;
244 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;
245 float aa_bb = aa * bb;
246
247 if (aa_bb == 0)
248 {
249 angle = 0;
250 }
251 else
252 {
253 float ab = k.StartRotation.X * ((Quaternion)k.Rotation).X +
254 k.StartRotation.Y * ((Quaternion)k.Rotation).Y +
255 k.StartRotation.Z * ((Quaternion)k.Rotation).Z +
256 k.StartRotation.W * ((Quaternion)k.Rotation).W;
257 float q = (ab * ab) / aa_bb;
258
259 if (q > 1.0f)
260 {
261 angle = 0;
262 }
263 else
264 {
265 angle = (float)Math.Acos(2 * q - 1);
266 }
267 }
268
269 k.AngularVelocity = (new Vector3(0, 0, 1) * (Quaternion)k.Rotation) * (angle / (k.TimeMS / 1000));
270 k.TimeTotal = k.TimeMS;
271
272 m_frames.Add(k);
273
274 pos = (Vector3)k.Position;
275 rot = (Quaternion)k.Rotation;
276 }
277
278 m_basePosition = pos;
279 m_baseRotation = rot;
280
281 m_iterations++;
282 }
283 }
284
285 protected void OnTimer(object sender, ElapsedEventArgs e)
286 {
287 if (m_frames.Count == 0)
288 {
289 GetNextList();
290
291 if (m_frames.Count == 0)
292 {
293 Stop();
294 return;
295 }
296
297 m_currentFrame = m_frames[0];
298 }
299
300 if (m_selected)
301 {
302 if (m_group.RootPart.Velocity != Vector3.Zero)
303 {
304 m_group.RootPart.Velocity = Vector3.Zero;
305 m_group.SendGroupRootTerseUpdate();
306 }
307 return;
308 }
309
310 // Do the frame processing
311 double steps = (double)m_currentFrame.TimeMS / timerInterval;
312 float complete = ((float)m_currentFrame.TimeTotal - (float)m_currentFrame.TimeMS) / (float)m_currentFrame.TimeTotal;
313
314 if (steps <= 1.0)
315 {
316 m_currentFrame.TimeMS = 0;
317
318 m_group.AbsolutePosition = (Vector3)m_currentFrame.Position;
319 m_group.UpdateGroupRotationR((Quaternion)m_currentFrame.Rotation);
320 }
321 else
322 {
323 Vector3 v = (Vector3)m_currentFrame.Position - m_group.AbsolutePosition;
324 Vector3 motionThisFrame = v / (float)steps;
325 v = v * 1000 / m_currentFrame.TimeMS;
326
327 bool update = false;
328
329 if (Vector3.Mag(motionThisFrame) >= 0.05f)
330 {
331 m_group.AbsolutePosition += motionThisFrame;
332 m_group.RootPart.Velocity = v;
333 update = true;
334 }
335
336 if ((Quaternion)m_currentFrame.Rotation != m_group.GroupRotation)
337 {
338 Quaternion current = m_group.GroupRotation;
339
340 Quaternion step = Quaternion.Slerp(m_currentFrame.StartRotation, (Quaternion)m_currentFrame.Rotation, complete);
341
342 float angle = 0;
343
344 float aa = current.X * current.X + current.Y * current.Y + current.Z * current.Z + current.W * current.W;
345 float bb = step.X * step.X + step.Y * step.Y + step.Z * step.Z + step.W * step.W;
346 float aa_bb = aa * bb;
347
348 if (aa_bb == 0)
349 {
350 angle = 0;
351 }
352 else
353 {
354 float ab = current.X * step.X +
355 current.Y * step.Y +
356 current.Z * step.Z +
357 current.W * step.W;
358 float q = (ab * ab) / aa_bb;
359
360 if (q > 1.0f)
361 {
362 angle = 0;
363 }
364 else
365 {
366 angle = (float)Math.Acos(2 * q - 1);
367 }
368 }
369
370 if (angle > 0.01f)
371 {
372 m_group.UpdateGroupRotationR(step);
373 //m_group.RootPart.UpdateAngularVelocity(m_currentFrame.AngularVelocity / 2);
374 update = true;
375 }
376 }
377
378 if (update)
379 m_group.SendGroupRootTerseUpdate();
380 }
381
382 m_currentFrame.TimeMS -= (int)timerInterval;
383
384 if (m_currentFrame.TimeMS <= 0)
385 {
386 m_group.RootPart.Velocity = Vector3.Zero;
387 m_group.RootPart.UpdateAngularVelocity(Vector3.Zero);
388 m_group.SendGroupRootTerseUpdate();
389
390 m_frames.RemoveAt(0);
391 if (m_frames.Count > 0)
392 m_currentFrame = m_frames[0];
393 }
394 }
395
396 public Byte[] Serialize()
397 {
398 MemoryStream ms = new MemoryStream();
399 m_timer.Stop();
400
401 BinaryFormatter fmt = new BinaryFormatter();
402 SceneObjectGroup tmp = m_group;
403 m_group = null;
404 m_serializedPosition = tmp.AbsolutePosition;
405 fmt.Serialize(ms, this);
406 m_group = tmp;
407 return ms.ToArray();
408 }
409
410 public void CrossingFailure()
411 {
412 // The serialization has stopped the timer, so let's wait a moment
413 // then retry the crossing. We'll get back here if it fails.
414 Util.FireAndForget(delegate (object x)
415 {
416 Thread.Sleep(60000);
417 if (m_running)
418 m_timer.Start();
419 });
420 }
421 }
422}
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 7e31d60..0b73df5 100644
--- a/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs
+++ b/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs
@@ -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,9 +1983,6 @@ namespace OpenSim.Region.Framework.Scenes
1940 1983
1941 SceneObjectGroup grp = part.ParentGroup; 1984 SceneObjectGroup grp = part.ParentGroup;
1942 1985
1943 deleteIDs.Add(localID);
1944 deleteGroups.Add(grp);
1945
1946 if (remoteClient == null) 1986 if (remoteClient == null)
1947 { 1987 {
1948 // Autoreturn has a null client. Nothing else does. So 1988 // Autoreturn has a null client. Nothing else does. So
@@ -1959,81 +1999,193 @@ namespace OpenSim.Region.Framework.Scenes
1959 } 1999 }
1960 else 2000 else
1961 { 2001 {
1962 if (!Permissions.CanTakeCopyObject(grp.UUID, remoteClient.AgentId)) 2002 if (action == DeRezAction.TakeCopy)
2003 {
2004 if (!Permissions.CanTakeCopyObject(grp.UUID, remoteClient.AgentId))
2005 permissionToTakeCopy = false;
2006 }
2007 else
2008 {
1963 permissionToTakeCopy = false; 2009 permissionToTakeCopy = false;
1964 2010 }
1965 if (!Permissions.CanTakeObject(grp.UUID, remoteClient.AgentId)) 2011 if (!Permissions.CanTakeObject(grp.UUID, remoteClient.AgentId))
1966 permissionToTake = false; 2012 permissionToTake = false;
1967 2013
1968 if (!Permissions.CanDeleteObject(grp.UUID, remoteClient.AgentId)) 2014 if (!Permissions.CanDeleteObject(grp.UUID, remoteClient.AgentId))
1969 permissionToDelete = false; 2015 permissionToDelete = false;
1970 } 2016 }
1971 }
1972 2017
1973 // Handle god perms 2018 // Handle god perms
1974 if ((remoteClient != null) && Permissions.IsGod(remoteClient.AgentId)) 2019 if ((remoteClient != null) && Permissions.IsGod(remoteClient.AgentId))
1975 { 2020 {
1976 permissionToTake = true; 2021 permissionToTake = true;
1977 permissionToTakeCopy = true; 2022 permissionToTakeCopy = true;
1978 permissionToDelete = true; 2023 permissionToDelete = true;
1979 } 2024 }
1980 2025
1981 // If we're re-saving, we don't even want to delete 2026 // If we're re-saving, we don't even want to delete
1982 if (action == DeRezAction.SaveToExistingUserInventoryItem) 2027 if (action == DeRezAction.SaveToExistingUserInventoryItem)
1983 permissionToDelete = false; 2028 permissionToDelete = false;
1984 2029
1985 // if we want to take a copy, we also don't want to delete 2030 // if we want to take a copy, we also don't want to delete
1986 // Note: after this point, the permissionToTakeCopy flag 2031 // Note: after this point, the permissionToTakeCopy flag
1987 // becomes irrelevant. It already includes the permissionToTake 2032 // becomes irrelevant. It already includes the permissionToTake
1988 // permission and after excluding no copy items here, we can 2033 // permission and after excluding no copy items here, we can
1989 // just use that. 2034 // just use that.
1990 if (action == DeRezAction.TakeCopy) 2035 if (action == DeRezAction.TakeCopy)
1991 { 2036 {
1992 // If we don't have permission, stop right here 2037 // If we don't have permission, stop right here
1993 if (!permissionToTakeCopy) 2038 if (!permissionToTakeCopy)
1994 return; 2039 return;
1995 2040
1996 permissionToTake = true; 2041 permissionToTake = true;
1997 // Don't delete 2042 // Don't delete
1998 permissionToDelete = false; 2043 permissionToDelete = false;
1999 } 2044 }
2000 2045
2001 if (action == DeRezAction.Return) 2046 if (action == DeRezAction.Return)
2002 {
2003 if (remoteClient != null)
2004 { 2047 {
2005 if (Permissions.CanReturnObjects( 2048 if (remoteClient != null)
2006 null,
2007 remoteClient.AgentId,
2008 deleteGroups))
2009 { 2049 {
2010 permissionToTake = true; 2050 if (Permissions.CanReturnObjects(
2011 permissionToDelete = true; 2051 null,
2012 2052 remoteClient.AgentId,
2013 foreach (SceneObjectGroup g in deleteGroups) 2053 deleteGroups))
2014 { 2054 {
2015 AddReturn(g.OwnerID == g.GroupID ? g.LastOwnerID : g.OwnerID, g.Name, g.AbsolutePosition, "parcel owner return"); 2055 permissionToTake = true;
2056 permissionToDelete = true;
2057
2058 AddReturn(grp.OwnerID == grp.GroupID ? grp.LastOwnerID : grp.OwnerID, grp.Name, grp.AbsolutePosition, "parcel owner return");
2016 } 2059 }
2017 } 2060 }
2061 else // Auto return passes through here with null agent
2062 {
2063 permissionToTake = true;
2064 permissionToDelete = true;
2065 }
2018 } 2066 }
2019 else // Auto return passes through here with null agent 2067
2068 if (permissionToTake && (!permissionToDelete))
2069 takeGroups.Add(grp);
2070
2071 if (permissionToDelete)
2020 { 2072 {
2021 permissionToTake = true; 2073 if (permissionToTake)
2022 permissionToDelete = true; 2074 deleteGroups.Add(grp);
2075 deleteIDs.Add(grp.LocalId);
2023 } 2076 }
2024 } 2077 }
2025 2078
2026 if (permissionToTake && (action != DeRezAction.Delete || this.m_useTrashOnDelete)) 2079 SendKillObject(deleteIDs);
2080
2081 if (deleteGroups.Count > 0)
2027 { 2082 {
2083 foreach (SceneObjectGroup g in deleteGroups)
2084 deleteIDs.Remove(g.LocalId);
2085
2028 m_asyncSceneObjectDeleter.DeleteToInventory( 2086 m_asyncSceneObjectDeleter.DeleteToInventory(
2029 action, destinationID, deleteGroups, remoteClient, 2087 action, destinationID, deleteGroups, remoteClient,
2030 permissionToDelete); 2088 true);
2031 } 2089 }
2032 else if (permissionToDelete) 2090 if (takeGroups.Count > 0)
2091 {
2092 m_asyncSceneObjectDeleter.DeleteToInventory(
2093 action, destinationID, takeGroups, remoteClient,
2094 false);
2095 }
2096 if (deleteIDs.Count > 0)
2033 { 2097 {
2034 foreach (SceneObjectGroup g in deleteGroups) 2098 foreach (SceneObjectGroup g in deleteGroups)
2035 DeleteSceneObject(g, false); 2099 DeleteSceneObject(g, true);
2100 }
2101 }
2102
2103 public UUID attachObjectAssetStore(IClientAPI remoteClient, SceneObjectGroup grp, UUID AgentId, out UUID itemID)
2104 {
2105 itemID = UUID.Zero;
2106 if (grp != null)
2107 {
2108 Vector3 inventoryStoredPosition = new Vector3
2109 (((grp.AbsolutePosition.X > (int)Constants.RegionSize)
2110 ? 250
2111 : grp.AbsolutePosition.X)
2112 ,
2113 (grp.AbsolutePosition.X > (int)Constants.RegionSize)
2114 ? 250
2115 : grp.AbsolutePosition.X,
2116 grp.AbsolutePosition.Z);
2117
2118 Vector3 originalPosition = grp.AbsolutePosition;
2119
2120 grp.AbsolutePosition = inventoryStoredPosition;
2121
2122 string sceneObjectXml = SceneObjectSerializer.ToOriginalXmlFormat(grp);
2123
2124 grp.AbsolutePosition = originalPosition;
2125
2126 AssetBase asset = CreateAsset(
2127 grp.GetPartName(grp.LocalId),
2128 grp.GetPartDescription(grp.LocalId),
2129 (sbyte)AssetType.Object,
2130 Utils.StringToBytes(sceneObjectXml),
2131 remoteClient.AgentId);
2132 AssetService.Store(asset);
2133
2134 InventoryItemBase item = new InventoryItemBase();
2135 item.CreatorId = grp.RootPart.CreatorID.ToString();
2136 item.CreatorData = grp.RootPart.CreatorData;
2137 item.Owner = remoteClient.AgentId;
2138 item.ID = UUID.Random();
2139 item.AssetID = asset.FullID;
2140 item.Description = asset.Description;
2141 item.Name = asset.Name;
2142 item.AssetType = asset.Type;
2143 item.InvType = (int)InventoryType.Object;
2144
2145 InventoryFolderBase folder = InventoryService.GetFolderForType(remoteClient.AgentId, AssetType.Object);
2146 if (folder != null)
2147 item.Folder = folder.ID;
2148 else // oopsies
2149 item.Folder = UUID.Zero;
2150
2151 // Set up base perms properly
2152 uint permsBase = (uint)(PermissionMask.Move | PermissionMask.Copy | PermissionMask.Transfer | PermissionMask.Modify);
2153 permsBase &= grp.RootPart.BaseMask;
2154 permsBase |= (uint)PermissionMask.Move;
2155
2156 // Make sure we don't lock it
2157 grp.RootPart.NextOwnerMask |= (uint)PermissionMask.Move;
2158
2159 if ((remoteClient.AgentId != grp.RootPart.OwnerID) && Permissions.PropagatePermissions())
2160 {
2161 item.BasePermissions = permsBase & grp.RootPart.NextOwnerMask;
2162 item.CurrentPermissions = permsBase & grp.RootPart.NextOwnerMask;
2163 item.NextPermissions = permsBase & grp.RootPart.NextOwnerMask;
2164 item.EveryOnePermissions = permsBase & grp.RootPart.EveryoneMask & grp.RootPart.NextOwnerMask;
2165 item.GroupPermissions = permsBase & grp.RootPart.GroupMask & grp.RootPart.NextOwnerMask;
2166 }
2167 else
2168 {
2169 item.BasePermissions = permsBase;
2170 item.CurrentPermissions = permsBase & grp.RootPart.OwnerMask;
2171 item.NextPermissions = permsBase & grp.RootPart.NextOwnerMask;
2172 item.EveryOnePermissions = permsBase & grp.RootPart.EveryoneMask;
2173 item.GroupPermissions = permsBase & grp.RootPart.GroupMask;
2174 }
2175 item.CreationDate = Util.UnixTimeSinceEpoch();
2176
2177 // sets itemID so client can show item as 'attached' in inventory
2178 grp.FromItemID = item.ID;
2179
2180 if (AddInventoryItem(item))
2181 remoteClient.SendInventoryItemCreateUpdate(item, 0);
2182 else
2183 m_dialogModule.SendAlertToUser(remoteClient, "Operation failed");
2184
2185 itemID = item.ID;
2186 return item.AssetID;
2036 } 2187 }
2188 return UUID.Zero;
2037 } 2189 }
2038 2190
2039 /// <summary> 2191 /// <summary>
@@ -2163,6 +2315,9 @@ namespace OpenSim.Region.Framework.Scenes
2163 2315
2164 public void SetScriptRunning(IClientAPI controllingClient, UUID objectID, UUID itemID, bool running) 2316 public void SetScriptRunning(IClientAPI controllingClient, UUID objectID, UUID itemID, bool running)
2165 { 2317 {
2318 if (!Permissions.CanEditScript(itemID, objectID, controllingClient.AgentId))
2319 return;
2320
2166 SceneObjectPart part = GetSceneObjectPart(objectID); 2321 SceneObjectPart part = GetSceneObjectPart(objectID);
2167 if (part == null) 2322 if (part == null)
2168 return; 2323 return;
@@ -2219,7 +2374,10 @@ namespace OpenSim.Region.Framework.Scenes
2219 } 2374 }
2220 else 2375 else
2221 { 2376 {
2222 if (!Permissions.CanEditObject(sog.UUID, remoteClient.AgentId)) 2377 if (!Permissions.IsGod(remoteClient.AgentId) && sog.OwnerID != remoteClient.AgentId)
2378 continue;
2379
2380 if (!Permissions.CanTransferObject(sog.UUID, groupID))
2223 continue; 2381 continue;
2224 2382
2225 if (sog.GroupID != groupID) 2383 if (sog.GroupID != groupID)
diff --git a/OpenSim/Region/Framework/Scenes/Scene.PacketHandlers.cs b/OpenSim/Region/Framework/Scenes/Scene.PacketHandlers.cs
index 2701d6e..431b903 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,
diff --git a/OpenSim/Region/Framework/Scenes/Scene.cs b/OpenSim/Region/Framework/Scenes/Scene.cs
index c77457c..3a28d42 100644
--- a/OpenSim/Region/Framework/Scenes/Scene.cs
+++ b/OpenSim/Region/Framework/Scenes/Scene.cs
@@ -128,6 +128,7 @@ namespace OpenSim.Region.Framework.Scenes
128 // TODO: need to figure out how allow client agents but deny 128 // TODO: need to figure out how allow client agents but deny
129 // root agents when ACL denies access to root agent 129 // root agents when ACL denies access to root agent
130 public bool m_strictAccessControl = true; 130 public bool m_strictAccessControl = true;
131 public bool m_seeIntoBannedRegion = false;
131 public int MaxUndoCount = 5; 132 public int MaxUndoCount = 5;
132 133
133 // Using this for RegionReady module to prevent LoginsDisabled from changing under our feet; 134 // Using this for RegionReady module to prevent LoginsDisabled from changing under our feet;
@@ -144,12 +145,14 @@ namespace OpenSim.Region.Framework.Scenes
144 145
145 protected int m_splitRegionID; 146 protected int m_splitRegionID;
146 protected Timer m_restartWaitTimer = new Timer(); 147 protected Timer m_restartWaitTimer = new Timer();
148 protected Timer m_timerWatchdog = new Timer();
147 protected List<RegionInfo> m_regionRestartNotifyList = new List<RegionInfo>(); 149 protected List<RegionInfo> m_regionRestartNotifyList = new List<RegionInfo>();
148 protected List<RegionInfo> m_neighbours = new List<RegionInfo>(); 150 protected List<RegionInfo> m_neighbours = new List<RegionInfo>();
149 protected string m_simulatorVersion = "OpenSimulator Server"; 151 protected string m_simulatorVersion = "OpenSimulator Server";
150 protected ModuleLoader m_moduleLoader; 152 protected ModuleLoader m_moduleLoader;
151 protected AgentCircuitManager m_authenticateHandler; 153 protected AgentCircuitManager m_authenticateHandler;
152 protected SceneCommunicationService m_sceneGridService; 154 protected SceneCommunicationService m_sceneGridService;
155 protected ISnmpModule m_snmpService = null;
153 156
154 protected ISimulationDataService m_SimulationDataService; 157 protected ISimulationDataService m_SimulationDataService;
155 protected IEstateDataService m_EstateDataService; 158 protected IEstateDataService m_EstateDataService;
@@ -211,7 +214,7 @@ namespace OpenSim.Region.Framework.Scenes
211 private int m_update_events = 1; 214 private int m_update_events = 1;
212 private int m_update_backup = 200; 215 private int m_update_backup = 200;
213 private int m_update_terrain = 50; 216 private int m_update_terrain = 50;
214// private int m_update_land = 1; 217 private int m_update_land = 10;
215 private int m_update_coarse_locations = 50; 218 private int m_update_coarse_locations = 50;
216 219
217 private int agentMS; 220 private int agentMS;
@@ -224,13 +227,13 @@ namespace OpenSim.Region.Framework.Scenes
224 private int backupMS; 227 private int backupMS;
225 private int terrainMS; 228 private int terrainMS;
226 private int landMS; 229 private int landMS;
227 private int spareMS;
228 230
229 /// <summary> 231 /// <summary>
230 /// Tick at which the last frame was processed. 232 /// Tick at which the last frame was processed.
231 /// </summary> 233 /// </summary>
232 private int m_lastFrameTick; 234 private int m_lastFrameTick;
233 235
236 public bool CombineRegions = false;
234 /// <summary> 237 /// <summary>
235 /// Tick at which the last maintenance run occurred. 238 /// Tick at which the last maintenance run occurred.
236 /// </summary> 239 /// </summary>
@@ -261,6 +264,11 @@ namespace OpenSim.Region.Framework.Scenes
261 /// </summary> 264 /// </summary>
262 private int m_LastLogin; 265 private int m_LastLogin;
263 266
267 private int m_lastIncoming;
268 private int m_lastOutgoing;
269 private int m_hbRestarts = 0;
270
271
264 /// <summary> 272 /// <summary>
265 /// Thread that runs the scene loop. 273 /// Thread that runs the scene loop.
266 /// </summary> 274 /// </summary>
@@ -276,7 +284,7 @@ namespace OpenSim.Region.Framework.Scenes
276 private volatile bool m_shuttingDown; 284 private volatile bool m_shuttingDown;
277 285
278// private int m_lastUpdate; 286// private int m_lastUpdate;
279// private bool m_firstHeartbeat = true; 287 private bool m_firstHeartbeat = true;
280 288
281 private UpdatePrioritizationSchemes m_priorityScheme = UpdatePrioritizationSchemes.Time; 289 private UpdatePrioritizationSchemes m_priorityScheme = UpdatePrioritizationSchemes.Time;
282 private bool m_reprioritizationEnabled = true; 290 private bool m_reprioritizationEnabled = true;
@@ -321,6 +329,19 @@ namespace OpenSim.Region.Framework.Scenes
321 get { return m_sceneGridService; } 329 get { return m_sceneGridService; }
322 } 330 }
323 331
332 public ISnmpModule SnmpService
333 {
334 get
335 {
336 if (m_snmpService == null)
337 {
338 m_snmpService = RequestModuleInterface<ISnmpModule>();
339 }
340
341 return m_snmpService;
342 }
343 }
344
324 public ISimulationDataService SimulationDataService 345 public ISimulationDataService SimulationDataService
325 { 346 {
326 get 347 get
@@ -620,6 +641,8 @@ namespace OpenSim.Region.Framework.Scenes
620 m_SimulationDataService = simDataService; 641 m_SimulationDataService = simDataService;
621 m_EstateDataService = estateDataService; 642 m_EstateDataService = estateDataService;
622 m_regionHandle = RegionInfo.RegionHandle; 643 m_regionHandle = RegionInfo.RegionHandle;
644 m_lastIncoming = 0;
645 m_lastOutgoing = 0;
623 646
624 m_asyncSceneObjectDeleter = new AsyncSceneObjectGroupDeleter(this); 647 m_asyncSceneObjectDeleter = new AsyncSceneObjectGroupDeleter(this);
625 m_asyncSceneObjectDeleter.Enabled = true; 648 m_asyncSceneObjectDeleter.Enabled = true;
@@ -700,122 +723,131 @@ namespace OpenSim.Region.Framework.Scenes
700 723
701 // Region config overrides global config 724 // Region config overrides global config
702 // 725 //
703 if (m_config.Configs["Startup"] != null) 726 try
704 { 727 {
705 IConfig startupConfig = m_config.Configs["Startup"]; 728 if (m_config.Configs["Startup"] != null)
706
707 StartDisabled = startupConfig.GetBoolean("StartDisabled", false);
708
709 m_defaultDrawDistance = startupConfig.GetFloat("DefaultDrawDistance", m_defaultDrawDistance);
710 m_useBackup = startupConfig.GetBoolean("UseSceneBackup", m_useBackup);
711 if (!m_useBackup)
712 m_log.InfoFormat("[SCENE]: Backup has been disabled for {0}", RegionInfo.RegionName);
713
714 //Animation states
715 m_useFlySlow = startupConfig.GetBoolean("enableflyslow", false);
716
717 PhysicalPrims = startupConfig.GetBoolean("physical_prim", PhysicalPrims);
718 CollidablePrims = startupConfig.GetBoolean("collidable_prim", CollidablePrims);
719
720 m_maxNonphys = startupConfig.GetFloat("NonphysicalPrimMax", m_maxNonphys);
721 if (RegionInfo.NonphysPrimMax > 0)
722 { 729 {
723 m_maxNonphys = RegionInfo.NonphysPrimMax; 730 IConfig startupConfig = m_config.Configs["Startup"];
724 }
725 731
726 m_maxPhys = startupConfig.GetFloat("PhysicalPrimMax", m_maxPhys); 732 StartDisabled = startupConfig.GetBoolean("StartDisabled", false);
727 733
728 if (RegionInfo.PhysPrimMax > 0) 734 m_defaultDrawDistance = startupConfig.GetFloat("DefaultDrawDistance",m_defaultDrawDistance);
729 { 735 m_useBackup = startupConfig.GetBoolean("UseSceneBackup", m_useBackup);
730 m_maxPhys = RegionInfo.PhysPrimMax; 736 if (!m_useBackup)
731 } 737 m_log.InfoFormat("[SCENE]: Backup has been disabled for {0}", RegionInfo.RegionName);
732 738
733 // Here, if clamping is requested in either global or 739 //Animation states
734 // local config, it will be used 740 m_useFlySlow = startupConfig.GetBoolean("enableflyslow", false);
735 //
736 m_clampPrimSize = startupConfig.GetBoolean("ClampPrimSize", m_clampPrimSize);
737 if (RegionInfo.ClampPrimSize)
738 {
739 m_clampPrimSize = true;
740 }
741 741
742 m_useTrashOnDelete = startupConfig.GetBoolean("UseTrashOnDelete", m_useTrashOnDelete); 742 PhysicalPrims = startupConfig.GetBoolean("physical_prim", true);
743 m_trustBinaries = startupConfig.GetBoolean("TrustBinaries", m_trustBinaries); 743 CollidablePrims = startupConfig.GetBoolean("collidable_prim", true);
744 m_allowScriptCrossings = startupConfig.GetBoolean("AllowScriptCrossing", m_allowScriptCrossings);
745 m_dontPersistBefore =
746 startupConfig.GetLong("MinimumTimeBeforePersistenceConsidered", DEFAULT_MIN_TIME_FOR_PERSISTENCE);
747 m_dontPersistBefore *= 10000000;
748 m_persistAfter =
749 startupConfig.GetLong("MaximumTimeBeforePersistenceConsidered", DEFAULT_MAX_TIME_FOR_PERSISTENCE);
750 m_persistAfter *= 10000000;
751 744
752 m_defaultScriptEngine = startupConfig.GetString("DefaultScriptEngine", "XEngine"); 745 m_maxNonphys = startupConfig.GetFloat("NonphysicalPrimMax", m_maxNonphys);
746 if (RegionInfo.NonphysPrimMax > 0)
747 {
748 m_maxNonphys = RegionInfo.NonphysPrimMax;
749 }
753 750
754 SpawnPointRouting = startupConfig.GetString("SpawnPointRouting", "closest"); 751 m_maxPhys = startupConfig.GetFloat("PhysicalPrimMax", m_maxPhys);
755 TelehubAllowLandmarks = startupConfig.GetBoolean("TelehubAllowLandmark", false);
756 752
757 IConfig packetConfig = m_config.Configs["PacketPool"]; 753 if (RegionInfo.PhysPrimMax > 0)
758 if (packetConfig != null) 754 {
759 { 755 m_maxPhys = RegionInfo.PhysPrimMax;
760 PacketPool.Instance.RecyclePackets = packetConfig.GetBoolean("RecyclePackets", true); 756 }
761 PacketPool.Instance.RecycleDataBlocks = packetConfig.GetBoolean("RecycleDataBlocks", true);
762 }
763 757
764 m_strictAccessControl = startupConfig.GetBoolean("StrictAccessControl", m_strictAccessControl); 758 SpawnPointRouting = startupConfig.GetString("SpawnPointRouting", "closest");
759 TelehubAllowLandmarks = startupConfig.GetBoolean("TelehubAllowLandmark", false);
765 760
766 m_generateMaptiles = startupConfig.GetBoolean("GenerateMaptiles", true); 761 // Here, if clamping is requested in either global or
767 if (m_generateMaptiles) 762 // local config, it will be used
768 { 763 //
769 int maptileRefresh = startupConfig.GetInt("MaptileRefresh", 0); 764 m_clampPrimSize = startupConfig.GetBoolean("ClampPrimSize", m_clampPrimSize);
770 if (maptileRefresh != 0) 765 if (RegionInfo.ClampPrimSize)
771 { 766 {
772 m_mapGenerationTimer.Interval = maptileRefresh * 1000; 767 m_clampPrimSize = true;
773 m_mapGenerationTimer.Elapsed += RegenerateMaptileAndReregister;
774 m_mapGenerationTimer.AutoReset = true;
775 m_mapGenerationTimer.Start();
776 } 768 }
777 }
778 else
779 {
780 string tile = startupConfig.GetString("MaptileStaticUUID", UUID.Zero.ToString());
781 UUID tileID;
782 769
783 if (UUID.TryParse(tile, out tileID)) 770 m_useTrashOnDelete = startupConfig.GetBoolean("UseTrashOnDelete",m_useTrashOnDelete);
771 m_trustBinaries = startupConfig.GetBoolean("TrustBinaries", m_trustBinaries);
772 m_allowScriptCrossings = startupConfig.GetBoolean("AllowScriptCrossing", m_allowScriptCrossings);
773 m_dontPersistBefore =
774 startupConfig.GetLong("MinimumTimeBeforePersistenceConsidered", DEFAULT_MIN_TIME_FOR_PERSISTENCE);
775 m_dontPersistBefore *= 10000000;
776 m_persistAfter =
777 startupConfig.GetLong("MaximumTimeBeforePersistenceConsidered", DEFAULT_MAX_TIME_FOR_PERSISTENCE);
778 m_persistAfter *= 10000000;
779
780 m_defaultScriptEngine = startupConfig.GetString("DefaultScriptEngine", "XEngine");
781 m_log.InfoFormat("[SCENE]: Default script engine {0}", m_defaultScriptEngine);
782
783 IConfig packetConfig = m_config.Configs["PacketPool"];
784 if (packetConfig != null)
784 { 785 {
785 RegionInfo.RegionSettings.TerrainImageID = tileID; 786 PacketPool.Instance.RecyclePackets = packetConfig.GetBoolean("RecyclePackets", true);
787 PacketPool.Instance.RecycleDataBlocks = packetConfig.GetBoolean("RecycleDataBlocks", true);
786 } 788 }
787 }
788 789
789 string grant = startupConfig.GetString("AllowedClients", String.Empty); 790 m_strictAccessControl = startupConfig.GetBoolean("StrictAccessControl", m_strictAccessControl);
790 if (grant.Length > 0) 791 m_seeIntoBannedRegion = startupConfig.GetBoolean("SeeIntoBannedRegion", m_seeIntoBannedRegion);
791 { 792 CombineRegions = startupConfig.GetBoolean("CombineContiguousRegions", false);
792 foreach (string viewer in grant.Split('|')) 793
794 m_generateMaptiles = startupConfig.GetBoolean("GenerateMaptiles", true);
795 if (m_generateMaptiles)
793 { 796 {
794 m_AllowedViewers.Add(viewer.Trim().ToLower()); 797 int maptileRefresh = startupConfig.GetInt("MaptileRefresh", 0);
798 if (maptileRefresh != 0)
799 {
800 m_mapGenerationTimer.Interval = maptileRefresh * 1000;
801 m_mapGenerationTimer.Elapsed += RegenerateMaptileAndReregister;
802 m_mapGenerationTimer.AutoReset = true;
803 m_mapGenerationTimer.Start();
804 }
795 } 805 }
796 } 806 else
807 {
808 string tile = startupConfig.GetString("MaptileStaticUUID", UUID.Zero.ToString());
809 UUID tileID;
797 810
798 grant = startupConfig.GetString("BannedClients", String.Empty); 811 if (UUID.TryParse(tile, out tileID))
799 if (grant.Length > 0) 812 {
800 { 813 RegionInfo.RegionSettings.TerrainImageID = tileID;
801 foreach (string viewer in grant.Split('|')) 814 }
815 }
816
817 string grant = startupConfig.GetString("AllowedClients", String.Empty);
818 if (grant.Length > 0)
802 { 819 {
803 m_BannedViewers.Add(viewer.Trim().ToLower()); 820 foreach (string viewer in grant.Split(','))
821 {
822 m_AllowedViewers.Add(viewer.Trim().ToLower());
823 }
804 } 824 }
805 }
806 825
807 MinFrameTime = startupConfig.GetFloat( "MinFrameTime", MinFrameTime); 826 grant = startupConfig.GetString("BannedClients", String.Empty);
808 m_update_backup = startupConfig.GetInt( "UpdateStorageEveryNFrames", m_update_backup); 827 if (grant.Length > 0)
809 m_update_coarse_locations = startupConfig.GetInt( "UpdateCoarseLocationsEveryNFrames", m_update_coarse_locations); 828 {
810 m_update_entitymovement = startupConfig.GetInt( "UpdateEntityMovementEveryNFrames", m_update_entitymovement); 829 foreach (string viewer in grant.Split(','))
811 m_update_events = startupConfig.GetInt( "UpdateEventsEveryNFrames", m_update_events); 830 {
812 m_update_objects = startupConfig.GetInt( "UpdateObjectsEveryNFrames", m_update_objects); 831 m_BannedViewers.Add(viewer.Trim().ToLower());
813 m_update_physics = startupConfig.GetInt( "UpdatePhysicsEveryNFrames", m_update_physics); 832 }
814 m_update_presences = startupConfig.GetInt( "UpdateAgentsEveryNFrames", m_update_presences); 833 }
815 m_update_terrain = startupConfig.GetInt( "UpdateTerrainEveryNFrames", m_update_terrain);
816 m_update_temp_cleaning = startupConfig.GetInt( "UpdateTempCleaningEveryNFrames", m_update_temp_cleaning);
817 834
818 SendPeriodicAppearanceUpdates = startupConfig.GetBoolean("SendPeriodicAppearanceUpdates", SendPeriodicAppearanceUpdates); 835 MinFrameTime = startupConfig.GetFloat( "MinFrameTime", MinFrameTime);
836 m_update_backup = startupConfig.GetInt( "UpdateStorageEveryNFrames", m_update_backup);
837 m_update_coarse_locations = startupConfig.GetInt( "UpdateCoarseLocationsEveryNFrames", m_update_coarse_locations);
838 m_update_entitymovement = startupConfig.GetInt( "UpdateEntityMovementEveryNFrames", m_update_entitymovement);
839 m_update_events = startupConfig.GetInt( "UpdateEventsEveryNFrames", m_update_events);
840 m_update_objects = startupConfig.GetInt( "UpdateObjectsEveryNFrames", m_update_objects);
841 m_update_physics = startupConfig.GetInt( "UpdatePhysicsEveryNFrames", m_update_physics);
842 m_update_presences = startupConfig.GetInt( "UpdateAgentsEveryNFrames", m_update_presences);
843 m_update_terrain = startupConfig.GetInt( "UpdateTerrainEveryNFrames", m_update_terrain);
844 m_update_temp_cleaning = startupConfig.GetInt( "UpdateTempCleaningEveryNFrames", m_update_temp_cleaning);
845 SendPeriodicAppearanceUpdates = startupConfig.GetBoolean("SendPeriodicAppearanceUpdates", SendPeriodicAppearanceUpdates);
846 }
847 }
848 catch (Exception e)
849 {
850 m_log.Error("[SCENE]: Failed to load StartupConfig: " + e.ToString());
819 } 851 }
820 852
821 #endregion Region Config 853 #endregion Region Config
@@ -850,6 +882,8 @@ namespace OpenSim.Region.Framework.Scenes
850 StatsReporter = new SimStatsReporter(this); 882 StatsReporter = new SimStatsReporter(this);
851 StatsReporter.OnSendStatsResult += SendSimStatsPackets; 883 StatsReporter.OnSendStatsResult += SendSimStatsPackets;
852 StatsReporter.OnStatsIncorrect += m_sceneGraph.RecalculateStats; 884 StatsReporter.OnStatsIncorrect += m_sceneGraph.RecalculateStats;
885
886 MainConsole.Instance.Commands.AddCommand("scene", false, "gc collect", "gc collect", "gc collect", "Cause the garbage collector to make a single pass", HandleGcCollect);
853 } 887 }
854 888
855 public Scene(RegionInfo regInfo) : base(regInfo) 889 public Scene(RegionInfo regInfo) : base(regInfo)
@@ -1252,7 +1286,22 @@ namespace OpenSim.Region.Framework.Scenes
1252 //m_heartbeatTimer.Elapsed += new ElapsedEventHandler(Heartbeat); 1286 //m_heartbeatTimer.Elapsed += new ElapsedEventHandler(Heartbeat);
1253 if (m_heartbeatThread != null) 1287 if (m_heartbeatThread != null)
1254 { 1288 {
1289 m_hbRestarts++;
1290 if(m_hbRestarts > 10)
1291 Environment.Exit(1);
1292 m_log.ErrorFormat("[SCENE]: Restarting heartbeat thread because it hasn't reported in in region {0}", RegionInfo.RegionName);
1293
1294//int pid = System.Diagnostics.Process.GetCurrentProcess().Id;
1295//System.Diagnostics.Process proc = new System.Diagnostics.Process();
1296//proc.EnableRaisingEvents=false;
1297//proc.StartInfo.FileName = "/bin/kill";
1298//proc.StartInfo.Arguments = "-QUIT " + pid.ToString();
1299//proc.Start();
1300//proc.WaitForExit();
1301//Thread.Sleep(1000);
1302//Environment.Exit(1);
1255 m_heartbeatThread.Abort(); 1303 m_heartbeatThread.Abort();
1304 Watchdog.AbortThread(m_heartbeatThread.ManagedThreadId);
1256 m_heartbeatThread = null; 1305 m_heartbeatThread = null;
1257 } 1306 }
1258// m_lastUpdate = Util.EnvironmentTickCount(); 1307// m_lastUpdate = Util.EnvironmentTickCount();
@@ -1399,16 +1448,20 @@ namespace OpenSim.Region.Framework.Scenes
1399 endFrame = Frame + frames; 1448 endFrame = Frame + frames;
1400 1449
1401 float physicsFPS = 0f; 1450 float physicsFPS = 0f;
1402 int previousFrameTick, tmpMS; 1451 int tmpMS;
1403 int maintc = Util.EnvironmentTickCount(); 1452 int previousFrameTick;
1453 int maintc;
1454 int sleepMS;
1455 int framestart;
1404 1456
1405 while (!m_shuttingDown && (endFrame == null || Frame < endFrame)) 1457 while (!m_shuttingDown && (endFrame == null || Frame < endFrame))
1406 { 1458 {
1459 framestart = Util.EnvironmentTickCount();
1407 ++Frame; 1460 ++Frame;
1408 1461
1409// m_log.DebugFormat("[SCENE]: Processing frame {0} in {1}", Frame, RegionInfo.RegionName); 1462// m_log.DebugFormat("[SCENE]: Processing frame {0} in {1}", Frame, RegionInfo.RegionName);
1410 1463
1411 agentMS = tempOnRezMS = eventMS = backupMS = terrainMS = landMS = spareMS = 0; 1464 agentMS = tempOnRezMS = eventMS = backupMS = terrainMS = landMS = 0;
1412 1465
1413 try 1466 try
1414 { 1467 {
@@ -1460,6 +1513,7 @@ namespace OpenSim.Region.Framework.Scenes
1460 m_sceneGraph.UpdatePresences(); 1513 m_sceneGraph.UpdatePresences();
1461 1514
1462 agentMS += Util.EnvironmentTickCountSubtract(tmpMS); 1515 agentMS += Util.EnvironmentTickCountSubtract(tmpMS);
1516
1463 1517
1464 // Delete temp-on-rez stuff 1518 // Delete temp-on-rez stuff
1465 if (Frame % m_update_temp_cleaning == 0 && !m_cleaningTemps) 1519 if (Frame % m_update_temp_cleaning == 0 && !m_cleaningTemps)
@@ -1541,34 +1595,37 @@ namespace OpenSim.Region.Framework.Scenes
1541 1595
1542 Watchdog.UpdateThread(); 1596 Watchdog.UpdateThread();
1543 1597
1598 otherMS = tempOnRezMS + eventMS + backupMS + terrainMS + landMS;
1599
1600 StatsReporter.AddPhysicsFPS(physicsFPS);
1601 StatsReporter.AddTimeDilation(TimeDilation);
1602 StatsReporter.AddFPS(1);
1603
1604 StatsReporter.addAgentMS(agentMS);
1605 StatsReporter.addPhysicsMS(physicsMS + physicsMS2);
1606 StatsReporter.addOtherMS(otherMS);
1607 StatsReporter.addScriptLines(m_sceneGraph.GetScriptLPS());
1608
1544 previousFrameTick = m_lastFrameTick; 1609 previousFrameTick = m_lastFrameTick;
1545 m_lastFrameTick = Util.EnvironmentTickCount(); 1610 m_lastFrameTick = Util.EnvironmentTickCount();
1546 tmpMS = Util.EnvironmentTickCountSubtract(m_lastFrameTick, maintc); 1611 tmpMS = Util.EnvironmentTickCountSubtract(m_lastFrameTick, framestart);
1547 tmpMS = (int)(MinFrameTime * 1000) - tmpMS; 1612 tmpMS = (int)(MinFrameTime * 1000) - tmpMS;
1548 1613
1614 m_firstHeartbeat = false;
1615
1616 sleepMS = Util.EnvironmentTickCount();
1617
1549 if (tmpMS > 0) 1618 if (tmpMS > 0)
1550 {
1551 Thread.Sleep(tmpMS); 1619 Thread.Sleep(tmpMS);
1552 spareMS += tmpMS;
1553 }
1554
1555 frameMS = Util.EnvironmentTickCountSubtract(maintc);
1556 maintc = Util.EnvironmentTickCount();
1557 1620
1558 otherMS = tempOnRezMS + eventMS + backupMS + terrainMS + landMS; 1621 sleepMS = Util.EnvironmentTickCountSubtract(sleepMS);
1622 frameMS = Util.EnvironmentTickCountSubtract(framestart);
1623 StatsReporter.addSleepMS(sleepMS);
1624 StatsReporter.addFrameMS(frameMS);
1559 1625
1560 // if (Frame%m_update_avatars == 0) 1626 // if (Frame%m_update_avatars == 0)
1561 // UpdateInWorldTime(); 1627 // UpdateInWorldTime();
1562 StatsReporter.AddPhysicsFPS(physicsFPS);
1563 StatsReporter.AddTimeDilation(TimeDilation);
1564 StatsReporter.AddFPS(1);
1565 1628
1566 StatsReporter.addFrameMS(frameMS);
1567 StatsReporter.addAgentMS(agentMS);
1568 StatsReporter.addPhysicsMS(physicsMS + physicsMS2);
1569 StatsReporter.addOtherMS(otherMS);
1570 StatsReporter.AddSpareMS(spareMS);
1571 StatsReporter.addScriptLines(m_sceneGraph.GetScriptLPS());
1572 1629
1573 // Optionally warn if a frame takes double the amount of time that it should. 1630 // Optionally warn if a frame takes double the amount of time that it should.
1574 if (DebugUpdates 1631 if (DebugUpdates
@@ -1596,9 +1653,9 @@ namespace OpenSim.Region.Framework.Scenes
1596 1653
1597 private void CheckAtTargets() 1654 private void CheckAtTargets()
1598 { 1655 {
1599 Dictionary<UUID, SceneObjectGroup>.ValueCollection objs; 1656 List<SceneObjectGroup> objs = new List<SceneObjectGroup>();
1600 lock (m_groupsWithTargets) 1657 lock (m_groupsWithTargets)
1601 objs = m_groupsWithTargets.Values; 1658 objs = new List<SceneObjectGroup>(m_groupsWithTargets.Values);
1602 1659
1603 foreach (SceneObjectGroup entry in objs) 1660 foreach (SceneObjectGroup entry in objs)
1604 entry.checkAtTargets(); 1661 entry.checkAtTargets();
@@ -1679,7 +1736,7 @@ namespace OpenSim.Region.Framework.Scenes
1679 msg.fromAgentName = "Server"; 1736 msg.fromAgentName = "Server";
1680 msg.dialog = (byte)19; // Object msg 1737 msg.dialog = (byte)19; // Object msg
1681 msg.fromGroup = false; 1738 msg.fromGroup = false;
1682 msg.offline = (byte)0; 1739 msg.offline = (byte)1;
1683 msg.ParentEstateID = RegionInfo.EstateSettings.ParentEstateID; 1740 msg.ParentEstateID = RegionInfo.EstateSettings.ParentEstateID;
1684 msg.Position = Vector3.Zero; 1741 msg.Position = Vector3.Zero;
1685 msg.RegionID = RegionInfo.RegionID.Guid; 1742 msg.RegionID = RegionInfo.RegionID.Guid;
@@ -1901,6 +1958,19 @@ namespace OpenSim.Region.Framework.Scenes
1901 EventManager.TriggerPrimsLoaded(this); 1958 EventManager.TriggerPrimsLoaded(this);
1902 } 1959 }
1903 1960
1961 public bool SuportsRayCastFiltered()
1962 {
1963 if (PhysicsScene == null)
1964 return false;
1965 return PhysicsScene.SuportsRaycastWorldFiltered();
1966 }
1967
1968 public object RayCastFiltered(Vector3 position, Vector3 direction, float length, int Count, RayFilterFlags filter)
1969 {
1970 if (PhysicsScene == null)
1971 return null;
1972 return PhysicsScene.RaycastWorld(position, direction, length, Count,filter);
1973 }
1904 1974
1905 /// <summary> 1975 /// <summary>
1906 /// Gets a new rez location based on the raycast and the size of the object that is being rezzed. 1976 /// Gets a new rez location based on the raycast and the size of the object that is being rezzed.
@@ -1917,14 +1987,24 @@ namespace OpenSim.Region.Framework.Scenes
1917 /// <returns></returns> 1987 /// <returns></returns>
1918 public Vector3 GetNewRezLocation(Vector3 RayStart, Vector3 RayEnd, UUID RayTargetID, Quaternion rot, byte bypassRayCast, byte RayEndIsIntersection, bool frontFacesOnly, Vector3 scale, bool FaceCenter) 1988 public Vector3 GetNewRezLocation(Vector3 RayStart, Vector3 RayEnd, UUID RayTargetID, Quaternion rot, byte bypassRayCast, byte RayEndIsIntersection, bool frontFacesOnly, Vector3 scale, bool FaceCenter)
1919 { 1989 {
1990
1991 float wheight = (float)RegionInfo.RegionSettings.WaterHeight;
1992 Vector3 wpos = Vector3.Zero;
1993 // Check for water surface intersection from above
1994 if ( (RayStart.Z > wheight) && (RayEnd.Z < wheight) )
1995 {
1996 float ratio = (RayStart.Z - wheight) / (RayStart.Z - RayEnd.Z);
1997 wpos.X = RayStart.X - (ratio * (RayStart.X - RayEnd.X));
1998 wpos.Y = RayStart.Y - (ratio * (RayStart.Y - RayEnd.Y));
1999 wpos.Z = wheight;
2000 }
2001
1920 Vector3 pos = Vector3.Zero; 2002 Vector3 pos = Vector3.Zero;
1921 if (RayEndIsIntersection == (byte)1) 2003 if (RayEndIsIntersection == (byte)1)
1922 { 2004 {
1923 pos = RayEnd; 2005 pos = RayEnd;
1924 return pos;
1925 } 2006 }
1926 2007 else if (RayTargetID != UUID.Zero)
1927 if (RayTargetID != UUID.Zero)
1928 { 2008 {
1929 SceneObjectPart target = GetSceneObjectPart(RayTargetID); 2009 SceneObjectPart target = GetSceneObjectPart(RayTargetID);
1930 2010
@@ -1946,7 +2026,7 @@ namespace OpenSim.Region.Framework.Scenes
1946 EntityIntersection ei = target.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, FaceCenter); 2026 EntityIntersection ei = target.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, FaceCenter);
1947 2027
1948 // Un-comment out the following line to Get Raytrace results printed to the console. 2028 // Un-comment out the following line to Get Raytrace results printed to the console.
1949 // m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString()); 2029 // m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
1950 float ScaleOffset = 0.5f; 2030 float ScaleOffset = 0.5f;
1951 2031
1952 // If we hit something 2032 // If we hit something
@@ -1969,13 +2049,10 @@ namespace OpenSim.Region.Framework.Scenes
1969 //pos.Z -= 0.25F; 2049 //pos.Z -= 0.25F;
1970 2050
1971 } 2051 }
1972
1973 return pos;
1974 } 2052 }
1975 else 2053 else
1976 { 2054 {
1977 // We don't have a target here, so we're going to raytrace all the objects in the scene. 2055 // We don't have a target here, so we're going to raytrace all the objects in the scene.
1978
1979 EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection), true, false); 2056 EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection), true, false);
1980 2057
1981 // Un-comment the following line to print the raytrace results to the console. 2058 // Un-comment the following line to print the raytrace results to the console.
@@ -1984,13 +2061,12 @@ namespace OpenSim.Region.Framework.Scenes
1984 if (ei.HitTF) 2061 if (ei.HitTF)
1985 { 2062 {
1986 pos = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z); 2063 pos = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
1987 } else 2064 }
2065 else
1988 { 2066 {
1989 // fall back to our stupid functionality 2067 // fall back to our stupid functionality
1990 pos = RayEnd; 2068 pos = RayEnd;
1991 } 2069 }
1992
1993 return pos;
1994 } 2070 }
1995 } 2071 }
1996 else 2072 else
@@ -2001,8 +2077,12 @@ namespace OpenSim.Region.Framework.Scenes
2001 //increase height so its above the ground. 2077 //increase height so its above the ground.
2002 //should be getting the normal of the ground at the rez point and using that? 2078 //should be getting the normal of the ground at the rez point and using that?
2003 pos.Z += scale.Z / 2f; 2079 pos.Z += scale.Z / 2f;
2004 return pos; 2080// return pos;
2005 } 2081 }
2082
2083 // check against posible water intercept
2084 if (wpos.Z > pos.Z) pos = wpos;
2085 return pos;
2006 } 2086 }
2007 2087
2008 2088
@@ -2091,7 +2171,10 @@ namespace OpenSim.Region.Framework.Scenes
2091 public bool AddRestoredSceneObject( 2171 public bool AddRestoredSceneObject(
2092 SceneObjectGroup sceneObject, bool attachToBackup, bool alreadyPersisted, bool sendClientUpdates) 2172 SceneObjectGroup sceneObject, bool attachToBackup, bool alreadyPersisted, bool sendClientUpdates)
2093 { 2173 {
2094 return m_sceneGraph.AddRestoredSceneObject(sceneObject, attachToBackup, alreadyPersisted, sendClientUpdates); 2174 bool result = m_sceneGraph.AddRestoredSceneObject(sceneObject, attachToBackup, alreadyPersisted, sendClientUpdates);
2175 if (result)
2176 sceneObject.IsDeleted = false;
2177 return result;
2095 } 2178 }
2096 2179
2097 /// <summary> 2180 /// <summary>
@@ -2183,6 +2266,15 @@ namespace OpenSim.Region.Framework.Scenes
2183 /// </summary> 2266 /// </summary>
2184 public void DeleteAllSceneObjects() 2267 public void DeleteAllSceneObjects()
2185 { 2268 {
2269 DeleteAllSceneObjects(false);
2270 }
2271
2272 /// <summary>
2273 /// Delete every object from the scene. This does not include attachments worn by avatars.
2274 /// </summary>
2275 public void DeleteAllSceneObjects(bool exceptNoCopy)
2276 {
2277 List<SceneObjectGroup> toReturn = new List<SceneObjectGroup>();
2186 lock (Entities) 2278 lock (Entities)
2187 { 2279 {
2188 EntityBase[] entities = Entities.GetEntities(); 2280 EntityBase[] entities = Entities.GetEntities();
@@ -2191,11 +2283,24 @@ namespace OpenSim.Region.Framework.Scenes
2191 if (e is SceneObjectGroup) 2283 if (e is SceneObjectGroup)
2192 { 2284 {
2193 SceneObjectGroup sog = (SceneObjectGroup)e; 2285 SceneObjectGroup sog = (SceneObjectGroup)e;
2194 if (!sog.IsAttachment) 2286 if (sog != null && !sog.IsAttachment)
2195 DeleteSceneObject((SceneObjectGroup)e, false); 2287 {
2288 if (!exceptNoCopy || ((sog.GetEffectivePermissions() & (uint)PermissionMask.Copy) != 0))
2289 {
2290 DeleteSceneObject((SceneObjectGroup)e, false);
2291 }
2292 else
2293 {
2294 toReturn.Add((SceneObjectGroup)e);
2295 }
2296 }
2196 } 2297 }
2197 } 2298 }
2198 } 2299 }
2300 if (toReturn.Count > 0)
2301 {
2302 returnObjects(toReturn.ToArray(), UUID.Zero);
2303 }
2199 } 2304 }
2200 2305
2201 /// <summary> 2306 /// <summary>
@@ -2247,6 +2352,8 @@ namespace OpenSim.Region.Framework.Scenes
2247 } 2352 }
2248 2353
2249 group.DeleteGroupFromScene(silent); 2354 group.DeleteGroupFromScene(silent);
2355 if (!silent)
2356 SendKillObject(new List<uint>() { group.LocalId });
2250 2357
2251// m_log.DebugFormat("[SCENE]: Exit DeleteSceneObject() for {0} {1}", group.Name, group.UUID); 2358// m_log.DebugFormat("[SCENE]: Exit DeleteSceneObject() for {0} {1}", group.Name, group.UUID);
2252 } 2359 }
@@ -2537,7 +2644,7 @@ namespace OpenSim.Region.Framework.Scenes
2537 // If the user is banned, we won't let any of their objects 2644 // If the user is banned, we won't let any of their objects
2538 // enter. Period. 2645 // enter. Period.
2539 // 2646 //
2540 if (RegionInfo.EstateSettings.IsBanned(newObject.OwnerID)) 2647 if (RegionInfo.EstateSettings.IsBanned(newObject.OwnerID, 36))
2541 { 2648 {
2542 m_log.InfoFormat("[INTERREGION]: Denied prim crossing for banned avatar {0}", newObject.OwnerID); 2649 m_log.InfoFormat("[INTERREGION]: Denied prim crossing for banned avatar {0}", newObject.OwnerID);
2543 return false; 2650 return false;
@@ -2545,6 +2652,8 @@ namespace OpenSim.Region.Framework.Scenes
2545 2652
2546 if (newPosition != Vector3.Zero) 2653 if (newPosition != Vector3.Zero)
2547 newObject.RootPart.GroupPosition = newPosition; 2654 newObject.RootPart.GroupPosition = newPosition;
2655 if (newObject.RootPart.KeyframeMotion != null)
2656 newObject.RootPart.KeyframeMotion.UpdateSceneObject(newObject);
2548 2657
2549 if (!AddSceneObject(newObject)) 2658 if (!AddSceneObject(newObject))
2550 { 2659 {
@@ -2589,6 +2698,23 @@ namespace OpenSim.Region.Framework.Scenes
2589 /// <returns>True if the SceneObjectGroup was added, False if it was not</returns> 2698 /// <returns>True if the SceneObjectGroup was added, False if it was not</returns>
2590 public bool AddSceneObject(SceneObjectGroup sceneObject) 2699 public bool AddSceneObject(SceneObjectGroup sceneObject)
2591 { 2700 {
2701 if (sceneObject.OwnerID == UUID.Zero)
2702 {
2703 m_log.ErrorFormat("[SCENE]: Owner ID for {0} was zero", sceneObject.UUID);
2704 return false;
2705 }
2706
2707 // If the user is banned, we won't let any of their objects
2708 // enter. Period.
2709 //
2710 int flags = GetUserFlags(sceneObject.OwnerID);
2711 if (RegionInfo.EstateSettings.IsBanned(sceneObject.OwnerID, flags))
2712 {
2713 m_log.InfoFormat("[INTERREGION]: Denied prim crossing for banned avatar {0}", sceneObject.OwnerID);
2714
2715 return false;
2716 }
2717
2592 // Force allocation of new LocalId 2718 // Force allocation of new LocalId
2593 // 2719 //
2594 SceneObjectPart[] parts = sceneObject.Parts; 2720 SceneObjectPart[] parts = sceneObject.Parts;
@@ -2622,16 +2748,27 @@ namespace OpenSim.Region.Framework.Scenes
2622 RootPrim.RemFlag(PrimFlags.TemporaryOnRez); 2748 RootPrim.RemFlag(PrimFlags.TemporaryOnRez);
2623 2749
2624 if (AttachmentsModule != null) 2750 if (AttachmentsModule != null)
2625 AttachmentsModule.AttachObject(sp, grp, 0, false); 2751 AttachmentsModule.AttachObject(sp, grp, 0, false, false);
2626 } 2752 }
2627 else 2753 else
2628 { 2754 {
2755 m_log.DebugFormat("[SCENE]: Attachment {0} arrived and scene presence was not found, setting to temp", sceneObject.UUID);
2629 RootPrim.RemFlag(PrimFlags.TemporaryOnRez); 2756 RootPrim.RemFlag(PrimFlags.TemporaryOnRez);
2630 RootPrim.AddFlag(PrimFlags.TemporaryOnRez); 2757 RootPrim.AddFlag(PrimFlags.TemporaryOnRez);
2631 } 2758 }
2759 if (sceneObject.OwnerID == UUID.Zero)
2760 {
2761 m_log.ErrorFormat("[SCENE]: Owner ID for {0} was zero after attachment processing. BUG!", sceneObject.UUID);
2762 return false;
2763 }
2632 } 2764 }
2633 else 2765 else
2634 { 2766 {
2767 if (sceneObject.OwnerID == UUID.Zero)
2768 {
2769 m_log.ErrorFormat("[SCENE]: Owner ID for non-attachment {0} was zero", sceneObject.UUID);
2770 return false;
2771 }
2635 AddRestoredSceneObject(sceneObject, true, false); 2772 AddRestoredSceneObject(sceneObject, true, false);
2636 } 2773 }
2637 2774
@@ -2648,6 +2785,24 @@ namespace OpenSim.Region.Framework.Scenes
2648 return 2; // StateSource.PrimCrossing 2785 return 2; // StateSource.PrimCrossing
2649 } 2786 }
2650 2787
2788 public int GetUserFlags(UUID user)
2789 {
2790 //Unfortunately the SP approach means that the value is cached until region is restarted
2791 /*
2792 ScenePresence sp;
2793 if (TryGetScenePresence(user, out sp))
2794 {
2795 return sp.UserFlags;
2796 }
2797 else
2798 {
2799 */
2800 UserAccount uac = UserAccountService.GetUserAccount(RegionInfo.ScopeID, user);
2801 if (uac == null)
2802 return 0;
2803 return uac.UserFlags;
2804 //}
2805 }
2651 #endregion 2806 #endregion
2652 2807
2653 #region Add/Remove Avatar Methods 2808 #region Add/Remove Avatar Methods
@@ -2661,7 +2816,7 @@ namespace OpenSim.Region.Framework.Scenes
2661 = (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin) != 0 2816 = (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin) != 0
2662 || (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaLogin) != 0; 2817 || (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaLogin) != 0;
2663 2818
2664// CheckHeartbeat(); 2819 CheckHeartbeat();
2665 2820
2666 ScenePresence sp = GetScenePresence(client.AgentId); 2821 ScenePresence sp = GetScenePresence(client.AgentId);
2667 2822
@@ -2715,7 +2870,13 @@ namespace OpenSim.Region.Framework.Scenes
2715 2870
2716 EventManager.TriggerOnNewClient(client); 2871 EventManager.TriggerOnNewClient(client);
2717 if (vialogin) 2872 if (vialogin)
2873 {
2718 EventManager.TriggerOnClientLogin(client); 2874 EventManager.TriggerOnClientLogin(client);
2875 // Send initial parcel data
2876 Vector3 pos = sp.AbsolutePosition;
2877 ILandObject land = LandChannel.GetLandObject(pos.X, pos.Y);
2878 land.SendLandUpdateToClient(client);
2879 }
2719 2880
2720 return sp; 2881 return sp;
2721 } 2882 }
@@ -2804,19 +2965,12 @@ namespace OpenSim.Region.Framework.Scenes
2804 // and the scene presence and the client, if they exist 2965 // and the scene presence and the client, if they exist
2805 try 2966 try
2806 { 2967 {
2807 // We need to wait for the client to make UDP contact first. 2968 ScenePresence sp = GetScenePresence(agentID);
2808 // It's the UDP contact that creates the scene presence 2969 PresenceService.LogoutAgent(sp.ControllingClient.SessionId);
2809 ScenePresence sp = WaitGetScenePresence(agentID); 2970
2810 if (sp != null) 2971 if (sp != null)
2811 {
2812 PresenceService.LogoutAgent(sp.ControllingClient.SessionId);
2813
2814 sp.ControllingClient.Close(); 2972 sp.ControllingClient.Close();
2815 } 2973
2816 else
2817 {
2818 m_log.WarnFormat("[SCENE]: Could not find scene presence for {0}", agentID);
2819 }
2820 // BANG! SLASH! 2974 // BANG! SLASH!
2821 m_authenticateHandler.RemoveCircuit(agentID); 2975 m_authenticateHandler.RemoveCircuit(agentID);
2822 2976
@@ -2861,6 +3015,8 @@ namespace OpenSim.Region.Framework.Scenes
2861 client.OnUpdatePrimGroupPosition += m_sceneGraph.UpdatePrimGroupPosition; 3015 client.OnUpdatePrimGroupPosition += m_sceneGraph.UpdatePrimGroupPosition;
2862 client.OnUpdatePrimSinglePosition += m_sceneGraph.UpdatePrimSinglePosition; 3016 client.OnUpdatePrimSinglePosition += m_sceneGraph.UpdatePrimSinglePosition;
2863 3017
3018 client.onClientChangeObject += m_sceneGraph.ClientChangeObject;
3019
2864 client.OnUpdatePrimGroupRotation += m_sceneGraph.UpdatePrimGroupRotation; 3020 client.OnUpdatePrimGroupRotation += m_sceneGraph.UpdatePrimGroupRotation;
2865 client.OnUpdatePrimGroupMouseRotation += m_sceneGraph.UpdatePrimGroupRotation; 3021 client.OnUpdatePrimGroupMouseRotation += m_sceneGraph.UpdatePrimGroupRotation;
2866 client.OnUpdatePrimSingleRotation += m_sceneGraph.UpdatePrimSingleRotation; 3022 client.OnUpdatePrimSingleRotation += m_sceneGraph.UpdatePrimSingleRotation;
@@ -2917,6 +3073,7 @@ namespace OpenSim.Region.Framework.Scenes
2917 client.OnFetchInventory += m_asyncInventorySender.HandleFetchInventory; 3073 client.OnFetchInventory += m_asyncInventorySender.HandleFetchInventory;
2918 client.OnUpdateInventoryItem += UpdateInventoryItemAsset; 3074 client.OnUpdateInventoryItem += UpdateInventoryItemAsset;
2919 client.OnCopyInventoryItem += CopyInventoryItem; 3075 client.OnCopyInventoryItem += CopyInventoryItem;
3076 client.OnMoveItemsAndLeaveCopy += MoveInventoryItemsLeaveCopy;
2920 client.OnMoveInventoryItem += MoveInventoryItem; 3077 client.OnMoveInventoryItem += MoveInventoryItem;
2921 client.OnRemoveInventoryItem += RemoveInventoryItem; 3078 client.OnRemoveInventoryItem += RemoveInventoryItem;
2922 client.OnRemoveInventoryFolder += RemoveInventoryFolder; 3079 client.OnRemoveInventoryFolder += RemoveInventoryFolder;
@@ -2988,6 +3145,8 @@ namespace OpenSim.Region.Framework.Scenes
2988 client.OnUpdatePrimGroupPosition -= m_sceneGraph.UpdatePrimGroupPosition; 3145 client.OnUpdatePrimGroupPosition -= m_sceneGraph.UpdatePrimGroupPosition;
2989 client.OnUpdatePrimSinglePosition -= m_sceneGraph.UpdatePrimSinglePosition; 3146 client.OnUpdatePrimSinglePosition -= m_sceneGraph.UpdatePrimSinglePosition;
2990 3147
3148 client.onClientChangeObject -= m_sceneGraph.ClientChangeObject;
3149
2991 client.OnUpdatePrimGroupRotation -= m_sceneGraph.UpdatePrimGroupRotation; 3150 client.OnUpdatePrimGroupRotation -= m_sceneGraph.UpdatePrimGroupRotation;
2992 client.OnUpdatePrimGroupMouseRotation -= m_sceneGraph.UpdatePrimGroupRotation; 3151 client.OnUpdatePrimGroupMouseRotation -= m_sceneGraph.UpdatePrimGroupRotation;
2993 client.OnUpdatePrimSingleRotation -= m_sceneGraph.UpdatePrimSingleRotation; 3152 client.OnUpdatePrimSingleRotation -= m_sceneGraph.UpdatePrimSingleRotation;
@@ -3090,7 +3249,7 @@ namespace OpenSim.Region.Framework.Scenes
3090 /// </summary> 3249 /// </summary>
3091 /// <param name="agentId">The avatar's Unique ID</param> 3250 /// <param name="agentId">The avatar's Unique ID</param>
3092 /// <param name="client">The IClientAPI for the client</param> 3251 /// <param name="client">The IClientAPI for the client</param>
3093 public virtual void TeleportClientHome(UUID agentId, IClientAPI client) 3252 public virtual bool TeleportClientHome(UUID agentId, IClientAPI client)
3094 { 3253 {
3095 if (EntityTransferModule != null) 3254 if (EntityTransferModule != null)
3096 { 3255 {
@@ -3101,6 +3260,7 @@ namespace OpenSim.Region.Framework.Scenes
3101 m_log.DebugFormat("[SCENE]: Unable to teleport user home: no AgentTransferModule is active"); 3260 m_log.DebugFormat("[SCENE]: Unable to teleport user home: no AgentTransferModule is active");
3102 client.SendTeleportFailed("Unable to perform teleports on this simulator."); 3261 client.SendTeleportFailed("Unable to perform teleports on this simulator.");
3103 } 3262 }
3263 return false;
3104 } 3264 }
3105 3265
3106 /// <summary> 3266 /// <summary>
@@ -3210,6 +3370,16 @@ namespace OpenSim.Region.Framework.Scenes
3210 /// <param name="flags"></param> 3370 /// <param name="flags"></param>
3211 public virtual void SetHomeRezPoint(IClientAPI remoteClient, ulong regionHandle, Vector3 position, Vector3 lookAt, uint flags) 3371 public virtual void SetHomeRezPoint(IClientAPI remoteClient, ulong regionHandle, Vector3 position, Vector3 lookAt, uint flags)
3212 { 3372 {
3373 //Add half the avatar's height so that the user doesn't fall through prims
3374 ScenePresence presence;
3375 if (TryGetScenePresence(remoteClient.AgentId, out presence))
3376 {
3377 if (presence.Appearance != null)
3378 {
3379 position.Z = position.Z + (presence.Appearance.AvatarHeight / 2);
3380 }
3381 }
3382
3213 if (GridUserService != null && GridUserService.SetHome(remoteClient.AgentId.ToString(), RegionInfo.RegionID, position, lookAt)) 3383 if (GridUserService != null && GridUserService.SetHome(remoteClient.AgentId.ToString(), RegionInfo.RegionID, position, lookAt))
3214 // FUBAR ALERT: this needs to be "Home position set." so the viewer saves a home-screenshot. 3384 // FUBAR ALERT: this needs to be "Home position set." so the viewer saves a home-screenshot.
3215 m_dialogModule.SendAlertToUser(remoteClient, "Home position set."); 3385 m_dialogModule.SendAlertToUser(remoteClient, "Home position set.");
@@ -3326,6 +3496,7 @@ namespace OpenSim.Region.Framework.Scenes
3326 AgentTransactionsModule.RemoveAgentAssetTransactions(agentID); 3496 AgentTransactionsModule.RemoveAgentAssetTransactions(agentID);
3327 3497
3328 m_authenticateHandler.RemoveCircuit(avatar.ControllingClient.CircuitCode); 3498 m_authenticateHandler.RemoveCircuit(avatar.ControllingClient.CircuitCode);
3499 m_log.Debug("[Scene] The avatar has left the building");
3329 } 3500 }
3330 catch (Exception e) 3501 catch (Exception e)
3331 { 3502 {
@@ -3527,13 +3698,16 @@ namespace OpenSim.Region.Framework.Scenes
3527 sp = null; 3698 sp = null;
3528 } 3699 }
3529 3700
3530 ILandObject land = LandChannel.GetLandObject(agent.startpos.X, agent.startpos.Y);
3531 3701
3532 //On login test land permisions 3702 //On login test land permisions
3533 if (vialogin) 3703 if (vialogin)
3534 { 3704 {
3535 if (land != null && !TestLandRestrictions(agent, land, out reason)) 3705 IUserAccountCacheModule cache = RequestModuleInterface<IUserAccountCacheModule>();
3706 if (cache != null)
3707 cache.Remove(agent.firstname + " " + agent.lastname);
3708 if (!TestLandRestrictions(agent.AgentID, out reason, ref agent.startpos.X, ref agent.startpos.Y))
3536 { 3709 {
3710 m_log.DebugFormat("[CONNECTION BEGIN]: Denying access to {0} due to no land access", agent.AgentID.ToString());
3537 return false; 3711 return false;
3538 } 3712 }
3539 } 3713 }
@@ -3556,9 +3730,15 @@ namespace OpenSim.Region.Framework.Scenes
3556 3730
3557 try 3731 try
3558 { 3732 {
3559 if (!AuthorizeUser(agent, out reason)) 3733 // Always check estate if this is a login. Always
3560 return false; 3734 // check if banned regions are to be blacked out.
3561 } catch (Exception e) 3735 if (vialogin || (!m_seeIntoBannedRegion))
3736 {
3737 if (!AuthorizeUser(agent, out reason))
3738 return false;
3739 }
3740 }
3741 catch (Exception e)
3562 { 3742 {
3563 m_log.ErrorFormat( 3743 m_log.ErrorFormat(
3564 "[SCENE]: Exception authorizing user {0}{1}", e.Message, e.StackTrace); 3744 "[SCENE]: Exception authorizing user {0}{1}", e.Message, e.StackTrace);
@@ -3689,6 +3869,8 @@ namespace OpenSim.Region.Framework.Scenes
3689 } 3869 }
3690 3870
3691 // Honor parcel landing type and position. 3871 // Honor parcel landing type and position.
3872 /*
3873 ILandObject land = LandChannel.GetLandObject(agent.startpos.X, agent.startpos.Y);
3692 if (land != null) 3874 if (land != null)
3693 { 3875 {
3694 if (land.LandData.LandingType == (byte)1 && land.LandData.UserLocation != Vector3.Zero) 3876 if (land.LandData.LandingType == (byte)1 && land.LandData.UserLocation != Vector3.Zero)
@@ -3696,25 +3878,34 @@ namespace OpenSim.Region.Framework.Scenes
3696 agent.startpos = land.LandData.UserLocation; 3878 agent.startpos = land.LandData.UserLocation;
3697 } 3879 }
3698 } 3880 }
3881 */// This is now handled properly in ScenePresence.MakeRootAgent
3699 } 3882 }
3700 3883
3701 return true; 3884 return true;
3702 } 3885 }
3703 3886
3704 private bool TestLandRestrictions(AgentCircuitData agent, ILandObject land, out string reason) 3887 public bool TestLandRestrictions(UUID agentID, out string reason, ref float posX, ref float posY)
3705 { 3888 {
3706 bool banned = land.IsBannedFromLand(agent.AgentID); 3889 reason = String.Empty;
3707 bool restricted = land.IsRestrictedFromLand(agent.AgentID); 3890 if (Permissions.IsGod(agentID))
3891 return true;
3892
3893 ILandObject land = LandChannel.GetLandObject(posX, posY);
3894 if (land == null)
3895 return false;
3896
3897 bool banned = land.IsBannedFromLand(agentID);
3898 bool restricted = land.IsRestrictedFromLand(agentID);
3708 3899
3709 if (banned || restricted) 3900 if (banned || restricted)
3710 { 3901 {
3711 ILandObject nearestParcel = GetNearestAllowedParcel(agent.AgentID, agent.startpos.X, agent.startpos.Y); 3902 ILandObject nearestParcel = GetNearestAllowedParcel(agentID, posX, posY);
3712 if (nearestParcel != null) 3903 if (nearestParcel != null)
3713 { 3904 {
3714 //Move agent to nearest allowed 3905 //Move agent to nearest allowed
3715 Vector3 newPosition = GetParcelCenterAtGround(nearestParcel); 3906 Vector3 newPosition = GetParcelCenterAtGround(nearestParcel);
3716 agent.startpos.X = newPosition.X; 3907 posX = newPosition.X;
3717 agent.startpos.Y = newPosition.Y; 3908 posY = newPosition.Y;
3718 } 3909 }
3719 else 3910 else
3720 { 3911 {
@@ -3776,7 +3967,7 @@ namespace OpenSim.Region.Framework.Scenes
3776 3967
3777 if (!m_strictAccessControl) return true; 3968 if (!m_strictAccessControl) return true;
3778 if (Permissions.IsGod(agent.AgentID)) return true; 3969 if (Permissions.IsGod(agent.AgentID)) return true;
3779 3970
3780 if (AuthorizationService != null) 3971 if (AuthorizationService != null)
3781 { 3972 {
3782 if (!AuthorizationService.IsAuthorizedForRegion( 3973 if (!AuthorizationService.IsAuthorizedForRegion(
@@ -3791,7 +3982,7 @@ namespace OpenSim.Region.Framework.Scenes
3791 3982
3792 if (RegionInfo.EstateSettings != null) 3983 if (RegionInfo.EstateSettings != null)
3793 { 3984 {
3794 if (RegionInfo.EstateSettings.IsBanned(agent.AgentID)) 3985 if (RegionInfo.EstateSettings.IsBanned(agent.AgentID, 0))
3795 { 3986 {
3796 m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user is on the banlist", 3987 m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user is on the banlist",
3797 agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName); 3988 agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
@@ -3981,6 +4172,15 @@ namespace OpenSim.Region.Framework.Scenes
3981 4172
3982 // XPTO: if this agent is not allowed here as root, always return false 4173 // XPTO: if this agent is not allowed here as root, always return false
3983 4174
4175 // We have to wait until the viewer contacts this region after receiving EAC.
4176 // That calls AddNewClient, which finally creates the ScenePresence
4177 int flags = GetUserFlags(cAgentData.AgentID);
4178 if (RegionInfo.EstateSettings.IsBanned(cAgentData.AgentID, flags))
4179 {
4180 m_log.DebugFormat("[SCENE]: Denying root agent entry to {0}: banned", cAgentData.AgentID);
4181 return false;
4182 }
4183
3984 // TODO: This check should probably be in QueryAccess(). 4184 // TODO: This check should probably be in QueryAccess().
3985 ILandObject nearestParcel = GetNearestAllowedParcel(cAgentData.AgentID, Constants.RegionSize / 2, Constants.RegionSize / 2); 4185 ILandObject nearestParcel = GetNearestAllowedParcel(cAgentData.AgentID, Constants.RegionSize / 2, Constants.RegionSize / 2);
3986 if (nearestParcel == null) 4186 if (nearestParcel == null)
@@ -4074,12 +4274,22 @@ namespace OpenSim.Region.Framework.Scenes
4074 return false; 4274 return false;
4075 } 4275 }
4076 4276
4277 public bool IncomingCloseAgent(UUID agentID)
4278 {
4279 return IncomingCloseAgent(agentID, false);
4280 }
4281
4282 public bool IncomingCloseChildAgent(UUID agentID)
4283 {
4284 return IncomingCloseAgent(agentID, true);
4285 }
4286
4077 /// <summary> 4287 /// <summary>
4078 /// Tell a single agent to disconnect from the region. 4288 /// Tell a single agent to disconnect from the region.
4079 /// </summary> 4289 /// </summary>
4080 /// <param name="regionHandle"></param>
4081 /// <param name="agentID"></param> 4290 /// <param name="agentID"></param>
4082 public bool IncomingCloseAgent(UUID agentID) 4291 /// <param name="childOnly"></param>
4292 public bool IncomingCloseAgent(UUID agentID, bool childOnly)
4083 { 4293 {
4084 //m_log.DebugFormat("[SCENE]: Processing incoming close agent for {0}", agentID); 4294 //m_log.DebugFormat("[SCENE]: Processing incoming close agent for {0}", agentID);
4085 4295
@@ -4700,35 +4910,81 @@ namespace OpenSim.Region.Framework.Scenes
4700 SimulationDataService.RemoveObject(uuid, RegionInfo.RegionID); 4910 SimulationDataService.RemoveObject(uuid, RegionInfo.RegionID);
4701 } 4911 }
4702 4912
4703 public int GetHealth() 4913 public int GetHealth(out int flags, out string message)
4704 { 4914 {
4705 // Returns: 4915 // Returns:
4706 // 1 = sim is up and accepting http requests. The heartbeat has 4916 // 1 = sim is up and accepting http requests. The heartbeat has
4707 // stopped and the sim is probably locked up, but a remote 4917 // stopped and the sim is probably locked up, but a remote
4708 // admin restart may succeed 4918 // admin restart may succeed
4709 // 4919 //
4710 // 2 = Sim is up and the heartbeat is running. The sim is likely 4920 // 2 = Sim is up and the heartbeat is running. The sim is likely
4711 // usable for people within and logins _may_ work 4921 // usable for people within
4922 //
4923 // 3 = Sim is up and one packet thread is running. Sim is
4924 // unstable and will not accept new logins
4925 //
4926 // 4 = Sim is up and both packet threads are running. Sim is
4927 // likely usable
4712 // 4928 //
4713 // 3 = We have seen a new user enter within the past 4 minutes 4929 // 5 = We have seen a new user enter within the past 4 minutes
4714 // which can be seen as positive confirmation of sim health 4930 // which can be seen as positive confirmation of sim health
4715 // 4931 //
4932
4933 flags = 0;
4934 message = String.Empty;
4935
4936 CheckHeartbeat();
4937
4938 if (m_firstHeartbeat || (m_lastIncoming == 0 && m_lastOutgoing == 0))
4939 {
4940 // We're still starting
4941 // 0 means "in startup", it can't happen another way, since
4942 // to get here, we must be able to accept http connections
4943 return 0;
4944 }
4945
4716 int health=1; // Start at 1, means we're up 4946 int health=1; // Start at 1, means we're up
4717 4947
4718 if ((Util.EnvironmentTickCountSubtract(m_lastFrameTick)) < 1000) 4948 if ((Util.EnvironmentTickCountSubtract(m_lastFrameTick)) < 1000)
4719 health += 1; 4949 {
4950 health+=1;
4951 flags |= 1;
4952 }
4953
4954 if (Util.EnvironmentTickCountSubtract(m_lastIncoming) < 1000)
4955 {
4956 health+=1;
4957 flags |= 2;
4958 }
4959
4960 if (Util.EnvironmentTickCountSubtract(m_lastOutgoing) < 1000)
4961 {
4962 health+=1;
4963 flags |= 4;
4964 }
4720 else 4965 else
4966 {
4967int pid = System.Diagnostics.Process.GetCurrentProcess().Id;
4968System.Diagnostics.Process proc = new System.Diagnostics.Process();
4969proc.EnableRaisingEvents=false;
4970proc.StartInfo.FileName = "/bin/kill";
4971proc.StartInfo.Arguments = "-QUIT " + pid.ToString();
4972proc.Start();
4973proc.WaitForExit();
4974Thread.Sleep(1000);
4975Environment.Exit(1);
4976 }
4977
4978 if (flags != 7)
4721 return health; 4979 return health;
4722 4980
4723 // A login in the last 4 mins? We can't be doing too badly 4981 // A login in the last 4 mins? We can't be doing too badly
4724 // 4982 //
4725 if ((Util.EnvironmentTickCountSubtract(m_LastLogin)) < 240000) 4983 if (Util.EnvironmentTickCountSubtract(m_LastLogin) < 240000)
4726 health++; 4984 health++;
4727 else 4985 else
4728 return health; 4986 return health;
4729 4987
4730// CheckHeartbeat();
4731
4732 return health; 4988 return health;
4733 } 4989 }
4734 4990
@@ -4816,7 +5072,7 @@ namespace OpenSim.Region.Framework.Scenes
4816 bool wasUsingPhysics = ((jointProxyObject.Flags & PrimFlags.Physics) != 0); 5072 bool wasUsingPhysics = ((jointProxyObject.Flags & PrimFlags.Physics) != 0);
4817 if (wasUsingPhysics) 5073 if (wasUsingPhysics)
4818 { 5074 {
4819 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 5075 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
4820 } 5076 }
4821 } 5077 }
4822 5078
@@ -4915,14 +5171,14 @@ namespace OpenSim.Region.Framework.Scenes
4915 return (((vsn.X * xdiff) + (vsn.Y * ydiff)) / (-1 * vsn.Z)) + p0.Z; 5171 return (((vsn.X * xdiff) + (vsn.Y * ydiff)) / (-1 * vsn.Z)) + p0.Z;
4916 } 5172 }
4917 5173
4918// private void CheckHeartbeat() 5174 private void CheckHeartbeat()
4919// { 5175 {
4920// if (m_firstHeartbeat) 5176 if (m_firstHeartbeat)
4921// return; 5177 return;
4922// 5178
4923// if (Util.EnvironmentTickCountSubtract(m_lastFrameTick) > 2000) 5179 if ((Util.EnvironmentTickCountSubtract(m_lastFrameTick)) > 5000)
4924// StartTimer(); 5180 Start();
4925// } 5181 }
4926 5182
4927 public override ISceneObject DeserializeObject(string representation) 5183 public override ISceneObject DeserializeObject(string representation)
4928 { 5184 {
@@ -4934,9 +5190,14 @@ namespace OpenSim.Region.Framework.Scenes
4934 get { return m_allowScriptCrossings; } 5190 get { return m_allowScriptCrossings; }
4935 } 5191 }
4936 5192
4937 public Vector3? GetNearestAllowedPosition(ScenePresence avatar) 5193 public Vector3 GetNearestAllowedPosition(ScenePresence avatar)
4938 { 5194 {
4939 ILandObject nearestParcel = GetNearestAllowedParcel(avatar.UUID, avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y); 5195 return GetNearestAllowedPosition(avatar, null);
5196 }
5197
5198 public Vector3 GetNearestAllowedPosition(ScenePresence avatar, ILandObject excludeParcel)
5199 {
5200 ILandObject nearestParcel = GetNearestAllowedParcel(avatar.UUID, avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y, excludeParcel);
4940 5201
4941 if (nearestParcel != null) 5202 if (nearestParcel != null)
4942 { 5203 {
@@ -4945,10 +5206,7 @@ namespace OpenSim.Region.Framework.Scenes
4945 Vector3? nearestPoint = GetNearestPointInParcelAlongDirectionFromPoint(avatar.AbsolutePosition, dir, nearestParcel); 5206 Vector3? nearestPoint = GetNearestPointInParcelAlongDirectionFromPoint(avatar.AbsolutePosition, dir, nearestParcel);
4946 if (nearestPoint != null) 5207 if (nearestPoint != null)
4947 { 5208 {
4948// m_log.DebugFormat( 5209 Debug.WriteLine("Found a sane previous position based on velocity, sending them to: " + nearestPoint.ToString());
4949// "[SCENE]: Found a sane previous position based on velocity for {0}, sending them to {1} in {2}",
4950// avatar.Name, nearestPoint, nearestParcel.LandData.Name);
4951
4952 return nearestPoint.Value; 5210 return nearestPoint.Value;
4953 } 5211 }
4954 5212
@@ -4958,17 +5216,20 @@ namespace OpenSim.Region.Framework.Scenes
4958 nearestPoint = GetNearestPointInParcelAlongDirectionFromPoint(avatar.AbsolutePosition, dir, nearestParcel); 5216 nearestPoint = GetNearestPointInParcelAlongDirectionFromPoint(avatar.AbsolutePosition, dir, nearestParcel);
4959 if (nearestPoint != null) 5217 if (nearestPoint != null)
4960 { 5218 {
4961// m_log.DebugFormat( 5219 Debug.WriteLine("They had a zero velocity, sending them to: " + nearestPoint.ToString());
4962// "[SCENE]: {0} had a zero velocity, sending them to {1}", avatar.Name, nearestPoint);
4963
4964 return nearestPoint.Value; 5220 return nearestPoint.Value;
4965 } 5221 }
4966 5222
4967 //Ultimate backup if we have no idea where they are 5223 ILandObject dest = LandChannel.GetLandObject(avatar.lastKnownAllowedPosition.X, avatar.lastKnownAllowedPosition.Y);
4968// m_log.DebugFormat( 5224 if (dest != excludeParcel)
4969// "[SCENE]: No idea where {0} is, sending them to {1}", avatar.Name, avatar.lastKnownAllowedPosition); 5225 {
5226 // Ultimate backup if we have no idea where they are and
5227 // the last allowed position was in another parcel
5228 Debug.WriteLine("Have no idea where they are, sending them to: " + avatar.lastKnownAllowedPosition.ToString());
5229 return avatar.lastKnownAllowedPosition;
5230 }
4970 5231
4971 return avatar.lastKnownAllowedPosition; 5232 // else fall through to region edge
4972 } 5233 }
4973 5234
4974 //Go to the edge, this happens in teleporting to a region with no available parcels 5235 //Go to the edge, this happens in teleporting to a region with no available parcels
@@ -5002,13 +5263,18 @@ namespace OpenSim.Region.Framework.Scenes
5002 5263
5003 public ILandObject GetNearestAllowedParcel(UUID avatarId, float x, float y) 5264 public ILandObject GetNearestAllowedParcel(UUID avatarId, float x, float y)
5004 { 5265 {
5266 return GetNearestAllowedParcel(avatarId, x, y, null);
5267 }
5268
5269 public ILandObject GetNearestAllowedParcel(UUID avatarId, float x, float y, ILandObject excludeParcel)
5270 {
5005 List<ILandObject> all = AllParcels(); 5271 List<ILandObject> all = AllParcels();
5006 float minParcelDistance = float.MaxValue; 5272 float minParcelDistance = float.MaxValue;
5007 ILandObject nearestParcel = null; 5273 ILandObject nearestParcel = null;
5008 5274
5009 foreach (var parcel in all) 5275 foreach (var parcel in all)
5010 { 5276 {
5011 if (!parcel.IsEitherBannedOrRestricted(avatarId)) 5277 if (!parcel.IsEitherBannedOrRestricted(avatarId) && parcel != excludeParcel)
5012 { 5278 {
5013 float parcelDistance = GetParcelDistancefromPoint(parcel, x, y); 5279 float parcelDistance = GetParcelDistancefromPoint(parcel, x, y);
5014 if (parcelDistance < minParcelDistance) 5280 if (parcelDistance < minParcelDistance)
@@ -5250,7 +5516,55 @@ namespace OpenSim.Region.Framework.Scenes
5250 mapModule.GenerateMaptile(); 5516 mapModule.GenerateMaptile();
5251 } 5517 }
5252 5518
5253 private void RegenerateMaptileAndReregister(object sender, ElapsedEventArgs e) 5519// public void CleanDroppedAttachments()
5520// {
5521// List<SceneObjectGroup> objectsToDelete =
5522// new List<SceneObjectGroup>();
5523//
5524// lock (m_cleaningAttachments)
5525// {
5526// ForEachSOG(delegate (SceneObjectGroup grp)
5527// {
5528// if (grp.RootPart.Shape.PCode == 0 && grp.RootPart.Shape.State != 0 && (!objectsToDelete.Contains(grp)))
5529// {
5530// UUID agentID = grp.OwnerID;
5531// if (agentID == UUID.Zero)
5532// {
5533// objectsToDelete.Add(grp);
5534// return;
5535// }
5536//
5537// ScenePresence sp = GetScenePresence(agentID);
5538// if (sp == null)
5539// {
5540// objectsToDelete.Add(grp);
5541// return;
5542// }
5543// }
5544// });
5545// }
5546//
5547// foreach (SceneObjectGroup grp in objectsToDelete)
5548// {
5549// m_log.InfoFormat("[SCENE]: Deleting dropped attachment {0} of user {1}", grp.UUID, grp.OwnerID);
5550// DeleteSceneObject(grp, true);
5551// }
5552// }
5553
5554 public void ThreadAlive(int threadCode)
5555 {
5556 switch(threadCode)
5557 {
5558 case 1: // Incoming
5559 m_lastIncoming = Util.EnvironmentTickCount();
5560 break;
5561 case 2: // Incoming
5562 m_lastOutgoing = Util.EnvironmentTickCount();
5563 break;
5564 }
5565 }
5566
5567 public void RegenerateMaptileAndReregister(object sender, ElapsedEventArgs e)
5254 { 5568 {
5255 RegenerateMaptile(); 5569 RegenerateMaptile();
5256 5570
@@ -5278,6 +5592,8 @@ namespace OpenSim.Region.Framework.Scenes
5278 /// <returns></returns> 5592 /// <returns></returns>
5279 public bool QueryAccess(UUID agentID, Vector3 position, out string reason) 5593 public bool QueryAccess(UUID agentID, Vector3 position, out string reason)
5280 { 5594 {
5595 reason = "You are banned from the region";
5596
5281 if (EntityTransferModule.IsInTransit(agentID)) 5597 if (EntityTransferModule.IsInTransit(agentID))
5282 { 5598 {
5283 reason = "Agent is still in transit from this region"; 5599 reason = "Agent is still in transit from this region";
@@ -5289,6 +5605,12 @@ namespace OpenSim.Region.Framework.Scenes
5289 return false; 5605 return false;
5290 } 5606 }
5291 5607
5608 if (Permissions.IsGod(agentID))
5609 {
5610 reason = String.Empty;
5611 return true;
5612 }
5613
5292 // FIXME: Root agent count is currently known to be inaccurate. This forces a recount before we check. 5614 // FIXME: Root agent count is currently known to be inaccurate. This forces a recount before we check.
5293 // However, the long term fix is to make sure root agent count is always accurate. 5615 // However, the long term fix is to make sure root agent count is always accurate.
5294 m_sceneGraph.RecalculateStats(); 5616 m_sceneGraph.RecalculateStats();
@@ -5309,6 +5631,41 @@ namespace OpenSim.Region.Framework.Scenes
5309 } 5631 }
5310 } 5632 }
5311 5633
5634 ScenePresence presence = GetScenePresence(agentID);
5635 IClientAPI client = null;
5636 AgentCircuitData aCircuit = null;
5637
5638 if (presence != null)
5639 {
5640 client = presence.ControllingClient;
5641 if (client != null)
5642 aCircuit = client.RequestClientInfo();
5643 }
5644
5645 // We may be called before there is a presence or a client.
5646 // Fake AgentCircuitData to keep IAuthorizationModule smiling
5647 if (client == null)
5648 {
5649 aCircuit = new AgentCircuitData();
5650 aCircuit.AgentID = agentID;
5651 aCircuit.firstname = String.Empty;
5652 aCircuit.lastname = String.Empty;
5653 }
5654
5655 try
5656 {
5657 if (!AuthorizeUser(aCircuit, out reason))
5658 {
5659 // m_log.DebugFormat("[SCENE]: Denying access for {0}", agentID);
5660 return false;
5661 }
5662 }
5663 catch (Exception e)
5664 {
5665 m_log.DebugFormat("[SCENE]: Exception authorizing agent: {0} "+ e.StackTrace, e.Message);
5666 return false;
5667 }
5668
5312 if (position == Vector3.Zero) // Teleport 5669 if (position == Vector3.Zero) // Teleport
5313 { 5670 {
5314 if (!RegionInfo.EstateSettings.AllowDirectTeleport) 5671 if (!RegionInfo.EstateSettings.AllowDirectTeleport)
@@ -5337,13 +5694,46 @@ namespace OpenSim.Region.Framework.Scenes
5337 } 5694 }
5338 } 5695 }
5339 } 5696 }
5697
5698 float posX = 128.0f;
5699 float posY = 128.0f;
5700
5701 if (!TestLandRestrictions(agentID, out reason, ref posX, ref posY))
5702 {
5703 // m_log.DebugFormat("[SCENE]: Denying {0} because they are banned on all parcels", agentID);
5704 return false;
5705 }
5706 }
5707 else // Walking
5708 {
5709 ILandObject land = LandChannel.GetLandObject(position.X, position.Y);
5710 if (land == null)
5711 return false;
5712
5713 bool banned = land.IsBannedFromLand(agentID);
5714 bool restricted = land.IsRestrictedFromLand(agentID);
5715
5716 if (banned || restricted)
5717 return false;
5340 } 5718 }
5341 5719
5342 reason = String.Empty; 5720 reason = String.Empty;
5343 return true; 5721 return true;
5344 } 5722 }
5345 5723
5346 /// <summary> 5724 public void StartTimerWatchdog()
5725 {
5726 m_timerWatchdog.Interval = 1000;
5727 m_timerWatchdog.Elapsed += TimerWatchdog;
5728 m_timerWatchdog.AutoReset = true;
5729 m_timerWatchdog.Start();
5730 }
5731
5732 public void TimerWatchdog(object sender, ElapsedEventArgs e)
5733 {
5734 CheckHeartbeat();
5735 }
5736
5347 /// This method deals with movement when an avatar is automatically moving (but this is distinct from the 5737 /// This method deals with movement when an avatar is automatically moving (but this is distinct from the
5348 /// autopilot that moves an avatar to a sit target!. 5738 /// autopilot that moves an avatar to a sit target!.
5349 /// </summary> 5739 /// </summary>
@@ -5422,6 +5812,11 @@ namespace OpenSim.Region.Framework.Scenes
5422 return m_SpawnPoint - 1; 5812 return m_SpawnPoint - 1;
5423 } 5813 }
5424 5814
5815 private void HandleGcCollect(string module, string[] args)
5816 {
5817 GC.Collect();
5818 }
5819
5425 // Wrappers to get physics modules retrieve assets. Has to be done this way 5820 // Wrappers to get physics modules retrieve assets. Has to be done this way
5426 // because we can't assign the asset service to physics directly - at the 5821 // because we can't assign the asset service to physics directly - at the
5427 // time physics are instantiated it's not registered but it will be by 5822 // 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 13842ad..e0260e2 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(
@@ -478,6 +524,30 @@ namespace OpenSim.Region.Framework.Scenes
478 m_updateList[obj.UUID] = obj; 524 m_updateList[obj.UUID] = obj;
479 } 525 }
480 526
527 public void FireAttachToBackup(SceneObjectGroup obj)
528 {
529 if (OnAttachToBackup != null)
530 {
531 OnAttachToBackup(obj);
532 }
533 }
534
535 public void FireDetachFromBackup(SceneObjectGroup obj)
536 {
537 if (OnDetachFromBackup != null)
538 {
539 OnDetachFromBackup(obj);
540 }
541 }
542
543 public void FireChangeBackup(SceneObjectGroup obj)
544 {
545 if (OnChangeBackup != null)
546 {
547 OnChangeBackup(obj);
548 }
549 }
550
481 /// <summary> 551 /// <summary>
482 /// Process all pending updates 552 /// Process all pending updates
483 /// </summary> 553 /// </summary>
@@ -522,12 +592,12 @@ namespace OpenSim.Region.Framework.Scenes
522 592
523 protected internal void AddPhysicalPrim(int number) 593 protected internal void AddPhysicalPrim(int number)
524 { 594 {
525 m_physicalPrim++; 595 m_physicalPrim += number;
526 } 596 }
527 597
528 protected internal void RemovePhysicalPrim(int number) 598 protected internal void RemovePhysicalPrim(int number)
529 { 599 {
530 m_physicalPrim--; 600 m_physicalPrim -= number;
531 } 601 }
532 602
533 protected internal void AddToScriptLPS(int number) 603 protected internal void AddToScriptLPS(int number)
@@ -595,7 +665,8 @@ namespace OpenSim.Region.Framework.Scenes
595 665
596 Entities[presence.UUID] = presence; 666 Entities[presence.UUID] = presence;
597 667
598 lock (m_presenceLock) 668 m_scenePresencesLock.EnterWriteLock();
669 try
599 { 670 {
600 Dictionary<UUID, ScenePresence> newmap = new Dictionary<UUID, ScenePresence>(m_scenePresenceMap); 671 Dictionary<UUID, ScenePresence> newmap = new Dictionary<UUID, ScenePresence>(m_scenePresenceMap);
601 List<ScenePresence> newlist = new List<ScenePresence>(m_scenePresenceArray); 672 List<ScenePresence> newlist = new List<ScenePresence>(m_scenePresenceArray);
@@ -619,6 +690,10 @@ namespace OpenSim.Region.Framework.Scenes
619 m_scenePresenceMap = newmap; 690 m_scenePresenceMap = newmap;
620 m_scenePresenceArray = newlist; 691 m_scenePresenceArray = newlist;
621 } 692 }
693 finally
694 {
695 m_scenePresencesLock.ExitWriteLock();
696 }
622 } 697 }
623 698
624 /// <summary> 699 /// <summary>
@@ -633,7 +708,8 @@ namespace OpenSim.Region.Framework.Scenes
633 agentID); 708 agentID);
634 } 709 }
635 710
636 lock (m_presenceLock) 711 m_scenePresencesLock.EnterWriteLock();
712 try
637 { 713 {
638 Dictionary<UUID, ScenePresence> newmap = new Dictionary<UUID, ScenePresence>(m_scenePresenceMap); 714 Dictionary<UUID, ScenePresence> newmap = new Dictionary<UUID, ScenePresence>(m_scenePresenceMap);
639 List<ScenePresence> newlist = new List<ScenePresence>(m_scenePresenceArray); 715 List<ScenePresence> newlist = new List<ScenePresence>(m_scenePresenceArray);
@@ -655,6 +731,10 @@ namespace OpenSim.Region.Framework.Scenes
655 m_log.WarnFormat("[SCENE GRAPH]: Tried to remove non-existent scene presence with agent ID {0} from scene ScenePresences list", agentID); 731 m_log.WarnFormat("[SCENE GRAPH]: Tried to remove non-existent scene presence with agent ID {0} from scene ScenePresences list", agentID);
656 } 732 }
657 } 733 }
734 finally
735 {
736 m_scenePresencesLock.ExitWriteLock();
737 }
658 } 738 }
659 739
660 protected internal void SwapRootChildAgent(bool direction_RC_CR_T_F) 740 protected internal void SwapRootChildAgent(bool direction_RC_CR_T_F)
@@ -1184,6 +1264,52 @@ namespace OpenSim.Region.Framework.Scenes
1184 1264
1185 #region Client Event handlers 1265 #region Client Event handlers
1186 1266
1267 protected internal void ClientChangeObject(uint localID, object odata, IClientAPI remoteClient)
1268 {
1269 SceneObjectPart part = GetSceneObjectPart(localID);
1270 ObjectChangeData data = (ObjectChangeData)odata;
1271
1272 if (part != null)
1273 {
1274 SceneObjectGroup grp = part.ParentGroup;
1275 if (grp != null)
1276 {
1277 if (m_parentScene.Permissions.CanEditObject(grp.UUID, remoteClient.AgentId))
1278 {
1279 // These two are exceptions SL makes in the interpretation
1280 // of the change flags. Must check them here because otherwise
1281 // the group flag (see below) would be lost
1282 if (data.change == ObjectChangeType.groupS)
1283 data.change = ObjectChangeType.primS;
1284 if (data.change == ObjectChangeType.groupPS)
1285 data.change = ObjectChangeType.primPS;
1286 part.StoreUndoState(data.change); // lets test only saving what we changed
1287 grp.doChangeObject(part, (ObjectChangeData)data);
1288 }
1289 else
1290 {
1291 // Is this any kind of group operation?
1292 if ((data.change & ObjectChangeType.Group) != 0)
1293 {
1294 // Is a move and/or rotation requested?
1295 if ((data.change & (ObjectChangeType.Position | ObjectChangeType.Rotation)) != 0)
1296 {
1297 // Are we allowed to move it?
1298 if (m_parentScene.Permissions.CanMoveObject(grp.UUID, remoteClient.AgentId))
1299 {
1300 // Strip all but move and rotation from request
1301 data.change &= (ObjectChangeType.Group | ObjectChangeType.Position | ObjectChangeType.Rotation);
1302
1303 part.StoreUndoState(data.change);
1304 grp.doChangeObject(part, (ObjectChangeData)data);
1305 }
1306 }
1307 }
1308 }
1309 }
1310 }
1311 }
1312
1187 /// <summary> 1313 /// <summary>
1188 /// Update the scale of an individual prim. 1314 /// Update the scale of an individual prim.
1189 /// </summary> 1315 /// </summary>
@@ -1198,7 +1324,17 @@ namespace OpenSim.Region.Framework.Scenes
1198 { 1324 {
1199 if (m_parentScene.Permissions.CanEditObject(part.ParentGroup.UUID, remoteClient.AgentId)) 1325 if (m_parentScene.Permissions.CanEditObject(part.ParentGroup.UUID, remoteClient.AgentId))
1200 { 1326 {
1327 bool physbuild = false;
1328 if (part.ParentGroup.RootPart.PhysActor != null)
1329 {
1330 part.ParentGroup.RootPart.PhysActor.Building = true;
1331 physbuild = true;
1332 }
1333
1201 part.Resize(scale); 1334 part.Resize(scale);
1335
1336 if (physbuild)
1337 part.ParentGroup.RootPart.PhysActor.Building = false;
1202 } 1338 }
1203 } 1339 }
1204 } 1340 }
@@ -1210,7 +1346,17 @@ namespace OpenSim.Region.Framework.Scenes
1210 { 1346 {
1211 if (m_parentScene.Permissions.CanEditObject(group.UUID, remoteClient.AgentId)) 1347 if (m_parentScene.Permissions.CanEditObject(group.UUID, remoteClient.AgentId))
1212 { 1348 {
1349 bool physbuild = false;
1350 if (group.RootPart.PhysActor != null)
1351 {
1352 group.RootPart.PhysActor.Building = true;
1353 physbuild = true;
1354 }
1355
1213 group.GroupResize(scale); 1356 group.GroupResize(scale);
1357
1358 if (physbuild)
1359 group.RootPart.PhysActor.Building = false;
1214 } 1360 }
1215 } 1361 }
1216 } 1362 }
@@ -1338,8 +1484,13 @@ namespace OpenSim.Region.Framework.Scenes
1338 { 1484 {
1339 if (group.IsAttachment || (group.RootPart.Shape.PCode == 9 && group.RootPart.Shape.State != 0)) 1485 if (group.IsAttachment || (group.RootPart.Shape.PCode == 9 && group.RootPart.Shape.State != 0))
1340 { 1486 {
1341 if (m_parentScene.AttachmentsModule != null) 1487 // Set the new attachment point data in the object
1342 m_parentScene.AttachmentsModule.UpdateAttachmentPosition(group, pos); 1488 byte attachmentPoint = group.GetAttachmentPoint();
1489 group.UpdateGroupPosition(pos);
1490 group.IsAttachment = false;
1491 group.AbsolutePosition = group.RootPart.AttachedPos;
1492 group.AttachmentPoint = attachmentPoint;
1493 group.HasGroupChanged = true;
1343 } 1494 }
1344 else 1495 else
1345 { 1496 {
@@ -1387,7 +1538,7 @@ namespace OpenSim.Region.Framework.Scenes
1387 /// <param name="SetPhantom"></param> 1538 /// <param name="SetPhantom"></param>
1388 /// <param name="remoteClient"></param> 1539 /// <param name="remoteClient"></param>
1389 protected internal void UpdatePrimFlags( 1540 protected internal void UpdatePrimFlags(
1390 uint localID, bool UsePhysics, bool SetTemporary, bool SetPhantom, IClientAPI remoteClient) 1541 uint localID, bool UsePhysics, bool SetTemporary, bool SetPhantom, ExtraPhysicsData PhysData, IClientAPI remoteClient)
1391 { 1542 {
1392 SceneObjectGroup group = GetGroupByPrim(localID); 1543 SceneObjectGroup group = GetGroupByPrim(localID);
1393 if (group != null) 1544 if (group != null)
@@ -1395,7 +1546,28 @@ namespace OpenSim.Region.Framework.Scenes
1395 if (m_parentScene.Permissions.CanEditObject(group.UUID, remoteClient.AgentId)) 1546 if (m_parentScene.Permissions.CanEditObject(group.UUID, remoteClient.AgentId))
1396 { 1547 {
1397 // VolumeDetect can't be set via UI and will always be off when a change is made there 1548 // VolumeDetect can't be set via UI and will always be off when a change is made there
1398 group.UpdatePrimFlags(localID, UsePhysics, SetTemporary, SetPhantom, false); 1549 // now only change volume dtc if phantom off
1550
1551 if (PhysData.PhysShapeType == PhysShapeType.invalid) // check for extraPhysics data
1552 {
1553 bool vdtc;
1554 if (SetPhantom) // if phantom keep volumedtc
1555 vdtc = group.RootPart.VolumeDetectActive;
1556 else // else turn it off
1557 vdtc = false;
1558
1559 group.UpdatePrimFlags(localID, UsePhysics, SetTemporary, SetPhantom, vdtc);
1560 }
1561 else
1562 {
1563 SceneObjectPart part = GetSceneObjectPart(localID);
1564 if (part != null)
1565 {
1566 part.UpdateExtraPhysics(PhysData);
1567 if (part.UpdatePhysRequired)
1568 remoteClient.SendPartPhysicsProprieties(part);
1569 }
1570 }
1399 } 1571 }
1400 } 1572 }
1401 } 1573 }
@@ -1539,6 +1711,7 @@ namespace OpenSim.Region.Framework.Scenes
1539 { 1711 {
1540 part.Material = Convert.ToByte(material); 1712 part.Material = Convert.ToByte(material);
1541 group.HasGroupChanged = true; 1713 group.HasGroupChanged = true;
1714 remoteClient.SendPartPhysicsProprieties(part);
1542 } 1715 }
1543 } 1716 }
1544 } 1717 }
@@ -1603,6 +1776,12 @@ namespace OpenSim.Region.Framework.Scenes
1603 /// <param name="childPrims"></param> 1776 /// <param name="childPrims"></param>
1604 protected internal void LinkObjects(SceneObjectPart root, List<SceneObjectPart> children) 1777 protected internal void LinkObjects(SceneObjectPart root, List<SceneObjectPart> children)
1605 { 1778 {
1779 if (root.KeyframeMotion != null)
1780 {
1781 root.KeyframeMotion.Stop();
1782 root.KeyframeMotion = null;
1783 }
1784
1606 SceneObjectGroup parentGroup = root.ParentGroup; 1785 SceneObjectGroup parentGroup = root.ParentGroup;
1607 if (parentGroup == null) return; 1786 if (parentGroup == null) return;
1608 1787
@@ -1611,8 +1790,11 @@ namespace OpenSim.Region.Framework.Scenes
1611 return; 1790 return;
1612 1791
1613 Monitor.Enter(m_updateLock); 1792 Monitor.Enter(m_updateLock);
1793
1614 try 1794 try
1615 { 1795 {
1796 parentGroup.areUpdatesSuspended = true;
1797
1616 List<SceneObjectGroup> childGroups = new List<SceneObjectGroup>(); 1798 List<SceneObjectGroup> childGroups = new List<SceneObjectGroup>();
1617 1799
1618 // We do this in reverse to get the link order of the prims correct 1800 // We do this in reverse to get the link order of the prims correct
@@ -1627,9 +1809,13 @@ namespace OpenSim.Region.Framework.Scenes
1627 // Make sure no child prim is set for sale 1809 // Make sure no child prim is set for sale
1628 // So that, on delink, no prims are unwittingly 1810 // So that, on delink, no prims are unwittingly
1629 // left for sale and sold off 1811 // left for sale and sold off
1630 child.RootPart.ObjectSaleType = 0; 1812
1631 child.RootPart.SalePrice = 10; 1813 if (child != null)
1632 childGroups.Add(child); 1814 {
1815 child.RootPart.ObjectSaleType = 0;
1816 child.RootPart.SalePrice = 10;
1817 childGroups.Add(child);
1818 }
1633 } 1819 }
1634 1820
1635 foreach (SceneObjectGroup child in childGroups) 1821 foreach (SceneObjectGroup child in childGroups)
@@ -1658,6 +1844,16 @@ namespace OpenSim.Region.Framework.Scenes
1658 } 1844 }
1659 finally 1845 finally
1660 { 1846 {
1847 lock (SceneObjectGroupsByLocalPartID)
1848 {
1849 foreach (SceneObjectPart part in parentGroup.Parts)
1850 SceneObjectGroupsByLocalPartID[part.LocalId] = parentGroup;
1851 }
1852
1853 parentGroup.areUpdatesSuspended = false;
1854 parentGroup.HasGroupChanged = true;
1855 parentGroup.ProcessBackup(m_parentScene.SimulationDataService, true);
1856 parentGroup.ScheduleGroupForFullUpdate();
1661 Monitor.Exit(m_updateLock); 1857 Monitor.Exit(m_updateLock);
1662 } 1858 }
1663 } 1859 }
@@ -1680,6 +1876,11 @@ namespace OpenSim.Region.Framework.Scenes
1680 { 1876 {
1681 if (part != null) 1877 if (part != null)
1682 { 1878 {
1879 if (part.KeyframeMotion != null)
1880 {
1881 part.KeyframeMotion.Stop();
1882 part.KeyframeMotion = null;
1883 }
1683 if (part.ParentGroup.PrimCount != 1) // Skip single 1884 if (part.ParentGroup.PrimCount != 1) // Skip single
1684 { 1885 {
1685 if (part.LinkNum < 2) // Root 1886 if (part.LinkNum < 2) // Root
@@ -1694,21 +1895,24 @@ namespace OpenSim.Region.Framework.Scenes
1694 1895
1695 SceneObjectGroup group = part.ParentGroup; 1896 SceneObjectGroup group = part.ParentGroup;
1696 if (!affectedGroups.Contains(group)) 1897 if (!affectedGroups.Contains(group))
1898 {
1899 group.areUpdatesSuspended = true;
1697 affectedGroups.Add(group); 1900 affectedGroups.Add(group);
1901 }
1698 } 1902 }
1699 } 1903 }
1700 } 1904 }
1701 1905
1702 foreach (SceneObjectPart child in childParts) 1906 if (childParts.Count > 0)
1703 { 1907 {
1704 // Unlink all child parts from their groups 1908 foreach (SceneObjectPart child in childParts)
1705 // 1909 {
1706 child.ParentGroup.DelinkFromGroup(child, true); 1910 // Unlink all child parts from their groups
1707 1911 //
1708 // These are not in affected groups and will not be 1912 child.ParentGroup.DelinkFromGroup(child, true);
1709 // handled further. Do the honors here. 1913 child.ParentGroup.HasGroupChanged = true;
1710 child.ParentGroup.HasGroupChanged = true; 1914 child.ParentGroup.ScheduleGroupForFullUpdate();
1711 child.ParentGroup.ScheduleGroupForFullUpdate(); 1915 }
1712 } 1916 }
1713 1917
1714 foreach (SceneObjectPart root in rootParts) 1918 foreach (SceneObjectPart root in rootParts)
@@ -1718,56 +1922,68 @@ namespace OpenSim.Region.Framework.Scenes
1718 // However, editing linked parts and unlinking may be different 1922 // However, editing linked parts and unlinking may be different
1719 // 1923 //
1720 SceneObjectGroup group = root.ParentGroup; 1924 SceneObjectGroup group = root.ParentGroup;
1925 group.areUpdatesSuspended = true;
1721 1926
1722 List<SceneObjectPart> newSet = new List<SceneObjectPart>(group.Parts); 1927 List<SceneObjectPart> newSet = new List<SceneObjectPart>(group.Parts);
1723 int numChildren = newSet.Count; 1928 int numChildren = newSet.Count;
1724 1929
1930 if (numChildren == 1)
1931 break;
1932
1725 // If there are prims left in a link set, but the root is 1933 // If there are prims left in a link set, but the root is
1726 // slated for unlink, we need to do this 1934 // slated for unlink, we need to do this
1935 // Unlink the remaining set
1727 // 1936 //
1728 if (numChildren != 1) 1937 bool sendEventsToRemainder = true;
1729 { 1938 if (numChildren > 1)
1730 // Unlink the remaining set 1939 sendEventsToRemainder = false;
1731 //
1732 bool sendEventsToRemainder = true;
1733 if (numChildren > 1)
1734 sendEventsToRemainder = false;
1735 1940
1736 foreach (SceneObjectPart p in newSet) 1941 foreach (SceneObjectPart p in newSet)
1942 {
1943 if (p != group.RootPart)
1737 { 1944 {
1738 if (p != group.RootPart) 1945 group.DelinkFromGroup(p, sendEventsToRemainder);
1739 group.DelinkFromGroup(p, sendEventsToRemainder); 1946 if (numChildren > 2)
1947 {
1948 p.ParentGroup.areUpdatesSuspended = true;
1949 }
1950 else
1951 {
1952 p.ParentGroup.HasGroupChanged = true;
1953 p.ParentGroup.ScheduleGroupForFullUpdate();
1954 }
1740 } 1955 }
1956 }
1957
1958 // If there is more than one prim remaining, we
1959 // need to re-link
1960 //
1961 if (numChildren > 2)
1962 {
1963 // Remove old root
1964 //
1965 if (newSet.Contains(root))
1966 newSet.Remove(root);
1741 1967
1742 // If there is more than one prim remaining, we 1968 // Preserve link ordering
1743 // need to re-link
1744 // 1969 //
1745 if (numChildren > 2) 1970 newSet.Sort(delegate (SceneObjectPart a, SceneObjectPart b)
1746 { 1971 {
1747 // Remove old root 1972 return a.LinkNum.CompareTo(b.LinkNum);
1748 // 1973 });
1749 if (newSet.Contains(root))
1750 newSet.Remove(root);
1751
1752 // Preserve link ordering
1753 //
1754 newSet.Sort(delegate (SceneObjectPart a, SceneObjectPart b)
1755 {
1756 return a.LinkNum.CompareTo(b.LinkNum);
1757 });
1758 1974
1759 // Determine new root 1975 // Determine new root
1760 // 1976 //
1761 SceneObjectPart newRoot = newSet[0]; 1977 SceneObjectPart newRoot = newSet[0];
1762 newSet.RemoveAt(0); 1978 newSet.RemoveAt(0);
1763 1979
1764 foreach (SceneObjectPart newChild in newSet) 1980 foreach (SceneObjectPart newChild in newSet)
1765 newChild.ClearUpdateSchedule(); 1981 newChild.ClearUpdateSchedule();
1766 1982
1767 LinkObjects(newRoot, newSet); 1983 newRoot.ParentGroup.areUpdatesSuspended = true;
1768 if (!affectedGroups.Contains(newRoot.ParentGroup)) 1984 LinkObjects(newRoot, newSet);
1769 affectedGroups.Add(newRoot.ParentGroup); 1985 if (!affectedGroups.Contains(newRoot.ParentGroup))
1770 } 1986 affectedGroups.Add(newRoot.ParentGroup);
1771 } 1987 }
1772 } 1988 }
1773 1989
@@ -1775,8 +1991,14 @@ namespace OpenSim.Region.Framework.Scenes
1775 // 1991 //
1776 foreach (SceneObjectGroup g in affectedGroups) 1992 foreach (SceneObjectGroup g in affectedGroups)
1777 { 1993 {
1994 // Child prims that have been unlinked and deleted will
1995 // return unless the root is deleted. This will remove them
1996 // from the database. They will be rewritten immediately,
1997 // minus the rows for the unlinked child prims.
1998 m_parentScene.SimulationDataService.RemoveObject(g.UUID, m_parentScene.RegionInfo.RegionID);
1778 g.TriggerScriptChangedEvent(Changed.LINK); 1999 g.TriggerScriptChangedEvent(Changed.LINK);
1779 g.HasGroupChanged = true; // Persist 2000 g.HasGroupChanged = true; // Persist
2001 g.areUpdatesSuspended = false;
1780 g.ScheduleGroupForFullUpdate(); 2002 g.ScheduleGroupForFullUpdate();
1781 } 2003 }
1782 } 2004 }
@@ -1848,108 +2070,96 @@ namespace OpenSim.Region.Framework.Scenes
1848 /// <param name="GroupID"></param> 2070 /// <param name="GroupID"></param>
1849 /// <param name="rot"></param> 2071 /// <param name="rot"></param>
1850 /// <returns>null if duplication fails, otherwise the duplicated object</returns> 2072 /// <returns>null if duplication fails, otherwise the duplicated object</returns>
1851 public SceneObjectGroup DuplicateObject( 2073 /// <summary>
1852 uint originalPrimID, Vector3 offset, uint flags, UUID AgentID, UUID GroupID, Quaternion rot) 2074 public SceneObjectGroup DuplicateObject(uint originalPrimID, Vector3 offset, uint flags, UUID AgentID, UUID GroupID, Quaternion rot)
1853 { 2075 {
1854 Monitor.Enter(m_updateLock); 2076// m_log.DebugFormat(
2077// "[SCENE]: Duplication of object {0} at offset {1} requested by agent {2}",
2078// originalPrimID, offset, AgentID);
1855 2079
1856 try 2080 SceneObjectGroup original = GetGroupByPrim(originalPrimID);
2081 if (original != null)
1857 { 2082 {
1858 // m_log.DebugFormat( 2083 if (m_parentScene.Permissions.CanDuplicateObject(
1859 // "[SCENE]: Duplication of object {0} at offset {1} requested by agent {2}", 2084 original.PrimCount, original.UUID, AgentID, original.AbsolutePosition))
1860 // originalPrimID, offset, AgentID);
1861
1862 SceneObjectGroup original = GetGroupByPrim(originalPrimID);
1863 if (original == null)
1864 { 2085 {
1865 m_log.WarnFormat( 2086 SceneObjectGroup copy = original.Copy(true);
1866 "[SCENEGRAPH]: Attempt to duplicate nonexistant prim id {0} by {1}", originalPrimID, AgentID); 2087 copy.AbsolutePosition = copy.AbsolutePosition + offset;
1867 2088
1868 return null; 2089 if (original.OwnerID != AgentID)
1869 } 2090 {
2091 copy.SetOwnerId(AgentID);
2092 copy.SetRootPartOwner(copy.RootPart, AgentID, GroupID);
1870 2093
1871 if (!m_parentScene.Permissions.CanDuplicateObject( 2094 SceneObjectPart[] partList = copy.Parts;
1872 original.PrimCount, original.UUID, AgentID, original.AbsolutePosition))
1873 return null;
1874 2095
1875 SceneObjectGroup copy = original.Copy(true); 2096 if (m_parentScene.Permissions.PropagatePermissions())
1876 copy.AbsolutePosition = copy.AbsolutePosition + offset; 2097 {
2098 foreach (SceneObjectPart child in partList)
2099 {
2100 child.Inventory.ChangeInventoryOwner(AgentID);
2101 child.TriggerScriptChangedEvent(Changed.OWNER);
2102 child.ApplyNextOwnerPermissions();
2103 }
2104 }
2105 }
1877 2106
1878 if (original.OwnerID != AgentID) 2107 // FIXME: This section needs to be refactored so that it just calls AddSceneObject()
1879 { 2108 Entities.Add(copy);
1880 copy.SetOwnerId(AgentID);
1881 copy.SetRootPartOwner(copy.RootPart, AgentID, GroupID);
1882 2109
1883 SceneObjectPart[] partList = copy.Parts; 2110 lock (SceneObjectGroupsByFullID)
2111 SceneObjectGroupsByFullID[copy.UUID] = copy;
1884 2112
1885 if (m_parentScene.Permissions.PropagatePermissions()) 2113 SceneObjectPart[] children = copy.Parts;
2114
2115 lock (SceneObjectGroupsByFullPartID)
1886 { 2116 {
1887 foreach (SceneObjectPart child in partList) 2117 SceneObjectGroupsByFullPartID[copy.UUID] = copy;
1888 { 2118 foreach (SceneObjectPart part in children)
1889 child.Inventory.ChangeInventoryOwner(AgentID); 2119 SceneObjectGroupsByFullPartID[part.UUID] = copy;
1890 child.TriggerScriptChangedEvent(Changed.OWNER);
1891 child.ApplyNextOwnerPermissions();
1892 }
1893 } 2120 }
1894 2121
1895 copy.RootPart.ObjectSaleType = 0; 2122 lock (SceneObjectGroupsByLocalPartID)
1896 copy.RootPart.SalePrice = 10; 2123 {
1897 } 2124 SceneObjectGroupsByLocalPartID[copy.LocalId] = copy;
2125 foreach (SceneObjectPart part in children)
2126 SceneObjectGroupsByLocalPartID[part.LocalId] = copy;
2127 }
2128 // PROBABLE END OF FIXME
1898 2129
1899 // FIXME: This section needs to be refactored so that it just calls AddSceneObject() 2130 // Since we copy from a source group that is in selected
1900 Entities.Add(copy); 2131 // state, but the copy is shown deselected in the viewer,
1901 2132 // We need to clear the selection flag here, else that
1902 lock (SceneObjectGroupsByFullID) 2133 // prim never gets persisted at all. The client doesn't
1903 SceneObjectGroupsByFullID[copy.UUID] = copy; 2134 // think it's selected, so it will never send a deselect...
1904 2135 copy.IsSelected = false;
1905 SceneObjectPart[] children = copy.Parts; 2136
1906 2137 m_numPrim += copy.Parts.Length;
1907 lock (SceneObjectGroupsByFullPartID) 2138
1908 { 2139 if (rot != Quaternion.Identity)
1909 SceneObjectGroupsByFullPartID[copy.UUID] = copy; 2140 {
1910 foreach (SceneObjectPart part in children) 2141 copy.UpdateGroupRotationR(rot);
1911 SceneObjectGroupsByFullPartID[part.UUID] = copy; 2142 }
1912 }
1913
1914 lock (SceneObjectGroupsByLocalPartID)
1915 {
1916 SceneObjectGroupsByLocalPartID[copy.LocalId] = copy;
1917 foreach (SceneObjectPart part in children)
1918 SceneObjectGroupsByLocalPartID[part.LocalId] = copy;
1919 }
1920 // PROBABLE END OF FIXME
1921
1922 // Since we copy from a source group that is in selected
1923 // state, but the copy is shown deselected in the viewer,
1924 // We need to clear the selection flag here, else that
1925 // prim never gets persisted at all. The client doesn't
1926 // think it's selected, so it will never send a deselect...
1927 copy.IsSelected = false;
1928
1929 m_numPrim += copy.Parts.Length;
1930
1931 if (rot != Quaternion.Identity)
1932 {
1933 copy.UpdateGroupRotationR(rot);
1934 }
1935 2143
1936 copy.CreateScriptInstances(0, false, m_parentScene.DefaultScriptEngine, 1); 2144 copy.CreateScriptInstances(0, false, m_parentScene.DefaultScriptEngine, 1);
1937 copy.HasGroupChanged = true; 2145 copy.HasGroupChanged = true;
1938 copy.ScheduleGroupForFullUpdate(); 2146 copy.ScheduleGroupForFullUpdate();
1939 copy.ResumeScripts(); 2147 copy.ResumeScripts();
1940 2148
1941 // required for physics to update it's position 2149 // required for physics to update it's position
1942 copy.AbsolutePosition = copy.AbsolutePosition; 2150 copy.AbsolutePosition = copy.AbsolutePosition;
1943 2151
1944 return copy; 2152 return copy;
2153 }
1945 } 2154 }
1946 finally 2155 else
1947 { 2156 {
1948 Monitor.Exit(m_updateLock); 2157 m_log.WarnFormat("[SCENE]: Attempted to duplicate nonexistant prim id {0}", GroupID);
1949 } 2158 }
2159
2160 return null;
1950 } 2161 }
1951 2162
1952 /// <summary>
1953 /// Calculates the distance between two Vector3s 2163 /// Calculates the distance between two Vector3s
1954 /// </summary> 2164 /// </summary>
1955 /// <param name="v1"></param> 2165 /// <param name="v1"></param>
diff --git a/OpenSim/Region/Framework/Scenes/SceneManager.cs b/OpenSim/Region/Framework/Scenes/SceneManager.cs
index c81b55d..f1b09ca 100644
--- a/OpenSim/Region/Framework/Scenes/SceneManager.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneManager.cs
@@ -95,12 +95,12 @@ namespace OpenSim.Region.Framework.Scenes
95 get { return m_instance; } 95 get { return m_instance; }
96 } 96 }
97 97
98 private readonly List<Scene> m_localScenes = new List<Scene>(); 98 private readonly DoubleDictionary<UUID, string, Scene> m_localScenes = new DoubleDictionary<UUID, string, Scene>();
99 private Scene m_currentScene = null; 99 private Scene m_currentScene = null;
100 100
101 public List<Scene> Scenes 101 public List<Scene> Scenes
102 { 102 {
103 get { return new List<Scene>(m_localScenes); } 103 get { return new List<Scene>(m_localScenes.FindAll(delegate(Scene s) { return true; })); }
104 } 104 }
105 105
106 public Scene CurrentScene 106 public Scene CurrentScene
@@ -114,13 +114,10 @@ namespace OpenSim.Region.Framework.Scenes
114 { 114 {
115 if (m_currentScene == null) 115 if (m_currentScene == null)
116 { 116 {
117 lock (m_localScenes) 117 List<Scene> sceneList = Scenes;
118 { 118 if (sceneList.Count == 0)
119 if (m_localScenes.Count > 0) 119 return null;
120 return m_localScenes[0]; 120 return sceneList[0];
121 else
122 return null;
123 }
124 } 121 }
125 else 122 else
126 { 123 {
@@ -132,7 +129,7 @@ namespace OpenSim.Region.Framework.Scenes
132 public SceneManager() 129 public SceneManager()
133 { 130 {
134 m_instance = this; 131 m_instance = this;
135 m_localScenes = new List<Scene>(); 132 m_localScenes = new DoubleDictionary<UUID, string, Scene>();
136 } 133 }
137 134
138 public void Close() 135 public void Close()
@@ -140,20 +137,18 @@ namespace OpenSim.Region.Framework.Scenes
140 // collect known shared modules in sharedModules 137 // collect known shared modules in sharedModules
141 Dictionary<string, IRegionModule> sharedModules = new Dictionary<string, IRegionModule>(); 138 Dictionary<string, IRegionModule> sharedModules = new Dictionary<string, IRegionModule>();
142 139
143 lock (m_localScenes) 140 List<Scene> sceneList = Scenes;
141 for (int i = 0; i < sceneList.Count; i++)
144 { 142 {
145 for (int i = 0; i < m_localScenes.Count; i++) 143 // extract known shared modules from scene
144 foreach (string k in sceneList[i].Modules.Keys)
146 { 145 {
147 // extract known shared modules from scene 146 if (sceneList[i].Modules[k].IsSharedModule &&
148 foreach (string k in m_localScenes[i].Modules.Keys) 147 !sharedModules.ContainsKey(k))
149 { 148 sharedModules[k] = sceneList[i].Modules[k];
150 if (m_localScenes[i].Modules[k].IsSharedModule &&
151 !sharedModules.ContainsKey(k))
152 sharedModules[k] = m_localScenes[i].Modules[k];
153 }
154 // close scene/region
155 m_localScenes[i].Close();
156 } 149 }
150 // close scene/region
151 sceneList[i].Close();
157 } 152 }
158 153
159 // all regions/scenes are now closed, we can now safely 154 // all regions/scenes are now closed, we can now safely
@@ -162,29 +157,21 @@ namespace OpenSim.Region.Framework.Scenes
162 { 157 {
163 mod.Close(); 158 mod.Close();
164 } 159 }
160
161 m_localScenes.Clear();
165 } 162 }
166 163
167 public void Close(Scene cscene) 164 public void Close(Scene cscene)
168 { 165 {
169 lock (m_localScenes) 166 if (!m_localScenes.ContainsKey(cscene.RegionInfo.RegionID))
170 { 167 return;
171 if (m_localScenes.Contains(cscene)) 168 cscene.Close();
172 {
173 for (int i = 0; i < m_localScenes.Count; i++)
174 {
175 if (m_localScenes[i].Equals(cscene))
176 {
177 m_localScenes[i].Close();
178 }
179 }
180 }
181 }
182 } 169 }
183 170
184 public void Add(Scene scene) 171 public void Add(Scene scene)
185 { 172 {
186 lock (m_localScenes) 173 lock (m_localScenes)
187 m_localScenes.Add(scene); 174 m_localScenes.Add(scene.RegionInfo.RegionID, scene.RegionInfo.RegionName, scene);
188 175
189 scene.OnRestart += HandleRestart; 176 scene.OnRestart += HandleRestart;
190 scene.EventManager.OnRegionReadyStatusChange += HandleRegionReadyStatusChange; 177 scene.EventManager.OnRegionReadyStatusChange += HandleRegionReadyStatusChange;
@@ -196,23 +183,7 @@ namespace OpenSim.Region.Framework.Scenes
196 int RegionSceneElement = -1; 183 int RegionSceneElement = -1;
197 184
198 lock (m_localScenes) 185 lock (m_localScenes)
199 { 186 m_localScenes.Remove(rdata.RegionID);
200 for (int i = 0; i < m_localScenes.Count; i++)
201 {
202 if (rdata.RegionName == m_localScenes[i].RegionInfo.RegionName)
203 {
204 RegionSceneElement = i;
205 }
206 }
207
208 // Now we make sure the region is no longer known about by the SceneManager
209 // Prevents duplicates.
210
211 if (RegionSceneElement >= 0)
212 {
213 m_localScenes.RemoveAt(RegionSceneElement);
214 }
215 }
216 187
217 // Send signal to main that we're restarting this sim. 188 // Send signal to main that we're restarting this sim.
218 OnRestartSim(rdata); 189 OnRestartSim(rdata);
@@ -221,39 +192,36 @@ namespace OpenSim.Region.Framework.Scenes
221 private void HandleRegionReadyStatusChange(IScene scene) 192 private void HandleRegionReadyStatusChange(IScene scene)
222 { 193 {
223 lock (m_localScenes) 194 lock (m_localScenes)
224 AllRegionsReady = m_localScenes.TrueForAll(s => s.Ready); 195 AllRegionsReady = m_localScenes.FindAll(s => !s.Ready).Count == 0;
225 } 196 }
226 197
227 public void SendSimOnlineNotification(ulong regionHandle) 198 public void SendSimOnlineNotification(ulong regionHandle)
228 { 199 {
229 RegionInfo Result = null; 200 RegionInfo Result = null;
230 201
231 lock (m_localScenes) 202 Scene s = m_localScenes.FindValue(delegate(Scene x)
232 {
233 for (int i = 0; i < m_localScenes.Count; i++)
234 {
235 if (m_localScenes[i].RegionInfo.RegionHandle == regionHandle)
236 { 203 {
237 // Inform other regions to tell their avatar about me 204 if (x.RegionInfo.RegionHandle == regionHandle)
238 Result = m_localScenes[i].RegionInfo; 205 return true;
239 } 206 return false;
240 } 207 });
241 208
242 if (Result != null) 209 if (s != null)
210 {
211 List<Scene> sceneList = Scenes;
212
213 for (int i = 0; i < sceneList.Count; i++)
243 { 214 {
244 for (int i = 0; i < m_localScenes.Count; i++) 215 if (sceneList[i]!= s)
245 { 216 {
246 if (m_localScenes[i].RegionInfo.RegionHandle != regionHandle) 217 // Inform other regions to tell their avatar about me
247 { 218 //sceneList[i].OtherRegionUp(Result);
248 // Inform other regions to tell their avatar about me
249 //m_localScenes[i].OtherRegionUp(Result);
250 }
251 } 219 }
252 } 220 }
253 else 221 }
254 { 222 else
255 m_log.Error("[REGION]: Unable to notify Other regions of this Region coming up"); 223 {
256 } 224 m_log.Error("[REGION]: Unable to notify Other regions of this Region coming up");
257 } 225 }
258 } 226 }
259 227
@@ -357,8 +325,8 @@ namespace OpenSim.Region.Framework.Scenes
357 { 325 {
358 if (m_currentScene == null) 326 if (m_currentScene == null)
359 { 327 {
360 lock (m_localScenes) 328 List<Scene> sceneList = Scenes;
361 m_localScenes.ForEach(func); 329 sceneList.ForEach(func);
362 } 330 }
363 else 331 else
364 { 332 {
@@ -387,16 +355,12 @@ namespace OpenSim.Region.Framework.Scenes
387 } 355 }
388 else 356 else
389 { 357 {
390 lock (m_localScenes) 358 Scene s;
359
360 if (m_localScenes.TryGetValue(regionName, out s))
391 { 361 {
392 foreach (Scene scene in m_localScenes) 362 m_currentScene = s;
393 { 363 return true;
394 if (String.Compare(scene.RegionInfo.RegionName, regionName, true) == 0)
395 {
396 m_currentScene = scene;
397 return true;
398 }
399 }
400 } 364 }
401 365
402 return false; 366 return false;
@@ -405,18 +369,14 @@ namespace OpenSim.Region.Framework.Scenes
405 369
406 public bool TrySetCurrentScene(UUID regionID) 370 public bool TrySetCurrentScene(UUID regionID)
407 { 371 {
408 m_log.Debug("Searching for Region: '" + regionID + "'"); 372// m_log.Debug("Searching for Region: '" + regionID + "'");
409 373
410 lock (m_localScenes) 374 Scene s;
375
376 if (m_localScenes.TryGetValue(regionID, out s))
411 { 377 {
412 foreach (Scene scene in m_localScenes) 378 m_currentScene = s;
413 { 379 return true;
414 if (scene.RegionInfo.RegionID == regionID)
415 {
416 m_currentScene = scene;
417 return true;
418 }
419 }
420 } 380 }
421 381
422 return false; 382 return false;
@@ -424,52 +384,24 @@ namespace OpenSim.Region.Framework.Scenes
424 384
425 public bool TryGetScene(string regionName, out Scene scene) 385 public bool TryGetScene(string regionName, out Scene scene)
426 { 386 {
427 lock (m_localScenes) 387 return m_localScenes.TryGetValue(regionName, out scene);
428 {
429 foreach (Scene mscene in m_localScenes)
430 {
431 if (String.Compare(mscene.RegionInfo.RegionName, regionName, true) == 0)
432 {
433 scene = mscene;
434 return true;
435 }
436 }
437 }
438
439 scene = null;
440 return false;
441 } 388 }
442 389
443 public bool TryGetScene(UUID regionID, out Scene scene) 390 public bool TryGetScene(UUID regionID, out Scene scene)
444 { 391 {
445 lock (m_localScenes) 392 return m_localScenes.TryGetValue(regionID, out scene);
446 {
447 foreach (Scene mscene in m_localScenes)
448 {
449 if (mscene.RegionInfo.RegionID == regionID)
450 {
451 scene = mscene;
452 return true;
453 }
454 }
455 }
456
457 scene = null;
458 return false;
459 } 393 }
460 394
461 public bool TryGetScene(uint locX, uint locY, out Scene scene) 395 public bool TryGetScene(uint locX, uint locY, out Scene scene)
462 { 396 {
463 lock (m_localScenes) 397 List<Scene> sceneList = Scenes;
398 foreach (Scene mscene in sceneList)
464 { 399 {
465 foreach (Scene mscene in m_localScenes) 400 if (mscene.RegionInfo.RegionLocX == locX &&
401 mscene.RegionInfo.RegionLocY == locY)
466 { 402 {
467 if (mscene.RegionInfo.RegionLocX == locX && 403 scene = mscene;
468 mscene.RegionInfo.RegionLocY == locY) 404 return true;
469 {
470 scene = mscene;
471 return true;
472 }
473 } 405 }
474 } 406 }
475 407
@@ -479,16 +411,14 @@ namespace OpenSim.Region.Framework.Scenes
479 411
480 public bool TryGetScene(IPEndPoint ipEndPoint, out Scene scene) 412 public bool TryGetScene(IPEndPoint ipEndPoint, out Scene scene)
481 { 413 {
482 lock (m_localScenes) 414 List<Scene> sceneList = Scenes;
415 foreach (Scene mscene in sceneList)
483 { 416 {
484 foreach (Scene mscene in m_localScenes) 417 if ((mscene.RegionInfo.InternalEndPoint.Equals(ipEndPoint.Address)) &&
418 (mscene.RegionInfo.InternalEndPoint.Port == ipEndPoint.Port))
485 { 419 {
486 if ((mscene.RegionInfo.InternalEndPoint.Equals(ipEndPoint.Address)) && 420 scene = mscene;
487 (mscene.RegionInfo.InternalEndPoint.Port == ipEndPoint.Port)) 421 return true;
488 {
489 scene = mscene;
490 return true;
491 }
492 } 422 }
493 } 423 }
494 424
@@ -553,15 +483,10 @@ namespace OpenSim.Region.Framework.Scenes
553 483
554 public RegionInfo GetRegionInfo(UUID regionID) 484 public RegionInfo GetRegionInfo(UUID regionID)
555 { 485 {
556 lock (m_localScenes) 486 Scene s;
487 if (m_localScenes.TryGetValue(regionID, out s))
557 { 488 {
558 foreach (Scene scene in m_localScenes) 489 return s.RegionInfo;
559 {
560 if (scene.RegionInfo.RegionID == regionID)
561 {
562 return scene.RegionInfo;
563 }
564 }
565 } 490 }
566 491
567 return null; 492 return null;
@@ -579,14 +504,12 @@ namespace OpenSim.Region.Framework.Scenes
579 504
580 public bool TryGetScenePresence(UUID avatarId, out ScenePresence avatar) 505 public bool TryGetScenePresence(UUID avatarId, out ScenePresence avatar)
581 { 506 {
582 lock (m_localScenes) 507 List<Scene> sceneList = Scenes;
508 foreach (Scene scene in sceneList)
583 { 509 {
584 foreach (Scene scene in m_localScenes) 510 if (scene.TryGetScenePresence(avatarId, out avatar))
585 { 511 {
586 if (scene.TryGetScenePresence(avatarId, out avatar)) 512 return true;
587 {
588 return true;
589 }
590 } 513 }
591 } 514 }
592 515
@@ -596,15 +519,13 @@ namespace OpenSim.Region.Framework.Scenes
596 519
597 public bool TryGetRootScenePresence(UUID avatarId, out ScenePresence avatar) 520 public bool TryGetRootScenePresence(UUID avatarId, out ScenePresence avatar)
598 { 521 {
599 lock (m_localScenes) 522 List<Scene> sceneList = Scenes;
523 foreach (Scene scene in sceneList)
600 { 524 {
601 foreach (Scene scene in m_localScenes) 525 avatar = scene.GetScenePresence(avatarId);
602 {
603 avatar = scene.GetScenePresence(avatarId);
604 526
605 if (avatar != null && !avatar.IsChildAgent) 527 if (avatar != null && !avatar.IsChildAgent)
606 return true; 528 return true;
607 }
608 } 529 }
609 530
610 avatar = null; 531 avatar = null;
@@ -614,21 +535,19 @@ namespace OpenSim.Region.Framework.Scenes
614 public void CloseScene(Scene scene) 535 public void CloseScene(Scene scene)
615 { 536 {
616 lock (m_localScenes) 537 lock (m_localScenes)
617 m_localScenes.Remove(scene); 538 m_localScenes.Remove(scene.RegionInfo.RegionID);
618 539
619 scene.Close(); 540 scene.Close();
620 } 541 }
621 542
622 public bool TryGetAvatarByName(string avatarName, out ScenePresence avatar) 543 public bool TryGetAvatarByName(string avatarName, out ScenePresence avatar)
623 { 544 {
624 lock (m_localScenes) 545 List<Scene> sceneList = Scenes;
546 foreach (Scene scene in sceneList)
625 { 547 {
626 foreach (Scene scene in m_localScenes) 548 if (scene.TryGetAvatarByName(avatarName, out avatar))
627 { 549 {
628 if (scene.TryGetAvatarByName(avatarName, out avatar)) 550 return true;
629 {
630 return true;
631 }
632 } 551 }
633 } 552 }
634 553
@@ -638,14 +557,12 @@ namespace OpenSim.Region.Framework.Scenes
638 557
639 public bool TryGetRootScenePresenceByName(string firstName, string lastName, out ScenePresence sp) 558 public bool TryGetRootScenePresenceByName(string firstName, string lastName, out ScenePresence sp)
640 { 559 {
641 lock (m_localScenes) 560 List<Scene> sceneList = Scenes;
561 foreach (Scene scene in sceneList)
642 { 562 {
643 foreach (Scene scene in m_localScenes) 563 sp = scene.GetScenePresence(firstName, lastName);
644 { 564 if (sp != null && !sp.IsChildAgent)
645 sp = scene.GetScenePresence(firstName, lastName); 565 return true;
646 if (sp != null && !sp.IsChildAgent)
647 return true;
648 }
649 } 566 }
650 567
651 sp = null; 568 sp = null;
@@ -654,8 +571,8 @@ namespace OpenSim.Region.Framework.Scenes
654 571
655 public void ForEachScene(Action<Scene> action) 572 public void ForEachScene(Action<Scene> action)
656 { 573 {
657 lock (m_localScenes) 574 List<Scene> sceneList = Scenes;
658 m_localScenes.ForEach(action); 575 sceneList.ForEach(action);
659 } 576 }
660 } 577 }
661} 578}
diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectGroup.Inventory.cs b/OpenSim/Region/Framework/Scenes/SceneObjectGroup.Inventory.cs
index ddf5da0..26524fb 100644
--- a/OpenSim/Region/Framework/Scenes/SceneObjectGroup.Inventory.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneObjectGroup.Inventory.cs
@@ -81,10 +81,6 @@ namespace OpenSim.Region.Framework.Scenes
81 /// <summary> 81 /// <summary>
82 /// Stop and remove the scripts contained in all the prims in this group 82 /// Stop and remove the scripts contained in all the prims in this group
83 /// </summary> 83 /// </summary>
84 /// <param name="sceneObjectBeingDeleted">
85 /// Should be true if these scripts are being removed because the scene
86 /// object is being deleted. This will prevent spurious updates to the client.
87 /// </param>
88 public void RemoveScriptInstances(bool sceneObjectBeingDeleted) 84 public void RemoveScriptInstances(bool sceneObjectBeingDeleted)
89 { 85 {
90 SceneObjectPart[] parts = m_parts.GetArray(); 86 SceneObjectPart[] parts = m_parts.GetArray();
@@ -247,6 +243,11 @@ namespace OpenSim.Region.Framework.Scenes
247 243
248 public uint GetEffectivePermissions() 244 public uint GetEffectivePermissions()
249 { 245 {
246 return GetEffectivePermissions(false);
247 }
248
249 public uint GetEffectivePermissions(bool useBase)
250 {
250 uint perms=(uint)(PermissionMask.Modify | 251 uint perms=(uint)(PermissionMask.Modify |
251 PermissionMask.Copy | 252 PermissionMask.Copy |
252 PermissionMask.Move | 253 PermissionMask.Move |
@@ -258,7 +259,10 @@ namespace OpenSim.Region.Framework.Scenes
258 for (int i = 0; i < parts.Length; i++) 259 for (int i = 0; i < parts.Length; i++)
259 { 260 {
260 SceneObjectPart part = parts[i]; 261 SceneObjectPart part = parts[i];
261 ownerMask &= part.OwnerMask; 262 if (useBase)
263 ownerMask &= part.BaseMask;
264 else
265 ownerMask &= part.OwnerMask;
262 perms &= part.Inventory.MaskEffectivePermissions(); 266 perms &= part.Inventory.MaskEffectivePermissions();
263 } 267 }
264 268
@@ -400,6 +404,9 @@ namespace OpenSim.Region.Framework.Scenes
400 404
401 public void ResumeScripts() 405 public void ResumeScripts()
402 { 406 {
407 if (m_scene.RegionInfo.RegionSettings.DisableScripts)
408 return;
409
403 SceneObjectPart[] parts = m_parts.GetArray(); 410 SceneObjectPart[] parts = m_parts.GetArray();
404 for (int i = 0; i < parts.Length; i++) 411 for (int i = 0; i < parts.Length; i++)
405 parts[i].Inventory.ResumeScripts(); 412 parts[i].Inventory.ResumeScripts();
diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs b/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs
index 7b284ae..d51281d 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,29 @@ 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 bool m_suspendUpdates;
117 private List<ScenePresence> m_linkedAvatars = new List<ScenePresence>();
118
119 public bool areUpdatesSuspended
120 {
121 get
122 {
123 return m_suspendUpdates;
124 }
125 set
126 {
127 m_suspendUpdates = value;
128 if (!value)
129 {
130 QueueForUpdateCheck();
131 }
132 }
133 }
111 134
112 /// <summary> 135 /// <summary>
113 /// This indicates whether the object has changed such that it needs to be repersisted to permenant storage 136 /// This indicates whether the object has changed such that it needs to be repersisted to permenant storage
@@ -124,9 +147,39 @@ namespace OpenSim.Region.Framework.Scenes
124 { 147 {
125 if (value) 148 if (value)
126 { 149 {
150 if (m_isBackedUp)
151 {
152 m_scene.SceneGraph.FireChangeBackup(this);
153 }
127 timeLastChanged = DateTime.Now.Ticks; 154 timeLastChanged = DateTime.Now.Ticks;
128 if (!m_hasGroupChanged) 155 if (!m_hasGroupChanged)
129 timeFirstChanged = DateTime.Now.Ticks; 156 timeFirstChanged = DateTime.Now.Ticks;
157 if (m_rootPart != null && m_rootPart.UUID != null && m_scene != null)
158 {
159 if (m_rand == null)
160 {
161 byte[] val = new byte[16];
162 m_rootPart.UUID.ToBytes(val, 0);
163 m_rand = new Random(BitConverter.ToInt32(val, 0));
164 }
165
166 if (m_scene.GetRootAgentCount() == 0)
167 {
168 //If the region is empty, this change has been made by an automated process
169 //and thus we delay the persist time by a random amount between 1.5 and 2.5.
170
171 float factor = 1.5f + (float)(m_rand.NextDouble());
172 m_maxPersistTime = (long)((float)m_scene.m_persistAfter * factor);
173 m_minPersistTime = (long)((float)m_scene.m_dontPersistBefore * factor);
174 }
175 else
176 {
177 //If the region is not empty, we want to obey the minimum and maximum persist times
178 //but add a random factor so we stagger the object persistance a little
179 m_maxPersistTime = (long)((float)m_scene.m_persistAfter * (1.0d - (m_rand.NextDouble() / 5.0d))); //Multiply by 1.0-1.5
180 m_minPersistTime = (long)((float)m_scene.m_dontPersistBefore * (1.0d + (m_rand.NextDouble() / 2.0d))); //Multiply by 0.8-1.0
181 }
182 }
130 } 183 }
131 m_hasGroupChanged = value; 184 m_hasGroupChanged = value;
132 185
@@ -141,7 +194,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 194 /// 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. 195 /// an unlinked group currently has to be persisted to the database before we can perform an unlink operation.
143 /// </summary> 196 /// </summary>
144 public bool HasGroupChangedDueToDelink { get; private set; } 197 public bool HasGroupChangedDueToDelink { get; set; }
145 198
146 private bool isTimeToPersist() 199 private bool isTimeToPersist()
147 { 200 {
@@ -151,8 +204,19 @@ namespace OpenSim.Region.Framework.Scenes
151 return false; 204 return false;
152 if (m_scene.ShuttingDown) 205 if (m_scene.ShuttingDown)
153 return true; 206 return true;
207
208 if (m_minPersistTime == 0 || m_maxPersistTime == 0)
209 {
210 m_maxPersistTime = m_scene.m_persistAfter;
211 m_minPersistTime = m_scene.m_dontPersistBefore;
212 }
213
154 long currentTime = DateTime.Now.Ticks; 214 long currentTime = DateTime.Now.Ticks;
155 if (currentTime - timeLastChanged > m_scene.m_dontPersistBefore || currentTime - timeFirstChanged > m_scene.m_persistAfter) 215
216 if (timeLastChanged == 0) timeLastChanged = currentTime;
217 if (timeFirstChanged == 0) timeFirstChanged = currentTime;
218
219 if (currentTime - timeLastChanged > m_minPersistTime || currentTime - timeFirstChanged > m_maxPersistTime)
156 return true; 220 return true;
157 return false; 221 return false;
158 } 222 }
@@ -271,10 +335,10 @@ namespace OpenSim.Region.Framework.Scenes
271 335
272 private bool m_scriptListens_atTarget; 336 private bool m_scriptListens_atTarget;
273 private bool m_scriptListens_notAtTarget; 337 private bool m_scriptListens_notAtTarget;
274
275 private bool m_scriptListens_atRotTarget; 338 private bool m_scriptListens_atRotTarget;
276 private bool m_scriptListens_notAtRotTarget; 339 private bool m_scriptListens_notAtRotTarget;
277 340
341 public bool m_dupeInProgress = false;
278 internal Dictionary<UUID, string> m_savedScriptState; 342 internal Dictionary<UUID, string> m_savedScriptState;
279 343
280 #region Properties 344 #region Properties
@@ -311,6 +375,16 @@ namespace OpenSim.Region.Framework.Scenes
311 get { return m_parts.Count; } 375 get { return m_parts.Count; }
312 } 376 }
313 377
378// protected Quaternion m_rotation = Quaternion.Identity;
379//
380// public virtual Quaternion Rotation
381// {
382// get { return m_rotation; }
383// set {
384// m_rotation = value;
385// }
386// }
387
314 public Quaternion GroupRotation 388 public Quaternion GroupRotation
315 { 389 {
316 get { return m_rootPart.RotationOffset; } 390 get { return m_rootPart.RotationOffset; }
@@ -417,7 +491,15 @@ namespace OpenSim.Region.Framework.Scenes
417 { 491 {
418 return (IsAttachment || (m_rootPart.Shape.PCode == 9 && m_rootPart.Shape.State != 0)); 492 return (IsAttachment || (m_rootPart.Shape.PCode == 9 && m_rootPart.Shape.State != 0));
419 } 493 }
420 494
495
496
497 private struct avtocrossInfo
498 {
499 public ScenePresence av;
500 public uint ParentID;
501 }
502
421 /// <summary> 503 /// <summary>
422 /// The absolute position of this scene object in the scene 504 /// The absolute position of this scene object in the scene
423 /// </summary> 505 /// </summary>
@@ -430,14 +512,128 @@ namespace OpenSim.Region.Framework.Scenes
430 512
431 if (Scene != null) 513 if (Scene != null)
432 { 514 {
433 if ((Scene.TestBorderCross(val - Vector3.UnitX, Cardinals.E) || Scene.TestBorderCross(val + Vector3.UnitX, Cardinals.W) 515 // 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)) 516 // || Scene.TestBorderCross(val - Vector3.UnitY, Cardinals.N) || Scene.TestBorderCross(val + Vector3.UnitY, Cardinals.S))
517 // && !IsAttachmentCheckFull() && (!Scene.LoadingPrims))
518 if ((Scene.TestBorderCross(val, Cardinals.E) || Scene.TestBorderCross(val, Cardinals.W)
519 || Scene.TestBorderCross(val, Cardinals.N) || Scene.TestBorderCross(val, Cardinals.S))
435 && !IsAttachmentCheckFull() && (!Scene.LoadingPrims)) 520 && !IsAttachmentCheckFull() && (!Scene.LoadingPrims))
436 { 521 {
437 m_scene.CrossPrimGroupIntoNewRegion(val, this, true); 522 IEntityTransferModule entityTransfer = m_scene.RequestModuleInterface<IEntityTransferModule>();
523 uint x = 0;
524 uint y = 0;
525 string version = String.Empty;
526 Vector3 newpos = Vector3.Zero;
527 OpenSim.Services.Interfaces.GridRegion destination = null;
528
529 bool canCross = true;
530 foreach (ScenePresence av in m_linkedAvatars)
531 {
532 // We need to cross these agents. First, let's find
533 // out if any of them can't cross for some reason.
534 // We have to deny the crossing entirely if any
535 // of them are banned. Alternatively, we could
536 // unsit banned agents....
537
538
539 // We set the avatar position as being the object
540 // position to get the region to send to
541 if ((destination = entityTransfer.GetDestination(m_scene, av.UUID, val, out x, out y, out version, out newpos)) == null)
542 {
543 canCross = false;
544 break;
545 }
546
547 m_log.DebugFormat("[SCENE OBJECT]: Avatar {0} needs to be crossed to {1}", av.Name, destination.RegionName);
548 }
549
550 if (canCross)
551 {
552 // We unparent the SP quietly so that it won't
553 // be made to stand up
554
555 List<avtocrossInfo> avsToCross = new List<avtocrossInfo>();
556
557 foreach (ScenePresence av in m_linkedAvatars)
558 {
559 avtocrossInfo avinfo = new avtocrossInfo();
560 SceneObjectPart parentPart = m_scene.GetSceneObjectPart(av.ParentID);
561 if (parentPart != null)
562 av.ParentUUID = parentPart.UUID;
563
564 avinfo.av = av;
565 avinfo.ParentID = av.ParentID;
566 avsToCross.Add(avinfo);
567
568 av.ParentID = 0;
569 }
570
571// m_linkedAvatars.Clear();
572 m_scene.CrossPrimGroupIntoNewRegion(val, this, true);
573
574 // Normalize
575 if (val.X >= Constants.RegionSize)
576 val.X -= Constants.RegionSize;
577 if (val.Y >= Constants.RegionSize)
578 val.Y -= Constants.RegionSize;
579 if (val.X < 0)
580 val.X += Constants.RegionSize;
581 if (val.Y < 0)
582 val.Y += Constants.RegionSize;
583
584 // If it's deleted, crossing was successful
585 if (IsDeleted)
586 {
587 // foreach (ScenePresence av in m_linkedAvatars)
588 foreach (avtocrossInfo avinfo in avsToCross)
589 {
590 ScenePresence av = avinfo.av;
591 if (!av.IsInTransit) // just in case...
592 {
593 m_log.DebugFormat("[SCENE OBJECT]: Crossing avatar {0} to {1}", av.Name, val);
594
595 av.IsInTransit = true;
596
597 CrossAgentToNewRegionDelegate d = entityTransfer.CrossAgentToNewRegionAsync;
598 d.BeginInvoke(av, val, x, y, destination, av.Flying, version, CrossAgentToNewRegionCompleted, d);
599 }
600 else
601 m_log.DebugFormat("[SCENE OBJECT]: Crossing avatar alreasy in transit {0} to {1}", av.Name, val);
602 }
603 avsToCross.Clear();
604 return;
605 }
606 else // cross failed, put avas back ??
607 {
608 foreach (avtocrossInfo avinfo in avsToCross)
609 {
610 ScenePresence av = avinfo.av;
611 av.ParentUUID = UUID.Zero;
612 av.ParentID = avinfo.ParentID;
613// m_linkedAvatars.Add(av);
614 }
615 }
616 avsToCross.Clear();
617
618 }
619 else if (RootPart.PhysActor != null)
620 {
621 RootPart.PhysActor.CrossingFailure();
622 }
623
624 Vector3 oldp = AbsolutePosition;
625 val.X = Util.Clamp<float>(oldp.X, 0.5f, (float)Constants.RegionSize - 0.5f);
626 val.Y = Util.Clamp<float>(oldp.Y, 0.5f, (float)Constants.RegionSize - 0.5f);
627 val.Z = Util.Clamp<float>(oldp.Z, 0.5f, 4096.0f);
438 } 628 }
439 } 629 }
440 630
631/* don't see the need but worse don't see where is restored to false if things stay in
632 foreach (SceneObjectPart part in m_parts.GetArray())
633 {
634 part.IgnoreUndoUpdate = true;
635 }
636 */
441 if (RootPart.GetStatusSandbox()) 637 if (RootPart.GetStatusSandbox())
442 { 638 {
443 if (Util.GetDistanceTo(RootPart.StatusSandboxPos, value) > 10) 639 if (Util.GetDistanceTo(RootPart.StatusSandboxPos, value) > 10)
@@ -455,9 +651,38 @@ namespace OpenSim.Region.Framework.Scenes
455 // Restuff the new GroupPosition into each SOP of the linkset. 651 // Restuff the new GroupPosition into each SOP of the linkset.
456 // This has the affect of resetting and tainting the physics actors. 652 // This has the affect of resetting and tainting the physics actors.
457 SceneObjectPart[] parts = m_parts.GetArray(); 653 SceneObjectPart[] parts = m_parts.GetArray();
458 for (int i = 0; i < parts.Length; i++) 654 bool triggerScriptEvent = m_rootPart.GroupPosition != val;
459 parts[i].GroupPosition = val; 655 if (m_dupeInProgress)
656 triggerScriptEvent = false;
657 foreach (SceneObjectPart part in parts)
658 {
659 part.GroupPosition = val;
660 if (triggerScriptEvent)
661 part.TriggerScriptChangedEvent(Changed.POSITION);
662 }
460 663
664/*
665 This seems not needed and should not be needed:
666 sp absolute position depends on sit part absolute position fixed above.
667 sp ParentPosition is not used anywhere.
668 Since presence is sitting, viewer considers it 'linked' to root prim, so it will move/rotate it
669 Sending a extra packet with avatar position is not only bandwidth waste, but may cause jitter in viewers due to UPD nature.
670
671 if (!m_dupeInProgress)
672 {
673 foreach (ScenePresence av in m_linkedAvatars)
674 {
675 SceneObjectPart p = m_scene.GetSceneObjectPart(av.ParentID);
676 if (p != null && m_parts.TryGetValue(p.UUID, out p))
677 {
678 Vector3 offset = p.GetWorldPosition() - av.ParentPosition;
679 av.AbsolutePosition += offset;
680// av.ParentPosition = p.GetWorldPosition(); //ParentPosition gets cleared by AbsolutePosition
681 av.SendAvatarDataToAllAgents();
682 }
683 }
684 }
685*/
461 //if (m_rootPart.PhysActor != null) 686 //if (m_rootPart.PhysActor != null)
462 //{ 687 //{
463 //m_rootPart.PhysActor.Position = 688 //m_rootPart.PhysActor.Position =
@@ -471,6 +696,40 @@ namespace OpenSim.Region.Framework.Scenes
471 } 696 }
472 } 697 }
473 698
699 public override Vector3 Velocity
700 {
701 get { return RootPart.Velocity; }
702 set { RootPart.Velocity = value; }
703 }
704
705 private void CrossAgentToNewRegionCompleted(IAsyncResult iar)
706 {
707 CrossAgentToNewRegionDelegate icon = (CrossAgentToNewRegionDelegate)iar.AsyncState;
708 ScenePresence agent = icon.EndInvoke(iar);
709
710 //// If the cross was successful, this agent is a child agent
711 if (agent.IsChildAgent)
712 {
713 if (agent.ParentUUID != UUID.Zero)
714 {
715 agent.ParentPart = null;
716// agent.ParentPosition = Vector3.Zero;
717// agent.ParentUUID = UUID.Zero;
718 }
719 }
720
721 agent.ParentUUID = UUID.Zero;
722
723// agent.Reset();
724// else // Not successful
725// agent.RestoreInCurrentScene();
726
727 // In any case
728 agent.IsInTransit = false;
729
730 m_log.DebugFormat("[SCENE OBJECT]: Crossing agent {0} {1} completed.", agent.Firstname, agent.Lastname);
731 }
732
474 public override uint LocalId 733 public override uint LocalId
475 { 734 {
476 get { return m_rootPart.LocalId; } 735 get { return m_rootPart.LocalId; }
@@ -541,6 +800,11 @@ namespace OpenSim.Region.Framework.Scenes
541 m_isSelected = value; 800 m_isSelected = value;
542 // Tell physics engine that group is selected 801 // Tell physics engine that group is selected
543 802
803 // this is not right
804 // but ode engines should only really need to know about root part
805 // so they can put entire object simulation on hold and not colliding
806 // keep as was for now
807
544 PhysicsActor pa = m_rootPart.PhysActor; 808 PhysicsActor pa = m_rootPart.PhysActor;
545 if (pa != null) 809 if (pa != null)
546 { 810 {
@@ -557,6 +821,42 @@ namespace OpenSim.Region.Framework.Scenes
557 childPa.Selected = value; 821 childPa.Selected = value;
558 } 822 }
559 } 823 }
824 if (RootPart.KeyframeMotion != null)
825 RootPart.KeyframeMotion.Selected = value;
826 }
827 }
828
829 public void PartSelectChanged(bool partSelect)
830 {
831 // any part selected makes group selected
832 if (m_isSelected == partSelect)
833 return;
834
835 if (partSelect)
836 {
837 IsSelected = partSelect;
838// if (!IsAttachment)
839// ScheduleGroupForFullUpdate();
840 }
841 else
842 {
843 // bad bad bad 2 heavy for large linksets
844 // since viewer does send lot of (un)selects
845 // this needs to be replaced by a specific list or count ?
846 // but that will require extra code in several places
847
848 SceneObjectPart[] parts = m_parts.GetArray();
849 for (int i = 0; i < parts.Length; i++)
850 {
851 SceneObjectPart part = parts[i];
852 if (part.IsSelected)
853 return;
854 }
855 IsSelected = partSelect;
856 if (!IsAttachment)
857 {
858 ScheduleGroupForFullUpdate();
859 }
560 } 860 }
561 } 861 }
562 862
@@ -642,6 +942,7 @@ namespace OpenSim.Region.Framework.Scenes
642 /// </summary> 942 /// </summary>
643 public SceneObjectGroup() 943 public SceneObjectGroup()
644 { 944 {
945
645 } 946 }
646 947
647 /// <summary> 948 /// <summary>
@@ -659,8 +960,8 @@ namespace OpenSim.Region.Framework.Scenes
659 /// Constructor. This object is added to the scene later via AttachToScene() 960 /// Constructor. This object is added to the scene later via AttachToScene()
660 /// </summary> 961 /// </summary>
661 public SceneObjectGroup(UUID ownerID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape) 962 public SceneObjectGroup(UUID ownerID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape)
662 :this(new SceneObjectPart(ownerID, shape, pos, rot, Vector3.Zero)) 963 {
663 { 964 SetRootPart(new SceneObjectPart(ownerID, shape, pos, rot, Vector3.Zero));
664 } 965 }
665 966
666 /// <summary> 967 /// <summary>
@@ -695,6 +996,9 @@ namespace OpenSim.Region.Framework.Scenes
695 /// </summary> 996 /// </summary>
696 public virtual void AttachToBackup() 997 public virtual void AttachToBackup()
697 { 998 {
999 if (IsAttachment) return;
1000 m_scene.SceneGraph.FireAttachToBackup(this);
1001
698 if (InSceneBackup) 1002 if (InSceneBackup)
699 { 1003 {
700 //m_log.DebugFormat( 1004 //m_log.DebugFormat(
@@ -737,6 +1041,13 @@ namespace OpenSim.Region.Framework.Scenes
737 1041
738 ApplyPhysics(); 1042 ApplyPhysics();
739 1043
1044 if (RootPart.PhysActor != null)
1045 RootPart.Force = RootPart.Force;
1046 if (RootPart.PhysActor != null)
1047 RootPart.Torque = RootPart.Torque;
1048 if (RootPart.PhysActor != null)
1049 RootPart.Buoyancy = RootPart.Buoyancy;
1050
740 // Don't trigger the update here - otherwise some client issues occur when multiple updates are scheduled 1051 // 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. 1052 // for the same object with very different properties. The caller must schedule the update.
742 //ScheduleGroupForFullUpdate(); 1053 //ScheduleGroupForFullUpdate();
@@ -752,6 +1063,10 @@ namespace OpenSim.Region.Framework.Scenes
752 EntityIntersection result = new EntityIntersection(); 1063 EntityIntersection result = new EntityIntersection();
753 1064
754 SceneObjectPart[] parts = m_parts.GetArray(); 1065 SceneObjectPart[] parts = m_parts.GetArray();
1066
1067 // Find closest hit here
1068 float idist = float.MaxValue;
1069
755 for (int i = 0; i < parts.Length; i++) 1070 for (int i = 0; i < parts.Length; i++)
756 { 1071 {
757 SceneObjectPart part = parts[i]; 1072 SceneObjectPart part = parts[i];
@@ -766,11 +1081,6 @@ namespace OpenSim.Region.Framework.Scenes
766 1081
767 EntityIntersection inter = part.TestIntersectionOBB(hRay, parentrotation, frontFacesOnly, faceCenters); 1082 EntityIntersection inter = part.TestIntersectionOBB(hRay, parentrotation, frontFacesOnly, faceCenters);
768 1083
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) 1084 if (inter.HitTF)
775 { 1085 {
776 // We need to find the closest prim to return to the testcaller along the ray 1086 // We need to find the closest prim to return to the testcaller along the ray
@@ -781,10 +1091,11 @@ namespace OpenSim.Region.Framework.Scenes
781 result.obj = part; 1091 result.obj = part;
782 result.normal = inter.normal; 1092 result.normal = inter.normal;
783 result.distance = inter.distance; 1093 result.distance = inter.distance;
1094
1095 idist = inter.distance;
784 } 1096 }
785 } 1097 }
786 } 1098 }
787
788 return result; 1099 return result;
789 } 1100 }
790 1101
@@ -796,25 +1107,27 @@ namespace OpenSim.Region.Framework.Scenes
796 /// <returns></returns> 1107 /// <returns></returns>
797 public void GetAxisAlignedBoundingBoxRaw(out float minX, out float maxX, out float minY, out float maxY, out float minZ, out float maxZ) 1108 public void GetAxisAlignedBoundingBoxRaw(out float minX, out float maxX, out float minY, out float maxY, out float minZ, out float maxZ)
798 { 1109 {
799 maxX = -256f; 1110 maxX = float.MinValue;
800 maxY = -256f; 1111 maxY = float.MinValue;
801 maxZ = -256f; 1112 maxZ = float.MinValue;
802 minX = 256f; 1113 minX = float.MaxValue;
803 minY = 256f; 1114 minY = float.MaxValue;
804 minZ = 8192f; 1115 minZ = float.MaxValue;
805 1116
806 SceneObjectPart[] parts = m_parts.GetArray(); 1117 SceneObjectPart[] parts = m_parts.GetArray();
807 for (int i = 0; i < parts.Length; i++) 1118 foreach (SceneObjectPart part in parts)
808 { 1119 {
809 SceneObjectPart part = parts[i];
810
811 Vector3 worldPos = part.GetWorldPosition(); 1120 Vector3 worldPos = part.GetWorldPosition();
812 Vector3 offset = worldPos - AbsolutePosition; 1121 Vector3 offset = worldPos - AbsolutePosition;
813 Quaternion worldRot; 1122 Quaternion worldRot;
814 if (part.ParentID == 0) 1123 if (part.ParentID == 0)
1124 {
815 worldRot = part.RotationOffset; 1125 worldRot = part.RotationOffset;
1126 }
816 else 1127 else
1128 {
817 worldRot = part.GetWorldRotation(); 1129 worldRot = part.GetWorldRotation();
1130 }
818 1131
819 Vector3 frontTopLeft; 1132 Vector3 frontTopLeft;
820 Vector3 frontTopRight; 1133 Vector3 frontTopRight;
@@ -826,6 +1139,8 @@ namespace OpenSim.Region.Framework.Scenes
826 Vector3 backBottomLeft; 1139 Vector3 backBottomLeft;
827 Vector3 backBottomRight; 1140 Vector3 backBottomRight;
828 1141
1142 // Vector3[] corners = new Vector3[8];
1143
829 Vector3 orig = Vector3.Zero; 1144 Vector3 orig = Vector3.Zero;
830 1145
831 frontTopLeft.X = orig.X - (part.Scale.X / 2); 1146 frontTopLeft.X = orig.X - (part.Scale.X / 2);
@@ -860,6 +1175,38 @@ namespace OpenSim.Region.Framework.Scenes
860 backBottomRight.Y = orig.Y + (part.Scale.Y / 2); 1175 backBottomRight.Y = orig.Y + (part.Scale.Y / 2);
861 backBottomRight.Z = orig.Z - (part.Scale.Z / 2); 1176 backBottomRight.Z = orig.Z - (part.Scale.Z / 2);
862 1177
1178
1179
1180 //m_log.InfoFormat("pre corner 1 is {0} {1} {2}", frontTopLeft.X, frontTopLeft.Y, frontTopLeft.Z);
1181 //m_log.InfoFormat("pre corner 2 is {0} {1} {2}", frontTopRight.X, frontTopRight.Y, frontTopRight.Z);
1182 //m_log.InfoFormat("pre corner 3 is {0} {1} {2}", frontBottomRight.X, frontBottomRight.Y, frontBottomRight.Z);
1183 //m_log.InfoFormat("pre corner 4 is {0} {1} {2}", frontBottomLeft.X, frontBottomLeft.Y, frontBottomLeft.Z);
1184 //m_log.InfoFormat("pre corner 5 is {0} {1} {2}", backTopLeft.X, backTopLeft.Y, backTopLeft.Z);
1185 //m_log.InfoFormat("pre corner 6 is {0} {1} {2}", backTopRight.X, backTopRight.Y, backTopRight.Z);
1186 //m_log.InfoFormat("pre corner 7 is {0} {1} {2}", backBottomRight.X, backBottomRight.Y, backBottomRight.Z);
1187 //m_log.InfoFormat("pre corner 8 is {0} {1} {2}", backBottomLeft.X, backBottomLeft.Y, backBottomLeft.Z);
1188
1189 //for (int i = 0; i < 8; i++)
1190 //{
1191 // corners[i] = corners[i] * worldRot;
1192 // corners[i] += offset;
1193
1194 // if (corners[i].X > maxX)
1195 // maxX = corners[i].X;
1196 // if (corners[i].X < minX)
1197 // minX = corners[i].X;
1198
1199 // if (corners[i].Y > maxY)
1200 // maxY = corners[i].Y;
1201 // if (corners[i].Y < minY)
1202 // minY = corners[i].Y;
1203
1204 // if (corners[i].Z > maxZ)
1205 // maxZ = corners[i].Y;
1206 // if (corners[i].Z < minZ)
1207 // minZ = corners[i].Z;
1208 //}
1209
863 frontTopLeft = frontTopLeft * worldRot; 1210 frontTopLeft = frontTopLeft * worldRot;
864 frontTopRight = frontTopRight * worldRot; 1211 frontTopRight = frontTopRight * worldRot;
865 frontBottomLeft = frontBottomLeft * worldRot; 1212 frontBottomLeft = frontBottomLeft * worldRot;
@@ -881,6 +1228,15 @@ namespace OpenSim.Region.Framework.Scenes
881 backTopLeft += offset; 1228 backTopLeft += offset;
882 backTopRight += offset; 1229 backTopRight += offset;
883 1230
1231 //m_log.InfoFormat("corner 1 is {0} {1} {2}", frontTopLeft.X, frontTopLeft.Y, frontTopLeft.Z);
1232 //m_log.InfoFormat("corner 2 is {0} {1} {2}", frontTopRight.X, frontTopRight.Y, frontTopRight.Z);
1233 //m_log.InfoFormat("corner 3 is {0} {1} {2}", frontBottomRight.X, frontBottomRight.Y, frontBottomRight.Z);
1234 //m_log.InfoFormat("corner 4 is {0} {1} {2}", frontBottomLeft.X, frontBottomLeft.Y, frontBottomLeft.Z);
1235 //m_log.InfoFormat("corner 5 is {0} {1} {2}", backTopLeft.X, backTopLeft.Y, backTopLeft.Z);
1236 //m_log.InfoFormat("corner 6 is {0} {1} {2}", backTopRight.X, backTopRight.Y, backTopRight.Z);
1237 //m_log.InfoFormat("corner 7 is {0} {1} {2}", backBottomRight.X, backBottomRight.Y, backBottomRight.Z);
1238 //m_log.InfoFormat("corner 8 is {0} {1} {2}", backBottomLeft.X, backBottomLeft.Y, backBottomLeft.Z);
1239
884 if (frontTopRight.X > maxX) 1240 if (frontTopRight.X > maxX)
885 maxX = frontTopRight.X; 1241 maxX = frontTopRight.X;
886 if (frontTopLeft.X > maxX) 1242 if (frontTopLeft.X > maxX)
@@ -1024,17 +1380,118 @@ namespace OpenSim.Region.Framework.Scenes
1024 1380
1025 #endregion 1381 #endregion
1026 1382
1383 public void GetResourcesCosts(SceneObjectPart apart,
1384 out float linksetResCost, out float linksetPhysCost, out float partCost, out float partPhysCost)
1385 {
1386 // this information may need to be cached
1387
1388 float cost;
1389 float tmpcost;
1390
1391 bool ComplexCost = false;
1392
1393 SceneObjectPart p;
1394 SceneObjectPart[] parts;
1395
1396 lock (m_parts)
1397 {
1398 parts = m_parts.GetArray();
1399 }
1400
1401 int nparts = parts.Length;
1402
1403
1404 for (int i = 0; i < nparts; i++)
1405 {
1406 p = parts[i];
1407
1408 if (p.UsesComplexCost)
1409 {
1410 ComplexCost = true;
1411 break;
1412 }
1413 }
1414
1415 if (ComplexCost)
1416 {
1417 linksetResCost = 0;
1418 linksetPhysCost = 0;
1419 partCost = 0;
1420 partPhysCost = 0;
1421
1422 for (int i = 0; i < nparts; i++)
1423 {
1424 p = parts[i];
1425
1426 cost = p.StreamingCost;
1427 tmpcost = p.SimulationCost;
1428 if (tmpcost > cost)
1429 cost = tmpcost;
1430 tmpcost = p.PhysicsCost;
1431 if (tmpcost > cost)
1432 cost = tmpcost;
1433
1434 linksetPhysCost += tmpcost;
1435 linksetResCost += cost;
1436
1437 if (p == apart)
1438 {
1439 partCost = cost;
1440 partPhysCost = tmpcost;
1441 }
1442 }
1443 }
1444 else
1445 {
1446 partPhysCost = 1.0f;
1447 partCost = 1.0f;
1448 linksetResCost = (float)nparts;
1449 linksetPhysCost = linksetResCost;
1450 }
1451 }
1452
1453 public void GetSelectedCosts(out float PhysCost, out float StreamCost, out float SimulCost)
1454 {
1455 SceneObjectPart p;
1456 SceneObjectPart[] parts;
1457
1458 lock (m_parts)
1459 {
1460 parts = m_parts.GetArray();
1461 }
1462
1463 int nparts = parts.Length;
1464
1465 PhysCost = 0;
1466 StreamCost = 0;
1467 SimulCost = 0;
1468
1469 for (int i = 0; i < nparts; i++)
1470 {
1471 p = parts[i];
1472
1473 StreamCost += p.StreamingCost;
1474 SimulCost += p.SimulationCost;
1475 PhysCost += p.PhysicsCost;
1476 }
1477 }
1478
1027 public void SaveScriptedState(XmlTextWriter writer) 1479 public void SaveScriptedState(XmlTextWriter writer)
1028 { 1480 {
1481 SaveScriptedState(writer, false);
1482 }
1483
1484 public void SaveScriptedState(XmlTextWriter writer, bool oldIDs)
1485 {
1029 XmlDocument doc = new XmlDocument(); 1486 XmlDocument doc = new XmlDocument();
1030 Dictionary<UUID,string> states = new Dictionary<UUID,string>(); 1487 Dictionary<UUID,string> states = new Dictionary<UUID,string>();
1031 1488
1032 SceneObjectPart[] parts = m_parts.GetArray(); 1489 SceneObjectPart[] parts = m_parts.GetArray();
1033 for (int i = 0; i < parts.Length; i++) 1490 for (int i = 0; i < parts.Length; i++)
1034 { 1491 {
1035 Dictionary<UUID, string> pstates = parts[i].Inventory.GetScriptStates(); 1492 Dictionary<UUID, string> pstates = parts[i].Inventory.GetScriptStates(oldIDs);
1036 foreach (KeyValuePair<UUID, string> kvp in pstates) 1493 foreach (KeyValuePair<UUID, string> kvp in pstates)
1037 states.Add(kvp.Key, kvp.Value); 1494 states[kvp.Key] = kvp.Value;
1038 } 1495 }
1039 1496
1040 if (states.Count > 0) 1497 if (states.Count > 0)
@@ -1054,6 +1511,169 @@ namespace OpenSim.Region.Framework.Scenes
1054 } 1511 }
1055 1512
1056 /// <summary> 1513 /// <summary>
1514 /// Add the avatar to this linkset (avatar is sat).
1515 /// </summary>
1516 /// <param name="agentID"></param>
1517 public void AddAvatar(UUID agentID)
1518 {
1519 ScenePresence presence;
1520 if (m_scene.TryGetScenePresence(agentID, out presence))
1521 {
1522 if (!m_linkedAvatars.Contains(presence))
1523 {
1524 m_linkedAvatars.Add(presence);
1525 }
1526 }
1527 }
1528
1529 /// <summary>
1530 /// Delete the avatar from this linkset (avatar is unsat).
1531 /// </summary>
1532 /// <param name="agentID"></param>
1533 public void DeleteAvatar(UUID agentID)
1534 {
1535 ScenePresence presence;
1536 if (m_scene.TryGetScenePresence(agentID, out presence))
1537 {
1538 if (m_linkedAvatars.Contains(presence))
1539 {
1540 m_linkedAvatars.Remove(presence);
1541 }
1542 }
1543 }
1544
1545 /// <summary>
1546 /// Returns the list of linked presences (avatars sat on this group)
1547 /// </summary>
1548 /// <param name="agentID"></param>
1549 public List<ScenePresence> GetLinkedAvatars()
1550 {
1551 return m_linkedAvatars;
1552 }
1553
1554 /// <summary>
1555 /// Attach this scene object to the given avatar.
1556 /// </summary>
1557 /// <param name="agentID"></param>
1558 /// <param name="attachmentpoint"></param>
1559 /// <param name="AttachOffset"></param>
1560 private void AttachToAgent(
1561 ScenePresence avatar, SceneObjectGroup so, uint attachmentpoint, Vector3 attachOffset, bool silent)
1562 {
1563 if (avatar != null)
1564 {
1565 // don't attach attachments to child agents
1566 if (avatar.IsChildAgent) return;
1567
1568 // Remove from database and parcel prim count
1569 m_scene.DeleteFromStorage(so.UUID);
1570 m_scene.EventManager.TriggerParcelPrimCountTainted();
1571
1572 so.AttachedAvatar = avatar.UUID;
1573
1574 if (so.RootPart.PhysActor != null)
1575 {
1576 m_scene.PhysicsScene.RemovePrim(so.RootPart.PhysActor);
1577 so.RootPart.PhysActor = null;
1578 }
1579
1580 so.AbsolutePosition = attachOffset;
1581 so.RootPart.AttachedPos = attachOffset;
1582 so.IsAttachment = true;
1583 so.RootPart.SetParentLocalId(avatar.LocalId);
1584 so.AttachmentPoint = attachmentpoint;
1585
1586 avatar.AddAttachment(this);
1587
1588 if (!silent)
1589 {
1590 // Killing it here will cause the client to deselect it
1591 // It then reappears on the avatar, deselected
1592 // through the full update below
1593 //
1594 if (IsSelected)
1595 {
1596 m_scene.SendKillObject(new List<uint> { m_rootPart.LocalId });
1597 }
1598
1599 IsSelected = false; // fudge....
1600 ScheduleGroupForFullUpdate();
1601 }
1602 }
1603 else
1604 {
1605 m_log.WarnFormat(
1606 "[SOG]: Tried to add attachment {0} to avatar with UUID {1} in region {2} but the avatar is not present",
1607 UUID, avatar.ControllingClient.AgentId, Scene.RegionInfo.RegionName);
1608 }
1609 }
1610
1611 public byte GetAttachmentPoint()
1612 {
1613 return m_rootPart.Shape.State;
1614 }
1615
1616 public void DetachToGround()
1617 {
1618 ScenePresence avatar = m_scene.GetScenePresence(AttachedAvatar);
1619 if (avatar == null)
1620 return;
1621
1622 avatar.RemoveAttachment(this);
1623
1624 Vector3 detachedpos = new Vector3(127f,127f,127f);
1625 if (avatar == null)
1626 return;
1627
1628 detachedpos = avatar.AbsolutePosition;
1629 FromItemID = UUID.Zero;
1630
1631 AbsolutePosition = detachedpos;
1632 AttachedAvatar = UUID.Zero;
1633
1634 //SceneObjectPart[] parts = m_parts.GetArray();
1635 //for (int i = 0; i < parts.Length; i++)
1636 // parts[i].AttachedAvatar = UUID.Zero;
1637
1638 m_rootPart.SetParentLocalId(0);
1639 AttachmentPoint = (byte)0;
1640 // must check if buildind should be true or false here
1641 m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_rootPart.VolumeDetectActive,false);
1642 HasGroupChanged = true;
1643 RootPart.Rezzed = DateTime.Now;
1644 RootPart.RemFlag(PrimFlags.TemporaryOnRez);
1645 AttachToBackup();
1646 m_scene.EventManager.TriggerParcelPrimCountTainted();
1647 m_rootPart.ScheduleFullUpdate();
1648 m_rootPart.ClearUndoState();
1649 }
1650
1651 public void DetachToInventoryPrep()
1652 {
1653 ScenePresence avatar = m_scene.GetScenePresence(AttachedAvatar);
1654 //Vector3 detachedpos = new Vector3(127f, 127f, 127f);
1655 if (avatar != null)
1656 {
1657 //detachedpos = avatar.AbsolutePosition;
1658 avatar.RemoveAttachment(this);
1659 }
1660
1661 AttachedAvatar = UUID.Zero;
1662
1663 /*SceneObjectPart[] parts = m_parts.GetArray();
1664 for (int i = 0; i < parts.Length; i++)
1665 parts[i].AttachedAvatar = UUID.Zero;*/
1666
1667 m_rootPart.SetParentLocalId(0);
1668 //m_rootPart.SetAttachmentPoint((byte)0);
1669 IsAttachment = false;
1670 AbsolutePosition = m_rootPart.AttachedPos;
1671 //m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_scene.m_physicalPrim);
1672 //AttachToBackup();
1673 //m_rootPart.ScheduleFullUpdate();
1674 }
1675
1676 /// <summary>
1057 /// 1677 ///
1058 /// </summary> 1678 /// </summary>
1059 /// <param name="part"></param> 1679 /// <param name="part"></param>
@@ -1093,7 +1713,10 @@ namespace OpenSim.Region.Framework.Scenes
1093 public void AddPart(SceneObjectPart part) 1713 public void AddPart(SceneObjectPart part)
1094 { 1714 {
1095 part.SetParent(this); 1715 part.SetParent(this);
1096 part.LinkNum = m_parts.Add(part.UUID, part); 1716 m_parts.Add(part.UUID, part);
1717
1718 part.LinkNum = m_parts.Count;
1719
1097 if (part.LinkNum == 2) 1720 if (part.LinkNum == 2)
1098 RootPart.LinkNum = 1; 1721 RootPart.LinkNum = 1;
1099 } 1722 }
@@ -1184,7 +1807,7 @@ namespace OpenSim.Region.Framework.Scenes
1184// "[SCENE OBJECT GROUP]: Processing OnGrabPart for {0} on {1} {2}, offsetPos {3}", 1807// "[SCENE OBJECT GROUP]: Processing OnGrabPart for {0} on {1} {2}, offsetPos {3}",
1185// remoteClient.Name, part.Name, part.LocalId, offsetPos); 1808// remoteClient.Name, part.Name, part.LocalId, offsetPos);
1186 1809
1187 part.StoreUndoState(); 1810// part.StoreUndoState();
1188 part.OnGrab(offsetPos, remoteClient); 1811 part.OnGrab(offsetPos, remoteClient);
1189 } 1812 }
1190 1813
@@ -1204,6 +1827,11 @@ namespace OpenSim.Region.Framework.Scenes
1204 /// <param name="silent">If true then deletion is not broadcast to clients</param> 1827 /// <param name="silent">If true then deletion is not broadcast to clients</param>
1205 public void DeleteGroupFromScene(bool silent) 1828 public void DeleteGroupFromScene(bool silent)
1206 { 1829 {
1830 // We need to keep track of this state in case this group is still queued for backup.
1831 IsDeleted = true;
1832
1833 DetachFromBackup();
1834
1207 SceneObjectPart[] parts = m_parts.GetArray(); 1835 SceneObjectPart[] parts = m_parts.GetArray();
1208 for (int i = 0; i < parts.Length; i++) 1836 for (int i = 0; i < parts.Length; i++)
1209 { 1837 {
@@ -1227,6 +1855,7 @@ namespace OpenSim.Region.Framework.Scenes
1227 } 1855 }
1228 }); 1856 });
1229 } 1857 }
1858
1230 } 1859 }
1231 1860
1232 public void AddScriptLPS(int count) 1861 public void AddScriptLPS(int count)
@@ -1296,28 +1925,43 @@ namespace OpenSim.Region.Framework.Scenes
1296 /// </summary> 1925 /// </summary>
1297 public void ApplyPhysics() 1926 public void ApplyPhysics()
1298 { 1927 {
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(); 1928 SceneObjectPart[] parts = m_parts.GetArray();
1304 if (parts.Length > 1) 1929 if (parts.Length > 1)
1305 { 1930 {
1931 ResetChildPrimPhysicsPositions();
1932
1933 // Apply physics to the root prim
1934 m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_rootPart.VolumeDetectActive, true);
1935
1936
1306 for (int i = 0; i < parts.Length; i++) 1937 for (int i = 0; i < parts.Length; i++)
1307 { 1938 {
1308 SceneObjectPart part = parts[i]; 1939 SceneObjectPart part = parts[i];
1309 if (part.LocalId != m_rootPart.LocalId) 1940 if (part.LocalId != m_rootPart.LocalId)
1310 part.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), part.VolumeDetectActive); 1941 part.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), part.VolumeDetectActive, true);
1311 } 1942 }
1312
1313 // Hack to get the physics scene geometries in the right spot 1943 // Hack to get the physics scene geometries in the right spot
1314 ResetChildPrimPhysicsPositions(); 1944// ResetChildPrimPhysicsPositions();
1945 if (m_rootPart.PhysActor != null)
1946 {
1947 m_rootPart.PhysActor.Building = false;
1948 }
1949 }
1950 else
1951 {
1952 // Apply physics to the root prim
1953 m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_rootPart.VolumeDetectActive, false);
1315 } 1954 }
1316 } 1955 }
1317 1956
1318 public void SetOwnerId(UUID userId) 1957 public void SetOwnerId(UUID userId)
1319 { 1958 {
1320 ForEachPart(delegate(SceneObjectPart part) { part.OwnerID = userId; }); 1959 ForEachPart(delegate(SceneObjectPart part)
1960 {
1961
1962 part.OwnerID = userId;
1963
1964 });
1321 } 1965 }
1322 1966
1323 public void ForEachPart(Action<SceneObjectPart> whatToDo) 1967 public void ForEachPart(Action<SceneObjectPart> whatToDo)
@@ -1349,11 +1993,17 @@ namespace OpenSim.Region.Framework.Scenes
1349 return; 1993 return;
1350 } 1994 }
1351 1995
1996 if ((RootPart.Flags & PrimFlags.TemporaryOnRez) != 0)
1997 return;
1998
1352 // Since this is the top of the section of call stack for backing up a particular scene object, don't let 1999 // 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. 2000 // any exception propogate upwards.
1354 try 2001 try
1355 { 2002 {
1356 if (!m_scene.ShuttingDown) // if shutting down then there will be nothing to handle the return so leave till next restart 2003 if (!m_scene.ShuttingDown || // if shutting down then there will be nothing to handle the return so leave till next restart
2004 !m_scene.LoginsEnabled || // We're starting up or doing maintenance, don't mess with things
2005 m_scene.LoadingPrims) // Land may not be valid yet
2006
1357 { 2007 {
1358 ILandObject parcel = m_scene.LandChannel.GetLandObject( 2008 ILandObject parcel = m_scene.LandChannel.GetLandObject(
1359 m_rootPart.GroupPosition.X, m_rootPart.GroupPosition.Y); 2009 m_rootPart.GroupPosition.X, m_rootPart.GroupPosition.Y);
@@ -1380,6 +2030,7 @@ namespace OpenSim.Region.Framework.Scenes
1380 } 2030 }
1381 } 2031 }
1382 } 2032 }
2033
1383 } 2034 }
1384 2035
1385 if (m_scene.UseBackup && HasGroupChanged) 2036 if (m_scene.UseBackup && HasGroupChanged)
@@ -1387,10 +2038,30 @@ namespace OpenSim.Region.Framework.Scenes
1387 // don't backup while it's selected or you're asking for changes mid stream. 2038 // don't backup while it's selected or you're asking for changes mid stream.
1388 if (isTimeToPersist() || forcedBackup) 2039 if (isTimeToPersist() || forcedBackup)
1389 { 2040 {
2041 if (m_rootPart.PhysActor != null &&
2042 (!m_rootPart.PhysActor.IsPhysical))
2043 {
2044 // Possible ghost prim
2045 if (m_rootPart.PhysActor.Position != m_rootPart.GroupPosition)
2046 {
2047 foreach (SceneObjectPart part in m_parts.GetArray())
2048 {
2049 // Re-set physics actor positions and
2050 // orientations
2051 part.GroupPosition = m_rootPart.GroupPosition;
2052 }
2053 }
2054 }
1390// m_log.DebugFormat( 2055// m_log.DebugFormat(
1391// "[SCENE]: Storing {0}, {1} in {2}", 2056// "[SCENE]: Storing {0}, {1} in {2}",
1392// Name, UUID, m_scene.RegionInfo.RegionName); 2057// Name, UUID, m_scene.RegionInfo.RegionName);
1393 2058
2059 if (RootPart.Shape.PCode == 9 && RootPart.Shape.State != 0)
2060 {
2061 RootPart.Shape.State = 0;
2062 ScheduleGroupForFullUpdate();
2063 }
2064
1394 SceneObjectGroup backup_group = Copy(false); 2065 SceneObjectGroup backup_group = Copy(false);
1395 backup_group.RootPart.Velocity = RootPart.Velocity; 2066 backup_group.RootPart.Velocity = RootPart.Velocity;
1396 backup_group.RootPart.Acceleration = RootPart.Acceleration; 2067 backup_group.RootPart.Acceleration = RootPart.Acceleration;
@@ -1400,6 +2071,15 @@ namespace OpenSim.Region.Framework.Scenes
1400 HasGroupChangedDueToDelink = false; 2071 HasGroupChangedDueToDelink = false;
1401 2072
1402 m_scene.EventManager.TriggerOnSceneObjectPreSave(backup_group, this); 2073 m_scene.EventManager.TriggerOnSceneObjectPreSave(backup_group, this);
2074 backup_group.ForEachPart(delegate(SceneObjectPart part)
2075 {
2076 if (part.KeyframeMotion != null)
2077 {
2078 part.KeyframeMotion = KeyframeMotion.FromData(backup_group, part.KeyframeMotion.Serialize());
2079 part.KeyframeMotion.UpdateSceneObject(this);
2080 }
2081 });
2082
1403 datastore.StoreObject(backup_group, m_scene.RegionInfo.RegionID); 2083 datastore.StoreObject(backup_group, m_scene.RegionInfo.RegionID);
1404 2084
1405 backup_group.ForEachPart(delegate(SceneObjectPart part) 2085 backup_group.ForEachPart(delegate(SceneObjectPart part)
@@ -1456,10 +2136,14 @@ namespace OpenSim.Region.Framework.Scenes
1456 /// <returns></returns> 2136 /// <returns></returns>
1457 public SceneObjectGroup Copy(bool userExposed) 2137 public SceneObjectGroup Copy(bool userExposed)
1458 { 2138 {
2139 m_dupeInProgress = true;
1459 SceneObjectGroup dupe = (SceneObjectGroup)MemberwiseClone(); 2140 SceneObjectGroup dupe = (SceneObjectGroup)MemberwiseClone();
1460 dupe.m_isBackedUp = false; 2141 dupe.m_isBackedUp = false;
1461 dupe.m_parts = new MapAndArray<OpenMetaverse.UUID, SceneObjectPart>(); 2142 dupe.m_parts = new MapAndArray<OpenMetaverse.UUID, SceneObjectPart>();
1462 2143
2144 // new group as no sitting avatars
2145 dupe.m_linkedAvatars = new List<ScenePresence>();
2146
1463 // Warning, The following code related to previousAttachmentStatus is needed so that clones of 2147 // 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! 2148 // 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! 2149 // Normally, setting AbsolutePosition will bordercross a prim if it's outside the region!
@@ -1470,7 +2154,7 @@ namespace OpenSim.Region.Framework.Scenes
1470 // This is only necessary when userExposed is false! 2154 // This is only necessary when userExposed is false!
1471 2155
1472 bool previousAttachmentStatus = dupe.IsAttachment; 2156 bool previousAttachmentStatus = dupe.IsAttachment;
1473 2157
1474 if (!userExposed) 2158 if (!userExposed)
1475 dupe.IsAttachment = true; 2159 dupe.IsAttachment = true;
1476 2160
@@ -1488,11 +2172,11 @@ namespace OpenSim.Region.Framework.Scenes
1488 dupe.m_rootPart.TrimPermissions(); 2172 dupe.m_rootPart.TrimPermissions();
1489 2173
1490 List<SceneObjectPart> partList = new List<SceneObjectPart>(m_parts.GetArray()); 2174 List<SceneObjectPart> partList = new List<SceneObjectPart>(m_parts.GetArray());
1491 2175
1492 partList.Sort(delegate(SceneObjectPart p1, SceneObjectPart p2) 2176 partList.Sort(delegate(SceneObjectPart p1, SceneObjectPart p2)
1493 { 2177 {
1494 return p1.LinkNum.CompareTo(p2.LinkNum); 2178 return p1.LinkNum.CompareTo(p2.LinkNum);
1495 } 2179 }
1496 ); 2180 );
1497 2181
1498 foreach (SceneObjectPart part in partList) 2182 foreach (SceneObjectPart part in partList)
@@ -1502,41 +2186,53 @@ namespace OpenSim.Region.Framework.Scenes
1502 { 2186 {
1503 newPart = dupe.CopyPart(part, OwnerID, GroupID, userExposed); 2187 newPart = dupe.CopyPart(part, OwnerID, GroupID, userExposed);
1504 newPart.LinkNum = part.LinkNum; 2188 newPart.LinkNum = part.LinkNum;
1505 } 2189 if (userExposed)
2190 newPart.ParentID = dupe.m_rootPart.LocalId;
2191 }
1506 else 2192 else
1507 { 2193 {
1508 newPart = dupe.m_rootPart; 2194 newPart = dupe.m_rootPart;
1509 } 2195 }
2196/*
2197 bool isphys = ((newPart.Flags & PrimFlags.Physics) != 0);
2198 bool isphan = ((newPart.Flags & PrimFlags.Phantom) != 0);
1510 2199
1511 // Need to duplicate the physics actor as well 2200 // Need to duplicate the physics actor as well
1512 PhysicsActor originalPartPa = part.PhysActor; 2201 if (userExposed && (isphys || !isphan || newPart.VolumeDetectActive))
1513 if (originalPartPa != null && userExposed)
1514 { 2202 {
1515 PrimitiveBaseShape pbs = newPart.Shape; 2203 PrimitiveBaseShape pbs = newPart.Shape;
1516
1517 newPart.PhysActor 2204 newPart.PhysActor
1518 = m_scene.PhysicsScene.AddPrimShape( 2205 = m_scene.PhysicsScene.AddPrimShape(
1519 string.Format("{0}/{1}", newPart.Name, newPart.UUID), 2206 string.Format("{0}/{1}", newPart.Name, newPart.UUID),
1520 pbs, 2207 pbs,
1521 newPart.AbsolutePosition, 2208 newPart.AbsolutePosition,
1522 newPart.Scale, 2209 newPart.Scale,
1523 newPart.RotationOffset, 2210 newPart.GetWorldRotation(),
1524 originalPartPa.IsPhysical, 2211 isphys,
2212 isphan,
1525 newPart.LocalId); 2213 newPart.LocalId);
1526 2214
1527 newPart.DoPhysicsPropertyUpdate(originalPartPa.IsPhysical, true); 2215 newPart.DoPhysicsPropertyUpdate(isphys, true);
1528 } 2216 */
2217 if (userExposed)
2218 newPart.ApplyPhysics((uint)newPart.Flags,newPart.VolumeDetectActive,true);
2219// }
1529 } 2220 }
1530 2221
1531 if (userExposed) 2222 if (userExposed)
1532 { 2223 {
1533 dupe.UpdateParentIDs(); 2224// done above dupe.UpdateParentIDs();
2225
2226 if (dupe.m_rootPart.PhysActor != null)
2227 dupe.m_rootPart.PhysActor.Building = false; // tell physics to finish building
2228
1534 dupe.HasGroupChanged = true; 2229 dupe.HasGroupChanged = true;
1535 dupe.AttachToBackup(); 2230 dupe.AttachToBackup();
1536 2231
1537 ScheduleGroupForFullUpdate(); 2232 ScheduleGroupForFullUpdate();
1538 } 2233 }
1539 2234
2235 m_dupeInProgress = false;
1540 return dupe; 2236 return dupe;
1541 } 2237 }
1542 2238
@@ -1548,11 +2244,24 @@ namespace OpenSim.Region.Framework.Scenes
1548 /// <param name="cGroupID"></param> 2244 /// <param name="cGroupID"></param>
1549 public void CopyRootPart(SceneObjectPart part, UUID cAgentID, UUID cGroupID, bool userExposed) 2245 public void CopyRootPart(SceneObjectPart part, UUID cAgentID, UUID cGroupID, bool userExposed)
1550 { 2246 {
1551 SetRootPart(part.Copy(m_scene.AllocateLocalId(), OwnerID, GroupID, 0, userExposed)); 2247 // SetRootPart(part.Copy(m_scene.AllocateLocalId(), OwnerID, GroupID, 0, userExposed));
2248 // give newpart a new local ID lettng old part keep same
2249 SceneObjectPart newpart = part.Copy(part.LocalId, OwnerID, GroupID, 0, userExposed);
2250 newpart.LocalId = m_scene.AllocateLocalId();
2251
2252 SetRootPart(newpart);
2253 if (userExposed)
2254 RootPart.Velocity = Vector3.Zero; // In case source is moving
1552 } 2255 }
1553 2256
1554 public void ScriptSetPhysicsStatus(bool usePhysics) 2257 public void ScriptSetPhysicsStatus(bool usePhysics)
1555 { 2258 {
2259 if (usePhysics)
2260 {
2261 if (RootPart.KeyframeMotion != null)
2262 RootPart.KeyframeMotion.Stop();
2263 RootPart.KeyframeMotion = null;
2264 }
1556 UpdatePrimFlags(RootPart.LocalId, usePhysics, IsTemporary, IsPhantom, IsVolumeDetect); 2265 UpdatePrimFlags(RootPart.LocalId, usePhysics, IsTemporary, IsPhantom, IsVolumeDetect);
1557 } 2266 }
1558 2267
@@ -1600,13 +2309,14 @@ namespace OpenSim.Region.Framework.Scenes
1600 2309
1601 if (pa != null) 2310 if (pa != null)
1602 { 2311 {
1603 pa.AddForce(impulse, true); 2312 // false to be applied as a impulse
2313 pa.AddForce(impulse, false);
1604 m_scene.PhysicsScene.AddPhysicsActorTaint(pa); 2314 m_scene.PhysicsScene.AddPhysicsActorTaint(pa);
1605 } 2315 }
1606 } 2316 }
1607 } 2317 }
1608 2318
1609 public void applyAngularImpulse(Vector3 impulse) 2319 public void ApplyAngularImpulse(Vector3 impulse)
1610 { 2320 {
1611 PhysicsActor pa = RootPart.PhysActor; 2321 PhysicsActor pa = RootPart.PhysActor;
1612 2322
@@ -1614,21 +2324,8 @@ namespace OpenSim.Region.Framework.Scenes
1614 { 2324 {
1615 if (!IsAttachment) 2325 if (!IsAttachment)
1616 { 2326 {
1617 pa.AddAngularForce(impulse, true); 2327 // false to be applied as a impulse
1618 m_scene.PhysicsScene.AddPhysicsActorTaint(pa); 2328 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); 2329 m_scene.PhysicsScene.AddPhysicsActorTaint(pa);
1633 } 2330 }
1634 } 2331 }
@@ -1636,20 +2333,10 @@ namespace OpenSim.Region.Framework.Scenes
1636 2333
1637 public Vector3 GetTorque() 2334 public Vector3 GetTorque()
1638 { 2335 {
1639 PhysicsActor pa = RootPart.PhysActor; 2336 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 } 2337 }
1652 2338
2339 // This is used by both Double-Click Auto-Pilot and llMoveToTarget() in an attached object
1653 public void moveToTarget(Vector3 target, float tau) 2340 public void moveToTarget(Vector3 target, float tau)
1654 { 2341 {
1655 if (IsAttachment) 2342 if (IsAttachment)
@@ -1681,6 +2368,46 @@ namespace OpenSim.Region.Framework.Scenes
1681 pa.PIDActive = false; 2368 pa.PIDActive = false;
1682 } 2369 }
1683 2370
2371 public void rotLookAt(Quaternion target, float strength, float damping)
2372 {
2373 SceneObjectPart rootpart = m_rootPart;
2374 if (rootpart != null)
2375 {
2376 if (IsAttachment)
2377 {
2378 /*
2379 ScenePresence avatar = m_scene.GetScenePresence(rootpart.AttachedAvatar);
2380 if (avatar != null)
2381 {
2382 Rotate the Av?
2383 } */
2384 }
2385 else
2386 {
2387 if (rootpart.PhysActor != null)
2388 { // APID must be implemented in your physics system for this to function.
2389 rootpart.PhysActor.APIDTarget = new Quaternion(target.X, target.Y, target.Z, target.W);
2390 rootpart.PhysActor.APIDStrength = strength;
2391 rootpart.PhysActor.APIDDamping = damping;
2392 rootpart.PhysActor.APIDActive = true;
2393 }
2394 }
2395 }
2396 }
2397
2398 public void stopLookAt()
2399 {
2400 SceneObjectPart rootpart = m_rootPart;
2401 if (rootpart != null)
2402 {
2403 if (rootpart.PhysActor != null)
2404 { // APID must be implemented in your physics system for this to function.
2405 rootpart.PhysActor.APIDActive = false;
2406 }
2407 }
2408
2409 }
2410
1684 /// <summary> 2411 /// <summary>
1685 /// Uses a PID to attempt to clamp the object on the Z axis at the given height over tau seconds. 2412 /// Uses a PID to attempt to clamp the object on the Z axis at the given height over tau seconds.
1686 /// </summary> 2413 /// </summary>
@@ -1697,7 +2424,7 @@ namespace OpenSim.Region.Framework.Scenes
1697 { 2424 {
1698 pa.PIDHoverHeight = height; 2425 pa.PIDHoverHeight = height;
1699 pa.PIDHoverType = hoverType; 2426 pa.PIDHoverType = hoverType;
1700 pa.PIDTau = tau; 2427 pa.PIDHoverTau = tau;
1701 pa.PIDHoverActive = true; 2428 pa.PIDHoverActive = true;
1702 } 2429 }
1703 else 2430 else
@@ -1737,7 +2464,12 @@ namespace OpenSim.Region.Framework.Scenes
1737 /// <param name="cGroupID"></param> 2464 /// <param name="cGroupID"></param>
1738 public SceneObjectPart CopyPart(SceneObjectPart part, UUID cAgentID, UUID cGroupID, bool userExposed) 2465 public SceneObjectPart CopyPart(SceneObjectPart part, UUID cAgentID, UUID cGroupID, bool userExposed)
1739 { 2466 {
1740 SceneObjectPart newPart = part.Copy(m_scene.AllocateLocalId(), OwnerID, GroupID, m_parts.Count, userExposed); 2467 // give new ID to the new part, letting old keep original
2468 // SceneObjectPart newPart = part.Copy(m_scene.AllocateLocalId(), OwnerID, GroupID, m_parts.Count, userExposed);
2469 SceneObjectPart newPart = part.Copy(part.LocalId, OwnerID, GroupID, m_parts.Count, userExposed);
2470 newPart.LocalId = m_scene.AllocateLocalId();
2471 newPart.SetParent(this);
2472
1741 AddPart(newPart); 2473 AddPart(newPart);
1742 2474
1743 SetPartAsNonRoot(newPart); 2475 SetPartAsNonRoot(newPart);
@@ -1876,11 +2608,11 @@ namespace OpenSim.Region.Framework.Scenes
1876 /// Immediately send a full update for this scene object. 2608 /// Immediately send a full update for this scene object.
1877 /// </summary> 2609 /// </summary>
1878 public void SendGroupFullUpdate() 2610 public void SendGroupFullUpdate()
1879 { 2611 {
1880 if (IsDeleted) 2612 if (IsDeleted)
1881 return; 2613 return;
1882 2614
1883// m_log.DebugFormat("[SOG]: Sending immediate full group update for {0} {1}", Name, UUID); 2615// m_log.DebugFormat("[SOG]: Sending immediate full group update for {0} {1}", Name, UUID);
1884 2616
1885 RootPart.SendFullUpdateToAllClients(); 2617 RootPart.SendFullUpdateToAllClients();
1886 2618
@@ -2017,6 +2749,11 @@ namespace OpenSim.Region.Framework.Scenes
2017 // 'linkPart' == the root of the group being linked into this group 2749 // 'linkPart' == the root of the group being linked into this group
2018 SceneObjectPart linkPart = objectGroup.m_rootPart; 2750 SceneObjectPart linkPart = objectGroup.m_rootPart;
2019 2751
2752 if (m_rootPart.PhysActor != null)
2753 m_rootPart.PhysActor.Building = true;
2754 if (linkPart.PhysActor != null)
2755 linkPart.PhysActor.Building = true;
2756
2020 // physics flags from group to be applied to linked parts 2757 // physics flags from group to be applied to linked parts
2021 bool grpusephys = UsesPhysics; 2758 bool grpusephys = UsesPhysics;
2022 bool grptemporary = IsTemporary; 2759 bool grptemporary = IsTemporary;
@@ -2042,12 +2779,12 @@ namespace OpenSim.Region.Framework.Scenes
2042 Vector3 axPos = linkPart.OffsetPosition; 2779 Vector3 axPos = linkPart.OffsetPosition;
2043 // Rotate the linking root SOP's position to be relative to the new root prim 2780 // Rotate the linking root SOP's position to be relative to the new root prim
2044 Quaternion parentRot = m_rootPart.RotationOffset; 2781 Quaternion parentRot = m_rootPart.RotationOffset;
2045 axPos *= Quaternion.Inverse(parentRot); 2782 axPos *= Quaternion.Conjugate(parentRot);
2046 linkPart.OffsetPosition = axPos; 2783 linkPart.OffsetPosition = axPos;
2047 2784
2048 // Make the linking root SOP's rotation relative to the new root prim 2785 // Make the linking root SOP's rotation relative to the new root prim
2049 Quaternion oldRot = linkPart.RotationOffset; 2786 Quaternion oldRot = linkPart.RotationOffset;
2050 Quaternion newRot = Quaternion.Inverse(parentRot) * oldRot; 2787 Quaternion newRot = Quaternion.Conjugate(parentRot) * oldRot;
2051 linkPart.RotationOffset = newRot; 2788 linkPart.RotationOffset = newRot;
2052 2789
2053 // If there is only one SOP in a SOG, the LinkNum is zero. I.e., not a linkset. 2790 // If there is only one SOP in a SOG, the LinkNum is zero. I.e., not a linkset.
@@ -2081,7 +2818,7 @@ namespace OpenSim.Region.Framework.Scenes
2081 linkPart.CreateSelected = true; 2818 linkPart.CreateSelected = true;
2082 2819
2083 // let physics know preserve part volume dtc messy since UpdatePrimFlags doesn't look to parent changes for now 2820 // let physics know preserve part volume dtc messy since UpdatePrimFlags doesn't look to parent changes for now
2084 linkPart.UpdatePrimFlags(grpusephys, grptemporary, (IsPhantom || (linkPart.Flags & PrimFlags.Phantom) != 0), linkPart.VolumeDetectActive); 2821 linkPart.UpdatePrimFlags(grpusephys, grptemporary, (IsPhantom || (linkPart.Flags & PrimFlags.Phantom) != 0), linkPart.VolumeDetectActive, true);
2085 2822
2086 // If the added SOP is physical, also tell the physics engine about the link relationship. 2823 // If the added SOP is physical, also tell the physics engine about the link relationship.
2087 if (linkPart.PhysActor != null && m_rootPart.PhysActor != null && m_rootPart.PhysActor.IsPhysical) 2824 if (linkPart.PhysActor != null && m_rootPart.PhysActor != null && m_rootPart.PhysActor.IsPhysical)
@@ -2091,6 +2828,7 @@ namespace OpenSim.Region.Framework.Scenes
2091 } 2828 }
2092 2829
2093 linkPart.LinkNum = linkNum++; 2830 linkPart.LinkNum = linkNum++;
2831 linkPart.UpdatePrimFlags(UsesPhysics, IsTemporary, IsPhantom, IsVolumeDetect, false);
2094 2832
2095 // Get a list of the SOP's in the old group in order of their linknum's. 2833 // Get a list of the SOP's in the old group in order of their linknum's.
2096 SceneObjectPart[] ogParts = objectGroup.Parts; 2834 SceneObjectPart[] ogParts = objectGroup.Parts;
@@ -2109,7 +2847,7 @@ namespace OpenSim.Region.Framework.Scenes
2109 2847
2110 // Update the physics flags for the newly added SOP 2848 // Update the physics flags for the newly added SOP
2111 // (Is this necessary? LinkNonRootPart() has already called UpdatePrimFlags but with different flags!??) 2849 // (Is this necessary? LinkNonRootPart() has already called UpdatePrimFlags but with different flags!??)
2112 part.UpdatePrimFlags(grpusephys, grptemporary, (IsPhantom || (part.Flags & PrimFlags.Phantom) != 0), part.VolumeDetectActive); 2850 part.UpdatePrimFlags(grpusephys, grptemporary, (IsPhantom || (part.Flags & PrimFlags.Phantom) != 0), part.VolumeDetectActive, true);
2113 2851
2114 // If the added SOP is physical, also tell the physics engine about the link relationship. 2852 // If the added SOP is physical, also tell the physics engine about the link relationship.
2115 if (part.PhysActor != null && m_rootPart.PhysActor != null && m_rootPart.PhysActor.IsPhysical) 2853 if (part.PhysActor != null && m_rootPart.PhysActor != null && m_rootPart.PhysActor.IsPhysical)
@@ -2127,7 +2865,7 @@ namespace OpenSim.Region.Framework.Scenes
2127 objectGroup.IsDeleted = true; 2865 objectGroup.IsDeleted = true;
2128 2866
2129 objectGroup.m_parts.Clear(); 2867 objectGroup.m_parts.Clear();
2130 2868
2131 // Can't do this yet since backup still makes use of the root part without any synchronization 2869 // Can't do this yet since backup still makes use of the root part without any synchronization
2132// objectGroup.m_rootPart = null; 2870// objectGroup.m_rootPart = null;
2133 2871
@@ -2138,6 +2876,9 @@ namespace OpenSim.Region.Framework.Scenes
2138 // unmoved prims! 2876 // unmoved prims!
2139 ResetChildPrimPhysicsPositions(); 2877 ResetChildPrimPhysicsPositions();
2140 2878
2879 if (m_rootPart.PhysActor != null)
2880 m_rootPart.PhysActor.Building = false;
2881
2141 //HasGroupChanged = true; 2882 //HasGroupChanged = true;
2142 //ScheduleGroupForFullUpdate(); 2883 //ScheduleGroupForFullUpdate();
2143 } 2884 }
@@ -2205,7 +2946,10 @@ namespace OpenSim.Region.Framework.Scenes
2205// m_log.DebugFormat( 2946// m_log.DebugFormat(
2206// "[SCENE OBJECT GROUP]: Delinking part {0}, {1} from group with root part {2}, {3}", 2947// "[SCENE OBJECT GROUP]: Delinking part {0}, {1} from group with root part {2}, {3}",
2207// linkPart.Name, linkPart.UUID, RootPart.Name, RootPart.UUID); 2948// linkPart.Name, linkPart.UUID, RootPart.Name, RootPart.UUID);
2208 2949
2950 if (m_rootPart.PhysActor != null)
2951 m_rootPart.PhysActor.Building = true;
2952
2209 linkPart.ClearUndoState(); 2953 linkPart.ClearUndoState();
2210 2954
2211 Vector3 worldPos = linkPart.GetWorldPosition(); 2955 Vector3 worldPos = linkPart.GetWorldPosition();
@@ -2276,6 +3020,14 @@ namespace OpenSim.Region.Framework.Scenes
2276 3020
2277 // When we delete a group, we currently have to force persist to the database if the object id has changed 3021 // When we delete a group, we currently have to force persist to the database if the object id has changed
2278 // (since delete works by deleting all rows which have a given object id) 3022 // (since delete works by deleting all rows which have a given object id)
3023
3024 // this is as it seems to be in sl now
3025 if(linkPart.PhysicsShapeType == (byte)PhysShapeType.none)
3026 linkPart.PhysicsShapeType = linkPart.DefaultPhysicsShapeType(); // root prims can't have type none for now
3027
3028 if (m_rootPart.PhysActor != null)
3029 m_rootPart.PhysActor.Building = false;
3030
2279 objectGroup.HasGroupChangedDueToDelink = true; 3031 objectGroup.HasGroupChangedDueToDelink = true;
2280 3032
2281 return objectGroup; 3033 return objectGroup;
@@ -2287,6 +3039,7 @@ namespace OpenSim.Region.Framework.Scenes
2287 /// <param name="objectGroup"></param> 3039 /// <param name="objectGroup"></param>
2288 public virtual void DetachFromBackup() 3040 public virtual void DetachFromBackup()
2289 { 3041 {
3042 m_scene.SceneGraph.FireDetachFromBackup(this);
2290 if (m_isBackedUp && Scene != null) 3043 if (m_isBackedUp && Scene != null)
2291 m_scene.EventManager.OnBackup -= ProcessBackup; 3044 m_scene.EventManager.OnBackup -= ProcessBackup;
2292 3045
@@ -2307,7 +3060,8 @@ namespace OpenSim.Region.Framework.Scenes
2307 Vector3 axPos = part.OffsetPosition; 3060 Vector3 axPos = part.OffsetPosition;
2308 axPos *= parentRot; 3061 axPos *= parentRot;
2309 part.OffsetPosition = axPos; 3062 part.OffsetPosition = axPos;
2310 part.GroupPosition = oldGroupPosition + part.OffsetPosition; 3063 Vector3 newPos = oldGroupPosition + part.OffsetPosition;
3064 part.GroupPosition = newPos;
2311 part.OffsetPosition = Vector3.Zero; 3065 part.OffsetPosition = Vector3.Zero;
2312 3066
2313 // Compution our rotation to be not relative to the old parent 3067 // Compution our rotation to be not relative to the old parent
@@ -2322,7 +3076,7 @@ namespace OpenSim.Region.Framework.Scenes
2322 part.LinkNum = linkNum; 3076 part.LinkNum = linkNum;
2323 3077
2324 // Compute the new position of this SOP relative to the group position 3078 // Compute the new position of this SOP relative to the group position
2325 part.OffsetPosition = part.GroupPosition - AbsolutePosition; 3079 part.OffsetPosition = newPos - AbsolutePosition;
2326 3080
2327 // (radams1 20120711: I don't know why part.OffsetPosition is set multiple times. 3081 // (radams1 20120711: I don't know why part.OffsetPosition is set multiple times.
2328 // It would have the affect of setting the physics engine position multiple 3082 // It would have the affect of setting the physics engine position multiple
@@ -2332,18 +3086,19 @@ namespace OpenSim.Region.Framework.Scenes
2332 // Rotate the relative position by the rotation of the group 3086 // Rotate the relative position by the rotation of the group
2333 Quaternion rootRotation = m_rootPart.RotationOffset; 3087 Quaternion rootRotation = m_rootPart.RotationOffset;
2334 Vector3 pos = part.OffsetPosition; 3088 Vector3 pos = part.OffsetPosition;
2335 pos *= Quaternion.Inverse(rootRotation); 3089 pos *= Quaternion.Conjugate(rootRotation);
2336 part.OffsetPosition = pos; 3090 part.OffsetPosition = pos;
2337 3091
2338 // Compute the SOP's rotation relative to the rotation of the group. 3092 // Compute the SOP's rotation relative to the rotation of the group.
2339 parentRot = m_rootPart.RotationOffset; 3093 parentRot = m_rootPart.RotationOffset;
2340 oldRot = part.RotationOffset; 3094 oldRot = part.RotationOffset;
2341 Quaternion newRot = Quaternion.Inverse(parentRot) * oldRot; 3095 Quaternion newRot = Quaternion.Conjugate(parentRot) * worldRot;
2342 part.RotationOffset = newRot; 3096 part.RotationOffset = newRot;
2343 3097
2344 // Since this SOP's state has changed, push those changes into the physics engine 3098 // Since this SOP's state has changed, push those changes into the physics engine
2345 // and the simulator. 3099 // and the simulator.
2346 part.UpdatePrimFlags(UsesPhysics, IsTemporary, IsPhantom, IsVolumeDetect); 3100 // done on caller
3101// part.UpdatePrimFlags(UsesPhysics, IsTemporary, IsPhantom, IsVolumeDetect, false);
2347 } 3102 }
2348 3103
2349 /// <summary> 3104 /// <summary>
@@ -2365,10 +3120,14 @@ namespace OpenSim.Region.Framework.Scenes
2365 { 3120 {
2366 if (!m_rootPart.BlockGrab) 3121 if (!m_rootPart.BlockGrab)
2367 { 3122 {
2368 Vector3 llmoveforce = pos - AbsolutePosition; 3123/* Vector3 llmoveforce = pos - AbsolutePosition;
2369 Vector3 grabforce = llmoveforce; 3124 Vector3 grabforce = llmoveforce;
2370 grabforce = (grabforce / 10) * pa.Mass; 3125 grabforce = (grabforce / 10) * pa.Mass;
2371 pa.AddForce(grabforce, true); 3126 */
3127 // empirically convert distance diference to a impulse
3128 Vector3 grabforce = pos - AbsolutePosition;
3129 grabforce = grabforce * (pa.Mass/ 10.0f);
3130 pa.AddForce(grabforce, false);
2372 m_scene.PhysicsScene.AddPhysicsActorTaint(pa); 3131 m_scene.PhysicsScene.AddPhysicsActorTaint(pa);
2373 } 3132 }
2374 } 3133 }
@@ -2594,8 +3353,22 @@ namespace OpenSim.Region.Framework.Scenes
2594 } 3353 }
2595 } 3354 }
2596 3355
2597 for (int i = 0; i < parts.Length; i++) 3356 if (parts.Length > 1)
2598 parts[i].UpdatePrimFlags(UsePhysics, SetTemporary, SetPhantom, SetVolumeDetect); 3357 {
3358 m_rootPart.UpdatePrimFlags(UsePhysics, SetTemporary, SetPhantom, SetVolumeDetect, true);
3359
3360 for (int i = 0; i < parts.Length; i++)
3361 {
3362
3363 if (parts[i].UUID != m_rootPart.UUID)
3364 parts[i].UpdatePrimFlags(UsePhysics, SetTemporary, SetPhantom, SetVolumeDetect, true);
3365 }
3366
3367 if (m_rootPart.PhysActor != null)
3368 m_rootPart.PhysActor.Building = false;
3369 }
3370 else
3371 m_rootPart.UpdatePrimFlags(UsePhysics, SetTemporary, SetPhantom, SetVolumeDetect, false);
2599 } 3372 }
2600 } 3373 }
2601 3374
@@ -2608,6 +3381,17 @@ namespace OpenSim.Region.Framework.Scenes
2608 } 3381 }
2609 } 3382 }
2610 3383
3384
3385
3386 /// <summary>
3387 /// Gets the number of parts
3388 /// </summary>
3389 /// <returns></returns>
3390 public int GetPartCount()
3391 {
3392 return Parts.Count();
3393 }
3394
2611 /// <summary> 3395 /// <summary>
2612 /// Update the texture entry for this part 3396 /// Update the texture entry for this part
2613 /// </summary> 3397 /// </summary>
@@ -2669,11 +3453,6 @@ namespace OpenSim.Region.Framework.Scenes
2669 /// <param name="scale"></param> 3453 /// <param name="scale"></param>
2670 public void GroupResize(Vector3 scale) 3454 public void GroupResize(Vector3 scale)
2671 { 3455 {
2672// m_log.DebugFormat(
2673// "[SCENE OBJECT GROUP]: Group resizing {0} {1} from {2} to {3}", Name, LocalId, RootPart.Scale, scale);
2674
2675 RootPart.StoreUndoState(true);
2676
2677 scale.X = Math.Min(scale.X, Scene.m_maxNonphys); 3456 scale.X = Math.Min(scale.X, Scene.m_maxNonphys);
2678 scale.Y = Math.Min(scale.Y, Scene.m_maxNonphys); 3457 scale.Y = Math.Min(scale.Y, Scene.m_maxNonphys);
2679 scale.Z = Math.Min(scale.Z, Scene.m_maxNonphys); 3458 scale.Z = Math.Min(scale.Z, Scene.m_maxNonphys);
@@ -2700,7 +3479,6 @@ namespace OpenSim.Region.Framework.Scenes
2700 SceneObjectPart obPart = parts[i]; 3479 SceneObjectPart obPart = parts[i];
2701 if (obPart.UUID != m_rootPart.UUID) 3480 if (obPart.UUID != m_rootPart.UUID)
2702 { 3481 {
2703// obPart.IgnoreUndoUpdate = true;
2704 Vector3 oldSize = new Vector3(obPart.Scale); 3482 Vector3 oldSize = new Vector3(obPart.Scale);
2705 3483
2706 float f = 1.0f; 3484 float f = 1.0f;
@@ -2764,8 +3542,6 @@ namespace OpenSim.Region.Framework.Scenes
2764 z *= a; 3542 z *= a;
2765 } 3543 }
2766 } 3544 }
2767
2768// obPart.IgnoreUndoUpdate = false;
2769 } 3545 }
2770 } 3546 }
2771 } 3547 }
@@ -2775,9 +3551,7 @@ namespace OpenSim.Region.Framework.Scenes
2775 prevScale.Y *= y; 3551 prevScale.Y *= y;
2776 prevScale.Z *= z; 3552 prevScale.Z *= z;
2777 3553
2778// RootPart.IgnoreUndoUpdate = true;
2779 RootPart.Resize(prevScale); 3554 RootPart.Resize(prevScale);
2780// RootPart.IgnoreUndoUpdate = false;
2781 3555
2782 parts = m_parts.GetArray(); 3556 parts = m_parts.GetArray();
2783 for (int i = 0; i < parts.Length; i++) 3557 for (int i = 0; i < parts.Length; i++)
@@ -2786,8 +3560,6 @@ namespace OpenSim.Region.Framework.Scenes
2786 3560
2787 if (obPart.UUID != m_rootPart.UUID) 3561 if (obPart.UUID != m_rootPart.UUID)
2788 { 3562 {
2789 obPart.IgnoreUndoUpdate = true;
2790
2791 Vector3 currentpos = new Vector3(obPart.OffsetPosition); 3563 Vector3 currentpos = new Vector3(obPart.OffsetPosition);
2792 currentpos.X *= x; 3564 currentpos.X *= x;
2793 currentpos.Y *= y; 3565 currentpos.Y *= y;
@@ -2800,16 +3572,12 @@ namespace OpenSim.Region.Framework.Scenes
2800 3572
2801 obPart.Resize(newSize); 3573 obPart.Resize(newSize);
2802 obPart.UpdateOffSet(currentpos); 3574 obPart.UpdateOffSet(currentpos);
2803
2804 obPart.IgnoreUndoUpdate = false;
2805 } 3575 }
2806 3576
2807// obPart.IgnoreUndoUpdate = false; 3577 HasGroupChanged = true;
2808// obPart.StoreUndoState(); 3578 m_rootPart.TriggerScriptChangedEvent(Changed.SCALE);
3579 ScheduleGroupForTerseUpdate();
2809 } 3580 }
2810
2811// m_log.DebugFormat(
2812// "[SCENE OBJECT GROUP]: Finished group resizing {0} {1} to {2}", Name, LocalId, RootPart.Scale);
2813 } 3581 }
2814 3582
2815 #endregion 3583 #endregion
@@ -2822,14 +3590,6 @@ namespace OpenSim.Region.Framework.Scenes
2822 /// <param name="pos"></param> 3590 /// <param name="pos"></param>
2823 public void UpdateGroupPosition(Vector3 pos) 3591 public void UpdateGroupPosition(Vector3 pos)
2824 { 3592 {
2825// m_log.DebugFormat("[SCENE OBJECT GROUP]: Updating group position on {0} {1} to {2}", Name, LocalId, pos);
2826
2827 RootPart.StoreUndoState(true);
2828
2829// SceneObjectPart[] parts = m_parts.GetArray();
2830// for (int i = 0; i < parts.Length; i++)
2831// parts[i].StoreUndoState();
2832
2833 if (m_scene.EventManager.TriggerGroupMove(UUID, pos)) 3593 if (m_scene.EventManager.TriggerGroupMove(UUID, pos))
2834 { 3594 {
2835 if (IsAttachment) 3595 if (IsAttachment)
@@ -2862,21 +3622,17 @@ namespace OpenSim.Region.Framework.Scenes
2862 /// </summary> 3622 /// </summary>
2863 /// <param name="pos"></param> 3623 /// <param name="pos"></param>
2864 /// <param name="localID"></param> 3624 /// <param name="localID"></param>
3625 ///
3626
2865 public void UpdateSinglePosition(Vector3 pos, uint localID) 3627 public void UpdateSinglePosition(Vector3 pos, uint localID)
2866 { 3628 {
2867 SceneObjectPart part = GetPart(localID); 3629 SceneObjectPart part = GetPart(localID);
2868 3630
2869// SceneObjectPart[] parts = m_parts.GetArray();
2870// for (int i = 0; i < parts.Length; i++)
2871// parts[i].StoreUndoState();
2872
2873 if (part != null) 3631 if (part != null)
2874 { 3632 {
2875// m_log.DebugFormat( 3633// unlock parts position change
2876// "[SCENE OBJECT GROUP]: Updating single position of {0} {1} to {2}", part.Name, part.LocalId, pos); 3634 if (m_rootPart.PhysActor != null)
2877 3635 m_rootPart.PhysActor.Building = true;
2878 part.StoreUndoState(false);
2879 part.IgnoreUndoUpdate = true;
2880 3636
2881 if (part.UUID == m_rootPart.UUID) 3637 if (part.UUID == m_rootPart.UUID)
2882 { 3638 {
@@ -2887,8 +3643,10 @@ namespace OpenSim.Region.Framework.Scenes
2887 part.UpdateOffSet(pos); 3643 part.UpdateOffSet(pos);
2888 } 3644 }
2889 3645
3646 if (m_rootPart.PhysActor != null)
3647 m_rootPart.PhysActor.Building = false;
3648
2890 HasGroupChanged = true; 3649 HasGroupChanged = true;
2891 part.IgnoreUndoUpdate = false;
2892 } 3650 }
2893 } 3651 }
2894 3652
@@ -2898,13 +3656,7 @@ namespace OpenSim.Region.Framework.Scenes
2898 /// <param name="pos"></param> 3656 /// <param name="pos"></param>
2899 public void UpdateRootPosition(Vector3 pos) 3657 public void UpdateRootPosition(Vector3 pos)
2900 { 3658 {
2901// m_log.DebugFormat( 3659 // needs to be called with phys building true
2902// "[SCENE OBJECT GROUP]: Updating root position of {0} {1} to {2}", Name, LocalId, pos);
2903
2904// SceneObjectPart[] parts = m_parts.GetArray();
2905// for (int i = 0; i < parts.Length; i++)
2906// parts[i].StoreUndoState();
2907
2908 Vector3 newPos = new Vector3(pos.X, pos.Y, pos.Z); 3660 Vector3 newPos = new Vector3(pos.X, pos.Y, pos.Z);
2909 Vector3 oldPos = 3661 Vector3 oldPos =
2910 new Vector3(AbsolutePosition.X + m_rootPart.OffsetPosition.X, 3662 new Vector3(AbsolutePosition.X + m_rootPart.OffsetPosition.X,
@@ -2927,7 +3679,14 @@ namespace OpenSim.Region.Framework.Scenes
2927 AbsolutePosition = newPos; 3679 AbsolutePosition = newPos;
2928 3680
2929 HasGroupChanged = true; 3681 HasGroupChanged = true;
2930 ScheduleGroupForTerseUpdate(); 3682 if (m_rootPart.Undoing)
3683 {
3684 ScheduleGroupForFullUpdate();
3685 }
3686 else
3687 {
3688 ScheduleGroupForTerseUpdate();
3689 }
2931 } 3690 }
2932 3691
2933 #endregion 3692 #endregion
@@ -2940,24 +3699,16 @@ namespace OpenSim.Region.Framework.Scenes
2940 /// <param name="rot"></param> 3699 /// <param name="rot"></param>
2941 public void UpdateGroupRotationR(Quaternion rot) 3700 public void UpdateGroupRotationR(Quaternion rot)
2942 { 3701 {
2943// m_log.DebugFormat(
2944// "[SCENE OBJECT GROUP]: Updating group rotation R of {0} {1} to {2}", Name, LocalId, rot);
2945
2946// SceneObjectPart[] parts = m_parts.GetArray();
2947// for (int i = 0; i < parts.Length; i++)
2948// parts[i].StoreUndoState();
2949
2950 m_rootPart.StoreUndoState(true);
2951
2952 m_rootPart.UpdateRotation(rot); 3702 m_rootPart.UpdateRotation(rot);
2953 3703
3704/* this is done by rootpart RotationOffset set called by UpdateRotation
2954 PhysicsActor actor = m_rootPart.PhysActor; 3705 PhysicsActor actor = m_rootPart.PhysActor;
2955 if (actor != null) 3706 if (actor != null)
2956 { 3707 {
2957 actor.Orientation = m_rootPart.RotationOffset; 3708 actor.Orientation = m_rootPart.RotationOffset;
2958 m_scene.PhysicsScene.AddPhysicsActorTaint(actor); 3709 m_scene.PhysicsScene.AddPhysicsActorTaint(actor);
2959 } 3710 }
2960 3711*/
2961 HasGroupChanged = true; 3712 HasGroupChanged = true;
2962 ScheduleGroupForTerseUpdate(); 3713 ScheduleGroupForTerseUpdate();
2963 } 3714 }
@@ -2969,16 +3720,6 @@ namespace OpenSim.Region.Framework.Scenes
2969 /// <param name="rot"></param> 3720 /// <param name="rot"></param>
2970 public void UpdateGroupRotationPR(Vector3 pos, Quaternion rot) 3721 public void UpdateGroupRotationPR(Vector3 pos, Quaternion rot)
2971 { 3722 {
2972// m_log.DebugFormat(
2973// "[SCENE OBJECT GROUP]: Updating group rotation PR of {0} {1} to {2}", Name, LocalId, rot);
2974
2975// SceneObjectPart[] parts = m_parts.GetArray();
2976// for (int i = 0; i < parts.Length; i++)
2977// parts[i].StoreUndoState();
2978
2979 RootPart.StoreUndoState(true);
2980 RootPart.IgnoreUndoUpdate = true;
2981
2982 m_rootPart.UpdateRotation(rot); 3723 m_rootPart.UpdateRotation(rot);
2983 3724
2984 PhysicsActor actor = m_rootPart.PhysActor; 3725 PhysicsActor actor = m_rootPart.PhysActor;
@@ -2997,8 +3738,6 @@ namespace OpenSim.Region.Framework.Scenes
2997 3738
2998 HasGroupChanged = true; 3739 HasGroupChanged = true;
2999 ScheduleGroupForTerseUpdate(); 3740 ScheduleGroupForTerseUpdate();
3000
3001 RootPart.IgnoreUndoUpdate = false;
3002 } 3741 }
3003 3742
3004 /// <summary> 3743 /// <summary>
@@ -3011,13 +3750,11 @@ namespace OpenSim.Region.Framework.Scenes
3011 SceneObjectPart part = GetPart(localID); 3750 SceneObjectPart part = GetPart(localID);
3012 3751
3013 SceneObjectPart[] parts = m_parts.GetArray(); 3752 SceneObjectPart[] parts = m_parts.GetArray();
3014 for (int i = 0; i < parts.Length; i++)
3015 parts[i].StoreUndoState();
3016 3753
3017 if (part != null) 3754 if (part != null)
3018 { 3755 {
3019// m_log.DebugFormat( 3756 if (m_rootPart.PhysActor != null)
3020// "[SCENE OBJECT GROUP]: Updating single rotation of {0} {1} to {2}", part.Name, part.LocalId, rot); 3757 m_rootPart.PhysActor.Building = true;
3021 3758
3022 if (part.UUID == m_rootPart.UUID) 3759 if (part.UUID == m_rootPart.UUID)
3023 { 3760 {
@@ -3027,6 +3764,9 @@ namespace OpenSim.Region.Framework.Scenes
3027 { 3764 {
3028 part.UpdateRotation(rot); 3765 part.UpdateRotation(rot);
3029 } 3766 }
3767
3768 if (m_rootPart.PhysActor != null)
3769 m_rootPart.PhysActor.Building = false;
3030 } 3770 }
3031 } 3771 }
3032 3772
@@ -3040,12 +3780,8 @@ namespace OpenSim.Region.Framework.Scenes
3040 SceneObjectPart part = GetPart(localID); 3780 SceneObjectPart part = GetPart(localID);
3041 if (part != null) 3781 if (part != null)
3042 { 3782 {
3043// m_log.DebugFormat( 3783 if (m_rootPart.PhysActor != null)
3044// "[SCENE OBJECT GROUP]: Updating single position and rotation of {0} {1} to {2}", 3784 m_rootPart.PhysActor.Building = true;
3045// part.Name, part.LocalId, rot);
3046
3047 part.StoreUndoState();
3048 part.IgnoreUndoUpdate = true;
3049 3785
3050 if (part.UUID == m_rootPart.UUID) 3786 if (part.UUID == m_rootPart.UUID)
3051 { 3787 {
@@ -3058,7 +3794,8 @@ namespace OpenSim.Region.Framework.Scenes
3058 part.OffsetPosition = pos; 3794 part.OffsetPosition = pos;
3059 } 3795 }
3060 3796
3061 part.IgnoreUndoUpdate = false; 3797 if (m_rootPart.PhysActor != null)
3798 m_rootPart.PhysActor.Building = false;
3062 } 3799 }
3063 } 3800 }
3064 3801
@@ -3068,15 +3805,12 @@ namespace OpenSim.Region.Framework.Scenes
3068 /// <param name="rot"></param> 3805 /// <param name="rot"></param>
3069 public void UpdateRootRotation(Quaternion rot) 3806 public void UpdateRootRotation(Quaternion rot)
3070 { 3807 {
3071// m_log.DebugFormat( 3808 // needs to be called with phys building true
3072// "[SCENE OBJECT GROUP]: Updating root rotation of {0} {1} to {2}",
3073// Name, LocalId, rot);
3074
3075 Quaternion axRot = rot; 3809 Quaternion axRot = rot;
3076 Quaternion oldParentRot = m_rootPart.RotationOffset; 3810 Quaternion oldParentRot = m_rootPart.RotationOffset;
3077 3811
3078 m_rootPart.StoreUndoState(); 3812 //Don't use UpdateRotation because it schedules an update prematurely
3079 m_rootPart.UpdateRotation(rot); 3813 m_rootPart.RotationOffset = rot;
3080 3814
3081 PhysicsActor pa = m_rootPart.PhysActor; 3815 PhysicsActor pa = m_rootPart.PhysActor;
3082 3816
@@ -3092,35 +3826,145 @@ namespace OpenSim.Region.Framework.Scenes
3092 SceneObjectPart prim = parts[i]; 3826 SceneObjectPart prim = parts[i];
3093 if (prim.UUID != m_rootPart.UUID) 3827 if (prim.UUID != m_rootPart.UUID)
3094 { 3828 {
3095 prim.IgnoreUndoUpdate = true; 3829 Quaternion NewRot = oldParentRot * prim.RotationOffset;
3830 NewRot = Quaternion.Inverse(axRot) * NewRot;
3831 prim.RotationOffset = NewRot;
3832
3096 Vector3 axPos = prim.OffsetPosition; 3833 Vector3 axPos = prim.OffsetPosition;
3834
3097 axPos *= oldParentRot; 3835 axPos *= oldParentRot;
3098 axPos *= Quaternion.Inverse(axRot); 3836 axPos *= Quaternion.Inverse(axRot);
3099 prim.OffsetPosition = axPos; 3837 prim.OffsetPosition = axPos;
3100 Quaternion primsRot = prim.RotationOffset; 3838 }
3101 Quaternion newRot = oldParentRot * primsRot; 3839 }
3102 newRot = Quaternion.Inverse(axRot) * newRot;
3103 prim.RotationOffset = newRot;
3104 prim.ScheduleTerseUpdate();
3105 prim.IgnoreUndoUpdate = false;
3106 }
3107 }
3108
3109// for (int i = 0; i < parts.Length; i++)
3110// {
3111// SceneObjectPart childpart = parts[i];
3112// if (childpart != m_rootPart)
3113// {
3114//// childpart.IgnoreUndoUpdate = false;
3115//// childpart.StoreUndoState();
3116// }
3117// }
3118 3840
3119 m_rootPart.ScheduleTerseUpdate(); 3841 HasGroupChanged = true;
3842 ScheduleGroupForFullUpdate();
3843 }
3120 3844
3121// m_log.DebugFormat( 3845 private enum updatetype :int
3122// "[SCENE OBJECT GROUP]: Updated root rotation of {0} {1} to {2}", 3846 {
3123// Name, LocalId, rot); 3847 none = 0,
3848 partterse = 1,
3849 partfull = 2,
3850 groupterse = 3,
3851 groupfull = 4
3852 }
3853
3854 public void doChangeObject(SceneObjectPart part, ObjectChangeData data)
3855 {
3856 // TODO this still as excessive *.Schedule*Update()s
3857
3858 if (part != null && part.ParentGroup != null)
3859 {
3860 ObjectChangeType change = data.change;
3861 bool togroup = ((change & ObjectChangeType.Group) != 0);
3862 // bool uniform = ((what & ObjectChangeType.UniformScale) != 0); not in use
3863
3864 SceneObjectGroup group = part.ParentGroup;
3865 PhysicsActor pha = group.RootPart.PhysActor;
3866
3867 updatetype updateType = updatetype.none;
3868
3869 if (togroup)
3870 {
3871 // related to group
3872 if ((change & (ObjectChangeType.Rotation | ObjectChangeType.Position)) != 0)
3873 {
3874 if ((change & ObjectChangeType.Rotation) != 0)
3875 {
3876 group.RootPart.UpdateRotation(data.rotation);
3877 updateType = updatetype.none;
3878 }
3879 if ((change & ObjectChangeType.Position) != 0)
3880 {
3881 if (IsAttachment || m_scene.Permissions.CanObjectEntry(group.UUID, false, data.position))
3882 UpdateGroupPosition(data.position);
3883 updateType = updatetype.groupterse;
3884 }
3885 else
3886 // ugly rotation update of all parts
3887 {
3888 group.ResetChildPrimPhysicsPositions();
3889 }
3890
3891 }
3892 if ((change & ObjectChangeType.Scale) != 0)
3893 {
3894 if (pha != null)
3895 pha.Building = true;
3896
3897 group.GroupResize(data.scale);
3898 updateType = updatetype.none;
3899
3900 if (pha != null)
3901 pha.Building = false;
3902 }
3903 }
3904 else
3905 {
3906 // related to single prim in a link-set ( ie group)
3907 if (pha != null)
3908 pha.Building = true;
3909
3910 // root part is special
3911 // parts offset positions or rotations need to change also
3912
3913 if (part == group.RootPart)
3914 {
3915 if ((change & ObjectChangeType.Rotation) != 0)
3916 group.UpdateRootRotation(data.rotation);
3917 if ((change & ObjectChangeType.Position) != 0)
3918 group.UpdateRootPosition(data.position);
3919 if ((change & ObjectChangeType.Scale) != 0)
3920 part.Resize(data.scale);
3921 }
3922 else
3923 {
3924 if ((change & ObjectChangeType.Position) != 0)
3925 {
3926 part.OffsetPosition = data.position;
3927 updateType = updatetype.partterse;
3928 }
3929 if ((change & ObjectChangeType.Rotation) != 0)
3930 {
3931 part.UpdateRotation(data.rotation);
3932 updateType = updatetype.none;
3933 }
3934 if ((change & ObjectChangeType.Scale) != 0)
3935 {
3936 part.Resize(data.scale);
3937 updateType = updatetype.none;
3938 }
3939 }
3940
3941 if (pha != null)
3942 pha.Building = false;
3943 }
3944
3945 if (updateType != updatetype.none)
3946 {
3947 group.HasGroupChanged = true;
3948
3949 switch (updateType)
3950 {
3951 case updatetype.partterse:
3952 part.ScheduleTerseUpdate();
3953 break;
3954 case updatetype.partfull:
3955 part.ScheduleFullUpdate();
3956 break;
3957 case updatetype.groupterse:
3958 group.ScheduleGroupForTerseUpdate();
3959 break;
3960 case updatetype.groupfull:
3961 group.ScheduleGroupForFullUpdate();
3962 break;
3963 default:
3964 break;
3965 }
3966 }
3967 }
3124 } 3968 }
3125 3969
3126 #endregion 3970 #endregion
@@ -3219,10 +4063,11 @@ namespace OpenSim.Region.Framework.Scenes
3219 scriptPosTarget target = m_targets[idx]; 4063 scriptPosTarget target = m_targets[idx];
3220 if (Util.GetDistanceTo(target.targetPos, m_rootPart.GroupPosition) <= target.tolerance) 4064 if (Util.GetDistanceTo(target.targetPos, m_rootPart.GroupPosition) <= target.tolerance)
3221 { 4065 {
4066 at_target = true;
4067
3222 // trigger at_target 4068 // trigger at_target
3223 if (m_scriptListens_atTarget) 4069 if (m_scriptListens_atTarget)
3224 { 4070 {
3225 at_target = true;
3226 scriptPosTarget att = new scriptPosTarget(); 4071 scriptPosTarget att = new scriptPosTarget();
3227 att.targetPos = target.targetPos; 4072 att.targetPos = target.targetPos;
3228 att.tolerance = target.tolerance; 4073 att.tolerance = target.tolerance;
@@ -3340,11 +4185,50 @@ namespace OpenSim.Region.Framework.Scenes
3340 } 4185 }
3341 } 4186 }
3342 } 4187 }
3343 4188
4189 public Vector3 GetGeometricCenter()
4190 {
4191 // this is not real geometric center but a average of positions relative to root prim acording to
4192 // http://wiki.secondlife.com/wiki/llGetGeometricCenter
4193 // ignoring tortured prims details since sl also seems to ignore
4194 // so no real use in doing it on physics
4195
4196 Vector3 gc = Vector3.Zero;
4197
4198 int nparts = m_parts.Count;
4199 if (nparts <= 1)
4200 return gc;
4201
4202 SceneObjectPart[] parts = m_parts.GetArray();
4203 nparts = parts.Length; // just in case it changed
4204 if (nparts <= 1)
4205 return gc;
4206
4207 Quaternion parentRot = RootPart.RotationOffset;
4208 Vector3 pPos;
4209
4210 // average all parts positions
4211 for (int i = 0; i < nparts; i++)
4212 {
4213 // do it directly
4214 // gc += parts[i].GetWorldPosition();
4215 if (parts[i] != RootPart)
4216 {
4217 pPos = parts[i].OffsetPosition;
4218 gc += pPos;
4219 }
4220
4221 }
4222 gc /= nparts;
4223
4224 // relative to root:
4225// gc -= AbsolutePosition;
4226 return gc;
4227 }
4228
3344 public float GetMass() 4229 public float GetMass()
3345 { 4230 {
3346 float retmass = 0f; 4231 float retmass = 0f;
3347
3348 SceneObjectPart[] parts = m_parts.GetArray(); 4232 SceneObjectPart[] parts = m_parts.GetArray();
3349 for (int i = 0; i < parts.Length; i++) 4233 for (int i = 0; i < parts.Length; i++)
3350 retmass += parts[i].GetMass(); 4234 retmass += parts[i].GetMass();
@@ -3352,6 +4236,39 @@ namespace OpenSim.Region.Framework.Scenes
3352 return retmass; 4236 return retmass;
3353 } 4237 }
3354 4238
4239 // center of mass of full object
4240 public Vector3 GetCenterOfMass()
4241 {
4242 PhysicsActor pa = RootPart.PhysActor;
4243
4244 if(((RootPart.Flags & PrimFlags.Physics) !=0) && pa !=null)
4245 {
4246 // physics knows better about center of mass of physical prims
4247 Vector3 tmp = pa.CenterOfMass;
4248 return tmp;
4249 }
4250
4251 Vector3 Ptot = Vector3.Zero;
4252 float totmass = 0f;
4253 float m;
4254
4255 SceneObjectPart[] parts = m_parts.GetArray();
4256 for (int i = 0; i < parts.Length; i++)
4257 {
4258 m = parts[i].GetMass();
4259 Ptot += parts[i].GetPartCenterOfMass() * m;
4260 totmass += m;
4261 }
4262
4263 if (totmass == 0)
4264 totmass = 0;
4265 else
4266 totmass = 1 / totmass;
4267 Ptot *= totmass;
4268
4269 return Ptot;
4270 }
4271
3355 /// <summary> 4272 /// <summary>
3356 /// If the object is a sculpt/mesh, retrieve the mesh data for each part and reinsert it into each shape so that 4273 /// If the object is a sculpt/mesh, retrieve the mesh data for each part and reinsert it into each shape so that
3357 /// the physics engine can use it. 4274 /// the physics engine can use it.
@@ -3519,6 +4436,14 @@ namespace OpenSim.Region.Framework.Scenes
3519 FromItemID = uuid; 4436 FromItemID = uuid;
3520 } 4437 }
3521 4438
4439 public void ResetOwnerChangeFlag()
4440 {
4441 ForEachPart(delegate(SceneObjectPart part)
4442 {
4443 part.ResetOwnerChangeFlag();
4444 });
4445 }
4446
3522 #endregion 4447 #endregion
3523 } 4448 }
3524} 4449}
diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs b/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs
index 4c87639..ce652b4 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 Stack<UndoState> m_undo = new Stack<UndoState>(5); 294 private UndoRedoState m_UndoRedo = null;
270 private readonly Stack<UndoState> m_redo = new Stack<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,12 +760,14 @@ 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)
716 { 773 {
@@ -736,16 +793,6 @@ namespace OpenSim.Region.Framework.Scenes
736 m_log.Error("[SCENEOBJECTPART]: GROUP POSITION. " + e.Message); 793 m_log.Error("[SCENEOBJECTPART]: GROUP POSITION. " + e.Message);
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
@@ -1628,8 +2120,12 @@ namespace OpenSim.Region.Framework.Scenes
1628 2120
1629 bool UsePhysics = ((dupe.Flags & PrimFlags.Physics) != 0); 2121 bool UsePhysics = ((dupe.Flags & PrimFlags.Physics) != 0);
1630 dupe.DoPhysicsPropertyUpdate(UsePhysics, true); 2122 dupe.DoPhysicsPropertyUpdate(UsePhysics, true);
2123// dupe.UpdatePhysicsSubscribedEvents(); // not sure...
1631 } 2124 }
1632 2125
2126 if (dupe.PhysActor != null)
2127 dupe.PhysActor.LocalID = localID;
2128
1633 ParentGroup.Scene.EventManager.TriggerOnSceneObjectPartCopy(dupe, this, userExposed); 2129 ParentGroup.Scene.EventManager.TriggerOnSceneObjectPartCopy(dupe, this, userExposed);
1634 2130
1635// m_log.DebugFormat("[SCENE OBJECT PART]: Clone of {0} {1} finished", Name, UUID); 2131// m_log.DebugFormat("[SCENE OBJECT PART]: Clone of {0} {1} finished", Name, UUID);
@@ -1749,6 +2245,7 @@ namespace OpenSim.Region.Framework.Scenes
1749 2245
1750 /// <summary> 2246 /// <summary>
1751 /// Do a physics propery update for this part. 2247 /// Do a physics propery update for this part.
2248 /// now also updates phantom and volume detector
1752 /// </summary> 2249 /// </summary>
1753 /// <param name="UsePhysics"></param> 2250 /// <param name="UsePhysics"></param>
1754 /// <param name="isNew"></param> 2251 /// <param name="isNew"></param>
@@ -1774,61 +2271,69 @@ namespace OpenSim.Region.Framework.Scenes
1774 { 2271 {
1775 if (pa.IsPhysical) // implies UsePhysics==false for this block 2272 if (pa.IsPhysical) // implies UsePhysics==false for this block
1776 { 2273 {
1777 if (!isNew) 2274 if (!isNew) // implies UsePhysics==false for this block
2275 {
1778 ParentGroup.Scene.RemovePhysicalPrim(1); 2276 ParentGroup.Scene.RemovePhysicalPrim(1);
1779 2277
1780 pa.OnRequestTerseUpdate -= PhysicsRequestingTerseUpdate; 2278 Velocity = new Vector3(0, 0, 0);
1781 pa.OnOutOfBounds -= PhysicsOutOfBounds; 2279 Acceleration = new Vector3(0, 0, 0);
1782 pa.delink(); 2280 if (ParentGroup.RootPart == this)
2281 AngularVelocity = new Vector3(0, 0, 0);
1783 2282
1784 if (ParentGroup.Scene.PhysicsScene.SupportsNINJAJoints && (!isNew)) 2283 if (pa.Phantom && !VolumeDetectActive)
1785 { 2284 {
1786 // destroy all joints connected to this now deactivated body 2285 RemoveFromPhysics();
1787 ParentGroup.Scene.PhysicsScene.RemoveAllJointsConnectedToActorThreadLocked(pa); 2286 return;
1788 } 2287 }
1789 2288
1790 // stop client-side interpolation of all joint proxy objects that have just been deleted 2289 pa.IsPhysical = UsePhysics;
1791 // this is done because RemoveAllJointsConnectedToActor invokes the OnJointDeactivated callback, 2290 pa.OnRequestTerseUpdate -= PhysicsRequestingTerseUpdate;
1792 // which stops client-side interpolation of deactivated joint proxy objects. 2291 pa.OnOutOfBounds -= PhysicsOutOfBounds;
2292 pa.delink();
2293 if (ParentGroup.Scene.PhysicsScene.SupportsNINJAJoints)
2294 {
2295 // destroy all joints connected to this now deactivated body
2296 ParentGroup.Scene.PhysicsScene.RemoveAllJointsConnectedToActorThreadLocked(pa);
2297 }
2298 }
1793 } 2299 }
1794 2300
1795 if (!UsePhysics && !isNew) 2301 if (pa.IsPhysical != UsePhysics)
1796 { 2302 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 2303
1806 pa.IsPhysical = UsePhysics; 2304 if (UsePhysics)
2305 {
2306 if (ParentGroup.RootPart.KeyframeMotion != null)
2307 ParentGroup.RootPart.KeyframeMotion.Stop();
2308 ParentGroup.RootPart.KeyframeMotion = null;
2309 ParentGroup.Scene.AddPhysicalPrim(1);
1807 2310
1808 // If we're not what we're supposed to be in the physics scene, recreate ourselves. 2311 PhysActor.OnRequestTerseUpdate += PhysicsRequestingTerseUpdate;
1809 //m_parentGroup.Scene.PhysicsScene.RemovePrim(PhysActor); 2312 PhysActor.OnOutOfBounds += PhysicsOutOfBounds;
1810 /// that's not wholesome. Had to make Scene public
1811 //PhysActor = null;
1812 2313
1813 if ((Flags & PrimFlags.Phantom) == 0) 2314 if (ParentID != 0 && ParentID != LocalId)
1814 {
1815 if (UsePhysics)
1816 { 2315 {
1817 ParentGroup.Scene.AddPhysicalPrim(1); 2316 PhysicsActor parentPa = ParentGroup.RootPart.PhysActor;
1818 2317
1819 pa.OnRequestTerseUpdate += PhysicsRequestingTerseUpdate; 2318 if (parentPa != null)
1820 pa.OnOutOfBounds += PhysicsOutOfBounds;
1821 if (ParentID != 0 && ParentID != LocalId)
1822 { 2319 {
1823 PhysicsActor parentPa = ParentGroup.RootPart.PhysActor; 2320 pa.link(parentPa);
1824
1825 if (parentPa != null)
1826 {
1827 pa.link(parentPa);
1828 }
1829 } 2321 }
1830 } 2322 }
1831 } 2323 }
2324 }
2325
2326 bool phan = ((Flags & PrimFlags.Phantom) != 0);
2327 if (pa.Phantom != phan)
2328 pa.Phantom = phan;
2329
2330// some engines dont' have this check still
2331// if (VolumeDetectActive != pa.IsVolumeDtc)
2332 {
2333 if (VolumeDetectActive)
2334 pa.SetVolumeDetect(1);
2335 else
2336 pa.SetVolumeDetect(0);
1832 } 2337 }
1833 2338
1834 // If this part is a sculpt then delay the physics update until we've asynchronously loaded the 2339 // If this part is a sculpt then delay the physics update until we've asynchronously loaded the
@@ -1947,12 +2452,26 @@ namespace OpenSim.Region.Framework.Scenes
1947 2452
1948 public Vector3 GetGeometricCenter() 2453 public Vector3 GetGeometricCenter()
1949 { 2454 {
1950 PhysicsActor pa = PhysActor; 2455 // this is not real geometric center but a average of positions relative to root prim acording to
1951 2456 // http://wiki.secondlife.com/wiki/llGetGeometricCenter
1952 if (pa != null) 2457 // ignoring tortured prims details since sl also seems to ignore
1953 return new Vector3(pa.CenterOfMass.X, pa.CenterOfMass.Y, pa.CenterOfMass.Z); 2458 // so no real use in doing it on physics
1954 else 2459 if (ParentGroup.IsDeleted)
1955 return new Vector3(0, 0, 0); 2460 return new Vector3(0, 0, 0);
2461
2462 return ParentGroup.GetGeometricCenter();
2463
2464 /*
2465 PhysicsActor pa = PhysActor;
2466
2467 if (pa != null)
2468 {
2469 Vector3 vtmp = pa.CenterOfMass;
2470 return vtmp;
2471 }
2472 else
2473 return new Vector3(0, 0, 0);
2474 */
1956 } 2475 }
1957 2476
1958 public float GetMass() 2477 public float GetMass()
@@ -1965,14 +2484,43 @@ namespace OpenSim.Region.Framework.Scenes
1965 return 0; 2484 return 0;
1966 } 2485 }
1967 2486
1968 public Vector3 GetForce() 2487 public Vector3 GetCenterOfMass()
1969 { 2488 {
2489 if (ParentGroup.RootPart == this)
2490 {
2491 if (ParentGroup.IsDeleted)
2492 return AbsolutePosition;
2493 return ParentGroup.GetCenterOfMass();
2494 }
2495
1970 PhysicsActor pa = PhysActor; 2496 PhysicsActor pa = PhysActor;
1971 2497
1972 if (pa != null) 2498 if (pa != null)
1973 return pa.Force; 2499 {
2500 Vector3 tmp = pa.CenterOfMass;
2501 return tmp;
2502 }
2503 else
2504 return AbsolutePosition;
2505 }
2506
2507 public Vector3 GetPartCenterOfMass()
2508 {
2509 PhysicsActor pa = PhysActor;
2510
2511 if (pa != null)
2512 {
2513 Vector3 tmp = pa.CenterOfMass;
2514 return tmp;
2515 }
1974 else 2516 else
1975 return Vector3.Zero; 2517 return AbsolutePosition;
2518 }
2519
2520
2521 public Vector3 GetForce()
2522 {
2523 return Force;
1976 } 2524 }
1977 2525
1978 /// <summary> 2526 /// <summary>
@@ -2187,15 +2735,25 @@ namespace OpenSim.Region.Framework.Scenes
2187 2735
2188 private void SendLandCollisionEvent(scriptEvents ev, ScriptCollidingNotification notify) 2736 private void SendLandCollisionEvent(scriptEvents ev, ScriptCollidingNotification notify)
2189 { 2737 {
2190 if ((ParentGroup.RootPart.ScriptEvents & ev) != 0) 2738 bool sendToRoot = true;
2191 { 2739
2192 ColliderArgs LandCollidingMessage = new ColliderArgs(); 2740 ColliderArgs LandCollidingMessage = new ColliderArgs();
2193 List<DetectedObject> colliding = new List<DetectedObject>(); 2741 List<DetectedObject> colliding = new List<DetectedObject>();
2194 2742
2195 colliding.Add(CreateDetObjectForGround()); 2743 colliding.Add(CreateDetObjectForGround());
2196 LandCollidingMessage.Colliders = colliding; 2744 LandCollidingMessage.Colliders = colliding;
2197 2745
2746 if (Inventory.ContainsScripts())
2747 {
2748 if (!PassCollisions)
2749 sendToRoot = false;
2750 }
2751 if ((ScriptEvents & ev) != 0)
2198 notify(LocalId, LandCollidingMessage); 2752 notify(LocalId, LandCollidingMessage);
2753
2754 if ((ParentGroup.RootPart.ScriptEvents & ev) != 0 && sendToRoot)
2755 {
2756 notify(ParentGroup.RootPart.LocalId, LandCollidingMessage);
2199 } 2757 }
2200 } 2758 }
2201 2759
@@ -2211,45 +2769,87 @@ namespace OpenSim.Region.Framework.Scenes
2211 List<uint> endedColliders = new List<uint>(); 2769 List<uint> endedColliders = new List<uint>();
2212 List<uint> startedColliders = new List<uint>(); 2770 List<uint> startedColliders = new List<uint>();
2213 2771
2214 // calculate things that started colliding this time 2772 if (collissionswith.Count == 0)
2215 // and build up list of colliders this time
2216 foreach (uint localid in collissionswith.Keys)
2217 { 2773 {
2218 thisHitColliders.Add(localid); 2774 if (m_lastColliders.Count == 0)
2219 if (!m_lastColliders.Contains(localid)) 2775 return; // nothing to do
2220 startedColliders.Add(localid);
2221 }
2222 2776
2223 // calculate things that ended colliding 2777 foreach (uint localID in m_lastColliders)
2224 foreach (uint localID in m_lastColliders) 2778 {
2225 {
2226 if (!thisHitColliders.Contains(localID))
2227 endedColliders.Add(localID); 2779 endedColliders.Add(localID);
2780 }
2781 m_lastColliders.Clear();
2228 } 2782 }
2229 2783
2230 //add the items that started colliding this time to the last colliders list. 2784 else
2231 foreach (uint localID in startedColliders) 2785 {
2232 m_lastColliders.Add(localID); 2786 List<CollisionForSoundInfo> soundinfolist = new List<CollisionForSoundInfo>();
2787
2788 // calculate things that started colliding this time
2789 // and build up list of colliders this time
2790 if (!VolumeDetectActive && CollisionSoundType >= 0)
2791 {
2792 CollisionForSoundInfo soundinfo;
2793 ContactPoint curcontact;
2794
2795 foreach (uint id in collissionswith.Keys)
2796 {
2797 thisHitColliders.Add(id);
2798 if (!m_lastColliders.Contains(id))
2799 {
2800 startedColliders.Add(id);
2801
2802 curcontact = collissionswith[id];
2803 if (Math.Abs(curcontact.RelativeSpeed) > 0.2)
2804 {
2805 soundinfo = new CollisionForSoundInfo();
2806 soundinfo.colliderID = id;
2807 soundinfo.position = curcontact.Position;
2808 soundinfo.relativeVel = curcontact.RelativeSpeed;
2809 soundinfolist.Add(soundinfo);
2810 }
2811 }
2812 }
2813 }
2814 else
2815 {
2816 foreach (uint id in collissionswith.Keys)
2817 {
2818 thisHitColliders.Add(id);
2819 if (!m_lastColliders.Contains(id))
2820 startedColliders.Add(id);
2821 }
2822 }
2823
2824 // calculate things that ended colliding
2825 foreach (uint localID in m_lastColliders)
2826 {
2827 if (!thisHitColliders.Contains(localID))
2828 endedColliders.Add(localID);
2829 }
2830
2831 //add the items that started colliding this time to the last colliders list.
2832 foreach (uint localID in startedColliders)
2833 m_lastColliders.Add(localID);
2233 2834
2234 // remove things that ended colliding from the last colliders list 2835 // remove things that ended colliding from the last colliders list
2235 foreach (uint localID in endedColliders) 2836 foreach (uint localID in endedColliders)
2236 m_lastColliders.Remove(localID); 2837 m_lastColliders.Remove(localID);
2237 2838
2238 // play the sound. 2839 // play sounds.
2239 if (startedColliders.Count > 0 && CollisionSound != UUID.Zero && CollisionSoundVolume > 0.0f) 2840 if (soundinfolist.Count > 0)
2240 SendSound(CollisionSound.ToString(), CollisionSoundVolume, true, (byte)0, 0, false, false); 2841 CollisionSounds.PartCollisionSound(this, soundinfolist);
2842 }
2241 2843
2242 SendCollisionEvent(scriptEvents.collision_start, startedColliders, ParentGroup.Scene.EventManager.TriggerScriptCollidingStart); 2844 SendCollisionEvent(scriptEvents.collision_start, startedColliders, ParentGroup.Scene.EventManager.TriggerScriptCollidingStart);
2243 SendCollisionEvent(scriptEvents.collision , m_lastColliders , ParentGroup.Scene.EventManager.TriggerScriptColliding); 2845 if (!VolumeDetectActive)
2846 SendCollisionEvent(scriptEvents.collision , m_lastColliders , ParentGroup.Scene.EventManager.TriggerScriptColliding);
2244 SendCollisionEvent(scriptEvents.collision_end , endedColliders , ParentGroup.Scene.EventManager.TriggerScriptCollidingEnd); 2847 SendCollisionEvent(scriptEvents.collision_end , endedColliders , ParentGroup.Scene.EventManager.TriggerScriptCollidingEnd);
2245 2848
2246 if (startedColliders.Contains(0)) 2849 if (startedColliders.Contains(0))
2247 { 2850 SendLandCollisionEvent(scriptEvents.land_collision_start, ParentGroup.Scene.EventManager.TriggerScriptLandCollidingStart);
2248 if (m_lastColliders.Contains(0)) 2851 if (m_lastColliders.Contains(0))
2249 SendLandCollisionEvent(scriptEvents.land_collision, ParentGroup.Scene.EventManager.TriggerScriptLandColliding); 2852 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)) 2853 if (endedColliders.Contains(0))
2254 SendLandCollisionEvent(scriptEvents.land_collision_end, ParentGroup.Scene.EventManager.TriggerScriptLandCollidingEnd); 2854 SendLandCollisionEvent(scriptEvents.land_collision_end, ParentGroup.Scene.EventManager.TriggerScriptLandCollidingEnd);
2255 } 2855 }
@@ -2272,9 +2872,9 @@ namespace OpenSim.Region.Framework.Scenes
2272 Vector3 newpos = new Vector3(pa.Position.GetBytes(), 0); 2872 Vector3 newpos = new Vector3(pa.Position.GetBytes(), 0);
2273 2873
2274 if (ParentGroup.Scene.TestBorderCross(newpos, Cardinals.N) 2874 if (ParentGroup.Scene.TestBorderCross(newpos, Cardinals.N)
2275 | ParentGroup.Scene.TestBorderCross(newpos, Cardinals.S) 2875 || ParentGroup.Scene.TestBorderCross(newpos, Cardinals.S)
2276 | ParentGroup.Scene.TestBorderCross(newpos, Cardinals.E) 2876 || ParentGroup.Scene.TestBorderCross(newpos, Cardinals.E)
2277 | ParentGroup.Scene.TestBorderCross(newpos, Cardinals.W)) 2877 || ParentGroup.Scene.TestBorderCross(newpos, Cardinals.W))
2278 { 2878 {
2279 ParentGroup.AbsolutePosition = newpos; 2879 ParentGroup.AbsolutePosition = newpos;
2280 return; 2880 return;
@@ -2296,17 +2896,18 @@ namespace OpenSim.Region.Framework.Scenes
2296 //Trys to fetch sound id from prim's inventory. 2896 //Trys to fetch sound id from prim's inventory.
2297 //Prim's inventory doesn't support non script items yet 2897 //Prim's inventory doesn't support non script items yet
2298 2898
2299 lock (TaskInventory) 2899 TaskInventory.LockItemsForRead(true);
2900
2901 foreach (KeyValuePair<UUID, TaskInventoryItem> item in TaskInventory)
2300 { 2902 {
2301 foreach (KeyValuePair<UUID, TaskInventoryItem> item in TaskInventory) 2903 if (item.Value.Name == sound)
2302 { 2904 {
2303 if (item.Value.Name == sound) 2905 soundID = item.Value.ItemID;
2304 { 2906 break;
2305 soundID = item.Value.ItemID;
2306 break;
2307 }
2308 } 2907 }
2309 } 2908 }
2909
2910 TaskInventory.LockItemsForRead(false);
2310 } 2911 }
2311 2912
2312 ParentGroup.Scene.ForEachRootScenePresence(delegate(ScenePresence sp) 2913 ParentGroup.Scene.ForEachRootScenePresence(delegate(ScenePresence sp)
@@ -2429,6 +3030,19 @@ namespace OpenSim.Region.Framework.Scenes
2429 APIDTarget = Quaternion.Identity; 3030 APIDTarget = Quaternion.Identity;
2430 } 3031 }
2431 3032
3033
3034
3035 public void ScheduleFullUpdateIfNone()
3036 {
3037 if (ParentGroup == null)
3038 return;
3039
3040// ??? ParentGroup.HasGroupChanged = true;
3041
3042 if (UpdateFlag != UpdateRequired.FULL)
3043 ScheduleFullUpdate();
3044 }
3045
2432 /// <summary> 3046 /// <summary>
2433 /// Schedules this prim for a full update 3047 /// Schedules this prim for a full update
2434 /// </summary> 3048 /// </summary>
@@ -2631,8 +3245,8 @@ namespace OpenSim.Region.Framework.Scenes
2631 { 3245 {
2632 const float ROTATION_TOLERANCE = 0.01f; 3246 const float ROTATION_TOLERANCE = 0.01f;
2633 const float VELOCITY_TOLERANCE = 0.001f; 3247 const float VELOCITY_TOLERANCE = 0.001f;
2634 const float POSITION_TOLERANCE = 0.05f; 3248 const float POSITION_TOLERANCE = 0.05f; // I don't like this, but I suppose it's necessary
2635 const int TIME_MS_TOLERANCE = 3000; 3249 const int TIME_MS_TOLERANCE = 200; //llSetPos has a 200ms delay. This should NOT be 3 seconds.
2636 3250
2637 switch (UpdateFlag) 3251 switch (UpdateFlag)
2638 { 3252 {
@@ -2694,17 +3308,16 @@ namespace OpenSim.Region.Framework.Scenes
2694 if (!UUID.TryParse(sound, out soundID)) 3308 if (!UUID.TryParse(sound, out soundID))
2695 { 3309 {
2696 // search sound file from inventory 3310 // search sound file from inventory
2697 lock (TaskInventory) 3311 TaskInventory.LockItemsForRead(true);
3312 foreach (KeyValuePair<UUID, TaskInventoryItem> item in TaskInventory)
2698 { 3313 {
2699 foreach (KeyValuePair<UUID, TaskInventoryItem> item in TaskInventory) 3314 if (item.Value.Name == sound && item.Value.Type == (int)AssetType.Sound)
2700 { 3315 {
2701 if (item.Value.Name == sound && item.Value.Type == (int)AssetType.Sound) 3316 soundID = item.Value.ItemID;
2702 { 3317 break;
2703 soundID = item.Value.ItemID;
2704 break;
2705 }
2706 } 3318 }
2707 } 3319 }
3320 TaskInventory.LockItemsForRead(false);
2708 } 3321 }
2709 3322
2710 if (soundID == UUID.Zero) 3323 if (soundID == UUID.Zero)
@@ -2761,6 +3374,35 @@ namespace OpenSim.Region.Framework.Scenes
2761 } 3374 }
2762 } 3375 }
2763 3376
3377 public void SendCollisionSound(UUID soundID, double volume, Vector3 position)
3378 {
3379 if (soundID == UUID.Zero)
3380 return;
3381
3382 ISoundModule soundModule = ParentGroup.Scene.RequestModuleInterface<ISoundModule>();
3383 if (soundModule == null)
3384 return;
3385
3386 if (volume > 1)
3387 volume = 1;
3388 if (volume < 0)
3389 volume = 0;
3390
3391 int now = Util.EnvironmentTickCount();
3392 if(Util.EnvironmentTickCountSubtract(now,LastColSoundSentTime) <200)
3393 return;
3394
3395 LastColSoundSentTime = now;
3396
3397 UUID ownerID = OwnerID;
3398 UUID objectID = ParentGroup.RootPart.UUID;
3399 UUID parentID = ParentGroup.UUID;
3400 ulong regionHandle = ParentGroup.Scene.RegionInfo.RegionHandle;
3401
3402 soundModule.TriggerSound(soundID, ownerID, objectID, parentID, volume, position, regionHandle, 0 );
3403 }
3404
3405
2764 /// <summary> 3406 /// <summary>
2765 /// Send a terse update to all clients 3407 /// Send a terse update to all clients
2766 /// </summary> 3408 /// </summary>
@@ -2789,10 +3431,13 @@ namespace OpenSim.Region.Framework.Scenes
2789 3431
2790 public void SetBuoyancy(float fvalue) 3432 public void SetBuoyancy(float fvalue)
2791 { 3433 {
2792 PhysicsActor pa = PhysActor; 3434 Buoyancy = fvalue;
2793 3435/*
2794 if (pa != null) 3436 if (PhysActor != null)
2795 pa.Buoyancy = fvalue; 3437 {
3438 PhysActor.Buoyancy = fvalue;
3439 }
3440 */
2796 } 3441 }
2797 3442
2798 public void SetDieAtEdge(bool p) 3443 public void SetDieAtEdge(bool p)
@@ -2808,47 +3453,111 @@ namespace OpenSim.Region.Framework.Scenes
2808 PhysicsActor pa = PhysActor; 3453 PhysicsActor pa = PhysActor;
2809 3454
2810 if (pa != null) 3455 if (pa != null)
2811 pa.FloatOnWater = floatYN == 1; 3456 pa.FloatOnWater = (floatYN == 1);
2812 } 3457 }
2813 3458
2814 public void SetForce(Vector3 force) 3459 public void SetForce(Vector3 force)
2815 { 3460 {
2816 PhysicsActor pa = PhysActor; 3461 Force = force;
3462 }
2817 3463
2818 if (pa != null) 3464 public SOPVehicle VehicleParams
2819 pa.Force = force; 3465 {
3466 get
3467 {
3468 return m_vehicleParams;
3469 }
3470 set
3471 {
3472 m_vehicleParams = value;
3473 }
3474 }
3475
3476
3477 public int VehicleType
3478 {
3479 get
3480 {
3481 if (m_vehicleParams == null)
3482 return (int)Vehicle.TYPE_NONE;
3483 else
3484 return (int)m_vehicleParams.Type;
3485 }
3486 set
3487 {
3488 SetVehicleType(value);
3489 }
2820 } 3490 }
2821 3491
2822 public void SetVehicleType(int type) 3492 public void SetVehicleType(int type)
2823 { 3493 {
2824 PhysicsActor pa = PhysActor; 3494 m_vehicleParams = null;
3495
3496 if (type == (int)Vehicle.TYPE_NONE)
3497 {
3498 if (_parentID ==0 && PhysActor != null)
3499 PhysActor.VehicleType = (int)Vehicle.TYPE_NONE;
3500 return;
3501 }
3502 m_vehicleParams = new SOPVehicle();
3503 m_vehicleParams.ProcessTypeChange((Vehicle)type);
3504 {
3505 if (_parentID ==0 && PhysActor != null)
3506 PhysActor.VehicleType = type;
3507 return;
3508 }
3509 }
2825 3510
2826 if (pa != null) 3511 public void SetVehicleFlags(int param, bool remove)
2827 pa.VehicleType = type; 3512 {
3513 if (m_vehicleParams == null)
3514 return;
3515
3516 m_vehicleParams.ProcessVehicleFlags(param, remove);
3517
3518 if (_parentID ==0 && PhysActor != null)
3519 {
3520 PhysActor.VehicleFlags(param, remove);
3521 }
2828 } 3522 }
2829 3523
2830 public void SetVehicleFloatParam(int param, float value) 3524 public void SetVehicleFloatParam(int param, float value)
2831 { 3525 {
2832 PhysicsActor pa = PhysActor; 3526 if (m_vehicleParams == null)
3527 return;
2833 3528
2834 if (pa != null) 3529 m_vehicleParams.ProcessFloatVehicleParam((Vehicle)param, value);
2835 pa.VehicleFloatParam(param, value); 3530
3531 if (_parentID == 0 && PhysActor != null)
3532 {
3533 PhysActor.VehicleFloatParam(param, value);
3534 }
2836 } 3535 }
2837 3536
2838 public void SetVehicleVectorParam(int param, Vector3 value) 3537 public void SetVehicleVectorParam(int param, Vector3 value)
2839 { 3538 {
2840 PhysicsActor pa = PhysActor; 3539 if (m_vehicleParams == null)
3540 return;
2841 3541
2842 if (pa != null) 3542 m_vehicleParams.ProcessVectorVehicleParam((Vehicle)param, value);
2843 pa.VehicleVectorParam(param, value); 3543
3544 if (_parentID == 0 && PhysActor != null)
3545 {
3546 PhysActor.VehicleVectorParam(param, value);
3547 }
2844 } 3548 }
2845 3549
2846 public void SetVehicleRotationParam(int param, Quaternion rotation) 3550 public void SetVehicleRotationParam(int param, Quaternion rotation)
2847 { 3551 {
2848 PhysicsActor pa = PhysActor; 3552 if (m_vehicleParams == null)
3553 return;
2849 3554
2850 if (pa != null) 3555 m_vehicleParams.ProcessRotationVehicleParam((Vehicle)param, rotation);
2851 pa.VehicleRotationParam(param, rotation); 3556
3557 if (_parentID == 0 && PhysActor != null)
3558 {
3559 PhysActor.VehicleRotationParam(param, rotation);
3560 }
2852 } 3561 }
2853 3562
2854 /// <summary> 3563 /// <summary>
@@ -3032,14 +3741,6 @@ namespace OpenSim.Region.Framework.Scenes
3032 hasProfileCut = hasDimple; // is it the same thing? 3741 hasProfileCut = hasDimple; // is it the same thing?
3033 } 3742 }
3034 3743
3035 public void SetVehicleFlags(int param, bool remove)
3036 {
3037 PhysicsActor pa = PhysActor;
3038
3039 if (pa != null)
3040 pa.VehicleFlags(param, remove);
3041 }
3042
3043 public void SetGroup(UUID groupID, IClientAPI client) 3744 public void SetGroup(UUID groupID, IClientAPI client)
3044 { 3745 {
3045 // Scene.AddNewPrims() calls with client == null so can't use this. 3746 // Scene.AddNewPrims() calls with client == null so can't use this.
@@ -3143,68 +3844,18 @@ namespace OpenSim.Region.Framework.Scenes
3143 //ParentGroup.ScheduleGroupForFullUpdate(); 3844 //ParentGroup.ScheduleGroupForFullUpdate();
3144 } 3845 }
3145 3846
3146 public void StoreUndoState() 3847 public void StoreUndoState(ObjectChangeType change)
3147 { 3848 {
3148 StoreUndoState(false); 3849 if (m_UndoRedo == null)
3149 } 3850 m_UndoRedo = new UndoRedoState(5);
3150 3851
3151 public void StoreUndoState(bool forGroup) 3852 lock (m_UndoRedo)
3152 {
3153 if (!Undoing)
3154 { 3853 {
3155 if (!IgnoreUndoUpdate) 3854 if (!Undoing && !IgnoreUndoUpdate && ParentGroup != null) // just to read better - undo is in progress, or suspended
3156 { 3855 {
3157 if (ParentGroup != null) 3856 m_UndoRedo.StoreUndo(this, change);
3158 {
3159 lock (m_undo)
3160 {
3161 if (m_undo.Count > 0)
3162 {
3163 UndoState last = m_undo.Peek();
3164 if (last != null)
3165 {
3166 // TODO: May need to fix for group comparison
3167 if (last.Compare(this))
3168 {
3169 // m_log.DebugFormat(
3170 // "[SCENE OBJECT PART]: Not storing undo for {0} {1} since current state is same as last undo state, initial stack size {2}",
3171 // Name, LocalId, m_undo.Count);
3172
3173 return;
3174 }
3175 }
3176 }
3177
3178 // m_log.DebugFormat(
3179 // "[SCENE OBJECT PART]: Storing undo state for {0} {1}, forGroup {2}, initial stack size {3}",
3180 // Name, LocalId, forGroup, m_undo.Count);
3181
3182 if (ParentGroup.GetSceneMaxUndo() > 0)
3183 {
3184 UndoState nUndo = new UndoState(this, forGroup);
3185
3186 m_undo.Push(nUndo);
3187
3188 if (m_redo.Count > 0)
3189 m_redo.Clear();
3190
3191 // m_log.DebugFormat(
3192 // "[SCENE OBJECT PART]: Stored undo state for {0} {1}, forGroup {2}, stack size now {3}",
3193 // Name, LocalId, forGroup, m_undo.Count);
3194 }
3195 }
3196 }
3197 } 3857 }
3198// else
3199// {
3200// m_log.DebugFormat("[SCENE OBJECT PART]: Ignoring undo store for {0} {1}", Name, LocalId);
3201// }
3202 } 3858 }
3203// else
3204// {
3205// m_log.DebugFormat(
3206// "[SCENE OBJECT PART]: Ignoring undo store for {0} {1} since already undoing", Name, LocalId);
3207// }
3208 } 3859 }
3209 3860
3210 /// <summary> 3861 /// <summary>
@@ -3214,84 +3865,46 @@ namespace OpenSim.Region.Framework.Scenes
3214 { 3865 {
3215 get 3866 get
3216 { 3867 {
3217 lock (m_undo) 3868 if (m_UndoRedo == null)
3218 return m_undo.Count; 3869 return 0;
3870 return m_UndoRedo.Count;
3219 } 3871 }
3220 } 3872 }
3221 3873
3222 public void Undo() 3874 public void Undo()
3223 { 3875 {
3224 lock (m_undo) 3876 if (m_UndoRedo == null || Undoing || ParentGroup == null)
3225 { 3877 return;
3226// m_log.DebugFormat(
3227// "[SCENE OBJECT PART]: Handling undo request for {0} {1}, stack size {2}",
3228// Name, LocalId, m_undo.Count);
3229
3230 if (m_undo.Count > 0)
3231 {
3232 UndoState goback = m_undo.Pop();
3233
3234 if (goback != null)
3235 {
3236 UndoState nUndo = null;
3237
3238 if (ParentGroup.GetSceneMaxUndo() > 0)
3239 {
3240 nUndo = new UndoState(this, goback.ForGroup);
3241 }
3242
3243 goback.PlaybackState(this);
3244
3245 if (nUndo != null)
3246 m_redo.Push(nUndo);
3247 }
3248 }
3249 3878
3250// m_log.DebugFormat( 3879 lock (m_UndoRedo)
3251// "[SCENE OBJECT PART]: Handled undo request for {0} {1}, stack size now {2}", 3880 {
3252// Name, LocalId, m_undo.Count); 3881 Undoing = true;
3882 m_UndoRedo.Undo(this);
3883 Undoing = false;
3253 } 3884 }
3254 } 3885 }
3255 3886
3256 public void Redo() 3887 public void Redo()
3257 { 3888 {
3258 lock (m_undo) 3889 if (m_UndoRedo == null || Undoing || ParentGroup == null)
3259 { 3890 return;
3260// m_log.DebugFormat(
3261// "[SCENE OBJECT PART]: Handling redo request for {0} {1}, stack size {2}",
3262// Name, LocalId, m_redo.Count);
3263
3264 if (m_redo.Count > 0)
3265 {
3266 UndoState gofwd = m_redo.Pop();
3267
3268 if (gofwd != null)
3269 {
3270 if (ParentGroup.GetSceneMaxUndo() > 0)
3271 {
3272 UndoState nUndo = new UndoState(this, gofwd.ForGroup);
3273
3274 m_undo.Push(nUndo);
3275 }
3276
3277 gofwd.PlayfwdState(this);
3278 }
3279 3891
3280// m_log.DebugFormat( 3892 lock (m_UndoRedo)
3281// "[SCENE OBJECT PART]: Handled redo request for {0} {1}, stack size now {2}", 3893 {
3282// Name, LocalId, m_redo.Count); 3894 Undoing = true;
3283 } 3895 m_UndoRedo.Redo(this);
3896 Undoing = false;
3284 } 3897 }
3285 } 3898 }
3286 3899
3287 public void ClearUndoState() 3900 public void ClearUndoState()
3288 { 3901 {
3289// m_log.DebugFormat("[SCENE OBJECT PART]: Clearing undo and redo stacks in {0} {1}", Name, LocalId); 3902 if (m_UndoRedo == null || Undoing)
3903 return;
3290 3904
3291 lock (m_undo) 3905 lock (m_UndoRedo)
3292 { 3906 {
3293 m_undo.Clear(); 3907 m_UndoRedo.Clear();
3294 m_redo.Clear();
3295 } 3908 }
3296 } 3909 }
3297 3910
@@ -3921,6 +4534,27 @@ namespace OpenSim.Region.Framework.Scenes
3921 } 4534 }
3922 } 4535 }
3923 4536
4537
4538 public void UpdateExtraPhysics(ExtraPhysicsData physdata)
4539 {
4540 if (physdata.PhysShapeType == PhysShapeType.invalid || ParentGroup == null)
4541 return;
4542
4543 if (PhysicsShapeType != (byte)physdata.PhysShapeType)
4544 {
4545 PhysicsShapeType = (byte)physdata.PhysShapeType;
4546
4547 }
4548
4549 if(Density != physdata.Density)
4550 Density = physdata.Density;
4551 if(GravityModifier != physdata.GravitationModifier)
4552 GravityModifier = physdata.GravitationModifier;
4553 if(Friction != physdata.Friction)
4554 Friction = physdata.Friction;
4555 if(Bounciness != physdata.Bounce)
4556 Bounciness = physdata.Bounce;
4557 }
3924 /// <summary> 4558 /// <summary>
3925 /// Update the flags on this prim. This covers properties such as phantom, physics and temporary. 4559 /// Update the flags on this prim. This covers properties such as phantom, physics and temporary.
3926 /// </summary> 4560 /// </summary>
@@ -3928,7 +4562,7 @@ namespace OpenSim.Region.Framework.Scenes
3928 /// <param name="SetTemporary"></param> 4562 /// <param name="SetTemporary"></param>
3929 /// <param name="SetPhantom"></param> 4563 /// <param name="SetPhantom"></param>
3930 /// <param name="SetVD"></param> 4564 /// <param name="SetVD"></param>
3931 public void UpdatePrimFlags(bool UsePhysics, bool SetTemporary, bool SetPhantom, bool SetVD) 4565 public void UpdatePrimFlags(bool UsePhysics, bool SetTemporary, bool SetPhantom, bool SetVD, bool building)
3932 { 4566 {
3933 bool wasUsingPhysics = ((Flags & PrimFlags.Physics) != 0); 4567 bool wasUsingPhysics = ((Flags & PrimFlags.Physics) != 0);
3934 bool wasTemporary = ((Flags & PrimFlags.TemporaryOnRez) != 0); 4568 bool wasTemporary = ((Flags & PrimFlags.TemporaryOnRez) != 0);
@@ -3938,237 +4572,230 @@ namespace OpenSim.Region.Framework.Scenes
3938 if ((UsePhysics == wasUsingPhysics) && (wasTemporary == SetTemporary) && (wasPhantom == SetPhantom) && (SetVD == wasVD)) 4572 if ((UsePhysics == wasUsingPhysics) && (wasTemporary == SetTemporary) && (wasPhantom == SetPhantom) && (SetVD == wasVD))
3939 return; 4573 return;
3940 4574
3941 PhysicsActor pa = PhysActor; 4575 VolumeDetectActive = SetVD;
3942
3943 // Special cases for VD. VD can only be called from a script
3944 // and can't be combined with changes to other states. So we can rely
3945 // that...
3946 // ... if VD is changed, all others are not.
3947 // ... if one of the others is changed, VD is not.
3948 if (SetVD) // VD is active, special logic applies
3949 {
3950 // State machine logic for VolumeDetect
3951 // More logic below
3952 bool phanReset = (SetPhantom != wasPhantom) && !SetPhantom;
3953
3954 if (phanReset) // Phantom changes from on to off switch VD off too
3955 {
3956 SetVD = false; // Switch it of for the course of this routine
3957 VolumeDetectActive = false; // and also permanently
3958
3959 if (pa != null)
3960 pa.SetVolumeDetect(0); // Let physics know about it too
3961 }
3962 else
3963 {
3964 // If volumedetect is active we don't want phantom to be applied.
3965 // If this is a new call to VD out of the state "phantom"
3966 // this will also cause the prim to be visible to physics
3967 SetPhantom = false;
3968 }
3969 }
3970 4576
3971 if (UsePhysics && IsJoint()) 4577 // volume detector implies phantom
3972 { 4578 if (VolumeDetectActive)
3973 SetPhantom = true; 4579 SetPhantom = true;
3974 }
3975 4580
3976 if (UsePhysics) 4581 if (UsePhysics)
3977 {
3978 AddFlag(PrimFlags.Physics); 4582 AddFlag(PrimFlags.Physics);
3979 if (!wasUsingPhysics)
3980 {
3981 DoPhysicsPropertyUpdate(UsePhysics, false);
3982
3983 if (!ParentGroup.IsDeleted)
3984 {
3985 if (LocalId == ParentGroup.RootPart.LocalId)
3986 {
3987 ParentGroup.CheckSculptAndLoad();
3988 }
3989 }
3990 }
3991 }
3992 else 4583 else
3993 {
3994 RemFlag(PrimFlags.Physics); 4584 RemFlag(PrimFlags.Physics);
3995 if (wasUsingPhysics)
3996 {
3997 DoPhysicsPropertyUpdate(UsePhysics, false);
3998 }
3999 }
4000 4585
4001 if (SetPhantom 4586 if (SetPhantom)
4002 || ParentGroup.IsAttachment
4003 || (Shape.PathCurve == (byte)Extrusion.Flexible)) // note: this may have been changed above in the case of joints
4004 {
4005 AddFlag(PrimFlags.Phantom); 4587 AddFlag(PrimFlags.Phantom);
4588 else
4589 RemFlag(PrimFlags.Phantom);
4006 4590
4007 if (PhysActor != null) 4591 if (SetTemporary)
4592 AddFlag(PrimFlags.TemporaryOnRez);
4593 else
4594 RemFlag(PrimFlags.TemporaryOnRez);
4595
4596
4597 if (ParentGroup.Scene == null)
4598 return;
4599
4600 PhysicsActor pa = PhysActor;
4601
4602 if (pa != null && building && pa.Building != building)
4603 pa.Building = building;
4604
4605 if ((SetPhantom && !UsePhysics && !SetVD) || ParentGroup.IsAttachment || PhysicsShapeType == (byte)PhysShapeType.none
4606 || (Shape.PathCurve == (byte)Extrusion.Flexible))
4607 {
4608 if (pa != null)
4008 { 4609 {
4610 if(wasUsingPhysics)
4611 ParentGroup.Scene.RemovePhysicalPrim(1);
4009 RemoveFromPhysics(); 4612 RemoveFromPhysics();
4010 pa = null;
4011 } 4613 }
4614
4615 Velocity = new Vector3(0, 0, 0);
4616 Acceleration = new Vector3(0, 0, 0);
4617 if (ParentGroup.RootPart == this)
4618 AngularVelocity = new Vector3(0, 0, 0);
4012 } 4619 }
4013 else // Not phantom 4620 else
4014 { 4621 {
4015 RemFlag(PrimFlags.Phantom); 4622 if (ParentGroup.Scene.CollidablePrims)
4016
4017 if (ParentGroup.Scene == null)
4018 return;
4019
4020 if (ParentGroup.Scene.CollidablePrims && pa == null)
4021 { 4623 {
4022 pa = AddToPhysics(UsePhysics); 4624 if (pa == null)
4023
4024 if (pa != null)
4025 { 4625 {
4026 pa.SetMaterial(Material); 4626 AddToPhysics(UsePhysics, SetPhantom, building, false);
4027 DoPhysicsPropertyUpdate(UsePhysics, true); 4627 pa = PhysActor;
4028 4628/*
4029 if (!ParentGroup.IsDeleted) 4629 if (pa != null)
4030 { 4630 {
4031 if (LocalId == ParentGroup.RootPart.LocalId) 4631 if (
4632// ((AggregateScriptEvents & scriptEvents.collision) != 0) ||
4633// ((AggregateScriptEvents & scriptEvents.collision_end) != 0) ||
4634// ((AggregateScriptEvents & scriptEvents.collision_start) != 0) ||
4635// ((AggregateScriptEvents & scriptEvents.land_collision_start) != 0) ||
4636// ((AggregateScriptEvents & scriptEvents.land_collision) != 0) ||
4637// ((AggregateScriptEvents & scriptEvents.land_collision_end) != 0) ||
4638 ((AggregateScriptEvents & PhysicsNeededSubsEvents) != 0) ||
4639 ((ParentGroup.RootPart.AggregateScriptEvents & PhysicsNeededSubsEvents) != 0) ||
4640 (CollisionSound != UUID.Zero)
4641 )
4032 { 4642 {
4033 ParentGroup.CheckSculptAndLoad(); 4643 pa.OnCollisionUpdate += PhysicsCollision;
4644 pa.SubscribeEvents(1000);
4034 } 4645 }
4035 } 4646 }
4036 4647*/
4037 if (
4038 ((AggregateScriptEvents & scriptEvents.collision) != 0) ||
4039 ((AggregateScriptEvents & scriptEvents.collision_end) != 0) ||
4040 ((AggregateScriptEvents & scriptEvents.collision_start) != 0) ||
4041 ((AggregateScriptEvents & scriptEvents.land_collision_start) != 0) ||
4042 ((AggregateScriptEvents & scriptEvents.land_collision) != 0) ||
4043 ((AggregateScriptEvents & scriptEvents.land_collision_end) != 0) ||
4044 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.collision) != 0) ||
4045 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.collision_end) != 0) ||
4046 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.collision_start) != 0) ||
4047 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.land_collision_start) != 0) ||
4048 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.land_collision) != 0) ||
4049 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.land_collision_end) != 0) ||
4050 (CollisionSound != UUID.Zero)
4051 )
4052 {
4053 pa.OnCollisionUpdate += PhysicsCollision;
4054 pa.SubscribeEvents(1000);
4055 }
4056 } 4648 }
4057 } 4649 else // it already has a physical representation
4058 else // it already has a physical representation
4059 {
4060 DoPhysicsPropertyUpdate(UsePhysics, false); // Update physical status. If it's phantom this will remove the prim
4061
4062 if (!ParentGroup.IsDeleted)
4063 { 4650 {
4064 if (LocalId == ParentGroup.RootPart.LocalId) 4651 DoPhysicsPropertyUpdate(UsePhysics, false); // Update physical status.
4065 { 4652/* moved into DoPhysicsPropertyUpdate
4066 ParentGroup.CheckSculptAndLoad(); 4653 if(VolumeDetectActive)
4067 } 4654 pa.SetVolumeDetect(1);
4655 else
4656 pa.SetVolumeDetect(0);
4657*/
4658
4659 if (pa.Building != building)
4660 pa.Building = building;
4068 } 4661 }
4069 }
4070 }
4071 4662
4072 if (SetVD) 4663 UpdatePhysicsSubscribedEvents();
4073 {
4074 // If the above logic worked (this is urgent candidate to unit tests!)
4075 // we now have a physicsactor.
4076 // Defensive programming calls for a check here.
4077 // Better would be throwing an exception that could be catched by a unit test as the internal
4078 // logic should make sure, this Physactor is always here.
4079 if (pa != null)
4080 {
4081 pa.SetVolumeDetect(1);
4082 AddFlag(PrimFlags.Phantom); // We set this flag also if VD is active
4083 VolumeDetectActive = true;
4084 } 4664 }
4085 } 4665 }
4086 else
4087 {
4088 // Remove VolumeDetect in any case. Note, it's safe to call SetVolumeDetect as often as you like
4089 // (mumbles, well, at least if you have infinte CPU powers :-))
4090 if (pa != null)
4091 pa.SetVolumeDetect(0);
4092
4093 VolumeDetectActive = false;
4094 }
4095
4096 if (SetTemporary)
4097 {
4098 AddFlag(PrimFlags.TemporaryOnRez);
4099 }
4100 else
4101 {
4102 RemFlag(PrimFlags.TemporaryOnRez);
4103 }
4104 4666
4105 // m_log.Debug("Update: PHY:" + UsePhysics.ToString() + ", T:" + IsTemporary.ToString() + ", PHA:" + IsPhantom.ToString() + " S:" + CastsShadows.ToString()); 4667 // m_log.Debug("Update: PHY:" + UsePhysics.ToString() + ", T:" + IsTemporary.ToString() + ", PHA:" + IsPhantom.ToString() + " S:" + CastsShadows.ToString());
4106 4668
4669 // and last in case we have a new actor and not building
4670
4107 if (ParentGroup != null) 4671 if (ParentGroup != null)
4108 { 4672 {
4109 ParentGroup.HasGroupChanged = true; 4673 ParentGroup.HasGroupChanged = true;
4110 ScheduleFullUpdate(); 4674 ScheduleFullUpdate();
4111 } 4675 }
4112 4676
4113// m_log.DebugFormat("[SCENE OBJECT PART]: Updated PrimFlags on {0} {1} to {2}", Name, LocalId, Flags); 4677// m_log.DebugFormat("[SCENE OBJECT PART]: Updated PrimFlags on {0} {1} to {2}", Name, LocalId, Flags);
4114 } 4678 }
4115 4679
4116 /// <summary> 4680 /// <summary>
4117 /// Adds this part to the physics scene. 4681 /// Adds this part to the physics scene.
4682 /// and sets the PhysActor property
4118 /// </summary> 4683 /// </summary>
4119 /// <remarks>This method also sets the PhysActor property.</remarks> 4684 /// <param name="isPhysical">Add this prim as physical.</param>
4120 /// <param name="rigidBody">Add this prim with a rigid body.</param> 4685 /// <param name="isPhantom">Add this prim as phantom.</param>
4121 /// <returns> 4686 /// <param name="building">tells physics to delay full construction of object</param>
4122 /// The physics actor. null if there was a failure. 4687 /// <param name="applyDynamics">applies velocities, force and torque</param>
4123 /// </returns> 4688 private void AddToPhysics(bool isPhysical, bool isPhantom, bool building, bool applyDynamics)
4124 private PhysicsActor AddToPhysics(bool rigidBody) 4689 {
4125 {
4126 PhysicsActor pa; 4690 PhysicsActor pa;
4127 4691
4692 Vector3 velocity = Velocity;
4693 Vector3 rotationalVelocity = AngularVelocity;;
4694
4128 try 4695 try
4129 { 4696 {
4130 pa = ParentGroup.Scene.PhysicsScene.AddPrimShape( 4697 pa = ParentGroup.Scene.PhysicsScene.AddPrimShape(
4131 string.Format("{0}/{1}", Name, UUID), 4698 string.Format("{0}/{1}", Name, UUID),
4132 Shape, 4699 Shape,
4133 AbsolutePosition, 4700 AbsolutePosition,
4134 Scale, 4701 Scale,
4135 RotationOffset, 4702 GetWorldRotation(),
4136 rigidBody, 4703 isPhysical,
4137 m_localId); 4704 isPhantom,
4705 PhysicsShapeType,
4706 m_localId);
4138 } 4707 }
4139 catch 4708 catch (Exception ex)
4140 { 4709 {
4141 m_log.ErrorFormat("[SCENE]: caught exception meshing object {0}. Object set to phantom.", m_uuid); 4710 m_log.ErrorFormat("[SCENE]: AddToPhysics object {0} failed: {1}", m_uuid, ex.Message);
4142 pa = null; 4711 pa = null;
4143 } 4712 }
4144 4713
4145 // FIXME: Ideally we wouldn't set the property here to reduce situations where threads changing physical
4146 // properties can stop on each other. However, DoPhysicsPropertyUpdate() currently relies on PhysActor
4147 // being set.
4148 PhysActor = pa;
4149
4150 // Basic Physics can also return null as well as an exception catch.
4151 if (pa != null) 4714 if (pa != null)
4152 { 4715 {
4153 pa.SOPName = this.Name; // save object into the PhysActor so ODE internals know the joint/body info 4716 pa.SOPName = this.Name; // save object into the PhysActor so ODE internals know the joint/body info
4154 pa.SetMaterial(Material); 4717 pa.SetMaterial(Material);
4155 DoPhysicsPropertyUpdate(rigidBody, true); 4718
4719 if (VolumeDetectActive) // change if not the default only
4720 pa.SetVolumeDetect(1);
4721
4722 if (m_vehicleParams != null && LocalId == ParentGroup.RootPart.LocalId)
4723 m_vehicleParams.SetVehicle(pa);
4724
4725 // we are going to tell rest of code about physics so better have this here
4726 PhysActor = pa;
4727
4728 // DoPhysicsPropertyUpdate(isPhysical, true);
4729 // lets expand it here just with what it really needs to do
4730
4731 if (isPhysical)
4732 {
4733 if (ParentGroup.RootPart.KeyframeMotion != null)
4734 ParentGroup.RootPart.KeyframeMotion.Stop();
4735 ParentGroup.RootPart.KeyframeMotion = null;
4736 ParentGroup.Scene.AddPhysicalPrim(1);
4737
4738 pa.OnRequestTerseUpdate += PhysicsRequestingTerseUpdate;
4739 pa.OnOutOfBounds += PhysicsOutOfBounds;
4740
4741 if (ParentID != 0 && ParentID != LocalId)
4742 {
4743 PhysicsActor parentPa = ParentGroup.RootPart.PhysActor;
4744
4745 if (parentPa != null)
4746 {
4747 pa.link(parentPa);
4748 }
4749 }
4750 }
4751
4752 if (applyDynamics)
4753 // do independent of isphysical so parameters get setted (at least some)
4754 {
4755 Velocity = velocity;
4756 AngularVelocity = rotationalVelocity;
4757// pa.Velocity = velocity;
4758 pa.RotationalVelocity = rotationalVelocity;
4759
4760 // if not vehicle and root part apply force and torque
4761 if ((m_vehicleParams == null || m_vehicleParams.Type == Vehicle.TYPE_NONE)
4762 && LocalId == ParentGroup.RootPart.LocalId)
4763 {
4764 pa.Force = Force;
4765 pa.Torque = Torque;
4766 }
4767 }
4768
4769 if (Shape.SculptEntry)
4770 CheckSculptAndLoad();
4771 else
4772 ParentGroup.Scene.PhysicsScene.AddPhysicsActorTaint(pa);
4773
4774 if (!building)
4775 pa.Building = false;
4156 } 4776 }
4157 4777
4158 return pa; 4778 PhysActor = pa;
4159 } 4779 }
4160 4780
4161 /// <summary> 4781 /// <summary>
4162 /// This removes the part from the physics scene. 4782 /// This removes the part from the physics scene.
4163 /// </summary> 4783 /// </summary>
4164 /// <remarks> 4784 /// <remarks>
4165 /// This isn't the same as turning off physical, since even without being physical the prim has a physics 4785 /// This isn't the same as turning off physical, since even without being physical the prim has a physics
4166 /// representation for collision detection. Rather, this would be used in situations such as making a prim 4786 /// representation for collision detection.
4167 /// phantom.
4168 /// </remarks> 4787 /// </remarks>
4169 public void RemoveFromPhysics() 4788 public void RemoveFromPhysics()
4170 { 4789 {
4171 ParentGroup.Scene.PhysicsScene.RemovePrim(PhysActor); 4790 PhysicsActor pa = PhysActor;
4791 if (pa != null)
4792 {
4793 pa.OnCollisionUpdate -= PhysicsCollision;
4794 pa.OnRequestTerseUpdate -= PhysicsRequestingTerseUpdate;
4795 pa.OnOutOfBounds -= PhysicsOutOfBounds;
4796
4797 ParentGroup.Scene.PhysicsScene.RemovePrim(pa);
4798 }
4172 PhysActor = null; 4799 PhysActor = null;
4173 } 4800 }
4174 4801
@@ -4328,6 +4955,44 @@ namespace OpenSim.Region.Framework.Scenes
4328 ScheduleFullUpdate(); 4955 ScheduleFullUpdate();
4329 } 4956 }
4330 4957
4958
4959 private void UpdatePhysicsSubscribedEvents()
4960 {
4961 PhysicsActor pa = PhysActor;
4962 if (pa == null)
4963 return;
4964
4965 pa.OnCollisionUpdate -= PhysicsCollision;
4966
4967 bool hassound = (!VolumeDetectActive && CollisionSoundType >= 0 && ((Flags & PrimFlags.Physics) != 0));
4968
4969 scriptEvents CombinedEvents = AggregateScriptEvents;
4970
4971 // merge with root part
4972 if (ParentGroup != null && ParentGroup.RootPart != null)
4973 CombinedEvents |= ParentGroup.RootPart.AggregateScriptEvents;
4974
4975 // submit to this part case
4976 if (VolumeDetectActive)
4977 CombinedEvents &= PhyscicsVolumeDtcSubsEvents;
4978 else if ((Flags & PrimFlags.Phantom) != 0)
4979 CombinedEvents &= PhyscicsPhantonSubsEvents;
4980 else
4981 CombinedEvents &= PhysicsNeededSubsEvents;
4982
4983 if (hassound || CombinedEvents != 0)
4984 {
4985 // subscribe to physics updates.
4986 pa.OnCollisionUpdate += PhysicsCollision;
4987 pa.SubscribeEvents(50); // 20 reports per second
4988 }
4989 else
4990 {
4991 pa.UnSubscribeEvents();
4992 }
4993 }
4994
4995
4331 public void aggregateScriptEvents() 4996 public void aggregateScriptEvents()
4332 { 4997 {
4333 if (ParentGroup == null || ParentGroup.RootPart == null) 4998 if (ParentGroup == null || ParentGroup.RootPart == null)
@@ -4364,40 +5029,32 @@ namespace OpenSim.Region.Framework.Scenes
4364 { 5029 {
4365 objectflagupdate |= (uint) PrimFlags.AllowInventoryDrop; 5030 objectflagupdate |= (uint) PrimFlags.AllowInventoryDrop;
4366 } 5031 }
4367 5032/*
4368 PhysicsActor pa = PhysActor; 5033 PhysicsActor pa = PhysActor;
4369 5034 if (pa != null)
4370 if (
4371 ((AggregateScriptEvents & scriptEvents.collision) != 0) ||
4372 ((AggregateScriptEvents & scriptEvents.collision_end) != 0) ||
4373 ((AggregateScriptEvents & scriptEvents.collision_start) != 0) ||
4374 ((AggregateScriptEvents & scriptEvents.land_collision_start) != 0) ||
4375 ((AggregateScriptEvents & scriptEvents.land_collision) != 0) ||
4376 ((AggregateScriptEvents & scriptEvents.land_collision_end) != 0) ||
4377 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.collision) != 0) ||
4378 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.collision_end) != 0) ||
4379 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.collision_start) != 0) ||
4380 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.land_collision_start) != 0) ||
4381 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.land_collision) != 0) ||
4382 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.land_collision_end) != 0) ||
4383 (CollisionSound != UUID.Zero)
4384 )
4385 { 5035 {
4386 // subscribe to physics updates. 5036 if (
4387 if (pa != null) 5037// ((AggregateScriptEvents & scriptEvents.collision) != 0) ||
5038// ((AggregateScriptEvents & scriptEvents.collision_end) != 0) ||
5039// ((AggregateScriptEvents & scriptEvents.collision_start) != 0) ||
5040// ((AggregateScriptEvents & scriptEvents.land_collision_start) != 0) ||
5041// ((AggregateScriptEvents & scriptEvents.land_collision) != 0) ||
5042// ((AggregateScriptEvents & scriptEvents.land_collision_end) != 0) ||
5043 ((AggregateScriptEvents & PhysicsNeededSubsEvents) != 0) || ((ParentGroup.RootPart.AggregateScriptEvents & PhysicsNeededSubsEvents) != 0) || (CollisionSound != UUID.Zero)
5044 )
4388 { 5045 {
5046 // subscribe to physics updates.
4389 pa.OnCollisionUpdate += PhysicsCollision; 5047 pa.OnCollisionUpdate += PhysicsCollision;
4390 pa.SubscribeEvents(1000); 5048 pa.SubscribeEvents(1000);
4391 } 5049 }
4392 } 5050 else
4393 else
4394 {
4395 if (pa != null)
4396 { 5051 {
4397 pa.UnSubscribeEvents(); 5052 pa.UnSubscribeEvents();
4398 pa.OnCollisionUpdate -= PhysicsCollision; 5053 pa.OnCollisionUpdate -= PhysicsCollision;
4399 } 5054 }
4400 } 5055 }
5056 */
5057 UpdatePhysicsSubscribedEvents();
4401 5058
4402 //if ((GetEffectiveObjectFlags() & (uint)PrimFlags.Scripted) != 0) 5059 //if ((GetEffectiveObjectFlags() & (uint)PrimFlags.Scripted) != 0)
4403 //{ 5060 //{
@@ -4527,6 +5184,18 @@ namespace OpenSim.Region.Framework.Scenes
4527 return new Color4(color.R, color.G, color.B, (byte)(0xFF - color.A)); 5184 return new Color4(color.R, color.G, color.B, (byte)(0xFF - color.A));
4528 } 5185 }
4529 5186
5187 public void ResetOwnerChangeFlag()
5188 {
5189 List<UUID> inv = Inventory.GetInventoryList();
5190
5191 foreach (UUID itemID in inv)
5192 {
5193 TaskInventoryItem item = Inventory.GetInventoryItem(itemID);
5194 item.OwnerChanged = false;
5195 Inventory.UpdateInventoryItem(item, false, false);
5196 }
5197 }
5198
4530 /// <summary> 5199 /// <summary>
4531 /// Record an avatar sitting on this part. 5200 /// Record an avatar sitting on this part.
4532 /// </summary> 5201 /// </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 548dfd3..4d3ab51 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
@@ -893,14 +976,19 @@ namespace OpenSim.Region.Framework.Scenes
893 { 976 {
894 m_log.DebugFormat("[SCENE PRESENCE]: Restarting scripts in attachments..."); 977 m_log.DebugFormat("[SCENE PRESENCE]: Restarting scripts in attachments...");
895 // Resume scripts 978 // Resume scripts
896 foreach (SceneObjectGroup sog in m_attachments) 979 Util.FireAndForget(delegate(object x) {
897 { 980 foreach (SceneObjectGroup sog in m_attachments)
898 sog.RootPart.ParentGroup.CreateScriptInstances(0, false, m_scene.DefaultScriptEngine, GetStateSource()); 981 {
899 sog.ResumeScripts(); 982 sog.ScheduleGroupForFullUpdate();
900 } 983 sog.RootPart.ParentGroup.CreateScriptInstances(0, false, m_scene.DefaultScriptEngine, GetStateSource());
984 sog.ResumeScripts();
985 }
986 });
901 } 987 }
902 } 988 }
903 989
990 SendAvatarDataToAllAgents();
991
904 // send the animations of the other presences to me 992 // send the animations of the other presences to me
905 m_scene.ForEachRootScenePresence(delegate(ScenePresence presence) 993 m_scene.ForEachRootScenePresence(delegate(ScenePresence presence)
906 { 994 {
@@ -911,9 +999,12 @@ namespace OpenSim.Region.Framework.Scenes
911 // If we don't reset the movement flag here, an avatar that crosses to a neighbouring sim and returns will 999 // If we don't reset the movement flag here, an avatar that crosses to a neighbouring sim and returns will
912 // stall on the border crossing since the existing child agent will still have the last movement 1000 // stall on the border crossing since the existing child agent will still have the last movement
913 // recorded, which stops the input from being processed. 1001 // recorded, which stops the input from being processed.
1002
914 MovementFlag = 0; 1003 MovementFlag = 0;
915 1004
916 m_scene.EventManager.TriggerOnMakeRootAgent(this); 1005 m_scene.EventManager.TriggerOnMakeRootAgent(this);
1006
1007 m_scene.EventManager.OnRegionHeartbeatEnd += RegionHeartbeatEnd;
917 } 1008 }
918 1009
919 public int GetStateSource() 1010 public int GetStateSource()
@@ -941,12 +1032,16 @@ namespace OpenSim.Region.Framework.Scenes
941 /// </remarks> 1032 /// </remarks>
942 public void MakeChildAgent() 1033 public void MakeChildAgent()
943 { 1034 {
1035 m_scene.EventManager.OnRegionHeartbeatEnd -= RegionHeartbeatEnd;
1036
944 m_log.DebugFormat("[SCENE PRESENCE]: Making {0} a child agent in {1}", Name, Scene.RegionInfo.RegionName); 1037 m_log.DebugFormat("[SCENE PRESENCE]: Making {0} a child agent in {1}", Name, Scene.RegionInfo.RegionName);
945 1038
946 // Reset these so that teleporting in and walking out isn't seen 1039 // Reset these so that teleporting in and walking out isn't seen
947 // as teleporting back 1040 // as teleporting back
948 TeleportFlags = TeleportFlags.Default; 1041 TeleportFlags = TeleportFlags.Default;
949 1042
1043 MovementFlag = 0;
1044
950 // It looks like Animator is set to null somewhere, and MakeChild 1045 // It looks like Animator is set to null somewhere, and MakeChild
951 // is called after that. Probably in aborted teleports. 1046 // is called after that. Probably in aborted teleports.
952 if (Animator == null) 1047 if (Animator == null)
@@ -954,6 +1049,7 @@ namespace OpenSim.Region.Framework.Scenes
954 else 1049 else
955 Animator.ResetAnimations(); 1050 Animator.ResetAnimations();
956 1051
1052
957// m_log.DebugFormat( 1053// m_log.DebugFormat(
958// "[SCENE PRESENCE]: Downgrading root agent {0}, {1} to a child agent in {2}", 1054// "[SCENE PRESENCE]: Downgrading root agent {0}, {1} to a child agent in {2}",
959// Name, UUID, m_scene.RegionInfo.RegionName); 1055// Name, UUID, m_scene.RegionInfo.RegionName);
@@ -965,6 +1061,7 @@ namespace OpenSim.Region.Framework.Scenes
965 IsChildAgent = true; 1061 IsChildAgent = true;
966 m_scene.SwapRootAgentCount(true); 1062 m_scene.SwapRootAgentCount(true);
967 RemoveFromPhysicalScene(); 1063 RemoveFromPhysicalScene();
1064 ParentID = 0; // Child agents can't be sitting
968 1065
969 // FIXME: Set RegionHandle to the region handle of the scene this agent is moving into 1066 // FIXME: Set RegionHandle to the region handle of the scene this agent is moving into
970 1067
@@ -980,9 +1077,9 @@ namespace OpenSim.Region.Framework.Scenes
980 { 1077 {
981// PhysicsActor.OnRequestTerseUpdate -= SendTerseUpdateToAllClients; 1078// PhysicsActor.OnRequestTerseUpdate -= SendTerseUpdateToAllClients;
982 PhysicsActor.OnOutOfBounds -= OutOfBoundsCall; 1079 PhysicsActor.OnOutOfBounds -= OutOfBoundsCall;
983 m_scene.PhysicsScene.RemoveAvatar(PhysicsActor);
984 PhysicsActor.UnSubscribeEvents();
985 PhysicsActor.OnCollisionUpdate -= PhysicsCollisionUpdate; 1080 PhysicsActor.OnCollisionUpdate -= PhysicsCollisionUpdate;
1081 PhysicsActor.UnSubscribeEvents();
1082 m_scene.PhysicsScene.RemoveAvatar(PhysicsActor);
986 PhysicsActor = null; 1083 PhysicsActor = null;
987 } 1084 }
988// else 1085// else
@@ -999,7 +1096,7 @@ namespace OpenSim.Region.Framework.Scenes
999 /// <param name="pos"></param> 1096 /// <param name="pos"></param>
1000 public void Teleport(Vector3 pos) 1097 public void Teleport(Vector3 pos)
1001 { 1098 {
1002 TeleportWithMomentum(pos, null); 1099 TeleportWithMomentum(pos, Vector3.Zero);
1003 } 1100 }
1004 1101
1005 public void TeleportWithMomentum(Vector3 pos, Vector3? v) 1102 public void TeleportWithMomentum(Vector3 pos, Vector3? v)
@@ -1023,6 +1120,41 @@ namespace OpenSim.Region.Framework.Scenes
1023 SendTerseUpdateToAllClients(); 1120 SendTerseUpdateToAllClients();
1024 } 1121 }
1025 1122
1123 public void avnLocalTeleport(Vector3 newpos, Vector3? newvel, bool rotateToVelXY)
1124 {
1125 CheckLandingPoint(ref newpos);
1126 AbsolutePosition = newpos;
1127
1128 if (newvel.HasValue)
1129 {
1130 if ((Vector3)newvel == Vector3.Zero)
1131 {
1132 if (PhysicsActor != null)
1133 PhysicsActor.SetMomentum(Vector3.Zero);
1134 m_velocity = Vector3.Zero;
1135 }
1136 else
1137 {
1138 if (PhysicsActor != null)
1139 PhysicsActor.SetMomentum((Vector3)newvel);
1140 m_velocity = (Vector3)newvel;
1141
1142 if (rotateToVelXY)
1143 {
1144 Vector3 lookAt = (Vector3)newvel;
1145 lookAt.Z = 0;
1146 lookAt.Normalize();
1147 ControllingClient.SendLocalTeleport(newpos, lookAt, (uint)TeleportFlags.ViaLocation);
1148 return;
1149 }
1150 }
1151 }
1152
1153 SendTerseUpdateToAllClients();
1154 }
1155
1156
1157
1026 public void StopFlying() 1158 public void StopFlying()
1027 { 1159 {
1028 ControllingClient.StopFlying(this); 1160 ControllingClient.StopFlying(this);
@@ -1338,8 +1470,18 @@ namespace OpenSim.Region.Framework.Scenes
1338 { 1470 {
1339 if (m_followCamAuto) 1471 if (m_followCamAuto)
1340 { 1472 {
1341 Vector3 posAdjusted = m_pos + HEAD_ADJUSTMENT; 1473 // Vector3 posAdjusted = m_pos + HEAD_ADJUSTMENT;
1342 m_scene.PhysicsScene.RaycastWorld(m_pos, Vector3.Normalize(CameraPosition - posAdjusted), Vector3.Distance(CameraPosition, posAdjusted) + 0.3f, RayCastCameraCallback); 1474 // m_scene.PhysicsScene.RaycastWorld(m_pos, Vector3.Normalize(CameraPosition - posAdjusted), Vector3.Distance(CameraPosition, posAdjusted) + 0.3f, RayCastCameraCallback);
1475
1476 Vector3 posAdjusted = AbsolutePosition + HEAD_ADJUSTMENT;
1477 Vector3 distTocam = CameraPosition - posAdjusted;
1478 float distTocamlen = distTocam.Length();
1479 if (distTocamlen > 0)
1480 {
1481 distTocam *= 1.0f / distTocamlen;
1482 m_scene.PhysicsScene.RaycastWorld(posAdjusted, distTocam, distTocamlen + 0.3f, RayCastCameraCallback);
1483 }
1484
1343 } 1485 }
1344 } 1486 }
1345 1487
@@ -1773,12 +1915,17 @@ namespace OpenSim.Region.Framework.Scenes
1773// m_log.DebugFormat("[SCENE PRESENCE]: StandUp() for {0}", Name); 1915// m_log.DebugFormat("[SCENE PRESENCE]: StandUp() for {0}", Name);
1774 1916
1775 SitGround = false; 1917 SitGround = false;
1918
1919/* move this down so avatar gets physical in the new position and not where it is siting
1776 if (PhysicsActor == null) 1920 if (PhysicsActor == null)
1777 AddToPhysicalScene(false); 1921 AddToPhysicalScene(false);
1922 */
1778 1923
1779 if (ParentID != 0) 1924 if (ParentID != 0)
1780 { 1925 {
1781 SceneObjectPart part = ParentPart; 1926 SceneObjectPart part = ParentPart;
1927 UnRegisterSeatControls(part.ParentGroup.UUID);
1928
1782 TaskInventoryDictionary taskIDict = part.TaskInventory; 1929 TaskInventoryDictionary taskIDict = part.TaskInventory;
1783 if (taskIDict != null) 1930 if (taskIDict != null)
1784 { 1931 {
@@ -1794,14 +1941,22 @@ namespace OpenSim.Region.Framework.Scenes
1794 } 1941 }
1795 } 1942 }
1796 1943
1797 ParentPosition = part.GetWorldPosition(); 1944 part.ParentGroup.DeleteAvatar(UUID);
1945// ParentPosition = part.GetWorldPosition();
1798 ControllingClient.SendClearFollowCamProperties(part.ParentUUID); 1946 ControllingClient.SendClearFollowCamProperties(part.ParentUUID);
1799 1947
1800 m_pos += ParentPosition + new Vector3(0.0f, 0.0f, 2.0f * m_sitAvatarHeight); 1948// m_pos += ParentPosition + new Vector3(0.0f, 0.0f, 2.0f * m_sitAvatarHeight);
1801 ParentPosition = Vector3.Zero; 1949// ParentPosition = Vector3.Zero;
1950 m_pos = part.AbsolutePosition + (m_pos * part.GetWorldRotation()) + new Vector3(0.0f, 0.0f, 2.0f * m_sitAvatarHeight);
1951 if (part.SitTargetAvatar == UUID)
1952 m_bodyRot = part.GetWorldRotation() * part.SitTargetOrientation;
1802 1953
1803 ParentID = 0; 1954 ParentID = 0;
1804 ParentPart = null; 1955 ParentPart = null;
1956
1957 if (PhysicsActor == null)
1958 AddToPhysicalScene(false);
1959
1805 SendAvatarDataToAllAgents(); 1960 SendAvatarDataToAllAgents();
1806 m_requestedSitTargetID = 0; 1961 m_requestedSitTargetID = 0;
1807 1962
@@ -1811,6 +1966,9 @@ namespace OpenSim.Region.Framework.Scenes
1811 part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK); 1966 part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK);
1812 } 1967 }
1813 1968
1969 else if (PhysicsActor == null)
1970 AddToPhysicalScene(false);
1971
1814 Animator.TrySetMovementAnimation("STAND"); 1972 Animator.TrySetMovementAnimation("STAND");
1815 } 1973 }
1816 1974
@@ -1862,7 +2020,7 @@ namespace OpenSim.Region.Framework.Scenes
1862 // see http://wiki.secondlife.com/wiki/User:Andrew_Linden/Office_Hours/2007_11_06 for details on how LL does it 2020 // see http://wiki.secondlife.com/wiki/User:Andrew_Linden/Office_Hours/2007_11_06 for details on how LL does it
1863 2021
1864 if (PhysicsActor != null) 2022 if (PhysicsActor != null)
1865 m_sitAvatarHeight = PhysicsActor.Size.Z; 2023 m_sitAvatarHeight = PhysicsActor.Size.Z * 0.5f;
1866 2024
1867 bool canSit = false; 2025 bool canSit = false;
1868 Vector3 pos = part.AbsolutePosition + offset; 2026 Vector3 pos = part.AbsolutePosition + offset;
@@ -1911,7 +2069,7 @@ namespace OpenSim.Region.Framework.Scenes
1911 forceMouselook = part.GetForceMouselook(); 2069 forceMouselook = part.GetForceMouselook();
1912 2070
1913 ControllingClient.SendSitResponse( 2071 ControllingClient.SendSitResponse(
1914 targetID, offset, sitOrientation, false, cameraAtOffset, cameraEyeOffset, forceMouselook); 2072 part.UUID, offset, sitOrientation, false, cameraAtOffset, cameraEyeOffset, forceMouselook);
1915 2073
1916 m_requestedSitTargetUUID = targetID; 2074 m_requestedSitTargetUUID = targetID;
1917 2075
@@ -1925,6 +2083,9 @@ namespace OpenSim.Region.Framework.Scenes
1925 2083
1926 public void HandleAgentRequestSit(IClientAPI remoteClient, UUID agentID, UUID targetID, Vector3 offset) 2084 public void HandleAgentRequestSit(IClientAPI remoteClient, UUID agentID, UUID targetID, Vector3 offset)
1927 { 2085 {
2086 if (IsChildAgent)
2087 return;
2088
1928 if (ParentID != 0) 2089 if (ParentID != 0)
1929 { 2090 {
1930 StandUp(); 2091 StandUp();
@@ -2202,14 +2363,39 @@ namespace OpenSim.Region.Framework.Scenes
2202 2363
2203 //Quaternion result = (sitTargetOrient * vq) * nq; 2364 //Quaternion result = (sitTargetOrient * vq) * nq;
2204 2365
2205 m_pos = sitTargetPos + SIT_TARGET_ADJUSTMENT; 2366 double x, y, z, m;
2367
2368 Quaternion r = sitTargetOrient;
2369 m = r.X * r.X + r.Y * r.Y + r.Z * r.Z + r.W * r.W;
2370
2371 if (Math.Abs(1.0 - m) > 0.000001)
2372 {
2373 m = 1.0 / Math.Sqrt(m);
2374 r.X *= (float)m;
2375 r.Y *= (float)m;
2376 r.Z *= (float)m;
2377 r.W *= (float)m;
2378 }
2379
2380 x = 2 * (r.X * r.Z + r.Y * r.W);
2381 y = 2 * (-r.X * r.W + r.Y * r.Z);
2382 z = -r.X * r.X - r.Y * r.Y + r.Z * r.Z + r.W * r.W;
2383
2384 Vector3 up = new Vector3((float)x, (float)y, (float)z);
2385 Vector3 sitOffset = up * Appearance.AvatarHeight * 0.02638f;
2386
2387 m_pos = sitTargetPos + sitOffset + SIT_TARGET_ADJUSTMENT;
2388
2389// m_pos = sitTargetPos + SIT_TARGET_ADJUSTMENT - sitOffset;
2206 Rotation = sitTargetOrient; 2390 Rotation = sitTargetOrient;
2207 ParentPosition = part.AbsolutePosition; 2391// ParentPosition = part.AbsolutePosition;
2392 part.ParentGroup.AddAvatar(UUID);
2208 } 2393 }
2209 else 2394 else
2210 { 2395 {
2211 m_pos -= part.AbsolutePosition; 2396 m_pos -= part.AbsolutePosition;
2212 ParentPosition = part.AbsolutePosition; 2397// ParentPosition = part.AbsolutePosition;
2398 part.ParentGroup.AddAvatar(UUID);
2213 2399
2214// m_log.DebugFormat( 2400// m_log.DebugFormat(
2215// "[SCENE PRESENCE]: Sitting {0} at position {1} ({2} + {3}) on part {4} {5} without sit target", 2401// "[SCENE PRESENCE]: Sitting {0} at position {1} ({2} + {3}) on part {4} {5} without sit target",
@@ -2254,6 +2440,13 @@ namespace OpenSim.Region.Framework.Scenes
2254 Animator.RemoveAnimation(animID); 2440 Animator.RemoveAnimation(animID);
2255 } 2441 }
2256 2442
2443 public void avnHandleChangeAnim(UUID animID, bool addRemove,bool sendPack)
2444 {
2445 Animator.avnChangeAnim(animID, addRemove, sendPack);
2446 }
2447
2448
2449
2257 /// <summary> 2450 /// <summary>
2258 /// Rotate the avatar to the given rotation and apply a movement in the given relative vector 2451 /// Rotate the avatar to the given rotation and apply a movement in the given relative vector
2259 /// </summary> 2452 /// </summary>
@@ -2307,14 +2500,15 @@ namespace OpenSim.Region.Framework.Scenes
2307 direc.Z *= 2.6f; 2500 direc.Z *= 2.6f;
2308 2501
2309 // TODO: PreJump and jump happen too quickly. Many times prejump gets ignored. 2502 // TODO: PreJump and jump happen too quickly. Many times prejump gets ignored.
2310 Animator.TrySetMovementAnimation("PREJUMP"); 2503// Animator.TrySetMovementAnimation("PREJUMP");
2311 Animator.TrySetMovementAnimation("JUMP"); 2504// Animator.TrySetMovementAnimation("JUMP");
2312 } 2505 }
2313 } 2506 }
2314 } 2507 }
2315 2508
2316 // TODO: Add the force instead of only setting it to support multiple forces per frame? 2509 // TODO: Add the force instead of only setting it to support multiple forces per frame?
2317 m_forceToApply = direc; 2510 m_forceToApply = direc;
2511 Animator.UpdateMovementAnimations();
2318 } 2512 }
2319 2513
2320 #endregion 2514 #endregion
@@ -2706,8 +2900,9 @@ namespace OpenSim.Region.Framework.Scenes
2706 2900
2707 // If we don't have a PhysActor, we can't cross anyway 2901 // If we don't have a PhysActor, we can't cross anyway
2708 // Also don't do this while sat, sitting avatars cross with the 2902 // Also don't do this while sat, sitting avatars cross with the
2709 // object they sit on. 2903 // object they sit on. ParentUUID denoted a pending sit, don't
2710 if (ParentID != 0 || PhysicsActor == null) 2904 // interfere with it.
2905 if (ParentID != 0 || PhysicsActor == null || ParentUUID != UUID.Zero)
2711 return; 2906 return;
2712 2907
2713 if (!IsInTransit) 2908 if (!IsInTransit)
@@ -3048,6 +3243,9 @@ namespace OpenSim.Region.Framework.Scenes
3048 cAgent.AlwaysRun = SetAlwaysRun; 3243 cAgent.AlwaysRun = SetAlwaysRun;
3049 3244
3050 cAgent.Appearance = new AvatarAppearance(Appearance); 3245 cAgent.Appearance = new AvatarAppearance(Appearance);
3246
3247 cAgent.ParentPart = ParentUUID;
3248 cAgent.SitOffset = m_pos;
3051 3249
3052 lock (scriptedcontrols) 3250 lock (scriptedcontrols)
3053 { 3251 {
@@ -3056,7 +3254,7 @@ namespace OpenSim.Region.Framework.Scenes
3056 3254
3057 foreach (ScriptControllers c in scriptedcontrols.Values) 3255 foreach (ScriptControllers c in scriptedcontrols.Values)
3058 { 3256 {
3059 controls[i++] = new ControllerData(c.itemID, (uint)c.ignoreControls, (uint)c.eventControls); 3257 controls[i++] = new ControllerData(c.objectID, c.itemID, (uint)c.ignoreControls, (uint)c.eventControls);
3060 } 3258 }
3061 cAgent.Controllers = controls; 3259 cAgent.Controllers = controls;
3062 } 3260 }
@@ -3067,6 +3265,7 @@ namespace OpenSim.Region.Framework.Scenes
3067 cAgent.Anims = Animator.Animations.ToArray(); 3265 cAgent.Anims = Animator.Animations.ToArray();
3068 } 3266 }
3069 catch { } 3267 catch { }
3268 cAgent.DefaultAnim = Animator.Animations.DefaultAnimation;
3070 3269
3071 if (Scene.AttachmentsModule != null) 3270 if (Scene.AttachmentsModule != null)
3072 Scene.AttachmentsModule.CopyAttachments(this, cAgent); 3271 Scene.AttachmentsModule.CopyAttachments(this, cAgent);
@@ -3087,6 +3286,8 @@ namespace OpenSim.Region.Framework.Scenes
3087 CameraAtAxis = cAgent.AtAxis; 3286 CameraAtAxis = cAgent.AtAxis;
3088 CameraLeftAxis = cAgent.LeftAxis; 3287 CameraLeftAxis = cAgent.LeftAxis;
3089 CameraUpAxis = cAgent.UpAxis; 3288 CameraUpAxis = cAgent.UpAxis;
3289 ParentUUID = cAgent.ParentPart;
3290 m_prevSitOffset = cAgent.SitOffset;
3090 3291
3091 // When we get to the point of re-computing neighbors everytime this 3292 // When we get to the point of re-computing neighbors everytime this
3092 // changes, then start using the agent's drawdistance rather than the 3293 // changes, then start using the agent's drawdistance rather than the
@@ -3124,6 +3325,7 @@ namespace OpenSim.Region.Framework.Scenes
3124 foreach (ControllerData c in cAgent.Controllers) 3325 foreach (ControllerData c in cAgent.Controllers)
3125 { 3326 {
3126 ScriptControllers sc = new ScriptControllers(); 3327 ScriptControllers sc = new ScriptControllers();
3328 sc.objectID = c.ObjectID;
3127 sc.itemID = c.ItemID; 3329 sc.itemID = c.ItemID;
3128 sc.ignoreControls = (ScriptControlled)c.IgnoreControls; 3330 sc.ignoreControls = (ScriptControlled)c.IgnoreControls;
3129 sc.eventControls = (ScriptControlled)c.EventControls; 3331 sc.eventControls = (ScriptControlled)c.EventControls;
@@ -3138,6 +3340,8 @@ namespace OpenSim.Region.Framework.Scenes
3138 // FIXME: Why is this null check necessary? Where are the cases where we get a null Anims object? 3340 // FIXME: Why is this null check necessary? Where are the cases where we get a null Anims object?
3139 if (cAgent.Anims != null) 3341 if (cAgent.Anims != null)
3140 Animator.Animations.FromArray(cAgent.Anims); 3342 Animator.Animations.FromArray(cAgent.Anims);
3343 if (cAgent.DefaultAnim != null)
3344 Animator.Animations.SetDefaultAnimation(cAgent.DefaultAnim.AnimID, cAgent.DefaultAnim.SequenceNum, UUID.Zero);
3141 3345
3142 if (Scene.AttachmentsModule != null) 3346 if (Scene.AttachmentsModule != null)
3143 Scene.AttachmentsModule.CopyAttachments(cAgent, this); 3347 Scene.AttachmentsModule.CopyAttachments(cAgent, this);
@@ -3200,7 +3404,7 @@ namespace OpenSim.Region.Framework.Scenes
3200 //PhysicsActor.OnRequestTerseUpdate += SendTerseUpdateToAllClients; 3404 //PhysicsActor.OnRequestTerseUpdate += SendTerseUpdateToAllClients;
3201 PhysicsActor.OnCollisionUpdate += PhysicsCollisionUpdate; 3405 PhysicsActor.OnCollisionUpdate += PhysicsCollisionUpdate;
3202 PhysicsActor.OnOutOfBounds += OutOfBoundsCall; // Called for PhysicsActors when there's something wrong 3406 PhysicsActor.OnOutOfBounds += OutOfBoundsCall; // Called for PhysicsActors when there's something wrong
3203 PhysicsActor.SubscribeEvents(500); 3407 PhysicsActor.SubscribeEvents(100);
3204 PhysicsActor.LocalID = LocalId; 3408 PhysicsActor.LocalID = LocalId;
3205 } 3409 }
3206 3410
@@ -3282,6 +3486,8 @@ namespace OpenSim.Region.Framework.Scenes
3282 } 3486 }
3283 } 3487 }
3284 3488
3489 RaiseCollisionScriptEvents(coldata);
3490
3285 // Gods do not take damage and Invulnerable is set depending on parcel/region flags 3491 // Gods do not take damage and Invulnerable is set depending on parcel/region flags
3286 if (Invulnerable || GodLevel > 0) 3492 if (Invulnerable || GodLevel > 0)
3287 return; 3493 return;
@@ -3609,10 +3815,18 @@ namespace OpenSim.Region.Framework.Scenes
3609 3815
3610 public void RegisterControlEventsToScript(int controls, int accept, int pass_on, uint Obj_localID, UUID Script_item_UUID) 3816 public void RegisterControlEventsToScript(int controls, int accept, int pass_on, uint Obj_localID, UUID Script_item_UUID)
3611 { 3817 {
3818 SceneObjectPart p = m_scene.GetSceneObjectPart(Obj_localID);
3819 if (p == null)
3820 return;
3821
3822 ControllingClient.SendTakeControls(controls, false, false);
3823 ControllingClient.SendTakeControls(controls, true, false);
3824
3612 ScriptControllers obj = new ScriptControllers(); 3825 ScriptControllers obj = new ScriptControllers();
3613 obj.ignoreControls = ScriptControlled.CONTROL_ZERO; 3826 obj.ignoreControls = ScriptControlled.CONTROL_ZERO;
3614 obj.eventControls = ScriptControlled.CONTROL_ZERO; 3827 obj.eventControls = ScriptControlled.CONTROL_ZERO;
3615 3828
3829 obj.objectID = p.ParentGroup.UUID;
3616 obj.itemID = Script_item_UUID; 3830 obj.itemID = Script_item_UUID;
3617 if (pass_on == 0 && accept == 0) 3831 if (pass_on == 0 && accept == 0)
3618 { 3832 {
@@ -3661,6 +3875,21 @@ namespace OpenSim.Region.Framework.Scenes
3661 ControllingClient.SendTakeControls(int.MaxValue, false, false); 3875 ControllingClient.SendTakeControls(int.MaxValue, false, false);
3662 } 3876 }
3663 3877
3878 private void UnRegisterSeatControls(UUID obj)
3879 {
3880 List<UUID> takers = new List<UUID>();
3881
3882 foreach (ScriptControllers c in scriptedcontrols.Values)
3883 {
3884 if (c.objectID == obj)
3885 takers.Add(c.itemID);
3886 }
3887 foreach (UUID t in takers)
3888 {
3889 UnRegisterControlEventsToScript(0, t);
3890 }
3891 }
3892
3664 public void UnRegisterControlEventsToScript(uint Obj_localID, UUID Script_item_UUID) 3893 public void UnRegisterControlEventsToScript(uint Obj_localID, UUID Script_item_UUID)
3665 { 3894 {
3666 ScriptControllers takecontrols; 3895 ScriptControllers takecontrols;
@@ -3979,6 +4208,12 @@ namespace OpenSim.Region.Framework.Scenes
3979 4208
3980 private void CheckAndAdjustLandingPoint(ref Vector3 pos) 4209 private void CheckAndAdjustLandingPoint(ref Vector3 pos)
3981 { 4210 {
4211 string reason;
4212
4213 // Honor bans
4214 if (!m_scene.TestLandRestrictions(UUID, out reason, ref pos.X, ref pos.Y))
4215 return;
4216
3982 SceneObjectGroup telehub = null; 4217 SceneObjectGroup telehub = null;
3983 if (m_scene.RegionInfo.RegionSettings.TelehubObject != UUID.Zero && (telehub = m_scene.GetSceneObjectGroup(m_scene.RegionInfo.RegionSettings.TelehubObject)) != null) 4218 if (m_scene.RegionInfo.RegionSettings.TelehubObject != UUID.Zero && (telehub = m_scene.GetSceneObjectGroup(m_scene.RegionInfo.RegionSettings.TelehubObject)) != null)
3984 { 4219 {
@@ -4018,11 +4253,206 @@ namespace OpenSim.Region.Framework.Scenes
4018 pos = land.LandData.UserLocation; 4253 pos = land.LandData.UserLocation;
4019 } 4254 }
4020 } 4255 }
4021 4256
4022 land.SendLandUpdateToClient(ControllingClient); 4257 land.SendLandUpdateToClient(ControllingClient);
4023 } 4258 }
4024 } 4259 }
4025 4260
4261 private DetectedObject CreateDetObject(SceneObjectPart obj)
4262 {
4263 DetectedObject detobj = new DetectedObject();
4264 detobj.keyUUID = obj.UUID;
4265 detobj.nameStr = obj.Name;
4266 detobj.ownerUUID = obj.OwnerID;
4267 detobj.posVector = obj.AbsolutePosition;
4268 detobj.rotQuat = obj.GetWorldRotation();
4269 detobj.velVector = obj.Velocity;
4270 detobj.colliderType = 0;
4271 detobj.groupUUID = obj.GroupID;
4272
4273 return detobj;
4274 }
4275
4276 private DetectedObject CreateDetObject(ScenePresence av)
4277 {
4278 DetectedObject detobj = new DetectedObject();
4279 detobj.keyUUID = av.UUID;
4280 detobj.nameStr = av.ControllingClient.Name;
4281 detobj.ownerUUID = av.UUID;
4282 detobj.posVector = av.AbsolutePosition;
4283 detobj.rotQuat = av.Rotation;
4284 detobj.velVector = av.Velocity;
4285 detobj.colliderType = 0;
4286 detobj.groupUUID = av.ControllingClient.ActiveGroupId;
4287
4288 return detobj;
4289 }
4290
4291 private DetectedObject CreateDetObjectForGround()
4292 {
4293 DetectedObject detobj = new DetectedObject();
4294 detobj.keyUUID = UUID.Zero;
4295 detobj.nameStr = "";
4296 detobj.ownerUUID = UUID.Zero;
4297 detobj.posVector = AbsolutePosition;
4298 detobj.rotQuat = Quaternion.Identity;
4299 detobj.velVector = Vector3.Zero;
4300 detobj.colliderType = 0;
4301 detobj.groupUUID = UUID.Zero;
4302
4303 return detobj;
4304 }
4305
4306 private ColliderArgs CreateColliderArgs(SceneObjectPart dest, List<uint> colliders)
4307 {
4308 ColliderArgs colliderArgs = new ColliderArgs();
4309 List<DetectedObject> colliding = new List<DetectedObject>();
4310 foreach (uint localId in colliders)
4311 {
4312 if (localId == 0)
4313 continue;
4314
4315 SceneObjectPart obj = m_scene.GetSceneObjectPart(localId);
4316 if (obj != null)
4317 {
4318 if (!dest.CollisionFilteredOut(obj.UUID, obj.Name))
4319 colliding.Add(CreateDetObject(obj));
4320 }
4321 else
4322 {
4323 ScenePresence av = m_scene.GetScenePresence(localId);
4324 if (av != null && (!av.IsChildAgent))
4325 {
4326 if (!dest.CollisionFilteredOut(av.UUID, av.Name))
4327 colliding.Add(CreateDetObject(av));
4328 }
4329 }
4330 }
4331
4332 colliderArgs.Colliders = colliding;
4333
4334 return colliderArgs;
4335 }
4336
4337 private delegate void ScriptCollidingNotification(uint localID, ColliderArgs message);
4338
4339 private void SendCollisionEvent(SceneObjectGroup dest, scriptEvents ev, List<uint> colliders, ScriptCollidingNotification notify)
4340 {
4341 ColliderArgs CollidingMessage;
4342
4343 if (colliders.Count > 0)
4344 {
4345 if ((dest.RootPart.ScriptEvents & ev) != 0)
4346 {
4347 CollidingMessage = CreateColliderArgs(dest.RootPart, colliders);
4348
4349 if (CollidingMessage.Colliders.Count > 0)
4350 notify(dest.RootPart.LocalId, CollidingMessage);
4351 }
4352 }
4353 }
4354
4355 private void SendLandCollisionEvent(SceneObjectGroup dest, scriptEvents ev, ScriptCollidingNotification notify)
4356 {
4357 if ((dest.RootPart.ScriptEvents & ev) != 0)
4358 {
4359 ColliderArgs LandCollidingMessage = new ColliderArgs();
4360 List<DetectedObject> colliding = new List<DetectedObject>();
4361
4362 colliding.Add(CreateDetObjectForGround());
4363 LandCollidingMessage.Colliders = colliding;
4364
4365 notify(dest.RootPart.LocalId, LandCollidingMessage);
4366 }
4367 }
4368
4369 private void RaiseCollisionScriptEvents(Dictionary<uint, ContactPoint> coldata)
4370 {
4371 try
4372 {
4373 List<uint> thisHitColliders = new List<uint>();
4374 List<uint> endedColliders = new List<uint>();
4375 List<uint> startedColliders = new List<uint>();
4376 List<CollisionForSoundInfo> soundinfolist = new List<CollisionForSoundInfo>();
4377 CollisionForSoundInfo soundinfo;
4378 ContactPoint curcontact;
4379
4380 if (coldata.Count == 0)
4381 {
4382 if (m_lastColliders.Count == 0)
4383 return; // nothing to do
4384
4385 foreach (uint localID in m_lastColliders)
4386 {
4387 endedColliders.Add(localID);
4388 }
4389 m_lastColliders.Clear();
4390 }
4391
4392 else
4393 {
4394 foreach (uint id in coldata.Keys)
4395 {
4396 thisHitColliders.Add(id);
4397 if (!m_lastColliders.Contains(id))
4398 {
4399 startedColliders.Add(id);
4400 curcontact = coldata[id];
4401 if (Math.Abs(curcontact.RelativeSpeed) > 0.2)
4402 {
4403 soundinfo = new CollisionForSoundInfo();
4404 soundinfo.colliderID = id;
4405 soundinfo.position = curcontact.Position;
4406 soundinfo.relativeVel = curcontact.RelativeSpeed;
4407 soundinfolist.Add(soundinfo);
4408 }
4409 }
4410 //m_log.Debug("[SCENE PRESENCE]: Collided with:" + localid.ToString() + " at depth of: " + collissionswith[localid].ToString());
4411 }
4412
4413 // calculate things that ended colliding
4414 foreach (uint localID in m_lastColliders)
4415 {
4416 if (!thisHitColliders.Contains(localID))
4417 {
4418 endedColliders.Add(localID);
4419 }
4420 }
4421 //add the items that started colliding this time to the last colliders list.
4422 foreach (uint localID in startedColliders)
4423 {
4424 m_lastColliders.Add(localID);
4425 }
4426 // remove things that ended colliding from the last colliders list
4427 foreach (uint localID in endedColliders)
4428 {
4429 m_lastColliders.Remove(localID);
4430 }
4431
4432 if (soundinfolist.Count > 0)
4433 CollisionSounds.AvatarCollisionSound(this, soundinfolist);
4434 }
4435
4436 foreach (SceneObjectGroup att in GetAttachments())
4437 {
4438 SendCollisionEvent(att, scriptEvents.collision_start, startedColliders, m_scene.EventManager.TriggerScriptCollidingStart);
4439 SendCollisionEvent(att, scriptEvents.collision , m_lastColliders , m_scene.EventManager.TriggerScriptColliding);
4440 SendCollisionEvent(att, scriptEvents.collision_end , endedColliders , m_scene.EventManager.TriggerScriptCollidingEnd);
4441
4442 if (startedColliders.Contains(0))
4443 SendLandCollisionEvent(att, scriptEvents.land_collision_start, m_scene.EventManager.TriggerScriptLandCollidingStart);
4444 if (m_lastColliders.Contains(0))
4445 SendLandCollisionEvent(att, scriptEvents.land_collision, m_scene.EventManager.TriggerScriptLandColliding);
4446 if (endedColliders.Contains(0))
4447 SendLandCollisionEvent(att, scriptEvents.land_collision_end, m_scene.EventManager.TriggerScriptLandCollidingEnd);
4448 }
4449 }
4450 finally
4451 {
4452 m_collisionEventFlag = false;
4453 }
4454 }
4455
4026 private void TeleportFlagsDebug() { 4456 private void TeleportFlagsDebug() {
4027 4457
4028 // Some temporary debugging help to show all the TeleportFlags we have... 4458 // Some temporary debugging help to show all the TeleportFlags we have...
@@ -4047,6 +4477,5 @@ namespace OpenSim.Region.Framework.Scenes
4047 m_log.InfoFormat("[SCENE PRESENCE]: TELEPORT ******************"); 4477 m_log.InfoFormat("[SCENE PRESENCE]: TELEPORT ******************");
4048 4478
4049 } 4479 }
4050
4051 } 4480 }
4052} 4481}
diff --git a/OpenSim/Region/Framework/Scenes/Serialization/SceneObjectSerializer.cs b/OpenSim/Region/Framework/Scenes/Serialization/SceneObjectSerializer.cs
index 2d4c60a..0d292e7 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,21 @@ 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
369 #endregion 390 #endregion
370 391
371 #region TaskInventoryXmlProcessors initialization 392 #region TaskInventoryXmlProcessors initialization
@@ -393,7 +414,7 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
393 m_TaskInventoryXmlProcessors.Add("PermsMask", ProcessTIPermsMask); 414 m_TaskInventoryXmlProcessors.Add("PermsMask", ProcessTIPermsMask);
394 m_TaskInventoryXmlProcessors.Add("Type", ProcessTIType); 415 m_TaskInventoryXmlProcessors.Add("Type", ProcessTIType);
395 m_TaskInventoryXmlProcessors.Add("OwnerChanged", ProcessTIOwnerChanged); 416 m_TaskInventoryXmlProcessors.Add("OwnerChanged", ProcessTIOwnerChanged);
396 417
397 #endregion 418 #endregion
398 419
399 #region ShapeXmlProcessors initialization 420 #region ShapeXmlProcessors initialization
@@ -593,6 +614,48 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
593 obj.ClickAction = (byte)reader.ReadElementContentAsInt("ClickAction", String.Empty); 614 obj.ClickAction = (byte)reader.ReadElementContentAsInt("ClickAction", String.Empty);
594 } 615 }
595 616
617 private static void ProcessPhysicsShapeType(SceneObjectPart obj, XmlTextReader reader)
618 {
619 obj.PhysicsShapeType = (byte)reader.ReadElementContentAsInt("PhysicsShapeType", String.Empty);
620 }
621
622 private static void ProcessDensity(SceneObjectPart obj, XmlTextReader reader)
623 {
624 obj.Density = reader.ReadElementContentAsFloat("Density", String.Empty);
625 }
626
627 private static void ProcessFriction(SceneObjectPart obj, XmlTextReader reader)
628 {
629 obj.Friction = reader.ReadElementContentAsFloat("Friction", String.Empty);
630 }
631
632 private static void ProcessBounce(SceneObjectPart obj, XmlTextReader reader)
633 {
634 obj.Bounciness = reader.ReadElementContentAsFloat("Bounce", String.Empty);
635 }
636
637 private static void ProcessGravityModifier(SceneObjectPart obj, XmlTextReader reader)
638 {
639 obj.GravityModifier = reader.ReadElementContentAsFloat("GravityModifier", String.Empty);
640 }
641
642 private static void ProcessVehicle(SceneObjectPart obj, XmlTextReader reader)
643 {
644 SOPVehicle vehicle = SOPVehicle.FromXml2(reader);
645
646 if (vehicle == null)
647 {
648 obj.VehicleParams = null;
649 m_log.DebugFormat(
650 "[SceneObjectSerializer]: Parsing Vehicle for object part {0} {1} encountered errors. Please see earlier log entries.",
651 obj.Name, obj.UUID);
652 }
653 else
654 {
655 obj.VehicleParams = vehicle;
656 }
657 }
658
596 private static void ProcessShape(SceneObjectPart obj, XmlTextReader reader) 659 private static void ProcessShape(SceneObjectPart obj, XmlTextReader reader)
597 { 660 {
598 List<string> errorNodeNames; 661 List<string> errorNodeNames;
@@ -757,6 +820,25 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
757 obj.PayPrice[4] = (int)reader.ReadElementContentAsInt("PayPrice4", String.Empty); 820 obj.PayPrice[4] = (int)reader.ReadElementContentAsInt("PayPrice4", String.Empty);
758 } 821 }
759 822
823 private static void ProcessBuoyancy(SceneObjectPart obj, XmlTextReader reader)
824 {
825 obj.Buoyancy = (float)reader.ReadElementContentAsFloat("Buoyancy", String.Empty);
826 }
827
828 private static void ProcessForce(SceneObjectPart obj, XmlTextReader reader)
829 {
830 obj.Force = Util.ReadVector(reader, "Force");
831 }
832 private static void ProcessTorque(SceneObjectPart obj, XmlTextReader reader)
833 {
834 obj.Torque = Util.ReadVector(reader, "Torque");
835 }
836
837 private static void ProcessVolumeDetectActive(SceneObjectPart obj, XmlTextReader reader)
838 {
839 obj.VolumeDetectActive = Util.ReadBoolean(reader);
840 }
841
760 #endregion 842 #endregion
761 843
762 #region TaskInventoryXmlProcessors 844 #region TaskInventoryXmlProcessors
@@ -1144,6 +1226,16 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
1144 }); 1226 });
1145 1227
1146 writer.WriteEndElement(); 1228 writer.WriteEndElement();
1229
1230 if (sog.RootPart.KeyframeMotion != null)
1231 {
1232 Byte[] data = sog.RootPart.KeyframeMotion.Serialize();
1233
1234 writer.WriteStartElement(String.Empty, "KeyframeMotion", String.Empty);
1235 writer.WriteBase64(data, 0, data.Length);
1236 writer.WriteEndElement();
1237 }
1238
1147 writer.WriteEndElement(); 1239 writer.WriteEndElement();
1148 } 1240 }
1149 1241
@@ -1243,6 +1335,27 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
1243 writer.WriteElementString("PayPrice3", sop.PayPrice[3].ToString()); 1335 writer.WriteElementString("PayPrice3", sop.PayPrice[3].ToString());
1244 writer.WriteElementString("PayPrice4", sop.PayPrice[4].ToString()); 1336 writer.WriteElementString("PayPrice4", sop.PayPrice[4].ToString());
1245 1337
1338 writer.WriteElementString("Buoyancy", sop.Buoyancy.ToString());
1339
1340 WriteVector(writer, "Force", sop.Force);
1341 WriteVector(writer, "Torque", sop.Torque);
1342
1343 writer.WriteElementString("VolumeDetectActive", sop.VolumeDetectActive.ToString().ToLower());
1344
1345 if (sop.VehicleParams != null)
1346 sop.VehicleParams.ToXml2(writer);
1347
1348 if(sop.PhysicsShapeType != sop.DefaultPhysicsShapeType())
1349 writer.WriteElementString("PhysicsShapeType", sop.PhysicsShapeType.ToString().ToLower());
1350 if (sop.Density != 1000.0f)
1351 writer.WriteElementString("Density", sop.Density.ToString().ToLower());
1352 if (sop.Friction != 0.6f)
1353 writer.WriteElementString("Friction", sop.Friction.ToString().ToLower());
1354 if (sop.Bounciness != 0.5f)
1355 writer.WriteElementString("Bounce", sop.Bounciness.ToString().ToLower());
1356 if (sop.GravityModifier != 1.0f)
1357 writer.WriteElementString("GravityModifier", sop.GravityModifier.ToString().ToLower());
1358
1246 writer.WriteEndElement(); 1359 writer.WriteEndElement();
1247 } 1360 }
1248 1361
@@ -1467,12 +1580,6 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
1467 { 1580 {
1468 TaskInventoryDictionary tinv = new TaskInventoryDictionary(); 1581 TaskInventoryDictionary tinv = new TaskInventoryDictionary();
1469 1582
1470 if (reader.IsEmptyElement)
1471 {
1472 reader.Read();
1473 return tinv;
1474 }
1475
1476 reader.ReadStartElement(name, String.Empty); 1583 reader.ReadStartElement(name, String.Empty);
1477 1584
1478 while (reader.Name == "TaskInventoryItem") 1585 while (reader.Name == "TaskInventoryItem")
diff --git a/OpenSim/Region/Framework/Scenes/SimStatsReporter.cs b/OpenSim/Region/Framework/Scenes/SimStatsReporter.cs
index 96317c3..20919a1 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 345
319 // 'statsUpdateFactor' is how often stats packets are sent in seconds. Used below to change 346 m_otherMS = m_frameMS - m_physicsMS - m_agentMS - m_sleeptimeMS;
320 // values to X-per-second values. 347 if (m_otherMS < 0)
348 m_otherMS = 0;
321 349
322 uint thisFrame = m_scene.Frame; 350 for (int i = 0; i < 23; i++)
323 float framesUpdated = (float)(thisFrame - m_lastUpdateFrame) * m_reportedFpsCorrectionFactor;
324 m_lastUpdateFrame = thisFrame;
325
326 // Avoid div-by-zero if somehow we've not updated any frames.
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 {
@@ -429,13 +452,14 @@ namespace OpenSim.Region.Framework.Scenes
429 // Need to change things so that stats source can indicate whether they are per second or 452 // Need to change things so that stats source can indicate whether they are per second or
430 // per frame. 453 // per frame.
431 if (tuple.Key.EndsWith("MS")) 454 if (tuple.Key.EndsWith("MS"))
432 m_lastReportedExtraSimStats[tuple.Key] = tuple.Value / framesUpdated; 455 m_lastReportedExtraSimStats[tuple.Key] = tuple.Value * perframe;
433 else 456 else
434 m_lastReportedExtraSimStats[tuple.Key] = tuple.Value / m_statsUpdateFactor; 457 m_lastReportedExtraSimStats[tuple.Key] = tuple.Value / m_statsUpdateFactor;
435 } 458 }
436 } 459 }
437 } 460 }
438 461
462// LastReportedObjectUpdates = m_objectUpdates / m_statsUpdateFactor;
439 ResetValues(); 463 ResetValues();
440 } 464 }
441 } 465 }
@@ -458,7 +482,8 @@ namespace OpenSim.Region.Framework.Scenes
458 m_physicsMS = 0; 482 m_physicsMS = 0;
459 m_imageMS = 0; 483 m_imageMS = 0;
460 m_otherMS = 0; 484 m_otherMS = 0;
461 m_spareMS = 0; 485// m_spareMS = 0;
486 m_sleeptimeMS = 0;
462 487
463//Ckrinke This variable is not used, so comment to remove compiler warning until it is used. 488//Ckrinke This variable is not used, so comment to remove compiler warning until it is used.
464//Ckrinke m_scriptMS = 0; 489//Ckrinke m_scriptMS = 0;
@@ -537,11 +562,6 @@ namespace OpenSim.Region.Framework.Scenes
537 m_frameMS += ms; 562 m_frameMS += ms;
538 } 563 }
539 564
540 public void AddSpareMS(int ms)
541 {
542 m_spareMS += ms;
543 }
544
545 public void addNetMS(int ms) 565 public void addNetMS(int ms)
546 { 566 {
547 m_netMS += ms; 567 m_netMS += ms;
@@ -567,6 +587,11 @@ namespace OpenSim.Region.Framework.Scenes
567 m_otherMS += ms; 587 m_otherMS += ms;
568 } 588 }
569 589
590 public void addSleepMS(int ms)
591 {
592 m_sleeptimeMS += ms;
593 }
594
570 public void AddPendingDownloads(int count) 595 public void AddPendingDownloads(int count)
571 { 596 {
572 m_pendingDownloads += count; 597 m_pendingDownloads += count;
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 efb68a2..411e421 100644
--- a/OpenSim/Region/Framework/Scenes/UuidGatherer.cs
+++ b/OpenSim/Region/Framework/Scenes/UuidGatherer.cs
@@ -87,10 +87,6 @@ namespace OpenSim.Region.Framework.Scenes
87 /// <param name="assetUuids">The assets gathered</param> 87 /// <param name="assetUuids">The assets gathered</param>
88 public void GatherAssetUuids(UUID assetUuid, AssetType assetType, IDictionary<UUID, AssetType> assetUuids) 88 public void GatherAssetUuids(UUID assetUuid, AssetType assetType, IDictionary<UUID, AssetType> assetUuids)
89 { 89 {
90 // avoid infinite loops
91 if (assetUuids.ContainsKey(assetUuid))
92 return;
93
94 try 90 try
95 { 91 {
96 assetUuids[assetUuid] = assetType; 92 assetUuids[assetUuid] = assetType;