TerrainEngine.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Drawing;
  5. using libTerrain;
  6. namespace OpenSim.Terrain
  7. {
  8. public class TerrainEngine
  9. {
  10. /// <summary>
  11. /// A [normally] 256x256 heightmap
  12. /// </summary>
  13. public Channel heightmap;
  14. /// <summary>
  15. /// Whether or not the terrain has been modified since it was last saved and sent to the Physics engine.
  16. /// Counts the number of modifications since the last save. (0 = Untainted)
  17. /// </summary>
  18. public int tainted;
  19. int w, h;
  20. /// <summary>
  21. /// Generate a new TerrainEngine instance and creates a new heightmap
  22. /// </summary>
  23. public TerrainEngine()
  24. {
  25. w = 256;
  26. h = 256;
  27. heightmap = new Channel(w, h);
  28. tainted++;
  29. }
  30. /// <summary>
  31. /// Converts the heightmap to a 65536 value 1D floating point array
  32. /// </summary>
  33. /// <returns>A float[65536] array containing the heightmap</returns>
  34. public float[] getHeights1D()
  35. {
  36. float[] heights = new float[w * h];
  37. int i;
  38. for (i = 0; i < w * h; i++)
  39. {
  40. heights[i] = (float)heightmap.map[i / w, i % w];
  41. }
  42. return heights;
  43. }
  44. /// <summary>
  45. /// Converts the heightmap to a 256x256 value 2D floating point array.
  46. /// </summary>
  47. /// <returns>An array of 256,256 values containing the heightmap</returns>
  48. public float[,] getHeights2D()
  49. {
  50. float[,] heights = new float[w, h];
  51. int x, y;
  52. for (x = 0; x < w; x++)
  53. {
  54. for (y = 0; y < h; y++)
  55. {
  56. heights[x, y] = (float)heightmap.map[x, y];
  57. }
  58. }
  59. return heights;
  60. }
  61. /// <summary>
  62. /// Imports a 1D floating point array into the 2D heightmap array
  63. /// </summary>
  64. /// <param name="heights">The array to import (must have 65536 members)</param>
  65. public void setHeights1D(float[] heights)
  66. {
  67. int i;
  68. for (i = 0; i < w * h; i++)
  69. {
  70. heightmap.map[i / w, i % w] = heights[i];
  71. }
  72. tainted++;
  73. }
  74. /// <summary>
  75. /// Loads a 2D array of values into the heightmap
  76. /// </summary>
  77. /// <param name="heights">An array of 256,256 float values</param>
  78. public void setHeights2D(float[,] heights)
  79. {
  80. int x, y;
  81. for (x = 0; x < w; x++)
  82. {
  83. for (y = 0; y < h; y++)
  84. {
  85. heightmap.set(x, y, (double)heights[x, y]);
  86. }
  87. }
  88. tainted++;
  89. }
  90. /// <summary>
  91. /// Processes a terrain-specific command
  92. /// </summary>
  93. /// <param name="args">Commandline arguments (space seperated)</param>
  94. /// <param name="resultText">Reference that returns error or help text if returning false</param>
  95. /// <returns>If the operation was successful (if not, the error is placed into resultText)</returns>
  96. public bool RunTerrainCmd(string[] args, ref string resultText)
  97. {
  98. string command = args[0];
  99. try
  100. {
  101. switch (command)
  102. {
  103. case "help":
  104. resultText += "terrain regenerate - rebuilds the sims terrain using a default algorithm\n";
  105. resultText += "terrain seed <seed> - sets the random seed value to <seed>\n";
  106. resultText += "terrain load <type> <filename> - loads a terrain from disk, type can be 'F32', 'F64', 'RAW' or 'IMG'\n";
  107. resultText += "terrain save <type> <filename> - saves a terrain to disk, type can be 'F32' or 'F64'\n";
  108. resultText += "terrain save grdmap <filename> <gradient map> - creates a PNG snapshot of the region using a named gradient map\n";
  109. resultText += "terrain rescale <min> <max> - rescales a terrain to be between <min> and <max> meters high\n";
  110. resultText += "terrain erode aerobic <windspeed> <pickupmin> <dropmin> <carry> <rounds> <lowest>\n";
  111. resultText += "terrain erode thermal <talus> <rounds> <carry>\n";
  112. resultText += "terrain multiply <val> - multiplies a terrain by <val>\n";
  113. return false;
  114. case "seed":
  115. setSeed(Convert.ToInt32(args[1]));
  116. break;
  117. case "erode":
  118. switch (args[1].ToLower())
  119. {
  120. case "aerobic":
  121. // WindSpeed, PickupMinimum,DropMinimum,Carry,Rounds,Lowest
  122. heightmap.AerobicErosion(Convert.ToDouble(args[2]), Convert.ToDouble(args[3]), Convert.ToDouble(args[4]), Convert.ToDouble(args[5]), Convert.ToInt32(args[6]), Convert.ToBoolean(args[7]));
  123. break;
  124. case "thermal":
  125. heightmap.thermalWeathering(Convert.ToDouble(args[2]), Convert.ToInt32(args[3]), Convert.ToDouble(args[4]));
  126. break;
  127. default:
  128. resultText = "Unknown erosion type";
  129. return false;
  130. }
  131. break;
  132. case "regenerate":
  133. hills();
  134. break;
  135. case "rescale":
  136. setRange(Convert.ToSingle(args[1]), Convert.ToSingle(args[2]));
  137. break;
  138. case "multiply":
  139. heightmap *= Convert.ToDouble(args[1]);
  140. break;
  141. case "load":
  142. switch (args[1].ToLower())
  143. {
  144. case "f32":
  145. loadFromFileF32(args[2]);
  146. break;
  147. case "f64":
  148. loadFromFileF64(args[2]);
  149. break;
  150. case "raw":
  151. loadFromFileSLRAW(args[2]);
  152. break;
  153. case "img":
  154. resultText = "Error - IMG mode is presently unsupported.";
  155. return false;
  156. default:
  157. resultText = "Unknown image or data format";
  158. return false;
  159. }
  160. break;
  161. case "save":
  162. switch (args[1].ToLower())
  163. {
  164. case "f32":
  165. writeToFileF32(args[2]);
  166. break;
  167. case "f64":
  168. writeToFileF64(args[2]);
  169. break;
  170. case "grdmap":
  171. exportImage(args[2], args[3]);
  172. break;
  173. default:
  174. resultText = "Unknown image or data format";
  175. return false;
  176. }
  177. break;
  178. default:
  179. resultText = "Unknown terrain command";
  180. return false;
  181. }
  182. return true;
  183. }
  184. catch (Exception e)
  185. {
  186. resultText = "Error running terrain command: " + e.ToString();
  187. return false;
  188. }
  189. }
  190. /// <summary>
  191. /// Renormalises the array between min and max
  192. /// </summary>
  193. /// <param name="min">Minimum value of the new array</param>
  194. /// <param name="max">Maximum value of the new array</param>
  195. public void setRange(float min, float max)
  196. {
  197. heightmap.normalise((double)min, (double)max);
  198. tainted++;
  199. }
  200. /// <summary>
  201. /// Loads a file consisting of 256x256 doubles and imports it as an array into the map.
  202. /// </summary>
  203. /// <remarks>TODO: Move this to libTerrain itself</remarks>
  204. /// <param name="filename">The filename of the double array to import</param>
  205. public void loadFromFileF64(string filename)
  206. {
  207. System.IO.FileInfo file = new System.IO.FileInfo(filename);
  208. System.IO.FileStream s = file.Open(System.IO.FileMode.Open, System.IO.FileAccess.Read);
  209. System.IO.BinaryReader bs = new System.IO.BinaryReader(s);
  210. int x, y;
  211. for (x = 0; x < w; x++)
  212. {
  213. for (y = 0; y < h; y++)
  214. {
  215. heightmap.map[x, y] = bs.ReadDouble();
  216. }
  217. }
  218. bs.Close();
  219. s.Close();
  220. tainted++;
  221. }
  222. /// <summary>
  223. /// Loads a file consisting of 256x256 floats and imports it as an array into the map.
  224. /// </summary>
  225. /// <remarks>TODO: Move this to libTerrain itself</remarks>
  226. /// <param name="filename">The filename of the float array to import</param>
  227. public void loadFromFileF32(string filename)
  228. {
  229. System.IO.FileInfo file = new System.IO.FileInfo(filename);
  230. System.IO.FileStream s = file.Open(System.IO.FileMode.Open, System.IO.FileAccess.Read);
  231. System.IO.BinaryReader bs = new System.IO.BinaryReader(s);
  232. int x, y;
  233. for (x = 0; x < w; x++)
  234. {
  235. for (y = 0; y < h; y++)
  236. {
  237. heightmap.map[x, y] = (double)bs.ReadSingle();
  238. }
  239. }
  240. bs.Close();
  241. s.Close();
  242. tainted++;
  243. }
  244. /// <summary>
  245. /// Loads a file formatted in the SL .RAW Format used on the main grid
  246. /// </summary>
  247. /// <remarks>This file format stinks and is best avoided.</remarks>
  248. /// <param name="filename">A path to the .RAW format</param>
  249. public void loadFromFileSLRAW(string filename)
  250. {
  251. System.IO.FileInfo file = new System.IO.FileInfo(filename);
  252. System.IO.FileStream s = file.Open(System.IO.FileMode.Open, System.IO.FileAccess.Read);
  253. System.IO.BinaryReader bs = new System.IO.BinaryReader(s);
  254. int x, y;
  255. for (x = 0; x < w; x++)
  256. {
  257. for (y = 0; y < h; y++)
  258. {
  259. heightmap.map[x, y] = (double)bs.ReadByte() * ((double)bs.ReadByte() / 127.0);
  260. bs.ReadBytes(11); // Advance the stream to next bytes.
  261. }
  262. }
  263. bs.Close();
  264. s.Close();
  265. tainted++;
  266. }
  267. /// <summary>
  268. /// Writes the current terrain heightmap to disk, in the format of a 65536 entry double[] array.
  269. /// </summary>
  270. /// <param name="filename">The desired output filename</param>
  271. public void writeToFileF64(string filename)
  272. {
  273. System.IO.FileInfo file = new System.IO.FileInfo(filename);
  274. System.IO.FileStream s = file.Open(System.IO.FileMode.CreateNew, System.IO.FileAccess.Write);
  275. System.IO.BinaryWriter bs = new System.IO.BinaryWriter(s);
  276. int x, y;
  277. for (x = 0; x < w; x++)
  278. {
  279. for (y = 0; y < h; y++)
  280. {
  281. bs.Write(heightmap.get(x, y));
  282. }
  283. }
  284. bs.Close();
  285. s.Close();
  286. }
  287. /// <summary>
  288. /// Writes the current terrain heightmap to disk, in the format of a 65536 entry float[] array
  289. /// </summary>
  290. /// <param name="filename">The desired output filename</param>
  291. public void writeToFileF32(string filename)
  292. {
  293. System.IO.FileInfo file = new System.IO.FileInfo(filename);
  294. System.IO.FileStream s = file.Open(System.IO.FileMode.CreateNew, System.IO.FileAccess.Write);
  295. System.IO.BinaryWriter bs = new System.IO.BinaryWriter(s);
  296. int x, y;
  297. for (x = 0; x < w; x++)
  298. {
  299. for (y = 0; y < h; y++)
  300. {
  301. bs.Write((float)heightmap.get(x, y));
  302. }
  303. }
  304. bs.Close();
  305. s.Close();
  306. }
  307. /// <summary>
  308. /// Sets the random seed to be used by procedural functions which involve random numbers.
  309. /// </summary>
  310. /// <param name="val">The desired seed</param>
  311. public void setSeed(int val)
  312. {
  313. heightmap.seed = val;
  314. }
  315. /// <summary>
  316. /// Raises land in a sphere around the specified coordinates
  317. /// </summary>
  318. /// <param name="rx">Center of the sphere on the X axis</param>
  319. /// <param name="ry">Center of the sphere on the Y axis</param>
  320. /// <param name="size">The radius of the sphere</param>
  321. /// <param name="amount">Scale the height of the sphere by this amount (recommended 0..2)</param>
  322. public void raise(double rx, double ry, double size, double amount)
  323. {
  324. lock (heightmap)
  325. {
  326. heightmap.raise(rx, ry, size, amount);
  327. }
  328. tainted++;
  329. }
  330. /// <summary>
  331. /// Lowers the land in a sphere around the specified coordinates
  332. /// </summary>
  333. /// <param name="rx">The center of the sphere at the X axis</param>
  334. /// <param name="ry">The center of the sphere at the Y axis</param>
  335. /// <param name="size">The radius of the sphere in meters</param>
  336. /// <param name="amount">Scale the height of the sphere by this amount (recommended 0..2)</param>
  337. public void lower(double rx, double ry, double size, double amount)
  338. {
  339. lock (heightmap)
  340. {
  341. heightmap.lower(rx, ry, size, amount);
  342. }
  343. tainted++;
  344. }
  345. /// <summary>
  346. /// Generates a simple set of hills in the shape of an island
  347. /// </summary>
  348. public void hills()
  349. {
  350. lock (heightmap)
  351. {
  352. heightmap.hillsSpheres(200, 20, 40, true, true, false);
  353. heightmap.normalise();
  354. heightmap *= 60.0; // Raise to 60m
  355. }
  356. tainted++;
  357. }
  358. /// <summary>
  359. /// Multiplies the heightfield by val
  360. /// </summary>
  361. /// <param name="meep">The heightfield</param>
  362. /// <param name="val">The multiplier</param>
  363. /// <returns></returns>
  364. public static TerrainEngine operator *(TerrainEngine meep, Double val)
  365. {
  366. meep.heightmap *= val;
  367. meep.tainted++;
  368. return meep;
  369. }
  370. /// <summary>
  371. /// Returns the height at the coordinates x,y
  372. /// </summary>
  373. /// <param name="x">X Coordinate</param>
  374. /// <param name="y">Y Coordinate</param>
  375. /// <returns></returns>
  376. public float this[int x, int y]
  377. {
  378. get
  379. {
  380. return (float)heightmap.get(x, y);
  381. }
  382. set
  383. {
  384. tainted++;
  385. heightmap.set(x, y, (double)value);
  386. }
  387. }
  388. /// <summary>
  389. /// Exports the current heightmap to a PNG file
  390. /// </summary>
  391. /// <param name="filename">The destination filename for the image</param>
  392. /// <param name="gradientmap">A 1x*height* image which contains the colour gradient to export with. Must be at least 1x2 pixels, 1x256 or more is ideal.</param>
  393. public void exportImage(string filename, string gradientmap)
  394. {
  395. try
  396. {
  397. Bitmap gradientmapLd = new Bitmap(gradientmap);
  398. int pallete = gradientmapLd.Height;
  399. Bitmap bmp = new Bitmap(heightmap.w, heightmap.h);
  400. Color[] colours = new Color[pallete];
  401. for (int i = 0; i < pallete; i++)
  402. {
  403. colours[i] = gradientmapLd.GetPixel(0, i);
  404. }
  405. Channel copy = heightmap.copy();
  406. for (int x = 0; x < copy.w; x++)
  407. {
  408. for (int y = 0; y < copy.h; y++)
  409. {
  410. // 512 is the largest possible height before colours clamp
  411. int colorindex = (int)(Math.Max(Math.Min(1.0, copy.get(x, y) / 512.0), 0.0) * pallete);
  412. bmp.SetPixel(x, y, colours[colorindex]);
  413. }
  414. }
  415. bmp.Save(filename, System.Drawing.Imaging.ImageFormat.Png);
  416. }
  417. catch (Exception e)
  418. {
  419. Console.WriteLine("Failed generating terrain map: " + e.ToString());
  420. }
  421. }
  422. }
  423. }