EntityTransferModule.cs 117 KB

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