1
0

MapImageService.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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, ImageFormat.Jpeg);
  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. // m_log.DebugFormat("[MAP IMAGE SERVICE]: Getting map tile {0}", fileName);
  122. format = ".jpg";
  123. string fullName = Path.Combine(m_TilesStoragePath, fileName);
  124. if (File.Exists(fullName))
  125. {
  126. format = Path.GetExtension(fileName).ToLower();
  127. //m_log.DebugFormat("[MAP IMAGE SERVICE]: Found file {0}, extension {1}", fileName, format);
  128. return File.ReadAllBytes(fullName);
  129. }
  130. else if (File.Exists(m_WaterTileFile))
  131. {
  132. return File.ReadAllBytes(m_WaterTileFile);
  133. }
  134. else
  135. {
  136. m_log.DebugFormat("[MAP IMAGE SERVICE]: unable to get file {0}", fileName);
  137. return new byte[0];
  138. }
  139. }
  140. #endregion
  141. private string GetFileName(uint zoomLevel, int x, int y)
  142. {
  143. string extension = "jpg";
  144. return Path.Combine(m_TilesStoragePath, string.Format("map-{0}-{1}-{2}-objects.{3}", zoomLevel, x, y, extension));
  145. }
  146. private Bitmap GetInputTileImage(string fileName)
  147. {
  148. try
  149. {
  150. if (File.Exists(fileName))
  151. return new Bitmap(fileName);
  152. }
  153. catch (Exception e)
  154. {
  155. m_log.WarnFormat("[MAP IMAGE SERVICE]: Unable to read image data from {0}: {1}", fileName, e);
  156. }
  157. return null;
  158. }
  159. private Bitmap GetOutputTileImage(string fileName)
  160. {
  161. try
  162. {
  163. if (File.Exists(fileName))
  164. return new Bitmap(fileName);
  165. else
  166. {
  167. // Create a new output tile with a transparent background
  168. Bitmap bm = new Bitmap(IMAGE_WIDTH, IMAGE_WIDTH, PixelFormat.Format24bppRgb);
  169. bm.MakeTransparent();
  170. return bm;
  171. }
  172. }
  173. catch (Exception e)
  174. {
  175. m_log.WarnFormat("[MAP IMAGE SERVICE]: Unable to read image data from {0}: {1}", fileName, e);
  176. }
  177. return null;
  178. }
  179. private bool CreateTile(uint zoomLevel, int x, int y)
  180. {
  181. // m_log.DebugFormat("[MAP IMAGE SERVICE]: Create tile for {0} {1}, zoom {2}", x, y, zoomLevel);
  182. int prevWidth = (int)Math.Pow(2, (double)zoomLevel - 2);
  183. int thisWidth = (int)Math.Pow(2, (double)zoomLevel - 1);
  184. // Convert x and y to the bottom left tile for this zoom level
  185. int xIn = x - (x % prevWidth);
  186. int yIn = y - (y % prevWidth);
  187. // Convert x and y to the bottom left tile for the next zoom level
  188. int xOut = x - (x % thisWidth);
  189. int yOut = y - (y % thisWidth);
  190. // Try to open the four input tiles from the previous zoom level
  191. Bitmap inputBL = GetInputTileImage(GetFileName(zoomLevel - 1, xIn, yIn));
  192. Bitmap inputBR = GetInputTileImage(GetFileName(zoomLevel - 1, xIn + prevWidth, yIn));
  193. Bitmap inputTL = GetInputTileImage(GetFileName(zoomLevel - 1, xIn, yIn + prevWidth));
  194. Bitmap inputTR = GetInputTileImage(GetFileName(zoomLevel - 1, xIn + prevWidth, yIn + prevWidth));
  195. // Open the output tile (current zoom level)
  196. string outputFile = GetFileName(zoomLevel, xOut, yOut);
  197. Bitmap output = GetOutputTileImage(outputFile);
  198. if (output == null)
  199. return false;
  200. FillImage(output, m_Watercolor);
  201. if (inputBL != null)
  202. {
  203. ImageCopyResampled(output, inputBL, 0, HALF_WIDTH, 0, 0);
  204. inputBL.Dispose();
  205. }
  206. if (inputBR != null)
  207. {
  208. ImageCopyResampled(output, inputBR, HALF_WIDTH, HALF_WIDTH, 0, 0);
  209. inputBR.Dispose();
  210. }
  211. if (inputTL != null)
  212. {
  213. ImageCopyResampled(output, inputTL, 0, 0, 0, 0);
  214. inputTL.Dispose();
  215. }
  216. if (inputTR != null)
  217. {
  218. ImageCopyResampled(output, inputTR, HALF_WIDTH, 0, 0, 0);
  219. inputTR.Dispose();
  220. }
  221. // Write the modified output
  222. try
  223. {
  224. using (Bitmap final = new Bitmap(output))
  225. {
  226. output.Dispose();
  227. final.Save(outputFile, ImageFormat.Jpeg);
  228. }
  229. }
  230. catch (Exception e)
  231. {
  232. m_log.WarnFormat("[MAP IMAGE SERVICE]: Oops on saving {0} {1}", outputFile, e);
  233. }
  234. // Save also as png?
  235. return true;
  236. }
  237. #region Image utilities
  238. private void FillImage(Bitmap bm, Color c)
  239. {
  240. for (int x = 0; x < bm.Width; x++)
  241. for (int y = 0; y < bm.Height; y++)
  242. bm.SetPixel(x, y, c);
  243. }
  244. private void ImageCopyResampled(Bitmap output, Bitmap input, int destX, int destY, int srcX, int srcY)
  245. {
  246. int resamplingRateX = 2; // (input.Width - srcX) / (output.Width - destX);
  247. int resamplingRateY = 2; // (input.Height - srcY) / (output.Height - destY);
  248. for (int x = destX; x < destX + HALF_WIDTH; x++)
  249. for (int y = destY; y < destY + HALF_WIDTH; y++)
  250. {
  251. Color p = input.GetPixel(srcX + (x - destX) * resamplingRateX, srcY + (y - destY) * resamplingRateY);
  252. output.SetPixel(x, y, p);
  253. }
  254. }
  255. #endregion
  256. }
  257. }