MapImageService.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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 log4net;
  32. using Nini.Config;
  33. using OpenMetaverse;
  34. using OpenSim.Framework;
  35. using OpenSim.Services.Interfaces;
  36. using System;
  37. using System.Collections.Generic;
  38. using System.Drawing;
  39. using System.Drawing.Imaging;
  40. using System.IO;
  41. using System.Reflection;
  42. using System.Threading;
  43. namespace OpenSim.Services.MapImageService
  44. {
  45. public class MapImageService : IMapImageService
  46. {
  47. private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType);
  48. #pragma warning disable 414
  49. private string LogHeader = "[MAP IMAGE SERVICE]";
  50. #pragma warning restore 414
  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 Color m_Watercolor = Color.FromArgb(29, 72, 96);
  59. private static Bitmap m_WaterBitmap = null;
  60. private static byte[] m_WaterJPEGBytes = null;
  61. public MapImageService(IConfigSource config)
  62. {
  63. lock (m_Sync)
  64. {
  65. if (!m_Initialized)
  66. {
  67. m_Initialized = true;
  68. m_log.Debug("[MAP IMAGE SERVICE]: Starting MapImage service");
  69. IConfig serviceConfig = config.Configs["MapImageService"];
  70. if (serviceConfig is not null)
  71. {
  72. m_TilesStoragePath = serviceConfig.GetString("TilesStoragePath", m_TilesStoragePath);
  73. //memory cache JPEG tile with just water.
  74. m_WaterBitmap = new Bitmap(IMAGE_WIDTH, IMAGE_WIDTH, PixelFormat.Format24bppRgb);
  75. FillImage(m_WaterBitmap, m_Watercolor);
  76. using (MemoryStream ms = new MemoryStream())
  77. {
  78. m_WaterBitmap.Save(ms, ImageFormat.Jpeg);
  79. ms.Seek(0, SeekOrigin.Begin);
  80. m_WaterJPEGBytes = ms.ToArray();
  81. }
  82. }
  83. }
  84. }
  85. }
  86. #region IMapImageService
  87. public bool AddMapTile(int x, int y, byte[] imageData, UUID scopeID, out string reason)
  88. {
  89. reason = string.Empty;
  90. ReadOnlySpan<char> path = GetFolder(scopeID);
  91. string fileName = GetFileName(1, x, y, path);
  92. lock (m_Sync)
  93. {
  94. try
  95. {
  96. File.WriteAllBytes(fileName, imageData);
  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 UpdateMultiResolutionFiles(x, y, scopeID);
  106. }
  107. public bool RemoveMapTile(int x, int y, UUID scopeID, out string reason)
  108. {
  109. reason = String.Empty;
  110. string fileName = GetFileName(1, x, y, scopeID);
  111. lock (m_Sync)
  112. {
  113. try
  114. {
  115. File.Delete(fileName);
  116. }
  117. catch (Exception e)
  118. {
  119. m_log.Warn($"[MAP IMAGE SERVICE]: Unable to save delete file {fileName}: {e.Message}");
  120. reason = e.Message;
  121. return false;
  122. }
  123. }
  124. return UpdateMultiResolutionFiles(x, y, scopeID);
  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 struct MapToMultiRez
  131. {
  132. public int x;
  133. public int y;
  134. public UUID scopeID;
  135. }
  136. private readonly Queue<MapToMultiRez> m_MultiRezToBuild = new Queue<MapToMultiRez>();
  137. private bool UpdateMultiResolutionFiles(int x, int y, UUID scopeID)
  138. {
  139. lock (m_MultiRezToBuild)
  140. {
  141. // m_log.DebugFormat("{0} UpdateMultiResolutionFilesAsync: scheduling update for <{1},{2}>", LogHeader, x, y);
  142. m_MultiRezToBuild.Enqueue(
  143. new MapToMultiRez
  144. {
  145. x = x,
  146. y = y,
  147. scopeID = scopeID
  148. }
  149. );
  150. if (m_MultiRezToBuild.Count == 1)
  151. Util.FireAndForget(DoUpdateMultiResolutionFilesAsync);
  152. }
  153. return true;
  154. }
  155. private void DoUpdateMultiResolutionFilesAsync(object o)
  156. {
  157. // let acumulate large region tiles
  158. Thread.Sleep(60 * 1000); // large regions take time to upload tiles
  159. while (true)
  160. {
  161. MapToMultiRez toMultiRez;
  162. lock (m_MultiRezToBuild)
  163. {
  164. if(!m_MultiRezToBuild.TryDequeue(out toMultiRez))
  165. return;
  166. }
  167. ReadOnlySpan<char> path = GetFolder(toMultiRez.scopeID);
  168. for (int zoomLevel = 2; zoomLevel <= ZOOM_LEVELS; zoomLevel++)
  169. {
  170. if (!CreateTile(zoomLevel, toMultiRez.x, toMultiRez.y, path))
  171. {
  172. m_log.WarnFormat("[MAP IMAGE SERVICE]: Unable to create tile for {0},{1} at zoom level {1}", toMultiRez.x, toMultiRez.y, zoomLevel);
  173. return;
  174. }
  175. }
  176. Thread.Sleep(50); // slow things a bit
  177. }
  178. }
  179. public byte[] GetMapTile(string fileName, UUID scopeID, out string format)
  180. {
  181. //m_log.DebugFormat("[MAP IMAGE SERVICE]: Getting map tile {0}", fileName);
  182. string fullName = Path.Combine(m_TilesStoragePath, scopeID.ToString());
  183. fullName = Path.Combine(fullName, fileName);
  184. try
  185. {
  186. lock (m_Sync)
  187. {
  188. format = Path.GetExtension(fileName).ToLower();
  189. //m_log.DebugFormat("[MAP IMAGE SERVICE]: Found file {0}, extension {1}", fileName, format);
  190. return File.ReadAllBytes(fullName);
  191. }
  192. }
  193. catch
  194. {
  195. format = ".jpg";
  196. return m_WaterJPEGBytes is null ? Array.Empty<byte>() : m_WaterJPEGBytes;
  197. }
  198. }
  199. #endregion
  200. private string GetFileName(int zoomLevel, int x, int y, UUID scopeID)
  201. {
  202. string path = Path.Combine(m_TilesStoragePath, scopeID.ToString());
  203. return Path.Combine(path, string.Format("map-{0}-{1}-{2}-objects.{3}", zoomLevel, x, y, "jpg"));
  204. }
  205. private string GetFileName(int zoomLevel, int x, int y, ReadOnlySpan<char> path)
  206. {
  207. return Path.Combine(path.ToString(), string.Format("map-{0}-{1}-{2}-objects.{3}", zoomLevel, x, y, "jpg"));
  208. }
  209. private string GetFolder(UUID scopeID)
  210. {
  211. string path = Path.Combine(m_TilesStoragePath, scopeID.ToString());
  212. Directory.CreateDirectory(path);
  213. return path;
  214. }
  215. private Bitmap GetInputTileImage(string fileName)
  216. {
  217. try
  218. {
  219. lock(m_Sync)
  220. {
  221. if (File.Exists(fileName))
  222. {
  223. Bitmap bm = new Bitmap(fileName);
  224. if (bm.Width != IMAGE_WIDTH || bm.Height != IMAGE_WIDTH || bm.PixelFormat != PixelFormat.Format24bppRgb)
  225. {
  226. m_log.Error($"[MAP IMAGE SERVICE]: invalid map tile {fileName}: {bm.Width} , {bm.Height}, {bm.PixelFormat}");
  227. bm.Dispose();
  228. return null;
  229. }
  230. return bm;
  231. }
  232. }
  233. }
  234. catch (Exception e)
  235. {
  236. m_log.Warn($"[MAP IMAGE SERVICE]: Unable to read image data from {fileName}: {e.Message}");
  237. }
  238. return null;
  239. }
  240. private Bitmap GetOutputTileImage(string fileName)
  241. {
  242. try
  243. {
  244. lock(m_Sync)
  245. {
  246. return File.Exists(fileName) ? new Bitmap(fileName) : new Bitmap(IMAGE_WIDTH, IMAGE_WIDTH, PixelFormat.Format24bppRgb);
  247. }
  248. }
  249. catch (Exception e)
  250. {
  251. m_log.WarnFormat("[MAP IMAGE SERVICE]: Unable to read image data from {0}: {1}", fileName, e);
  252. }
  253. return null;
  254. }
  255. private bool CreateTile(int zoomLevel, int inx, int iny, ReadOnlySpan<char> path)
  256. {
  257. int previusLevel = zoomLevel - 1;
  258. int prevStep = 1 << previusLevel - 1;
  259. int mask = unchecked((int)0xffffffff) << previusLevel;
  260. // Convert x and y to the bottom left of current tile
  261. int x = inx & mask;
  262. int y = iny & mask;
  263. int ntiles = 0;
  264. Bitmap output = (Bitmap)m_WaterBitmap.Clone();
  265. Bitmap input = GetInputTileImage(GetFileName(previusLevel, x, y, path));
  266. if (input is not null)
  267. {
  268. ImageCopyResampled(output, input, 0, HALF_WIDTH);
  269. input.Dispose();
  270. ntiles++;
  271. }
  272. input = GetInputTileImage(GetFileName(previusLevel, x + prevStep, y, path));
  273. if (input is not null)
  274. {
  275. ImageCopyResampled(output, input, HALF_WIDTH, HALF_WIDTH);
  276. input.Dispose();
  277. ntiles++;
  278. }
  279. input = GetInputTileImage(GetFileName(previusLevel, x, y + prevStep, path));
  280. if (input is not null)
  281. {
  282. ImageCopyResampled(output, input, 0, 0);
  283. input.Dispose();
  284. ntiles++;
  285. }
  286. input = GetInputTileImage(GetFileName(previusLevel, x + prevStep, y + prevStep, path));
  287. if (input is not null)
  288. {
  289. ImageCopyResampled(output, input, HALF_WIDTH, 0);
  290. input.Dispose();
  291. ntiles++;
  292. }
  293. string outputFile = GetFileName(zoomLevel, x, y, path);
  294. try
  295. {
  296. lock(m_Sync)
  297. {
  298. File.Delete(outputFile);
  299. if (ntiles > 0)
  300. output.Save(outputFile, ImageFormat.Jpeg);
  301. }
  302. }
  303. catch (Exception e)
  304. {
  305. m_log.Warn($"[MAP IMAGE SERVICE]: Oops on saving {outputFile} {e.Message}");
  306. }
  307. output.Dispose();
  308. return true;
  309. }
  310. #region Image utilities
  311. private void FillImage(Bitmap bm, Color c)
  312. {
  313. BitmapData srcData = bm.LockBits(new Rectangle(0, 0, bm.Width, bm.Height), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
  314. byte r = c.R;
  315. byte g = c.G;
  316. byte b = c.B;
  317. unsafe
  318. {
  319. byte* ptr = (byte*)srcData.Scan0;
  320. for(int y = 0; y < bm.Height; y++)
  321. {
  322. for(int x = 0; x < bm.Width; x++)
  323. {
  324. *ptr++ = b;
  325. *ptr++ = g;
  326. *ptr++ = r;
  327. }
  328. }
  329. }
  330. bm.UnlockBits(srcData);
  331. }
  332. private void ImageCopyResampled(Bitmap output, Bitmap input, int destX, int destY)
  333. {
  334. try
  335. {
  336. BitmapData srcData = input.LockBits(new Rectangle(0, 0, input.Width, input.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
  337. BitmapData dstData = output.LockBits(new Rectangle(0, 0, output.Width, output.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
  338. unsafe
  339. {
  340. byte* srcPointer = (byte*)srcData.Scan0;
  341. byte* srcPointer2 = (byte*)srcData.Scan0 + srcData.Stride;
  342. byte* dstPointer = (byte*)dstData.Scan0 + destY * dstData.Stride + 3 * destX;
  343. for (int y = 0; y < HALF_WIDTH; y++)
  344. {
  345. byte* dxptr = dstPointer;
  346. for (int i = 0; i < HALF_WIDTH; i++)
  347. {
  348. // Blue
  349. int t = srcPointer[0] + srcPointer[3] + srcPointer2[0] + srcPointer2[3];
  350. dxptr[0] = (byte)(t >> 2);
  351. // Green
  352. t = srcPointer[1] + srcPointer[4] + srcPointer2[1] + srcPointer2[4];
  353. dxptr[1] = (byte)(t >> 2);
  354. // Red
  355. t = srcPointer[2] + srcPointer[5] + srcPointer2[2] + srcPointer2[5];
  356. dxptr[2] = (byte)(t >> 2);
  357. /*
  358. dxptr[0] = srcPointer[0]; // Blue
  359. dxptr[1] = srcPointer[1]; // Green
  360. dxptr[2] = srcPointer[2]; // Red
  361. */
  362. srcPointer += 6; // skip one point
  363. srcPointer2 += 6; // skip one point
  364. dxptr += 3;
  365. }
  366. srcPointer += srcData.Stride; // skip extra line
  367. srcPointer2 += srcData.Stride;
  368. dstPointer += dstData.Stride;
  369. }
  370. }
  371. output.UnlockBits(dstData);
  372. input.UnlockBits(srcData);
  373. }
  374. //catch (InvalidOperationException e)
  375. catch
  376. {
  377. }
  378. }
  379. #endregion
  380. }
  381. }