clockwerk-opensim-stable – Blame information for rev 1

Subversion Repositories:
Rev:
Rev Author Line No. Line
1 vero 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  
28 using System;
29 using System.Collections.Generic;
30 using System.Net;
31 using System.Reflection;
32 using System.Threading;
33 using OpenSim.Framework;
34 using OpenSim.Framework.Capabilities;
35 using OpenSim.Framework.Client;
36 using OpenSim.Framework.Monitoring;
37 using OpenSim.Region.Framework.Interfaces;
38 using OpenSim.Region.Framework.Scenes;
39 using OpenSim.Region.Physics.Manager;
40 using OpenSim.Services.Interfaces;
41  
42 using GridRegion = OpenSim.Services.Interfaces.GridRegion;
43  
44 using OpenMetaverse;
45 using log4net;
46 using Nini.Config;
47 using Mono.Addins;
48  
49 namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
50 {
51 [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "EntityTransferModule")]
52 public class EntityTransferModule : INonSharedRegionModule, IEntityTransferModule
53 {
54 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
55  
56 public const int DefaultMaxTransferDistance = 4095;
57 public const bool WaitForAgentArrivedAtDestinationDefault = true;
58  
59 public string OutgoingTransferVersionName { get; set; }
60  
61 /// <summary>
62 /// Determine the maximum entity transfer version we will use for teleports.
63 /// </summary>
64 public float MaxOutgoingTransferVersion { get; set; }
65  
66 /// <summary>
67 /// The maximum distance, in standard region units (256m) that an agent is allowed to transfer.
68 /// </summary>
69 public int MaxTransferDistance { get; set; }
70  
71 /// <summary>
72 /// If true then on a teleport, the source region waits for a callback from the destination region. If
73 /// a callback fails to arrive within a set time then the user is pulled back into the source region.
74 /// </summary>
75 public bool WaitForAgentArrivedAtDestination { get; set; }
76  
77 /// <summary>
78 /// If true then we ask the viewer to disable teleport cancellation and ignore teleport requests.
79 /// </summary>
80 /// <remarks>
81 /// This is useful in situations where teleport is very likely to always succeed and we want to avoid a
82 /// situation where avatars can be come 'stuck' due to a failed teleport cancellation. Unfortunately, the
83 /// nature of the teleport protocol makes it extremely difficult (maybe impossible) to make teleport
84 /// cancellation consistently suceed.
85 /// </remarks>
86 public bool DisableInterRegionTeleportCancellation { get; set; }
87  
88 /// <summary>
89 /// Number of times inter-region teleport was attempted.
90 /// </summary>
91 private Stat m_interRegionTeleportAttempts;
92  
93 /// <summary>
94 /// Number of times inter-region teleport was aborted (due to simultaneous client logout).
95 /// </summary>
96 private Stat m_interRegionTeleportAborts;
97  
98 /// <summary>
99 /// Number of times inter-region teleport was successfully cancelled by the client.
100 /// </summary>
101 private Stat m_interRegionTeleportCancels;
102  
103 /// <summary>
104 /// Number of times inter-region teleport failed due to server/client/network problems (e.g. viewer failed to
105 /// connect with destination region).
106 /// </summary>
107 /// <remarks>
108 /// This is not necessarily a problem for this simulator - in open-grid/hg conditions, viewer connectivity to
109 /// destination simulator is unknown.
110 /// </remarks>
111 private Stat m_interRegionTeleportFailures;
112  
113 protected bool m_Enabled = false;
114  
115 public Scene Scene { get; private set; }
116  
117 /// <summary>
118 /// Handles recording and manipulation of state for entities that are in transfer within or between regions
119 /// (cross or teleport).
120 /// </summary>
121 private EntityTransferStateMachine m_entityTransferStateMachine;
122  
123 private ExpiringCache<UUID, ExpiringCache<ulong, DateTime>> m_bannedRegions =
124 new ExpiringCache<UUID, ExpiringCache<ulong, DateTime>>();
125  
126 private IEventQueue m_eqModule;
127 private IRegionCombinerModule m_regionCombinerModule;
128  
129 #region ISharedRegionModule
130  
131 public Type ReplaceableInterface
132 {
133 get { return null; }
134 }
135  
136 public virtual string Name
137 {
138 get { return "BasicEntityTransferModule"; }
139 }
140  
141 public virtual void Initialise(IConfigSource source)
142 {
143 IConfig moduleConfig = source.Configs["Modules"];
144 if (moduleConfig != null)
145 {
146 string name = moduleConfig.GetString("EntityTransferModule", "");
147 if (name == Name)
148 {
149 InitialiseCommon(source);
150 m_log.DebugFormat("[ENTITY TRANSFER MODULE]: {0} enabled.", Name);
151 }
152 }
153 }
154  
155 /// <summary>
156 /// Initialize config common for this module and any descendents.
157 /// </summary>
158 /// <param name="source"></param>
159 protected virtual void InitialiseCommon(IConfigSource source)
160 {
161 string transferVersionName = "SIMULATION";
162 float maxTransferVersion = 0.2f;
163  
164 IConfig transferConfig = source.Configs["EntityTransfer"];
165 if (transferConfig != null)
166 {
167 string rawVersion
168 = transferConfig.GetString(
169 "MaxOutgoingTransferVersion",
170 string.Format("{0}/{1}", transferVersionName, maxTransferVersion));
171  
172 string[] rawVersionComponents = rawVersion.Split(new char[] { '/' });
173  
174 bool versionValid = false;
175  
176 if (rawVersionComponents.Length >= 2)
177 versionValid = float.TryParse(rawVersionComponents[1], out maxTransferVersion);
178  
179 if (!versionValid)
180 {
181 m_log.ErrorFormat(
182 "[ENTITY TRANSFER MODULE]: MaxOutgoingTransferVersion {0} is invalid, using {1}",
183 rawVersion, string.Format("{0}/{1}", transferVersionName, maxTransferVersion));
184 }
185 else
186 {
187 transferVersionName = rawVersionComponents[0];
188  
189 m_log.InfoFormat(
190 "[ENTITY TRANSFER MODULE]: MaxOutgoingTransferVersion set to {0}",
191 string.Format("{0}/{1}", transferVersionName, maxTransferVersion));
192 }
193  
194 DisableInterRegionTeleportCancellation
195 = transferConfig.GetBoolean("DisableInterRegionTeleportCancellation", false);
196  
197 WaitForAgentArrivedAtDestination
198 = transferConfig.GetBoolean("wait_for_callback", WaitForAgentArrivedAtDestinationDefault);
199  
200 MaxTransferDistance = transferConfig.GetInt("max_distance", DefaultMaxTransferDistance);
201 }
202 else
203 {
204 MaxTransferDistance = DefaultMaxTransferDistance;
205 }
206  
207 OutgoingTransferVersionName = transferVersionName;
208 MaxOutgoingTransferVersion = maxTransferVersion;
209  
210 m_entityTransferStateMachine = new EntityTransferStateMachine(this);
211  
212 m_Enabled = true;
213 }
214  
215 public virtual void PostInitialise()
216 {
217 }
218  
219 public virtual void AddRegion(Scene scene)
220 {
221 if (!m_Enabled)
222 return;
223  
224 Scene = scene;
225  
226 m_interRegionTeleportAttempts =
227 new Stat(
228 "InterRegionTeleportAttempts",
229 "Number of inter-region teleports attempted.",
230 "This does not count attempts which failed due to pre-conditions (e.g. target simulator refused access).\n"
231 + "You can get successfully teleports by subtracting aborts, cancels and teleport failures from this figure.",
232 "",
233 "entitytransfer",
234 Scene.Name,
235 StatType.Push,
236 null,
237 StatVerbosity.Debug);
238  
239 m_interRegionTeleportAborts =
240 new Stat(
241 "InterRegionTeleportAborts",
242 "Number of inter-region teleports aborted due to client actions.",
243 "The chief action is simultaneous logout whilst teleporting.",
244 "",
245 "entitytransfer",
246 Scene.Name,
247 StatType.Push,
248 null,
249 StatVerbosity.Debug);
250  
251 m_interRegionTeleportCancels =
252 new Stat(
253 "InterRegionTeleportCancels",
254 "Number of inter-region teleports cancelled by the client.",
255 null,
256 "",
257 "entitytransfer",
258 Scene.Name,
259 StatType.Push,
260 null,
261 StatVerbosity.Debug);
262  
263 m_interRegionTeleportFailures =
264 new Stat(
265 "InterRegionTeleportFailures",
266 "Number of inter-region teleports that failed due to server/client/network issues.",
267 "This number may not be very helpful in open-grid/hg situations as the network connectivity/quality of destinations is uncontrollable.",
268 "",
269 "entitytransfer",
270 Scene.Name,
271 StatType.Push,
272 null,
273 StatVerbosity.Debug);
274  
275 StatsManager.RegisterStat(m_interRegionTeleportAttempts);
276 StatsManager.RegisterStat(m_interRegionTeleportAborts);
277 StatsManager.RegisterStat(m_interRegionTeleportCancels);
278 StatsManager.RegisterStat(m_interRegionTeleportFailures);
279  
280 scene.RegisterModuleInterface<IEntityTransferModule>(this);
281 scene.EventManager.OnNewClient += OnNewClient;
282 }
283  
284 protected virtual void OnNewClient(IClientAPI client)
285 {
286 client.OnTeleportHomeRequest += TriggerTeleportHome;
287 client.OnTeleportLandmarkRequest += RequestTeleportLandmark;
288  
289 if (!DisableInterRegionTeleportCancellation)
290 client.OnTeleportCancel += OnClientCancelTeleport;
291  
292 client.OnConnectionClosed += OnConnectionClosed;
293 }
294  
295 public virtual void Close() {}
296  
297 public virtual void RemoveRegion(Scene scene)
298 {
299 if (m_Enabled)
300 {
301 StatsManager.DeregisterStat(m_interRegionTeleportAttempts);
302 StatsManager.DeregisterStat(m_interRegionTeleportAborts);
303 StatsManager.DeregisterStat(m_interRegionTeleportCancels);
304 StatsManager.DeregisterStat(m_interRegionTeleportFailures);
305 }
306 }
307  
308 public virtual void RegionLoaded(Scene scene)
309 {
310 if (!m_Enabled)
311 return;
312  
313 m_eqModule = Scene.RequestModuleInterface<IEventQueue>();
314 m_regionCombinerModule = Scene.RequestModuleInterface<IRegionCombinerModule>();
315 }
316  
317 #endregion
318  
319 #region Agent Teleports
320  
321 private void OnConnectionClosed(IClientAPI client)
322 {
323 if (client.IsLoggingOut && m_entityTransferStateMachine.UpdateInTransit(client.AgentId, AgentTransferState.Aborting))
324 {
325 m_log.DebugFormat(
326 "[ENTITY TRANSFER MODULE]: Aborted teleport request from {0} in {1} due to simultaneous logout",
327 client.Name, Scene.Name);
328 }
329 }
330  
331 private void OnClientCancelTeleport(IClientAPI client)
332 {
333 m_entityTransferStateMachine.UpdateInTransit(client.AgentId, AgentTransferState.Cancelling);
334  
335 m_log.DebugFormat(
336 "[ENTITY TRANSFER MODULE]: Received teleport cancel request from {0} in {1}", client.Name, Scene.Name);
337 }
338  
339 public void Teleport(ScenePresence sp, ulong regionHandle, Vector3 position, Vector3 lookAt, uint teleportFlags)
340 {
341 if (sp.Scene.Permissions.IsGridGod(sp.UUID))
342 {
343 // This user will be a God in the destination scene, too
344 teleportFlags |= (uint)TeleportFlags.Godlike;
345 }
346  
347 if (!sp.Scene.Permissions.CanTeleport(sp.UUID))
348 return;
349  
350 string destinationRegionName = "(not found)";
351  
352 // Record that this agent is in transit so that we can prevent simultaneous requests and do later detection
353 // of whether the destination region completes the teleport.
354 if (!m_entityTransferStateMachine.SetInTransit(sp.UUID))
355 {
356 m_log.DebugFormat(
357 "[ENTITY TRANSFER MODULE]: Ignoring teleport request of {0} {1} to {2}@{3} - agent is already in transit.",
358 sp.Name, sp.UUID, position, regionHandle);
359  
360 sp.ControllingClient.SendTeleportFailed("Previous teleport process incomplete. Please retry shortly.");
361  
362 return;
363 }
364  
365 try
366 {
367 // Reset animations; the viewer does that in teleports.
368 sp.Animator.ResetAnimations();
369  
370 if (regionHandle == sp.Scene.RegionInfo.RegionHandle)
371 {
372 destinationRegionName = sp.Scene.RegionInfo.RegionName;
373  
374 TeleportAgentWithinRegion(sp, position, lookAt, teleportFlags);
375 }
376 else // Another region possibly in another simulator
377 {
378 GridRegion finalDestination = null;
379 try
380 {
381 TeleportAgentToDifferentRegion(
382 sp, regionHandle, position, lookAt, teleportFlags, out finalDestination);
383 }
384 finally
385 {
386 if (finalDestination != null)
387 destinationRegionName = finalDestination.RegionName;
388 }
389 }
390 }
391 catch (Exception e)
392 {
393 m_log.ErrorFormat(
394 "[ENTITY TRANSFER MODULE]: Exception on teleport of {0} from {1}@{2} to {3}@{4}: {5}{6}",
395 sp.Name, sp.AbsolutePosition, sp.Scene.RegionInfo.RegionName, position, destinationRegionName,
396 e.Message, e.StackTrace);
397  
398 sp.ControllingClient.SendTeleportFailed("Internal error");
399 }
400 finally
401 {
402 m_entityTransferStateMachine.ResetFromTransit(sp.UUID);
403 }
404 }
405  
406 /// <summary>
407 /// Teleports the agent within its current region.
408 /// </summary>
409 /// <param name="sp"></param>
410 /// <param name="position"></param>
411 /// <param name="lookAt"></param>
412 /// <param name="teleportFlags"></param
413 private void TeleportAgentWithinRegion(ScenePresence sp, Vector3 position, Vector3 lookAt, uint teleportFlags)
414 {
415 m_log.DebugFormat(
416 "[ENTITY TRANSFER MODULE]: Teleport for {0} to {1} within {2}",
417 sp.Name, position, sp.Scene.RegionInfo.RegionName);
418  
419 // Teleport within the same region
420 if (IsOutsideRegion(sp.Scene, position) || position.Z < 0)
421 {
422 Vector3 emergencyPos = new Vector3(128, 128, 128);
423  
424 m_log.WarnFormat(
425 "[ENTITY TRANSFER MODULE]: RequestTeleportToLocation() was given an illegal position of {0} for avatar {1}, {2} in {3}. Substituting {4}",
426 position, sp.Name, sp.UUID, Scene.Name, emergencyPos);
427  
428 position = emergencyPos;
429 }
430  
431 // TODO: Get proper AVG Height
432 float localAVHeight = 1.56f;
433 float posZLimit = 22;
434  
435 // TODO: Check other Scene HeightField
436 if (position.X > 0 && position.X <= (int)Constants.RegionSize && position.Y > 0 && position.Y <= (int)Constants.RegionSize)
437 {
438 posZLimit = (float)sp.Scene.Heightmap[(int)position.X, (int)position.Y];
439 }
440  
441 float newPosZ = posZLimit + localAVHeight;
442 if (posZLimit >= (position.Z - (localAVHeight / 2)) && !(Single.IsInfinity(newPosZ) || Single.IsNaN(newPosZ)))
443 {
444 position.Z = newPosZ;
445 }
446  
447 m_entityTransferStateMachine.UpdateInTransit(sp.UUID, AgentTransferState.Transferring);
448  
449 sp.ControllingClient.SendTeleportStart(teleportFlags);
450  
451 sp.ControllingClient.SendLocalTeleport(position, lookAt, teleportFlags);
452 sp.Velocity = Vector3.Zero;
453 sp.Teleport(position);
454  
455 m_entityTransferStateMachine.UpdateInTransit(sp.UUID, AgentTransferState.ReceivedAtDestination);
456  
457 foreach (SceneObjectGroup grp in sp.GetAttachments())
458 {
459 sp.Scene.EventManager.TriggerOnScriptChangedEvent(grp.LocalId, (uint)Changed.TELEPORT);
460 }
461  
462 m_entityTransferStateMachine.UpdateInTransit(sp.UUID, AgentTransferState.CleaningUp);
463 }
464  
465 /// <summary>
466 /// Teleports the agent to a different region.
467 /// </summary>
468 /// <param name='sp'></param>
469 /// <param name='regionHandle'>/param>
470 /// <param name='position'></param>
471 /// <param name='lookAt'></param>
472 /// <param name='teleportFlags'></param>
473 /// <param name='finalDestination'></param>
474 private void TeleportAgentToDifferentRegion(
475 ScenePresence sp, ulong regionHandle, Vector3 position,
476 Vector3 lookAt, uint teleportFlags, out GridRegion finalDestination)
477 {
478 uint x = 0, y = 0;
479 Utils.LongToUInts(regionHandle, out x, out y);
480 GridRegion reg = Scene.GridService.GetRegionByPosition(sp.Scene.RegionInfo.ScopeID, (int)x, (int)y);
481  
482 if (reg != null)
483 {
484 finalDestination = GetFinalDestination(reg);
485  
486 if (finalDestination == null)
487 {
488 m_log.WarnFormat(
489 "[ENTITY TRANSFER MODULE]: Final destination is having problems. Unable to teleport {0} {1}",
490 sp.Name, sp.UUID);
491  
492 sp.ControllingClient.SendTeleportFailed("Problem at destination");
493 return;
494 }
495  
496 // Check that these are not the same coordinates
497 if (finalDestination.RegionLocX == sp.Scene.RegionInfo.RegionLocX &&
498 finalDestination.RegionLocY == sp.Scene.RegionInfo.RegionLocY)
499 {
500 // Can't do. Viewer crashes
501 sp.ControllingClient.SendTeleportFailed("Space warp! You would crash. Move to a different region and try again.");
502 return;
503 }
504  
505 // Validate assorted conditions
506 string reason = string.Empty;
507 if (!ValidateGenericConditions(sp, reg, finalDestination, teleportFlags, out reason))
508 {
509 sp.ControllingClient.SendTeleportFailed(reason);
510 return;
511 }
512  
513 //
514 // This is it
515 //
516 DoTeleportInternal(sp, reg, finalDestination, position, lookAt, teleportFlags);
517 //
518 //
519 //
520 }
521 else
522 {
523 finalDestination = null;
524  
525 // TP to a place that doesn't exist (anymore)
526 // Inform the viewer about that
527 sp.ControllingClient.SendTeleportFailed("The region you tried to teleport to doesn't exist anymore");
528  
529 // and set the map-tile to '(Offline)'
530 uint regX, regY;
531 Utils.LongToUInts(regionHandle, out regX, out regY);
532  
533 MapBlockData block = new MapBlockData();
534 block.X = (ushort)(regX / Constants.RegionSize);
535 block.Y = (ushort)(regY / Constants.RegionSize);
536 block.Access = 254; // == not there
537  
538 List<MapBlockData> blocks = new List<MapBlockData>();
539 blocks.Add(block);
540 sp.ControllingClient.SendMapBlock(blocks, 0);
541 }
542 }
543  
544 // Nothing to validate here
545 protected virtual bool ValidateGenericConditions(ScenePresence sp, GridRegion reg, GridRegion finalDestination, uint teleportFlags, out string reason)
546 {
547 reason = String.Empty;
548 return true;
549 }
550  
551 /// <summary>
552 /// Determines whether this instance is within the max transfer distance.
553 /// </summary>
554 /// <param name="sourceRegion"></param>
555 /// <param name="destRegion"></param>
556 /// <returns>
557 /// <c>true</c> if this instance is within max transfer distance; otherwise, <c>false</c>.
558 /// </returns>
559 private bool IsWithinMaxTeleportDistance(RegionInfo sourceRegion, GridRegion destRegion)
560 {
561 if(MaxTransferDistance == 0)
562 return true;
563  
564 // m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Source co-ords are x={0} y={1}", curRegionX, curRegionY);
565 //
566 // m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Final dest is x={0} y={1} {2}@{3}",
567 // destRegionX, destRegionY, finalDestination.RegionID, finalDestination.ServerURI);
568  
569 // Insanely, RegionLoc on RegionInfo is the 256m map co-ord whilst GridRegion.RegionLoc is the raw meters position.
570 return Math.Abs(sourceRegion.RegionLocX - destRegion.RegionCoordX) <= MaxTransferDistance
571 && Math.Abs(sourceRegion.RegionLocY - destRegion.RegionCoordY) <= MaxTransferDistance;
572 }
573  
574 /// <summary>
575 /// Wraps DoTeleportInternal() and manages the transfer state.
576 /// </summary>
577 public void DoTeleport(
578 ScenePresence sp, GridRegion reg, GridRegion finalDestination,
579 Vector3 position, Vector3 lookAt, uint teleportFlags)
580 {
581 // Record that this agent is in transit so that we can prevent simultaneous requests and do later detection
582 // of whether the destination region completes the teleport.
583 if (!m_entityTransferStateMachine.SetInTransit(sp.UUID))
584 {
585 m_log.DebugFormat(
586 "[ENTITY TRANSFER MODULE]: Ignoring teleport request of {0} {1} to {2} ({3}) {4}/{5} - agent is already in transit.",
587 sp.Name, sp.UUID, reg.ServerURI, finalDestination.ServerURI, finalDestination.RegionName, position);
588  
589 return;
590 }
591  
592 try
593 {
594 DoTeleportInternal(sp, reg, finalDestination, position, lookAt, teleportFlags);
595 }
596 catch (Exception e)
597 {
598 m_log.ErrorFormat(
599 "[ENTITY TRANSFER MODULE]: Exception on teleport of {0} from {1}@{2} to {3}@{4}: {5}{6}",
600 sp.Name, sp.AbsolutePosition, sp.Scene.RegionInfo.RegionName, position, finalDestination.RegionName,
601 e.Message, e.StackTrace);
602  
603 sp.ControllingClient.SendTeleportFailed("Internal error");
604 }
605 finally
606 {
607 m_entityTransferStateMachine.ResetFromTransit(sp.UUID);
608 }
609 }
610  
611 /// <summary>
612 /// Teleports the agent to another region.
613 /// This method doesn't manage the transfer state; the caller must do that.
614 /// </summary>
615 private void DoTeleportInternal(
616 ScenePresence sp, GridRegion reg, GridRegion finalDestination,
617 Vector3 position, Vector3 lookAt, uint teleportFlags)
618 {
619 if (reg == null || finalDestination == null)
620 {
621 sp.ControllingClient.SendTeleportFailed("Unable to locate destination");
622 return;
623 }
624  
625 m_log.DebugFormat(
626 "[ENTITY TRANSFER MODULE]: Teleporting {0} {1} from {2} to {3} ({4}) {5}/{6}",
627 sp.Name, sp.UUID, sp.Scene.RegionInfo.RegionName,
628 reg.ServerURI, finalDestination.ServerURI, finalDestination.RegionName, position);
629  
630 RegionInfo sourceRegion = sp.Scene.RegionInfo;
631  
632 if (!IsWithinMaxTeleportDistance(sourceRegion, finalDestination))
633 {
634 sp.ControllingClient.SendTeleportFailed(
635 string.Format(
636 "Can't teleport to {0} ({1},{2}) from {3} ({4},{5}), destination is more than {6} regions way",
637 finalDestination.RegionName, finalDestination.RegionCoordX, finalDestination.RegionCoordY,
638 sourceRegion.RegionName, sourceRegion.RegionLocX, sourceRegion.RegionLocY,
639 MaxTransferDistance));
640  
641 return;
642 }
643  
644 uint newRegionX = (uint)(reg.RegionHandle >> 40);
645 uint newRegionY = (((uint)(reg.RegionHandle)) >> 8);
646 uint oldRegionX = (uint)(sp.Scene.RegionInfo.RegionHandle >> 40);
647 uint oldRegionY = (((uint)(sp.Scene.RegionInfo.RegionHandle)) >> 8);
648  
649 ulong destinationHandle = finalDestination.RegionHandle;
650  
651 // Let's do DNS resolution only once in this process, please!
652 // This may be a costly operation. The reg.ExternalEndPoint field is not a passive field,
653 // it's actually doing a lot of work.
654 IPEndPoint endPoint = finalDestination.ExternalEndPoint;
655  
656 if (endPoint.Address == null)
657 {
658 sp.ControllingClient.SendTeleportFailed("Remote Region appears to be down");
659  
660 return;
661 }
662  
663 if (!sp.ValidateAttachments())
664 m_log.DebugFormat(
665 "[ENTITY TRANSFER MODULE]: Failed validation of all attachments for teleport of {0} from {1} to {2}. Continuing.",
666 sp.Name, sp.Scene.Name, finalDestination.RegionName);
667  
668 string reason;
669 string version;
670 if (!Scene.SimulationService.QueryAccess(
671 finalDestination, sp.ControllingClient.AgentId, Vector3.Zero, out version, out reason))
672 {
673 sp.ControllingClient.SendTeleportFailed(reason);
674  
675 m_log.DebugFormat(
676 "[ENTITY TRANSFER MODULE]: {0} was stopped from teleporting from {1} to {2} because {3}",
677 sp.Name, sp.Scene.Name, finalDestination.RegionName, reason);
678  
679 return;
680 }
681  
682 // Before this point, teleport 'failure' is due to checkable pre-conditions such as whether the target
683 // simulator can be found and is explicitly prepared to allow access. Therefore, we will not count these
684 // as server attempts.
685 m_interRegionTeleportAttempts.Value++;
686  
687 m_log.DebugFormat(
688 "[ENTITY TRANSFER MODULE]: {0} max transfer version is {1}/{2}, {3} max version is {4}",
689 sp.Scene.Name, OutgoingTransferVersionName, MaxOutgoingTransferVersion, finalDestination.RegionName, version);
690  
691 // Fixing a bug where teleporting while sitting results in the avatar ending up removed from
692 // both regions
693 if (sp.ParentID != (uint)0)
694 sp.StandUp();
695  
696 if (DisableInterRegionTeleportCancellation)
697 teleportFlags |= (uint)TeleportFlags.DisableCancel;
698  
699 // At least on LL 3.3.4, this is not strictly necessary - a teleport will succeed without sending this to
700 // the viewer. However, it might mean that the viewer does not see the black teleport screen (untested).
701 sp.ControllingClient.SendTeleportStart(teleportFlags);
702  
703 // the avatar.Close below will clear the child region list. We need this below for (possibly)
704 // closing the child agents, so save it here (we need a copy as it is Clear()-ed).
705 //List<ulong> childRegions = avatar.KnownRegionHandles;
706 // Compared to ScenePresence.CrossToNewRegion(), there's no obvious code to handle a teleport
707 // failure at this point (unlike a border crossing failure). So perhaps this can never fail
708 // once we reach here...
709 //avatar.Scene.RemoveCapsHandler(avatar.UUID);
710  
711 string capsPath = String.Empty;
712  
713 AgentCircuitData currentAgentCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
714 AgentCircuitData agentCircuit = sp.ControllingClient.RequestClientInfo();
715 agentCircuit.startpos = position;
716 agentCircuit.child = true;
717 agentCircuit.Appearance = sp.Appearance;
718 if (currentAgentCircuit != null)
719 {
720 agentCircuit.ServiceURLs = currentAgentCircuit.ServiceURLs;
721 agentCircuit.IPAddress = currentAgentCircuit.IPAddress;
722 agentCircuit.Viewer = currentAgentCircuit.Viewer;
723 agentCircuit.Channel = currentAgentCircuit.Channel;
724 agentCircuit.Mac = currentAgentCircuit.Mac;
725 agentCircuit.Id0 = currentAgentCircuit.Id0;
726 }
727  
728 if (NeedsNewAgent(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY))
729 {
730 // brand new agent, let's create a new caps seed
731 agentCircuit.CapsPath = CapsUtil.GetRandomCapsObjectPath();
732 }
733  
734 // We're going to fallback to V1 if the destination gives us anything smaller than 0.2 or we're forcing
735 // use of the earlier protocol
736 float versionNumber = 0.1f;
737 string[] versionComponents = version.Split(new char[] { '/' });
738 if (versionComponents.Length >= 2)
739 float.TryParse(versionComponents[1], out versionNumber);
740  
741 if (versionNumber == 0.2f && MaxOutgoingTransferVersion >= versionNumber)
742 TransferAgent_V2(sp, agentCircuit, reg, finalDestination, endPoint, teleportFlags, oldRegionX, newRegionX, oldRegionY, newRegionY, version, out reason);
743 else
744 TransferAgent_V1(sp, agentCircuit, reg, finalDestination, endPoint, teleportFlags, oldRegionX, newRegionX, oldRegionY, newRegionY, version, out reason);
745 }
746  
747 private void TransferAgent_V1(ScenePresence sp, AgentCircuitData agentCircuit, GridRegion reg, GridRegion finalDestination,
748 IPEndPoint endPoint, uint teleportFlags, uint oldRegionX, uint newRegionX, uint oldRegionY, uint newRegionY, string version, out string reason)
749 {
750 ulong destinationHandle = finalDestination.RegionHandle;
751 AgentCircuitData currentAgentCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
752  
753 m_log.DebugFormat(
754 "[ENTITY TRANSFER MODULE]: Using TP V1 for {0} going from {1} to {2}",
755 sp.Name, Scene.Name, finalDestination.RegionName);
756  
757 // Let's create an agent there if one doesn't exist yet.
758 // NOTE: logout will always be false for a non-HG teleport.
759 bool logout = false;
760 if (!CreateAgent(sp, reg, finalDestination, agentCircuit, teleportFlags, out reason, out logout))
761 {
762 m_interRegionTeleportFailures.Value++;
763  
764 sp.ControllingClient.SendTeleportFailed(String.Format("Teleport refused: {0}", reason));
765  
766 m_log.DebugFormat(
767 "[ENTITY TRANSFER MODULE]: Teleport of {0} from {1} to {2} was refused because {3}",
768 sp.Name, sp.Scene.RegionInfo.RegionName, finalDestination.RegionName, reason);
769  
770 return;
771 }
772  
773 if (m_entityTransferStateMachine.GetAgentTransferState(sp.UUID) == AgentTransferState.Cancelling)
774 {
775 m_interRegionTeleportCancels.Value++;
776  
777 m_log.DebugFormat(
778 "[ENTITY TRANSFER MODULE]: Cancelled teleport of {0} to {1} from {2} after CreateAgent on client request",
779 sp.Name, finalDestination.RegionName, sp.Scene.Name);
780  
781 return;
782 }
783 else if (m_entityTransferStateMachine.GetAgentTransferState(sp.UUID) == AgentTransferState.Aborting)
784 {
785 m_interRegionTeleportAborts.Value++;
786  
787 m_log.DebugFormat(
788 "[ENTITY TRANSFER MODULE]: Aborted teleport of {0} to {1} from {2} after CreateAgent due to previous client close.",
789 sp.Name, finalDestination.RegionName, sp.Scene.Name);
790  
791 return;
792 }
793  
794 // Past this point we have to attempt clean up if the teleport fails, so update transfer state.
795 m_entityTransferStateMachine.UpdateInTransit(sp.UUID, AgentTransferState.Transferring);
796  
797 // OK, it got this agent. Let's close some child agents
798 sp.CloseChildAgents(newRegionX, newRegionY);
799  
800 IClientIPEndpoint ipepClient;
801 string capsPath = String.Empty;
802 if (NeedsNewAgent(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY))
803 {
804 m_log.DebugFormat(
805 "[ENTITY TRANSFER MODULE]: Determined that region {0} at {1},{2} needs new child agent for incoming agent {3} from {4}",
806 finalDestination.RegionName, newRegionX, newRegionY, sp.Name, Scene.Name);
807  
808 //sp.ControllingClient.SendTeleportProgress(teleportFlags, "Creating agent...");
809 #region IP Translation for NAT
810 // Uses ipepClient above
811 if (sp.ClientView.TryGet(out ipepClient))
812 {
813 endPoint.Address = NetworkUtil.GetIPFor(ipepClient.EndPoint, endPoint.Address);
814 }
815 #endregion
816 capsPath = finalDestination.ServerURI + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
817  
818 if (m_eqModule != null)
819 {
820 // The EnableSimulator message makes the client establish a connection with the destination
821 // simulator by sending the initial UseCircuitCode UDP packet to the destination containing the
822 // correct circuit code.
823 m_eqModule.EnableSimulator(destinationHandle, endPoint, sp.UUID);
824  
825 // XXX: Is this wait necessary? We will always end up waiting on UpdateAgent for the destination
826 // simulator to confirm that it has established communication with the viewer.
827 Thread.Sleep(200);
828  
829 // At least on LL 3.3.4 for teleports between different regions on the same simulator this appears
830 // unnecessary - teleport will succeed and SEED caps will be requested without it (though possibly
831 // only on TeleportFinish). This is untested for region teleport between different simulators
832 // though this probably also works.
833 m_eqModule.EstablishAgentCommunication(sp.UUID, endPoint, capsPath);
834 }
835 else
836 {
837 // XXX: This is a little misleading since we're information the client of its avatar destination,
838 // which may or may not be a neighbour region of the source region. This path is probably little
839 // used anyway (with EQ being the one used). But it is currently being used for test code.
840 sp.ControllingClient.InformClientOfNeighbour(destinationHandle, endPoint);
841 }
842 }
843 else
844 {
845 agentCircuit.CapsPath = sp.Scene.CapsModule.GetChildSeed(sp.UUID, reg.RegionHandle);
846 capsPath = finalDestination.ServerURI + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
847 }
848  
849 // Let's send a full update of the agent. This is a synchronous call.
850 AgentData agent = new AgentData();
851 sp.CopyTo(agent);
852 agent.Position = agentCircuit.startpos;
853 SetCallbackURL(agent, sp.Scene.RegionInfo);
854  
855  
856 // We will check for an abort before UpdateAgent since UpdateAgent will require an active viewer to
857 // establish th econnection to the destination which makes it return true.
858 if (m_entityTransferStateMachine.GetAgentTransferState(sp.UUID) == AgentTransferState.Aborting)
859 {
860 m_interRegionTeleportAborts.Value++;
861  
862 m_log.DebugFormat(
863 "[ENTITY TRANSFER MODULE]: Aborted teleport of {0} to {1} from {2} before UpdateAgent",
864 sp.Name, finalDestination.RegionName, sp.Scene.Name);
865  
866 return;
867 }
868  
869 // A common teleport failure occurs when we can send CreateAgent to the
870 // destination region but the viewer cannot establish the connection (e.g. due to network issues between
871 // the viewer and the destination). In this case, UpdateAgent timesout after 10 seconds, although then
872 // there's a further 10 second wait whilst we attempt to tell the destination to delete the agent in Fail().
873 if (!UpdateAgent(reg, finalDestination, agent, sp))
874 {
875 if (m_entityTransferStateMachine.GetAgentTransferState(sp.UUID) == AgentTransferState.Aborting)
876 {
877 m_interRegionTeleportAborts.Value++;
878  
879 m_log.DebugFormat(
880 "[ENTITY TRANSFER MODULE]: Aborted teleport of {0} to {1} from {2} after UpdateAgent due to previous client close.",
881 sp.Name, finalDestination.RegionName, sp.Scene.Name);
882  
883 return;
884 }
885  
886 m_log.WarnFormat(
887 "[ENTITY TRANSFER MODULE]: UpdateAgent failed on teleport of {0} to {1}. Keeping avatar in {2}",
888 sp.Name, finalDestination.RegionName, sp.Scene.Name);
889  
890 Fail(sp, finalDestination, logout, currentAgentCircuit.SessionID.ToString(), "Connection between viewer and destination region could not be established.");
891 return;
892 }
893  
894 if (m_entityTransferStateMachine.GetAgentTransferState(sp.UUID) == AgentTransferState.Cancelling)
895 {
896 m_interRegionTeleportCancels.Value++;
897  
898 m_log.DebugFormat(
899 "[ENTITY TRANSFER MODULE]: Cancelled teleport of {0} to {1} from {2} after UpdateAgent on client request",
900 sp.Name, finalDestination.RegionName, sp.Scene.Name);
901  
902 CleanupFailedInterRegionTeleport(sp, currentAgentCircuit.SessionID.ToString(), finalDestination);
903  
904 return;
905 }
906  
907 m_log.DebugFormat(
908 "[ENTITY TRANSFER MODULE]: Sending new CAPS seed url {0} from {1} to {2}",
909 capsPath, sp.Scene.RegionInfo.RegionName, sp.Name);
910  
911 // We need to set this here to avoid an unlikely race condition when teleporting to a neighbour simulator,
912 // where that neighbour simulator could otherwise request a child agent create on the source which then
913 // closes our existing agent which is still signalled as root.
914 sp.IsChildAgent = true;
915  
916 // OK, send TPFinish to the client, so that it starts the process of contacting the destination region
917 if (m_eqModule != null)
918 {
919 m_eqModule.TeleportFinishEvent(destinationHandle, 13, endPoint, 0, teleportFlags, capsPath, sp.UUID);
920 }
921 else
922 {
923 sp.ControllingClient.SendRegionTeleport(destinationHandle, 13, endPoint, 4,
924 teleportFlags, capsPath);
925 }
926  
927 // TeleportFinish makes the client send CompleteMovementIntoRegion (at the destination), which
928 // trigers a whole shebang of things there, including MakeRoot. So let's wait for confirmation
929 // that the client contacted the destination before we close things here.
930 if (!m_entityTransferStateMachine.WaitForAgentArrivedAtDestination(sp.UUID))
931 {
932 if (m_entityTransferStateMachine.GetAgentTransferState(sp.UUID) == AgentTransferState.Aborting)
933 {
934 m_interRegionTeleportAborts.Value++;
935  
936 m_log.DebugFormat(
937 "[ENTITY TRANSFER MODULE]: Aborted teleport of {0} to {1} from {2} after WaitForAgentArrivedAtDestination due to previous client close.",
938 sp.Name, finalDestination.RegionName, sp.Scene.Name);
939  
940 return;
941 }
942  
943 m_log.WarnFormat(
944 "[ENTITY TRANSFER MODULE]: Teleport of {0} to {1} from {2} failed due to no callback from destination region. Returning avatar to source region.",
945 sp.Name, finalDestination.RegionName, sp.Scene.RegionInfo.RegionName);
946  
947 Fail(sp, finalDestination, logout, currentAgentCircuit.SessionID.ToString(), "Destination region did not signal teleport completion.");
948  
949 return;
950 }
951  
952 m_entityTransferStateMachine.UpdateInTransit(sp.UUID, AgentTransferState.CleaningUp);
953  
954 // For backwards compatibility
955 if (version == "Unknown" || version == string.Empty)
956 {
957 // CrossAttachmentsIntoNewRegion is a synchronous call. We shouldn't need to wait after it
958 m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Old simulator, sending attachments one by one...");
959 CrossAttachmentsIntoNewRegion(finalDestination, sp, true);
960 }
961  
962 // May need to logout or other cleanup
963 AgentHasMovedAway(sp, logout);
964  
965 // Well, this is it. The agent is over there.
966 KillEntity(sp.Scene, sp.LocalId);
967  
968 // Now let's make it officially a child agent
969 sp.MakeChildAgent();
970  
971 // Finally, let's close this previously-known-as-root agent, when the jump is outside the view zone
972  
973 if (NeedsClosing(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY, reg))
974 {
975 if (!sp.Scene.IncomingPreCloseClient(sp))
976 return;
977  
978 // We need to delay here because Imprudence viewers, unlike v1 or v3, have a short (<200ms, <500ms) delay before
979 // they regard the new region as the current region after receiving the AgentMovementComplete
980 // response. If close is sent before then, it will cause the viewer to quit instead.
981 //
982 // This sleep can be increased if necessary. However, whilst it's active,
983 // an agent cannot teleport back to this region if it has teleported away.
984 Thread.Sleep(2000);
985  
986 sp.Scene.CloseAgent(sp.UUID, false);
987 }
988 else
989 {
990 // now we have a child agent in this region.
991 sp.Reset();
992 }
993 }
994  
995 private void TransferAgent_V2(ScenePresence sp, AgentCircuitData agentCircuit, GridRegion reg, GridRegion finalDestination,
996 IPEndPoint endPoint, uint teleportFlags, uint oldRegionX, uint newRegionX, uint oldRegionY, uint newRegionY, string version, out string reason)
997 {
998 ulong destinationHandle = finalDestination.RegionHandle;
999 AgentCircuitData currentAgentCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
1000  
1001 // Let's create an agent there if one doesn't exist yet.
1002 // NOTE: logout will always be false for a non-HG teleport.
1003 bool logout = false;
1004 if (!CreateAgent(sp, reg, finalDestination, agentCircuit, teleportFlags, out reason, out logout))
1005 {
1006 m_interRegionTeleportFailures.Value++;
1007  
1008 sp.ControllingClient.SendTeleportFailed(String.Format("Teleport refused: {0}", reason));
1009  
1010 m_log.DebugFormat(
1011 "[ENTITY TRANSFER MODULE]: Teleport of {0} from {1} to {2} was refused because {3}",
1012 sp.Name, sp.Scene.RegionInfo.RegionName, finalDestination.RegionName, reason);
1013  
1014 return;
1015 }
1016  
1017 if (m_entityTransferStateMachine.GetAgentTransferState(sp.UUID) == AgentTransferState.Cancelling)
1018 {
1019 m_interRegionTeleportCancels.Value++;
1020  
1021 m_log.DebugFormat(
1022 "[ENTITY TRANSFER MODULE]: Cancelled teleport of {0} to {1} from {2} after CreateAgent on client request",
1023 sp.Name, finalDestination.RegionName, sp.Scene.Name);
1024  
1025 return;
1026 }
1027 else if (m_entityTransferStateMachine.GetAgentTransferState(sp.UUID) == AgentTransferState.Aborting)
1028 {
1029 m_interRegionTeleportAborts.Value++;
1030  
1031 m_log.DebugFormat(
1032 "[ENTITY TRANSFER MODULE]: Aborted teleport of {0} to {1} from {2} after CreateAgent due to previous client close.",
1033 sp.Name, finalDestination.RegionName, sp.Scene.Name);
1034  
1035 return;
1036 }
1037  
1038 // Past this point we have to attempt clean up if the teleport fails, so update transfer state.
1039 m_entityTransferStateMachine.UpdateInTransit(sp.UUID, AgentTransferState.Transferring);
1040  
1041 IClientIPEndpoint ipepClient;
1042 string capsPath = String.Empty;
1043 if (NeedsNewAgent(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY))
1044 {
1045 m_log.DebugFormat(
1046 "[ENTITY TRANSFER MODULE]: Determined that region {0} at {1},{2} needs new child agent for agent {3} from {4}",
1047 finalDestination.RegionName, newRegionX, newRegionY, sp.Name, Scene.Name);
1048  
1049 //sp.ControllingClient.SendTeleportProgress(teleportFlags, "Creating agent...");
1050 #region IP Translation for NAT
1051 // Uses ipepClient above
1052 if (sp.ClientView.TryGet(out ipepClient))
1053 {
1054 endPoint.Address = NetworkUtil.GetIPFor(ipepClient.EndPoint, endPoint.Address);
1055 }
1056 #endregion
1057 capsPath = finalDestination.ServerURI + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
1058 }
1059 else
1060 {
1061 agentCircuit.CapsPath = sp.Scene.CapsModule.GetChildSeed(sp.UUID, reg.RegionHandle);
1062 capsPath = finalDestination.ServerURI + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
1063 }
1064  
1065 // We need to set this here to avoid an unlikely race condition when teleporting to a neighbour simulator,
1066 // where that neighbour simulator could otherwise request a child agent create on the source which then
1067 // closes our existing agent which is still signalled as root.
1068 //sp.IsChildAgent = true;
1069  
1070 // New protocol: send TP Finish directly, without prior ES or EAC. That's what happens in the Linden grid
1071 if (m_eqModule != null)
1072 m_eqModule.TeleportFinishEvent(destinationHandle, 13, endPoint, 0, teleportFlags, capsPath, sp.UUID);
1073 else
1074 sp.ControllingClient.SendRegionTeleport(destinationHandle, 13, endPoint, 4,
1075 teleportFlags, capsPath);
1076  
1077 m_log.DebugFormat(
1078 "[ENTITY TRANSFER MODULE]: Sending new CAPS seed url {0} from {1} to {2}",
1079 capsPath, sp.Scene.RegionInfo.RegionName, sp.Name);
1080  
1081 // Let's send a full update of the agent.
1082 AgentData agent = new AgentData();
1083 sp.CopyTo(agent);
1084 agent.Position = agentCircuit.startpos;
1085 agent.SenderWantsToWaitForRoot = true;
1086 //SetCallbackURL(agent, sp.Scene.RegionInfo);
1087  
1088 // Reset the do not close flag. This must be done before the destination opens child connections (here
1089 // triggered by UpdateAgent) to avoid race conditions. However, we also want to reset it as late as possible
1090 // to avoid a situation where an unexpectedly early call to Scene.NewUserConnection() wrongly results
1091 // in no close.
1092 sp.DoNotCloseAfterTeleport = false;
1093  
1094 // Send the Update. If this returns true, we know the client has contacted the destination
1095 // via CompleteMovementIntoRegion, so we can let go.
1096 // If it returns false, something went wrong, and we need to abort.
1097 if (!UpdateAgent(reg, finalDestination, agent, sp))
1098 {
1099 if (m_entityTransferStateMachine.GetAgentTransferState(sp.UUID) == AgentTransferState.Aborting)
1100 {
1101 m_interRegionTeleportAborts.Value++;
1102  
1103 m_log.DebugFormat(
1104 "[ENTITY TRANSFER MODULE]: Aborted teleport of {0} to {1} from {2} after UpdateAgent due to previous client close.",
1105 sp.Name, finalDestination.RegionName, sp.Scene.Name);
1106  
1107 return;
1108 }
1109  
1110 m_log.WarnFormat(
1111 "[ENTITY TRANSFER MODULE]: UpdateAgent failed on teleport of {0} to {1}. Keeping avatar in {2}",
1112 sp.Name, finalDestination.RegionName, sp.Scene.Name);
1113  
1114 Fail(sp, finalDestination, logout, currentAgentCircuit.SessionID.ToString(), "Connection between viewer and destination region could not be established.");
1115 return;
1116 }
1117  
1118 m_entityTransferStateMachine.UpdateInTransit(sp.UUID, AgentTransferState.CleaningUp);
1119  
1120 // Need to signal neighbours whether child agents may need closing irrespective of whether this
1121 // one needed closing. We also need to close child agents as quickly as possible to avoid complicated
1122 // race conditions with rapid agent releporting (e.g. from A1 to a non-neighbour B, back
1123 // to a neighbour A2 then off to a non-neighbour C). Closing child agents any later requires complex
1124 // distributed checks to avoid problems in rapid reteleporting scenarios and where child agents are
1125 // abandoned without proper close by viewer but then re-used by an incoming connection.
1126 sp.CloseChildAgents(newRegionX, newRegionY);
1127  
1128 // May need to logout or other cleanup
1129 AgentHasMovedAway(sp, logout);
1130  
1131 // Well, this is it. The agent is over there.
1132 KillEntity(sp.Scene, sp.LocalId);
1133  
1134 // Now let's make it officially a child agent
1135 sp.MakeChildAgent();
1136  
1137 // Finally, let's close this previously-known-as-root agent, when the jump is outside the view zone
1138 if (NeedsClosing(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY, reg))
1139 {
1140 if (!sp.Scene.IncomingPreCloseClient(sp))
1141 return;
1142  
1143 // RED ALERT!!!!
1144 // PLEASE DO NOT DECREASE THIS WAIT TIME UNDER ANY CIRCUMSTANCES.
1145 // THE VIEWERS SEEM TO NEED SOME TIME AFTER RECEIVING MoveAgentIntoRegion
1146 // BEFORE THEY SETTLE IN THE NEW REGION.
1147 // DECREASING THE WAIT TIME HERE WILL EITHER RESULT IN A VIEWER CRASH OR
1148 // IN THE AVIE BEING PLACED IN INFINITY FOR A COUPLE OF SECONDS.
1149 Thread.Sleep(15000);
1150  
1151 // OK, it got this agent. Let's close everything
1152 // If we shouldn't close the agent due to some other region renewing the connection
1153 // then this will be handled in IncomingCloseAgent under lock conditions
1154 m_log.DebugFormat(
1155 "[ENTITY TRANSFER MODULE]: Closing agent {0} in {1} after teleport", sp.Name, Scene.Name);
1156  
1157 sp.Scene.CloseAgent(sp.UUID, false);
1158 }
1159 else
1160 {
1161 // now we have a child agent in this region.
1162 sp.Reset();
1163 }
1164 }
1165  
1166 /// <summary>
1167 /// Clean up an inter-region teleport that did not complete, either because of simulator failure or cancellation.
1168 /// </summary>
1169 /// <remarks>
1170 /// All operations here must be idempotent so that we can call this method at any point in the teleport process
1171 /// up until we send the TeleportFinish event quene event to the viewer.
1172 /// <remarks>
1173 /// <param name='sp'> </param>
1174 /// <param name='finalDestination'></param>
1175 protected virtual void CleanupFailedInterRegionTeleport(ScenePresence sp, string auth_token, GridRegion finalDestination)
1176 {
1177 m_entityTransferStateMachine.UpdateInTransit(sp.UUID, AgentTransferState.CleaningUp);
1178  
1179 if (sp.IsChildAgent) // We had set it to child before attempted TP (V1)
1180 {
1181 sp.IsChildAgent = false;
1182 ReInstantiateScripts(sp);
1183  
1184 EnableChildAgents(sp);
1185 }
1186 // Finally, kill the agent we just created at the destination.
1187 // XXX: Possibly this should be done asynchronously.
1188 Scene.SimulationService.CloseAgent(finalDestination, sp.UUID, auth_token);
1189 }
1190  
1191 /// <summary>
1192 /// Signal that the inter-region teleport failed and perform cleanup.
1193 /// </summary>
1194 /// <param name='sp'></param>
1195 /// <param name='finalDestination'></param>
1196 /// <param name='logout'></param>
1197 /// <param name='reason'>Human readable reason for teleport failure. Will be sent to client.</param>
1198 protected virtual void Fail(ScenePresence sp, GridRegion finalDestination, bool logout, string auth_code, string reason)
1199 {
1200 CleanupFailedInterRegionTeleport(sp, auth_code, finalDestination);
1201  
1202 m_interRegionTeleportFailures.Value++;
1203  
1204 sp.ControllingClient.SendTeleportFailed(
1205 string.Format(
1206 "Problems connecting to destination {0}, reason: {1}", finalDestination.RegionName, reason));
1207  
1208 sp.Scene.EventManager.TriggerTeleportFail(sp.ControllingClient, logout);
1209 }
1210  
1211 protected virtual bool CreateAgent(ScenePresence sp, GridRegion reg, GridRegion finalDestination, AgentCircuitData agentCircuit, uint teleportFlags, out string reason, out bool logout)
1212 {
1213 logout = false;
1214 bool success = Scene.SimulationService.CreateAgent(finalDestination, agentCircuit, teleportFlags, out reason);
1215  
1216 if (success)
1217 sp.Scene.EventManager.TriggerTeleportStart(sp.ControllingClient, reg, finalDestination, teleportFlags, logout);
1218  
1219 return success;
1220 }
1221  
1222 protected virtual bool UpdateAgent(GridRegion reg, GridRegion finalDestination, AgentData agent, ScenePresence sp)
1223 {
1224 return Scene.SimulationService.UpdateAgent(finalDestination, agent);
1225 }
1226  
1227 protected virtual void SetCallbackURL(AgentData agent, RegionInfo region)
1228 {
1229 agent.CallbackURI = region.ServerURI + "agent/" + agent.AgentID.ToString() + "/" + region.RegionID.ToString() + "/release/";
1230  
1231 m_log.DebugFormat(
1232 "[ENTITY TRANSFER MODULE]: Set release callback URL to {0} in {1}",
1233 agent.CallbackURI, region.RegionName);
1234 }
1235  
1236 /// <summary>
1237 /// Clean up operations once an agent has moved away through cross or teleport.
1238 /// </summary>
1239 /// <param name='sp'></param>
1240 /// <param name='logout'></param>
1241 protected virtual void AgentHasMovedAway(ScenePresence sp, bool logout)
1242 {
1243 if (sp.Scene.AttachmentsModule != null)
1244 sp.Scene.AttachmentsModule.DeleteAttachmentsFromScene(sp, true);
1245 }
1246  
1247 protected void KillEntity(Scene scene, uint localID)
1248 {
1249 scene.SendKillObject(new List<uint> { localID });
1250 }
1251  
1252 protected virtual GridRegion GetFinalDestination(GridRegion region)
1253 {
1254 return region;
1255 }
1256  
1257 protected virtual bool NeedsNewAgent(float drawdist, uint oldRegionX, uint newRegionX, uint oldRegionY, uint newRegionY)
1258 {
1259 if (m_regionCombinerModule != null && m_regionCombinerModule.IsRootForMegaregion(Scene.RegionInfo.RegionID))
1260 {
1261 Vector2 swCorner, neCorner;
1262 GetMegaregionViewRange(out swCorner, out neCorner);
1263  
1264 m_log.DebugFormat(
1265 "[ENTITY TRANSFER MODULE]: Megaregion view of {0} is from {1} to {2} with new agent check for {3},{4}",
1266 Scene.Name, swCorner, neCorner, newRegionX, newRegionY);
1267  
1268 return !(newRegionX >= swCorner.X && newRegionX <= neCorner.X && newRegionY >= swCorner.Y && newRegionY <= neCorner.Y);
1269 }
1270 else
1271 {
1272 return Util.IsOutsideView(drawdist, oldRegionX, newRegionX, oldRegionY, newRegionY);
1273 }
1274 }
1275  
1276 protected virtual bool NeedsClosing(float drawdist, uint oldRegionX, uint newRegionX, uint oldRegionY, uint newRegionY, GridRegion reg)
1277 {
1278 return Util.IsOutsideView(drawdist, oldRegionX, newRegionX, oldRegionY, newRegionY);
1279 }
1280  
1281 protected virtual bool IsOutsideRegion(Scene s, Vector3 pos)
1282 {
1283 if (s.TestBorderCross(pos, Cardinals.N))
1284 return true;
1285 if (s.TestBorderCross(pos, Cardinals.S))
1286 return true;
1287 if (s.TestBorderCross(pos, Cardinals.E))
1288 return true;
1289 if (s.TestBorderCross(pos, Cardinals.W))
1290 return true;
1291  
1292 return false;
1293 }
1294  
1295 #endregion
1296  
1297 #region Landmark Teleport
1298 /// <summary>
1299 /// Tries to teleport agent to landmark.
1300 /// </summary>
1301 /// <param name="remoteClient"></param>
1302 /// <param name="regionHandle"></param>
1303 /// <param name="position"></param>
1304 public virtual void RequestTeleportLandmark(IClientAPI remoteClient, AssetLandmark lm)
1305 {
1306 GridRegion info = Scene.GridService.GetRegionByUUID(UUID.Zero, lm.RegionID);
1307  
1308 if (info == null)
1309 {
1310 // can't find the region: Tell viewer and abort
1311 remoteClient.SendTeleportFailed("The teleport destination could not be found.");
1312 return;
1313 }
1314 ((Scene)(remoteClient.Scene)).RequestTeleportLocation(remoteClient, info.RegionHandle, lm.Position,
1315 Vector3.Zero, (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaLandmark));
1316 }
1317  
1318 #endregion
1319  
1320 #region Teleport Home
1321  
1322 public virtual void TriggerTeleportHome(UUID id, IClientAPI client)
1323 {
1324 TeleportHome(id, client);
1325 }
1326  
1327 public virtual bool TeleportHome(UUID id, IClientAPI client)
1328 {
1329 m_log.DebugFormat(
1330 "[ENTITY TRANSFER MODULE]: Request to teleport {0} {1} home", client.Name, client.AgentId);
1331  
1332 //OpenSim.Services.Interfaces.PresenceInfo pinfo = Scene.PresenceService.GetAgent(client.SessionId);
1333 GridUserInfo uinfo = Scene.GridUserService.GetGridUserInfo(client.AgentId.ToString());
1334  
1335 if (uinfo != null)
1336 {
1337 GridRegion regionInfo = Scene.GridService.GetRegionByUUID(UUID.Zero, uinfo.HomeRegionID);
1338 if (regionInfo == null)
1339 {
1340 // can't find the Home region: Tell viewer and abort
1341 client.SendTeleportFailed("Your home region could not be found.");
1342 return false;
1343 }
1344  
1345 m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Home region of {0} is {1} ({2}-{3})",
1346 client.Name, regionInfo.RegionName, regionInfo.RegionCoordX, regionInfo.RegionCoordY);
1347  
1348 // a little eekie that this goes back to Scene and with a forced cast, will fix that at some point...
1349 ((Scene)(client.Scene)).RequestTeleportLocation(
1350 client, regionInfo.RegionHandle, uinfo.HomePosition, uinfo.HomeLookAt,
1351 (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaHome));
1352 return true;
1353 }
1354 else
1355 {
1356 m_log.ErrorFormat(
1357 "[ENTITY TRANSFER MODULE]: No grid user information found for {0} {1}. Cannot send home.",
1358 client.Name, client.AgentId);
1359 }
1360 return false;
1361 }
1362  
1363 #endregion
1364  
1365  
1366 #region Agent Crossings
1367  
1368 public bool Cross(ScenePresence agent, bool isFlying)
1369 {
1370 Scene scene = agent.Scene;
1371 Vector3 pos = agent.AbsolutePosition;
1372  
1373 // m_log.DebugFormat(
1374 // "[ENTITY TRANSFER MODULE]: Crossing agent {0} at pos {1} in {2}", agent.Name, pos, scene.Name);
1375  
1376 Vector3 newpos = new Vector3(pos.X, pos.Y, pos.Z);
1377 uint neighbourx = scene.RegionInfo.RegionLocX;
1378 uint neighboury = scene.RegionInfo.RegionLocY;
1379 const float boundaryDistance = 1.7f;
1380 Vector3 northCross = new Vector3(0, boundaryDistance, 0);
1381 Vector3 southCross = new Vector3(0, -1 * boundaryDistance, 0);
1382 Vector3 eastCross = new Vector3(boundaryDistance, 0, 0);
1383 Vector3 westCross = new Vector3(-1 * boundaryDistance, 0, 0);
1384  
1385 // distance into new region to place avatar
1386 const float enterDistance = 0.5f;
1387  
1388 if (scene.TestBorderCross(pos + westCross, Cardinals.W))
1389 {
1390 if (scene.TestBorderCross(pos + northCross, Cardinals.N))
1391 {
1392 Border b = scene.GetCrossedBorder(pos + northCross, Cardinals.N);
1393 neighboury += (uint)(int)(b.BorderLine.Z / (int)Constants.RegionSize);
1394 }
1395 else if (scene.TestBorderCross(pos + southCross, Cardinals.S))
1396 {
1397 Border b = scene.GetCrossedBorder(pos + southCross, Cardinals.S);
1398 if (b.TriggerRegionX == 0 && b.TriggerRegionY == 0)
1399 {
1400 neighboury--;
1401 newpos.Y = Constants.RegionSize - enterDistance;
1402 }
1403 else
1404 {
1405 agent.IsInTransit = true;
1406  
1407 neighboury = b.TriggerRegionY;
1408 neighbourx = b.TriggerRegionX;
1409  
1410 Vector3 newposition = pos;
1411 newposition.X += (scene.RegionInfo.RegionLocX - neighbourx) * Constants.RegionSize;
1412 newposition.Y += (scene.RegionInfo.RegionLocY - neighboury) * Constants.RegionSize;
1413 agent.ControllingClient.SendAgentAlertMessage(
1414 String.Format("Moving you to region {0},{1}", neighbourx, neighboury), false);
1415 InformClientToInitiateTeleportToLocation(agent, neighbourx, neighboury, newposition, scene);
1416 return true;
1417 }
1418 }
1419  
1420 Border ba = scene.GetCrossedBorder(pos + westCross, Cardinals.W);
1421 if (ba.TriggerRegionX == 0 && ba.TriggerRegionY == 0)
1422 {
1423 neighbourx--;
1424 newpos.X = Constants.RegionSize - enterDistance;
1425 }
1426 else
1427 {
1428 agent.IsInTransit = true;
1429  
1430 neighboury = ba.TriggerRegionY;
1431 neighbourx = ba.TriggerRegionX;
1432  
1433 Vector3 newposition = pos;
1434 newposition.X += (scene.RegionInfo.RegionLocX - neighbourx) * Constants.RegionSize;
1435 newposition.Y += (scene.RegionInfo.RegionLocY - neighboury) * Constants.RegionSize;
1436 agent.ControllingClient.SendAgentAlertMessage(
1437 String.Format("Moving you to region {0},{1}", neighbourx, neighboury), false);
1438 InformClientToInitiateTeleportToLocation(agent, neighbourx, neighboury, newposition, scene);
1439  
1440 return true;
1441 }
1442  
1443 }
1444 else if (scene.TestBorderCross(pos + eastCross, Cardinals.E))
1445 {
1446 Border b = scene.GetCrossedBorder(pos + eastCross, Cardinals.E);
1447 neighbourx += (uint)(int)(b.BorderLine.Z / (int)Constants.RegionSize);
1448 newpos.X = enterDistance;
1449  
1450 if (scene.TestBorderCross(pos + southCross, Cardinals.S))
1451 {
1452 Border ba = scene.GetCrossedBorder(pos + southCross, Cardinals.S);
1453 if (ba.TriggerRegionX == 0 && ba.TriggerRegionY == 0)
1454 {
1455 neighboury--;
1456 newpos.Y = Constants.RegionSize - enterDistance;
1457 }
1458 else
1459 {
1460 agent.IsInTransit = true;
1461  
1462 neighboury = ba.TriggerRegionY;
1463 neighbourx = ba.TriggerRegionX;
1464 Vector3 newposition = pos;
1465 newposition.X += (scene.RegionInfo.RegionLocX - neighbourx) * Constants.RegionSize;
1466 newposition.Y += (scene.RegionInfo.RegionLocY - neighboury) * Constants.RegionSize;
1467 agent.ControllingClient.SendAgentAlertMessage(
1468 String.Format("Moving you to region {0},{1}", neighbourx, neighboury), false);
1469 InformClientToInitiateTeleportToLocation(agent, neighbourx, neighboury, newposition, scene);
1470 return true;
1471 }
1472 }
1473 else if (scene.TestBorderCross(pos + northCross, Cardinals.N))
1474 {
1475 Border c = scene.GetCrossedBorder(pos + northCross, Cardinals.N);
1476 neighboury += (uint)(int)(c.BorderLine.Z / (int)Constants.RegionSize);
1477 newpos.Y = enterDistance;
1478 }
1479 }
1480 else if (scene.TestBorderCross(pos + southCross, Cardinals.S))
1481 {
1482 Border b = scene.GetCrossedBorder(pos + southCross, Cardinals.S);
1483 if (b.TriggerRegionX == 0 && b.TriggerRegionY == 0)
1484 {
1485 neighboury--;
1486 newpos.Y = Constants.RegionSize - enterDistance;
1487 }
1488 else
1489 {
1490 agent.IsInTransit = true;
1491  
1492 neighboury = b.TriggerRegionY;
1493 neighbourx = b.TriggerRegionX;
1494 Vector3 newposition = pos;
1495 newposition.X += (scene.RegionInfo.RegionLocX - neighbourx) * Constants.RegionSize;
1496 newposition.Y += (scene.RegionInfo.RegionLocY - neighboury) * Constants.RegionSize;
1497 agent.ControllingClient.SendAgentAlertMessage(
1498 String.Format("Moving you to region {0},{1}", neighbourx, neighboury), false);
1499 InformClientToInitiateTeleportToLocation(agent, neighbourx, neighboury, newposition, scene);
1500 return true;
1501 }
1502 }
1503 else if (scene.TestBorderCross(pos + northCross, Cardinals.N))
1504 {
1505 Border b = scene.GetCrossedBorder(pos + northCross, Cardinals.N);
1506 neighboury += (uint)(int)(b.BorderLine.Z / (int)Constants.RegionSize);
1507 newpos.Y = enterDistance;
1508 }
1509  
1510 /*
1511  
1512 if (pos.X < boundaryDistance) //West
1513 {
1514 neighbourx--;
1515 newpos.X = Constants.RegionSize - enterDistance;
1516 }
1517 else if (pos.X > Constants.RegionSize - boundaryDistance) // East
1518 {
1519 neighbourx++;
1520 newpos.X = enterDistance;
1521 }
1522  
1523 if (pos.Y < boundaryDistance) // South
1524 {
1525 neighboury--;
1526 newpos.Y = Constants.RegionSize - enterDistance;
1527 }
1528 else if (pos.Y > Constants.RegionSize - boundaryDistance) // North
1529 {
1530 neighboury++;
1531 newpos.Y = enterDistance;
1532 }
1533 */
1534  
1535 ulong neighbourHandle = Utils.UIntsToLong((uint)(neighbourx * Constants.RegionSize), (uint)(neighboury * Constants.RegionSize));
1536  
1537 int x = (int)(neighbourx * Constants.RegionSize), y = (int)(neighboury * Constants.RegionSize);
1538  
1539 ExpiringCache<ulong, DateTime> r;
1540 DateTime banUntil;
1541  
1542 if (m_bannedRegions.TryGetValue(agent.ControllingClient.AgentId, out r))
1543 {
1544 if (r.TryGetValue(neighbourHandle, out banUntil))
1545 {
1546 if (DateTime.Now < banUntil)
1547 return false;
1548 r.Remove(neighbourHandle);
1549 }
1550 }
1551 else
1552 {
1553 r = null;
1554 }
1555  
1556 GridRegion neighbourRegion = scene.GridService.GetRegionByPosition(scene.RegionInfo.ScopeID, (int)x, (int)y);
1557  
1558 string reason;
1559 string version;
1560 if (!scene.SimulationService.QueryAccess(neighbourRegion, agent.ControllingClient.AgentId, newpos, out version, out reason))
1561 {
1562 agent.ControllingClient.SendAlertMessage("Cannot region cross into banned parcel");
1563 if (r == null)
1564 {
1565 r = new ExpiringCache<ulong, DateTime>();
1566 r.Add(neighbourHandle, DateTime.Now + TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(15));
1567  
1568 m_bannedRegions.Add(agent.ControllingClient.AgentId, r, TimeSpan.FromSeconds(45));
1569 }
1570 else
1571 {
1572 r.Add(neighbourHandle, DateTime.Now + TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(15));
1573 }
1574 return false;
1575 }
1576  
1577 agent.IsInTransit = true;
1578  
1579 CrossAgentToNewRegionDelegate d = CrossAgentToNewRegionAsync;
1580 d.BeginInvoke(agent, newpos, neighbourx, neighboury, neighbourRegion, isFlying, version, CrossAgentToNewRegionCompleted, d);
1581  
1582 return true;
1583 }
1584  
1585  
1586 public delegate void InformClientToInitiateTeleportToLocationDelegate(ScenePresence agent, uint regionX, uint regionY,
1587 Vector3 position,
1588 Scene initiatingScene);
1589  
1590 private void InformClientToInitiateTeleportToLocation(ScenePresence agent, uint regionX, uint regionY, Vector3 position, Scene initiatingScene)
1591 {
1592  
1593 // This assumes that we know what our neighbours are.
1594  
1595 InformClientToInitiateTeleportToLocationDelegate d = InformClientToInitiateTeleportToLocationAsync;
1596 d.BeginInvoke(agent, regionX, regionY, position, initiatingScene,
1597 InformClientToInitiateTeleportToLocationCompleted,
1598 d);
1599 }
1600  
1601 public void InformClientToInitiateTeleportToLocationAsync(ScenePresence agent, uint regionX, uint regionY, Vector3 position,
1602 Scene initiatingScene)
1603 {
1604 Thread.Sleep(10000);
1605  
1606 m_log.DebugFormat(
1607 "[ENTITY TRANSFER MODULE]: Auto-reteleporting {0} to correct megaregion location {1},{2},{3} from {4}",
1608 agent.Name, regionX, regionY, position, initiatingScene.Name);
1609  
1610 agent.Scene.RequestTeleportLocation(
1611 agent.ControllingClient,
1612 Utils.UIntsToLong(regionX * (uint)Constants.RegionSize, regionY * (uint)Constants.RegionSize),
1613 position,
1614 agent.Lookat,
1615 (uint)Constants.TeleportFlags.ViaLocation);
1616  
1617 /*
1618 IMessageTransferModule im = initiatingScene.RequestModuleInterface<IMessageTransferModule>();
1619 if (im != null)
1620 {
1621 UUID gotoLocation = Util.BuildFakeParcelID(
1622 Util.UIntsToLong(
1623 (regionX *
1624 (uint)Constants.RegionSize),
1625 (regionY *
1626 (uint)Constants.RegionSize)),
1627 (uint)(int)position.X,
1628 (uint)(int)position.Y,
1629 (uint)(int)position.Z);
1630  
1631 GridInstantMessage m
1632 = new GridInstantMessage(
1633 initiatingScene,
1634 UUID.Zero,
1635 "Region",
1636 agent.UUID,
1637 (byte)InstantMessageDialog.GodLikeRequestTeleport,
1638 false,
1639 "",
1640 gotoLocation,
1641 false,
1642 new Vector3(127, 0, 0),
1643 new Byte[0],
1644 false);
1645  
1646 im.SendInstantMessage(m, delegate(bool success)
1647 {
1648 m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Client Initiating Teleport sending IM success = {0}", success);
1649 });
1650  
1651 }
1652 */
1653 }
1654  
1655 private void InformClientToInitiateTeleportToLocationCompleted(IAsyncResult iar)
1656 {
1657 InformClientToInitiateTeleportToLocationDelegate icon =
1658 (InformClientToInitiateTeleportToLocationDelegate)iar.AsyncState;
1659 icon.EndInvoke(iar);
1660 }
1661  
1662 public delegate ScenePresence CrossAgentToNewRegionDelegate(ScenePresence agent, Vector3 pos, uint neighbourx, uint neighboury, GridRegion neighbourRegion, bool isFlying, string version);
1663  
1664 /// <summary>
1665 /// This Closes child agents on neighbouring regions
1666 /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
1667 /// </summary>
1668 protected ScenePresence CrossAgentToNewRegionAsync(
1669 ScenePresence agent, Vector3 pos, uint neighbourx, uint neighboury, GridRegion neighbourRegion,
1670 bool isFlying, string version)
1671 {
1672 if (neighbourRegion == null)
1673 return agent;
1674  
1675 if (!m_entityTransferStateMachine.SetInTransit(agent.UUID))
1676 {
1677 m_log.ErrorFormat(
1678 "[ENTITY TRANSFER MODULE]: Problem crossing user {0} to new region {1} from {2} - agent is already in transit",
1679 agent.Name, neighbourRegion.RegionName, agent.Scene.RegionInfo.RegionName);
1680 return agent;
1681 }
1682  
1683 bool transitWasReset = false;
1684  
1685 try
1686 {
1687 ulong neighbourHandle = Utils.UIntsToLong((uint)(neighbourx * Constants.RegionSize), (uint)(neighboury * Constants.RegionSize));
1688  
1689 m_log.DebugFormat(
1690 "[ENTITY TRANSFER MODULE]: Crossing agent {0} {1} to {2}-{3} running version {4}",
1691 agent.Firstname, agent.Lastname, neighbourx, neighboury, version);
1692  
1693 Scene m_scene = agent.Scene;
1694  
1695 if (!agent.ValidateAttachments())
1696 m_log.DebugFormat(
1697 "[ENTITY TRANSFER MODULE]: Failed validation of all attachments for region crossing of {0} from {1} to {2}. Continuing.",
1698 agent.Name, agent.Scene.RegionInfo.RegionName, neighbourRegion.RegionName);
1699  
1700 pos = pos + agent.Velocity;
1701 Vector3 vel2 = new Vector3(agent.Velocity.X, agent.Velocity.Y, 0);
1702  
1703 agent.RemoveFromPhysicalScene();
1704  
1705 AgentData cAgent = new AgentData();
1706 agent.CopyTo(cAgent);
1707 cAgent.Position = pos;
1708 if (isFlying)
1709 cAgent.ControlFlags |= (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY;
1710  
1711 // We don't need the callback anymnore
1712 cAgent.CallbackURI = String.Empty;
1713  
1714 // Beyond this point, extra cleanup is needed beyond removing transit state
1715 m_entityTransferStateMachine.UpdateInTransit(agent.UUID, AgentTransferState.Transferring);
1716  
1717 if (!m_scene.SimulationService.UpdateAgent(neighbourRegion, cAgent))
1718 {
1719 // region doesn't take it
1720 m_entityTransferStateMachine.UpdateInTransit(agent.UUID, AgentTransferState.CleaningUp);
1721  
1722 m_log.WarnFormat(
1723 "[ENTITY TRANSFER MODULE]: Region {0} would not accept update for agent {1} on cross attempt. Returning to original region.",
1724 neighbourRegion.RegionName, agent.Name);
1725  
1726 ReInstantiateScripts(agent);
1727 agent.AddToPhysicalScene(isFlying);
1728  
1729 return agent;
1730 }
1731  
1732 //m_log.Debug("BEFORE CROSS");
1733 //Scene.DumpChildrenSeeds(UUID);
1734 //DumpKnownRegions();
1735 string agentcaps;
1736 if (!agent.KnownRegions.TryGetValue(neighbourRegion.RegionHandle, out agentcaps))
1737 {
1738 m_log.ErrorFormat("[ENTITY TRANSFER MODULE]: No ENTITY TRANSFER MODULE information for region handle {0}, exiting CrossToNewRegion.",
1739 neighbourRegion.RegionHandle);
1740 return agent;
1741 }
1742  
1743 // No turning back
1744 agent.IsChildAgent = true;
1745  
1746 string capsPath = neighbourRegion.ServerURI + CapsUtil.GetCapsSeedPath(agentcaps);
1747  
1748 m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Sending new CAPS seed url {0} to client {1}", capsPath, agent.UUID);
1749  
1750 if (m_eqModule != null)
1751 {
1752 m_eqModule.CrossRegion(
1753 neighbourHandle, pos, vel2 /* agent.Velocity */, neighbourRegion.ExternalEndPoint,
1754 capsPath, agent.UUID, agent.ControllingClient.SessionId);
1755 }
1756 else
1757 {
1758 agent.ControllingClient.CrossRegion(neighbourHandle, pos, agent.Velocity, neighbourRegion.ExternalEndPoint,
1759 capsPath);
1760 }
1761  
1762 // SUCCESS!
1763 m_entityTransferStateMachine.UpdateInTransit(agent.UUID, AgentTransferState.ReceivedAtDestination);
1764  
1765 // Unlike a teleport, here we do not wait for the destination region to confirm the receipt.
1766 m_entityTransferStateMachine.UpdateInTransit(agent.UUID, AgentTransferState.CleaningUp);
1767  
1768 agent.MakeChildAgent();
1769  
1770 // FIXME: Possibly this should occur lower down after other commands to close other agents,
1771 // but not sure yet what the side effects would be.
1772 m_entityTransferStateMachine.ResetFromTransit(agent.UUID);
1773 transitWasReset = true;
1774  
1775 // now we have a child agent in this region. Request all interesting data about other (root) agents
1776 agent.SendOtherAgentsAvatarDataToMe();
1777 agent.SendOtherAgentsAppearanceToMe();
1778  
1779 // Backwards compatibility. Best effort
1780 if (version == "Unknown" || version == string.Empty)
1781 {
1782 m_log.DebugFormat("[ENTITY TRANSFER MODULE]: neighbor with old version, passing attachments one by one...");
1783 Thread.Sleep(3000); // wait a little now that we're not waiting for the callback
1784 CrossAttachmentsIntoNewRegion(neighbourRegion, agent, true);
1785 }
1786  
1787 // Next, let's close the child agent connections that are too far away.
1788 agent.CloseChildAgents(neighbourx, neighboury);
1789  
1790 AgentHasMovedAway(agent, false);
1791  
1792 //m_log.Debug("AFTER CROSS");
1793 //Scene.DumpChildrenSeeds(UUID);
1794 //DumpKnownRegions();
1795 }
1796 catch (Exception e)
1797 {
1798 m_log.ErrorFormat(
1799 "[ENTITY TRANSFER MODULE]: Problem crossing user {0} to new region {1} from {2}. Exception {3}{4}",
1800 agent.Name, neighbourRegion.RegionName, agent.Scene.RegionInfo.RegionName, e.Message, e.StackTrace);
1801  
1802 // TODO: Might be worth attempting other restoration here such as reinstantiation of scripts, etc.
1803 }
1804 finally
1805 {
1806 if (!transitWasReset)
1807 m_entityTransferStateMachine.ResetFromTransit(agent.UUID);
1808 }
1809  
1810 return agent;
1811 }
1812  
1813 private void CrossAgentToNewRegionCompleted(IAsyncResult iar)
1814 {
1815 CrossAgentToNewRegionDelegate icon = (CrossAgentToNewRegionDelegate)iar.AsyncState;
1816 ScenePresence agent = icon.EndInvoke(iar);
1817  
1818 //// If the cross was successful, this agent is a child agent
1819 //if (agent.IsChildAgent)
1820 // agent.Reset();
1821 //else // Not successful
1822 // agent.RestoreInCurrentScene();
1823  
1824 // In any case
1825 agent.IsInTransit = false;
1826  
1827 m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Crossing agent {0} {1} completed.", agent.Firstname, agent.Lastname);
1828 }
1829  
1830 #endregion
1831  
1832 #region Enable Child Agent
1833  
1834 /// <summary>
1835 /// This informs a single neighbouring region about agent "avatar".
1836 /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
1837 /// </summary>
1838 /// <param name="sp"></param>
1839 /// <param name="region"></param>
1840 public void EnableChildAgent(ScenePresence sp, GridRegion region)
1841 {
1842 m_log.DebugFormat("[ENTITY TRANSFER]: Enabling child agent in new neighbour {0}", region.RegionName);
1843  
1844 AgentCircuitData currentAgentCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
1845 AgentCircuitData agent = sp.ControllingClient.RequestClientInfo();
1846 agent.BaseFolder = UUID.Zero;
1847 agent.InventoryFolder = UUID.Zero;
1848 agent.startpos = new Vector3(128, 128, 70);
1849 agent.child = true;
1850 agent.Appearance = sp.Appearance;
1851 agent.CapsPath = CapsUtil.GetRandomCapsObjectPath();
1852  
1853 agent.ChildrenCapSeeds = new Dictionary<ulong, string>(sp.Scene.CapsModule.GetChildrenSeeds(sp.UUID));
1854 //m_log.DebugFormat("[XXX] Seeds 1 {0}", agent.ChildrenCapSeeds.Count);
1855  
1856 if (!agent.ChildrenCapSeeds.ContainsKey(sp.Scene.RegionInfo.RegionHandle))
1857 agent.ChildrenCapSeeds.Add(sp.Scene.RegionInfo.RegionHandle, sp.ControllingClient.RequestClientInfo().CapsPath);
1858 //m_log.DebugFormat("[XXX] Seeds 2 {0}", agent.ChildrenCapSeeds.Count);
1859  
1860 sp.AddNeighbourRegion(region.RegionHandle, agent.CapsPath);
1861 //foreach (ulong h in agent.ChildrenCapSeeds.Keys)
1862 // m_log.DebugFormat("[XXX] --> {0}", h);
1863 //m_log.DebugFormat("[XXX] Adding {0}", region.RegionHandle);
1864 agent.ChildrenCapSeeds.Add(region.RegionHandle, agent.CapsPath);
1865  
1866 if (sp.Scene.CapsModule != null)
1867 {
1868 sp.Scene.CapsModule.SetChildrenSeed(sp.UUID, agent.ChildrenCapSeeds);
1869 }
1870  
1871 if (currentAgentCircuit != null)
1872 {
1873 agent.ServiceURLs = currentAgentCircuit.ServiceURLs;
1874 agent.IPAddress = currentAgentCircuit.IPAddress;
1875 agent.Viewer = currentAgentCircuit.Viewer;
1876 agent.Channel = currentAgentCircuit.Channel;
1877 agent.Mac = currentAgentCircuit.Mac;
1878 agent.Id0 = currentAgentCircuit.Id0;
1879 }
1880  
1881 InformClientOfNeighbourDelegate d = InformClientOfNeighbourAsync;
1882 d.BeginInvoke(sp, agent, region, region.ExternalEndPoint, true,
1883 InformClientOfNeighbourCompleted,
1884 d);
1885 }
1886 #endregion
1887  
1888 #region Enable Child Agents
1889  
1890 private delegate void InformClientOfNeighbourDelegate(
1891 ScenePresence avatar, AgentCircuitData a, GridRegion reg, IPEndPoint endPoint, bool newAgent);
1892  
1893 /// <summary>
1894 /// This informs all neighbouring regions about agent "avatar".
1895 /// </summary>
1896 /// <param name="sp"></param>
1897 public void EnableChildAgents(ScenePresence sp)
1898 {
1899 List<GridRegion> neighbours = new List<GridRegion>();
1900 RegionInfo m_regionInfo = sp.Scene.RegionInfo;
1901  
1902 if (m_regionInfo != null)
1903 {
1904 neighbours = RequestNeighbours(sp, m_regionInfo.RegionLocX, m_regionInfo.RegionLocY);
1905 }
1906 else
1907 {
1908 m_log.Debug("[ENTITY TRANSFER MODULE]: m_regionInfo was null in EnableChildAgents, is this a NPC?");
1909 }
1910  
1911 /// We need to find the difference between the new regions where there are no child agents
1912 /// and the regions where there are already child agents. We only send notification to the former.
1913 List<ulong> neighbourHandles = NeighbourHandles(neighbours); // on this region
1914 neighbourHandles.Add(sp.Scene.RegionInfo.RegionHandle); // add this region too
1915 List<ulong> previousRegionNeighbourHandles;
1916  
1917 if (sp.Scene.CapsModule != null)
1918 {
1919 previousRegionNeighbourHandles =
1920 new List<ulong>(sp.Scene.CapsModule.GetChildrenSeeds(sp.UUID).Keys);
1921 }
1922 else
1923 {
1924 previousRegionNeighbourHandles = new List<ulong>();
1925 }
1926  
1927 List<ulong> newRegions = NewNeighbours(neighbourHandles, previousRegionNeighbourHandles);
1928 List<ulong> oldRegions = OldNeighbours(neighbourHandles, previousRegionNeighbourHandles);
1929  
1930 // Dump("Current Neighbors", neighbourHandles);
1931 // Dump("Previous Neighbours", previousRegionNeighbourHandles);
1932 // Dump("New Neighbours", newRegions);
1933 // Dump("Old Neighbours", oldRegions);
1934  
1935 /// Update the scene presence's known regions here on this region
1936 sp.DropOldNeighbours(oldRegions);
1937  
1938 /// Collect as many seeds as possible
1939 Dictionary<ulong, string> seeds;
1940 if (sp.Scene.CapsModule != null)
1941 seeds = new Dictionary<ulong, string>(sp.Scene.CapsModule.GetChildrenSeeds(sp.UUID));
1942 else
1943 seeds = new Dictionary<ulong, string>();
1944  
1945 //m_log.Debug(" !!! No. of seeds: " + seeds.Count);
1946 if (!seeds.ContainsKey(sp.Scene.RegionInfo.RegionHandle))
1947 seeds.Add(sp.Scene.RegionInfo.RegionHandle, sp.ControllingClient.RequestClientInfo().CapsPath);
1948  
1949 /// Create the necessary child agents
1950 List<AgentCircuitData> cagents = new List<AgentCircuitData>();
1951 foreach (GridRegion neighbour in neighbours)
1952 {
1953 if (neighbour.RegionHandle != sp.Scene.RegionInfo.RegionHandle)
1954 {
1955 AgentCircuitData currentAgentCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
1956 AgentCircuitData agent = sp.ControllingClient.RequestClientInfo();
1957 agent.BaseFolder = UUID.Zero;
1958 agent.InventoryFolder = UUID.Zero;
1959 agent.startpos = sp.AbsolutePosition + CalculateOffset(sp, neighbour);
1960 agent.child = true;
1961 agent.Appearance = sp.Appearance;
1962 if (currentAgentCircuit != null)
1963 {
1964 agent.ServiceURLs = currentAgentCircuit.ServiceURLs;
1965 agent.IPAddress = currentAgentCircuit.IPAddress;
1966 agent.Viewer = currentAgentCircuit.Viewer;
1967 agent.Channel = currentAgentCircuit.Channel;
1968 agent.Mac = currentAgentCircuit.Mac;
1969 agent.Id0 = currentAgentCircuit.Id0;
1970 }
1971  
1972 if (newRegions.Contains(neighbour.RegionHandle))
1973 {
1974 agent.CapsPath = CapsUtil.GetRandomCapsObjectPath();
1975 sp.AddNeighbourRegion(neighbour.RegionHandle, agent.CapsPath);
1976 seeds.Add(neighbour.RegionHandle, agent.CapsPath);
1977 }
1978 else
1979 {
1980 agent.CapsPath = sp.Scene.CapsModule.GetChildSeed(sp.UUID, neighbour.RegionHandle);
1981 }
1982  
1983 cagents.Add(agent);
1984 }
1985 }
1986  
1987 /// Update all child agent with everyone's seeds
1988 foreach (AgentCircuitData a in cagents)
1989 {
1990 a.ChildrenCapSeeds = new Dictionary<ulong, string>(seeds);
1991 }
1992  
1993 if (sp.Scene.CapsModule != null)
1994 {
1995 sp.Scene.CapsModule.SetChildrenSeed(sp.UUID, seeds);
1996 }
1997 sp.KnownRegions = seeds;
1998 //avatar.Scene.DumpChildrenSeeds(avatar.UUID);
1999 //avatar.DumpKnownRegions();
2000  
2001 bool newAgent = false;
2002 int count = 0;
2003 foreach (GridRegion neighbour in neighbours)
2004 {
2005 //m_log.WarnFormat("--> Going to send child agent to {0}", neighbour.RegionName);
2006 // Don't do it if there's already an agent in that region
2007 if (newRegions.Contains(neighbour.RegionHandle))
2008 newAgent = true;
2009 else
2010 newAgent = false;
2011 // continue;
2012  
2013 if (neighbour.RegionHandle != sp.Scene.RegionInfo.RegionHandle)
2014 {
2015 try
2016 {
2017 // Let's put this back at sync, so that it doesn't clog
2018 // the network, especially for regions in the same physical server.
2019 // We're really not in a hurry here.
2020 InformClientOfNeighbourAsync(sp, cagents[count], neighbour, neighbour.ExternalEndPoint, newAgent);
2021 //InformClientOfNeighbourDelegate d = InformClientOfNeighbourAsync;
2022 //d.BeginInvoke(sp, cagents[count], neighbour, neighbour.ExternalEndPoint, newAgent,
2023 // InformClientOfNeighbourCompleted,
2024 // d);
2025 }
2026  
2027 catch (ArgumentOutOfRangeException)
2028 {
2029 m_log.ErrorFormat(
2030 "[ENTITY TRANSFER MODULE]: Neighbour Regions response included the current region in the neighbour list. The following region will not display to the client: {0} for region {1} ({2}, {3}).",
2031 neighbour.ExternalHostName,
2032 neighbour.RegionHandle,
2033 neighbour.RegionLocX,
2034 neighbour.RegionLocY);
2035 }
2036 catch (Exception e)
2037 {
2038 m_log.ErrorFormat(
2039 "[ENTITY TRANSFER MODULE]: Could not resolve external hostname {0} for region {1} ({2}, {3}). {4}",
2040 neighbour.ExternalHostName,
2041 neighbour.RegionHandle,
2042 neighbour.RegionLocX,
2043 neighbour.RegionLocY,
2044 e);
2045  
2046 // FIXME: Okay, even though we've failed, we're still going to throw the exception on,
2047 // since I don't know what will happen if we just let the client continue
2048  
2049 // XXX: Well, decided to swallow the exception instead for now. Let us see how that goes.
2050 // throw e;
2051  
2052 }
2053 }
2054 count++;
2055 }
2056 }
2057  
2058 Vector3 CalculateOffset(ScenePresence sp, GridRegion neighbour)
2059 {
2060 int rRegionX = (int)sp.Scene.RegionInfo.RegionLocX;
2061 int rRegionY = (int)sp.Scene.RegionInfo.RegionLocY;
2062 int tRegionX = neighbour.RegionLocX / (int)Constants.RegionSize;
2063 int tRegionY = neighbour.RegionLocY / (int)Constants.RegionSize;
2064 int shiftx = (rRegionX - tRegionX) * (int)Constants.RegionSize;
2065 int shifty = (rRegionY - tRegionY) * (int)Constants.RegionSize;
2066 return new Vector3(shiftx, shifty, 0f);
2067 }
2068  
2069 private void InformClientOfNeighbourCompleted(IAsyncResult iar)
2070 {
2071 InformClientOfNeighbourDelegate icon = (InformClientOfNeighbourDelegate)iar.AsyncState;
2072 icon.EndInvoke(iar);
2073 //m_log.WarnFormat(" --> InformClientOfNeighbourCompleted");
2074 }
2075  
2076 /// <summary>
2077 /// Async component for informing client of which neighbours exist
2078 /// </summary>
2079 /// <remarks>
2080 /// This needs to run asynchronously, as a network timeout may block the thread for a long while
2081 /// </remarks>
2082 /// <param name="remoteClient"></param>
2083 /// <param name="a"></param>
2084 /// <param name="regionHandle"></param>
2085 /// <param name="endPoint"></param>
2086 private void InformClientOfNeighbourAsync(ScenePresence sp, AgentCircuitData a, GridRegion reg,
2087 IPEndPoint endPoint, bool newAgent)
2088 {
2089 // Let's wait just a little to give time to originating regions to catch up with closing child agents
2090 // after a cross here
2091 Thread.Sleep(500);
2092  
2093 Scene scene = sp.Scene;
2094  
2095 m_log.DebugFormat(
2096 "[ENTITY TRANSFER MODULE]: Informing {0} {1} about neighbour {2} {3} at ({4},{5})",
2097 sp.Name, sp.UUID, reg.RegionName, endPoint, reg.RegionCoordX, reg.RegionCoordY);
2098  
2099 string capsPath = reg.ServerURI + CapsUtil.GetCapsSeedPath(a.CapsPath);
2100  
2101 string reason = String.Empty;
2102  
2103 bool regionAccepted = scene.SimulationService.CreateAgent(reg, a, (uint)TeleportFlags.Default, out reason);
2104  
2105 if (regionAccepted && newAgent)
2106 {
2107 if (m_eqModule != null)
2108 {
2109 #region IP Translation for NAT
2110 IClientIPEndpoint ipepClient;
2111 if (sp.ClientView.TryGet(out ipepClient))
2112 {
2113 endPoint.Address = NetworkUtil.GetIPFor(ipepClient.EndPoint, endPoint.Address);
2114 }
2115 #endregion
2116  
2117 m_log.DebugFormat("[ENTITY TRANSFER MODULE]: {0} is sending {1} EnableSimulator for neighbour region {2} @ {3} " +
2118 "and EstablishAgentCommunication with seed cap {4}",
2119 scene.RegionInfo.RegionName, sp.Name, reg.RegionName, reg.RegionHandle, capsPath);
2120  
2121 m_eqModule.EnableSimulator(reg.RegionHandle, endPoint, sp.UUID);
2122 m_eqModule.EstablishAgentCommunication(sp.UUID, endPoint, capsPath);
2123 }
2124 else
2125 {
2126 sp.ControllingClient.InformClientOfNeighbour(reg.RegionHandle, endPoint);
2127 // TODO: make Event Queue disablable!
2128 }
2129  
2130 m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Completed inform {0} {1} about neighbour {2}", sp.Name, sp.UUID, endPoint);
2131 }
2132  
2133 if (!regionAccepted)
2134 m_log.WarnFormat(
2135 "[ENTITY TRANSFER MODULE]: Region {0} did not accept {1} {2}: {3}",
2136 reg.RegionName, sp.Name, sp.UUID, reason);
2137 }
2138  
2139 /// <summary>
2140 /// Gets the range considered in view of this megaregion (assuming this is a megaregion).
2141 /// </summary>
2142 /// <remarks>Expressed in 256m units</remarks>
2143 /// <param name='swCorner'></param>
2144 /// <param name='neCorner'></param>
2145 private void GetMegaregionViewRange(out Vector2 swCorner, out Vector2 neCorner)
2146 {
2147 Border[] northBorders = Scene.NorthBorders.ToArray();
2148 Border[] eastBorders = Scene.EastBorders.ToArray();
2149  
2150 Vector2 extent = Vector2.Zero;
2151 for (int i = 0; i < eastBorders.Length; i++)
2152 {
2153 extent.X = (eastBorders[i].BorderLine.Z > extent.X) ? eastBorders[i].BorderLine.Z : extent.X;
2154 }
2155 for (int i = 0; i < northBorders.Length; i++)
2156 {
2157 extent.Y = (northBorders[i].BorderLine.Z > extent.Y) ? northBorders[i].BorderLine.Z : extent.Y;
2158 }
2159  
2160 // Loss of fraction on purpose
2161 extent.X = ((int)extent.X / (int)Constants.RegionSize);
2162 extent.Y = ((int)extent.Y / (int)Constants.RegionSize);
2163  
2164 swCorner.X = Scene.RegionInfo.RegionLocX - 1;
2165 swCorner.Y = Scene.RegionInfo.RegionLocY - 1;
2166 neCorner.X = Scene.RegionInfo.RegionLocX + extent.X;
2167 neCorner.Y = Scene.RegionInfo.RegionLocY + extent.Y;
2168 }
2169  
2170 /// <summary>
2171 /// Return the list of regions that are considered to be neighbours to the given scene.
2172 /// </summary>
2173 /// <param name="pScene"></param>
2174 /// <param name="pRegionLocX"></param>
2175 /// <param name="pRegionLocY"></param>
2176 /// <returns></returns>
2177 protected List<GridRegion> RequestNeighbours(ScenePresence avatar, uint pRegionLocX, uint pRegionLocY)
2178 {
2179 Scene pScene = avatar.Scene;
2180 RegionInfo m_regionInfo = pScene.RegionInfo;
2181  
2182 // Leaving this as a "megaregions" computation vs "non-megaregions" computation; it isn't
2183 // clear what should be done with a "far view" given that megaregions already extended the
2184 // view to include everything in the megaregion
2185 if (m_regionCombinerModule == null || !m_regionCombinerModule.IsRootForMegaregion(Scene.RegionInfo.RegionID))
2186 {
2187 int dd = avatar.DrawDistance < Constants.RegionSize ? (int)Constants.RegionSize : (int)avatar.DrawDistance;
2188  
2189 int startX = (int)pRegionLocX * (int)Constants.RegionSize - dd + (int)(Constants.RegionSize/2);
2190 int startY = (int)pRegionLocY * (int)Constants.RegionSize - dd + (int)(Constants.RegionSize/2);
2191  
2192 int endX = (int)pRegionLocX * (int)Constants.RegionSize + dd + (int)(Constants.RegionSize/2);
2193 int endY = (int)pRegionLocY * (int)Constants.RegionSize + dd + (int)(Constants.RegionSize/2);
2194  
2195 List<GridRegion> neighbours =
2196 avatar.Scene.GridService.GetRegionRange(m_regionInfo.ScopeID, startX, endX, startY, endY);
2197  
2198 neighbours.RemoveAll(delegate(GridRegion r) { return r.RegionID == m_regionInfo.RegionID; });
2199 return neighbours;
2200 }
2201 else
2202 {
2203 Vector2 swCorner, neCorner;
2204 GetMegaregionViewRange(out swCorner, out neCorner);
2205  
2206 List<GridRegion> neighbours
2207 = pScene.GridService.GetRegionRange(
2208 m_regionInfo.ScopeID,
2209 (int)swCorner.X * (int)Constants.RegionSize,
2210 (int)neCorner.X * (int)Constants.RegionSize,
2211 (int)swCorner.Y * (int)Constants.RegionSize,
2212 (int)neCorner.Y * (int)Constants.RegionSize);
2213  
2214 neighbours.RemoveAll(delegate(GridRegion r) { return r.RegionID == m_regionInfo.RegionID; });
2215  
2216 return neighbours;
2217 }
2218 }
2219  
2220 private List<ulong> NewNeighbours(List<ulong> currentNeighbours, List<ulong> previousNeighbours)
2221 {
2222 return currentNeighbours.FindAll(delegate(ulong handle) { return !previousNeighbours.Contains(handle); });
2223 }
2224  
2225 // private List<ulong> CommonNeighbours(List<ulong> currentNeighbours, List<ulong> previousNeighbours)
2226 // {
2227 // return currentNeighbours.FindAll(delegate(ulong handle) { return previousNeighbours.Contains(handle); });
2228 // }
2229  
2230 private List<ulong> OldNeighbours(List<ulong> currentNeighbours, List<ulong> previousNeighbours)
2231 {
2232 return previousNeighbours.FindAll(delegate(ulong handle) { return !currentNeighbours.Contains(handle); });
2233 }
2234  
2235 private List<ulong> NeighbourHandles(List<GridRegion> neighbours)
2236 {
2237 List<ulong> handles = new List<ulong>();
2238 foreach (GridRegion reg in neighbours)
2239 {
2240 handles.Add(reg.RegionHandle);
2241 }
2242 return handles;
2243 }
2244  
2245 // private void Dump(string msg, List<ulong> handles)
2246 // {
2247 // m_log.InfoFormat("-------------- HANDLE DUMP ({0}) ---------", msg);
2248 // foreach (ulong handle in handles)
2249 // {
2250 // uint x, y;
2251 // Utils.LongToUInts(handle, out x, out y);
2252 // x = x / Constants.RegionSize;
2253 // y = y / Constants.RegionSize;
2254 // m_log.InfoFormat("({0}, {1})", x, y);
2255 // }
2256 // }
2257  
2258 #endregion
2259  
2260 #region Agent Arrived
2261  
2262 public void AgentArrivedAtDestination(UUID id)
2263 {
2264 m_entityTransferStateMachine.SetAgentArrivedAtDestination(id);
2265 }
2266  
2267 #endregion
2268  
2269 #region Object Transfers
2270  
2271 /// <summary>
2272 /// Move the given scene object into a new region depending on which region its absolute position has moved
2273 /// into.
2274 ///
2275 /// This method locates the new region handle and offsets the prim position for the new region
2276 /// </summary>
2277 /// <param name="attemptedPosition">the attempted out of region position of the scene object</param>
2278 /// <param name="grp">the scene object that we're crossing</param>
2279 public void Cross(SceneObjectGroup grp, Vector3 attemptedPosition, bool silent)
2280 {
2281 if (grp == null)
2282 return;
2283 if (grp.IsDeleted)
2284 return;
2285  
2286 Scene scene = grp.Scene;
2287 if (scene == null)
2288 return;
2289  
2290 if (grp.RootPart.DIE_AT_EDGE)
2291 {
2292 // We remove the object here
2293 try
2294 {
2295 scene.DeleteSceneObject(grp, false);
2296 }
2297 catch (Exception)
2298 {
2299 m_log.Warn("[DATABASE]: exception when trying to remove the prim that crossed the border.");
2300 }
2301 return;
2302 }
2303  
2304 int thisx = (int)scene.RegionInfo.RegionLocX;
2305 int thisy = (int)scene.RegionInfo.RegionLocY;
2306 Vector3 EastCross = new Vector3(0.1f, 0, 0);
2307 Vector3 WestCross = new Vector3(-0.1f, 0, 0);
2308 Vector3 NorthCross = new Vector3(0, 0.1f, 0);
2309 Vector3 SouthCross = new Vector3(0, -0.1f, 0);
2310  
2311  
2312 // use this if no borders were crossed!
2313 ulong newRegionHandle
2314 = Util.UIntsToLong((uint)((thisx) * Constants.RegionSize),
2315 (uint)((thisy) * Constants.RegionSize));
2316  
2317 Vector3 pos = attemptedPosition;
2318  
2319 int changeX = 1;
2320 int changeY = 1;
2321  
2322 if (scene.TestBorderCross(attemptedPosition + WestCross, Cardinals.W))
2323 {
2324 if (scene.TestBorderCross(attemptedPosition + SouthCross, Cardinals.S))
2325 {
2326  
2327 Border crossedBorderx = scene.GetCrossedBorder(attemptedPosition + WestCross, Cardinals.W);
2328  
2329 if (crossedBorderx.BorderLine.Z > 0)
2330 {
2331 pos.X = ((pos.X + crossedBorderx.BorderLine.Z));
2332 changeX = (int)(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize);
2333 }
2334 else
2335 pos.X = ((pos.X + Constants.RegionSize));
2336  
2337 Border crossedBordery = scene.GetCrossedBorder(attemptedPosition + SouthCross, Cardinals.S);
2338 //(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize)
2339  
2340 if (crossedBordery.BorderLine.Z > 0)
2341 {
2342 pos.Y = ((pos.Y + crossedBordery.BorderLine.Z));
2343 changeY = (int)(crossedBordery.BorderLine.Z / (int)Constants.RegionSize);
2344 }
2345 else
2346 pos.Y = ((pos.Y + Constants.RegionSize));
2347  
2348  
2349  
2350 newRegionHandle
2351 = Util.UIntsToLong((uint)((thisx - changeX) * Constants.RegionSize),
2352 (uint)((thisy - changeY) * Constants.RegionSize));
2353 // x - 1
2354 // y - 1
2355 }
2356 else if (scene.TestBorderCross(attemptedPosition + NorthCross, Cardinals.N))
2357 {
2358 Border crossedBorderx = scene.GetCrossedBorder(attemptedPosition + WestCross, Cardinals.W);
2359  
2360 if (crossedBorderx.BorderLine.Z > 0)
2361 {
2362 pos.X = ((pos.X + crossedBorderx.BorderLine.Z));
2363 changeX = (int)(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize);
2364 }
2365 else
2366 pos.X = ((pos.X + Constants.RegionSize));
2367  
2368  
2369 Border crossedBordery = scene.GetCrossedBorder(attemptedPosition + SouthCross, Cardinals.S);
2370 //(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize)
2371  
2372 if (crossedBordery.BorderLine.Z > 0)
2373 {
2374 pos.Y = ((pos.Y + crossedBordery.BorderLine.Z));
2375 changeY = (int)(crossedBordery.BorderLine.Z / (int)Constants.RegionSize);
2376 }
2377 else
2378 pos.Y = ((pos.Y + Constants.RegionSize));
2379  
2380 newRegionHandle
2381 = Util.UIntsToLong((uint)((thisx - changeX) * Constants.RegionSize),
2382 (uint)((thisy + changeY) * Constants.RegionSize));
2383 // x - 1
2384 // y + 1
2385 }
2386 else
2387 {
2388 Border crossedBorderx = scene.GetCrossedBorder(attemptedPosition + WestCross, Cardinals.W);
2389  
2390 if (crossedBorderx.BorderLine.Z > 0)
2391 {
2392 pos.X = ((pos.X + crossedBorderx.BorderLine.Z));
2393 changeX = (int)(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize);
2394 }
2395 else
2396 pos.X = ((pos.X + Constants.RegionSize));
2397  
2398 newRegionHandle
2399 = Util.UIntsToLong((uint)((thisx - changeX) * Constants.RegionSize),
2400 (uint)(thisy * Constants.RegionSize));
2401 // x - 1
2402 }
2403 }
2404 else if (scene.TestBorderCross(attemptedPosition + EastCross, Cardinals.E))
2405 {
2406 if (scene.TestBorderCross(attemptedPosition + SouthCross, Cardinals.S))
2407 {
2408  
2409 pos.X = ((pos.X - Constants.RegionSize));
2410 Border crossedBordery = scene.GetCrossedBorder(attemptedPosition + SouthCross, Cardinals.S);
2411 //(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize)
2412  
2413 if (crossedBordery.BorderLine.Z > 0)
2414 {
2415 pos.Y = ((pos.Y + crossedBordery.BorderLine.Z));
2416 changeY = (int)(crossedBordery.BorderLine.Z / (int)Constants.RegionSize);
2417 }
2418 else
2419 pos.Y = ((pos.Y + Constants.RegionSize));
2420  
2421  
2422 newRegionHandle
2423 = Util.UIntsToLong((uint)((thisx + changeX) * Constants.RegionSize),
2424 (uint)((thisy - changeY) * Constants.RegionSize));
2425 // x + 1
2426 // y - 1
2427 }
2428 else if (scene.TestBorderCross(attemptedPosition + NorthCross, Cardinals.N))
2429 {
2430 pos.X = ((pos.X - Constants.RegionSize));
2431 pos.Y = ((pos.Y - Constants.RegionSize));
2432 newRegionHandle
2433 = Util.UIntsToLong((uint)((thisx + changeX) * Constants.RegionSize),
2434 (uint)((thisy + changeY) * Constants.RegionSize));
2435 // x + 1
2436 // y + 1
2437 }
2438 else
2439 {
2440 pos.X = ((pos.X - Constants.RegionSize));
2441 newRegionHandle
2442 = Util.UIntsToLong((uint)((thisx + changeX) * Constants.RegionSize),
2443 (uint)(thisy * Constants.RegionSize));
2444 // x + 1
2445 }
2446 }
2447 else if (scene.TestBorderCross(attemptedPosition + SouthCross, Cardinals.S))
2448 {
2449 Border crossedBordery = scene.GetCrossedBorder(attemptedPosition + SouthCross, Cardinals.S);
2450 //(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize)
2451  
2452 if (crossedBordery.BorderLine.Z > 0)
2453 {
2454 pos.Y = ((pos.Y + crossedBordery.BorderLine.Z));
2455 changeY = (int)(crossedBordery.BorderLine.Z / (int)Constants.RegionSize);
2456 }
2457 else
2458 pos.Y = ((pos.Y + Constants.RegionSize));
2459  
2460 newRegionHandle
2461 = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy - changeY) * Constants.RegionSize));
2462 // y - 1
2463 }
2464 else if (scene.TestBorderCross(attemptedPosition + NorthCross, Cardinals.N))
2465 {
2466  
2467 pos.Y = ((pos.Y - Constants.RegionSize));
2468 newRegionHandle
2469 = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy + changeY) * Constants.RegionSize));
2470 // y + 1
2471 }
2472  
2473 // Offset the positions for the new region across the border
2474 Vector3 oldGroupPosition = grp.RootPart.GroupPosition;
2475  
2476 // If we fail to cross the border, then reset the position of the scene object on that border.
2477 uint x = 0, y = 0;
2478 Utils.LongToUInts(newRegionHandle, out x, out y);
2479 GridRegion destination = scene.GridService.GetRegionByPosition(scene.RegionInfo.ScopeID, (int)x, (int)y);
2480  
2481 if (destination == null || !CrossPrimGroupIntoNewRegion(destination, pos, grp, silent))
2482 {
2483 m_log.InfoFormat("[ENTITY TRANSFER MODULE] cross region transfer failed for object {0}",grp.UUID);
2484  
2485 // We are going to move the object back to the old position so long as the old position
2486 // is in the region
2487 oldGroupPosition.X = Util.Clamp<float>(oldGroupPosition.X,1.0f,(float)Constants.RegionSize-1);
2488 oldGroupPosition.Y = Util.Clamp<float>(oldGroupPosition.Y,1.0f,(float)Constants.RegionSize-1);
2489 oldGroupPosition.Z = Util.Clamp<float>(oldGroupPosition.Z,1.0f,4096.0f);
2490  
2491 grp.RootPart.GroupPosition = oldGroupPosition;
2492  
2493 // Need to turn off the physics flags, otherwise the object will continue to attempt to
2494 // move out of the region creating an infinite loop of failed attempts to cross
2495 grp.UpdatePrimFlags(grp.RootPart.LocalId,false,grp.IsTemporary,grp.IsPhantom,false);
2496  
2497 if (grp.RootPart.KeyframeMotion != null)
2498 grp.RootPart.KeyframeMotion.CrossingFailure();
2499  
2500 grp.ScheduleGroupForFullUpdate();
2501 }
2502 }
2503  
2504  
2505 /// <summary>
2506 /// Move the given scene object into a new region
2507 /// </summary>
2508 /// <param name="newRegionHandle"></param>
2509 /// <param name="grp">Scene Object Group that we're crossing</param>
2510 /// <returns>
2511 /// true if the crossing itself was successful, false on failure
2512 /// FIMXE: we still return true if the crossing object was not successfully deleted from the originating region
2513 /// </returns>
2514 protected bool CrossPrimGroupIntoNewRegion(GridRegion destination, Vector3 newPosition, SceneObjectGroup grp, bool silent)
2515 {
2516 //m_log.Debug(" >>> CrossPrimGroupIntoNewRegion <<<");
2517  
2518 bool successYN = false;
2519 grp.RootPart.ClearUpdateSchedule();
2520 //int primcrossingXMLmethod = 0;
2521  
2522 if (destination != null)
2523 {
2524 //string objectState = grp.GetStateSnapshot();
2525  
2526 //successYN
2527 // = m_sceneGridService.PrimCrossToNeighboringRegion(
2528 // newRegionHandle, grp.UUID, m_serialiser.SaveGroupToXml2(grp), primcrossingXMLmethod);
2529 //if (successYN && (objectState != "") && m_allowScriptCrossings)
2530 //{
2531 // successYN = m_sceneGridService.PrimCrossToNeighboringRegion(
2532 // newRegionHandle, grp.UUID, objectState, 100);
2533 //}
2534  
2535 //// And the new channel...
2536 //if (m_interregionCommsOut != null)
2537 // successYN = m_interregionCommsOut.SendCreateObject(newRegionHandle, grp, true);
2538 if (Scene.SimulationService != null)
2539 successYN = Scene.SimulationService.CreateObject(destination, newPosition, grp, true);
2540  
2541 if (successYN)
2542 {
2543 // We remove the object here
2544 try
2545 {
2546 grp.Scene.DeleteSceneObject(grp, silent);
2547 }
2548 catch (Exception e)
2549 {
2550 m_log.ErrorFormat(
2551 "[ENTITY TRANSFER MODULE]: Exception deleting the old object left behind on a border crossing for {0}, {1}",
2552 grp, e);
2553 }
2554 }
2555 else
2556 {
2557 if (!grp.IsDeleted)
2558 {
2559 PhysicsActor pa = grp.RootPart.PhysActor;
2560 if (pa != null)
2561 pa.CrossingFailure();
2562 }
2563  
2564 m_log.ErrorFormat("[ENTITY TRANSFER MODULE]: Prim crossing failed for {0}", grp);
2565 }
2566 }
2567 else
2568 {
2569 m_log.Error("[ENTITY TRANSFER MODULE]: destination was unexpectedly null in Scene.CrossPrimGroupIntoNewRegion()");
2570 }
2571  
2572 return successYN;
2573 }
2574  
2575 /// <summary>
2576 /// Cross the attachments for an avatar into the destination region.
2577 /// </summary>
2578 /// <remarks>
2579 /// This is only invoked for simulators released prior to April 2011. Versions of OpenSimulator since then
2580 /// transfer attachments in one go as part of the ChildAgentDataUpdate data passed in the update agent call.
2581 /// </remarks>
2582 /// <param name='destination'></param>
2583 /// <param name='sp'></param>
2584 /// <param name='silent'></param>
2585 protected void CrossAttachmentsIntoNewRegion(GridRegion destination, ScenePresence sp, bool silent)
2586 {
2587 List<SceneObjectGroup> attachments = sp.GetAttachments();
2588  
2589 // m_log.DebugFormat(
2590 // "[ENTITY TRANSFER MODULE]: Crossing {0} attachments into {1} for {2}",
2591 // m_attachments.Count, destination.RegionName, sp.Name);
2592  
2593 foreach (SceneObjectGroup gobj in attachments)
2594 {
2595 // If the prim group is null then something must have happened to it!
2596 if (gobj != null && !gobj.IsDeleted)
2597 {
2598 SceneObjectGroup clone = (SceneObjectGroup)gobj.CloneForNewScene();
2599 clone.RootPart.GroupPosition = gobj.RootPart.AttachedPos;
2600 clone.IsAttachment = false;
2601  
2602 //gobj.RootPart.LastOwnerID = gobj.GetFromAssetID();
2603 m_log.DebugFormat(
2604 "[ENTITY TRANSFER MODULE]: Sending attachment {0} to region {1}",
2605 clone.UUID, destination.RegionName);
2606  
2607 CrossPrimGroupIntoNewRegion(destination, Vector3.Zero, clone, silent);
2608 }
2609 }
2610  
2611 sp.ClearAttachments();
2612 }
2613  
2614 #endregion
2615  
2616 #region Misc
2617  
2618 public bool IsInTransit(UUID id)
2619 {
2620 return m_entityTransferStateMachine.GetAgentTransferState(id) != null;
2621 }
2622  
2623 protected void ReInstantiateScripts(ScenePresence sp)
2624 {
2625 int i = 0;
2626 if (sp.InTransitScriptStates.Count > 0)
2627 {
2628 List<SceneObjectGroup> attachments = sp.GetAttachments();
2629  
2630 foreach (SceneObjectGroup sog in attachments)
2631 {
2632 if (i < sp.InTransitScriptStates.Count)
2633 {
2634 sog.SetState(sp.InTransitScriptStates[i++], sp.Scene);
2635 sog.CreateScriptInstances(0, false, sp.Scene.DefaultScriptEngine, 0);
2636 sog.ResumeScripts();
2637 }
2638 else
2639 m_log.ErrorFormat(
2640 "[ENTITY TRANSFER MODULE]: InTransitScriptStates.Count={0} smaller than Attachments.Count={1}",
2641 sp.InTransitScriptStates.Count, attachments.Count);
2642 }
2643  
2644 sp.InTransitScriptStates.Clear();
2645 }
2646 }
2647 #endregion
2648  
2649 }
2650 }