EntityTransferModule.cs 126 KB

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