TerrainChannel.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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.IO;
  29. using System.Text;
  30. using System.Reflection;
  31. using System.Xml;
  32. using System.Xml.Serialization;
  33. using OpenSim.Data;
  34. using OpenSim.Framework;
  35. using OpenSim.Region.Framework.Interfaces;
  36. using OpenMetaverse;
  37. using log4net;
  38. namespace OpenSim.Region.Framework.Scenes
  39. {
  40. /// <summary>
  41. /// A new version of the old Channel class, simplified
  42. /// </summary>
  43. public class TerrainChannel : ITerrainChannel
  44. {
  45. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  46. private static string LogHeader = "[TERRAIN CHANNEL]";
  47. protected TerrainData m_terrainData;
  48. public int Width { get { return m_terrainData.SizeX; } } // X dimension
  49. // Unfortunately, for historical reasons, in this module 'Width' is X and 'Height' is Y
  50. public int Height { get { return m_terrainData.SizeY; } } // Y dimension
  51. public int Altitude { get { return m_terrainData.SizeZ; } } // Y dimension
  52. // Default, not-often-used builder
  53. public TerrainChannel()
  54. {
  55. m_terrainData = new HeightmapTerrainData((int)Constants.RegionSize, (int)Constants.RegionSize, (int)Constants.RegionHeight);
  56. FlatLand();
  57. // PinHeadIsland();
  58. }
  59. // Create terrain of given size
  60. public TerrainChannel(int pX, int pY)
  61. {
  62. m_terrainData = new HeightmapTerrainData(pX, pY, (int)Constants.RegionHeight);
  63. }
  64. // Create terrain of specified size and initialize with specified terrain.
  65. // TODO: join this with the terrain initializers.
  66. public TerrainChannel(String type, int pX, int pY, int pZ)
  67. {
  68. m_terrainData = new HeightmapTerrainData(pX, pY, pZ);
  69. if (type.Equals("flat"))
  70. FlatLand();
  71. else
  72. PinHeadIsland();
  73. }
  74. // Create channel passed a heightmap and expected dimensions of the region.
  75. // The heightmap might not fit the passed size so accomodations must be made.
  76. public TerrainChannel(double[,] pM, int pSizeX, int pSizeY, int pAltitude)
  77. {
  78. int hmSizeX = pM.GetLength(0);
  79. int hmSizeY = pM.GetLength(1);
  80. m_terrainData = new HeightmapTerrainData(pSizeX, pSizeY, pAltitude);
  81. for (int xx = 0; xx < pSizeX; xx++)
  82. for (int yy = 0; yy < pSizeY; yy++)
  83. if (xx > hmSizeX || yy > hmSizeY)
  84. m_terrainData[xx, yy] = TerrainData.DefaultTerrainHeight;
  85. else
  86. m_terrainData[xx, yy] = (float)pM[xx, yy];
  87. }
  88. public TerrainChannel(TerrainData pTerrData)
  89. {
  90. m_terrainData = pTerrData;
  91. }
  92. #region ITerrainChannel Members
  93. // ITerrainChannel.MakeCopy()
  94. public ITerrainChannel MakeCopy()
  95. {
  96. return this.Copy();
  97. }
  98. // ITerrainChannel.GetTerrainData()
  99. public TerrainData GetTerrainData()
  100. {
  101. return m_terrainData;
  102. }
  103. // ITerrainChannel.GetFloatsSerialized()
  104. // This one dimensional version is ordered so height = map[y*sizeX+x];
  105. // DEPRECATED: don't use this function as it does not retain the dimensions of the terrain
  106. // and the caller will probably do the wrong thing if the terrain is not the legacy 256x256.
  107. public float[] GetFloatsSerialised()
  108. {
  109. return m_terrainData.GetFloatsSerialized();
  110. }
  111. // ITerrainChannel.GetDoubles()
  112. public double[,] GetDoubles()
  113. {
  114. double[,] heights = new double[Width, Height];
  115. int idx = 0; // index into serialized array
  116. for (int ii = 0; ii < Width; ii++)
  117. {
  118. for (int jj = 0; jj < Height; jj++)
  119. {
  120. heights[ii, jj] = (double)m_terrainData[ii, jj];
  121. idx++;
  122. }
  123. }
  124. return heights;
  125. }
  126. // ITerrainChannel.this[x,y]
  127. public double this[int x, int y]
  128. {
  129. get {
  130. if (x < 0 || x >= Width || y < 0 || y >= Height)
  131. return 0;
  132. return (double)m_terrainData[x, y];
  133. }
  134. set
  135. {
  136. if (Double.IsNaN(value) || Double.IsInfinity(value))
  137. return;
  138. m_terrainData[x, y] = (float)value;
  139. }
  140. }
  141. // ITerrainChannel.GetHieghtAtXYZ(x, y, z)
  142. public float GetHeightAtXYZ(float x, float y, float z)
  143. {
  144. if (x < 0 || x >= Width || y < 0 || y >= Height)
  145. return 0;
  146. return m_terrainData[(int)x, (int)y];
  147. }
  148. // ITerrainChannel.Tainted()
  149. public bool Tainted(int x, int y)
  150. {
  151. return m_terrainData.IsTaintedAt(x, y);
  152. }
  153. // ITerrainChannel.SaveToXmlString()
  154. public string SaveToXmlString()
  155. {
  156. XmlWriterSettings settings = new XmlWriterSettings();
  157. settings.Encoding = Util.UTF8;
  158. using (StringWriter sw = new StringWriter())
  159. {
  160. using (XmlWriter writer = XmlWriter.Create(sw, settings))
  161. {
  162. WriteXml(writer);
  163. }
  164. string output = sw.ToString();
  165. return output;
  166. }
  167. }
  168. // ITerrainChannel.LoadFromXmlString()
  169. public void LoadFromXmlString(string data)
  170. {
  171. StringReader sr = new StringReader(data);
  172. XmlTextReader reader = new XmlTextReader(sr);
  173. reader.Read();
  174. ReadXml(reader);
  175. reader.Close();
  176. sr.Close();
  177. }
  178. // ITerrainChannel.Merge
  179. public void Merge(ITerrainChannel newTerrain, Vector3 displacement, float radianRotation, Vector2 rotationDisplacement)
  180. {
  181. m_log.DebugFormat("{0} Merge. inSize=<{1},{2}>, disp={3}, rot={4}, rotDisp={5}, outSize=<{6},{7}>", LogHeader,
  182. newTerrain.Width, newTerrain.Height,
  183. displacement, radianRotation, rotationDisplacement,
  184. m_terrainData.SizeX, m_terrainData.SizeY);
  185. for (int xx = 0; xx < newTerrain.Width; xx++)
  186. {
  187. for (int yy = 0; yy < newTerrain.Height; yy++)
  188. {
  189. int dispX = (int)displacement.X;
  190. int dispY = (int)displacement.Y;
  191. float newHeight = (float)newTerrain[xx, yy] + displacement.Z;
  192. if (radianRotation == 0)
  193. {
  194. // If no rotation, place the new height in the specified location
  195. dispX += xx;
  196. dispY += yy;
  197. if (dispX >= 0 && dispX < m_terrainData.SizeX && dispY >= 0 && dispY < m_terrainData.SizeY)
  198. {
  199. m_terrainData[dispX, dispY] = newHeight;
  200. }
  201. }
  202. else
  203. {
  204. // If rotating, we have to smooth the result because the conversion
  205. // to ints will mean heightmap entries will not get changed
  206. // First compute the rotation location for the new height.
  207. dispX += (int)(rotationDisplacement.X
  208. + ((float)xx - rotationDisplacement.X) * Math.Cos(radianRotation)
  209. - ((float)yy - rotationDisplacement.Y) * Math.Sin(radianRotation) );
  210. dispY += (int)(rotationDisplacement.Y
  211. + ((float)xx - rotationDisplacement.X) * Math.Sin(radianRotation)
  212. + ((float)yy - rotationDisplacement.Y) * Math.Cos(radianRotation) );
  213. if (dispX >= 0 && dispX < m_terrainData.SizeX && dispY >= 0 && dispY < m_terrainData.SizeY)
  214. {
  215. float oldHeight = m_terrainData[dispX, dispY];
  216. // Smooth the heights around this location if the old height is far from this one
  217. for (int sxx = dispX - 2; sxx < dispX + 2; sxx++)
  218. {
  219. for (int syy = dispY - 2; syy < dispY + 2; syy++)
  220. {
  221. if (sxx >= 0 && sxx < m_terrainData.SizeX && syy >= 0 && syy < m_terrainData.SizeY)
  222. {
  223. if (sxx == dispX && syy == dispY)
  224. {
  225. // Set height for the exact rotated point
  226. m_terrainData[dispX, dispY] = newHeight;
  227. }
  228. else
  229. {
  230. if (Math.Abs(m_terrainData[sxx, syy] - newHeight) > 1f)
  231. {
  232. // If the adjacent height is far off, force it to this height
  233. m_terrainData[sxx, syy] = newHeight;
  234. }
  235. }
  236. }
  237. }
  238. }
  239. }
  240. if (dispX >= 0 && dispX < m_terrainData.SizeX && dispY >= 0 && dispY < m_terrainData.SizeY)
  241. {
  242. m_terrainData[dispX, dispY] = (float)newTerrain[xx, yy];
  243. }
  244. }
  245. }
  246. }
  247. }
  248. #endregion
  249. public TerrainChannel Copy()
  250. {
  251. TerrainChannel copy = new TerrainChannel();
  252. copy.m_terrainData = m_terrainData.Clone();
  253. return copy;
  254. }
  255. private void WriteXml(XmlWriter writer)
  256. {
  257. if (Width == Constants.RegionSize && Height == Constants.RegionSize)
  258. {
  259. // Downward compatibility for legacy region terrain maps.
  260. // If region is exactly legacy size, return the old format XML.
  261. writer.WriteStartElement(String.Empty, "TerrainMap", String.Empty);
  262. ToXml(writer);
  263. writer.WriteEndElement();
  264. }
  265. else
  266. {
  267. // New format XML that includes width and length.
  268. writer.WriteStartElement(String.Empty, "TerrainMap2", String.Empty);
  269. ToXml2(writer);
  270. writer.WriteEndElement();
  271. }
  272. }
  273. private void ReadXml(XmlReader reader)
  274. {
  275. // Check the first element. If legacy element, use the legacy reader.
  276. if (reader.IsStartElement("TerrainMap"))
  277. {
  278. reader.ReadStartElement("TerrainMap");
  279. FromXml(reader);
  280. }
  281. else
  282. {
  283. reader.ReadStartElement("TerrainMap2");
  284. FromXml2(reader);
  285. }
  286. }
  287. // Write legacy terrain map. Presumed to be 256x256 of data encoded as floats in a byte array.
  288. private void ToXml(XmlWriter xmlWriter)
  289. {
  290. float[] mapData = GetFloatsSerialised();
  291. byte[] buffer = new byte[mapData.Length * 4];
  292. for (int i = 0; i < mapData.Length; i++)
  293. {
  294. byte[] value = BitConverter.GetBytes(mapData[i]);
  295. Array.Copy(value, 0, buffer, (i * 4), 4);
  296. }
  297. XmlSerializer serializer = new XmlSerializer(typeof(byte[]));
  298. serializer.Serialize(xmlWriter, buffer);
  299. }
  300. // Read legacy terrain map. Presumed to be 256x256 of data encoded as floats in a byte array.
  301. private void FromXml(XmlReader xmlReader)
  302. {
  303. XmlSerializer serializer = new XmlSerializer(typeof(byte[]));
  304. byte[] dataArray = (byte[])serializer.Deserialize(xmlReader);
  305. int index = 0;
  306. m_terrainData = new HeightmapTerrainData(Height, Width, (int)Constants.RegionHeight);
  307. for (int y = 0; y < Height; y++)
  308. {
  309. for (int x = 0; x < Width; x++)
  310. {
  311. float value;
  312. value = BitConverter.ToSingle(dataArray, index);
  313. index += 4;
  314. this[x, y] = (double)value;
  315. }
  316. }
  317. }
  318. private class TerrainChannelXMLPackage
  319. {
  320. public int Version;
  321. public int SizeX;
  322. public int SizeY;
  323. public int SizeZ;
  324. public float CompressionFactor;
  325. public short[] Map;
  326. public TerrainChannelXMLPackage(int pX, int pY, int pZ, float pCompressionFactor, short[] pMap)
  327. {
  328. Version = 1;
  329. SizeX = pX;
  330. SizeY = pY;
  331. SizeZ = pZ;
  332. CompressionFactor = pCompressionFactor;
  333. Map = pMap;
  334. }
  335. }
  336. // New terrain serialization format that includes the width and length.
  337. private void ToXml2(XmlWriter xmlWriter)
  338. {
  339. TerrainChannelXMLPackage package = new TerrainChannelXMLPackage(Width, Height, Altitude, m_terrainData.CompressionFactor,
  340. m_terrainData.GetCompressedMap());
  341. XmlSerializer serializer = new XmlSerializer(typeof(TerrainChannelXMLPackage));
  342. serializer.Serialize(xmlWriter, package);
  343. }
  344. // New terrain serialization format that includes the width and length.
  345. private void FromXml2(XmlReader xmlReader)
  346. {
  347. XmlSerializer serializer = new XmlSerializer(typeof(TerrainChannelXMLPackage));
  348. TerrainChannelXMLPackage package = (TerrainChannelXMLPackage)serializer.Deserialize(xmlReader);
  349. m_terrainData = new HeightmapTerrainData(package.Map, package.CompressionFactor, package.SizeX, package.SizeY, package.SizeZ);
  350. }
  351. // Fill the heightmap with the center bump terrain
  352. private void PinHeadIsland()
  353. {
  354. for (int x = 0; x < Width; x++)
  355. {
  356. for (int y = 0; y < Height; y++)
  357. {
  358. m_terrainData[x, y] = (float)TerrainUtil.PerlinNoise2D(x, y, 2, 0.125) * 10;
  359. float spherFacA = (float)(TerrainUtil.SphericalFactor(x, y, m_terrainData.SizeX / 2.0, m_terrainData.SizeY / 2.0, 50) * 0.01d);
  360. float spherFacB = (float)(TerrainUtil.SphericalFactor(x, y, m_terrainData.SizeX / 2.0, m_terrainData.SizeY / 2.0, 100) * 0.001d);
  361. if (m_terrainData[x, y]< spherFacA)
  362. m_terrainData[x, y]= spherFacA;
  363. if (m_terrainData[x, y]< spherFacB)
  364. m_terrainData[x, y] = spherFacB;
  365. }
  366. }
  367. }
  368. private void FlatLand()
  369. {
  370. m_terrainData.ClearLand();
  371. }
  372. }
  373. }