MapImageService.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. * The design of this map service is based on SimianGrid's PHP-based
  28. * map service. See this URL for the original PHP version:
  29. * https://github.com/openmetaversefoundation/simiangrid/
  30. */
  31. using System;
  32. using System.Collections.Generic;
  33. using System.Drawing;
  34. using System.Drawing.Imaging;
  35. using System.IO;
  36. using System.Net;
  37. using System.Reflection;
  38. using System.Threading;
  39. using Nini.Config;
  40. using log4net;
  41. using OpenMetaverse;
  42. using OpenSim.Framework;
  43. using OpenSim.Framework.Console;
  44. using OpenSim.Services.Interfaces;
  45. namespace OpenSim.Services.MapImageService
  46. {
  47. public class MapImageService : IMapImageService
  48. {
  49. private static readonly ILog m_log =
  50. LogManager.GetLogger(
  51. MethodBase.GetCurrentMethod().DeclaringType);
  52. #pragma warning disable 414
  53. private string LogHeader = "[MAP IMAGE SERVICE]";
  54. #pragma warning restore 414
  55. private const int ZOOM_LEVELS = 8;
  56. private const int IMAGE_WIDTH = 256;
  57. private const int HALF_WIDTH = 128;
  58. private const int JPEG_QUALITY = 80;
  59. private static string m_TilesStoragePath = "maptiles";
  60. private static object m_Sync = new object();
  61. private static bool m_Initialized = false;
  62. private static string m_WaterTileFile = string.Empty;
  63. private static Color m_Watercolor = Color.FromArgb(29, 71, 95);
  64. public MapImageService(IConfigSource config)
  65. {
  66. if (!m_Initialized)
  67. {
  68. m_Initialized = true;
  69. m_log.Debug("[MAP IMAGE SERVICE]: Starting MapImage service");
  70. IConfig serviceConfig = config.Configs["MapImageService"];
  71. if (serviceConfig != null)
  72. {
  73. m_TilesStoragePath = serviceConfig.GetString("TilesStoragePath", m_TilesStoragePath);
  74. if (!Directory.Exists(m_TilesStoragePath))
  75. Directory.CreateDirectory(m_TilesStoragePath);
  76. m_WaterTileFile = Path.Combine(m_TilesStoragePath, "water.jpg");
  77. if (!File.Exists(m_WaterTileFile))
  78. {
  79. Bitmap waterTile = new Bitmap(IMAGE_WIDTH, IMAGE_WIDTH);
  80. FillImage(waterTile, m_Watercolor);
  81. waterTile.Save(m_WaterTileFile, ImageFormat.Jpeg);
  82. }
  83. }
  84. }
  85. }
  86. #region IMapImageService
  87. public bool AddMapTile(int x, int y, byte[] imageData, out string reason)
  88. {
  89. reason = string.Empty;
  90. string fileName = GetFileName(1, x, y);
  91. lock (m_Sync)
  92. {
  93. try
  94. {
  95. using (FileStream f = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.Write))
  96. f.Write(imageData, 0, imageData.Length);
  97. }
  98. catch (Exception e)
  99. {
  100. m_log.WarnFormat("[MAP IMAGE SERVICE]: Unable to save image file {0}: {1}", fileName, e);
  101. reason = e.Message;
  102. return false;
  103. }
  104. }
  105. return UpdateMultiResolutionFilesAsync(x, y, out reason);
  106. }
  107. public bool RemoveMapTile(int x, int y, out string reason)
  108. {
  109. reason = String.Empty;
  110. string fileName = GetFileName(1, x, y);
  111. lock (m_Sync)
  112. {
  113. try
  114. {
  115. File.Delete(fileName);
  116. }
  117. catch (Exception e)
  118. {
  119. m_log.WarnFormat("[MAP IMAGE SERVICE]: Unable to save delete file {0}: {1}", fileName, e);
  120. reason = e.Message;
  121. return false;
  122. }
  123. }
  124. return UpdateMultiResolutionFilesAsync(x, y, out reason);
  125. }
  126. // When large varregions start up, they can send piles of new map tiles. This causes
  127. // this multi-resolution routine to be called a zillion times an causes much CPU
  128. // time to be spent creating multi-resolution tiles that will be replaced when
  129. // the next maptile arrives.
  130. private class mapToMultiRez
  131. {
  132. public int xx;
  133. public int yy;
  134. public mapToMultiRez(int pX, int pY)
  135. {
  136. xx = pX;
  137. yy = pY;
  138. }
  139. };
  140. private Queue<mapToMultiRez> multiRezToBuild = new Queue<mapToMultiRez>();
  141. private bool UpdateMultiResolutionFilesAsync(int x, int y, out string reason)
  142. {
  143. reason = String.Empty;
  144. lock (multiRezToBuild)
  145. {
  146. // m_log.DebugFormat("{0} UpdateMultiResolutionFilesAsync: scheduling update for <{1},{2}>", LogHeader, x, y);
  147. multiRezToBuild.Enqueue(new mapToMultiRez(x, y));
  148. if (multiRezToBuild.Count == 1)
  149. Util.FireAndForget(
  150. DoUpdateMultiResolutionFilesAsync, null, "MapImageService.DoUpdateMultiResolutionFilesAsync");
  151. }
  152. return true;
  153. }
  154. private void DoUpdateMultiResolutionFilesAsync(object o)
  155. {
  156. // This sleep causes the FireAndForget thread to be different than the invocation thread.
  157. // It also allows other tiles to be uploaded so the multi-rez images are more likely
  158. // to be correct.
  159. Thread.Sleep(1 * 1000);
  160. while (multiRezToBuild.Count > 0)
  161. {
  162. mapToMultiRez toMultiRez = null;
  163. lock (multiRezToBuild)
  164. {
  165. if (multiRezToBuild.Count > 0)
  166. toMultiRez = multiRezToBuild.Dequeue();
  167. }
  168. if (toMultiRez != null)
  169. {
  170. int x = toMultiRez.xx;
  171. int y = toMultiRez.yy;
  172. // m_log.DebugFormat("{0} DoUpdateMultiResolutionFilesAsync: doing build for <{1},{2}>", LogHeader, x, y);
  173. // Stitch seven more aggregate tiles together
  174. for (uint zoomLevel = 2; zoomLevel <= ZOOM_LEVELS; zoomLevel++)
  175. {
  176. // Calculate the width (in full resolution tiles) and bottom-left
  177. // corner of the current zoom level
  178. int width = (int)Math.Pow(2, (double)(zoomLevel - 1));
  179. int x1 = x - (x % width);
  180. int y1 = y - (y % width);
  181. lock (m_Sync) // must lock the reading and writing of the maptile files
  182. {
  183. if (!CreateTile(zoomLevel, x1, y1))
  184. {
  185. m_log.WarnFormat("[MAP IMAGE SERVICE]: Unable to create tile for {0},{1} at zoom level {1}", x, y, zoomLevel);
  186. return;
  187. }
  188. }
  189. }
  190. }
  191. }
  192. return;
  193. }
  194. public byte[] GetMapTile(string fileName, out string format)
  195. {
  196. // m_log.DebugFormat("[MAP IMAGE SERVICE]: Getting map tile {0}", fileName);
  197. format = ".jpg";
  198. string fullName = Path.Combine(m_TilesStoragePath, fileName);
  199. if (File.Exists(fullName))
  200. {
  201. format = Path.GetExtension(fileName).ToLower();
  202. //m_log.DebugFormat("[MAP IMAGE SERVICE]: Found file {0}, extension {1}", fileName, format);
  203. return File.ReadAllBytes(fullName);
  204. }
  205. else if (File.Exists(m_WaterTileFile))
  206. {
  207. return File.ReadAllBytes(m_WaterTileFile);
  208. }
  209. else
  210. {
  211. m_log.DebugFormat("[MAP IMAGE SERVICE]: unable to get file {0}", fileName);
  212. return new byte[0];
  213. }
  214. }
  215. #endregion
  216. private string GetFileName(uint zoomLevel, int x, int y)
  217. {
  218. string extension = "jpg";
  219. return Path.Combine(m_TilesStoragePath, string.Format("map-{0}-{1}-{2}-objects.{3}", zoomLevel, x, y, extension));
  220. }
  221. private Bitmap GetInputTileImage(string fileName)
  222. {
  223. try
  224. {
  225. if (File.Exists(fileName))
  226. return new Bitmap(fileName);
  227. }
  228. catch (Exception e)
  229. {
  230. m_log.WarnFormat("[MAP IMAGE SERVICE]: Unable to read image data from {0}: {1}", fileName, e);
  231. }
  232. return null;
  233. }
  234. private Bitmap GetOutputTileImage(string fileName)
  235. {
  236. try
  237. {
  238. if (File.Exists(fileName))
  239. return new Bitmap(fileName);
  240. else
  241. {
  242. // Create a new output tile with a transparent background
  243. Bitmap bm = new Bitmap(IMAGE_WIDTH, IMAGE_WIDTH, PixelFormat.Format24bppRgb);
  244. bm.MakeTransparent();
  245. return bm;
  246. }
  247. }
  248. catch (Exception e)
  249. {
  250. m_log.WarnFormat("[MAP IMAGE SERVICE]: Unable to read image data from {0}: {1}", fileName, e);
  251. }
  252. return null;
  253. }
  254. private bool CreateTile(uint zoomLevel, int x, int y)
  255. {
  256. // m_log.DebugFormat("[MAP IMAGE SERVICE]: Create tile for {0} {1}, zoom {2}", x, y, zoomLevel);
  257. int prevWidth = (int)Math.Pow(2, (double)zoomLevel - 2);
  258. int thisWidth = (int)Math.Pow(2, (double)zoomLevel - 1);
  259. // Convert x and y to the bottom left tile for this zoom level
  260. int xIn = x - (x % prevWidth);
  261. int yIn = y - (y % prevWidth);
  262. // Convert x and y to the bottom left tile for the next zoom level
  263. int xOut = x - (x % thisWidth);
  264. int yOut = y - (y % thisWidth);
  265. // Try to open the four input tiles from the previous zoom level
  266. Bitmap inputBL = GetInputTileImage(GetFileName(zoomLevel - 1, xIn, yIn));
  267. Bitmap inputBR = GetInputTileImage(GetFileName(zoomLevel - 1, xIn + prevWidth, yIn));
  268. Bitmap inputTL = GetInputTileImage(GetFileName(zoomLevel - 1, xIn, yIn + prevWidth));
  269. Bitmap inputTR = GetInputTileImage(GetFileName(zoomLevel - 1, xIn + prevWidth, yIn + prevWidth));
  270. // Open the output tile (current zoom level)
  271. string outputFile = GetFileName(zoomLevel, xOut, yOut);
  272. Bitmap output = GetOutputTileImage(outputFile);
  273. if (output == null)
  274. return false;
  275. FillImage(output, m_Watercolor);
  276. if (inputBL != null)
  277. {
  278. ImageCopyResampled(output, inputBL, 0, HALF_WIDTH, 0, 0);
  279. inputBL.Dispose();
  280. }
  281. if (inputBR != null)
  282. {
  283. ImageCopyResampled(output, inputBR, HALF_WIDTH, HALF_WIDTH, 0, 0);
  284. inputBR.Dispose();
  285. }
  286. if (inputTL != null)
  287. {
  288. ImageCopyResampled(output, inputTL, 0, 0, 0, 0);
  289. inputTL.Dispose();
  290. }
  291. if (inputTR != null)
  292. {
  293. ImageCopyResampled(output, inputTR, HALF_WIDTH, 0, 0, 0);
  294. inputTR.Dispose();
  295. }
  296. // Write the modified output
  297. try
  298. {
  299. using (Bitmap final = new Bitmap(output))
  300. {
  301. output.Dispose();
  302. final.Save(outputFile, ImageFormat.Jpeg);
  303. }
  304. }
  305. catch (Exception e)
  306. {
  307. m_log.WarnFormat("[MAP IMAGE SERVICE]: Oops on saving {0} {1}", outputFile, e);
  308. }
  309. // Save also as png?
  310. return true;
  311. }
  312. #region Image utilities
  313. private void FillImage(Bitmap bm, Color c)
  314. {
  315. for (int x = 0; x < bm.Width; x++)
  316. for (int y = 0; y < bm.Height; y++)
  317. bm.SetPixel(x, y, c);
  318. }
  319. private void ImageCopyResampled(Bitmap output, Bitmap input, int destX, int destY, int srcX, int srcY)
  320. {
  321. int resamplingRateX = 2; // (input.Width - srcX) / (output.Width - destX);
  322. int resamplingRateY = 2; // (input.Height - srcY) / (output.Height - destY);
  323. for (int x = destX; x < destX + HALF_WIDTH; x++)
  324. for (int y = destY; y < destY + HALF_WIDTH; y++)
  325. {
  326. Color p = input.GetPixel(srcX + (x - destX) * resamplingRateX, srcY + (y - destY) * resamplingRateY);
  327. output.SetPixel(x, y, p);
  328. }
  329. }
  330. #endregion
  331. }
  332. }