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.cs24
-rw-r--r--OpenSim/Region/Framework/Scenes/KeyframeMotion.cs422
-rw-r--r--OpenSim/Region/Framework/Scenes/Prioritizer.cs4
-rw-r--r--OpenSim/Region/Framework/Scenes/SOPMaterial.cs95
-rw-r--r--OpenSim/Region/Framework/Scenes/SOPVehicle.cs792
-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.cs733
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneBase.cs2
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneCommunicationService.cs32
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneGraph.cs486
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneManager.cs268
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneObjectGroup.Inventory.cs17
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs1354
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneObjectPart.cs1701
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs787
-rw-r--r--OpenSim/Region/Framework/Scenes/ScenePresence.cs593
-rw-r--r--OpenSim/Region/Framework/Scenes/Serialization/SceneObjectSerializer.cs121
-rw-r--r--OpenSim/Region/Framework/Scenes/SimStatsReporter.cs30
-rw-r--r--OpenSim/Region/Framework/Scenes/UndoState.cs367
-rw-r--r--OpenSim/Region/Framework/Scenes/UuidGatherer.cs4
23 files changed, 6657 insertions, 1914 deletions
diff --git a/OpenSim/Region/Framework/Scenes/Animation/ScenePresenceAnimator.cs b/OpenSim/Region/Framework/Scenes/Animation/ScenePresenceAnimator.cs
index 14ae287..9ddac19 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 f92ed8e..76a952b 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;
@@ -896,6 +900,26 @@ namespace OpenSim.Region.Framework.Scenes
896 } 900 }
897 } 901 }
898 } 902 }
903 public void TriggerTerrainUpdate()
904 {
905 OnTerrainUpdateDelegate handlerTerrainUpdate = OnTerrainUpdate;
906 if (handlerTerrainUpdate != null)
907 {
908 foreach (OnTerrainUpdateDelegate d in handlerTerrainUpdate.GetInvocationList())
909 {
910 try
911 {
912 d();
913 }
914 catch (Exception e)
915 {
916 m_log.ErrorFormat(
917 "[EVENT MANAGER]: Delegate for TriggerTerrainUpdate failed - continuing. {0} {1}",
918 e.Message, e.StackTrace);
919 }
920 }
921 }
922 }
899 923
900 public void TriggerTerrainTick() 924 public void TriggerTerrainTick()
901 { 925 {
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..0a34a4c 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)
@@ -226,7 +226,7 @@ namespace OpenSim.Region.Framework.Scenes
226 226
227 for (int i = 0; i < queues - 1; i++) 227 for (int i = 0; i < queues - 1; i++)
228 { 228 {
229 if (distance < 10 * Math.Pow(2.0,i)) 229 if (distance < 30 * Math.Pow(2.0,i))
230 break; 230 break;
231 pqueue++; 231 pqueue++;
232 } 232 }
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..41e8944
--- /dev/null
+++ b/OpenSim/Region/Framework/Scenes/SOPVehicle.cs
@@ -0,0 +1,792 @@
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;
39using OpenSim.Region.Framework.Scenes.Serialization;
40
41namespace OpenSim.Region.Framework.Scenes
42{
43 public class SOPVehicle
44 {
45 public VehicleData vd;
46
47 public Vehicle Type
48 {
49 get { return vd.m_type; }
50 }
51
52 public SOPVehicle()
53 {
54 vd = new VehicleData();
55 ProcessTypeChange(Vehicle.TYPE_NONE); // is needed?
56 }
57
58 public void ProcessFloatVehicleParam(Vehicle pParam, float pValue)
59 {
60 float len;
61 float timestep = 0.01f;
62 switch (pParam)
63 {
64 case Vehicle.ANGULAR_DEFLECTION_EFFICIENCY:
65 if (pValue < 0f) pValue = 0f;
66 if (pValue > 1f) pValue = 1f;
67 vd.m_angularDeflectionEfficiency = pValue;
68 break;
69 case Vehicle.ANGULAR_DEFLECTION_TIMESCALE:
70 if (pValue < timestep) pValue = timestep;
71 vd.m_angularDeflectionTimescale = pValue;
72 break;
73 case Vehicle.ANGULAR_MOTOR_DECAY_TIMESCALE:
74 if (pValue < timestep) pValue = timestep;
75 else if (pValue > 120) pValue = 120;
76 vd.m_angularMotorDecayTimescale = pValue;
77 break;
78 case Vehicle.ANGULAR_MOTOR_TIMESCALE:
79 if (pValue < timestep) pValue = timestep;
80 vd.m_angularMotorTimescale = pValue;
81 break;
82 case Vehicle.BANKING_EFFICIENCY:
83 if (pValue < -1f) pValue = -1f;
84 if (pValue > 1f) pValue = 1f;
85 vd.m_bankingEfficiency = pValue;
86 break;
87 case Vehicle.BANKING_MIX:
88 if (pValue < 0f) pValue = 0f;
89 if (pValue > 1f) pValue = 1f;
90 vd.m_bankingMix = pValue;
91 break;
92 case Vehicle.BANKING_TIMESCALE:
93 if (pValue < timestep) pValue = timestep;
94 vd.m_bankingTimescale = pValue;
95 break;
96 case Vehicle.BUOYANCY:
97 if (pValue < -1f) pValue = -1f;
98 if (pValue > 1f) pValue = 1f;
99 vd.m_VehicleBuoyancy = pValue;
100 break;
101 case Vehicle.HOVER_EFFICIENCY:
102 if (pValue < 0f) pValue = 0f;
103 if (pValue > 1f) pValue = 1f;
104 vd.m_VhoverEfficiency = pValue;
105 break;
106 case Vehicle.HOVER_HEIGHT:
107 vd.m_VhoverHeight = pValue;
108 break;
109 case Vehicle.HOVER_TIMESCALE:
110 if (pValue < timestep) pValue = timestep;
111 vd.m_VhoverTimescale = pValue;
112 break;
113 case Vehicle.LINEAR_DEFLECTION_EFFICIENCY:
114 if (pValue < 0f) pValue = 0f;
115 if (pValue > 1f) pValue = 1f;
116 vd.m_linearDeflectionEfficiency = pValue;
117 break;
118 case Vehicle.LINEAR_DEFLECTION_TIMESCALE:
119 if (pValue < timestep) pValue = timestep;
120 vd.m_linearDeflectionTimescale = pValue;
121 break;
122 case Vehicle.LINEAR_MOTOR_DECAY_TIMESCALE:
123 if (pValue < timestep) pValue = timestep;
124 else if (pValue > 120) pValue = 120;
125 vd.m_linearMotorDecayTimescale = pValue;
126 break;
127 case Vehicle.LINEAR_MOTOR_TIMESCALE:
128 if (pValue < timestep) pValue = timestep;
129 vd.m_linearMotorTimescale = pValue;
130 break;
131 case Vehicle.VERTICAL_ATTRACTION_EFFICIENCY:
132 if (pValue < 0f) pValue = 0f;
133 if (pValue > 1f) pValue = 1f;
134 vd.m_verticalAttractionEfficiency = pValue;
135 break;
136 case Vehicle.VERTICAL_ATTRACTION_TIMESCALE:
137 if (pValue < timestep) pValue = timestep;
138 vd.m_verticalAttractionTimescale = pValue;
139 break;
140
141 // These are vector properties but the engine lets you use a single float value to
142 // set all of the components to the same value
143 case Vehicle.ANGULAR_FRICTION_TIMESCALE:
144 if (pValue < timestep) pValue = timestep;
145 vd.m_angularFrictionTimescale = new Vector3(pValue, pValue, pValue);
146 break;
147 case Vehicle.ANGULAR_MOTOR_DIRECTION:
148 vd.m_angularMotorDirection = new Vector3(pValue, pValue, pValue);
149 len = vd.m_angularMotorDirection.Length();
150 if (len > 12.566f)
151 vd.m_angularMotorDirection *= (12.566f / len);
152 break;
153 case Vehicle.LINEAR_FRICTION_TIMESCALE:
154 if (pValue < timestep) pValue = timestep;
155 vd.m_linearFrictionTimescale = new Vector3(pValue, pValue, pValue);
156 break;
157 case Vehicle.LINEAR_MOTOR_DIRECTION:
158 vd.m_linearMotorDirection = new Vector3(pValue, pValue, pValue);
159 len = vd.m_linearMotorDirection.Length();
160 if (len > 30.0f)
161 vd.m_linearMotorDirection *= (30.0f / len);
162 break;
163 case Vehicle.LINEAR_MOTOR_OFFSET:
164 vd.m_linearMotorOffset = new Vector3(pValue, pValue, pValue);
165 len = vd.m_linearMotorOffset.Length();
166 if (len > 100.0f)
167 vd.m_linearMotorOffset *= (100.0f / len);
168 break;
169 }
170 }//end ProcessFloatVehicleParam
171
172 public void ProcessVectorVehicleParam(Vehicle pParam, Vector3 pValue)
173 {
174 float len;
175 float timestep = 0.01f;
176 switch (pParam)
177 {
178 case Vehicle.ANGULAR_FRICTION_TIMESCALE:
179 if (pValue.X < timestep) pValue.X = timestep;
180 if (pValue.Y < timestep) pValue.Y = timestep;
181 if (pValue.Z < timestep) pValue.Z = timestep;
182
183 vd.m_angularFrictionTimescale = new Vector3(pValue.X, pValue.Y, pValue.Z);
184 break;
185 case Vehicle.ANGULAR_MOTOR_DIRECTION:
186 vd.m_angularMotorDirection = new Vector3(pValue.X, pValue.Y, pValue.Z);
187 // Limit requested angular speed to 2 rps= 4 pi rads/sec
188 len = vd.m_angularMotorDirection.Length();
189 if (len > 12.566f)
190 vd.m_angularMotorDirection *= (12.566f / len);
191 break;
192 case Vehicle.LINEAR_FRICTION_TIMESCALE:
193 if (pValue.X < timestep) pValue.X = timestep;
194 if (pValue.Y < timestep) pValue.Y = timestep;
195 if (pValue.Z < timestep) pValue.Z = timestep;
196 vd.m_linearFrictionTimescale = new Vector3(pValue.X, pValue.Y, pValue.Z);
197 break;
198 case Vehicle.LINEAR_MOTOR_DIRECTION:
199 vd.m_linearMotorDirection = new Vector3(pValue.X, pValue.Y, pValue.Z);
200 len = vd.m_linearMotorDirection.Length();
201 if (len > 30.0f)
202 vd.m_linearMotorDirection *= (30.0f / len);
203 break;
204 case Vehicle.LINEAR_MOTOR_OFFSET:
205 vd.m_linearMotorOffset = new Vector3(pValue.X, pValue.Y, pValue.Z);
206 len = vd.m_linearMotorOffset.Length();
207 if (len > 100.0f)
208 vd.m_linearMotorOffset *= (100.0f / len);
209 break;
210 }
211 }//end ProcessVectorVehicleParam
212
213 public void ProcessRotationVehicleParam(Vehicle pParam, Quaternion pValue)
214 {
215 switch (pParam)
216 {
217 case Vehicle.REFERENCE_FRAME:
218 vd.m_referenceFrame = Quaternion.Inverse(pValue);
219 break;
220 }
221 }//end ProcessRotationVehicleParam
222
223 public void ProcessVehicleFlags(int pParam, bool remove)
224 {
225 if (remove)
226 {
227 vd.m_flags &= ~((VehicleFlag)pParam);
228 }
229 else
230 {
231 vd.m_flags |= (VehicleFlag)pParam;
232 }
233 }//end ProcessVehicleFlags
234
235 public void ProcessTypeChange(Vehicle pType)
236 {
237 vd.m_linearMotorDirection = Vector3.Zero;
238 vd.m_angularMotorDirection = Vector3.Zero;
239 vd.m_linearMotorOffset = Vector3.Zero;
240 vd.m_referenceFrame = Quaternion.Identity;
241
242 // Set Defaults For Type
243 vd.m_type = pType;
244 switch (pType)
245 {
246 case Vehicle.TYPE_NONE:
247 vd.m_linearFrictionTimescale = new Vector3(1000, 1000, 1000);
248 vd.m_angularFrictionTimescale = new Vector3(1000, 1000, 1000);
249 vd.m_linearMotorTimescale = 1000;
250 vd.m_linearMotorDecayTimescale = 120;
251 vd.m_angularMotorTimescale = 1000;
252 vd.m_angularMotorDecayTimescale = 1000;
253 vd.m_VhoverHeight = 0;
254 vd.m_VhoverEfficiency = 1;
255 vd.m_VhoverTimescale = 1000;
256 vd.m_VehicleBuoyancy = 0;
257 vd.m_linearDeflectionEfficiency = 0;
258 vd.m_linearDeflectionTimescale = 1000;
259 vd.m_angularDeflectionEfficiency = 0;
260 vd.m_angularDeflectionTimescale = 1000;
261 vd.m_bankingEfficiency = 0;
262 vd.m_bankingMix = 1;
263 vd.m_bankingTimescale = 1000;
264 vd.m_verticalAttractionEfficiency = 0;
265 vd.m_verticalAttractionTimescale = 1000;
266
267 vd.m_flags = (VehicleFlag)0;
268 break;
269
270 case Vehicle.TYPE_SLED:
271 vd.m_linearFrictionTimescale = new Vector3(30, 1, 1000);
272 vd.m_angularFrictionTimescale = new Vector3(1000, 1000, 1000);
273 vd.m_linearMotorTimescale = 1000;
274 vd.m_linearMotorDecayTimescale = 120;
275 vd.m_angularMotorTimescale = 1000;
276 vd.m_angularMotorDecayTimescale = 120;
277 vd.m_VhoverHeight = 0;
278 vd.m_VhoverEfficiency = 1;
279 vd.m_VhoverTimescale = 10;
280 vd.m_VehicleBuoyancy = 0;
281 vd.m_linearDeflectionEfficiency = 1;
282 vd.m_linearDeflectionTimescale = 1;
283 vd.m_angularDeflectionEfficiency = 0;
284 vd.m_angularDeflectionTimescale = 1000;
285 vd.m_bankingEfficiency = 0;
286 vd.m_bankingMix = 1;
287 vd.m_bankingTimescale = 10;
288 vd.m_flags &=
289 ~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY |
290 VehicleFlag.HOVER_GLOBAL_HEIGHT | VehicleFlag.HOVER_UP_ONLY);
291 vd.m_flags |= (VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.LIMIT_ROLL_ONLY | VehicleFlag.LIMIT_MOTOR_UP);
292 break;
293 case Vehicle.TYPE_CAR:
294 vd.m_linearFrictionTimescale = new Vector3(100, 2, 1000);
295 vd.m_angularFrictionTimescale = new Vector3(1000, 1000, 1000);
296 vd.m_linearMotorTimescale = 1;
297 vd.m_linearMotorDecayTimescale = 60;
298 vd.m_angularMotorTimescale = 1;
299 vd.m_angularMotorDecayTimescale = 0.8f;
300 vd.m_VhoverHeight = 0;
301 vd.m_VhoverEfficiency = 0;
302 vd.m_VhoverTimescale = 1000;
303 vd.m_VehicleBuoyancy = 0;
304 vd.m_linearDeflectionEfficiency = 1;
305 vd.m_linearDeflectionTimescale = 2;
306 vd.m_angularDeflectionEfficiency = 0;
307 vd.m_angularDeflectionTimescale = 10;
308 vd.m_verticalAttractionEfficiency = 1f;
309 vd.m_verticalAttractionTimescale = 10f;
310 vd.m_bankingEfficiency = -0.2f;
311 vd.m_bankingMix = 1;
312 vd.m_bankingTimescale = 1;
313 vd.m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY | VehicleFlag.HOVER_GLOBAL_HEIGHT);
314 vd.m_flags |= (VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.LIMIT_ROLL_ONLY |
315 VehicleFlag.LIMIT_MOTOR_UP | VehicleFlag.HOVER_UP_ONLY);
316 break;
317 case Vehicle.TYPE_BOAT:
318 vd.m_linearFrictionTimescale = new Vector3(10, 3, 2);
319 vd.m_angularFrictionTimescale = new Vector3(10, 10, 10);
320 vd.m_linearMotorTimescale = 5;
321 vd.m_linearMotorDecayTimescale = 60;
322 vd.m_angularMotorTimescale = 4;
323 vd.m_angularMotorDecayTimescale = 4;
324 vd.m_VhoverHeight = 0;
325 vd.m_VhoverEfficiency = 0.5f;
326 vd.m_VhoverTimescale = 2;
327 vd.m_VehicleBuoyancy = 1;
328 vd.m_linearDeflectionEfficiency = 0.5f;
329 vd.m_linearDeflectionTimescale = 3;
330 vd.m_angularDeflectionEfficiency = 0.5f;
331 vd.m_angularDeflectionTimescale = 5;
332 vd.m_verticalAttractionEfficiency = 0.5f;
333 vd.m_verticalAttractionTimescale = 5f;
334 vd.m_bankingEfficiency = -0.3f;
335 vd.m_bankingMix = 0.8f;
336 vd.m_bankingTimescale = 1;
337 vd.m_flags &= ~(VehicleFlag.HOVER_TERRAIN_ONLY |
338 VehicleFlag.HOVER_GLOBAL_HEIGHT |
339 VehicleFlag.HOVER_UP_ONLY |
340 VehicleFlag.LIMIT_ROLL_ONLY);
341 vd.m_flags |= (VehicleFlag.NO_DEFLECTION_UP |
342 VehicleFlag.LIMIT_MOTOR_UP |
343 VehicleFlag.HOVER_WATER_ONLY);
344 break;
345 case Vehicle.TYPE_AIRPLANE:
346 vd.m_linearFrictionTimescale = new Vector3(200, 10, 5);
347 vd.m_angularFrictionTimescale = new Vector3(20, 20, 20);
348 vd.m_linearMotorTimescale = 2;
349 vd.m_linearMotorDecayTimescale = 60;
350 vd.m_angularMotorTimescale = 4;
351 vd.m_angularMotorDecayTimescale = 8;
352 vd.m_VhoverHeight = 0;
353 vd.m_VhoverEfficiency = 0.5f;
354 vd.m_VhoverTimescale = 1000;
355 vd.m_VehicleBuoyancy = 0;
356 vd.m_linearDeflectionEfficiency = 0.5f;
357 vd.m_linearDeflectionTimescale = 0.5f;
358 vd.m_angularDeflectionEfficiency = 1;
359 vd.m_angularDeflectionTimescale = 2;
360 vd.m_verticalAttractionEfficiency = 0.9f;
361 vd.m_verticalAttractionTimescale = 2f;
362 vd.m_bankingEfficiency = 1;
363 vd.m_bankingMix = 0.7f;
364 vd.m_bankingTimescale = 2;
365 vd.m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY |
366 VehicleFlag.HOVER_TERRAIN_ONLY |
367 VehicleFlag.HOVER_GLOBAL_HEIGHT |
368 VehicleFlag.HOVER_UP_ONLY |
369 VehicleFlag.NO_DEFLECTION_UP |
370 VehicleFlag.LIMIT_MOTOR_UP);
371 vd.m_flags |= (VehicleFlag.LIMIT_ROLL_ONLY);
372 break;
373 case Vehicle.TYPE_BALLOON:
374 vd.m_linearFrictionTimescale = new Vector3(5, 5, 5);
375 vd.m_angularFrictionTimescale = new Vector3(10, 10, 10);
376 vd.m_linearMotorTimescale = 5;
377 vd.m_linearMotorDecayTimescale = 60;
378 vd.m_angularMotorTimescale = 6;
379 vd.m_angularMotorDecayTimescale = 10;
380 vd.m_VhoverHeight = 5;
381 vd.m_VhoverEfficiency = 0.8f;
382 vd.m_VhoverTimescale = 10;
383 vd.m_VehicleBuoyancy = 1;
384 vd.m_linearDeflectionEfficiency = 0;
385 vd.m_linearDeflectionTimescale = 5;
386 vd.m_angularDeflectionEfficiency = 0;
387 vd.m_angularDeflectionTimescale = 5;
388 vd.m_verticalAttractionEfficiency = 0f;
389 vd.m_verticalAttractionTimescale = 1000f;
390 vd.m_bankingEfficiency = 0;
391 vd.m_bankingMix = 0.7f;
392 vd.m_bankingTimescale = 5;
393 vd.m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY |
394 VehicleFlag.HOVER_TERRAIN_ONLY |
395 VehicleFlag.HOVER_UP_ONLY |
396 VehicleFlag.NO_DEFLECTION_UP |
397 VehicleFlag.LIMIT_MOTOR_UP);
398 vd.m_flags |= (VehicleFlag.LIMIT_ROLL_ONLY |
399 VehicleFlag.HOVER_GLOBAL_HEIGHT);
400 break;
401 }
402 }
403 public void SetVehicle(PhysicsActor ph)
404 {
405 if (ph == null)
406 return;
407 ph.SetVehicle(vd);
408 }
409
410 private XmlTextWriter writer;
411
412 private void XWint(string name, int i)
413 {
414 writer.WriteElementString(name, i.ToString());
415 }
416
417 private void XWfloat(string name, float f)
418 {
419 writer.WriteElementString(name, f.ToString(Utils.EnUsCulture));
420 }
421
422 private void XWVector(string name, Vector3 vec)
423 {
424 writer.WriteStartElement(name);
425 writer.WriteElementString("X", vec.X.ToString(Utils.EnUsCulture));
426 writer.WriteElementString("Y", vec.Y.ToString(Utils.EnUsCulture));
427 writer.WriteElementString("Z", vec.Z.ToString(Utils.EnUsCulture));
428 writer.WriteEndElement();
429 }
430
431 private void XWQuat(string name, Quaternion quat)
432 {
433 writer.WriteStartElement(name);
434 writer.WriteElementString("X", quat.X.ToString(Utils.EnUsCulture));
435 writer.WriteElementString("Y", quat.Y.ToString(Utils.EnUsCulture));
436 writer.WriteElementString("Z", quat.Z.ToString(Utils.EnUsCulture));
437 writer.WriteElementString("W", quat.W.ToString(Utils.EnUsCulture));
438 writer.WriteEndElement();
439 }
440
441 public void ToXml2(XmlTextWriter twriter)
442 {
443 writer = twriter;
444 writer.WriteStartElement("Vehicle");
445
446 XWint("TYPE", (int)vd.m_type);
447 XWint("FLAGS", (int)vd.m_flags);
448
449 // Linear properties
450 XWVector("LMDIR", vd.m_linearMotorDirection);
451 XWVector("LMFTIME", vd.m_linearFrictionTimescale);
452 XWfloat("LMDTIME", vd.m_linearMotorDecayTimescale);
453 XWfloat("LMTIME", vd.m_linearMotorTimescale);
454 XWVector("LMOFF", vd.m_linearMotorOffset);
455
456 //Angular properties
457 XWVector("AMDIR", vd.m_angularMotorDirection);
458 XWfloat("AMTIME", vd.m_angularMotorTimescale);
459 XWfloat("AMDTIME", vd.m_angularMotorDecayTimescale);
460 XWVector("AMFTIME", vd.m_angularFrictionTimescale);
461
462 //Deflection properties
463 XWfloat("ADEFF", vd.m_angularDeflectionEfficiency);
464 XWfloat("ADTIME", vd.m_angularDeflectionTimescale);
465 XWfloat("LDEFF", vd.m_linearDeflectionEfficiency);
466 XWfloat("LDTIME", vd.m_linearDeflectionTimescale);
467
468 //Banking properties
469 XWfloat("BEFF", vd.m_bankingEfficiency);
470 XWfloat("BMIX", vd.m_bankingMix);
471 XWfloat("BTIME", vd.m_bankingTimescale);
472
473 //Hover and Buoyancy properties
474 XWfloat("HHEI", vd.m_VhoverHeight);
475 XWfloat("HEFF", vd.m_VhoverEfficiency);
476 XWfloat("HTIME", vd.m_VhoverTimescale);
477 XWfloat("VBUO", vd.m_VehicleBuoyancy);
478
479 //Attractor properties
480 XWfloat("VAEFF", vd.m_verticalAttractionEfficiency);
481 XWfloat("VATIME", vd.m_verticalAttractionTimescale);
482
483 XWQuat("REF_FRAME", vd.m_referenceFrame);
484
485 writer.WriteEndElement();
486 writer = null;
487 }
488
489
490
491 XmlTextReader reader;
492
493 private int XRint()
494 {
495 return reader.ReadElementContentAsInt();
496 }
497
498 private float XRfloat()
499 {
500 return reader.ReadElementContentAsFloat();
501 }
502
503 public Vector3 XRvector()
504 {
505 Vector3 vec;
506 reader.ReadStartElement();
507 vec.X = reader.ReadElementContentAsFloat();
508 vec.Y = reader.ReadElementContentAsFloat();
509 vec.Z = reader.ReadElementContentAsFloat();
510 reader.ReadEndElement();
511 return vec;
512 }
513
514 public Quaternion XRquat()
515 {
516 Quaternion q;
517 reader.ReadStartElement();
518 q.X = reader.ReadElementContentAsFloat();
519 q.Y = reader.ReadElementContentAsFloat();
520 q.Z = reader.ReadElementContentAsFloat();
521 q.W = reader.ReadElementContentAsFloat();
522 reader.ReadEndElement();
523 return q;
524 }
525
526 public static bool EReadProcessors(
527 Dictionary<string, Action> processors,
528 XmlTextReader xtr)
529 {
530 bool errors = false;
531
532 string nodeName = string.Empty;
533 while (xtr.NodeType != XmlNodeType.EndElement)
534 {
535 nodeName = xtr.Name;
536
537 // m_log.DebugFormat("[ExternalRepresentationUtils]: Processing: {0}", nodeName);
538
539 Action p = null;
540 if (processors.TryGetValue(xtr.Name, out p))
541 {
542 // m_log.DebugFormat("[ExternalRepresentationUtils]: Found {0} processor, nodeName);
543
544 try
545 {
546 p();
547 }
548 catch (Exception e)
549 {
550 errors = true;
551 if (xtr.NodeType == XmlNodeType.EndElement)
552 xtr.Read();
553 }
554 }
555 else
556 {
557 // m_log.DebugFormat("[LandDataSerializer]: caught unknown element {0}", nodeName);
558 xtr.ReadOuterXml(); // ignore
559 }
560 }
561
562 return errors;
563 }
564
565
566 public string ToXml2()
567 {
568 MemoryStream ms = new MemoryStream(512);
569 UTF8Encoding enc = new UTF8Encoding();
570 XmlTextWriter xwriter = new XmlTextWriter(ms, enc);
571 ToXml2(xwriter);
572 xwriter.Flush();
573 string s = ms.GetStreamString();
574 xwriter.Close();
575 return s;
576 }
577
578 public static SOPVehicle FromXml2(string text)
579 {
580 if (text == String.Empty)
581 return null;
582
583 UTF8Encoding enc = new UTF8Encoding();
584 MemoryStream ms = new MemoryStream(enc.GetBytes(text));
585 XmlTextReader xreader = new XmlTextReader(ms);
586
587 SOPVehicle v = new SOPVehicle();
588 bool error;
589
590 v.FromXml2(xreader, out error);
591
592 xreader.Close();
593
594 if (error)
595 {
596 v = null;
597 return null;
598 }
599 return v;
600 }
601
602 public static SOPVehicle FromXml2(XmlTextReader reader)
603 {
604 SOPVehicle vehicle = new SOPVehicle();
605
606 bool errors = false;
607
608 vehicle.FromXml2(reader, out errors);
609 if (errors)
610 return null;
611
612 return vehicle;
613 }
614
615 private void FromXml2(XmlTextReader _reader, out bool errors)
616 {
617 errors = false;
618 reader = _reader;
619
620 Dictionary<string, Action> m_VehicleXmlProcessors
621 = new Dictionary<string, Action>();
622
623 m_VehicleXmlProcessors.Add("TYPE", ProcessXR_type);
624 m_VehicleXmlProcessors.Add("FLAGS", ProcessXR_flags);
625
626 // Linear properties
627 m_VehicleXmlProcessors.Add("LMDIR", ProcessXR_linearMotorDirection);
628 m_VehicleXmlProcessors.Add("LMFTIME", ProcessXR_linearFrictionTimescale);
629 m_VehicleXmlProcessors.Add("LMDTIME", ProcessXR_linearMotorDecayTimescale);
630 m_VehicleXmlProcessors.Add("LMTIME", ProcessXR_linearMotorTimescale);
631 m_VehicleXmlProcessors.Add("LMOFF", ProcessXR_linearMotorOffset);
632
633 //Angular properties
634 m_VehicleXmlProcessors.Add("AMDIR", ProcessXR_angularMotorDirection);
635 m_VehicleXmlProcessors.Add("AMTIME", ProcessXR_angularMotorTimescale);
636 m_VehicleXmlProcessors.Add("AMDTIME", ProcessXR_angularMotorDecayTimescale);
637 m_VehicleXmlProcessors.Add("AMFTIME", ProcessXR_angularFrictionTimescale);
638
639 //Deflection properties
640 m_VehicleXmlProcessors.Add("ADEFF", ProcessXR_angularDeflectionEfficiency);
641 m_VehicleXmlProcessors.Add("ADTIME", ProcessXR_angularDeflectionTimescale);
642 m_VehicleXmlProcessors.Add("LDEFF", ProcessXR_linearDeflectionEfficiency);
643 m_VehicleXmlProcessors.Add("LDTIME", ProcessXR_linearDeflectionTimescale);
644
645 //Banking properties
646 m_VehicleXmlProcessors.Add("BEFF", ProcessXR_bankingEfficiency);
647 m_VehicleXmlProcessors.Add("BMIX", ProcessXR_bankingMix);
648 m_VehicleXmlProcessors.Add("BTIME", ProcessXR_bankingTimescale);
649
650 //Hover and Buoyancy properties
651 m_VehicleXmlProcessors.Add("HHEI", ProcessXR_VhoverHeight);
652 m_VehicleXmlProcessors.Add("HEFF", ProcessXR_VhoverEfficiency);
653 m_VehicleXmlProcessors.Add("HTIME", ProcessXR_VhoverTimescale);
654
655 m_VehicleXmlProcessors.Add("VBUO", ProcessXR_VehicleBuoyancy);
656
657 //Attractor properties
658 m_VehicleXmlProcessors.Add("VAEFF", ProcessXR_verticalAttractionEfficiency);
659 m_VehicleXmlProcessors.Add("VATIME", ProcessXR_verticalAttractionTimescale);
660
661 m_VehicleXmlProcessors.Add("REF_FRAME", ProcessXR_referenceFrame);
662
663 vd = new VehicleData();
664
665 reader.ReadStartElement("Vehicle", String.Empty);
666
667 errors = EReadProcessors(
668 m_VehicleXmlProcessors,
669 reader);
670
671 reader.ReadEndElement();
672 reader = null;
673 }
674
675 private void ProcessXR_type()
676 {
677 vd.m_type = (Vehicle)XRint();
678 }
679 private void ProcessXR_flags()
680 {
681 vd.m_flags = (VehicleFlag)XRint();
682 }
683 // Linear properties
684 private void ProcessXR_linearMotorDirection()
685 {
686 vd.m_linearMotorDirection = XRvector();
687 }
688
689 private void ProcessXR_linearFrictionTimescale()
690 {
691 vd.m_linearFrictionTimescale = XRvector();
692 }
693
694 private void ProcessXR_linearMotorDecayTimescale()
695 {
696 vd.m_linearMotorDecayTimescale = XRfloat();
697 }
698 private void ProcessXR_linearMotorTimescale()
699 {
700 vd.m_linearMotorTimescale = XRfloat();
701 }
702 private void ProcessXR_linearMotorOffset()
703 {
704 vd.m_linearMotorOffset = XRvector();
705 }
706
707
708 //Angular properties
709 private void ProcessXR_angularMotorDirection()
710 {
711 vd.m_angularMotorDirection = XRvector();
712 }
713 private void ProcessXR_angularMotorTimescale()
714 {
715 vd.m_angularMotorTimescale = XRfloat();
716 }
717 private void ProcessXR_angularMotorDecayTimescale()
718 {
719 vd.m_angularMotorDecayTimescale = XRfloat();
720 }
721 private void ProcessXR_angularFrictionTimescale()
722 {
723 vd.m_angularFrictionTimescale = XRvector();
724 }
725
726 //Deflection properties
727 private void ProcessXR_angularDeflectionEfficiency()
728 {
729 vd.m_angularDeflectionEfficiency = XRfloat();
730 }
731 private void ProcessXR_angularDeflectionTimescale()
732 {
733 vd.m_angularDeflectionTimescale = XRfloat();
734 }
735 private void ProcessXR_linearDeflectionEfficiency()
736 {
737 vd.m_linearDeflectionEfficiency = XRfloat();
738 }
739 private void ProcessXR_linearDeflectionTimescale()
740 {
741 vd.m_linearDeflectionTimescale = XRfloat();
742 }
743
744 //Banking properties
745 private void ProcessXR_bankingEfficiency()
746 {
747 vd.m_bankingEfficiency = XRfloat();
748 }
749 private void ProcessXR_bankingMix()
750 {
751 vd.m_bankingMix = XRfloat();
752 }
753 private void ProcessXR_bankingTimescale()
754 {
755 vd.m_bankingTimescale = XRfloat();
756 }
757
758 //Hover and Buoyancy properties
759 private void ProcessXR_VhoverHeight()
760 {
761 vd.m_VhoverHeight = XRfloat();
762 }
763 private void ProcessXR_VhoverEfficiency()
764 {
765 vd.m_VhoverEfficiency = XRfloat();
766 }
767 private void ProcessXR_VhoverTimescale()
768 {
769 vd.m_VhoverTimescale = XRfloat();
770 }
771
772 private void ProcessXR_VehicleBuoyancy()
773 {
774 vd.m_VehicleBuoyancy = XRfloat();
775 }
776
777 //Attractor properties
778 private void ProcessXR_verticalAttractionEfficiency()
779 {
780 vd.m_verticalAttractionEfficiency = XRfloat();
781 }
782 private void ProcessXR_verticalAttractionTimescale()
783 {
784 vd.m_verticalAttractionTimescale = XRfloat();
785 }
786
787 private void ProcessXR_referenceFrame()
788 {
789 vd.m_referenceFrame = XRquat();
790 }
791 }
792}
diff --git a/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs b/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs
index 9ff8467..9776a82 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)
@@ -851,6 +848,24 @@ namespace OpenSim.Region.Framework.Scenes
851 } 848 }
852 849
853 /// <summary> 850 /// <summary>
851 /// Move an item within the agent's inventory, and leave a copy (used in making a new outfit)
852 /// </summary>
853 public void MoveInventoryItemsLeaveCopy(IClientAPI remoteClient, List<InventoryItemBase> items, UUID destfolder)
854 {
855 List<InventoryItemBase> moveitems = new List<InventoryItemBase>();
856 foreach (InventoryItemBase b in items)
857 {
858 CopyInventoryItem(remoteClient, 0, remoteClient.AgentId, b.ID, b.Folder, null);
859 InventoryItemBase n = InventoryService.GetItem(b);
860 n.Folder = destfolder;
861 moveitems.Add(n);
862 remoteClient.SendInventoryItemCreateUpdate(n, 0);
863 }
864
865 MoveInventoryItem(remoteClient, moveitems);
866 }
867
868 /// <summary>
854 /// Move an item within the agent's inventory. 869 /// Move an item within the agent's inventory.
855 /// </summary> 870 /// </summary>
856 /// <param name="remoteClient"></param> 871 /// <param name="remoteClient"></param>
@@ -1193,6 +1208,10 @@ namespace OpenSim.Region.Framework.Scenes
1193 { 1208 {
1194 SceneObjectPart part = GetSceneObjectPart(primLocalId); 1209 SceneObjectPart part = GetSceneObjectPart(primLocalId);
1195 1210
1211 // Can't move a null item
1212 if (itemId == UUID.Zero)
1213 return;
1214
1196 if (null == part) 1215 if (null == part)
1197 { 1216 {
1198 m_log.WarnFormat( 1217 m_log.WarnFormat(
@@ -1297,21 +1316,28 @@ namespace OpenSim.Region.Framework.Scenes
1297 return; 1316 return;
1298 } 1317 }
1299 1318
1300 if (part.OwnerID != destPart.OwnerID) 1319 // Can't transfer this
1320 //
1321 if (part.OwnerID != destPart.OwnerID && (srcTaskItem.CurrentPermissions & (uint)PermissionMask.Transfer) == 0)
1322 return;
1323
1324 bool overrideNoMod = false;
1325 if ((part.GetEffectiveObjectFlags() & (uint)PrimFlags.AllowInventoryDrop) != 0)
1326 overrideNoMod = true;
1327
1328 if (part.OwnerID != destPart.OwnerID && (destPart.GetEffectiveObjectFlags() & (uint)PrimFlags.AllowInventoryDrop) == 0)
1301 { 1329 {
1302 // Source must have transfer permissions 1330 // object cannot copy items to an object owned by a different owner
1303 if ((srcTaskItem.CurrentPermissions & (uint)PermissionMask.Transfer) == 0) 1331 // unless llAllowInventoryDrop has been called
1304 return;
1305 1332
1306 // Object cannot copy items to an object owned by a different owner 1333 return;
1307 // unless llAllowInventoryDrop has been called on the destination
1308 if ((destPart.GetEffectiveObjectFlags() & (uint)PrimFlags.AllowInventoryDrop) == 0)
1309 return;
1310 } 1334 }
1311 1335
1312 // must have both move and modify permission to put an item in an object 1336 // must have both move and modify permission to put an item in an object
1313 if ((part.OwnerMask & ((uint)PermissionMask.Move | (uint)PermissionMask.Modify)) == 0) 1337 if (((part.OwnerMask & (uint)PermissionMask.Modify) == 0) && (!overrideNoMod))
1338 {
1314 return; 1339 return;
1340 }
1315 1341
1316 TaskInventoryItem destTaskItem = new TaskInventoryItem(); 1342 TaskInventoryItem destTaskItem = new TaskInventoryItem();
1317 1343
@@ -1367,6 +1393,14 @@ namespace OpenSim.Region.Framework.Scenes
1367 1393
1368 public UUID MoveTaskInventoryItems(UUID destID, string category, SceneObjectPart host, List<UUID> items) 1394 public UUID MoveTaskInventoryItems(UUID destID, string category, SceneObjectPart host, List<UUID> items)
1369 { 1395 {
1396 SceneObjectPart destPart = GetSceneObjectPart(destID);
1397 if (destPart != null) // Move into a prim
1398 {
1399 foreach(UUID itemID in items)
1400 MoveTaskInventoryItem(destID, host, itemID);
1401 return destID; // Prim folder ID == prim ID
1402 }
1403
1370 InventoryFolderBase rootFolder = InventoryService.GetRootFolder(destID); 1404 InventoryFolderBase rootFolder = InventoryService.GetRootFolder(destID);
1371 1405
1372 UUID newFolderID = UUID.Random(); 1406 UUID newFolderID = UUID.Random();
@@ -1549,12 +1583,12 @@ namespace OpenSim.Region.Framework.Scenes
1549 AgentTransactionsModule.HandleTaskItemUpdateFromTransaction( 1583 AgentTransactionsModule.HandleTaskItemUpdateFromTransaction(
1550 remoteClient, part, transactionID, currentItem); 1584 remoteClient, part, transactionID, currentItem);
1551 1585
1552 if ((InventoryType)itemInfo.InvType == InventoryType.Notecard) 1586// if ((InventoryType)itemInfo.InvType == InventoryType.Notecard)
1553 remoteClient.SendAgentAlertMessage("Notecard saved", false); 1587// remoteClient.SendAgentAlertMessage("Notecard saved", false);
1554 else if ((InventoryType)itemInfo.InvType == InventoryType.LSL) 1588// else if ((InventoryType)itemInfo.InvType == InventoryType.LSL)
1555 remoteClient.SendAgentAlertMessage("Script saved", false); 1589// remoteClient.SendAgentAlertMessage("Script saved", false);
1556 else 1590// else
1557 remoteClient.SendAgentAlertMessage("Item saved", false); 1591// remoteClient.SendAgentAlertMessage("Item saved", false);
1558 } 1592 }
1559 1593
1560 // Base ALWAYS has move 1594 // Base ALWAYS has move
@@ -1737,7 +1771,7 @@ namespace OpenSim.Region.Framework.Scenes
1737 } 1771 }
1738 1772
1739 AssetBase asset = CreateAsset(itemBase.Name, itemBase.Description, (sbyte)itemBase.AssetType, 1773 AssetBase asset = CreateAsset(itemBase.Name, itemBase.Description, (sbyte)itemBase.AssetType,
1740 Encoding.ASCII.GetBytes("default\n{\n state_entry()\n {\n llSay(0, \"Script running\");\n }\n}"), 1774 Encoding.ASCII.GetBytes("default\n{\n state_entry()\n {\n llSay(0, \"Script running\");\n }\n\n touch_start(integer num)\n {\n }\n}"),
1741 agentID); 1775 agentID);
1742 AssetService.Store(asset); 1776 AssetService.Store(asset);
1743 1777
@@ -1893,23 +1927,32 @@ namespace OpenSim.Region.Framework.Scenes
1893 // build a list of eligible objects 1927 // build a list of eligible objects
1894 List<uint> deleteIDs = new List<uint>(); 1928 List<uint> deleteIDs = new List<uint>();
1895 List<SceneObjectGroup> deleteGroups = new List<SceneObjectGroup>(); 1929 List<SceneObjectGroup> deleteGroups = new List<SceneObjectGroup>();
1896 1930 List<SceneObjectGroup> takeGroups = new List<SceneObjectGroup>();
1897 // Start with true for both, then remove the flags if objects
1898 // that we can't derez are part of the selection
1899 bool permissionToTake = true;
1900 bool permissionToTakeCopy = true;
1901 bool permissionToDelete = true;
1902 1931
1903 foreach (uint localID in localIDs) 1932 foreach (uint localID in localIDs)
1904 { 1933 {
1934 // Start with true for both, then remove the flags if objects
1935 // that we can't derez are part of the selection
1936 bool permissionToTake = true;
1937 bool permissionToTakeCopy = true;
1938 bool permissionToDelete = true;
1939
1905 // Invalid id 1940 // Invalid id
1906 SceneObjectPart part = GetSceneObjectPart(localID); 1941 SceneObjectPart part = GetSceneObjectPart(localID);
1907 if (part == null) 1942 if (part == null)
1943 {
1944 //Client still thinks the object exists, kill it
1945 deleteIDs.Add(localID);
1908 continue; 1946 continue;
1947 }
1909 1948
1910 // Already deleted by someone else 1949 // Already deleted by someone else
1911 if (part.ParentGroup.IsDeleted) 1950 if (part.ParentGroup.IsDeleted)
1951 {
1952 //Client still thinks the object exists, kill it
1953 deleteIDs.Add(localID);
1912 continue; 1954 continue;
1955 }
1913 1956
1914 // Can't delete child prims 1957 // Can't delete child prims
1915 if (part != part.ParentGroup.RootPart) 1958 if (part != part.ParentGroup.RootPart)
@@ -1917,9 +1960,6 @@ namespace OpenSim.Region.Framework.Scenes
1917 1960
1918 SceneObjectGroup grp = part.ParentGroup; 1961 SceneObjectGroup grp = part.ParentGroup;
1919 1962
1920 deleteIDs.Add(localID);
1921 deleteGroups.Add(grp);
1922
1923 if (remoteClient == null) 1963 if (remoteClient == null)
1924 { 1964 {
1925 // Autoreturn has a null client. Nothing else does. So 1965 // Autoreturn has a null client. Nothing else does. So
@@ -1936,81 +1976,193 @@ namespace OpenSim.Region.Framework.Scenes
1936 } 1976 }
1937 else 1977 else
1938 { 1978 {
1939 if (!Permissions.CanTakeCopyObject(grp.UUID, remoteClient.AgentId)) 1979 if (action == DeRezAction.TakeCopy)
1980 {
1981 if (!Permissions.CanTakeCopyObject(grp.UUID, remoteClient.AgentId))
1982 permissionToTakeCopy = false;
1983 }
1984 else
1985 {
1940 permissionToTakeCopy = false; 1986 permissionToTakeCopy = false;
1941 1987 }
1942 if (!Permissions.CanTakeObject(grp.UUID, remoteClient.AgentId)) 1988 if (!Permissions.CanTakeObject(grp.UUID, remoteClient.AgentId))
1943 permissionToTake = false; 1989 permissionToTake = false;
1944 1990
1945 if (!Permissions.CanDeleteObject(grp.UUID, remoteClient.AgentId)) 1991 if (!Permissions.CanDeleteObject(grp.UUID, remoteClient.AgentId))
1946 permissionToDelete = false; 1992 permissionToDelete = false;
1947 } 1993 }
1948 }
1949 1994
1950 // Handle god perms 1995 // Handle god perms
1951 if ((remoteClient != null) && Permissions.IsGod(remoteClient.AgentId)) 1996 if ((remoteClient != null) && Permissions.IsGod(remoteClient.AgentId))
1952 { 1997 {
1953 permissionToTake = true; 1998 permissionToTake = true;
1954 permissionToTakeCopy = true; 1999 permissionToTakeCopy = true;
1955 permissionToDelete = true; 2000 permissionToDelete = true;
1956 } 2001 }
1957 2002
1958 // If we're re-saving, we don't even want to delete 2003 // If we're re-saving, we don't even want to delete
1959 if (action == DeRezAction.SaveToExistingUserInventoryItem) 2004 if (action == DeRezAction.SaveToExistingUserInventoryItem)
1960 permissionToDelete = false; 2005 permissionToDelete = false;
1961 2006
1962 // if we want to take a copy, we also don't want to delete 2007 // if we want to take a copy, we also don't want to delete
1963 // Note: after this point, the permissionToTakeCopy flag 2008 // Note: after this point, the permissionToTakeCopy flag
1964 // becomes irrelevant. It already includes the permissionToTake 2009 // becomes irrelevant. It already includes the permissionToTake
1965 // permission and after excluding no copy items here, we can 2010 // permission and after excluding no copy items here, we can
1966 // just use that. 2011 // just use that.
1967 if (action == DeRezAction.TakeCopy) 2012 if (action == DeRezAction.TakeCopy)
1968 { 2013 {
1969 // If we don't have permission, stop right here 2014 // If we don't have permission, stop right here
1970 if (!permissionToTakeCopy) 2015 if (!permissionToTakeCopy)
1971 return; 2016 return;
1972 2017
1973 permissionToTake = true; 2018 permissionToTake = true;
1974 // Don't delete 2019 // Don't delete
1975 permissionToDelete = false; 2020 permissionToDelete = false;
1976 } 2021 }
1977 2022
1978 if (action == DeRezAction.Return) 2023 if (action == DeRezAction.Return)
1979 {
1980 if (remoteClient != null)
1981 { 2024 {
1982 if (Permissions.CanReturnObjects( 2025 if (remoteClient != null)
1983 null,
1984 remoteClient.AgentId,
1985 deleteGroups))
1986 { 2026 {
1987 permissionToTake = true; 2027 if (Permissions.CanReturnObjects(
1988 permissionToDelete = true; 2028 null,
1989 2029 remoteClient.AgentId,
1990 foreach (SceneObjectGroup g in deleteGroups) 2030 deleteGroups))
1991 { 2031 {
1992 AddReturn(g.OwnerID == g.GroupID ? g.LastOwnerID : g.OwnerID, g.Name, g.AbsolutePosition, "parcel owner return"); 2032 permissionToTake = true;
2033 permissionToDelete = true;
2034
2035 AddReturn(grp.OwnerID == grp.GroupID ? grp.LastOwnerID : grp.OwnerID, grp.Name, grp.AbsolutePosition, "parcel owner return");
1993 } 2036 }
1994 } 2037 }
2038 else // Auto return passes through here with null agent
2039 {
2040 permissionToTake = true;
2041 permissionToDelete = true;
2042 }
1995 } 2043 }
1996 else // Auto return passes through here with null agent 2044
2045 if (permissionToTake && (!permissionToDelete))
2046 takeGroups.Add(grp);
2047
2048 if (permissionToDelete)
1997 { 2049 {
1998 permissionToTake = true; 2050 if (permissionToTake)
1999 permissionToDelete = true; 2051 deleteGroups.Add(grp);
2052 deleteIDs.Add(grp.LocalId);
2000 } 2053 }
2001 } 2054 }
2002 2055
2003 if (permissionToTake && (action != DeRezAction.Delete || this.m_useTrashOnDelete)) 2056 SendKillObject(deleteIDs);
2057
2058 if (deleteGroups.Count > 0)
2004 { 2059 {
2060 foreach (SceneObjectGroup g in deleteGroups)
2061 deleteIDs.Remove(g.LocalId);
2062
2005 m_asyncSceneObjectDeleter.DeleteToInventory( 2063 m_asyncSceneObjectDeleter.DeleteToInventory(
2006 action, destinationID, deleteGroups, remoteClient, 2064 action, destinationID, deleteGroups, remoteClient,
2007 permissionToDelete); 2065 true);
2008 } 2066 }
2009 else if (permissionToDelete) 2067 if (takeGroups.Count > 0)
2068 {
2069 m_asyncSceneObjectDeleter.DeleteToInventory(
2070 action, destinationID, takeGroups, remoteClient,
2071 false);
2072 }
2073 if (deleteIDs.Count > 0)
2010 { 2074 {
2011 foreach (SceneObjectGroup g in deleteGroups) 2075 foreach (SceneObjectGroup g in deleteGroups)
2012 DeleteSceneObject(g, false); 2076 DeleteSceneObject(g, true);
2077 }
2078 }
2079
2080 public UUID attachObjectAssetStore(IClientAPI remoteClient, SceneObjectGroup grp, UUID AgentId, out UUID itemID)
2081 {
2082 itemID = UUID.Zero;
2083 if (grp != null)
2084 {
2085 Vector3 inventoryStoredPosition = new Vector3
2086 (((grp.AbsolutePosition.X > (int)Constants.RegionSize)
2087 ? 250
2088 : grp.AbsolutePosition.X)
2089 ,
2090 (grp.AbsolutePosition.X > (int)Constants.RegionSize)
2091 ? 250
2092 : grp.AbsolutePosition.X,
2093 grp.AbsolutePosition.Z);
2094
2095 Vector3 originalPosition = grp.AbsolutePosition;
2096
2097 grp.AbsolutePosition = inventoryStoredPosition;
2098
2099 string sceneObjectXml = SceneObjectSerializer.ToOriginalXmlFormat(grp);
2100
2101 grp.AbsolutePosition = originalPosition;
2102
2103 AssetBase asset = CreateAsset(
2104 grp.GetPartName(grp.LocalId),
2105 grp.GetPartDescription(grp.LocalId),
2106 (sbyte)AssetType.Object,
2107 Utils.StringToBytes(sceneObjectXml),
2108 remoteClient.AgentId);
2109 AssetService.Store(asset);
2110
2111 InventoryItemBase item = new InventoryItemBase();
2112 item.CreatorId = grp.RootPart.CreatorID.ToString();
2113 item.CreatorData = grp.RootPart.CreatorData;
2114 item.Owner = remoteClient.AgentId;
2115 item.ID = UUID.Random();
2116 item.AssetID = asset.FullID;
2117 item.Description = asset.Description;
2118 item.Name = asset.Name;
2119 item.AssetType = asset.Type;
2120 item.InvType = (int)InventoryType.Object;
2121
2122 InventoryFolderBase folder = InventoryService.GetFolderForType(remoteClient.AgentId, AssetType.Object);
2123 if (folder != null)
2124 item.Folder = folder.ID;
2125 else // oopsies
2126 item.Folder = UUID.Zero;
2127
2128 // Set up base perms properly
2129 uint permsBase = (uint)(PermissionMask.Move | PermissionMask.Copy | PermissionMask.Transfer | PermissionMask.Modify);
2130 permsBase &= grp.RootPart.BaseMask;
2131 permsBase |= (uint)PermissionMask.Move;
2132
2133 // Make sure we don't lock it
2134 grp.RootPart.NextOwnerMask |= (uint)PermissionMask.Move;
2135
2136 if ((remoteClient.AgentId != grp.RootPart.OwnerID) && Permissions.PropagatePermissions())
2137 {
2138 item.BasePermissions = permsBase & grp.RootPart.NextOwnerMask;
2139 item.CurrentPermissions = permsBase & grp.RootPart.NextOwnerMask;
2140 item.NextPermissions = permsBase & grp.RootPart.NextOwnerMask;
2141 item.EveryOnePermissions = permsBase & grp.RootPart.EveryoneMask & grp.RootPart.NextOwnerMask;
2142 item.GroupPermissions = permsBase & grp.RootPart.GroupMask & grp.RootPart.NextOwnerMask;
2143 }
2144 else
2145 {
2146 item.BasePermissions = permsBase;
2147 item.CurrentPermissions = permsBase & grp.RootPart.OwnerMask;
2148 item.NextPermissions = permsBase & grp.RootPart.NextOwnerMask;
2149 item.EveryOnePermissions = permsBase & grp.RootPart.EveryoneMask;
2150 item.GroupPermissions = permsBase & grp.RootPart.GroupMask;
2151 }
2152 item.CreationDate = Util.UnixTimeSinceEpoch();
2153
2154 // sets itemID so client can show item as 'attached' in inventory
2155 grp.FromItemID = item.ID;
2156
2157 if (AddInventoryItem(item))
2158 remoteClient.SendInventoryItemCreateUpdate(item, 0);
2159 else
2160 m_dialogModule.SendAlertToUser(remoteClient, "Operation failed");
2161
2162 itemID = item.ID;
2163 return item.AssetID;
2013 } 2164 }
2165 return UUID.Zero;
2014 } 2166 }
2015 2167
2016 /// <summary> 2168 /// <summary>
@@ -2139,6 +2291,9 @@ namespace OpenSim.Region.Framework.Scenes
2139 2291
2140 public void SetScriptRunning(IClientAPI controllingClient, UUID objectID, UUID itemID, bool running) 2292 public void SetScriptRunning(IClientAPI controllingClient, UUID objectID, UUID itemID, bool running)
2141 { 2293 {
2294 if (!Permissions.CanEditScript(itemID, objectID, controllingClient.AgentId))
2295 return;
2296
2142 SceneObjectPart part = GetSceneObjectPart(objectID); 2297 SceneObjectPart part = GetSceneObjectPart(objectID);
2143 if (part == null) 2298 if (part == null)
2144 return; 2299 return;
@@ -2209,7 +2364,10 @@ namespace OpenSim.Region.Framework.Scenes
2209 } 2364 }
2210 else 2365 else
2211 { 2366 {
2212 if (!Permissions.CanEditObject(sog.UUID, remoteClient.AgentId)) 2367 if (!Permissions.IsGod(remoteClient.AgentId) && sog.OwnerID != remoteClient.AgentId)
2368 continue;
2369
2370 if (!Permissions.CanTransferObject(sog.UUID, groupID))
2213 continue; 2371 continue;
2214 2372
2215 if (sog.GroupID != groupID) 2373 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 25223b9..eae8b8e 100644
--- a/OpenSim/Region/Framework/Scenes/Scene.cs
+++ b/OpenSim/Region/Framework/Scenes/Scene.cs
@@ -127,6 +127,7 @@ namespace OpenSim.Region.Framework.Scenes
127 // TODO: need to figure out how allow client agents but deny 127 // TODO: need to figure out how allow client agents but deny
128 // root agents when ACL denies access to root agent 128 // root agents when ACL denies access to root agent
129 public bool m_strictAccessControl = true; 129 public bool m_strictAccessControl = true;
130 public bool m_seeIntoBannedRegion = false;
130 public int MaxUndoCount = 5; 131 public int MaxUndoCount = 5;
131 // Using this for RegionReady module to prevent LoginsDisabled from changing under our feet; 132 // Using this for RegionReady module to prevent LoginsDisabled from changing under our feet;
132 public bool LoginLock = false; 133 public bool LoginLock = false;
@@ -142,12 +143,14 @@ namespace OpenSim.Region.Framework.Scenes
142 143
143 protected int m_splitRegionID; 144 protected int m_splitRegionID;
144 protected Timer m_restartWaitTimer = new Timer(); 145 protected Timer m_restartWaitTimer = new Timer();
146 protected Timer m_timerWatchdog = new Timer();
145 protected List<RegionInfo> m_regionRestartNotifyList = new List<RegionInfo>(); 147 protected List<RegionInfo> m_regionRestartNotifyList = new List<RegionInfo>();
146 protected List<RegionInfo> m_neighbours = new List<RegionInfo>(); 148 protected List<RegionInfo> m_neighbours = new List<RegionInfo>();
147 protected string m_simulatorVersion = "OpenSimulator Server"; 149 protected string m_simulatorVersion = "OpenSimulator Server";
148 protected ModuleLoader m_moduleLoader; 150 protected ModuleLoader m_moduleLoader;
149 protected AgentCircuitManager m_authenticateHandler; 151 protected AgentCircuitManager m_authenticateHandler;
150 protected SceneCommunicationService m_sceneGridService; 152 protected SceneCommunicationService m_sceneGridService;
153 protected ISnmpModule m_snmpService = null;
151 154
152 protected ISimulationDataService m_SimulationDataService; 155 protected ISimulationDataService m_SimulationDataService;
153 protected IEstateDataService m_EstateDataService; 156 protected IEstateDataService m_EstateDataService;
@@ -209,7 +212,7 @@ namespace OpenSim.Region.Framework.Scenes
209 private int m_update_events = 1; 212 private int m_update_events = 1;
210 private int m_update_backup = 200; 213 private int m_update_backup = 200;
211 private int m_update_terrain = 50; 214 private int m_update_terrain = 50;
212// private int m_update_land = 1; 215 private int m_update_land = 10;
213 private int m_update_coarse_locations = 50; 216 private int m_update_coarse_locations = 50;
214 217
215 private int agentMS; 218 private int agentMS;
@@ -229,6 +232,7 @@ namespace OpenSim.Region.Framework.Scenes
229 /// </summary> 232 /// </summary>
230 private int m_lastFrameTick; 233 private int m_lastFrameTick;
231 234
235 public bool CombineRegions = false;
232 /// <summary> 236 /// <summary>
233 /// Tick at which the last maintenance run occurred. 237 /// Tick at which the last maintenance run occurred.
234 /// </summary> 238 /// </summary>
@@ -259,6 +263,11 @@ namespace OpenSim.Region.Framework.Scenes
259 /// </summary> 263 /// </summary>
260 private int m_LastLogin; 264 private int m_LastLogin;
261 265
266 private int m_lastIncoming;
267 private int m_lastOutgoing;
268 private int m_hbRestarts = 0;
269
270
262 /// <summary> 271 /// <summary>
263 /// Thread that runs the scene loop. 272 /// Thread that runs the scene loop.
264 /// </summary> 273 /// </summary>
@@ -274,7 +283,7 @@ namespace OpenSim.Region.Framework.Scenes
274 private volatile bool m_shuttingDown; 283 private volatile bool m_shuttingDown;
275 284
276// private int m_lastUpdate; 285// private int m_lastUpdate;
277// private bool m_firstHeartbeat = true; 286 private bool m_firstHeartbeat = true;
278 287
279 private UpdatePrioritizationSchemes m_priorityScheme = UpdatePrioritizationSchemes.Time; 288 private UpdatePrioritizationSchemes m_priorityScheme = UpdatePrioritizationSchemes.Time;
280 private bool m_reprioritizationEnabled = true; 289 private bool m_reprioritizationEnabled = true;
@@ -319,6 +328,19 @@ namespace OpenSim.Region.Framework.Scenes
319 get { return m_sceneGridService; } 328 get { return m_sceneGridService; }
320 } 329 }
321 330
331 public ISnmpModule SnmpService
332 {
333 get
334 {
335 if (m_snmpService == null)
336 {
337 m_snmpService = RequestModuleInterface<ISnmpModule>();
338 }
339
340 return m_snmpService;
341 }
342 }
343
322 public ISimulationDataService SimulationDataService 344 public ISimulationDataService SimulationDataService
323 { 345 {
324 get 346 get
@@ -617,7 +639,9 @@ namespace OpenSim.Region.Framework.Scenes
617 m_sceneGridService = sceneGridService; 639 m_sceneGridService = sceneGridService;
618 m_SimulationDataService = simDataService; 640 m_SimulationDataService = simDataService;
619 m_EstateDataService = estateDataService; 641 m_EstateDataService = estateDataService;
620 m_regionHandle = RegionInfo.RegionHandle; 642 m_regionHandle = m_regInfo.RegionHandle;
643 m_lastIncoming = 0;
644 m_lastOutgoing = 0;
621 645
622 m_asyncSceneObjectDeleter = new AsyncSceneObjectGroupDeleter(this); 646 m_asyncSceneObjectDeleter = new AsyncSceneObjectGroupDeleter(this);
623 m_asyncSceneObjectDeleter.Enabled = true; 647 m_asyncSceneObjectDeleter.Enabled = true;
@@ -698,120 +722,129 @@ namespace OpenSim.Region.Framework.Scenes
698 722
699 // Region config overrides global config 723 // Region config overrides global config
700 // 724 //
701 if (m_config.Configs["Startup"] != null) 725 try
702 { 726 {
703 IConfig startupConfig = m_config.Configs["Startup"]; 727 if (m_config.Configs["Startup"] != null)
704
705 m_defaultDrawDistance = startupConfig.GetFloat("DefaultDrawDistance", m_defaultDrawDistance);
706 m_useBackup = startupConfig.GetBoolean("UseSceneBackup", m_useBackup);
707 if (!m_useBackup)
708 m_log.InfoFormat("[SCENE]: Backup has been disabled for {0}", RegionInfo.RegionName);
709
710 //Animation states
711 m_useFlySlow = startupConfig.GetBoolean("enableflyslow", false);
712
713 PhysicalPrims = startupConfig.GetBoolean("physical_prim", PhysicalPrims);
714 CollidablePrims = startupConfig.GetBoolean("collidable_prim", CollidablePrims);
715
716 m_maxNonphys = startupConfig.GetFloat("NonphysicalPrimMax", m_maxNonphys);
717 if (RegionInfo.NonphysPrimMax > 0)
718 {
719 m_maxNonphys = RegionInfo.NonphysPrimMax;
720 }
721
722 m_maxPhys = startupConfig.GetFloat("PhysicalPrimMax", m_maxPhys);
723
724 if (RegionInfo.PhysPrimMax > 0)
725 { 728 {
726 m_maxPhys = RegionInfo.PhysPrimMax; 729 IConfig startupConfig = m_config.Configs["Startup"];
727 }
728 730
729 // Here, if clamping is requested in either global or 731 m_defaultDrawDistance = startupConfig.GetFloat("DefaultDrawDistance",m_defaultDrawDistance);
730 // local config, it will be used 732 m_useBackup = startupConfig.GetBoolean("UseSceneBackup", m_useBackup);
731 // 733 if (!m_useBackup)
732 m_clampPrimSize = startupConfig.GetBoolean("ClampPrimSize", m_clampPrimSize); 734 m_log.InfoFormat("[SCENE]: Backup has been disabled for {0}", RegionInfo.RegionName);
733 if (RegionInfo.ClampPrimSize) 735
734 { 736 //Animation states
735 m_clampPrimSize = true; 737 m_useFlySlow = startupConfig.GetBoolean("enableflyslow", false);
736 }
737 738
738 m_useTrashOnDelete = startupConfig.GetBoolean("UseTrashOnDelete", m_useTrashOnDelete); 739 PhysicalPrims = startupConfig.GetBoolean("physical_prim", true);
739 m_trustBinaries = startupConfig.GetBoolean("TrustBinaries", m_trustBinaries); 740 CollidablePrims = startupConfig.GetBoolean("collidable_prim", true);
740 m_allowScriptCrossings = startupConfig.GetBoolean("AllowScriptCrossing", m_allowScriptCrossings);
741 m_dontPersistBefore =
742 startupConfig.GetLong("MinimumTimeBeforePersistenceConsidered", DEFAULT_MIN_TIME_FOR_PERSISTENCE);
743 m_dontPersistBefore *= 10000000;
744 m_persistAfter =
745 startupConfig.GetLong("MaximumTimeBeforePersistenceConsidered", DEFAULT_MAX_TIME_FOR_PERSISTENCE);
746 m_persistAfter *= 10000000;
747 741
748 m_defaultScriptEngine = startupConfig.GetString("DefaultScriptEngine", "XEngine"); 742 m_maxNonphys = startupConfig.GetFloat("NonphysicalPrimMax", m_maxNonphys);
743 if (RegionInfo.NonphysPrimMax > 0)
744 {
745 m_maxNonphys = RegionInfo.NonphysPrimMax;
746 }
749 747
750 SpawnPointRouting = startupConfig.GetString("SpawnPointRouting", "closest"); 748 m_maxPhys = startupConfig.GetFloat("PhysicalPrimMax", m_maxPhys);
751 TelehubAllowLandmarks = startupConfig.GetBoolean("TelehubAllowLandmark", false);
752 749
753 IConfig packetConfig = m_config.Configs["PacketPool"]; 750 if (RegionInfo.PhysPrimMax > 0)
754 if (packetConfig != null) 751 {
755 { 752 m_maxPhys = RegionInfo.PhysPrimMax;
756 PacketPool.Instance.RecyclePackets = packetConfig.GetBoolean("RecyclePackets", true); 753 }
757 PacketPool.Instance.RecycleDataBlocks = packetConfig.GetBoolean("RecycleDataBlocks", true);
758 }
759 754
760 m_strictAccessControl = startupConfig.GetBoolean("StrictAccessControl", m_strictAccessControl); 755 SpawnPointRouting = startupConfig.GetString("SpawnPointRouting", "closest");
756 TelehubAllowLandmarks = startupConfig.GetBoolean("TelehubAllowLandmark", false);
761 757
762 m_generateMaptiles = startupConfig.GetBoolean("GenerateMaptiles", true); 758 // Here, if clamping is requested in either global or
763 if (m_generateMaptiles) 759 // local config, it will be used
764 { 760 //
765 int maptileRefresh = startupConfig.GetInt("MaptileRefresh", 0); 761 m_clampPrimSize = startupConfig.GetBoolean("ClampPrimSize", m_clampPrimSize);
766 if (maptileRefresh != 0) 762 if (RegionInfo.ClampPrimSize)
767 { 763 {
768 m_mapGenerationTimer.Interval = maptileRefresh * 1000; 764 m_clampPrimSize = true;
769 m_mapGenerationTimer.Elapsed += RegenerateMaptileAndReregister;
770 m_mapGenerationTimer.AutoReset = true;
771 m_mapGenerationTimer.Start();
772 } 765 }
773 }
774 else
775 {
776 string tile = startupConfig.GetString("MaptileStaticUUID", UUID.Zero.ToString());
777 UUID tileID;
778 766
779 if (UUID.TryParse(tile, out tileID)) 767 m_useTrashOnDelete = startupConfig.GetBoolean("UseTrashOnDelete",m_useTrashOnDelete);
768 m_trustBinaries = startupConfig.GetBoolean("TrustBinaries", m_trustBinaries);
769 m_allowScriptCrossings = startupConfig.GetBoolean("AllowScriptCrossing", m_allowScriptCrossings);
770 m_dontPersistBefore =
771 startupConfig.GetLong("MinimumTimeBeforePersistenceConsidered", DEFAULT_MIN_TIME_FOR_PERSISTENCE);
772 m_dontPersistBefore *= 10000000;
773 m_persistAfter =
774 startupConfig.GetLong("MaximumTimeBeforePersistenceConsidered", DEFAULT_MAX_TIME_FOR_PERSISTENCE);
775 m_persistAfter *= 10000000;
776
777 m_defaultScriptEngine = startupConfig.GetString("DefaultScriptEngine", "XEngine");
778 m_log.InfoFormat("[SCENE]: Default script engine {0}", m_defaultScriptEngine);
779
780 IConfig packetConfig = m_config.Configs["PacketPool"];
781 if (packetConfig != null)
780 { 782 {
781 RegionInfo.RegionSettings.TerrainImageID = tileID; 783 PacketPool.Instance.RecyclePackets = packetConfig.GetBoolean("RecyclePackets", true);
784 PacketPool.Instance.RecycleDataBlocks = packetConfig.GetBoolean("RecycleDataBlocks", true);
782 } 785 }
783 }
784 786
785 string grant = startupConfig.GetString("AllowedViewerList", String.Empty); 787 m_strictAccessControl = startupConfig.GetBoolean("StrictAccessControl", m_strictAccessControl);
786 if (grant.Length > 0) 788 m_seeIntoBannedRegion = startupConfig.GetBoolean("SeeIntoBannedRegion", m_seeIntoBannedRegion);
787 { 789 CombineRegions = startupConfig.GetBoolean("CombineContiguousRegions", false);
788 foreach (string viewer in grant.Split(',')) 790
791 m_generateMaptiles = startupConfig.GetBoolean("GenerateMaptiles", true);
792 if (m_generateMaptiles)
789 { 793 {
790 m_AllowedViewers.Add(viewer.Trim().ToLower()); 794 int maptileRefresh = startupConfig.GetInt("MaptileRefresh", 0);
795 if (maptileRefresh != 0)
796 {
797 m_mapGenerationTimer.Interval = maptileRefresh * 1000;
798 m_mapGenerationTimer.Elapsed += RegenerateMaptileAndReregister;
799 m_mapGenerationTimer.AutoReset = true;
800 m_mapGenerationTimer.Start();
801 }
791 } 802 }
792 } 803 else
804 {
805 string tile = startupConfig.GetString("MaptileStaticUUID", UUID.Zero.ToString());
806 UUID tileID;
793 807
794 grant = startupConfig.GetString("BannedViewerList", String.Empty); 808 if (UUID.TryParse(tile, out tileID))
795 if (grant.Length > 0) 809 {
796 { 810 RegionInfo.RegionSettings.TerrainImageID = tileID;
797 foreach (string viewer in grant.Split(',')) 811 }
812 }
813
814 string grant = startupConfig.GetString("AllowedViewerList", String.Empty);
815 if (grant.Length > 0)
798 { 816 {
799 m_BannedViewers.Add(viewer.Trim().ToLower()); 817 foreach (string viewer in grant.Split(','))
818 {
819 m_AllowedViewers.Add(viewer.Trim().ToLower());
820 }
800 } 821 }
801 }
802 822
803 MinFrameTime = startupConfig.GetFloat( "MinFrameTime", MinFrameTime); 823 grant = startupConfig.GetString("BannedViewerList", String.Empty);
804 m_update_backup = startupConfig.GetInt( "UpdateStorageEveryNFrames", m_update_backup); 824 if (grant.Length > 0)
805 m_update_coarse_locations = startupConfig.GetInt( "UpdateCoarseLocationsEveryNFrames", m_update_coarse_locations); 825 {
806 m_update_entitymovement = startupConfig.GetInt( "UpdateEntityMovementEveryNFrames", m_update_entitymovement); 826 foreach (string viewer in grant.Split(','))
807 m_update_events = startupConfig.GetInt( "UpdateEventsEveryNFrames", m_update_events); 827 {
808 m_update_objects = startupConfig.GetInt( "UpdateObjectsEveryNFrames", m_update_objects); 828 m_BannedViewers.Add(viewer.Trim().ToLower());
809 m_update_physics = startupConfig.GetInt( "UpdatePhysicsEveryNFrames", m_update_physics); 829 }
810 m_update_presences = startupConfig.GetInt( "UpdateAgentsEveryNFrames", m_update_presences); 830 }
811 m_update_terrain = startupConfig.GetInt( "UpdateTerrainEveryNFrames", m_update_terrain);
812 m_update_temp_cleaning = startupConfig.GetInt( "UpdateTempCleaningEveryNFrames", m_update_temp_cleaning);
813 831
814 SendPeriodicAppearanceUpdates = startupConfig.GetBoolean("SendPeriodicAppearanceUpdates", SendPeriodicAppearanceUpdates); 832 MinFrameTime = startupConfig.GetFloat( "MinFrameTime", MinFrameTime);
833 m_update_backup = startupConfig.GetInt( "UpdateStorageEveryNFrames", m_update_backup);
834 m_update_coarse_locations = startupConfig.GetInt( "UpdateCoarseLocationsEveryNFrames", m_update_coarse_locations);
835 m_update_entitymovement = startupConfig.GetInt( "UpdateEntityMovementEveryNFrames", m_update_entitymovement);
836 m_update_events = startupConfig.GetInt( "UpdateEventsEveryNFrames", m_update_events);
837 m_update_objects = startupConfig.GetInt( "UpdateObjectsEveryNFrames", m_update_objects);
838 m_update_physics = startupConfig.GetInt( "UpdatePhysicsEveryNFrames", m_update_physics);
839 m_update_presences = startupConfig.GetInt( "UpdateAgentsEveryNFrames", m_update_presences);
840 m_update_terrain = startupConfig.GetInt( "UpdateTerrainEveryNFrames", m_update_terrain);
841 m_update_temp_cleaning = startupConfig.GetInt( "UpdateTempCleaningEveryNFrames", m_update_temp_cleaning);
842 SendPeriodicAppearanceUpdates = startupConfig.GetBoolean("SendPeriodicAppearanceUpdates", SendPeriodicAppearanceUpdates);
843 }
844 }
845 catch (Exception e)
846 {
847 m_log.Error("[SCENE]: Failed to load StartupConfig: " + e.ToString());
815 } 848 }
816 849
817 #endregion Region Config 850 #endregion Region Config
@@ -1237,7 +1270,22 @@ namespace OpenSim.Region.Framework.Scenes
1237 //m_heartbeatTimer.Elapsed += new ElapsedEventHandler(Heartbeat); 1270 //m_heartbeatTimer.Elapsed += new ElapsedEventHandler(Heartbeat);
1238 if (m_heartbeatThread != null) 1271 if (m_heartbeatThread != null)
1239 { 1272 {
1273 m_hbRestarts++;
1274 if(m_hbRestarts > 10)
1275 Environment.Exit(1);
1276 m_log.ErrorFormat("[SCENE]: Restarting heartbeat thread because it hasn't reported in in region {0}", RegionInfo.RegionName);
1277
1278//int pid = System.Diagnostics.Process.GetCurrentProcess().Id;
1279//System.Diagnostics.Process proc = new System.Diagnostics.Process();
1280//proc.EnableRaisingEvents=false;
1281//proc.StartInfo.FileName = "/bin/kill";
1282//proc.StartInfo.Arguments = "-QUIT " + pid.ToString();
1283//proc.Start();
1284//proc.WaitForExit();
1285//Thread.Sleep(1000);
1286//Environment.Exit(1);
1240 m_heartbeatThread.Abort(); 1287 m_heartbeatThread.Abort();
1288 Watchdog.AbortThread(m_heartbeatThread.ManagedThreadId);
1241 m_heartbeatThread = null; 1289 m_heartbeatThread = null;
1242 } 1290 }
1243// m_lastUpdate = Util.EnvironmentTickCount(); 1291// m_lastUpdate = Util.EnvironmentTickCount();
@@ -1528,6 +1576,8 @@ namespace OpenSim.Region.Framework.Scenes
1528 tmpMS = Util.EnvironmentTickCountSubtract(m_lastFrameTick, maintc); 1576 tmpMS = Util.EnvironmentTickCountSubtract(m_lastFrameTick, maintc);
1529 tmpMS = (int)(MinFrameTime * 1000) - tmpMS; 1577 tmpMS = (int)(MinFrameTime * 1000) - tmpMS;
1530 1578
1579 m_firstHeartbeat = false;
1580
1531 if (tmpMS > 0) 1581 if (tmpMS > 0)
1532 { 1582 {
1533 Thread.Sleep(tmpMS); 1583 Thread.Sleep(tmpMS);
@@ -1578,9 +1628,9 @@ namespace OpenSim.Region.Framework.Scenes
1578 1628
1579 private void CheckAtTargets() 1629 private void CheckAtTargets()
1580 { 1630 {
1581 Dictionary<UUID, SceneObjectGroup>.ValueCollection objs; 1631 List<SceneObjectGroup> objs = new List<SceneObjectGroup>();
1582 lock (m_groupsWithTargets) 1632 lock (m_groupsWithTargets)
1583 objs = m_groupsWithTargets.Values; 1633 objs = new List<SceneObjectGroup>(m_groupsWithTargets.Values);
1584 1634
1585 foreach (SceneObjectGroup entry in objs) 1635 foreach (SceneObjectGroup entry in objs)
1586 entry.checkAtTargets(); 1636 entry.checkAtTargets();
@@ -1661,7 +1711,7 @@ namespace OpenSim.Region.Framework.Scenes
1661 msg.fromAgentName = "Server"; 1711 msg.fromAgentName = "Server";
1662 msg.dialog = (byte)19; // Object msg 1712 msg.dialog = (byte)19; // Object msg
1663 msg.fromGroup = false; 1713 msg.fromGroup = false;
1664 msg.offline = (byte)0; 1714 msg.offline = (byte)1;
1665 msg.ParentEstateID = RegionInfo.EstateSettings.ParentEstateID; 1715 msg.ParentEstateID = RegionInfo.EstateSettings.ParentEstateID;
1666 msg.Position = Vector3.Zero; 1716 msg.Position = Vector3.Zero;
1667 msg.RegionID = RegionInfo.RegionID.Guid; 1717 msg.RegionID = RegionInfo.RegionID.Guid;
@@ -1883,6 +1933,19 @@ namespace OpenSim.Region.Framework.Scenes
1883 EventManager.TriggerPrimsLoaded(this); 1933 EventManager.TriggerPrimsLoaded(this);
1884 } 1934 }
1885 1935
1936 public bool SuportsRayCastFiltered()
1937 {
1938 if (PhysicsScene == null)
1939 return false;
1940 return PhysicsScene.SuportsRaycastWorldFiltered();
1941 }
1942
1943 public object RayCastFiltered(Vector3 position, Vector3 direction, float length, int Count, RayFilterFlags filter)
1944 {
1945 if (PhysicsScene == null)
1946 return null;
1947 return PhysicsScene.RaycastWorld(position, direction, length, Count,filter);
1948 }
1886 1949
1887 /// <summary> 1950 /// <summary>
1888 /// Gets a new rez location based on the raycast and the size of the object that is being rezzed. 1951 /// Gets a new rez location based on the raycast and the size of the object that is being rezzed.
@@ -1899,14 +1962,24 @@ namespace OpenSim.Region.Framework.Scenes
1899 /// <returns></returns> 1962 /// <returns></returns>
1900 public Vector3 GetNewRezLocation(Vector3 RayStart, Vector3 RayEnd, UUID RayTargetID, Quaternion rot, byte bypassRayCast, byte RayEndIsIntersection, bool frontFacesOnly, Vector3 scale, bool FaceCenter) 1963 public Vector3 GetNewRezLocation(Vector3 RayStart, Vector3 RayEnd, UUID RayTargetID, Quaternion rot, byte bypassRayCast, byte RayEndIsIntersection, bool frontFacesOnly, Vector3 scale, bool FaceCenter)
1901 { 1964 {
1965
1966 float wheight = (float)RegionInfo.RegionSettings.WaterHeight;
1967 Vector3 wpos = Vector3.Zero;
1968 // Check for water surface intersection from above
1969 if ( (RayStart.Z > wheight) && (RayEnd.Z < wheight) )
1970 {
1971 float ratio = (RayStart.Z - wheight) / (RayStart.Z - RayEnd.Z);
1972 wpos.X = RayStart.X - (ratio * (RayStart.X - RayEnd.X));
1973 wpos.Y = RayStart.Y - (ratio * (RayStart.Y - RayEnd.Y));
1974 wpos.Z = wheight;
1975 }
1976
1902 Vector3 pos = Vector3.Zero; 1977 Vector3 pos = Vector3.Zero;
1903 if (RayEndIsIntersection == (byte)1) 1978 if (RayEndIsIntersection == (byte)1)
1904 { 1979 {
1905 pos = RayEnd; 1980 pos = RayEnd;
1906 return pos;
1907 } 1981 }
1908 1982 else if (RayTargetID != UUID.Zero)
1909 if (RayTargetID != UUID.Zero)
1910 { 1983 {
1911 SceneObjectPart target = GetSceneObjectPart(RayTargetID); 1984 SceneObjectPart target = GetSceneObjectPart(RayTargetID);
1912 1985
@@ -1928,7 +2001,7 @@ namespace OpenSim.Region.Framework.Scenes
1928 EntityIntersection ei = target.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, FaceCenter); 2001 EntityIntersection ei = target.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, FaceCenter);
1929 2002
1930 // Un-comment out the following line to Get Raytrace results printed to the console. 2003 // Un-comment out the following line to Get Raytrace results printed to the console.
1931 // m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString()); 2004 // m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
1932 float ScaleOffset = 0.5f; 2005 float ScaleOffset = 0.5f;
1933 2006
1934 // If we hit something 2007 // If we hit something
@@ -1951,13 +2024,10 @@ namespace OpenSim.Region.Framework.Scenes
1951 //pos.Z -= 0.25F; 2024 //pos.Z -= 0.25F;
1952 2025
1953 } 2026 }
1954
1955 return pos;
1956 } 2027 }
1957 else 2028 else
1958 { 2029 {
1959 // We don't have a target here, so we're going to raytrace all the objects in the scene. 2030 // We don't have a target here, so we're going to raytrace all the objects in the scene.
1960
1961 EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection), true, false); 2031 EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection), true, false);
1962 2032
1963 // Un-comment the following line to print the raytrace results to the console. 2033 // Un-comment the following line to print the raytrace results to the console.
@@ -1966,13 +2036,12 @@ namespace OpenSim.Region.Framework.Scenes
1966 if (ei.HitTF) 2036 if (ei.HitTF)
1967 { 2037 {
1968 pos = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z); 2038 pos = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
1969 } else 2039 }
2040 else
1970 { 2041 {
1971 // fall back to our stupid functionality 2042 // fall back to our stupid functionality
1972 pos = RayEnd; 2043 pos = RayEnd;
1973 } 2044 }
1974
1975 return pos;
1976 } 2045 }
1977 } 2046 }
1978 else 2047 else
@@ -1983,8 +2052,12 @@ namespace OpenSim.Region.Framework.Scenes
1983 //increase height so its above the ground. 2052 //increase height so its above the ground.
1984 //should be getting the normal of the ground at the rez point and using that? 2053 //should be getting the normal of the ground at the rez point and using that?
1985 pos.Z += scale.Z / 2f; 2054 pos.Z += scale.Z / 2f;
1986 return pos; 2055// return pos;
1987 } 2056 }
2057
2058 // check against posible water intercept
2059 if (wpos.Z > pos.Z) pos = wpos;
2060 return pos;
1988 } 2061 }
1989 2062
1990 2063
@@ -2073,7 +2146,10 @@ namespace OpenSim.Region.Framework.Scenes
2073 public bool AddRestoredSceneObject( 2146 public bool AddRestoredSceneObject(
2074 SceneObjectGroup sceneObject, bool attachToBackup, bool alreadyPersisted, bool sendClientUpdates) 2147 SceneObjectGroup sceneObject, bool attachToBackup, bool alreadyPersisted, bool sendClientUpdates)
2075 { 2148 {
2076 return m_sceneGraph.AddRestoredSceneObject(sceneObject, attachToBackup, alreadyPersisted, sendClientUpdates); 2149 bool result = m_sceneGraph.AddRestoredSceneObject(sceneObject, attachToBackup, alreadyPersisted, sendClientUpdates);
2150 if (result)
2151 sceneObject.IsDeleted = false;
2152 return result;
2077 } 2153 }
2078 2154
2079 /// <summary> 2155 /// <summary>
@@ -2165,6 +2241,15 @@ namespace OpenSim.Region.Framework.Scenes
2165 /// </summary> 2241 /// </summary>
2166 public void DeleteAllSceneObjects() 2242 public void DeleteAllSceneObjects()
2167 { 2243 {
2244 DeleteAllSceneObjects(false);
2245 }
2246
2247 /// <summary>
2248 /// Delete every object from the scene. This does not include attachments worn by avatars.
2249 /// </summary>
2250 public void DeleteAllSceneObjects(bool exceptNoCopy)
2251 {
2252 List<SceneObjectGroup> toReturn = new List<SceneObjectGroup>();
2168 lock (Entities) 2253 lock (Entities)
2169 { 2254 {
2170 EntityBase[] entities = Entities.GetEntities(); 2255 EntityBase[] entities = Entities.GetEntities();
@@ -2173,11 +2258,24 @@ namespace OpenSim.Region.Framework.Scenes
2173 if (e is SceneObjectGroup) 2258 if (e is SceneObjectGroup)
2174 { 2259 {
2175 SceneObjectGroup sog = (SceneObjectGroup)e; 2260 SceneObjectGroup sog = (SceneObjectGroup)e;
2176 if (!sog.IsAttachment) 2261 if (sog != null && !sog.IsAttachment)
2177 DeleteSceneObject((SceneObjectGroup)e, false); 2262 {
2263 if (!exceptNoCopy || ((sog.GetEffectivePermissions() & (uint)PermissionMask.Copy) != 0))
2264 {
2265 DeleteSceneObject((SceneObjectGroup)e, false);
2266 }
2267 else
2268 {
2269 toReturn.Add((SceneObjectGroup)e);
2270 }
2271 }
2178 } 2272 }
2179 } 2273 }
2180 } 2274 }
2275 if (toReturn.Count > 0)
2276 {
2277 returnObjects(toReturn.ToArray(), UUID.Zero);
2278 }
2181 } 2279 }
2182 2280
2183 /// <summary> 2281 /// <summary>
@@ -2229,6 +2327,8 @@ namespace OpenSim.Region.Framework.Scenes
2229 } 2327 }
2230 2328
2231 group.DeleteGroupFromScene(silent); 2329 group.DeleteGroupFromScene(silent);
2330 if (!silent)
2331 SendKillObject(new List<uint>() { group.LocalId });
2232 2332
2233// m_log.DebugFormat("[SCENE]: Exit DeleteSceneObject() for {0} {1}", group.Name, group.UUID); 2333// m_log.DebugFormat("[SCENE]: Exit DeleteSceneObject() for {0} {1}", group.Name, group.UUID);
2234 } 2334 }
@@ -2519,7 +2619,7 @@ namespace OpenSim.Region.Framework.Scenes
2519 // If the user is banned, we won't let any of their objects 2619 // If the user is banned, we won't let any of their objects
2520 // enter. Period. 2620 // enter. Period.
2521 // 2621 //
2522 if (RegionInfo.EstateSettings.IsBanned(newObject.OwnerID)) 2622 if (RegionInfo.EstateSettings.IsBanned(newObject.OwnerID, 36))
2523 { 2623 {
2524 m_log.InfoFormat("[INTERREGION]: Denied prim crossing for banned avatar {0}", newObject.OwnerID); 2624 m_log.InfoFormat("[INTERREGION]: Denied prim crossing for banned avatar {0}", newObject.OwnerID);
2525 return false; 2625 return false;
@@ -2527,6 +2627,8 @@ namespace OpenSim.Region.Framework.Scenes
2527 2627
2528 if (newPosition != Vector3.Zero) 2628 if (newPosition != Vector3.Zero)
2529 newObject.RootPart.GroupPosition = newPosition; 2629 newObject.RootPart.GroupPosition = newPosition;
2630 if (newObject.RootPart.KeyframeMotion != null)
2631 newObject.RootPart.KeyframeMotion.UpdateSceneObject(newObject);
2530 2632
2531 if (!AddSceneObject(newObject)) 2633 if (!AddSceneObject(newObject))
2532 { 2634 {
@@ -2571,6 +2673,23 @@ namespace OpenSim.Region.Framework.Scenes
2571 /// <returns>True if the SceneObjectGroup was added, False if it was not</returns> 2673 /// <returns>True if the SceneObjectGroup was added, False if it was not</returns>
2572 public bool AddSceneObject(SceneObjectGroup sceneObject) 2674 public bool AddSceneObject(SceneObjectGroup sceneObject)
2573 { 2675 {
2676 if (sceneObject.OwnerID == UUID.Zero)
2677 {
2678 m_log.ErrorFormat("[SCENE]: Owner ID for {0} was zero", sceneObject.UUID);
2679 return false;
2680 }
2681
2682 // If the user is banned, we won't let any of their objects
2683 // enter. Period.
2684 //
2685 int flags = GetUserFlags(sceneObject.OwnerID);
2686 if (RegionInfo.EstateSettings.IsBanned(sceneObject.OwnerID, flags))
2687 {
2688 m_log.InfoFormat("[INTERREGION]: Denied prim crossing for banned avatar {0}", sceneObject.OwnerID);
2689
2690 return false;
2691 }
2692
2574 // Force allocation of new LocalId 2693 // Force allocation of new LocalId
2575 // 2694 //
2576 SceneObjectPart[] parts = sceneObject.Parts; 2695 SceneObjectPart[] parts = sceneObject.Parts;
@@ -2604,16 +2723,27 @@ namespace OpenSim.Region.Framework.Scenes
2604 RootPrim.RemFlag(PrimFlags.TemporaryOnRez); 2723 RootPrim.RemFlag(PrimFlags.TemporaryOnRez);
2605 2724
2606 if (AttachmentsModule != null) 2725 if (AttachmentsModule != null)
2607 AttachmentsModule.AttachObject(sp, grp, 0, false); 2726 AttachmentsModule.AttachObject(sp, grp, 0, false, false);
2608 } 2727 }
2609 else 2728 else
2610 { 2729 {
2730 m_log.DebugFormat("[SCENE]: Attachment {0} arrived and scene presence was not found, setting to temp", sceneObject.UUID);
2611 RootPrim.RemFlag(PrimFlags.TemporaryOnRez); 2731 RootPrim.RemFlag(PrimFlags.TemporaryOnRez);
2612 RootPrim.AddFlag(PrimFlags.TemporaryOnRez); 2732 RootPrim.AddFlag(PrimFlags.TemporaryOnRez);
2613 } 2733 }
2734 if (sceneObject.OwnerID == UUID.Zero)
2735 {
2736 m_log.ErrorFormat("[SCENE]: Owner ID for {0} was zero after attachment processing. BUG!", sceneObject.UUID);
2737 return false;
2738 }
2614 } 2739 }
2615 else 2740 else
2616 { 2741 {
2742 if (sceneObject.OwnerID == UUID.Zero)
2743 {
2744 m_log.ErrorFormat("[SCENE]: Owner ID for non-attachment {0} was zero", sceneObject.UUID);
2745 return false;
2746 }
2617 AddRestoredSceneObject(sceneObject, true, false); 2747 AddRestoredSceneObject(sceneObject, true, false);
2618 } 2748 }
2619 2749
@@ -2630,6 +2760,24 @@ namespace OpenSim.Region.Framework.Scenes
2630 return 2; // StateSource.PrimCrossing 2760 return 2; // StateSource.PrimCrossing
2631 } 2761 }
2632 2762
2763 public int GetUserFlags(UUID user)
2764 {
2765 //Unfortunately the SP approach means that the value is cached until region is restarted
2766 /*
2767 ScenePresence sp;
2768 if (TryGetScenePresence(user, out sp))
2769 {
2770 return sp.UserFlags;
2771 }
2772 else
2773 {
2774 */
2775 UserAccount uac = UserAccountService.GetUserAccount(RegionInfo.ScopeID, user);
2776 if (uac == null)
2777 return 0;
2778 return uac.UserFlags;
2779 //}
2780 }
2633 #endregion 2781 #endregion
2634 2782
2635 #region Add/Remove Avatar Methods 2783 #region Add/Remove Avatar Methods
@@ -2643,7 +2791,7 @@ namespace OpenSim.Region.Framework.Scenes
2643 = (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin) != 0 2791 = (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin) != 0
2644 || (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaLogin) != 0; 2792 || (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaLogin) != 0;
2645 2793
2646// CheckHeartbeat(); 2794 CheckHeartbeat();
2647 2795
2648 ScenePresence sp = GetScenePresence(client.AgentId); 2796 ScenePresence sp = GetScenePresence(client.AgentId);
2649 2797
@@ -2697,7 +2845,13 @@ namespace OpenSim.Region.Framework.Scenes
2697 2845
2698 EventManager.TriggerOnNewClient(client); 2846 EventManager.TriggerOnNewClient(client);
2699 if (vialogin) 2847 if (vialogin)
2848 {
2700 EventManager.TriggerOnClientLogin(client); 2849 EventManager.TriggerOnClientLogin(client);
2850 // Send initial parcel data
2851 Vector3 pos = sp.AbsolutePosition;
2852 ILandObject land = LandChannel.GetLandObject(pos.X, pos.Y);
2853 land.SendLandUpdateToClient(client);
2854 }
2701 2855
2702 return sp; 2856 return sp;
2703 } 2857 }
@@ -2786,19 +2940,12 @@ namespace OpenSim.Region.Framework.Scenes
2786 // and the scene presence and the client, if they exist 2940 // and the scene presence and the client, if they exist
2787 try 2941 try
2788 { 2942 {
2789 // We need to wait for the client to make UDP contact first. 2943 ScenePresence sp = GetScenePresence(agentID);
2790 // It's the UDP contact that creates the scene presence 2944 PresenceService.LogoutAgent(sp.ControllingClient.SessionId);
2791 ScenePresence sp = WaitGetScenePresence(agentID); 2945
2792 if (sp != null) 2946 if (sp != null)
2793 {
2794 PresenceService.LogoutAgent(sp.ControllingClient.SessionId);
2795
2796 sp.ControllingClient.Close(); 2947 sp.ControllingClient.Close();
2797 } 2948
2798 else
2799 {
2800 m_log.WarnFormat("[SCENE]: Could not find scene presence for {0}", agentID);
2801 }
2802 // BANG! SLASH! 2949 // BANG! SLASH!
2803 m_authenticateHandler.RemoveCircuit(agentID); 2950 m_authenticateHandler.RemoveCircuit(agentID);
2804 2951
@@ -2843,6 +2990,8 @@ namespace OpenSim.Region.Framework.Scenes
2843 client.OnUpdatePrimGroupPosition += m_sceneGraph.UpdatePrimGroupPosition; 2990 client.OnUpdatePrimGroupPosition += m_sceneGraph.UpdatePrimGroupPosition;
2844 client.OnUpdatePrimSinglePosition += m_sceneGraph.UpdatePrimSinglePosition; 2991 client.OnUpdatePrimSinglePosition += m_sceneGraph.UpdatePrimSinglePosition;
2845 2992
2993 client.onClientChangeObject += m_sceneGraph.ClientChangeObject;
2994
2846 client.OnUpdatePrimGroupRotation += m_sceneGraph.UpdatePrimGroupRotation; 2995 client.OnUpdatePrimGroupRotation += m_sceneGraph.UpdatePrimGroupRotation;
2847 client.OnUpdatePrimGroupMouseRotation += m_sceneGraph.UpdatePrimGroupRotation; 2996 client.OnUpdatePrimGroupMouseRotation += m_sceneGraph.UpdatePrimGroupRotation;
2848 client.OnUpdatePrimSingleRotation += m_sceneGraph.UpdatePrimSingleRotation; 2997 client.OnUpdatePrimSingleRotation += m_sceneGraph.UpdatePrimSingleRotation;
@@ -2899,6 +3048,7 @@ namespace OpenSim.Region.Framework.Scenes
2899 client.OnFetchInventory += m_asyncInventorySender.HandleFetchInventory; 3048 client.OnFetchInventory += m_asyncInventorySender.HandleFetchInventory;
2900 client.OnUpdateInventoryItem += UpdateInventoryItemAsset; 3049 client.OnUpdateInventoryItem += UpdateInventoryItemAsset;
2901 client.OnCopyInventoryItem += CopyInventoryItem; 3050 client.OnCopyInventoryItem += CopyInventoryItem;
3051 client.OnMoveItemsAndLeaveCopy += MoveInventoryItemsLeaveCopy;
2902 client.OnMoveInventoryItem += MoveInventoryItem; 3052 client.OnMoveInventoryItem += MoveInventoryItem;
2903 client.OnRemoveInventoryItem += RemoveInventoryItem; 3053 client.OnRemoveInventoryItem += RemoveInventoryItem;
2904 client.OnRemoveInventoryFolder += RemoveInventoryFolder; 3054 client.OnRemoveInventoryFolder += RemoveInventoryFolder;
@@ -2970,6 +3120,8 @@ namespace OpenSim.Region.Framework.Scenes
2970 client.OnUpdatePrimGroupPosition -= m_sceneGraph.UpdatePrimGroupPosition; 3120 client.OnUpdatePrimGroupPosition -= m_sceneGraph.UpdatePrimGroupPosition;
2971 client.OnUpdatePrimSinglePosition -= m_sceneGraph.UpdatePrimSinglePosition; 3121 client.OnUpdatePrimSinglePosition -= m_sceneGraph.UpdatePrimSinglePosition;
2972 3122
3123 client.onClientChangeObject -= m_sceneGraph.ClientChangeObject;
3124
2973 client.OnUpdatePrimGroupRotation -= m_sceneGraph.UpdatePrimGroupRotation; 3125 client.OnUpdatePrimGroupRotation -= m_sceneGraph.UpdatePrimGroupRotation;
2974 client.OnUpdatePrimGroupMouseRotation -= m_sceneGraph.UpdatePrimGroupRotation; 3126 client.OnUpdatePrimGroupMouseRotation -= m_sceneGraph.UpdatePrimGroupRotation;
2975 client.OnUpdatePrimSingleRotation -= m_sceneGraph.UpdatePrimSingleRotation; 3127 client.OnUpdatePrimSingleRotation -= m_sceneGraph.UpdatePrimSingleRotation;
@@ -3072,7 +3224,7 @@ namespace OpenSim.Region.Framework.Scenes
3072 /// </summary> 3224 /// </summary>
3073 /// <param name="agentId">The avatar's Unique ID</param> 3225 /// <param name="agentId">The avatar's Unique ID</param>
3074 /// <param name="client">The IClientAPI for the client</param> 3226 /// <param name="client">The IClientAPI for the client</param>
3075 public virtual void TeleportClientHome(UUID agentId, IClientAPI client) 3227 public virtual bool TeleportClientHome(UUID agentId, IClientAPI client)
3076 { 3228 {
3077 if (EntityTransferModule != null) 3229 if (EntityTransferModule != null)
3078 { 3230 {
@@ -3083,6 +3235,7 @@ namespace OpenSim.Region.Framework.Scenes
3083 m_log.DebugFormat("[SCENE]: Unable to teleport user home: no AgentTransferModule is active"); 3235 m_log.DebugFormat("[SCENE]: Unable to teleport user home: no AgentTransferModule is active");
3084 client.SendTeleportFailed("Unable to perform teleports on this simulator."); 3236 client.SendTeleportFailed("Unable to perform teleports on this simulator.");
3085 } 3237 }
3238 return false;
3086 } 3239 }
3087 3240
3088 /// <summary> 3241 /// <summary>
@@ -3192,6 +3345,16 @@ namespace OpenSim.Region.Framework.Scenes
3192 /// <param name="flags"></param> 3345 /// <param name="flags"></param>
3193 public virtual void SetHomeRezPoint(IClientAPI remoteClient, ulong regionHandle, Vector3 position, Vector3 lookAt, uint flags) 3346 public virtual void SetHomeRezPoint(IClientAPI remoteClient, ulong regionHandle, Vector3 position, Vector3 lookAt, uint flags)
3194 { 3347 {
3348 //Add half the avatar's height so that the user doesn't fall through prims
3349 ScenePresence presence;
3350 if (TryGetScenePresence(remoteClient.AgentId, out presence))
3351 {
3352 if (presence.Appearance != null)
3353 {
3354 position.Z = position.Z + (presence.Appearance.AvatarHeight / 2);
3355 }
3356 }
3357
3195 if (GridUserService != null && GridUserService.SetHome(remoteClient.AgentId.ToString(), RegionInfo.RegionID, position, lookAt)) 3358 if (GridUserService != null && GridUserService.SetHome(remoteClient.AgentId.ToString(), RegionInfo.RegionID, position, lookAt))
3196 // FUBAR ALERT: this needs to be "Home position set." so the viewer saves a home-screenshot. 3359 // FUBAR ALERT: this needs to be "Home position set." so the viewer saves a home-screenshot.
3197 m_dialogModule.SendAlertToUser(remoteClient, "Home position set."); 3360 m_dialogModule.SendAlertToUser(remoteClient, "Home position set.");
@@ -3320,6 +3483,7 @@ namespace OpenSim.Region.Framework.Scenes
3320 avatar.Close(); 3483 avatar.Close();
3321 3484
3322 m_authenticateHandler.RemoveCircuit(avatar.ControllingClient.CircuitCode); 3485 m_authenticateHandler.RemoveCircuit(avatar.ControllingClient.CircuitCode);
3486 m_log.Debug("[Scene] The avatar has left the building");
3323 } 3487 }
3324 catch (Exception e) 3488 catch (Exception e)
3325 { 3489 {
@@ -3513,13 +3677,16 @@ namespace OpenSim.Region.Framework.Scenes
3513 sp = null; 3677 sp = null;
3514 } 3678 }
3515 3679
3516 ILandObject land = LandChannel.GetLandObject(agent.startpos.X, agent.startpos.Y);
3517 3680
3518 //On login test land permisions 3681 //On login test land permisions
3519 if (vialogin) 3682 if (vialogin)
3520 { 3683 {
3521 if (land != null && !TestLandRestrictions(agent, land, out reason)) 3684 IUserAccountCacheModule cache = RequestModuleInterface<IUserAccountCacheModule>();
3685 if (cache != null)
3686 cache.Remove(agent.firstname + " " + agent.lastname);
3687 if (!TestLandRestrictions(agent.AgentID, out reason, ref agent.startpos.X, ref agent.startpos.Y))
3522 { 3688 {
3689 m_log.DebugFormat("[CONNECTION BEGIN]: Denying access to {0} due to no land access", agent.AgentID.ToString());
3523 return false; 3690 return false;
3524 } 3691 }
3525 } 3692 }
@@ -3542,9 +3709,15 @@ namespace OpenSim.Region.Framework.Scenes
3542 3709
3543 try 3710 try
3544 { 3711 {
3545 if (!AuthorizeUser(agent, out reason)) 3712 // Always check estate if this is a login. Always
3546 return false; 3713 // check if banned regions are to be blacked out.
3547 } catch (Exception e) 3714 if (vialogin || (!m_seeIntoBannedRegion))
3715 {
3716 if (!AuthorizeUser(agent, out reason))
3717 return false;
3718 }
3719 }
3720 catch (Exception e)
3548 { 3721 {
3549 m_log.ErrorFormat( 3722 m_log.ErrorFormat(
3550 "[SCENE]: Exception authorizing user {0}{1}", e.Message, e.StackTrace); 3723 "[SCENE]: Exception authorizing user {0}{1}", e.Message, e.StackTrace);
@@ -3675,6 +3848,8 @@ namespace OpenSim.Region.Framework.Scenes
3675 } 3848 }
3676 3849
3677 // Honor parcel landing type and position. 3850 // Honor parcel landing type and position.
3851 /*
3852 ILandObject land = LandChannel.GetLandObject(agent.startpos.X, agent.startpos.Y);
3678 if (land != null) 3853 if (land != null)
3679 { 3854 {
3680 if (land.LandData.LandingType == (byte)1 && land.LandData.UserLocation != Vector3.Zero) 3855 if (land.LandData.LandingType == (byte)1 && land.LandData.UserLocation != Vector3.Zero)
@@ -3682,25 +3857,34 @@ namespace OpenSim.Region.Framework.Scenes
3682 agent.startpos = land.LandData.UserLocation; 3857 agent.startpos = land.LandData.UserLocation;
3683 } 3858 }
3684 } 3859 }
3860 */// This is now handled properly in ScenePresence.MakeRootAgent
3685 } 3861 }
3686 3862
3687 return true; 3863 return true;
3688 } 3864 }
3689 3865
3690 private bool TestLandRestrictions(AgentCircuitData agent, ILandObject land, out string reason) 3866 public bool TestLandRestrictions(UUID agentID, out string reason, ref float posX, ref float posY)
3691 { 3867 {
3692 bool banned = land.IsBannedFromLand(agent.AgentID); 3868 reason = String.Empty;
3693 bool restricted = land.IsRestrictedFromLand(agent.AgentID); 3869 if (Permissions.IsGod(agentID))
3870 return true;
3871
3872 ILandObject land = LandChannel.GetLandObject(posX, posY);
3873 if (land == null)
3874 return false;
3875
3876 bool banned = land.IsBannedFromLand(agentID);
3877 bool restricted = land.IsRestrictedFromLand(agentID);
3694 3878
3695 if (banned || restricted) 3879 if (banned || restricted)
3696 { 3880 {
3697 ILandObject nearestParcel = GetNearestAllowedParcel(agent.AgentID, agent.startpos.X, agent.startpos.Y); 3881 ILandObject nearestParcel = GetNearestAllowedParcel(agentID, posX, posY);
3698 if (nearestParcel != null) 3882 if (nearestParcel != null)
3699 { 3883 {
3700 //Move agent to nearest allowed 3884 //Move agent to nearest allowed
3701 Vector3 newPosition = GetParcelCenterAtGround(nearestParcel); 3885 Vector3 newPosition = GetParcelCenterAtGround(nearestParcel);
3702 agent.startpos.X = newPosition.X; 3886 posX = newPosition.X;
3703 agent.startpos.Y = newPosition.Y; 3887 posY = newPosition.Y;
3704 } 3888 }
3705 else 3889 else
3706 { 3890 {
@@ -3762,7 +3946,7 @@ namespace OpenSim.Region.Framework.Scenes
3762 3946
3763 if (!m_strictAccessControl) return true; 3947 if (!m_strictAccessControl) return true;
3764 if (Permissions.IsGod(agent.AgentID)) return true; 3948 if (Permissions.IsGod(agent.AgentID)) return true;
3765 3949
3766 if (AuthorizationService != null) 3950 if (AuthorizationService != null)
3767 { 3951 {
3768 if (!AuthorizationService.IsAuthorizedForRegion( 3952 if (!AuthorizationService.IsAuthorizedForRegion(
@@ -3777,7 +3961,7 @@ namespace OpenSim.Region.Framework.Scenes
3777 3961
3778 if (RegionInfo.EstateSettings != null) 3962 if (RegionInfo.EstateSettings != null)
3779 { 3963 {
3780 if (RegionInfo.EstateSettings.IsBanned(agent.AgentID)) 3964 if (RegionInfo.EstateSettings.IsBanned(agent.AgentID, 0))
3781 { 3965 {
3782 m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user is on the banlist", 3966 m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user is on the banlist",
3783 agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName); 3967 agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
@@ -3967,6 +4151,15 @@ namespace OpenSim.Region.Framework.Scenes
3967 4151
3968 // XPTO: if this agent is not allowed here as root, always return false 4152 // XPTO: if this agent is not allowed here as root, always return false
3969 4153
4154 // We have to wait until the viewer contacts this region after receiving EAC.
4155 // That calls AddNewClient, which finally creates the ScenePresence
4156 int flags = GetUserFlags(cAgentData.AgentID);
4157 if (m_regInfo.EstateSettings.IsBanned(cAgentData.AgentID, flags))
4158 {
4159 m_log.DebugFormat("[SCENE]: Denying root agent entry to {0}: banned", cAgentData.AgentID);
4160 return false;
4161 }
4162
3970 // TODO: This check should probably be in QueryAccess(). 4163 // TODO: This check should probably be in QueryAccess().
3971 ILandObject nearestParcel = GetNearestAllowedParcel(cAgentData.AgentID, Constants.RegionSize / 2, Constants.RegionSize / 2); 4164 ILandObject nearestParcel = GetNearestAllowedParcel(cAgentData.AgentID, Constants.RegionSize / 2, Constants.RegionSize / 2);
3972 if (nearestParcel == null) 4165 if (nearestParcel == null)
@@ -4060,12 +4253,22 @@ namespace OpenSim.Region.Framework.Scenes
4060 return false; 4253 return false;
4061 } 4254 }
4062 4255
4256 public bool IncomingCloseAgent(UUID agentID)
4257 {
4258 return IncomingCloseAgent(agentID, false);
4259 }
4260
4261 public bool IncomingCloseChildAgent(UUID agentID)
4262 {
4263 return IncomingCloseAgent(agentID, true);
4264 }
4265
4063 /// <summary> 4266 /// <summary>
4064 /// Tell a single agent to disconnect from the region. 4267 /// Tell a single agent to disconnect from the region.
4065 /// </summary> 4268 /// </summary>
4066 /// <param name="regionHandle"></param>
4067 /// <param name="agentID"></param> 4269 /// <param name="agentID"></param>
4068 public bool IncomingCloseAgent(UUID agentID) 4270 /// <param name="childOnly"></param>
4271 public bool IncomingCloseAgent(UUID agentID, bool childOnly)
4069 { 4272 {
4070 //m_log.DebugFormat("[SCENE]: Processing incoming close agent for {0}", agentID); 4273 //m_log.DebugFormat("[SCENE]: Processing incoming close agent for {0}", agentID);
4071 4274
@@ -4669,35 +4872,81 @@ namespace OpenSim.Region.Framework.Scenes
4669 SimulationDataService.RemoveObject(uuid, RegionInfo.RegionID); 4872 SimulationDataService.RemoveObject(uuid, RegionInfo.RegionID);
4670 } 4873 }
4671 4874
4672 public int GetHealth() 4875 public int GetHealth(out int flags, out string message)
4673 { 4876 {
4674 // Returns: 4877 // Returns:
4675 // 1 = sim is up and accepting http requests. The heartbeat has 4878 // 1 = sim is up and accepting http requests. The heartbeat has
4676 // stopped and the sim is probably locked up, but a remote 4879 // stopped and the sim is probably locked up, but a remote
4677 // admin restart may succeed 4880 // admin restart may succeed
4678 // 4881 //
4679 // 2 = Sim is up and the heartbeat is running. The sim is likely 4882 // 2 = Sim is up and the heartbeat is running. The sim is likely
4680 // usable for people within and logins _may_ work 4883 // usable for people within
4884 //
4885 // 3 = Sim is up and one packet thread is running. Sim is
4886 // unstable and will not accept new logins
4681 // 4887 //
4682 // 3 = We have seen a new user enter within the past 4 minutes 4888 // 4 = Sim is up and both packet threads are running. Sim is
4889 // likely usable
4890 //
4891 // 5 = We have seen a new user enter within the past 4 minutes
4683 // which can be seen as positive confirmation of sim health 4892 // which can be seen as positive confirmation of sim health
4684 // 4893 //
4894
4895 flags = 0;
4896 message = String.Empty;
4897
4898 CheckHeartbeat();
4899
4900 if (m_firstHeartbeat || (m_lastIncoming == 0 && m_lastOutgoing == 0))
4901 {
4902 // We're still starting
4903 // 0 means "in startup", it can't happen another way, since
4904 // to get here, we must be able to accept http connections
4905 return 0;
4906 }
4907
4685 int health=1; // Start at 1, means we're up 4908 int health=1; // Start at 1, means we're up
4686 4909
4687 if ((Util.EnvironmentTickCountSubtract(m_lastFrameTick)) < 1000) 4910 if ((Util.EnvironmentTickCountSubtract(m_lastFrameTick)) < 1000)
4688 health += 1; 4911 {
4912 health+=1;
4913 flags |= 1;
4914 }
4915
4916 if (Util.EnvironmentTickCountSubtract(m_lastIncoming) < 1000)
4917 {
4918 health+=1;
4919 flags |= 2;
4920 }
4921
4922 if (Util.EnvironmentTickCountSubtract(m_lastOutgoing) < 1000)
4923 {
4924 health+=1;
4925 flags |= 4;
4926 }
4689 else 4927 else
4928 {
4929int pid = System.Diagnostics.Process.GetCurrentProcess().Id;
4930System.Diagnostics.Process proc = new System.Diagnostics.Process();
4931proc.EnableRaisingEvents=false;
4932proc.StartInfo.FileName = "/bin/kill";
4933proc.StartInfo.Arguments = "-QUIT " + pid.ToString();
4934proc.Start();
4935proc.WaitForExit();
4936Thread.Sleep(1000);
4937Environment.Exit(1);
4938 }
4939
4940 if (flags != 7)
4690 return health; 4941 return health;
4691 4942
4692 // A login in the last 4 mins? We can't be doing too badly 4943 // A login in the last 4 mins? We can't be doing too badly
4693 // 4944 //
4694 if ((Util.EnvironmentTickCountSubtract(m_LastLogin)) < 240000) 4945 if (Util.EnvironmentTickCountSubtract(m_LastLogin) < 240000)
4695 health++; 4946 health++;
4696 else 4947 else
4697 return health; 4948 return health;
4698 4949
4699// CheckHeartbeat();
4700
4701 return health; 4950 return health;
4702 } 4951 }
4703 4952
@@ -4785,7 +5034,7 @@ namespace OpenSim.Region.Framework.Scenes
4785 bool wasUsingPhysics = ((jointProxyObject.Flags & PrimFlags.Physics) != 0); 5034 bool wasUsingPhysics = ((jointProxyObject.Flags & PrimFlags.Physics) != 0);
4786 if (wasUsingPhysics) 5035 if (wasUsingPhysics)
4787 { 5036 {
4788 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 5037 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
4789 } 5038 }
4790 } 5039 }
4791 5040
@@ -4884,14 +5133,14 @@ namespace OpenSim.Region.Framework.Scenes
4884 return (((vsn.X * xdiff) + (vsn.Y * ydiff)) / (-1 * vsn.Z)) + p0.Z; 5133 return (((vsn.X * xdiff) + (vsn.Y * ydiff)) / (-1 * vsn.Z)) + p0.Z;
4885 } 5134 }
4886 5135
4887// private void CheckHeartbeat() 5136 private void CheckHeartbeat()
4888// { 5137 {
4889// if (m_firstHeartbeat) 5138 if (m_firstHeartbeat)
4890// return; 5139 return;
4891// 5140
4892// if (Util.EnvironmentTickCountSubtract(m_lastFrameTick) > 2000) 5141 if ((Util.EnvironmentTickCountSubtract(m_lastFrameTick)) > 5000)
4893// StartTimer(); 5142 Start();
4894// } 5143 }
4895 5144
4896 public override ISceneObject DeserializeObject(string representation) 5145 public override ISceneObject DeserializeObject(string representation)
4897 { 5146 {
@@ -4903,9 +5152,14 @@ namespace OpenSim.Region.Framework.Scenes
4903 get { return m_allowScriptCrossings; } 5152 get { return m_allowScriptCrossings; }
4904 } 5153 }
4905 5154
4906 public Vector3? GetNearestAllowedPosition(ScenePresence avatar) 5155 public Vector3 GetNearestAllowedPosition(ScenePresence avatar)
4907 { 5156 {
4908 ILandObject nearestParcel = GetNearestAllowedParcel(avatar.UUID, avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y); 5157 return GetNearestAllowedPosition(avatar, null);
5158 }
5159
5160 public Vector3 GetNearestAllowedPosition(ScenePresence avatar, ILandObject excludeParcel)
5161 {
5162 ILandObject nearestParcel = GetNearestAllowedParcel(avatar.UUID, avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y, excludeParcel);
4909 5163
4910 if (nearestParcel != null) 5164 if (nearestParcel != null)
4911 { 5165 {
@@ -4914,10 +5168,7 @@ namespace OpenSim.Region.Framework.Scenes
4914 Vector3? nearestPoint = GetNearestPointInParcelAlongDirectionFromPoint(avatar.AbsolutePosition, dir, nearestParcel); 5168 Vector3? nearestPoint = GetNearestPointInParcelAlongDirectionFromPoint(avatar.AbsolutePosition, dir, nearestParcel);
4915 if (nearestPoint != null) 5169 if (nearestPoint != null)
4916 { 5170 {
4917// m_log.DebugFormat( 5171 Debug.WriteLine("Found a sane previous position based on velocity, sending them to: " + nearestPoint.ToString());
4918// "[SCENE]: Found a sane previous position based on velocity for {0}, sending them to {1} in {2}",
4919// avatar.Name, nearestPoint, nearestParcel.LandData.Name);
4920
4921 return nearestPoint.Value; 5172 return nearestPoint.Value;
4922 } 5173 }
4923 5174
@@ -4927,17 +5178,20 @@ namespace OpenSim.Region.Framework.Scenes
4927 nearestPoint = GetNearestPointInParcelAlongDirectionFromPoint(avatar.AbsolutePosition, dir, nearestParcel); 5178 nearestPoint = GetNearestPointInParcelAlongDirectionFromPoint(avatar.AbsolutePosition, dir, nearestParcel);
4928 if (nearestPoint != null) 5179 if (nearestPoint != null)
4929 { 5180 {
4930// m_log.DebugFormat( 5181 Debug.WriteLine("They had a zero velocity, sending them to: " + nearestPoint.ToString());
4931// "[SCENE]: {0} had a zero velocity, sending them to {1}", avatar.Name, nearestPoint);
4932
4933 return nearestPoint.Value; 5182 return nearestPoint.Value;
4934 } 5183 }
4935 5184
4936 //Ultimate backup if we have no idea where they are 5185 ILandObject dest = LandChannel.GetLandObject(avatar.lastKnownAllowedPosition.X, avatar.lastKnownAllowedPosition.Y);
4937// m_log.DebugFormat( 5186 if (dest != excludeParcel)
4938// "[SCENE]: No idea where {0} is, sending them to {1}", avatar.Name, avatar.lastKnownAllowedPosition); 5187 {
5188 // Ultimate backup if we have no idea where they are and
5189 // the last allowed position was in another parcel
5190 Debug.WriteLine("Have no idea where they are, sending them to: " + avatar.lastKnownAllowedPosition.ToString());
5191 return avatar.lastKnownAllowedPosition;
5192 }
4939 5193
4940 return avatar.lastKnownAllowedPosition; 5194 // else fall through to region edge
4941 } 5195 }
4942 5196
4943 //Go to the edge, this happens in teleporting to a region with no available parcels 5197 //Go to the edge, this happens in teleporting to a region with no available parcels
@@ -4971,13 +5225,18 @@ namespace OpenSim.Region.Framework.Scenes
4971 5225
4972 public ILandObject GetNearestAllowedParcel(UUID avatarId, float x, float y) 5226 public ILandObject GetNearestAllowedParcel(UUID avatarId, float x, float y)
4973 { 5227 {
5228 return GetNearestAllowedParcel(avatarId, x, y, null);
5229 }
5230
5231 public ILandObject GetNearestAllowedParcel(UUID avatarId, float x, float y, ILandObject excludeParcel)
5232 {
4974 List<ILandObject> all = AllParcels(); 5233 List<ILandObject> all = AllParcels();
4975 float minParcelDistance = float.MaxValue; 5234 float minParcelDistance = float.MaxValue;
4976 ILandObject nearestParcel = null; 5235 ILandObject nearestParcel = null;
4977 5236
4978 foreach (var parcel in all) 5237 foreach (var parcel in all)
4979 { 5238 {
4980 if (!parcel.IsEitherBannedOrRestricted(avatarId)) 5239 if (!parcel.IsEitherBannedOrRestricted(avatarId) && parcel != excludeParcel)
4981 { 5240 {
4982 float parcelDistance = GetParcelDistancefromPoint(parcel, x, y); 5241 float parcelDistance = GetParcelDistancefromPoint(parcel, x, y);
4983 if (parcelDistance < minParcelDistance) 5242 if (parcelDistance < minParcelDistance)
@@ -5219,7 +5478,55 @@ namespace OpenSim.Region.Framework.Scenes
5219 mapModule.GenerateMaptile(); 5478 mapModule.GenerateMaptile();
5220 } 5479 }
5221 5480
5222 private void RegenerateMaptileAndReregister(object sender, ElapsedEventArgs e) 5481// public void CleanDroppedAttachments()
5482// {
5483// List<SceneObjectGroup> objectsToDelete =
5484// new List<SceneObjectGroup>();
5485//
5486// lock (m_cleaningAttachments)
5487// {
5488// ForEachSOG(delegate (SceneObjectGroup grp)
5489// {
5490// if (grp.RootPart.Shape.PCode == 0 && grp.RootPart.Shape.State != 0 && (!objectsToDelete.Contains(grp)))
5491// {
5492// UUID agentID = grp.OwnerID;
5493// if (agentID == UUID.Zero)
5494// {
5495// objectsToDelete.Add(grp);
5496// return;
5497// }
5498//
5499// ScenePresence sp = GetScenePresence(agentID);
5500// if (sp == null)
5501// {
5502// objectsToDelete.Add(grp);
5503// return;
5504// }
5505// }
5506// });
5507// }
5508//
5509// foreach (SceneObjectGroup grp in objectsToDelete)
5510// {
5511// m_log.InfoFormat("[SCENE]: Deleting dropped attachment {0} of user {1}", grp.UUID, grp.OwnerID);
5512// DeleteSceneObject(grp, true);
5513// }
5514// }
5515
5516 public void ThreadAlive(int threadCode)
5517 {
5518 switch(threadCode)
5519 {
5520 case 1: // Incoming
5521 m_lastIncoming = Util.EnvironmentTickCount();
5522 break;
5523 case 2: // Incoming
5524 m_lastOutgoing = Util.EnvironmentTickCount();
5525 break;
5526 }
5527 }
5528
5529 public void RegenerateMaptileAndReregister(object sender, ElapsedEventArgs e)
5223 { 5530 {
5224 RegenerateMaptile(); 5531 RegenerateMaptile();
5225 5532
@@ -5247,6 +5554,8 @@ namespace OpenSim.Region.Framework.Scenes
5247 /// <returns></returns> 5554 /// <returns></returns>
5248 public bool QueryAccess(UUID agentID, Vector3 position, out string reason) 5555 public bool QueryAccess(UUID agentID, Vector3 position, out string reason)
5249 { 5556 {
5557 reason = "You are banned from the region";
5558
5250 if (EntityTransferModule.IsInTransit(agentID)) 5559 if (EntityTransferModule.IsInTransit(agentID))
5251 { 5560 {
5252 reason = "Agent is still in transit from this region"; 5561 reason = "Agent is still in transit from this region";
@@ -5258,6 +5567,12 @@ namespace OpenSim.Region.Framework.Scenes
5258 return false; 5567 return false;
5259 } 5568 }
5260 5569
5570 if (Permissions.IsGod(agentID))
5571 {
5572 reason = String.Empty;
5573 return true;
5574 }
5575
5261 // FIXME: Root agent count is currently known to be inaccurate. This forces a recount before we check. 5576 // FIXME: Root agent count is currently known to be inaccurate. This forces a recount before we check.
5262 // However, the long term fix is to make sure root agent count is always accurate. 5577 // However, the long term fix is to make sure root agent count is always accurate.
5263 m_sceneGraph.RecalculateStats(); 5578 m_sceneGraph.RecalculateStats();
@@ -5278,6 +5593,41 @@ namespace OpenSim.Region.Framework.Scenes
5278 } 5593 }
5279 } 5594 }
5280 5595
5596 ScenePresence presence = GetScenePresence(agentID);
5597 IClientAPI client = null;
5598 AgentCircuitData aCircuit = null;
5599
5600 if (presence != null)
5601 {
5602 client = presence.ControllingClient;
5603 if (client != null)
5604 aCircuit = client.RequestClientInfo();
5605 }
5606
5607 // We may be called before there is a presence or a client.
5608 // Fake AgentCircuitData to keep IAuthorizationModule smiling
5609 if (client == null)
5610 {
5611 aCircuit = new AgentCircuitData();
5612 aCircuit.AgentID = agentID;
5613 aCircuit.firstname = String.Empty;
5614 aCircuit.lastname = String.Empty;
5615 }
5616
5617 try
5618 {
5619 if (!AuthorizeUser(aCircuit, out reason))
5620 {
5621 // m_log.DebugFormat("[SCENE]: Denying access for {0}", agentID);
5622 return false;
5623 }
5624 }
5625 catch (Exception e)
5626 {
5627 m_log.DebugFormat("[SCENE]: Exception authorizing agent: {0} "+ e.StackTrace, e.Message);
5628 return false;
5629 }
5630
5281 if (position == Vector3.Zero) // Teleport 5631 if (position == Vector3.Zero) // Teleport
5282 { 5632 {
5283 if (!RegionInfo.EstateSettings.AllowDirectTeleport) 5633 if (!RegionInfo.EstateSettings.AllowDirectTeleport)
@@ -5306,13 +5656,46 @@ namespace OpenSim.Region.Framework.Scenes
5306 } 5656 }
5307 } 5657 }
5308 } 5658 }
5659
5660 float posX = 128.0f;
5661 float posY = 128.0f;
5662
5663 if (!TestLandRestrictions(agentID, out reason, ref posX, ref posY))
5664 {
5665 // m_log.DebugFormat("[SCENE]: Denying {0} because they are banned on all parcels", agentID);
5666 return false;
5667 }
5668 }
5669 else // Walking
5670 {
5671 ILandObject land = LandChannel.GetLandObject(position.X, position.Y);
5672 if (land == null)
5673 return false;
5674
5675 bool banned = land.IsBannedFromLand(agentID);
5676 bool restricted = land.IsRestrictedFromLand(agentID);
5677
5678 if (banned || restricted)
5679 return false;
5309 } 5680 }
5310 5681
5311 reason = String.Empty; 5682 reason = String.Empty;
5312 return true; 5683 return true;
5313 } 5684 }
5314 5685
5315 /// <summary> 5686 public void StartTimerWatchdog()
5687 {
5688 m_timerWatchdog.Interval = 1000;
5689 m_timerWatchdog.Elapsed += TimerWatchdog;
5690 m_timerWatchdog.AutoReset = true;
5691 m_timerWatchdog.Start();
5692 }
5693
5694 public void TimerWatchdog(object sender, ElapsedEventArgs e)
5695 {
5696 CheckHeartbeat();
5697 }
5698
5316 /// This method deals with movement when an avatar is automatically moving (but this is distinct from the 5699 /// This method deals with movement when an avatar is automatically moving (but this is distinct from the
5317 /// autopilot that moves an avatar to a sit target!. 5700 /// autopilot that moves an avatar to a sit target!.
5318 /// </summary> 5701 /// </summary>
diff --git a/OpenSim/Region/Framework/Scenes/SceneBase.cs b/OpenSim/Region/Framework/Scenes/SceneBase.cs
index f50fbfc..e8134cd 100644
--- a/OpenSim/Region/Framework/Scenes/SceneBase.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneBase.cs
@@ -138,6 +138,8 @@ namespace OpenSim.Region.Framework.Scenes
138 get { return m_permissions; } 138 get { return m_permissions; }
139 } 139 }
140 140
141 protected string m_datastore;
142
141 /* Used by the loadbalancer plugin on GForge */ 143 /* Used by the loadbalancer plugin on GForge */
142 protected RegionStatus m_regStatus; 144 protected RegionStatus m_regStatus;
143 public RegionStatus RegionStatus 145 public RegionStatus RegionStatus
diff --git a/OpenSim/Region/Framework/Scenes/SceneCommunicationService.cs b/OpenSim/Region/Framework/Scenes/SceneCommunicationService.cs
index eff635b..c1414ee 100644
--- a/OpenSim/Region/Framework/Scenes/SceneCommunicationService.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneCommunicationService.cs
@@ -182,10 +182,13 @@ namespace OpenSim.Region.Framework.Scenes
182 } 182 }
183 } 183 }
184 184
185 public delegate void SendCloseChildAgentDelegate(UUID agentID, ulong regionHandle);
186
185 /// <summary> 187 /// <summary>
186 /// Closes a child agent on a given region 188 /// This Closes child agents on neighboring regions
189 /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
187 /// </summary> 190 /// </summary>
188 protected void SendCloseChildAgent(UUID agentID, ulong regionHandle) 191 protected void SendCloseChildAgentAsync(UUID agentID, ulong regionHandle)
189 { 192 {
190 // let's do our best, but there's not much we can do if the neighbour doesn't accept. 193 // let's do our best, but there's not much we can do if the neighbour doesn't accept.
191 194
@@ -194,30 +197,29 @@ namespace OpenSim.Region.Framework.Scenes
194 Utils.LongToUInts(regionHandle, out x, out y); 197 Utils.LongToUInts(regionHandle, out x, out y);
195 198
196 GridRegion destination = m_scene.GridService.GetRegionByPosition(m_regionInfo.ScopeID, (int)x, (int)y); 199 GridRegion destination = m_scene.GridService.GetRegionByPosition(m_regionInfo.ScopeID, (int)x, (int)y);
200 m_scene.SimulationService.CloseChildAgent(destination, agentID);
201 }
197 202
198 m_log.DebugFormat( 203 private void SendCloseChildAgentCompleted(IAsyncResult iar)
199 "[SCENE COMMUNICATION SERVICE]: Sending close agent ID {0} to {1}", agentID, destination.RegionName); 204 {
200 205 SendCloseChildAgentDelegate icon = (SendCloseChildAgentDelegate)iar.AsyncState;
201 m_scene.SimulationService.CloseAgent(destination, agentID); 206 icon.EndInvoke(iar);
202 } 207 }
203 208
204 /// <summary>
205 /// Closes a child agents in a collection of regions. Does so asynchronously
206 /// so that the caller doesn't wait.
207 /// </summary>
208 /// <param name="agentID"></param>
209 /// <param name="regionslst"></param>
210 public void SendCloseChildAgentConnections(UUID agentID, List<ulong> regionslst) 209 public void SendCloseChildAgentConnections(UUID agentID, List<ulong> regionslst)
211 { 210 {
212 foreach (ulong handle in regionslst) 211 foreach (ulong handle in regionslst)
213 { 212 {
214 SendCloseChildAgent(agentID, handle); 213 SendCloseChildAgentDelegate d = SendCloseChildAgentAsync;
214 d.BeginInvoke(agentID, handle,
215 SendCloseChildAgentCompleted,
216 d);
215 } 217 }
216 } 218 }
217 219
218 public List<GridRegion> RequestNamedRegions(string name, int maxNumber) 220 public List<GridRegion> RequestNamedRegions(string name, int maxNumber)
219 { 221 {
220 return m_scene.GridService.GetRegionsByName(UUID.Zero, name, maxNumber); 222 return m_scene.GridService.GetRegionsByName(UUID.Zero, name, maxNumber);
221 } 223 }
222 } 224 }
223} \ No newline at end of file 225}
diff --git a/OpenSim/Region/Framework/Scenes/SceneGraph.cs b/OpenSim/Region/Framework/Scenes/SceneGraph.cs
index 2be5364..c3d66eb 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)
@@ -1638,6 +1824,8 @@ namespace OpenSim.Region.Framework.Scenes
1638 { 1824 {
1639 parentGroup.LinkToGroup(child); 1825 parentGroup.LinkToGroup(child);
1640 1826
1827 child.DetachFromBackup();
1828
1641 // this is here so physics gets updated! 1829 // this is here so physics gets updated!
1642 // Don't remove! Bad juju! Stay away! or fix physics! 1830 // Don't remove! Bad juju! Stay away! or fix physics!
1643 child.AbsolutePosition = child.AbsolutePosition; 1831 child.AbsolutePosition = child.AbsolutePosition;
@@ -1656,6 +1844,16 @@ namespace OpenSim.Region.Framework.Scenes
1656 } 1844 }
1657 finally 1845 finally
1658 { 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();
1659 Monitor.Exit(m_updateLock); 1857 Monitor.Exit(m_updateLock);
1660 } 1858 }
1661 } 1859 }
@@ -1678,6 +1876,11 @@ namespace OpenSim.Region.Framework.Scenes
1678 { 1876 {
1679 if (part != null) 1877 if (part != null)
1680 { 1878 {
1879 if (part.KeyframeMotion != null)
1880 {
1881 part.KeyframeMotion.Stop();
1882 part.KeyframeMotion = null;
1883 }
1681 if (part.ParentGroup.PrimCount != 1) // Skip single 1884 if (part.ParentGroup.PrimCount != 1) // Skip single
1682 { 1885 {
1683 if (part.LinkNum < 2) // Root 1886 if (part.LinkNum < 2) // Root
@@ -1692,21 +1895,24 @@ namespace OpenSim.Region.Framework.Scenes
1692 1895
1693 SceneObjectGroup group = part.ParentGroup; 1896 SceneObjectGroup group = part.ParentGroup;
1694 if (!affectedGroups.Contains(group)) 1897 if (!affectedGroups.Contains(group))
1898 {
1899 group.areUpdatesSuspended = true;
1695 affectedGroups.Add(group); 1900 affectedGroups.Add(group);
1901 }
1696 } 1902 }
1697 } 1903 }
1698 } 1904 }
1699 1905
1700 foreach (SceneObjectPart child in childParts) 1906 if (childParts.Count > 0)
1701 { 1907 {
1702 // Unlink all child parts from their groups 1908 foreach (SceneObjectPart child in childParts)
1703 // 1909 {
1704 child.ParentGroup.DelinkFromGroup(child, true); 1910 // Unlink all child parts from their groups
1705 1911 //
1706 // These are not in affected groups and will not be 1912 child.ParentGroup.DelinkFromGroup(child, true);
1707 // handled further. Do the honors here. 1913 child.ParentGroup.HasGroupChanged = true;
1708 child.ParentGroup.HasGroupChanged = true; 1914 child.ParentGroup.ScheduleGroupForFullUpdate();
1709 child.ParentGroup.ScheduleGroupForFullUpdate(); 1915 }
1710 } 1916 }
1711 1917
1712 foreach (SceneObjectPart root in rootParts) 1918 foreach (SceneObjectPart root in rootParts)
@@ -1716,56 +1922,68 @@ namespace OpenSim.Region.Framework.Scenes
1716 // However, editing linked parts and unlinking may be different 1922 // However, editing linked parts and unlinking may be different
1717 // 1923 //
1718 SceneObjectGroup group = root.ParentGroup; 1924 SceneObjectGroup group = root.ParentGroup;
1925 group.areUpdatesSuspended = true;
1719 1926
1720 List<SceneObjectPart> newSet = new List<SceneObjectPart>(group.Parts); 1927 List<SceneObjectPart> newSet = new List<SceneObjectPart>(group.Parts);
1721 int numChildren = newSet.Count; 1928 int numChildren = newSet.Count;
1722 1929
1930 if (numChildren == 1)
1931 break;
1932
1723 // 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
1724 // slated for unlink, we need to do this 1934 // slated for unlink, we need to do this
1935 // Unlink the remaining set
1725 // 1936 //
1726 if (numChildren != 1) 1937 bool sendEventsToRemainder = true;
1727 { 1938 if (numChildren > 1)
1728 // Unlink the remaining set 1939 sendEventsToRemainder = false;
1729 //
1730 bool sendEventsToRemainder = true;
1731 if (numChildren > 1)
1732 sendEventsToRemainder = false;
1733 1940
1734 foreach (SceneObjectPart p in newSet) 1941 foreach (SceneObjectPart p in newSet)
1942 {
1943 if (p != group.RootPart)
1735 { 1944 {
1736 if (p != group.RootPart) 1945 group.DelinkFromGroup(p, sendEventsToRemainder);
1737 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 }
1738 } 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);
1739 1967
1740 // If there is more than one prim remaining, we 1968 // Preserve link ordering
1741 // need to re-link
1742 // 1969 //
1743 if (numChildren > 2) 1970 newSet.Sort(delegate (SceneObjectPart a, SceneObjectPart b)
1744 { 1971 {
1745 // Remove old root 1972 return a.LinkNum.CompareTo(b.LinkNum);
1746 // 1973 });
1747 if (newSet.Contains(root))
1748 newSet.Remove(root);
1749
1750 // Preserve link ordering
1751 //
1752 newSet.Sort(delegate (SceneObjectPart a, SceneObjectPart b)
1753 {
1754 return a.LinkNum.CompareTo(b.LinkNum);
1755 });
1756 1974
1757 // Determine new root 1975 // Determine new root
1758 // 1976 //
1759 SceneObjectPart newRoot = newSet[0]; 1977 SceneObjectPart newRoot = newSet[0];
1760 newSet.RemoveAt(0); 1978 newSet.RemoveAt(0);
1761 1979
1762 foreach (SceneObjectPart newChild in newSet) 1980 foreach (SceneObjectPart newChild in newSet)
1763 newChild.ClearUpdateSchedule(); 1981 newChild.ClearUpdateSchedule();
1764 1982
1765 LinkObjects(newRoot, newSet); 1983 newRoot.ParentGroup.areUpdatesSuspended = true;
1766 if (!affectedGroups.Contains(newRoot.ParentGroup)) 1984 LinkObjects(newRoot, newSet);
1767 affectedGroups.Add(newRoot.ParentGroup); 1985 if (!affectedGroups.Contains(newRoot.ParentGroup))
1768 } 1986 affectedGroups.Add(newRoot.ParentGroup);
1769 } 1987 }
1770 } 1988 }
1771 1989
@@ -1773,8 +1991,14 @@ namespace OpenSim.Region.Framework.Scenes
1773 // 1991 //
1774 foreach (SceneObjectGroup g in affectedGroups) 1992 foreach (SceneObjectGroup g in affectedGroups)
1775 { 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);
1776 g.TriggerScriptChangedEvent(Changed.LINK); 1999 g.TriggerScriptChangedEvent(Changed.LINK);
1777 g.HasGroupChanged = true; // Persist 2000 g.HasGroupChanged = true; // Persist
2001 g.areUpdatesSuspended = false;
1778 g.ScheduleGroupForFullUpdate(); 2002 g.ScheduleGroupForFullUpdate();
1779 } 2003 }
1780 } 2004 }
@@ -1846,108 +2070,96 @@ namespace OpenSim.Region.Framework.Scenes
1846 /// <param name="GroupID"></param> 2070 /// <param name="GroupID"></param>
1847 /// <param name="rot"></param> 2071 /// <param name="rot"></param>
1848 /// <returns>null if duplication fails, otherwise the duplicated object</returns> 2072 /// <returns>null if duplication fails, otherwise the duplicated object</returns>
1849 public SceneObjectGroup DuplicateObject( 2073 /// <summary>
1850 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)
1851 { 2075 {
1852 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);
1853 2079
1854 try 2080 SceneObjectGroup original = GetGroupByPrim(originalPrimID);
2081 if (original != null)
1855 { 2082 {
1856 // m_log.DebugFormat( 2083 if (m_parentScene.Permissions.CanDuplicateObject(
1857 // "[SCENE]: Duplication of object {0} at offset {1} requested by agent {2}", 2084 original.PrimCount, original.UUID, AgentID, original.AbsolutePosition))
1858 // originalPrimID, offset, AgentID);
1859
1860 SceneObjectGroup original = GetGroupByPrim(originalPrimID);
1861 if (original == null)
1862 { 2085 {
1863 m_log.WarnFormat( 2086 SceneObjectGroup copy = original.Copy(true);
1864 "[SCENEGRAPH]: Attempt to duplicate nonexistant prim id {0} by {1}", originalPrimID, AgentID); 2087 copy.AbsolutePosition = copy.AbsolutePosition + offset;
1865 2088
1866 return null; 2089 if (original.OwnerID != AgentID)
1867 } 2090 {
2091 copy.SetOwnerId(AgentID);
2092 copy.SetRootPartOwner(copy.RootPart, AgentID, GroupID);
1868 2093
1869 if (!m_parentScene.Permissions.CanDuplicateObject( 2094 SceneObjectPart[] partList = copy.Parts;
1870 original.PrimCount, original.UUID, AgentID, original.AbsolutePosition))
1871 return null;
1872 2095
1873 SceneObjectGroup copy = original.Copy(true); 2096 if (m_parentScene.Permissions.PropagatePermissions())
1874 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 }
1875 2106
1876 if (original.OwnerID != AgentID) 2107 // FIXME: This section needs to be refactored so that it just calls AddSceneObject()
1877 { 2108 Entities.Add(copy);
1878 copy.SetOwnerId(AgentID);
1879 copy.SetRootPartOwner(copy.RootPart, AgentID, GroupID);
1880 2109
1881 SceneObjectPart[] partList = copy.Parts; 2110 lock (SceneObjectGroupsByFullID)
2111 SceneObjectGroupsByFullID[copy.UUID] = copy;
1882 2112
1883 if (m_parentScene.Permissions.PropagatePermissions()) 2113 SceneObjectPart[] children = copy.Parts;
2114
2115 lock (SceneObjectGroupsByFullPartID)
1884 { 2116 {
1885 foreach (SceneObjectPart child in partList) 2117 SceneObjectGroupsByFullPartID[copy.UUID] = copy;
1886 { 2118 foreach (SceneObjectPart part in children)
1887 child.Inventory.ChangeInventoryOwner(AgentID); 2119 SceneObjectGroupsByFullPartID[part.UUID] = copy;
1888 child.TriggerScriptChangedEvent(Changed.OWNER);
1889 child.ApplyNextOwnerPermissions();
1890 }
1891 } 2120 }
1892 2121
1893 copy.RootPart.ObjectSaleType = 0; 2122 lock (SceneObjectGroupsByLocalPartID)
1894 copy.RootPart.SalePrice = 10; 2123 {
1895 } 2124 SceneObjectGroupsByLocalPartID[copy.LocalId] = copy;
2125 foreach (SceneObjectPart part in children)
2126 SceneObjectGroupsByLocalPartID[part.LocalId] = copy;
2127 }
2128 // PROBABLE END OF FIXME
1896 2129
1897 // 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
1898 Entities.Add(copy); 2131 // state, but the copy is shown deselected in the viewer,
1899 2132 // We need to clear the selection flag here, else that
1900 lock (SceneObjectGroupsByFullID) 2133 // prim never gets persisted at all. The client doesn't
1901 SceneObjectGroupsByFullID[copy.UUID] = copy; 2134 // think it's selected, so it will never send a deselect...
1902 2135 copy.IsSelected = false;
1903 SceneObjectPart[] children = copy.Parts; 2136
1904 2137 m_numPrim += copy.Parts.Length;
1905 lock (SceneObjectGroupsByFullPartID) 2138
1906 { 2139 if (rot != Quaternion.Identity)
1907 SceneObjectGroupsByFullPartID[copy.UUID] = copy; 2140 {
1908 foreach (SceneObjectPart part in children) 2141 copy.UpdateGroupRotationR(rot);
1909 SceneObjectGroupsByFullPartID[part.UUID] = copy; 2142 }
1910 }
1911
1912 lock (SceneObjectGroupsByLocalPartID)
1913 {
1914 SceneObjectGroupsByLocalPartID[copy.LocalId] = copy;
1915 foreach (SceneObjectPart part in children)
1916 SceneObjectGroupsByLocalPartID[part.LocalId] = copy;
1917 }
1918 // PROBABLE END OF FIXME
1919
1920 // Since we copy from a source group that is in selected
1921 // state, but the copy is shown deselected in the viewer,
1922 // We need to clear the selection flag here, else that
1923 // prim never gets persisted at all. The client doesn't
1924 // think it's selected, so it will never send a deselect...
1925 copy.IsSelected = false;
1926
1927 m_numPrim += copy.Parts.Length;
1928
1929 if (rot != Quaternion.Identity)
1930 {
1931 copy.UpdateGroupRotationR(rot);
1932 }
1933 2143
1934 copy.CreateScriptInstances(0, false, m_parentScene.DefaultScriptEngine, 1); 2144 copy.CreateScriptInstances(0, false, m_parentScene.DefaultScriptEngine, 1);
1935 copy.HasGroupChanged = true; 2145 copy.HasGroupChanged = true;
1936 copy.ScheduleGroupForFullUpdate(); 2146 copy.ScheduleGroupForFullUpdate();
1937 copy.ResumeScripts(); 2147 copy.ResumeScripts();
1938 2148
1939 // required for physics to update it's position 2149 // required for physics to update it's position
1940 copy.AbsolutePosition = copy.AbsolutePosition; 2150 copy.AbsolutePosition = copy.AbsolutePosition;
1941 2151
1942 return copy; 2152 return copy;
2153 }
1943 } 2154 }
1944 finally 2155 else
1945 { 2156 {
1946 Monitor.Exit(m_updateLock); 2157 m_log.WarnFormat("[SCENE]: Attempted to duplicate nonexistant prim id {0}", GroupID);
1947 } 2158 }
2159
2160 return null;
1948 } 2161 }
1949 2162
1950 /// <summary>
1951 /// Calculates the distance between two Vector3s 2163 /// Calculates the distance between two Vector3s
1952 /// </summary> 2164 /// </summary>
1953 /// <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 d73a959..e3fed49 100644
--- a/OpenSim/Region/Framework/Scenes/SceneManager.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneManager.cs
@@ -53,12 +53,12 @@ namespace OpenSim.Region.Framework.Scenes
53 get { return m_instance; } 53 get { return m_instance; }
54 } 54 }
55 55
56 private readonly List<Scene> m_localScenes = new List<Scene>(); 56 private readonly DoubleDictionary<UUID, string, Scene> m_localScenes = new DoubleDictionary<UUID, string, Scene>();
57 private Scene m_currentScene = null; 57 private Scene m_currentScene = null;
58 58
59 public List<Scene> Scenes 59 public List<Scene> Scenes
60 { 60 {
61 get { return new List<Scene>(m_localScenes); } 61 get { return new List<Scene>(m_localScenes.FindAll(delegate(Scene s) { return true; })); }
62 } 62 }
63 63
64 public Scene CurrentScene 64 public Scene CurrentScene
@@ -72,13 +72,10 @@ namespace OpenSim.Region.Framework.Scenes
72 { 72 {
73 if (m_currentScene == null) 73 if (m_currentScene == null)
74 { 74 {
75 lock (m_localScenes) 75 List<Scene> sceneList = Scenes;
76 { 76 if (sceneList.Count == 0)
77 if (m_localScenes.Count > 0) 77 return null;
78 return m_localScenes[0]; 78 return sceneList[0];
79 else
80 return null;
81 }
82 } 79 }
83 else 80 else
84 { 81 {
@@ -90,7 +87,7 @@ namespace OpenSim.Region.Framework.Scenes
90 public SceneManager() 87 public SceneManager()
91 { 88 {
92 m_instance = this; 89 m_instance = this;
93 m_localScenes = new List<Scene>(); 90 m_localScenes = new DoubleDictionary<UUID, string, Scene>();
94 } 91 }
95 92
96 public void Close() 93 public void Close()
@@ -98,20 +95,18 @@ namespace OpenSim.Region.Framework.Scenes
98 // collect known shared modules in sharedModules 95 // collect known shared modules in sharedModules
99 Dictionary<string, IRegionModule> sharedModules = new Dictionary<string, IRegionModule>(); 96 Dictionary<string, IRegionModule> sharedModules = new Dictionary<string, IRegionModule>();
100 97
101 lock (m_localScenes) 98 List<Scene> sceneList = Scenes;
99 for (int i = 0; i < sceneList.Count; i++)
102 { 100 {
103 for (int i = 0; i < m_localScenes.Count; i++) 101 // extract known shared modules from scene
102 foreach (string k in sceneList[i].Modules.Keys)
104 { 103 {
105 // extract known shared modules from scene 104 if (sceneList[i].Modules[k].IsSharedModule &&
106 foreach (string k in m_localScenes[i].Modules.Keys) 105 !sharedModules.ContainsKey(k))
107 { 106 sharedModules[k] = sceneList[i].Modules[k];
108 if (m_localScenes[i].Modules[k].IsSharedModule &&
109 !sharedModules.ContainsKey(k))
110 sharedModules[k] = m_localScenes[i].Modules[k];
111 }
112 // close scene/region
113 m_localScenes[i].Close();
114 } 107 }
108 // close scene/region
109 sceneList[i].Close();
115 } 110 }
116 111
117 // all regions/scenes are now closed, we can now safely 112 // all regions/scenes are now closed, we can now safely
@@ -120,31 +115,22 @@ namespace OpenSim.Region.Framework.Scenes
120 { 115 {
121 mod.Close(); 116 mod.Close();
122 } 117 }
118
119 m_localScenes.Clear();
123 } 120 }
124 121
125 public void Close(Scene cscene) 122 public void Close(Scene cscene)
126 { 123 {
127 lock (m_localScenes) 124 if (!m_localScenes.ContainsKey(cscene.RegionInfo.RegionID))
128 { 125 return;
129 if (m_localScenes.Contains(cscene)) 126 cscene.Close();
130 {
131 for (int i = 0; i < m_localScenes.Count; i++)
132 {
133 if (m_localScenes[i].Equals(cscene))
134 {
135 m_localScenes[i].Close();
136 }
137 }
138 }
139 }
140 } 127 }
141 128
142 public void Add(Scene scene) 129 public void Add(Scene scene)
143 { 130 {
144 scene.OnRestart += HandleRestart; 131 scene.OnRestart += HandleRestart;
145 132
146 lock (m_localScenes) 133 m_localScenes.Add(scene.RegionInfo.RegionID, scene.RegionInfo.RegionName, scene);
147 m_localScenes.Add(scene);
148 } 134 }
149 135
150 public void HandleRestart(RegionInfo rdata) 136 public void HandleRestart(RegionInfo rdata)
@@ -152,24 +138,7 @@ namespace OpenSim.Region.Framework.Scenes
152 m_log.Error("[SCENEMANAGER]: Got Restart message for region:" + rdata.RegionName + " Sending up to main"); 138 m_log.Error("[SCENEMANAGER]: Got Restart message for region:" + rdata.RegionName + " Sending up to main");
153 int RegionSceneElement = -1; 139 int RegionSceneElement = -1;
154 140
155 lock (m_localScenes) 141 m_localScenes.Remove(rdata.RegionID);
156 {
157 for (int i = 0; i < m_localScenes.Count; i++)
158 {
159 if (rdata.RegionName == m_localScenes[i].RegionInfo.RegionName)
160 {
161 RegionSceneElement = i;
162 }
163 }
164
165 // Now we make sure the region is no longer known about by the SceneManager
166 // Prevents duplicates.
167
168 if (RegionSceneElement >= 0)
169 {
170 m_localScenes.RemoveAt(RegionSceneElement);
171 }
172 }
173 142
174 // Send signal to main that we're restarting this sim. 143 // Send signal to main that we're restarting this sim.
175 OnRestartSim(rdata); 144 OnRestartSim(rdata);
@@ -179,32 +148,29 @@ namespace OpenSim.Region.Framework.Scenes
179 { 148 {
180 RegionInfo Result = null; 149 RegionInfo Result = null;
181 150
182 lock (m_localScenes) 151 Scene s = m_localScenes.FindValue(delegate(Scene x)
183 {
184 for (int i = 0; i < m_localScenes.Count; i++)
185 {
186 if (m_localScenes[i].RegionInfo.RegionHandle == regionHandle)
187 { 152 {
188 // Inform other regions to tell their avatar about me 153 if (x.RegionInfo.RegionHandle == regionHandle)
189 Result = m_localScenes[i].RegionInfo; 154 return true;
190 } 155 return false;
191 } 156 });
192 157
193 if (Result != null) 158 if (s != null)
159 {
160 List<Scene> sceneList = Scenes;
161
162 for (int i = 0; i < sceneList.Count; i++)
194 { 163 {
195 for (int i = 0; i < m_localScenes.Count; i++) 164 if (sceneList[i]!= s)
196 { 165 {
197 if (m_localScenes[i].RegionInfo.RegionHandle != regionHandle) 166 // Inform other regions to tell their avatar about me
198 { 167 //sceneList[i].OtherRegionUp(Result);
199 // Inform other regions to tell their avatar about me
200 //m_localScenes[i].OtherRegionUp(Result);
201 }
202 } 168 }
203 } 169 }
204 else 170 }
205 { 171 else
206 m_log.Error("[REGION]: Unable to notify Other regions of this Region coming up"); 172 {
207 } 173 m_log.Error("[REGION]: Unable to notify Other regions of this Region coming up");
208 } 174 }
209 } 175 }
210 176
@@ -308,8 +274,8 @@ namespace OpenSim.Region.Framework.Scenes
308 { 274 {
309 if (m_currentScene == null) 275 if (m_currentScene == null)
310 { 276 {
311 lock (m_localScenes) 277 List<Scene> sceneList = Scenes;
312 m_localScenes.ForEach(func); 278 sceneList.ForEach(func);
313 } 279 }
314 else 280 else
315 { 281 {
@@ -338,16 +304,12 @@ namespace OpenSim.Region.Framework.Scenes
338 } 304 }
339 else 305 else
340 { 306 {
341 lock (m_localScenes) 307 Scene s;
308
309 if (m_localScenes.TryGetValue(regionName, out s))
342 { 310 {
343 foreach (Scene scene in m_localScenes) 311 m_currentScene = s;
344 { 312 return true;
345 if (String.Compare(scene.RegionInfo.RegionName, regionName, true) == 0)
346 {
347 m_currentScene = scene;
348 return true;
349 }
350 }
351 } 313 }
352 314
353 return false; 315 return false;
@@ -356,18 +318,14 @@ namespace OpenSim.Region.Framework.Scenes
356 318
357 public bool TrySetCurrentScene(UUID regionID) 319 public bool TrySetCurrentScene(UUID regionID)
358 { 320 {
359 m_log.Debug("Searching for Region: '" + regionID + "'"); 321// m_log.Debug("Searching for Region: '" + regionID + "'");
360 322
361 lock (m_localScenes) 323 Scene s;
324
325 if (m_localScenes.TryGetValue(regionID, out s))
362 { 326 {
363 foreach (Scene scene in m_localScenes) 327 m_currentScene = s;
364 { 328 return true;
365 if (scene.RegionInfo.RegionID == regionID)
366 {
367 m_currentScene = scene;
368 return true;
369 }
370 }
371 } 329 }
372 330
373 return false; 331 return false;
@@ -375,52 +333,24 @@ namespace OpenSim.Region.Framework.Scenes
375 333
376 public bool TryGetScene(string regionName, out Scene scene) 334 public bool TryGetScene(string regionName, out Scene scene)
377 { 335 {
378 lock (m_localScenes) 336 return m_localScenes.TryGetValue(regionName, out scene);
379 {
380 foreach (Scene mscene in m_localScenes)
381 {
382 if (String.Compare(mscene.RegionInfo.RegionName, regionName, true) == 0)
383 {
384 scene = mscene;
385 return true;
386 }
387 }
388 }
389
390 scene = null;
391 return false;
392 } 337 }
393 338
394 public bool TryGetScene(UUID regionID, out Scene scene) 339 public bool TryGetScene(UUID regionID, out Scene scene)
395 { 340 {
396 lock (m_localScenes) 341 return m_localScenes.TryGetValue(regionID, out scene);
397 {
398 foreach (Scene mscene in m_localScenes)
399 {
400 if (mscene.RegionInfo.RegionID == regionID)
401 {
402 scene = mscene;
403 return true;
404 }
405 }
406 }
407
408 scene = null;
409 return false;
410 } 342 }
411 343
412 public bool TryGetScene(uint locX, uint locY, out Scene scene) 344 public bool TryGetScene(uint locX, uint locY, out Scene scene)
413 { 345 {
414 lock (m_localScenes) 346 List<Scene> sceneList = Scenes;
347 foreach (Scene mscene in sceneList)
415 { 348 {
416 foreach (Scene mscene in m_localScenes) 349 if (mscene.RegionInfo.RegionLocX == locX &&
350 mscene.RegionInfo.RegionLocY == locY)
417 { 351 {
418 if (mscene.RegionInfo.RegionLocX == locX && 352 scene = mscene;
419 mscene.RegionInfo.RegionLocY == locY) 353 return true;
420 {
421 scene = mscene;
422 return true;
423 }
424 } 354 }
425 } 355 }
426 356
@@ -430,16 +360,14 @@ namespace OpenSim.Region.Framework.Scenes
430 360
431 public bool TryGetScene(IPEndPoint ipEndPoint, out Scene scene) 361 public bool TryGetScene(IPEndPoint ipEndPoint, out Scene scene)
432 { 362 {
433 lock (m_localScenes) 363 List<Scene> sceneList = Scenes;
364 foreach (Scene mscene in sceneList)
434 { 365 {
435 foreach (Scene mscene in m_localScenes) 366 if ((mscene.RegionInfo.InternalEndPoint.Equals(ipEndPoint.Address)) &&
367 (mscene.RegionInfo.InternalEndPoint.Port == ipEndPoint.Port))
436 { 368 {
437 if ((mscene.RegionInfo.InternalEndPoint.Equals(ipEndPoint.Address)) && 369 scene = mscene;
438 (mscene.RegionInfo.InternalEndPoint.Port == ipEndPoint.Port)) 370 return true;
439 {
440 scene = mscene;
441 return true;
442 }
443 } 371 }
444 } 372 }
445 373
@@ -504,15 +432,10 @@ namespace OpenSim.Region.Framework.Scenes
504 432
505 public RegionInfo GetRegionInfo(UUID regionID) 433 public RegionInfo GetRegionInfo(UUID regionID)
506 { 434 {
507 lock (m_localScenes) 435 Scene s;
436 if (m_localScenes.TryGetValue(regionID, out s))
508 { 437 {
509 foreach (Scene scene in m_localScenes) 438 return s.RegionInfo;
510 {
511 if (scene.RegionInfo.RegionID == regionID)
512 {
513 return scene.RegionInfo;
514 }
515 }
516 } 439 }
517 440
518 return null; 441 return null;
@@ -530,14 +453,12 @@ namespace OpenSim.Region.Framework.Scenes
530 453
531 public bool TryGetScenePresence(UUID avatarId, out ScenePresence avatar) 454 public bool TryGetScenePresence(UUID avatarId, out ScenePresence avatar)
532 { 455 {
533 lock (m_localScenes) 456 List<Scene> sceneList = Scenes;
457 foreach (Scene scene in sceneList)
534 { 458 {
535 foreach (Scene scene in m_localScenes) 459 if (scene.TryGetScenePresence(avatarId, out avatar))
536 { 460 {
537 if (scene.TryGetScenePresence(avatarId, out avatar)) 461 return true;
538 {
539 return true;
540 }
541 } 462 }
542 } 463 }
543 464
@@ -547,15 +468,13 @@ namespace OpenSim.Region.Framework.Scenes
547 468
548 public bool TryGetRootScenePresence(UUID avatarId, out ScenePresence avatar) 469 public bool TryGetRootScenePresence(UUID avatarId, out ScenePresence avatar)
549 { 470 {
550 lock (m_localScenes) 471 List<Scene> sceneList = Scenes;
472 foreach (Scene scene in sceneList)
551 { 473 {
552 foreach (Scene scene in m_localScenes) 474 avatar = scene.GetScenePresence(avatarId);
553 {
554 avatar = scene.GetScenePresence(avatarId);
555 475
556 if (avatar != null && !avatar.IsChildAgent) 476 if (avatar != null && !avatar.IsChildAgent)
557 return true; 477 return true;
558 }
559 } 478 }
560 479
561 avatar = null; 480 avatar = null;
@@ -564,22 +483,19 @@ namespace OpenSim.Region.Framework.Scenes
564 483
565 public void CloseScene(Scene scene) 484 public void CloseScene(Scene scene)
566 { 485 {
567 lock (m_localScenes) 486 m_localScenes.Remove(scene.RegionInfo.RegionID);
568 m_localScenes.Remove(scene);
569 487
570 scene.Close(); 488 scene.Close();
571 } 489 }
572 490
573 public bool TryGetAvatarByName(string avatarName, out ScenePresence avatar) 491 public bool TryGetAvatarByName(string avatarName, out ScenePresence avatar)
574 { 492 {
575 lock (m_localScenes) 493 List<Scene> sceneList = Scenes;
494 foreach (Scene scene in sceneList)
576 { 495 {
577 foreach (Scene scene in m_localScenes) 496 if (scene.TryGetAvatarByName(avatarName, out avatar))
578 { 497 {
579 if (scene.TryGetAvatarByName(avatarName, out avatar)) 498 return true;
580 {
581 return true;
582 }
583 } 499 }
584 } 500 }
585 501
@@ -589,14 +505,12 @@ namespace OpenSim.Region.Framework.Scenes
589 505
590 public bool TryGetRootScenePresenceByName(string firstName, string lastName, out ScenePresence sp) 506 public bool TryGetRootScenePresenceByName(string firstName, string lastName, out ScenePresence sp)
591 { 507 {
592 lock (m_localScenes) 508 List<Scene> sceneList = Scenes;
509 foreach (Scene scene in sceneList)
593 { 510 {
594 foreach (Scene scene in m_localScenes) 511 sp = scene.GetScenePresence(firstName, lastName);
595 { 512 if (sp != null && !sp.IsChildAgent)
596 sp = scene.GetScenePresence(firstName, lastName); 513 return true;
597 if (sp != null && !sp.IsChildAgent)
598 return true;
599 }
600 } 514 }
601 515
602 sp = null; 516 sp = null;
@@ -605,8 +519,8 @@ namespace OpenSim.Region.Framework.Scenes
605 519
606 public void ForEachScene(Action<Scene> action) 520 public void ForEachScene(Action<Scene> action)
607 { 521 {
608 lock (m_localScenes) 522 List<Scene> sceneList = Scenes;
609 m_localScenes.ForEach(action); 523 sceneList.ForEach(action);
610 } 524 }
611 } 525 }
612} 526}
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 52469a2..33a2cc5 100644
--- a/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs
@@ -24,11 +24,12 @@
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.Collections.Generic; 29using System.Collections.Generic;
30using System.Drawing; 30using System.Drawing;
31using System.IO; 31using System.IO;
32using System.Diagnostics;
32using System.Linq; 33using System.Linq;
33using System.Threading; 34using System.Threading;
34using System.Xml; 35using System.Xml;
@@ -42,6 +43,7 @@ using OpenSim.Region.Framework.Scenes.Serialization;
42 43
43namespace OpenSim.Region.Framework.Scenes 44namespace OpenSim.Region.Framework.Scenes
44{ 45{
46
45 [Flags] 47 [Flags]
46 public enum scriptEvents 48 public enum scriptEvents
47 { 49 {
@@ -105,8 +107,29 @@ namespace OpenSim.Region.Framework.Scenes
105 /// since the group's last persistent backup 107 /// since the group's last persistent backup
106 /// </summary> 108 /// </summary>
107 private bool m_hasGroupChanged = false; 109 private bool m_hasGroupChanged = false;
108 private long timeFirstChanged; 110 private long timeFirstChanged = 0;
109 private long timeLastChanged; 111 private long timeLastChanged = 0;
112 private long m_maxPersistTime = 0;
113 private long m_minPersistTime = 0;
114 private Random m_rand;
115 private bool m_suspendUpdates;
116 private List<ScenePresence> m_linkedAvatars = new List<ScenePresence>();
117
118 public bool areUpdatesSuspended
119 {
120 get
121 {
122 return m_suspendUpdates;
123 }
124 set
125 {
126 m_suspendUpdates = value;
127 if (!value)
128 {
129 QueueForUpdateCheck();
130 }
131 }
132 }
110 133
111 /// <summary> 134 /// <summary>
112 /// This indicates whether the object has changed such that it needs to be repersisted to permenant storage 135 /// This indicates whether the object has changed such that it needs to be repersisted to permenant storage
@@ -123,9 +146,39 @@ namespace OpenSim.Region.Framework.Scenes
123 { 146 {
124 if (value) 147 if (value)
125 { 148 {
149 if (m_isBackedUp)
150 {
151 m_scene.SceneGraph.FireChangeBackup(this);
152 }
126 timeLastChanged = DateTime.Now.Ticks; 153 timeLastChanged = DateTime.Now.Ticks;
127 if (!m_hasGroupChanged) 154 if (!m_hasGroupChanged)
128 timeFirstChanged = DateTime.Now.Ticks; 155 timeFirstChanged = DateTime.Now.Ticks;
156 if (m_rootPart != null && m_rootPart.UUID != null && m_scene != null)
157 {
158 if (m_rand == null)
159 {
160 byte[] val = new byte[16];
161 m_rootPart.UUID.ToBytes(val, 0);
162 m_rand = new Random(BitConverter.ToInt32(val, 0));
163 }
164
165 if (m_scene.GetRootAgentCount() == 0)
166 {
167 //If the region is empty, this change has been made by an automated process
168 //and thus we delay the persist time by a random amount between 1.5 and 2.5.
169
170 float factor = 1.5f + (float)(m_rand.NextDouble());
171 m_maxPersistTime = (long)((float)m_scene.m_persistAfter * factor);
172 m_minPersistTime = (long)((float)m_scene.m_dontPersistBefore * factor);
173 }
174 else
175 {
176 //If the region is not empty, we want to obey the minimum and maximum persist times
177 //but add a random factor so we stagger the object persistance a little
178 m_maxPersistTime = (long)((float)m_scene.m_persistAfter * (1.0d - (m_rand.NextDouble() / 5.0d))); //Multiply by 1.0-1.5
179 m_minPersistTime = (long)((float)m_scene.m_dontPersistBefore * (1.0d + (m_rand.NextDouble() / 2.0d))); //Multiply by 0.8-1.0
180 }
181 }
129 } 182 }
130 m_hasGroupChanged = value; 183 m_hasGroupChanged = value;
131 184
@@ -140,7 +193,7 @@ namespace OpenSim.Region.Framework.Scenes
140 /// Has the group changed due to an unlink operation? We record this in order to optimize deletion, since 193 /// Has the group changed due to an unlink operation? We record this in order to optimize deletion, since
141 /// an unlinked group currently has to be persisted to the database before we can perform an unlink operation. 194 /// an unlinked group currently has to be persisted to the database before we can perform an unlink operation.
142 /// </summary> 195 /// </summary>
143 public bool HasGroupChangedDueToDelink { get; private set; } 196 public bool HasGroupChangedDueToDelink { get; set; }
144 197
145 private bool isTimeToPersist() 198 private bool isTimeToPersist()
146 { 199 {
@@ -150,8 +203,19 @@ namespace OpenSim.Region.Framework.Scenes
150 return false; 203 return false;
151 if (m_scene.ShuttingDown) 204 if (m_scene.ShuttingDown)
152 return true; 205 return true;
206
207 if (m_minPersistTime == 0 || m_maxPersistTime == 0)
208 {
209 m_maxPersistTime = m_scene.m_persistAfter;
210 m_minPersistTime = m_scene.m_dontPersistBefore;
211 }
212
153 long currentTime = DateTime.Now.Ticks; 213 long currentTime = DateTime.Now.Ticks;
154 if (currentTime - timeLastChanged > m_scene.m_dontPersistBefore || currentTime - timeFirstChanged > m_scene.m_persistAfter) 214
215 if (timeLastChanged == 0) timeLastChanged = currentTime;
216 if (timeFirstChanged == 0) timeFirstChanged = currentTime;
217
218 if (currentTime - timeLastChanged > m_minPersistTime || currentTime - timeFirstChanged > m_maxPersistTime)
155 return true; 219 return true;
156 return false; 220 return false;
157 } 221 }
@@ -270,10 +334,10 @@ namespace OpenSim.Region.Framework.Scenes
270 334
271 private bool m_scriptListens_atTarget; 335 private bool m_scriptListens_atTarget;
272 private bool m_scriptListens_notAtTarget; 336 private bool m_scriptListens_notAtTarget;
273
274 private bool m_scriptListens_atRotTarget; 337 private bool m_scriptListens_atRotTarget;
275 private bool m_scriptListens_notAtRotTarget; 338 private bool m_scriptListens_notAtRotTarget;
276 339
340 public bool m_dupeInProgress = false;
277 internal Dictionary<UUID, string> m_savedScriptState; 341 internal Dictionary<UUID, string> m_savedScriptState;
278 342
279 #region Properties 343 #region Properties
@@ -310,6 +374,16 @@ namespace OpenSim.Region.Framework.Scenes
310 get { return m_parts.Count; } 374 get { return m_parts.Count; }
311 } 375 }
312 376
377// protected Quaternion m_rotation = Quaternion.Identity;
378//
379// public virtual Quaternion Rotation
380// {
381// get { return m_rotation; }
382// set {
383// m_rotation = value;
384// }
385// }
386
313 public Quaternion GroupRotation 387 public Quaternion GroupRotation
314 { 388 {
315 get { return m_rootPart.RotationOffset; } 389 get { return m_rootPart.RotationOffset; }
@@ -416,7 +490,15 @@ namespace OpenSim.Region.Framework.Scenes
416 { 490 {
417 return (IsAttachment || (m_rootPart.Shape.PCode == 9 && m_rootPart.Shape.State != 0)); 491 return (IsAttachment || (m_rootPart.Shape.PCode == 9 && m_rootPart.Shape.State != 0));
418 } 492 }
419 493
494
495
496 private struct avtocrossInfo
497 {
498 public ScenePresence av;
499 public uint ParentID;
500 }
501
420 /// <summary> 502 /// <summary>
421 /// The absolute position of this scene object in the scene 503 /// The absolute position of this scene object in the scene
422 /// </summary> 504 /// </summary>
@@ -429,14 +511,128 @@ namespace OpenSim.Region.Framework.Scenes
429 511
430 if (Scene != null) 512 if (Scene != null)
431 { 513 {
432 if ((Scene.TestBorderCross(val - Vector3.UnitX, Cardinals.E) || Scene.TestBorderCross(val + Vector3.UnitX, Cardinals.W) 514 // if ((Scene.TestBorderCross(val - Vector3.UnitX, Cardinals.E) || Scene.TestBorderCross(val + Vector3.UnitX, Cardinals.W)
433 || Scene.TestBorderCross(val - Vector3.UnitY, Cardinals.N) || Scene.TestBorderCross(val + Vector3.UnitY, Cardinals.S)) 515 // || Scene.TestBorderCross(val - Vector3.UnitY, Cardinals.N) || Scene.TestBorderCross(val + Vector3.UnitY, Cardinals.S))
516 // && !IsAttachmentCheckFull() && (!Scene.LoadingPrims))
517 if ((Scene.TestBorderCross(val, Cardinals.E) || Scene.TestBorderCross(val, Cardinals.W)
518 || Scene.TestBorderCross(val, Cardinals.N) || Scene.TestBorderCross(val, Cardinals.S))
434 && !IsAttachmentCheckFull() && (!Scene.LoadingPrims)) 519 && !IsAttachmentCheckFull() && (!Scene.LoadingPrims))
435 { 520 {
436 m_scene.CrossPrimGroupIntoNewRegion(val, this, true); 521 IEntityTransferModule entityTransfer = m_scene.RequestModuleInterface<IEntityTransferModule>();
522 uint x = 0;
523 uint y = 0;
524 string version = String.Empty;
525 Vector3 newpos = Vector3.Zero;
526 OpenSim.Services.Interfaces.GridRegion destination = null;
527
528 bool canCross = true;
529 foreach (ScenePresence av in m_linkedAvatars)
530 {
531 // We need to cross these agents. First, let's find
532 // out if any of them can't cross for some reason.
533 // We have to deny the crossing entirely if any
534 // of them are banned. Alternatively, we could
535 // unsit banned agents....
536
537
538 // We set the avatar position as being the object
539 // position to get the region to send to
540 if ((destination = entityTransfer.GetDestination(m_scene, av.UUID, val, out x, out y, out version, out newpos)) == null)
541 {
542 canCross = false;
543 break;
544 }
545
546 m_log.DebugFormat("[SCENE OBJECT]: Avatar {0} needs to be crossed to {1}", av.Name, destination.RegionName);
547 }
548
549 if (canCross)
550 {
551 // We unparent the SP quietly so that it won't
552 // be made to stand up
553
554 List<avtocrossInfo> avsToCross = new List<avtocrossInfo>();
555
556 foreach (ScenePresence av in m_linkedAvatars)
557 {
558 avtocrossInfo avinfo = new avtocrossInfo();
559 SceneObjectPart parentPart = m_scene.GetSceneObjectPart(av.ParentID);
560 if (parentPart != null)
561 av.ParentUUID = parentPart.UUID;
562
563 avinfo.av = av;
564 avinfo.ParentID = av.ParentID;
565 avsToCross.Add(avinfo);
566
567 av.ParentID = 0;
568 }
569
570// m_linkedAvatars.Clear();
571 m_scene.CrossPrimGroupIntoNewRegion(val, this, true);
572
573 // Normalize
574 if (val.X >= Constants.RegionSize)
575 val.X -= Constants.RegionSize;
576 if (val.Y >= Constants.RegionSize)
577 val.Y -= Constants.RegionSize;
578 if (val.X < 0)
579 val.X += Constants.RegionSize;
580 if (val.Y < 0)
581 val.Y += Constants.RegionSize;
582
583 // If it's deleted, crossing was successful
584 if (IsDeleted)
585 {
586 // foreach (ScenePresence av in m_linkedAvatars)
587 foreach (avtocrossInfo avinfo in avsToCross)
588 {
589 ScenePresence av = avinfo.av;
590 if (!av.IsInTransit) // just in case...
591 {
592 m_log.DebugFormat("[SCENE OBJECT]: Crossing avatar {0} to {1}", av.Name, val);
593
594 av.IsInTransit = true;
595
596 CrossAgentToNewRegionDelegate d = entityTransfer.CrossAgentToNewRegionAsync;
597 d.BeginInvoke(av, val, x, y, destination, av.Flying, version, CrossAgentToNewRegionCompleted, d);
598 }
599 else
600 m_log.DebugFormat("[SCENE OBJECT]: Crossing avatar alreasy in transit {0} to {1}", av.Name, val);
601 }
602 avsToCross.Clear();
603 return;
604 }
605 else // cross failed, put avas back ??
606 {
607 foreach (avtocrossInfo avinfo in avsToCross)
608 {
609 ScenePresence av = avinfo.av;
610 av.ParentUUID = UUID.Zero;
611 av.ParentID = avinfo.ParentID;
612// m_linkedAvatars.Add(av);
613 }
614 }
615 avsToCross.Clear();
616
617 }
618 else if (RootPart.PhysActor != null)
619 {
620 RootPart.PhysActor.CrossingFailure();
621 }
622
623 Vector3 oldp = AbsolutePosition;
624 val.X = Util.Clamp<float>(oldp.X, 0.5f, (float)Constants.RegionSize - 0.5f);
625 val.Y = Util.Clamp<float>(oldp.Y, 0.5f, (float)Constants.RegionSize - 0.5f);
626 val.Z = Util.Clamp<float>(oldp.Z, 0.5f, 4096.0f);
437 } 627 }
438 } 628 }
439 629
630/* don't see the need but worse don't see where is restored to false if things stay in
631 foreach (SceneObjectPart part in m_parts.GetArray())
632 {
633 part.IgnoreUndoUpdate = true;
634 }
635 */
440 if (RootPart.GetStatusSandbox()) 636 if (RootPart.GetStatusSandbox())
441 { 637 {
442 if (Util.GetDistanceTo(RootPart.StatusSandboxPos, value) > 10) 638 if (Util.GetDistanceTo(RootPart.StatusSandboxPos, value) > 10)
@@ -454,9 +650,38 @@ namespace OpenSim.Region.Framework.Scenes
454 // Restuff the new GroupPosition into each SOP of the linkset. 650 // Restuff the new GroupPosition into each SOP of the linkset.
455 // This has the affect of resetting and tainting the physics actors. 651 // This has the affect of resetting and tainting the physics actors.
456 SceneObjectPart[] parts = m_parts.GetArray(); 652 SceneObjectPart[] parts = m_parts.GetArray();
457 for (int i = 0; i < parts.Length; i++) 653 bool triggerScriptEvent = m_rootPart.GroupPosition != val;
458 parts[i].GroupPosition = val; 654 if (m_dupeInProgress)
655 triggerScriptEvent = false;
656 foreach (SceneObjectPart part in parts)
657 {
658 part.GroupPosition = val;
659 if (triggerScriptEvent)
660 part.TriggerScriptChangedEvent(Changed.POSITION);
661 }
459 662
663/*
664 This seems not needed and should not be needed:
665 sp absolute position depends on sit part absolute position fixed above.
666 sp ParentPosition is not used anywhere.
667 Since presence is sitting, viewer considers it 'linked' to root prim, so it will move/rotate it
668 Sending a extra packet with avatar position is not only bandwidth waste, but may cause jitter in viewers due to UPD nature.
669
670 if (!m_dupeInProgress)
671 {
672 foreach (ScenePresence av in m_linkedAvatars)
673 {
674 SceneObjectPart p = m_scene.GetSceneObjectPart(av.ParentID);
675 if (p != null && m_parts.TryGetValue(p.UUID, out p))
676 {
677 Vector3 offset = p.GetWorldPosition() - av.ParentPosition;
678 av.AbsolutePosition += offset;
679// av.ParentPosition = p.GetWorldPosition(); //ParentPosition gets cleared by AbsolutePosition
680 av.SendAvatarDataToAllAgents();
681 }
682 }
683 }
684*/
460 //if (m_rootPart.PhysActor != null) 685 //if (m_rootPart.PhysActor != null)
461 //{ 686 //{
462 //m_rootPart.PhysActor.Position = 687 //m_rootPart.PhysActor.Position =
@@ -470,6 +695,40 @@ namespace OpenSim.Region.Framework.Scenes
470 } 695 }
471 } 696 }
472 697
698 public override Vector3 Velocity
699 {
700 get { return RootPart.Velocity; }
701 set { RootPart.Velocity = value; }
702 }
703
704 private void CrossAgentToNewRegionCompleted(IAsyncResult iar)
705 {
706 CrossAgentToNewRegionDelegate icon = (CrossAgentToNewRegionDelegate)iar.AsyncState;
707 ScenePresence agent = icon.EndInvoke(iar);
708
709 //// If the cross was successful, this agent is a child agent
710 if (agent.IsChildAgent)
711 {
712 if (agent.ParentUUID != UUID.Zero)
713 {
714 agent.ParentPart = null;
715// agent.ParentPosition = Vector3.Zero;
716// agent.ParentUUID = UUID.Zero;
717 }
718 }
719
720 agent.ParentUUID = UUID.Zero;
721
722// agent.Reset();
723// else // Not successful
724// agent.RestoreInCurrentScene();
725
726 // In any case
727 agent.IsInTransit = false;
728
729 m_log.DebugFormat("[SCENE OBJECT]: Crossing agent {0} {1} completed.", agent.Firstname, agent.Lastname);
730 }
731
473 public override uint LocalId 732 public override uint LocalId
474 { 733 {
475 get { return m_rootPart.LocalId; } 734 get { return m_rootPart.LocalId; }
@@ -540,6 +799,11 @@ namespace OpenSim.Region.Framework.Scenes
540 m_isSelected = value; 799 m_isSelected = value;
541 // Tell physics engine that group is selected 800 // Tell physics engine that group is selected
542 801
802 // this is not right
803 // but ode engines should only really need to know about root part
804 // so they can put entire object simulation on hold and not colliding
805 // keep as was for now
806
543 PhysicsActor pa = m_rootPart.PhysActor; 807 PhysicsActor pa = m_rootPart.PhysActor;
544 if (pa != null) 808 if (pa != null)
545 { 809 {
@@ -556,6 +820,42 @@ namespace OpenSim.Region.Framework.Scenes
556 childPa.Selected = value; 820 childPa.Selected = value;
557 } 821 }
558 } 822 }
823 if (RootPart.KeyframeMotion != null)
824 RootPart.KeyframeMotion.Selected = value;
825 }
826 }
827
828 public void PartSelectChanged(bool partSelect)
829 {
830 // any part selected makes group selected
831 if (m_isSelected == partSelect)
832 return;
833
834 if (partSelect)
835 {
836 IsSelected = partSelect;
837// if (!IsAttachment)
838// ScheduleGroupForFullUpdate();
839 }
840 else
841 {
842 // bad bad bad 2 heavy for large linksets
843 // since viewer does send lot of (un)selects
844 // this needs to be replaced by a specific list or count ?
845 // but that will require extra code in several places
846
847 SceneObjectPart[] parts = m_parts.GetArray();
848 for (int i = 0; i < parts.Length; i++)
849 {
850 SceneObjectPart part = parts[i];
851 if (part.IsSelected)
852 return;
853 }
854 IsSelected = partSelect;
855 if (!IsAttachment)
856 {
857 ScheduleGroupForFullUpdate();
858 }
559 } 859 }
560 } 860 }
561 861
@@ -633,6 +933,7 @@ namespace OpenSim.Region.Framework.Scenes
633 /// </summary> 933 /// </summary>
634 public SceneObjectGroup() 934 public SceneObjectGroup()
635 { 935 {
936
636 } 937 }
637 938
638 /// <summary> 939 /// <summary>
@@ -649,7 +950,7 @@ namespace OpenSim.Region.Framework.Scenes
649 /// Constructor. This object is added to the scene later via AttachToScene() 950 /// Constructor. This object is added to the scene later via AttachToScene()
650 /// </summary> 951 /// </summary>
651 public SceneObjectGroup(UUID ownerID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape) 952 public SceneObjectGroup(UUID ownerID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape)
652 { 953 {
653 SetRootPart(new SceneObjectPart(ownerID, shape, pos, rot, Vector3.Zero)); 954 SetRootPart(new SceneObjectPart(ownerID, shape, pos, rot, Vector3.Zero));
654 } 955 }
655 956
@@ -685,6 +986,9 @@ namespace OpenSim.Region.Framework.Scenes
685 /// </summary> 986 /// </summary>
686 public virtual void AttachToBackup() 987 public virtual void AttachToBackup()
687 { 988 {
989 if (IsAttachment) return;
990 m_scene.SceneGraph.FireAttachToBackup(this);
991
688 if (InSceneBackup) 992 if (InSceneBackup)
689 { 993 {
690 //m_log.DebugFormat( 994 //m_log.DebugFormat(
@@ -727,6 +1031,13 @@ namespace OpenSim.Region.Framework.Scenes
727 1031
728 ApplyPhysics(); 1032 ApplyPhysics();
729 1033
1034 if (RootPart.PhysActor != null)
1035 RootPart.Force = RootPart.Force;
1036 if (RootPart.PhysActor != null)
1037 RootPart.Torque = RootPart.Torque;
1038 if (RootPart.PhysActor != null)
1039 RootPart.Buoyancy = RootPart.Buoyancy;
1040
730 // Don't trigger the update here - otherwise some client issues occur when multiple updates are scheduled 1041 // Don't trigger the update here - otherwise some client issues occur when multiple updates are scheduled
731 // for the same object with very different properties. The caller must schedule the update. 1042 // for the same object with very different properties. The caller must schedule the update.
732 //ScheduleGroupForFullUpdate(); 1043 //ScheduleGroupForFullUpdate();
@@ -742,6 +1053,10 @@ namespace OpenSim.Region.Framework.Scenes
742 EntityIntersection result = new EntityIntersection(); 1053 EntityIntersection result = new EntityIntersection();
743 1054
744 SceneObjectPart[] parts = m_parts.GetArray(); 1055 SceneObjectPart[] parts = m_parts.GetArray();
1056
1057 // Find closest hit here
1058 float idist = float.MaxValue;
1059
745 for (int i = 0; i < parts.Length; i++) 1060 for (int i = 0; i < parts.Length; i++)
746 { 1061 {
747 SceneObjectPart part = parts[i]; 1062 SceneObjectPart part = parts[i];
@@ -756,11 +1071,6 @@ namespace OpenSim.Region.Framework.Scenes
756 1071
757 EntityIntersection inter = part.TestIntersectionOBB(hRay, parentrotation, frontFacesOnly, faceCenters); 1072 EntityIntersection inter = part.TestIntersectionOBB(hRay, parentrotation, frontFacesOnly, faceCenters);
758 1073
759 // This may need to be updated to the maximum draw distance possible..
760 // We might (and probably will) be checking for prim creation from other sims
761 // when the camera crosses the border.
762 float idist = Constants.RegionSize;
763
764 if (inter.HitTF) 1074 if (inter.HitTF)
765 { 1075 {
766 // We need to find the closest prim to return to the testcaller along the ray 1076 // We need to find the closest prim to return to the testcaller along the ray
@@ -771,10 +1081,11 @@ namespace OpenSim.Region.Framework.Scenes
771 result.obj = part; 1081 result.obj = part;
772 result.normal = inter.normal; 1082 result.normal = inter.normal;
773 result.distance = inter.distance; 1083 result.distance = inter.distance;
1084
1085 idist = inter.distance;
774 } 1086 }
775 } 1087 }
776 } 1088 }
777
778 return result; 1089 return result;
779 } 1090 }
780 1091
@@ -786,25 +1097,27 @@ namespace OpenSim.Region.Framework.Scenes
786 /// <returns></returns> 1097 /// <returns></returns>
787 public void GetAxisAlignedBoundingBoxRaw(out float minX, out float maxX, out float minY, out float maxY, out float minZ, out float maxZ) 1098 public void GetAxisAlignedBoundingBoxRaw(out float minX, out float maxX, out float minY, out float maxY, out float minZ, out float maxZ)
788 { 1099 {
789 maxX = -256f; 1100 maxX = float.MinValue;
790 maxY = -256f; 1101 maxY = float.MinValue;
791 maxZ = -256f; 1102 maxZ = float.MinValue;
792 minX = 256f; 1103 minX = float.MaxValue;
793 minY = 256f; 1104 minY = float.MaxValue;
794 minZ = 8192f; 1105 minZ = float.MaxValue;
795 1106
796 SceneObjectPart[] parts = m_parts.GetArray(); 1107 SceneObjectPart[] parts = m_parts.GetArray();
797 for (int i = 0; i < parts.Length; i++) 1108 foreach (SceneObjectPart part in parts)
798 { 1109 {
799 SceneObjectPart part = parts[i];
800
801 Vector3 worldPos = part.GetWorldPosition(); 1110 Vector3 worldPos = part.GetWorldPosition();
802 Vector3 offset = worldPos - AbsolutePosition; 1111 Vector3 offset = worldPos - AbsolutePosition;
803 Quaternion worldRot; 1112 Quaternion worldRot;
804 if (part.ParentID == 0) 1113 if (part.ParentID == 0)
1114 {
805 worldRot = part.RotationOffset; 1115 worldRot = part.RotationOffset;
1116 }
806 else 1117 else
1118 {
807 worldRot = part.GetWorldRotation(); 1119 worldRot = part.GetWorldRotation();
1120 }
808 1121
809 Vector3 frontTopLeft; 1122 Vector3 frontTopLeft;
810 Vector3 frontTopRight; 1123 Vector3 frontTopRight;
@@ -816,6 +1129,8 @@ namespace OpenSim.Region.Framework.Scenes
816 Vector3 backBottomLeft; 1129 Vector3 backBottomLeft;
817 Vector3 backBottomRight; 1130 Vector3 backBottomRight;
818 1131
1132 // Vector3[] corners = new Vector3[8];
1133
819 Vector3 orig = Vector3.Zero; 1134 Vector3 orig = Vector3.Zero;
820 1135
821 frontTopLeft.X = orig.X - (part.Scale.X / 2); 1136 frontTopLeft.X = orig.X - (part.Scale.X / 2);
@@ -850,6 +1165,38 @@ namespace OpenSim.Region.Framework.Scenes
850 backBottomRight.Y = orig.Y + (part.Scale.Y / 2); 1165 backBottomRight.Y = orig.Y + (part.Scale.Y / 2);
851 backBottomRight.Z = orig.Z - (part.Scale.Z / 2); 1166 backBottomRight.Z = orig.Z - (part.Scale.Z / 2);
852 1167
1168
1169
1170 //m_log.InfoFormat("pre corner 1 is {0} {1} {2}", frontTopLeft.X, frontTopLeft.Y, frontTopLeft.Z);
1171 //m_log.InfoFormat("pre corner 2 is {0} {1} {2}", frontTopRight.X, frontTopRight.Y, frontTopRight.Z);
1172 //m_log.InfoFormat("pre corner 3 is {0} {1} {2}", frontBottomRight.X, frontBottomRight.Y, frontBottomRight.Z);
1173 //m_log.InfoFormat("pre corner 4 is {0} {1} {2}", frontBottomLeft.X, frontBottomLeft.Y, frontBottomLeft.Z);
1174 //m_log.InfoFormat("pre corner 5 is {0} {1} {2}", backTopLeft.X, backTopLeft.Y, backTopLeft.Z);
1175 //m_log.InfoFormat("pre corner 6 is {0} {1} {2}", backTopRight.X, backTopRight.Y, backTopRight.Z);
1176 //m_log.InfoFormat("pre corner 7 is {0} {1} {2}", backBottomRight.X, backBottomRight.Y, backBottomRight.Z);
1177 //m_log.InfoFormat("pre corner 8 is {0} {1} {2}", backBottomLeft.X, backBottomLeft.Y, backBottomLeft.Z);
1178
1179 //for (int i = 0; i < 8; i++)
1180 //{
1181 // corners[i] = corners[i] * worldRot;
1182 // corners[i] += offset;
1183
1184 // if (corners[i].X > maxX)
1185 // maxX = corners[i].X;
1186 // if (corners[i].X < minX)
1187 // minX = corners[i].X;
1188
1189 // if (corners[i].Y > maxY)
1190 // maxY = corners[i].Y;
1191 // if (corners[i].Y < minY)
1192 // minY = corners[i].Y;
1193
1194 // if (corners[i].Z > maxZ)
1195 // maxZ = corners[i].Y;
1196 // if (corners[i].Z < minZ)
1197 // minZ = corners[i].Z;
1198 //}
1199
853 frontTopLeft = frontTopLeft * worldRot; 1200 frontTopLeft = frontTopLeft * worldRot;
854 frontTopRight = frontTopRight * worldRot; 1201 frontTopRight = frontTopRight * worldRot;
855 frontBottomLeft = frontBottomLeft * worldRot; 1202 frontBottomLeft = frontBottomLeft * worldRot;
@@ -871,6 +1218,15 @@ namespace OpenSim.Region.Framework.Scenes
871 backTopLeft += offset; 1218 backTopLeft += offset;
872 backTopRight += offset; 1219 backTopRight += offset;
873 1220
1221 //m_log.InfoFormat("corner 1 is {0} {1} {2}", frontTopLeft.X, frontTopLeft.Y, frontTopLeft.Z);
1222 //m_log.InfoFormat("corner 2 is {0} {1} {2}", frontTopRight.X, frontTopRight.Y, frontTopRight.Z);
1223 //m_log.InfoFormat("corner 3 is {0} {1} {2}", frontBottomRight.X, frontBottomRight.Y, frontBottomRight.Z);
1224 //m_log.InfoFormat("corner 4 is {0} {1} {2}", frontBottomLeft.X, frontBottomLeft.Y, frontBottomLeft.Z);
1225 //m_log.InfoFormat("corner 5 is {0} {1} {2}", backTopLeft.X, backTopLeft.Y, backTopLeft.Z);
1226 //m_log.InfoFormat("corner 6 is {0} {1} {2}", backTopRight.X, backTopRight.Y, backTopRight.Z);
1227 //m_log.InfoFormat("corner 7 is {0} {1} {2}", backBottomRight.X, backBottomRight.Y, backBottomRight.Z);
1228 //m_log.InfoFormat("corner 8 is {0} {1} {2}", backBottomLeft.X, backBottomLeft.Y, backBottomLeft.Z);
1229
874 if (frontTopRight.X > maxX) 1230 if (frontTopRight.X > maxX)
875 maxX = frontTopRight.X; 1231 maxX = frontTopRight.X;
876 if (frontTopLeft.X > maxX) 1232 if (frontTopLeft.X > maxX)
@@ -1014,17 +1370,118 @@ namespace OpenSim.Region.Framework.Scenes
1014 1370
1015 #endregion 1371 #endregion
1016 1372
1373 public void GetResourcesCosts(SceneObjectPart apart,
1374 out float linksetResCost, out float linksetPhysCost, out float partCost, out float partPhysCost)
1375 {
1376 // this information may need to be cached
1377
1378 float cost;
1379 float tmpcost;
1380
1381 bool ComplexCost = false;
1382
1383 SceneObjectPart p;
1384 SceneObjectPart[] parts;
1385
1386 lock (m_parts)
1387 {
1388 parts = m_parts.GetArray();
1389 }
1390
1391 int nparts = parts.Length;
1392
1393
1394 for (int i = 0; i < nparts; i++)
1395 {
1396 p = parts[i];
1397
1398 if (p.UsesComplexCost)
1399 {
1400 ComplexCost = true;
1401 break;
1402 }
1403 }
1404
1405 if (ComplexCost)
1406 {
1407 linksetResCost = 0;
1408 linksetPhysCost = 0;
1409 partCost = 0;
1410 partPhysCost = 0;
1411
1412 for (int i = 0; i < nparts; i++)
1413 {
1414 p = parts[i];
1415
1416 cost = p.StreamingCost;
1417 tmpcost = p.SimulationCost;
1418 if (tmpcost > cost)
1419 cost = tmpcost;
1420 tmpcost = p.PhysicsCost;
1421 if (tmpcost > cost)
1422 cost = tmpcost;
1423
1424 linksetPhysCost += tmpcost;
1425 linksetResCost += cost;
1426
1427 if (p == apart)
1428 {
1429 partCost = cost;
1430 partPhysCost = tmpcost;
1431 }
1432 }
1433 }
1434 else
1435 {
1436 partPhysCost = 1.0f;
1437 partCost = 1.0f;
1438 linksetResCost = (float)nparts;
1439 linksetPhysCost = linksetResCost;
1440 }
1441 }
1442
1443 public void GetSelectedCosts(out float PhysCost, out float StreamCost, out float SimulCost)
1444 {
1445 SceneObjectPart p;
1446 SceneObjectPart[] parts;
1447
1448 lock (m_parts)
1449 {
1450 parts = m_parts.GetArray();
1451 }
1452
1453 int nparts = parts.Length;
1454
1455 PhysCost = 0;
1456 StreamCost = 0;
1457 SimulCost = 0;
1458
1459 for (int i = 0; i < nparts; i++)
1460 {
1461 p = parts[i];
1462
1463 StreamCost += p.StreamingCost;
1464 SimulCost += p.SimulationCost;
1465 PhysCost += p.PhysicsCost;
1466 }
1467 }
1468
1017 public void SaveScriptedState(XmlTextWriter writer) 1469 public void SaveScriptedState(XmlTextWriter writer)
1018 { 1470 {
1471 SaveScriptedState(writer, false);
1472 }
1473
1474 public void SaveScriptedState(XmlTextWriter writer, bool oldIDs)
1475 {
1019 XmlDocument doc = new XmlDocument(); 1476 XmlDocument doc = new XmlDocument();
1020 Dictionary<UUID,string> states = new Dictionary<UUID,string>(); 1477 Dictionary<UUID,string> states = new Dictionary<UUID,string>();
1021 1478
1022 SceneObjectPart[] parts = m_parts.GetArray(); 1479 SceneObjectPart[] parts = m_parts.GetArray();
1023 for (int i = 0; i < parts.Length; i++) 1480 for (int i = 0; i < parts.Length; i++)
1024 { 1481 {
1025 Dictionary<UUID, string> pstates = parts[i].Inventory.GetScriptStates(); 1482 Dictionary<UUID, string> pstates = parts[i].Inventory.GetScriptStates(oldIDs);
1026 foreach (KeyValuePair<UUID, string> kvp in pstates) 1483 foreach (KeyValuePair<UUID, string> kvp in pstates)
1027 states.Add(kvp.Key, kvp.Value); 1484 states[kvp.Key] = kvp.Value;
1028 } 1485 }
1029 1486
1030 if (states.Count > 0) 1487 if (states.Count > 0)
@@ -1044,6 +1501,169 @@ namespace OpenSim.Region.Framework.Scenes
1044 } 1501 }
1045 1502
1046 /// <summary> 1503 /// <summary>
1504 /// Add the avatar to this linkset (avatar is sat).
1505 /// </summary>
1506 /// <param name="agentID"></param>
1507 public void AddAvatar(UUID agentID)
1508 {
1509 ScenePresence presence;
1510 if (m_scene.TryGetScenePresence(agentID, out presence))
1511 {
1512 if (!m_linkedAvatars.Contains(presence))
1513 {
1514 m_linkedAvatars.Add(presence);
1515 }
1516 }
1517 }
1518
1519 /// <summary>
1520 /// Delete the avatar from this linkset (avatar is unsat).
1521 /// </summary>
1522 /// <param name="agentID"></param>
1523 public void DeleteAvatar(UUID agentID)
1524 {
1525 ScenePresence presence;
1526 if (m_scene.TryGetScenePresence(agentID, out presence))
1527 {
1528 if (m_linkedAvatars.Contains(presence))
1529 {
1530 m_linkedAvatars.Remove(presence);
1531 }
1532 }
1533 }
1534
1535 /// <summary>
1536 /// Returns the list of linked presences (avatars sat on this group)
1537 /// </summary>
1538 /// <param name="agentID"></param>
1539 public List<ScenePresence> GetLinkedAvatars()
1540 {
1541 return m_linkedAvatars;
1542 }
1543
1544 /// <summary>
1545 /// Attach this scene object to the given avatar.
1546 /// </summary>
1547 /// <param name="agentID"></param>
1548 /// <param name="attachmentpoint"></param>
1549 /// <param name="AttachOffset"></param>
1550 private void AttachToAgent(
1551 ScenePresence avatar, SceneObjectGroup so, uint attachmentpoint, Vector3 attachOffset, bool silent)
1552 {
1553 if (avatar != null)
1554 {
1555 // don't attach attachments to child agents
1556 if (avatar.IsChildAgent) return;
1557
1558 // Remove from database and parcel prim count
1559 m_scene.DeleteFromStorage(so.UUID);
1560 m_scene.EventManager.TriggerParcelPrimCountTainted();
1561
1562 so.AttachedAvatar = avatar.UUID;
1563
1564 if (so.RootPart.PhysActor != null)
1565 {
1566 m_scene.PhysicsScene.RemovePrim(so.RootPart.PhysActor);
1567 so.RootPart.PhysActor = null;
1568 }
1569
1570 so.AbsolutePosition = attachOffset;
1571 so.RootPart.AttachedPos = attachOffset;
1572 so.IsAttachment = true;
1573 so.RootPart.SetParentLocalId(avatar.LocalId);
1574 so.AttachmentPoint = attachmentpoint;
1575
1576 avatar.AddAttachment(this);
1577
1578 if (!silent)
1579 {
1580 // Killing it here will cause the client to deselect it
1581 // It then reappears on the avatar, deselected
1582 // through the full update below
1583 //
1584 if (IsSelected)
1585 {
1586 m_scene.SendKillObject(new List<uint> { m_rootPart.LocalId });
1587 }
1588
1589 IsSelected = false; // fudge....
1590 ScheduleGroupForFullUpdate();
1591 }
1592 }
1593 else
1594 {
1595 m_log.WarnFormat(
1596 "[SOG]: Tried to add attachment {0} to avatar with UUID {1} in region {2} but the avatar is not present",
1597 UUID, avatar.ControllingClient.AgentId, Scene.RegionInfo.RegionName);
1598 }
1599 }
1600
1601 public byte GetAttachmentPoint()
1602 {
1603 return m_rootPart.Shape.State;
1604 }
1605
1606 public void DetachToGround()
1607 {
1608 ScenePresence avatar = m_scene.GetScenePresence(AttachedAvatar);
1609 if (avatar == null)
1610 return;
1611
1612 avatar.RemoveAttachment(this);
1613
1614 Vector3 detachedpos = new Vector3(127f,127f,127f);
1615 if (avatar == null)
1616 return;
1617
1618 detachedpos = avatar.AbsolutePosition;
1619 FromItemID = UUID.Zero;
1620
1621 AbsolutePosition = detachedpos;
1622 AttachedAvatar = UUID.Zero;
1623
1624 //SceneObjectPart[] parts = m_parts.GetArray();
1625 //for (int i = 0; i < parts.Length; i++)
1626 // parts[i].AttachedAvatar = UUID.Zero;
1627
1628 m_rootPart.SetParentLocalId(0);
1629 AttachmentPoint = (byte)0;
1630 // must check if buildind should be true or false here
1631 m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_rootPart.VolumeDetectActive,false);
1632 HasGroupChanged = true;
1633 RootPart.Rezzed = DateTime.Now;
1634 RootPart.RemFlag(PrimFlags.TemporaryOnRez);
1635 AttachToBackup();
1636 m_scene.EventManager.TriggerParcelPrimCountTainted();
1637 m_rootPart.ScheduleFullUpdate();
1638 m_rootPart.ClearUndoState();
1639 }
1640
1641 public void DetachToInventoryPrep()
1642 {
1643 ScenePresence avatar = m_scene.GetScenePresence(AttachedAvatar);
1644 //Vector3 detachedpos = new Vector3(127f, 127f, 127f);
1645 if (avatar != null)
1646 {
1647 //detachedpos = avatar.AbsolutePosition;
1648 avatar.RemoveAttachment(this);
1649 }
1650
1651 AttachedAvatar = UUID.Zero;
1652
1653 /*SceneObjectPart[] parts = m_parts.GetArray();
1654 for (int i = 0; i < parts.Length; i++)
1655 parts[i].AttachedAvatar = UUID.Zero;*/
1656
1657 m_rootPart.SetParentLocalId(0);
1658 //m_rootPart.SetAttachmentPoint((byte)0);
1659 IsAttachment = false;
1660 AbsolutePosition = m_rootPart.AttachedPos;
1661 //m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_scene.m_physicalPrim);
1662 //AttachToBackup();
1663 //m_rootPart.ScheduleFullUpdate();
1664 }
1665
1666 /// <summary>
1047 /// 1667 ///
1048 /// </summary> 1668 /// </summary>
1049 /// <param name="part"></param> 1669 /// <param name="part"></param>
@@ -1083,7 +1703,10 @@ namespace OpenSim.Region.Framework.Scenes
1083 public void AddPart(SceneObjectPart part) 1703 public void AddPart(SceneObjectPart part)
1084 { 1704 {
1085 part.SetParent(this); 1705 part.SetParent(this);
1086 part.LinkNum = m_parts.Add(part.UUID, part); 1706 m_parts.Add(part.UUID, part);
1707
1708 part.LinkNum = m_parts.Count;
1709
1087 if (part.LinkNum == 2) 1710 if (part.LinkNum == 2)
1088 RootPart.LinkNum = 1; 1711 RootPart.LinkNum = 1;
1089 } 1712 }
@@ -1174,7 +1797,7 @@ namespace OpenSim.Region.Framework.Scenes
1174// "[SCENE OBJECT GROUP]: Processing OnGrabPart for {0} on {1} {2}, offsetPos {3}", 1797// "[SCENE OBJECT GROUP]: Processing OnGrabPart for {0} on {1} {2}, offsetPos {3}",
1175// remoteClient.Name, part.Name, part.LocalId, offsetPos); 1798// remoteClient.Name, part.Name, part.LocalId, offsetPos);
1176 1799
1177 part.StoreUndoState(); 1800// part.StoreUndoState();
1178 part.OnGrab(offsetPos, remoteClient); 1801 part.OnGrab(offsetPos, remoteClient);
1179 } 1802 }
1180 1803
@@ -1194,6 +1817,11 @@ namespace OpenSim.Region.Framework.Scenes
1194 /// <param name="silent">If true then deletion is not broadcast to clients</param> 1817 /// <param name="silent">If true then deletion is not broadcast to clients</param>
1195 public void DeleteGroupFromScene(bool silent) 1818 public void DeleteGroupFromScene(bool silent)
1196 { 1819 {
1820 // We need to keep track of this state in case this group is still queued for backup.
1821 IsDeleted = true;
1822
1823 DetachFromBackup();
1824
1197 SceneObjectPart[] parts = m_parts.GetArray(); 1825 SceneObjectPart[] parts = m_parts.GetArray();
1198 for (int i = 0; i < parts.Length; i++) 1826 for (int i = 0; i < parts.Length; i++)
1199 { 1827 {
@@ -1217,6 +1845,7 @@ namespace OpenSim.Region.Framework.Scenes
1217 } 1845 }
1218 }); 1846 });
1219 } 1847 }
1848
1220 } 1849 }
1221 1850
1222 public void AddScriptLPS(int count) 1851 public void AddScriptLPS(int count)
@@ -1286,28 +1915,43 @@ namespace OpenSim.Region.Framework.Scenes
1286 /// </summary> 1915 /// </summary>
1287 public void ApplyPhysics() 1916 public void ApplyPhysics()
1288 { 1917 {
1289 // Apply physics to the root prim
1290 m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_rootPart.VolumeDetectActive);
1291
1292 // Apply physics to child prims
1293 SceneObjectPart[] parts = m_parts.GetArray(); 1918 SceneObjectPart[] parts = m_parts.GetArray();
1294 if (parts.Length > 1) 1919 if (parts.Length > 1)
1295 { 1920 {
1921 ResetChildPrimPhysicsPositions();
1922
1923 // Apply physics to the root prim
1924 m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_rootPart.VolumeDetectActive, true);
1925
1926
1296 for (int i = 0; i < parts.Length; i++) 1927 for (int i = 0; i < parts.Length; i++)
1297 { 1928 {
1298 SceneObjectPart part = parts[i]; 1929 SceneObjectPart part = parts[i];
1299 if (part.LocalId != m_rootPart.LocalId) 1930 if (part.LocalId != m_rootPart.LocalId)
1300 part.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), part.VolumeDetectActive); 1931 part.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), part.VolumeDetectActive, true);
1301 } 1932 }
1302
1303 // Hack to get the physics scene geometries in the right spot 1933 // Hack to get the physics scene geometries in the right spot
1304 ResetChildPrimPhysicsPositions(); 1934// ResetChildPrimPhysicsPositions();
1935 if (m_rootPart.PhysActor != null)
1936 {
1937 m_rootPart.PhysActor.Building = false;
1938 }
1939 }
1940 else
1941 {
1942 // Apply physics to the root prim
1943 m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_rootPart.VolumeDetectActive, false);
1305 } 1944 }
1306 } 1945 }
1307 1946
1308 public void SetOwnerId(UUID userId) 1947 public void SetOwnerId(UUID userId)
1309 { 1948 {
1310 ForEachPart(delegate(SceneObjectPart part) { part.OwnerID = userId; }); 1949 ForEachPart(delegate(SceneObjectPart part)
1950 {
1951
1952 part.OwnerID = userId;
1953
1954 });
1311 } 1955 }
1312 1956
1313 public void ForEachPart(Action<SceneObjectPart> whatToDo) 1957 public void ForEachPart(Action<SceneObjectPart> whatToDo)
@@ -1339,11 +1983,17 @@ namespace OpenSim.Region.Framework.Scenes
1339 return; 1983 return;
1340 } 1984 }
1341 1985
1986 if ((RootPart.Flags & PrimFlags.TemporaryOnRez) != 0)
1987 return;
1988
1342 // Since this is the top of the section of call stack for backing up a particular scene object, don't let 1989 // Since this is the top of the section of call stack for backing up a particular scene object, don't let
1343 // any exception propogate upwards. 1990 // any exception propogate upwards.
1344 try 1991 try
1345 { 1992 {
1346 if (!m_scene.ShuttingDown) // if shutting down then there will be nothing to handle the return so leave till next restart 1993 if (!m_scene.ShuttingDown || // if shutting down then there will be nothing to handle the return so leave till next restart
1994 m_scene.LoginsDisabled || // We're starting up or doing maintenance, don't mess with things
1995 m_scene.LoadingPrims) // Land may not be valid yet
1996
1347 { 1997 {
1348 ILandObject parcel = m_scene.LandChannel.GetLandObject( 1998 ILandObject parcel = m_scene.LandChannel.GetLandObject(
1349 m_rootPart.GroupPosition.X, m_rootPart.GroupPosition.Y); 1999 m_rootPart.GroupPosition.X, m_rootPart.GroupPosition.Y);
@@ -1370,6 +2020,7 @@ namespace OpenSim.Region.Framework.Scenes
1370 } 2020 }
1371 } 2021 }
1372 } 2022 }
2023
1373 } 2024 }
1374 2025
1375 if (m_scene.UseBackup && HasGroupChanged) 2026 if (m_scene.UseBackup && HasGroupChanged)
@@ -1377,10 +2028,30 @@ namespace OpenSim.Region.Framework.Scenes
1377 // don't backup while it's selected or you're asking for changes mid stream. 2028 // don't backup while it's selected or you're asking for changes mid stream.
1378 if (isTimeToPersist() || forcedBackup) 2029 if (isTimeToPersist() || forcedBackup)
1379 { 2030 {
2031 if (m_rootPart.PhysActor != null &&
2032 (!m_rootPart.PhysActor.IsPhysical))
2033 {
2034 // Possible ghost prim
2035 if (m_rootPart.PhysActor.Position != m_rootPart.GroupPosition)
2036 {
2037 foreach (SceneObjectPart part in m_parts.GetArray())
2038 {
2039 // Re-set physics actor positions and
2040 // orientations
2041 part.GroupPosition = m_rootPart.GroupPosition;
2042 }
2043 }
2044 }
1380// m_log.DebugFormat( 2045// m_log.DebugFormat(
1381// "[SCENE]: Storing {0}, {1} in {2}", 2046// "[SCENE]: Storing {0}, {1} in {2}",
1382// Name, UUID, m_scene.RegionInfo.RegionName); 2047// Name, UUID, m_scene.RegionInfo.RegionName);
1383 2048
2049 if (RootPart.Shape.PCode == 9 && RootPart.Shape.State != 0)
2050 {
2051 RootPart.Shape.State = 0;
2052 ScheduleGroupForFullUpdate();
2053 }
2054
1384 SceneObjectGroup backup_group = Copy(false); 2055 SceneObjectGroup backup_group = Copy(false);
1385 backup_group.RootPart.Velocity = RootPart.Velocity; 2056 backup_group.RootPart.Velocity = RootPart.Velocity;
1386 backup_group.RootPart.Acceleration = RootPart.Acceleration; 2057 backup_group.RootPart.Acceleration = RootPart.Acceleration;
@@ -1394,6 +2065,11 @@ namespace OpenSim.Region.Framework.Scenes
1394 2065
1395 backup_group.ForEachPart(delegate(SceneObjectPart part) 2066 backup_group.ForEachPart(delegate(SceneObjectPart part)
1396 { 2067 {
2068 if (part.KeyframeMotion != null)
2069 {
2070 part.KeyframeMotion = KeyframeMotion.FromData(backup_group, part.KeyframeMotion.Serialize());
2071 part.KeyframeMotion.UpdateSceneObject(this);
2072 }
1397 part.Inventory.ProcessInventoryBackup(datastore); 2073 part.Inventory.ProcessInventoryBackup(datastore);
1398 }); 2074 });
1399 2075
@@ -1446,10 +2122,14 @@ namespace OpenSim.Region.Framework.Scenes
1446 /// <returns></returns> 2122 /// <returns></returns>
1447 public SceneObjectGroup Copy(bool userExposed) 2123 public SceneObjectGroup Copy(bool userExposed)
1448 { 2124 {
2125 m_dupeInProgress = true;
1449 SceneObjectGroup dupe = (SceneObjectGroup)MemberwiseClone(); 2126 SceneObjectGroup dupe = (SceneObjectGroup)MemberwiseClone();
1450 dupe.m_isBackedUp = false; 2127 dupe.m_isBackedUp = false;
1451 dupe.m_parts = new MapAndArray<OpenMetaverse.UUID, SceneObjectPart>(); 2128 dupe.m_parts = new MapAndArray<OpenMetaverse.UUID, SceneObjectPart>();
1452 2129
2130 // new group as no sitting avatars
2131 dupe.m_linkedAvatars = new List<ScenePresence>();
2132
1453 // Warning, The following code related to previousAttachmentStatus is needed so that clones of 2133 // Warning, The following code related to previousAttachmentStatus is needed so that clones of
1454 // attachments do not bordercross while they're being duplicated. This is hacktastic! 2134 // attachments do not bordercross while they're being duplicated. This is hacktastic!
1455 // Normally, setting AbsolutePosition will bordercross a prim if it's outside the region! 2135 // Normally, setting AbsolutePosition will bordercross a prim if it's outside the region!
@@ -1460,7 +2140,7 @@ namespace OpenSim.Region.Framework.Scenes
1460 // This is only necessary when userExposed is false! 2140 // This is only necessary when userExposed is false!
1461 2141
1462 bool previousAttachmentStatus = dupe.IsAttachment; 2142 bool previousAttachmentStatus = dupe.IsAttachment;
1463 2143
1464 if (!userExposed) 2144 if (!userExposed)
1465 dupe.IsAttachment = true; 2145 dupe.IsAttachment = true;
1466 2146
@@ -1478,11 +2158,11 @@ namespace OpenSim.Region.Framework.Scenes
1478 dupe.m_rootPart.TrimPermissions(); 2158 dupe.m_rootPart.TrimPermissions();
1479 2159
1480 List<SceneObjectPart> partList = new List<SceneObjectPart>(m_parts.GetArray()); 2160 List<SceneObjectPart> partList = new List<SceneObjectPart>(m_parts.GetArray());
1481 2161
1482 partList.Sort(delegate(SceneObjectPart p1, SceneObjectPart p2) 2162 partList.Sort(delegate(SceneObjectPart p1, SceneObjectPart p2)
1483 { 2163 {
1484 return p1.LinkNum.CompareTo(p2.LinkNum); 2164 return p1.LinkNum.CompareTo(p2.LinkNum);
1485 } 2165 }
1486 ); 2166 );
1487 2167
1488 foreach (SceneObjectPart part in partList) 2168 foreach (SceneObjectPart part in partList)
@@ -1492,41 +2172,53 @@ namespace OpenSim.Region.Framework.Scenes
1492 { 2172 {
1493 newPart = dupe.CopyPart(part, OwnerID, GroupID, userExposed); 2173 newPart = dupe.CopyPart(part, OwnerID, GroupID, userExposed);
1494 newPart.LinkNum = part.LinkNum; 2174 newPart.LinkNum = part.LinkNum;
1495 } 2175 if (userExposed)
2176 newPart.ParentID = dupe.m_rootPart.LocalId;
2177 }
1496 else 2178 else
1497 { 2179 {
1498 newPart = dupe.m_rootPart; 2180 newPart = dupe.m_rootPart;
1499 } 2181 }
2182/*
2183 bool isphys = ((newPart.Flags & PrimFlags.Physics) != 0);
2184 bool isphan = ((newPart.Flags & PrimFlags.Phantom) != 0);
1500 2185
1501 // Need to duplicate the physics actor as well 2186 // Need to duplicate the physics actor as well
1502 PhysicsActor originalPartPa = part.PhysActor; 2187 if (userExposed && (isphys || !isphan || newPart.VolumeDetectActive))
1503 if (originalPartPa != null && userExposed)
1504 { 2188 {
1505 PrimitiveBaseShape pbs = newPart.Shape; 2189 PrimitiveBaseShape pbs = newPart.Shape;
1506
1507 newPart.PhysActor 2190 newPart.PhysActor
1508 = m_scene.PhysicsScene.AddPrimShape( 2191 = m_scene.PhysicsScene.AddPrimShape(
1509 string.Format("{0}/{1}", newPart.Name, newPart.UUID), 2192 string.Format("{0}/{1}", newPart.Name, newPart.UUID),
1510 pbs, 2193 pbs,
1511 newPart.AbsolutePosition, 2194 newPart.AbsolutePosition,
1512 newPart.Scale, 2195 newPart.Scale,
1513 newPart.RotationOffset, 2196 newPart.GetWorldRotation(),
1514 originalPartPa.IsPhysical, 2197 isphys,
2198 isphan,
1515 newPart.LocalId); 2199 newPart.LocalId);
1516 2200
1517 newPart.DoPhysicsPropertyUpdate(originalPartPa.IsPhysical, true); 2201 newPart.DoPhysicsPropertyUpdate(isphys, true);
1518 } 2202 */
2203 if (userExposed)
2204 newPart.ApplyPhysics((uint)newPart.Flags,newPart.VolumeDetectActive,true);
2205// }
1519 } 2206 }
1520 2207
1521 if (userExposed) 2208 if (userExposed)
1522 { 2209 {
1523 dupe.UpdateParentIDs(); 2210// done above dupe.UpdateParentIDs();
2211
2212 if (dupe.m_rootPart.PhysActor != null)
2213 dupe.m_rootPart.PhysActor.Building = false; // tell physics to finish building
2214
1524 dupe.HasGroupChanged = true; 2215 dupe.HasGroupChanged = true;
1525 dupe.AttachToBackup(); 2216 dupe.AttachToBackup();
1526 2217
1527 ScheduleGroupForFullUpdate(); 2218 ScheduleGroupForFullUpdate();
1528 } 2219 }
1529 2220
2221 m_dupeInProgress = false;
1530 return dupe; 2222 return dupe;
1531 } 2223 }
1532 2224
@@ -1538,11 +2230,24 @@ namespace OpenSim.Region.Framework.Scenes
1538 /// <param name="cGroupID"></param> 2230 /// <param name="cGroupID"></param>
1539 public void CopyRootPart(SceneObjectPart part, UUID cAgentID, UUID cGroupID, bool userExposed) 2231 public void CopyRootPart(SceneObjectPart part, UUID cAgentID, UUID cGroupID, bool userExposed)
1540 { 2232 {
1541 SetRootPart(part.Copy(m_scene.AllocateLocalId(), OwnerID, GroupID, 0, userExposed)); 2233 // SetRootPart(part.Copy(m_scene.AllocateLocalId(), OwnerID, GroupID, 0, userExposed));
2234 // give newpart a new local ID lettng old part keep same
2235 SceneObjectPart newpart = part.Copy(part.LocalId, OwnerID, GroupID, 0, userExposed);
2236 newpart.LocalId = m_scene.AllocateLocalId();
2237
2238 SetRootPart(newpart);
2239 if (userExposed)
2240 RootPart.Velocity = Vector3.Zero; // In case source is moving
1542 } 2241 }
1543 2242
1544 public void ScriptSetPhysicsStatus(bool usePhysics) 2243 public void ScriptSetPhysicsStatus(bool usePhysics)
1545 { 2244 {
2245 if (usePhysics)
2246 {
2247 if (RootPart.KeyframeMotion != null)
2248 RootPart.KeyframeMotion.Stop();
2249 RootPart.KeyframeMotion = null;
2250 }
1546 UpdatePrimFlags(RootPart.LocalId, usePhysics, IsTemporary, IsPhantom, IsVolumeDetect); 2251 UpdatePrimFlags(RootPart.LocalId, usePhysics, IsTemporary, IsPhantom, IsVolumeDetect);
1547 } 2252 }
1548 2253
@@ -1590,13 +2295,14 @@ namespace OpenSim.Region.Framework.Scenes
1590 2295
1591 if (pa != null) 2296 if (pa != null)
1592 { 2297 {
1593 pa.AddForce(impulse, true); 2298 // false to be applied as a impulse
2299 pa.AddForce(impulse, false);
1594 m_scene.PhysicsScene.AddPhysicsActorTaint(pa); 2300 m_scene.PhysicsScene.AddPhysicsActorTaint(pa);
1595 } 2301 }
1596 } 2302 }
1597 } 2303 }
1598 2304
1599 public void applyAngularImpulse(Vector3 impulse) 2305 public void ApplyAngularImpulse(Vector3 impulse)
1600 { 2306 {
1601 PhysicsActor pa = RootPart.PhysActor; 2307 PhysicsActor pa = RootPart.PhysActor;
1602 2308
@@ -1604,21 +2310,8 @@ namespace OpenSim.Region.Framework.Scenes
1604 { 2310 {
1605 if (!IsAttachment) 2311 if (!IsAttachment)
1606 { 2312 {
1607 pa.AddAngularForce(impulse, true); 2313 // false to be applied as a impulse
1608 m_scene.PhysicsScene.AddPhysicsActorTaint(pa); 2314 pa.AddAngularForce(impulse, false);
1609 }
1610 }
1611 }
1612
1613 public void setAngularImpulse(Vector3 impulse)
1614 {
1615 PhysicsActor pa = RootPart.PhysActor;
1616
1617 if (pa != null)
1618 {
1619 if (!IsAttachment)
1620 {
1621 pa.Torque = impulse;
1622 m_scene.PhysicsScene.AddPhysicsActorTaint(pa); 2315 m_scene.PhysicsScene.AddPhysicsActorTaint(pa);
1623 } 2316 }
1624 } 2317 }
@@ -1626,20 +2319,10 @@ namespace OpenSim.Region.Framework.Scenes
1626 2319
1627 public Vector3 GetTorque() 2320 public Vector3 GetTorque()
1628 { 2321 {
1629 PhysicsActor pa = RootPart.PhysActor; 2322 return RootPart.Torque;
1630
1631 if (pa != null)
1632 {
1633 if (!IsAttachment)
1634 {
1635 Vector3 torque = pa.Torque;
1636 return torque;
1637 }
1638 }
1639
1640 return Vector3.Zero;
1641 } 2323 }
1642 2324
2325 // This is used by both Double-Click Auto-Pilot and llMoveToTarget() in an attached object
1643 public void moveToTarget(Vector3 target, float tau) 2326 public void moveToTarget(Vector3 target, float tau)
1644 { 2327 {
1645 if (IsAttachment) 2328 if (IsAttachment)
@@ -1671,6 +2354,46 @@ namespace OpenSim.Region.Framework.Scenes
1671 pa.PIDActive = false; 2354 pa.PIDActive = false;
1672 } 2355 }
1673 2356
2357 public void rotLookAt(Quaternion target, float strength, float damping)
2358 {
2359 SceneObjectPart rootpart = m_rootPart;
2360 if (rootpart != null)
2361 {
2362 if (IsAttachment)
2363 {
2364 /*
2365 ScenePresence avatar = m_scene.GetScenePresence(rootpart.AttachedAvatar);
2366 if (avatar != null)
2367 {
2368 Rotate the Av?
2369 } */
2370 }
2371 else
2372 {
2373 if (rootpart.PhysActor != null)
2374 { // APID must be implemented in your physics system for this to function.
2375 rootpart.PhysActor.APIDTarget = new Quaternion(target.X, target.Y, target.Z, target.W);
2376 rootpart.PhysActor.APIDStrength = strength;
2377 rootpart.PhysActor.APIDDamping = damping;
2378 rootpart.PhysActor.APIDActive = true;
2379 }
2380 }
2381 }
2382 }
2383
2384 public void stopLookAt()
2385 {
2386 SceneObjectPart rootpart = m_rootPart;
2387 if (rootpart != null)
2388 {
2389 if (rootpart.PhysActor != null)
2390 { // APID must be implemented in your physics system for this to function.
2391 rootpart.PhysActor.APIDActive = false;
2392 }
2393 }
2394
2395 }
2396
1674 /// <summary> 2397 /// <summary>
1675 /// Uses a PID to attempt to clamp the object on the Z axis at the given height over tau seconds. 2398 /// Uses a PID to attempt to clamp the object on the Z axis at the given height over tau seconds.
1676 /// </summary> 2399 /// </summary>
@@ -1687,7 +2410,7 @@ namespace OpenSim.Region.Framework.Scenes
1687 { 2410 {
1688 pa.PIDHoverHeight = height; 2411 pa.PIDHoverHeight = height;
1689 pa.PIDHoverType = hoverType; 2412 pa.PIDHoverType = hoverType;
1690 pa.PIDTau = tau; 2413 pa.PIDHoverTau = tau;
1691 pa.PIDHoverActive = true; 2414 pa.PIDHoverActive = true;
1692 } 2415 }
1693 else 2416 else
@@ -1727,7 +2450,12 @@ namespace OpenSim.Region.Framework.Scenes
1727 /// <param name="cGroupID"></param> 2450 /// <param name="cGroupID"></param>
1728 public SceneObjectPart CopyPart(SceneObjectPart part, UUID cAgentID, UUID cGroupID, bool userExposed) 2451 public SceneObjectPart CopyPart(SceneObjectPart part, UUID cAgentID, UUID cGroupID, bool userExposed)
1729 { 2452 {
1730 SceneObjectPart newPart = part.Copy(m_scene.AllocateLocalId(), OwnerID, GroupID, m_parts.Count, userExposed); 2453 // give new ID to the new part, letting old keep original
2454 // SceneObjectPart newPart = part.Copy(m_scene.AllocateLocalId(), OwnerID, GroupID, m_parts.Count, userExposed);
2455 SceneObjectPart newPart = part.Copy(part.LocalId, OwnerID, GroupID, m_parts.Count, userExposed);
2456 newPart.LocalId = m_scene.AllocateLocalId();
2457 newPart.SetParent(this);
2458
1731 AddPart(newPart); 2459 AddPart(newPart);
1732 2460
1733 SetPartAsNonRoot(newPart); 2461 SetPartAsNonRoot(newPart);
@@ -1866,11 +2594,11 @@ namespace OpenSim.Region.Framework.Scenes
1866 /// Immediately send a full update for this scene object. 2594 /// Immediately send a full update for this scene object.
1867 /// </summary> 2595 /// </summary>
1868 public void SendGroupFullUpdate() 2596 public void SendGroupFullUpdate()
1869 { 2597 {
1870 if (IsDeleted) 2598 if (IsDeleted)
1871 return; 2599 return;
1872 2600
1873// m_log.DebugFormat("[SOG]: Sending immediate full group update for {0} {1}", Name, UUID); 2601// m_log.DebugFormat("[SOG]: Sending immediate full group update for {0} {1}", Name, UUID);
1874 2602
1875 RootPart.SendFullUpdateToAllClients(); 2603 RootPart.SendFullUpdateToAllClients();
1876 2604
@@ -2007,6 +2735,11 @@ namespace OpenSim.Region.Framework.Scenes
2007 // 'linkPart' == the root of the group being linked into this group 2735 // 'linkPart' == the root of the group being linked into this group
2008 SceneObjectPart linkPart = objectGroup.m_rootPart; 2736 SceneObjectPart linkPart = objectGroup.m_rootPart;
2009 2737
2738 if (m_rootPart.PhysActor != null)
2739 m_rootPart.PhysActor.Building = true;
2740 if (linkPart.PhysActor != null)
2741 linkPart.PhysActor.Building = true;
2742
2010 // physics flags from group to be applied to linked parts 2743 // physics flags from group to be applied to linked parts
2011 bool grpusephys = UsesPhysics; 2744 bool grpusephys = UsesPhysics;
2012 bool grptemporary = IsTemporary; 2745 bool grptemporary = IsTemporary;
@@ -2032,12 +2765,12 @@ namespace OpenSim.Region.Framework.Scenes
2032 Vector3 axPos = linkPart.OffsetPosition; 2765 Vector3 axPos = linkPart.OffsetPosition;
2033 // Rotate the linking root SOP's position to be relative to the new root prim 2766 // Rotate the linking root SOP's position to be relative to the new root prim
2034 Quaternion parentRot = m_rootPart.RotationOffset; 2767 Quaternion parentRot = m_rootPart.RotationOffset;
2035 axPos *= Quaternion.Inverse(parentRot); 2768 axPos *= Quaternion.Conjugate(parentRot);
2036 linkPart.OffsetPosition = axPos; 2769 linkPart.OffsetPosition = axPos;
2037 2770
2038 // Make the linking root SOP's rotation relative to the new root prim 2771 // Make the linking root SOP's rotation relative to the new root prim
2039 Quaternion oldRot = linkPart.RotationOffset; 2772 Quaternion oldRot = linkPart.RotationOffset;
2040 Quaternion newRot = Quaternion.Inverse(parentRot) * oldRot; 2773 Quaternion newRot = Quaternion.Conjugate(parentRot) * oldRot;
2041 linkPart.RotationOffset = newRot; 2774 linkPart.RotationOffset = newRot;
2042 2775
2043 // If there is only one SOP in a SOG, the LinkNum is zero. I.e., not a linkset. 2776 // If there is only one SOP in a SOG, the LinkNum is zero. I.e., not a linkset.
@@ -2071,7 +2804,7 @@ namespace OpenSim.Region.Framework.Scenes
2071 linkPart.CreateSelected = true; 2804 linkPart.CreateSelected = true;
2072 2805
2073 // let physics know preserve part volume dtc messy since UpdatePrimFlags doesn't look to parent changes for now 2806 // let physics know preserve part volume dtc messy since UpdatePrimFlags doesn't look to parent changes for now
2074 linkPart.UpdatePrimFlags(grpusephys, grptemporary, (IsPhantom || (linkPart.Flags & PrimFlags.Phantom) != 0), linkPart.VolumeDetectActive); 2807 linkPart.UpdatePrimFlags(grpusephys, grptemporary, (IsPhantom || (linkPart.Flags & PrimFlags.Phantom) != 0), linkPart.VolumeDetectActive, true);
2075 2808
2076 // If the added SOP is physical, also tell the physics engine about the link relationship. 2809 // If the added SOP is physical, also tell the physics engine about the link relationship.
2077 if (linkPart.PhysActor != null && m_rootPart.PhysActor != null && m_rootPart.PhysActor.IsPhysical) 2810 if (linkPart.PhysActor != null && m_rootPart.PhysActor != null && m_rootPart.PhysActor.IsPhysical)
@@ -2081,6 +2814,7 @@ namespace OpenSim.Region.Framework.Scenes
2081 } 2814 }
2082 2815
2083 linkPart.LinkNum = linkNum++; 2816 linkPart.LinkNum = linkNum++;
2817 linkPart.UpdatePrimFlags(UsesPhysics, IsTemporary, IsPhantom, IsVolumeDetect, false);
2084 2818
2085 // Get a list of the SOP's in the old group in order of their linknum's. 2819 // Get a list of the SOP's in the old group in order of their linknum's.
2086 SceneObjectPart[] ogParts = objectGroup.Parts; 2820 SceneObjectPart[] ogParts = objectGroup.Parts;
@@ -2099,7 +2833,7 @@ namespace OpenSim.Region.Framework.Scenes
2099 2833
2100 // Update the physics flags for the newly added SOP 2834 // Update the physics flags for the newly added SOP
2101 // (Is this necessary? LinkNonRootPart() has already called UpdatePrimFlags but with different flags!??) 2835 // (Is this necessary? LinkNonRootPart() has already called UpdatePrimFlags but with different flags!??)
2102 part.UpdatePrimFlags(grpusephys, grptemporary, (IsPhantom || (part.Flags & PrimFlags.Phantom) != 0), part.VolumeDetectActive); 2836 part.UpdatePrimFlags(grpusephys, grptemporary, (IsPhantom || (part.Flags & PrimFlags.Phantom) != 0), part.VolumeDetectActive, true);
2103 2837
2104 // If the added SOP is physical, also tell the physics engine about the link relationship. 2838 // If the added SOP is physical, also tell the physics engine about the link relationship.
2105 if (part.PhysActor != null && m_rootPart.PhysActor != null && m_rootPart.PhysActor.IsPhysical) 2839 if (part.PhysActor != null && m_rootPart.PhysActor != null && m_rootPart.PhysActor.IsPhysical)
@@ -2117,7 +2851,7 @@ namespace OpenSim.Region.Framework.Scenes
2117 objectGroup.IsDeleted = true; 2851 objectGroup.IsDeleted = true;
2118 2852
2119 objectGroup.m_parts.Clear(); 2853 objectGroup.m_parts.Clear();
2120 2854
2121 // Can't do this yet since backup still makes use of the root part without any synchronization 2855 // Can't do this yet since backup still makes use of the root part without any synchronization
2122// objectGroup.m_rootPart = null; 2856// objectGroup.m_rootPart = null;
2123 2857
@@ -2128,6 +2862,9 @@ namespace OpenSim.Region.Framework.Scenes
2128 // unmoved prims! 2862 // unmoved prims!
2129 ResetChildPrimPhysicsPositions(); 2863 ResetChildPrimPhysicsPositions();
2130 2864
2865 if (m_rootPart.PhysActor != null)
2866 m_rootPart.PhysActor.Building = false;
2867
2131 //HasGroupChanged = true; 2868 //HasGroupChanged = true;
2132 //ScheduleGroupForFullUpdate(); 2869 //ScheduleGroupForFullUpdate();
2133 } 2870 }
@@ -2195,7 +2932,10 @@ namespace OpenSim.Region.Framework.Scenes
2195// m_log.DebugFormat( 2932// m_log.DebugFormat(
2196// "[SCENE OBJECT GROUP]: Delinking part {0}, {1} from group with root part {2}, {3}", 2933// "[SCENE OBJECT GROUP]: Delinking part {0}, {1} from group with root part {2}, {3}",
2197// linkPart.Name, linkPart.UUID, RootPart.Name, RootPart.UUID); 2934// linkPart.Name, linkPart.UUID, RootPart.Name, RootPart.UUID);
2198 2935
2936 if (m_rootPart.PhysActor != null)
2937 m_rootPart.PhysActor.Building = true;
2938
2199 linkPart.ClearUndoState(); 2939 linkPart.ClearUndoState();
2200 2940
2201 Vector3 worldPos = linkPart.GetWorldPosition(); 2941 Vector3 worldPos = linkPart.GetWorldPosition();
@@ -2266,6 +3006,14 @@ namespace OpenSim.Region.Framework.Scenes
2266 3006
2267 // When we delete a group, we currently have to force persist to the database if the object id has changed 3007 // When we delete a group, we currently have to force persist to the database if the object id has changed
2268 // (since delete works by deleting all rows which have a given object id) 3008 // (since delete works by deleting all rows which have a given object id)
3009
3010 // this is as it seems to be in sl now
3011 if(linkPart.PhysicsShapeType == (byte)PhysShapeType.none)
3012 linkPart.PhysicsShapeType = linkPart.DefaultPhysicsShapeType(); // root prims can't have type none for now
3013
3014 if (m_rootPart.PhysActor != null)
3015 m_rootPart.PhysActor.Building = false;
3016
2269 objectGroup.HasGroupChangedDueToDelink = true; 3017 objectGroup.HasGroupChangedDueToDelink = true;
2270 3018
2271 return objectGroup; 3019 return objectGroup;
@@ -2277,6 +3025,7 @@ namespace OpenSim.Region.Framework.Scenes
2277 /// <param name="objectGroup"></param> 3025 /// <param name="objectGroup"></param>
2278 public virtual void DetachFromBackup() 3026 public virtual void DetachFromBackup()
2279 { 3027 {
3028 m_scene.SceneGraph.FireDetachFromBackup(this);
2280 if (m_isBackedUp && Scene != null) 3029 if (m_isBackedUp && Scene != null)
2281 m_scene.EventManager.OnBackup -= ProcessBackup; 3030 m_scene.EventManager.OnBackup -= ProcessBackup;
2282 3031
@@ -2297,7 +3046,8 @@ namespace OpenSim.Region.Framework.Scenes
2297 Vector3 axPos = part.OffsetPosition; 3046 Vector3 axPos = part.OffsetPosition;
2298 axPos *= parentRot; 3047 axPos *= parentRot;
2299 part.OffsetPosition = axPos; 3048 part.OffsetPosition = axPos;
2300 part.GroupPosition = oldGroupPosition + part.OffsetPosition; 3049 Vector3 newPos = oldGroupPosition + part.OffsetPosition;
3050 part.GroupPosition = newPos;
2301 part.OffsetPosition = Vector3.Zero; 3051 part.OffsetPosition = Vector3.Zero;
2302 3052
2303 // Compution our rotation to be not relative to the old parent 3053 // Compution our rotation to be not relative to the old parent
@@ -2322,18 +3072,18 @@ namespace OpenSim.Region.Framework.Scenes
2322 // Rotate the relative position by the rotation of the group 3072 // Rotate the relative position by the rotation of the group
2323 Quaternion rootRotation = m_rootPart.RotationOffset; 3073 Quaternion rootRotation = m_rootPart.RotationOffset;
2324 Vector3 pos = part.OffsetPosition; 3074 Vector3 pos = part.OffsetPosition;
2325 pos *= Quaternion.Inverse(rootRotation); 3075 pos *= Quaternion.Conjugate(rootRotation);
2326 part.OffsetPosition = pos; 3076 part.OffsetPosition = pos;
2327 3077
2328 // Compute the SOP's rotation relative to the rotation of the group. 3078 // Compute the SOP's rotation relative to the rotation of the group.
2329 parentRot = m_rootPart.RotationOffset; 3079 parentRot = m_rootPart.RotationOffset;
2330 oldRot = part.RotationOffset; 3080 oldRot = part.RotationOffset;
2331 Quaternion newRot = Quaternion.Inverse(parentRot) * oldRot; 3081 Quaternion newRot = Quaternion.Conjugate(parentRot) * worldRot;
2332 part.RotationOffset = newRot; 3082 part.RotationOffset = newRot;
2333 3083
2334 // Since this SOP's state has changed, push those changes into the physics engine 3084 // Since this SOP's state has changed, push those changes into the physics engine
2335 // and the simulator. 3085 // and the simulator.
2336 part.UpdatePrimFlags(UsesPhysics, IsTemporary, IsPhantom, IsVolumeDetect); 3086 part.UpdatePrimFlags(UsesPhysics, IsTemporary, IsPhantom, IsVolumeDetect, false);
2337 } 3087 }
2338 3088
2339 /// <summary> 3089 /// <summary>
@@ -2355,10 +3105,14 @@ namespace OpenSim.Region.Framework.Scenes
2355 { 3105 {
2356 if (!m_rootPart.BlockGrab) 3106 if (!m_rootPart.BlockGrab)
2357 { 3107 {
2358 Vector3 llmoveforce = pos - AbsolutePosition; 3108/* Vector3 llmoveforce = pos - AbsolutePosition;
2359 Vector3 grabforce = llmoveforce; 3109 Vector3 grabforce = llmoveforce;
2360 grabforce = (grabforce / 10) * pa.Mass; 3110 grabforce = (grabforce / 10) * pa.Mass;
2361 pa.AddForce(grabforce, true); 3111 */
3112 // empirically convert distance diference to a impulse
3113 Vector3 grabforce = pos - AbsolutePosition;
3114 grabforce = grabforce * (pa.Mass/ 10.0f);
3115 pa.AddForce(grabforce, false);
2362 m_scene.PhysicsScene.AddPhysicsActorTaint(pa); 3116 m_scene.PhysicsScene.AddPhysicsActorTaint(pa);
2363 } 3117 }
2364 } 3118 }
@@ -2584,8 +3338,22 @@ namespace OpenSim.Region.Framework.Scenes
2584 } 3338 }
2585 } 3339 }
2586 3340
2587 for (int i = 0; i < parts.Length; i++) 3341 if (parts.Length > 1)
2588 parts[i].UpdatePrimFlags(UsePhysics, SetTemporary, SetPhantom, SetVolumeDetect); 3342 {
3343 m_rootPart.UpdatePrimFlags(UsePhysics, SetTemporary, SetPhantom, SetVolumeDetect, true);
3344
3345 for (int i = 0; i < parts.Length; i++)
3346 {
3347
3348 if (parts[i].UUID != m_rootPart.UUID)
3349 parts[i].UpdatePrimFlags(UsePhysics, SetTemporary, SetPhantom, SetVolumeDetect, true);
3350 }
3351
3352 if (m_rootPart.PhysActor != null)
3353 m_rootPart.PhysActor.Building = false;
3354 }
3355 else
3356 m_rootPart.UpdatePrimFlags(UsePhysics, SetTemporary, SetPhantom, SetVolumeDetect, false);
2589 } 3357 }
2590 } 3358 }
2591 3359
@@ -2598,6 +3366,17 @@ namespace OpenSim.Region.Framework.Scenes
2598 } 3366 }
2599 } 3367 }
2600 3368
3369
3370
3371 /// <summary>
3372 /// Gets the number of parts
3373 /// </summary>
3374 /// <returns></returns>
3375 public int GetPartCount()
3376 {
3377 return Parts.Count();
3378 }
3379
2601 /// <summary> 3380 /// <summary>
2602 /// Update the texture entry for this part 3381 /// Update the texture entry for this part
2603 /// </summary> 3382 /// </summary>
@@ -2659,11 +3438,6 @@ namespace OpenSim.Region.Framework.Scenes
2659 /// <param name="scale"></param> 3438 /// <param name="scale"></param>
2660 public void GroupResize(Vector3 scale) 3439 public void GroupResize(Vector3 scale)
2661 { 3440 {
2662// m_log.DebugFormat(
2663// "[SCENE OBJECT GROUP]: Group resizing {0} {1} from {2} to {3}", Name, LocalId, RootPart.Scale, scale);
2664
2665 RootPart.StoreUndoState(true);
2666
2667 scale.X = Math.Min(scale.X, Scene.m_maxNonphys); 3441 scale.X = Math.Min(scale.X, Scene.m_maxNonphys);
2668 scale.Y = Math.Min(scale.Y, Scene.m_maxNonphys); 3442 scale.Y = Math.Min(scale.Y, Scene.m_maxNonphys);
2669 scale.Z = Math.Min(scale.Z, Scene.m_maxNonphys); 3443 scale.Z = Math.Min(scale.Z, Scene.m_maxNonphys);
@@ -2690,7 +3464,6 @@ namespace OpenSim.Region.Framework.Scenes
2690 SceneObjectPart obPart = parts[i]; 3464 SceneObjectPart obPart = parts[i];
2691 if (obPart.UUID != m_rootPart.UUID) 3465 if (obPart.UUID != m_rootPart.UUID)
2692 { 3466 {
2693// obPart.IgnoreUndoUpdate = true;
2694 Vector3 oldSize = new Vector3(obPart.Scale); 3467 Vector3 oldSize = new Vector3(obPart.Scale);
2695 3468
2696 float f = 1.0f; 3469 float f = 1.0f;
@@ -2754,8 +3527,6 @@ namespace OpenSim.Region.Framework.Scenes
2754 z *= a; 3527 z *= a;
2755 } 3528 }
2756 } 3529 }
2757
2758// obPart.IgnoreUndoUpdate = false;
2759 } 3530 }
2760 } 3531 }
2761 } 3532 }
@@ -2765,9 +3536,7 @@ namespace OpenSim.Region.Framework.Scenes
2765 prevScale.Y *= y; 3536 prevScale.Y *= y;
2766 prevScale.Z *= z; 3537 prevScale.Z *= z;
2767 3538
2768// RootPart.IgnoreUndoUpdate = true;
2769 RootPart.Resize(prevScale); 3539 RootPart.Resize(prevScale);
2770// RootPart.IgnoreUndoUpdate = false;
2771 3540
2772 parts = m_parts.GetArray(); 3541 parts = m_parts.GetArray();
2773 for (int i = 0; i < parts.Length; i++) 3542 for (int i = 0; i < parts.Length; i++)
@@ -2776,8 +3545,6 @@ namespace OpenSim.Region.Framework.Scenes
2776 3545
2777 if (obPart.UUID != m_rootPart.UUID) 3546 if (obPart.UUID != m_rootPart.UUID)
2778 { 3547 {
2779 obPart.IgnoreUndoUpdate = true;
2780
2781 Vector3 currentpos = new Vector3(obPart.OffsetPosition); 3548 Vector3 currentpos = new Vector3(obPart.OffsetPosition);
2782 currentpos.X *= x; 3549 currentpos.X *= x;
2783 currentpos.Y *= y; 3550 currentpos.Y *= y;
@@ -2790,16 +3557,12 @@ namespace OpenSim.Region.Framework.Scenes
2790 3557
2791 obPart.Resize(newSize); 3558 obPart.Resize(newSize);
2792 obPart.UpdateOffSet(currentpos); 3559 obPart.UpdateOffSet(currentpos);
2793
2794 obPart.IgnoreUndoUpdate = false;
2795 } 3560 }
2796 3561
2797// obPart.IgnoreUndoUpdate = false; 3562 HasGroupChanged = true;
2798// obPart.StoreUndoState(); 3563 m_rootPart.TriggerScriptChangedEvent(Changed.SCALE);
3564 ScheduleGroupForTerseUpdate();
2799 } 3565 }
2800
2801// m_log.DebugFormat(
2802// "[SCENE OBJECT GROUP]: Finished group resizing {0} {1} to {2}", Name, LocalId, RootPart.Scale);
2803 } 3566 }
2804 3567
2805 #endregion 3568 #endregion
@@ -2812,14 +3575,6 @@ namespace OpenSim.Region.Framework.Scenes
2812 /// <param name="pos"></param> 3575 /// <param name="pos"></param>
2813 public void UpdateGroupPosition(Vector3 pos) 3576 public void UpdateGroupPosition(Vector3 pos)
2814 { 3577 {
2815// m_log.DebugFormat("[SCENE OBJECT GROUP]: Updating group position on {0} {1} to {2}", Name, LocalId, pos);
2816
2817 RootPart.StoreUndoState(true);
2818
2819// SceneObjectPart[] parts = m_parts.GetArray();
2820// for (int i = 0; i < parts.Length; i++)
2821// parts[i].StoreUndoState();
2822
2823 if (m_scene.EventManager.TriggerGroupMove(UUID, pos)) 3578 if (m_scene.EventManager.TriggerGroupMove(UUID, pos))
2824 { 3579 {
2825 if (IsAttachment) 3580 if (IsAttachment)
@@ -2852,21 +3607,17 @@ namespace OpenSim.Region.Framework.Scenes
2852 /// </summary> 3607 /// </summary>
2853 /// <param name="pos"></param> 3608 /// <param name="pos"></param>
2854 /// <param name="localID"></param> 3609 /// <param name="localID"></param>
3610 ///
3611
2855 public void UpdateSinglePosition(Vector3 pos, uint localID) 3612 public void UpdateSinglePosition(Vector3 pos, uint localID)
2856 { 3613 {
2857 SceneObjectPart part = GetPart(localID); 3614 SceneObjectPart part = GetPart(localID);
2858 3615
2859// SceneObjectPart[] parts = m_parts.GetArray();
2860// for (int i = 0; i < parts.Length; i++)
2861// parts[i].StoreUndoState();
2862
2863 if (part != null) 3616 if (part != null)
2864 { 3617 {
2865// m_log.DebugFormat( 3618// unlock parts position change
2866// "[SCENE OBJECT GROUP]: Updating single position of {0} {1} to {2}", part.Name, part.LocalId, pos); 3619 if (m_rootPart.PhysActor != null)
2867 3620 m_rootPart.PhysActor.Building = true;
2868 part.StoreUndoState(false);
2869 part.IgnoreUndoUpdate = true;
2870 3621
2871 if (part.UUID == m_rootPart.UUID) 3622 if (part.UUID == m_rootPart.UUID)
2872 { 3623 {
@@ -2877,8 +3628,10 @@ namespace OpenSim.Region.Framework.Scenes
2877 part.UpdateOffSet(pos); 3628 part.UpdateOffSet(pos);
2878 } 3629 }
2879 3630
3631 if (m_rootPart.PhysActor != null)
3632 m_rootPart.PhysActor.Building = false;
3633
2880 HasGroupChanged = true; 3634 HasGroupChanged = true;
2881 part.IgnoreUndoUpdate = false;
2882 } 3635 }
2883 } 3636 }
2884 3637
@@ -2888,13 +3641,7 @@ namespace OpenSim.Region.Framework.Scenes
2888 /// <param name="pos"></param> 3641 /// <param name="pos"></param>
2889 public void UpdateRootPosition(Vector3 pos) 3642 public void UpdateRootPosition(Vector3 pos)
2890 { 3643 {
2891// m_log.DebugFormat( 3644 // needs to be called with phys building true
2892// "[SCENE OBJECT GROUP]: Updating root position of {0} {1} to {2}", Name, LocalId, pos);
2893
2894// SceneObjectPart[] parts = m_parts.GetArray();
2895// for (int i = 0; i < parts.Length; i++)
2896// parts[i].StoreUndoState();
2897
2898 Vector3 newPos = new Vector3(pos.X, pos.Y, pos.Z); 3645 Vector3 newPos = new Vector3(pos.X, pos.Y, pos.Z);
2899 Vector3 oldPos = 3646 Vector3 oldPos =
2900 new Vector3(AbsolutePosition.X + m_rootPart.OffsetPosition.X, 3647 new Vector3(AbsolutePosition.X + m_rootPart.OffsetPosition.X,
@@ -2917,7 +3664,14 @@ namespace OpenSim.Region.Framework.Scenes
2917 AbsolutePosition = newPos; 3664 AbsolutePosition = newPos;
2918 3665
2919 HasGroupChanged = true; 3666 HasGroupChanged = true;
2920 ScheduleGroupForTerseUpdate(); 3667 if (m_rootPart.Undoing)
3668 {
3669 ScheduleGroupForFullUpdate();
3670 }
3671 else
3672 {
3673 ScheduleGroupForTerseUpdate();
3674 }
2921 } 3675 }
2922 3676
2923 #endregion 3677 #endregion
@@ -2930,24 +3684,16 @@ namespace OpenSim.Region.Framework.Scenes
2930 /// <param name="rot"></param> 3684 /// <param name="rot"></param>
2931 public void UpdateGroupRotationR(Quaternion rot) 3685 public void UpdateGroupRotationR(Quaternion rot)
2932 { 3686 {
2933// m_log.DebugFormat(
2934// "[SCENE OBJECT GROUP]: Updating group rotation R of {0} {1} to {2}", Name, LocalId, rot);
2935
2936// SceneObjectPart[] parts = m_parts.GetArray();
2937// for (int i = 0; i < parts.Length; i++)
2938// parts[i].StoreUndoState();
2939
2940 m_rootPart.StoreUndoState(true);
2941
2942 m_rootPart.UpdateRotation(rot); 3687 m_rootPart.UpdateRotation(rot);
2943 3688
3689/* this is done by rootpart RotationOffset set called by UpdateRotation
2944 PhysicsActor actor = m_rootPart.PhysActor; 3690 PhysicsActor actor = m_rootPart.PhysActor;
2945 if (actor != null) 3691 if (actor != null)
2946 { 3692 {
2947 actor.Orientation = m_rootPart.RotationOffset; 3693 actor.Orientation = m_rootPart.RotationOffset;
2948 m_scene.PhysicsScene.AddPhysicsActorTaint(actor); 3694 m_scene.PhysicsScene.AddPhysicsActorTaint(actor);
2949 } 3695 }
2950 3696*/
2951 HasGroupChanged = true; 3697 HasGroupChanged = true;
2952 ScheduleGroupForTerseUpdate(); 3698 ScheduleGroupForTerseUpdate();
2953 } 3699 }
@@ -2959,16 +3705,6 @@ namespace OpenSim.Region.Framework.Scenes
2959 /// <param name="rot"></param> 3705 /// <param name="rot"></param>
2960 public void UpdateGroupRotationPR(Vector3 pos, Quaternion rot) 3706 public void UpdateGroupRotationPR(Vector3 pos, Quaternion rot)
2961 { 3707 {
2962// m_log.DebugFormat(
2963// "[SCENE OBJECT GROUP]: Updating group rotation PR of {0} {1} to {2}", Name, LocalId, rot);
2964
2965// SceneObjectPart[] parts = m_parts.GetArray();
2966// for (int i = 0; i < parts.Length; i++)
2967// parts[i].StoreUndoState();
2968
2969 RootPart.StoreUndoState(true);
2970 RootPart.IgnoreUndoUpdate = true;
2971
2972 m_rootPart.UpdateRotation(rot); 3708 m_rootPart.UpdateRotation(rot);
2973 3709
2974 PhysicsActor actor = m_rootPart.PhysActor; 3710 PhysicsActor actor = m_rootPart.PhysActor;
@@ -2987,8 +3723,6 @@ namespace OpenSim.Region.Framework.Scenes
2987 3723
2988 HasGroupChanged = true; 3724 HasGroupChanged = true;
2989 ScheduleGroupForTerseUpdate(); 3725 ScheduleGroupForTerseUpdate();
2990
2991 RootPart.IgnoreUndoUpdate = false;
2992 } 3726 }
2993 3727
2994 /// <summary> 3728 /// <summary>
@@ -3001,13 +3735,11 @@ namespace OpenSim.Region.Framework.Scenes
3001 SceneObjectPart part = GetPart(localID); 3735 SceneObjectPart part = GetPart(localID);
3002 3736
3003 SceneObjectPart[] parts = m_parts.GetArray(); 3737 SceneObjectPart[] parts = m_parts.GetArray();
3004 for (int i = 0; i < parts.Length; i++)
3005 parts[i].StoreUndoState();
3006 3738
3007 if (part != null) 3739 if (part != null)
3008 { 3740 {
3009// m_log.DebugFormat( 3741 if (m_rootPart.PhysActor != null)
3010// "[SCENE OBJECT GROUP]: Updating single rotation of {0} {1} to {2}", part.Name, part.LocalId, rot); 3742 m_rootPart.PhysActor.Building = true;
3011 3743
3012 if (part.UUID == m_rootPart.UUID) 3744 if (part.UUID == m_rootPart.UUID)
3013 { 3745 {
@@ -3017,6 +3749,9 @@ namespace OpenSim.Region.Framework.Scenes
3017 { 3749 {
3018 part.UpdateRotation(rot); 3750 part.UpdateRotation(rot);
3019 } 3751 }
3752
3753 if (m_rootPart.PhysActor != null)
3754 m_rootPart.PhysActor.Building = false;
3020 } 3755 }
3021 } 3756 }
3022 3757
@@ -3030,12 +3765,8 @@ namespace OpenSim.Region.Framework.Scenes
3030 SceneObjectPart part = GetPart(localID); 3765 SceneObjectPart part = GetPart(localID);
3031 if (part != null) 3766 if (part != null)
3032 { 3767 {
3033// m_log.DebugFormat( 3768 if (m_rootPart.PhysActor != null)
3034// "[SCENE OBJECT GROUP]: Updating single position and rotation of {0} {1} to {2}", 3769 m_rootPart.PhysActor.Building = true;
3035// part.Name, part.LocalId, rot);
3036
3037 part.StoreUndoState();
3038 part.IgnoreUndoUpdate = true;
3039 3770
3040 if (part.UUID == m_rootPart.UUID) 3771 if (part.UUID == m_rootPart.UUID)
3041 { 3772 {
@@ -3048,7 +3779,8 @@ namespace OpenSim.Region.Framework.Scenes
3048 part.OffsetPosition = pos; 3779 part.OffsetPosition = pos;
3049 } 3780 }
3050 3781
3051 part.IgnoreUndoUpdate = false; 3782 if (m_rootPart.PhysActor != null)
3783 m_rootPart.PhysActor.Building = false;
3052 } 3784 }
3053 } 3785 }
3054 3786
@@ -3058,15 +3790,12 @@ namespace OpenSim.Region.Framework.Scenes
3058 /// <param name="rot"></param> 3790 /// <param name="rot"></param>
3059 public void UpdateRootRotation(Quaternion rot) 3791 public void UpdateRootRotation(Quaternion rot)
3060 { 3792 {
3061// m_log.DebugFormat( 3793 // needs to be called with phys building true
3062// "[SCENE OBJECT GROUP]: Updating root rotation of {0} {1} to {2}",
3063// Name, LocalId, rot);
3064
3065 Quaternion axRot = rot; 3794 Quaternion axRot = rot;
3066 Quaternion oldParentRot = m_rootPart.RotationOffset; 3795 Quaternion oldParentRot = m_rootPart.RotationOffset;
3067 3796
3068 m_rootPart.StoreUndoState(); 3797 //Don't use UpdateRotation because it schedules an update prematurely
3069 m_rootPart.UpdateRotation(rot); 3798 m_rootPart.RotationOffset = rot;
3070 3799
3071 PhysicsActor pa = m_rootPart.PhysActor; 3800 PhysicsActor pa = m_rootPart.PhysActor;
3072 3801
@@ -3082,35 +3811,145 @@ namespace OpenSim.Region.Framework.Scenes
3082 SceneObjectPart prim = parts[i]; 3811 SceneObjectPart prim = parts[i];
3083 if (prim.UUID != m_rootPart.UUID) 3812 if (prim.UUID != m_rootPart.UUID)
3084 { 3813 {
3085 prim.IgnoreUndoUpdate = true; 3814 Quaternion NewRot = oldParentRot * prim.RotationOffset;
3815 NewRot = Quaternion.Inverse(axRot) * NewRot;
3816 prim.RotationOffset = NewRot;
3817
3086 Vector3 axPos = prim.OffsetPosition; 3818 Vector3 axPos = prim.OffsetPosition;
3819
3087 axPos *= oldParentRot; 3820 axPos *= oldParentRot;
3088 axPos *= Quaternion.Inverse(axRot); 3821 axPos *= Quaternion.Inverse(axRot);
3089 prim.OffsetPosition = axPos; 3822 prim.OffsetPosition = axPos;
3090 Quaternion primsRot = prim.RotationOffset; 3823 }
3091 Quaternion newRot = oldParentRot * primsRot; 3824 }
3092 newRot = Quaternion.Inverse(axRot) * newRot;
3093 prim.RotationOffset = newRot;
3094 prim.ScheduleTerseUpdate();
3095 prim.IgnoreUndoUpdate = false;
3096 }
3097 }
3098
3099// for (int i = 0; i < parts.Length; i++)
3100// {
3101// SceneObjectPart childpart = parts[i];
3102// if (childpart != m_rootPart)
3103// {
3104//// childpart.IgnoreUndoUpdate = false;
3105//// childpart.StoreUndoState();
3106// }
3107// }
3108 3825
3109 m_rootPart.ScheduleTerseUpdate(); 3826 HasGroupChanged = true;
3827 ScheduleGroupForFullUpdate();
3828 }
3110 3829
3111// m_log.DebugFormat( 3830 private enum updatetype :int
3112// "[SCENE OBJECT GROUP]: Updated root rotation of {0} {1} to {2}", 3831 {
3113// Name, LocalId, rot); 3832 none = 0,
3833 partterse = 1,
3834 partfull = 2,
3835 groupterse = 3,
3836 groupfull = 4
3837 }
3838
3839 public void doChangeObject(SceneObjectPart part, ObjectChangeData data)
3840 {
3841 // TODO this still as excessive *.Schedule*Update()s
3842
3843 if (part != null && part.ParentGroup != null)
3844 {
3845 ObjectChangeType change = data.change;
3846 bool togroup = ((change & ObjectChangeType.Group) != 0);
3847 // bool uniform = ((what & ObjectChangeType.UniformScale) != 0); not in use
3848
3849 SceneObjectGroup group = part.ParentGroup;
3850 PhysicsActor pha = group.RootPart.PhysActor;
3851
3852 updatetype updateType = updatetype.none;
3853
3854 if (togroup)
3855 {
3856 // related to group
3857 if ((change & (ObjectChangeType.Rotation | ObjectChangeType.Position)) != 0)
3858 {
3859 if ((change & ObjectChangeType.Rotation) != 0)
3860 {
3861 group.RootPart.UpdateRotation(data.rotation);
3862 updateType = updatetype.none;
3863 }
3864 if ((change & ObjectChangeType.Position) != 0)
3865 {
3866 if (IsAttachment || m_scene.Permissions.CanObjectEntry(group.UUID, false, data.position))
3867 UpdateGroupPosition(data.position);
3868 updateType = updatetype.groupterse;
3869 }
3870 else
3871 // ugly rotation update of all parts
3872 {
3873 group.ResetChildPrimPhysicsPositions();
3874 }
3875
3876 }
3877 if ((change & ObjectChangeType.Scale) != 0)
3878 {
3879 if (pha != null)
3880 pha.Building = true;
3881
3882 group.GroupResize(data.scale);
3883 updateType = updatetype.none;
3884
3885 if (pha != null)
3886 pha.Building = false;
3887 }
3888 }
3889 else
3890 {
3891 // related to single prim in a link-set ( ie group)
3892 if (pha != null)
3893 pha.Building = true;
3894
3895 // root part is special
3896 // parts offset positions or rotations need to change also
3897
3898 if (part == group.RootPart)
3899 {
3900 if ((change & ObjectChangeType.Rotation) != 0)
3901 group.UpdateRootRotation(data.rotation);
3902 if ((change & ObjectChangeType.Position) != 0)
3903 group.UpdateRootPosition(data.position);
3904 if ((change & ObjectChangeType.Scale) != 0)
3905 part.Resize(data.scale);
3906 }
3907 else
3908 {
3909 if ((change & ObjectChangeType.Position) != 0)
3910 {
3911 part.OffsetPosition = data.position;
3912 updateType = updatetype.partterse;
3913 }
3914 if ((change & ObjectChangeType.Rotation) != 0)
3915 {
3916 part.UpdateRotation(data.rotation);
3917 updateType = updatetype.none;
3918 }
3919 if ((change & ObjectChangeType.Scale) != 0)
3920 {
3921 part.Resize(data.scale);
3922 updateType = updatetype.none;
3923 }
3924 }
3925
3926 if (pha != null)
3927 pha.Building = false;
3928 }
3929
3930 if (updateType != updatetype.none)
3931 {
3932 group.HasGroupChanged = true;
3933
3934 switch (updateType)
3935 {
3936 case updatetype.partterse:
3937 part.ScheduleTerseUpdate();
3938 break;
3939 case updatetype.partfull:
3940 part.ScheduleFullUpdate();
3941 break;
3942 case updatetype.groupterse:
3943 group.ScheduleGroupForTerseUpdate();
3944 break;
3945 case updatetype.groupfull:
3946 group.ScheduleGroupForFullUpdate();
3947 break;
3948 default:
3949 break;
3950 }
3951 }
3952 }
3114 } 3953 }
3115 3954
3116 #endregion 3955 #endregion
@@ -3209,10 +4048,11 @@ namespace OpenSim.Region.Framework.Scenes
3209 scriptPosTarget target = m_targets[idx]; 4048 scriptPosTarget target = m_targets[idx];
3210 if (Util.GetDistanceTo(target.targetPos, m_rootPart.GroupPosition) <= target.tolerance) 4049 if (Util.GetDistanceTo(target.targetPos, m_rootPart.GroupPosition) <= target.tolerance)
3211 { 4050 {
4051 at_target = true;
4052
3212 // trigger at_target 4053 // trigger at_target
3213 if (m_scriptListens_atTarget) 4054 if (m_scriptListens_atTarget)
3214 { 4055 {
3215 at_target = true;
3216 scriptPosTarget att = new scriptPosTarget(); 4056 scriptPosTarget att = new scriptPosTarget();
3217 att.targetPos = target.targetPos; 4057 att.targetPos = target.targetPos;
3218 att.tolerance = target.tolerance; 4058 att.tolerance = target.tolerance;
@@ -3330,11 +4170,50 @@ namespace OpenSim.Region.Framework.Scenes
3330 } 4170 }
3331 } 4171 }
3332 } 4172 }
3333 4173
4174 public Vector3 GetGeometricCenter()
4175 {
4176 // this is not real geometric center but a average of positions relative to root prim acording to
4177 // http://wiki.secondlife.com/wiki/llGetGeometricCenter
4178 // ignoring tortured prims details since sl also seems to ignore
4179 // so no real use in doing it on physics
4180
4181 Vector3 gc = Vector3.Zero;
4182
4183 int nparts = m_parts.Count;
4184 if (nparts <= 1)
4185 return gc;
4186
4187 SceneObjectPart[] parts = m_parts.GetArray();
4188 nparts = parts.Length; // just in case it changed
4189 if (nparts <= 1)
4190 return gc;
4191
4192 Quaternion parentRot = RootPart.RotationOffset;
4193 Vector3 pPos;
4194
4195 // average all parts positions
4196 for (int i = 0; i < nparts; i++)
4197 {
4198 // do it directly
4199 // gc += parts[i].GetWorldPosition();
4200 if (parts[i] != RootPart)
4201 {
4202 pPos = parts[i].OffsetPosition;
4203 gc += pPos;
4204 }
4205
4206 }
4207 gc /= nparts;
4208
4209 // relative to root:
4210// gc -= AbsolutePosition;
4211 return gc;
4212 }
4213
3334 public float GetMass() 4214 public float GetMass()
3335 { 4215 {
3336 float retmass = 0f; 4216 float retmass = 0f;
3337
3338 SceneObjectPart[] parts = m_parts.GetArray(); 4217 SceneObjectPart[] parts = m_parts.GetArray();
3339 for (int i = 0; i < parts.Length; i++) 4218 for (int i = 0; i < parts.Length; i++)
3340 retmass += parts[i].GetMass(); 4219 retmass += parts[i].GetMass();
@@ -3342,6 +4221,39 @@ namespace OpenSim.Region.Framework.Scenes
3342 return retmass; 4221 return retmass;
3343 } 4222 }
3344 4223
4224 // center of mass of full object
4225 public Vector3 GetCenterOfMass()
4226 {
4227 PhysicsActor pa = RootPart.PhysActor;
4228
4229 if(((RootPart.Flags & PrimFlags.Physics) !=0) && pa !=null)
4230 {
4231 // physics knows better about center of mass of physical prims
4232 Vector3 tmp = pa.CenterOfMass;
4233 return tmp;
4234 }
4235
4236 Vector3 Ptot = Vector3.Zero;
4237 float totmass = 0f;
4238 float m;
4239
4240 SceneObjectPart[] parts = m_parts.GetArray();
4241 for (int i = 0; i < parts.Length; i++)
4242 {
4243 m = parts[i].GetMass();
4244 Ptot += parts[i].GetPartCenterOfMass() * m;
4245 totmass += m;
4246 }
4247
4248 if (totmass == 0)
4249 totmass = 0;
4250 else
4251 totmass = 1 / totmass;
4252 Ptot *= totmass;
4253
4254 return Ptot;
4255 }
4256
3345 /// <summary> 4257 /// <summary>
3346 /// If the object is a sculpt/mesh, retrieve the mesh data for each part and reinsert it into each shape so that 4258 /// If the object is a sculpt/mesh, retrieve the mesh data for each part and reinsert it into each shape so that
3347 /// the physics engine can use it. 4259 /// the physics engine can use it.
@@ -3509,6 +4421,14 @@ namespace OpenSim.Region.Framework.Scenes
3509 FromItemID = uuid; 4421 FromItemID = uuid;
3510 } 4422 }
3511 4423
4424 public void ResetOwnerChangeFlag()
4425 {
4426 ForEachPart(delegate(SceneObjectPart part)
4427 {
4428 part.ResetOwnerChangeFlag();
4429 });
4430 }
4431
3512 #endregion 4432 #endregion
3513 } 4433 }
3514} 4434}
diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs b/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs
index 4b2fede..b038876 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 = (CollisionSoundType >= 0 && !VolumeDetectActive);
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..1c9a17e 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 {
169 if (0 == Items.Count)
170 {
171 return;
172 }
173 }
174 180
181 if (items.Count == 0)
182 return;
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;
@@ -350,16 +367,25 @@ namespace OpenSim.Region.Framework.Scenes
350 if (m_part.ParentGroup.m_savedScriptState != null) 367 if (m_part.ParentGroup.m_savedScriptState != null)
351 item.OldItemID = RestoreSavedScriptState(item.LoadedItemID, item.OldItemID, item.ItemID); 368 item.OldItemID = RestoreSavedScriptState(item.LoadedItemID, item.OldItemID, item.ItemID);
352 369
353 lock (m_items) 370 string msg = String.Format("asset ID {0} could not be found", item.AssetID);
354 { 371 StoreScriptError(item.ItemID, msg);
355 m_items[item.ItemID].OldItemID = item.OldItemID; 372 m_log.ErrorFormat(
356 m_items[item.ItemID].PermsMask = 0; 373 "[PRIM INVENTORY]: Couldn't start script {0}, {1} at {2} in {3} since asset ID {4} could not be found",
357 m_items[item.ItemID].PermsGranter = UUID.Zero; 374 item.Name, item.ItemID, m_part.AbsolutePosition,
358 } 375 m_part.ParentGroup.Scene.RegionInfo.RegionName, item.AssetID);
359 376
377 m_items.LockItemsForWrite(true);
378
379 m_items[item.ItemID].OldItemID = item.OldItemID;
380 m_items[item.ItemID].PermsMask = 0;
381 m_items[item.ItemID].PermsGranter = UUID.Zero;
382
383 m_items.LockItemsForWrite(false);
384
360 string script = Utils.BytesToString(asset.Data); 385 string script = Utils.BytesToString(asset.Data);
361 m_part.ParentGroup.Scene.EventManager.TriggerRezScript( 386 m_part.ParentGroup.Scene.EventManager.TriggerRezScript(
362 m_part.LocalId, item.ItemID, script, startParam, postOnRez, engine, stateSource); 387 m_part.LocalId, item.ItemID, script, startParam, postOnRez, engine, stateSource);
388 StoreScriptErrors(item.ItemID, null);
363 if (!item.ScriptRunning) 389 if (!item.ScriptRunning)
364 m_part.ParentGroup.Scene.EventManager.TriggerStopScript( 390 m_part.ParentGroup.Scene.EventManager.TriggerStopScript(
365 m_part.LocalId, item.ItemID); 391 m_part.LocalId, item.ItemID);
@@ -432,22 +458,149 @@ namespace OpenSim.Region.Framework.Scenes
432 return stateID; 458 return stateID;
433 } 459 }
434 460
461 /// <summary>
462 /// Start a script which is in this prim's inventory.
463 /// Some processing may occur in the background, but this routine returns asap.
464 /// </summary>
465 /// <param name="itemId">
466 /// A <see cref="UUID"/>
467 /// </param>
435 public bool CreateScriptInstance(UUID itemId, int startParam, bool postOnRez, string engine, int stateSource) 468 public bool CreateScriptInstance(UUID itemId, int startParam, bool postOnRez, string engine, int stateSource)
436 { 469 {
437 TaskInventoryItem item = GetInventoryItem(itemId); 470 lock (m_scriptErrors)
438 if (item != null)
439 { 471 {
440 return CreateScriptInstance(item, startParam, postOnRez, engine, stateSource); 472 // Indicate to CreateScriptInstanceInternal() we don't want it to wait for completion
473 m_scriptErrors.Remove(itemId);
474 }
475 CreateScriptInstanceInternal(itemId, startParam, postOnRez, engine, stateSource);
476 return true;
477 }
478
479 private void CreateScriptInstanceInternal(UUID itemId, int startParam, bool postOnRez, string engine, int stateSource)
480 {
481 m_items.LockItemsForRead(true);
482 if (m_items.ContainsKey(itemId))
483 {
484 if (m_items.ContainsKey(itemId))
485 {
486 m_items.LockItemsForRead(false);
487 CreateScriptInstance(m_items[itemId], startParam, postOnRez, engine, stateSource);
488 }
489 else
490 {
491 m_items.LockItemsForRead(false);
492 string msg = String.Format("couldn't be found for prim {0}, {1} at {2} in {3}", m_part.Name, m_part.UUID,
493 m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
494 StoreScriptError(itemId, msg);
495 m_log.ErrorFormat(
496 "[PRIM INVENTORY]: " +
497 "Couldn't start script with ID {0} since it {1}", itemId, msg);
498 }
441 } 499 }
442 else 500 else
443 { 501 {
502 m_items.LockItemsForRead(false);
503 string msg = String.Format("couldn't be found for prim {0}, {1}", m_part.Name, m_part.UUID);
504 StoreScriptError(itemId, msg);
444 m_log.ErrorFormat( 505 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}", 506 "[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, 507 itemId, m_part.Name, m_part.UUID,
447 m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName); 508 m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
509 }
510
511 }
448 512
449 return false; 513 /// <summary>
514 /// Start a script which is in this prim's inventory and return any compilation error messages.
515 /// </summary>
516 /// <param name="itemId">
517 /// A <see cref="UUID"/>
518 /// </param>
519 public ArrayList CreateScriptInstanceEr(UUID itemId, int startParam, bool postOnRez, string engine, int stateSource)
520 {
521 ArrayList errors;
522
523 // Indicate to CreateScriptInstanceInternal() we want it to
524 // post any compilation/loading error messages
525 lock (m_scriptErrors)
526 {
527 m_scriptErrors[itemId] = null;
528 }
529
530 // Perform compilation/loading
531 CreateScriptInstanceInternal(itemId, startParam, postOnRez, engine, stateSource);
532
533 // Wait for and retrieve any errors
534 lock (m_scriptErrors)
535 {
536 while ((errors = m_scriptErrors[itemId]) == null)
537 {
538 if (!System.Threading.Monitor.Wait(m_scriptErrors, 15000))
539 {
540 m_log.ErrorFormat(
541 "[PRIM INVENTORY]: " +
542 "timedout waiting for script {0} errors", itemId);
543 errors = m_scriptErrors[itemId];
544 if (errors == null)
545 {
546 errors = new ArrayList(1);
547 errors.Add("timedout waiting for errors");
548 }
549 break;
550 }
551 }
552 m_scriptErrors.Remove(itemId);
553 }
554 return errors;
555 }
556
557 // Signal to CreateScriptInstanceEr() that compilation/loading is complete
558 private void StoreScriptErrors(UUID itemId, ArrayList errors)
559 {
560 lock (m_scriptErrors)
561 {
562 // If compilation/loading initiated via CreateScriptInstance(),
563 // it does not want the errors, so just get out
564 if (!m_scriptErrors.ContainsKey(itemId))
565 {
566 return;
567 }
568
569 // Initiated via CreateScriptInstanceEr(), if we know what the
570 // errors are, save them and wake CreateScriptInstanceEr().
571 if (errors != null)
572 {
573 m_scriptErrors[itemId] = errors;
574 System.Threading.Monitor.PulseAll(m_scriptErrors);
575 return;
576 }
450 } 577 }
578
579 // Initiated via CreateScriptInstanceEr() but we don't know what
580 // the errors are yet, so retrieve them from the script engine.
581 // This may involve some waiting internal to GetScriptErrors().
582 errors = GetScriptErrors(itemId);
583
584 // Get a default non-null value to indicate success.
585 if (errors == null)
586 {
587 errors = new ArrayList();
588 }
589
590 // Post to CreateScriptInstanceEr() and wake it up
591 lock (m_scriptErrors)
592 {
593 m_scriptErrors[itemId] = errors;
594 System.Threading.Monitor.PulseAll(m_scriptErrors);
595 }
596 }
597
598 // Like StoreScriptErrors(), but just posts a single string message
599 private void StoreScriptError(UUID itemId, string message)
600 {
601 ArrayList errors = new ArrayList(1);
602 errors.Add(message);
603 StoreScriptErrors(itemId, errors);
451 } 604 }
452 605
453 /// <summary> 606 /// <summary>
@@ -460,15 +613,7 @@ namespace OpenSim.Region.Framework.Scenes
460 /// </param> 613 /// </param>
461 public void RemoveScriptInstance(UUID itemId, bool sceneObjectBeingDeleted) 614 public void RemoveScriptInstance(UUID itemId, bool sceneObjectBeingDeleted)
462 { 615 {
463 bool scriptPresent = false; 616 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 { 617 {
473 if (!sceneObjectBeingDeleted) 618 if (!sceneObjectBeingDeleted)
474 m_part.RemoveScriptEvents(itemId); 619 m_part.RemoveScriptEvents(itemId);
@@ -538,14 +683,16 @@ namespace OpenSim.Region.Framework.Scenes
538 /// <returns></returns> 683 /// <returns></returns>
539 private bool InventoryContainsName(string name) 684 private bool InventoryContainsName(string name)
540 { 685 {
541 lock (m_items) 686 m_items.LockItemsForRead(true);
687 foreach (TaskInventoryItem item in m_items.Values)
542 { 688 {
543 foreach (TaskInventoryItem item in m_items.Values) 689 if (item.Name == name)
544 { 690 {
545 if (item.Name == name) 691 m_items.LockItemsForRead(false);
546 return true; 692 return true;
547 } 693 }
548 } 694 }
695 m_items.LockItemsForRead(false);
549 return false; 696 return false;
550 } 697 }
551 698
@@ -587,8 +734,9 @@ namespace OpenSim.Region.Framework.Scenes
587 /// <param name="item"></param> 734 /// <param name="item"></param>
588 public void AddInventoryItemExclusive(TaskInventoryItem item, bool allowedDrop) 735 public void AddInventoryItemExclusive(TaskInventoryItem item, bool allowedDrop)
589 { 736 {
590 List<TaskInventoryItem> il = GetInventoryItems(); 737 m_items.LockItemsForRead(true);
591 738 List<TaskInventoryItem> il = new List<TaskInventoryItem>(m_items.Values);
739 m_items.LockItemsForRead(false);
592 foreach (TaskInventoryItem i in il) 740 foreach (TaskInventoryItem i in il)
593 { 741 {
594 if (i.Name == item.Name) 742 if (i.Name == item.Name)
@@ -626,14 +774,14 @@ namespace OpenSim.Region.Framework.Scenes
626 item.Name = name; 774 item.Name = name;
627 item.GroupID = m_part.GroupID; 775 item.GroupID = m_part.GroupID;
628 776
629 lock (m_items) 777 m_items.LockItemsForWrite(true);
630 m_items.Add(item.ItemID, item); 778 m_items.Add(item.ItemID, item);
631 779 m_items.LockItemsForWrite(false);
632 if (allowedDrop) 780 if (allowedDrop)
633 m_part.TriggerScriptChangedEvent(Changed.ALLOWED_DROP); 781 m_part.TriggerScriptChangedEvent(Changed.ALLOWED_DROP);
634 else 782 else
635 m_part.TriggerScriptChangedEvent(Changed.INVENTORY); 783 m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
636 784
637 m_inventorySerial++; 785 m_inventorySerial++;
638 //m_inventorySerial += 2; 786 //m_inventorySerial += 2;
639 HasInventoryChanged = true; 787 HasInventoryChanged = true;
@@ -649,15 +797,15 @@ namespace OpenSim.Region.Framework.Scenes
649 /// <param name="items"></param> 797 /// <param name="items"></param>
650 public void RestoreInventoryItems(ICollection<TaskInventoryItem> items) 798 public void RestoreInventoryItems(ICollection<TaskInventoryItem> items)
651 { 799 {
652 lock (m_items) 800 m_items.LockItemsForWrite(true);
801 foreach (TaskInventoryItem item in items)
653 { 802 {
654 foreach (TaskInventoryItem item in items) 803 m_items.Add(item.ItemID, item);
655 { 804// m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
656 m_items.Add(item.ItemID, item);
657// m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
658 }
659 m_inventorySerial++;
660 } 805 }
806 m_items.LockItemsForWrite(false);
807
808 m_inventorySerial++;
661 } 809 }
662 810
663 /// <summary> 811 /// <summary>
@@ -668,23 +816,24 @@ namespace OpenSim.Region.Framework.Scenes
668 public TaskInventoryItem GetInventoryItem(UUID itemId) 816 public TaskInventoryItem GetInventoryItem(UUID itemId)
669 { 817 {
670 TaskInventoryItem item; 818 TaskInventoryItem item;
671 819 m_items.LockItemsForRead(true);
672 lock (m_items) 820 m_items.TryGetValue(itemId, out item);
673 m_items.TryGetValue(itemId, out item); 821 m_items.LockItemsForRead(false);
674
675 return item; 822 return item;
676 } 823 }
677 824
678 public TaskInventoryItem GetInventoryItem(string name) 825 public TaskInventoryItem GetInventoryItem(string name)
679 { 826 {
680 lock (m_items) 827 m_items.LockItemsForRead(true);
828 foreach (TaskInventoryItem item in m_items.Values)
681 { 829 {
682 foreach (TaskInventoryItem item in m_items.Values) 830 if (item.Name == name)
683 { 831 {
684 if (item.Name == name) 832 m_items.LockItemsForRead(false);
685 return item; 833 return item;
686 } 834 }
687 } 835 }
836 m_items.LockItemsForRead(false);
688 837
689 return null; 838 return null;
690 } 839 }
@@ -693,15 +842,16 @@ namespace OpenSim.Region.Framework.Scenes
693 { 842 {
694 List<TaskInventoryItem> items = new List<TaskInventoryItem>(); 843 List<TaskInventoryItem> items = new List<TaskInventoryItem>();
695 844
696 lock (m_items) 845 m_items.LockItemsForRead(true);
846
847 foreach (TaskInventoryItem item in m_items.Values)
697 { 848 {
698 foreach (TaskInventoryItem item in m_items.Values) 849 if (item.Name == name)
699 { 850 items.Add(item);
700 if (item.Name == name)
701 items.Add(item);
702 }
703 } 851 }
704 852
853 m_items.LockItemsForRead(false);
854
705 return items; 855 return items;
706 } 856 }
707 857
@@ -720,6 +870,10 @@ namespace OpenSim.Region.Framework.Scenes
720 string xmlData = Utils.BytesToString(rezAsset.Data); 870 string xmlData = Utils.BytesToString(rezAsset.Data);
721 SceneObjectGroup group = SceneObjectSerializer.FromOriginalXmlFormat(xmlData); 871 SceneObjectGroup group = SceneObjectSerializer.FromOriginalXmlFormat(xmlData);
722 872
873 group.RootPart.AttachPoint = group.RootPart.Shape.State;
874 group.RootPart.AttachOffset = group.AbsolutePosition;
875 group.RootPart.AttachRotation = group.GroupRotation;
876
723 group.ResetIDs(); 877 group.ResetIDs();
724 878
725 SceneObjectPart rootPart = group.GetPart(group.UUID); 879 SceneObjectPart rootPart = group.GetPart(group.UUID);
@@ -794,8 +948,9 @@ namespace OpenSim.Region.Framework.Scenes
794 948
795 public bool UpdateInventoryItem(TaskInventoryItem item, bool fireScriptEvents, bool considerChanged) 949 public bool UpdateInventoryItem(TaskInventoryItem item, bool fireScriptEvents, bool considerChanged)
796 { 950 {
797 TaskInventoryItem it = GetInventoryItem(item.ItemID); 951 m_items.LockItemsForWrite(true);
798 if (it != null) 952
953 if (m_items.ContainsKey(item.ItemID))
799 { 954 {
800// m_log.DebugFormat("[PRIM INVENTORY]: Updating item {0} in {1}", item.Name, m_part.Name); 955// m_log.DebugFormat("[PRIM INVENTORY]: Updating item {0} in {1}", item.Name, m_part.Name);
801 956
@@ -808,14 +963,10 @@ namespace OpenSim.Region.Framework.Scenes
808 item.GroupID = m_part.GroupID; 963 item.GroupID = m_part.GroupID;
809 964
810 if (item.AssetID == UUID.Zero) 965 if (item.AssetID == UUID.Zero)
811 item.AssetID = it.AssetID; 966 item.AssetID = m_items[item.ItemID].AssetID;
812 967
813 lock (m_items) 968 m_items[item.ItemID] = item;
814 { 969 m_inventorySerial++;
815 m_items[item.ItemID] = item;
816 m_inventorySerial++;
817 }
818
819 if (fireScriptEvents) 970 if (fireScriptEvents)
820 m_part.TriggerScriptChangedEvent(Changed.INVENTORY); 971 m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
821 972
@@ -824,7 +975,7 @@ namespace OpenSim.Region.Framework.Scenes
824 HasInventoryChanged = true; 975 HasInventoryChanged = true;
825 m_part.ParentGroup.HasGroupChanged = true; 976 m_part.ParentGroup.HasGroupChanged = true;
826 } 977 }
827 978 m_items.LockItemsForWrite(false);
828 return true; 979 return true;
829 } 980 }
830 else 981 else
@@ -835,8 +986,9 @@ namespace OpenSim.Region.Framework.Scenes
835 item.ItemID, m_part.Name, m_part.UUID, 986 item.ItemID, m_part.Name, m_part.UUID,
836 m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName); 987 m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
837 } 988 }
838 return false; 989 m_items.LockItemsForWrite(false);
839 990
991 return false;
840 } 992 }
841 993
842 /// <summary> 994 /// <summary>
@@ -847,43 +999,59 @@ namespace OpenSim.Region.Framework.Scenes
847 /// in this prim's inventory.</returns> 999 /// in this prim's inventory.</returns>
848 public int RemoveInventoryItem(UUID itemID) 1000 public int RemoveInventoryItem(UUID itemID)
849 { 1001 {
850 TaskInventoryItem item = GetInventoryItem(itemID); 1002 m_items.LockItemsForRead(true);
851 if (item != null) 1003
1004 if (m_items.ContainsKey(itemID))
852 { 1005 {
853 int type = m_items[itemID].InvType; 1006 int type = m_items[itemID].InvType;
1007 m_items.LockItemsForRead(false);
854 if (type == 10) // Script 1008 if (type == 10) // Script
855 { 1009 {
856 m_part.RemoveScriptEvents(itemID);
857 m_part.ParentGroup.Scene.EventManager.TriggerRemoveScript(m_part.LocalId, itemID); 1010 m_part.ParentGroup.Scene.EventManager.TriggerRemoveScript(m_part.LocalId, itemID);
858 } 1011 }
1012 m_items.LockItemsForWrite(true);
859 m_items.Remove(itemID); 1013 m_items.Remove(itemID);
1014 m_items.LockItemsForWrite(false);
860 m_inventorySerial++; 1015 m_inventorySerial++;
861 m_part.TriggerScriptChangedEvent(Changed.INVENTORY); 1016 m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
862 1017
863 HasInventoryChanged = true; 1018 HasInventoryChanged = true;
864 m_part.ParentGroup.HasGroupChanged = true; 1019 m_part.ParentGroup.HasGroupChanged = true;
865 1020
866 if (!ContainsScripts()) 1021 int scriptcount = 0;
1022 m_items.LockItemsForRead(true);
1023 foreach (TaskInventoryItem item in m_items.Values)
1024 {
1025 if (item.Type == 10)
1026 {
1027 scriptcount++;
1028 }
1029 }
1030 m_items.LockItemsForRead(false);
1031
1032
1033 if (scriptcount <= 0)
1034 {
867 m_part.RemFlag(PrimFlags.Scripted); 1035 m_part.RemFlag(PrimFlags.Scripted);
1036 }
868 1037
869 m_part.ScheduleFullUpdate(); 1038 m_part.ScheduleFullUpdate();
870 1039
871 return type; 1040 return type;
872
873 } 1041 }
874 else 1042 else
875 { 1043 {
1044 m_items.LockItemsForRead(false);
876 m_log.ErrorFormat( 1045 m_log.ErrorFormat(
877 "[PRIM INVENTORY]: " + 1046 "[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", 1047 "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, 1048 itemID, m_part.Name, m_part.UUID);
880 m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
881 } 1049 }
882 1050
883 return -1; 1051 return -1;
884 } 1052 }
885 1053
886 private bool CreateInventoryFile() 1054 private bool CreateInventoryFileName()
887 { 1055 {
888// m_log.DebugFormat( 1056// m_log.DebugFormat(
889// "[PRIM INVENTORY]: Creating inventory file for {0} {1} {2}, serial {3}", 1057// "[PRIM INVENTORY]: Creating inventory file for {0} {1} {2}, serial {3}",
@@ -892,70 +1060,12 @@ namespace OpenSim.Region.Framework.Scenes
892 if (m_inventoryFileName == String.Empty || 1060 if (m_inventoryFileName == String.Empty ||
893 m_inventoryFileNameSerial < m_inventorySerial) 1061 m_inventoryFileNameSerial < m_inventorySerial)
894 { 1062 {
895 // Something changed, we need to create a new file
896 m_inventoryFileName = "inventory_" + UUID.Random().ToString() + ".tmp"; 1063 m_inventoryFileName = "inventory_" + UUID.Random().ToString() + ".tmp";
897 m_inventoryFileNameSerial = m_inventorySerial; 1064 m_inventoryFileNameSerial = m_inventorySerial;
898 1065
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; 1066 return true;
956 } 1067 }
957 1068
958 // No need to recreate, the existing file is fine
959 return false; 1069 return false;
960 } 1070 }
961 1071
@@ -965,43 +1075,110 @@ namespace OpenSim.Region.Framework.Scenes
965 /// <param name="xferManager"></param> 1075 /// <param name="xferManager"></param>
966 public void RequestInventoryFile(IClientAPI client, IXfer xferManager) 1076 public void RequestInventoryFile(IClientAPI client, IXfer xferManager)
967 { 1077 {
968 lock (m_items) 1078 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 1079
978 client.SendTaskInventory(m_part.UUID, 0, new byte[0]); 1080 bool includeAssets = false;
979 return; 1081 if (m_part.ParentGroup.Scene.Permissions.CanEditObjectInventory(m_part.UUID, client.AgentId))
980 } 1082 includeAssets = true;
1083
1084 if (m_inventoryPrivileged != includeAssets)
1085 changed = true;
981 1086
982 CreateInventoryFile(); 1087 InventoryStringBuilder invString = new InventoryStringBuilder(m_part.UUID, UUID.Zero);
1088
1089 Items.LockItemsForRead(true);
1090
1091 if (m_inventorySerial == 0) // No inventory
1092 {
1093 client.SendTaskInventory(m_part.UUID, 0, new byte[0]);
1094 Items.LockItemsForRead(false);
1095 return;
1096 }
1097
1098 if (m_items.Count == 0) // No inventory
1099 {
1100 client.SendTaskInventory(m_part.UUID, 0, new byte[0]);
1101 Items.LockItemsForRead(false);
1102 return;
1103 }
983 1104
984 // In principle, we should only do the rest if the inventory changed; 1105 if (!changed)
985 // by sending m_inventorySerial to the client, it ought to know 1106 {
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) 1107 if (m_inventoryFileData.Length > 2)
992 { 1108 {
993 // Add the file for Xfer 1109 xferManager.AddNewFile(m_inventoryFileName,
994 // m_log.DebugFormat( 1110 m_inventoryFileData);
995 // "[PRIM INVENTORY]: Adding inventory file {0} (length {1}) for transfer on {2} {3} {4}", 1111 client.SendTaskInventory(m_part.UUID, (short)m_inventorySerial,
996 // m_inventoryFileName, m_inventoryFileData.Length, m_part.Name, m_part.UUID, m_part.LocalId); 1112 Util.StringToBytes256(m_inventoryFileName));
997 1113
998 xferManager.AddNewFile(m_inventoryFileName, m_inventoryFileData); 1114 Items.LockItemsForRead(false);
1115 return;
999 } 1116 }
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 } 1117 }
1118
1119 m_inventoryPrivileged = includeAssets;
1120
1121 foreach (TaskInventoryItem item in m_items.Values)
1122 {
1123 UUID ownerID = item.OwnerID;
1124 uint everyoneMask = 0;
1125 uint baseMask = item.BasePermissions;
1126 uint ownerMask = item.CurrentPermissions;
1127 uint groupMask = item.GroupPermissions;
1128
1129 invString.AddItemStart();
1130 invString.AddNameValueLine("item_id", item.ItemID.ToString());
1131 invString.AddNameValueLine("parent_id", m_part.UUID.ToString());
1132
1133 invString.AddPermissionsStart();
1134
1135 invString.AddNameValueLine("base_mask", Utils.UIntToHexString(baseMask));
1136 invString.AddNameValueLine("owner_mask", Utils.UIntToHexString(ownerMask));
1137 invString.AddNameValueLine("group_mask", Utils.UIntToHexString(groupMask));
1138 invString.AddNameValueLine("everyone_mask", Utils.UIntToHexString(everyoneMask));
1139 invString.AddNameValueLine("next_owner_mask", Utils.UIntToHexString(item.NextPermissions));
1140
1141 invString.AddNameValueLine("creator_id", item.CreatorID.ToString());
1142 invString.AddNameValueLine("owner_id", ownerID.ToString());
1143
1144 invString.AddNameValueLine("last_owner_id", item.LastOwnerID.ToString());
1145
1146 invString.AddNameValueLine("group_id", item.GroupID.ToString());
1147 invString.AddSectionEnd();
1148
1149 if (includeAssets)
1150 invString.AddNameValueLine("asset_id", item.AssetID.ToString());
1151 else
1152 invString.AddNameValueLine("asset_id", UUID.Zero.ToString());
1153 invString.AddNameValueLine("type", Utils.AssetTypeToString((AssetType)item.Type));
1154 invString.AddNameValueLine("inv_type", Utils.InventoryTypeToString((InventoryType)item.InvType));
1155 invString.AddNameValueLine("flags", Utils.UIntToHexString(item.Flags));
1156
1157 invString.AddSaleStart();
1158 invString.AddNameValueLine("sale_type", "not");
1159 invString.AddNameValueLine("sale_price", "0");
1160 invString.AddSectionEnd();
1161
1162 invString.AddNameValueLine("name", item.Name + "|");
1163 invString.AddNameValueLine("desc", item.Description + "|");
1164
1165 invString.AddNameValueLine("creation_date", item.CreationDate.ToString());
1166 invString.AddSectionEnd();
1167 }
1168
1169 Items.LockItemsForRead(false);
1170
1171 m_inventoryFileData = Utils.StringToBytes(invString.BuildString);
1172
1173 if (m_inventoryFileData.Length > 2)
1174 {
1175 xferManager.AddNewFile(m_inventoryFileName, m_inventoryFileData);
1176 client.SendTaskInventory(m_part.UUID, (short)m_inventorySerial,
1177 Util.StringToBytes256(m_inventoryFileName));
1178 return;
1179 }
1180
1181 client.SendTaskInventory(m_part.UUID, 0, new byte[0]);
1005 } 1182 }
1006 1183
1007 /// <summary> 1184 /// <summary>
@@ -1010,13 +1187,19 @@ namespace OpenSim.Region.Framework.Scenes
1010 /// <param name="datastore"></param> 1187 /// <param name="datastore"></param>
1011 public void ProcessInventoryBackup(ISimulationDataService datastore) 1188 public void ProcessInventoryBackup(ISimulationDataService datastore)
1012 { 1189 {
1013 if (HasInventoryChanged) 1190// Removed this because linking will cause an immediate delete of the new
1014 { 1191// child prim from the database and the subsequent storing of the prim sees
1015 HasInventoryChanged = false; 1192// the inventory of it as unchanged and doesn't store it at all. The overhead
1016 List<TaskInventoryItem> items = GetInventoryItems(); 1193// of storing prim inventory needlessly is much less than the aggravation
1017 datastore.StorePrimInventory(m_part.UUID, items); 1194// of prim inventory loss.
1195// if (HasInventoryChanged)
1196// {
1197 Items.LockItemsForRead(true);
1198 datastore.StorePrimInventory(m_part.UUID, Items.Values);
1199 Items.LockItemsForRead(false);
1018 1200
1019 } 1201 HasInventoryChanged = false;
1202// }
1020 } 1203 }
1021 1204
1022 public class InventoryStringBuilder 1205 public class InventoryStringBuilder
@@ -1082,87 +1265,63 @@ namespace OpenSim.Region.Framework.Scenes
1082 { 1265 {
1083 uint mask=0x7fffffff; 1266 uint mask=0x7fffffff;
1084 1267
1085 lock (m_items) 1268 foreach (TaskInventoryItem item in m_items.Values)
1086 { 1269 {
1087 foreach (TaskInventoryItem item in m_items.Values) 1270 if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Copy) == 0)
1271 mask &= ~((uint)PermissionMask.Copy >> 13);
1272 if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Transfer) == 0)
1273 mask &= ~((uint)PermissionMask.Transfer >> 13);
1274 if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Modify) == 0)
1275 mask &= ~((uint)PermissionMask.Modify >> 13);
1276
1277 if (item.InvType == (int)InventoryType.Object)
1088 { 1278 {
1089 if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Copy) == 0) 1279 if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0)
1090 mask &= ~((uint)PermissionMask.Copy >> 13); 1280 mask &= ~((uint)PermissionMask.Copy >> 13);
1091 if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Transfer) == 0) 1281 if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0)
1092 mask &= ~((uint)PermissionMask.Transfer >> 13); 1282 mask &= ~((uint)PermissionMask.Transfer >> 13);
1093 if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Modify) == 0) 1283 if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0)
1094 mask &= ~((uint)PermissionMask.Modify >> 13); 1284 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 } 1285 }
1286
1287 if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
1288 mask &= ~(uint)PermissionMask.Copy;
1289 if ((item.CurrentPermissions & (uint)PermissionMask.Transfer) == 0)
1290 mask &= ~(uint)PermissionMask.Transfer;
1291 if ((item.CurrentPermissions & (uint)PermissionMask.Modify) == 0)
1292 mask &= ~(uint)PermissionMask.Modify;
1122 } 1293 }
1123
1124 return mask; 1294 return mask;
1125 } 1295 }
1126 1296
1127 public void ApplyNextOwnerPermissions() 1297 public void ApplyNextOwnerPermissions()
1128 { 1298 {
1129 lock (m_items) 1299 foreach (TaskInventoryItem item in m_items.Values)
1130 { 1300 {
1131 foreach (TaskInventoryItem item in m_items.Values) 1301 if (item.InvType == (int)InventoryType.Object && (item.CurrentPermissions & 7) != 0)
1132 { 1302 {
1133// m_log.DebugFormat ( 1303 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}", 1304 item.CurrentPermissions &= ~(uint)PermissionMask.Copy;
1135// item.NextPermissions, item.Name, m_part.Name, item.CurrentPermissions, item.BasePermissions, item.EveryonePermissions); 1305 if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0)
1136 1306 item.CurrentPermissions &= ~(uint)PermissionMask.Transfer;
1137 if (item.InvType == (int)InventoryType.Object && (item.CurrentPermissions & 7) != 0) 1307 if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0)
1138 { 1308 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 } 1309 }
1310 item.CurrentPermissions &= item.NextPermissions;
1311 item.BasePermissions &= item.NextPermissions;
1312 item.EveryonePermissions &= item.NextPermissions;
1313 item.OwnerChanged = true;
1314 item.PermsMask = 0;
1315 item.PermsGranter = UUID.Zero;
1154 } 1316 }
1155 } 1317 }
1156 1318
1157 public void ApplyGodPermissions(uint perms) 1319 public void ApplyGodPermissions(uint perms)
1158 { 1320 {
1159 lock (m_items) 1321 foreach (TaskInventoryItem item in m_items.Values)
1160 { 1322 {
1161 foreach (TaskInventoryItem item in m_items.Values) 1323 item.CurrentPermissions = perms;
1162 { 1324 item.BasePermissions = perms;
1163 item.CurrentPermissions = perms;
1164 item.BasePermissions = perms;
1165 }
1166 } 1325 }
1167 1326
1168 m_inventorySerial++; 1327 m_inventorySerial++;
@@ -1175,14 +1334,11 @@ namespace OpenSim.Region.Framework.Scenes
1175 /// <returns></returns> 1334 /// <returns></returns>
1176 public bool ContainsScripts() 1335 public bool ContainsScripts()
1177 { 1336 {
1178 lock (m_items) 1337 foreach (TaskInventoryItem item in m_items.Values)
1179 { 1338 {
1180 foreach (TaskInventoryItem item in m_items.Values) 1339 if (item.InvType == (int)InventoryType.LSL)
1181 { 1340 {
1182 if (item.InvType == (int)InventoryType.LSL) 1341 return true;
1183 {
1184 return true;
1185 }
1186 } 1342 }
1187 } 1343 }
1188 1344
@@ -1196,17 +1352,15 @@ namespace OpenSim.Region.Framework.Scenes
1196 public int ScriptCount() 1352 public int ScriptCount()
1197 { 1353 {
1198 int count = 0; 1354 int count = 0;
1199 lock (m_items) 1355 Items.LockItemsForRead(true);
1356 foreach (TaskInventoryItem item in m_items.Values)
1200 { 1357 {
1201 foreach (TaskInventoryItem item in m_items.Values) 1358 if (item.InvType == (int)InventoryType.LSL)
1202 { 1359 {
1203 if (item.InvType == (int)InventoryType.LSL) 1360 count++;
1204 {
1205 count++;
1206 }
1207 } 1361 }
1208 } 1362 }
1209 1363 Items.LockItemsForRead(false);
1210 return count; 1364 return count;
1211 } 1365 }
1212 /// <summary> 1366 /// <summary>
@@ -1242,11 +1396,8 @@ namespace OpenSim.Region.Framework.Scenes
1242 { 1396 {
1243 List<UUID> ret = new List<UUID>(); 1397 List<UUID> ret = new List<UUID>();
1244 1398
1245 lock (m_items) 1399 foreach (TaskInventoryItem item in m_items.Values)
1246 { 1400 ret.Add(item.ItemID);
1247 foreach (TaskInventoryItem item in m_items.Values)
1248 ret.Add(item.ItemID);
1249 }
1250 1401
1251 return ret; 1402 return ret;
1252 } 1403 }
@@ -1255,8 +1406,9 @@ namespace OpenSim.Region.Framework.Scenes
1255 { 1406 {
1256 List<TaskInventoryItem> ret = new List<TaskInventoryItem>(); 1407 List<TaskInventoryItem> ret = new List<TaskInventoryItem>();
1257 1408
1258 lock (m_items) 1409 Items.LockItemsForRead(true);
1259 ret = new List<TaskInventoryItem>(m_items.Values); 1410 ret = new List<TaskInventoryItem>(m_items.Values);
1411 Items.LockItemsForRead(false);
1260 1412
1261 return ret; 1413 return ret;
1262 } 1414 }
@@ -1265,18 +1417,24 @@ namespace OpenSim.Region.Framework.Scenes
1265 { 1417 {
1266 List<TaskInventoryItem> ret = new List<TaskInventoryItem>(); 1418 List<TaskInventoryItem> ret = new List<TaskInventoryItem>();
1267 1419
1268 lock (m_items) 1420 Items.LockItemsForRead(true);
1269 { 1421
1270 foreach (TaskInventoryItem item in m_items.Values) 1422 foreach (TaskInventoryItem item in m_items.Values)
1271 if (item.InvType == (int)type) 1423 if (item.InvType == (int)type)
1272 ret.Add(item); 1424 ret.Add(item);
1273 } 1425
1426 Items.LockItemsForRead(false);
1274 1427
1275 return ret; 1428 return ret;
1276 } 1429 }
1277 1430
1278 public Dictionary<UUID, string> GetScriptStates() 1431 public Dictionary<UUID, string> GetScriptStates()
1279 { 1432 {
1433 return GetScriptStates(false);
1434 }
1435
1436 public Dictionary<UUID, string> GetScriptStates(bool oldIDs)
1437 {
1280 Dictionary<UUID, string> ret = new Dictionary<UUID, string>(); 1438 Dictionary<UUID, string> ret = new Dictionary<UUID, string>();
1281 1439
1282 if (m_part.ParentGroup.Scene == null) // Group not in a scene 1440 if (m_part.ParentGroup.Scene == null) // Group not in a scene
@@ -1302,14 +1460,21 @@ namespace OpenSim.Region.Framework.Scenes
1302 string n = e.GetXMLState(item.ItemID); 1460 string n = e.GetXMLState(item.ItemID);
1303 if (n != String.Empty) 1461 if (n != String.Empty)
1304 { 1462 {
1305 if (!ret.ContainsKey(item.ItemID)) 1463 if (oldIDs)
1306 ret[item.ItemID] = n; 1464 {
1465 if (!ret.ContainsKey(item.OldItemID))
1466 ret[item.OldItemID] = n;
1467 }
1468 else
1469 {
1470 if (!ret.ContainsKey(item.ItemID))
1471 ret[item.ItemID] = n;
1472 }
1307 break; 1473 break;
1308 } 1474 }
1309 } 1475 }
1310 } 1476 }
1311 } 1477 }
1312
1313 return ret; 1478 return ret;
1314 } 1479 }
1315 1480
diff --git a/OpenSim/Region/Framework/Scenes/ScenePresence.cs b/OpenSim/Region/Framework/Scenes/ScenePresence.cs
index 0e7f2e5..e27d309 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.
@@ -175,6 +176,7 @@ namespace OpenSim.Region.Framework.Scenes
175// private int m_lastColCount = -1; //KF: Look for Collision chnages 176// private int m_lastColCount = -1; //KF: Look for Collision chnages
176// private int m_updateCount = 0; //KF: Update Anims for a while 177// private int m_updateCount = 0; //KF: Update Anims for a while
177// private static readonly int UPDATE_COUNT = 10; // how many frames to update for 178// private static readonly int UPDATE_COUNT = 10; // how many frames to update for
179 private List<uint> m_lastColliders = new List<uint>();
178 180
179 private TeleportFlags m_teleportFlags; 181 private TeleportFlags m_teleportFlags;
180 public TeleportFlags TeleportFlags 182 public TeleportFlags TeleportFlags
@@ -236,6 +238,13 @@ namespace OpenSim.Region.Framework.Scenes
236 //private int m_moveToPositionStateStatus; 238 //private int m_moveToPositionStateStatus;
237 //***************************************************** 239 //*****************************************************
238 240
241 private bool m_collisionEventFlag = false;
242 private object m_collisionEventLock = new Object();
243
244 private int m_movementAnimationUpdateCounter = 0;
245
246 private Vector3 m_prevSitOffset;
247
239 protected AvatarAppearance m_appearance; 248 protected AvatarAppearance m_appearance;
240 249
241 public AvatarAppearance Appearance 250 public AvatarAppearance Appearance
@@ -430,7 +439,7 @@ namespace OpenSim.Region.Framework.Scenes
430 get { return (IClientCore)ControllingClient; } 439 get { return (IClientCore)ControllingClient; }
431 } 440 }
432 441
433 public Vector3 ParentPosition { get; set; } 442// public Vector3 ParentPosition { get; set; }
434 443
435 /// <summary> 444 /// <summary>
436 /// Position of this avatar relative to the region the avatar is in 445 /// Position of this avatar relative to the region the avatar is in
@@ -488,7 +497,7 @@ namespace OpenSim.Region.Framework.Scenes
488 if (ParentID == 0) 497 if (ParentID == 0)
489 { 498 {
490 m_pos = value; 499 m_pos = value;
491 ParentPosition = Vector3.Zero; 500// ParentPosition = Vector3.Zero;
492 } 501 }
493 502
494 //m_log.DebugFormat( 503 //m_log.DebugFormat(
@@ -577,6 +586,13 @@ namespace OpenSim.Region.Framework.Scenes
577 /// </summary> 586 /// </summary>
578 public uint ParentID { get; set; } 587 public uint ParentID { get; set; }
579 588
589 public UUID ParentUUID
590 {
591 get { return m_parentUUID; }
592 set { m_parentUUID = value; }
593 }
594 private UUID m_parentUUID = UUID.Zero;
595
580 /// <summary> 596 /// <summary>
581 /// Are we sitting on an object? 597 /// Are we sitting on an object?
582 /// </summary> 598 /// </summary>
@@ -743,6 +759,33 @@ namespace OpenSim.Region.Framework.Scenes
743 Appearance = appearance; 759 Appearance = appearance;
744 } 760 }
745 761
762 private void RegionHeartbeatEnd(Scene scene)
763 {
764 if (IsChildAgent)
765 return;
766
767 m_movementAnimationUpdateCounter ++;
768 if (m_movementAnimationUpdateCounter >= 2)
769 {
770 m_movementAnimationUpdateCounter = 0;
771 if (Animator != null)
772 {
773 // If the parentID == 0 we are not sitting
774 // if !SitGournd then we are not sitting on the ground
775 // Fairly straightforward, now here comes the twist
776 // if ParentUUID is NOT UUID.Zero, we are looking to
777 // be sat on an object that isn't there yet. Should
778 // be treated as if sat.
779 if(ParentID == 0 && !SitGround && ParentUUID == UUID.Zero) // skip it if sitting
780 Animator.UpdateMovementAnimations();
781 }
782 else
783 {
784 m_scene.EventManager.OnRegionHeartbeatEnd -= RegionHeartbeatEnd;
785 }
786 }
787 }
788
746 public void RegisterToEvents() 789 public void RegisterToEvents()
747 { 790 {
748 ControllingClient.OnCompleteMovementToRegion += CompleteMovement; 791 ControllingClient.OnCompleteMovementToRegion += CompleteMovement;
@@ -752,6 +795,7 @@ namespace OpenSim.Region.Framework.Scenes
752 ControllingClient.OnSetAlwaysRun += HandleSetAlwaysRun; 795 ControllingClient.OnSetAlwaysRun += HandleSetAlwaysRun;
753 ControllingClient.OnStartAnim += HandleStartAnim; 796 ControllingClient.OnStartAnim += HandleStartAnim;
754 ControllingClient.OnStopAnim += HandleStopAnim; 797 ControllingClient.OnStopAnim += HandleStopAnim;
798 ControllingClient.OnChangeAnim += avnHandleChangeAnim;
755 ControllingClient.OnForceReleaseControls += HandleForceReleaseControls; 799 ControllingClient.OnForceReleaseControls += HandleForceReleaseControls;
756 ControllingClient.OnAutoPilotGo += MoveToTarget; 800 ControllingClient.OnAutoPilotGo += MoveToTarget;
757 801
@@ -812,10 +856,39 @@ namespace OpenSim.Region.Framework.Scenes
812 "[SCENE]: Upgrading child to root agent for {0} in {1}", 856 "[SCENE]: Upgrading child to root agent for {0} in {1}",
813 Name, m_scene.RegionInfo.RegionName); 857 Name, m_scene.RegionInfo.RegionName);
814 858
815 //m_log.DebugFormat("[SCENE]: known regions in {0}: {1}", Scene.RegionInfo.RegionName, KnownChildRegionHandles.Count);
816
817 bool wasChild = IsChildAgent; 859 bool wasChild = IsChildAgent;
818 IsChildAgent = false; 860
861 if (ParentUUID != UUID.Zero)
862 {
863 m_log.DebugFormat("[SCENE PRESENCE]: Sitting avatar back on prim {0}", ParentUUID);
864 SceneObjectPart part = m_scene.GetSceneObjectPart(ParentUUID);
865 if (part == null)
866 {
867 m_log.ErrorFormat("[SCENE PRESENCE]: Can't find prim {0} to sit on", ParentUUID);
868 }
869 else
870 {
871 part.ParentGroup.AddAvatar(UUID);
872 if (part.SitTargetPosition != Vector3.Zero)
873 part.SitTargetAvatar = UUID;
874// ParentPosition = part.GetWorldPosition();
875 ParentID = part.LocalId;
876 ParentPart = part;
877 m_pos = m_prevSitOffset;
878// pos = ParentPosition;
879 pos = part.GetWorldPosition();
880 }
881 ParentUUID = UUID.Zero;
882
883 IsChildAgent = false;
884
885// Animator.TrySetMovementAnimation("SIT");
886 }
887 else
888 {
889 IsChildAgent = false;
890 }
891
819 892
820 IGroupsModule gm = m_scene.RequestModuleInterface<IGroupsModule>(); 893 IGroupsModule gm = m_scene.RequestModuleInterface<IGroupsModule>();
821 if (gm != null) 894 if (gm != null)
@@ -825,62 +898,72 @@ namespace OpenSim.Region.Framework.Scenes
825 898
826 m_scene.EventManager.TriggerSetRootAgentScene(m_uuid, m_scene); 899 m_scene.EventManager.TriggerSetRootAgentScene(m_uuid, m_scene);
827 900
828 // Moved this from SendInitialData to ensure that Appearance is initialized 901 if (ParentID == 0)
829 // before the inventory is processed in MakeRootAgent. This fixes a race condition
830 // related to the handling of attachments
831 //m_scene.GetAvatarAppearance(ControllingClient, out Appearance);
832 if (m_scene.TestBorderCross(pos, Cardinals.E))
833 { 902 {
834 Border crossedBorder = m_scene.GetCrossedBorder(pos, Cardinals.E); 903 // Moved this from SendInitialData to ensure that Appearance is initialized
835 pos.X = crossedBorder.BorderLine.Z - 1; 904 // before the inventory is processed in MakeRootAgent. This fixes a race condition
836 } 905 // related to the handling of attachments
906 //m_scene.GetAvatarAppearance(ControllingClient, out Appearance);
907 if (m_scene.TestBorderCross(pos, Cardinals.E))
908 {
909 Border crossedBorder = m_scene.GetCrossedBorder(pos, Cardinals.E);
910 pos.X = crossedBorder.BorderLine.Z - 1;
911 }
837 912
838 if (m_scene.TestBorderCross(pos, Cardinals.N)) 913 if (m_scene.TestBorderCross(pos, Cardinals.N))
839 { 914 {
840 Border crossedBorder = m_scene.GetCrossedBorder(pos, Cardinals.N); 915 Border crossedBorder = m_scene.GetCrossedBorder(pos, Cardinals.N);
841 pos.Y = crossedBorder.BorderLine.Z - 1; 916 pos.Y = crossedBorder.BorderLine.Z - 1;
842 } 917 }
843 918
844 CheckAndAdjustLandingPoint(ref pos); 919 CheckAndAdjustLandingPoint(ref pos);
845 920
846 if (pos.X < 0f || pos.Y < 0f || pos.Z < 0f) 921 if (pos.X < 0f || pos.Y < 0f || pos.Z < 0f)
847 { 922 {
848 m_log.WarnFormat( 923 m_log.WarnFormat(
849 "[SCENE PRESENCE]: MakeRootAgent() was given an illegal position of {0} for avatar {1}, {2}. Clamping", 924 "[SCENE PRESENCE]: MakeRootAgent() was given an illegal position of {0} for avatar {1}, {2}. Clamping",
850 pos, Name, UUID); 925 pos, Name, UUID);
851 926
852 if (pos.X < 0f) pos.X = 0f; 927 if (pos.X < 0f) pos.X = 0f;
853 if (pos.Y < 0f) pos.Y = 0f; 928 if (pos.Y < 0f) pos.Y = 0f;
854 if (pos.Z < 0f) pos.Z = 0f; 929 if (pos.Z < 0f) pos.Z = 0f;
855 } 930 }
856 931
857 float localAVHeight = 1.56f; 932 float localAVHeight = 1.56f;
858 if (Appearance.AvatarHeight > 0) 933 if (Appearance.AvatarHeight > 0)
859 localAVHeight = Appearance.AvatarHeight; 934 localAVHeight = Appearance.AvatarHeight;
860 935
861 float posZLimit = 0; 936 float posZLimit = 0;
862 937
863 if (pos.X < Constants.RegionSize && pos.Y < Constants.RegionSize) 938 if (pos.X < Constants.RegionSize && pos.Y < Constants.RegionSize)
864 posZLimit = (float)m_scene.Heightmap[(int)pos.X, (int)pos.Y]; 939 posZLimit = (float)m_scene.Heightmap[(int)pos.X, (int)pos.Y];
865 940
866 float newPosZ = posZLimit + localAVHeight / 2; 941 float newPosZ = posZLimit + localAVHeight / 2;
867 if (posZLimit >= (pos.Z - (localAVHeight / 2)) && !(Single.IsInfinity(newPosZ) || Single.IsNaN(newPosZ))) 942 if (posZLimit >= (pos.Z - (localAVHeight / 2)) && !(Single.IsInfinity(newPosZ) || Single.IsNaN(newPosZ)))
868 { 943 {
869 pos.Z = newPosZ; 944 pos.Z = newPosZ;
870 } 945 }
871 AbsolutePosition = pos; 946 AbsolutePosition = pos;
872 947
873 AddToPhysicalScene(isFlying); 948 if (m_teleportFlags == TeleportFlags.Default)
949 {
950 Vector3 vel = Velocity;
951 AddToPhysicalScene(isFlying);
952 if (PhysicsActor != null)
953 PhysicsActor.SetMomentum(vel);
954 }
955 else
956 AddToPhysicalScene(isFlying);
874 957
875 if (ForceFly) 958 if (ForceFly)
876 { 959 {
877 Flying = true; 960 Flying = true;
878 } 961 }
879 else if (FlyDisabled) 962 else if (FlyDisabled)
880 { 963 {
881 Flying = false; 964 Flying = false;
965 }
882 } 966 }
883
884 // Don't send an animation pack here, since on a region crossing this will sometimes cause a flying 967 // Don't send an animation pack here, since on a region crossing this will sometimes cause a flying
885 // avatar to return to the standing position in mid-air. On login it looks like this is being sent 968 // avatar to return to the standing position in mid-air. On login it looks like this is being sent
886 // elsewhere anyway 969 // elsewhere anyway
@@ -898,14 +981,19 @@ namespace OpenSim.Region.Framework.Scenes
898 { 981 {
899 m_log.DebugFormat("[SCENE PRESENCE]: Restarting scripts in attachments..."); 982 m_log.DebugFormat("[SCENE PRESENCE]: Restarting scripts in attachments...");
900 // Resume scripts 983 // Resume scripts
901 foreach (SceneObjectGroup sog in m_attachments) 984 Util.FireAndForget(delegate(object x) {
902 { 985 foreach (SceneObjectGroup sog in m_attachments)
903 sog.RootPart.ParentGroup.CreateScriptInstances(0, false, m_scene.DefaultScriptEngine, GetStateSource()); 986 {
904 sog.ResumeScripts(); 987 sog.ScheduleGroupForFullUpdate();
905 } 988 sog.RootPart.ParentGroup.CreateScriptInstances(0, false, m_scene.DefaultScriptEngine, GetStateSource());
989 sog.ResumeScripts();
990 }
991 });
906 } 992 }
907 } 993 }
908 994
995 SendAvatarDataToAllAgents();
996
909 // send the animations of the other presences to me 997 // send the animations of the other presences to me
910 m_scene.ForEachRootScenePresence(delegate(ScenePresence presence) 998 m_scene.ForEachRootScenePresence(delegate(ScenePresence presence)
911 { 999 {
@@ -916,9 +1004,12 @@ namespace OpenSim.Region.Framework.Scenes
916 // If we don't reset the movement flag here, an avatar that crosses to a neighbouring sim and returns will 1004 // If we don't reset the movement flag here, an avatar that crosses to a neighbouring sim and returns will
917 // stall on the border crossing since the existing child agent will still have the last movement 1005 // stall on the border crossing since the existing child agent will still have the last movement
918 // recorded, which stops the input from being processed. 1006 // recorded, which stops the input from being processed.
1007
919 MovementFlag = 0; 1008 MovementFlag = 0;
920 1009
921 m_scene.EventManager.TriggerOnMakeRootAgent(this); 1010 m_scene.EventManager.TriggerOnMakeRootAgent(this);
1011
1012 m_scene.EventManager.OnRegionHeartbeatEnd += RegionHeartbeatEnd;
922 } 1013 }
923 1014
924 public int GetStateSource() 1015 public int GetStateSource()
@@ -946,12 +1037,16 @@ namespace OpenSim.Region.Framework.Scenes
946 /// </remarks> 1037 /// </remarks>
947 public void MakeChildAgent() 1038 public void MakeChildAgent()
948 { 1039 {
1040 m_scene.EventManager.OnRegionHeartbeatEnd -= RegionHeartbeatEnd;
1041
949 m_log.DebugFormat("[SCENE PRESENCE]: Making {0} a child agent in {1}", Name, Scene.RegionInfo.RegionName); 1042 m_log.DebugFormat("[SCENE PRESENCE]: Making {0} a child agent in {1}", Name, Scene.RegionInfo.RegionName);
950 1043
951 // Reset these so that teleporting in and walking out isn't seen 1044 // Reset these so that teleporting in and walking out isn't seen
952 // as teleporting back 1045 // as teleporting back
953 TeleportFlags = TeleportFlags.Default; 1046 TeleportFlags = TeleportFlags.Default;
954 1047
1048 MovementFlag = 0;
1049
955 // It looks like Animator is set to null somewhere, and MakeChild 1050 // It looks like Animator is set to null somewhere, and MakeChild
956 // is called after that. Probably in aborted teleports. 1051 // is called after that. Probably in aborted teleports.
957 if (Animator == null) 1052 if (Animator == null)
@@ -959,6 +1054,7 @@ namespace OpenSim.Region.Framework.Scenes
959 else 1054 else
960 Animator.ResetAnimations(); 1055 Animator.ResetAnimations();
961 1056
1057
962// m_log.DebugFormat( 1058// m_log.DebugFormat(
963// "[SCENE PRESENCE]: Downgrading root agent {0}, {1} to a child agent in {2}", 1059// "[SCENE PRESENCE]: Downgrading root agent {0}, {1} to a child agent in {2}",
964// Name, UUID, m_scene.RegionInfo.RegionName); 1060// Name, UUID, m_scene.RegionInfo.RegionName);
@@ -970,6 +1066,7 @@ namespace OpenSim.Region.Framework.Scenes
970 IsChildAgent = true; 1066 IsChildAgent = true;
971 m_scene.SwapRootAgentCount(true); 1067 m_scene.SwapRootAgentCount(true);
972 RemoveFromPhysicalScene(); 1068 RemoveFromPhysicalScene();
1069 ParentID = 0; // Child agents can't be sitting
973 1070
974 // FIXME: Set RegionHandle to the region handle of the scene this agent is moving into 1071 // FIXME: Set RegionHandle to the region handle of the scene this agent is moving into
975 1072
@@ -985,9 +1082,9 @@ namespace OpenSim.Region.Framework.Scenes
985 { 1082 {
986// PhysicsActor.OnRequestTerseUpdate -= SendTerseUpdateToAllClients; 1083// PhysicsActor.OnRequestTerseUpdate -= SendTerseUpdateToAllClients;
987 PhysicsActor.OnOutOfBounds -= OutOfBoundsCall; 1084 PhysicsActor.OnOutOfBounds -= OutOfBoundsCall;
988 m_scene.PhysicsScene.RemoveAvatar(PhysicsActor);
989 PhysicsActor.UnSubscribeEvents();
990 PhysicsActor.OnCollisionUpdate -= PhysicsCollisionUpdate; 1085 PhysicsActor.OnCollisionUpdate -= PhysicsCollisionUpdate;
1086 PhysicsActor.UnSubscribeEvents();
1087 m_scene.PhysicsScene.RemoveAvatar(PhysicsActor);
991 PhysicsActor = null; 1088 PhysicsActor = null;
992 } 1089 }
993// else 1090// else
@@ -1004,7 +1101,7 @@ namespace OpenSim.Region.Framework.Scenes
1004 /// <param name="pos"></param> 1101 /// <param name="pos"></param>
1005 public void Teleport(Vector3 pos) 1102 public void Teleport(Vector3 pos)
1006 { 1103 {
1007 TeleportWithMomentum(pos, null); 1104 TeleportWithMomentum(pos, Vector3.Zero);
1008 } 1105 }
1009 1106
1010 public void TeleportWithMomentum(Vector3 pos, Vector3? v) 1107 public void TeleportWithMomentum(Vector3 pos, Vector3? v)
@@ -1028,6 +1125,41 @@ namespace OpenSim.Region.Framework.Scenes
1028 SendTerseUpdateToAllClients(); 1125 SendTerseUpdateToAllClients();
1029 } 1126 }
1030 1127
1128 public void avnLocalTeleport(Vector3 newpos, Vector3? newvel, bool rotateToVelXY)
1129 {
1130 CheckLandingPoint(ref newpos);
1131 AbsolutePosition = newpos;
1132
1133 if (newvel.HasValue)
1134 {
1135 if ((Vector3)newvel == Vector3.Zero)
1136 {
1137 if (PhysicsActor != null)
1138 PhysicsActor.SetMomentum(Vector3.Zero);
1139 m_velocity = Vector3.Zero;
1140 }
1141 else
1142 {
1143 if (PhysicsActor != null)
1144 PhysicsActor.SetMomentum((Vector3)newvel);
1145 m_velocity = (Vector3)newvel;
1146
1147 if (rotateToVelXY)
1148 {
1149 Vector3 lookAt = (Vector3)newvel;
1150 lookAt.Z = 0;
1151 lookAt.Normalize();
1152 ControllingClient.SendLocalTeleport(newpos, lookAt, (uint)TeleportFlags.ViaLocation);
1153 return;
1154 }
1155 }
1156 }
1157
1158 SendTerseUpdateToAllClients();
1159 }
1160
1161
1162
1031 public void StopFlying() 1163 public void StopFlying()
1032 { 1164 {
1033 ControllingClient.StopFlying(this); 1165 ControllingClient.StopFlying(this);
@@ -1343,8 +1475,18 @@ namespace OpenSim.Region.Framework.Scenes
1343 { 1475 {
1344 if (m_followCamAuto) 1476 if (m_followCamAuto)
1345 { 1477 {
1346 Vector3 posAdjusted = m_pos + HEAD_ADJUSTMENT; 1478 // Vector3 posAdjusted = m_pos + HEAD_ADJUSTMENT;
1347 m_scene.PhysicsScene.RaycastWorld(m_pos, Vector3.Normalize(CameraPosition - posAdjusted), Vector3.Distance(CameraPosition, posAdjusted) + 0.3f, RayCastCameraCallback); 1479 // m_scene.PhysicsScene.RaycastWorld(m_pos, Vector3.Normalize(CameraPosition - posAdjusted), Vector3.Distance(CameraPosition, posAdjusted) + 0.3f, RayCastCameraCallback);
1480
1481 Vector3 posAdjusted = AbsolutePosition + HEAD_ADJUSTMENT;
1482 Vector3 distTocam = CameraPosition - posAdjusted;
1483 float distTocamlen = distTocam.Length();
1484 if (distTocamlen > 0)
1485 {
1486 distTocam *= 1.0f / distTocamlen;
1487 m_scene.PhysicsScene.RaycastWorld(posAdjusted, distTocam, distTocamlen + 0.3f, RayCastCameraCallback);
1488 }
1489
1348 } 1490 }
1349 } 1491 }
1350 1492
@@ -1778,12 +1920,17 @@ namespace OpenSim.Region.Framework.Scenes
1778// m_log.DebugFormat("[SCENE PRESENCE]: StandUp() for {0}", Name); 1920// m_log.DebugFormat("[SCENE PRESENCE]: StandUp() for {0}", Name);
1779 1921
1780 SitGround = false; 1922 SitGround = false;
1923
1924/* move this down so avatar gets physical in the new position and not where it is siting
1781 if (PhysicsActor == null) 1925 if (PhysicsActor == null)
1782 AddToPhysicalScene(false); 1926 AddToPhysicalScene(false);
1927 */
1783 1928
1784 if (ParentID != 0) 1929 if (ParentID != 0)
1785 { 1930 {
1786 SceneObjectPart part = ParentPart; 1931 SceneObjectPart part = ParentPart;
1932 UnRegisterSeatControls(part.ParentGroup.UUID);
1933
1787 TaskInventoryDictionary taskIDict = part.TaskInventory; 1934 TaskInventoryDictionary taskIDict = part.TaskInventory;
1788 if (taskIDict != null) 1935 if (taskIDict != null)
1789 { 1936 {
@@ -1799,14 +1946,20 @@ namespace OpenSim.Region.Framework.Scenes
1799 } 1946 }
1800 } 1947 }
1801 1948
1802 ParentPosition = part.GetWorldPosition(); 1949 part.ParentGroup.DeleteAvatar(UUID);
1950// ParentPosition = part.GetWorldPosition();
1803 ControllingClient.SendClearFollowCamProperties(part.ParentUUID); 1951 ControllingClient.SendClearFollowCamProperties(part.ParentUUID);
1804 1952
1805 m_pos += ParentPosition + new Vector3(0.0f, 0.0f, 2.0f * m_sitAvatarHeight); 1953// m_pos += ParentPosition + new Vector3(0.0f, 0.0f, 2.0f * m_sitAvatarHeight);
1806 ParentPosition = Vector3.Zero; 1954// ParentPosition = Vector3.Zero;
1955 m_pos += part.GetWorldPosition() + new Vector3(0.0f, 0.0f, 2.0f * m_sitAvatarHeight);
1807 1956
1808 ParentID = 0; 1957 ParentID = 0;
1809 ParentPart = null; 1958 ParentPart = null;
1959
1960 if (PhysicsActor == null)
1961 AddToPhysicalScene(false);
1962
1810 SendAvatarDataToAllAgents(); 1963 SendAvatarDataToAllAgents();
1811 m_requestedSitTargetID = 0; 1964 m_requestedSitTargetID = 0;
1812 1965
@@ -1816,6 +1969,9 @@ namespace OpenSim.Region.Framework.Scenes
1816 part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK); 1969 part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK);
1817 } 1970 }
1818 1971
1972 else if (PhysicsActor == null)
1973 AddToPhysicalScene(false);
1974
1819 Animator.TrySetMovementAnimation("STAND"); 1975 Animator.TrySetMovementAnimation("STAND");
1820 } 1976 }
1821 1977
@@ -1867,7 +2023,7 @@ namespace OpenSim.Region.Framework.Scenes
1867 // see http://wiki.secondlife.com/wiki/User:Andrew_Linden/Office_Hours/2007_11_06 for details on how LL does it 2023 // see http://wiki.secondlife.com/wiki/User:Andrew_Linden/Office_Hours/2007_11_06 for details on how LL does it
1868 2024
1869 if (PhysicsActor != null) 2025 if (PhysicsActor != null)
1870 m_sitAvatarHeight = PhysicsActor.Size.Z; 2026 m_sitAvatarHeight = PhysicsActor.Size.Z * 0.5f;
1871 2027
1872 bool canSit = false; 2028 bool canSit = false;
1873 Vector3 pos = part.AbsolutePosition + offset; 2029 Vector3 pos = part.AbsolutePosition + offset;
@@ -1916,7 +2072,7 @@ namespace OpenSim.Region.Framework.Scenes
1916 forceMouselook = part.GetForceMouselook(); 2072 forceMouselook = part.GetForceMouselook();
1917 2073
1918 ControllingClient.SendSitResponse( 2074 ControllingClient.SendSitResponse(
1919 targetID, offset, sitOrientation, false, cameraAtOffset, cameraEyeOffset, forceMouselook); 2075 part.UUID, offset, sitOrientation, false, cameraAtOffset, cameraEyeOffset, forceMouselook);
1920 2076
1921 m_requestedSitTargetUUID = targetID; 2077 m_requestedSitTargetUUID = targetID;
1922 2078
@@ -1930,6 +2086,9 @@ namespace OpenSim.Region.Framework.Scenes
1930 2086
1931 public void HandleAgentRequestSit(IClientAPI remoteClient, UUID agentID, UUID targetID, Vector3 offset) 2087 public void HandleAgentRequestSit(IClientAPI remoteClient, UUID agentID, UUID targetID, Vector3 offset)
1932 { 2088 {
2089 if (IsChildAgent)
2090 return;
2091
1933 if (ParentID != 0) 2092 if (ParentID != 0)
1934 { 2093 {
1935 StandUp(); 2094 StandUp();
@@ -2207,14 +2366,39 @@ namespace OpenSim.Region.Framework.Scenes
2207 2366
2208 //Quaternion result = (sitTargetOrient * vq) * nq; 2367 //Quaternion result = (sitTargetOrient * vq) * nq;
2209 2368
2210 m_pos = sitTargetPos + SIT_TARGET_ADJUSTMENT; 2369 double x, y, z, m;
2370
2371 Quaternion r = sitTargetOrient;
2372 m = r.X * r.X + r.Y * r.Y + r.Z * r.Z + r.W * r.W;
2373
2374 if (Math.Abs(1.0 - m) > 0.000001)
2375 {
2376 m = 1.0 / Math.Sqrt(m);
2377 r.X *= (float)m;
2378 r.Y *= (float)m;
2379 r.Z *= (float)m;
2380 r.W *= (float)m;
2381 }
2382
2383 x = 2 * (r.X * r.Z + r.Y * r.W);
2384 y = 2 * (-r.X * r.W + r.Y * r.Z);
2385 z = -r.X * r.X - r.Y * r.Y + r.Z * r.Z + r.W * r.W;
2386
2387 Vector3 up = new Vector3((float)x, (float)y, (float)z);
2388 Vector3 sitOffset = up * Appearance.AvatarHeight * 0.02638f;
2389
2390 m_pos = sitTargetPos + sitOffset + SIT_TARGET_ADJUSTMENT;
2391
2392// m_pos = sitTargetPos + SIT_TARGET_ADJUSTMENT - sitOffset;
2211 Rotation = sitTargetOrient; 2393 Rotation = sitTargetOrient;
2212 ParentPosition = part.AbsolutePosition; 2394// ParentPosition = part.AbsolutePosition;
2395 part.ParentGroup.AddAvatar(UUID);
2213 } 2396 }
2214 else 2397 else
2215 { 2398 {
2216 m_pos -= part.AbsolutePosition; 2399 m_pos -= part.AbsolutePosition;
2217 ParentPosition = part.AbsolutePosition; 2400// ParentPosition = part.AbsolutePosition;
2401 part.ParentGroup.AddAvatar(UUID);
2218 2402
2219// m_log.DebugFormat( 2403// m_log.DebugFormat(
2220// "[SCENE PRESENCE]: Sitting {0} at position {1} ({2} + {3}) on part {4} {5} without sit target", 2404// "[SCENE PRESENCE]: Sitting {0} at position {1} ({2} + {3}) on part {4} {5} without sit target",
@@ -2259,6 +2443,13 @@ namespace OpenSim.Region.Framework.Scenes
2259 Animator.RemoveAnimation(animID); 2443 Animator.RemoveAnimation(animID);
2260 } 2444 }
2261 2445
2446 public void avnHandleChangeAnim(UUID animID, bool addRemove,bool sendPack)
2447 {
2448 Animator.avnChangeAnim(animID, addRemove, sendPack);
2449 }
2450
2451
2452
2262 /// <summary> 2453 /// <summary>
2263 /// Rotate the avatar to the given rotation and apply a movement in the given relative vector 2454 /// Rotate the avatar to the given rotation and apply a movement in the given relative vector
2264 /// </summary> 2455 /// </summary>
@@ -2312,14 +2503,15 @@ namespace OpenSim.Region.Framework.Scenes
2312 direc.Z *= 2.6f; 2503 direc.Z *= 2.6f;
2313 2504
2314 // TODO: PreJump and jump happen too quickly. Many times prejump gets ignored. 2505 // TODO: PreJump and jump happen too quickly. Many times prejump gets ignored.
2315 Animator.TrySetMovementAnimation("PREJUMP"); 2506// Animator.TrySetMovementAnimation("PREJUMP");
2316 Animator.TrySetMovementAnimation("JUMP"); 2507// Animator.TrySetMovementAnimation("JUMP");
2317 } 2508 }
2318 } 2509 }
2319 } 2510 }
2320 2511
2321 // TODO: Add the force instead of only setting it to support multiple forces per frame? 2512 // TODO: Add the force instead of only setting it to support multiple forces per frame?
2322 m_forceToApply = direc; 2513 m_forceToApply = direc;
2514 Animator.UpdateMovementAnimations();
2323 } 2515 }
2324 2516
2325 #endregion 2517 #endregion
@@ -2712,8 +2904,9 @@ namespace OpenSim.Region.Framework.Scenes
2712 2904
2713 // If we don't have a PhysActor, we can't cross anyway 2905 // If we don't have a PhysActor, we can't cross anyway
2714 // Also don't do this while sat, sitting avatars cross with the 2906 // Also don't do this while sat, sitting avatars cross with the
2715 // object they sit on. 2907 // object they sit on. ParentUUID denoted a pending sit, don't
2716 if (ParentID != 0 || PhysicsActor == null) 2908 // interfere with it.
2909 if (ParentID != 0 || PhysicsActor == null || ParentUUID != UUID.Zero)
2717 return; 2910 return;
2718 2911
2719 if (!IsInTransit) 2912 if (!IsInTransit)
@@ -3054,6 +3247,9 @@ namespace OpenSim.Region.Framework.Scenes
3054 cAgent.AlwaysRun = SetAlwaysRun; 3247 cAgent.AlwaysRun = SetAlwaysRun;
3055 3248
3056 cAgent.Appearance = new AvatarAppearance(Appearance); 3249 cAgent.Appearance = new AvatarAppearance(Appearance);
3250
3251 cAgent.ParentPart = ParentUUID;
3252 cAgent.SitOffset = m_pos;
3057 3253
3058 lock (scriptedcontrols) 3254 lock (scriptedcontrols)
3059 { 3255 {
@@ -3062,7 +3258,7 @@ namespace OpenSim.Region.Framework.Scenes
3062 3258
3063 foreach (ScriptControllers c in scriptedcontrols.Values) 3259 foreach (ScriptControllers c in scriptedcontrols.Values)
3064 { 3260 {
3065 controls[i++] = new ControllerData(c.itemID, (uint)c.ignoreControls, (uint)c.eventControls); 3261 controls[i++] = new ControllerData(c.objectID, c.itemID, (uint)c.ignoreControls, (uint)c.eventControls);
3066 } 3262 }
3067 cAgent.Controllers = controls; 3263 cAgent.Controllers = controls;
3068 } 3264 }
@@ -3073,6 +3269,7 @@ namespace OpenSim.Region.Framework.Scenes
3073 cAgent.Anims = Animator.Animations.ToArray(); 3269 cAgent.Anims = Animator.Animations.ToArray();
3074 } 3270 }
3075 catch { } 3271 catch { }
3272 cAgent.DefaultAnim = Animator.Animations.DefaultAnimation;
3076 3273
3077 if (Scene.AttachmentsModule != null) 3274 if (Scene.AttachmentsModule != null)
3078 Scene.AttachmentsModule.CopyAttachments(this, cAgent); 3275 Scene.AttachmentsModule.CopyAttachments(this, cAgent);
@@ -3093,6 +3290,8 @@ namespace OpenSim.Region.Framework.Scenes
3093 CameraAtAxis = cAgent.AtAxis; 3290 CameraAtAxis = cAgent.AtAxis;
3094 CameraLeftAxis = cAgent.LeftAxis; 3291 CameraLeftAxis = cAgent.LeftAxis;
3095 CameraUpAxis = cAgent.UpAxis; 3292 CameraUpAxis = cAgent.UpAxis;
3293 ParentUUID = cAgent.ParentPart;
3294 m_prevSitOffset = cAgent.SitOffset;
3096 3295
3097 // When we get to the point of re-computing neighbors everytime this 3296 // When we get to the point of re-computing neighbors everytime this
3098 // changes, then start using the agent's drawdistance rather than the 3297 // changes, then start using the agent's drawdistance rather than the
@@ -3130,6 +3329,7 @@ namespace OpenSim.Region.Framework.Scenes
3130 foreach (ControllerData c in cAgent.Controllers) 3329 foreach (ControllerData c in cAgent.Controllers)
3131 { 3330 {
3132 ScriptControllers sc = new ScriptControllers(); 3331 ScriptControllers sc = new ScriptControllers();
3332 sc.objectID = c.ObjectID;
3133 sc.itemID = c.ItemID; 3333 sc.itemID = c.ItemID;
3134 sc.ignoreControls = (ScriptControlled)c.IgnoreControls; 3334 sc.ignoreControls = (ScriptControlled)c.IgnoreControls;
3135 sc.eventControls = (ScriptControlled)c.EventControls; 3335 sc.eventControls = (ScriptControlled)c.EventControls;
@@ -3144,6 +3344,8 @@ namespace OpenSim.Region.Framework.Scenes
3144 // FIXME: Why is this null check necessary? Where are the cases where we get a null Anims object? 3344 // FIXME: Why is this null check necessary? Where are the cases where we get a null Anims object?
3145 if (cAgent.Anims != null) 3345 if (cAgent.Anims != null)
3146 Animator.Animations.FromArray(cAgent.Anims); 3346 Animator.Animations.FromArray(cAgent.Anims);
3347 if (cAgent.DefaultAnim != null)
3348 Animator.Animations.SetDefaultAnimation(cAgent.DefaultAnim.AnimID, cAgent.DefaultAnim.SequenceNum, UUID.Zero);
3147 3349
3148 if (Scene.AttachmentsModule != null) 3350 if (Scene.AttachmentsModule != null)
3149 Scene.AttachmentsModule.CopyAttachments(cAgent, this); 3351 Scene.AttachmentsModule.CopyAttachments(cAgent, this);
@@ -3206,7 +3408,7 @@ namespace OpenSim.Region.Framework.Scenes
3206 //PhysicsActor.OnRequestTerseUpdate += SendTerseUpdateToAllClients; 3408 //PhysicsActor.OnRequestTerseUpdate += SendTerseUpdateToAllClients;
3207 PhysicsActor.OnCollisionUpdate += PhysicsCollisionUpdate; 3409 PhysicsActor.OnCollisionUpdate += PhysicsCollisionUpdate;
3208 PhysicsActor.OnOutOfBounds += OutOfBoundsCall; // Called for PhysicsActors when there's something wrong 3410 PhysicsActor.OnOutOfBounds += OutOfBoundsCall; // Called for PhysicsActors when there's something wrong
3209 PhysicsActor.SubscribeEvents(500); 3411 PhysicsActor.SubscribeEvents(100);
3210 PhysicsActor.LocalID = LocalId; 3412 PhysicsActor.LocalID = LocalId;
3211 } 3413 }
3212 3414
@@ -3236,18 +3438,6 @@ namespace OpenSim.Region.Framework.Scenes
3236 if (IsChildAgent) 3438 if (IsChildAgent)
3237 return; 3439 return;
3238 3440
3239 //if ((Math.Abs(Velocity.X) > 0.1e-9f) || (Math.Abs(Velocity.Y) > 0.1e-9f))
3240 // The Physics Scene will send updates every 500 ms grep: PhysicsActor.SubscribeEvents(
3241 // as of this comment the interval is set in AddToPhysicalScene
3242 if (Animator != null)
3243 {
3244// if (m_updateCount > 0)
3245// {
3246 Animator.UpdateMovementAnimations();
3247// m_updateCount--;
3248// }
3249 }
3250
3251 CollisionEventUpdate collisionData = (CollisionEventUpdate)e; 3441 CollisionEventUpdate collisionData = (CollisionEventUpdate)e;
3252 Dictionary<uint, ContactPoint> coldata = collisionData.m_objCollisionList; 3442 Dictionary<uint, ContactPoint> coldata = collisionData.m_objCollisionList;
3253 3443
@@ -3290,6 +3480,8 @@ namespace OpenSim.Region.Framework.Scenes
3290 } 3480 }
3291 } 3481 }
3292 3482
3483 RaiseCollisionScriptEvents(coldata);
3484
3293 // Gods do not take damage and Invulnerable is set depending on parcel/region flags 3485 // Gods do not take damage and Invulnerable is set depending on parcel/region flags
3294 if (Invulnerable || GodLevel > 0) 3486 if (Invulnerable || GodLevel > 0)
3295 return; 3487 return;
@@ -3387,7 +3579,8 @@ namespace OpenSim.Region.Framework.Scenes
3387 // m_reprioritizationTimer.Dispose(); 3579 // m_reprioritizationTimer.Dispose();
3388 3580
3389 RemoveFromPhysicalScene(); 3581 RemoveFromPhysicalScene();
3390 Animator.Close(); 3582 if(Animator != null)
3583 Animator.Close();
3391 Animator = null; 3584 Animator = null;
3392 } 3585 }
3393 3586
@@ -3619,10 +3812,15 @@ namespace OpenSim.Region.Framework.Scenes
3619 3812
3620 public void RegisterControlEventsToScript(int controls, int accept, int pass_on, uint Obj_localID, UUID Script_item_UUID) 3813 public void RegisterControlEventsToScript(int controls, int accept, int pass_on, uint Obj_localID, UUID Script_item_UUID)
3621 { 3814 {
3815 SceneObjectPart p = m_scene.GetSceneObjectPart(Obj_localID);
3816 if (p == null)
3817 return;
3818
3622 ScriptControllers obj = new ScriptControllers(); 3819 ScriptControllers obj = new ScriptControllers();
3623 obj.ignoreControls = ScriptControlled.CONTROL_ZERO; 3820 obj.ignoreControls = ScriptControlled.CONTROL_ZERO;
3624 obj.eventControls = ScriptControlled.CONTROL_ZERO; 3821 obj.eventControls = ScriptControlled.CONTROL_ZERO;
3625 3822
3823 obj.objectID = p.ParentGroup.UUID;
3626 obj.itemID = Script_item_UUID; 3824 obj.itemID = Script_item_UUID;
3627 if (pass_on == 0 && accept == 0) 3825 if (pass_on == 0 && accept == 0)
3628 { 3826 {
@@ -3671,6 +3869,21 @@ namespace OpenSim.Region.Framework.Scenes
3671 ControllingClient.SendTakeControls(int.MaxValue, false, false); 3869 ControllingClient.SendTakeControls(int.MaxValue, false, false);
3672 } 3870 }
3673 3871
3872 private void UnRegisterSeatControls(UUID obj)
3873 {
3874 List<UUID> takers = new List<UUID>();
3875
3876 foreach (ScriptControllers c in scriptedcontrols.Values)
3877 {
3878 if (c.objectID == obj)
3879 takers.Add(c.itemID);
3880 }
3881 foreach (UUID t in takers)
3882 {
3883 UnRegisterControlEventsToScript(0, t);
3884 }
3885 }
3886
3674 public void UnRegisterControlEventsToScript(uint Obj_localID, UUID Script_item_UUID) 3887 public void UnRegisterControlEventsToScript(uint Obj_localID, UUID Script_item_UUID)
3675 { 3888 {
3676 ScriptControllers takecontrols; 3889 ScriptControllers takecontrols;
@@ -3989,6 +4202,12 @@ namespace OpenSim.Region.Framework.Scenes
3989 4202
3990 private void CheckAndAdjustLandingPoint(ref Vector3 pos) 4203 private void CheckAndAdjustLandingPoint(ref Vector3 pos)
3991 { 4204 {
4205 string reason;
4206
4207 // Honor bans
4208 if (!m_scene.TestLandRestrictions(UUID, out reason, ref pos.X, ref pos.Y))
4209 return;
4210
3992 SceneObjectGroup telehub = null; 4211 SceneObjectGroup telehub = null;
3993 if (m_scene.RegionInfo.RegionSettings.TelehubObject != UUID.Zero && (telehub = m_scene.GetSceneObjectGroup(m_scene.RegionInfo.RegionSettings.TelehubObject)) != null) 4212 if (m_scene.RegionInfo.RegionSettings.TelehubObject != UUID.Zero && (telehub = m_scene.GetSceneObjectGroup(m_scene.RegionInfo.RegionSettings.TelehubObject)) != null)
3994 { 4213 {
@@ -4028,11 +4247,206 @@ namespace OpenSim.Region.Framework.Scenes
4028 pos = land.LandData.UserLocation; 4247 pos = land.LandData.UserLocation;
4029 } 4248 }
4030 } 4249 }
4031 4250
4032 land.SendLandUpdateToClient(ControllingClient); 4251 land.SendLandUpdateToClient(ControllingClient);
4033 } 4252 }
4034 } 4253 }
4035 4254
4255 private DetectedObject CreateDetObject(SceneObjectPart obj)
4256 {
4257 DetectedObject detobj = new DetectedObject();
4258 detobj.keyUUID = obj.UUID;
4259 detobj.nameStr = obj.Name;
4260 detobj.ownerUUID = obj.OwnerID;
4261 detobj.posVector = obj.AbsolutePosition;
4262 detobj.rotQuat = obj.GetWorldRotation();
4263 detobj.velVector = obj.Velocity;
4264 detobj.colliderType = 0;
4265 detobj.groupUUID = obj.GroupID;
4266
4267 return detobj;
4268 }
4269
4270 private DetectedObject CreateDetObject(ScenePresence av)
4271 {
4272 DetectedObject detobj = new DetectedObject();
4273 detobj.keyUUID = av.UUID;
4274 detobj.nameStr = av.ControllingClient.Name;
4275 detobj.ownerUUID = av.UUID;
4276 detobj.posVector = av.AbsolutePosition;
4277 detobj.rotQuat = av.Rotation;
4278 detobj.velVector = av.Velocity;
4279 detobj.colliderType = 0;
4280 detobj.groupUUID = av.ControllingClient.ActiveGroupId;
4281
4282 return detobj;
4283 }
4284
4285 private DetectedObject CreateDetObjectForGround()
4286 {
4287 DetectedObject detobj = new DetectedObject();
4288 detobj.keyUUID = UUID.Zero;
4289 detobj.nameStr = "";
4290 detobj.ownerUUID = UUID.Zero;
4291 detobj.posVector = AbsolutePosition;
4292 detobj.rotQuat = Quaternion.Identity;
4293 detobj.velVector = Vector3.Zero;
4294 detobj.colliderType = 0;
4295 detobj.groupUUID = UUID.Zero;
4296
4297 return detobj;
4298 }
4299
4300 private ColliderArgs CreateColliderArgs(SceneObjectPart dest, List<uint> colliders)
4301 {
4302 ColliderArgs colliderArgs = new ColliderArgs();
4303 List<DetectedObject> colliding = new List<DetectedObject>();
4304 foreach (uint localId in colliders)
4305 {
4306 if (localId == 0)
4307 continue;
4308
4309 SceneObjectPart obj = m_scene.GetSceneObjectPart(localId);
4310 if (obj != null)
4311 {
4312 if (!dest.CollisionFilteredOut(obj.UUID, obj.Name))
4313 colliding.Add(CreateDetObject(obj));
4314 }
4315 else
4316 {
4317 ScenePresence av = m_scene.GetScenePresence(localId);
4318 if (av != null && (!av.IsChildAgent))
4319 {
4320 if (!dest.CollisionFilteredOut(av.UUID, av.Name))
4321 colliding.Add(CreateDetObject(av));
4322 }
4323 }
4324 }
4325
4326 colliderArgs.Colliders = colliding;
4327
4328 return colliderArgs;
4329 }
4330
4331 private delegate void ScriptCollidingNotification(uint localID, ColliderArgs message);
4332
4333 private void SendCollisionEvent(SceneObjectGroup dest, scriptEvents ev, List<uint> colliders, ScriptCollidingNotification notify)
4334 {
4335 ColliderArgs CollidingMessage;
4336
4337 if (colliders.Count > 0)
4338 {
4339 if ((dest.RootPart.ScriptEvents & ev) != 0)
4340 {
4341 CollidingMessage = CreateColliderArgs(dest.RootPart, colliders);
4342
4343 if (CollidingMessage.Colliders.Count > 0)
4344 notify(dest.RootPart.LocalId, CollidingMessage);
4345 }
4346 }
4347 }
4348
4349 private void SendLandCollisionEvent(SceneObjectGroup dest, scriptEvents ev, ScriptCollidingNotification notify)
4350 {
4351 if ((dest.RootPart.ScriptEvents & ev) != 0)
4352 {
4353 ColliderArgs LandCollidingMessage = new ColliderArgs();
4354 List<DetectedObject> colliding = new List<DetectedObject>();
4355
4356 colliding.Add(CreateDetObjectForGround());
4357 LandCollidingMessage.Colliders = colliding;
4358
4359 notify(dest.RootPart.LocalId, LandCollidingMessage);
4360 }
4361 }
4362
4363 private void RaiseCollisionScriptEvents(Dictionary<uint, ContactPoint> coldata)
4364 {
4365 try
4366 {
4367 List<uint> thisHitColliders = new List<uint>();
4368 List<uint> endedColliders = new List<uint>();
4369 List<uint> startedColliders = new List<uint>();
4370 List<CollisionForSoundInfo> soundinfolist = new List<CollisionForSoundInfo>();
4371 CollisionForSoundInfo soundinfo;
4372 ContactPoint curcontact;
4373
4374 if (coldata.Count == 0)
4375 {
4376 if (m_lastColliders.Count == 0)
4377 return; // nothing to do
4378
4379 foreach (uint localID in m_lastColliders)
4380 {
4381 endedColliders.Add(localID);
4382 }
4383 m_lastColliders.Clear();
4384 }
4385
4386 else
4387 {
4388 foreach (uint id in coldata.Keys)
4389 {
4390 thisHitColliders.Add(id);
4391 if (!m_lastColliders.Contains(id))
4392 {
4393 startedColliders.Add(id);
4394 curcontact = coldata[id];
4395 if (Math.Abs(curcontact.RelativeSpeed) > 0.2)
4396 {
4397 soundinfo = new CollisionForSoundInfo();
4398 soundinfo.colliderID = id;
4399 soundinfo.position = curcontact.Position;
4400 soundinfo.relativeVel = curcontact.RelativeSpeed;
4401 soundinfolist.Add(soundinfo);
4402 }
4403 }
4404 //m_log.Debug("[SCENE PRESENCE]: Collided with:" + localid.ToString() + " at depth of: " + collissionswith[localid].ToString());
4405 }
4406
4407 // calculate things that ended colliding
4408 foreach (uint localID in m_lastColliders)
4409 {
4410 if (!thisHitColliders.Contains(localID))
4411 {
4412 endedColliders.Add(localID);
4413 }
4414 }
4415 //add the items that started colliding this time to the last colliders list.
4416 foreach (uint localID in startedColliders)
4417 {
4418 m_lastColliders.Add(localID);
4419 }
4420 // remove things that ended colliding from the last colliders list
4421 foreach (uint localID in endedColliders)
4422 {
4423 m_lastColliders.Remove(localID);
4424 }
4425
4426 if (soundinfolist.Count > 0)
4427 CollisionSounds.AvatarCollisionSound(this, soundinfolist);
4428 }
4429
4430 foreach (SceneObjectGroup att in GetAttachments())
4431 {
4432 SendCollisionEvent(att, scriptEvents.collision_start, startedColliders, m_scene.EventManager.TriggerScriptCollidingStart);
4433 SendCollisionEvent(att, scriptEvents.collision , m_lastColliders , m_scene.EventManager.TriggerScriptColliding);
4434 SendCollisionEvent(att, scriptEvents.collision_end , endedColliders , m_scene.EventManager.TriggerScriptCollidingEnd);
4435
4436 if (startedColliders.Contains(0))
4437 SendLandCollisionEvent(att, scriptEvents.land_collision_start, m_scene.EventManager.TriggerScriptLandCollidingStart);
4438 if (m_lastColliders.Contains(0))
4439 SendLandCollisionEvent(att, scriptEvents.land_collision, m_scene.EventManager.TriggerScriptLandColliding);
4440 if (endedColliders.Contains(0))
4441 SendLandCollisionEvent(att, scriptEvents.land_collision_end, m_scene.EventManager.TriggerScriptLandCollidingEnd);
4442 }
4443 }
4444 finally
4445 {
4446 m_collisionEventFlag = false;
4447 }
4448 }
4449
4036 private void TeleportFlagsDebug() { 4450 private void TeleportFlagsDebug() {
4037 4451
4038 // Some temporary debugging help to show all the TeleportFlags we have... 4452 // Some temporary debugging help to show all the TeleportFlags we have...
@@ -4057,6 +4471,5 @@ namespace OpenSim.Region.Framework.Scenes
4057 m_log.InfoFormat("[SCENE PRESENCE]: TELEPORT ******************"); 4471 m_log.InfoFormat("[SCENE PRESENCE]: TELEPORT ******************");
4058 4472
4059 } 4473 }
4060
4061 } 4474 }
4062} 4475}
diff --git a/OpenSim/Region/Framework/Scenes/Serialization/SceneObjectSerializer.cs b/OpenSim/Region/Framework/Scenes/Serialization/SceneObjectSerializer.cs
index 0b34156..2372d6b 100644
--- a/OpenSim/Region/Framework/Scenes/Serialization/SceneObjectSerializer.cs
+++ b/OpenSim/Region/Framework/Scenes/Serialization/SceneObjectSerializer.cs
@@ -244,6 +244,12 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
244 sr.Close(); 244 sr.Close();
245 } 245 }
246 246
247 XmlNodeList keymotion = doc.GetElementsByTagName("KeyframeMotion");
248 if (keymotion.Count > 0)
249 sceneObject.RootPart.KeyframeMotion = KeyframeMotion.FromData(sceneObject, Convert.FromBase64String(keymotion[0].InnerText));
250 else
251 sceneObject.RootPart.KeyframeMotion = null;
252
247 // Script state may, or may not, exist. Not having any, is NOT 253 // Script state may, or may not, exist. Not having any, is NOT
248 // ever a problem. 254 // ever a problem.
249 sceneObject.LoadScriptState(doc); 255 sceneObject.LoadScriptState(doc);
@@ -348,6 +354,21 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
348 m_SOPXmlProcessors.Add("PayPrice2", ProcessPayPrice2); 354 m_SOPXmlProcessors.Add("PayPrice2", ProcessPayPrice2);
349 m_SOPXmlProcessors.Add("PayPrice3", ProcessPayPrice3); 355 m_SOPXmlProcessors.Add("PayPrice3", ProcessPayPrice3);
350 m_SOPXmlProcessors.Add("PayPrice4", ProcessPayPrice4); 356 m_SOPXmlProcessors.Add("PayPrice4", ProcessPayPrice4);
357
358 m_SOPXmlProcessors.Add("Buoyancy", ProcessBuoyancy);
359 m_SOPXmlProcessors.Add("Force", ProcessForce);
360 m_SOPXmlProcessors.Add("Torque", ProcessTorque);
361 m_SOPXmlProcessors.Add("VolumeDetectActive", ProcessVolumeDetectActive);
362
363
364 m_SOPXmlProcessors.Add("Vehicle", ProcessVehicle);
365
366 m_SOPXmlProcessors.Add("PhysicsShapeType", ProcessPhysicsShapeType);
367 m_SOPXmlProcessors.Add("Density", ProcessDensity);
368 m_SOPXmlProcessors.Add("Friction", ProcessFriction);
369 m_SOPXmlProcessors.Add("Bounce", ProcessBounce);
370 m_SOPXmlProcessors.Add("GravityModifier", ProcessGravityModifier);
371
351 #endregion 372 #endregion
352 373
353 #region TaskInventoryXmlProcessors initialization 374 #region TaskInventoryXmlProcessors initialization
@@ -375,7 +396,7 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
375 m_TaskInventoryXmlProcessors.Add("PermsMask", ProcessTIPermsMask); 396 m_TaskInventoryXmlProcessors.Add("PermsMask", ProcessTIPermsMask);
376 m_TaskInventoryXmlProcessors.Add("Type", ProcessTIType); 397 m_TaskInventoryXmlProcessors.Add("Type", ProcessTIType);
377 m_TaskInventoryXmlProcessors.Add("OwnerChanged", ProcessTIOwnerChanged); 398 m_TaskInventoryXmlProcessors.Add("OwnerChanged", ProcessTIOwnerChanged);
378 399
379 #endregion 400 #endregion
380 401
381 #region ShapeXmlProcessors initialization 402 #region ShapeXmlProcessors initialization
@@ -575,6 +596,48 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
575 obj.ClickAction = (byte)reader.ReadElementContentAsInt("ClickAction", String.Empty); 596 obj.ClickAction = (byte)reader.ReadElementContentAsInt("ClickAction", String.Empty);
576 } 597 }
577 598
599 private static void ProcessPhysicsShapeType(SceneObjectPart obj, XmlTextReader reader)
600 {
601 obj.PhysicsShapeType = (byte)reader.ReadElementContentAsInt("PhysicsShapeType", String.Empty);
602 }
603
604 private static void ProcessDensity(SceneObjectPart obj, XmlTextReader reader)
605 {
606 obj.Density = reader.ReadElementContentAsFloat("Density", String.Empty);
607 }
608
609 private static void ProcessFriction(SceneObjectPart obj, XmlTextReader reader)
610 {
611 obj.Friction = reader.ReadElementContentAsFloat("Friction", String.Empty);
612 }
613
614 private static void ProcessBounce(SceneObjectPart obj, XmlTextReader reader)
615 {
616 obj.Bounciness = reader.ReadElementContentAsFloat("Bounce", String.Empty);
617 }
618
619 private static void ProcessGravityModifier(SceneObjectPart obj, XmlTextReader reader)
620 {
621 obj.GravityModifier = reader.ReadElementContentAsFloat("GravityModifier", String.Empty);
622 }
623
624 private static void ProcessVehicle(SceneObjectPart obj, XmlTextReader reader)
625 {
626 SOPVehicle vehicle = SOPVehicle.FromXml2(reader);
627
628 if (vehicle == null)
629 {
630 obj.VehicleParams = null;
631 m_log.DebugFormat(
632 "[SceneObjectSerializer]: Parsing Vehicle for object part {0} {1} encountered errors. Please see earlier log entries.",
633 obj.Name, obj.UUID);
634 }
635 else
636 {
637 obj.VehicleParams = vehicle;
638 }
639 }
640
578 private static void ProcessShape(SceneObjectPart obj, XmlTextReader reader) 641 private static void ProcessShape(SceneObjectPart obj, XmlTextReader reader)
579 { 642 {
580 List<string> errorNodeNames; 643 List<string> errorNodeNames;
@@ -739,6 +802,25 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
739 obj.PayPrice[4] = (int)reader.ReadElementContentAsInt("PayPrice4", String.Empty); 802 obj.PayPrice[4] = (int)reader.ReadElementContentAsInt("PayPrice4", String.Empty);
740 } 803 }
741 804
805 private static void ProcessBuoyancy(SceneObjectPart obj, XmlTextReader reader)
806 {
807 obj.Buoyancy = (float)reader.ReadElementContentAsFloat("Buoyancy", String.Empty);
808 }
809
810 private static void ProcessForce(SceneObjectPart obj, XmlTextReader reader)
811 {
812 obj.Force = Util.ReadVector(reader, "Force");
813 }
814 private static void ProcessTorque(SceneObjectPart obj, XmlTextReader reader)
815 {
816 obj.Torque = Util.ReadVector(reader, "Torque");
817 }
818
819 private static void ProcessVolumeDetectActive(SceneObjectPart obj, XmlTextReader reader)
820 {
821 obj.VolumeDetectActive = Util.ReadBoolean(reader);
822 }
823
742 #endregion 824 #endregion
743 825
744 #region TaskInventoryXmlProcessors 826 #region TaskInventoryXmlProcessors
@@ -1126,6 +1208,16 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
1126 }); 1208 });
1127 1209
1128 writer.WriteEndElement(); 1210 writer.WriteEndElement();
1211
1212 if (sog.RootPart.KeyframeMotion != null)
1213 {
1214 Byte[] data = sog.RootPart.KeyframeMotion.Serialize();
1215
1216 writer.WriteStartElement(String.Empty, "KeyframeMotion", String.Empty);
1217 writer.WriteBase64(data, 0, data.Length);
1218 writer.WriteEndElement();
1219 }
1220
1129 writer.WriteEndElement(); 1221 writer.WriteEndElement();
1130 } 1222 }
1131 1223
@@ -1225,6 +1317,27 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
1225 writer.WriteElementString("PayPrice3", sop.PayPrice[3].ToString()); 1317 writer.WriteElementString("PayPrice3", sop.PayPrice[3].ToString());
1226 writer.WriteElementString("PayPrice4", sop.PayPrice[4].ToString()); 1318 writer.WriteElementString("PayPrice4", sop.PayPrice[4].ToString());
1227 1319
1320 writer.WriteElementString("Buoyancy", sop.Buoyancy.ToString());
1321
1322 WriteVector(writer, "Force", sop.Force);
1323 WriteVector(writer, "Torque", sop.Torque);
1324
1325 writer.WriteElementString("VolumeDetectActive", sop.VolumeDetectActive.ToString().ToLower());
1326
1327 if (sop.VehicleParams != null)
1328 sop.VehicleParams.ToXml2(writer);
1329
1330 if(sop.PhysicsShapeType != sop.DefaultPhysicsShapeType())
1331 writer.WriteElementString("PhysicsShapeType", sop.PhysicsShapeType.ToString().ToLower());
1332 if (sop.Density != 1000.0f)
1333 writer.WriteElementString("Density", sop.Density.ToString().ToLower());
1334 if (sop.Friction != 0.6f)
1335 writer.WriteElementString("Friction", sop.Friction.ToString().ToLower());
1336 if (sop.Bounciness != 0.5f)
1337 writer.WriteElementString("Bounce", sop.Bounciness.ToString().ToLower());
1338 if (sop.GravityModifier != 1.0f)
1339 writer.WriteElementString("GravityModifier", sop.GravityModifier.ToString().ToLower());
1340
1228 writer.WriteEndElement(); 1341 writer.WriteEndElement();
1229 } 1342 }
1230 1343
@@ -1449,12 +1562,6 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
1449 { 1562 {
1450 TaskInventoryDictionary tinv = new TaskInventoryDictionary(); 1563 TaskInventoryDictionary tinv = new TaskInventoryDictionary();
1451 1564
1452 if (reader.IsEmptyElement)
1453 {
1454 reader.Read();
1455 return tinv;
1456 }
1457
1458 reader.ReadStartElement(name, String.Empty); 1565 reader.ReadStartElement(name, String.Empty);
1459 1566
1460 while (reader.Name == "TaskInventoryItem") 1567 while (reader.Name == "TaskInventoryItem")
diff --git a/OpenSim/Region/Framework/Scenes/SimStatsReporter.cs b/OpenSim/Region/Framework/Scenes/SimStatsReporter.cs
index 742d42a..18e6ece 100644
--- a/OpenSim/Region/Framework/Scenes/SimStatsReporter.cs
+++ b/OpenSim/Region/Framework/Scenes/SimStatsReporter.cs
@@ -298,6 +298,20 @@ namespace OpenSim.Region.Framework.Scenes
298 physfps = 0; 298 physfps = 0;
299 299
300#endregion 300#endregion
301 if (reportedFPS <= 0)
302 reportedFPS = 1;
303
304 float perframe = 1.0f / (float)reportedFPS;
305
306 float TotalFrameTime = m_frameMS * perframe;
307
308 float targetframetime = 1100.0f / (float)m_nominalReportedFps;
309
310 float sparetime;
311 if (TotalFrameTime > targetframetime)
312 {
313 sparetime = 0;
314 }
301 315
302 m_rootAgents = m_scene.SceneGraph.GetRootAgentCount(); 316 m_rootAgents = m_scene.SceneGraph.GetRootAgentCount();
303 m_childAgents = m_scene.SceneGraph.GetChildAgentCount(); 317 m_childAgents = m_scene.SceneGraph.GetChildAgentCount();
@@ -309,15 +323,13 @@ namespace OpenSim.Region.Framework.Scenes
309 // so that stat numbers are always consistent. 323 // so that stat numbers are always consistent.
310 CheckStatSanity(); 324 CheckStatSanity();
311 325
312 //Our time dilation is 0.91 when we're running a full speed, 326 // other MS is actually simulation time
313 // therefore to make sure we get an appropriate range, 327 // m_otherMS = m_frameMS - m_physicsMS - m_imageMS - m_netMS - m_agentMS;
314 // we have to factor in our error. (0.10f * statsUpdateFactor) 328 // 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 329
316 // / 10 divides the value by the number of times the sim heartbeat runs (10fps) 330 m_otherMS = m_frameMS - m_physicsMS - m_agentMS;
317 // Then we divide the whole amount by the amount of seconds pass in between stats updates. 331 if (m_otherMS < 0)
318 332 m_otherMS = 0;
319 // 'statsUpdateFactor' is how often stats packets are sent in seconds. Used below to change
320 // values to X-per-second values.
321 333
322 uint thisFrame = m_scene.Frame; 334 uint thisFrame = m_scene.Frame;
323 float framesUpdated = (float)(thisFrame - m_lastUpdateFrame) * m_reportedFpsCorrectionFactor; 335 float framesUpdated = (float)(thisFrame - m_lastUpdateFrame) * m_reportedFpsCorrectionFactor;
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;