EntityTransferModule.cs 91 KB

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