EntityTransferModule.cs 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861
  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. using System;
  28. using System.Collections.Generic;
  29. using System.Net;
  30. using System.Reflection;
  31. using System.Threading;
  32. using OpenSim.Framework;
  33. using OpenSim.Framework.Capabilities;
  34. using OpenSim.Framework.Client;
  35. using OpenSim.Region.Framework.Interfaces;
  36. using OpenSim.Region.Framework.Scenes;
  37. using OpenSim.Services.Interfaces;
  38. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  39. using OpenMetaverse;
  40. using log4net;
  41. using Nini.Config;
  42. namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
  43. {
  44. public class EntityTransferModule : ISharedRegionModule, IEntityTransferModule
  45. {
  46. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  47. /// <summary>
  48. /// The maximum distance, in standard region units (256m) that an agent is allowed to transfer.
  49. /// </summary>
  50. private int m_MaxTransferDistance = 4095;
  51. public int MaxTransferDistance
  52. {
  53. get { return m_MaxTransferDistance; }
  54. set { m_MaxTransferDistance = value; }
  55. }
  56. protected bool m_Enabled = false;
  57. protected Scene m_aScene;
  58. protected List<Scene> m_Scenes = new List<Scene>();
  59. protected List<UUID> m_agentsInTransit;
  60. private ExpiringCache<UUID, ExpiringCache<ulong, DateTime>> m_bannedRegions =
  61. new ExpiringCache<UUID, ExpiringCache<ulong, DateTime>>();
  62. #region ISharedRegionModule
  63. public Type ReplaceableInterface
  64. {
  65. get { return null; }
  66. }
  67. public virtual string Name
  68. {
  69. get { return "BasicEntityTransferModule"; }
  70. }
  71. public virtual void Initialise(IConfigSource source)
  72. {
  73. IConfig moduleConfig = source.Configs["Modules"];
  74. if (moduleConfig != null)
  75. {
  76. string name = moduleConfig.GetString("EntityTransferModule", "");
  77. if (name == Name)
  78. {
  79. InitialiseCommon(source);
  80. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: {0} enabled.", Name);
  81. }
  82. }
  83. }
  84. /// <summary>
  85. /// Initialize config common for this module and any descendents.
  86. /// </summary>
  87. /// <param name="source"></param>
  88. protected virtual void InitialiseCommon(IConfigSource source)
  89. {
  90. IConfig transferConfig = source.Configs["EntityTransfer"];
  91. if (transferConfig != null)
  92. MaxTransferDistance = transferConfig.GetInt("max_distance", 4095);
  93. m_agentsInTransit = new List<UUID>();
  94. m_Enabled = true;
  95. }
  96. public virtual void PostInitialise()
  97. {
  98. }
  99. public virtual void AddRegion(Scene scene)
  100. {
  101. if (!m_Enabled)
  102. return;
  103. if (m_aScene == null)
  104. m_aScene = scene;
  105. m_Scenes.Add(scene);
  106. scene.RegisterModuleInterface<IEntityTransferModule>(this);
  107. scene.EventManager.OnNewClient += OnNewClient;
  108. }
  109. protected virtual void OnNewClient(IClientAPI client)
  110. {
  111. client.OnTeleportHomeRequest += TeleportHome;
  112. client.OnTeleportLandmarkRequest += RequestTeleportLandmark;
  113. }
  114. public virtual void Close()
  115. {
  116. if (!m_Enabled)
  117. return;
  118. }
  119. public virtual void RemoveRegion(Scene scene)
  120. {
  121. if (!m_Enabled)
  122. return;
  123. if (scene == m_aScene)
  124. m_aScene = null;
  125. m_Scenes.Remove(scene);
  126. }
  127. public virtual void RegionLoaded(Scene scene)
  128. {
  129. if (!m_Enabled)
  130. return;
  131. }
  132. #endregion
  133. #region Agent Teleports
  134. public void Teleport(ScenePresence sp, ulong regionHandle, Vector3 position, Vector3 lookAt, uint teleportFlags)
  135. {
  136. if (!sp.Scene.Permissions.CanTeleport(sp.UUID))
  137. return;
  138. IEventQueue eq = sp.Scene.RequestModuleInterface<IEventQueue>();
  139. // Reset animations; the viewer does that in teleports.
  140. sp.Animator.ResetAnimations();
  141. try
  142. {
  143. if (regionHandle == sp.Scene.RegionInfo.RegionHandle)
  144. {
  145. m_log.DebugFormat(
  146. "[ENTITY TRANSFER MODULE]: RequestTeleportToLocation {0} within {1}",
  147. position, sp.Scene.RegionInfo.RegionName);
  148. // Teleport within the same region
  149. if (IsOutsideRegion(sp.Scene, position) || position.Z < 0)
  150. {
  151. Vector3 emergencyPos = new Vector3(128, 128, 128);
  152. m_log.WarnFormat(
  153. "[ENTITY TRANSFER MODULE]: RequestTeleportToLocation() was given an illegal position of {0} for avatar {1}, {2}. Substituting {3}",
  154. position, sp.Name, sp.UUID, emergencyPos);
  155. position = emergencyPos;
  156. }
  157. // TODO: Get proper AVG Height
  158. float localAVHeight = 1.56f;
  159. float posZLimit = 22;
  160. // TODO: Check other Scene HeightField
  161. if (position.X > 0 && position.X <= (int)Constants.RegionSize && position.Y > 0 && position.Y <= (int)Constants.RegionSize)
  162. {
  163. posZLimit = (float)sp.Scene.Heightmap[(int)position.X, (int)position.Y];
  164. }
  165. float newPosZ = posZLimit + localAVHeight;
  166. if (posZLimit >= (position.Z - (localAVHeight / 2)) && !(Single.IsInfinity(newPosZ) || Single.IsNaN(newPosZ)))
  167. {
  168. position.Z = newPosZ;
  169. }
  170. sp.ControllingClient.SendTeleportStart(teleportFlags);
  171. sp.ControllingClient.SendLocalTeleport(position, lookAt, teleportFlags);
  172. sp.Teleport(position);
  173. foreach (SceneObjectGroup grp in sp.Attachments)
  174. sp.Scene.EventManager.TriggerOnScriptChangedEvent(grp.LocalId, (uint)Changed.TELEPORT);
  175. }
  176. else // Another region possibly in another simulator
  177. {
  178. uint x = 0, y = 0;
  179. Utils.LongToUInts(regionHandle, out x, out y);
  180. GridRegion reg = m_aScene.GridService.GetRegionByPosition(sp.Scene.RegionInfo.ScopeID, (int)x, (int)y);
  181. if (reg != null)
  182. {
  183. GridRegion finalDestination = GetFinalDestination(reg);
  184. if (finalDestination == null)
  185. {
  186. m_log.WarnFormat("[ENTITY TRANSFER MODULE]: Final destination is having problems. Unable to teleport agent.");
  187. sp.ControllingClient.SendTeleportFailed("Problem at destination");
  188. return;
  189. }
  190. uint curX = 0, curY = 0;
  191. Utils.LongToUInts(sp.Scene.RegionInfo.RegionHandle, out curX, out curY);
  192. int curCellX = (int)(curX / Constants.RegionSize);
  193. int curCellY = (int)(curY / Constants.RegionSize);
  194. int destCellX = (int)(finalDestination.RegionLocX / Constants.RegionSize);
  195. int destCellY = (int)(finalDestination.RegionLocY / Constants.RegionSize);
  196. // m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Source co-ords are x={0} y={1}", curRegionX, curRegionY);
  197. //
  198. // m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Final dest is x={0} y={1} {2}@{3}",
  199. // destRegionX, destRegionY, finalDestination.RegionID, finalDestination.ServerURI);
  200. // Check that these are not the same coordinates
  201. if (finalDestination.RegionLocX == sp.Scene.RegionInfo.RegionLocX &&
  202. finalDestination.RegionLocY == sp.Scene.RegionInfo.RegionLocY)
  203. {
  204. // Can't do. Viewer crashes
  205. sp.ControllingClient.SendTeleportFailed("Space warp! You would crash. Move to a different region and try again.");
  206. return;
  207. }
  208. if (Math.Abs(curCellX - destCellX) > MaxTransferDistance || Math.Abs(curCellY - destCellY) > MaxTransferDistance)
  209. {
  210. sp.ControllingClient.SendTeleportFailed(
  211. string.Format(
  212. "Can't teleport to {0} ({1},{2}) from {3} ({4},{5}), destination is more than {6} regions way",
  213. finalDestination.RegionName, destCellX, destCellY,
  214. sp.Scene.RegionInfo.RegionName, curCellX, curCellY,
  215. MaxTransferDistance));
  216. return;
  217. }
  218. //
  219. // This is it
  220. //
  221. DoTeleport(sp, reg, finalDestination, position, lookAt, teleportFlags, eq);
  222. //
  223. //
  224. //
  225. }
  226. else
  227. {
  228. // TP to a place that doesn't exist (anymore)
  229. // Inform the viewer about that
  230. sp.ControllingClient.SendTeleportFailed("The region you tried to teleport to doesn't exist anymore");
  231. // and set the map-tile to '(Offline)'
  232. uint regX, regY;
  233. Utils.LongToUInts(regionHandle, out regX, out regY);
  234. MapBlockData block = new MapBlockData();
  235. block.X = (ushort)(regX / Constants.RegionSize);
  236. block.Y = (ushort)(regY / Constants.RegionSize);
  237. block.Access = 254; // == not there
  238. List<MapBlockData> blocks = new List<MapBlockData>();
  239. blocks.Add(block);
  240. sp.ControllingClient.SendMapBlock(blocks, 0);
  241. }
  242. }
  243. }
  244. catch (Exception e)
  245. {
  246. m_log.WarnFormat("[ENTITY TRANSFER MODULE]: Exception on teleport: {0} {1}", e.Message, e.StackTrace);
  247. sp.ControllingClient.SendTeleportFailed("Internal error");
  248. }
  249. }
  250. public void DoTeleport(ScenePresence sp, GridRegion reg, GridRegion finalDestination, Vector3 position, Vector3 lookAt, uint teleportFlags, IEventQueue eq)
  251. {
  252. if (reg == null || finalDestination == null)
  253. {
  254. sp.ControllingClient.SendTeleportFailed("Unable to locate destination");
  255. return;
  256. }
  257. m_log.DebugFormat(
  258. "[ENTITY TRANSFER MODULE]: Request Teleport to {0} ({1}) {2}/{3}",
  259. reg.ServerURI, finalDestination.ServerURI, finalDestination.RegionName, position);
  260. uint newRegionX = (uint)(reg.RegionHandle >> 40);
  261. uint newRegionY = (((uint)(reg.RegionHandle)) >> 8);
  262. uint oldRegionX = (uint)(sp.Scene.RegionInfo.RegionHandle >> 40);
  263. uint oldRegionY = (((uint)(sp.Scene.RegionInfo.RegionHandle)) >> 8);
  264. ulong destinationHandle = finalDestination.RegionHandle;
  265. // Let's do DNS resolution only once in this process, please!
  266. // This may be a costly operation. The reg.ExternalEndPoint field is not a passive field,
  267. // it's actually doing a lot of work.
  268. IPEndPoint endPoint = finalDestination.ExternalEndPoint;
  269. if (endPoint.Address != null)
  270. {
  271. // Fixing a bug where teleporting while sitting results in the avatar ending up removed from
  272. // both regions
  273. if (sp.ParentID != (uint)0)
  274. sp.StandUp();
  275. if (!sp.ValidateAttachments())
  276. {
  277. sp.ControllingClient.SendTeleportFailed("Inconsistent attachment state");
  278. return;
  279. }
  280. string reason;
  281. string version;
  282. if (!m_aScene.SimulationService.QueryAccess(finalDestination, sp.ControllingClient.AgentId, Vector3.Zero, out version, out reason))
  283. {
  284. sp.ControllingClient.SendTeleportFailed("Teleport failed: " + reason);
  285. return;
  286. }
  287. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Destination is running version {0}", version);
  288. sp.ControllingClient.SendTeleportStart(teleportFlags);
  289. // the avatar.Close below will clear the child region list. We need this below for (possibly)
  290. // closing the child agents, so save it here (we need a copy as it is Clear()-ed).
  291. //List<ulong> childRegions = new List<ulong>(avatar.GetKnownRegionList());
  292. // Compared to ScenePresence.CrossToNewRegion(), there's no obvious code to handle a teleport
  293. // failure at this point (unlike a border crossing failure). So perhaps this can never fail
  294. // once we reach here...
  295. //avatar.Scene.RemoveCapsHandler(avatar.UUID);
  296. string capsPath = String.Empty;
  297. AgentCircuitData currentAgentCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
  298. AgentCircuitData agentCircuit = sp.ControllingClient.RequestClientInfo();
  299. agentCircuit.startpos = position;
  300. agentCircuit.child = true;
  301. agentCircuit.Appearance = sp.Appearance;
  302. if (currentAgentCircuit != null)
  303. {
  304. agentCircuit.ServiceURLs = currentAgentCircuit.ServiceURLs;
  305. agentCircuit.IPAddress = currentAgentCircuit.IPAddress;
  306. agentCircuit.Viewer = currentAgentCircuit.Viewer;
  307. agentCircuit.Channel = currentAgentCircuit.Channel;
  308. agentCircuit.Mac = currentAgentCircuit.Mac;
  309. agentCircuit.Id0 = currentAgentCircuit.Id0;
  310. }
  311. if (NeedsNewAgent(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY))
  312. {
  313. // brand new agent, let's create a new caps seed
  314. agentCircuit.CapsPath = CapsUtil.GetRandomCapsObjectPath();
  315. }
  316. // Let's create an agent there if one doesn't exist yet.
  317. bool logout = false;
  318. if (!CreateAgent(sp, reg, finalDestination, agentCircuit, teleportFlags, out reason, out logout))
  319. {
  320. sp.ControllingClient.SendTeleportFailed(String.Format("Destination refused: {0}",
  321. reason));
  322. return;
  323. }
  324. // OK, it got this agent. Let's close some child agents
  325. sp.CloseChildAgents(newRegionX, newRegionY);
  326. IClientIPEndpoint ipepClient;
  327. if (NeedsNewAgent(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY))
  328. {
  329. //sp.ControllingClient.SendTeleportProgress(teleportFlags, "Creating agent...");
  330. #region IP Translation for NAT
  331. // Uses ipepClient above
  332. if (sp.ClientView.TryGet(out ipepClient))
  333. {
  334. endPoint.Address = NetworkUtil.GetIPFor(ipepClient.EndPoint, endPoint.Address);
  335. }
  336. #endregion
  337. capsPath = finalDestination.ServerURI + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
  338. if (eq != null)
  339. {
  340. eq.EnableSimulator(destinationHandle, endPoint, sp.UUID);
  341. // ES makes the client send a UseCircuitCode message to the destination,
  342. // which triggers a bunch of things there.
  343. // So let's wait
  344. Thread.Sleep(200);
  345. eq.EstablishAgentCommunication(sp.UUID, endPoint, capsPath);
  346. }
  347. else
  348. {
  349. sp.ControllingClient.InformClientOfNeighbour(destinationHandle, endPoint);
  350. }
  351. }
  352. else
  353. {
  354. agentCircuit.CapsPath = sp.Scene.CapsModule.GetChildSeed(sp.UUID, reg.RegionHandle);
  355. capsPath = finalDestination.ServerURI + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
  356. }
  357. SetInTransit(sp.UUID);
  358. // Let's send a full update of the agent. This is a synchronous call.
  359. AgentData agent = new AgentData();
  360. sp.CopyTo(agent);
  361. agent.Position = position;
  362. SetCallbackURL(agent, sp.Scene.RegionInfo);
  363. //sp.ControllingClient.SendTeleportProgress(teleportFlags, "Updating agent...");
  364. if (!UpdateAgent(reg, finalDestination, agent))
  365. {
  366. // Region doesn't take it
  367. m_log.WarnFormat(
  368. "[ENTITY TRANSFER MODULE]: UpdateAgent failed on teleport of {0} to {1}. Returning avatar to source region.",
  369. sp.Name, finalDestination.RegionName);
  370. Fail(sp, finalDestination);
  371. return;
  372. }
  373. sp.ControllingClient.SendTeleportProgress(teleportFlags | (uint)TeleportFlags.DisableCancel, "sending_dest");
  374. m_log.DebugFormat(
  375. "[ENTITY TRANSFER MODULE]: Sending new CAPS seed url {0} to client {1}", capsPath, sp.UUID);
  376. if (eq != null)
  377. {
  378. eq.TeleportFinishEvent(destinationHandle, 13, endPoint,
  379. 0, teleportFlags, capsPath, sp.UUID);
  380. }
  381. else
  382. {
  383. sp.ControllingClient.SendRegionTeleport(destinationHandle, 13, endPoint, 4,
  384. teleportFlags, capsPath);
  385. }
  386. // Let's set this to true tentatively. This does not trigger OnChildAgent
  387. sp.IsChildAgent = true;
  388. // TeleportFinish makes the client send CompleteMovementIntoRegion (at the destination), which
  389. // trigers a whole shebang of things there, including MakeRoot. So let's wait for confirmation
  390. // that the client contacted the destination before we close things here.
  391. if (!WaitForCallback(sp.UUID))
  392. {
  393. m_log.WarnFormat(
  394. "[ENTITY TRANSFER MODULE]: Teleport of {0} to {1} failed due to no callback from destination region. Returning avatar to source region.",
  395. sp.Name, finalDestination.RegionName);
  396. Fail(sp, finalDestination);
  397. return;
  398. }
  399. // For backwards compatibility
  400. if (version == "Unknown" || version == string.Empty)
  401. {
  402. // CrossAttachmentsIntoNewRegion is a synchronous call. We shouldn't need to wait after it
  403. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Old simulator, sending attachments one by one...");
  404. CrossAttachmentsIntoNewRegion(finalDestination, sp, true);
  405. }
  406. // May need to logout or other cleanup
  407. AgentHasMovedAway(sp, logout);
  408. // Well, this is it. The agent is over there.
  409. KillEntity(sp.Scene, sp.LocalId);
  410. // Now let's make it officially a child agent
  411. sp.MakeChildAgent();
  412. sp.Scene.CleanDroppedAttachments();
  413. // Finally, let's close this previously-known-as-root agent, when the jump is outside the view zone
  414. if (NeedsClosing(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY, reg))
  415. {
  416. Thread.Sleep(5000);
  417. sp.Close();
  418. sp.Scene.IncomingCloseAgent(sp.UUID);
  419. }
  420. else
  421. // now we have a child agent in this region.
  422. sp.Reset();
  423. // REFACTORING PROBLEM. Well, not a problem, but this method is HORRIBLE!
  424. if (sp.Scene.NeedSceneCacheClear(sp.UUID))
  425. {
  426. m_log.DebugFormat(
  427. "[ENTITY TRANSFER MODULE]: User {0} is going to another region, profile cache removed",
  428. sp.UUID);
  429. }
  430. }
  431. else
  432. {
  433. sp.ControllingClient.SendTeleportFailed("Remote Region appears to be down");
  434. }
  435. }
  436. private void Fail(ScenePresence sp, GridRegion finalDestination)
  437. {
  438. // Client never contacted destination. Let's restore everything back
  439. sp.ControllingClient.SendTeleportFailed("Problems connecting to destination.");
  440. // Fail. Reset it back
  441. sp.IsChildAgent = false;
  442. ReInstantiateScripts(sp);
  443. ResetFromTransit(sp.UUID);
  444. EnableChildAgents(sp);
  445. // Finally, kill the agent we just created at the destination.
  446. m_aScene.SimulationService.CloseAgent(finalDestination, sp.UUID);
  447. }
  448. protected virtual bool CreateAgent(ScenePresence sp, GridRegion reg, GridRegion finalDestination, AgentCircuitData agentCircuit, uint teleportFlags, out string reason, out bool logout)
  449. {
  450. logout = false;
  451. return m_aScene.SimulationService.CreateAgent(finalDestination, agentCircuit, teleportFlags, out reason);
  452. }
  453. protected virtual bool UpdateAgent(GridRegion reg, GridRegion finalDestination, AgentData agent)
  454. {
  455. return m_aScene.SimulationService.UpdateAgent(finalDestination, agent);
  456. }
  457. protected virtual void SetCallbackURL(AgentData agent, RegionInfo region)
  458. {
  459. agent.CallbackURI = region.ServerURI + "agent/" + agent.AgentID.ToString() + "/" + region.RegionID.ToString() + "/release/";
  460. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Set callback URL to {0}", agent.CallbackURI);
  461. }
  462. protected virtual void AgentHasMovedAway(ScenePresence sp, bool logout)
  463. {
  464. foreach (SceneObjectGroup sop in sp.Attachments)
  465. {
  466. sop.Scene.DeleteSceneObject(sop, true);
  467. }
  468. sp.Attachments.Clear();
  469. }
  470. protected void KillEntity(Scene scene, uint localID)
  471. {
  472. scene.SendKillObject(localID);
  473. }
  474. protected virtual GridRegion GetFinalDestination(GridRegion region)
  475. {
  476. return region;
  477. }
  478. protected virtual bool NeedsNewAgent(float drawdist, uint oldRegionX, uint newRegionX, uint oldRegionY, uint newRegionY)
  479. {
  480. return Util.IsOutsideView(drawdist, oldRegionX, newRegionX, oldRegionY, newRegionY);
  481. }
  482. protected virtual bool NeedsClosing(float drawdist, uint oldRegionX, uint newRegionX, uint oldRegionY, uint newRegionY, GridRegion reg)
  483. {
  484. return Util.IsOutsideView(drawdist, oldRegionX, newRegionX, oldRegionY, newRegionY);
  485. }
  486. protected virtual bool IsOutsideRegion(Scene s, Vector3 pos)
  487. {
  488. if (s.TestBorderCross(pos, Cardinals.N))
  489. return true;
  490. if (s.TestBorderCross(pos, Cardinals.S))
  491. return true;
  492. if (s.TestBorderCross(pos, Cardinals.E))
  493. return true;
  494. if (s.TestBorderCross(pos, Cardinals.W))
  495. return true;
  496. return false;
  497. }
  498. #endregion
  499. #region Landmark Teleport
  500. /// <summary>
  501. /// Tries to teleport agent to landmark.
  502. /// </summary>
  503. /// <param name="remoteClient"></param>
  504. /// <param name="regionHandle"></param>
  505. /// <param name="position"></param>
  506. public virtual void RequestTeleportLandmark(IClientAPI remoteClient, AssetLandmark lm)
  507. {
  508. GridRegion info = m_aScene.GridService.GetRegionByUUID(UUID.Zero, lm.RegionID);
  509. if (info == null)
  510. {
  511. // can't find the region: Tell viewer and abort
  512. remoteClient.SendTeleportFailed("The teleport destination could not be found.");
  513. return;
  514. }
  515. ((Scene)(remoteClient.Scene)).RequestTeleportLocation(remoteClient, info.RegionHandle, lm.Position,
  516. Vector3.Zero, (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaLandmark));
  517. }
  518. #endregion
  519. #region Teleport Home
  520. public virtual void TeleportHome(UUID id, IClientAPI client)
  521. {
  522. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Request to teleport {0} {1} home", client.FirstName, client.LastName);
  523. //OpenSim.Services.Interfaces.PresenceInfo pinfo = m_aScene.PresenceService.GetAgent(client.SessionId);
  524. GridUserInfo uinfo = m_aScene.GridUserService.GetGridUserInfo(client.AgentId.ToString());
  525. if (uinfo != null)
  526. {
  527. GridRegion regionInfo = m_aScene.GridService.GetRegionByUUID(UUID.Zero, uinfo.HomeRegionID);
  528. if (regionInfo == null)
  529. {
  530. // can't find the Home region: Tell viewer and abort
  531. client.SendTeleportFailed("Your home region could not be found.");
  532. return;
  533. }
  534. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: User's home region is {0} {1} ({2}-{3})",
  535. regionInfo.RegionName, regionInfo.RegionID, regionInfo.RegionLocX / Constants.RegionSize, regionInfo.RegionLocY / Constants.RegionSize);
  536. // a little eekie that this goes back to Scene and with a forced cast, will fix that at some point...
  537. ((Scene)(client.Scene)).RequestTeleportLocation(
  538. client, regionInfo.RegionHandle, uinfo.HomePosition, uinfo.HomeLookAt,
  539. (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaHome));
  540. }
  541. }
  542. #endregion
  543. #region Agent Crossings
  544. public bool Cross(ScenePresence agent, bool isFlying)
  545. {
  546. Scene scene = agent.Scene;
  547. Vector3 pos = agent.AbsolutePosition;
  548. Vector3 newpos = new Vector3(pos.X, pos.Y, pos.Z);
  549. uint neighbourx = scene.RegionInfo.RegionLocX;
  550. uint neighboury = scene.RegionInfo.RegionLocY;
  551. const float boundaryDistance = 1.7f;
  552. Vector3 northCross = new Vector3(0, boundaryDistance, 0);
  553. Vector3 southCross = new Vector3(0, -1 * boundaryDistance, 0);
  554. Vector3 eastCross = new Vector3(boundaryDistance, 0, 0);
  555. Vector3 westCross = new Vector3(-1 * boundaryDistance, 0, 0);
  556. // distance to edge that will trigger crossing
  557. // distance into new region to place avatar
  558. const float enterDistance = 0.5f;
  559. if (scene.TestBorderCross(pos + westCross, Cardinals.W))
  560. {
  561. if (scene.TestBorderCross(pos + northCross, Cardinals.N))
  562. {
  563. Border b = scene.GetCrossedBorder(pos + northCross, Cardinals.N);
  564. neighboury += (uint)(int)(b.BorderLine.Z / (int)Constants.RegionSize);
  565. }
  566. else if (scene.TestBorderCross(pos + southCross, Cardinals.S))
  567. {
  568. Border b = scene.GetCrossedBorder(pos + southCross, Cardinals.S);
  569. if (b.TriggerRegionX == 0 && b.TriggerRegionY == 0)
  570. {
  571. neighboury--;
  572. newpos.Y = Constants.RegionSize - enterDistance;
  573. }
  574. else
  575. {
  576. agent.InTransit();
  577. neighboury = b.TriggerRegionY;
  578. neighbourx = b.TriggerRegionX;
  579. Vector3 newposition = pos;
  580. newposition.X += (scene.RegionInfo.RegionLocX - neighbourx) * Constants.RegionSize;
  581. newposition.Y += (scene.RegionInfo.RegionLocY - neighboury) * Constants.RegionSize;
  582. agent.ControllingClient.SendAgentAlertMessage(
  583. String.Format("Moving you to region {0},{1}", neighbourx, neighboury), false);
  584. InformClientToInitateTeleportToLocation(agent, neighbourx, neighboury, newposition, scene);
  585. return true;
  586. }
  587. }
  588. Border ba = scene.GetCrossedBorder(pos + westCross, Cardinals.W);
  589. if (ba.TriggerRegionX == 0 && ba.TriggerRegionY == 0)
  590. {
  591. neighbourx--;
  592. newpos.X = Constants.RegionSize - enterDistance;
  593. }
  594. else
  595. {
  596. agent.InTransit();
  597. neighboury = ba.TriggerRegionY;
  598. neighbourx = ba.TriggerRegionX;
  599. Vector3 newposition = pos;
  600. newposition.X += (scene.RegionInfo.RegionLocX - neighbourx) * Constants.RegionSize;
  601. newposition.Y += (scene.RegionInfo.RegionLocY - neighboury) * Constants.RegionSize;
  602. agent.ControllingClient.SendAgentAlertMessage(
  603. String.Format("Moving you to region {0},{1}", neighbourx, neighboury), false);
  604. InformClientToInitateTeleportToLocation(agent, neighbourx, neighboury, newposition, scene);
  605. return true;
  606. }
  607. }
  608. else if (scene.TestBorderCross(pos + eastCross, Cardinals.E))
  609. {
  610. Border b = scene.GetCrossedBorder(pos + eastCross, Cardinals.E);
  611. neighbourx += (uint)(int)(b.BorderLine.Z / (int)Constants.RegionSize);
  612. newpos.X = enterDistance;
  613. if (scene.TestBorderCross(pos + southCross, Cardinals.S))
  614. {
  615. Border ba = scene.GetCrossedBorder(pos + southCross, Cardinals.S);
  616. if (ba.TriggerRegionX == 0 && ba.TriggerRegionY == 0)
  617. {
  618. neighboury--;
  619. newpos.Y = Constants.RegionSize - enterDistance;
  620. }
  621. else
  622. {
  623. agent.InTransit();
  624. neighboury = ba.TriggerRegionY;
  625. neighbourx = ba.TriggerRegionX;
  626. Vector3 newposition = pos;
  627. newposition.X += (scene.RegionInfo.RegionLocX - neighbourx) * Constants.RegionSize;
  628. newposition.Y += (scene.RegionInfo.RegionLocY - neighboury) * Constants.RegionSize;
  629. agent.ControllingClient.SendAgentAlertMessage(
  630. String.Format("Moving you to region {0},{1}", neighbourx, neighboury), false);
  631. InformClientToInitateTeleportToLocation(agent, neighbourx, neighboury, newposition, scene);
  632. return true;
  633. }
  634. }
  635. else if (scene.TestBorderCross(pos + northCross, Cardinals.N))
  636. {
  637. Border c = scene.GetCrossedBorder(pos + northCross, Cardinals.N);
  638. neighboury += (uint)(int)(c.BorderLine.Z / (int)Constants.RegionSize);
  639. newpos.Y = enterDistance;
  640. }
  641. }
  642. else if (scene.TestBorderCross(pos + southCross, Cardinals.S))
  643. {
  644. Border b = scene.GetCrossedBorder(pos + southCross, Cardinals.S);
  645. if (b.TriggerRegionX == 0 && b.TriggerRegionY == 0)
  646. {
  647. neighboury--;
  648. newpos.Y = Constants.RegionSize - enterDistance;
  649. }
  650. else
  651. {
  652. agent.InTransit();
  653. neighboury = b.TriggerRegionY;
  654. neighbourx = b.TriggerRegionX;
  655. Vector3 newposition = pos;
  656. newposition.X += (scene.RegionInfo.RegionLocX - neighbourx) * Constants.RegionSize;
  657. newposition.Y += (scene.RegionInfo.RegionLocY - neighboury) * Constants.RegionSize;
  658. agent.ControllingClient.SendAgentAlertMessage(
  659. String.Format("Moving you to region {0},{1}", neighbourx, neighboury), false);
  660. InformClientToInitateTeleportToLocation(agent, neighbourx, neighboury, newposition, scene);
  661. return true;
  662. }
  663. }
  664. else if (scene.TestBorderCross(pos + northCross, Cardinals.N))
  665. {
  666. Border b = scene.GetCrossedBorder(pos + northCross, Cardinals.N);
  667. neighboury += (uint)(int)(b.BorderLine.Z / (int)Constants.RegionSize);
  668. newpos.Y = enterDistance;
  669. }
  670. /*
  671. if (pos.X < boundaryDistance) //West
  672. {
  673. neighbourx--;
  674. newpos.X = Constants.RegionSize - enterDistance;
  675. }
  676. else if (pos.X > Constants.RegionSize - boundaryDistance) // East
  677. {
  678. neighbourx++;
  679. newpos.X = enterDistance;
  680. }
  681. if (pos.Y < boundaryDistance) // South
  682. {
  683. neighboury--;
  684. newpos.Y = Constants.RegionSize - enterDistance;
  685. }
  686. else if (pos.Y > Constants.RegionSize - boundaryDistance) // North
  687. {
  688. neighboury++;
  689. newpos.Y = enterDistance;
  690. }
  691. */
  692. ulong neighbourHandle = Utils.UIntsToLong((uint)(neighbourx * Constants.RegionSize), (uint)(neighboury * Constants.RegionSize));
  693. int x = (int)(neighbourx * Constants.RegionSize), y = (int)(neighboury * Constants.RegionSize);
  694. ExpiringCache<ulong, DateTime> r;
  695. DateTime banUntil;
  696. if (m_bannedRegions.TryGetValue(agent.ControllingClient.AgentId, out r))
  697. {
  698. if (r.TryGetValue(neighbourHandle, out banUntil))
  699. {
  700. if (DateTime.Now < banUntil)
  701. return false;
  702. r.Remove(neighbourHandle);
  703. }
  704. }
  705. else
  706. {
  707. r = null;
  708. }
  709. GridRegion neighbourRegion = scene.GridService.GetRegionByPosition(scene.RegionInfo.ScopeID, (int)x, (int)y);
  710. string reason;
  711. string version;
  712. if (!scene.SimulationService.QueryAccess(neighbourRegion, agent.ControllingClient.AgentId, newpos, out version, out reason))
  713. {
  714. agent.ControllingClient.SendAlertMessage("Cannot region cross into banned parcel");
  715. if (r == null)
  716. {
  717. r = new ExpiringCache<ulong, DateTime>();
  718. r.Add(neighbourHandle, DateTime.Now + TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(15));
  719. m_bannedRegions.Add(agent.ControllingClient.AgentId, r, TimeSpan.FromSeconds(45));
  720. }
  721. else
  722. {
  723. r.Add(neighbourHandle, DateTime.Now + TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(15));
  724. }
  725. return false;
  726. }
  727. agent.InTransit();
  728. CrossAgentToNewRegionDelegate d = CrossAgentToNewRegionAsync;
  729. d.BeginInvoke(agent, newpos, neighbourx, neighboury, neighbourRegion, isFlying, version, CrossAgentToNewRegionCompleted, d);
  730. return true;
  731. }
  732. public delegate void InformClientToInitateTeleportToLocationDelegate(ScenePresence agent, uint regionX, uint regionY,
  733. Vector3 position,
  734. Scene initiatingScene);
  735. private void InformClientToInitateTeleportToLocation(ScenePresence agent, uint regionX, uint regionY, Vector3 position, Scene initiatingScene)
  736. {
  737. // This assumes that we know what our neighbours are.
  738. InformClientToInitateTeleportToLocationDelegate d = InformClientToInitiateTeleportToLocationAsync;
  739. d.BeginInvoke(agent, regionX, regionY, position, initiatingScene,
  740. InformClientToInitiateTeleportToLocationCompleted,
  741. d);
  742. }
  743. public void InformClientToInitiateTeleportToLocationAsync(ScenePresence agent, uint regionX, uint regionY, Vector3 position,
  744. Scene initiatingScene)
  745. {
  746. Thread.Sleep(10000);
  747. IMessageTransferModule im = initiatingScene.RequestModuleInterface<IMessageTransferModule>();
  748. if (im != null)
  749. {
  750. UUID gotoLocation = Util.BuildFakeParcelID(
  751. Util.UIntsToLong(
  752. (regionX *
  753. (uint)Constants.RegionSize),
  754. (regionY *
  755. (uint)Constants.RegionSize)),
  756. (uint)(int)position.X,
  757. (uint)(int)position.Y,
  758. (uint)(int)position.Z);
  759. GridInstantMessage m = new GridInstantMessage(initiatingScene, UUID.Zero,
  760. "Region", agent.UUID,
  761. (byte)InstantMessageDialog.GodLikeRequestTeleport, false,
  762. "", gotoLocation, false, new Vector3(127, 0, 0),
  763. new Byte[0]);
  764. im.SendInstantMessage(m, delegate(bool success)
  765. {
  766. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Client Initiating Teleport sending IM success = {0}", success);
  767. });
  768. }
  769. }
  770. private void InformClientToInitiateTeleportToLocationCompleted(IAsyncResult iar)
  771. {
  772. InformClientToInitateTeleportToLocationDelegate icon =
  773. (InformClientToInitateTeleportToLocationDelegate)iar.AsyncState;
  774. icon.EndInvoke(iar);
  775. }
  776. public delegate ScenePresence CrossAgentToNewRegionDelegate(ScenePresence agent, Vector3 pos, uint neighbourx, uint neighboury, GridRegion neighbourRegion, bool isFlying, string version);
  777. /// <summary>
  778. /// This Closes child agents on neighbouring regions
  779. /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
  780. /// </summary>
  781. protected ScenePresence CrossAgentToNewRegionAsync(ScenePresence agent, Vector3 pos, uint neighbourx, uint neighboury, GridRegion neighbourRegion, bool isFlying, string version)
  782. {
  783. ulong neighbourHandle = Utils.UIntsToLong((uint)(neighbourx * Constants.RegionSize), (uint)(neighboury * Constants.RegionSize));
  784. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Crossing agent {0} {1} to {2}-{3} running version {4}", agent.Firstname, agent.Lastname, neighbourx, neighboury, version);
  785. Scene m_scene = agent.Scene;
  786. if (neighbourRegion != null && agent.ValidateAttachments())
  787. {
  788. pos = pos + (agent.Velocity);
  789. SetInTransit(agent.UUID);
  790. AgentData cAgent = new AgentData();
  791. agent.CopyTo(cAgent);
  792. cAgent.Position = pos;
  793. if (isFlying)
  794. cAgent.ControlFlags |= (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY;
  795. cAgent.CallbackURI = m_scene.RegionInfo.ServerURI +
  796. "agent/" + agent.UUID.ToString() + "/" + m_scene.RegionInfo.RegionID.ToString() + "/release/";
  797. if (!m_scene.SimulationService.UpdateAgent(neighbourRegion, cAgent))
  798. {
  799. // region doesn't take it
  800. ReInstantiateScripts(agent);
  801. ResetFromTransit(agent.UUID);
  802. return agent;
  803. }
  804. // Next, let's close the child agent connections that are too far away.
  805. agent.CloseChildAgents(neighbourx, neighboury);
  806. //AgentCircuitData circuitdata = m_controllingClient.RequestClientInfo();
  807. agent.ControllingClient.RequestClientInfo();
  808. //m_log.Debug("BEFORE CROSS");
  809. //Scene.DumpChildrenSeeds(UUID);
  810. //DumpKnownRegions();
  811. string agentcaps;
  812. if (!agent.KnownRegions.TryGetValue(neighbourRegion.RegionHandle, out agentcaps))
  813. {
  814. m_log.ErrorFormat("[ENTITY TRANSFER MODULE]: No ENTITY TRANSFER MODULE information for region handle {0}, exiting CrossToNewRegion.",
  815. neighbourRegion.RegionHandle);
  816. return agent;
  817. }
  818. string capsPath = neighbourRegion.ServerURI + CapsUtil.GetCapsSeedPath(agentcaps);
  819. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Sending new CAPS seed url {0} to client {1}", capsPath, agent.UUID);
  820. IEventQueue eq = agent.Scene.RequestModuleInterface<IEventQueue>();
  821. if (eq != null)
  822. {
  823. eq.CrossRegion(neighbourHandle, pos, agent.Velocity, neighbourRegion.ExternalEndPoint,
  824. capsPath, agent.UUID, agent.ControllingClient.SessionId);
  825. }
  826. else
  827. {
  828. agent.ControllingClient.CrossRegion(neighbourHandle, pos, agent.Velocity, neighbourRegion.ExternalEndPoint,
  829. capsPath);
  830. }
  831. if (!WaitForCallback(agent.UUID))
  832. {
  833. m_log.Debug("[ENTITY TRANSFER MODULE]: Callback never came in crossing agent");
  834. ReInstantiateScripts(agent);
  835. ResetFromTransit(agent.UUID);
  836. // Yikes! We should just have a ref to scene here.
  837. //agent.Scene.InformClientOfNeighbours(agent);
  838. EnableChildAgents(agent);
  839. return agent;
  840. }
  841. agent.MakeChildAgent();
  842. // now we have a child agent in this region. Request all interesting data about other (root) agents
  843. agent.SendOtherAgentsAvatarDataToMe();
  844. agent.SendOtherAgentsAppearanceToMe();
  845. // Backwards compatibility
  846. if (version == "Unknown" || version == string.Empty)
  847. {
  848. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Old neighbor, passing attachments one by one...");
  849. CrossAttachmentsIntoNewRegion(neighbourRegion, agent, true);
  850. }
  851. AgentHasMovedAway(agent, false);
  852. // the user may change their profile information in other region,
  853. // so the userinfo in UserProfileCache is not reliable any more, delete it
  854. // REFACTORING PROBLEM. Well, not a problem, but this method is HORRIBLE!
  855. if (agent.Scene.NeedSceneCacheClear(agent.UUID))
  856. {
  857. m_log.DebugFormat(
  858. "[ENTITY TRANSFER MODULE]: User {0} is going to another region", agent.UUID);
  859. }
  860. }
  861. //m_log.Debug("AFTER CROSS");
  862. //Scene.DumpChildrenSeeds(UUID);
  863. //DumpKnownRegions();
  864. return agent;
  865. }
  866. private void CrossAgentToNewRegionCompleted(IAsyncResult iar)
  867. {
  868. CrossAgentToNewRegionDelegate icon = (CrossAgentToNewRegionDelegate)iar.AsyncState;
  869. ScenePresence agent = icon.EndInvoke(iar);
  870. // If the cross was successful, this agent is a child agent
  871. if (agent.IsChildAgent)
  872. agent.Reset();
  873. else // Not successful
  874. agent.RestoreInCurrentScene();
  875. // In any case
  876. agent.NotInTransit();
  877. //m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Crossing agent {0} {1} completed.", agent.Firstname, agent.Lastname);
  878. }
  879. #endregion
  880. #region Enable Child Agent
  881. /// <summary>
  882. /// This informs a single neighbouring region about agent "avatar".
  883. /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
  884. /// </summary>
  885. /// <param name="sp"></param>
  886. /// <param name="region"></param>
  887. public void EnableChildAgent(ScenePresence sp, GridRegion region)
  888. {
  889. m_log.DebugFormat("[ENTITY TRANSFER]: Enabling child agent in new neighbour {0}", region.RegionName);
  890. AgentCircuitData currentAgentCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
  891. AgentCircuitData agent = sp.ControllingClient.RequestClientInfo();
  892. agent.BaseFolder = UUID.Zero;
  893. agent.InventoryFolder = UUID.Zero;
  894. agent.startpos = new Vector3(128, 128, 70);
  895. agent.child = true;
  896. agent.Appearance = sp.Appearance;
  897. agent.CapsPath = CapsUtil.GetRandomCapsObjectPath();
  898. agent.ChildrenCapSeeds = new Dictionary<ulong, string>(sp.Scene.CapsModule.GetChildrenSeeds(sp.UUID));
  899. //m_log.DebugFormat("[XXX] Seeds 1 {0}", agent.ChildrenCapSeeds.Count);
  900. if (!agent.ChildrenCapSeeds.ContainsKey(sp.Scene.RegionInfo.RegionHandle))
  901. agent.ChildrenCapSeeds.Add(sp.Scene.RegionInfo.RegionHandle, sp.ControllingClient.RequestClientInfo().CapsPath);
  902. //m_log.DebugFormat("[XXX] Seeds 2 {0}", agent.ChildrenCapSeeds.Count);
  903. sp.AddNeighbourRegion(region.RegionHandle, agent.CapsPath);
  904. //foreach (ulong h in agent.ChildrenCapSeeds.Keys)
  905. // m_log.DebugFormat("[XXX] --> {0}", h);
  906. //m_log.DebugFormat("[XXX] Adding {0}", region.RegionHandle);
  907. agent.ChildrenCapSeeds.Add(region.RegionHandle, agent.CapsPath);
  908. if (sp.Scene.CapsModule != null)
  909. {
  910. sp.Scene.CapsModule.SetChildrenSeed(sp.UUID, agent.ChildrenCapSeeds);
  911. }
  912. if (currentAgentCircuit != null)
  913. {
  914. agent.ServiceURLs = currentAgentCircuit.ServiceURLs;
  915. agent.IPAddress = currentAgentCircuit.IPAddress;
  916. agent.Viewer = currentAgentCircuit.Viewer;
  917. agent.Channel = currentAgentCircuit.Channel;
  918. agent.Mac = currentAgentCircuit.Mac;
  919. agent.Id0 = currentAgentCircuit.Id0;
  920. }
  921. InformClientOfNeighbourDelegate d = InformClientOfNeighbourAsync;
  922. d.BeginInvoke(sp, agent, region, region.ExternalEndPoint, true,
  923. InformClientOfNeighbourCompleted,
  924. d);
  925. }
  926. #endregion
  927. #region Enable Child Agents
  928. private delegate void InformClientOfNeighbourDelegate(
  929. ScenePresence avatar, AgentCircuitData a, GridRegion reg, IPEndPoint endPoint, bool newAgent);
  930. /// <summary>
  931. /// This informs all neighbouring regions about agent "avatar".
  932. /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
  933. /// </summary>
  934. /// <param name="sp"></param>
  935. public void EnableChildAgents(ScenePresence sp)
  936. {
  937. List<GridRegion> neighbours = new List<GridRegion>();
  938. RegionInfo m_regionInfo = sp.Scene.RegionInfo;
  939. if (m_regionInfo != null)
  940. {
  941. neighbours = RequestNeighbours(sp, m_regionInfo.RegionLocX, m_regionInfo.RegionLocY);
  942. }
  943. else
  944. {
  945. m_log.Debug("[ENTITY TRANSFER MODULE]: m_regionInfo was null in EnableChildAgents, is this a NPC?");
  946. }
  947. /// We need to find the difference between the new regions where there are no child agents
  948. /// and the regions where there are already child agents. We only send notification to the former.
  949. List<ulong> neighbourHandles = NeighbourHandles(neighbours); // on this region
  950. neighbourHandles.Add(sp.Scene.RegionInfo.RegionHandle); // add this region too
  951. List<ulong> previousRegionNeighbourHandles;
  952. if (sp.Scene.CapsModule != null)
  953. {
  954. previousRegionNeighbourHandles =
  955. new List<ulong>(sp.Scene.CapsModule.GetChildrenSeeds(sp.UUID).Keys);
  956. }
  957. else
  958. {
  959. previousRegionNeighbourHandles = new List<ulong>();
  960. }
  961. List<ulong> newRegions = NewNeighbours(neighbourHandles, previousRegionNeighbourHandles);
  962. List<ulong> oldRegions = OldNeighbours(neighbourHandles, previousRegionNeighbourHandles);
  963. //Dump("Current Neighbors", neighbourHandles);
  964. //Dump("Previous Neighbours", previousRegionNeighbourHandles);
  965. //Dump("New Neighbours", newRegions);
  966. //Dump("Old Neighbours", oldRegions);
  967. /// Update the scene presence's known regions here on this region
  968. sp.DropOldNeighbours(oldRegions);
  969. /// Collect as many seeds as possible
  970. Dictionary<ulong, string> seeds;
  971. if (sp.Scene.CapsModule != null)
  972. seeds
  973. = new Dictionary<ulong, string>(sp.Scene.CapsModule.GetChildrenSeeds(sp.UUID));
  974. else
  975. seeds = new Dictionary<ulong, string>();
  976. //m_log.Debug(" !!! No. of seeds: " + seeds.Count);
  977. if (!seeds.ContainsKey(sp.Scene.RegionInfo.RegionHandle))
  978. seeds.Add(sp.Scene.RegionInfo.RegionHandle, sp.ControllingClient.RequestClientInfo().CapsPath);
  979. /// Create the necessary child agents
  980. List<AgentCircuitData> cagents = new List<AgentCircuitData>();
  981. foreach (GridRegion neighbour in neighbours)
  982. {
  983. if (neighbour.RegionHandle != sp.Scene.RegionInfo.RegionHandle)
  984. {
  985. AgentCircuitData currentAgentCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
  986. AgentCircuitData agent = sp.ControllingClient.RequestClientInfo();
  987. agent.BaseFolder = UUID.Zero;
  988. agent.InventoryFolder = UUID.Zero;
  989. agent.startpos = new Vector3(128, 128, 70);
  990. agent.child = true;
  991. agent.Appearance = sp.Appearance;
  992. if (currentAgentCircuit != null)
  993. {
  994. agent.ServiceURLs = currentAgentCircuit.ServiceURLs;
  995. agent.IPAddress = currentAgentCircuit.IPAddress;
  996. agent.Viewer = currentAgentCircuit.Viewer;
  997. agent.Channel = currentAgentCircuit.Channel;
  998. agent.Mac = currentAgentCircuit.Mac;
  999. agent.Id0 = currentAgentCircuit.Id0;
  1000. }
  1001. if (newRegions.Contains(neighbour.RegionHandle))
  1002. {
  1003. agent.CapsPath = CapsUtil.GetRandomCapsObjectPath();
  1004. sp.AddNeighbourRegion(neighbour.RegionHandle, agent.CapsPath);
  1005. seeds.Add(neighbour.RegionHandle, agent.CapsPath);
  1006. }
  1007. else
  1008. agent.CapsPath = sp.Scene.CapsModule.GetChildSeed(sp.UUID, neighbour.RegionHandle);
  1009. cagents.Add(agent);
  1010. }
  1011. }
  1012. /// Update all child agent with everyone's seeds
  1013. foreach (AgentCircuitData a in cagents)
  1014. {
  1015. a.ChildrenCapSeeds = new Dictionary<ulong, string>(seeds);
  1016. }
  1017. if (sp.Scene.CapsModule != null)
  1018. {
  1019. sp.Scene.CapsModule.SetChildrenSeed(sp.UUID, seeds);
  1020. }
  1021. sp.KnownRegions = seeds;
  1022. //avatar.Scene.DumpChildrenSeeds(avatar.UUID);
  1023. //avatar.DumpKnownRegions();
  1024. bool newAgent = false;
  1025. int count = 0;
  1026. foreach (GridRegion neighbour in neighbours)
  1027. {
  1028. //m_log.WarnFormat("--> Going to send child agent to {0}", neighbour.RegionName);
  1029. // Don't do it if there's already an agent in that region
  1030. if (newRegions.Contains(neighbour.RegionHandle))
  1031. newAgent = true;
  1032. else
  1033. newAgent = false;
  1034. if (neighbour.RegionHandle != sp.Scene.RegionInfo.RegionHandle)
  1035. {
  1036. InformClientOfNeighbourDelegate d = InformClientOfNeighbourAsync;
  1037. try
  1038. {
  1039. d.BeginInvoke(sp, cagents[count], neighbour, neighbour.ExternalEndPoint, newAgent,
  1040. InformClientOfNeighbourCompleted,
  1041. d);
  1042. }
  1043. catch (ArgumentOutOfRangeException)
  1044. {
  1045. m_log.ErrorFormat(
  1046. "[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}).",
  1047. neighbour.ExternalHostName,
  1048. neighbour.RegionHandle,
  1049. neighbour.RegionLocX,
  1050. neighbour.RegionLocY);
  1051. }
  1052. catch (Exception e)
  1053. {
  1054. m_log.ErrorFormat(
  1055. "[ENTITY TRANSFER MODULE]: Could not resolve external hostname {0} for region {1} ({2}, {3}). {4}",
  1056. neighbour.ExternalHostName,
  1057. neighbour.RegionHandle,
  1058. neighbour.RegionLocX,
  1059. neighbour.RegionLocY,
  1060. e);
  1061. // FIXME: Okay, even though we've failed, we're still going to throw the exception on,
  1062. // since I don't know what will happen if we just let the client continue
  1063. // XXX: Well, decided to swallow the exception instead for now. Let us see how that goes.
  1064. // throw e;
  1065. }
  1066. }
  1067. count++;
  1068. }
  1069. }
  1070. private void InformClientOfNeighbourCompleted(IAsyncResult iar)
  1071. {
  1072. InformClientOfNeighbourDelegate icon = (InformClientOfNeighbourDelegate)iar.AsyncState;
  1073. icon.EndInvoke(iar);
  1074. //m_log.WarnFormat(" --> InformClientOfNeighbourCompleted");
  1075. }
  1076. /// <summary>
  1077. /// Async component for informing client of which neighbours exist
  1078. /// </summary>
  1079. /// <remarks>
  1080. /// This needs to run asynchronously, as a network timeout may block the thread for a long while
  1081. /// </remarks>
  1082. /// <param name="remoteClient"></param>
  1083. /// <param name="a"></param>
  1084. /// <param name="regionHandle"></param>
  1085. /// <param name="endPoint"></param>
  1086. private void InformClientOfNeighbourAsync(ScenePresence sp, AgentCircuitData a, GridRegion reg,
  1087. IPEndPoint endPoint, bool newAgent)
  1088. {
  1089. // Let's wait just a little to give time to originating regions to catch up with closing child agents
  1090. // after a cross here
  1091. Thread.Sleep(500);
  1092. Scene m_scene = sp.Scene;
  1093. uint x, y;
  1094. Utils.LongToUInts(reg.RegionHandle, out x, out y);
  1095. x = x / Constants.RegionSize;
  1096. y = y / Constants.RegionSize;
  1097. m_log.Debug("[ENTITY TRANSFER MODULE]: Starting to inform client about neighbour " + x + ", " + y + "(" + endPoint + ")");
  1098. string capsPath = reg.ServerURI + CapsUtil.GetCapsSeedPath(a.CapsPath);
  1099. string reason = String.Empty;
  1100. bool regionAccepted = m_scene.SimulationService.CreateAgent(reg, a, (uint)TeleportFlags.Default, out reason);
  1101. if (regionAccepted && newAgent)
  1102. {
  1103. IEventQueue eq = sp.Scene.RequestModuleInterface<IEventQueue>();
  1104. if (eq != null)
  1105. {
  1106. #region IP Translation for NAT
  1107. IClientIPEndpoint ipepClient;
  1108. if (sp.ClientView.TryGet(out ipepClient))
  1109. {
  1110. endPoint.Address = NetworkUtil.GetIPFor(ipepClient.EndPoint, endPoint.Address);
  1111. }
  1112. #endregion
  1113. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: {0} is sending {1} EnableSimulator for neighbour region {2} @ {3} " +
  1114. "and EstablishAgentCommunication with seed cap {4}",
  1115. m_scene.RegionInfo.RegionName, sp.Name, reg.RegionName, reg.RegionHandle, capsPath);
  1116. eq.EnableSimulator(reg.RegionHandle, endPoint, sp.UUID);
  1117. eq.EstablishAgentCommunication(sp.UUID, endPoint, capsPath);
  1118. }
  1119. else
  1120. {
  1121. sp.ControllingClient.InformClientOfNeighbour(reg.RegionHandle, endPoint);
  1122. // TODO: make Event Queue disablable!
  1123. }
  1124. m_log.Debug("[ENTITY TRANSFER MODULE]: Completed inform client about neighbour " + endPoint.ToString());
  1125. }
  1126. if (!regionAccepted)
  1127. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Region {0} did not accept agent: {1}", reg.RegionName, reason);
  1128. }
  1129. /// <summary>
  1130. /// Return the list of regions that are considered to be neighbours to the given scene.
  1131. /// </summary>
  1132. /// <param name="pScene"></param>
  1133. /// <param name="pRegionLocX"></param>
  1134. /// <param name="pRegionLocY"></param>
  1135. /// <returns></returns>
  1136. protected List<GridRegion> RequestNeighbours(ScenePresence avatar, uint pRegionLocX, uint pRegionLocY)
  1137. {
  1138. Scene pScene = avatar.Scene;
  1139. RegionInfo m_regionInfo = pScene.RegionInfo;
  1140. Border[] northBorders = pScene.NorthBorders.ToArray();
  1141. Border[] southBorders = pScene.SouthBorders.ToArray();
  1142. Border[] eastBorders = pScene.EastBorders.ToArray();
  1143. Border[] westBorders = pScene.WestBorders.ToArray();
  1144. // Leaving this as a "megaregions" computation vs "non-megaregions" computation; it isn't
  1145. // clear what should be done with a "far view" given that megaregions already extended the
  1146. // view to include everything in the megaregion
  1147. if (northBorders.Length <= 1 && southBorders.Length <= 1 && eastBorders.Length <= 1 && westBorders.Length <= 1)
  1148. {
  1149. int dd = avatar.DrawDistance < Constants.RegionSize ? (int)Constants.RegionSize : (int)avatar.DrawDistance;
  1150. int startX = (int)pRegionLocX * (int)Constants.RegionSize - dd + (int)(Constants.RegionSize/2);
  1151. int startY = (int)pRegionLocY * (int)Constants.RegionSize - dd + (int)(Constants.RegionSize/2);
  1152. int endX = (int)pRegionLocX * (int)Constants.RegionSize + dd + (int)(Constants.RegionSize/2);
  1153. int endY = (int)pRegionLocY * (int)Constants.RegionSize + dd + (int)(Constants.RegionSize/2);
  1154. List<GridRegion> neighbours =
  1155. avatar.Scene.GridService.GetRegionRange(m_regionInfo.ScopeID, startX, endX, startY, endY);
  1156. neighbours.RemoveAll(delegate(GridRegion r) { return r.RegionID == m_regionInfo.RegionID; });
  1157. return neighbours;
  1158. }
  1159. else
  1160. {
  1161. Vector2 extent = Vector2.Zero;
  1162. for (int i = 0; i < eastBorders.Length; i++)
  1163. {
  1164. extent.X = (eastBorders[i].BorderLine.Z > extent.X) ? eastBorders[i].BorderLine.Z : extent.X;
  1165. }
  1166. for (int i = 0; i < northBorders.Length; i++)
  1167. {
  1168. extent.Y = (northBorders[i].BorderLine.Z > extent.Y) ? northBorders[i].BorderLine.Z : extent.Y;
  1169. }
  1170. // Loss of fraction on purpose
  1171. extent.X = ((int)extent.X / (int)Constants.RegionSize) + 1;
  1172. extent.Y = ((int)extent.Y / (int)Constants.RegionSize) + 1;
  1173. int startX = (int)(pRegionLocX - 1) * (int)Constants.RegionSize;
  1174. int startY = (int)(pRegionLocY - 1) * (int)Constants.RegionSize;
  1175. int endX = ((int)pRegionLocX + (int)extent.X) * (int)Constants.RegionSize;
  1176. int endY = ((int)pRegionLocY + (int)extent.Y) * (int)Constants.RegionSize;
  1177. List<GridRegion> neighbours = pScene.GridService.GetRegionRange(m_regionInfo.ScopeID, startX, endX, startY, endY);
  1178. neighbours.RemoveAll(delegate(GridRegion r) { return r.RegionID == m_regionInfo.RegionID; });
  1179. return neighbours;
  1180. }
  1181. }
  1182. private List<ulong> NewNeighbours(List<ulong> currentNeighbours, List<ulong> previousNeighbours)
  1183. {
  1184. return currentNeighbours.FindAll(delegate(ulong handle) { return !previousNeighbours.Contains(handle); });
  1185. }
  1186. // private List<ulong> CommonNeighbours(List<ulong> currentNeighbours, List<ulong> previousNeighbours)
  1187. // {
  1188. // return currentNeighbours.FindAll(delegate(ulong handle) { return previousNeighbours.Contains(handle); });
  1189. // }
  1190. private List<ulong> OldNeighbours(List<ulong> currentNeighbours, List<ulong> previousNeighbours)
  1191. {
  1192. return previousNeighbours.FindAll(delegate(ulong handle) { return !currentNeighbours.Contains(handle); });
  1193. }
  1194. private List<ulong> NeighbourHandles(List<GridRegion> neighbours)
  1195. {
  1196. List<ulong> handles = new List<ulong>();
  1197. foreach (GridRegion reg in neighbours)
  1198. {
  1199. handles.Add(reg.RegionHandle);
  1200. }
  1201. return handles;
  1202. }
  1203. // private void Dump(string msg, List<ulong> handles)
  1204. // {
  1205. // m_log.InfoFormat("-------------- HANDLE DUMP ({0}) ---------", msg);
  1206. // foreach (ulong handle in handles)
  1207. // {
  1208. // uint x, y;
  1209. // Utils.LongToUInts(handle, out x, out y);
  1210. // x = x / Constants.RegionSize;
  1211. // y = y / Constants.RegionSize;
  1212. // m_log.InfoFormat("({0}, {1})", x, y);
  1213. // }
  1214. // }
  1215. #endregion
  1216. #region Agent Arrived
  1217. public void AgentArrivedAtDestination(UUID id)
  1218. {
  1219. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Agent {0} released", id);
  1220. ResetFromTransit(id);
  1221. }
  1222. #endregion
  1223. #region Object Transfers
  1224. /// <summary>
  1225. /// Move the given scene object into a new region depending on which region its absolute position has moved
  1226. /// into.
  1227. ///
  1228. /// This method locates the new region handle and offsets the prim position for the new region
  1229. /// </summary>
  1230. /// <param name="attemptedPosition">the attempted out of region position of the scene object</param>
  1231. /// <param name="grp">the scene object that we're crossing</param>
  1232. public void Cross(SceneObjectGroup grp, Vector3 attemptedPosition, bool silent)
  1233. {
  1234. if (grp == null)
  1235. return;
  1236. if (grp.IsDeleted)
  1237. return;
  1238. Scene scene = grp.Scene;
  1239. if (scene == null)
  1240. return;
  1241. if (grp.RootPart.DIE_AT_EDGE)
  1242. {
  1243. // We remove the object here
  1244. try
  1245. {
  1246. scene.DeleteSceneObject(grp, false);
  1247. }
  1248. catch (Exception)
  1249. {
  1250. m_log.Warn("[DATABASE]: exception when trying to remove the prim that crossed the border.");
  1251. }
  1252. return;
  1253. }
  1254. int thisx = (int)scene.RegionInfo.RegionLocX;
  1255. int thisy = (int)scene.RegionInfo.RegionLocY;
  1256. Vector3 EastCross = new Vector3(0.1f, 0, 0);
  1257. Vector3 WestCross = new Vector3(-0.1f, 0, 0);
  1258. Vector3 NorthCross = new Vector3(0, 0.1f, 0);
  1259. Vector3 SouthCross = new Vector3(0, -0.1f, 0);
  1260. // use this if no borders were crossed!
  1261. ulong newRegionHandle
  1262. = Util.UIntsToLong((uint)((thisx) * Constants.RegionSize),
  1263. (uint)((thisy) * Constants.RegionSize));
  1264. Vector3 pos = attemptedPosition;
  1265. int changeX = 1;
  1266. int changeY = 1;
  1267. if (scene.TestBorderCross(attemptedPosition + WestCross, Cardinals.W))
  1268. {
  1269. if (scene.TestBorderCross(attemptedPosition + SouthCross, Cardinals.S))
  1270. {
  1271. Border crossedBorderx = scene.GetCrossedBorder(attemptedPosition + WestCross, Cardinals.W);
  1272. if (crossedBorderx.BorderLine.Z > 0)
  1273. {
  1274. pos.X = ((pos.X + crossedBorderx.BorderLine.Z));
  1275. changeX = (int)(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize);
  1276. }
  1277. else
  1278. pos.X = ((pos.X + Constants.RegionSize));
  1279. Border crossedBordery = scene.GetCrossedBorder(attemptedPosition + SouthCross, Cardinals.S);
  1280. //(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize)
  1281. if (crossedBordery.BorderLine.Z > 0)
  1282. {
  1283. pos.Y = ((pos.Y + crossedBordery.BorderLine.Z));
  1284. changeY = (int)(crossedBordery.BorderLine.Z / (int)Constants.RegionSize);
  1285. }
  1286. else
  1287. pos.Y = ((pos.Y + Constants.RegionSize));
  1288. newRegionHandle
  1289. = Util.UIntsToLong((uint)((thisx - changeX) * Constants.RegionSize),
  1290. (uint)((thisy - changeY) * Constants.RegionSize));
  1291. // x - 1
  1292. // y - 1
  1293. }
  1294. else if (scene.TestBorderCross(attemptedPosition + NorthCross, Cardinals.N))
  1295. {
  1296. Border crossedBorderx = scene.GetCrossedBorder(attemptedPosition + WestCross, Cardinals.W);
  1297. if (crossedBorderx.BorderLine.Z > 0)
  1298. {
  1299. pos.X = ((pos.X + crossedBorderx.BorderLine.Z));
  1300. changeX = (int)(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize);
  1301. }
  1302. else
  1303. pos.X = ((pos.X + Constants.RegionSize));
  1304. Border crossedBordery = scene.GetCrossedBorder(attemptedPosition + SouthCross, Cardinals.S);
  1305. //(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize)
  1306. if (crossedBordery.BorderLine.Z > 0)
  1307. {
  1308. pos.Y = ((pos.Y + crossedBordery.BorderLine.Z));
  1309. changeY = (int)(crossedBordery.BorderLine.Z / (int)Constants.RegionSize);
  1310. }
  1311. else
  1312. pos.Y = ((pos.Y + Constants.RegionSize));
  1313. newRegionHandle
  1314. = Util.UIntsToLong((uint)((thisx - changeX) * Constants.RegionSize),
  1315. (uint)((thisy + changeY) * Constants.RegionSize));
  1316. // x - 1
  1317. // y + 1
  1318. }
  1319. else
  1320. {
  1321. Border crossedBorderx = scene.GetCrossedBorder(attemptedPosition + WestCross, Cardinals.W);
  1322. if (crossedBorderx.BorderLine.Z > 0)
  1323. {
  1324. pos.X = ((pos.X + crossedBorderx.BorderLine.Z));
  1325. changeX = (int)(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize);
  1326. }
  1327. else
  1328. pos.X = ((pos.X + Constants.RegionSize));
  1329. newRegionHandle
  1330. = Util.UIntsToLong((uint)((thisx - changeX) * Constants.RegionSize),
  1331. (uint)(thisy * Constants.RegionSize));
  1332. // x - 1
  1333. }
  1334. }
  1335. else if (scene.TestBorderCross(attemptedPosition + EastCross, Cardinals.E))
  1336. {
  1337. if (scene.TestBorderCross(attemptedPosition + SouthCross, Cardinals.S))
  1338. {
  1339. pos.X = ((pos.X - Constants.RegionSize));
  1340. Border crossedBordery = scene.GetCrossedBorder(attemptedPosition + SouthCross, Cardinals.S);
  1341. //(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize)
  1342. if (crossedBordery.BorderLine.Z > 0)
  1343. {
  1344. pos.Y = ((pos.Y + crossedBordery.BorderLine.Z));
  1345. changeY = (int)(crossedBordery.BorderLine.Z / (int)Constants.RegionSize);
  1346. }
  1347. else
  1348. pos.Y = ((pos.Y + Constants.RegionSize));
  1349. newRegionHandle
  1350. = Util.UIntsToLong((uint)((thisx + changeX) * Constants.RegionSize),
  1351. (uint)((thisy - changeY) * Constants.RegionSize));
  1352. // x + 1
  1353. // y - 1
  1354. }
  1355. else if (scene.TestBorderCross(attemptedPosition + NorthCross, Cardinals.N))
  1356. {
  1357. pos.X = ((pos.X - Constants.RegionSize));
  1358. pos.Y = ((pos.Y - Constants.RegionSize));
  1359. newRegionHandle
  1360. = Util.UIntsToLong((uint)((thisx + changeX) * Constants.RegionSize),
  1361. (uint)((thisy + changeY) * Constants.RegionSize));
  1362. // x + 1
  1363. // y + 1
  1364. }
  1365. else
  1366. {
  1367. pos.X = ((pos.X - Constants.RegionSize));
  1368. newRegionHandle
  1369. = Util.UIntsToLong((uint)((thisx + changeX) * Constants.RegionSize),
  1370. (uint)(thisy * Constants.RegionSize));
  1371. // x + 1
  1372. }
  1373. }
  1374. else if (scene.TestBorderCross(attemptedPosition + SouthCross, Cardinals.S))
  1375. {
  1376. Border crossedBordery = scene.GetCrossedBorder(attemptedPosition + SouthCross, Cardinals.S);
  1377. //(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize)
  1378. if (crossedBordery.BorderLine.Z > 0)
  1379. {
  1380. pos.Y = ((pos.Y + crossedBordery.BorderLine.Z));
  1381. changeY = (int)(crossedBordery.BorderLine.Z / (int)Constants.RegionSize);
  1382. }
  1383. else
  1384. pos.Y = ((pos.Y + Constants.RegionSize));
  1385. newRegionHandle
  1386. = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy - changeY) * Constants.RegionSize));
  1387. // y - 1
  1388. }
  1389. else if (scene.TestBorderCross(attemptedPosition + NorthCross, Cardinals.N))
  1390. {
  1391. pos.Y = ((pos.Y - Constants.RegionSize));
  1392. newRegionHandle
  1393. = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy + changeY) * Constants.RegionSize));
  1394. // y + 1
  1395. }
  1396. // Offset the positions for the new region across the border
  1397. Vector3 oldGroupPosition = grp.RootPart.GroupPosition;
  1398. grp.OffsetForNewRegion(pos);
  1399. // If we fail to cross the border, then reset the position of the scene object on that border.
  1400. uint x = 0, y = 0;
  1401. Utils.LongToUInts(newRegionHandle, out x, out y);
  1402. GridRegion destination = scene.GridService.GetRegionByPosition(scene.RegionInfo.ScopeID, (int)x, (int)y);
  1403. if (destination != null && !CrossPrimGroupIntoNewRegion(destination, grp, silent))
  1404. {
  1405. grp.OffsetForNewRegion(oldGroupPosition);
  1406. grp.ScheduleGroupForFullUpdate();
  1407. }
  1408. }
  1409. /// <summary>
  1410. /// Move the given scene object into a new region
  1411. /// </summary>
  1412. /// <param name="newRegionHandle"></param>
  1413. /// <param name="grp">Scene Object Group that we're crossing</param>
  1414. /// <returns>
  1415. /// true if the crossing itself was successful, false on failure
  1416. /// FIMXE: we still return true if the crossing object was not successfully deleted from the originating region
  1417. /// </returns>
  1418. protected bool CrossPrimGroupIntoNewRegion(GridRegion destination, SceneObjectGroup grp, bool silent)
  1419. {
  1420. //m_log.Debug(" >>> CrossPrimGroupIntoNewRegion <<<");
  1421. bool successYN = false;
  1422. grp.RootPart.UpdateFlag = 0;
  1423. //int primcrossingXMLmethod = 0;
  1424. if (destination != null)
  1425. {
  1426. //string objectState = grp.GetStateSnapshot();
  1427. //successYN
  1428. // = m_sceneGridService.PrimCrossToNeighboringRegion(
  1429. // newRegionHandle, grp.UUID, m_serialiser.SaveGroupToXml2(grp), primcrossingXMLmethod);
  1430. //if (successYN && (objectState != "") && m_allowScriptCrossings)
  1431. //{
  1432. // successYN = m_sceneGridService.PrimCrossToNeighboringRegion(
  1433. // newRegionHandle, grp.UUID, objectState, 100);
  1434. //}
  1435. //// And the new channel...
  1436. //if (m_interregionCommsOut != null)
  1437. // successYN = m_interregionCommsOut.SendCreateObject(newRegionHandle, grp, true);
  1438. if (m_aScene.SimulationService != null)
  1439. successYN = m_aScene.SimulationService.CreateObject(destination, grp, true);
  1440. if (successYN)
  1441. {
  1442. // We remove the object here
  1443. try
  1444. {
  1445. grp.Scene.DeleteSceneObject(grp, silent);
  1446. }
  1447. catch (Exception e)
  1448. {
  1449. m_log.ErrorFormat(
  1450. "[ENTITY TRANSFER MODULE]: Exception deleting the old object left behind on a border crossing for {0}, {1}",
  1451. grp, e);
  1452. }
  1453. }
  1454. else
  1455. {
  1456. if (!grp.IsDeleted)
  1457. {
  1458. if (grp.RootPart.PhysActor != null)
  1459. {
  1460. grp.RootPart.PhysActor.CrossingFailure();
  1461. }
  1462. }
  1463. m_log.ErrorFormat("[ENTITY TRANSFER MODULE]: Prim crossing failed for {0}", grp);
  1464. }
  1465. }
  1466. else
  1467. {
  1468. m_log.Error("[ENTITY TRANSFER MODULE]: destination was unexpectedly null in Scene.CrossPrimGroupIntoNewRegion()");
  1469. }
  1470. return successYN;
  1471. }
  1472. protected bool CrossAttachmentsIntoNewRegion(GridRegion destination, ScenePresence sp, bool silent)
  1473. {
  1474. List<SceneObjectGroup> m_attachments = sp.Attachments;
  1475. lock (m_attachments)
  1476. {
  1477. // Validate
  1478. foreach (SceneObjectGroup gobj in m_attachments)
  1479. {
  1480. if (gobj == null || gobj.IsDeleted)
  1481. return false;
  1482. }
  1483. foreach (SceneObjectGroup gobj in m_attachments)
  1484. {
  1485. // If the prim group is null then something must have happened to it!
  1486. if (gobj != null && gobj.RootPart != null)
  1487. {
  1488. // Set the parent localID to 0 so it transfers over properly.
  1489. gobj.RootPart.SetParentLocalId(0);
  1490. gobj.AbsolutePosition = gobj.RootPart.AttachedPos;
  1491. gobj.IsAttachment = false;
  1492. //gobj.RootPart.LastOwnerID = gobj.GetFromAssetID();
  1493. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Sending attachment {0} to region {1}", gobj.UUID, destination.RegionName);
  1494. CrossPrimGroupIntoNewRegion(destination, gobj, silent);
  1495. }
  1496. }
  1497. m_attachments.Clear();
  1498. return true;
  1499. }
  1500. }
  1501. #endregion
  1502. #region Misc
  1503. protected bool WaitForCallback(UUID id)
  1504. {
  1505. int count = 200;
  1506. while (m_agentsInTransit.Contains(id) && count-- > 0)
  1507. {
  1508. //m_log.Debug(" >>> Waiting... " + count);
  1509. Thread.Sleep(100);
  1510. }
  1511. if (count > 0)
  1512. return true;
  1513. else
  1514. return false;
  1515. }
  1516. protected void SetInTransit(UUID id)
  1517. {
  1518. lock (m_agentsInTransit)
  1519. {
  1520. if (!m_agentsInTransit.Contains(id))
  1521. m_agentsInTransit.Add(id);
  1522. }
  1523. }
  1524. protected bool ResetFromTransit(UUID id)
  1525. {
  1526. lock (m_agentsInTransit)
  1527. {
  1528. if (m_agentsInTransit.Contains(id))
  1529. {
  1530. m_agentsInTransit.Remove(id);
  1531. return true;
  1532. }
  1533. }
  1534. return false;
  1535. }
  1536. protected void ReInstantiateScripts(ScenePresence sp)
  1537. {
  1538. int i = 0;
  1539. if (sp.InTransitScriptStates.Count > 0)
  1540. {
  1541. sp.Attachments.ForEach(delegate(SceneObjectGroup sog)
  1542. {
  1543. if (i < sp.InTransitScriptStates.Count)
  1544. {
  1545. sog.SetState(sp.InTransitScriptStates[i++], sp.Scene);
  1546. sog.CreateScriptInstances(0, false, sp.Scene.DefaultScriptEngine, 0);
  1547. sog.ResumeScripts();
  1548. }
  1549. else
  1550. m_log.ErrorFormat("[ENTITY TRANSFER MODULE]: InTransitScriptStates.Count={0} smaller than Attachments.Count={1}", sp.InTransitScriptStates.Count, sp.Attachments.Count);
  1551. });
  1552. sp.InTransitScriptStates.Clear();
  1553. }
  1554. }
  1555. #endregion
  1556. }
  1557. }