EntityTransferModule.cs 118 KB

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