aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Region
diff options
context:
space:
mode:
authorMelanie2010-10-03 16:34:55 +0100
committerMelanie2010-10-03 16:34:55 +0100
commit27340f616edfc2c6c199cb9d550b0ca3f67d2c6f (patch)
tree2c77b3e286970a6984eaa4d04eb7ca316462baed /OpenSim/Region
parentInitial port of the Warp3D map tile renderer (diff)
downloadopensim-SC_OLD-27340f616edfc2c6c199cb9d550b0ca3f67d2c6f.zip
opensim-SC_OLD-27340f616edfc2c6c199cb9d550b0ca3f67d2c6f.tar.gz
opensim-SC_OLD-27340f616edfc2c6c199cb9d550b0ca3f67d2c6f.tar.bz2
opensim-SC_OLD-27340f616edfc2c6c199cb9d550b0ca3f67d2c6f.tar.xz
Addign the new / renamed files for previous commit
Diffstat (limited to 'OpenSim/Region')
-rw-r--r--OpenSim/Region/CoreModules/World/LegacyMap/IMapTileTerrainRenderer.cs39
-rw-r--r--OpenSim/Region/CoreModules/World/LegacyMap/MapImageModule.cs549
-rw-r--r--OpenSim/Region/CoreModules/World/LegacyMap/ShadedMapTileRenderer.cs244
-rw-r--r--OpenSim/Region/CoreModules/World/LegacyMap/TexturedMapTileRenderer.cs418
-rw-r--r--OpenSim/Region/CoreModules/World/Warp3DMap/MapImageModule.cs624
-rw-r--r--OpenSim/Region/CoreModules/World/Warp3DMap/Perlin.cs273
-rw-r--r--OpenSim/Region/CoreModules/World/Warp3DMap/TerrainSplat.cs343
-rw-r--r--OpenSim/Region/CoreModules/World/Warp3DMap/Viewport.cs165
8 files changed, 2655 insertions, 0 deletions
diff --git a/OpenSim/Region/CoreModules/World/LegacyMap/IMapTileTerrainRenderer.cs b/OpenSim/Region/CoreModules/World/LegacyMap/IMapTileTerrainRenderer.cs
new file mode 100644
index 0000000..e892b14
--- /dev/null
+++ b/OpenSim/Region/CoreModules/World/LegacyMap/IMapTileTerrainRenderer.cs
@@ -0,0 +1,39 @@
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
28using System.Drawing;
29using Nini.Config;
30using OpenSim.Region.Framework.Scenes;
31
32namespace OpenSim.Region.CoreModules.World.LegacyMap
33{
34 public interface IMapTileTerrainRenderer
35 {
36 void Initialise(Scene scene, IConfigSource config);
37 void TerrainToBitmap(Bitmap mapbmp);
38 }
39}
diff --git a/OpenSim/Region/CoreModules/World/LegacyMap/MapImageModule.cs b/OpenSim/Region/CoreModules/World/LegacyMap/MapImageModule.cs
new file mode 100644
index 0000000..9e6e366
--- /dev/null
+++ b/OpenSim/Region/CoreModules/World/LegacyMap/MapImageModule.cs
@@ -0,0 +1,549 @@
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
28using System;
29using System.Collections.Generic;
30using System.Drawing;
31using System.Reflection;
32using log4net;
33using Nini.Config;
34using OpenMetaverse;
35using OpenMetaverse.Imaging;
36using OpenSim.Framework;
37using OpenSim.Region.Framework.Interfaces;
38using OpenSim.Region.Framework.Scenes;
39
40namespace OpenSim.Region.CoreModules.World.LegacyMap
41{
42 public enum DrawRoutine
43 {
44 Rectangle,
45 Polygon,
46 Ellipse
47 }
48
49 public struct face
50 {
51 public Point[] pts;
52 }
53
54 public struct DrawStruct
55 {
56 public DrawRoutine dr;
57 public Rectangle rect;
58 public SolidBrush brush;
59 public face[] trns;
60 }
61
62 public class MapImageModule : IMapImageGenerator, IRegionModule
63 {
64 private static readonly ILog m_log =
65 LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
66
67 private Scene m_scene;
68 private IConfigSource m_config;
69 private IMapTileTerrainRenderer terrainRenderer;
70
71 #region IMapImageGenerator Members
72
73 public Bitmap CreateMapTile()
74 {
75 bool drawPrimVolume = true;
76 bool textureTerrain = false;
77
78 try
79 {
80 IConfig startupConfig = m_config.Configs["Startup"];
81 drawPrimVolume = startupConfig.GetBoolean("DrawPrimOnMapTile", drawPrimVolume);
82 textureTerrain = startupConfig.GetBoolean("TextureOnMapTile", textureTerrain);
83 }
84 catch
85 {
86 m_log.Warn("[MAPTILE]: Failed to load StartupConfig");
87 }
88
89 if (textureTerrain)
90 {
91 terrainRenderer = new TexturedMapTileRenderer();
92 }
93 else
94 {
95 terrainRenderer = new ShadedMapTileRenderer();
96 }
97 terrainRenderer.Initialise(m_scene, m_config);
98
99 Bitmap mapbmp = new Bitmap((int)Constants.RegionSize, (int)Constants.RegionSize, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
100 //long t = System.Environment.TickCount;
101 //for (int i = 0; i < 10; ++i) {
102 terrainRenderer.TerrainToBitmap(mapbmp);
103 //}
104 //t = System.Environment.TickCount - t;
105 //m_log.InfoFormat("[MAPTILE] generation of 10 maptiles needed {0} ms", t);
106
107
108 if (drawPrimVolume)
109 {
110 DrawObjectVolume(m_scene, mapbmp);
111 }
112
113 return mapbmp;
114 }
115
116 public byte[] WriteJpeg2000Image()
117 {
118 try
119 {
120 using (Bitmap mapbmp = CreateMapTile())
121 return OpenJPEG.EncodeFromImage(mapbmp, true);
122 }
123 catch (Exception e) // LEGIT: Catching problems caused by OpenJPEG p/invoke
124 {
125 m_log.Error("Failed generating terrain map: " + e);
126 }
127
128 return null;
129 }
130
131 #endregion
132
133 #region IRegionModule Members
134
135 public void Initialise(Scene scene, IConfigSource source)
136 {
137 m_scene = scene;
138 m_config = source;
139
140 IConfig startupConfig = m_config.Configs["Startup"];
141 if (startupConfig.GetString("MapImageModule", "MapImageModule") !=
142 "MapImageModule")
143 return;
144
145 m_scene.RegisterModuleInterface<IMapImageGenerator>(this);
146 }
147
148 public void PostInitialise()
149 {
150 }
151
152 public void Close()
153 {
154 }
155
156 public string Name
157 {
158 get { return "MapImageModule"; }
159 }
160
161 public bool IsSharedModule
162 {
163 get { return false; }
164 }
165
166 #endregion
167
168// TODO: unused:
169// private void ShadeBuildings(Bitmap map)
170// {
171// lock (map)
172// {
173// lock (m_scene.Entities)
174// {
175// foreach (EntityBase entity in m_scene.Entities.Values)
176// {
177// if (entity is SceneObjectGroup)
178// {
179// SceneObjectGroup sog = (SceneObjectGroup) entity;
180//
181// foreach (SceneObjectPart primitive in sog.Children.Values)
182// {
183// int x = (int) (primitive.AbsolutePosition.X - (primitive.Scale.X / 2));
184// int y = (int) (primitive.AbsolutePosition.Y - (primitive.Scale.Y / 2));
185// int w = (int) primitive.Scale.X;
186// int h = (int) primitive.Scale.Y;
187//
188// int dx;
189// for (dx = x; dx < x + w; dx++)
190// {
191// int dy;
192// for (dy = y; dy < y + h; dy++)
193// {
194// if (x < 0 || y < 0)
195// continue;
196// if (x >= map.Width || y >= map.Height)
197// continue;
198//
199// map.SetPixel(dx, dy, Color.DarkGray);
200// }
201// }
202// }
203// }
204// }
205// }
206// }
207// }
208
209 private Bitmap DrawObjectVolume(Scene whichScene, Bitmap mapbmp)
210 {
211 int tc = 0;
212 double[,] hm = whichScene.Heightmap.GetDoubles();
213 tc = Environment.TickCount;
214 m_log.Info("[MAPTILE]: Generating Maptile Step 2: Object Volume Profile");
215 EntityBase[] objs = whichScene.GetEntities();
216 Dictionary<uint, DrawStruct> z_sort = new Dictionary<uint, DrawStruct>();
217 //SortedList<float, RectangleDrawStruct> z_sort = new SortedList<float, RectangleDrawStruct>();
218 List<float> z_sortheights = new List<float>();
219 List<uint> z_localIDs = new List<uint>();
220
221 lock (objs)
222 {
223 foreach (EntityBase obj in objs)
224 {
225 // Only draw the contents of SceneObjectGroup
226 if (obj is SceneObjectGroup)
227 {
228 SceneObjectGroup mapdot = (SceneObjectGroup)obj;
229 Color mapdotspot = Color.Gray; // Default color when prim color is white
230
231 // Loop over prim in group
232 foreach (SceneObjectPart part in mapdot.Parts)
233 {
234 if (part == null)
235 continue;
236
237 // Draw if the object is at least 1 meter wide in any direction
238 if (part.Scale.X > 1f || part.Scale.Y > 1f || part.Scale.Z > 1f)
239 {
240 // Try to get the RGBA of the default texture entry..
241 //
242 try
243 {
244 // get the null checks out of the way
245 // skip the ones that break
246 if (part == null)
247 continue;
248
249 if (part.Shape == null)
250 continue;
251
252 if (part.Shape.PCode == (byte)PCode.Tree || part.Shape.PCode == (byte)PCode.NewTree || part.Shape.PCode == (byte)PCode.Grass)
253 continue; // eliminates trees from this since we don't really have a good tree representation
254 // if you want tree blocks on the map comment the above line and uncomment the below line
255 //mapdotspot = Color.PaleGreen;
256
257 Primitive.TextureEntry textureEntry = part.Shape.Textures;
258
259 if (textureEntry == null || textureEntry.DefaultTexture == null)
260 continue;
261
262 Color4 texcolor = textureEntry.DefaultTexture.RGBA;
263
264 // Not sure why some of these are null, oh well.
265
266 int colorr = 255 - (int)(texcolor.R * 255f);
267 int colorg = 255 - (int)(texcolor.G * 255f);
268 int colorb = 255 - (int)(texcolor.B * 255f);
269
270 if (!(colorr == 255 && colorg == 255 && colorb == 255))
271 {
272 //Try to set the map spot color
273 try
274 {
275 // If the color gets goofy somehow, skip it *shakes fist at Color4
276 mapdotspot = Color.FromArgb(colorr, colorg, colorb);
277 }
278 catch (ArgumentException)
279 {
280 }
281 }
282 }
283 catch (IndexOutOfRangeException)
284 {
285 // Windows Array
286 }
287 catch (ArgumentOutOfRangeException)
288 {
289 // Mono Array
290 }
291
292 Vector3 pos = part.GetWorldPosition();
293
294 // skip prim outside of retion
295 if (pos.X < 0f || pos.X > 256f || pos.Y < 0f || pos.Y > 256f)
296 continue;
297
298 // skip prim in non-finite position
299 if (Single.IsNaN(pos.X) || Single.IsNaN(pos.Y) ||
300 Single.IsInfinity(pos.X) || Single.IsInfinity(pos.Y))
301 continue;
302
303 // Figure out if object is under 256m above the height of the terrain
304 bool isBelow256AboveTerrain = false;
305
306 try
307 {
308 isBelow256AboveTerrain = (pos.Z < ((float)hm[(int)pos.X, (int)pos.Y] + 256f));
309 }
310 catch (Exception)
311 {
312 }
313
314 if (isBelow256AboveTerrain)
315 {
316 // Translate scale by rotation so scale is represented properly when object is rotated
317 Vector3 lscale = new Vector3(part.Shape.Scale.X, part.Shape.Scale.Y, part.Shape.Scale.Z);
318 Vector3 scale = new Vector3();
319 Vector3 tScale = new Vector3();
320 Vector3 axPos = new Vector3(pos.X,pos.Y,pos.Z);
321
322 Quaternion llrot = part.GetWorldRotation();
323 Quaternion rot = new Quaternion(llrot.W, llrot.X, llrot.Y, llrot.Z);
324 scale = lscale * rot;
325
326 // negative scales don't work in this situation
327 scale.X = Math.Abs(scale.X);
328 scale.Y = Math.Abs(scale.Y);
329 scale.Z = Math.Abs(scale.Z);
330
331 // This scaling isn't very accurate and doesn't take into account the face rotation :P
332 int mapdrawstartX = (int)(pos.X - scale.X);
333 int mapdrawstartY = (int)(pos.Y - scale.Y);
334 int mapdrawendX = (int)(pos.X + scale.X);
335 int mapdrawendY = (int)(pos.Y + scale.Y);
336
337 // If object is beyond the edge of the map, don't draw it to avoid errors
338 if (mapdrawstartX < 0 || mapdrawstartX > ((int)Constants.RegionSize - 1) || mapdrawendX < 0 || mapdrawendX > ((int)Constants.RegionSize - 1)
339 || mapdrawstartY < 0 || mapdrawstartY > ((int)Constants.RegionSize - 1) || mapdrawendY < 0
340 || mapdrawendY > ((int)Constants.RegionSize - 1))
341 continue;
342
343#region obb face reconstruction part duex
344 Vector3[] vertexes = new Vector3[8];
345
346 // float[] distance = new float[6];
347 Vector3[] FaceA = new Vector3[6]; // vertex A for Facei
348 Vector3[] FaceB = new Vector3[6]; // vertex B for Facei
349 Vector3[] FaceC = new Vector3[6]; // vertex C for Facei
350 Vector3[] FaceD = new Vector3[6]; // vertex D for Facei
351
352 tScale = new Vector3(lscale.X, -lscale.Y, lscale.Z);
353 scale = ((tScale * rot));
354 vertexes[0] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
355 // vertexes[0].x = pos.X + vertexes[0].x;
356 //vertexes[0].y = pos.Y + vertexes[0].y;
357 //vertexes[0].z = pos.Z + vertexes[0].z;
358
359 FaceA[0] = vertexes[0];
360 FaceB[3] = vertexes[0];
361 FaceA[4] = vertexes[0];
362
363 tScale = lscale;
364 scale = ((tScale * rot));
365 vertexes[1] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
366
367 // vertexes[1].x = pos.X + vertexes[1].x;
368 // vertexes[1].y = pos.Y + vertexes[1].y;
369 //vertexes[1].z = pos.Z + vertexes[1].z;
370
371 FaceB[0] = vertexes[1];
372 FaceA[1] = vertexes[1];
373 FaceC[4] = vertexes[1];
374
375 tScale = new Vector3(lscale.X, -lscale.Y, -lscale.Z);
376 scale = ((tScale * rot));
377
378 vertexes[2] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
379
380 //vertexes[2].x = pos.X + vertexes[2].x;
381 //vertexes[2].y = pos.Y + vertexes[2].y;
382 //vertexes[2].z = pos.Z + vertexes[2].z;
383
384 FaceC[0] = vertexes[2];
385 FaceD[3] = vertexes[2];
386 FaceC[5] = vertexes[2];
387
388 tScale = new Vector3(lscale.X, lscale.Y, -lscale.Z);
389 scale = ((tScale * rot));
390 vertexes[3] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
391
392 //vertexes[3].x = pos.X + vertexes[3].x;
393 // vertexes[3].y = pos.Y + vertexes[3].y;
394 // vertexes[3].z = pos.Z + vertexes[3].z;
395
396 FaceD[0] = vertexes[3];
397 FaceC[1] = vertexes[3];
398 FaceA[5] = vertexes[3];
399
400 tScale = new Vector3(-lscale.X, lscale.Y, lscale.Z);
401 scale = ((tScale * rot));
402 vertexes[4] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
403
404 // vertexes[4].x = pos.X + vertexes[4].x;
405 // vertexes[4].y = pos.Y + vertexes[4].y;
406 // vertexes[4].z = pos.Z + vertexes[4].z;
407
408 FaceB[1] = vertexes[4];
409 FaceA[2] = vertexes[4];
410 FaceD[4] = vertexes[4];
411
412 tScale = new Vector3(-lscale.X, lscale.Y, -lscale.Z);
413 scale = ((tScale * rot));
414 vertexes[5] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
415
416 // vertexes[5].x = pos.X + vertexes[5].x;
417 // vertexes[5].y = pos.Y + vertexes[5].y;
418 // vertexes[5].z = pos.Z + vertexes[5].z;
419
420 FaceD[1] = vertexes[5];
421 FaceC[2] = vertexes[5];
422 FaceB[5] = vertexes[5];
423
424 tScale = new Vector3(-lscale.X, -lscale.Y, lscale.Z);
425 scale = ((tScale * rot));
426 vertexes[6] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
427
428 // vertexes[6].x = pos.X + vertexes[6].x;
429 // vertexes[6].y = pos.Y + vertexes[6].y;
430 // vertexes[6].z = pos.Z + vertexes[6].z;
431
432 FaceB[2] = vertexes[6];
433 FaceA[3] = vertexes[6];
434 FaceB[4] = vertexes[6];
435
436 tScale = new Vector3(-lscale.X, -lscale.Y, -lscale.Z);
437 scale = ((tScale * rot));
438 vertexes[7] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
439
440 // vertexes[7].x = pos.X + vertexes[7].x;
441 // vertexes[7].y = pos.Y + vertexes[7].y;
442 // vertexes[7].z = pos.Z + vertexes[7].z;
443
444 FaceD[2] = vertexes[7];
445 FaceC[3] = vertexes[7];
446 FaceD[5] = vertexes[7];
447#endregion
448
449 //int wy = 0;
450
451 //bool breakYN = false; // If we run into an error drawing, break out of the
452 // loop so we don't lag to death on error handling
453 DrawStruct ds = new DrawStruct();
454 ds.brush = new SolidBrush(mapdotspot);
455 //ds.rect = new Rectangle(mapdrawstartX, (255 - mapdrawstartY), mapdrawendX - mapdrawstartX, mapdrawendY - mapdrawstartY);
456
457 ds.trns = new face[FaceA.Length];
458
459 for (int i = 0; i < FaceA.Length; i++)
460 {
461 Point[] working = new Point[5];
462 working[0] = project(FaceA[i], axPos);
463 working[1] = project(FaceB[i], axPos);
464 working[2] = project(FaceD[i], axPos);
465 working[3] = project(FaceC[i], axPos);
466 working[4] = project(FaceA[i], axPos);
467
468 face workingface = new face();
469 workingface.pts = working;
470
471 ds.trns[i] = workingface;
472 }
473
474 z_sort.Add(part.LocalId, ds);
475 z_localIDs.Add(part.LocalId);
476 z_sortheights.Add(pos.Z);
477
478 //for (int wx = mapdrawstartX; wx < mapdrawendX; wx++)
479 //{
480 //for (wy = mapdrawstartY; wy < mapdrawendY; wy++)
481 //{
482 //m_log.InfoFormat("[MAPDEBUG]: {0},{1}({2})", wx, (255 - wy),wy);
483 //try
484 //{
485 // Remember, flip the y!
486 // mapbmp.SetPixel(wx, (255 - wy), mapdotspot);
487 //}
488 //catch (ArgumentException)
489 //{
490 // breakYN = true;
491 //}
492
493 //if (breakYN)
494 // break;
495 //}
496
497 //if (breakYN)
498 // break;
499 //}
500 } // Object is within 256m Z of terrain
501 } // object is at least a meter wide
502 } // loop over group children
503 } // entitybase is sceneobject group
504 } // foreach loop over entities
505
506 float[] sortedZHeights = z_sortheights.ToArray();
507 uint[] sortedlocalIds = z_localIDs.ToArray();
508
509 // Sort prim by Z position
510 Array.Sort(sortedZHeights, sortedlocalIds);
511
512 Graphics g = Graphics.FromImage(mapbmp);
513
514 for (int s = 0; s < sortedZHeights.Length; s++)
515 {
516 if (z_sort.ContainsKey(sortedlocalIds[s]))
517 {
518 DrawStruct rectDrawStruct = z_sort[sortedlocalIds[s]];
519 for (int r = 0; r < rectDrawStruct.trns.Length; r++)
520 {
521 g.FillPolygon(rectDrawStruct.brush,rectDrawStruct.trns[r].pts);
522 }
523 //g.FillRectangle(rectDrawStruct.brush , rectDrawStruct.rect);
524 }
525 }
526
527 g.Dispose();
528 } // lock entities objs
529
530 m_log.Info("[MAPTILE]: Generating Maptile Step 2: Done in " + (Environment.TickCount - tc) + " ms");
531 return mapbmp;
532 }
533
534 private Point project(Vector3 point3d, Vector3 originpos)
535 {
536 Point returnpt = new Point();
537 //originpos = point3d;
538 //int d = (int)(256f / 1.5f);
539
540 //Vector3 topos = new Vector3(0, 0, 0);
541 // float z = -point3d.z - topos.z;
542
543 returnpt.X = (int)point3d.X;//(int)((topos.x - point3d.x) / z * d);
544 returnpt.Y = (int)(((int)Constants.RegionSize - 1) - point3d.Y);//(int)(255 - (((topos.y - point3d.y) / z * d)));
545
546 return returnpt;
547 }
548 }
549}
diff --git a/OpenSim/Region/CoreModules/World/LegacyMap/ShadedMapTileRenderer.cs b/OpenSim/Region/CoreModules/World/LegacyMap/ShadedMapTileRenderer.cs
new file mode 100644
index 0000000..eb1a27f
--- /dev/null
+++ b/OpenSim/Region/CoreModules/World/LegacyMap/ShadedMapTileRenderer.cs
@@ -0,0 +1,244 @@
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
28using System;
29using System.Drawing;
30using System.Reflection;
31using log4net;
32using Nini.Config;
33using OpenSim.Framework;
34using OpenSim.Region.Framework.Scenes;
35
36namespace OpenSim.Region.CoreModules.World.LegacyMap
37{
38 public class ShadedMapTileRenderer : IMapTileTerrainRenderer
39 {
40 private static readonly Color WATER_COLOR = Color.FromArgb(29, 71, 95);
41
42 private static readonly ILog m_log =
43 LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
44
45 private Scene m_scene;
46 //private IConfigSource m_config; // not used currently
47
48 public void Initialise(Scene scene, IConfigSource config)
49 {
50 m_scene = scene;
51 // m_config = config; // not used currently
52 }
53
54 public void TerrainToBitmap(Bitmap mapbmp)
55 {
56 int tc = Environment.TickCount;
57 m_log.Info("[MAPTILE]: Generating Maptile Step 1: Terrain");
58
59 double[,] hm = m_scene.Heightmap.GetDoubles();
60 bool ShadowDebugContinue = true;
61
62 bool terraincorruptedwarningsaid = false;
63
64 float low = 255;
65 float high = 0;
66 for (int x = 0; x < (int)Constants.RegionSize; x++)
67 {
68 for (int y = 0; y < (int)Constants.RegionSize; y++)
69 {
70 float hmval = (float)hm[x, y];
71 if (hmval < low)
72 low = hmval;
73 if (hmval > high)
74 high = hmval;
75 }
76 }
77
78 float waterHeight = (float)m_scene.RegionInfo.RegionSettings.WaterHeight;
79
80 for (int x = 0; x < (int)Constants.RegionSize; x++)
81 {
82 for (int y = 0; y < (int)Constants.RegionSize; y++)
83 {
84 // Y flip the cordinates for the bitmap: hf origin is lower left, bm origin is upper left
85 int yr = ((int)Constants.RegionSize - 1) - y;
86
87 float heightvalue = (float)hm[x, y];
88
89 if (heightvalue > waterHeight)
90 {
91 // scale height value
92 // No, that doesn't scale it:
93 // heightvalue = low + mid * (heightvalue - low) / mid; => low + (heightvalue - low) * mid / mid = low + (heightvalue - low) * 1 = low + heightvalue - low = heightvalue
94
95 if (Single.IsInfinity(heightvalue) || Single.IsNaN(heightvalue))
96 heightvalue = 0;
97 else if (heightvalue > 255f)
98 heightvalue = 255f;
99 else if (heightvalue < 0f)
100 heightvalue = 0f;
101
102 Color color = Color.FromArgb((int)heightvalue, 100, (int)heightvalue);
103
104 mapbmp.SetPixel(x, yr, color);
105
106 try
107 {
108 //X
109 // .
110 //
111 // Shade the terrain for shadows
112 if (x < ((int)Constants.RegionSize - 1) && yr < ((int)Constants.RegionSize - 1))
113 {
114 float hfvalue = (float)hm[x, y];
115 float hfvaluecompare = 0f;
116
117 if ((x + 1 < (int)Constants.RegionSize) && (y + 1 < (int)Constants.RegionSize))
118 {
119 hfvaluecompare = (float)hm[x + 1, y + 1]; // light from north-east => look at land height there
120 }
121 if (Single.IsInfinity(hfvalue) || Single.IsNaN(hfvalue))
122 hfvalue = 0f;
123
124 if (Single.IsInfinity(hfvaluecompare) || Single.IsNaN(hfvaluecompare))
125 hfvaluecompare = 0f;
126
127 float hfdiff = hfvalue - hfvaluecompare; // => positive if NE is lower, negative if here is lower
128
129 int hfdiffi = 0;
130 int hfdiffihighlight = 0;
131 float highlightfactor = 0.18f;
132
133 try
134 {
135 // hfdiffi = Math.Abs((int)((hfdiff * 4) + (hfdiff * 0.5))) + 1;
136 hfdiffi = Math.Abs((int)(hfdiff * 4.5f)) + 1;
137 if (hfdiff % 1f != 0)
138 {
139 // hfdiffi = hfdiffi + Math.Abs((int)(((hfdiff % 1) * 0.5f) * 10f) - 1);
140 hfdiffi = hfdiffi + Math.Abs((int)((hfdiff % 1f) * 5f) - 1);
141 }
142
143 hfdiffihighlight = Math.Abs((int)((hfdiff * highlightfactor) * 4.5f)) + 1;
144 if (hfdiff % 1f != 0)
145 {
146 // hfdiffi = hfdiffi + Math.Abs((int)(((hfdiff % 1) * 0.5f) * 10f) - 1);
147 hfdiffihighlight = hfdiffihighlight + Math.Abs((int)(((hfdiff * highlightfactor) % 1f) * 5f) - 1);
148 }
149 }
150 catch (OverflowException)
151 {
152 m_log.Debug("[MAPTILE]: Shadow failed at value: " + hfdiff.ToString());
153 ShadowDebugContinue = false;
154 }
155
156 if (hfdiff > 0.3f)
157 {
158 // NE is lower than here
159 // We have to desaturate and lighten the land at the same time
160 // we use floats, colors use bytes, so shrink are space down to
161 // 0-255
162
163 if (ShadowDebugContinue)
164 {
165 int r = color.R;
166 int g = color.G;
167 int b = color.B;
168 color = Color.FromArgb((r + hfdiffihighlight < 255) ? r + hfdiffihighlight : 255,
169 (g + hfdiffihighlight < 255) ? g + hfdiffihighlight : 255,
170 (b + hfdiffihighlight < 255) ? b + hfdiffihighlight : 255);
171 }
172 }
173 else if (hfdiff < -0.3f)
174 {
175 // here is lower than NE:
176 // We have to desaturate and blacken the land at the same time
177 // we use floats, colors use bytes, so shrink are space down to
178 // 0-255
179
180 if (ShadowDebugContinue)
181 {
182 if ((x - 1 > 0) && (yr + 1 < (int)Constants.RegionSize))
183 {
184 color = mapbmp.GetPixel(x - 1, yr + 1);
185 int r = color.R;
186 int g = color.G;
187 int b = color.B;
188 color = Color.FromArgb((r - hfdiffi > 0) ? r - hfdiffi : 0,
189 (g - hfdiffi > 0) ? g - hfdiffi : 0,
190 (b - hfdiffi > 0) ? b - hfdiffi : 0);
191
192 mapbmp.SetPixel(x-1, yr+1, color);
193 }
194 }
195 }
196 }
197 }
198 catch (ArgumentException)
199 {
200 if (!terraincorruptedwarningsaid)
201 {
202 m_log.WarnFormat("[MAPIMAGE]: Your terrain is corrupted in region {0}, it might take a few minutes to generate the map image depending on the corruption level", m_scene.RegionInfo.RegionName);
203 terraincorruptedwarningsaid = true;
204 }
205 color = Color.Black;
206 mapbmp.SetPixel(x, yr, color);
207 }
208 }
209 else
210 {
211 // We're under the water level with the terrain, so paint water instead of land
212
213 // Y flip the cordinates
214 heightvalue = waterHeight - heightvalue;
215 if (Single.IsInfinity(heightvalue) || Single.IsNaN(heightvalue))
216 heightvalue = 0f;
217 else if (heightvalue > 19f)
218 heightvalue = 19f;
219 else if (heightvalue < 0f)
220 heightvalue = 0f;
221
222 heightvalue = 100f - (heightvalue * 100f) / 19f;
223
224 try
225 {
226 mapbmp.SetPixel(x, yr, WATER_COLOR);
227 }
228 catch (ArgumentException)
229 {
230 if (!terraincorruptedwarningsaid)
231 {
232 m_log.WarnFormat("[MAPIMAGE]: Your terrain is corrupted in region {0}, it might take a few minutes to generate the map image depending on the corruption level", m_scene.RegionInfo.RegionName);
233 terraincorruptedwarningsaid = true;
234 }
235 Color black = Color.Black;
236 mapbmp.SetPixel(x, ((int)Constants.RegionSize - y) - 1, black);
237 }
238 }
239 }
240 }
241 m_log.Info("[MAPTILE]: Generating Maptile Step 1: Done in " + (Environment.TickCount - tc) + " ms");
242 }
243 }
244}
diff --git a/OpenSim/Region/CoreModules/World/LegacyMap/TexturedMapTileRenderer.cs b/OpenSim/Region/CoreModules/World/LegacyMap/TexturedMapTileRenderer.cs
new file mode 100644
index 0000000..071314a
--- /dev/null
+++ b/OpenSim/Region/CoreModules/World/LegacyMap/TexturedMapTileRenderer.cs
@@ -0,0 +1,418 @@
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
28using System;
29using System.Collections.Generic;
30using System.Drawing;
31using System.Reflection;
32using log4net;
33using Nini.Config;
34using OpenMetaverse;
35using OpenMetaverse.Imaging;
36using OpenSim.Framework;
37using OpenSim.Region.Framework.Scenes;
38
39namespace 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
45 public float h;
46 public float s;
47 public float v;
48
49 public HSV(float h, float s, float v)
50 {
51 this.h = h;
52 this.s = s;
53 this.v = v;
54 }
55
56 // (for info about algorithm, see http://en.wikipedia.org/wiki/HSL_and_HSV)
57 public HSV(Color c)
58 {
59 float r = c.R / 255f;
60 float g = c.G / 255f;
61 float b = c.B / 255f;
62 float max = Math.Max(Math.Max(r, g), b);
63 float min = Math.Min(Math.Min(r, g), b);
64 float diff = max - min;
65
66 if (max == min) h = 0f;
67 else if (max == r) h = (g - b) / diff * 60f;
68 else if (max == g) h = (b - r) / diff * 60f + 120f;
69 else h = (r - g) / diff * 60f + 240f;
70 if (h < 0f) h += 360f;
71
72 if (max == 0f) s = 0f;
73 else s = diff / max;
74
75 v = max;
76 }
77
78 // (for info about algorithm, see http://en.wikipedia.org/wiki/HSL_and_HSV)
79 public Color toColor()
80 {
81 if (s < 0f) m_log.Debug("S < 0: " + s);
82 else if (s > 1f) m_log.Debug("S > 1: " + s);
83 if (v < 0f) m_log.Debug("V < 0: " + v);
84 else if (v > 1f) m_log.Debug("V > 1: " + v);
85
86 float f = h / 60f;
87 int sector = (int)f % 6;
88 f = f - (int)f;
89 int pi = (int)(v * (1f - s) * 255f);
90 int qi = (int)(v * (1f - s * f) * 255f);
91 int ti = (int)(v * (1f - (1f - f) * s) * 255f);
92 int vi = (int)(v * 255f);
93
94 if (pi < 0) pi = 0;
95 if (pi > 255) pi = 255;
96 if (qi < 0) qi = 0;
97 if (qi > 255) qi = 255;
98 if (ti < 0) ti = 0;
99 if (ti > 255) ti = 255;
100 if (vi < 0) vi = 0;
101 if (vi > 255) vi = 255;
102
103 switch (sector)
104 {
105 case 0:
106 return Color.FromArgb(vi, ti, pi);
107 case 1:
108 return Color.FromArgb(qi, vi, pi);
109 case 2:
110 return Color.FromArgb(pi, vi, ti);
111 case 3:
112 return Color.FromArgb(pi, qi, vi);
113 case 4:
114 return Color.FromArgb(ti, pi, vi);
115 default:
116 return Color.FromArgb(vi, pi, qi);
117 }
118 }
119 }
120
121 public class TexturedMapTileRenderer : IMapTileTerrainRenderer
122 {
123 #region Constants
124
125 private static readonly ILog m_log =
126 LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
127
128 // some hardcoded terrain UUIDs that work with SL 1.20 (the four default textures and "Blank").
129 // The color-values were choosen because they "look right" (at least to me) ;-)
130 private static readonly UUID defaultTerrainTexture1 = new UUID("0bc58228-74a0-7e83-89bc-5c23464bcec5");
131 private static readonly Color defaultColor1 = Color.FromArgb(165, 137, 118);
132 private static readonly UUID defaultTerrainTexture2 = new UUID("63338ede-0037-c4fd-855b-015d77112fc8");
133 private static readonly Color defaultColor2 = Color.FromArgb(69, 89, 49);
134 private static readonly UUID defaultTerrainTexture3 = new UUID("303cd381-8560-7579-23f1-f0a880799740");
135 private static readonly Color defaultColor3 = Color.FromArgb(162, 154, 141);
136 private static readonly UUID defaultTerrainTexture4 = new UUID("53a2f406-4895-1d13-d541-d2e3b86bc19c");
137 private static readonly Color defaultColor4 = Color.FromArgb(200, 200, 200);
138
139 private static readonly Color WATER_COLOR = Color.FromArgb(29, 71, 95);
140
141 #endregion
142
143
144 private Scene m_scene;
145 // private IConfigSource m_config; // not used currently
146
147 // mapping from texture UUIDs to averaged color. This will contain 5-9 values, in general; new values are only
148 // added when the terrain textures are changed in the estate dialog and a new map is generated (and will stay in
149 // that map until the region-server restarts. This could be considered a memory-leak, but it's a *very* small one.
150 // TODO does it make sense to use a "real" cache and regenerate missing entries on fetch?
151 private Dictionary<UUID, Color> m_mapping;
152
153
154 public void Initialise(Scene scene, IConfigSource source)
155 {
156 m_scene = scene;
157 // m_config = source; // not used currently
158 m_mapping = new Dictionary<UUID,Color>();
159 m_mapping.Add(defaultTerrainTexture1, defaultColor1);
160 m_mapping.Add(defaultTerrainTexture2, defaultColor2);
161 m_mapping.Add(defaultTerrainTexture3, defaultColor3);
162 m_mapping.Add(defaultTerrainTexture4, defaultColor4);
163 m_mapping.Add(Util.BLANK_TEXTURE_UUID, Color.White);
164 }
165
166 #region Helpers
167 // This fetches the texture from the asset server synchroneously. That should be ok, as we
168 // call map-creation only in those places:
169 // - on start: We can wait here until the asset server returns the texture
170 // TODO (- on "map" command: We are in the command-line thread, we will wait for completion anyway)
171 // TODO (- on "automatic" update after some change: We are called from the mapUpdateTimer here and
172 // will wait anyway)
173 private Bitmap fetchTexture(UUID id)
174 {
175 AssetBase asset = m_scene.AssetService.Get(id.ToString());
176 m_log.DebugFormat("Fetched texture {0}, found: {1}", id, asset != null);
177 if (asset == null) return null;
178
179 ManagedImage managedImage;
180 Image image;
181
182 try
183 {
184 if (OpenJPEG.DecodeToImage(asset.Data, out managedImage, out image))
185 return new Bitmap(image);
186 else
187 return null;
188 }
189 catch (DllNotFoundException)
190 {
191 m_log.ErrorFormat("[TexturedMapTileRenderer]: OpenJpeg is not installed correctly on this system. Asset Data is emtpy for {0}", id);
192
193 }
194 catch (IndexOutOfRangeException)
195 {
196 m_log.ErrorFormat("[TexturedMapTileRenderer]: OpenJpeg was unable to encode this. Asset Data is emtpy for {0}", id);
197
198 }
199 catch (Exception)
200 {
201 m_log.ErrorFormat("[TexturedMapTileRenderer]: OpenJpeg was unable to encode this. Asset Data is emtpy for {0}", id);
202
203 }
204 return null;
205
206 }
207
208 // Compute the average color of a texture.
209 private Color computeAverageColor(Bitmap bmp)
210 {
211 // we have 256 x 256 pixel, each with 256 possible color-values per
212 // color-channel, so 2^24 is the maximum value we can get, adding everything.
213 // int is be big enough for that.
214 int r = 0, g = 0, b = 0;
215 for (int y = 0; y < bmp.Height; ++y)
216 {
217 for (int x = 0; x < bmp.Width; ++x)
218 {
219 Color c = bmp.GetPixel(x, y);
220 r += (int)c.R & 0xff;
221 g += (int)c.G & 0xff;
222 b += (int)c.B & 0xff;
223 }
224 }
225
226 int pixels = bmp.Width * bmp.Height;
227 return Color.FromArgb(r / pixels, g / pixels, b / pixels);
228 }
229
230 // return either the average color of the texture, or the defaultColor if the texturID is invalid
231 // or the texture couldn't be found
232 private Color computeAverageColor(UUID textureID, Color defaultColor) {
233 if (textureID == UUID.Zero) return defaultColor; // not set
234 if (m_mapping.ContainsKey(textureID)) return m_mapping[textureID]; // one of the predefined textures
235
236 Bitmap bmp = fetchTexture(textureID);
237 Color color = bmp == null ? defaultColor : computeAverageColor(bmp);
238 // store it for future reference
239 m_mapping[textureID] = color;
240
241 return color;
242 }
243
244 // S-curve: f(x) = 3x² - 2x³:
245 // f(0) = 0, f(0.5) = 0.5, f(1) = 1,
246 // f'(x) = 0 at x = 0 and x = 1; f'(0.5) = 1.5,
247 // f''(0.5) = 0, f''(x) != 0 for x != 0.5
248 private float S(float v) {
249 return (v * v * (3f - 2f * v));
250 }
251
252 // interpolate two colors in HSV space and return the resulting color
253 private HSV interpolateHSV(ref HSV c1, ref HSV c2, float ratio) {
254 if (ratio <= 0f) return c1;
255 if (ratio >= 1f) return c2;
256
257 // make sure we are on the same side on the hue-circle for interpolation
258 // We change the hue of the parameters here, but we don't change the color
259 // represented by that value
260 if (c1.h - c2.h > 180f) c1.h -= 360f;
261 else if (c2.h - c1.h > 180f) c1.h += 360f;
262
263 return new HSV(c1.h * (1f - ratio) + c2.h * ratio,
264 c1.s * (1f - ratio) + c2.s * ratio,
265 c1.v * (1f - ratio) + c2.v * ratio);
266 }
267
268 // the heigthfield might have some jumps in values. Rendered land is smooth, though,
269 // as a slope is rendered at that place. So average 4 neighbour values to emulate that.
270 private float getHeight(double[,] hm, int x, int y) {
271 if (x < ((int)Constants.RegionSize - 1) && y < ((int)Constants.RegionSize - 1))
272 return (float)(hm[x, y] * .444 + (hm[x + 1, y] + hm[x, y + 1]) * .222 + hm[x + 1, y +1] * .112);
273 else
274 return (float)hm[x, y];
275 }
276 #endregion
277
278 public void TerrainToBitmap(Bitmap mapbmp)
279 {
280 int tc = Environment.TickCount;
281 m_log.Info("[MAPTILE]: Generating Maptile Step 1: Terrain");
282
283 // These textures should be in the AssetCache anyway, as every client conneting to this
284 // region needs them. Except on start, when the map is recreated (before anyone connected),
285 // and on change of the estate settings (textures and terrain values), when the map should
286 // be recreated.
287 RegionSettings settings = m_scene.RegionInfo.RegionSettings;
288
289 // the four terrain colors as HSVs for interpolation
290 HSV hsv1 = new HSV(computeAverageColor(settings.TerrainTexture1, defaultColor1));
291 HSV hsv2 = new HSV(computeAverageColor(settings.TerrainTexture2, defaultColor2));
292 HSV hsv3 = new HSV(computeAverageColor(settings.TerrainTexture3, defaultColor3));
293 HSV hsv4 = new HSV(computeAverageColor(settings.TerrainTexture4, defaultColor4));
294
295 float levelNElow = (float)settings.Elevation1NE;
296 float levelNEhigh = (float)settings.Elevation2NE;
297
298 float levelNWlow = (float)settings.Elevation1NW;
299 float levelNWhigh = (float)settings.Elevation2NW;
300
301 float levelSElow = (float)settings.Elevation1SE;
302 float levelSEhigh = (float)settings.Elevation2SE;
303
304 float levelSWlow = (float)settings.Elevation1SW;
305 float levelSWhigh = (float)settings.Elevation2SW;
306
307 float waterHeight = (float)settings.WaterHeight;
308
309 double[,] hm = m_scene.Heightmap.GetDoubles();
310
311 for (int x = 0; x < (int)Constants.RegionSize; x++)
312 {
313 float columnRatio = x / ((float)Constants.RegionSize - 1); // 0 - 1, for interpolation
314 for (int y = 0; y < (int)Constants.RegionSize; y++)
315 {
316 float rowRatio = y / ((float)Constants.RegionSize - 1); // 0 - 1, for interpolation
317
318 // Y flip the cordinates for the bitmap: hf origin is lower left, bm origin is upper left
319 int yr = ((int)Constants.RegionSize - 1) - y;
320
321 float heightvalue = getHeight(hm, x, y);
322 if (Single.IsInfinity(heightvalue) || Single.IsNaN(heightvalue))
323 heightvalue = 0;
324
325 if (heightvalue > waterHeight)
326 {
327 // add a bit noise for breaking up those flat colors:
328 // - a large-scale noise, for the "patches" (using an doubled s-curve for sharper contrast)
329 // - a small-scale noise, for bringing in some small scale variation
330 //float bigNoise = (float)TerrainUtil.InterpolatedNoise(x / 8.0, y / 8.0) * .5f + .5f; // map to 0.0 - 1.0
331 //float smallNoise = (float)TerrainUtil.InterpolatedNoise(x + 33, y + 43) * .5f + .5f;
332 //float hmod = heightvalue + smallNoise * 3f + S(S(bigNoise)) * 10f;
333 float hmod =
334 heightvalue +
335 (float)TerrainUtil.InterpolatedNoise(x + 33, y + 43) * 1.5f + 1.5f + // 0 - 3
336 S(S((float)TerrainUtil.InterpolatedNoise(x / 8.0, y / 8.0) * .5f + .5f)) * 10f; // 0 - 10
337
338 // find the low/high values for this point (interpolated bilinearily)
339 // (and remember, x=0,y=0 is SW)
340 float low = levelSWlow * (1f - rowRatio) * (1f - columnRatio) +
341 levelSElow * (1f - rowRatio) * columnRatio +
342 levelNWlow * rowRatio * (1f - columnRatio) +
343 levelNElow * rowRatio * columnRatio;
344 float high = levelSWhigh * (1f - rowRatio) * (1f - columnRatio) +
345 levelSEhigh * (1f - rowRatio) * columnRatio +
346 levelNWhigh * rowRatio * (1f - columnRatio) +
347 levelNEhigh * rowRatio * columnRatio;
348 if (high < low)
349 {
350 // someone tried to fool us. High value should be higher than low every time
351 float tmp = high;
352 high = low;
353 low = tmp;
354 }
355
356 HSV hsv;
357 if (hmod <= low) hsv = hsv1; // too low
358 else if (hmod >= high) hsv = hsv4; // too high
359 else
360 {
361 // HSV-interpolate along the colors
362 // first, rescale h to 0.0 - 1.0
363 hmod = (hmod - low) / (high - low);
364 // now we have to split: 0.00 => color1, 0.33 => color2, 0.67 => color3, 1.00 => color4
365 if (hmod < 1f/3f) hsv = interpolateHSV(ref hsv1, ref hsv2, hmod * 3f);
366 else if (hmod < 2f/3f) hsv = interpolateHSV(ref hsv2, ref hsv3, (hmod * 3f) - 1f);
367 else hsv = interpolateHSV(ref hsv3, ref hsv4, (hmod * 3f) - 2f);
368 }
369
370 // Shade the terrain for shadows
371 if (x < ((int)Constants.RegionSize - 1) && y < ((int)Constants.RegionSize - 1))
372 {
373 float hfvaluecompare = getHeight(hm, x + 1, y + 1); // light from north-east => look at land height there
374 if (Single.IsInfinity(hfvaluecompare) || Single.IsNaN(hfvaluecompare))
375 hfvaluecompare = 0f;
376
377 float hfdiff = heightvalue - hfvaluecompare; // => positive if NE is lower, negative if here is lower
378 hfdiff *= 0.06f; // some random factor so "it looks good"
379 if (hfdiff > 0.02f)
380 {
381 float highlightfactor = 0.18f;
382 // NE is lower than here
383 // We have to desaturate and lighten the land at the same time
384 hsv.s = (hsv.s - (hfdiff * highlightfactor) > 0f) ? hsv.s - (hfdiff * highlightfactor) : 0f;
385 hsv.v = (hsv.v + (hfdiff * highlightfactor) < 1f) ? hsv.v + (hfdiff * highlightfactor) : 1f;
386 }
387 else if (hfdiff < -0.02f)
388 {
389 // here is lower than NE:
390 // We have to desaturate and blacken the land at the same time
391 hsv.s = (hsv.s + hfdiff > 0f) ? hsv.s + hfdiff : 0f;
392 hsv.v = (hsv.v + hfdiff > 0f) ? hsv.v + hfdiff : 0f;
393 }
394 }
395 mapbmp.SetPixel(x, yr, hsv.toColor());
396 }
397 else
398 {
399 // We're under the water level with the terrain, so paint water instead of land
400
401 heightvalue = waterHeight - heightvalue;
402 if (Single.IsInfinity(heightvalue) || Single.IsNaN(heightvalue))
403 heightvalue = 0f;
404 else if (heightvalue > 19f)
405 heightvalue = 19f;
406 else if (heightvalue < 0f)
407 heightvalue = 0f;
408
409 heightvalue = 100f - (heightvalue * 100f) / 19f; // 0 - 19 => 100 - 0
410
411 mapbmp.SetPixel(x, yr, WATER_COLOR);
412 }
413 }
414 }
415 m_log.Info("[MAPTILE]: Generating Maptile Step 1: Done in " + (Environment.TickCount - tc) + " ms");
416 }
417 }
418}
diff --git a/OpenSim/Region/CoreModules/World/Warp3DMap/MapImageModule.cs b/OpenSim/Region/CoreModules/World/Warp3DMap/MapImageModule.cs
new file mode 100644
index 0000000..47b1639
--- /dev/null
+++ b/OpenSim/Region/CoreModules/World/Warp3DMap/MapImageModule.cs
@@ -0,0 +1,624 @@
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
28using System;
29using System.Collections.Generic;
30using System.Drawing;
31using System.Drawing.Imaging;
32using System.IO;
33using System.Reflection;
34using CSJ2K;
35using Nini.Config;
36using log4net;
37using Rednettle.Warp3D;
38using OpenMetaverse;
39using OpenMetaverse.Imaging;
40using OpenMetaverse.Rendering;
41using OpenMetaverse.StructuredData;
42using OpenSim.Framework;
43using OpenSim.Region.Framework.Interfaces;
44using OpenSim.Region.Framework.Scenes;
45using OpenSim.Region.Physics.Manager;
46using OpenSim.Services.Interfaces;
47
48using WarpRenderer = global::Warp3D.Warp3D;
49
50namespace OpenSim.Region.CoreModules.World.Warp3DMap
51{
52 public class Warp3DImageModule : IMapImageGenerator, IRegionModule
53 {
54 private static readonly UUID TEXTURE_METADATA_MAGIC = new UUID("802dc0e0-f080-4931-8b57-d1be8611c4f3");
55 private static readonly Color4 WATER_COLOR = new Color4(29, 71, 95, 216);
56
57 private static readonly ILog m_log =
58 LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
59
60 private Scene m_scene;
61 private IRendering m_primMesher;
62 private IConfigSource m_config;
63 private Dictionary<UUID, Color4> m_colors = new Dictionary<UUID, Color4>();
64 private bool m_useAntiAliasing = true; // TODO: Make this a config option
65
66 #region IRegionModule Members
67
68 public void Initialise(Scene scene, IConfigSource source)
69 {
70 m_scene = scene;
71 m_config = source;
72
73 IConfig startupConfig = m_config.Configs["Startup"];
74 if (startupConfig.GetString("MapImageModule", "MapImageModule") != "Warp3DImageModule")
75 return;
76
77 List<string> renderers = RenderingLoader.ListRenderers(Util.ExecutingDirectory());
78 if (renderers.Count > 0)
79 {
80 m_primMesher = RenderingLoader.LoadRenderer(renderers[0]);
81 m_log.Info("[MAPTILE]: Loaded prim mesher " + m_primMesher.ToString());
82 }
83 else
84 {
85 m_log.Info("[MAPTILE]: No prim mesher loaded, prim rendering will be disabled");
86 }
87
88 m_scene.RegisterModuleInterface<IMapImageGenerator>(this);
89 }
90
91 public void PostInitialise()
92 {
93 }
94
95 public void Close()
96 {
97 }
98
99 public string Name
100 {
101 get { return "Warp3DImageModule"; }
102 }
103
104 public bool IsSharedModule
105 {
106 get { return false; }
107 }
108
109 #endregion
110
111 #region IMapImageGenerator Members
112
113 public Bitmap CreateMapTile()
114 {
115 bool drawPrimVolume = true;
116 bool textureTerrain = true;
117
118 try
119 {
120 IConfig startupConfig = m_config.Configs["Startup"];
121 drawPrimVolume = startupConfig.GetBoolean("DrawPrimOnMapTile", drawPrimVolume);
122 textureTerrain = startupConfig.GetBoolean("TextureOnMapTile", textureTerrain);
123 }
124 catch
125 {
126 m_log.Warn("[MAPTILE]: Failed to load StartupConfig");
127 }
128
129 m_colors.Clear();
130
131 Vector3 camPos = new Vector3(127.5f, 127.5f, 221.7025033688163f);
132 Viewport viewport = new Viewport(camPos, -Vector3.UnitZ, 1024f, 0.1f, (int)Constants.RegionSize, (int)Constants.RegionSize, (float)Constants.RegionSize, (float)Constants.RegionSize);
133
134 int width = viewport.Width;
135 int height = viewport.Height;
136
137 if (m_useAntiAliasing)
138 {
139 width *= 2;
140 height *= 2;
141 }
142
143 WarpRenderer renderer = new WarpRenderer();
144 renderer.CreateScene(width, height);
145 renderer.Scene.autoCalcNormals = false;
146
147 #region Camera
148
149 warp_Vector pos = ConvertVector(viewport.Position);
150 pos.z -= 0.001f; // Works around an issue with the Warp3D camera
151 warp_Vector lookat = warp_Vector.add(ConvertVector(viewport.Position), ConvertVector(viewport.LookDirection));
152
153 renderer.Scene.defaultCamera.setPos(pos);
154 renderer.Scene.defaultCamera.lookAt(lookat);
155
156 if (viewport.Orthographic)
157 {
158 renderer.Scene.defaultCamera.isOrthographic = true;
159 renderer.Scene.defaultCamera.orthoViewWidth = viewport.OrthoWindowWidth;
160 renderer.Scene.defaultCamera.orthoViewHeight = viewport.OrthoWindowHeight;
161 }
162 else
163 {
164 float fov = viewport.FieldOfView;
165 fov *= 1.75f; // FIXME: ???
166 renderer.Scene.defaultCamera.setFov(fov);
167 }
168
169 #endregion Camera
170
171 renderer.Scene.addLight("Light1", new warp_Light(new warp_Vector(0.2f, 0.2f, 1f), 0xffffff, 320, 80));
172 renderer.Scene.addLight("Light2", new warp_Light(new warp_Vector(-1f, -1f, 1f), 0xffffff, 100, 40));
173
174 CreateWater(renderer);
175 CreateTerrain(renderer, textureTerrain);
176 if (drawPrimVolume)
177 CreateAllPrims(renderer);
178
179 renderer.Render();
180 Bitmap bitmap = renderer.Scene.getImage();
181
182 if (m_useAntiAliasing)
183 bitmap = ImageUtils.ResizeImage(bitmap, viewport.Width, viewport.Height);
184
185 return bitmap;
186 }
187
188 public byte[] WriteJpeg2000Image()
189 {
190 try
191 {
192 using (Bitmap mapbmp = CreateMapTile())
193 return OpenJPEG.EncodeFromImage(mapbmp, true);
194 }
195 catch (Exception e)
196 {
197 // JPEG2000 encoder failed
198 m_log.Error("[MAPTILE]: Failed generating terrain map: " + e);
199 }
200
201 return null;
202 }
203
204 #endregion
205
206 #region Rendering Methods
207
208 private void CreateWater(WarpRenderer renderer)
209 {
210 float waterHeight = (float)m_scene.RegionInfo.RegionSettings.WaterHeight;
211
212 renderer.AddPlane("Water", 256f * 0.5f);
213 renderer.Scene.sceneobject("Water").setPos(127.5f, waterHeight, 127.5f);
214
215 renderer.AddMaterial("WaterColor", ConvertColor(WATER_COLOR));
216 renderer.Scene.material("WaterColor").setTransparency((byte)((1f - WATER_COLOR.A) * 255f));
217 renderer.SetObjectMaterial("Water", "WaterColor");
218 }
219
220 private void CreateTerrain(WarpRenderer renderer, bool textureTerrain)
221 {
222 ITerrainChannel terrain = m_scene.Heightmap;
223 float[] heightmap = terrain.GetFloatsSerialised();
224
225 warp_Object obj = new warp_Object(256 * 256, 255 * 255 * 2);
226
227 for (int y = 0; y < 256; y++)
228 {
229 for (int x = 0; x < 256; x++)
230 {
231 int v = y * 256 + x;
232 float height = heightmap[v];
233
234 warp_Vector pos = ConvertVector(new Vector3(x, y, height));
235 obj.addVertex(new warp_Vertex(pos, (float)x / 255f, (float)(255 - y) / 255f));
236 }
237 }
238
239 for (int y = 0; y < 256; y++)
240 {
241 for (int x = 0; x < 256; x++)
242 {
243 if (x < 255 && y < 255)
244 {
245 int v = y * 256 + x;
246
247 // Normal
248 Vector3 v1 = new Vector3(x, y, heightmap[y * 256 + x]);
249 Vector3 v2 = new Vector3(x + 1, y, heightmap[y * 256 + x + 1]);
250 Vector3 v3 = new Vector3(x, y + 1, heightmap[(y + 1) * 256 + x]);
251 warp_Vector norm = ConvertVector(SurfaceNormal(v1, v2, v3));
252 norm = norm.reverse();
253 obj.vertex(v).n = norm;
254
255 // Triangle 1
256 obj.addTriangle(
257 v,
258 v + 1,
259 v + 256);
260
261 // Triangle 2
262 obj.addTriangle(
263 v + 256 + 1,
264 v + 256,
265 v + 1);
266 }
267 }
268 }
269
270 renderer.Scene.addObject("Terrain", obj);
271
272 UUID[] textureIDs = new UUID[4];
273 float[] startHeights = new float[4];
274 float[] heightRanges = new float[4];
275
276 RegionSettings regionInfo = m_scene.RegionInfo.RegionSettings;
277
278 textureIDs[0] = regionInfo.TerrainTexture1;
279 textureIDs[1] = regionInfo.TerrainTexture2;
280 textureIDs[2] = regionInfo.TerrainTexture3;
281 textureIDs[3] = regionInfo.TerrainTexture4;
282
283 startHeights[0] = (float)regionInfo.Elevation1SW;
284 startHeights[1] = (float)regionInfo.Elevation1NW;
285 startHeights[2] = (float)regionInfo.Elevation1SE;
286 startHeights[3] = (float)regionInfo.Elevation1NE;
287
288 heightRanges[0] = (float)regionInfo.Elevation2SW;
289 heightRanges[1] = (float)regionInfo.Elevation2NW;
290 heightRanges[2] = (float)regionInfo.Elevation2SE;
291 heightRanges[3] = (float)regionInfo.Elevation2NE;
292
293 uint globalX, globalY;
294 Utils.LongToUInts(m_scene.RegionInfo.RegionHandle, out globalX, out globalY);
295
296 Bitmap image = TerrainSplat.Splat(heightmap, textureIDs, startHeights, heightRanges, new Vector3d(globalX, globalY, 0.0), m_scene.AssetService, textureTerrain);
297 warp_Texture texture = new warp_Texture(image);
298 warp_Material material = new warp_Material(texture);
299 material.setReflectivity(50);
300 renderer.Scene.addMaterial("TerrainColor", material);
301 renderer.SetObjectMaterial("Terrain", "TerrainColor");
302 }
303
304 private void CreateAllPrims(WarpRenderer renderer)
305 {
306 if (m_primMesher == null)
307 return;
308
309 m_scene.ForEachSOG(
310 delegate(SceneObjectGroup group)
311 {
312 CreatePrim(renderer, group.RootPart);
313 foreach (SceneObjectPart child in group.Children.Values)
314 CreatePrim(renderer, child);
315 }
316 );
317 }
318
319 private void CreatePrim(WarpRenderer renderer, SceneObjectPart prim)
320 {
321 const float MIN_SIZE = 2f;
322
323 if ((PCode)prim.Shape.PCode != PCode.Prim)
324 return;
325 if (prim.Scale.LengthSquared() < MIN_SIZE * MIN_SIZE)
326 return;
327
328 Primitive omvPrim = prim.Shape.ToOmvPrimitive(prim.OffsetPosition, prim.RotationOffset);
329 FacetedMesh renderMesh = m_primMesher.GenerateFacetedMesh(omvPrim, DetailLevel.Medium);
330 if (renderMesh == null)
331 return;
332
333 warp_Vector primPos = ConvertVector(prim.AbsolutePosition);
334 warp_Quaternion primRot = ConvertQuaternion(prim.RotationOffset);
335
336 warp_Matrix m = warp_Matrix.quaternionMatrix(primRot);
337
338 if (prim.ParentID != 0)
339 {
340 SceneObjectGroup group = m_scene.SceneGraph.GetGroupByPrim(prim.LocalId);
341 if (group != null)
342 m.transform(warp_Matrix.quaternionMatrix(ConvertQuaternion(group.RootPart.RotationOffset)));
343 }
344
345 warp_Vector primScale = ConvertVector(prim.Scale);
346
347 string primID = prim.UUID.ToString();
348
349 // Create the prim faces
350 for (int i = 0; i < renderMesh.Faces.Count; i++)
351 {
352 Face face = renderMesh.Faces[i];
353 string meshName = primID + "-Face-" + i.ToString();
354
355 warp_Object faceObj = new warp_Object(face.Vertices.Count, face.Indices.Count / 3);
356
357 for (int j = 0; j < face.Vertices.Count; j++)
358 {
359 Vertex v = face.Vertices[j];
360
361 warp_Vector pos = ConvertVector(v.Position);
362 warp_Vector norm = ConvertVector(v.Normal);
363
364 if (prim.Shape.SculptTexture == UUID.Zero)
365 norm = norm.reverse();
366 warp_Vertex vert = new warp_Vertex(pos, norm, v.TexCoord.X, v.TexCoord.Y);
367
368 faceObj.addVertex(vert);
369 }
370
371 for (int j = 0; j < face.Indices.Count; j += 3)
372 {
373 faceObj.addTriangle(
374 face.Indices[j + 0],
375 face.Indices[j + 1],
376 face.Indices[j + 2]);
377 }
378
379 Primitive.TextureEntryFace teFace = prim.Shape.Textures.GetFace((uint)i);
380 Color4 faceColor = GetFaceColor(teFace);
381 string materialName = GetOrCreateMaterial(renderer, faceColor);
382
383 faceObj.transform(m);
384 faceObj.setPos(primPos);
385 faceObj.scaleSelf(primScale.x, primScale.y, primScale.z);
386
387 renderer.Scene.addObject(meshName, faceObj);
388
389 renderer.SetObjectMaterial(meshName, materialName);
390 }
391 }
392
393 private Color4 GetFaceColor(Primitive.TextureEntryFace face)
394 {
395 Color4 color;
396
397 if (face.TextureID == UUID.Zero)
398 return face.RGBA;
399
400 if (!m_colors.TryGetValue(face.TextureID, out color))
401 {
402 bool fetched = false;
403
404 // Attempt to fetch the texture metadata
405 UUID metadataID = UUID.Combine(face.TextureID, TEXTURE_METADATA_MAGIC);
406 AssetBase metadata = m_scene.AssetService.GetCached(metadataID.ToString());
407 if (metadata != null)
408 {
409 OSDMap map = null;
410 try { map = OSDParser.Deserialize(metadata.Data) as OSDMap; } catch { }
411
412 if (map != null)
413 {
414 color = map["X-JPEG2000-RGBA"].AsColor4();
415 fetched = true;
416 }
417 }
418
419 if (!fetched)
420 {
421 // Fetch the texture, decode and get the average color,
422 // then save it to a temporary metadata asset
423 AssetBase textureAsset = m_scene.AssetService.Get(face.TextureID.ToString());
424 if (textureAsset != null)
425 {
426 int width, height;
427 color = GetAverageColor(textureAsset.FullID, textureAsset.Data, out width, out height);
428
429 OSDMap data = new OSDMap { { "X-JPEG2000-RGBA", OSD.FromColor4(color) } };
430 metadata = new AssetBase
431 {
432 Data = System.Text.Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(data)),
433 Description = "Metadata for JPEG2000 texture " + face.TextureID.ToString(),
434 Flags = AssetFlags.Collectable,
435 FullID = metadataID,
436 ID = metadataID.ToString(),
437 Local = true,
438 Temporary = true,
439 Name = String.Empty,
440 Type = (sbyte)AssetType.Unknown
441 };
442 m_scene.AssetService.Store(metadata);
443 }
444 else
445 {
446 color = new Color4(0.5f, 0.5f, 0.5f, 1.0f);
447 }
448 }
449
450 m_colors[face.TextureID] = color;
451 }
452
453 return color * face.RGBA;
454 }
455
456 private string GetOrCreateMaterial(WarpRenderer renderer, Color4 color)
457 {
458 string name = color.ToString();
459
460 warp_Material material = renderer.Scene.material(name);
461 if (material != null)
462 return name;
463
464 renderer.AddMaterial(name, ConvertColor(color));
465 if (color.A < 1f)
466 renderer.Scene.material(name).setTransparency((byte)((1f - color.A) * 255f));
467 return name;
468 }
469
470 #endregion Rendering Methods
471
472 #region Static Helpers
473
474 private static warp_Vector ConvertVector(Vector3 vector)
475 {
476 return new warp_Vector(vector.X, vector.Z, vector.Y);
477 }
478
479 private static warp_Quaternion ConvertQuaternion(Quaternion quat)
480 {
481 return new warp_Quaternion(quat.X, quat.Z, quat.Y, -quat.W);
482 }
483
484 private static int ConvertColor(Color4 color)
485 {
486 int c = warp_Color.getColor((byte)(color.R * 255f), (byte)(color.G * 255f), (byte)(color.B * 255f));
487 if (color.A < 1f)
488 c |= (byte)(color.A * 255f) << 24;
489
490 return c;
491 }
492
493 private static Vector3 SurfaceNormal(Vector3 c1, Vector3 c2, Vector3 c3)
494 {
495 Vector3 edge1 = new Vector3(c2.X - c1.X, c2.Y - c1.Y, c2.Z - c1.Z);
496 Vector3 edge2 = new Vector3(c3.X - c1.X, c3.Y - c1.Y, c3.Z - c1.Z);
497
498 Vector3 normal = Vector3.Cross(edge1, edge2);
499 normal.Normalize();
500
501 return normal;
502 }
503
504 public static Color4 GetAverageColor(UUID textureID, byte[] j2kData, out int width, out int height)
505 {
506 ulong r = 0;
507 ulong g = 0;
508 ulong b = 0;
509 ulong a = 0;
510
511 using (MemoryStream stream = new MemoryStream(j2kData))
512 {
513 try
514 {
515 Bitmap bitmap = (Bitmap)J2kImage.FromStream(stream);
516 width = bitmap.Width;
517 height = bitmap.Height;
518
519 BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
520 int pixelBytes = (bitmap.PixelFormat == PixelFormat.Format24bppRgb) ? 3 : 4;
521
522 // Sum up the individual channels
523 unsafe
524 {
525 if (pixelBytes == 4)
526 {
527 for (int y = 0; y < height; y++)
528 {
529 byte* row = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride);
530
531 for (int x = 0; x < width; x++)
532 {
533 b += row[x * pixelBytes + 0];
534 g += row[x * pixelBytes + 1];
535 r += row[x * pixelBytes + 2];
536 a += row[x * pixelBytes + 3];
537 }
538 }
539 }
540 else
541 {
542 for (int y = 0; y < height; y++)
543 {
544 byte* row = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride);
545
546 for (int x = 0; x < width; x++)
547 {
548 b += row[x * pixelBytes + 0];
549 g += row[x * pixelBytes + 1];
550 r += row[x * pixelBytes + 2];
551 }
552 }
553 }
554 }
555
556 // Get the averages for each channel
557 const decimal OO_255 = 1m / 255m;
558 decimal totalPixels = (decimal)(width * height);
559
560 decimal rm = ((decimal)r / totalPixels) * OO_255;
561 decimal gm = ((decimal)g / totalPixels) * OO_255;
562 decimal bm = ((decimal)b / totalPixels) * OO_255;
563 decimal am = ((decimal)a / totalPixels) * OO_255;
564
565 if (pixelBytes == 3)
566 am = 1m;
567
568 return new Color4((float)rm, (float)gm, (float)bm, (float)am);
569 }
570 catch (Exception ex)
571 {
572 m_log.WarnFormat("[MAPTILE]: Error decoding JPEG2000 texture {0} ({1} bytes): {2}", textureID, j2kData.Length, ex.Message);
573 width = 0;
574 height = 0;
575 return new Color4(0.5f, 0.5f, 0.5f, 1.0f);
576 }
577 }
578 }
579
580 #endregion Static Helpers
581 }
582
583 public static class ImageUtils
584 {
585 /// <summary>
586 /// Performs bilinear interpolation between four values
587 /// </summary>
588 /// <param name="v00">First, or top left value</param>
589 /// <param name="v01">Second, or top right value</param>
590 /// <param name="v10">Third, or bottom left value</param>
591 /// <param name="v11">Fourth, or bottom right value</param>
592 /// <param name="xPercent">Interpolation value on the X axis, between 0.0 and 1.0</param>
593 /// <param name="yPercent">Interpolation value on fht Y axis, between 0.0 and 1.0</param>
594 /// <returns>The bilinearly interpolated result</returns>
595 public static float Bilinear(float v00, float v01, float v10, float v11, float xPercent, float yPercent)
596 {
597 return Utils.Lerp(Utils.Lerp(v00, v01, xPercent), Utils.Lerp(v10, v11, xPercent), yPercent);
598 }
599
600 /// <summary>
601 /// Performs a high quality image resize
602 /// </summary>
603 /// <param name="image">Image to resize</param>
604 /// <param name="width">New width</param>
605 /// <param name="height">New height</param>
606 /// <returns>Resized image</returns>
607 public static Bitmap ResizeImage(Image image, int width, int height)
608 {
609 Bitmap result = new Bitmap(width, height);
610
611 using (Graphics graphics = Graphics.FromImage(result))
612 {
613 graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
614 graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
615 graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
616 graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
617
618 graphics.DrawImage(image, 0, 0, result.Width, result.Height);
619 }
620
621 return result;
622 }
623 }
624}
diff --git a/OpenSim/Region/CoreModules/World/Warp3DMap/Perlin.cs b/OpenSim/Region/CoreModules/World/Warp3DMap/Perlin.cs
new file mode 100644
index 0000000..af59d7a
--- /dev/null
+++ b/OpenSim/Region/CoreModules/World/Warp3DMap/Perlin.cs
@@ -0,0 +1,273 @@
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
28using System;
29using OpenMetaverse;
30
31namespace OpenSim.Region.CoreModules.World.Warp3DMap
32{
33 public static class Perlin
34 {
35 // We use a hardcoded seed to keep the noise generation consistent between runs
36 private const int SEED = 42;
37
38 private const int SAMPLE_SIZE = 1024;
39 private const int B = SAMPLE_SIZE;
40 private const int BM = SAMPLE_SIZE - 1;
41 private const int N = 0x1000;
42
43 private static readonly int[] p = new int[SAMPLE_SIZE + SAMPLE_SIZE + 2];
44 private static readonly float[,] g3 = new float[SAMPLE_SIZE + SAMPLE_SIZE + 2, 3];
45 private static readonly float[,] g2 = new float[SAMPLE_SIZE + SAMPLE_SIZE + 2, 2];
46 private static readonly float[] g1 = new float[SAMPLE_SIZE + SAMPLE_SIZE + 2];
47
48 static Perlin()
49 {
50 Random rng = new Random(SEED);
51 int i, j, k;
52
53 for (i = 0; i < B; i++)
54 {
55 p[i] = i;
56 g1[i] = (float)((rng.Next() % (B + B)) - B) / B;
57
58 for (j = 0; j < 2; j++)
59 g2[i, j] = (float)((rng.Next() % (B + B)) - B) / B;
60 normalize2(g2, i);
61
62 for (j = 0; j < 3; j++)
63 g3[i, j] = (float)((rng.Next() % (B + B)) - B) / B;
64 normalize3(g3, i);
65 }
66
67 while (--i > 0)
68 {
69 k = p[i];
70 p[i] = p[j = rng.Next() % B];
71 p[j] = k;
72 }
73
74 for (i = 0; i < B + 2; i++)
75 {
76 p[B + i] = p[i];
77 g1[B + i] = g1[i];
78 for (j = 0; j < 2; j++)
79 g2[B + i, j] = g2[i, j];
80 for (j = 0; j < 3; j++)
81 g3[B + i, j] = g3[i, j];
82 }
83 }
84
85 public static float noise1(float arg)
86 {
87 int bx0, bx1;
88 float rx0, rx1, sx, t, u, v, a;
89
90 a = arg;
91
92 t = arg + N;
93 bx0 = ((int)t) & BM;
94 bx1 = (bx0 + 1) & BM;
95 rx0 = t - (int)t;
96 rx1 = rx0 - 1f;
97
98 sx = s_curve(rx0);
99
100 u = rx0 * g1[p[bx0]];
101 v = rx1 * g1[p[bx1]];
102
103 return Utils.Lerp(u, v, sx);
104 }
105
106 public static float noise2(float x, float y)
107 {
108 int bx0, bx1, by0, by1, b00, b10, b01, b11;
109 float rx0, rx1, ry0, ry1, sx, sy, a, b, t, u, v;
110 int i, j;
111
112 t = x + N;
113 bx0 = ((int)t) & BM;
114 bx1 = (bx0 + 1) & BM;
115 rx0 = t - (int)t;
116 rx1 = rx0 - 1f;
117
118 t = y + N;
119 by0 = ((int)t) & BM;
120 by1 = (by0 + 1) & BM;
121 ry0 = t - (int)t;
122 ry1 = ry0 - 1f;
123
124 i = p[bx0];
125 j = p[bx1];
126
127 b00 = p[i + by0];
128 b10 = p[j + by0];
129 b01 = p[i + by1];
130 b11 = p[j + by1];
131
132 sx = s_curve(rx0);
133 sy = s_curve(ry0);
134
135 u = rx0 * g2[b00, 0] + ry0 * g2[b00, 1];
136 v = rx1 * g2[b10, 0] + ry0 * g2[b10, 1];
137 a = Utils.Lerp(u, v, sx);
138
139 u = rx0 * g2[b01, 0] + ry1 * g2[b01, 1];
140 v = rx1 * g2[b11, 0] + ry1 * g2[b11, 1];
141 b = Utils.Lerp(u, v, sx);
142
143 return Utils.Lerp(a, b, sy);
144 }
145
146 public static float noise3(float x, float y, float z)
147 {
148 int bx0, bx1, by0, by1, bz0, bz1, b00, b10, b01, b11;
149 float rx0, rx1, ry0, ry1, rz0, rz1, sy, sz, a, b, c, d, t, u, v;
150 int i, j;
151
152 t = x + N;
153 bx0 = ((int)t) & BM;
154 bx1 = (bx0 + 1) & BM;
155 rx0 = t - (int)t;
156 rx1 = rx0 - 1f;
157
158 t = y + N;
159 by0 = ((int)t) & BM;
160 by1 = (by0 + 1) & BM;
161 ry0 = t - (int)t;
162 ry1 = ry0 - 1f;
163
164 t = z + N;
165 bz0 = ((int)t) & BM;
166 bz1 = (bz0 + 1) & BM;
167 rz0 = t - (int)t;
168 rz1 = rz0 - 1f;
169
170 i = p[bx0];
171 j = p[bx1];
172
173 b00 = p[i + by0];
174 b10 = p[j + by0];
175 b01 = p[i + by1];
176 b11 = p[j + by1];
177
178 t = s_curve(rx0);
179 sy = s_curve(ry0);
180 sz = s_curve(rz0);
181
182 u = rx0 * g3[b00 + bz0, 0] + ry0 * g3[b00 + bz0, 1] + rz0 * g3[b00 + bz0, 2];
183 v = rx1 * g3[b10 + bz0, 0] + ry0 * g3[b10 + bz0, 1] + rz0 * g3[b10 + bz0, 2];
184 a = Utils.Lerp(u, v, t);
185
186 u = rx0 * g3[b01 + bz0, 0] + ry1 * g3[b01 + bz0, 1] + rz0 * g3[b01 + bz0, 2];
187 v = rx1 * g3[b11 + bz0, 0] + ry1 * g3[b11 + bz0, 1] + rz0 * g3[b11 + bz0, 2];
188 b = Utils.Lerp(u, v, t);
189
190 c = Utils.Lerp(a, b, sy);
191
192 u = rx0 * g3[b00 + bz1, 0] + ry0 * g3[b00 + bz1, 1] + rz1 * g3[b00 + bz1, 2];
193 v = rx1 * g3[b10 + bz1, 0] + ry0 * g3[b10 + bz1, 1] + rz1 * g3[b10 + bz1, 2];
194 a = Utils.Lerp(u, v, t);
195
196 u = rx0 * g3[b01 + bz1, 0] + ry1 * g3[b01 + bz1, 1] + rz1 * g3[b01 + bz1, 2];
197 v = rx1 * g3[b11 + bz1, 0] + ry1 * g3[b11 + bz1, 1] + rz1 * g3[b11 + bz1, 2];
198 b = Utils.Lerp(u, v, t);
199
200 d = Utils.Lerp(a, b, sy);
201 return Utils.Lerp(c, d, sz);
202 }
203
204 public static float turbulence1(float x, float freq)
205 {
206 float t;
207 float v;
208
209 for (t = 0f; freq >= 1f; freq *= 0.5f)
210 {
211 v = freq * x;
212 t += noise1(v) / freq;
213 }
214 return t;
215 }
216
217 public static float turbulence2(float x, float y, float freq)
218 {
219 float t;
220 Vector2 vec;
221
222 for (t = 0f; freq >= 1f; freq *= 0.5f)
223 {
224 vec.X = freq * x;
225 vec.Y = freq * y;
226 t += noise2(vec.X, vec.Y) / freq;
227 }
228 return t;
229 }
230
231 public static float turbulence3(float x, float y, float z, float freq)
232 {
233 float t;
234 Vector3 vec;
235
236 for (t = 0f; freq >= 1f; freq *= 0.5f)
237 {
238 vec.X = freq * x;
239 vec.Y = freq * y;
240 vec.Z = freq * z;
241 t += noise3(vec.X, vec.Y, vec.Z) / freq;
242 }
243 return t;
244 }
245
246 private static void normalize2(float[,] v, int i)
247 {
248 float s;
249
250 s = (float)Math.Sqrt(v[i, 0] * v[i, 0] + v[i, 1] * v[i, 1]);
251 s = 1.0f / s;
252 v[i, 0] = v[i, 0] * s;
253 v[i, 1] = v[i, 1] * s;
254 }
255
256 private static void normalize3(float[,] v, int i)
257 {
258 float s;
259
260 s = (float)Math.Sqrt(v[i, 0] * v[i, 0] + v[i, 1] * v[i, 1] + v[i, 2] * v[i, 2]);
261 s = 1.0f / s;
262
263 v[i, 0] = v[i, 0] * s;
264 v[i, 1] = v[i, 1] * s;
265 v[i, 2] = v[i, 2] * s;
266 }
267
268 private static float s_curve(float t)
269 {
270 return t * t * (3f - 2f * t);
271 }
272 }
273}
diff --git a/OpenSim/Region/CoreModules/World/Warp3DMap/TerrainSplat.cs b/OpenSim/Region/CoreModules/World/Warp3DMap/TerrainSplat.cs
new file mode 100644
index 0000000..7bf675d
--- /dev/null
+++ b/OpenSim/Region/CoreModules/World/Warp3DMap/TerrainSplat.cs
@@ -0,0 +1,343 @@
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
28using System;
29using System.Diagnostics;
30using System.Drawing;
31using System.Drawing.Imaging;
32using log4net;
33using OpenMetaverse;
34using OpenSim.Framework;
35using OpenSim.Services.Interfaces;
36
37namespace OpenSim.Region.CoreModules.World.Warp3DMap
38{
39 public static class TerrainSplat
40 {
41 #region Constants
42
43 private static readonly UUID DIRT_DETAIL = new UUID("0bc58228-74a0-7e83-89bc-5c23464bcec5");
44 private static readonly UUID GRASS_DETAIL = new UUID("63338ede-0037-c4fd-855b-015d77112fc8");
45 private static readonly UUID MOUNTAIN_DETAIL = new UUID("303cd381-8560-7579-23f1-f0a880799740");
46 private static readonly UUID ROCK_DETAIL = new UUID("53a2f406-4895-1d13-d541-d2e3b86bc19c");
47
48 private static readonly UUID[] DEFAULT_TERRAIN_DETAIL = new UUID[]
49 {
50 DIRT_DETAIL,
51 GRASS_DETAIL,
52 MOUNTAIN_DETAIL,
53 ROCK_DETAIL
54 };
55
56 private static readonly Color[] DEFAULT_TERRAIN_COLOR = new Color[]
57 {
58 Color.FromArgb(255, 164, 136, 117),
59 Color.FromArgb(255, 65, 87, 47),
60 Color.FromArgb(255, 157, 145, 131),
61 Color.FromArgb(255, 125, 128, 130)
62 };
63
64 private static readonly UUID TERRAIN_CACHE_MAGIC = new UUID("2c0c7ef2-56be-4eb8-aacb-76712c535b4b");
65
66 #endregion Constants
67
68 private static readonly ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name);
69
70 /// <summary>
71 /// Builds a composited terrain texture given the region texture
72 /// and heightmap settings
73 /// </summary>
74 /// <param name="heightmap">Terrain heightmap</param>
75 /// <param name="regionInfo">Region information including terrain texture parameters</param>
76 /// <returns>A composited 256x256 RGB texture ready for rendering</returns>
77 /// <remarks>Based on the algorithm described at http://opensimulator.org/wiki/Terrain_Splatting
78 /// </remarks>
79 public static Bitmap Splat(float[] heightmap, UUID[] textureIDs, float[] startHeights, float[] heightRanges, Vector3d regionPosition, IAssetService assetService, bool textureTerrain)
80 {
81 Debug.Assert(heightmap.Length == 256 * 256);
82 Debug.Assert(textureIDs.Length == 4);
83 Debug.Assert(startHeights.Length == 4);
84 Debug.Assert(heightRanges.Length == 4);
85
86 Bitmap[] detailTexture = new Bitmap[4];
87
88 if (textureTerrain)
89 {
90 // Swap empty terrain textureIDs with default IDs
91 for (int i = 0; i < textureIDs.Length; i++)
92 {
93 if (textureIDs[i] == UUID.Zero)
94 textureIDs[i] = DEFAULT_TERRAIN_DETAIL[i];
95 }
96
97 #region Texture Fetching
98
99 if (assetService != null)
100 {
101 for (int i = 0; i < 4; i++)
102 {
103 AssetBase asset;
104 UUID cacheID = UUID.Combine(TERRAIN_CACHE_MAGIC, textureIDs[i]);
105
106 // Try to fetch a cached copy of the decoded/resized version of this texture
107 asset = assetService.GetCached(cacheID.ToString());
108 if (asset != null)
109 {
110 try
111 {
112 using (System.IO.MemoryStream stream = new System.IO.MemoryStream(asset.Data))
113 detailTexture[i] = (Bitmap)Image.FromStream(stream);
114 }
115 catch (Exception ex)
116 {
117 m_log.Warn("Failed to decode cached terrain texture " + cacheID +
118 " (textureID: " + textureIDs[i] + "): " + ex.Message);
119 }
120 }
121
122 if (detailTexture[i] == null)
123 {
124 // Try to fetch the original JPEG2000 texture, resize if needed, and cache as PNG
125 asset = assetService.Get(textureIDs[i].ToString());
126 if (asset != null)
127 {
128 try { detailTexture[i] = (Bitmap)CSJ2K.J2kImage.FromBytes(asset.Data); }
129 catch (Exception ex)
130 {
131 m_log.Warn("Failed to decode terrain texture " + asset.ID + ": " + ex.Message);
132 }
133 }
134
135 if (detailTexture[i] != null)
136 {
137 Bitmap bitmap = detailTexture[i];
138
139 // Make sure this texture is the correct size, otherwise resize
140 if (bitmap.Width != 256 || bitmap.Height != 256)
141 bitmap = ImageUtils.ResizeImage(bitmap, 256, 256);
142
143 // Save the decoded and resized texture to the cache
144 byte[] data;
145 using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
146 {
147 bitmap.Save(stream, ImageFormat.Png);
148 data = stream.ToArray();
149 }
150
151 // Cache a PNG copy of this terrain texture
152 AssetBase newAsset = new AssetBase
153 {
154 Data = data,
155 Description = "PNG",
156 Flags = AssetFlags.Collectable,
157 FullID = cacheID,
158 ID = cacheID.ToString(),
159 Local = true,
160 Name = String.Empty,
161 Temporary = true,
162 Type = (sbyte)AssetType.Unknown
163 };
164 newAsset.Metadata.ContentType = "image/png";
165 assetService.Store(newAsset);
166 }
167 }
168 }
169 }
170
171 #endregion Texture Fetching
172 }
173
174 // Fill in any missing textures with a solid color
175 for (int i = 0; i < 4; i++)
176 {
177 if (detailTexture[i] == null)
178 {
179 // Create a solid color texture for this layer
180 detailTexture[i] = new Bitmap(256, 256, PixelFormat.Format24bppRgb);
181 using (Graphics gfx = Graphics.FromImage(detailTexture[i]))
182 {
183 using (SolidBrush brush = new SolidBrush(DEFAULT_TERRAIN_COLOR[i]))
184 gfx.FillRectangle(brush, 0, 0, 256, 256);
185 }
186 }
187 }
188
189 #region Layer Map
190
191 float[] layermap = new float[256 * 256];
192
193 for (int y = 0; y < 256; y++)
194 {
195 for (int x = 0; x < 256; x++)
196 {
197 float height = heightmap[y * 256 + x];
198
199 float pctX = (float)x / 255f;
200 float pctY = (float)y / 255f;
201
202 // Use bilinear interpolation between the four corners of start height and
203 // height range to select the current values at this position
204 float startHeight = ImageUtils.Bilinear(
205 startHeights[0],
206 startHeights[2],
207 startHeights[1],
208 startHeights[3],
209 pctX, pctY);
210 startHeight = Utils.Clamp(startHeight, 0f, 255f);
211
212 float heightRange = ImageUtils.Bilinear(
213 heightRanges[0],
214 heightRanges[2],
215 heightRanges[1],
216 heightRanges[3],
217 pctX, pctY);
218 heightRange = Utils.Clamp(heightRange, 0f, 255f);
219
220 // Generate two frequencies of perlin noise based on our global position
221 // The magic values were taken from http://opensimulator.org/wiki/Terrain_Splatting
222 Vector3 vec = new Vector3
223 (
224 ((float)regionPosition.X + x) * 0.20319f,
225 ((float)regionPosition.Y + y) * 0.20319f,
226 height * 0.25f
227 );
228
229 float lowFreq = Perlin.noise2(vec.X * 0.222222f, vec.Y * 0.222222f) * 6.5f;
230 float highFreq = Perlin.turbulence2(vec.X, vec.Y, 2f) * 2.25f;
231 float noise = (lowFreq + highFreq) * 2f;
232
233 // Combine the current height, generated noise, start height, and height range parameters, then scale all of it
234 float layer = ((height + noise - startHeight) / heightRange) * 4f;
235 if (Single.IsNaN(layer)) layer = 0f;
236 layermap[y * 256 + x] = Utils.Clamp(layer, 0f, 3f);
237 }
238 }
239
240 #endregion Layer Map
241
242 #region Texture Compositing
243
244 Bitmap output = new Bitmap(256, 256, PixelFormat.Format24bppRgb);
245 BitmapData outputData = output.LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
246
247 unsafe
248 {
249 // Get handles to all of the texture data arrays
250 BitmapData[] datas = new BitmapData[]
251 {
252 detailTexture[0].LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.ReadOnly, detailTexture[0].PixelFormat),
253 detailTexture[1].LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.ReadOnly, detailTexture[1].PixelFormat),
254 detailTexture[2].LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.ReadOnly, detailTexture[2].PixelFormat),
255 detailTexture[3].LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.ReadOnly, detailTexture[3].PixelFormat)
256 };
257
258 int[] comps = new int[]
259 {
260 (datas[0].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3,
261 (datas[1].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3,
262 (datas[2].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3,
263 (datas[3].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3
264 };
265
266 for (int y = 0; y < 256; y++)
267 {
268 for (int x = 0; x < 256; x++)
269 {
270 float layer = layermap[y * 256 + x];
271
272 // Select two textures
273 int l0 = (int)Math.Floor(layer);
274 int l1 = Math.Min(l0 + 1, 3);
275
276 byte* ptrA = (byte*)datas[l0].Scan0 + y * datas[l0].Stride + x * comps[l0];
277 byte* ptrB = (byte*)datas[l1].Scan0 + y * datas[l1].Stride + x * comps[l1];
278 byte* ptrO = (byte*)outputData.Scan0 + y * outputData.Stride + x * 3;
279
280 float aB = *(ptrA + 0);
281 float aG = *(ptrA + 1);
282 float aR = *(ptrA + 2);
283
284 float bB = *(ptrB + 0);
285 float bG = *(ptrB + 1);
286 float bR = *(ptrB + 2);
287
288 float layerDiff = layer - l0;
289
290 // Interpolate between the two selected textures
291 *(ptrO + 0) = (byte)Math.Floor(aB + layerDiff * (bB - aB));
292 *(ptrO + 1) = (byte)Math.Floor(aG + layerDiff * (bG - aG));
293 *(ptrO + 2) = (byte)Math.Floor(aR + layerDiff * (bR - aR));
294 }
295 }
296
297 for (int i = 0; i < 4; i++)
298 detailTexture[i].UnlockBits(datas[i]);
299 }
300
301 output.UnlockBits(outputData);
302
303 // We generated the texture upside down, so flip it
304 output.RotateFlip(RotateFlipType.RotateNoneFlipY);
305
306 #endregion Texture Compositing
307
308 return output;
309 }
310
311 public static Bitmap SplatSimple(float[] heightmap)
312 {
313 const float BASE_HSV_H = 93f / 360f;
314 const float BASE_HSV_S = 44f / 100f;
315 const float BASE_HSV_V = 34f / 100f;
316
317 Bitmap img = new Bitmap(256, 256);
318 BitmapData bitmapData = img.LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
319
320 unsafe
321 {
322 for (int y = 255; y >= 0; y--)
323 {
324 for (int x = 0; x < 256; x++)
325 {
326 float normHeight = heightmap[y * 256 + x] / 255f;
327 normHeight = Utils.Clamp(normHeight, BASE_HSV_V, 1.0f);
328
329 Color4 color = Color4.FromHSV(BASE_HSV_H, BASE_HSV_S, normHeight);
330
331 byte* ptr = (byte*)bitmapData.Scan0 + y * bitmapData.Stride + x * 3;
332 *(ptr + 0) = (byte)(color.B * 255f);
333 *(ptr + 1) = (byte)(color.G * 255f);
334 *(ptr + 2) = (byte)(color.R * 255f);
335 }
336 }
337 }
338
339 img.UnlockBits(bitmapData);
340 return img;
341 }
342 }
343}
diff --git a/OpenSim/Region/CoreModules/World/Warp3DMap/Viewport.cs b/OpenSim/Region/CoreModules/World/Warp3DMap/Viewport.cs
new file mode 100644
index 0000000..472f86e
--- /dev/null
+++ b/OpenSim/Region/CoreModules/World/Warp3DMap/Viewport.cs
@@ -0,0 +1,165 @@
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
28using System;
29using System.Drawing;
30using OpenMetaverse;
31
32namespace OpenSim.Region.CoreModules.World.Warp3DMap
33{
34 public class Viewport
35 {
36 private const float DEG_TO_RAD = (float)Math.PI / 180f;
37 private static readonly Vector3 UP_DIRECTION = Vector3.UnitZ;
38
39 public Vector3 Position;
40 public Vector3 LookDirection;
41 public float FieldOfView;
42 public float NearPlaneDistance;
43 public float FarPlaneDistance;
44 public int Width;
45 public int Height;
46 public bool Orthographic;
47 public float OrthoWindowWidth;
48 public float OrthoWindowHeight;
49
50 public Viewport(Vector3 position, Vector3 lookDirection, float fieldOfView, float farPlaneDist, float nearPlaneDist, int width, int height)
51 {
52 // Perspective projection mode
53 Position = position;
54 LookDirection = lookDirection;
55 FieldOfView = fieldOfView;
56 FarPlaneDistance = farPlaneDist;
57 NearPlaneDistance = nearPlaneDist;
58 Width = width;
59 Height = height;
60 }
61
62 public Viewport(Vector3 position, Vector3 lookDirection, float farPlaneDist, float nearPlaneDist, int width, int height, float orthoWindowWidth, float orthoWindowHeight)
63 {
64 // Orthographic projection mode
65 Position = position;
66 LookDirection = lookDirection;
67 FarPlaneDistance = farPlaneDist;
68 NearPlaneDistance = nearPlaneDist;
69 Width = width;
70 Height = height;
71 OrthoWindowWidth = orthoWindowWidth;
72 OrthoWindowHeight = orthoWindowHeight;
73 Orthographic = true;
74 }
75
76 public Point VectorToScreen(Vector3 v)
77 {
78 Matrix4 m = GetWorldToViewportMatrix();
79 Vector3 screenPoint = v * m;
80 return new Point((int)screenPoint.X, (int)screenPoint.Y);
81 }
82
83 public Matrix4 GetWorldToViewportMatrix()
84 {
85 Matrix4 result = GetViewMatrix();
86 result *= GetPerspectiveProjectionMatrix();
87 result *= GetViewportMatrix();
88
89 return result;
90 }
91
92 public Matrix4 GetViewMatrix()
93 {
94 Vector3 zAxis = -LookDirection;
95 zAxis.Normalize();
96
97 Vector3 xAxis = Vector3.Cross(UP_DIRECTION, zAxis);
98 xAxis.Normalize();
99
100 Vector3 yAxis = Vector3.Cross(zAxis, xAxis);
101
102 Vector3 position = Position;
103 float offsetX = -Vector3.Dot(xAxis, position);
104 float offsetY = -Vector3.Dot(yAxis, position);
105 float offsetZ = -Vector3.Dot(zAxis, position);
106
107 return new Matrix4(
108 xAxis.X, yAxis.X, zAxis.X, 0f,
109 xAxis.Y, yAxis.Y, zAxis.Y, 0f,
110 xAxis.Z, yAxis.Z, zAxis.Z, 0f,
111 offsetX, offsetY, offsetZ, 1f);
112 }
113
114 public Matrix4 GetPerspectiveProjectionMatrix()
115 {
116 float aspectRatio = (float)Width / (float)Height;
117
118 float hFoV = FieldOfView * DEG_TO_RAD;
119 float zn = NearPlaneDistance;
120 float zf = FarPlaneDistance;
121
122 float xScale = 1f / (float)Math.Tan(hFoV / 2f);
123 float yScale = aspectRatio * xScale;
124 float m33 = (zf == double.PositiveInfinity) ? -1 : (zf / (zn - zf));
125 float m43 = zn * m33;
126
127 return new Matrix4(
128 xScale, 0f, 0f, 0f,
129 0f, yScale, 0f, 0f,
130 0f, 0f, m33, -1f,
131 0f, 0f, m43, 0f);
132 }
133
134 public Matrix4 GetOrthographicProjectionMatrix(float aspectRatio)
135 {
136 float w = Width;
137 float h = Height;
138 float zn = NearPlaneDistance;
139 float zf = FarPlaneDistance;
140
141 float m33 = 1 / (zn - zf);
142 float m43 = zn * m33;
143
144 return new Matrix4(
145 2f / w, 0f, 0f, 0f,
146 0f, 2f / h, 0f, 0f,
147 0f, 0f, m33, 0f,
148 0f, 0f, m43, 1f);
149 }
150
151 public Matrix4 GetViewportMatrix()
152 {
153 float scaleX = (float)Width * 0.5f;
154 float scaleY = (float)Height * 0.5f;
155 float offsetX = 0f + scaleX;
156 float offsetY = 0f + scaleY;
157
158 return new Matrix4(
159 scaleX, 0f, 0f, 0f,
160 0f, -scaleY, 0f, 0f,
161 0f, 0f, 1f, 0f,
162 offsetX, offsetY, 0f, 1f);
163 }
164 }
165}