SimianGridMaptileModule.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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.Collections.Specialized;
  30. using System.Reflection;
  31. using System.Net;
  32. using System.IO;
  33. using System.Timers;
  34. using System.Drawing;
  35. using System.Drawing.Imaging;
  36. using log4net;
  37. using Mono.Addins;
  38. using Nini.Config;
  39. using OpenSim.Framework;
  40. using OpenSim.Region.Framework.Interfaces;
  41. using OpenSim.Region.Framework.Scenes;
  42. using OpenMetaverse;
  43. using OpenMetaverse.StructuredData;
  44. //namespace OpenSim.Region.OptionalModules.Simian
  45. namespace OpenSim.Services.Connectors.SimianGrid
  46. {
  47. /// <summary>
  48. /// </summary>
  49. /// <remarks>
  50. /// </remarks>
  51. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "SimianGridMaptile")]
  52. public class SimianGridMaptile : ISharedRegionModule
  53. {
  54. private static readonly ILog m_log =
  55. LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  56. private bool m_enabled = false;
  57. private string m_serverUrl = String.Empty;
  58. private Dictionary<UUID, Scene> m_scenes = new Dictionary<UUID, Scene>();
  59. private int m_refreshtime = 0;
  60. private int m_lastrefresh = 0;
  61. private System.Timers.Timer m_refreshTimer = new System.Timers.Timer();
  62. #region ISharedRegionModule
  63. public Type ReplaceableInterface { get { return null; } }
  64. public string Name { get { return "SimianGridMaptile"; } }
  65. public void RegionLoaded(Scene scene) { }
  66. public void Close() { }
  67. ///<summary>
  68. ///
  69. ///</summary>
  70. public void Initialise(IConfigSource source)
  71. {
  72. IConfig config = source.Configs["SimianGridMaptiles"];
  73. if (config == null)
  74. return;
  75. if (! config.GetBoolean("Enabled", false))
  76. return;
  77. m_serverUrl = config.GetString("MaptileURL");
  78. if (String.IsNullOrEmpty(m_serverUrl))
  79. return;
  80. int refreshseconds = Convert.ToInt32(config.GetString("RefreshTime"));
  81. if (refreshseconds <= 0)
  82. return;
  83. m_refreshtime = refreshseconds * 1000; // convert from seconds to ms
  84. m_log.InfoFormat("[SIMIAN MAPTILE] enabled with refresh timeout {0} and URL {1}",
  85. m_refreshtime,m_serverUrl);
  86. m_enabled = true;
  87. }
  88. ///<summary>
  89. ///
  90. ///</summary>
  91. public void PostInitialise()
  92. {
  93. if (m_enabled)
  94. {
  95. m_refreshTimer.Enabled = true;
  96. m_refreshTimer.AutoReset = true;
  97. m_refreshTimer.Interval = 5 * 60 * 1000; // every 5 minutes
  98. m_refreshTimer.Elapsed += new ElapsedEventHandler(HandleMaptileRefresh);
  99. }
  100. }
  101. ///<summary>
  102. ///
  103. ///</summary>
  104. public void AddRegion(Scene scene)
  105. {
  106. if (! m_enabled)
  107. return;
  108. // Every shared region module has to maintain an indepedent list of
  109. // currently running regions
  110. lock (m_scenes)
  111. m_scenes[scene.RegionInfo.RegionID] = scene;
  112. }
  113. ///<summary>
  114. ///
  115. ///</summary>
  116. public void RemoveRegion(Scene scene)
  117. {
  118. if (! m_enabled)
  119. return;
  120. lock (m_scenes)
  121. m_scenes.Remove(scene.RegionInfo.RegionID);
  122. }
  123. #endregion ISharedRegionModule
  124. ///<summary>
  125. ///
  126. ///</summary>
  127. private void HandleMaptileRefresh(object sender, EventArgs ea)
  128. {
  129. // this approach is a bit convoluted becase we want to wait for the
  130. // first upload to happen on startup but after all the objects are
  131. // loaded and initialized
  132. if (m_lastrefresh > 0 && Util.EnvironmentTickCountSubtract(m_lastrefresh) < m_refreshtime)
  133. return;
  134. m_log.DebugFormat("[SIMIAN MAPTILE] map refresh fired");
  135. lock (m_scenes)
  136. {
  137. foreach (IScene scene in m_scenes.Values)
  138. {
  139. try
  140. {
  141. UploadMapTile(scene);
  142. }
  143. catch (Exception ex)
  144. {
  145. m_log.WarnFormat("[SIMIAN MAPTILE] something bad happened {0}",ex.Message);
  146. }
  147. }
  148. }
  149. m_lastrefresh = Util.EnvironmentTickCount();
  150. }
  151. ///<summary>
  152. ///
  153. ///</summary>
  154. private void UploadMapTile(IScene scene)
  155. {
  156. m_log.DebugFormat("[SIMIAN MAPTILE]: upload maptile for {0}",scene.RegionInfo.RegionName);
  157. // Create a PNG map tile and upload it to the AddMapTile API
  158. IMapImageGenerator tileGenerator = scene.RequestModuleInterface<IMapImageGenerator>();
  159. if (tileGenerator == null)
  160. {
  161. m_log.Warn("[SIMIAN MAPTILE]: Cannot upload PNG map tile without an ImageGenerator");
  162. return;
  163. }
  164. using (Bitmap mapTile = tileGenerator.CreateMapTile())
  165. {
  166. if (mapTile != null)
  167. {
  168. // If the region/maptile is legacy sized, just upload the one tile like it has always been done
  169. if (mapTile.Width == Constants.RegionSize && mapTile.Height == Constants.RegionSize)
  170. {
  171. ConvertAndUploadMaptile(mapTile, scene.RegionInfo.RegionLocX, scene.RegionInfo.RegionLocY);
  172. }
  173. else
  174. {
  175. // For larger regions (varregion) we must cut the region image into legacy sized
  176. // pieces since that is how the maptile system works.
  177. // Note the assumption that varregions are always a multiple of legacy size.
  178. for (uint xx = 0; xx < mapTile.Width; xx += Constants.RegionSize)
  179. {
  180. for (uint yy = 0; yy < mapTile.Height; yy += Constants.RegionSize)
  181. {
  182. // Images are addressed from the upper left corner so have to do funny
  183. // math to pick out the sub-tile since regions are numbered from
  184. // the lower left.
  185. Rectangle rect = new Rectangle(
  186. (int)xx,
  187. mapTile.Height - (int)yy - (int)Constants.RegionSize,
  188. (int)Constants.RegionSize, (int)Constants.RegionSize);
  189. using (Bitmap subMapTile = mapTile.Clone(rect, mapTile.PixelFormat))
  190. {
  191. uint locX = scene.RegionInfo.RegionLocX + (xx / Constants.RegionSize);
  192. uint locY = scene.RegionInfo.RegionLocY + (yy / Constants.RegionSize);
  193. ConvertAndUploadMaptile(subMapTile, locX, locY);
  194. }
  195. }
  196. }
  197. }
  198. }
  199. else
  200. {
  201. m_log.WarnFormat("[SIMIAN MAPTILE] Tile image generation failed");
  202. }
  203. }
  204. }
  205. ///<summary>
  206. ///
  207. ///</summary>
  208. private void ConvertAndUploadMaptile(Image mapTile, uint locX, uint locY)
  209. {
  210. //m_log.DebugFormat("[SIMIAN MAPTILE]: upload maptile for location {0}, {1}", locX, locY);
  211. byte[] pngData = Utils.EmptyBytes;
  212. using (MemoryStream stream = new MemoryStream())
  213. {
  214. mapTile.Save(stream, ImageFormat.Png);
  215. pngData = stream.ToArray();
  216. }
  217. NameValueCollection requestArgs = new NameValueCollection
  218. {
  219. { "RequestMethod", "xAddMapTile" },
  220. { "X", locX.ToString() },
  221. { "Y", locY.ToString() },
  222. { "ContentType", "image/png" },
  223. { "EncodedData", System.Convert.ToBase64String(pngData) }
  224. };
  225. OSDMap response = SimianGrid.PostToService(m_serverUrl,requestArgs);
  226. if (! response["Success"].AsBoolean())
  227. {
  228. m_log.WarnFormat("[SIMIAN MAPTILE] failed to store map tile; {0}",response["Message"].AsString());
  229. }
  230. }
  231. }
  232. }