SceneCommunicationService.cs 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601
  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 OpenMetaverse;
  33. using OpenMetaverse.StructuredData;
  34. using log4net;
  35. using OpenSim.Framework;
  36. using OpenSim.Framework.Client;
  37. using OpenSim.Framework.Communications;
  38. using OpenSim.Framework.Communications.Cache;
  39. using OpenSim.Framework.Capabilities;
  40. using OpenSim.Region.Framework.Interfaces;
  41. using OpenSim.Services.Interfaces;
  42. using OSD = OpenMetaverse.StructuredData.OSD;
  43. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  44. namespace OpenSim.Region.Framework.Scenes
  45. {
  46. public delegate void KiPrimitiveDelegate(uint localID);
  47. public delegate void RemoveKnownRegionsFromAvatarList(UUID avatarID, List<ulong> regionlst);
  48. /// <summary>
  49. /// Class that Region communications runs through
  50. /// </summary>
  51. public class SceneCommunicationService //one instance per region
  52. {
  53. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  54. protected CommunicationsManager m_commsProvider;
  55. protected IInterregionCommsOut m_interregionCommsOut;
  56. protected RegionInfo m_regionInfo;
  57. protected Scene m_scene;
  58. protected RegionCommsListener regionCommsHost;
  59. protected List<UUID> m_agentsInTransit;
  60. public bool RegionLoginsEnabled
  61. {
  62. get { return m_regionLoginsEnabled; }
  63. set { m_regionLoginsEnabled = value; }
  64. }
  65. private bool m_regionLoginsEnabled = false;
  66. /// <summary>
  67. /// An agent is crossing into this region
  68. /// </summary>
  69. public event AgentCrossing OnAvatarCrossingIntoRegion;
  70. /// <summary>
  71. /// A user will arrive shortly, set up appropriate credentials so it can connect
  72. /// </summary>
  73. public event ExpectUserDelegate OnExpectUser;
  74. /// <summary>
  75. /// A Prim will arrive shortly
  76. /// </summary>
  77. public event ExpectPrimDelegate OnExpectPrim;
  78. public event CloseAgentConnection OnCloseAgentConnection;
  79. /// <summary>
  80. /// A new prim has arrived
  81. /// </summary>
  82. public event PrimCrossing OnPrimCrossingIntoRegion;
  83. ///// <summary>
  84. ///// A New Region is up and available
  85. ///// </summary>
  86. //public event RegionUp OnRegionUp;
  87. /// <summary>
  88. /// We have a child agent for this avatar and we're getting a status update about it
  89. /// </summary>
  90. public event ChildAgentUpdate OnChildAgentUpdate;
  91. //public event RemoveKnownRegionsFromAvatarList OnRemoveKnownRegionFromAvatar;
  92. /// <summary>
  93. /// Time to log one of our users off. Grid Service sends this mostly
  94. /// </summary>
  95. public event LogOffUser OnLogOffUser;
  96. /// <summary>
  97. /// A region wants land data from us!
  98. /// </summary>
  99. public event GetLandData OnGetLandData;
  100. private AgentCrossing handlerAvatarCrossingIntoRegion = null; // OnAvatarCrossingIntoRegion;
  101. private ExpectUserDelegate handlerExpectUser = null; // OnExpectUser;
  102. private ExpectPrimDelegate handlerExpectPrim = null; // OnExpectPrim;
  103. private CloseAgentConnection handlerCloseAgentConnection = null; // OnCloseAgentConnection;
  104. private PrimCrossing handlerPrimCrossingIntoRegion = null; // OnPrimCrossingIntoRegion;
  105. //private RegionUp handlerRegionUp = null; // OnRegionUp;
  106. private ChildAgentUpdate handlerChildAgentUpdate = null; // OnChildAgentUpdate;
  107. //private RemoveKnownRegionsFromAvatarList handlerRemoveKnownRegionFromAvatar = null; // OnRemoveKnownRegionFromAvatar;
  108. private LogOffUser handlerLogOffUser = null;
  109. private GetLandData handlerGetLandData = null; // OnGetLandData
  110. public KiPrimitiveDelegate KiPrimitive;
  111. public SceneCommunicationService(CommunicationsManager commsMan)
  112. {
  113. m_commsProvider = commsMan;
  114. m_agentsInTransit = new List<UUID>();
  115. }
  116. public void SetScene(Scene s)
  117. {
  118. m_scene = s;
  119. m_regionInfo = s.RegionInfo;
  120. m_interregionCommsOut = m_scene.RequestModuleInterface<IInterregionCommsOut>();
  121. }
  122. /// <summary>
  123. /// Register a region with the grid
  124. /// </summary>
  125. /// <param name="regionInfos"></param>
  126. /// <exception cref="System.Exception">Thrown if region registration fails.</exception>
  127. public void RegisterRegion(IInterregionCommsOut comms_out, RegionInfo regionInfos)
  128. {
  129. //m_interregionCommsOut = comms_out;
  130. //m_regionInfo = regionInfos;
  131. //m_commsProvider.GridService.gdebugRegionName = regionInfos.RegionName;
  132. //regionCommsHost = m_commsProvider.GridService.RegisterRegion(m_regionInfo);
  133. //if (regionCommsHost != null)
  134. //{
  135. // //m_log.Info("[INTER]: " + debugRegionName + ": SceneCommunicationService: registered with gridservice and got" + regionCommsHost.ToString());
  136. // regionCommsHost.debugRegionName = regionInfos.RegionName;
  137. // regionCommsHost.OnExpectPrim += IncomingPrimCrossing;
  138. // regionCommsHost.OnExpectUser += NewUserConnection;
  139. // regionCommsHost.OnAvatarCrossingIntoRegion += AgentCrossing;
  140. // regionCommsHost.OnCloseAgentConnection += CloseConnection;
  141. // regionCommsHost.OnRegionUp += newRegionUp;
  142. // regionCommsHost.OnChildAgentUpdate += ChildAgentUpdate;
  143. // regionCommsHost.OnLogOffUser += GridLogOffUser;
  144. // regionCommsHost.OnGetLandData += FetchLandData;
  145. //}
  146. //else
  147. //{
  148. // //m_log.Info("[INTER]: " + debugRegionName + ": SceneCommunicationService: registered with gridservice and got null");
  149. //}
  150. }
  151. /// <summary>
  152. /// This region is shutting down, de-register all events!
  153. /// De-Register region from Grid!
  154. /// </summary>
  155. public void Close()
  156. {
  157. //if (regionCommsHost != null)
  158. //{
  159. // regionCommsHost.OnLogOffUser -= GridLogOffUser;
  160. // regionCommsHost.OnChildAgentUpdate -= ChildAgentUpdate;
  161. // regionCommsHost.OnRegionUp -= newRegionUp;
  162. // regionCommsHost.OnExpectUser -= NewUserConnection;
  163. // regionCommsHost.OnExpectPrim -= IncomingPrimCrossing;
  164. // regionCommsHost.OnAvatarCrossingIntoRegion -= AgentCrossing;
  165. // regionCommsHost.OnCloseAgentConnection -= CloseConnection;
  166. // regionCommsHost.OnGetLandData -= FetchLandData;
  167. // try
  168. // {
  169. // m_commsProvider.GridService.DeregisterRegion(m_regionInfo);
  170. // }
  171. // catch (Exception e)
  172. // {
  173. // m_log.ErrorFormat(
  174. // "[GRID]: Deregistration of region {0} from the grid failed - {1}. Continuing",
  175. // m_regionInfo.RegionName, e);
  176. // }
  177. // regionCommsHost = null;
  178. //}
  179. }
  180. #region CommsManager Event handlers
  181. /// <summary>
  182. /// A New User will arrive shortly, Informs the scene that there's a new user on the way
  183. /// </summary>
  184. /// <param name="agent">Data we need to ensure that the agent can connect</param>
  185. ///
  186. protected void NewUserConnection(AgentCircuitData agent)
  187. {
  188. handlerExpectUser = OnExpectUser;
  189. if (handlerExpectUser != null)
  190. {
  191. //m_log.Info("[INTER]: " + debugRegionName + ": SceneCommunicationService: OnExpectUser Fired for User:" + agent.firstname + " " + agent.lastname);
  192. handlerExpectUser(agent);
  193. }
  194. }
  195. /// <summary>
  196. /// The Grid has requested us to log-off the user
  197. /// </summary>
  198. /// <param name="AgentID">Unique ID of agent to log-off</param>
  199. /// <param name="RegionSecret">The secret string that the region establishes with the grid when registering</param>
  200. /// <param name="message">The message to send to the user that tells them why they were logged off</param>
  201. protected void GridLogOffUser(UUID AgentID, UUID RegionSecret, string message)
  202. {
  203. handlerLogOffUser = OnLogOffUser;
  204. if (handlerLogOffUser != null)
  205. {
  206. handlerLogOffUser(AgentID, RegionSecret, message);
  207. }
  208. }
  209. /// <summary>
  210. /// Inform the scene that we've got an update about a child agent that we have
  211. /// </summary>
  212. /// <param name="cAgentData"></param>
  213. /// <returns></returns>
  214. protected bool ChildAgentUpdate(ChildAgentDataUpdate cAgentData)
  215. {
  216. handlerChildAgentUpdate = OnChildAgentUpdate;
  217. if (handlerChildAgentUpdate != null)
  218. handlerChildAgentUpdate(cAgentData);
  219. return true;
  220. }
  221. protected void AgentCrossing(UUID agentID, Vector3 position, bool isFlying)
  222. {
  223. handlerAvatarCrossingIntoRegion = OnAvatarCrossingIntoRegion;
  224. if (handlerAvatarCrossingIntoRegion != null)
  225. {
  226. handlerAvatarCrossingIntoRegion(agentID, position, isFlying);
  227. }
  228. }
  229. /// <summary>
  230. /// We have a new prim from a neighbor
  231. /// </summary>
  232. /// <param name="primID">unique ID for the primative</param>
  233. /// <param name="objXMLData">XML2 encoded data of the primative</param>
  234. /// <param name="XMLMethod">An Int that represents the version of the XMLMethod</param>
  235. /// <returns>True if the prim was accepted, false if it was not</returns>
  236. protected bool IncomingPrimCrossing(UUID primID, String objXMLData, int XMLMethod)
  237. {
  238. handlerExpectPrim = OnExpectPrim;
  239. if (handlerExpectPrim != null)
  240. {
  241. return handlerExpectPrim(primID, objXMLData, XMLMethod);
  242. }
  243. else
  244. {
  245. return false;
  246. }
  247. }
  248. protected void PrimCrossing(UUID primID, Vector3 position, bool isPhysical)
  249. {
  250. handlerPrimCrossingIntoRegion = OnPrimCrossingIntoRegion;
  251. if (handlerPrimCrossingIntoRegion != null)
  252. {
  253. handlerPrimCrossingIntoRegion(primID, position, isPhysical);
  254. }
  255. }
  256. protected bool CloseConnection(UUID agentID)
  257. {
  258. m_log.Debug("[INTERREGION]: Incoming Agent Close Request for agent: " + agentID);
  259. handlerCloseAgentConnection = OnCloseAgentConnection;
  260. if (handlerCloseAgentConnection != null)
  261. {
  262. return handlerCloseAgentConnection(agentID);
  263. }
  264. return false;
  265. }
  266. protected LandData FetchLandData(uint x, uint y)
  267. {
  268. handlerGetLandData = OnGetLandData;
  269. if (handlerGetLandData != null)
  270. {
  271. return handlerGetLandData(x, y);
  272. }
  273. return null;
  274. }
  275. #endregion
  276. #region Inform Client of Neighbours
  277. private delegate void InformClientOfNeighbourDelegate(
  278. ScenePresence avatar, AgentCircuitData a, GridRegion reg, IPEndPoint endPoint, bool newAgent);
  279. private void InformClientOfNeighbourCompleted(IAsyncResult iar)
  280. {
  281. InformClientOfNeighbourDelegate icon = (InformClientOfNeighbourDelegate) iar.AsyncState;
  282. icon.EndInvoke(iar);
  283. }
  284. /// <summary>
  285. /// Async component for informing client of which neighbours exist
  286. /// </summary>
  287. /// <remarks>
  288. /// This needs to run asynchronously, as a network timeout may block the thread for a long while
  289. /// </remarks>
  290. /// <param name="remoteClient"></param>
  291. /// <param name="a"></param>
  292. /// <param name="regionHandle"></param>
  293. /// <param name="endPoint"></param>
  294. private void InformClientOfNeighbourAsync(ScenePresence avatar, AgentCircuitData a, GridRegion reg,
  295. IPEndPoint endPoint, bool newAgent)
  296. {
  297. // Let's wait just a little to give time to originating regions to catch up with closing child agents
  298. // after a cross here
  299. Thread.Sleep(500);
  300. uint x, y;
  301. Utils.LongToUInts(reg.RegionHandle, out x, out y);
  302. x = x / Constants.RegionSize;
  303. y = y / Constants.RegionSize;
  304. m_log.Info("[INTERGRID]: Starting to inform client about neighbour " + x + ", " + y + "(" + endPoint.ToString() + ")");
  305. string capsPath = "http://" + reg.ExternalHostName + ":" + reg.HttpPort
  306. + "/CAPS/" + a.CapsPath + "0000/";
  307. string reason = String.Empty;
  308. bool regionAccepted = m_interregionCommsOut.SendCreateChildAgent(reg.RegionHandle, a, out reason);
  309. if (regionAccepted && newAgent)
  310. {
  311. IEventQueue eq = avatar.Scene.RequestModuleInterface<IEventQueue>();
  312. if (eq != null)
  313. {
  314. #region IP Translation for NAT
  315. IClientIPEndpoint ipepClient;
  316. if (avatar.ClientView.TryGet(out ipepClient))
  317. {
  318. endPoint.Address = NetworkUtil.GetIPFor(ipepClient.EndPoint, endPoint.Address);
  319. }
  320. #endregion
  321. eq.EnableSimulator(reg.RegionHandle, endPoint, avatar.UUID);
  322. eq.EstablishAgentCommunication(avatar.UUID, endPoint, capsPath);
  323. m_log.DebugFormat("[CAPS]: Sending new CAPS seed url {0} to client {1} in region {2}",
  324. capsPath, avatar.UUID, avatar.Scene.RegionInfo.RegionName);
  325. }
  326. else
  327. {
  328. avatar.ControllingClient.InformClientOfNeighbour(reg.RegionHandle, endPoint);
  329. // TODO: make Event Queue disablable!
  330. }
  331. m_log.Info("[INTERGRID]: Completed inform client about neighbour " + endPoint.ToString());
  332. }
  333. }
  334. public List<GridRegion> RequestNeighbours(Scene pScene, uint pRegionLocX, uint pRegionLocY)
  335. {
  336. Border[] northBorders = pScene.NorthBorders.ToArray();
  337. Border[] southBorders = pScene.SouthBorders.ToArray();
  338. Border[] eastBorders = pScene.EastBorders.ToArray();
  339. Border[] westBorders = pScene.WestBorders.ToArray();
  340. // Legacy one region. Provided for simplicity while testing the all inclusive method in the else statement.
  341. if (northBorders.Length <= 1 && southBorders.Length <= 1 && eastBorders.Length <= 1 && westBorders.Length <= 1)
  342. {
  343. return m_scene.GridService.GetNeighbours(m_regionInfo.ScopeID, m_regionInfo.RegionID);
  344. }
  345. else
  346. {
  347. Vector2 extent = Vector2.Zero;
  348. for (int i = 0; i < eastBorders.Length; i++)
  349. {
  350. extent.X = (eastBorders[i].BorderLine.Z > extent.X) ? eastBorders[i].BorderLine.Z : extent.X;
  351. }
  352. for (int i = 0; i < northBorders.Length; i++)
  353. {
  354. extent.Y = (northBorders[i].BorderLine.Z > extent.Y) ? northBorders[i].BorderLine.Z : extent.Y;
  355. }
  356. // Loss of fraction on purpose
  357. extent.X = ((int)extent.X / (int)Constants.RegionSize) + 1;
  358. extent.Y = ((int)extent.Y / (int)Constants.RegionSize) + 1;
  359. int startX = (int)(pRegionLocX - 1) * (int)Constants.RegionSize;
  360. int startY = (int)(pRegionLocY - 1) * (int)Constants.RegionSize;
  361. int endX = ((int)pRegionLocX + (int)extent.X) * (int)Constants.RegionSize;
  362. int endY = ((int)pRegionLocY + (int)extent.Y) * (int)Constants.RegionSize;
  363. List<GridRegion> neighbours = m_scene.GridService.GetRegionRange(m_regionInfo.ScopeID, startX, endX, startY, endY);
  364. neighbours.RemoveAll(delegate(GridRegion r) { return r.RegionID == m_regionInfo.RegionID; });
  365. return neighbours;
  366. //SimpleRegionInfo regionData = m_commsProvider.GridService.RequestNeighbourInfo()
  367. //return m_commsProvider.GridService.RequestNeighbours(pRegionLocX, pRegionLocY);
  368. }
  369. }
  370. /// <summary>
  371. /// This informs all neighboring regions about agent "avatar".
  372. /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
  373. /// </summary>
  374. public void EnableNeighbourChildAgents(ScenePresence avatar, List<RegionInfo> lstneighbours)
  375. {
  376. //List<SimpleRegionInfo> neighbours = new List<SimpleRegionInfo>();
  377. List<GridRegion> neighbours = new List<GridRegion>();
  378. ////m_commsProvider.GridService.RequestNeighbours(m_regionInfo.RegionLocX, m_regionInfo.RegionLocY);
  379. //for (int i = 0; i < lstneighbours.Count; i++)
  380. //{
  381. // // We don't want to keep sending to regions that consistently fail on comms.
  382. // if (!(lstneighbours[i].commFailTF))
  383. // {
  384. // neighbours.Add(new SimpleRegionInfo(lstneighbours[i]));
  385. // }
  386. //}
  387. // we're going to be using the above code once neighbour cache is correct. Currently it doesn't appear to be
  388. // So we're temporarily going back to the old method of grabbing it from the Grid Server Every time :/
  389. if (m_regionInfo != null)
  390. {
  391. neighbours = RequestNeighbours(avatar.Scene,m_regionInfo.RegionLocX, m_regionInfo.RegionLocY);
  392. }
  393. else
  394. {
  395. m_log.Debug("[ENABLENEIGHBOURCHILDAGENTS]: m_regionInfo was null in EnableNeighbourChildAgents, is this a NPC?");
  396. }
  397. /// We need to find the difference between the new regions where there are no child agents
  398. /// and the regions where there are already child agents. We only send notification to the former.
  399. List<ulong> neighbourHandles = NeighbourHandles(neighbours); // on this region
  400. neighbourHandles.Add(avatar.Scene.RegionInfo.RegionHandle); // add this region too
  401. List<ulong> previousRegionNeighbourHandles ;
  402. if (avatar.Scene.CapsModule != null)
  403. {
  404. previousRegionNeighbourHandles =
  405. new List<ulong>(avatar.Scene.CapsModule.GetChildrenSeeds(avatar.UUID).Keys);
  406. }
  407. else
  408. {
  409. previousRegionNeighbourHandles = new List<ulong>();
  410. }
  411. List<ulong> newRegions = NewNeighbours(neighbourHandles, previousRegionNeighbourHandles);
  412. List<ulong> oldRegions = OldNeighbours(neighbourHandles, previousRegionNeighbourHandles);
  413. //Dump("Current Neighbors", neighbourHandles);
  414. //Dump("Previous Neighbours", previousRegionNeighbourHandles);
  415. //Dump("New Neighbours", newRegions);
  416. //Dump("Old Neighbours", oldRegions);
  417. /// Update the scene presence's known regions here on this region
  418. avatar.DropOldNeighbours(oldRegions);
  419. /// Collect as many seeds as possible
  420. Dictionary<ulong, string> seeds;
  421. if (avatar.Scene.CapsModule != null)
  422. seeds
  423. = new Dictionary<ulong, string>(avatar.Scene.CapsModule.GetChildrenSeeds(avatar.UUID));
  424. else
  425. seeds = new Dictionary<ulong, string>();
  426. //m_log.Debug(" !!! No. of seeds: " + seeds.Count);
  427. if (!seeds.ContainsKey(avatar.Scene.RegionInfo.RegionHandle))
  428. seeds.Add(avatar.Scene.RegionInfo.RegionHandle, avatar.ControllingClient.RequestClientInfo().CapsPath);
  429. /// Create the necessary child agents
  430. List<AgentCircuitData> cagents = new List<AgentCircuitData>();
  431. //foreach (SimpleRegionInfo neighbour in neighbours)
  432. foreach (GridRegion neighbour in neighbours)
  433. {
  434. if (neighbour.RegionHandle != avatar.Scene.RegionInfo.RegionHandle)
  435. {
  436. AgentCircuitData agent = avatar.ControllingClient.RequestClientInfo();
  437. agent.BaseFolder = UUID.Zero;
  438. agent.InventoryFolder = UUID.Zero;
  439. agent.startpos = new Vector3(128, 128, 70);
  440. agent.child = true;
  441. if (newRegions.Contains(neighbour.RegionHandle))
  442. {
  443. agent.CapsPath = CapsUtil.GetRandomCapsObjectPath();
  444. avatar.AddNeighbourRegion(neighbour.RegionHandle, agent.CapsPath);
  445. seeds.Add(neighbour.RegionHandle, agent.CapsPath);
  446. }
  447. else
  448. agent.CapsPath = avatar.Scene.CapsModule.GetChildSeed(avatar.UUID, neighbour.RegionHandle);
  449. cagents.Add(agent);
  450. }
  451. }
  452. /// Update all child agent with everyone's seeds
  453. foreach (AgentCircuitData a in cagents)
  454. {
  455. a.ChildrenCapSeeds = new Dictionary<ulong, string>(seeds);
  456. }
  457. if (avatar.Scene.CapsModule != null)
  458. {
  459. // These two are the same thing!
  460. avatar.Scene.CapsModule.SetChildrenSeed(avatar.UUID, seeds);
  461. }
  462. avatar.KnownRegions = seeds;
  463. //avatar.Scene.DumpChildrenSeeds(avatar.UUID);
  464. //avatar.DumpKnownRegions();
  465. bool newAgent = false;
  466. int count = 0;
  467. foreach (GridRegion neighbour in neighbours)
  468. {
  469. // Don't do it if there's already an agent in that region
  470. if (newRegions.Contains(neighbour.RegionHandle))
  471. newAgent = true;
  472. else
  473. newAgent = false;
  474. if (neighbour.RegionHandle != avatar.Scene.RegionInfo.RegionHandle)
  475. {
  476. InformClientOfNeighbourDelegate d = InformClientOfNeighbourAsync;
  477. try
  478. {
  479. d.BeginInvoke(avatar, cagents[count], neighbour, neighbour.ExternalEndPoint, newAgent,
  480. InformClientOfNeighbourCompleted,
  481. d);
  482. }
  483. catch (ArgumentOutOfRangeException)
  484. {
  485. m_log.ErrorFormat(
  486. "[REGIONINFO]: Neighbour Regions response included the current region in the neighbor list. The following region will not display to the client: {0} for region {1} ({2}, {3}).",
  487. neighbour.ExternalHostName,
  488. neighbour.RegionHandle,
  489. neighbour.RegionLocX,
  490. neighbour.RegionLocY);
  491. }
  492. catch (Exception e)
  493. {
  494. m_log.ErrorFormat(
  495. "[REGIONINFO]: Could not resolve external hostname {0} for region {1} ({2}, {3}). {4}",
  496. neighbour.ExternalHostName,
  497. neighbour.RegionHandle,
  498. neighbour.RegionLocX,
  499. neighbour.RegionLocY,
  500. e);
  501. // FIXME: Okay, even though we've failed, we're still going to throw the exception on,
  502. // since I don't know what will happen if we just let the client continue
  503. // XXX: Well, decided to swallow the exception instead for now. Let us see how that goes.
  504. // throw e;
  505. }
  506. }
  507. count++;
  508. }
  509. }
  510. /// <summary>
  511. /// This informs a single neighboring region about agent "avatar".
  512. /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
  513. /// </summary>
  514. public void InformNeighborChildAgent(ScenePresence avatar, GridRegion region)
  515. {
  516. AgentCircuitData agent = avatar.ControllingClient.RequestClientInfo();
  517. agent.BaseFolder = UUID.Zero;
  518. agent.InventoryFolder = UUID.Zero;
  519. agent.startpos = new Vector3(128, 128, 70);
  520. agent.child = true;
  521. InformClientOfNeighbourDelegate d = InformClientOfNeighbourAsync;
  522. d.BeginInvoke(avatar, agent, region, region.ExternalEndPoint, true,
  523. InformClientOfNeighbourCompleted,
  524. d);
  525. }
  526. #endregion
  527. public delegate void InformNeighbourThatRegionUpDelegate(INeighbourService nService, RegionInfo region, ulong regionhandle);
  528. private void InformNeighborsThatRegionisUpCompleted(IAsyncResult iar)
  529. {
  530. InformNeighbourThatRegionUpDelegate icon = (InformNeighbourThatRegionUpDelegate) iar.AsyncState;
  531. icon.EndInvoke(iar);
  532. }
  533. /// <summary>
  534. /// Asynchronous call to information neighbouring regions that this region is up
  535. /// </summary>
  536. /// <param name="region"></param>
  537. /// <param name="regionhandle"></param>
  538. private void InformNeighboursThatRegionIsUpAsync(INeighbourService neighbourService, RegionInfo region, ulong regionhandle)
  539. {
  540. uint x = 0, y = 0;
  541. Utils.LongToUInts(regionhandle, out x, out y);
  542. GridRegion neighbour = null;
  543. if (neighbourService != null)
  544. neighbour = neighbourService.HelloNeighbour(regionhandle, region);
  545. else
  546. m_log.DebugFormat("[SCS]: No neighbour service provided for informing neigbhours of this region");
  547. if (neighbour != null)
  548. {
  549. m_log.DebugFormat("[INTERGRID]: Successfully informed neighbour {0}-{1} that I'm here", x / Constants.RegionSize, y / Constants.RegionSize);
  550. m_scene.EventManager.TriggerOnRegionUp(neighbour);
  551. }
  552. else
  553. {
  554. m_log.WarnFormat("[INTERGRID]: Failed to inform neighbour {0}-{1} that I'm here.", x / Constants.RegionSize, y / Constants.RegionSize);
  555. }
  556. }
  557. public void InformNeighborsThatRegionisUp(INeighbourService neighbourService, RegionInfo region)
  558. {
  559. //m_log.Info("[INTER]: " + debugRegionName + ": SceneCommunicationService: Sending InterRegion Notification that region is up " + region.RegionName);
  560. for (int x = (int)region.RegionLocX - 1; x <= region.RegionLocX + 1; x++)
  561. for (int y = (int)region.RegionLocY - 1; y <= region.RegionLocY + 1; y++)
  562. if (!((x == region.RegionLocX) && (y == region.RegionLocY))) // skip this region
  563. {
  564. ulong handle = Utils.UIntsToLong((uint)x * Constants.RegionSize, (uint)y * Constants.RegionSize);
  565. InformNeighbourThatRegionUpDelegate d = InformNeighboursThatRegionIsUpAsync;
  566. d.BeginInvoke(neighbourService, region, handle,
  567. InformNeighborsThatRegionisUpCompleted,
  568. d);
  569. }
  570. //List<GridRegion> neighbours = new List<GridRegion>();
  571. //// This stays uncached because we don't already know about our neighbors at this point.
  572. //neighbours = m_scene.GridService.GetNeighbours(m_regionInfo.ScopeID, m_regionInfo.RegionID);
  573. //if (neighbours != null)
  574. //{
  575. // for (int i = 0; i < neighbours.Count; i++)
  576. // {
  577. // InformNeighbourThatRegionUpDelegate d = InformNeighboursThatRegionIsUpAsync;
  578. // d.BeginInvoke(neighbourService, region, neighbours[i].RegionHandle,
  579. // InformNeighborsThatRegionisUpCompleted,
  580. // d);
  581. // }
  582. //}
  583. //bool val = m_commsProvider.InterRegion.RegionUp(new SerializableRegionInfo(region));
  584. }
  585. public delegate void SendChildAgentDataUpdateDelegate(AgentPosition cAgentData, ulong regionHandle);
  586. /// <summary>
  587. /// This informs all neighboring regions about the settings of it's child agent.
  588. /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
  589. ///
  590. /// This contains information, such as, Draw Distance, Camera location, Current Position, Current throttle settings, etc.
  591. ///
  592. /// </summary>
  593. private void SendChildAgentDataUpdateAsync(AgentPosition cAgentData, ulong regionHandle)
  594. {
  595. //m_log.Info("[INTERGRID]: Informing neighbors about my agent in " + m_regionInfo.RegionName);
  596. try
  597. {
  598. //m_commsProvider.InterRegion.ChildAgentUpdate(regionHandle, cAgentData);
  599. m_interregionCommsOut.SendChildAgentUpdate(regionHandle, cAgentData);
  600. }
  601. catch
  602. {
  603. // Ignore; we did our best
  604. }
  605. //if (regionAccepted)
  606. //{
  607. // //m_log.Info("[INTERGRID]: Completed sending a neighbor an update about my agent");
  608. //}
  609. //else
  610. //{
  611. // //m_log.Info("[INTERGRID]: Failed sending a neighbor an update about my agent");
  612. //}
  613. }
  614. private void SendChildAgentDataUpdateCompleted(IAsyncResult iar)
  615. {
  616. SendChildAgentDataUpdateDelegate icon = (SendChildAgentDataUpdateDelegate) iar.AsyncState;
  617. icon.EndInvoke(iar);
  618. }
  619. public void SendChildAgentDataUpdate(AgentPosition cAgentData, ScenePresence presence)
  620. {
  621. // This assumes that we know what our neighbors are.
  622. try
  623. {
  624. foreach (ulong regionHandle in presence.KnownChildRegionHandles)
  625. {
  626. if (regionHandle != m_regionInfo.RegionHandle)
  627. {
  628. SendChildAgentDataUpdateDelegate d = SendChildAgentDataUpdateAsync;
  629. d.BeginInvoke(cAgentData, regionHandle,
  630. SendChildAgentDataUpdateCompleted,
  631. d);
  632. }
  633. }
  634. }
  635. catch (InvalidOperationException)
  636. {
  637. // We're ignoring a collection was modified error because this data gets old and outdated fast.
  638. }
  639. }
  640. public delegate void SendCloseChildAgentDelegate(UUID agentID, ulong regionHandle);
  641. /// <summary>
  642. /// This Closes child agents on neighboring regions
  643. /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
  644. /// </summary>
  645. protected void SendCloseChildAgentAsync(UUID agentID, ulong regionHandle)
  646. {
  647. m_log.Debug("[INTERGRID]: Sending close agent to " + regionHandle);
  648. // let's do our best, but there's not much we can do if the neighbour doesn't accept.
  649. //m_commsProvider.InterRegion.TellRegionToCloseChildConnection(regionHandle, agentID);
  650. m_interregionCommsOut.SendCloseAgent(regionHandle, agentID);
  651. }
  652. private void SendCloseChildAgentCompleted(IAsyncResult iar)
  653. {
  654. SendCloseChildAgentDelegate icon = (SendCloseChildAgentDelegate)iar.AsyncState;
  655. icon.EndInvoke(iar);
  656. }
  657. public void SendCloseChildAgentConnections(UUID agentID, List<ulong> regionslst)
  658. {
  659. foreach (ulong handle in regionslst)
  660. {
  661. SendCloseChildAgentDelegate d = SendCloseChildAgentAsync;
  662. d.BeginInvoke(agentID, handle,
  663. SendCloseChildAgentCompleted,
  664. d);
  665. }
  666. }
  667. /// <summary>
  668. /// Try to teleport an agent to a new region.
  669. /// </summary>
  670. /// <param name="remoteClient"></param>
  671. /// <param name="RegionHandle"></param>
  672. /// <param name="position"></param>
  673. /// <param name="lookAt"></param>
  674. /// <param name="flags"></param>
  675. public virtual void RequestTeleportToLocation(ScenePresence avatar, ulong regionHandle, Vector3 position,
  676. Vector3 lookAt, uint teleportFlags)
  677. {
  678. if (!avatar.Scene.Permissions.CanTeleport(avatar.UUID))
  679. return;
  680. bool destRegionUp = true;
  681. IEventQueue eq = avatar.Scene.RequestModuleInterface<IEventQueue>();
  682. // Reset animations; the viewer does that in teleports.
  683. avatar.ResetAnimations();
  684. if (regionHandle == m_regionInfo.RegionHandle)
  685. {
  686. m_log.DebugFormat(
  687. "[SCENE COMMUNICATION SERVICE]: RequestTeleportToLocation {0} within {1}",
  688. position, m_regionInfo.RegionName);
  689. // Teleport within the same region
  690. if (IsOutsideRegion(avatar.Scene, position) || position.Z < 0)
  691. {
  692. Vector3 emergencyPos = new Vector3(128, 128, 128);
  693. m_log.WarnFormat(
  694. "[SCENE COMMUNICATION SERVICE]: RequestTeleportToLocation() was given an illegal position of {0} for avatar {1}, {2}. Substituting {3}",
  695. position, avatar.Name, avatar.UUID, emergencyPos);
  696. position = emergencyPos;
  697. }
  698. // TODO: Get proper AVG Height
  699. float localAVHeight = 1.56f;
  700. float posZLimit = 22;
  701. // TODO: Check other Scene HeightField
  702. if (position.X > 0 && position.X <= (int)Constants.RegionSize && position.Y > 0 && position.Y <=(int)Constants.RegionSize)
  703. {
  704. posZLimit = (float) avatar.Scene.Heightmap[(int) position.X, (int) position.Y];
  705. }
  706. float newPosZ = posZLimit + localAVHeight;
  707. if (posZLimit >= (position.Z - (localAVHeight / 2)) && !(Single.IsInfinity(newPosZ) || Single.IsNaN(newPosZ)))
  708. {
  709. position.Z = newPosZ;
  710. }
  711. // Only send this if the event queue is null
  712. if (eq == null)
  713. avatar.ControllingClient.SendTeleportLocationStart();
  714. avatar.ControllingClient.SendLocalTeleport(position, lookAt, teleportFlags);
  715. avatar.Teleport(position);
  716. }
  717. else
  718. {
  719. uint x = 0, y = 0;
  720. Utils.LongToUInts(regionHandle, out x, out y);
  721. GridRegion reg = m_scene.GridService.GetRegionByPosition(m_scene.RegionInfo.ScopeID, (int)x, (int)y);
  722. if (reg != null)
  723. {
  724. m_log.DebugFormat(
  725. "[SCENE COMMUNICATION SERVICE]: RequestTeleportToLocation to {0} in {1}",
  726. position, reg.RegionName);
  727. if (eq == null)
  728. avatar.ControllingClient.SendTeleportLocationStart();
  729. // Let's do DNS resolution only once in this process, please!
  730. // This may be a costly operation. The reg.ExternalEndPoint field is not a passive field,
  731. // it's actually doing a lot of work.
  732. IPEndPoint endPoint = reg.ExternalEndPoint;
  733. if (endPoint.Address == null)
  734. {
  735. // Couldn't resolve the name. Can't TP, because the viewer wants IP addresses.
  736. destRegionUp = false;
  737. }
  738. if (destRegionUp)
  739. {
  740. uint newRegionX = (uint)(reg.RegionHandle >> 40);
  741. uint newRegionY = (((uint)(reg.RegionHandle)) >> 8);
  742. uint oldRegionX = (uint)(m_regionInfo.RegionHandle >> 40);
  743. uint oldRegionY = (((uint)(m_regionInfo.RegionHandle)) >> 8);
  744. // Fixing a bug where teleporting while sitting results in the avatar ending up removed from
  745. // both regions
  746. if (avatar.ParentID != (uint)0)
  747. avatar.StandUp();
  748. if (!avatar.ValidateAttachments())
  749. {
  750. avatar.ControllingClient.SendTeleportFailed("Inconsistent attachment state");
  751. return;
  752. }
  753. // the avatar.Close below will clear the child region list. We need this below for (possibly)
  754. // closing the child agents, so save it here (we need a copy as it is Clear()-ed).
  755. //List<ulong> childRegions = new List<ulong>(avatar.GetKnownRegionList());
  756. // Compared to ScenePresence.CrossToNewRegion(), there's no obvious code to handle a teleport
  757. // failure at this point (unlike a border crossing failure). So perhaps this can never fail
  758. // once we reach here...
  759. //avatar.Scene.RemoveCapsHandler(avatar.UUID);
  760. string capsPath = String.Empty;
  761. AgentCircuitData agentCircuit = avatar.ControllingClient.RequestClientInfo();
  762. agentCircuit.BaseFolder = UUID.Zero;
  763. agentCircuit.InventoryFolder = UUID.Zero;
  764. agentCircuit.startpos = position;
  765. agentCircuit.child = true;
  766. if (Util.IsOutsideView(oldRegionX, newRegionX, oldRegionY, newRegionY))
  767. {
  768. // brand new agent, let's create a new caps seed
  769. agentCircuit.CapsPath = CapsUtil.GetRandomCapsObjectPath();
  770. }
  771. string reason = String.Empty;
  772. // Let's create an agent there if one doesn't exist yet.
  773. //if (!m_commsProvider.InterRegion.InformRegionOfChildAgent(reg.RegionHandle, agentCircuit))
  774. if (!m_interregionCommsOut.SendCreateChildAgent(reg.RegionHandle, agentCircuit, out reason))
  775. {
  776. avatar.ControllingClient.SendTeleportFailed(String.Format("Destination is not accepting teleports: {0}",
  777. reason));
  778. return;
  779. }
  780. // OK, it got this agent. Let's close some child agents
  781. avatar.CloseChildAgents(newRegionX, newRegionY);
  782. if (Util.IsOutsideView(oldRegionX, newRegionX, oldRegionY, newRegionY))
  783. {
  784. #region IP Translation for NAT
  785. IClientIPEndpoint ipepClient;
  786. if (avatar.ClientView.TryGet(out ipepClient))
  787. {
  788. capsPath
  789. = "http://"
  790. + NetworkUtil.GetHostFor(ipepClient.EndPoint, reg.ExternalHostName)
  791. + ":"
  792. + reg.HttpPort
  793. + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
  794. }
  795. else
  796. {
  797. capsPath
  798. = "http://"
  799. + reg.ExternalHostName
  800. + ":"
  801. + reg.HttpPort
  802. + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
  803. }
  804. #endregion
  805. if (eq != null)
  806. {
  807. #region IP Translation for NAT
  808. // Uses ipepClient above
  809. if (avatar.ClientView.TryGet(out ipepClient))
  810. {
  811. endPoint.Address = NetworkUtil.GetIPFor(ipepClient.EndPoint, endPoint.Address);
  812. }
  813. #endregion
  814. eq.EnableSimulator(reg.RegionHandle, endPoint, avatar.UUID);
  815. // ES makes the client send a UseCircuitCode message to the destination,
  816. // which triggers a bunch of things there.
  817. // So let's wait
  818. Thread.Sleep(2000);
  819. eq.EstablishAgentCommunication(avatar.UUID, endPoint, capsPath);
  820. }
  821. else
  822. {
  823. avatar.ControllingClient.InformClientOfNeighbour(reg.RegionHandle, endPoint);
  824. }
  825. }
  826. else
  827. {
  828. agentCircuit.CapsPath = avatar.Scene.CapsModule.GetChildSeed(avatar.UUID, reg.RegionHandle);
  829. capsPath = "http://" + reg.ExternalHostName + ":" + reg.HttpPort
  830. + "/CAPS/" + agentCircuit.CapsPath + "0000/";
  831. }
  832. // Expect avatar crossing is a heavy-duty function at the destination.
  833. // That is where MakeRoot is called, which fetches appearance and inventory.
  834. // Plus triggers OnMakeRoot, which spawns a series of asynchronous updates.
  835. //m_commsProvider.InterRegion.ExpectAvatarCrossing(reg.RegionHandle, avatar.ControllingClient.AgentId,
  836. // position, false);
  837. //{
  838. // avatar.ControllingClient.SendTeleportFailed("Problem with destination.");
  839. // // We should close that agent we just created over at destination...
  840. // List<ulong> lst = new List<ulong>();
  841. // lst.Add(reg.RegionHandle);
  842. // SendCloseChildAgentAsync(avatar.UUID, lst);
  843. // return;
  844. //}
  845. SetInTransit(avatar.UUID);
  846. // Let's send a full update of the agent. This is a synchronous call.
  847. AgentData agent = new AgentData();
  848. avatar.CopyTo(agent);
  849. agent.Position = position;
  850. agent.CallbackURI = "http://" + m_regionInfo.ExternalHostName + ":" + m_regionInfo.HttpPort +
  851. "/agent/" + avatar.UUID.ToString() + "/" + avatar.Scene.RegionInfo.RegionHandle.ToString() + "/release/";
  852. m_interregionCommsOut.SendChildAgentUpdate(reg.RegionHandle, agent);
  853. m_log.DebugFormat(
  854. "[CAPS]: Sending new CAPS seed url {0} to client {1}", capsPath, avatar.UUID);
  855. if (eq != null)
  856. {
  857. eq.TeleportFinishEvent(reg.RegionHandle, 13, endPoint,
  858. 0, teleportFlags, capsPath, avatar.UUID);
  859. }
  860. else
  861. {
  862. avatar.ControllingClient.SendRegionTeleport(reg.RegionHandle, 13, endPoint, 4,
  863. teleportFlags, capsPath);
  864. }
  865. // TeleportFinish makes the client send CompleteMovementIntoRegion (at the destination), which
  866. // trigers a whole shebang of things there, including MakeRoot. So let's wait for confirmation
  867. // that the client contacted the destination before we send the attachments and close things here.
  868. if (!WaitForCallback(avatar.UUID))
  869. {
  870. // Client never contacted destination. Let's restore everything back
  871. avatar.ControllingClient.SendTeleportFailed("Problems connecting to destination.");
  872. ResetFromTransit(avatar.UUID);
  873. // Yikes! We should just have a ref to scene here.
  874. avatar.Scene.InformClientOfNeighbours(avatar);
  875. // Finally, kill the agent we just created at the destination.
  876. m_interregionCommsOut.SendCloseAgent(reg.RegionHandle, avatar.UUID);
  877. return;
  878. }
  879. // Can't go back from here
  880. if (KiPrimitive != null)
  881. {
  882. KiPrimitive(avatar.LocalId);
  883. }
  884. avatar.MakeChildAgent();
  885. // CrossAttachmentsIntoNewRegion is a synchronous call. We shouldn't need to wait after it
  886. avatar.CrossAttachmentsIntoNewRegion(reg.RegionHandle, true);
  887. // Finally, let's close this previously-known-as-root agent, when the jump is outside the view zone
  888. if (Util.IsOutsideView(oldRegionX, newRegionX, oldRegionY, newRegionY))
  889. {
  890. Thread.Sleep(5000);
  891. avatar.Close();
  892. CloseConnection(avatar.UUID);
  893. }
  894. else
  895. // now we have a child agent in this region.
  896. avatar.Reset();
  897. // if (teleport success) // seems to be always success here
  898. // the user may change their profile information in other region,
  899. // so the userinfo in UserProfileCache is not reliable any more, delete it
  900. if (avatar.Scene.NeedSceneCacheClear(avatar.UUID))
  901. {
  902. m_commsProvider.UserProfileCacheService.RemoveUser(avatar.UUID);
  903. m_log.DebugFormat(
  904. "[SCENE COMMUNICATION SERVICE]: User {0} is going to another region, profile cache removed",
  905. avatar.UUID);
  906. }
  907. }
  908. else
  909. {
  910. avatar.ControllingClient.SendTeleportFailed("Remote Region appears to be down");
  911. }
  912. }
  913. else
  914. {
  915. // TP to a place that doesn't exist (anymore)
  916. // Inform the viewer about that
  917. avatar.ControllingClient.SendTeleportFailed("The region you tried to teleport to doesn't exist anymore");
  918. // and set the map-tile to '(Offline)'
  919. uint regX, regY;
  920. Utils.LongToUInts(regionHandle, out regX, out regY);
  921. MapBlockData block = new MapBlockData();
  922. block.X = (ushort)(regX / Constants.RegionSize);
  923. block.Y = (ushort)(regY / Constants.RegionSize);
  924. block.Access = 254; // == not there
  925. List<MapBlockData> blocks = new List<MapBlockData>();
  926. blocks.Add(block);
  927. avatar.ControllingClient.SendMapBlock(blocks, 0);
  928. }
  929. }
  930. }
  931. protected bool IsOutsideRegion(Scene s, Vector3 pos)
  932. {
  933. if (s.TestBorderCross(pos,Cardinals.N))
  934. return true;
  935. if (s.TestBorderCross(pos, Cardinals.S))
  936. return true;
  937. if (s.TestBorderCross(pos, Cardinals.E))
  938. return true;
  939. if (s.TestBorderCross(pos, Cardinals.W))
  940. return true;
  941. return false;
  942. }
  943. public bool WaitForCallback(UUID id)
  944. {
  945. int count = 200;
  946. while (m_agentsInTransit.Contains(id) && count-- > 0)
  947. {
  948. //m_log.Debug(" >>> Waiting... " + count);
  949. Thread.Sleep(100);
  950. }
  951. if (count > 0)
  952. return true;
  953. else
  954. return false;
  955. }
  956. public bool ReleaseAgent(UUID id)
  957. {
  958. //m_log.Debug(" >>> ReleaseAgent called <<< ");
  959. return ResetFromTransit(id);
  960. }
  961. public void SetInTransit(UUID id)
  962. {
  963. lock (m_agentsInTransit)
  964. {
  965. if (!m_agentsInTransit.Contains(id))
  966. m_agentsInTransit.Add(id);
  967. }
  968. }
  969. protected bool ResetFromTransit(UUID id)
  970. {
  971. lock (m_agentsInTransit)
  972. {
  973. if (m_agentsInTransit.Contains(id))
  974. {
  975. m_agentsInTransit.Remove(id);
  976. return true;
  977. }
  978. }
  979. return false;
  980. }
  981. private List<ulong> NeighbourHandles(List<GridRegion> neighbours)
  982. {
  983. List<ulong> handles = new List<ulong>();
  984. foreach (GridRegion reg in neighbours)
  985. {
  986. handles.Add(reg.RegionHandle);
  987. }
  988. return handles;
  989. }
  990. private List<ulong> NewNeighbours(List<ulong> currentNeighbours, List<ulong> previousNeighbours)
  991. {
  992. return currentNeighbours.FindAll(delegate(ulong handle) { return !previousNeighbours.Contains(handle); });
  993. }
  994. // private List<ulong> CommonNeighbours(List<ulong> currentNeighbours, List<ulong> previousNeighbours)
  995. // {
  996. // return currentNeighbours.FindAll(delegate(ulong handle) { return previousNeighbours.Contains(handle); });
  997. // }
  998. private List<ulong> OldNeighbours(List<ulong> currentNeighbours, List<ulong> previousNeighbours)
  999. {
  1000. return previousNeighbours.FindAll(delegate(ulong handle) { return !currentNeighbours.Contains(handle); });
  1001. }
  1002. public void CrossAgentToNewRegion(Scene scene, ScenePresence agent, bool isFlying)
  1003. {
  1004. Vector3 pos = agent.AbsolutePosition;
  1005. Vector3 newpos = new Vector3(pos.X, pos.Y, pos.Z);
  1006. uint neighbourx = m_regionInfo.RegionLocX;
  1007. uint neighboury = m_regionInfo.RegionLocY;
  1008. const float boundaryDistance = 1.7f;
  1009. Vector3 northCross = new Vector3(0,boundaryDistance, 0);
  1010. Vector3 southCross = new Vector3(0, -1 * boundaryDistance, 0);
  1011. Vector3 eastCross = new Vector3(boundaryDistance, 0, 0);
  1012. Vector3 westCross = new Vector3(-1 * boundaryDistance, 0, 0);
  1013. // distance to edge that will trigger crossing
  1014. // distance into new region to place avatar
  1015. const float enterDistance = 0.5f;
  1016. if (scene.TestBorderCross(pos + westCross, Cardinals.W))
  1017. {
  1018. if (scene.TestBorderCross(pos + northCross, Cardinals.N))
  1019. {
  1020. Border b = scene.GetCrossedBorder(pos + northCross, Cardinals.N);
  1021. neighboury += (uint)(int)(b.BorderLine.Z / (int)Constants.RegionSize);
  1022. }
  1023. else if (scene.TestBorderCross(pos + southCross, Cardinals.S))
  1024. {
  1025. Border b = scene.GetCrossedBorder(pos + southCross, Cardinals.S);
  1026. if (b.TriggerRegionX == 0 && b.TriggerRegionY == 0)
  1027. {
  1028. neighboury--;
  1029. newpos.Y = Constants.RegionSize - enterDistance;
  1030. }
  1031. else
  1032. {
  1033. neighboury = b.TriggerRegionY;
  1034. neighbourx = b.TriggerRegionX;
  1035. Vector3 newposition = pos;
  1036. newposition.X += (scene.RegionInfo.RegionLocX - neighbourx) * Constants.RegionSize;
  1037. newposition.Y += (scene.RegionInfo.RegionLocY - neighboury) * Constants.RegionSize;
  1038. agent.ControllingClient.SendAgentAlertMessage(
  1039. String.Format("Moving you to region {0},{1}", neighbourx, neighboury), false);
  1040. InformClientToInitateTeleportToLocation(agent, neighbourx, neighboury, newposition, scene);
  1041. return;
  1042. }
  1043. }
  1044. Border ba = scene.GetCrossedBorder(pos + westCross, Cardinals.W);
  1045. if (ba.TriggerRegionX == 0 && ba.TriggerRegionY == 0)
  1046. {
  1047. neighbourx--;
  1048. newpos.X = Constants.RegionSize - enterDistance;
  1049. }
  1050. else
  1051. {
  1052. neighboury = ba.TriggerRegionY;
  1053. neighbourx = ba.TriggerRegionX;
  1054. Vector3 newposition = pos;
  1055. newposition.X += (scene.RegionInfo.RegionLocX - neighbourx) * Constants.RegionSize;
  1056. newposition.Y += (scene.RegionInfo.RegionLocY - neighboury) * Constants.RegionSize;
  1057. agent.ControllingClient.SendAgentAlertMessage(
  1058. String.Format("Moving you to region {0},{1}", neighbourx, neighboury), false);
  1059. InformClientToInitateTeleportToLocation(agent, neighbourx, neighboury, newposition, scene);
  1060. return;
  1061. }
  1062. }
  1063. else if (scene.TestBorderCross(pos + eastCross, Cardinals.E))
  1064. {
  1065. Border b = scene.GetCrossedBorder(pos + eastCross, Cardinals.E);
  1066. neighbourx += (uint)(int)(b.BorderLine.Z / (int)Constants.RegionSize);
  1067. newpos.X = enterDistance;
  1068. if (scene.TestBorderCross(pos + southCross, Cardinals.S))
  1069. {
  1070. Border ba = scene.GetCrossedBorder(pos + southCross, Cardinals.S);
  1071. if (ba.TriggerRegionX == 0 && ba.TriggerRegionY == 0)
  1072. {
  1073. neighboury--;
  1074. newpos.Y = Constants.RegionSize - enterDistance;
  1075. }
  1076. else
  1077. {
  1078. neighboury = ba.TriggerRegionY;
  1079. neighbourx = ba.TriggerRegionX;
  1080. Vector3 newposition = pos;
  1081. newposition.X += (scene.RegionInfo.RegionLocX - neighbourx) * Constants.RegionSize;
  1082. newposition.Y += (scene.RegionInfo.RegionLocY - neighboury) * Constants.RegionSize;
  1083. agent.ControllingClient.SendAgentAlertMessage(
  1084. String.Format("Moving you to region {0},{1}", neighbourx, neighboury), false);
  1085. InformClientToInitateTeleportToLocation(agent, neighbourx, neighboury, newposition, scene);
  1086. return;
  1087. }
  1088. }
  1089. else if (scene.TestBorderCross(pos + northCross, Cardinals.N))
  1090. {
  1091. Border c = scene.GetCrossedBorder(pos + northCross, Cardinals.N);
  1092. neighboury += (uint)(int)(c.BorderLine.Z / (int)Constants.RegionSize);
  1093. newpos.Y = enterDistance;
  1094. }
  1095. }
  1096. else if (scene.TestBorderCross(pos + southCross, Cardinals.S))
  1097. {
  1098. Border b = scene.GetCrossedBorder(pos + southCross, Cardinals.S);
  1099. if (b.TriggerRegionX == 0 && b.TriggerRegionY == 0)
  1100. {
  1101. neighboury--;
  1102. newpos.Y = Constants.RegionSize - enterDistance;
  1103. }
  1104. else
  1105. {
  1106. neighboury = b.TriggerRegionY;
  1107. neighbourx = b.TriggerRegionX;
  1108. Vector3 newposition = pos;
  1109. newposition.X += (scene.RegionInfo.RegionLocX - neighbourx) * Constants.RegionSize;
  1110. newposition.Y += (scene.RegionInfo.RegionLocY - neighboury) * Constants.RegionSize;
  1111. agent.ControllingClient.SendAgentAlertMessage(
  1112. String.Format("Moving you to region {0},{1}", neighbourx, neighboury), false);
  1113. InformClientToInitateTeleportToLocation(agent, neighbourx, neighboury, newposition, scene);
  1114. return;
  1115. }
  1116. }
  1117. else if (scene.TestBorderCross(pos + northCross, Cardinals.N))
  1118. {
  1119. Border b = scene.GetCrossedBorder(pos + northCross, Cardinals.N);
  1120. neighboury += (uint)(int)(b.BorderLine.Z / (int)Constants.RegionSize);
  1121. newpos.Y = enterDistance;
  1122. }
  1123. /*
  1124. if (pos.X < boundaryDistance) //West
  1125. {
  1126. neighbourx--;
  1127. newpos.X = Constants.RegionSize - enterDistance;
  1128. }
  1129. else if (pos.X > Constants.RegionSize - boundaryDistance) // East
  1130. {
  1131. neighbourx++;
  1132. newpos.X = enterDistance;
  1133. }
  1134. if (pos.Y < boundaryDistance) // South
  1135. {
  1136. neighboury--;
  1137. newpos.Y = Constants.RegionSize - enterDistance;
  1138. }
  1139. else if (pos.Y > Constants.RegionSize - boundaryDistance) // North
  1140. {
  1141. neighboury++;
  1142. newpos.Y = enterDistance;
  1143. }
  1144. */
  1145. CrossAgentToNewRegionDelegate d = CrossAgentToNewRegionAsync;
  1146. d.BeginInvoke(agent, newpos, neighbourx, neighboury, isFlying, CrossAgentToNewRegionCompleted, d);
  1147. }
  1148. public delegate void InformClientToInitateTeleportToLocationDelegate(ScenePresence agent, uint regionX, uint regionY,
  1149. Vector3 position,
  1150. Scene initiatingScene);
  1151. public void InformClientToInitateTeleportToLocation(ScenePresence agent, uint regionX, uint regionY, Vector3 position,
  1152. Scene initiatingScene)
  1153. {
  1154. // This assumes that we know what our neighbors are.
  1155. InformClientToInitateTeleportToLocationDelegate d = InformClientToInitiateTeleportToLocationAsync;
  1156. d.BeginInvoke(agent,regionX,regionY,position,initiatingScene,
  1157. InformClientToInitiateTeleportToLocationCompleted,
  1158. d);
  1159. }
  1160. public void InformClientToInitiateTeleportToLocationAsync(ScenePresence agent, uint regionX, uint regionY, Vector3 position,
  1161. Scene initiatingScene)
  1162. {
  1163. Thread.Sleep(10000);
  1164. IMessageTransferModule im = initiatingScene.RequestModuleInterface<IMessageTransferModule>();
  1165. if (im != null)
  1166. {
  1167. UUID gotoLocation = Util.BuildFakeParcelID(
  1168. Util.UIntsToLong(
  1169. (regionX *
  1170. (uint)Constants.RegionSize),
  1171. (regionY *
  1172. (uint)Constants.RegionSize)),
  1173. (uint)(int)position.X,
  1174. (uint)(int)position.Y,
  1175. (uint)(int)position.Z);
  1176. GridInstantMessage m = new GridInstantMessage(initiatingScene, UUID.Zero,
  1177. "Region", agent.UUID,
  1178. (byte)InstantMessageDialog.GodLikeRequestTeleport, false,
  1179. "", gotoLocation, false, new Vector3(127, 0, 0),
  1180. new Byte[0]);
  1181. im.SendInstantMessage(m, delegate(bool success)
  1182. {
  1183. m_log.DebugFormat("[CLIENT]: Client Initiating Teleport sending IM success = {0}", success);
  1184. });
  1185. }
  1186. }
  1187. private void InformClientToInitiateTeleportToLocationCompleted(IAsyncResult iar)
  1188. {
  1189. InformClientToInitateTeleportToLocationDelegate icon =
  1190. (InformClientToInitateTeleportToLocationDelegate) iar.AsyncState;
  1191. icon.EndInvoke(iar);
  1192. }
  1193. public delegate ScenePresence CrossAgentToNewRegionDelegate(ScenePresence agent, Vector3 pos, uint neighbourx, uint neighboury, bool isFlying);
  1194. /// <summary>
  1195. /// This Closes child agents on neighboring regions
  1196. /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
  1197. /// </summary>
  1198. protected ScenePresence CrossAgentToNewRegionAsync(ScenePresence agent, Vector3 pos, uint neighbourx, uint neighboury, bool isFlying)
  1199. {
  1200. m_log.DebugFormat("[SCENE COMM]: Crossing agent {0} {1} to {2}-{3}", agent.Firstname, agent.Lastname, neighbourx, neighboury);
  1201. ulong neighbourHandle = Utils.UIntsToLong((uint)(neighbourx * Constants.RegionSize), (uint)(neighboury * Constants.RegionSize));
  1202. int x = (int)(neighbourx * Constants.RegionSize), y = (int)(neighboury * Constants.RegionSize);
  1203. GridRegion neighbourRegion = m_scene.GridService.GetRegionByPosition(m_scene.RegionInfo.ScopeID, (int)x, (int)y);
  1204. if (neighbourRegion != null && agent.ValidateAttachments())
  1205. {
  1206. pos = pos + (agent.Velocity);
  1207. //CachedUserInfo userInfo = m_commsProvider.UserProfileCacheService.GetUserDetails(agent.UUID);
  1208. //if (userInfo != null)
  1209. //{
  1210. // userInfo.DropInventory();
  1211. //}
  1212. //else
  1213. //{
  1214. // m_log.WarnFormat("[SCENE COMM]: No cached user info found for {0} {1} on leaving region {2}",
  1215. // agent.Name, agent.UUID, agent.Scene.RegionInfo.RegionName);
  1216. //}
  1217. //bool crossingSuccessful =
  1218. // CrossToNeighbouringRegion(neighbourHandle, agent.ControllingClient.AgentId, pos,
  1219. //isFlying);
  1220. SetInTransit(agent.UUID);
  1221. AgentData cAgent = new AgentData();
  1222. agent.CopyTo(cAgent);
  1223. cAgent.Position = pos;
  1224. if (isFlying)
  1225. cAgent.ControlFlags |= (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY;
  1226. cAgent.CallbackURI = "http://" + m_regionInfo.ExternalHostName + ":" + m_regionInfo.HttpPort +
  1227. "/agent/" + agent.UUID.ToString() + "/" + agent.Scene.RegionInfo.RegionHandle.ToString() + "/release/";
  1228. m_interregionCommsOut.SendChildAgentUpdate(neighbourHandle, cAgent);
  1229. // Next, let's close the child agent connections that are too far away.
  1230. agent.CloseChildAgents(neighbourx, neighboury);
  1231. //AgentCircuitData circuitdata = m_controllingClient.RequestClientInfo();
  1232. agent.ControllingClient.RequestClientInfo();
  1233. //m_log.Debug("BEFORE CROSS");
  1234. //Scene.DumpChildrenSeeds(UUID);
  1235. //DumpKnownRegions();
  1236. string agentcaps;
  1237. if (!agent.KnownRegions.TryGetValue(neighbourRegion.RegionHandle, out agentcaps))
  1238. {
  1239. m_log.ErrorFormat("[SCENE COMM]: No CAPS information for region handle {0}, exiting CrossToNewRegion.",
  1240. neighbourRegion.RegionHandle);
  1241. return agent;
  1242. }
  1243. // TODO Should construct this behind a method
  1244. string capsPath =
  1245. "http://" + neighbourRegion.ExternalHostName + ":" + neighbourRegion.HttpPort
  1246. + "/CAPS/" + agentcaps /*circuitdata.CapsPath*/ + "0000/";
  1247. m_log.DebugFormat("[CAPS]: Sending new CAPS seed url {0} to client {1}", capsPath, agent.UUID);
  1248. IEventQueue eq = agent.Scene.RequestModuleInterface<IEventQueue>();
  1249. if (eq != null)
  1250. {
  1251. eq.CrossRegion(neighbourHandle, pos, agent.Velocity, neighbourRegion.ExternalEndPoint,
  1252. capsPath, agent.UUID, agent.ControllingClient.SessionId);
  1253. }
  1254. else
  1255. {
  1256. agent.ControllingClient.CrossRegion(neighbourHandle, pos, agent.Velocity, neighbourRegion.ExternalEndPoint,
  1257. capsPath);
  1258. }
  1259. if (!WaitForCallback(agent.UUID))
  1260. {
  1261. ResetFromTransit(agent.UUID);
  1262. // Yikes! We should just have a ref to scene here.
  1263. agent.Scene.InformClientOfNeighbours(agent);
  1264. return agent;
  1265. }
  1266. agent.MakeChildAgent();
  1267. // now we have a child agent in this region. Request all interesting data about other (root) agents
  1268. agent.SendInitialFullUpdateToAllClients();
  1269. agent.CrossAttachmentsIntoNewRegion(neighbourHandle, true);
  1270. // m_scene.SendKillObject(m_localId);
  1271. agent.Scene.NotifyMyCoarseLocationChange();
  1272. // the user may change their profile information in other region,
  1273. // so the userinfo in UserProfileCache is not reliable any more, delete it
  1274. if (agent.Scene.NeedSceneCacheClear(agent.UUID))
  1275. {
  1276. agent.Scene.CommsManager.UserProfileCacheService.RemoveUser(agent.UUID);
  1277. m_log.DebugFormat(
  1278. "[SCENE COMM]: User {0} is going to another region, profile cache removed", agent.UUID);
  1279. }
  1280. }
  1281. //m_log.Debug("AFTER CROSS");
  1282. //Scene.DumpChildrenSeeds(UUID);
  1283. //DumpKnownRegions();
  1284. return agent;
  1285. }
  1286. private void CrossAgentToNewRegionCompleted(IAsyncResult iar)
  1287. {
  1288. CrossAgentToNewRegionDelegate icon = (CrossAgentToNewRegionDelegate)iar.AsyncState;
  1289. ScenePresence agent = icon.EndInvoke(iar);
  1290. // If the cross was successful, this agent is a child agent
  1291. if (agent.IsChildAgent)
  1292. {
  1293. agent.Reset();
  1294. }
  1295. else // Not successful
  1296. {
  1297. //CachedUserInfo userInfo = m_commsProvider.UserProfileCacheService.GetUserDetails(agent.UUID);
  1298. //if (userInfo != null)
  1299. //{
  1300. // userInfo.FetchInventory();
  1301. //}
  1302. agent.RestoreInCurrentScene();
  1303. }
  1304. // In any case
  1305. agent.NotInTransit();
  1306. //m_log.DebugFormat("[SCENE COMM]: Crossing agent {0} {1} completed.", agent.Firstname, agent.Lastname);
  1307. }
  1308. public void LogOffUser(UUID userid, UUID regionid, ulong regionhandle, Vector3 position, Vector3 lookat)
  1309. {
  1310. m_commsProvider.LogOffUser(userid, regionid, regionhandle, position, lookat);
  1311. }
  1312. // deprecated as of 2008-08-27
  1313. public void LogOffUser(UUID userid, UUID regionid, ulong regionhandle, float posx, float posy, float posz)
  1314. {
  1315. m_commsProvider.LogOffUser(userid, regionid, regionhandle, posx, posy, posz);
  1316. }
  1317. public void ClearUserAgent(UUID avatarID)
  1318. {
  1319. m_commsProvider.UserService.ClearUserAgent(avatarID);
  1320. }
  1321. public void AddNewUserFriend(UUID friendlistowner, UUID friend, uint perms)
  1322. {
  1323. m_commsProvider.AddNewUserFriend(friendlistowner, friend, perms);
  1324. }
  1325. public void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms)
  1326. {
  1327. m_commsProvider.UpdateUserFriendPerms(friendlistowner, friend, perms);
  1328. }
  1329. public void RemoveUserFriend(UUID friendlistowner, UUID friend)
  1330. {
  1331. m_commsProvider.RemoveUserFriend(friendlistowner, friend);
  1332. }
  1333. public List<FriendListItem> GetUserFriendList(UUID friendlistowner)
  1334. {
  1335. return m_commsProvider.GetUserFriendList(friendlistowner);
  1336. }
  1337. public List<AvatarPickerAvatar> GenerateAgentPickerRequestResponse(UUID queryID, string query)
  1338. {
  1339. return m_commsProvider.GenerateAgentPickerRequestResponse(queryID, query);
  1340. }
  1341. public List<GridRegion> RequestNamedRegions(string name, int maxNumber)
  1342. {
  1343. return m_scene.GridService.GetRegionsByName(UUID.Zero, name, maxNumber);
  1344. }
  1345. //private void Dump(string msg, List<ulong> handles)
  1346. //{
  1347. // m_log.InfoFormat("-------------- HANDLE DUMP ({0}) ---------", msg);
  1348. // foreach (ulong handle in handles)
  1349. // {
  1350. // uint x, y;
  1351. // Utils.LongToUInts(handle, out x, out y);
  1352. // x = x / Constants.RegionSize;
  1353. // y = y / Constants.RegionSize;
  1354. // m_log.InfoFormat("({0}, {1})", x, y);
  1355. // }
  1356. //}
  1357. }
  1358. }