From 180be7de07014aa33bc6066f12a0819b731c1c9d Mon Sep 17 00:00:00 2001 From: Dr Scofield Date: Tue, 10 Feb 2009 13:10:57 +0000 Subject: 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 --- .../World/WorldMap/IMapTileTerrainRenderer.cs | 39 + .../CoreModules/World/WorldMap/MapImageModule.cs | 586 +++++++++++++ .../CoreModules/World/WorldMap/MapSearchModule.cs | 172 ++++ .../World/WorldMap/ShadedMapTileRenderer.cs | 249 ++++++ .../World/WorldMap/TexturedMapTileRenderer.cs | 411 ++++++++++ .../CoreModules/World/WorldMap/WorldMapModule.cs | 905 +++++++++++++++++++++ 6 files changed, 2362 insertions(+) create mode 100644 OpenSim/Region/CoreModules/World/WorldMap/IMapTileTerrainRenderer.cs create mode 100644 OpenSim/Region/CoreModules/World/WorldMap/MapImageModule.cs create mode 100644 OpenSim/Region/CoreModules/World/WorldMap/MapSearchModule.cs create mode 100644 OpenSim/Region/CoreModules/World/WorldMap/ShadedMapTileRenderer.cs create mode 100644 OpenSim/Region/CoreModules/World/WorldMap/TexturedMapTileRenderer.cs create mode 100644 OpenSim/Region/CoreModules/World/WorldMap/WorldMapModule.cs (limited to 'OpenSim/Region/CoreModules/World/WorldMap') diff --git a/OpenSim/Region/CoreModules/World/WorldMap/IMapTileTerrainRenderer.cs b/OpenSim/Region/CoreModules/World/WorldMap/IMapTileTerrainRenderer.cs new file mode 100644 index 0000000..3684df0 --- /dev/null +++ b/OpenSim/Region/CoreModules/World/WorldMap/IMapTileTerrainRenderer.cs @@ -0,0 +1,39 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSim Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System.Drawing; +using OpenSim.Region.Framework.Scenes; +using Nini.Config; + +namespace OpenSim.Region.CoreModules.World.WorldMap +{ + public interface IMapTileTerrainRenderer + { + void Initialise(Scene scene, IConfigSource config); + void TerrainToBitmap(Bitmap mapbmp); + } +} diff --git a/OpenSim/Region/CoreModules/World/WorldMap/MapImageModule.cs b/OpenSim/Region/CoreModules/World/WorldMap/MapImageModule.cs new file mode 100644 index 0000000..eea6cf6 --- /dev/null +++ b/OpenSim/Region/CoreModules/World/WorldMap/MapImageModule.cs @@ -0,0 +1,586 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSim Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using System.Reflection; +using Nini.Config; +using OpenMetaverse.Imaging; +using log4net; +using OpenSim.Region.Framework.Interfaces; +using OpenSim.Region.Framework.Scenes; +using OpenMetaverse; + +namespace OpenSim.Region.CoreModules.World.WorldMap +{ + public enum DrawRoutine + { + Rectangle, + Polygon, + Ellipse + } + + public struct face + { + public Point[] pts; + } + + public struct DrawStruct + { + public DrawRoutine dr; + public Rectangle rect; + public SolidBrush brush; + public face[] trns; + } + + public class MapImageModule : IMapImageGenerator, IRegionModule + { + private static readonly ILog m_log = + LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private Scene m_scene; + private IConfigSource m_config; + private IMapTileTerrainRenderer terrainRenderer; + + #region IMapImageGenerator Members + + public byte[] WriteJpeg2000Image(string gradientmap) + { + byte[] imageData = null; + + bool drawPrimVolume = true; + bool textureTerrain = true; + + try + { + IConfig startupConfig = m_config.Configs["Startup"]; + drawPrimVolume = startupConfig.GetBoolean("DrawPrimOnMapTile", drawPrimVolume); + textureTerrain = startupConfig.GetBoolean("TextureOnMapTile", textureTerrain); + } + catch + { + m_log.Warn("[MAPTILE]: Failed to load StartupConfig"); + } + + if (textureTerrain) + { + terrainRenderer = new TexturedMapTileRenderer(); + } + else + { + terrainRenderer = new ShadedMapTileRenderer(); + } + terrainRenderer.Initialise(m_scene, m_config); + + Bitmap mapbmp = new Bitmap(256, 256); + //long t = System.Environment.TickCount; + //for (int i = 0; i < 10; ++i) { + terrainRenderer.TerrainToBitmap(mapbmp); + //} + //t = System.Environment.TickCount - t; + //m_log.InfoFormat("[MAPTILE] generation of 10 maptiles needed {0} ms", t); + + + if (drawPrimVolume) + { + DrawObjectVolume(m_scene, mapbmp); + } + + try + { + imageData = OpenJPEG.EncodeFromImage(mapbmp, true); + } + catch (Exception e) // LEGIT: Catching problems caused by OpenJPEG p/invoke + { + Console.WriteLine("Failed generating terrain map: " + e); + } + + return imageData; + } + + #endregion + + #region IRegionModule Members + + public void Initialise(Scene scene, IConfigSource source) + { + m_scene = scene; + m_config = source; + + IConfig startupConfig = m_config.Configs["Startup"]; + if (startupConfig.GetString("MapImageModule", "MapImageModule") != + "MapImageModule") + return; + + m_scene.RegisterModuleInterface(this); + } + + public void PostInitialise() + { + } + + public void Close() + { + } + + public string Name + { + get { return "MapImageModule"; } + } + + public bool IsSharedModule + { + get { return false; } + } + + #endregion + +// TODO: unused: +// private void ShadeBuildings(Bitmap map) +// { +// lock (map) +// { +// lock (m_scene.Entities) +// { +// foreach (EntityBase entity in m_scene.Entities.Values) +// { +// if (entity is SceneObjectGroup) +// { +// SceneObjectGroup sog = (SceneObjectGroup) entity; +// +// foreach (SceneObjectPart primitive in sog.Children.Values) +// { +// int x = (int) (primitive.AbsolutePosition.X - (primitive.Scale.X / 2)); +// int y = (int) (primitive.AbsolutePosition.Y - (primitive.Scale.Y / 2)); +// int w = (int) primitive.Scale.X; +// int h = (int) primitive.Scale.Y; +// +// int dx; +// for (dx = x; dx < x + w; dx++) +// { +// int dy; +// for (dy = y; dy < y + h; dy++) +// { +// if (x < 0 || y < 0) +// continue; +// if (x >= map.Width || y >= map.Height) +// continue; +// +// map.SetPixel(dx, dy, Color.DarkGray); +// } +// } +// } +// } +// } +// } +// } +// } + + private Bitmap DrawObjectVolume(Scene whichScene, Bitmap mapbmp) + { + int tc = 0; + double[,] hm = whichScene.Heightmap.GetDoubles(); + tc = System.Environment.TickCount; + m_log.Info("[MAPTILE]: Generating Maptile Step 2: Object Volume Profile"); + List objs = whichScene.GetEntities(); + Dictionary z_sort = new Dictionary(); + //SortedList z_sort = new SortedList(); + List z_sortheights = new List(); + List z_localIDs = new List(); + + lock (objs) + { + foreach (EntityBase obj in objs) + { + // Only draw the contents of SceneObjectGroup + if (obj is SceneObjectGroup) + { + SceneObjectGroup mapdot = (SceneObjectGroup)obj; + Color mapdotspot = Color.Gray; // Default color when prim color is white + // Loop over prim in group + foreach (SceneObjectPart part in mapdot.Children.Values) + { + if (part == null) + continue; + + // Draw if the object is at least 1 meter wide in any direction + if (part.Scale.X > 1f || part.Scale.Y > 1f || part.Scale.Z > 1f) + { + // Try to get the RGBA of the default texture entry.. + // + try + { + // get the null checks out of the way + // skip the ones that break + if (part == null) + continue; + + if (part.Shape == null) + continue; + + if (part.Shape.PCode == (byte)PCode.Tree || part.Shape.PCode == (byte)PCode.NewTree || part.Shape.PCode == (byte)PCode.Grass) + continue; // eliminates trees from this since we don't really have a good tree representation + // if you want tree blocks on the map comment the above line and uncomment the below line + //mapdotspot = Color.PaleGreen; + + if (part.Shape.Textures == null) + continue; + + if (part.Shape.Textures.DefaultTexture == null) + continue; + + Color4 texcolor = part.Shape.Textures.DefaultTexture.RGBA; + + // Not sure why some of these are null, oh well. + + int colorr = 255 - (int)(texcolor.R * 255f); + int colorg = 255 - (int)(texcolor.G * 255f); + int colorb = 255 - (int)(texcolor.B * 255f); + + if (!(colorr == 255 && colorg == 255 && colorb == 255)) + { + //Try to set the map spot color + try + { + // If the color gets goofy somehow, skip it *shakes fist at Color4 + mapdotspot = Color.FromArgb(colorr, colorg, colorb); + } + catch (ArgumentException) + { + } + } + } + catch (IndexOutOfRangeException) + { + // Windows Array + } + catch (ArgumentOutOfRangeException) + { + // Mono Array + } + + Vector3 pos = part.GetWorldPosition(); + + // skip prim outside of retion + if (pos.X < 0f || pos.X > 256f || pos.Y < 0f || pos.Y > 256f) + continue; + + // skip prim in non-finite position + if (Single.IsNaN(pos.X) || Single.IsNaN(pos.Y) || + Single.IsInfinity(pos.X) || Single.IsInfinity(pos.Y)) + continue; + + // Figure out if object is under 256m above the height of the terrain + bool isBelow256AboveTerrain = false; + + try + { + isBelow256AboveTerrain = (pos.Z < ((float)hm[(int)pos.X, (int)pos.Y] + 256f)); + } + catch (Exception) + { + } + + if (isBelow256AboveTerrain) + { + // Translate scale by rotation so scale is represented properly when object is rotated + Vector3 lscale = new Vector3(part.Shape.Scale.X, part.Shape.Scale.Y, part.Shape.Scale.Z); + Vector3 scale = new Vector3(); + Vector3 tScale = new Vector3(); + Vector3 axPos = new Vector3(pos.X,pos.Y,pos.Z); + + Quaternion llrot = part.GetWorldRotation(); + Quaternion rot = new Quaternion(llrot.W, llrot.X, llrot.Y, llrot.Z); + scale = lscale * rot; + + // negative scales don't work in this situation + scale.X = Math.Abs(scale.X); + scale.Y = Math.Abs(scale.Y); + scale.Z = Math.Abs(scale.Z); + + // This scaling isn't very accurate and doesn't take into account the face rotation :P + int mapdrawstartX = (int)(pos.X - scale.X); + int mapdrawstartY = (int)(pos.Y - scale.Y); + int mapdrawendX = (int)(pos.X + scale.X); + int mapdrawendY = (int)(pos.Y + scale.Y); + + // If object is beyond the edge of the map, don't draw it to avoid errors + if (mapdrawstartX < 0 || mapdrawstartX > 255 || mapdrawendX < 0 || mapdrawendX > 255 + || mapdrawstartY < 0 || mapdrawstartY > 255 || mapdrawendY < 0 + || mapdrawendY > 255) + continue; + +#region obb face reconstruction part duex + Vector3[] vertexes = new Vector3[8]; + + // float[] distance = new float[6]; + Vector3[] FaceA = new Vector3[6]; // vertex A for Facei + Vector3[] FaceB = new Vector3[6]; // vertex B for Facei + Vector3[] FaceC = new Vector3[6]; // vertex C for Facei + Vector3[] FaceD = new Vector3[6]; // vertex D for Facei + + tScale = new Vector3(lscale.X, -lscale.Y, lscale.Z); + scale = ((tScale * rot)); + vertexes[0] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z))); + // vertexes[0].x = pos.X + vertexes[0].x; + //vertexes[0].y = pos.Y + vertexes[0].y; + //vertexes[0].z = pos.Z + vertexes[0].z; + + FaceA[0] = vertexes[0]; + FaceB[3] = vertexes[0]; + FaceA[4] = vertexes[0]; + + tScale = lscale; + scale = ((tScale * rot)); + vertexes[1] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z))); + + // vertexes[1].x = pos.X + vertexes[1].x; + // vertexes[1].y = pos.Y + vertexes[1].y; + //vertexes[1].z = pos.Z + vertexes[1].z; + + FaceB[0] = vertexes[1]; + FaceA[1] = vertexes[1]; + FaceC[4] = vertexes[1]; + + tScale = new Vector3(lscale.X, -lscale.Y, -lscale.Z); + scale = ((tScale * rot)); + + vertexes[2] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z))); + + //vertexes[2].x = pos.X + vertexes[2].x; + //vertexes[2].y = pos.Y + vertexes[2].y; + //vertexes[2].z = pos.Z + vertexes[2].z; + + FaceC[0] = vertexes[2]; + FaceD[3] = vertexes[2]; + FaceC[5] = vertexes[2]; + + tScale = new Vector3(lscale.X, lscale.Y, -lscale.Z); + scale = ((tScale * rot)); + vertexes[3] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z))); + + //vertexes[3].x = pos.X + vertexes[3].x; + // vertexes[3].y = pos.Y + vertexes[3].y; + // vertexes[3].z = pos.Z + vertexes[3].z; + + FaceD[0] = vertexes[3]; + FaceC[1] = vertexes[3]; + FaceA[5] = vertexes[3]; + + tScale = new Vector3(-lscale.X, lscale.Y, lscale.Z); + scale = ((tScale * rot)); + vertexes[4] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z))); + + // vertexes[4].x = pos.X + vertexes[4].x; + // vertexes[4].y = pos.Y + vertexes[4].y; + // vertexes[4].z = pos.Z + vertexes[4].z; + + FaceB[1] = vertexes[4]; + FaceA[2] = vertexes[4]; + FaceD[4] = vertexes[4]; + + tScale = new Vector3(-lscale.X, lscale.Y, -lscale.Z); + scale = ((tScale * rot)); + vertexes[5] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z))); + + // vertexes[5].x = pos.X + vertexes[5].x; + // vertexes[5].y = pos.Y + vertexes[5].y; + // vertexes[5].z = pos.Z + vertexes[5].z; + + FaceD[1] = vertexes[5]; + FaceC[2] = vertexes[5]; + FaceB[5] = vertexes[5]; + + tScale = new Vector3(-lscale.X, -lscale.Y, lscale.Z); + scale = ((tScale * rot)); + vertexes[6] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z))); + + // vertexes[6].x = pos.X + vertexes[6].x; + // vertexes[6].y = pos.Y + vertexes[6].y; + // vertexes[6].z = pos.Z + vertexes[6].z; + + FaceB[2] = vertexes[6]; + FaceA[3] = vertexes[6]; + FaceB[4] = vertexes[6]; + + tScale = new Vector3(-lscale.X, -lscale.Y, -lscale.Z); + scale = ((tScale * rot)); + vertexes[7] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z))); + + // vertexes[7].x = pos.X + vertexes[7].x; + // vertexes[7].y = pos.Y + vertexes[7].y; + // vertexes[7].z = pos.Z + vertexes[7].z; + + FaceD[2] = vertexes[7]; + FaceC[3] = vertexes[7]; + FaceD[5] = vertexes[7]; +#endregion + + //int wy = 0; + + //bool breakYN = false; // If we run into an error drawing, break out of the + // loop so we don't lag to death on error handling + DrawStruct ds = new DrawStruct(); + ds.brush = new SolidBrush(mapdotspot); + //ds.rect = new Rectangle(mapdrawstartX, (255 - mapdrawstartY), mapdrawendX - mapdrawstartX, mapdrawendY - mapdrawstartY); + + ds.trns = new face[FaceA.Length]; + + for (int i = 0; i < FaceA.Length; i++) + { + Point[] working = new Point[5]; + working[0] = project(FaceA[i], axPos); + working[1] = project(FaceB[i], axPos); + working[2] = project(FaceD[i], axPos); + working[3] = project(FaceC[i], axPos); + working[4] = project(FaceA[i], axPos); + + face workingface = new face(); + workingface.pts = working; + + ds.trns[i] = workingface; + } + + z_sort.Add(part.LocalId, ds); + z_localIDs.Add(part.LocalId); + z_sortheights.Add(pos.Z); + + //for (int wx = mapdrawstartX; wx < mapdrawendX; wx++) + //{ + //for (wy = mapdrawstartY; wy < mapdrawendY; wy++) + //{ + //m_log.InfoFormat("[MAPDEBUG]: {0},{1}({2})", wx, (255 - wy),wy); + //try + //{ + // Remember, flip the y! + // mapbmp.SetPixel(wx, (255 - wy), mapdotspot); + //} + //catch (ArgumentException) + //{ + // breakYN = true; + //} + + //if (breakYN) + // break; + //} + + //if (breakYN) + // break; + //} + } // Object is within 256m Z of terrain + } // object is at least a meter wide + } // loop over group children + } // entitybase is sceneobject group + } // foreach loop over entities + + float[] sortedZHeights = z_sortheights.ToArray(); + uint[] sortedlocalIds = z_localIDs.ToArray(); + + // Sort prim by Z position + Array.Sort(sortedZHeights, sortedlocalIds); + + Graphics g = Graphics.FromImage(mapbmp); + + for (int s = 0; s < sortedZHeights.Length; s++) + { + if (z_sort.ContainsKey(sortedlocalIds[s])) + { + DrawStruct rectDrawStruct = z_sort[sortedlocalIds[s]]; + for (int r = 0; r < rectDrawStruct.trns.Length; r++ ) + { + g.FillPolygon(rectDrawStruct.brush,rectDrawStruct.trns[r].pts); + } + //g.FillRectangle(rectDrawStruct.brush , rectDrawStruct.rect); + } + } + + g.Dispose(); + } // lock entities objs + + m_log.Info("[MAPTILE]: Generating Maptile Step 2: Done in " + (System.Environment.TickCount - tc) + " ms"); + return mapbmp; + } + + private Point project(Vector3 point3d, Vector3 originpos) + { + Point returnpt = new Point(); + //originpos = point3d; + //int d = (int)(256f / 1.5f); + + //Vector3 topos = new Vector3(0, 0, 0); + // float z = -point3d.z - topos.z; + + returnpt.X = (int)point3d.X;//(int)((topos.x - point3d.x) / z * d); + returnpt.Y = (int)(255 - point3d.Y);//(int)(255 - (((topos.y - point3d.y) / z * d))); + + return returnpt; + } + +// TODO: unused: +// #region Deprecated Maptile Generation. Adam may update this +// private Bitmap TerrainToBitmap(string gradientmap) +// { +// Bitmap gradientmapLd = new Bitmap(gradientmap); +// +// int pallete = gradientmapLd.Height; +// +// Bitmap bmp = new Bitmap(m_scene.Heightmap.Width, m_scene.Heightmap.Height); +// Color[] colours = new Color[pallete]; +// +// for (int i = 0; i < pallete; i++) +// { +// colours[i] = gradientmapLd.GetPixel(0, i); +// } +// +// lock (m_scene.Heightmap) +// { +// ITerrainChannel copy = m_scene.Heightmap; +// for (int y = 0; y < copy.Height; y++) +// { +// for (int x = 0; x < copy.Width; x++) +// { +// // 512 is the largest possible height before colours clamp +// int colorindex = (int) (Math.Max(Math.Min(1.0, copy[x, y] / 512.0), 0.0) * (pallete - 1)); +// +// // Handle error conditions +// if (colorindex > pallete - 1 || colorindex < 0) +// bmp.SetPixel(x, copy.Height - y - 1, Color.Red); +// else +// bmp.SetPixel(x, copy.Height - y - 1, colours[colorindex]); +// } +// } +// ShadeBuildings(bmp); +// return bmp; +// } +// } +// #endregion + } +} diff --git a/OpenSim/Region/CoreModules/World/WorldMap/MapSearchModule.cs b/OpenSim/Region/CoreModules/World/WorldMap/MapSearchModule.cs new file mode 100644 index 0000000..45a99a9 --- /dev/null +++ b/OpenSim/Region/CoreModules/World/WorldMap/MapSearchModule.cs @@ -0,0 +1,172 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSim Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +using System; +using System.Reflection; +using System.Collections.Generic; +using System.Net; +using OpenSim.Framework; +using OpenSim.Region.Framework.Interfaces; +using OpenSim.Region.Framework.Scenes; +using OpenSim.Region.Framework.Scenes.Hypergrid; +using OpenMetaverse; +using log4net; +using Nini.Config; + +namespace OpenSim.Region.CoreModules.World.WorldMap +{ + public class MapSearchModule : IRegionModule + { + private static readonly ILog m_log = + LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + Scene m_scene = null; // only need one for communication with GridService + List m_scenes = new List(); + + #region IRegionModule Members + public void Initialise(Scene scene, IConfigSource source) + { + if (m_scene == null) + { + m_scene = scene; + } + + m_scenes.Add(scene); + scene.EventManager.OnNewClient += OnNewClient; + } + + public void PostInitialise() + { + } + + public void Close() + { + m_scene = null; + m_scenes.Clear(); + } + + public string Name + { + get { return "MapSearchModule"; } + } + + public bool IsSharedModule + { + get { return true; } + } + + #endregion + + private void OnNewClient(IClientAPI client) + { + client.OnMapNameRequest += OnMapNameRequest; + } + + private void OnMapNameRequest(IClientAPI remoteClient, string mapName) + { + if (mapName.Length < 3) + { + remoteClient.SendAlertMessage("Use a search string with at least 3 characters"); + return; + } + + // try to fetch from GridServer + List regionInfos = m_scene.SceneGridService.RequestNamedRegions(mapName, 20); + if (regionInfos == null) + { + m_log.Warn("[MAPSEARCHMODULE]: RequestNamedRegions returned null. Old gridserver?"); + // service wasn't available; maybe still an old GridServer. Try the old API, though it will return only one region + regionInfos = new List(); + RegionInfo info = m_scene.SceneGridService.RequestClosestRegion(mapName); + if (info != null) regionInfos.Add(info); + } + + if ((regionInfos.Count == 0) && IsHypergridOn()) + { + // OK, we tried but there are no regions matching that name. + // Let's check quickly if this is a domain name, and if so link to it + if (mapName.Contains(".") && mapName.Contains(":")) + { + // It probably is a domain name. Try to link to it. + RegionInfo regInfo; + Scene cScene = GetClientScene(remoteClient); + regInfo = HGHyperlink.TryLinkRegion(cScene, remoteClient, mapName); + if (regInfo != null) + regionInfos.Add(regInfo); + } + } + + List blocks = new List(); + + MapBlockData data; + if (regionInfos.Count > 0) + { + foreach (RegionInfo info in regionInfos) + { + data = new MapBlockData(); + data.Agents = 0; + data.Access = 21; // TODO what's this? + data.MapImageId = info.RegionSettings.TerrainImageID; + data.Name = info.RegionName; + data.RegionFlags = 0; // TODO not used? + data.WaterHeight = 0; // not used + data.X = (ushort)info.RegionLocX; + data.Y = (ushort)info.RegionLocY; + blocks.Add(data); + } + } + + // final block, closing the search result + data = new MapBlockData(); + data.Agents = 0; + data.Access = 255; + data.MapImageId = UUID.Zero; + data.Name = mapName; + data.RegionFlags = 0; + data.WaterHeight = 0; // not used + data.X = 0; + data.Y = 0; + blocks.Add(data); + + remoteClient.SendMapBlock(blocks, 0); + } + + private bool IsHypergridOn() + { + return (m_scene.SceneGridService is HGSceneCommunicationService); + } + + private Scene GetClientScene(IClientAPI client) + { + foreach (Scene s in m_scenes) + { + if (client.Scene.RegionInfo.RegionHandle == s.RegionInfo.RegionHandle) + return s; + } + return m_scene; + } + } +} diff --git a/OpenSim/Region/CoreModules/World/WorldMap/ShadedMapTileRenderer.cs b/OpenSim/Region/CoreModules/World/WorldMap/ShadedMapTileRenderer.cs new file mode 100644 index 0000000..b783d7c --- /dev/null +++ b/OpenSim/Region/CoreModules/World/WorldMap/ShadedMapTileRenderer.cs @@ -0,0 +1,249 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSim Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using System.Reflection; +using OpenMetaverse; +using OpenMetaverse.Imaging; +using Nini.Config; +using log4net; +using OpenSim.Region.Framework.Interfaces; +using OpenSim.Region.Framework.Scenes; + +namespace OpenSim.Region.CoreModules.World.WorldMap +{ + public class ShadedMapTileRenderer : IMapTileTerrainRenderer + { + private static readonly ILog m_log = + LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private Scene m_scene; + //private IConfigSource m_config; // not used currently + + public void Initialise(Scene scene, IConfigSource config) + { + m_scene = scene; + // m_config = config; // not used currently + } + + public void TerrainToBitmap(Bitmap mapbmp) + { + int tc = System.Environment.TickCount; + m_log.Info("[MAPTILE]: Generating Maptile Step 1: Terrain"); + + double[,] hm = m_scene.Heightmap.GetDoubles(); + bool ShadowDebugContinue = true; + + bool terraincorruptedwarningsaid = false; + + float low = 255; + float high = 0; + for (int x = 0; x < 256; x++) + { + for (int y = 0; y < 256; y++) + { + float hmval = (float)hm[x, y]; + if (hmval < low) + low = hmval; + if (hmval > high) + high = hmval; + } + } + + float waterHeight = (float)m_scene.RegionInfo.RegionSettings.WaterHeight; + + for (int x = 0; x < 256; x++) + { + for (int y = 0; y < 256; y++) + { + // Y flip the cordinates for the bitmap: hf origin is lower left, bm origin is upper left + int yr = 255 - y; + + float heightvalue = (float)hm[x, y]; + + if (heightvalue > waterHeight) + { + // scale height value + // No, that doesn't scale it: + // heightvalue = low + mid * (heightvalue - low) / mid; => low + (heightvalue - low) * mid / mid = low + (heightvalue - low) * 1 = low + heightvalue - low = heightvalue + + if (Single.IsInfinity(heightvalue) || Single.IsNaN(heightvalue)) + heightvalue = 0; + else if (heightvalue > 255f) + heightvalue = 255f; + else if (heightvalue < 0f) + heightvalue = 0f; + + Color color = Color.FromArgb((int)heightvalue, 100, (int)heightvalue); + + mapbmp.SetPixel(x, yr, color); + + try + { + //X + // . + // + // Shade the terrain for shadows + if (x < 255 && yr < 255) + { + float hfvalue = (float)hm[x, y]; + float hfvaluecompare = 0f; + + if ((x + 1 < 256) && (y + 1 < 256)) + { + hfvaluecompare = (float)hm[x + 1, y + 1]; // light from north-east => look at land height there + } + if (Single.IsInfinity(hfvalue) || Single.IsNaN(hfvalue)) + hfvalue = 0f; + + if (Single.IsInfinity(hfvaluecompare) || Single.IsNaN(hfvaluecompare)) + hfvaluecompare = 0f; + + float hfdiff = hfvalue - hfvaluecompare; // => positive if NE is lower, negative if here is lower + + int hfdiffi = 0; + int hfdiffihighlight = 0; + float highlightfactor = 0.18f; + + try + { + // hfdiffi = Math.Abs((int)((hfdiff * 4) + (hfdiff * 0.5))) + 1; + hfdiffi = Math.Abs((int)(hfdiff * 4.5f)) + 1; + if (hfdiff % 1f != 0) + { + // hfdiffi = hfdiffi + Math.Abs((int)(((hfdiff % 1) * 0.5f) * 10f) - 1); + hfdiffi = hfdiffi + Math.Abs((int)((hfdiff % 1f) * 5f) - 1); + } + + hfdiffihighlight = Math.Abs((int)((hfdiff * highlightfactor) * 4.5f)) + 1; + if (hfdiff % 1f != 0) + { + // hfdiffi = hfdiffi + Math.Abs((int)(((hfdiff % 1) * 0.5f) * 10f) - 1); + hfdiffihighlight = hfdiffihighlight + Math.Abs((int)(((hfdiff * highlightfactor) % 1f) * 5f) - 1); + } + } + catch (System.OverflowException) + { + m_log.Debug("[MAPTILE]: Shadow failed at value: " + hfdiff.ToString()); + ShadowDebugContinue = false; + } + + if (hfdiff > 0.3f) + { + // NE is lower than here + // We have to desaturate and lighten the land at the same time + // we use floats, colors use bytes, so shrink are space down to + // 0-255 + + if (ShadowDebugContinue) + { + int r = color.R; + int g = color.G; + int b = color.B; + color = Color.FromArgb((r + hfdiffihighlight < 255) ? r + hfdiffihighlight : 255, + (g + hfdiffihighlight < 255) ? g + hfdiffihighlight : 255, + (b + hfdiffihighlight < 255) ? b + hfdiffihighlight : 255); + } + } + else if (hfdiff < -0.3f) + { + // here is lower than NE: + // We have to desaturate and blacken the land at the same time + // we use floats, colors use bytes, so shrink are space down to + // 0-255 + + if (ShadowDebugContinue) + { + if ((x - 1 > 0) && (yr + 1 < 256)) + { + color = mapbmp.GetPixel(x - 1, yr + 1); + int r = color.R; + int g = color.G; + int b = color.B; + color = Color.FromArgb((r - hfdiffi > 0) ? r - hfdiffi : 0, + (g - hfdiffi > 0) ? g - hfdiffi : 0, + (b - hfdiffi > 0) ? b - hfdiffi : 0); + + mapbmp.SetPixel(x-1, yr+1, color); + } + } + } + } + } + catch (System.ArgumentException) + { + if (!terraincorruptedwarningsaid) + { + 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); + terraincorruptedwarningsaid = true; + } + color = Color.Black; + mapbmp.SetPixel(x, yr, color); + } + } + else + { + // We're under the water level with the terrain, so paint water instead of land + + // Y flip the cordinates + heightvalue = waterHeight - heightvalue; + if (Single.IsInfinity(heightvalue) || Single.IsNaN(heightvalue)) + heightvalue = 0f; + else if (heightvalue > 19f) + heightvalue = 19f; + else if (heightvalue < 0f) + heightvalue = 0f; + + heightvalue = 100f - (heightvalue * 100f) / 19f; + + try + { + Color water = Color.FromArgb((int)heightvalue, (int)heightvalue, 255); + mapbmp.SetPixel(x, yr, water); + } + catch (System.ArgumentException) + { + if (!terraincorruptedwarningsaid) + { + 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); + terraincorruptedwarningsaid = true; + } + Color black = Color.Black; + mapbmp.SetPixel(x, (256 - y) - 1, black); + } + } + } + } + m_log.Info("[MAPTILE]: Generating Maptile Step 1: Done in " + (System.Environment.TickCount - tc) + " ms"); + } + } +} 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 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSim Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using System.Reflection; +using OpenMetaverse; +using Nini.Config; +using log4net; +using OpenMetaverse.Imaging; +using OpenSim.Framework; +using OpenSim.Region.Framework.Interfaces; +using OpenSim.Region.Framework.Scenes; +using OpenSim.Region.CoreModules.World.Terrain; + +namespace OpenSim.Region.CoreModules.World.WorldMap +{ + // Hue, Saturation, Value; used for color-interpolation + struct HSV { + public float h; + public float s; + public float v; + + public HSV(float h, float s, float v) + { + this.h = h; + this.s = s; + this.v = v; + } + + // (for info about algorithm, see http://en.wikipedia.org/wiki/HSL_and_HSV) + public HSV(Color c) + { + float r = c.R / 255f; + float g = c.G / 255f; + float b = c.B / 255f; + float max = Math.Max(Math.Max(r, g), b); + float min = Math.Min(Math.Min(r, g), b); + float diff = max - min; + + if (max == min) h = 0f; + else if (max == r) h = (g - b) / diff * 60f; + else if (max == g) h = (b - r) / diff * 60f + 120f; + else h = (r - g) / diff * 60f + 240f; + if (h < 0f) h += 360f; + + if (max == 0f) s = 0f; + else s = diff / max; + + v = max; + } + + // (for info about algorithm, see http://en.wikipedia.org/wiki/HSL_and_HSV) + public Color toColor() + { + if (s < 0f) Console.WriteLine("S < 0: " + s); + else if (s > 1f) Console.WriteLine("S > 1: " + s); + if (v < 0f) Console.WriteLine("V < 0: " + v); + else if (v > 1f) Console.WriteLine("V > 1: " + v); + + float f = h / 60f; + int sector = (int)f % 6; + f = f - (int)f; + int pi = (int)(v * (1f - s) * 255f); + int qi = (int)(v * (1f - s * f) * 255f); + int ti = (int)(v * (1f - (1f - f) * s) * 255f); + int vi = (int)(v * 255f); + + switch (sector) + { + case 0: + return Color.FromArgb(vi, ti, pi); + case 1: + return Color.FromArgb(qi, vi, pi); + case 2: + return Color.FromArgb(pi, vi, ti); + case 3: + return Color.FromArgb(pi, qi, vi); + case 4: + return Color.FromArgb(ti, pi, vi); + default: + return Color.FromArgb(vi, pi, qi); + } + } + } + + public class TexturedMapTileRenderer : IMapTileTerrainRenderer + { + #region Constants + + private static readonly ILog m_log = + LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + // some hardcoded terrain UUIDs that work with SL 1.20 (the four default textures and "Blank"). + // The color-values were choosen because they "look right" (at least to me) ;-) + private static readonly UUID defaultTerrainTexture1 = new UUID("0bc58228-74a0-7e83-89bc-5c23464bcec5"); + private static readonly Color defaultColor1 = Color.FromArgb(165, 137, 118); + private static readonly UUID defaultTerrainTexture2 = new UUID("63338ede-0037-c4fd-855b-015d77112fc8"); + private static readonly Color defaultColor2 = Color.FromArgb(69, 89, 49); + private static readonly UUID defaultTerrainTexture3 = new UUID("303cd381-8560-7579-23f1-f0a880799740"); + private static readonly Color defaultColor3 = Color.FromArgb(162, 154, 141); + private static readonly UUID defaultTerrainTexture4 = new UUID("53a2f406-4895-1d13-d541-d2e3b86bc19c"); + private static readonly Color defaultColor4 = Color.FromArgb(200, 200, 200); + + #endregion + + + private Scene m_scene; + // private IConfigSource m_config; // not used currently + + // mapping from texture UUIDs to averaged color. This will contain 5-9 values, in general; new values are only + // added when the terrain textures are changed in the estate dialog and a new map is generated (and will stay in + // that map until the region-server restarts. This could be considered a memory-leak, but it's a *very* small one. + // TODO does it make sense to use a "real" cache and regenerate missing entries on fetch? + private Dictionary m_mapping; + + + public void Initialise(Scene scene, IConfigSource source) + { + m_scene = scene; + // m_config = source; // not used currently + m_mapping = new Dictionary(); + m_mapping.Add(defaultTerrainTexture1, defaultColor1); + m_mapping.Add(defaultTerrainTexture2, defaultColor2); + m_mapping.Add(defaultTerrainTexture3, defaultColor3); + m_mapping.Add(defaultTerrainTexture4, defaultColor4); + m_mapping.Add(Util.BLANK_TEXTURE_UUID, Color.White); + } + + #region Helpers + // This fetches the texture from the asset server synchroneously. That should be ok, as we + // call map-creation only in those places: + // - on start: We can wait here until the asset server returns the texture + // TODO (- on "map" command: We are in the command-line thread, we will wait for completion anyway) + // TODO (- on "automatic" update after some change: We are called from the mapUpdateTimer here and + // will wait anyway) + private Bitmap fetchTexture(UUID id) + { + AssetBase asset = m_scene.AssetCache.GetAsset(id, true); + m_log.DebugFormat("Fetched texture {0}, found: {1}", id, asset != null); + if (asset == null) return null; + + ManagedImage managedImage; + Image image; + + try + { + if (OpenJPEG.DecodeToImage(asset.Data, out managedImage, out image)) + return new Bitmap(image); + else + return null; + } + catch (DllNotFoundException) + { + m_log.ErrorFormat("[TexturedMapTileRenderer]: OpenJpeg is not installed correctly on this system. Asset Data is emtpy for {0}", id); + + } + catch (IndexOutOfRangeException) + { + m_log.ErrorFormat("[TexturedMapTileRenderer]: OpenJpeg was unable to encode this. Asset Data is emtpy for {0}", id); + + } + catch (Exception) + { + m_log.ErrorFormat("[TexturedMapTileRenderer]: OpenJpeg was unable to encode this. Asset Data is emtpy for {0}", id); + + } + return null; + + } + + // Compute the average color of a texture. + private Color computeAverageColor(Bitmap bmp) + { + // we have 256 x 256 pixel, each with 256 possible color-values per + // color-channel, so 2^24 is the maximum value we can get, adding everything. + // int is be big enough for that. + int r = 0, g = 0, b = 0; + for (int y = 0; y < bmp.Height; ++y) + { + for (int x = 0; x < bmp.Width; ++x) + { + Color c = bmp.GetPixel(x, y); + r += (int)c.R & 0xff; + g += (int)c.G & 0xff; + b += (int)c.B & 0xff; + } + } + + int pixels = bmp.Width * bmp.Height; + return Color.FromArgb(r / pixels, g / pixels, b / pixels); + } + + // return either the average color of the texture, or the defaultColor if the texturID is invalid + // or the texture couldn't be found + private Color computeAverageColor(UUID textureID, Color defaultColor) { + if (textureID == UUID.Zero) return defaultColor; // not set + if (m_mapping.ContainsKey(textureID)) return m_mapping[textureID]; // one of the predefined textures + + Bitmap bmp = fetchTexture(textureID); + Color color = bmp == null ? defaultColor : computeAverageColor(bmp); + // store it for future reference + m_mapping[textureID] = color; + + return color; + } + + // S-curve: f(x) = 3x² - 2x³: + // f(0) = 0, f(0.5) = 0.5, f(1) = 1, + // f'(x) = 0 at x = 0 and x = 1; f'(0.5) = 1.5, + // f''(0.5) = 0, f''(x) != 0 for x != 0.5 + private float S(float v) { + return (v * v * (3f - 2f * v)); + } + + // interpolate two colors in HSV space and return the resulting color + private HSV interpolateHSV(ref HSV c1, ref HSV c2, float ratio) { + if (ratio <= 0f) return c1; + if (ratio >= 1f) return c2; + + // make sure we are on the same side on the hue-circle for interpolation + // We change the hue of the parameters here, but we don't change the color + // represented by that value + if (c1.h - c2.h > 180f) c1.h -= 360f; + else if (c2.h - c1.h > 180f) c1.h += 360f; + + return new HSV(c1.h * (1f - ratio) + c2.h * ratio, + c1.s * (1f - ratio) + c2.s * ratio, + c1.v * (1f - ratio) + c2.v * ratio); + } + + // the heigthfield might have some jumps in values. Rendered land is smooth, though, + // as a slope is rendered at that place. So average 4 neighbour values to emulate that. + private float getHeight(double[,] hm, int x, int y) { + if (x < 255 && y < 255) + return (float)(hm[x, y] * .444 + (hm[x + 1, y] + hm[x, y + 1]) * .222 + hm[x + 1, y +1] * .112); + else + return (float)hm[x, y]; + } + #endregion + + public void TerrainToBitmap(Bitmap mapbmp) + { + int tc = System.Environment.TickCount; + m_log.Info("[MAPTILE]: Generating Maptile Step 1: Terrain"); + + // These textures should be in the AssetCache anyway, as every client conneting to this + // region needs them. Except on start, when the map is recreated (before anyone connected), + // and on change of the estate settings (textures and terrain values), when the map should + // be recreated. + RegionSettings settings = m_scene.RegionInfo.RegionSettings; + + // the four terrain colors as HSVs for interpolation + HSV hsv1 = new HSV(computeAverageColor(settings.TerrainTexture1, defaultColor1)); + HSV hsv2 = new HSV(computeAverageColor(settings.TerrainTexture2, defaultColor2)); + HSV hsv3 = new HSV(computeAverageColor(settings.TerrainTexture3, defaultColor3)); + HSV hsv4 = new HSV(computeAverageColor(settings.TerrainTexture4, defaultColor4)); + + float levelNElow = (float)settings.Elevation1NE; + float levelNEhigh = (float)settings.Elevation2NE; + + float levelNWlow = (float)settings.Elevation1NW; + float levelNWhigh = (float)settings.Elevation2NW; + + float levelSElow = (float)settings.Elevation1SE; + float levelSEhigh = (float)settings.Elevation2SE; + + float levelSWlow = (float)settings.Elevation1SW; + float levelSWhigh = (float)settings.Elevation2SW; + + float waterHeight = (float)settings.WaterHeight; + + double[,] hm = m_scene.Heightmap.GetDoubles(); + + for (int x = 0; x < 256; x++) + { + float columnRatio = x / 255f; // 0 - 1, for interpolation + for (int y = 0; y < 256; y++) + { + float rowRatio = y / 255f; // 0 - 1, for interpolation + + // Y flip the cordinates for the bitmap: hf origin is lower left, bm origin is upper left + int yr = 255 - y; + + float heightvalue = getHeight(hm, x, y); + if (Single.IsInfinity(heightvalue) || Single.IsNaN(heightvalue)) + heightvalue = 0; + + if (heightvalue > waterHeight) + { + // add a bit noise for breaking up those flat colors: + // - a large-scale noise, for the "patches" (using an doubled s-curve for sharper contrast) + // - a small-scale noise, for bringing in some small scale variation + //float bigNoise = (float)TerrainUtil.InterpolatedNoise(x / 8.0, y / 8.0) * .5f + .5f; // map to 0.0 - 1.0 + //float smallNoise = (float)TerrainUtil.InterpolatedNoise(x + 33, y + 43) * .5f + .5f; + //float hmod = heightvalue + smallNoise * 3f + S(S(bigNoise)) * 10f; + float hmod = + heightvalue + + (float)TerrainUtil.InterpolatedNoise(x + 33, y + 43) * 1.5f + 1.5f + // 0 - 3 + S(S((float)TerrainUtil.InterpolatedNoise(x / 8.0, y / 8.0) * .5f + .5f)) * 10f; // 0 - 10 + + // find the low/high values for this point (interpolated bilinearily) + // (and remember, x=0,y=0 is SW) + float low = levelSWlow * (1f - rowRatio) * (1f - columnRatio) + + levelSElow * (1f - rowRatio) * columnRatio + + levelNWlow * rowRatio * (1f - columnRatio) + + levelNElow * rowRatio * columnRatio; + float high = levelSWhigh * (1f - rowRatio) * (1f - columnRatio) + + levelSEhigh * (1f - rowRatio) * columnRatio + + levelNWhigh * rowRatio * (1f - columnRatio) + + levelNEhigh * rowRatio * columnRatio; + if (high < low) + { + // someone tried to fool us. High value should be higher than low every time + float tmp = high; + high = low; + low = tmp; + } + + HSV hsv; + if (hmod <= low) hsv = hsv1; // too low + else if (hmod >= high) hsv = hsv4; // too high + else + { + // HSV-interpolate along the colors + // first, rescale h to 0.0 - 1.0 + hmod = (hmod - low) / (high - low); + // now we have to split: 0.00 => color1, 0.33 => color2, 0.67 => color3, 1.00 => color4 + if (hmod < 1f/3f) hsv = interpolateHSV(ref hsv1, ref hsv2, hmod * 3f); + else if (hmod < 2f/3f) hsv = interpolateHSV(ref hsv2, ref hsv3, (hmod * 3f) - 1f); + else hsv = interpolateHSV(ref hsv3, ref hsv4, (hmod * 3f) - 2f); + } + + // Shade the terrain for shadows + if (x < 255 && y < 255) + { + float hfvaluecompare = getHeight(hm, x + 1, y + 1); // light from north-east => look at land height there + if (Single.IsInfinity(hfvaluecompare) || Single.IsNaN(hfvaluecompare)) + hfvaluecompare = 0f; + + float hfdiff = heightvalue - hfvaluecompare; // => positive if NE is lower, negative if here is lower + hfdiff *= 0.06f; // some random factor so "it looks good" + if (hfdiff > 0.02f) + { + float highlightfactor = 0.18f; + // NE is lower than here + // We have to desaturate and lighten the land at the same time + hsv.s = (hsv.s - (hfdiff * highlightfactor) > 0f) ? hsv.s - (hfdiff * highlightfactor) : 0f; + hsv.v = (hsv.v + (hfdiff * highlightfactor) < 1f) ? hsv.v + (hfdiff * highlightfactor) : 1f; + } + else if (hfdiff < -0.02f) + { + // here is lower than NE: + // We have to desaturate and blacken the land at the same time + hsv.s = (hsv.s + hfdiff > 0f) ? hsv.s + hfdiff : 0f; + hsv.v = (hsv.v + hfdiff > 0f) ? hsv.v + hfdiff : 0f; + } + } + mapbmp.SetPixel(x, yr, hsv.toColor()); + } + else + { + // We're under the water level with the terrain, so paint water instead of land + + heightvalue = waterHeight - heightvalue; + if (Single.IsInfinity(heightvalue) || Single.IsNaN(heightvalue)) + heightvalue = 0f; + else if (heightvalue > 19f) + heightvalue = 19f; + else if (heightvalue < 0f) + heightvalue = 0f; + + heightvalue = 100f - (heightvalue * 100f) / 19f; // 0 - 19 => 100 - 0 + + Color water = Color.FromArgb((int)heightvalue, (int)heightvalue, 255); + mapbmp.SetPixel(x, yr, water); + } + } + } + m_log.Info("[MAPTILE]: Generating Maptile Step 1: Done in " + (System.Environment.TickCount - tc) + " ms"); + } + } +} diff --git a/OpenSim/Region/CoreModules/World/WorldMap/WorldMapModule.cs b/OpenSim/Region/CoreModules/World/WorldMap/WorldMapModule.cs new file mode 100644 index 0000000..376e365 --- /dev/null +++ b/OpenSim/Region/CoreModules/World/WorldMap/WorldMapModule.cs @@ -0,0 +1,905 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSim Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Imaging; +using System.IO; +using System.Net; +using System.Reflection; +using System.Threading; +using OpenMetaverse; +using OpenMetaverse.Imaging; +using OpenMetaverse.StructuredData; +using log4net; +using Nini.Config; +using OpenSim.Framework; +using OpenSim.Framework.Communications.Cache; +using OpenSim.Framework.Communications.Capabilities; +using OpenSim.Framework.Servers; +using OpenSim.Region.Framework.Interfaces; +using OpenSim.Region.Framework.Scenes; +using OpenSim.Region.Framework.Scenes.Types; +using Caps = OpenSim.Framework.Communications.Capabilities.Caps; + +using OSD = OpenMetaverse.StructuredData.OSD; +using OSDMap = OpenMetaverse.StructuredData.OSDMap; +using OSDArray = OpenMetaverse.StructuredData.OSDArray; + +namespace OpenSim.Region.CoreModules.World.WorldMap +{ + public class WorldMapModule : IRegionModule + { + private static readonly ILog m_log = + LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private static readonly string m_mapLayerPath = "0001/"; + + private OpenSim.Framework.BlockingQueue requests = new OpenSim.Framework.BlockingQueue(); + + //private IConfig m_config; + protected Scene m_scene; + private List cachedMapBlocks = new List(); + private int cachedTime = 0; + private byte[] myMapImageJPEG; + protected bool m_Enabled = false; + private Dictionary m_openRequests = new Dictionary(); + private Dictionary m_blacklistedurls = new Dictionary(); + private Dictionary m_blacklistedregions = new Dictionary(); + private Dictionary m_cachedRegionMapItemsAddress = new Dictionary(); + private List m_rootAgents = new List(); + private Thread mapItemReqThread; + private volatile bool threadrunning = false; + + //private int CacheRegionsDistance = 256; + + #region IRegionModule Members + + public virtual void Initialise(Scene scene, IConfigSource config) + { + IConfig startupConfig = config.Configs["Startup"]; + if (startupConfig.GetString("WorldMapModule", "WorldMap") == + "WorldMap") + m_Enabled = true; + + if (!m_Enabled) + return; + + m_scene = scene; + } + + public virtual void PostInitialise() + { + if (m_Enabled) + AddHandlers(); + } + + public virtual void Close() + { + } + + public virtual string Name + { + get { return "WorldMapModule"; } + } + + public bool IsSharedModule + { + get { return false; } + } + + #endregion + + protected virtual void AddHandlers() + { + myMapImageJPEG = new byte[0]; + + string regionimage = "regionImage" + m_scene.RegionInfo.RegionID.ToString(); + regionimage = regionimage.Replace("-", ""); + m_log.Info("[WORLD MAP]: JPEG Map location: http://" + m_scene.RegionInfo.ExternalEndPoint.Address.ToString() + ":" + m_scene.RegionInfo.HttpPort.ToString() + "/index.php?method=" + regionimage); + + m_scene.CommsManager.HttpServer.AddHTTPHandler(regionimage, OnHTTPGetMapImage); + m_scene.CommsManager.HttpServer.AddLLSDHandler( + "/MAP/MapItems/" + m_scene.RegionInfo.RegionHandle.ToString(), HandleRemoteMapItemRequest); + + m_scene.EventManager.OnRegisterCaps += OnRegisterCaps; + m_scene.EventManager.OnNewClient += OnNewClient; + m_scene.EventManager.OnClientClosed += ClientLoggedOut; + m_scene.EventManager.OnMakeChildAgent += MakeChildAgent; + m_scene.EventManager.OnMakeRootAgent += MakeRootAgent; + } + + public void OnRegisterCaps(UUID agentID, Caps caps) + { + //m_log.DebugFormat("[WORLD MAP]: OnRegisterCaps: agentID {0} caps {1}", agentID, caps); + string capsBase = "/CAPS/" + caps.CapsObjectPath; + caps.RegisterHandler("MapLayer", + new RestStreamHandler("POST", capsBase + m_mapLayerPath, + delegate(string request, string path, string param, + OSHttpRequest httpRequest, OSHttpResponse httpResponse) + { + return MapLayerRequest(request, path, param, + agentID, caps); + })); + } + + /// + /// Callback for a map layer request + /// + /// + /// + /// + /// + /// + /// + public string MapLayerRequest(string request, string path, string param, + UUID agentID, Caps caps) + { + //try + //{ + //m_log.DebugFormat("[MAPLAYER]: request: {0}, path: {1}, param: {2}, agent:{3}", + //request, path, param,agentID.ToString()); + + // this is here because CAPS map requests work even beyond the 10,000 limit. + ScenePresence avatarPresence = null; + + m_scene.TryGetAvatar(agentID, out avatarPresence); + + if (avatarPresence != null) + { + bool lookup = false; + + lock (cachedMapBlocks) + { + if (cachedMapBlocks.Count > 0 && ((cachedTime + 1800) > Util.UnixTimeSinceEpoch())) + { + List mapBlocks; + + mapBlocks = cachedMapBlocks; + avatarPresence.ControllingClient.SendMapBlock(mapBlocks, 0); + } + else + { + lookup = true; + } + } + if (lookup) + { + List mapBlocks; + + mapBlocks = m_scene.SceneGridService.RequestNeighbourMapBlocks((int)m_scene.RegionInfo.RegionLocX - 8, (int)m_scene.RegionInfo.RegionLocY - 8, (int)m_scene.RegionInfo.RegionLocX + 8, (int)m_scene.RegionInfo.RegionLocY + 8); + avatarPresence.ControllingClient.SendMapBlock(mapBlocks,0); + + lock (cachedMapBlocks) + cachedMapBlocks = mapBlocks; + + cachedTime = Util.UnixTimeSinceEpoch(); + } + } + LLSDMapLayerResponse mapResponse = new LLSDMapLayerResponse(); + mapResponse.LayerData.Array.Add(GetOSDMapLayerResponse()); + return mapResponse.ToString(); + } + + /// + /// + /// + /// + /// + public LLSDMapLayerResponse GetMapLayer(LLSDMapRequest mapReq) + { + m_log.Debug("[WORLD MAP]: MapLayer Request in region: " + m_scene.RegionInfo.RegionName); + LLSDMapLayerResponse mapResponse = new LLSDMapLayerResponse(); + mapResponse.LayerData.Array.Add(GetOSDMapLayerResponse()); + return mapResponse; + } + + /// + /// + /// + /// + protected static OSDMapLayer GetOSDMapLayerResponse() + { + OSDMapLayer mapLayer = new OSDMapLayer(); + mapLayer.Right = 5000; + mapLayer.Top = 5000; + mapLayer.ImageID = new UUID("00000000-0000-1111-9999-000000000006"); + + return mapLayer; + } + #region EventHandlers + + /// + /// Registered for event + /// + /// + private void OnNewClient(IClientAPI client) + { + client.OnRequestMapBlocks += RequestMapBlocks; + client.OnMapItemRequest += HandleMapItemRequest; + } + + /// + /// Client logged out, check to see if there are any more root agents in the simulator + /// If not, stop the mapItemRequest Thread + /// Event handler + /// + /// AgentID that logged out + private void ClientLoggedOut(UUID AgentId) + { + List presences = m_scene.GetAvatars(); + int rootcount = 0; + for (int i=0;i + /// Starts the MapItemRequest Thread + /// Note that this only gets started when there are actually agents in the region + /// Additionally, it gets stopped when there are none. + /// + /// + private void StartThread(object o) + { + if (threadrunning) return; + threadrunning = true; + m_log.Debug("[WORLD MAP]: Starting remote MapItem request thread"); + mapItemReqThread = new Thread(new ThreadStart(process)); + mapItemReqThread.IsBackground = true; + mapItemReqThread.Name = "MapItemRequestThread"; + mapItemReqThread.Priority = ThreadPriority.BelowNormal; + mapItemReqThread.SetApartmentState(ApartmentState.MTA); + mapItemReqThread.Start(); + ThreadTracker.Add(mapItemReqThread); + } + + /// + /// Enqueues a 'stop thread' MapRequestState. Causes the MapItemRequest thread to end + /// + private void StopThread() + { + MapRequestState st = new MapRequestState(); + st.agentID=UUID.Zero; + st.EstateID=0; + st.flags=0; + st.godlike=false; + st.itemtype=0; + st.regionhandle=0; + + requests.Enqueue(st); + } + + public virtual void HandleMapItemRequest(IClientAPI remoteClient, uint flags, + uint EstateID, bool godlike, uint itemtype, ulong regionhandle) + { + lock (m_rootAgents) + { + if (!m_rootAgents.Contains(remoteClient.AgentId)) + return; + } + uint xstart = 0; + uint ystart = 0; + Utils.LongToUInts(m_scene.RegionInfo.RegionHandle, out xstart, out ystart); + if (itemtype == 6) // we only sevice 6 right now (avatar green dots) + { + if (regionhandle == 0 || regionhandle == m_scene.RegionInfo.RegionHandle) + { + // Local Map Item Request + List avatars = m_scene.GetAvatars(); + int tc = System.Environment.TickCount; + List mapitems = new List(); + mapItemReply mapitem = new mapItemReply(); + if (avatars.Count == 0 || avatars.Count == 1) + { + mapitem = new mapItemReply(); + mapitem.x = (uint)(xstart + 1); + mapitem.y = (uint)(ystart + 1); + mapitem.id = UUID.Zero; + mapitem.name = Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString()); + mapitem.Extra = 0; + mapitem.Extra2 = 0; + mapitems.Add(mapitem); + } + else + { + foreach (ScenePresence av in avatars) + { + // Don't send a green dot for yourself + if (av.UUID != remoteClient.AgentId) + { + mapitem = new mapItemReply(); + mapitem.x = (uint)(xstart + av.AbsolutePosition.X); + mapitem.y = (uint)(ystart + av.AbsolutePosition.Y); + mapitem.id = UUID.Zero; + mapitem.name = Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString()); + mapitem.Extra = 1; + mapitem.Extra2 = 0; + mapitems.Add(mapitem); + } + } + } + remoteClient.SendMapItemReply(mapitems.ToArray(), itemtype, flags); + } + else + { + // Remote Map Item Request + + // ensures that the blockingqueue doesn't get borked if the GetAgents() timing changes. + // Note that we only start up a remote mapItem Request thread if there's users who could + // be making requests + if (!threadrunning) + { + m_log.Warn("[WORLD MAP]: Starting new remote request thread manually. This means that AvatarEnteringParcel never fired! This needs to be fixed! Don't Mantis this, as the developers can see it in this message"); + StartThread(new object()); + } + + RequestMapItems("",remoteClient.AgentId,flags,EstateID,godlike,itemtype,regionhandle); + } + } + } + + /// + /// Processing thread main() loop for doing remote mapitem requests + /// + public void process() + { + try + { + while (true) + { + MapRequestState st = requests.Dequeue(); + + // end gracefully + if (st.agentID == UUID.Zero) + { + ThreadTracker.Remove(mapItemReqThread); + break; + } + + bool dorequest = true; + lock (m_rootAgents) + { + if (!m_rootAgents.Contains(st.agentID)) + dorequest = false; + } + + if (dorequest) + { + OSDMap response = RequestMapItemsAsync("", st.agentID, st.flags, st.EstateID, st.godlike, st.itemtype, st.regionhandle); + RequestMapItemsCompleted(response); + } + } + } + catch (Exception e) + { + m_log.ErrorFormat("[WORLD MAP]: Map item request thread terminated abnormally with exception {0}", e); + } + + threadrunning = false; + } + + /// + /// Enqueues the map item request into the processing thread + /// + /// + public void EnqueueMapItemRequest(MapRequestState state) + { + requests.Enqueue(state); + } + + /// + /// Sends the mapitem response to the IClientAPI + /// + /// The OSDMap Response for the mapitem + private void RequestMapItemsCompleted(OSDMap response) + { + UUID requestID = response["requestID"].AsUUID(); + + if (requestID != UUID.Zero) + { + MapRequestState mrs = new MapRequestState(); + mrs.agentID = UUID.Zero; + lock (m_openRequests) + { + if (m_openRequests.ContainsKey(requestID)) + { + mrs = m_openRequests[requestID]; + m_openRequests.Remove(requestID); + } + } + + if (mrs.agentID != UUID.Zero) + { + ScenePresence av = null; + m_scene.TryGetAvatar(mrs.agentID, out av); + if (av != null) + { + if (response.ContainsKey(mrs.itemtype.ToString())) + { + List returnitems = new List(); + OSDArray itemarray = (OSDArray)response[mrs.itemtype.ToString()]; + for (int i = 0; i < itemarray.Count; i++) + { + OSDMap mapitem = (OSDMap)itemarray[i]; + mapItemReply mi = new mapItemReply(); + mi.x = (uint)mapitem["X"].AsInteger(); + mi.y = (uint)mapitem["Y"].AsInteger(); + mi.id = mapitem["ID"].AsUUID(); + mi.Extra = mapitem["Extra"].AsInteger(); + mi.Extra2 = mapitem["Extra2"].AsInteger(); + mi.name = mapitem["Name"].AsString(); + returnitems.Add(mi); + } + av.ControllingClient.SendMapItemReply(returnitems.ToArray(), mrs.itemtype, mrs.flags); + } + } + } + } + } + + /// + /// Enqueue the MapItem request for remote processing + /// + /// blank string, we discover this in the process + /// Agent ID that we are making this request on behalf + /// passed in from packet + /// passed in from packet + /// passed in from packet + /// passed in from packet + /// Region we're looking up + public void RequestMapItems(string httpserver, UUID id, uint flags, + uint EstateID, bool godlike, uint itemtype, ulong regionhandle) + { + MapRequestState st = new MapRequestState(); + st.agentID = id; + st.flags = flags; + st.EstateID = EstateID; + st.godlike = godlike; + st.itemtype = itemtype; + st.regionhandle = regionhandle; + EnqueueMapItemRequest(st); + } + + /// + /// Does the actual remote mapitem request + /// This should be called from an asynchronous thread + /// Request failures get blacklisted until region restart so we don't + /// continue to spend resources trying to contact regions that are down. + /// + /// blank string, we discover this in the process + /// Agent ID that we are making this request on behalf + /// passed in from packet + /// passed in from packet + /// passed in from packet + /// passed in from packet + /// Region we're looking up + /// + private OSDMap RequestMapItemsAsync(string httpserver, UUID id, uint flags, + uint EstateID, bool godlike, uint itemtype, ulong regionhandle) + { + bool blacklisted = false; + lock (m_blacklistedregions) + { + if (m_blacklistedregions.ContainsKey(regionhandle)) + blacklisted = true; + } + + if (blacklisted) + return new OSDMap(); + + UUID requestID = UUID.Random(); + lock (m_cachedRegionMapItemsAddress) + { + if (m_cachedRegionMapItemsAddress.ContainsKey(regionhandle)) + httpserver = m_cachedRegionMapItemsAddress[regionhandle]; + } + if (httpserver.Length == 0) + { + RegionInfo mreg = m_scene.SceneGridService.RequestNeighbouringRegionInfo(regionhandle); + + if (mreg != null) + { + httpserver = "http://" + mreg.ExternalEndPoint.Address.ToString() + ":" + mreg.HttpPort + "/MAP/MapItems/" + regionhandle.ToString(); + lock (m_cachedRegionMapItemsAddress) + { + if (!m_cachedRegionMapItemsAddress.ContainsKey(regionhandle)) + m_cachedRegionMapItemsAddress.Add(regionhandle, httpserver); + } + } + else + { + lock (m_blacklistedregions) + { + if (!m_blacklistedregions.ContainsKey(regionhandle)) + m_blacklistedregions.Add(regionhandle, System.Environment.TickCount); + } + m_log.InfoFormat("[WORLD MAP]: Blacklisted region {0}", regionhandle.ToString()); + } + } + + blacklisted = false; + lock (m_blacklistedurls) + { + if (m_blacklistedurls.ContainsKey(httpserver)) + blacklisted = true; + } + + // Can't find the http server + if (httpserver.Length == 0 || blacklisted) + return new OSDMap(); + + MapRequestState mrs = new MapRequestState(); + mrs.agentID = id; + mrs.EstateID = EstateID; + mrs.flags = flags; + mrs.godlike = godlike; + mrs.itemtype=itemtype; + mrs.regionhandle = regionhandle; + + lock (m_openRequests) + m_openRequests.Add(requestID, mrs); + + WebRequest mapitemsrequest = WebRequest.Create(httpserver); + mapitemsrequest.Method = "POST"; + mapitemsrequest.ContentType = "application/xml+llsd"; + OSDMap RAMap = new OSDMap(); + + // string RAMapString = RAMap.ToString(); + OSD LLSDofRAMap = RAMap; // RENAME if this works + + byte[] buffer = OSDParser.SerializeLLSDXmlBytes(LLSDofRAMap); + OSDMap responseMap = new OSDMap(); + responseMap["requestID"] = OSD.FromUUID(requestID); + + Stream os = null; + try + { // send the Post + mapitemsrequest.ContentLength = buffer.Length; //Count bytes to send + os = mapitemsrequest.GetRequestStream(); + os.Write(buffer, 0, buffer.Length); //Send it + os.Close(); + //m_log.DebugFormat("[WORLD MAP]: Getting MapItems from Sim {0}", httpserver); + } + catch (WebException ex) + { + m_log.WarnFormat("[WORLD MAP]: Bad send on GetMapItems {0}", ex.Message); + responseMap["connect"] = OSD.FromBoolean(false); + lock (m_blacklistedurls) + { + if (!m_blacklistedurls.ContainsKey(httpserver)) + m_blacklistedurls.Add(httpserver, System.Environment.TickCount); + } + + m_log.WarnFormat("[WORLD MAP]: Blacklisted {0}", httpserver); + + return responseMap; + } + + string response_mapItems_reply = null; + { // get the response + try + { + WebResponse webResponse = mapitemsrequest.GetResponse(); + if (webResponse != null) + { + StreamReader sr = new StreamReader(webResponse.GetResponseStream()); + response_mapItems_reply = sr.ReadToEnd().Trim(); + } + else + { + return new OSDMap(); + } + } + catch (WebException) + { + responseMap["connect"] = OSD.FromBoolean(false); + lock (m_blacklistedurls) + { + if (!m_blacklistedurls.ContainsKey(httpserver)) + m_blacklistedurls.Add(httpserver, System.Environment.TickCount); + } + + m_log.WarnFormat("[WORLD MAP]: Blacklisted {0}", httpserver); + + return responseMap; + } + OSD rezResponse = null; + try + { + rezResponse = OSDParser.DeserializeLLSDXml(response_mapItems_reply); + + responseMap = (OSDMap)rezResponse; + responseMap["requestID"] = OSD.FromUUID(requestID); + } + catch (Exception) + { + //m_log.InfoFormat("[OGP]: exception on parse of rez reply {0}", ex.Message); + responseMap["connect"] = OSD.FromBoolean(false); + + return responseMap; + } + } + return responseMap; + } + + /// + /// Requests map blocks in area of minX, maxX, minY, MaxY in world cordinates + /// + /// + /// + /// + /// + public virtual void RequestMapBlocks(IClientAPI remoteClient, int minX, int minY, int maxX, int maxY, uint flag) + { + List mapBlocks; + if ((flag & 0x10000) != 0) // user clicked on the map a tile that isn't visible + { + List response = new List(); + + // this should return one mapblock at most. But make sure: Look whether the one we requested is in there + mapBlocks = m_scene.SceneGridService.RequestNeighbourMapBlocks(minX, minY, maxX, maxY); + if (mapBlocks != null) + { + foreach (MapBlockData block in mapBlocks) + { + if (block.X == minX && block.Y == minY) + { + // found it => add it to response + response.Add(block); + break; + } + } + } + + if (response.Count == 0) + { + // response still empty => couldn't find the map-tile the user clicked on => tell the client + MapBlockData block = new MapBlockData(); + block.X = (ushort)minX; + block.Y = (ushort)minY; + block.Access = 254; // == not there + response.Add(block); + } + remoteClient.SendMapBlock(response, 0); + } + else + { + // normal mapblock request. Use the provided values + mapBlocks = m_scene.SceneGridService.RequestNeighbourMapBlocks(minX - 4, minY - 4, maxX + 4, maxY + 4); + remoteClient.SendMapBlock(mapBlocks, flag); + } + } + + public Hashtable OnHTTPGetMapImage(Hashtable keysvals) + { + m_log.Debug("[WORLD MAP]: Sending map image jpeg"); + Hashtable reply = new Hashtable(); + int statuscode = 200; + byte[] jpeg = new byte[0]; + + if (myMapImageJPEG.Length == 0) + { + MemoryStream imgstream = new MemoryStream(); + Bitmap mapTexture = new Bitmap(1,1); + ManagedImage managedImage; + Image image = (Image)mapTexture; + + try + { + // Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular jpeg data + + imgstream = new MemoryStream(); + + // non-async because we know we have the asset immediately. + AssetBase mapasset = m_scene.AssetCache.GetAsset(m_scene.RegionInfo.lastMapUUID, true); + + // Decode image to System.Drawing.Image + if (OpenJPEG.DecodeToImage(mapasset.Data, out managedImage, out image)) + { + // Save to bitmap + mapTexture = new Bitmap(image); + + EncoderParameters myEncoderParameters = new EncoderParameters(); + myEncoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 95L); + + // Save bitmap to stream + mapTexture.Save(imgstream, GetEncoderInfo("image/jpeg"), myEncoderParameters); + + // Write the stream to a byte array for output + jpeg = imgstream.ToArray(); + myMapImageJPEG = jpeg; + } + } + catch (Exception) + { + // Dummy! + m_log.Warn("[WORLD MAP]: Unable to generate Map image"); + } + finally + { + // Reclaim memory, these are unmanaged resources + mapTexture.Dispose(); + image.Dispose(); + imgstream.Close(); + imgstream.Dispose(); + } + } + else + { + // Use cached version so we don't have to loose our mind + jpeg = myMapImageJPEG; + } + + reply["str_response_string"] = Convert.ToBase64String(jpeg); + reply["int_response_code"] = statuscode; + reply["content_type"] = "image/jpeg"; + + return reply; + } + + // From msdn + private static ImageCodecInfo GetEncoderInfo(String mimeType) + { + ImageCodecInfo[] encoders; + encoders = ImageCodecInfo.GetImageEncoders(); + for (int j = 0; j < encoders.Length; ++j) + { + if (encoders[j].MimeType == mimeType) + return encoders[j]; + } + return null; + } + + public OSD HandleRemoteMapItemRequest(string path, OSD request, string endpoint) + { + uint xstart = 0; + uint ystart = 0; + + Utils.LongToUInts(m_scene.RegionInfo.RegionHandle,out xstart,out ystart); + + OSDMap responsemap = new OSDMap(); + List avatars = m_scene.GetAvatars(); + OSDArray responsearr = new OSDArray(avatars.Count); + OSDMap responsemapdata = new OSDMap(); + int tc = System.Environment.TickCount; + /* + foreach (ScenePresence av in avatars) + { + responsemapdata = new OSDMap(); + responsemapdata["X"] = OSD.FromInteger((int)(xstart + av.AbsolutePosition.X)); + responsemapdata["Y"] = OSD.FromInteger((int)(ystart + av.AbsolutePosition.Y)); + responsemapdata["ID"] = OSD.FromUUID(UUID.Zero); + responsemapdata["Name"] = OSD.FromString("TH"); + responsemapdata["Extra"] = OSD.FromInteger(0); + responsemapdata["Extra2"] = OSD.FromInteger(0); + responsearr.Add(responsemapdata); + } + responsemap["1"] = responsearr; + */ + if (avatars.Count == 0) + { + responsemapdata = new OSDMap(); + responsemapdata["X"] = OSD.FromInteger((int)(xstart + 1)); + responsemapdata["Y"] = OSD.FromInteger((int)(ystart + 1)); + responsemapdata["ID"] = OSD.FromUUID(UUID.Zero); + responsemapdata["Name"] = OSD.FromString(Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString())); + responsemapdata["Extra"] = OSD.FromInteger(0); + responsemapdata["Extra2"] = OSD.FromInteger(0); + responsearr.Add(responsemapdata); + + responsemap["6"] = responsearr; + } + else + { + responsearr = new OSDArray(avatars.Count); + foreach (ScenePresence av in avatars) + { + responsemapdata = new OSDMap(); + responsemapdata["X"] = OSD.FromInteger((int)(xstart + av.AbsolutePosition.X)); + responsemapdata["Y"] = OSD.FromInteger((int)(ystart + av.AbsolutePosition.Y)); + responsemapdata["ID"] = OSD.FromUUID(UUID.Zero); + responsemapdata["Name"] = OSD.FromString(Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString())); + responsemapdata["Extra"] = OSD.FromInteger(1); + responsemapdata["Extra2"] = OSD.FromInteger(0); + responsearr.Add(responsemapdata); + } + responsemap["6"] = responsearr; + } + return responsemap; + } + + private void MakeRootAgent(ScenePresence avatar) + { + // You may ask, why this is in a threadpool to start with.. + // The reason is so we don't cause the thread to freeze waiting + // for the 1 second it costs to start a thread manually. + if (!threadrunning) + ThreadPool.QueueUserWorkItem(new WaitCallback(this.StartThread)); + + lock (m_rootAgents) + { + if (!m_rootAgents.Contains(avatar.UUID)) + { + m_rootAgents.Add(avatar.UUID); + } + } + } + + private void MakeChildAgent(ScenePresence avatar) + { + List presences = m_scene.GetAvatars(); + int rootcount = 0; + for (int i = 0; i < presences.Count; i++) + { + if (presences[i] != null) + { + if (!presences[i].IsChildAgent) + rootcount++; + } + } + if (rootcount <= 1) + StopThread(); + + lock (m_rootAgents) + { + if (m_rootAgents.Contains(avatar.UUID)) + { + m_rootAgents.Remove(avatar.UUID); + } + } + } + } + + public struct MapRequestState + { + public UUID agentID; + public uint flags; + public uint EstateID; + public bool godlike; + public uint itemtype; + public ulong regionhandle; + } +} -- cgit v1.1