TexturedMapTileRenderer.cs 20 KB

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