SceneCommunicationService.cs 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  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 OpenSim 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.Region.Environment.Interfaces;
  36. using OpenSim.Framework;
  37. using OpenSim.Framework.Communications;
  38. using OpenSim.Region.Interfaces;
  39. using OSD = OpenMetaverse.StructuredData.OSD;
  40. namespace OpenSim.Region.Environment.Scenes
  41. {
  42. public delegate void KiPrimitiveDelegate(uint localID);
  43. public delegate void RemoveKnownRegionsFromAvatarList(UUID avatarID, List<ulong> regionlst);
  44. public class SceneCommunicationService //one instance per region
  45. {
  46. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  47. protected CommunicationsManager m_commsProvider;
  48. protected IInterregionCommsOut m_interregionCommsOut;
  49. protected RegionInfo m_regionInfo;
  50. protected RegionCommsListener regionCommsHost;
  51. public event AgentCrossing OnAvatarCrossingIntoRegion;
  52. public event ExpectUserDelegate OnExpectUser;
  53. public event ExpectPrimDelegate OnExpectPrim;
  54. public event CloseAgentConnection OnCloseAgentConnection;
  55. public event PrimCrossing OnPrimCrossingIntoRegion;
  56. public event RegionUp OnRegionUp;
  57. public event ChildAgentUpdate OnChildAgentUpdate;
  58. //public event RemoveKnownRegionsFromAvatarList OnRemoveKnownRegionFromAvatar;
  59. public event LogOffUser OnLogOffUser;
  60. public event GetLandData OnGetLandData;
  61. private AgentCrossing handlerAvatarCrossingIntoRegion = null; // OnAvatarCrossingIntoRegion;
  62. private ExpectUserDelegate handlerExpectUser = null; // OnExpectUser;
  63. private ExpectPrimDelegate handlerExpectPrim = null; // OnExpectPrim;
  64. private CloseAgentConnection handlerCloseAgentConnection = null; // OnCloseAgentConnection;
  65. private PrimCrossing handlerPrimCrossingIntoRegion = null; // OnPrimCrossingIntoRegion;
  66. private RegionUp handlerRegionUp = null; // OnRegionUp;
  67. private ChildAgentUpdate handlerChildAgentUpdate = null; // OnChildAgentUpdate;
  68. //private RemoveKnownRegionsFromAvatarList handlerRemoveKnownRegionFromAvatar = null; // OnRemoveKnownRegionFromAvatar;
  69. private LogOffUser handlerLogOffUser = null;
  70. private GetLandData handlerGetLandData = null; // OnGetLandData
  71. public KiPrimitiveDelegate KiPrimitive;
  72. public SceneCommunicationService(CommunicationsManager commsMan)
  73. {
  74. m_commsProvider = commsMan;
  75. }
  76. /// <summary>
  77. /// Register a region with the grid
  78. /// </summary>
  79. /// <param name="regionInfos"></param>
  80. /// <exception cref="System.Exception">Thrown if region registration fails.</exception>
  81. public void RegisterRegion(IInterregionCommsOut comms_out, RegionInfo regionInfos)
  82. {
  83. m_interregionCommsOut = comms_out;
  84. m_regionInfo = regionInfos;
  85. m_commsProvider.GridService.gdebugRegionName = regionInfos.RegionName;
  86. m_commsProvider.InterRegion.rdebugRegionName = regionInfos.RegionName;
  87. regionCommsHost = m_commsProvider.GridService.RegisterRegion(m_regionInfo);
  88. if (regionCommsHost != null)
  89. {
  90. //m_log.Info("[INTER]: " + debugRegionName + ": SceneCommunicationService: registered with gridservice and got" + regionCommsHost.ToString());
  91. regionCommsHost.debugRegionName = regionInfos.RegionName;
  92. regionCommsHost.OnExpectPrim += IncomingPrimCrossing;
  93. regionCommsHost.OnExpectUser += NewUserConnection;
  94. regionCommsHost.OnAvatarCrossingIntoRegion += AgentCrossing;
  95. regionCommsHost.OnCloseAgentConnection += CloseConnection;
  96. regionCommsHost.OnRegionUp += newRegionUp;
  97. regionCommsHost.OnChildAgentUpdate += ChildAgentUpdate;
  98. regionCommsHost.OnLogOffUser += GridLogOffUser;
  99. regionCommsHost.OnGetLandData += FetchLandData;
  100. }
  101. else
  102. {
  103. //m_log.Info("[INTER]: " + debugRegionName + ": SceneCommunicationService: registered with gridservice and got null");
  104. }
  105. }
  106. public RegionInfo RequestClosestRegion(string name)
  107. {
  108. return m_commsProvider.GridService.RequestClosestRegion(name);
  109. }
  110. public void Close()
  111. {
  112. if (regionCommsHost != null)
  113. {
  114. regionCommsHost.OnLogOffUser -= GridLogOffUser;
  115. regionCommsHost.OnChildAgentUpdate -= ChildAgentUpdate;
  116. regionCommsHost.OnRegionUp -= newRegionUp;
  117. regionCommsHost.OnExpectUser -= NewUserConnection;
  118. regionCommsHost.OnExpectPrim -= IncomingPrimCrossing;
  119. regionCommsHost.OnAvatarCrossingIntoRegion -= AgentCrossing;
  120. regionCommsHost.OnCloseAgentConnection -= CloseConnection;
  121. regionCommsHost.OnGetLandData -= FetchLandData;
  122. try
  123. {
  124. m_commsProvider.GridService.DeregisterRegion(m_regionInfo);
  125. }
  126. catch (Exception e)
  127. {
  128. m_log.ErrorFormat(
  129. "[GRID]: Deregistration of region {0} from the grid failed - {1}. Continuing",
  130. m_regionInfo.RegionName, e);
  131. }
  132. regionCommsHost = null;
  133. }
  134. }
  135. #region CommsManager Event handlers
  136. /// <summary>
  137. ///
  138. /// </summary>
  139. /// <param name="regionHandle"></param>
  140. /// <param name="agent"></param>
  141. ///
  142. protected void NewUserConnection(AgentCircuitData agent)
  143. {
  144. handlerExpectUser = OnExpectUser;
  145. if (handlerExpectUser != null)
  146. {
  147. //m_log.Info("[INTER]: " + debugRegionName + ": SceneCommunicationService: OnExpectUser Fired for User:" + agent.firstname + " " + agent.lastname);
  148. handlerExpectUser(agent);
  149. }
  150. }
  151. protected void GridLogOffUser(UUID AgentID, UUID RegionSecret, string message)
  152. {
  153. handlerLogOffUser = OnLogOffUser;
  154. if (handlerLogOffUser != null)
  155. {
  156. handlerLogOffUser(AgentID, RegionSecret, message);
  157. }
  158. }
  159. protected bool newRegionUp(RegionInfo region)
  160. {
  161. handlerRegionUp = OnRegionUp;
  162. if (handlerRegionUp != null)
  163. {
  164. //m_log.Info("[INTER]: " + debugRegionName + ": SceneCommunicationService: newRegionUp Fired for User:" + region.RegionName);
  165. handlerRegionUp(region);
  166. }
  167. return true;
  168. }
  169. protected bool ChildAgentUpdate(ChildAgentDataUpdate cAgentData)
  170. {
  171. handlerChildAgentUpdate = OnChildAgentUpdate;
  172. if (handlerChildAgentUpdate != null)
  173. handlerChildAgentUpdate(cAgentData);
  174. return true;
  175. }
  176. protected void AgentCrossing(UUID agentID, Vector3 position, bool isFlying)
  177. {
  178. handlerAvatarCrossingIntoRegion = OnAvatarCrossingIntoRegion;
  179. if (handlerAvatarCrossingIntoRegion != null)
  180. {
  181. handlerAvatarCrossingIntoRegion(agentID, position, isFlying);
  182. }
  183. }
  184. protected bool IncomingPrimCrossing(UUID primID, String objXMLData, int XMLMethod)
  185. {
  186. handlerExpectPrim = OnExpectPrim;
  187. if (handlerExpectPrim != null)
  188. {
  189. return handlerExpectPrim(primID, objXMLData, XMLMethod);
  190. }
  191. else
  192. {
  193. return false;
  194. }
  195. }
  196. protected void PrimCrossing(UUID primID, Vector3 position, bool isPhysical)
  197. {
  198. handlerPrimCrossingIntoRegion = OnPrimCrossingIntoRegion;
  199. if (handlerPrimCrossingIntoRegion != null)
  200. {
  201. handlerPrimCrossingIntoRegion(primID, position, isPhysical);
  202. }
  203. }
  204. protected bool CloseConnection(UUID agentID)
  205. {
  206. m_log.Debug("[INTERREGION]: Incoming Agent Close Request for agent: " + agentID);
  207. handlerCloseAgentConnection = OnCloseAgentConnection;
  208. if (handlerCloseAgentConnection != null)
  209. {
  210. return handlerCloseAgentConnection(agentID);
  211. }
  212. return false;
  213. }
  214. protected LandData FetchLandData(uint x, uint y)
  215. {
  216. handlerGetLandData = OnGetLandData;
  217. if (handlerGetLandData != null)
  218. {
  219. return handlerGetLandData(x, y);
  220. }
  221. return null;
  222. }
  223. #endregion
  224. #region Inform Client of Neighbours
  225. private delegate void InformClientOfNeighbourDelegate(
  226. ScenePresence avatar, AgentCircuitData a, SimpleRegionInfo reg, IPEndPoint endPoint, bool newAgent);
  227. private void InformClientOfNeighbourCompleted(IAsyncResult iar)
  228. {
  229. InformClientOfNeighbourDelegate icon = (InformClientOfNeighbourDelegate) iar.AsyncState;
  230. icon.EndInvoke(iar);
  231. }
  232. /// <summary>
  233. /// Async component for informing client of which neighbours exist
  234. /// </summary>
  235. /// <remarks>
  236. /// This needs to run asynchronesously, as a network timeout may block the thread for a long while
  237. /// </remarks>
  238. /// <param name="remoteClient"></param>
  239. /// <param name="a"></param>
  240. /// <param name="regionHandle"></param>
  241. /// <param name="endPoint"></param>
  242. private void InformClientOfNeighbourAsync(ScenePresence avatar, AgentCircuitData a, SimpleRegionInfo reg,
  243. IPEndPoint endPoint, bool newAgent)
  244. {
  245. // Let's wait just a little to give time to originating regions to catch up with closing child agents
  246. // after a cross here
  247. Thread.Sleep(500);
  248. uint x, y;
  249. Utils.LongToUInts(reg.RegionHandle, out x, out y);
  250. x = x / Constants.RegionSize;
  251. y = y / Constants.RegionSize;
  252. m_log.Info("[INTERGRID]: Starting to inform client about neighbour " + x + ", " + y + "(" + endPoint.ToString() + ")");
  253. string capsPath = "http://" + reg.ExternalHostName + ":" + reg.HttpPort
  254. + "/CAPS/" + a.CapsPath + "0000/";
  255. bool regionAccepted = m_commsProvider.InterRegion.InformRegionOfChildAgent(reg.RegionHandle, a);
  256. if (regionAccepted && newAgent)
  257. {
  258. IEventQueue eq = avatar.Scene.RequestModuleInterface<IEventQueue>();
  259. if (eq != null)
  260. {
  261. OSD Item = EventQueueHelper.EnableSimulator(reg.RegionHandle, endPoint);
  262. eq.Enqueue(Item, avatar.UUID);
  263. Item = EventQueueHelper.EstablishAgentCommunication(avatar.UUID, endPoint.ToString(), capsPath);
  264. eq.Enqueue(Item, avatar.UUID);
  265. m_log.DebugFormat("[CAPS]: Sending new CAPS seed url {0} to client {1} in region {2}", capsPath, avatar.UUID, avatar.Scene.RegionInfo.RegionName);
  266. }
  267. else
  268. {
  269. avatar.ControllingClient.InformClientOfNeighbour(reg.RegionHandle, endPoint);
  270. // TODO: make Event Queue disablable!
  271. }
  272. m_log.Info("[INTERGRID]: Completed inform client about neighbour " + endPoint.ToString());
  273. }
  274. }
  275. public void RequestNeighbors(RegionInfo region)
  276. {
  277. // List<SimpleRegionInfo> neighbours =
  278. m_commsProvider.GridService.RequestNeighbours(m_regionInfo.RegionLocX, m_regionInfo.RegionLocY);
  279. //IPEndPoint blah = new IPEndPoint();
  280. //blah.Address = region.RemotingAddress;
  281. //blah.Port = region.RemotingPort;
  282. }
  283. /// <summary>
  284. /// This informs all neighboring regions about agent "avatar".
  285. /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
  286. /// </summary>
  287. public void EnableNeighbourChildAgents(ScenePresence avatar, List<RegionInfo> lstneighbours)
  288. {
  289. List<SimpleRegionInfo> neighbours = new List<SimpleRegionInfo>();
  290. //m_commsProvider.GridService.RequestNeighbours(m_regionInfo.RegionLocX, m_regionInfo.RegionLocY);
  291. for (int i = 0; i < lstneighbours.Count; i++)
  292. {
  293. // We don't want to keep sending to regions that consistently fail on comms.
  294. if (!(lstneighbours[i].commFailTF))
  295. {
  296. neighbours.Add(new SimpleRegionInfo(lstneighbours[i]));
  297. }
  298. }
  299. // we're going to be using the above code once neighbour cache is correct. Currently it doesn't appear to be
  300. // So we're temporarily going back to the old method of grabbing it from the Grid Server Every time :/
  301. neighbours =
  302. m_commsProvider.GridService.RequestNeighbours(m_regionInfo.RegionLocX, m_regionInfo.RegionLocY);
  303. m_log.Debug("[SCM]: EnableChildAgents from " + avatar.Scene.RegionInfo.RegionName);
  304. /// We need to find the difference between the new regions where there are no child agents
  305. /// and the regions where there are already child agents. We only send notification to the former.
  306. List<ulong> neighbourHandles = NeighbourHandles(neighbours); // on this region
  307. neighbourHandles.Add(avatar.Scene.RegionInfo.RegionHandle); // add this region too
  308. List<ulong> previousRegionNeighbourHandles = new List<ulong>(avatar.Scene.GetChildrenSeeds(avatar.UUID).Keys);
  309. List<ulong> newRegions = NewNeighbours(neighbourHandles, previousRegionNeighbourHandles);
  310. List<ulong> oldRegions = OldNeighbours(neighbourHandles, previousRegionNeighbourHandles);
  311. //Dump("Current Neighbors", neighbourHandles);
  312. //Dump("Previous Neighbours", previousRegionNeighbourHandles);
  313. //Dump("New Neighbours", newRegions);
  314. //Dump("Old Neighbours", oldRegions);
  315. /// Update the scene presence's known regions here on this region
  316. avatar.DropOldNeighbours(oldRegions);
  317. /// Collect as many seeds as possible
  318. Dictionary<ulong, string> seeds = new Dictionary<ulong, string>(avatar.Scene.GetChildrenSeeds(avatar.UUID));
  319. //Console.WriteLine(" !!! No. of seeds: " + seeds.Count);
  320. if (!seeds.ContainsKey(avatar.Scene.RegionInfo.RegionHandle))
  321. seeds.Add(avatar.Scene.RegionInfo.RegionHandle, avatar.ControllingClient.RequestClientInfo().CapsPath);
  322. /// Create the necessary child agents
  323. List<AgentCircuitData> cagents = new List<AgentCircuitData>();
  324. foreach (SimpleRegionInfo neighbour in neighbours)
  325. {
  326. if (neighbour.RegionHandle != avatar.Scene.RegionInfo.RegionHandle)
  327. {
  328. AgentCircuitData agent = avatar.ControllingClient.RequestClientInfo();
  329. agent.BaseFolder = UUID.Zero;
  330. agent.InventoryFolder = UUID.Zero;
  331. agent.startpos = new Vector3(128, 128, 70);
  332. agent.child = true;
  333. if (newRegions.Contains(neighbour.RegionHandle))
  334. {
  335. agent.CapsPath = Util.GetRandomCapsPath();
  336. avatar.AddNeighbourRegion(neighbour.RegionHandle, agent.CapsPath);
  337. seeds.Add(neighbour.RegionHandle, agent.CapsPath);
  338. }
  339. else
  340. agent.CapsPath = avatar.Scene.GetChildSeed(avatar.UUID, neighbour.RegionHandle);
  341. cagents.Add(agent);
  342. }
  343. }
  344. /// Update all child agent with everyone's seeds
  345. foreach (AgentCircuitData a in cagents)
  346. {
  347. a.ChildrenCapSeeds = new Dictionary<ulong, string>(seeds);
  348. }
  349. // These two are the same thing!
  350. avatar.Scene.SetChildrenSeed(avatar.UUID, seeds);
  351. avatar.KnownRegions = seeds;
  352. //avatar.Scene.DumpChildrenSeeds(avatar.UUID);
  353. //avatar.DumpKnownRegions();
  354. bool newAgent = false;
  355. int count = 0;
  356. foreach (SimpleRegionInfo neighbour in neighbours)
  357. {
  358. // Don't do it if there's already an agent in that region
  359. if (newRegions.Contains(neighbour.RegionHandle))
  360. newAgent = true;
  361. else
  362. newAgent = false;
  363. if (neighbour.RegionHandle != avatar.Scene.RegionInfo.RegionHandle)
  364. {
  365. InformClientOfNeighbourDelegate d = InformClientOfNeighbourAsync;
  366. try
  367. {
  368. d.BeginInvoke(avatar, cagents[count], neighbour, neighbour.ExternalEndPoint, newAgent,
  369. InformClientOfNeighbourCompleted,
  370. d);
  371. }
  372. catch (Exception e)
  373. {
  374. m_log.ErrorFormat(
  375. "[REGIONINFO]: Could not resolve external hostname {0} for region {1} ({2}, {3}). {4}",
  376. neighbour.ExternalHostName,
  377. neighbour.RegionHandle,
  378. neighbour.RegionLocX,
  379. neighbour.RegionLocY,
  380. e);
  381. // FIXME: Okay, even though we've failed, we're still going to throw the exception on,
  382. // since I don't know what will happen if we just let the client continue
  383. // XXX: Well, decided to swallow the exception instead for now. Let us see how that goes.
  384. // throw e;
  385. }
  386. }
  387. count++;
  388. }
  389. }
  390. /// <summary>
  391. /// This informs a single neighboring region about agent "avatar".
  392. /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
  393. /// </summary>
  394. public void InformNeighborChildAgent(ScenePresence avatar, SimpleRegionInfo region, List<RegionInfo> neighbours)
  395. {
  396. AgentCircuitData agent = avatar.ControllingClient.RequestClientInfo();
  397. agent.BaseFolder = UUID.Zero;
  398. agent.InventoryFolder = UUID.Zero;
  399. agent.startpos = new Vector3(128, 128, 70);
  400. agent.child = true;
  401. InformClientOfNeighbourDelegate d = InformClientOfNeighbourAsync;
  402. d.BeginInvoke(avatar, agent, region, region.ExternalEndPoint, true,
  403. InformClientOfNeighbourCompleted,
  404. d);
  405. }
  406. #endregion
  407. public delegate void InformNeighbourThatRegionUpDelegate(RegionInfo region, ulong regionhandle);
  408. private void InformNeighborsThatRegionisUpCompleted(IAsyncResult iar)
  409. {
  410. InformNeighbourThatRegionUpDelegate icon = (InformNeighbourThatRegionUpDelegate) iar.AsyncState;
  411. icon.EndInvoke(iar);
  412. }
  413. /// <summary>
  414. /// Asynchronous call to information neighbouring regions that this region is up
  415. /// </summary>
  416. /// <param name="region"></param>
  417. /// <param name="regionhandle"></param>
  418. private void InformNeighboursThatRegionIsUpAsync(RegionInfo region, ulong regionhandle)
  419. {
  420. m_log.Info("[INTERGRID]: Starting to inform neighbors that I'm here");
  421. //RegionUpData regiondata = new RegionUpData(region.RegionLocX, region.RegionLocY, region.ExternalHostName, region.InternalEndPoint.Port);
  422. bool regionAccepted =
  423. m_commsProvider.InterRegion.RegionUp(new SerializableRegionInfo(region), regionhandle);
  424. if (regionAccepted)
  425. {
  426. m_log.Info("[INTERGRID]: Completed informing neighbors that I'm here");
  427. handlerRegionUp = OnRegionUp;
  428. // yes, we're notifying ourselves.
  429. if (handlerRegionUp != null)
  430. handlerRegionUp(region);
  431. }
  432. else
  433. {
  434. m_log.Warn("[INTERGRID]: Failed to inform neighbors that I'm here.");
  435. }
  436. }
  437. /// <summary>
  438. /// Called by scene when region is initialized (not always when it's listening for agents)
  439. /// This is an inter-region message that informs the surrounding neighbors that the sim is up.
  440. /// </summary>
  441. public void InformNeighborsThatRegionisUp(RegionInfo region)
  442. {
  443. //m_log.Info("[INTER]: " + debugRegionName + ": SceneCommunicationService: Sending InterRegion Notification that region is up " + region.RegionName);
  444. List<SimpleRegionInfo> neighbours = new List<SimpleRegionInfo>();
  445. // This stays uncached because we don't already know about our neighbors at this point.
  446. neighbours = m_commsProvider.GridService.RequestNeighbours(m_regionInfo.RegionLocX, m_regionInfo.RegionLocY);
  447. if (neighbours != null)
  448. {
  449. for (int i = 0; i < neighbours.Count; i++)
  450. {
  451. InformNeighbourThatRegionUpDelegate d = InformNeighboursThatRegionIsUpAsync;
  452. d.BeginInvoke(region, neighbours[i].RegionHandle,
  453. InformNeighborsThatRegionisUpCompleted,
  454. d);
  455. }
  456. }
  457. //bool val = m_commsProvider.InterRegion.RegionUp(new SerializableRegionInfo(region));
  458. }
  459. public delegate void SendChildAgentDataUpdateDelegate(AgentData cAgentData, ulong regionHandle);
  460. /// <summary>
  461. /// This informs all neighboring regions about the settings of it's child agent.
  462. /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
  463. ///
  464. /// This contains information, such as, Draw Distance, Camera location, Current Position, Current throttle settings, etc.
  465. ///
  466. /// </summary>
  467. private void SendChildAgentDataUpdateAsync(AgentData cAgentData, ulong regionHandle)
  468. {
  469. m_log.Info("[INTERGRID]: Informing neighbors about my agent in " + m_regionInfo.RegionName);
  470. //bool regionAccepted = m_commsProvider.InterRegion.ChildAgentUpdate(regionHandle, cAgentData);
  471. try
  472. {
  473. //m_commsProvider.InterRegion.ChildAgentUpdate(regionHandle, cAgentData);
  474. m_interregionCommsOut.SendChildAgentUpdate(regionHandle, cAgentData);
  475. }
  476. catch
  477. {
  478. // Ignore; we did our best
  479. }
  480. //if (regionAccepted)
  481. //{
  482. // //m_log.Info("[INTERGRID]: Completed sending a neighbor an update about my agent");
  483. //}
  484. //else
  485. //{
  486. // //m_log.Info("[INTERGRID]: Failed sending a neighbor an update about my agent");
  487. //}
  488. }
  489. private void SendChildAgentDataUpdateCompleted(IAsyncResult iar)
  490. {
  491. SendChildAgentDataUpdateDelegate icon = (SendChildAgentDataUpdateDelegate) iar.AsyncState;
  492. icon.EndInvoke(iar);
  493. }
  494. public void SendChildAgentDataUpdate(AgentData cAgentData, ScenePresence presence)
  495. {
  496. // This assumes that we know what our neighbors are.
  497. try
  498. {
  499. foreach (ulong regionHandle in presence.KnownChildRegionHandles)
  500. {
  501. if (regionHandle != m_regionInfo.RegionHandle)
  502. {
  503. SendChildAgentDataUpdateDelegate d = SendChildAgentDataUpdateAsync;
  504. d.BeginInvoke(cAgentData, regionHandle,
  505. SendChildAgentDataUpdateCompleted,
  506. d);
  507. }
  508. }
  509. }
  510. catch (InvalidOperationException)
  511. {
  512. // We're ignoring a collection was modified error because this data gets old and outdated fast.
  513. }
  514. }
  515. public delegate void SendCloseChildAgentDelegate(UUID agentID, ulong regionHandle);
  516. /// <summary>
  517. /// This Closes child agents on neighboring regions
  518. /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
  519. /// </summary>
  520. protected void SendCloseChildAgentAsync(UUID agentID, ulong regionHandle)
  521. {
  522. m_log.Debug("[INTERGRID]: Sending close agent to " + regionHandle);
  523. //bool regionAccepted = m_commsProvider.InterRegion.TellRegionToCloseChildConnection(regionHandle, agentID);
  524. // let's do our best, but there's not much we can do if the neighbour doesn't accept.
  525. m_commsProvider.InterRegion.TellRegionToCloseChildConnection(regionHandle, agentID);
  526. //if (regionAccepted)
  527. //{
  528. // m_log.Info("[INTERGRID]: Completed sending agent Close agent Request to neighbor");
  529. //}
  530. //else
  531. //{
  532. // m_log.Info("[INTERGRID]: Failed sending agent Close agent Request to neighbor");
  533. //}
  534. //// We remove the list of known regions from the agent's known region list through an event
  535. //// to scene, because, if an agent logged of, it's likely that there will be no scene presence
  536. //// by the time we get to this part of the method.
  537. //handlerRemoveKnownRegionFromAvatar = OnRemoveKnownRegionFromAvatar;
  538. //if (handlerRemoveKnownRegionFromAvatar != null)
  539. //{
  540. // handlerRemoveKnownRegionFromAvatar(agentID, regionlst);
  541. //}
  542. }
  543. private void SendCloseChildAgentCompleted(IAsyncResult iar)
  544. {
  545. SendCloseChildAgentDelegate icon = (SendCloseChildAgentDelegate)iar.AsyncState;
  546. icon.EndInvoke(iar);
  547. }
  548. public void SendCloseChildAgentConnections(UUID agentID, List<ulong> regionslst)
  549. {
  550. foreach (ulong handle in regionslst)
  551. {
  552. SendCloseChildAgentDelegate d = SendCloseChildAgentAsync;
  553. d.BeginInvoke(agentID, handle,
  554. SendCloseChildAgentCompleted,
  555. d);
  556. }
  557. }
  558. /// <summary>
  559. /// Helper function to request neighbors from grid-comms
  560. /// </summary>
  561. /// <param name="regionHandle"></param>
  562. /// <returns></returns>
  563. public virtual RegionInfo RequestNeighbouringRegionInfo(ulong regionHandle)
  564. {
  565. //m_log.Info("[INTER]: " + debugRegionName + ": SceneCommunicationService: Sending Grid Services Request about neighbor " + regionHandle.ToString());
  566. return m_commsProvider.GridService.RequestNeighbourInfo(regionHandle);
  567. }
  568. /// <summary>
  569. /// Helper function to request neighbors from grid-comms
  570. /// </summary>
  571. /// <param name="regionID"></param>
  572. /// <returns></returns>
  573. public virtual RegionInfo RequestNeighbouringRegionInfo(UUID regionID)
  574. {
  575. //m_log.Info("[INTER]: " + debugRegionName + ": SceneCommunicationService: Sending Grid Services Request about neighbor " + regionID);
  576. return m_commsProvider.GridService.RequestNeighbourInfo(regionID);
  577. }
  578. /// <summary>
  579. /// Requests map blocks in area of minX, maxX, minY, MaxY in world cordinates
  580. /// </summary>
  581. /// <param name="minX"></param>
  582. /// <param name="minY"></param>
  583. /// <param name="maxX"></param>
  584. /// <param name="maxY"></param>
  585. public virtual void RequestMapBlocks(IClientAPI remoteClient, int minX, int minY, int maxX, int maxY)
  586. {
  587. List<MapBlockData> mapBlocks;
  588. mapBlocks = m_commsProvider.GridService.RequestNeighbourMapBlocks(minX - 4, minY - 4, minX + 4, minY + 4);
  589. remoteClient.SendMapBlock(mapBlocks, 0);
  590. }
  591. /// <summary>
  592. /// Try to teleport an agent to a new region.
  593. /// </summary>
  594. /// <param name="remoteClient"></param>
  595. /// <param name="RegionHandle"></param>
  596. /// <param name="position"></param>
  597. /// <param name="lookAt"></param>
  598. /// <param name="flags"></param>
  599. public virtual void RequestTeleportToLocation(ScenePresence avatar, ulong regionHandle, Vector3 position,
  600. Vector3 lookAt, uint teleportFlags)
  601. {
  602. m_log.DebugFormat("[SCENE COMMUNICATION SERVICE] RequestTeleportToLocation {0} ", position.ToString());
  603. if (!avatar.Scene.Permissions.CanTeleport(avatar.UUID))
  604. return;
  605. bool destRegionUp = false;
  606. IEventQueue eq = avatar.Scene.RequestModuleInterface<IEventQueue>();
  607. if (regionHandle == m_regionInfo.RegionHandle)
  608. {
  609. // Teleport within the same region
  610. if (position.X < 0 || position.X > Constants.RegionSize || position.Y < 0 || position.Y > Constants.RegionSize || position.Z < 0)
  611. {
  612. Vector3 emergencyPos = new Vector3(128, 128, 128);
  613. m_log.WarnFormat(
  614. "[SCENE COMMUNICATION SERVICE]: RequestTeleportToLocation() was given an illegal position of {0} for avatar {1}, {2}. Substituting {3}",
  615. position, avatar.Name, avatar.UUID, emergencyPos);
  616. position = emergencyPos;
  617. }
  618. // TODO: Get proper AVG Height
  619. float localAVHeight = 1.56f;
  620. float posZLimit = (float)avatar.Scene.GetLandHeight((int)position.X, (int)position.Y);
  621. float newPosZ = posZLimit + localAVHeight;
  622. if (posZLimit >= (position.Z - (localAVHeight / 2)) && !(Single.IsInfinity(newPosZ) || Single.IsNaN(newPosZ)))
  623. {
  624. position.Z = newPosZ;
  625. }
  626. // Only send this if the event queue is null
  627. if (eq == null)
  628. avatar.ControllingClient.SendTeleportLocationStart();
  629. avatar.ControllingClient.SendLocalTeleport(position, lookAt, teleportFlags);
  630. avatar.Teleport(position);
  631. }
  632. else
  633. {
  634. RegionInfo reg = RequestNeighbouringRegionInfo(regionHandle);
  635. if (reg != null)
  636. {
  637. if (eq == null)
  638. avatar.ControllingClient.SendTeleportLocationStart();
  639. if (reg.RemotingAddress != "" && reg.RemotingPort != 0)
  640. {
  641. // region is remote. see if it is up
  642. destRegionUp = m_commsProvider.InterRegion.CheckRegion(reg.RemotingAddress, reg.RemotingPort);
  643. }
  644. else
  645. {
  646. // assume local regions are always up
  647. destRegionUp = true;
  648. }
  649. // Let's do DNS resolution only once in this process, please!
  650. // This may be a costly operation. The reg.ExternalEndPoint field is not a passive field,
  651. // it's actually doing a lot of work.
  652. IPEndPoint endPoint = reg.ExternalEndPoint;
  653. if (endPoint.Address == null)
  654. {
  655. // Couldn't resolve the name. Can't TP, because the viewer wants IP addresses.
  656. destRegionUp = false;
  657. }
  658. if (destRegionUp)
  659. {
  660. uint newRegionX = (uint)(reg.RegionHandle >> 40);
  661. uint newRegionY = (((uint)(reg.RegionHandle)) >> 8);
  662. uint oldRegionX = (uint)(m_regionInfo.RegionHandle >> 40);
  663. uint oldRegionY = (((uint)(m_regionInfo.RegionHandle)) >> 8);
  664. // Fixing a bug where teleporting while sitting results in the avatar ending up removed from
  665. // both regions
  666. if (avatar.ParentID != (uint)0)
  667. avatar.StandUp();
  668. if (!avatar.ValidateAttachments())
  669. {
  670. avatar.ControllingClient.SendTeleportFailed("Inconsistent attachment state");
  671. return;
  672. }
  673. // the avatar.Close below will clear the child region list. We need this below for (possibly)
  674. // closing the child agents, so save it here (we need a copy as it is Clear()-ed).
  675. //List<ulong> childRegions = new List<ulong>(avatar.GetKnownRegionList());
  676. // Compared to ScenePresence.CrossToNewRegion(), there's no obvious code to handle a teleport
  677. // failure at this point (unlike a border crossing failure). So perhaps this can never fail
  678. // once we reach here...
  679. //avatar.Scene.RemoveCapsHandler(avatar.UUID);
  680. // Let's close some agents
  681. avatar.CloseChildAgents(newRegionX, newRegionY);
  682. string capsPath = String.Empty;
  683. AgentCircuitData agent = avatar.ControllingClient.RequestClientInfo();
  684. agent.BaseFolder = UUID.Zero;
  685. agent.InventoryFolder = UUID.Zero;
  686. agent.startpos = position;
  687. agent.child = true;
  688. if (Util.IsOutsideView(oldRegionX, newRegionX, oldRegionY, newRegionY))
  689. {
  690. // brand new agent, let's create a new caps seed
  691. agent.CapsPath = Util.GetRandomCapsPath();
  692. }
  693. if (!m_commsProvider.InterRegion.InformRegionOfChildAgent(reg.RegionHandle, agent))
  694. {
  695. avatar.ControllingClient.SendTeleportFailed("Destination is not accepting teleports.");
  696. return;
  697. }
  698. if (Util.IsOutsideView(oldRegionX, newRegionX, oldRegionY, newRegionY))
  699. {
  700. // TODO Should construct this behind a method
  701. capsPath =
  702. "http://" + reg.ExternalHostName + ":" + reg.HttpPort
  703. + "/CAPS/" + agent.CapsPath + "0000/";
  704. if (eq != null)
  705. {
  706. OSD Item = EventQueueHelper.EnableSimulator(reg.RegionHandle, endPoint);
  707. eq.Enqueue(Item, avatar.UUID);
  708. // ES makes the client send a UseCircuitCode message to the destination,
  709. // which triggers a bunch of things there.
  710. // So let's wait
  711. Thread.Sleep(2000);
  712. Item = EventQueueHelper.EstablishAgentCommunication(avatar.UUID, endPoint.ToString(), capsPath);
  713. eq.Enqueue(Item, avatar.UUID);
  714. }
  715. else
  716. {
  717. avatar.ControllingClient.InformClientOfNeighbour(reg.RegionHandle, endPoint);
  718. }
  719. }
  720. else
  721. {
  722. agent.CapsPath = avatar.Scene.GetChildSeed(avatar.UUID, reg.RegionHandle);
  723. capsPath = "http://" + reg.ExternalHostName + ":" + reg.HttpPort
  724. + "/CAPS/" + agent.CapsPath + "0000/";
  725. }
  726. // Expect avatar crossing is a heavy-duty function at the destination.
  727. // That is where MakeRoot is called, which fetches appearance and inventory.
  728. // Plus triggers OnMakeRoot, which spawns a series of asynchronous updates.
  729. //m_commsProvider.InterRegion.ExpectAvatarCrossing(reg.RegionHandle, avatar.ControllingClient.AgentId,
  730. // position, false);
  731. //{
  732. // avatar.ControllingClient.SendTeleportFailed("Problem with destination.");
  733. // // We should close that agent we just created over at destination...
  734. // List<ulong> lst = new List<ulong>();
  735. // lst.Add(reg.RegionHandle);
  736. // SendCloseChildAgentAsync(avatar.UUID, lst);
  737. // return;
  738. //}
  739. avatar.MakeChildAgent();
  740. m_log.DebugFormat(
  741. "[CAPS]: Sending new CAPS seed url {0} to client {1}", capsPath, avatar.UUID);
  742. if (eq != null)
  743. {
  744. OSD Item = EventQueueHelper.TeleportFinishEvent(reg.RegionHandle, 13, endPoint,
  745. 4, teleportFlags, capsPath, avatar.UUID);
  746. eq.Enqueue(Item, avatar.UUID);
  747. }
  748. else
  749. {
  750. avatar.ControllingClient.SendRegionTeleport(reg.RegionHandle, 13, endPoint, 4,
  751. teleportFlags, capsPath);
  752. }
  753. if (KiPrimitive != null)
  754. {
  755. KiPrimitive(avatar.LocalId);
  756. }
  757. // TeleportFinish makes the client send CompleteMovementIntoRegion (at the destination), which
  758. // trigers a whole shebang of things there, including MakeRoot. So let's wait plenty before
  759. // we send the attachments and close things here.
  760. Thread.Sleep(3000);
  761. // CrossAttachmentsIntoNewRegion is a synchronous call. We shouldn't need to wait after it
  762. avatar.CrossAttachmentsIntoNewRegion(reg.RegionHandle, true);
  763. // Finally, let's close this previously-known-as-root agent, when the jump is outside the view zone
  764. if (Util.IsOutsideView(oldRegionX, newRegionX, oldRegionY, newRegionY))
  765. {
  766. Thread.Sleep(5000);
  767. avatar.Close();
  768. CloseConnection(avatar.UUID);
  769. }
  770. // if (teleport success) // seems to be always success here
  771. // the user may change their profile information in other region,
  772. // so the userinfo in UserProfileCache is not reliable any more, delete it
  773. if (avatar.Scene.NeedSceneCacheClear(avatar.UUID))
  774. {
  775. m_commsProvider.UserProfileCacheService.RemoveUser(avatar.UUID);
  776. m_log.InfoFormat("User {0} is going to another region, profile cache removed", avatar.UUID);
  777. }
  778. }
  779. else
  780. {
  781. avatar.ControllingClient.SendTeleportFailed("Remote Region appears to be down");
  782. }
  783. }
  784. else
  785. {
  786. // TP to a place that doesn't exist (anymore)
  787. // Inform the viewer about that
  788. avatar.ControllingClient.SendTeleportFailed("The region you tried to teleport to doesn't exist anymore");
  789. // and set the map-tile to '(Offline)'
  790. uint regX, regY;
  791. Utils.LongToUInts(regionHandle, out regX, out regY);
  792. MapBlockData block = new MapBlockData();
  793. block.X = (ushort)(regX / Constants.RegionSize);
  794. block.Y = (ushort)(regY / Constants.RegionSize);
  795. block.Access = 254; // == not there
  796. List<MapBlockData> blocks = new List<MapBlockData>();
  797. blocks.Add(block);
  798. avatar.ControllingClient.SendMapBlock(blocks, 0);
  799. }
  800. }
  801. }
  802. private List<ulong> NeighbourHandles(List<SimpleRegionInfo> neighbours)
  803. {
  804. List<ulong> handles = new List<ulong>();
  805. foreach (SimpleRegionInfo reg in neighbours)
  806. {
  807. handles.Add(reg.RegionHandle);
  808. }
  809. return handles;
  810. }
  811. private List<ulong> NewNeighbours(List<ulong> currentNeighbours, List<ulong> previousNeighbours)
  812. {
  813. return currentNeighbours.FindAll(delegate(ulong handle) { return !previousNeighbours.Contains(handle); });
  814. }
  815. // private List<ulong> CommonNeighbours(List<ulong> currentNeighbours, List<ulong> previousNeighbours)
  816. // {
  817. // return currentNeighbours.FindAll(delegate(ulong handle) { return previousNeighbours.Contains(handle); });
  818. // }
  819. private List<ulong> OldNeighbours(List<ulong> currentNeighbours, List<ulong> previousNeighbours)
  820. {
  821. return previousNeighbours.FindAll(delegate(ulong handle) { return !currentNeighbours.Contains(handle); });
  822. }
  823. /// <summary>
  824. /// Inform a neighbouring region that an avatar is about to cross into it.
  825. /// </summary>
  826. /// <param name="regionhandle"></param>
  827. /// <param name="agentID"></param>
  828. /// <param name="position"></param>
  829. public bool CrossToNeighbouringRegion(ulong regionhandle, UUID agentID, Vector3 position, bool isFlying)
  830. {
  831. return m_commsProvider.InterRegion.ExpectAvatarCrossing(regionhandle, agentID, position, isFlying);
  832. }
  833. public bool PrimCrossToNeighboringRegion(ulong regionhandle, UUID primID, string objData, int XMLMethod)
  834. {
  835. return m_commsProvider.InterRegion.InformRegionOfPrimCrossing(regionhandle, primID, objData, XMLMethod);
  836. }
  837. public Dictionary<string, string> GetGridSettings()
  838. {
  839. return m_commsProvider.GridService.GetGridSettings();
  840. }
  841. public void LogOffUser(UUID userid, UUID regionid, ulong regionhandle, Vector3 position, Vector3 lookat)
  842. {
  843. m_commsProvider.LogOffUser(userid, regionid, regionhandle, position, lookat);
  844. }
  845. // deprecated as of 2008-08-27
  846. public void LogOffUser(UUID userid, UUID regionid, ulong regionhandle, float posx, float posy, float posz)
  847. {
  848. m_commsProvider.LogOffUser(userid, regionid, regionhandle, posx, posy, posz);
  849. }
  850. public void ClearUserAgent(UUID avatarID)
  851. {
  852. m_commsProvider.UserService.ClearUserAgent(avatarID);
  853. }
  854. public void AddNewUserFriend(UUID friendlistowner, UUID friend, uint perms)
  855. {
  856. m_commsProvider.AddNewUserFriend(friendlistowner, friend, perms);
  857. }
  858. public void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms)
  859. {
  860. m_commsProvider.UpdateUserFriendPerms(friendlistowner, friend, perms);
  861. }
  862. public void RemoveUserFriend(UUID friendlistowner, UUID friend)
  863. {
  864. m_commsProvider.RemoveUserFriend(friendlistowner, friend);
  865. }
  866. public List<FriendListItem> GetUserFriendList(UUID friendlistowner)
  867. {
  868. return m_commsProvider.GetUserFriendList(friendlistowner);
  869. }
  870. public List<MapBlockData> RequestNeighbourMapBlocks(int minX, int minY, int maxX, int maxY)
  871. {
  872. return m_commsProvider.GridService.RequestNeighbourMapBlocks(minX, minY, maxX, maxY);
  873. }
  874. public List<AvatarPickerAvatar> GenerateAgentPickerRequestResponse(UUID queryID, string query)
  875. {
  876. return m_commsProvider.GenerateAgentPickerRequestResponse(queryID, query);
  877. }
  878. public List<RegionInfo> RequestNamedRegions(string name, int maxNumber)
  879. {
  880. return m_commsProvider.GridService.RequestNamedRegions(name, maxNumber);
  881. }
  882. // private void Dump(string msg, List<ulong> handles)
  883. // {
  884. // Console.WriteLine("-------------- HANDLE DUMP ({0}) ---------", msg);
  885. // foreach (ulong handle in handles)
  886. // {
  887. // uint x, y;
  888. // Utils.LongToUInts(handle, out x, out y);
  889. // x = x / Constants.RegionSize;
  890. // y = y / Constants.RegionSize;
  891. // Console.WriteLine("({0}, {1})", x, y);
  892. // }
  893. // }
  894. }
  895. }