TerrainSplat.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Diagnostics;
  29. using System.Drawing;
  30. using System.Drawing.Imaging;
  31. using System.IO;
  32. using log4net;
  33. using OpenMetaverse;
  34. using OpenSim.Framework;
  35. using OpenSim.Region.Framework.Interfaces;
  36. using OpenSim.Services.Interfaces;
  37. namespace OpenSim.Region.CoreModules.World.Warp3DMap
  38. {
  39. public static class TerrainSplat
  40. {
  41. #region Constants
  42. private static readonly UUID DIRT_DETAIL = new UUID("0bc58228-74a0-7e83-89bc-5c23464bcec5");
  43. private static readonly UUID GRASS_DETAIL = new UUID("63338ede-0037-c4fd-855b-015d77112fc8");
  44. private static readonly UUID MOUNTAIN_DETAIL = new UUID("303cd381-8560-7579-23f1-f0a880799740");
  45. private static readonly UUID ROCK_DETAIL = new UUID("53a2f406-4895-1d13-d541-d2e3b86bc19c");
  46. private static readonly UUID[] DEFAULT_TERRAIN_DETAIL = new UUID[]
  47. {
  48. DIRT_DETAIL,
  49. GRASS_DETAIL,
  50. MOUNTAIN_DETAIL,
  51. ROCK_DETAIL
  52. };
  53. private static readonly Color[] DEFAULT_TERRAIN_COLOR = new Color[]
  54. {
  55. Color.FromArgb(255, 164, 136, 117),
  56. Color.FromArgb(255, 65, 87, 47),
  57. Color.FromArgb(255, 157, 145, 131),
  58. Color.FromArgb(255, 125, 128, 130)
  59. };
  60. private static readonly UUID TERRAIN_CACHE_MAGIC = new UUID("2c0c7ef2-56be-4eb8-aacb-76712c535b4b");
  61. #endregion Constants
  62. private static readonly ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name);
  63. private static string LogHeader = "[WARP3D TERRAIN SPLAT]";
  64. /// <summary>
  65. /// Builds a composited terrain texture given the region texture
  66. /// and heightmap settings
  67. /// </summary>
  68. /// <param name="terrain">Terrain heightmap</param>
  69. /// <param name="regionInfo">Region information including terrain texture parameters</param>
  70. /// <returns>A 256x256 square RGB texture ready for rendering</returns>
  71. /// <remarks>Based on the algorithm described at http://opensimulator.org/wiki/Terrain_Splatting
  72. /// Note we create a 256x256 dimension texture even if the actual terrain is larger.
  73. /// </remarks>
  74. public static Bitmap Splat(ITerrainChannel terrain, UUID[] textureIDs,
  75. float[] startHeights, float[] heightRanges,
  76. uint regionPositionX, uint regionPositionY,
  77. IAssetService assetService, IJ2KDecoder decoder,
  78. bool textureTerrain, bool averagetextureTerrain,
  79. int twidth, int theight)
  80. {
  81. Bitmap[] detailTexture = new Bitmap[4];
  82. byte[] mapColorsRed = new byte[4];
  83. byte[] mapColorsGreen = new byte[4];
  84. byte[] mapColorsBlue = new byte[4];
  85. bool usecolors = false;
  86. if (textureTerrain)
  87. {
  88. // Swap empty terrain textureIDs with default IDs
  89. for(int i = 0; i < textureIDs.Length; i++)
  90. {
  91. if(textureIDs[i].IsZero())
  92. textureIDs[i] = DEFAULT_TERRAIN_DETAIL[i];
  93. }
  94. #region Texture Fetching
  95. if(assetService != null)
  96. {
  97. for(int i = 0; i < 4; i++)
  98. {
  99. // asset cache indexes are strings
  100. string cacheName = "MAP" + textureIDs[i].ToString();
  101. // Try to fetch a cached copy of the decoded/resized version of this texture
  102. AssetBase asset = assetService.GetCached(cacheName);
  103. if(asset != null)
  104. {
  105. try
  106. {
  107. using(MemoryStream stream = new MemoryStream(asset.Data))
  108. detailTexture[i] = (Bitmap)Image.FromStream(stream);
  109. if(detailTexture[i].PixelFormat != PixelFormat.Format24bppRgb ||
  110. detailTexture[i].Width != 16 || detailTexture[i].Height != 16)
  111. {
  112. detailTexture[i].Dispose();
  113. detailTexture[i] = null;
  114. }
  115. }
  116. catch(Exception ex)
  117. {
  118. m_log.Warn("Failed to decode cached terrain patch texture" + textureIDs[i] + "): " + ex.Message);
  119. }
  120. }
  121. if(detailTexture[i] == null)
  122. {
  123. // Try to fetch the original JPEG2000 texture, resize if needed, and cache as PNG
  124. asset = assetService.Get(textureIDs[i].ToString());
  125. if(asset != null)
  126. {
  127. try
  128. {
  129. detailTexture[i] = (Bitmap)decoder.DecodeToImage(asset.Data);
  130. }
  131. catch(Exception ex)
  132. {
  133. m_log.Warn("Failed to decode terrain texture " + asset.ID + ": " + ex.Message);
  134. }
  135. }
  136. if(detailTexture[i] != null)
  137. {
  138. //detailTexture[i].Save("terrOri" + i.ToString() + ".png");
  139. if (detailTexture[i].PixelFormat != PixelFormat.Format24bppRgb ||
  140. detailTexture[i].Width != 16 || detailTexture[i].Height != 16)
  141. using(Bitmap origBitmap = detailTexture[i])
  142. detailTexture[i] = Util.ResizeImageSolid(origBitmap, 16, 16);
  143. //detailTexture[i].Save("terr" + i.ToString() + ".png");
  144. // Save the decoded and resized texture to the cache
  145. byte[] data;
  146. using(MemoryStream stream = new MemoryStream())
  147. {
  148. detailTexture[i].Save(stream, ImageFormat.Png);
  149. data = stream.ToArray();
  150. }
  151. // Cache a PNG copy of this terrain texture
  152. AssetBase newAsset = new AssetBase
  153. {
  154. Data = data,
  155. Description = "PNG",
  156. Flags = AssetFlags.Collectable,
  157. FullID = UUID.Zero,
  158. ID = cacheName,
  159. Local = true,
  160. Name = String.Empty,
  161. Temporary = true,
  162. Type = (sbyte)AssetType.Unknown
  163. };
  164. newAsset.Metadata.ContentType = "image/png";
  165. assetService.Store(newAsset);
  166. }
  167. }
  168. }
  169. }
  170. #endregion Texture Fetching
  171. if(averagetextureTerrain)
  172. {
  173. for(int t = 0; t < 4; t++)
  174. {
  175. usecolors = true;
  176. if(detailTexture[t] == null)
  177. {
  178. mapColorsRed[t] = DEFAULT_TERRAIN_COLOR[t].R;
  179. mapColorsGreen[t] = DEFAULT_TERRAIN_COLOR[t].G;
  180. mapColorsBlue[t] = DEFAULT_TERRAIN_COLOR[t].B;
  181. continue;
  182. }
  183. int npixeis = 0;
  184. int cR = 0;
  185. int cG = 0;
  186. int cB = 0;
  187. BitmapData bmdata = detailTexture[t].LockBits(new Rectangle(0, 0, 16, 16),
  188. ImageLockMode.ReadOnly, detailTexture[t].PixelFormat);
  189. npixeis = bmdata.Height * bmdata.Width;
  190. int ylen = bmdata.Height * bmdata.Stride;
  191. unsafe
  192. {
  193. for(int y = 0; y < ylen; y += bmdata.Stride)
  194. {
  195. byte* ptrc = (byte*)bmdata.Scan0 + y;
  196. for(int x = 0 ; x < bmdata.Width; ++x, ptrc += 3)
  197. {
  198. cR += ptrc[0];
  199. cG += ptrc[1];
  200. cB += ptrc[2];
  201. }
  202. }
  203. }
  204. detailTexture[t].UnlockBits(bmdata);
  205. detailTexture[t].Dispose();
  206. mapColorsRed[t] = (byte)Math.Clamp(cR / npixeis, 0 , 255);
  207. mapColorsGreen[t] = (byte)Math.Clamp(cG / npixeis, 0 , 255);
  208. mapColorsBlue[t] = (byte)Math.Clamp(cB / npixeis, 0 , 255);
  209. }
  210. }
  211. else
  212. {
  213. // Fill in any missing textures with a solid color
  214. for (int i = 0; i < 4; i++)
  215. {
  216. if (detailTexture[i] == null)
  217. {
  218. m_log.DebugFormat("{0} Missing terrain texture for layer {1}. Filling with solid default color", LogHeader, i);
  219. // Create a solid color texture for this layer
  220. detailTexture[i] = new Bitmap(16, 16, PixelFormat.Format24bppRgb);
  221. using(Graphics gfx = Graphics.FromImage(detailTexture[i]))
  222. {
  223. using(SolidBrush brush = new SolidBrush(DEFAULT_TERRAIN_COLOR[i]))
  224. gfx.FillRectangle(brush, 0, 0, 16, 16);
  225. }
  226. }
  227. else
  228. {
  229. if(detailTexture[i].Width != 16 || detailTexture[i].Height != 16)
  230. {
  231. using(Bitmap origBitmap = detailTexture[i])
  232. detailTexture[i] = Util.ResizeImageSolid(origBitmap, 16, 16);
  233. }
  234. }
  235. //detailTexture[i].Save("terr" + i.ToString()+".png", ImageFormat.Png);
  236. }
  237. }
  238. }
  239. else
  240. {
  241. usecolors = true;
  242. for(int t = 0; t < 4; t++)
  243. {
  244. mapColorsRed[t] = DEFAULT_TERRAIN_COLOR[t].R;
  245. mapColorsGreen[t] = DEFAULT_TERRAIN_COLOR[t].G;
  246. mapColorsBlue[t] = DEFAULT_TERRAIN_COLOR[t].B;
  247. }
  248. }
  249. #region Layer Map
  250. float xFactor = terrain.Width / twidth;
  251. float yFactor = terrain.Height / theight;
  252. #endregion Layer Map
  253. #region Texture Compositing
  254. Bitmap output = new Bitmap(twidth, theight, PixelFormat.Format24bppRgb);
  255. BitmapData outputData = output.LockBits(new Rectangle(0, 0, twidth, theight), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
  256. // Unsafe work as we lock down the source textures for quicker access and access the
  257. // pixel data directly
  258. float invtwitdthMinus1 = 1.0f / (twidth - 1);
  259. float invtheightMinus1 = 1.0f / (theight - 1);
  260. int ty;
  261. int tx;
  262. float pctx;
  263. float pcty;
  264. float height;
  265. float layer;
  266. float layerDiff;
  267. int l0;
  268. uint yglobalpos;
  269. if(usecolors)
  270. {
  271. float a;
  272. float b;
  273. int l1;
  274. unsafe
  275. {
  276. byte* ptrO;
  277. for(int y = 0; y < theight; ++y)
  278. {
  279. pcty = y * invtheightMinus1;
  280. ptrO = (byte*)outputData.Scan0.ToPointer() + y * outputData.Stride;
  281. ty = (int)(y * yFactor);
  282. yglobalpos = (uint)ty + regionPositionY;
  283. for(int x = 0; x < twidth; ++x, ptrO +=3)
  284. {
  285. tx = (int)(x * xFactor);
  286. pctx = x * invtwitdthMinus1;
  287. height = (float)terrain[tx, ty];
  288. layer = getLayerTex(height, pctx, pcty,
  289. (uint)tx + regionPositionX, yglobalpos,
  290. startHeights, heightRanges);
  291. // Select two textures
  292. l0 = (int)layer;
  293. layerDiff = layer - l0;
  294. if (l0 >= 2)
  295. l1 = 3;
  296. else
  297. l1 = l0 + 1;
  298. a = mapColorsRed[l0];
  299. b = mapColorsRed[l1];
  300. ptrO[0] = (byte)(a + layerDiff * (b - a));
  301. a = mapColorsGreen[l0];
  302. b = mapColorsGreen[l1];
  303. ptrO[1] = (byte)(a + layerDiff * (b - a));
  304. a = mapColorsBlue[l0];
  305. b = mapColorsBlue[l1];
  306. ptrO[2] = (byte)(a + layerDiff * (b - a));
  307. }
  308. }
  309. }
  310. }
  311. else
  312. {
  313. float aB;
  314. float aG;
  315. float aR;
  316. float bB;
  317. float bG;
  318. float bR;
  319. unsafe
  320. {
  321. // Get handles to all of the texture data arrays
  322. BitmapData[] datas = new BitmapData[]
  323. {
  324. detailTexture[0].LockBits(new Rectangle(0, 0, 16, 16), ImageLockMode.ReadOnly, detailTexture[0].PixelFormat),
  325. detailTexture[1].LockBits(new Rectangle(0, 0, 16, 16), ImageLockMode.ReadOnly, detailTexture[1].PixelFormat),
  326. detailTexture[2].LockBits(new Rectangle(0, 0, 16, 16), ImageLockMode.ReadOnly, detailTexture[2].PixelFormat),
  327. detailTexture[3].LockBits(new Rectangle(0, 0, 16, 16), ImageLockMode.ReadOnly, detailTexture[3].PixelFormat)
  328. };
  329. byte* ptr;
  330. byte* ptrO;
  331. for (int y = 0; y < theight; y++)
  332. {
  333. pcty = y * invtheightMinus1;
  334. ty = (int)(y * yFactor);
  335. int ypatch = (ty & 0x0f) * datas[0].Stride;
  336. yglobalpos = (uint)ty + regionPositionY;
  337. ptrO = (byte*)outputData.Scan0.ToPointer() + y * outputData.Stride;
  338. for (int x = 0; x < twidth; x++, ptrO += 3)
  339. {
  340. tx = (int)(x * xFactor);
  341. pctx = x * invtwitdthMinus1;
  342. height = (float)terrain[tx, ty];
  343. layer = getLayerTex(height, pctx, pcty,
  344. (uint)tx + regionPositionX, yglobalpos,
  345. startHeights, heightRanges);
  346. // Select two textures
  347. l0 = (int)layer;
  348. layerDiff = layer - l0;
  349. int patchOffset = (tx & 0x0f) * 3 + ypatch;
  350. ptr = (byte*)datas[l0].Scan0.ToPointer() + patchOffset;
  351. aB = ptr[0];
  352. aG = ptr[1];
  353. aR = ptr[2];
  354. if(l0 >= 2 )
  355. l0 = 3;
  356. else
  357. l0++;
  358. ptr = (byte*)datas[l0].Scan0.ToPointer() + patchOffset;
  359. bB = ptr[0];
  360. bG = ptr[1];
  361. bR = ptr[2];
  362. // Interpolate between the two selected textures
  363. ptrO[0] = (byte)(aB + layerDiff * (bB - aB));
  364. ptrO[1] = (byte)(aG + layerDiff * (bG - aG));
  365. ptrO[2] = (byte)(aR + layerDiff * (bR - aR));
  366. }
  367. }
  368. for (int i = 0; i < detailTexture.Length; i++)
  369. detailTexture[i].UnlockBits(datas[i]);
  370. }
  371. for(int i = 0; i < detailTexture.Length; i++)
  372. if(detailTexture[i] != null)
  373. detailTexture[i].Dispose();
  374. }
  375. output.UnlockBits(outputData);
  376. //output.Save("terr.jpg",ImageFormat.Jpeg);
  377. #endregion Texture Compositing
  378. return output;
  379. }
  380. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  381. private static float getLayerTex(float height, float pctX, float pctY, uint X, uint Y,
  382. float[] startHeights, float[] heightRanges)
  383. {
  384. // Use bilinear interpolation between the four corners of start height and
  385. // height range to select the current values at this position
  386. float startHeight = ImageUtils.Bilinear(startHeights, pctX, pctY);
  387. if (float.IsNaN(startHeight))
  388. return 0;
  389. startHeight = Utils.Clamp(startHeight, 0f, 255f);
  390. float heightRange = ImageUtils.Bilinear(heightRanges, pctX, pctY);
  391. heightRange = Utils.Clamp(heightRange, 0f, 255f);
  392. if(heightRange == 0f)
  393. return 0;
  394. // Generate two frequencies of perlin noise based on our global position
  395. // The magic values were taken from http://opensimulator.org/wiki/Terrain_Splatting
  396. float sX = X * 0.20319f;
  397. float sY = Y * 0.20319f;
  398. float noise = Perlin.noise2(sX * 0.222222f, sY * 0.222222f) * 13.0f;
  399. noise += Perlin.turbulence2(sX, sY, 2f) * 4.5f;
  400. // Combine the current height, generated noise, start height, and height range parameters, then scale all of it
  401. float layer = ((height + noise - startHeight) / heightRange) * 4f;
  402. return Utils.Clamp(layer, 0f, 3f);
  403. }
  404. }
  405. }