MapImageService.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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 Nini.Config;
  39. using log4net;
  40. using OpenMetaverse;
  41. using OpenSim.Framework;
  42. using OpenSim.Framework.Console;
  43. using OpenSim.Services.Interfaces;
  44. namespace OpenSim.Services.MapImageService
  45. {
  46. public class MapImageService : IMapImageService
  47. {
  48. private static readonly ILog m_log =
  49. LogManager.GetLogger(
  50. MethodBase.GetCurrentMethod().DeclaringType);
  51. private const int ZOOM_LEVELS = 8;
  52. private const int IMAGE_WIDTH = 256;
  53. private const int HALF_WIDTH = 128;
  54. private const int JPEG_QUALITY = 80;
  55. private static string m_TilesStoragePath = "maptiles";
  56. private static object m_Sync = new object();
  57. private static bool m_Initialized = false;
  58. private static string m_WaterTileFile = string.Empty;
  59. private static Color m_Watercolor = Color.FromArgb(29, 71, 95);
  60. public MapImageService(IConfigSource config)
  61. {
  62. if (!m_Initialized)
  63. {
  64. m_Initialized = true;
  65. m_log.Debug("[MAP IMAGE SERVICE]: Starting MapImage service");
  66. IConfig serviceConfig = config.Configs["MapImageService"];
  67. if (serviceConfig != null)
  68. {
  69. m_TilesStoragePath = serviceConfig.GetString("TilesStoragePath", m_TilesStoragePath);
  70. if (!Directory.Exists(m_TilesStoragePath))
  71. Directory.CreateDirectory(m_TilesStoragePath);
  72. m_WaterTileFile = Path.Combine(m_TilesStoragePath, "water.jpg");
  73. if (!File.Exists(m_WaterTileFile))
  74. {
  75. Bitmap waterTile = new Bitmap(IMAGE_WIDTH, IMAGE_WIDTH);
  76. FillImage(waterTile, m_Watercolor);
  77. waterTile.Save(m_WaterTileFile);
  78. }
  79. }
  80. }
  81. }
  82. #region IMapImageService
  83. public bool AddMapTile(int x, int y, byte[] imageData, out string reason)
  84. {
  85. reason = string.Empty;
  86. string fileName = GetFileName(1, x, y);
  87. lock (m_Sync)
  88. {
  89. try
  90. {
  91. using (FileStream f = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.Write))
  92. f.Write(imageData, 0, imageData.Length);
  93. }
  94. catch (Exception e)
  95. {
  96. m_log.WarnFormat("[MAP IMAGE SERVICE]: Unable to save image file {0}: {1}", fileName, e);
  97. reason = e.Message;
  98. return false;
  99. }
  100. // Also save in png format?
  101. // Stitch seven more aggregate tiles together
  102. for (uint zoomLevel = 2; zoomLevel <= ZOOM_LEVELS; zoomLevel++)
  103. {
  104. // Calculate the width (in full resolution tiles) and bottom-left
  105. // corner of the current zoom level
  106. int width = (int)Math.Pow(2, (double)(zoomLevel - 1));
  107. int x1 = x - (x % width);
  108. int y1 = y - (y % width);
  109. if (!CreateTile(zoomLevel, x1, y1))
  110. {
  111. m_log.WarnFormat("[MAP IMAGE SERVICE]: Unable to create tile for {0} at zoom level {1}", fileName, zoomLevel);
  112. reason = string.Format("Map tile at zoom level {0} failed", zoomLevel);
  113. return false;
  114. }
  115. }
  116. }
  117. return true;
  118. }
  119. public byte[] GetMapTile(string fileName, out string format)
  120. {
  121. format = ".jpg";
  122. string fullName = Path.Combine(m_TilesStoragePath, fileName);
  123. if (File.Exists(fullName))
  124. {
  125. format = Path.GetExtension(fileName).ToLower();
  126. //m_log.DebugFormat("[MAP IMAGE SERVICE]: Found file {0}, extension {1}", fileName, format);
  127. return File.ReadAllBytes(fullName);
  128. }
  129. else if (File.Exists(m_WaterTileFile))
  130. {
  131. return File.ReadAllBytes(m_WaterTileFile);
  132. }
  133. else
  134. {
  135. m_log.DebugFormat("[MAP IMAGE SERVICE]: unable to get file {0}", fileName);
  136. return new byte[0];
  137. }
  138. }
  139. #endregion
  140. private string GetFileName(uint zoomLevel, int x, int y)
  141. {
  142. string extension = "jpg";
  143. return Path.Combine(m_TilesStoragePath, string.Format("map-{0}-{1}-{2}-objects.{3}", zoomLevel, x, y, extension));
  144. }
  145. private Bitmap GetInputTileImage(string fileName)
  146. {
  147. try
  148. {
  149. if (File.Exists(fileName))
  150. return new Bitmap(fileName);
  151. }
  152. catch (Exception e)
  153. {
  154. m_log.WarnFormat("[MAP IMAGE SERVICE]: Unable to read image data from {0}: {1}", fileName, e);
  155. }
  156. return null;
  157. }
  158. private Bitmap GetOutputTileImage(string fileName)
  159. {
  160. try
  161. {
  162. if (File.Exists(fileName))
  163. return new Bitmap(fileName);
  164. else
  165. {
  166. // Create a new output tile with a transparent background
  167. Bitmap bm = new Bitmap(IMAGE_WIDTH, IMAGE_WIDTH, PixelFormat.Format24bppRgb);
  168. bm.MakeTransparent();
  169. return bm;
  170. }
  171. }
  172. catch (Exception e)
  173. {
  174. m_log.WarnFormat("[MAP IMAGE SERVICE]: Unable to read image data from {0}: {1}", fileName, e);
  175. }
  176. return null;
  177. }
  178. private bool CreateTile(uint zoomLevel, int x, int y)
  179. {
  180. m_log.DebugFormat("[MAP IMAGE SERVICE]: Create tile for {0} {1}, zoom {2}", x, y, zoomLevel);
  181. int prevWidth = (int)Math.Pow(2, (double)zoomLevel - 2);
  182. int thisWidth = (int)Math.Pow(2, (double)zoomLevel - 1);
  183. // Convert x and y to the bottom left tile for this zoom level
  184. int xIn = x - (x % prevWidth);
  185. int yIn = y - (y % prevWidth);
  186. // Convert x and y to the bottom left tile for the next zoom level
  187. int xOut = x - (x % thisWidth);
  188. int yOut = y - (y % thisWidth);
  189. // Try to open the four input tiles from the previous zoom level
  190. Bitmap inputBL = GetInputTileImage(GetFileName(zoomLevel - 1, xIn, yIn));
  191. Bitmap inputBR = GetInputTileImage(GetFileName(zoomLevel - 1, xIn + prevWidth, yIn));
  192. Bitmap inputTL = GetInputTileImage(GetFileName(zoomLevel - 1, xIn, yIn + prevWidth));
  193. Bitmap inputTR = GetInputTileImage(GetFileName(zoomLevel - 1, xIn + prevWidth, yIn + prevWidth));
  194. // Open the output tile (current zoom level)
  195. string outputFile = GetFileName(zoomLevel, xOut, yOut);
  196. Bitmap output = GetOutputTileImage(outputFile);
  197. if (output == null)
  198. return false;
  199. FillImage(output, m_Watercolor);
  200. if (inputBL != null)
  201. {
  202. ImageCopyResampled(output, inputBL, 0, HALF_WIDTH, 0, 0);
  203. inputBL.Dispose();
  204. }
  205. if (inputBR != null)
  206. {
  207. ImageCopyResampled(output, inputBR, HALF_WIDTH, HALF_WIDTH, 0, 0);
  208. inputBR.Dispose();
  209. }
  210. if (inputTL != null)
  211. {
  212. ImageCopyResampled(output, inputTL, 0, 0, 0, 0);
  213. inputTL.Dispose();
  214. }
  215. if (inputTR != null)
  216. {
  217. ImageCopyResampled(output, inputTR, HALF_WIDTH, 0, 0, 0);
  218. inputTR.Dispose();
  219. }
  220. // Write the modified output
  221. try
  222. {
  223. using (Bitmap final = new Bitmap(output))
  224. {
  225. output.Dispose();
  226. final.Save(outputFile, ImageFormat.Jpeg);
  227. }
  228. }
  229. catch (Exception e)
  230. {
  231. m_log.WarnFormat("[MAP IMAGE SERVICE]: Oops on saving {0} {1}", outputFile, e);
  232. }
  233. // Save also as png?
  234. return true;
  235. }
  236. #region Image utilities
  237. private void FillImage(Bitmap bm, Color c)
  238. {
  239. for (int x = 0; x < bm.Width; x++)
  240. for (int y = 0; y < bm.Height; y++)
  241. bm.SetPixel(x, y, c);
  242. }
  243. private void ImageCopyResampled(Bitmap output, Bitmap input, int destX, int destY, int srcX, int srcY)
  244. {
  245. int resamplingRateX = 2; // (input.Width - srcX) / (output.Width - destX);
  246. int resamplingRateY = 2; // (input.Height - srcY) / (output.Height - destY);
  247. for (int x = destX; x < destX + HALF_WIDTH; x++)
  248. for (int y = destY; y < destY + HALF_WIDTH; y++)
  249. {
  250. Color p = input.GetPixel(srcX + (x - destX) * resamplingRateX, srcY + (y - destY) * resamplingRateY);
  251. output.SetPixel(x, y, p);
  252. }
  253. }
  254. #endregion
  255. }
  256. }