EntityTransferModule.cs 125 KB

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