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