EntityTransferModule.cs 89 KB

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