OpenSim
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Events Macros
TerrainChannel.cs
Go to the documentation of this file.
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 
28 using System;
29 using System.IO;
30 using System.Text;
31 using System.Reflection;
32 using System.Xml;
33 using System.Xml.Serialization;
34 
35 using OpenSim.Data;
36 using OpenSim.Framework;
37 using OpenSim.Region.Framework.Interfaces;
38 
39 using OpenMetaverse;
40 
41 using log4net;
42 
43 namespace OpenSim.Region.Framework.Scenes
44 {
49  {
50  private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
51  private static string LogHeader = "[TERRAIN CHANNEL]";
52 
54 
55  public int Width { get { return m_terrainData.SizeX; } } // X dimension
56  // Unfortunately, for historical reasons, in this module 'Width' is X and 'Height' is Y
57  public int Height { get { return m_terrainData.SizeY; } } // Y dimension
58  public int Altitude { get { return m_terrainData.SizeZ; } } // Y dimension
59 
60 
61  // Default, not-often-used builder
62  public TerrainChannel()
63  {
65  FlatLand();
66  // PinHeadIsland();
67  }
68 
69  // Create terrain of given size
70  public TerrainChannel(int pX, int pY)
71  {
72  m_terrainData = new HeightmapTerrainData(pX, pY, (int)Constants.RegionHeight);
73  }
74 
75  // Create terrain of specified size and initialize with specified terrain.
76  // TODO: join this with the terrain initializers.
77  public TerrainChannel(String type, int pX, int pY, int pZ)
78  {
79  m_terrainData = new HeightmapTerrainData(pX, pY, pZ);
80  if (type.Equals("flat"))
81  FlatLand();
82  else
83  PinHeadIsland();
84  }
85 
86  // Create channel passed a heightmap and expected dimensions of the region.
87  // The heightmap might not fit the passed size so accomodations must be made.
88  public TerrainChannel(double[,] pM, int pSizeX, int pSizeY, int pAltitude)
89  {
90  int hmSizeX = pM.GetLength(0);
91  int hmSizeY = pM.GetLength(1);
92 
93  m_terrainData = new HeightmapTerrainData(pSizeX, pSizeY, pAltitude);
94 
95  for (int xx = 0; xx < pSizeX; xx++)
96  for (int yy = 0; yy < pSizeY; yy++)
97  if (xx > hmSizeX || yy > hmSizeY)
98  m_terrainData[xx, yy] = TerrainData.DefaultTerrainHeight;
99  else
100  m_terrainData[xx, yy] = (float)pM[xx, yy];
101  }
102 
103  public TerrainChannel(TerrainData pTerrData)
104  {
105  m_terrainData = pTerrData;
106  }
107 
108  #region ITerrainChannel Members
109 
110  // ITerrainChannel.MakeCopy()
112  {
113  return this.Copy();
114  }
115 
116  // ITerrainChannel.GetTerrainData()
118  {
119  return m_terrainData;
120  }
121 
122  // ITerrainChannel.GetFloatsSerialized()
123  // This one dimensional version is ordered so height = map[y*sizeX+x];
124  // DEPRECATED: don't use this function as it does not retain the dimensions of the terrain
125  // and the caller will probably do the wrong thing if the terrain is not the legacy 256x256.
126  public float[] GetFloatsSerialised()
127  {
128  return m_terrainData.GetFloatsSerialized();
129  }
130 
131  // ITerrainChannel.GetDoubles()
132  public double[,] GetDoubles()
133  {
134  double[,] heights = new double[Width, Height];
135 
136  int idx = 0; // index into serialized array
137  for (int ii = 0; ii < Width; ii++)
138  {
139  for (int jj = 0; jj < Height; jj++)
140  {
141  heights[ii, jj] = (double)m_terrainData[ii, jj];
142  idx++;
143  }
144  }
145 
146  return heights;
147  }
148 
149  // ITerrainChannel.this[x,y]
150  public double this[int x, int y]
151  {
152  get {
153  if (x < 0 || x >= Width || y < 0 || y >= Height)
154  return 0;
155  return (double)m_terrainData[x, y];
156  }
157  set
158  {
159  if (Double.IsNaN(value) || Double.IsInfinity(value))
160  return;
161 
162  m_terrainData[x, y] = (float)value;
163  }
164  }
165 
166  // ITerrainChannel.GetHieghtAtXYZ(x, y, z)
167  public float GetHeightAtXYZ(float x, float y, float z)
168  {
169  if (x < 0 || x >= Width || y < 0 || y >= Height)
170  return 0;
171  return m_terrainData[(int)x, (int)y];
172  }
173 
174  // ITerrainChannel.Tainted()
175  public bool Tainted(int x, int y)
176  {
177  return m_terrainData.IsTaintedAt(x, y);
178  }
179 
180  // ITerrainChannel.SaveToXmlString()
181  public string SaveToXmlString()
182  {
183  XmlWriterSettings settings = new XmlWriterSettings();
184  settings.Encoding = Util.UTF8;
185  using (StringWriter sw = new StringWriter())
186  {
187  using (XmlWriter writer = XmlWriter.Create(sw, settings))
188  {
189  WriteXml(writer);
190  }
191  string output = sw.ToString();
192  return output;
193  }
194  }
195 
196  // ITerrainChannel.LoadFromXmlString()
197  public void LoadFromXmlString(string data)
198  {
199  StringReader sr = new StringReader(data);
200  XmlTextReader reader = new XmlTextReader(sr);
201  reader.Read();
202 
203  ReadXml(reader);
204  reader.Close();
205  sr.Close();
206  }
207 
208  // ITerrainChannel.Merge
209  public void Merge(ITerrainChannel newTerrain, Vector3 displacement, float radianRotation, Vector2 rotationDisplacement)
210  {
211  m_log.DebugFormat("{0} Merge. inSize=<{1},{2}>, disp={3}, rot={4}, rotDisp={5}, outSize=<{6},{7}>", LogHeader,
212  newTerrain.Width, newTerrain.Height,
213  displacement, radianRotation, rotationDisplacement,
214  m_terrainData.SizeX, m_terrainData.SizeY);
215  for (int xx = 0; xx < newTerrain.Width; xx++)
216  {
217  for (int yy = 0; yy < newTerrain.Height; yy++)
218  {
219  int dispX = (int)displacement.X;
220  int dispY = (int)displacement.Y;
221  float newHeight = (float)newTerrain[xx, yy] + displacement.Z;
222  if (radianRotation == 0)
223  {
224  // If no rotation, place the new height in the specified location
225  dispX += xx;
226  dispY += yy;
227  if (dispX >= 0 && dispX < m_terrainData.SizeX && dispY >= 0 && dispY < m_terrainData.SizeY)
228  {
229  m_terrainData[dispX, dispY] = newHeight;
230  }
231  }
232  else
233  {
234  // If rotating, we have to smooth the result because the conversion
235  // to ints will mean heightmap entries will not get changed
236  // First compute the rotation location for the new height.
237  dispX += (int)(rotationDisplacement.X
238  + ((float)xx - rotationDisplacement.X) * Math.Cos(radianRotation)
239  - ((float)yy - rotationDisplacement.Y) * Math.Sin(radianRotation) );
240 
241  dispY += (int)(rotationDisplacement.Y
242  + ((float)xx - rotationDisplacement.X) * Math.Sin(radianRotation)
243  + ((float)yy - rotationDisplacement.Y) * Math.Cos(radianRotation) );
244 
245  if (dispX >= 0 && dispX < m_terrainData.SizeX && dispY >= 0 && dispY < m_terrainData.SizeY)
246  {
247  float oldHeight = m_terrainData[dispX, dispY];
248  // Smooth the heights around this location if the old height is far from this one
249  for (int sxx = dispX - 2; sxx < dispX + 2; sxx++)
250  {
251  for (int syy = dispY - 2; syy < dispY + 2; syy++)
252  {
253  if (sxx >= 0 && sxx < m_terrainData.SizeX && syy >= 0 && syy < m_terrainData.SizeY)
254  {
255  if (sxx == dispX && syy == dispY)
256  {
257  // Set height for the exact rotated point
258  m_terrainData[dispX, dispY] = newHeight;
259  }
260  else
261  {
262  if (Math.Abs(m_terrainData[sxx, syy] - newHeight) > 1f)
263  {
264  // If the adjacent height is far off, force it to this height
265  m_terrainData[sxx, syy] = newHeight;
266  }
267  }
268  }
269  }
270  }
271  }
272 
273  if (dispX >= 0 && dispX < m_terrainData.SizeX && dispY >= 0 && dispY < m_terrainData.SizeY)
274  {
275  m_terrainData[dispX, dispY] = (float)newTerrain[xx, yy];
276  }
277  }
278  }
279  }
280  }
281 
297  public void MergeWithBounding(ITerrainChannel newTerrain, Vector3 displacement, float rotationDegrees, Vector2 boundingOrigin, Vector2 boundingSize)
298  {
299  m_log.DebugFormat("{0} MergeWithBounding: inSize=<{1},{2}>, rot={3}, boundingOrigin={4}, boundingSize={5}, disp={6}, outSize=<{7},{8}>",
300  LogHeader, newTerrain.Width, newTerrain.Height, rotationDegrees, boundingOrigin.ToString(),
301  boundingSize.ToString(), displacement, m_terrainData.SizeX, m_terrainData.SizeY);
302 
303  // get the size of the incoming terrain
304  int baseX = newTerrain.Width;
305  int baseY = newTerrain.Height;
306 
307  // create an intermediate terrain map that is 25% bigger on each side that we can work with to handle rotation
308  int offsetX = baseX / 4; // the original origin will now be at these coordinates so now we can have imaginary negative coordinates ;)
309  int offsetY = baseY / 4;
310  int tmpX = baseX + baseX / 2;
311  int tmpY = baseY + baseY / 2;
312  int centreX = tmpX / 2;
313  int centreY = tmpY / 2;
314  TerrainData terrain_tmp = new HeightmapTerrainData(tmpX, tmpY, (int)Constants.RegionHeight);
315  for (int xx = 0; xx < tmpX; xx++)
316  for (int yy = 0; yy < tmpY; yy++)
317  terrain_tmp[xx, yy] = -65535f; //use this height like an 'alpha' mask channel
318 
319  double radianRotation = Math.PI * rotationDegrees / 180f;
320  double cosR = Math.Cos(radianRotation);
321  double sinR = Math.Sin(radianRotation);
322  if (rotationDegrees < 0f) rotationDegrees += 360f; //-90=270 -180=180 -270=90
323 
324  // So first we apply the rotation to the incoming terrain, storing the result in terrain_tmp
325  // We special case orthogonal rotations for accuracy because even using double precision math, Math.Cos(90 degrees) is never fully 0
326  // and we can never rotate around a centre 'pixel' because the 'bitmap' size is always even
327 
328  int x, y, sx, sy;
329  for (y = 0; y <= tmpY; y++)
330  {
331  for (x = 0; x <= tmpX; x++)
332  {
333  if (rotationDegrees == 0f)
334  {
335  sx = x - offsetX;
336  sy = y - offsetY;
337  }
338  else if (rotationDegrees == 90f)
339  {
340  sx = y - offsetX;
341  sy = tmpY - 1 - x - offsetY;
342  }
343  else if (rotationDegrees == 180f)
344  {
345  sx = tmpX - 1 - x - offsetX;
346  sy = tmpY - 1 - y - offsetY;
347  }
348  else if (rotationDegrees == 270f)
349  {
350  sx = tmpX - 1 - y - offsetX;
351  sy = x - offsetY;
352  }
353  else
354  {
355  // arbitary rotation: hmmm should I be using (centreX - 0.5) and (centreY - 0.5) and round cosR and sinR to say only 5 decimal places?
356  sx = centreX + (int)Math.Round((((double)x - centreX) * cosR) + (((double)y - centreY) * sinR)) - offsetX;
357  sy = centreY + (int)Math.Round((((double)y - centreY) * cosR) - (((double)x - centreX) * sinR)) - offsetY;
358  }
359 
360  if (sx >= 0 && sx < baseX && sy >= 0 && sy < baseY)
361  {
362  try
363  {
364  terrain_tmp[x, y] = (float)newTerrain[sx, sy];
365  }
366  catch (Exception) //just in case we've still not taken care of every way the arrays might go out of bounds! ;)
367  {
368  m_log.DebugFormat("{0} MergeWithBounding - Rotate: Out of Bounds sx={1} sy={2} dx={3} dy={4}", sx, sy, x, y);
369  }
370  }
371  }
372  }
373 
374  // We could also incorporate the next steps, bounding-rectangle and displacement in the loop above, but it's simpler to visualise if done separately
375  // and will also make it much easier when later I want the option for maybe a circular or oval bounding shape too ;).
376 
377  int newX = m_terrainData.SizeX;
378  int newY = m_terrainData.SizeY;
379  // displacement is relative to <0,0> in the destination region and defines where the origin of the data selected by the bounding-rectangle is placed
380  int dispX = (int)Math.Floor(displacement.X);
381  int dispY = (int)Math.Floor(displacement.Y);
382 
383  // startX/Y and endX/Y are coordinates in bitmap_tmp
384  int startX = (int)Math.Floor(boundingOrigin.X) + offsetX;
385  if (startX > tmpX) startX = tmpX;
386  if (startX < 0) startX = 0;
387  int startY = (int)Math.Floor(boundingOrigin.Y) + offsetY;
388  if (startY > tmpY) startY = tmpY;
389  if (startY < 0) startY = 0;
390 
391  int endX = (int)Math.Floor(boundingOrigin.X + boundingSize.X) + offsetX;
392  if (endX > tmpX) endX = tmpX;
393  if (endX < 0) endX = 0;
394  int endY = (int)Math.Floor(boundingOrigin.Y + boundingSize.Y) + offsetY;
395  if (endY > tmpY) endY = tmpY;
396  if (endY < 0) endY = 0;
397 
398  //m_log.DebugFormat("{0} MergeWithBounding: inSize=<{1},{2}>, disp=<{3},{4}> rot={5}, offset=<{6},{7}>, boundingStart=<{8},{9}>, boundingEnd=<{10},{11}>, cosR={12}, sinR={13}, outSize=<{14},{15}>", LogHeader,
399  // baseX, baseY, dispX, dispY, radianRotation, offsetX, offsetY, startX, startY, endX, endY, cosR, sinR, newX, newY);
400 
401  int dx, dy;
402  for (y = startY; y < endY; y++)
403  {
404  for (x = startX; x < endX; x++)
405  {
406  dx = x - startX + dispX;
407  dy = y - startY + dispY;
408  if (dx >= 0 && dx < newX && dy >= 0 && dy < newY)
409  {
410  try
411  {
412  float newHeight = (float)terrain_tmp[x, y]; //use 'alpha' mask
413  if (newHeight != -65535f) m_terrainData[dx, dy] = newHeight + displacement.Z;
414  }
415  catch (Exception) //just in case we've still not taken care of every way the arrays might go out of bounds! ;)
416  {
417  m_log.DebugFormat("{0} MergeWithBounding - Bound & Displace: Out of Bounds sx={1} sy={2} dx={3} dy={4}", x, y, dx, dy);
418  }
419  }
420  }
421  }
422  }
423 
424  #endregion
425 
427  {
428  TerrainChannel copy = new TerrainChannel();
429  copy.m_terrainData = m_terrainData.Clone();
430  return copy;
431  }
432 
433  private void WriteXml(XmlWriter writer)
434  {
435  if (Width == Constants.RegionSize && Height == Constants.RegionSize)
436  {
437  // Downward compatibility for legacy region terrain maps.
438  // If region is exactly legacy size, return the old format XML.
439  writer.WriteStartElement(String.Empty, "TerrainMap", String.Empty);
440  ToXml(writer);
441  writer.WriteEndElement();
442  }
443  else
444  {
445  // New format XML that includes width and length.
446  writer.WriteStartElement(String.Empty, "TerrainMap2", String.Empty);
447  ToXml2(writer);
448  writer.WriteEndElement();
449  }
450  }
451 
452  private void ReadXml(XmlReader reader)
453  {
454  // Check the first element. If legacy element, use the legacy reader.
455  if (reader.IsStartElement("TerrainMap"))
456  {
457  reader.ReadStartElement("TerrainMap");
458  FromXml(reader);
459  }
460  else
461  {
462  reader.ReadStartElement("TerrainMap2");
463  FromXml2(reader);
464  }
465  }
466 
467  // Write legacy terrain map. Presumed to be 256x256 of data encoded as floats in a byte array.
468  private void ToXml(XmlWriter xmlWriter)
469  {
470  float[] mapData = GetFloatsSerialised();
471  byte[] buffer = new byte[mapData.Length * 4];
472  for (int i = 0; i < mapData.Length; i++)
473  {
474  byte[] value = BitConverter.GetBytes(mapData[i]);
475  Array.Copy(value, 0, buffer, (i * 4), 4);
476  }
477  XmlSerializer serializer = new XmlSerializer(typeof(byte[]));
478  serializer.Serialize(xmlWriter, buffer);
479  }
480 
481  // Read legacy terrain map. Presumed to be 256x256 of data encoded as floats in a byte array.
482  private void FromXml(XmlReader xmlReader)
483  {
484  XmlSerializer serializer = new XmlSerializer(typeof(byte[]));
485  byte[] dataArray = (byte[])serializer.Deserialize(xmlReader);
486  int index = 0;
487 
488  m_terrainData = new HeightmapTerrainData(Height, Width, (int)Constants.RegionHeight);
489 
490  for (int y = 0; y < Height; y++)
491  {
492  for (int x = 0; x < Width; x++)
493  {
494  float value;
495  value = BitConverter.ToSingle(dataArray, index);
496  index += 4;
497  this[x, y] = (double)value;
498  }
499  }
500  }
501 
502  private class TerrainChannelXMLPackage
503  {
504  public int Version;
505  public int SizeX;
506  public int SizeY;
507  public int SizeZ;
508  public float CompressionFactor;
509  public float[] Map;
510  public TerrainChannelXMLPackage(int pX, int pY, int pZ, float pCompressionFactor, float[] pMap)
511  {
512  Version = 1;
513  SizeX = pX;
514  SizeY = pY;
515  SizeZ = pZ;
516  CompressionFactor = pCompressionFactor;
517  Map = pMap;
518  }
519  }
520 
521  // New terrain serialization format that includes the width and length.
522  private void ToXml2(XmlWriter xmlWriter)
523  {
524  TerrainChannelXMLPackage package = new TerrainChannelXMLPackage(Width, Height, Altitude, m_terrainData.CompressionFactor,
525  m_terrainData.GetCompressedMap());
526  XmlSerializer serializer = new XmlSerializer(typeof(TerrainChannelXMLPackage));
527  serializer.Serialize(xmlWriter, package);
528  }
529 
530  // New terrain serialization format that includes the width and length.
531  private void FromXml2(XmlReader xmlReader)
532  {
533  XmlSerializer serializer = new XmlSerializer(typeof(TerrainChannelXMLPackage));
534  TerrainChannelXMLPackage package = (TerrainChannelXMLPackage)serializer.Deserialize(xmlReader);
535  m_terrainData = new HeightmapTerrainData(package.Map, package.CompressionFactor, package.SizeX, package.SizeY, package.SizeZ);
536  }
537 
538  // Fill the heightmap with the center bump terrain
539  private void PinHeadIsland()
540  {
541  float cx = m_terrainData.SizeX * 0.5f;
542  float cy = m_terrainData.SizeY * 0.5f;
543  float h;
544  for (int x = 0; x < Width; x++)
545  {
546  for (int y = 0; y < Height; y++)
547  {
548  // h = (float)TerrainUtil.PerlinNoise2D(x, y, 2, 0.125) * 10;
549  h = 1.0f;
550  float spherFacA = (float)(TerrainUtil.SphericalFactor(x, y, cx, cy, 50) * 0.01d);
551  float spherFacB = (float)(TerrainUtil.SphericalFactor(x, y, cx, cy, 100) * 0.001d);
552  if (h < spherFacA)
553  h = spherFacA;
554  if (h < spherFacB)
555  h = spherFacB;
556  m_terrainData[x, y] = h;
557  }
558  }
559  }
560 
561  private void FlatLand()
562  {
563  m_terrainData.ClearLand();
564  }
565  }
566 }
float GetHeightAtXYZ(float x, float y, float z)
TerrainChannel(double[,] pM, int pSizeX, int pSizeY, int pAltitude)
float[] GetFloatsSerialised()
Squash the entire heightmap into a single dimensioned array
TerrainChannel(String type, int pX, int pY, int pZ)
void MergeWithBounding(ITerrainChannel newTerrain, Vector3 displacement, float rotationDegrees, Vector2 boundingOrigin, Vector2 boundingSize)
A new version of terrain merge that processes the terrain in a specific order and corrects the proble...
A new version of the old Channel class, simplified
void Merge(ITerrainChannel newTerrain, Vector3 displacement, float radianRotation, Vector2 rotationDisplacement)