EntityTransferModule.cs 118 KB

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