Revert "remake for 0910"

This reverts commit db05da4a5c.
master
Unknown 2018-10-16 17:36:59 +02:00
parent db05da4a5c
commit 35e24e9091
4 changed files with 755 additions and 651 deletions

View File

@ -103,39 +103,41 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
public static float noise2(float x, float y) public static float noise2(float x, float y)
{ {
int bx, by, b00, b10, b01, b11; int bx0, bx1, by0, by1, b00, b10, b01, b11;
float rx0, rx1, ry0, ry1, sx, sy, a, b, t, u, v; float rx0, rx1, ry0, ry1, sx, sy, a, b, t, u, v;
int i, j; int i, j;
t = x + N; t = x + N;
bx0 = ((int)t) & BM;
bx1 = (bx0 + 1) & BM;
rx0 = t - (int)t; rx0 = t - (int)t;
bx = ((int)t) & BM; rx1 = rx0 - 1f;
i = p[bx];
bx = (bx + 1) & BM;
j = p[bx];
t = y + N; t = y + N;
by0 = ((int)t) & BM;
by1 = (by0 + 1) & BM;
ry0 = t - (int)t; ry0 = t - (int)t;
by = ((int)t) & BM; ry1 = ry0 - 1f;
b00 = p[i + by];
b10 = p[j + by];
by = (by + 1) & BM; i = p[bx0];
b01 = p[i + by]; j = p[bx1];
b11 = p[j + by];
b00 = p[i + by0];
b10 = p[j + by0];
b01 = p[i + by1];
b11 = p[j + by1];
sx = s_curve(rx0); sx = s_curve(rx0);
sy = s_curve(ry0);
u = rx0 * g2[b00, 0] + ry0 * g2[b00, 1]; u = rx0 * g2[b00, 0] + ry0 * g2[b00, 1];
rx1 = rx0 - 1f;
v = rx1 * g2[b10, 0] + ry0 * g2[b10, 1]; v = rx1 * g2[b10, 0] + ry0 * g2[b10, 1];
a = Utils.Lerp(u, v, sx); a = Utils.Lerp(u, v, sx);
ry1 = ry0 - 1f;
u = rx0 * g2[b01, 0] + ry1 * g2[b01, 1]; u = rx0 * g2[b01, 0] + ry1 * g2[b01, 1];
v = rx1 * g2[b11, 0] + ry1 * g2[b11, 1]; v = rx1 * g2[b11, 0] + ry1 * g2[b11, 1];
b = Utils.Lerp(u, v, sx); b = Utils.Lerp(u, v, sx);
sy = s_curve(ry0);
return Utils.Lerp(a, b, sy); return Utils.Lerp(a, b, sy);
} }
@ -200,10 +202,12 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
public static float turbulence1(float x, float freq) public static float turbulence1(float x, float freq)
{ {
float t; float t;
float v;
for (t = 0f; freq >= 1f; freq *= 0.5f) for (t = 0f; freq >= 1f; freq *= 0.5f)
{ {
t += noise1(freq * x) / freq; v = freq * x;
t += noise1(v) / freq;
} }
return t; return t;
} }
@ -211,20 +215,28 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
public static float turbulence2(float x, float y, float freq) public static float turbulence2(float x, float y, float freq)
{ {
float t; float t;
Vector2 vec;
for (t = 0f; freq >= 1f; freq *= 0.5f) for (t = 0f; freq >= 1f; freq *= 0.5f)
t += noise2(freq * x, freq * y) / freq; {
vec.X = freq * x;
vec.Y = freq * y;
t += noise2(vec.X, vec.Y) / freq;
}
return t; return t;
} }
public static float turbulence3(float x, float y, float z, float freq) public static float turbulence3(float x, float y, float z, float freq)
{ {
float t; float t;
Vector3 vec;
for (t = 0f; freq >= 1f; freq *= 0.5f) for (t = 0f; freq >= 1f; freq *= 0.5f)
{ {
t += noise3(freq * x, freq * y, freq * z) / freq; vec.X = freq * x;
vec.Y = freq * y;
vec.Z = freq * z;
t += noise3(vec.X, vec.Y, vec.Z) / freq;
} }
return t; return t;
} }
@ -232,28 +244,23 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
private static void normalize2(float[,] v, int i) private static void normalize2(float[,] v, int i)
{ {
float s; float s;
float a = v[i, 0];
float b = v[i, 1];
s = (float)Math.Sqrt(a * a + b * b); s = (float)Math.Sqrt(v[i, 0] * v[i, 0] + v[i, 1] * v[i, 1]);
s = 1.0f / s; s = 1.0f / s;
v[i, 0] = a * s; v[i, 0] = v[i, 0] * s;
v[i, 1] = b * s; v[i, 1] = v[i, 1] * s;
} }
private static void normalize3(float[,] v, int i) private static void normalize3(float[,] v, int i)
{ {
float s; float s;
float a = v[i, 0];
float b = v[i, 1];
float c = v[i, 2];
s = (float)Math.Sqrt(a * a + b * b + c * c); s = (float)Math.Sqrt(v[i, 0] * v[i, 0] + v[i, 1] * v[i, 1] + v[i, 2] * v[i, 2]);
s = 1.0f / s; s = 1.0f / s;
v[i, 0] = a * s; v[i, 0] = v[i, 0] * s;
v[i, 1] = b * s; v[i, 1] = v[i, 1] * s;
v[i, 2] = c * s; v[i, 2] = v[i, 2] * s;
} }
private static float s_curve(float t) private static float s_curve(float t)

View File

@ -80,12 +80,9 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
/// Note we create a 256x256 dimension texture even if the actual terrain is larger. /// Note we create a 256x256 dimension texture even if the actual terrain is larger.
/// </remarks> /// </remarks>
public static Bitmap Splat(ITerrainChannel terrain, UUID[] textureIDs, public static Bitmap Splat(ITerrainChannel terrain,
float[] startHeights, float[] heightRanges, UUID[] textureIDs, float[] startHeights, float[] heightRanges,
uint regionPositionX, uint regionPositionY, Vector3d regionPosition, IAssetService assetService, bool textureTerrain)
IAssetService assetService, IJ2KDecoder decoder,
bool textureTerrain, bool averagetextureTerrain,
int twidth, int theight)
{ {
Debug.Assert(textureIDs.Length == 4); Debug.Assert(textureIDs.Length == 4);
Debug.Assert(startHeights.Length == 4); Debug.Assert(startHeights.Length == 4);
@ -93,12 +90,6 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
Bitmap[] detailTexture = new Bitmap[4]; Bitmap[] detailTexture = new Bitmap[4];
byte[] mapColorsRed = new byte[4];
byte[] mapColorsGreen = new byte[4];
byte[] mapColorsBlue = new byte[4];
bool usecolors = false;
if (textureTerrain) if (textureTerrain)
{ {
// Swap empty terrain textureIDs with default IDs // Swap empty terrain textureIDs with default IDs
@ -114,30 +105,22 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
{ {
for (int i = 0; i < 4; i++) for (int i = 0; i < 4; i++)
{ {
AssetBase asset = null; AssetBase asset;
UUID cacheID = UUID.Combine(TERRAIN_CACHE_MAGIC, textureIDs[i]);
// asset cache indexes are strings
string cacheName = "MAP-Patch" + textureIDs[i].ToString();
// Try to fetch a cached copy of the decoded/resized version of this texture // Try to fetch a cached copy of the decoded/resized version of this texture
asset = assetService.GetCached(cacheName); asset = assetService.GetCached(cacheID.ToString());
if (asset != null) if (asset != null)
{ {
try try
{ {
using (System.IO.MemoryStream stream = new System.IO.MemoryStream(asset.Data)) using (System.IO.MemoryStream stream = new System.IO.MemoryStream(asset.Data))
detailTexture[i] = (Bitmap)Image.FromStream(stream); detailTexture[i] = (Bitmap)Image.FromStream(stream);
if (detailTexture[i].PixelFormat != PixelFormat.Format24bppRgb ||
detailTexture[i].Width != 16 || detailTexture[i].Height != 16)
{
detailTexture[i].Dispose();
detailTexture[i] = null;
}
} }
catch (Exception ex) catch (Exception ex)
{ {
m_log.Warn("Failed to decode cached terrain patch texture" + textureIDs[i] + "): " + ex.Message); m_log.Warn("Failed to decode cached terrain texture " + cacheID +
" (textureID: " + textureIDs[i] + "): " + ex.Message);
} }
} }
@ -147,10 +130,10 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
asset = assetService.Get(textureIDs[i].ToString()); asset = assetService.Get(textureIDs[i].ToString());
if (asset != null) if (asset != null)
{ {
try // m_log.DebugFormat(
{ // "[TERRAIN SPLAT]: Got cached original JPEG2000 terrain texture {0} {1}", i, asset.ID);
detailTexture[i] = (Bitmap)decoder.DecodeToImage(asset.Data);
} try { detailTexture[i] = (Bitmap)CSJ2K.J2kImage.FromBytes(asset.Data); }
catch (Exception ex) catch (Exception ex)
{ {
m_log.Warn("Failed to decode terrain texture " + asset.ID + ": " + ex.Message); m_log.Warn("Failed to decode terrain texture " + asset.ID + ": " + ex.Message);
@ -159,10 +142,14 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
if (detailTexture[i] != null) if (detailTexture[i] != null)
{ {
if (detailTexture[i].PixelFormat != PixelFormat.Format24bppRgb || // Make sure this texture is the correct size, otherwise resize
detailTexture[i].Width != 16 || detailTexture[i].Height != 16) if (detailTexture[i].Width != 256 || detailTexture[i].Height != 256)
{
using (Bitmap origBitmap = detailTexture[i]) using (Bitmap origBitmap = detailTexture[i])
detailTexture[i] = Util.ResizeImageSolid(origBitmap, 16, 16); {
detailTexture[i] = ImageUtils.ResizeImage(origBitmap, 256, 256);
}
}
// Save the decoded and resized texture to the cache // Save the decoded and resized texture to the cache
byte[] data; byte[] data;
@ -178,8 +165,8 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
Data = data, Data = data,
Description = "PNG", Description = "PNG",
Flags = AssetFlags.Collectable, Flags = AssetFlags.Collectable,
FullID = UUID.Zero, FullID = cacheID,
ID = cacheName, ID = cacheID.ToString(),
Local = true, Local = true,
Name = String.Empty, Name = String.Empty,
Temporary = true, Temporary = true,
@ -193,223 +180,148 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
} }
#endregion Texture Fetching #endregion Texture Fetching
if (averagetextureTerrain)
{
for (int t = 0; t < 4; t++)
{
usecolors = true;
if (detailTexture[t] == null)
{
mapColorsRed[t] = DEFAULT_TERRAIN_COLOR[t].R;
mapColorsGreen[t] = DEFAULT_TERRAIN_COLOR[t].G;
mapColorsBlue[t] = DEFAULT_TERRAIN_COLOR[t].B;
continue;
} }
int npixeis = 0;
int cR = 0;
int cG = 0;
int cB = 0;
BitmapData bmdata = detailTexture[t].LockBits(new Rectangle(0, 0, 16, 16),
ImageLockMode.ReadOnly, detailTexture[t].PixelFormat);
npixeis = bmdata.Height * bmdata.Width;
int ylen = bmdata.Height * bmdata.Stride;
unsafe
{
for (int y = 0; y < ylen; y += bmdata.Stride)
{
byte* ptrc = (byte*)bmdata.Scan0 + y;
for (int x = 0; x < bmdata.Width; ++x)
{
cR += *(ptrc++);
cG += *(ptrc++);
cB += *(ptrc++);
}
}
}
detailTexture[t].UnlockBits(bmdata);
detailTexture[t].Dispose();
mapColorsRed[t] = (byte)Util.Clamp(cR / npixeis, 0, 255);
mapColorsGreen[t] = (byte)Util.Clamp(cG / npixeis, 0, 255);
mapColorsBlue[t] = (byte)Util.Clamp(cB / npixeis, 0, 255);
}
}
else
{
// Fill in any missing textures with a solid color // Fill in any missing textures with a solid color
for (int i = 0; i < 4; i++) for (int i = 0; i < 4; i++)
{ {
if (detailTexture[i] == null) if (detailTexture[i] == null)
{ {
m_log.DebugFormat("{0} Missing terrain texture for layer {1}. Filling with solid default color", LogHeader, i); m_log.DebugFormat("{0} Missing terrain texture for layer {1}. Filling with solid default color",
LogHeader, i);
// Create a solid color texture for this layer // Create a solid color texture for this layer
detailTexture[i] = new Bitmap(16, 16, PixelFormat.Format24bppRgb); detailTexture[i] = new Bitmap(256, 256, PixelFormat.Format24bppRgb);
using (Graphics gfx = Graphics.FromImage(detailTexture[i])) using (Graphics gfx = Graphics.FromImage(detailTexture[i]))
{ {
using (SolidBrush brush = new SolidBrush(DEFAULT_TERRAIN_COLOR[i])) using (SolidBrush brush = new SolidBrush(DEFAULT_TERRAIN_COLOR[i]))
gfx.FillRectangle(brush, 0, 0, 16, 16); gfx.FillRectangle(brush, 0, 0, 256, 256);
} }
} }
else else
{ {
if (detailTexture[i].Width != 16 || detailTexture[i].Height != 16) if (detailTexture[i].Width != 256 || detailTexture[i].Height != 256)
{ {
using (Bitmap origBitmap = detailTexture[i]) detailTexture[i] = ResizeBitmap(detailTexture[i], 256, 256);
detailTexture[i] = Util.ResizeImageSolid(origBitmap, 16, 16);
} }
} }
} }
}
}
else
{
usecolors = true;
for (int t = 0; t < 4; t++)
{
mapColorsRed[t] = DEFAULT_TERRAIN_COLOR[t].R;
mapColorsGreen[t] = DEFAULT_TERRAIN_COLOR[t].G;
mapColorsBlue[t] = DEFAULT_TERRAIN_COLOR[t].B;
}
}
#region Layer Map #region Layer Map
float xFactor = terrain.Width / twidth; float[,] layermap = new float[256, 256];
float yFactor = terrain.Height / theight;
// Scale difference between actual region size and the 256 texture being created
int xFactor = terrain.Width / 256;
int yFactor = terrain.Height / 256;
// Create 'layermap' where each value is the fractional layer number to place
// at that point. For instance, a value of 1.345 gives the blending of
// layer 1 and layer 2 for that point.
for (int y = 0; y < 256; y++)
{
for (int x = 0; x < 256; x++)
{
float height = (float)terrain[x * xFactor, y * yFactor];
float pctX = (float)x / 255f;
float pctY = (float)y / 255f;
// Use bilinear interpolation between the four corners of start height and
// height range to select the current values at this position
float startHeight = ImageUtils.Bilinear(
startHeights[0],
startHeights[2],
startHeights[1],
startHeights[3],
pctX, pctY);
startHeight = Utils.Clamp(startHeight, 0f, 255f);
float heightRange = ImageUtils.Bilinear(
heightRanges[0],
heightRanges[2],
heightRanges[1],
heightRanges[3],
pctX, pctY);
heightRange = Utils.Clamp(heightRange, 0f, 255f);
// Generate two frequencies of perlin noise based on our global position
// The magic values were taken from http://opensimulator.org/wiki/Terrain_Splatting
Vector3 vec = new Vector3
(
((float)regionPosition.X + (x * xFactor)) * 0.20319f,
((float)regionPosition.Y + (y * yFactor)) * 0.20319f,
height * 0.25f
);
float lowFreq = Perlin.noise2(vec.X * 0.222222f, vec.Y * 0.222222f) * 6.5f;
float highFreq = Perlin.turbulence2(vec.X, vec.Y, 2f) * 2.25f;
float noise = (lowFreq + highFreq) * 2f;
// Combine the current height, generated noise, start height, and height range parameters, then scale all of it
float layer = ((height + noise - startHeight) / heightRange) * 4f;
if (Single.IsNaN(layer))
layer = 0f;
layermap[x, y] = Utils.Clamp(layer, 0f, 3f);
}
}
#endregion Layer Map #endregion Layer Map
#region Texture Compositing #region Texture Compositing
Bitmap output = new Bitmap(twidth, theight, PixelFormat.Format24bppRgb); Bitmap output = new Bitmap(256, 256, PixelFormat.Format24bppRgb);
BitmapData outputData = output.LockBits(new Rectangle(0, 0, twidth, theight), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb); BitmapData outputData = output.LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
// Unsafe work as we lock down the source textures for quicker access and access the // Unsafe work as we lock down the source textures for quicker access and access the
// pixel data directly // pixel data directly
float invtwitdthMinus1 = 1.0f / (twidth - 1);
float invtheightMinus1 = 1.0f / (theight - 1);
int ty;
int tx;
float pctx;
float pcty;
float height;
float layer;
float layerDiff;
int l0;
int l1;
uint yglobalpos;
if (usecolors)
{
float a;
float b;
unsafe
{
byte* ptrO;
for (int y = 0; y < theight; ++y)
{
pcty = y * invtheightMinus1;
ptrO = (byte*)outputData.Scan0 + y * outputData.Stride;
ty = (int)(y * yFactor);
yglobalpos = (uint)ty + regionPositionY;
for (int x = 0; x < twidth; ++x)
{
tx = (int)(x * xFactor);
pctx = x * invtwitdthMinus1;
height = (float)terrain[tx, ty];
layer = getLayerTex(height, pctx, pcty,
(uint)tx + regionPositionX, yglobalpos,
startHeights, heightRanges);
// Select two textures
l0 = (int)layer;
l1 = Math.Min(l0 + 1, 3);
layerDiff = layer - l0;
a = mapColorsRed[l0];
b = mapColorsRed[l1];
*(ptrO++) = (byte)(a + layerDiff * (b - a));
a = mapColorsGreen[l0];
b = mapColorsGreen[l1];
*(ptrO++) = (byte)(a + layerDiff * (b - a));
a = mapColorsBlue[l0];
b = mapColorsBlue[l1];
*(ptrO++) = (byte)(a + layerDiff * (b - a));
}
}
}
}
else
{
float aB;
float aG;
float aR;
float bB;
float bG;
float bR;
unsafe unsafe
{ {
// Get handles to all of the texture data arrays // Get handles to all of the texture data arrays
BitmapData[] datas = new BitmapData[] BitmapData[] datas = new BitmapData[]
{ {
detailTexture[0].LockBits(new Rectangle(0, 0, 16, 16), ImageLockMode.ReadOnly, detailTexture[0].PixelFormat), detailTexture[0].LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.ReadOnly, detailTexture[0].PixelFormat),
detailTexture[1].LockBits(new Rectangle(0, 0, 16, 16), ImageLockMode.ReadOnly, detailTexture[1].PixelFormat), detailTexture[1].LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.ReadOnly, detailTexture[1].PixelFormat),
detailTexture[2].LockBits(new Rectangle(0, 0, 16, 16), ImageLockMode.ReadOnly, detailTexture[2].PixelFormat), detailTexture[2].LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.ReadOnly, detailTexture[2].PixelFormat),
detailTexture[3].LockBits(new Rectangle(0, 0, 16, 16), ImageLockMode.ReadOnly, detailTexture[3].PixelFormat) detailTexture[3].LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.ReadOnly, detailTexture[3].PixelFormat)
}; };
byte* ptr; // Compute size of each pixel data (used to address into the pixel data array)
byte* ptrO; int[] comps = new int[]
for (int y = 0; y < theight; y++)
{ {
pcty = y * invtheightMinus1; (datas[0].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3,
int ypatch = ((int)(y * yFactor) & 0x0f) * datas[0].Stride; (datas[1].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3,
ptrO = (byte*)outputData.Scan0 + y * outputData.Stride; (datas[2].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3,
ty = (int)(y * yFactor); (datas[3].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3
yglobalpos = (uint)ty + regionPositionY; };
for (int x = 0; x < twidth; x++) for (int y = 0; y < 256; y++)
{ {
tx = (int)(x * xFactor); for (int x = 0; x < 256; x++)
pctx = x * invtwitdthMinus1; {
height = (float)terrain[tx, ty]; float layer = layermap[x, y];
layer = getLayerTex(height, pctx, pcty,
(uint)tx + regionPositionX, yglobalpos,
startHeights, heightRanges);
// Select two textures // Select two textures
l0 = (int)layer; int l0 = (int)Math.Floor(layer);
layerDiff = layer - l0; int l1 = Math.Min(l0 + 1, 3);
int patchOffset = (tx & 0x0f) * 3 + ypatch; byte* ptrA = (byte*)datas[l0].Scan0 + y * datas[l0].Stride + x * comps[l0];
byte* ptrB = (byte*)datas[l1].Scan0 + y * datas[l1].Stride + x * comps[l1];
byte* ptrO = (byte*)outputData.Scan0 + y * outputData.Stride + x * 3;
ptr = (byte*)datas[l0].Scan0 + patchOffset; float aB = *(ptrA + 0);
aB = *(ptr++); float aG = *(ptrA + 1);
aG = *(ptr++); float aR = *(ptrA + 2);
aR = *(ptr);
l1 = Math.Min(l0 + 1, 3); float bB = *(ptrB + 0);
ptr = (byte*)datas[l1].Scan0 + patchOffset; float bG = *(ptrB + 1);
bB = *(ptr++); float bR = *(ptrB + 2);
bG = *(ptr++);
bR = *(ptr);
float layerDiff = layer - l0;
// Interpolate between the two selected textures // Interpolate between the two selected textures
*(ptrO++) = (byte)(aB + layerDiff * (bB - aB)); *(ptrO + 0) = (byte)Math.Floor(aB + layerDiff * (bB - aB));
*(ptrO++) = (byte)(aG + layerDiff * (bG - aG)); *(ptrO + 1) = (byte)Math.Floor(aG + layerDiff * (bG - aG));
*(ptrO++) = (byte)(aR + layerDiff * (bR - aR)); *(ptrO + 2) = (byte)Math.Floor(aR + layerDiff * (bR - aR));
} }
} }
@ -420,47 +332,57 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
for (int i = 0; i < detailTexture.Length; i++) for (int i = 0; i < detailTexture.Length; i++)
if (detailTexture[i] != null) if (detailTexture[i] != null)
detailTexture[i].Dispose(); detailTexture[i].Dispose();
}
output.UnlockBits(outputData); output.UnlockBits(outputData);
//output.Save("terr.png",ImageFormat.Png); // We generated the texture upside down, so flip it
output.RotateFlip(RotateFlipType.RotateNoneFlipY);
#endregion Texture Compositing #endregion Texture Compositing
return output; return output;
} }
private static float getLayerTex(float height, float pctX, float pctY, uint X, uint Y, public static Bitmap ResizeBitmap(Bitmap b, int nWidth, int nHeight)
float[] startHeights, float[] heightRanges)
{ {
// Use bilinear interpolation between the four corners of start height and m_log.DebugFormat("{0} ResizeBitmap. From <{1},{2}> to <{3},{4}>",
// height range to select the current values at this position LogHeader, b.Width, b.Height, nWidth, nHeight);
float startHeight = ImageUtils.Bilinear( Bitmap result = new Bitmap(nWidth, nHeight);
startHeights[0], startHeights[2], using (Graphics g = Graphics.FromImage(result))
startHeights[1], startHeights[3], g.DrawImage(b, 0, 0, nWidth, nHeight);
pctX, pctY); b.Dispose();
startHeight = Utils.Clamp(startHeight, 0f, 255f); return result;
}
public static Bitmap SplatSimple(float[] heightmap)
{
const float BASE_HSV_H = 93f / 360f;
const float BASE_HSV_S = 44f / 100f;
const float BASE_HSV_V = 34f / 100f;
float heightRange = ImageUtils.Bilinear( Bitmap img = new Bitmap(256, 256);
heightRanges[0], heightRanges[2], BitmapData bitmapData = img.LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
heightRanges[1], heightRanges[3],
pctX, pctY);
heightRange = Utils.Clamp(heightRange, 0f, 255f);
if (heightRange == 0f)
return 0;
// Generate two frequencies of perlin noise based on our global position unsafe
// The magic values were taken from http://opensimulator.org/wiki/Terrain_Splatting {
float sX = X * 0.20319f; for (int y = 255; y >= 0; y--)
float sY = Y * 0.20319f; {
for (int x = 0; x < 256; x++)
{
float normHeight = heightmap[y * 256 + x] / 255f;
normHeight = Utils.Clamp(normHeight, BASE_HSV_V, 1.0f);
float noise = Perlin.noise2(sX * 0.222222f, sY * 0.222222f) * 13.0f; Color4 color = Color4.FromHSV(BASE_HSV_H, BASE_HSV_S, normHeight);
noise += Perlin.turbulence2(sX, sY, 2f) * 4.5f;
// Combine the current height, generated noise, start height, and height range parameters, then scale all of it byte* ptr = (byte*)bitmapData.Scan0 + y * bitmapData.Stride + x * 3;
float layer = ((height + noise - startHeight) / heightRange) * 4f; *(ptr + 0) = (byte)(color.B * 255f);
return Utils.Clamp(layer, 0f, 3f); *(ptr + 1) = (byte)(color.G * 255f);
*(ptr + 2) = (byte)(color.R * 255f);
}
}
}
img.UnlockBits(bitmapData);
return img;
} }
} }
} }

165
src/Viewport.cs Normal file
View File

@ -0,0 +1,165 @@
/*
* 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 OpenSimulator 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.Drawing;
using OpenMetaverse;
namespace OpenSim.Region.CoreModules.World.Warp3DMap
{
public class Viewport
{
private const float DEG_TO_RAD = (float)Math.PI / 180f;
private static readonly Vector3 UP_DIRECTION = Vector3.UnitZ;
public Vector3 Position;
public Vector3 LookDirection;
public float FieldOfView;
public float NearPlaneDistance;
public float FarPlaneDistance;
public int Width;
public int Height;
public bool Orthographic;
public float OrthoWindowWidth;
public float OrthoWindowHeight;
public Viewport(Vector3 position, Vector3 lookDirection, float fieldOfView, float farPlaneDist, float nearPlaneDist, int width, int height)
{
// Perspective projection mode
Position = position;
LookDirection = lookDirection;
FieldOfView = fieldOfView;
FarPlaneDistance = farPlaneDist;
NearPlaneDistance = nearPlaneDist;
Width = width;
Height = height;
}
public Viewport(Vector3 position, Vector3 lookDirection, float farPlaneDist, float nearPlaneDist, int width, int height, float orthoWindowWidth, float orthoWindowHeight)
{
// Orthographic projection mode
Position = position;
LookDirection = lookDirection;
FarPlaneDistance = farPlaneDist;
NearPlaneDistance = nearPlaneDist;
Width = width;
Height = height;
OrthoWindowWidth = orthoWindowWidth;
OrthoWindowHeight = orthoWindowHeight;
Orthographic = true;
}
public Point VectorToScreen(Vector3 v)
{
Matrix4 m = GetWorldToViewportMatrix();
Vector3 screenPoint = v * m;
return new Point((int)screenPoint.X, (int)screenPoint.Y);
}
public Matrix4 GetWorldToViewportMatrix()
{
Matrix4 result = GetViewMatrix();
result *= GetPerspectiveProjectionMatrix();
result *= GetViewportMatrix();
return result;
}
public Matrix4 GetViewMatrix()
{
Vector3 zAxis = -LookDirection;
zAxis.Normalize();
Vector3 xAxis = Vector3.Cross(UP_DIRECTION, zAxis);
xAxis.Normalize();
Vector3 yAxis = Vector3.Cross(zAxis, xAxis);
Vector3 position = Position;
float offsetX = -Vector3.Dot(xAxis, position);
float offsetY = -Vector3.Dot(yAxis, position);
float offsetZ = -Vector3.Dot(zAxis, position);
return new Matrix4(
xAxis.X, yAxis.X, zAxis.X, 0f,
xAxis.Y, yAxis.Y, zAxis.Y, 0f,
xAxis.Z, yAxis.Z, zAxis.Z, 0f,
offsetX, offsetY, offsetZ, 1f);
}
public Matrix4 GetPerspectiveProjectionMatrix()
{
float aspectRatio = (float)Width / (float)Height;
float hFoV = FieldOfView * DEG_TO_RAD;
float zn = NearPlaneDistance;
float zf = FarPlaneDistance;
float xScale = 1f / (float)Math.Tan(hFoV / 2f);
float yScale = aspectRatio * xScale;
float m33 = (zf == double.PositiveInfinity) ? -1 : (zf / (zn - zf));
float m43 = zn * m33;
return new Matrix4(
xScale, 0f, 0f, 0f,
0f, yScale, 0f, 0f,
0f, 0f, m33, -1f,
0f, 0f, m43, 0f);
}
public Matrix4 GetOrthographicProjectionMatrix(float aspectRatio)
{
float w = Width;
float h = Height;
float zn = NearPlaneDistance;
float zf = FarPlaneDistance;
float m33 = 1 / (zn - zf);
float m43 = zn * m33;
return new Matrix4(
2f / w, 0f, 0f, 0f,
0f, 2f / h, 0f, 0f,
0f, 0f, m33, 0f,
0f, 0f, m43, 1f);
}
public Matrix4 GetViewportMatrix()
{
float scaleX = (float)Width * 0.5f;
float scaleY = (float)Height * 0.5f;
float offsetX = 0f + scaleX;
float offsetY = 0f + scaleY;
return new Matrix4(
scaleX, 0f, 0f, 0f,
0f, -scaleY, 0f, 0f,
0f, 0f, 1f, 0f,
offsetX, offsetY, 0f, 1f);
}
}
}

View File

@ -31,7 +31,6 @@ using System.Drawing;
using System.Drawing.Imaging; using System.Drawing.Imaging;
using System.IO; using System.IO;
using System.Reflection; using System.Reflection;
using System.Runtime;
using CSJ2K; using CSJ2K;
using Nini.Config; using Nini.Config;
@ -42,8 +41,6 @@ using Mono.Addins;
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.PhysicsModules.SharedBase;
using OpenSim.Services.Interfaces;
using OpenMetaverse; using OpenMetaverse;
using OpenMetaverse.Assets; using OpenMetaverse.Assets;
@ -51,41 +48,45 @@ using OpenMetaverse.Imaging;
using OpenMetaverse.Rendering; using OpenMetaverse.Rendering;
using OpenMetaverse.StructuredData; using OpenMetaverse.StructuredData;
using WarpRenderer = Warp3D.Warp3D; using WarpRenderer = global::Warp3D.Warp3D;
using System.Drawing.Drawing2D;
[assembly: Addin("Warp3DCachedImageModule", "1.0")]
[assembly: AddinDependency("OpenSim.Region.Framework", OpenSim.VersionInfo.VersionNumber)]
namespace OpenSim.Region.CoreModules.World.Warp3DMap namespace OpenSim.Region.CoreModules.World.Warp3DMap
{ {
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "Warp3DCACHEDImageModule")] [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "Warp3DCachedImageModule")]
public class Warp3DImageModule : IMapImageGenerator, INonSharedRegionModule public class Warp3DImageModule : IMapImageGenerator, INonSharedRegionModule
{ {
private static readonly UUID TEXTURE_METADATA_MAGIC = new UUID("802dc0e0-f080-4931-8b57-d1be8611c4f3");
private static readonly Color4 WATER_COLOR = new Color4(29, 72, 96, 216); private static readonly Color4 WATER_COLOR = new Color4(29, 72, 96, 216);
// private static readonly Color4 WATER_COLOR = new Color4(29, 72, 96, 128);
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
#pragma warning disable 414 #pragma warning disable 414
private static string LogHeader = "[WARP 3D CACHED IMAGE MODULE]"; private static string LogHeader = "[CACHED WARP 3D IMAGE MODULE]";
#pragma warning restore 414 #pragma warning restore 414
internal Scene m_scene; private Scene m_scene;
private IRendering m_primMesher; private IRendering m_primMesher;
internal IJ2KDecoder m_imgDecoder; private Dictionary<UUID, Color4> m_colors = new Dictionary<UUID, Color4>();
// caches per rendering
private Dictionary<string, warp_Texture> m_warpTextures = new Dictionary<string, warp_Texture>();
private Dictionary<UUID, int> m_colors = new Dictionary<UUID, int>();
private IConfigSource m_config; private IConfigSource m_config;
private bool m_drawPrimVolume = true; // true if should render the prims on the tile private bool m_drawPrimVolume = true; // true if should render the prims on the tile
private bool m_textureTerrain = true; // true if to create terrain splatting texture private bool m_textureTerrain = true; // true if to create terrain splatting texture
private bool m_textureAverageTerrain = false; // replace terrain textures by their average color
private bool m_texturePrims = true; // true if should texture the rendered prims private bool m_texturePrims = true; // true if should texture the rendered prims
private float m_texturePrimSize = 48f; // size of prim before we consider texturing it private float m_texturePrimSize = 48f; // size of prim before we consider texturing it
private bool m_renderMeshes = false; // true if to render meshes rather than just bounding boxes private bool m_renderMeshes = false; // true if to render meshes rather than just bounding boxes
private String m_cacheDirectory = "";
private String m_cacheDirectory = "MapImageCache";
private bool m_Enabled = false; private bool m_Enabled = false;
private bool m_enable_date = false;
private bool m_enable_regionName = false;
private bool m_enable_regionPosition = false;
private bool m_enable_refreshEveryMonth = false;
private bool m_enable_HostedBy = false;
private String m_enable_HostedByText = "";
// private Bitmap lastImage = null; // private Bitmap lastImage = null;
private DateTime lastImageTime = DateTime.MinValue; private DateTime lastImageTime = DateTime.MinValue;
@ -98,33 +99,34 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
string[] configSections = new string[] { "Map", "Startup" }; string[] configSections = new string[] { "Map", "Startup" };
if (Util.GetConfigVarFromSections<string>( if (Util.GetConfigVarFromSections<string>(
m_config, "MapImageModule", configSections, "MapImageModule") != "Warp3DImageModule") m_config, "MapImageModule", configSections, "MapImageModule") != "Warp3DCachedImageModule")
return; return;
m_Enabled = true; m_Enabled = true;
m_drawPrimVolume = m_drawPrimVolume
Util.GetConfigVarFromSections<bool>(m_config, "DrawPrimOnMapTile", configSections, m_drawPrimVolume); = Util.GetConfigVarFromSections<bool>(m_config, "DrawPrimOnMapTile", configSections, m_drawPrimVolume);
m_textureTerrain = m_textureTerrain
Util.GetConfigVarFromSections<bool>(m_config, "TextureOnMapTile", configSections, m_textureTerrain); = Util.GetConfigVarFromSections<bool>(m_config, "TextureOnMapTile", configSections, m_textureTerrain);
m_textureAverageTerrain = m_texturePrims
Util.GetConfigVarFromSections<bool>(m_config, "AverageTextureColorOnMapTile", configSections, m_textureAverageTerrain); = Util.GetConfigVarFromSections<bool>(m_config, "TexturePrims", configSections, m_texturePrims);
if (m_textureAverageTerrain) m_texturePrimSize
m_textureTerrain = true; = Util.GetConfigVarFromSections<float>(m_config, "TexturePrimSize", configSections, m_texturePrimSize);
m_texturePrims = m_renderMeshes
Util.GetConfigVarFromSections<bool>(m_config, "TexturePrims", configSections, m_texturePrims); = Util.GetConfigVarFromSections<bool>(m_config, "RenderMeshes", configSections, m_renderMeshes);
m_texturePrimSize =
Util.GetConfigVarFromSections<float>(m_config, "TexturePrimSize", configSections, m_texturePrimSize);
m_renderMeshes =
Util.GetConfigVarFromSections<bool>(m_config, "RenderMeshes", configSections, m_renderMeshes);
m_cacheDirectory m_cacheDirectory
= Util.GetConfigVarFromSections<string>(m_config, "CacheDirectory", configSections, System.IO.Path.Combine(new DirectoryInfo(".").FullName, m_cacheDirectory)); = Util.GetConfigVarFromSections<string>(m_config, "CacheDirectory", configSections, System.IO.Path.Combine(new DirectoryInfo(".").FullName, "MapImageCache"));
m_enable_date = Util.GetConfigVarFromSections<bool>(m_config, "enableDate", configSections, false);
m_enable_regionName = Util.GetConfigVarFromSections<bool>(m_config, "enableName", configSections, false);
m_enable_regionPosition = Util.GetConfigVarFromSections<bool>(m_config, "enablePosition", configSections, false);
m_enable_refreshEveryMonth = Util.GetConfigVarFromSections<bool>(m_config, "RefreshEveryMonth", configSections, true);
m_enable_HostedBy = Util.GetConfigVarFromSections<bool>(m_config, "enableHostedBy", configSections, false);
m_enable_HostedByText = Util.GetConfigVarFromSections<String>(m_config, "HosterText", configSections, String.Empty);
if (!Directory.Exists(m_cacheDirectory)) if (!Directory.Exists(m_cacheDirectory))
Directory.CreateDirectory(m_cacheDirectory); Directory.CreateDirectory(m_cacheDirectory);
} }
public void AddRegion(Scene scene) public void AddRegion(Scene scene)
@ -145,10 +147,6 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
public void RegionLoaded(Scene scene) public void RegionLoaded(Scene scene)
{ {
if (!m_Enabled)
return;
m_imgDecoder = m_scene.RequestModuleInterface<IJ2KDecoder>();
} }
public void RemoveRegion(Scene scene) public void RemoveRegion(Scene scene)
@ -161,7 +159,7 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
public string Name public string Name
{ {
get { return "Warp3DCACHEDImageModule"; } get { return "Warp3DCachedImageModule"; }
} }
public Type ReplaceableInterface public Type ReplaceableInterface
@ -172,17 +170,83 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
#endregion #endregion
#region IMapImageGenerator Members #region IMapImageGenerator Members
public static string fillInt(int _i, int _l)
{
String _return = _i.ToString();
private Vector3 cameraPos; while(_return.Length < _l)
private Vector3 cameraDir; {
private int viewWitdh = 256; _return = 0 + _return;
private int viewHeight = 256; }
private float fov;
private bool orto; return _return;
}
public static int getCurrentUnixTime()
{
return (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
}
public static String unixTimeToDateString(int unixTime)
{
DateTime unixStart = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
long unixTimeStampInTicks = (long)(unixTime * TimeSpan.TicksPerSecond);
DateTime _date = new DateTime(unixStart.Ticks + unixTimeStampInTicks, System.DateTimeKind.Utc);
return fillInt(_date.Day, 2) + "." + fillInt(_date.Month, 2) + "." + fillInt(_date.Year, 4) + " " + fillInt(_date.Hour, 2) + ":" + fillInt(_date.Minute, 2);
}
private void writeDateOnMap(ref Bitmap _map)
{
RectangleF rectf = new RectangleF(2, 1, 200, 25);
Graphics g = Graphics.FromImage(_map);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawString(unixTimeToDateString(getCurrentUnixTime()), new Font("Arial", 8), Brushes.White, rectf);
g.Flush();
}
private void writeNameOnMap(ref Bitmap _map)
{
RectangleF rectf = new RectangleF(2, m_scene.RegionInfo.RegionSizeX - 15, 200, 25);
Graphics g = Graphics.FromImage(_map);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawString(m_scene.Name, new Font("Arial", 8), Brushes.White, rectf);
g.Flush();
}
private void writePositionOnMap(ref Bitmap _map)
{
RectangleF rectf = new RectangleF(m_scene.RegionInfo.RegionSizeY - 75, m_scene.RegionInfo.RegionSizeX - 15, 80, 25);
Graphics g = Graphics.FromImage(_map);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawString("<" + m_scene.RegionInfo.RegionLocX + " " + m_scene.RegionInfo.RegionLocY + ">", new Font("Arial", 8), Brushes.White, rectf);
g.Flush();
}
private void writeHostedByOnMap(ref Bitmap _map)
{
RectangleF rectf = new RectangleF(2, m_scene.RegionInfo.RegionSizeX - 15, 200, 25);
Graphics g = Graphics.FromImage(_map);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawString(m_enable_HostedByText, new Font("Arial", 8), Brushes.Gray, rectf);
g.Flush();
}
public Bitmap CreateMapTile() public Bitmap CreateMapTile()
{ {
if ((File.GetCreationTime(System.IO.Path.Combine(m_cacheDirectory, m_scene.RegionInfo.RegionID + ".bmp")).Month != DateTime.Now.Month)) if ((File.GetCreationTime(System.IO.Path.Combine(m_cacheDirectory, m_scene.RegionInfo.RegionID + ".bmp")).Month != DateTime.Now.Month) && m_enable_refreshEveryMonth == true)
File.Delete(System.IO.Path.Combine(m_cacheDirectory, m_scene.RegionInfo.RegionID + ".bmp")); File.Delete(System.IO.Path.Combine(m_cacheDirectory, m_scene.RegionInfo.RegionID + ".bmp"));
if(File.Exists(System.IO.Path.Combine(m_cacheDirectory, m_scene.RegionInfo.RegionID + ".bmp"))) if(File.Exists(System.IO.Path.Combine(m_cacheDirectory, m_scene.RegionInfo.RegionID + ".bmp")))
@ -191,86 +255,100 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
} }
else else
{ {
/* this must be on all map, not just its image
if ((DateTime.Now - lastImageTime).TotalSeconds < 3600)
{
return (Bitmap)lastImage.Clone();
}
*/
List<string> renderers = RenderingLoader.ListRenderers(Util.ExecutingDirectory()); List<string> renderers = RenderingLoader.ListRenderers(Util.ExecutingDirectory());
if (renderers.Count > 0) if (renderers.Count > 0)
{ {
m_primMesher = RenderingLoader.LoadRenderer(renderers[0]); m_primMesher = RenderingLoader.LoadRenderer(renderers[0]);
} }
cameraPos = new Vector3( Vector3 camPos = new Vector3(
(m_scene.RegionInfo.RegionSizeX) * 0.5f, m_scene.RegionInfo.RegionSizeX / 2 - 0.5f,
(m_scene.RegionInfo.RegionSizeY) * 0.5f, m_scene.RegionInfo.RegionSizeY / 2 - 0.5f,
4096f); 221.7025033688163f);
// Viewport viewing down onto the region
Viewport viewport = new Viewport(camPos, -Vector3.UnitZ, 1024f, 0.1f,
(int)m_scene.RegionInfo.RegionSizeX, (int)m_scene.RegionInfo.RegionSizeY,
(float)m_scene.RegionInfo.RegionSizeX, (float)m_scene.RegionInfo.RegionSizeY);
cameraDir = -Vector3.UnitZ; Bitmap tile = CreateMapTile(viewport, false);
viewWitdh = (int)m_scene.RegionInfo.RegionSizeX;
viewHeight = (int)m_scene.RegionInfo.RegionSizeY;
orto = true;
// fov = warp_Math.rad2deg(2f * (float)Math.Atan2(viewWitdh, 4096f)); if (m_enable_date)
// orto = false; writeDateOnMap(ref tile);
if (m_enable_regionName)
writeNameOnMap(ref tile);
if (m_enable_regionPosition)
writePositionOnMap(ref tile);
if (m_enable_HostedBy)
writeHostedByOnMap(ref tile);
Bitmap tile = GenImage();
// image may be reloaded elsewhere, so no compression format
string filename = "MAP-" + m_scene.RegionInfo.RegionID.ToString() + ".png";
tile.Save(filename, ImageFormat.Png);
m_primMesher = null;
tile.Save(System.IO.Path.Combine(m_cacheDirectory, m_scene.RegionInfo.RegionID + ".bmp")); tile.Save(System.IO.Path.Combine(m_cacheDirectory, m_scene.RegionInfo.RegionID + ".bmp"));
return tile;
}
}
public Bitmap CreateViewImage(Vector3 camPos, Vector3 camDir, float pfov, int width, int height, bool useTextures)
{
List<string> renderers = RenderingLoader.ListRenderers(Util.ExecutingDirectory());
if (renderers.Count > 0)
{
m_primMesher = RenderingLoader.LoadRenderer(renderers[0]);
}
cameraPos = camPos;
cameraDir = camDir;
viewWitdh = width;
viewHeight = height;
fov = pfov;
orto = false;
Bitmap tile = GenImage();
m_primMesher = null; m_primMesher = null;
return tile; return tile;
/*
lastImage = tile;
lastImageTime = DateTime.Now;
return (Bitmap)lastImage.Clone();
*/
}
} }
private Bitmap GenImage() public Bitmap CreateViewImage(Vector3 camPos, Vector3 camDir, float fov, int width, int height, bool useTextures)
{
Viewport viewport = new Viewport(camPos, camDir, fov, Constants.RegionSize, 0.1f, width, height);
return CreateMapTile(viewport, useTextures);
}
public Bitmap CreateMapTile(Viewport viewport, bool useTextures)
{ {
m_colors.Clear(); m_colors.Clear();
m_warpTextures.Clear();
int width = viewport.Width;
int height = viewport.Height;
WarpRenderer renderer = new WarpRenderer(); WarpRenderer renderer = new WarpRenderer();
if (!renderer.CreateScene(viewWitdh, viewHeight)) if(!renderer.CreateScene(width, height))
return new Bitmap(viewWitdh, viewHeight); return new Bitmap(width,height);
#region Camera #region Camera
warp_Vector pos = ConvertVector(cameraPos); warp_Vector pos = ConvertVector(viewport.Position);
warp_Vector lookat = warp_Vector.add(pos, ConvertVector(cameraDir)); warp_Vector lookat = warp_Vector.add(ConvertVector(viewport.Position), ConvertVector(viewport.LookDirection));
if (orto)
renderer.Scene.defaultCamera.setOrthographic(true, viewWitdh, viewHeight);
else
renderer.Scene.defaultCamera.setFov(fov);
renderer.Scene.defaultCamera.setPos(pos); renderer.Scene.defaultCamera.setPos(pos);
renderer.Scene.defaultCamera.lookAt(lookat); renderer.Scene.defaultCamera.lookAt(lookat);
if (viewport.Orthographic)
{
renderer.Scene.defaultCamera.setOrthographic(true,viewport.OrthoWindowWidth, viewport.OrthoWindowHeight);
}
else
{
float fov = viewport.FieldOfView;
fov *= 1.75f; // FIXME: ???
renderer.Scene.defaultCamera.setFov(fov);
}
#endregion Camera #endregion Camera
renderer.Scene.setAmbient(warp_Color.getColor(192, 191, 173)); renderer.Scene.addLight("Light1", new warp_Light(new warp_Vector(1.0f, 0.5f, 1f), 0xffffff, 0, 320, 40));
renderer.Scene.addLight("Light1", new warp_Light(new warp_Vector(0f, 1f, 8f), warp_Color.White, 0, 320, 40)); renderer.Scene.addLight("Light2", new warp_Light(new warp_Vector(-1f, -1f, 1f), 0xffffff, 0, 100, 40));
CreateWater(renderer); CreateWater(renderer);
CreateTerrain(renderer); CreateTerrain(renderer, m_textureTerrain);
if (m_drawPrimVolume) if (m_drawPrimVolume)
CreateAllPrims(renderer); CreateAllPrims(renderer, useTextures);
renderer.Render(); renderer.Render();
Bitmap bitmap = renderer.Scene.getImage(); Bitmap bitmap = renderer.Scene.getImage();
@ -278,12 +356,11 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
renderer.Scene.destroy(); renderer.Scene.destroy();
renderer.Reset(); renderer.Reset();
renderer = null; renderer = null;
viewport = null;
m_colors.Clear(); m_colors.Clear();
m_warpTextures.Clear();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect(); GC.Collect();
m_log.Debug("[WARP 3D IMAGE MODULE]: GC.Collect()");
return bitmap; return bitmap;
} }
@ -293,12 +370,12 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
try try
{ {
using (Bitmap mapbmp = CreateMapTile()) using (Bitmap mapbmp = CreateMapTile())
return OpenJPEG.EncodeFromImage(mapbmp, false); return OpenJPEG.EncodeFromImage(mapbmp, true);
} }
catch (Exception e) catch (Exception e)
{ {
// JPEG2000 encoder failed // JPEG2000 encoder failed
m_log.Error("[WARP 3D CACHED IMAGE MODULE]: Failed generating terrain map: ", e); m_log.Error("[WARP 3D IMAGE MODULE]: Failed generating terrain map: ", e);
} }
return null; return null;
@ -314,6 +391,8 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
float waterHeight = (float)m_scene.RegionInfo.RegionSettings.WaterHeight; float waterHeight = (float)m_scene.RegionInfo.RegionSettings.WaterHeight;
warp_Material waterColorMaterial = new warp_Material(ConvertColor(WATER_COLOR)); warp_Material waterColorMaterial = new warp_Material(ConvertColor(WATER_COLOR));
waterColorMaterial.setReflectivity(0); // match water color with standard map module thanks lkalif
waterColorMaterial.setTransparency((byte)((1f - WATER_COLOR.A) * 255f));
renderer.Scene.addMaterial("WaterColor", waterColorMaterial); renderer.Scene.addMaterial("WaterColor", waterColorMaterial);
for (int x = 0; x < m_scene.RegionInfo.RegionSizeX / 256; x++) for (int x = 0; x < m_scene.RegionInfo.RegionSizeX / 256; x++)
@ -328,9 +407,9 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
} }
// Add a terrain to the renderer. // Add a terrain to the renderer.
// Note that we create a 'low resolution' 257x257 vertex terrain rather than trying for // Note that we create a 'low resolution' 256x256 vertex terrain rather than trying for
// full resolution. This saves a lot of memory especially for very large regions. // full resolution. This saves a lot of memory especially for very large regions.
private void CreateTerrain(WarpRenderer renderer) private void CreateTerrain(WarpRenderer renderer, bool textureTerrain)
{ {
ITerrainChannel terrain = m_scene.Heightmap; ITerrainChannel terrain = m_scene.Heightmap;
@ -338,67 +417,39 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
float regionsy = m_scene.RegionInfo.RegionSizeY; float regionsy = m_scene.RegionInfo.RegionSizeY;
// 'diff' is the difference in scale between the real region size and the size of terrain we're buiding // 'diff' is the difference in scale between the real region size and the size of terrain we're buiding
float diff = regionsx / 256f;
int bitWidth;
int bitHeight;
const double log2inv = 1.4426950408889634073599246810019;
bitWidth = (int)Math.Ceiling((Math.Log(terrain.Width) * log2inv));
bitHeight = (int)Math.Ceiling((Math.Log(terrain.Height) * log2inv));
if (bitWidth > 8) // more than 256 is very heavy :(
bitWidth = 8;
if (bitHeight > 8)
bitHeight = 8;
int twidth = (int)Math.Pow(2, bitWidth);
int theight = (int)Math.Pow(2, bitHeight);
float diff = regionsx / twidth;
int npointsx =(int)(regionsx / diff); int npointsx =(int)(regionsx / diff);
int npointsy =(int)(regionsy / diff); int npointsy =(int)(regionsy / diff);
float invsx = 1.0f / (npointsx * diff); float invsx = 1.0f / regionsx;
float invsy = 1.0f / (npointsy * diff); float invsy = 1.0f / (float)m_scene.RegionInfo.RegionSizeY;
npointsx++;
npointsy++;
// Create all the vertices for the terrain // Create all the vertices for the terrain
warp_Object obj = new warp_Object(); warp_Object obj = new warp_Object();
warp_Vector pos; for (float y = 0; y < regionsy; y += diff)
float x, y;
float tv;
for (y = 0; y < regionsy; y += diff)
{ {
tv = y * invsy; for (float x = 0; x < regionsx; x += diff)
for (x = 0; x < regionsx; x += diff)
{ {
pos = ConvertVector(x, y, (float)terrain[(int)x, (int)y]); warp_Vector pos = ConvertVector(x , y , (float)terrain[(int)x, (int)y]);
obj.addVertex(new warp_Vertex(pos, x * invsx, tv)); obj.addVertex(new warp_Vertex(pos, x * invsx, 1.0f - y * invsy));
} }
pos = ConvertVector(x, y, (float)terrain[(int)(x - diff), (int)y]);
obj.addVertex(new warp_Vertex(pos, 1.0f, tv));
} }
int lastY = (int)(y - diff); // Now that we have all the vertices, make another pass and
for (x = 0; x < regionsx; x += diff) // create the list of triangle indices.
{ float invdiff = 1.0f / diff;
pos = ConvertVector(x, y, (float)terrain[(int)x, lastY]);
obj.addVertex(new warp_Vertex(pos, x * invsx, 1.0f));
}
pos = ConvertVector(x, y, (float)terrain[(int)(x - diff), lastY]);
obj.addVertex(new warp_Vertex(pos, 1.0f, 1.0f));
// create triangles.
int limx = npointsx - 1; int limx = npointsx - 1;
int limy = npointsy - 1; int limy = npointsy - 1;
for (int j = 0; j < limy; j++) for (float y = 0; y < regionsy; y += diff)
{ {
for (int i = 0; i < limx; i++) for (float x = 0; x < regionsx; x += diff)
{ {
int v = j * npointsx + i; float newX = x * invdiff;
float newY = y * invdiff;
if (newX < limx && newY < limy)
{
int v = (int)newY * npointsx + (int)newX;
// Make two triangles for each of the squares in the grid of vertices // Make two triangles for each of the squares in the grid of vertices
obj.addTriangle( obj.addTriangle(
@ -412,6 +463,7 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
v + 1); v + 1);
} }
} }
}
renderer.Scene.addObject("Terrain", obj); renderer.Scene.addObject("Terrain", obj);
@ -436,19 +488,23 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
heightRanges[2] = (float)regionInfo.Elevation2SE; heightRanges[2] = (float)regionInfo.Elevation2SE;
heightRanges[3] = (float)regionInfo.Elevation2NE; heightRanges[3] = (float)regionInfo.Elevation2NE;
uint globalX, globalY;
Util.RegionHandleToWorldLoc(m_scene.RegionInfo.RegionHandle, out globalX, out globalY);
warp_Texture texture; warp_Texture texture;
using (Bitmap image = TerrainSplat.Splat(terrain, textureIDs, startHeights, heightRanges, using (Bitmap image = TerrainSplat.Splat(
m_scene.RegionInfo.WorldLocX, m_scene.RegionInfo.WorldLocY, terrain, textureIDs, startHeights, heightRanges,
m_scene.AssetService, m_imgDecoder, m_textureTerrain, m_textureAverageTerrain, new Vector3d(globalX, globalY, 0.0), m_scene.AssetService, textureTerrain))
twidth, twidth))
texture = new warp_Texture(image); texture = new warp_Texture(image);
warp_Material material = new warp_Material(texture); warp_Material material = new warp_Material(texture);
renderer.Scene.addMaterial("TerrainMat", material); material.setReflectivity(50);
renderer.SetObjectMaterial("Terrain", "TerrainMat"); renderer.Scene.addMaterial("TerrainColor", material);
renderer.Scene.material("TerrainColor").setReflectivity(0); // reduces tile seams a bit thanks lkalif
renderer.SetObjectMaterial("Terrain", "TerrainColor");
} }
private void CreateAllPrims(WarpRenderer renderer) private void CreateAllPrims(WarpRenderer renderer, bool useTextures)
{ {
if (m_primMesher == null) if (m_primMesher == null)
return; return;
@ -457,33 +513,22 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
delegate(SceneObjectGroup group) delegate(SceneObjectGroup group)
{ {
foreach (SceneObjectPart child in group.Parts) foreach (SceneObjectPart child in group.Parts)
CreatePrim(renderer, child); CreatePrim(renderer, child, useTextures);
} }
); );
} }
private void CreatePrim(WarpRenderer renderer, SceneObjectPart prim) private void CreatePrim(WarpRenderer renderer, SceneObjectPart prim, bool useTextures)
{ {
const float MIN_SIZE_SQUARE = 4f;
if ((PCode)prim.Shape.PCode != PCode.Prim) if ((PCode)prim.Shape.PCode != PCode.Prim)
return; return;
float primScaleLenSquared = prim.Scale.LengthSquared();
warp_Vector primPos = ConvertVector(prim.GetWorldPosition()); if (primScaleLenSquared < MIN_SIZE_SQUARE)
warp_Quaternion primRot = ConvertQuaternion(prim.GetWorldRotation());
warp_Matrix m = warp_Matrix.quaternionMatrix(primRot);
float screenFactor = renderer.Scene.EstimateBoxProjectedArea(primPos, ConvertVector(prim.Scale), m);
if (screenFactor < 0)
return; return;
int p2 = (int)(-(float)Math.Log(screenFactor) * 1.442695f * 0.5 - 1);
if (p2 < 0)
p2 = 0;
else if (p2 > 3)
p2 = 3;
DetailLevel lod = (DetailLevel)(3 - p2);
FacetedMesh renderMesh = null; FacetedMesh renderMesh = null;
Primitive omvPrim = prim.Shape.ToOmvPrimitive(prim.OffsetPosition, prim.RotationOffset); Primitive omvPrim = prim.Shape.ToOmvPrimitive(prim.OffsetPosition, prim.RotationOffset);
@ -499,19 +544,27 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
if (omvPrim.Sculpt.Type == SculptType.Mesh) if (omvPrim.Sculpt.Type == SculptType.Mesh)
{ {
AssetMesh meshAsset = new AssetMesh(omvPrim.Sculpt.SculptTexture, sculptAsset); AssetMesh meshAsset = new AssetMesh(omvPrim.Sculpt.SculptTexture, sculptAsset);
FacetedMesh.TryDecodeFromAsset(omvPrim, meshAsset, lod, out renderMesh); FacetedMesh.TryDecodeFromAsset(omvPrim, meshAsset, DetailLevel.Highest, out renderMesh);
meshAsset = null; meshAsset = null;
} }
else // It's sculptie else // It's sculptie
{ {
if (m_imgDecoder != null) IJ2KDecoder imgDecoder = m_scene.RequestModuleInterface<IJ2KDecoder>();
if(imgDecoder != null)
{ {
Image sculpt = m_imgDecoder.DecodeToImage(sculptAsset); try
{
Image sculpt = imgDecoder.DecodeToImage(sculptAsset);
if (sculpt != null) if (sculpt != null)
{ {
renderMesh = m_primMesher.GenerateFacetedSculptMesh(omvPrim, (Bitmap)sculpt, lod); renderMesh = m_primMesher.GenerateFacetedSculptMesh(omvPrim, (Bitmap)sculpt,
DetailLevel.Medium);
sculpt.Dispose(); sculpt.Dispose();
} }
}catch(Exception _e)
{
m_log.Error(LogHeader + "Fail to read asset data for scene object " + omvPrim.GroupID + "(" + omvPrim.Properties.Name + ")");
}
} }
} }
} }
@ -521,7 +574,7 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
// If not a mesh or sculptie, try the regular mesher // If not a mesh or sculptie, try the regular mesher
if (renderMesh == null) if (renderMesh == null)
{ {
renderMesh = m_primMesher.GenerateFacetedMesh(omvPrim, lod); renderMesh = m_primMesher.GenerateFacetedMesh(omvPrim, DetailLevel.Medium);
} }
if (renderMesh == null) if (renderMesh == null)
@ -541,32 +594,6 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
continue; continue;
warp_Object faceObj = new warp_Object(); warp_Object faceObj = new warp_Object();
Primitive.TextureEntryFace teFace = prim.Shape.Textures.GetFace((uint)i);
Color4 faceColor = teFace.RGBA;
if (faceColor.A == 0)
continue;
string materialName = String.Empty;
if (m_texturePrims)
{
// if(lod > DetailLevel.Low)
{
// materialName = GetOrCreateMaterial(renderer, faceColor, teFace.TextureID, lod == DetailLevel.Low);
materialName = GetOrCreateMaterial(renderer, faceColor, teFace.TextureID, false);
if (String.IsNullOrEmpty(materialName))
continue;
int c = renderer.Scene.material(materialName).getColor();
if ((c & warp_Color.MASKALPHA) == 0)
continue;
}
}
else
materialName = GetOrCreateMaterial(renderer, faceColor);
if (renderer.Scene.material(materialName).getTexture() == null)
{
// uv map details dont not matter for color;
for (int j = 0; j < face.Vertices.Count; j++) for (int j = 0; j < face.Vertices.Count; j++)
{ {
Vertex v = face.Vertices[j]; Vertex v = face.Vertices[j];
@ -574,54 +601,6 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
warp_Vertex vert = new warp_Vertex(pos, v.TexCoord.X, v.TexCoord.Y); warp_Vertex vert = new warp_Vertex(pos, v.TexCoord.X, v.TexCoord.Y);
faceObj.addVertex(vert); faceObj.addVertex(vert);
} }
}
else
{
float tu;
float tv;
float offsetu = teFace.OffsetU + 0.5f;
float offsetv = teFace.OffsetV + 0.5f;
float scaleu = teFace.RepeatU;
float scalev = teFace.RepeatV;
float rotation = teFace.Rotation;
float rc = 0;
float rs = 0;
if (rotation != 0)
{
rc = (float)Math.Cos(rotation);
rs = (float)Math.Sin(rotation);
}
for (int j = 0; j < face.Vertices.Count; j++)
{
warp_Vertex vert;
Vertex v = face.Vertices[j];
warp_Vector pos = ConvertVector(v.Position);
tu = v.TexCoord.X - 0.5f;
tv = 0.5f - v.TexCoord.Y;
if (rotation != 0)
{
float tur = tu * rc - tv * rs;
float tvr = tu * rs + tv * rc;
tur *= scaleu;
tur += offsetu;
tvr *= scalev;
tvr += offsetv;
vert = new warp_Vertex(pos, tur, tvr);
}
else
{
tu *= scaleu;
tu += offsetu;
tv *= scalev;
tv += offsetv;
vert = new warp_Vertex(pos, tu, tv);
}
faceObj.addVertex(vert);
}
}
for (int j = 0; j < face.Indices.Count; j += 3) for (int j = 0; j < face.Indices.Count; j += 3)
{ {
@ -631,30 +610,40 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
face.Indices[j + 2]); face.Indices[j + 2]);
} }
faceObj.scaleSelf(prim.Scale.X, prim.Scale.Z, prim.Scale.Y); Primitive.TextureEntryFace teFace = prim.Shape.Textures.GetFace((uint)i);
Color4 faceColor = GetFaceColor(teFace);
string materialName = String.Empty;
if (m_texturePrims && primScaleLenSquared > m_texturePrimSize*m_texturePrimSize)
materialName = GetOrCreateMaterial(renderer, faceColor, teFace.TextureID);
else
materialName = GetOrCreateMaterial(renderer, faceColor);
warp_Vector primPos = ConvertVector(prim.GetWorldPosition());
warp_Quaternion primRot = ConvertQuaternion(prim.GetWorldRotation());
warp_Matrix m = warp_Matrix.quaternionMatrix(primRot);
faceObj.transform(m); faceObj.transform(m);
faceObj.setPos(primPos); faceObj.setPos(primPos);
faceObj.scaleSelf(prim.Scale.X, prim.Scale.Z, prim.Scale.Y);
renderer.Scene.addObject(meshName, faceObj); renderer.Scene.addObject(meshName, faceObj);
renderer.SetObjectMaterial(meshName, materialName); renderer.SetObjectMaterial(meshName, materialName);
} }
} }
private int GetFaceColor(Primitive.TextureEntryFace face) private Color4 GetFaceColor(Primitive.TextureEntryFace face)
{ {
int color; Color4 color;
Color4 ctmp = Color4.White;
if (face.TextureID == UUID.Zero) if (face.TextureID == UUID.Zero)
return warp_Color.White; return face.RGBA;
if (!m_colors.TryGetValue(face.TextureID, out color)) if (!m_colors.TryGetValue(face.TextureID, out color))
{ {
bool fetched = false; bool fetched = false;
// Attempt to fetch the texture metadata // Attempt to fetch the texture metadata
string cacheName = "MAPCLR" + face.TextureID.ToString(); UUID metadataID = UUID.Combine(face.TextureID, TEXTURE_METADATA_MAGIC);
AssetBase metadata = m_scene.AssetService.GetCached(cacheName); AssetBase metadata = m_scene.AssetService.GetCached(metadataID.ToString());
if (metadata != null) if (metadata != null)
{ {
OSDMap map = null; OSDMap map = null;
@ -662,7 +651,7 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
if (map != null) if (map != null)
{ {
ctmp = map["X-RGBA"].AsColor4(); color = map["X-JPEG2000-RGBA"].AsColor4();
fetched = true; fetched = true;
} }
} }
@ -675,16 +664,16 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
if (textureAsset != null) if (textureAsset != null)
{ {
int width, height; int width, height;
ctmp = GetAverageColor(textureAsset.FullID, textureAsset.Data, out width, out height); color = GetAverageColor(textureAsset.FullID, textureAsset.Data, out width, out height);
OSDMap data = new OSDMap { { "X-RGBA", OSD.FromColor4(ctmp) } }; OSDMap data = new OSDMap { { "X-JPEG2000-RGBA", OSD.FromColor4(color) } };
metadata = new AssetBase metadata = new AssetBase
{ {
Data = System.Text.Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(data)), Data = System.Text.Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(data)),
Description = "Metadata for texture color" + face.TextureID.ToString(), Description = "Metadata for JPEG2000 texture " + face.TextureID.ToString(),
Flags = AssetFlags.Collectable, Flags = AssetFlags.Collectable,
FullID = UUID.Zero, FullID = metadataID,
ID = cacheName, ID = metadataID.ToString(),
Local = true, Local = true,
Temporary = true, Temporary = true,
Name = String.Empty, Name = String.Empty,
@ -694,14 +683,14 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
} }
else else
{ {
ctmp = new Color4(0.5f, 0.5f, 0.5f, 1.0f); color = new Color4(0.5f, 0.5f, 0.5f, 1.0f);
} }
} }
color = ConvertColor(ctmp);
m_colors[face.TextureID] = color; m_colors[face.TextureID] = color;
} }
return color; return color * face.RGBA;
} }
private string GetOrCreateMaterial(WarpRenderer renderer, Color4 color) private string GetOrCreateMaterial(WarpRenderer renderer, Color4 color)
@ -713,32 +702,26 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
return name; return name;
renderer.AddMaterial(name, ConvertColor(color)); renderer.AddMaterial(name, ConvertColor(color));
if (color.A < 1f)
renderer.Scene.material(name).setTransparency((byte)((1f - color.A) * 255f));
return name; return name;
} }
public string GetOrCreateMaterial(WarpRenderer renderer, Color4 faceColor, UUID textureID, bool useAverageTextureColor) public string GetOrCreateMaterial(WarpRenderer renderer, Color4 faceColor, UUID textureID)
{ {
int color = ConvertColor(faceColor); string materialName = "Color-" + faceColor.ToString() + "-Texture-" + textureID.ToString();
string idstr = textureID.ToString() + color.ToString();
string materialName = "MAPMAT" + idstr;
if (renderer.Scene.material(materialName) != null) if (renderer.Scene.material(materialName) == null)
return materialName; {
renderer.AddMaterial(materialName, ConvertColor(faceColor));
warp_Material mat = new warp_Material(); if (faceColor.A < 1f)
{
renderer.Scene.material(materialName).setTransparency((byte) ((1f - faceColor.A)*255f));
}
warp_Texture texture = GetTexture(textureID); warp_Texture texture = GetTexture(textureID);
if (texture != null) if (texture != null)
{ renderer.Scene.material(materialName).setTexture(texture);
if (useAverageTextureColor)
color = warp_Color.multiply(color, texture.averageColor);
else
mat.setTexture(texture);
} }
else
color = warp_Color.multiply(color, warp_Color.Grey);
mat.setColor(color);
renderer.Scene.addMaterial(materialName, mat);
return materialName; return materialName;
} }
@ -746,27 +729,24 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
private warp_Texture GetTexture(UUID id) private warp_Texture GetTexture(UUID id)
{ {
warp_Texture ret = null; warp_Texture ret = null;
if (id == UUID.Zero)
return ret;
if (m_warpTextures.TryGetValue(id.ToString(), out ret))
return ret;
byte[] asset = m_scene.AssetService.GetData(id.ToString()); byte[] asset = m_scene.AssetService.GetData(id.ToString());
if (asset != null) if (asset != null)
{ {
IJ2KDecoder imgDecoder = m_scene.RequestModuleInterface<IJ2KDecoder>();
try try
{ {
using (Bitmap img = (Bitmap)m_imgDecoder.DecodeToImage(asset)) using (Bitmap img = (Bitmap)imgDecoder.DecodeToImage(asset))
ret = new warp_Texture(img); ret = new warp_Texture(img);
} }
catch (Exception e) catch (Exception e)
{ {
m_log.Warn(string.Format("[WARP 3D CACHED IMAGE MODULE]: Failed to decode asset {0}, exception ", id), e); //m_log.Warn(string.Format("[WARP 3D IMAGE MODULE]: Failed to decode asset {0}, exception ", id), e);
} }
} }
m_warpTextures[id.ToString()] = ret;
return ret; return ret;
} }
@ -791,7 +771,10 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
private static int ConvertColor(Color4 color) private static int ConvertColor(Color4 color)
{ {
int c = warp_Color.getColor((byte)(color.R * 255f), (byte)(color.G * 255f), (byte)(color.B * 255f), (byte)(color.A * 255f)); int c = warp_Color.getColor((byte)(color.R * 255f), (byte)(color.G * 255f), (byte)(color.B * 255f));
if (color.A < 1f)
c |= (byte)(color.A * 255f) << 24;
return c; return c;
} }
@ -806,17 +789,19 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
return normal; return normal;
} }
public Color4 GetAverageColor(UUID textureID, byte[] j2kData, out int width, out int height) public static Color4 GetAverageColor(UUID textureID, byte[] j2kData, out int width, out int height)
{ {
ulong r = 0; ulong r = 0;
ulong g = 0; ulong g = 0;
ulong b = 0; ulong b = 0;
ulong a = 0; ulong a = 0;
int pixelBytes;
using (MemoryStream stream = new MemoryStream(j2kData))
{
try try
{ {
using (MemoryStream stream = new MemoryStream(j2kData)) int pixelBytes;
using (Bitmap bitmap = (Bitmap)J2kImage.FromStream(stream)) using (Bitmap bitmap = (Bitmap)J2kImage.FromStream(stream))
{ {
width = bitmap.Width; width = bitmap.Width;
@ -859,6 +844,7 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
} }
} }
} }
// Get the averages for each channel // Get the averages for each channel
const decimal OO_255 = 1m / 255m; const decimal OO_255 = 1m / 255m;
decimal totalPixels = (decimal)(width * height); decimal totalPixels = (decimal)(width * height);
@ -872,19 +858,19 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
am = 1m; am = 1m;
return new Color4((float)rm, (float)gm, (float)bm, (float)am); return new Color4((float)rm, (float)gm, (float)bm, (float)am);
} }
catch (Exception ex) catch (Exception ex)
{ {
m_log.WarnFormat( //m_log.WarnFormat(
"[WARP 3D CACHED IMAGE MODULE]: Error decoding JPEG2000 texture {0} ({1} bytes): {2}", //"[WARP 3D IMAGE MODULE]: Error decoding JPEG2000 texture {0} ({1} bytes): {2}",
textureID, j2kData.Length, ex.Message); // textureID, j2kData.Length, ex.Message);
width = 0; width = 0;
height = 0; height = 0;
return new Color4(0.5f, 0.5f, 0.5f, 1.0f); return new Color4(0.5f, 0.5f, 0.5f, 1.0f);
} }
} }
}
#endregion Static Helpers #endregion Static Helpers
} }
@ -905,5 +891,29 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap
{ {
return Utils.Lerp(Utils.Lerp(v00, v01, xPercent), Utils.Lerp(v10, v11, xPercent), yPercent); return Utils.Lerp(Utils.Lerp(v00, v01, xPercent), Utils.Lerp(v10, v11, xPercent), yPercent);
} }
/// <summary>
/// Performs a high quality image resize
/// </summary>
/// <param name="image">Image to resize</param>
/// <param name="width">New width</param>
/// <param name="height">New height</param>
/// <returns>Resized image</returns>
public static Bitmap ResizeImage(Image image, int width, int height)
{
Bitmap result = new Bitmap(width, height);
using (Graphics graphics = Graphics.FromImage(result))
{
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
graphics.DrawImage(image, 0, 0, result.Width, result.Height);
}
return result;
}
} }
} }