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