OpenSim
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Events Macros
TexturedMapTileRenderer.cs
Go to the documentation of this file.
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 
28 using System;
29 using System.Collections.Generic;
30 using System.Drawing;
31 using System.Reflection;
32 using log4net;
33 using Nini.Config;
34 using OpenMetaverse;
35 using OpenMetaverse.Imaging;
36 using OpenSim.Framework;
37 using OpenSim.Region.Framework;
38 using OpenSim.Region.Framework.Interfaces;
39 using OpenSim.Region.Framework.Scenes;
40 
41 namespace OpenSim.Region.CoreModules.World.LegacyMap
42 {
43  // Hue, Saturation, Value; used for color-interpolation
44  struct HSV {
45  private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
46 
47  public float h;
48  public float s;
49  public float v;
50 
51  public HSV(float h, float s, float v)
52  {
53  this.h = h;
54  this.s = s;
55  this.v = v;
56  }
57 
58  // (for info about algorithm, see http://en.wikipedia.org/wiki/HSL_and_HSV)
59  public HSV(Color c)
60  {
61  float r = c.R / 255f;
62  float g = c.G / 255f;
63  float b = c.B / 255f;
64  float max = Math.Max(Math.Max(r, g), b);
65  float min = Math.Min(Math.Min(r, g), b);
66  float diff = max - min;
67 
68  if (max == min) h = 0f;
69  else if (max == r) h = (g - b) / diff * 60f;
70  else if (max == g) h = (b - r) / diff * 60f + 120f;
71  else h = (r - g) / diff * 60f + 240f;
72  if (h < 0f) h += 360f;
73 
74  if (max == 0f) s = 0f;
75  else s = diff / max;
76 
77  v = max;
78  }
79 
80  // (for info about algorithm, see http://en.wikipedia.org/wiki/HSL_and_HSV)
81  public Color toColor()
82  {
83  if (s < 0f) m_log.Debug("S < 0: " + s);
84  else if (s > 1f) m_log.Debug("S > 1: " + s);
85  if (v < 0f) m_log.Debug("V < 0: " + v);
86  else if (v > 1f) m_log.Debug("V > 1: " + v);
87 
88  float f = h / 60f;
89  int sector = (int)f % 6;
90  f = f - (int)f;
91  int pi = (int)(v * (1f - s) * 255f);
92  int qi = (int)(v * (1f - s * f) * 255f);
93  int ti = (int)(v * (1f - (1f - f) * s) * 255f);
94  int vi = (int)(v * 255f);
95 
96  if (pi < 0) pi = 0;
97  if (pi > 255) pi = 255;
98  if (qi < 0) qi = 0;
99  if (qi > 255) qi = 255;
100  if (ti < 0) ti = 0;
101  if (ti > 255) ti = 255;
102  if (vi < 0) vi = 0;
103  if (vi > 255) vi = 255;
104 
105  switch (sector)
106  {
107  case 0:
108  return Color.FromArgb(vi, ti, pi);
109  case 1:
110  return Color.FromArgb(qi, vi, pi);
111  case 2:
112  return Color.FromArgb(pi, vi, ti);
113  case 3:
114  return Color.FromArgb(pi, qi, vi);
115  case 4:
116  return Color.FromArgb(ti, pi, vi);
117  default:
118  return Color.FromArgb(vi, pi, qi);
119  }
120  }
121  }
122 
124  {
125  #region Constants
126 
127  private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
128  private static readonly string LogHeader = "[TEXTURED MAPTILE RENDERER]";
129 
130  // some hardcoded terrain UUIDs that work with SL 1.20 (the four default textures and "Blank").
131  // The color-values were choosen because they "look right" (at least to me) ;-)
132  private static readonly UUID defaultTerrainTexture1 = new UUID("0bc58228-74a0-7e83-89bc-5c23464bcec5");
133  private static readonly Color defaultColor1 = Color.FromArgb(165, 137, 118);
134  private static readonly UUID defaultTerrainTexture2 = new UUID("63338ede-0037-c4fd-855b-015d77112fc8");
135  private static readonly Color defaultColor2 = Color.FromArgb(69, 89, 49);
136  private static readonly UUID defaultTerrainTexture3 = new UUID("303cd381-8560-7579-23f1-f0a880799740");
137  private static readonly Color defaultColor3 = Color.FromArgb(162, 154, 141);
138  private static readonly UUID defaultTerrainTexture4 = new UUID("53a2f406-4895-1d13-d541-d2e3b86bc19c");
139  private static readonly Color defaultColor4 = Color.FromArgb(200, 200, 200);
140 
141  private static readonly Color WATER_COLOR = Color.FromArgb(29, 71, 95);
142 
143  #endregion
144 
145 
146  private Scene m_scene;
147  // private IConfigSource m_config; // not used currently
148 
149  // mapping from texture UUIDs to averaged color. This will contain 5-9 values, in general; new values are only
150  // added when the terrain textures are changed in the estate dialog and a new map is generated (and will stay in
151  // that map until the region-server restarts. This could be considered a memory-leak, but it's a *very* small one.
152  // TODO does it make sense to use a "real" cache and regenerate missing entries on fetch?
153  private Dictionary<UUID, Color> m_mapping;
154 
155 
156  public void Initialise(Scene scene, IConfigSource source)
157  {
158  m_scene = scene;
159  // m_config = source; // not used currently
160  m_mapping = new Dictionary<UUID,Color>();
161  m_mapping.Add(defaultTerrainTexture1, defaultColor1);
162  m_mapping.Add(defaultTerrainTexture2, defaultColor2);
163  m_mapping.Add(defaultTerrainTexture3, defaultColor3);
164  m_mapping.Add(defaultTerrainTexture4, defaultColor4);
165  m_mapping.Add(Util.BLANK_TEXTURE_UUID, Color.White);
166  }
167 
168  #region Helpers
169  // This fetches the texture from the asset server synchroneously. That should be ok, as we
170  // call map-creation only in those places:
171  // - on start: We can wait here until the asset server returns the texture
172  // TODO (- on "map" command: We are in the command-line thread, we will wait for completion anyway)
173  // TODO (- on "automatic" update after some change: We are called from the mapUpdateTimer here and
174  // will wait anyway)
175  private Bitmap fetchTexture(UUID id)
176  {
177  AssetBase asset = m_scene.AssetService.Get(id.ToString());
178  m_log.DebugFormat("{0} Fetched texture {1}, found: {2}", LogHeader, id, asset != null);
179  if (asset == null) return null;
180 
181  ManagedImage managedImage;
182  Image image;
183 
184  try
185  {
186  if (OpenJPEG.DecodeToImage(asset.Data, out managedImage, out image))
187  return new Bitmap(image);
188  else
189  return null;
190  }
191  catch (DllNotFoundException)
192  {
193  m_log.ErrorFormat("{0} OpenJpeg is not installed correctly on this system. Asset Data is empty for {1}", LogHeader, id);
194  }
195  catch (IndexOutOfRangeException)
196  {
197  m_log.ErrorFormat("{0} OpenJpeg was unable to encode this. Asset Data is empty for {1}", LogHeader, id);
198  }
199  catch (Exception)
200  {
201  m_log.ErrorFormat("{0} OpenJpeg was unable to encode this. Asset Data is empty for {1}", LogHeader, id);
202  }
203  return null;
204 
205  }
206 
207  // Compute the average color of a texture.
208  private Color computeAverageColor(Bitmap bmp)
209  {
210  // we have 256 x 256 pixel, each with 256 possible color-values per
211  // color-channel, so 2^24 is the maximum value we can get, adding everything.
212  // int is be big enough for that.
213  int r = 0, g = 0, b = 0;
214  for (int y = 0; y < bmp.Height; ++y)
215  {
216  for (int x = 0; x < bmp.Width; ++x)
217  {
218  Color c = bmp.GetPixel(x, y);
219  r += (int)c.R & 0xff;
220  g += (int)c.G & 0xff;
221  b += (int)c.B & 0xff;
222  }
223  }
224 
225  int pixels = bmp.Width * bmp.Height;
226  return Color.FromArgb(r / pixels, g / pixels, b / pixels);
227  }
228 
229  // return either the average color of the texture, or the defaultColor if the texturID is invalid
230  // or the texture couldn't be found
231  private Color computeAverageColor(UUID textureID, Color defaultColor) {
232  if (textureID == UUID.Zero) return defaultColor; // not set
233  if (m_mapping.ContainsKey(textureID)) return m_mapping[textureID]; // one of the predefined textures
234 
235  Color color;
236 
237  using (Bitmap bmp = fetchTexture(textureID))
238  {
239  color = bmp == null ? defaultColor : computeAverageColor(bmp);
240  // store it for future reference
241  m_mapping[textureID] = color;
242  }
243 
244  return color;
245  }
246 
247  // S-curve: f(x) = 3x² - 2x³:
248  // f(0) = 0, f(0.5) = 0.5, f(1) = 1,
249  // f'(x) = 0 at x = 0 and x = 1; f'(0.5) = 1.5,
250  // f''(0.5) = 0, f''(x) != 0 for x != 0.5
251  private float S(float v) {
252  return (v * v * (3f - 2f * v));
253  }
254 
255  // interpolate two colors in HSV space and return the resulting color
256  private HSV interpolateHSV(ref HSV c1, ref HSV c2, float ratio) {
257  if (ratio <= 0f) return c1;
258  if (ratio >= 1f) return c2;
259 
260  // make sure we are on the same side on the hue-circle for interpolation
261  // We change the hue of the parameters here, but we don't change the color
262  // represented by that value
263  if (c1.h - c2.h > 180f) c1.h -= 360f;
264  else if (c2.h - c1.h > 180f) c1.h += 360f;
265 
266  return new HSV(c1.h * (1f - ratio) + c2.h * ratio,
267  c1.s * (1f - ratio) + c2.s * ratio,
268  c1.v * (1f - ratio) + c2.v * ratio);
269  }
270 
271  // the heigthfield might have some jumps in values. Rendered land is smooth, though,
272  // as a slope is rendered at that place. So average 4 neighbour values to emulate that.
273  private float getHeight(ITerrainChannel hm, int x, int y) {
274  if (x < (hm.Width - 1) && y < (hm.Height - 1))
275  return (float)(hm[x, y] * .444 + (hm[x + 1, y] + hm[x, y + 1]) * .222 + hm[x + 1, y +1] * .112);
276  else
277  return (float)hm[x, y];
278  }
279  #endregion
280 
281  public void TerrainToBitmap(Bitmap mapbmp)
282  {
283  int tc = Environment.TickCount;
284  m_log.DebugFormat("{0} Generating Maptile Step 1: Terrain", LogHeader);
285 
286  ITerrainChannel hm = m_scene.Heightmap;
287 
288  if (mapbmp.Width != hm.Width || mapbmp.Height != hm.Height)
289  {
290  m_log.ErrorFormat("{0} TerrainToBitmap. Passed bitmap wrong dimensions. passed=<{1},{2}>, size=<{3},{4}>",
291  "[TEXTURED MAP TILE RENDERER]", mapbmp.Width, mapbmp.Height, hm.Width, hm.Height);
292  }
293 
294  // These textures should be in the AssetCache anyway, as every client conneting to this
295  // region needs them. Except on start, when the map is recreated (before anyone connected),
296  // and on change of the estate settings (textures and terrain values), when the map should
297  // be recreated.
299 
300  // the four terrain colors as HSVs for interpolation
301  HSV hsv1 = new HSV(computeAverageColor(settings.TerrainTexture1, defaultColor1));
302  HSV hsv2 = new HSV(computeAverageColor(settings.TerrainTexture2, defaultColor2));
303  HSV hsv3 = new HSV(computeAverageColor(settings.TerrainTexture3, defaultColor3));
304  HSV hsv4 = new HSV(computeAverageColor(settings.TerrainTexture4, defaultColor4));
305 
306  float levelNElow = (float)settings.Elevation1NE;
307  float levelNEhigh = (float)settings.Elevation2NE;
308 
309  float levelNWlow = (float)settings.Elevation1NW;
310  float levelNWhigh = (float)settings.Elevation2NW;
311 
312  float levelSElow = (float)settings.Elevation1SE;
313  float levelSEhigh = (float)settings.Elevation2SE;
314 
315  float levelSWlow = (float)settings.Elevation1SW;
316  float levelSWhigh = (float)settings.Elevation2SW;
317 
318  float waterHeight = (float)settings.WaterHeight;
319 
320  for (int x = 0; x < hm.Width; x++)
321  {
322  float columnRatio = x / (hm.Width - 1); // 0 - 1, for interpolation
323  for (int y = 0; y < hm.Height; y++)
324  {
325  float rowRatio = y / (hm.Height - 1); // 0 - 1, for interpolation
326 
327  // Y flip the cordinates for the bitmap: hf origin is lower left, bm origin is upper left
328  int yr = (hm.Height - 1) - y;
329 
330  float heightvalue = getHeight(m_scene.Heightmap, x, y);
331  if (Single.IsInfinity(heightvalue) || Single.IsNaN(heightvalue))
332  heightvalue = 0;
333 
334  if (heightvalue > waterHeight)
335  {
336  // add a bit noise for breaking up those flat colors:
337  // - a large-scale noise, for the "patches" (using an doubled s-curve for sharper contrast)
338  // - a small-scale noise, for bringing in some small scale variation
339  //float bigNoise = (float)TerrainUtil.InterpolatedNoise(x / 8.0, y / 8.0) * .5f + .5f; // map to 0.0 - 1.0
340  //float smallNoise = (float)TerrainUtil.InterpolatedNoise(x + 33, y + 43) * .5f + .5f;
341  //float hmod = heightvalue + smallNoise * 3f + S(S(bigNoise)) * 10f;
342  float hmod =
343  heightvalue +
344  (float)TerrainUtil.InterpolatedNoise(x + 33, y + 43) * 1.5f + 1.5f + // 0 - 3
345  S(S((float)TerrainUtil.InterpolatedNoise(x / 8.0, y / 8.0) * .5f + .5f)) * 10f; // 0 - 10
346 
347  // find the low/high values for this point (interpolated bilinearily)
348  // (and remember, x=0,y=0 is SW)
349  float low = levelSWlow * (1f - rowRatio) * (1f - columnRatio) +
350  levelSElow * (1f - rowRatio) * columnRatio +
351  levelNWlow * rowRatio * (1f - columnRatio) +
352  levelNElow * rowRatio * columnRatio;
353  float high = levelSWhigh * (1f - rowRatio) * (1f - columnRatio) +
354  levelSEhigh * (1f - rowRatio) * columnRatio +
355  levelNWhigh * rowRatio * (1f - columnRatio) +
356  levelNEhigh * rowRatio * columnRatio;
357  if (high < low)
358  {
359  // someone tried to fool us. High value should be higher than low every time
360  float tmp = high;
361  high = low;
362  low = tmp;
363  }
364 
365  HSV hsv;
366  if (hmod <= low) hsv = hsv1; // too low
367  else if (hmod >= high) hsv = hsv4; // too high
368  else
369  {
370  // HSV-interpolate along the colors
371  // first, rescale h to 0.0 - 1.0
372  hmod = (hmod - low) / (high - low);
373  // now we have to split: 0.00 => color1, 0.33 => color2, 0.67 => color3, 1.00 => color4
374  if (hmod < 1f / 3f) hsv = interpolateHSV(ref hsv1, ref hsv2, hmod * 3f);
375  else if (hmod < 2f / 3f) hsv = interpolateHSV(ref hsv2, ref hsv3, (hmod * 3f) - 1f);
376  else hsv = interpolateHSV(ref hsv3, ref hsv4, (hmod * 3f) - 2f);
377  }
378 
379  // Shade the terrain for shadows
380  if (x < (hm.Width - 1) && y < (hm.Height - 1))
381  {
382  float hfvaluecompare = getHeight(m_scene.Heightmap, x + 1, y + 1); // light from north-east => look at land height there
383  if (Single.IsInfinity(hfvaluecompare) || Single.IsNaN(hfvaluecompare))
384  hfvaluecompare = 0f;
385 
386  float hfdiff = heightvalue - hfvaluecompare; // => positive if NE is lower, negative if here is lower
387  hfdiff *= 0.06f; // some random factor so "it looks good"
388  if (hfdiff > 0.02f)
389  {
390  float highlightfactor = 0.18f;
391  // NE is lower than here
392  // We have to desaturate and lighten the land at the same time
393  hsv.s = (hsv.s - (hfdiff * highlightfactor) > 0f) ? hsv.s - (hfdiff * highlightfactor) : 0f;
394  hsv.v = (hsv.v + (hfdiff * highlightfactor) < 1f) ? hsv.v + (hfdiff * highlightfactor) : 1f;
395  }
396  else if (hfdiff < -0.02f)
397  {
398  // here is lower than NE:
399  // We have to desaturate and blacken the land at the same time
400  hsv.s = (hsv.s + hfdiff > 0f) ? hsv.s + hfdiff : 0f;
401  hsv.v = (hsv.v + hfdiff > 0f) ? hsv.v + hfdiff : 0f;
402  }
403  }
404  mapbmp.SetPixel(x, yr, hsv.toColor());
405  }
406  else
407  {
408  // We're under the water level with the terrain, so paint water instead of land
409 
410  heightvalue = waterHeight - heightvalue;
411  if (Single.IsInfinity(heightvalue) || Single.IsNaN(heightvalue))
412  heightvalue = 0f;
413  else if (heightvalue > 19f)
414  heightvalue = 19f;
415  else if (heightvalue < 0f)
416  heightvalue = 0f;
417 
418  heightvalue = 100f - (heightvalue * 100f) / 19f; // 0 - 19 => 100 - 0
419 
420  mapbmp.SetPixel(x, yr, WATER_COLOR);
421  }
422  }
423  }
424 
425  m_log.Debug("[TEXTURED MAP TILE RENDERER]: Generating Maptile Step 1: Done in " + (Environment.TickCount - tc) + " ms");
426  }
427  }
428 }
OpenSim.Framework.RegionSettings RegionSettings
Asset class. All Assets are reference by this class or a class derived from this class ...
Definition: AssetBase.cs:49